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