f6b7fb5113f9f2897ec15e2c51e31e843a83f9a9
[projects/chimara/chimara.git] / libchimara / input.c
1 #include "charset.h"
2 #include "magic.h"
3 #include "input.h"
4 #include "pager.h"
5 #include "chimara-glk-private.h"
6 #include "garglk.h"
7
8 extern GPrivate glk_data_key;
9
10 /* Forward declarations */
11 static int finish_text_buffer_line_input(winid_t win, gboolean emit_signal);
12 static int finish_text_grid_line_input(winid_t win, gboolean emit_signal);
13 static void cancel_old_input_request(winid_t win);
14
15 /* Internal function: code common to both flavors of char event request */
16 void
17 request_char_event_common(winid_t win, gboolean unicode)
18 {
19         VALID_WINDOW(win, return);
20         g_return_if_fail(win->type != wintype_TextBuffer || win->type != wintype_TextGrid);
21
22         cancel_old_input_request(win);
23
24         flush_window_buffer(win);
25
26         if(win->type == wintype_TextBuffer) {
27                 /* Move the input_position mark to the end of the window_buffer */
28                 GtkTextBuffer *buffer = gtk_text_view_get_buffer( GTK_TEXT_VIEW(win->widget) );
29                 GtkTextMark *input_position = gtk_text_buffer_get_mark(buffer, "input_position");
30                 GtkTextIter end_iter;
31                 gtk_text_buffer_get_end_iter(buffer, &end_iter);
32                 gtk_text_buffer_move_mark(buffer, input_position, &end_iter);
33         }
34
35
36         win->input_request_type = unicode? INPUT_REQUEST_CHARACTER_UNICODE : INPUT_REQUEST_CHARACTER;
37         g_signal_handler_unblock( win->widget, win->char_input_keypress_handler );
38
39         gdk_threads_enter();
40         gtk_widget_grab_focus( GTK_WIDGET(win->widget) );
41         gdk_threads_leave();
42
43         /* Emit the "waiting" signal to let listeners know we are ready for input */
44         ChimaraGlkPrivate *glk_data = g_private_get(&glk_data_key);
45         g_signal_emit_by_name(glk_data->self, "waiting");
46 }
47
48 /**
49  * glk_request_char_event:
50  * @win: A window to request char events from.
51  *
52  * Request input of a Latin-1 character or special key. A window cannot have
53  * requests for both character and line input at the same time. Nor can it have
54  * requests for character input of both types (Latin-1 and Unicode). It is
55  * illegal to call glk_request_char_event() if the window already has a pending
56  * request for either character or line input.
57  */
58 void
59 glk_request_char_event(winid_t win)
60 {
61         request_char_event_common(win, FALSE);
62 }
63
64 /**
65  * glk_request_char_event_uni:
66  * @win: A window to request char events from.
67  *
68  * Request input of a Unicode character or special key. See
69  * glk_request_char_event().
70  */
71 void
72 glk_request_char_event_uni(winid_t win)
73 {
74         request_char_event_common(win, TRUE);
75 }
76
77 /**
78  * glk_cancel_char_event:
79  * @win: A window to cancel the latest char event request on.
80  *
81  * This cancels a pending request for character input. (Either Latin-1 or
82  * Unicode.) For convenience, it is legal to call glk_cancel_char_event() even
83  * if there is no charcter input request on that window. Glk will ignore the
84  * call in this case.
85  */
86 void
87 glk_cancel_char_event(winid_t win)
88 {
89         VALID_WINDOW(win, return);
90         g_return_if_fail(win->type != wintype_TextBuffer || win->type != wintype_TextGrid);
91
92         if(win->input_request_type == INPUT_REQUEST_CHARACTER || win->input_request_type == INPUT_REQUEST_CHARACTER_UNICODE)
93         {
94                 win->input_request_type = INPUT_REQUEST_NONE;
95                 g_signal_handler_block( win->widget, win->char_input_keypress_handler );
96         }
97 }
98
99 /* Internal function: Request either latin-1 or unicode line input, in a text grid window. */
100 static void
101 text_grid_request_line_event_common(winid_t win, glui32 maxlen, gboolean insert, gchar *inserttext)
102 {
103         /* All outstanding printing _must_ be finished before putting an input entry
104          into the buffer */
105         flush_window_buffer(win);
106
107         gdk_threads_enter();
108
109         GtkTextBuffer *buffer = gtk_text_view_get_buffer( GTK_TEXT_VIEW(win->widget) );
110
111     GtkTextMark *cursor = gtk_text_buffer_get_mark(buffer, "cursor_position");
112     GtkTextIter start_iter, end_iter;
113     gtk_text_buffer_get_iter_at_mark(buffer, &start_iter, cursor);
114
115     /* Determine the maximum length of the line input */
116     gint cursorpos = gtk_text_iter_get_line_offset(&start_iter);
117     /* Odd; the Glk spec says the maximum input length is
118     windowwidth - 1 - cursorposition. I say no, because if cursorposition is
119     zero, then the input should fill the whole line. FIXME??? */
120     win->input_length = MIN(win->width - cursorpos, win->line_input_buffer_max_len);
121     end_iter = start_iter;
122     gtk_text_iter_set_line_offset(&end_iter, cursorpos + win->input_length);
123
124         /* If the buffer currently has a selection with one bound in the middle of
125         the input field, then deselect it. Otherwise the input field gets trashed */
126         GtkTextIter start_sel, end_sel;
127         if( gtk_text_buffer_get_selection_bounds(buffer, &start_sel, &end_sel) )
128         {
129                 if( gtk_text_iter_in_range(&start_sel, &start_iter, &end_iter) )
130                         gtk_text_buffer_place_cursor(buffer, &end_sel);
131                 if( gtk_text_iter_in_range(&end_sel, &start_iter, &end_iter) )
132                         gtk_text_buffer_place_cursor(buffer, &start_sel);
133         }
134
135     /* Erase the text currently in the input field and replace it with a GtkEntry */
136     gtk_text_buffer_delete(buffer, &start_iter, &end_iter);
137     win->input_anchor = gtk_text_buffer_create_child_anchor(buffer, &start_iter);
138     win->input_entry = gtk_entry_new();
139         /* Set the entry's font to match that of the window */
140     GtkRcStyle *style = gtk_widget_get_modifier_style(win->widget);     /* Don't free */
141         gtk_widget_modify_font(win->input_entry, style->font_desc);
142         /* Make the entry as small as possible to fit with the text */
143         gtk_entry_set_has_frame(GTK_ENTRY(win->input_entry), FALSE);
144         GtkBorder border = { 0, 0, 0, 0 };
145
146         gtk_entry_set_inner_border(GTK_ENTRY(win->input_entry), &border);
147     gtk_entry_set_max_length(GTK_ENTRY(win->input_entry), win->input_length);
148     gtk_entry_set_width_chars(GTK_ENTRY(win->input_entry), win->input_length);
149
150     /* Insert pre-entered text if needed */
151     if(insert)
152         gtk_entry_set_text(GTK_ENTRY(win->input_entry), inserttext);
153
154     /* Set background color of entry (TODO: implement as property) */
155     GdkColor background;
156         gdk_color_parse("grey", &background);
157     gtk_widget_modify_base(win->input_entry, GTK_STATE_NORMAL, &background);
158
159     g_signal_connect(win->input_entry, "activate", G_CALLBACK(on_input_entry_activate), win);
160     g_signal_connect(win->input_entry, "key-press-event", G_CALLBACK(on_input_entry_key_press_event), win);
161     win->line_input_entry_changed = g_signal_connect(win->input_entry, "changed", G_CALLBACK(on_input_entry_changed), win);
162
163     gtk_widget_show(win->input_entry);
164     gtk_text_view_add_child_at_anchor(GTK_TEXT_VIEW(win->widget), win->input_entry, win->input_anchor);
165
166         gtk_widget_grab_focus(win->input_entry);
167
168         gdk_threads_leave();
169 }
170
171 /* Internal function: Request either latin-1 or unicode line input, in a text buffer window. */
172 static void
173 text_buffer_request_line_event_common(winid_t win, glui32 maxlen, gboolean insert, gchar *inserttext)
174 {
175         flush_window_buffer(win);
176
177         gdk_threads_enter();
178
179         GtkTextBuffer *buffer = gtk_text_view_get_buffer( GTK_TEXT_VIEW(win->widget) );
180
181     /* Move the input_position mark to the end of the window_buffer */
182     GtkTextMark *input_position = gtk_text_buffer_get_mark(buffer, "input_position");
183     GtkTextIter end_iter;
184     gtk_text_buffer_get_end_iter(buffer, &end_iter);
185     gtk_text_buffer_move_mark(buffer, input_position, &end_iter);
186
187     /* Set the entire contents of the window_buffer as uneditable
188      * (so input can only be entered at the end) */
189     GtkTextIter start_iter;
190     gtk_text_buffer_get_start_iter(buffer, &start_iter);
191     gtk_text_buffer_remove_tag_by_name(buffer, "uneditable", &start_iter, &end_iter);
192     gtk_text_buffer_apply_tag_by_name(buffer, "uneditable", &start_iter, &end_iter);
193
194     /* Insert pre-entered text if needed */
195     if(insert) {
196         gtk_text_buffer_insert(buffer, &end_iter, inserttext, -1);
197                 gtk_text_buffer_get_end_iter(buffer, &end_iter); /* update after text insertion */
198         }
199
200         /* Apply the correct style to the input prompt */
201         GtkTextIter input_iter;
202     gtk_text_buffer_get_iter_at_mark(buffer, &input_iter, input_position);
203     gtk_text_buffer_apply_tag_by_name(buffer, "default", &input_iter, &end_iter);
204     gtk_text_buffer_apply_tag_by_name(buffer, "input", &input_iter, &end_iter);
205     gtk_text_buffer_apply_tag_by_name(buffer, "glk-input", &input_iter, &end_iter);
206
207     gtk_text_view_set_editable(GTK_TEXT_VIEW(win->widget), TRUE);
208
209         g_signal_handler_unblock(buffer, win->insert_text_handler);
210         gtk_widget_grab_focus(win->widget);
211
212         gdk_threads_leave();
213 }
214
215 /**
216  * glk_request_line_event:
217  * @win: A text buffer or text grid window to request line input on.
218  * @buf: A buffer of at least @maxlen bytes.
219  * @maxlen: Length of the buffer.
220  * @initlen: The number of characters in @buf to pre-enter.
221  *
222  * Requests input of a line of Latin-1 characters. A window cannot have requests
223  * for both character and line input at the same time. Nor can it have requests
224  * for line input of both types (Latin-1 and Unicode). It is illegal to call
225  * glk_request_line_event() if the window already has a pending request for
226  * either character or line input.
227  *
228  * The @buf argument is a pointer to space where the line input will be stored.
229  * (This may not be %NULL.) @maxlen is the length of this space, in bytes; the
230  * library will not accept more characters than this. If @initlen is nonzero,
231  * then the first @initlen bytes of @buf will be entered as pre-existing input
232  * — just as if the player had typed them himself. (The player can continue
233  * composing after this pre-entered input, or delete it or edit as usual.)
234  *
235  * The contents of the buffer are undefined until the input is completed (either
236  * by a line input event, or glk_cancel_line_event(). The library may or may not
237  * fill in the buffer as the player composes, while the input is still pending;
238  * it is illegal to change the contents of the buffer yourself.
239  */
240 void
241 glk_request_line_event(winid_t win, char *buf, glui32 maxlen, glui32 initlen)
242 {
243         VALID_WINDOW(win, return);
244         g_return_if_fail(buf);
245         g_return_if_fail(win->type != wintype_TextBuffer || win->type != wintype_TextGrid);
246         g_return_if_fail(initlen <= maxlen);
247
248         cancel_old_input_request(win);
249
250         ChimaraGlkPrivate *glk_data = g_private_get(&glk_data_key);
251
252         /* Register the buffer */
253         if(glk_data->register_arr)
254         win->buffer_rock = (*glk_data->register_arr)(buf, maxlen, "&+#!Cn");
255
256         win->input_request_type = INPUT_REQUEST_LINE;
257         win->line_input_buffer = buf;
258         win->line_input_buffer_max_len = maxlen;
259         win->echo_current_line_input = win->echo_line_input;
260         win->current_extra_line_terminators = g_slist_copy(win->extra_line_terminators);
261
262         gchar *inserttext = (initlen > 0)? g_strndup(buf, initlen) : g_strdup("");
263         switch(win->type)
264         {
265             case wintype_TextBuffer:
266                 text_buffer_request_line_event_common(win, maxlen, (initlen > 0), inserttext);
267                 break;
268             case wintype_TextGrid:
269                 text_grid_request_line_event_common(win, maxlen, (initlen > 0), inserttext);
270                 break;
271     }
272         g_free(inserttext);
273         g_signal_handler_unblock(win->widget, win->line_input_keypress_handler);
274
275         /* Emit the "waiting" signal to let listeners know we are ready for input */
276         g_signal_emit_by_name(glk_data->self, "waiting");
277 }
278
279 /**
280  * glk_request_line_event_uni:
281  * @win: A text buffer or text grid window to request line input on.
282  * @buf: A buffer of at least @maxlen characters.
283  * @maxlen: Length of the buffer.
284  * @initlen: The number of characters in @buf to pre-enter.
285  *
286  * Request input of a line of Unicode characters. This works the same as
287  * glk_request_line_event(), except the result is stored in an array of
288  * <type>glui32</type> values instead of an array of characters, and the values
289  * may be any valid Unicode code points.
290  *
291  * If possible, the library should return fully composed Unicode characters,
292  * rather than strings of base and composition characters.
293  *
294  * <note><para>
295  *   Fully-composed characters are the norm for Unicode text, so an
296  *   implementation that ignores this issue will probably produce the right
297  *   result. However, the game may not want to rely on that. Another factor is
298  *   that case-folding can (occasionally) produce non-normalized text.
299  *   Therefore, to cover all its bases, a game should call
300  *   glk_buffer_to_lower_case_uni(), followed by
301  *   glk_buffer_canon_normalize_uni(), before parsing.
302  * </para></note>
303  *
304  * <note><para>
305  *   Earlier versions of this spec said that line input must always be in
306  *   Unicode Normalization Form C. However, this has not been universally
307  *   implemented. It is also somewhat redundant, for the results noted above.
308  *   Therefore, we now merely recommend that line input be fully composed. The
309  *   game is ultimately responsible for all case-folding and normalization. See
310  *   <link linkend="chimara-Unicode-String-Normalization">Unicode String
311  *   Normalization</link>.
312  * </para></note>
313  */
314 void
315 glk_request_line_event_uni(winid_t win, glui32 *buf, glui32 maxlen, glui32 initlen)
316 {
317         VALID_WINDOW(win, return);
318         g_return_if_fail(buf);
319         g_return_if_fail(win->type != wintype_TextBuffer || win->type != wintype_TextGrid);
320         g_return_if_fail(initlen <= maxlen);
321
322         cancel_old_input_request(win);
323         ChimaraGlkPrivate *glk_data = g_private_get(&glk_data_key);
324
325         /* Register the buffer */
326         if(glk_data->register_arr)
327         win->buffer_rock = (*glk_data->register_arr)(buf, maxlen, "&+#!Iu");
328
329         win->input_request_type = INPUT_REQUEST_LINE_UNICODE;
330         win->line_input_buffer_unicode = buf;
331         win->line_input_buffer_max_len = maxlen;
332         win->echo_current_line_input = win->echo_line_input;
333         win->current_extra_line_terminators = g_slist_copy(win->extra_line_terminators);
334
335         gchar *utf8;
336         if(initlen > 0) {
337                 utf8 = convert_ucs4_to_utf8(buf, initlen);
338                 if(utf8 == NULL)
339                         return;
340         }
341         else
342                 utf8 = g_strdup("");
343
344     switch(win->type)
345         {
346             case wintype_TextBuffer:
347                 text_buffer_request_line_event_common(win, maxlen, (initlen > 0), utf8);
348                 break;
349             case wintype_TextGrid:
350                 text_grid_request_line_event_common(win, maxlen, (initlen > 0), utf8);
351                 break;
352     }
353     g_signal_handler_unblock(win->widget, win->line_input_keypress_handler);
354         g_free(utf8);
355
356         /* Emit the "waiting" signal to let listeners know we are ready for input */
357         g_signal_emit_by_name(glk_data->self, "waiting");
358 }
359
360 /**
361  * glk_cancel_line_event:
362  * @win: A text buffer or text grid window to cancel line input on.
363  * @event: Will be filled in if the user had already input something.
364  *
365  * This cancels a pending request for line input. (Either Latin-1 or Unicode.)
366  *
367  * The event pointed to by the event argument will be filled in as if the
368  * player had hit <keycap>enter</keycap>, and the input composed so far will be
369  * stored in the buffer; see below. If you do not care about this information,
370  * pass %NULL as the @event argument. (The buffer will still be filled.)
371  *
372  * For convenience, it is legal to call glk_cancel_line_event() even if there
373  * is no line input request on that window. The event type will be set to
374  * %evtype_None in this case.
375  */
376 void
377 glk_cancel_line_event(winid_t win, event_t *event)
378 {
379         VALID_WINDOW(win, return);
380         g_return_if_fail(win->type != wintype_TextBuffer || win->type != wintype_TextGrid);
381
382         if(event != NULL) {
383                 event->type = evtype_None;
384                 event->win = win;
385                 event->val1 = 0;
386                 event->val2 = 0;
387         }
388
389         if(win->input_request_type != INPUT_REQUEST_LINE && win->input_request_type != INPUT_REQUEST_LINE_UNICODE)
390                 return;
391
392         g_signal_handler_block( win->widget, win->line_input_keypress_handler );
393
394         int chars_written = 0;
395
396         gdk_threads_enter();
397         if(win->type == wintype_TextGrid) {
398                 chars_written = finish_text_grid_line_input(win, FALSE);
399         } else if(win->type == wintype_TextBuffer) {
400                 gtk_text_view_set_editable( GTK_TEXT_VIEW(win->widget), FALSE );
401                 GtkTextBuffer *window_buffer = gtk_text_view_get_buffer( GTK_TEXT_VIEW(win->widget) );
402                 g_signal_handler_block(window_buffer, win->insert_text_handler);
403                 chars_written = finish_text_buffer_line_input(win, FALSE);
404         }
405         gdk_threads_leave();
406
407         ChimaraGlkPrivate *glk_data = g_private_get(&glk_data_key);
408         if(glk_data->unregister_arr)
409         {
410                 if(win->input_request_type == INPUT_REQUEST_LINE_UNICODE)
411                         (*glk_data->unregister_arr)(win->line_input_buffer_unicode, win->line_input_buffer_max_len, "&+#!Iu", win->buffer_rock);
412                 else
413                 (*glk_data->unregister_arr)(win->line_input_buffer, win->line_input_buffer_max_len, "&+#!Cn", win->buffer_rock);
414     }
415
416         if(event != NULL && chars_written > 0) {
417                 event->type = evtype_LineInput;
418                 event->val1 = chars_written;
419         }
420 }
421
422 /* Helper function: Turn off shutdown key-press-event signal handler */
423 static gboolean
424 turn_off_handler(GNode *node)
425 {
426         winid_t win = node->data;
427         g_signal_handler_block(win->widget, win->shutdown_keypress_handler);
428         return FALSE; /* don't stop */
429 }
430
431 /* Internal function: Callback for signal key-press-event while waiting for shutdown. */
432 gboolean
433 on_shutdown_key_press_event(GtkWidget *widget, GdkEventKey *event, winid_t win)
434 {
435         ChimaraGlk *glk = CHIMARA_GLK(gtk_widget_get_ancestor(widget, CHIMARA_TYPE_GLK));
436         g_assert(glk);
437         CHIMARA_GLK_USE_PRIVATE(glk, priv);
438         
439         /* Turn off all the signal handlers */
440         if(priv->root_window)
441                 g_node_traverse(priv->root_window, G_IN_ORDER, G_TRAVERSE_LEAVES, -1, (GNodeTraverseFunc)turn_off_handler, NULL);
442         
443         /* Signal the Glk library that it can shut everything down now */
444         g_mutex_lock(&priv->shutdown_lock);
445         g_cond_signal(&priv->shutdown_key_pressed);
446         g_mutex_unlock(&priv->shutdown_lock);
447
448         return TRUE; /* block the event */
449 }
450
451 /* Internal function: General callback for signal key-press-event on a text buffer or text grid window. Used in character input on both text buffers and grids. Blocked when not in use. */
452 gboolean
453 on_char_input_key_press_event(GtkWidget *widget, GdkEventKey *event, winid_t win)
454 {
455         /* Ignore modifier keys, otherwise the char input will already trigger on 
456         the shift key when the user tries to type a capital letter */
457         if(event->is_modifier)
458                 return FALSE; /* don't stop the event */
459
460         /* All text up to the input position is now regarded as being read by the user */
461         if(win->type == wintype_TextBuffer)
462                 pager_update(win);
463         
464         glui32 keycode = keyval_to_glk_keycode(event->keyval, win->input_request_type == INPUT_REQUEST_CHARACTER_UNICODE);
465
466         ChimaraGlk *glk = CHIMARA_GLK(gtk_widget_get_ancestor(widget, CHIMARA_TYPE_GLK));
467         g_assert(glk);
468         event_throw(glk, evtype_CharInput, win, keycode, 0);
469         g_signal_emit_by_name(glk, "char-input", win->rock, event->keyval);
470
471         /* Only one keypress will be handled */
472         win->input_request_type = INPUT_REQUEST_NONE;
473         g_signal_handler_block(win->widget, win->char_input_keypress_handler);
474
475         return TRUE;
476 }
477
478 gboolean
479 on_line_input_key_press_event(GtkWidget *widget, GdkEventKey *event, winid_t win)
480 {
481         switch(win->type)
482         {
483                 case wintype_TextBuffer:
484                 {
485                         GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(win->widget));
486                         GtkTextMark *input_position_mark = gtk_text_buffer_get_mark(buffer, "input_position");
487                         GtkTextIter input_position_iter;
488                         gtk_text_buffer_get_iter_at_mark(buffer, &input_position_iter, input_position_mark);
489                         GtkTextIter end_iter;
490                         gtk_text_buffer_get_end_iter(buffer, &end_iter);
491
492                         /* Check whether the cursor is at the prompt or somewhere else in the text */
493                         GtkTextIter selection_start, selection_end;
494                         gtk_text_buffer_get_selection_bounds(buffer, &selection_start, &selection_end);
495                         if(gtk_text_iter_compare(&selection_start, &input_position_iter) < 0) {
496                                 // Cursor is somewhere else in the text, place it at the end if the user starts typing
497                                 if(event->keyval >= GDK_KEY_space && event->keyval <= GDK_KEY_asciitilde) {
498                                         gtk_text_buffer_place_cursor(buffer, &end_iter);
499                                 } else {
500                                         // User is walking around, let him be.
501                                         return FALSE;
502                                 }
503                         }
504
505                         /* All text up to the input position is now regarded as being read by the user */
506                         pager_update(win);
507
508                         /* History up/down */
509                         if(event->keyval == GDK_KEY_Up || event->keyval == GDK_KEY_KP_Up
510                                 || event->keyval == GDK_KEY_Down || event->keyval == GDK_KEY_KP_Down)
511                         {
512                                 /* Prevent falling off the end of the history list */
513                                 if(win->history == NULL)
514                                         return TRUE;
515                                 if( (event->keyval == GDK_KEY_Up || event->keyval == GDK_KEY_KP_Up)
516                                         && win->history_pos && win->history_pos->next == NULL)
517                                         return TRUE;
518                                 if( (event->keyval == GDK_KEY_Down || event->keyval == GDK_KEY_KP_Down)
519                                         && (win->history_pos == NULL || win->history_pos->prev == NULL) )
520                                         return TRUE;
521
522                                 /* Erase any text that was already typed */
523                                 if(win->history_pos == NULL) {
524                                         gchar *current_input = gtk_text_buffer_get_text(buffer, &input_position_iter, &end_iter, FALSE);
525                                         win->history = g_list_prepend(win->history, current_input);
526                                         win->history_pos = win->history;
527                                 }
528
529                                 gtk_text_buffer_delete(buffer, &input_position_iter, &end_iter);
530
531                                 if(event->keyval == GDK_KEY_Up || event->keyval == GDK_KEY_KP_Up)
532                                 {
533                                         if(win->history_pos)
534                                                 win->history_pos = g_list_next(win->history_pos);
535                                         else
536                                                 win->history_pos = win->history;
537                                 }
538                                 else /* down */
539                                         win->history_pos = g_list_previous(win->history_pos);
540
541                                 /* Insert the history item into the window */
542                                 gtk_text_buffer_get_end_iter(buffer, &end_iter);
543
544                                 g_signal_handler_block(buffer, win->insert_text_handler);
545                                 gtk_text_buffer_insert_with_tags_by_name(buffer, &end_iter, win->history_pos->data, -1, "default", "input", "glk-input", NULL);
546                                 g_signal_handler_unblock(buffer, win->insert_text_handler);
547
548                                 return TRUE;
549                         }
550
551                         /* Move to beginning/end of input field */
552                         else if(event->keyval == GDK_KEY_Home) {
553                                 GtkTextIter input_iter;
554                                 GtkTextMark *input_position = gtk_text_buffer_get_mark(buffer, "input_position");
555                                 gtk_text_buffer_get_iter_at_mark(buffer, &input_iter, input_position);
556                                 gtk_text_buffer_place_cursor(buffer, &input_iter);
557                                 return TRUE;
558                         }
559                         else if(event->keyval == GDK_KEY_End) {
560                                 gtk_text_buffer_place_cursor(buffer, &end_iter);
561                                 return TRUE;
562                         }
563
564                         /* Handle the line terminators */
565                         else if(event->keyval == GDK_KEY_Return || event->keyval == GDK_KEY_KP_Enter
566                            || g_slist_find(win->current_extra_line_terminators, GUINT_TO_POINTER(event->keyval)))
567                         {
568                                 /* Remove signal handlers */
569                                 g_signal_handler_block(buffer, win->insert_text_handler);
570                                 g_signal_handler_block(win->widget, win->line_input_keypress_handler);
571
572                                 /* Insert a newline (even if line input was terminated with a different key */
573                                 gtk_text_buffer_get_end_iter(buffer, &end_iter);
574                                 gtk_text_buffer_insert(buffer, &end_iter, "\n", 1);
575                                 gtk_text_buffer_place_cursor(buffer, &end_iter);
576
577                                 /* Make the window uneditable again and retrieve the text that was input */
578                                 gtk_text_view_set_editable(GTK_TEXT_VIEW(win->widget), FALSE);
579
580                                 int chars_written = finish_text_buffer_line_input(win, TRUE);
581                                 ChimaraGlk *glk = CHIMARA_GLK(gtk_widget_get_ancestor(win->widget, CHIMARA_TYPE_GLK));
582                                 event_throw(glk, evtype_LineInput, win, chars_written, 0);
583                                 return TRUE;
584                         }
585                 }
586                         return FALSE;
587
588                 /* If this is a text grid window, then redirect the key press to the line input GtkEntry */
589                 case wintype_TextGrid:
590                 {
591                         if(event->keyval == GDK_KEY_Up || event->keyval == GDK_KEY_KP_Up
592                                 || event->keyval == GDK_KEY_Down || event->keyval == GDK_KEY_KP_Down
593                                 || event->keyval == GDK_KEY_Left || event->keyval == GDK_KEY_KP_Left
594                                 || event->keyval == GDK_KEY_Right || event->keyval == GDK_KEY_KP_Right
595                                 || event->keyval == GDK_KEY_Tab || event->keyval == GDK_KEY_KP_Tab
596                                 || event->keyval == GDK_KEY_Page_Up || event->keyval == GDK_KEY_KP_Page_Up
597                                 || event->keyval == GDK_KEY_Page_Down || event->keyval == GDK_KEY_KP_Page_Down
598                                 || event->keyval == GDK_KEY_Home || event->keyval == GDK_KEY_KP_Home
599                                 || event->keyval == GDK_KEY_End || event->keyval == GDK_KEY_KP_End)
600                                 return FALSE; /* Don't redirect these keys */
601                         gtk_widget_grab_focus(win->input_entry);
602                         gtk_editable_set_position(GTK_EDITABLE(win->input_entry), -1);
603                         gboolean retval = TRUE;
604                         g_signal_emit_by_name(win->input_entry, "key-press-event", event, &retval);
605                         return retval; /* Block this key event if the entry handled it */
606                 }
607         }
608         return FALSE;
609 }
610
611 /* Internal function: finish handling a line input request, for both text grid and text buffer windows. */
612 static int
613 write_to_window_buffer(winid_t win, const gchar *inserted_text)
614 {
615         int copycount = 0;
616
617     /* Convert the string from UTF-8 to Latin-1 or Unicode */
618     if(win->input_request_type == INPUT_REQUEST_LINE)
619     {
620         gsize bytes_written;
621         gchar *latin1 = convert_utf8_to_latin1(inserted_text, &bytes_written);
622
623         if(latin1 == NULL)
624             return 0;
625
626         /* Place input in the echo stream */
627         if(win->echo_stream != NULL)
628             glk_put_string_stream(win->echo_stream, latin1);
629
630         /* Copy the string (bytes_written does not include the NULL at the end) */
631         copycount = MIN(win->line_input_buffer_max_len, bytes_written);
632         memcpy(win->line_input_buffer, latin1, copycount);
633         g_free(latin1);
634     }
635     else if(win->input_request_type == INPUT_REQUEST_LINE_UNICODE)
636     {
637         glong items_written;
638         gunichar *unicode = convert_utf8_to_ucs4(inserted_text, &items_written);
639
640         if(unicode == NULL)
641             return 0;
642
643         /* Place input in the echo stream */
644         if(win->echo_stream != NULL)
645             glk_put_string_stream_uni(win->echo_stream, unicode);
646
647         /* Copy the string (but not the NULL at the end) */
648         copycount = MIN(win->line_input_buffer_max_len, items_written);
649         memcpy(win->line_input_buffer_unicode, unicode, copycount * sizeof(gunichar));
650         g_free(unicode);
651     }
652     else
653         WARNING("Wrong input request type");
654
655     win->input_request_type = INPUT_REQUEST_NONE;
656         return copycount;
657 }
658
659 /* Internal function: Retrieves the input of a TextBuffer window and stores it in the window buffer.
660  * Returns the number of characters written, suitable for inclusion in a line input event. */
661 static int
662 finish_text_buffer_line_input(winid_t win, gboolean emit_signal)
663 {
664         VALID_WINDOW(win, return 0);
665         g_return_val_if_fail(win->type == wintype_TextBuffer, 0);
666
667         GtkTextIter start_iter, end_iter;
668
669         GtkTextBuffer *window_buffer = gtk_text_view_get_buffer( GTK_TEXT_VIEW(win->widget) );
670         GtkTextMark *input_position = gtk_text_buffer_get_mark(window_buffer, "input_position");
671         gtk_text_buffer_get_iter_at_mark(window_buffer, &start_iter, input_position);
672         gtk_text_buffer_get_end_iter(window_buffer, &end_iter);
673
674         gchar *inserted_text = gtk_text_buffer_get_text(window_buffer, &start_iter, &end_iter, FALSE);
675
676         /* If echoing is turned off, remove the text from the window */
677         if(!win->echo_current_line_input)
678                 gtk_text_buffer_delete(window_buffer, &start_iter, &end_iter);
679
680         /* Don't include the newline in the input */
681         char *last_char = inserted_text + strlen(inserted_text) - 1;
682         if(*last_char == '\n')
683                 *last_char = '\0';
684
685         int chars_written = write_to_window_buffer(win, inserted_text);
686         if(emit_signal)
687         {
688                 ChimaraGlk *glk = CHIMARA_GLK(gtk_widget_get_ancestor(win->widget, CHIMARA_TYPE_GLK));
689                 g_assert(glk);
690                 g_signal_emit_by_name(glk, "line-input", win->rock, inserted_text);
691         }
692
693         /* Add the text to the window input history */
694         if(win->history_pos != NULL)
695         {
696                 g_free(win->history->data);
697                 win->history = g_list_delete_link(win->history, win->history);
698         }
699         if(*inserted_text != 0)
700                 win->history = g_list_prepend(win->history, g_strdup(inserted_text));
701
702         win->history_pos = NULL;
703
704         g_free(inserted_text);
705
706         return chars_written;
707 }
708
709 /* Internal function: Retrieves the input of a TextGrid window and stores it in the window buffer.
710  * Returns the number of characters written, suitable for inclusion in a line input event. */
711 static int
712 finish_text_grid_line_input(winid_t win, gboolean emit_signal)
713 {
714         VALID_WINDOW(win, return 0);
715         g_return_val_if_fail(win->type == wintype_TextGrid, 0);
716
717         GtkTextBuffer *buffer = gtk_text_view_get_buffer( GTK_TEXT_VIEW(win->widget) );
718
719         gchar *text = g_strdup( gtk_entry_get_text(GTK_ENTRY(win->input_entry)) );
720         /* Move the focus back into the text view */
721         gtk_widget_grab_focus(win->widget);
722         /* Remove entry widget from text view */
723         /* Should be ok even though this is the widget's own signal handler */
724         gtk_container_remove( GTK_CONTAINER(win->widget), GTK_WIDGET(win->input_entry) );
725         win->input_entry = NULL;
726         /* Delete the child anchor */
727         GtkTextIter start, end;
728         gtk_text_buffer_get_iter_at_child_anchor(buffer, &start, win->input_anchor);
729         end = start;
730         gtk_text_iter_forward_char(&end); /* Point after the child anchor */
731         gtk_text_buffer_delete(buffer, &start, &end);
732         win->input_anchor = NULL;
733
734     gchar *spaces = g_strnfill(win->input_length - g_utf8_strlen(text, -1), ' ');
735     gchar *text_to_insert = g_strconcat(text, spaces, NULL);
736         g_free(spaces);
737     gtk_text_buffer_insert(buffer, &start, text_to_insert, -1);
738     g_free(text_to_insert);
739
740     int chars_written = write_to_window_buffer(win, text);
741     if(emit_signal)
742     {
743                 ChimaraGlk *glk = CHIMARA_GLK(gtk_widget_get_ancestor(win->widget, CHIMARA_TYPE_GLK));
744                 g_assert(glk);
745                 g_signal_emit_by_name(glk, "line-input", win->rock, text);
746     }
747
748         /* Add the text to the window input history */
749         if(win->history_pos != NULL)
750         {
751                 g_free(win->history->data);
752                 win->history = g_list_delete_link(win->history, win->history);
753         }
754         if(*text != 0)
755                 win->history = g_list_prepend(win->history, g_strdup(text));
756         win->history_pos = NULL;
757
758         g_free(text);
759         return chars_written;
760 }
761
762 /* Internal function: Callback for signal insert-text on a text buffer window.
763 Runs after the default handler has already inserted the text. */
764 void
765 after_window_insert_text(GtkTextBuffer *textbuffer, GtkTextIter *location, gchar *text, gint len, winid_t win)
766 {
767         GtkTextBuffer *window_buffer = gtk_text_view_get_buffer( GTK_TEXT_VIEW(win->widget) );
768
769         /* Set the history position to NULL and erase the text we were already editing */
770         if(win->history_pos != NULL)
771         {
772                 g_free(win->history->data);
773                 win->history = g_list_delete_link(win->history, win->history);
774                 win->history_pos = NULL;
775         }
776
777         /* Apply the 'input' style to the text that was entered */
778         GtkTextIter end_iter;
779         gtk_text_buffer_get_end_iter(window_buffer, &end_iter);
780         GtkTextIter input_iter;
781         GtkTextMark *input_position = gtk_text_buffer_get_mark(window_buffer, "input_position");
782         gtk_text_buffer_get_iter_at_mark(window_buffer, &input_iter, input_position);
783         gtk_text_buffer_apply_tag_by_name(window_buffer, "default", &input_iter, &end_iter);
784         gtk_text_buffer_apply_tag_by_name(window_buffer, "input", &input_iter, &end_iter);
785         gtk_text_buffer_apply_tag_by_name(window_buffer, "glk-input", &input_iter, &end_iter);
786 }
787
788 /* Internal function: Callback for signal activate on the line input GtkEntry
789 in a text grid window. */
790 void
791 on_input_entry_activate(GtkEntry *input_entry, winid_t win)
792 {
793         g_signal_handler_block(win->widget, win->line_input_keypress_handler);
794
795         int chars_written = finish_text_grid_line_input(win, TRUE);
796         ChimaraGlk *glk = CHIMARA_GLK(gtk_widget_get_ancestor(win->widget, CHIMARA_TYPE_GLK));
797         event_throw(glk, evtype_LineInput, win, chars_written, 0);
798 }
799
800 /* Internal function: Callback for signal key-press-event on the line input
801 GtkEntry in a text grid window. */
802 gboolean
803 on_input_entry_key_press_event(GtkEntry *input_entry, GdkEventKey *event, winid_t win)
804 {
805         if(event->keyval == GDK_KEY_Up || event->keyval == GDK_KEY_KP_Up
806                 || event->keyval == GDK_KEY_Down || event->keyval == GDK_KEY_KP_Down)
807         {
808                 /* Prevent falling off the end of the history list */
809                 if( (event->keyval == GDK_KEY_Up || event->keyval == GDK_KEY_KP_Up)
810                         && win->history_pos && win->history_pos->next == NULL)
811                         return TRUE;
812                 if( (event->keyval == GDK_KEY_Down || event->keyval == GDK_KEY_KP_Down)
813                         && (win->history_pos == NULL || win->history_pos->prev == NULL) )
814                         return TRUE;
815
816                 if(win->history_pos == NULL)
817                 {
818                         const gchar *current_input = gtk_entry_get_text(input_entry);
819                         win->history = g_list_prepend(win->history, g_strdup(current_input));
820                         win->history_pos = win->history;
821                 }
822
823                 if(event->keyval == GDK_KEY_Up || event->keyval == GDK_KEY_KP_Up)
824                 {
825                         if(win->history_pos)
826                                 win->history_pos = g_list_next(win->history_pos);
827                         else
828                                 win->history_pos = win->history;
829                 }
830                 else /* down */
831                         win->history_pos = g_list_previous(win->history_pos);
832
833                 /* Insert the history item into the window */
834                 g_signal_handler_block(input_entry, win->line_input_entry_changed);
835                 gtk_entry_set_text(input_entry, win->history_pos->data);
836                 g_signal_handler_unblock(input_entry, win->line_input_entry_changed);
837                 return TRUE;
838         }
839         else if(g_slist_find(win->current_extra_line_terminators, GUINT_TO_POINTER(event->keyval)))
840         {
841                 /* If this key was a line terminator, pretend we pressed enter */
842                 on_input_entry_activate(input_entry, win);
843         }
844         return FALSE;
845 }
846
847 void
848 on_input_entry_changed(GtkEditable *editable, winid_t win)
849 {
850         /* Set the history position to NULL and erase the text we were already editing */
851         if(win->history_pos != NULL)
852         {
853                 g_free(win->history->data);
854                 win->history = g_list_delete_link(win->history, win->history);
855                 win->history_pos = NULL;
856         }
857 }
858
859 glui32
860 keyval_to_glk_keycode(guint keyval, gboolean unicode)
861 {
862         glui32 keycode;
863         switch(keyval) {
864                 case GDK_KEY_Up:
865                 case GDK_KEY_KP_Up: return keycode_Up;
866                 case GDK_KEY_Down:
867                 case GDK_KEY_KP_Down: return keycode_Down;
868                 case GDK_KEY_Left:
869                 case GDK_KEY_KP_Left: return keycode_Left;
870                 case GDK_KEY_Right:
871                 case GDK_KEY_KP_Right: return keycode_Right;
872                 case GDK_KEY_Linefeed:
873                 case GDK_KEY_Return:
874                 case GDK_KEY_KP_Enter: return keycode_Return;
875                 case GDK_KEY_Delete:
876                 case GDK_KEY_BackSpace:
877                 case GDK_KEY_KP_Delete: return keycode_Delete;
878                 case GDK_KEY_Escape: return keycode_Escape;
879                 case GDK_KEY_Tab:
880                 case GDK_KEY_KP_Tab: return keycode_Tab;
881                 case GDK_KEY_Page_Up:
882                 case GDK_KEY_KP_Page_Up: return keycode_PageUp;
883                 case GDK_KEY_Page_Down:
884                 case GDK_KEY_KP_Page_Down: return keycode_PageDown;
885                 case GDK_KEY_Home:
886                 case GDK_KEY_KP_Home: return keycode_Home;
887                 case GDK_KEY_End:
888                 case GDK_KEY_KP_End: return keycode_End;
889                 case GDK_KEY_F1:
890                 case GDK_KEY_KP_F1: return keycode_Func1;
891                 case GDK_KEY_F2:
892                 case GDK_KEY_KP_F2: return keycode_Func2;
893                 case GDK_KEY_F3:
894                 case GDK_KEY_KP_F3: return keycode_Func3;
895                 case GDK_KEY_F4:
896                 case GDK_KEY_KP_F4: return keycode_Func4;
897                 case GDK_KEY_F5: return keycode_Func5;
898                 case GDK_KEY_F6: return keycode_Func6;
899                 case GDK_KEY_F7: return keycode_Func7;
900                 case GDK_KEY_F8: return keycode_Func8;
901                 case GDK_KEY_F9: return keycode_Func9;
902                 case GDK_KEY_F10: return keycode_Func10;
903                 case GDK_KEY_F11: return keycode_Func11;
904                 case GDK_KEY_F12: return keycode_Func12;
905                 default:
906                         keycode = gdk_keyval_to_unicode(keyval);
907                         /* If keycode is 0, then keyval was not recognized; also return
908                         unknown if Latin-1 input was requested and the character is not in
909                         Latin-1 */
910                         if(keycode == 0 || (!unicode && keycode > 255))
911                                 return keycode_Unknown;
912                         return keycode;
913         }
914 }
915
916 void
917 force_char_input_from_queue(winid_t win, event_t *event)
918 {
919         ChimaraGlkPrivate *glk_data = g_private_get(&glk_data_key);
920         guint keyval = GPOINTER_TO_UINT(g_async_queue_pop(glk_data->char_input_queue));
921
922         glk_cancel_char_event(win);
923
924         gdk_threads_enter();
925         ChimaraGlk *glk = CHIMARA_GLK(gtk_widget_get_ancestor(win->widget, CHIMARA_TYPE_GLK));
926         g_assert(glk);
927         g_signal_emit_by_name(glk, "char-input", win->rock, keyval);
928         gdk_threads_leave();
929
930         event->type = evtype_CharInput;
931         event->win = win;
932         event->val1 = keyval_to_glk_keycode(keyval, win->input_request_type == INPUT_REQUEST_CHARACTER_UNICODE);
933         event->val2 = 0;
934 }
935
936 void
937 force_line_input_from_queue(winid_t win, event_t *event)
938 {
939         ChimaraGlkPrivate *glk_data = g_private_get(&glk_data_key);
940         const gchar *text = g_async_queue_pop(glk_data->line_input_queue);
941         glui32 chars_written = 0;
942
943         gdk_threads_enter();
944         if(win->type == wintype_TextBuffer)
945         {
946                 GtkTextBuffer *buffer = gtk_text_view_get_buffer( GTK_TEXT_VIEW(win->widget) );
947                 GtkTextIter start, end;
948
949                 /* Remove signal handlers so the line input doesn't get picked up again */
950                 g_signal_handler_block(buffer, win->insert_text_handler);
951                 g_signal_handler_block(win->widget, win->line_input_keypress_handler);
952
953                 /* Erase any text that was already typed */
954                 GtkTextMark *input_position = gtk_text_buffer_get_mark(buffer, "input_position");
955                 gtk_text_buffer_get_iter_at_mark(buffer, &start, input_position);
956                 gtk_text_buffer_get_end_iter(buffer, &end);
957                 gtk_text_buffer_delete(buffer, &start, &end);
958
959                 /* Make the window uneditable again */
960                 gtk_text_view_set_editable(GTK_TEXT_VIEW(win->widget), FALSE);
961
962                 /* Insert the forced input into the window */
963                 if(win->echo_current_line_input)
964                 {
965                         gtk_text_buffer_get_end_iter(buffer, &end);
966                         gchar *text_to_insert = g_strconcat(text, "\n", NULL);
967                         gtk_text_buffer_insert_with_tags_by_name(buffer, &end, text_to_insert, -1, "default", "input", "glk-input", NULL);
968                 }
969
970                 chars_written = finish_text_buffer_line_input(win, TRUE);
971         }
972         else if(win->type == wintype_TextGrid)
973         {
974                 /* Remove signal handlers so the line input doesn't get picked up again */
975                 g_signal_handler_block(win->widget, win->char_input_keypress_handler);
976
977                 /* Insert the forced input into the window */
978                 gtk_entry_set_text(GTK_ENTRY(win->input_entry), text);
979                 chars_written = finish_text_grid_line_input(win, TRUE);
980         }
981         gdk_threads_leave();
982
983         event->type = evtype_LineInput;
984         event->win = win;
985         event->val1 = chars_written;
986         event->val2 = 0;
987 }
988
989 /*** Internal function: cancels any pending input requests on the window and presents a warning if not INPUT_REQUEST_NONE ***/
990 void
991 cancel_old_input_request(winid_t win)
992 {
993         switch(win->input_request_type) {
994         case INPUT_REQUEST_NONE:
995                 break; /* All is well */
996         case INPUT_REQUEST_CHARACTER:
997         case INPUT_REQUEST_CHARACTER_UNICODE:
998                 glk_cancel_char_event(win);
999                 WARNING("Cancelling pending char event");
1000                 break;
1001         case INPUT_REQUEST_LINE:
1002         case INPUT_REQUEST_LINE_UNICODE:
1003                 glk_cancel_line_event(win, NULL);
1004                 WARNING("Cancelling pending line event");
1005                 break;
1006         default:
1007                 WARNING("Could not cancel pending input request: unknown input request");
1008         }
1009 }
1010
1011 /**
1012  * glk_set_echo_line_event:
1013  * @win: The window in which to change the echoing behavior.
1014  * @val: Zero to turn off echoing, nonzero for normal echoing.
1015  *
1016  * Normally, after line input is completed or cancelled in a buffer window, the
1017  * library ensures that the complete input line (or its latest state, after
1018  * cancelling) is displayed at the end of the buffer, followed by a newline.
1019  * This call allows you to suppress this behavior. If the @val argument is zero,
1020  * all <emphasis>subsequent</emphasis> line input requests in the given window
1021  * will leave the buffer unchanged after the input is completed or cancelled;
1022  * the player's input will not be printed. If @val is nonzero, subsequent input
1023  * requests will have the normal printing behavior.
1024  *
1025  * <note><para>
1026  *   Note that this feature is unrelated to the window's echo stream.
1027  * </para></note>
1028  *
1029  * If you turn off line input echoing, you can reproduce the standard input
1030  * behavior by following each line input event (or line input cancellation) by
1031  * printing the input line, in the Input style, followed by a newline in the
1032  * original style.
1033  *
1034  * The glk_set_echo_line_event() does not affect a pending line input request.
1035  * It also has no effect in non-buffer windows.
1036  * <note><para>
1037  *   In a grid window, the game can overwrite the input area at will, so there
1038  *   is no need for this distinction.
1039  * </para></note>
1040  *
1041  * Not all libraries support this feature. You can test for it with
1042  * %gestalt_LineInputEcho.
1043  */
1044 void
1045 glk_set_echo_line_event(winid_t win, glui32 val)
1046 {
1047         VALID_WINDOW(win, return);
1048
1049         if(win->type != wintype_TextBuffer)
1050                 return; /* Quietly do nothing */
1051
1052         win->echo_line_input = val? TRUE : FALSE;
1053 }
1054
1055 /* Internal function to convert from a Glk keycode to a GDK keyval. */
1056 static unsigned
1057 keycode_to_gdk_keyval(glui32 keycode)
1058 {
1059         switch (keycode)
1060         {
1061                 case keycode_Left:
1062                         return GDK_KEY_Left;
1063                 case keycode_Right:
1064                         return GDK_KEY_Right;
1065                 case keycode_Up:
1066                         return GDK_KEY_Up;
1067                 case keycode_Down:
1068                         return GDK_KEY_Down;
1069                 case keycode_Return:
1070                         return GDK_KEY_Return;
1071                 case keycode_Delete:
1072                         return GDK_KEY_Delete;
1073                 case keycode_Escape:
1074                         return GDK_KEY_Escape;
1075                 case keycode_Tab:
1076                         return GDK_KEY_Tab;
1077                 case keycode_PageUp:
1078                         return GDK_KEY_Page_Up;
1079                 case keycode_PageDown:
1080                         return GDK_KEY_Page_Down;
1081                 case keycode_Home:
1082                         return GDK_KEY_Home;
1083                 case keycode_End:
1084                         return GDK_KEY_End;
1085                 case keycode_Func1:
1086                         return GDK_KEY_F1;
1087                 case keycode_Func2:
1088                         return GDK_KEY_F2;
1089                 case keycode_Func3:
1090                         return GDK_KEY_F3;
1091                 case keycode_Func4:
1092                         return GDK_KEY_F4;
1093                 case keycode_Func5:
1094                         return GDK_KEY_F5;
1095                 case keycode_Func6:
1096                         return GDK_KEY_F6;
1097                 case keycode_Func7:
1098                         return GDK_KEY_F7;
1099                 case keycode_Func8:
1100                         return GDK_KEY_F8;
1101                 case keycode_Func9:
1102                         return GDK_KEY_F9;
1103                 case keycode_Func10:
1104                         return GDK_KEY_F10;
1105                 case keycode_Func11:
1106                         return GDK_KEY_F11;
1107                 case keycode_Func12:
1108                         return GDK_KEY_F12;
1109                 case keycode_Erase:
1110                         return GDK_KEY_BackSpace;
1111         }
1112         unsigned keyval = gdk_unicode_to_keyval(keycode);
1113         if(keyval < 0x01000000) /* magic number meaning illegal unicode point */
1114                 return keyval;
1115         return 0;
1116 }
1117
1118 /* Internal function to decide whether @keycode is a valid line terminator. */
1119 gboolean
1120 is_valid_line_terminator(glui32 keycode)
1121 {
1122         switch(keycode) {
1123                 case keycode_Escape:
1124                 case keycode_Func1:
1125                 case keycode_Func2:
1126                 case keycode_Func3:
1127                 case keycode_Func4:
1128                 case keycode_Func5:
1129                 case keycode_Func6:
1130                 case keycode_Func7:
1131                 case keycode_Func8:
1132                 case keycode_Func9:
1133                 case keycode_Func10:
1134                 case keycode_Func11:
1135                 case keycode_Func12:
1136                         return TRUE;
1137         }
1138         return FALSE;
1139 }
1140
1141 /**
1142  * glk_set_terminators_line_event:
1143  * @win: The window for which to set the line input terminator keys.
1144  * @keycodes: An array of <code>keycode_</code> constants, of length @count.
1145  * @count: The array length of @keycodes.
1146  *
1147  * It is possible to request that other keystrokes complete line input as well.
1148  * (This allows a game to intercept function keys or other special keys during
1149  * line input.) To do this, call glk_set_terminators_line_event(), and pass an
1150  * array of @count keycodes. These must all be special keycodes (see <link
1151  * linkend="chimara-Character-Input">Character Input</link>). Do not include
1152  * regular printable characters in the array, nor %keycode_Return (which
1153  * represents the default <keycap>enter</keycap> key and will always be
1154  * recognized). To return to the default behavior, pass a %NULL or empty array.
1155  *
1156  * The glk_set_terminators_line_event() affects <emphasis>subsequent</emphasis>
1157  * line input requests in the given window. It does not affect a pending line
1158  * input request.
1159  *
1160  * <note><para>
1161  *   This distinction makes life easier for interpreters that set up UI
1162  *   callbacks only at the start of input.
1163  * </para></note>
1164  *
1165  * A library may not support this feature; if it does, it may not support all
1166  * special keys as terminators. (Some keystrokes are reserved for OS or
1167  * interpreter control.) You can test for this with %gestalt_LineTerminators and
1168  * %gestalt_LineTerminatorKey.
1169  */
1170 void
1171 glk_set_terminators_line_event(winid_t win, glui32 *keycodes, glui32 count)
1172 {
1173         VALID_WINDOW(win, return);
1174
1175         g_slist_free(win->extra_line_terminators);
1176         win->extra_line_terminators = NULL;
1177
1178         if(keycodes == NULL || count == 0)
1179                 return;
1180
1181         int i;
1182         for(i = 0; i < count; i++)
1183         {
1184                 unsigned key = keycode_to_gdk_keyval(keycodes[i]);
1185                 if(is_valid_line_terminator(keycodes[i]))
1186                         win->extra_line_terminators = g_slist_prepend(win->extra_line_terminators, GUINT_TO_POINTER(key));
1187                 else
1188                    WARNING_S("Ignoring invalid line terminator", gdk_keyval_name(key));
1189         }
1190 }