648f44f03ae0a16c880071d433ec0093844ad123
[rodin/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
247         gchar *inserttext = (initlen > 0)? g_strndup(buf, initlen) : g_strdup("");
248         switch(win->type)
249         {
250             case wintype_TextBuffer:
251                 text_buffer_request_line_event_common(win, maxlen, (initlen > 0), inserttext);
252                 break;
253             case wintype_TextGrid:
254                 text_grid_request_line_event_common(win, maxlen, (initlen > 0), inserttext);
255                 break;
256     }
257         g_free(inserttext);
258         g_signal_handler_unblock(win->widget, win->line_input_keypress_handler);
259
260         /* Emit the "waiting" signal to let listeners know we are ready for input */
261         g_signal_emit_by_name(glk_data->self, "waiting");
262 }
263
264 /**
265  * glk_request_line_event_uni:
266  * @win: A text buffer or text grid window to request line input on.
267  * @buf: A buffer of at least @maxlen characters.
268  * @maxlen: Length of the buffer.
269  * @initlen: The number of characters in @buf to pre-enter.
270  *
271  * Request input of a line of Unicode characters. This works the same as
272  * glk_request_line_event(), except the result is stored in an array of
273  * <type>glui32</type> values instead of an array of characters, and the values
274  * may be any valid Unicode code points.
275  *
276  * The result will be in Unicode Normalization Form C. This basically means that
277  * composite characters will be single characters where possible, instead of
278  * sequences of base and combining marks. See
279  * <ulink url="http://www.unicode.org/reports/tr15/">Unicode Standard Annex
280  * #15</ulink> for the details.
281  */
282 void
283 glk_request_line_event_uni(winid_t win, glui32 *buf, glui32 maxlen, glui32 initlen)
284 {
285         VALID_WINDOW(win, return);
286         g_return_if_fail(buf);
287         g_return_if_fail(win->type != wintype_TextBuffer || win->type != wintype_TextGrid);
288         g_return_if_fail(initlen <= maxlen);
289
290         cancel_old_input_request(win);
291         ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
292
293         /* Register the buffer */
294         if(glk_data->register_arr)
295         win->buffer_rock = (*glk_data->register_arr)(buf, maxlen, "&+#!Iu");
296
297
298
299         win->input_request_type = INPUT_REQUEST_LINE_UNICODE;
300         win->line_input_buffer_unicode = buf;
301         win->line_input_buffer_max_len = maxlen;
302
303         gchar *utf8;
304         if(initlen > 0) {
305                 utf8 = convert_ucs4_to_utf8(buf, initlen);
306                 if(utf8 == NULL)
307                         return;
308         }
309         else
310                 utf8 = g_strdup("");
311
312     switch(win->type)
313         {
314             case wintype_TextBuffer:
315                 text_buffer_request_line_event_common(win, maxlen, (initlen > 0), utf8);
316                 break;
317             case wintype_TextGrid:
318                 text_grid_request_line_event_common(win, maxlen, (initlen > 0), utf8);
319                 break;
320     }
321     g_signal_handler_unblock(win->widget, win->line_input_keypress_handler);
322         g_free(utf8);
323
324         /* Emit the "waiting" signal to let listeners know we are ready for input */
325         g_signal_emit_by_name(glk_data->self, "waiting");
326 }
327
328 /**
329  * glk_cancel_line_event:
330  * @win: A text buffer or text grid window to cancel line input on.
331  * @event: Will be filled in if the user had already input something.
332  *
333  * This cancels a pending request for line input. (Either Latin-1 or Unicode.)
334  *
335  * The event pointed to by the event argument will be filled in as if the
336  * player had hit <keycap>enter</keycap>, and the input composed so far will be
337  * stored in the buffer; see below. If you do not care about this information,
338  * pass %NULL as the @event argument. (The buffer will still be filled.)
339  *
340  * For convenience, it is legal to call glk_cancel_line_event() even if there
341  * is no line input request on that window. The event type will be set to
342  * %evtype_None in this case.
343  */
344 void
345 glk_cancel_line_event(winid_t win, event_t *event)
346 {
347         VALID_WINDOW(win, return);
348         g_return_if_fail(win->type != wintype_TextBuffer || win->type != wintype_TextGrid);
349
350         if(event != NULL) {
351                 event->type = evtype_None;
352                 event->win = win;
353                 event->val1 = 0;
354                 event->val2 = 0;
355         }
356
357         if(win->input_request_type != INPUT_REQUEST_LINE && win->input_request_type != INPUT_REQUEST_LINE_UNICODE)
358                 return;
359
360         g_signal_handler_block( win->widget, win->line_input_keypress_handler );
361
362         int chars_written = 0;
363
364         gdk_threads_enter();
365         if(win->type == wintype_TextGrid) {
366                 chars_written = finish_text_grid_line_input(win, FALSE);
367         } else if(win->type == wintype_TextBuffer) {
368                 gtk_text_view_set_editable( GTK_TEXT_VIEW(win->widget), FALSE );
369                 GtkTextBuffer *window_buffer = gtk_text_view_get_buffer( GTK_TEXT_VIEW(win->widget) );
370                 g_signal_handler_block(window_buffer, win->insert_text_handler);
371                 chars_written = finish_text_buffer_line_input(win, FALSE);
372         }
373         gdk_threads_leave();
374
375         ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
376         if(glk_data->unregister_arr)
377         {
378                 if(win->input_request_type == INPUT_REQUEST_LINE_UNICODE)
379                         (*glk_data->unregister_arr)(win->line_input_buffer_unicode, win->line_input_buffer_max_len, "&+#!Iu", win->buffer_rock);
380                 else
381                 (*glk_data->unregister_arr)(win->line_input_buffer, win->line_input_buffer_max_len, "&+#!Cn", win->buffer_rock);
382     }
383
384         if(event != NULL && chars_written > 0) {
385                 event->type = evtype_LineInput;
386                 event->val1 = chars_written;
387         }
388 }
389
390 /* Helper function: Turn off shutdown key-press-event signal handler */
391 static gboolean
392 turn_off_handler(GNode *node)
393 {
394         winid_t win = node->data;
395         g_signal_handler_block(win->widget, win->shutdown_keypress_handler);
396         return FALSE; /* don't stop */
397 }
398
399 /* Internal function: Callback for signal key-press-event while waiting for shutdown. */
400 gboolean
401 on_shutdown_key_press_event(GtkWidget *widget, GdkEventKey *event, winid_t win)
402 {
403         ChimaraGlk *glk = CHIMARA_GLK(gtk_widget_get_ancestor(widget, CHIMARA_TYPE_GLK));
404         g_assert(glk);
405         CHIMARA_GLK_USE_PRIVATE(glk, priv);
406         
407         /* Turn off all the signal handlers */
408         if(priv->root_window)
409                 g_node_traverse(priv->root_window, G_IN_ORDER, G_TRAVERSE_LEAVES, -1, (GNodeTraverseFunc)turn_off_handler, NULL);
410         
411         /* Signal the Glk library that it can shut everything down now */
412         g_mutex_lock(priv->shutdown_lock);
413         g_cond_signal(priv->shutdown_key_pressed);
414         g_mutex_unlock(priv->shutdown_lock);
415         
416         return TRUE; /* block the event */
417 }
418
419 /* 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. */
420 gboolean
421 on_char_input_key_press_event(GtkWidget *widget, GdkEventKey *event, winid_t win)
422 {
423         /* Ignore modifier keys, otherwise the char input will already trigger on 
424         the shift key when the user tries to type a capital letter */
425         if(event->is_modifier)
426                 return FALSE; /* don't stop the event */
427
428         /* All text up to the input position is now regarded as being read by the user */
429         if(win->type == wintype_TextBuffer)
430                 pager_update(win);
431         
432         glui32 keycode = keyval_to_glk_keycode(event->keyval, win->input_request_type == INPUT_REQUEST_CHARACTER_UNICODE);
433
434         ChimaraGlk *glk = CHIMARA_GLK(gtk_widget_get_ancestor(widget, CHIMARA_TYPE_GLK));
435         g_assert(glk);
436         event_throw(glk, evtype_CharInput, win, keycode, 0);
437         g_signal_emit_by_name(glk, "char-input", win->rock, event->keyval);
438
439         /* Only one keypress will be handled */
440         win->input_request_type = INPUT_REQUEST_NONE;
441         g_signal_handler_block(win->widget, win->char_input_keypress_handler);
442
443         return TRUE;
444 }
445
446 gboolean
447 on_line_input_key_press_event(GtkWidget *widget, GdkEventKey *event, winid_t win)
448 {
449         switch(win->type)
450         {
451                 case wintype_TextBuffer:
452                         /* All text up to the input position is now regarded as being read by the user */
453                         pager_update(win);
454
455                         /* History up/down */
456                         if(event->keyval == GDK_Up || event->keyval == GDK_KP_Up
457                                 || event->keyval == GDK_Down || event->keyval == GDK_KP_Down)
458                         {
459                                 /* Prevent falling off the end of the history list */
460                                 if(win->history == NULL)
461                                         return TRUE;
462                                 if( (event->keyval == GDK_Up || event->keyval == GDK_KP_Up)
463                                         && win->history_pos && win->history_pos->next == NULL)
464                                         return TRUE;
465                                 if( (event->keyval == GDK_Down || event->keyval == GDK_KP_Down)
466                                         && (win->history_pos == NULL || win->history_pos->prev == NULL) )
467                                         return TRUE;
468
469                                 GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(win->widget));
470                                 GtkTextIter start, end;
471                                 /* Erase any text that was already typed */
472                                 GtkTextMark *input_position = gtk_text_buffer_get_mark(buffer, "input_position");
473                                 gtk_text_buffer_get_iter_at_mark(buffer, &start, input_position);
474                                 gtk_text_buffer_get_end_iter(buffer, &end);
475
476                                 if(win->history_pos == NULL) {
477                                         gchar *current_input = gtk_text_buffer_get_text(buffer, &start, &end, FALSE);
478                                         win->history = g_list_prepend(win->history, current_input);
479                                         win->history_pos = win->history;
480                                 }
481
482                                 gtk_text_buffer_delete(buffer, &start, &end);
483
484                                 if(event->keyval == GDK_Up || event->keyval == GDK_KP_Up)
485                                 {
486                                         if(win->history_pos)
487                                                 win->history_pos = g_list_next(win->history_pos);
488                                         else
489                                                 win->history_pos = win->history;
490                                 }
491                                 else /* down */
492                                         win->history_pos = g_list_previous(win->history_pos);
493
494                                 /* Insert the history item into the window */
495                                 gtk_text_buffer_get_end_iter(buffer, &end);
496
497                                 g_signal_handler_block(buffer, win->insert_text_handler);
498                                 gtk_text_buffer_insert_with_tags_by_name(buffer, &end, win->history_pos->data, -1, "input", NULL);
499                                 g_signal_handler_unblock(buffer, win->insert_text_handler);
500                                 return TRUE;
501                         }
502
503                         /* Move to beginning/end of input field */
504                         else if(event->keyval == GDK_Home) {
505                                 GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(win->widget));
506                                 GtkTextIter input_iter;
507                                 GtkTextMark *input_position = gtk_text_buffer_get_mark(buffer, "input_position");
508                                 gtk_text_buffer_get_iter_at_mark(buffer, &input_iter, input_position);
509                                 gtk_text_buffer_place_cursor(buffer, &input_iter);
510                                 return TRUE;
511                         }
512                         else if(event->keyval == GDK_End) {
513                                 GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(win->widget));
514                                 GtkTextIter end_iter;
515                                 gtk_text_buffer_get_end_iter(buffer, &end_iter);
516                                 gtk_text_buffer_place_cursor(buffer, &end_iter);
517                                 return TRUE;
518                         }
519
520                         /* Handle the enter key, which could occur in the middle of the sentence. */
521                         else if(event->keyval == GDK_Return || event->keyval == GDK_KP_Enter) {
522                                 GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(win->widget));
523                                 GtkTextIter end_iter;
524                                 gtk_text_buffer_get_end_iter(buffer, &end_iter);
525                                 gtk_text_buffer_place_cursor(buffer, &end_iter);
526                                 return FALSE; 
527                         }
528
529                         return FALSE;
530
531                 /* If this is a text grid window, then redirect the key press to the line input GtkEntry */
532                 case wintype_TextGrid:
533                 {
534                         if(event->keyval == GDK_Up || event->keyval == GDK_KP_Up
535                                 || event->keyval == GDK_Down || event->keyval == GDK_KP_Down
536                                 || event->keyval == GDK_Left || event->keyval == GDK_KP_Left
537                                 || event->keyval == GDK_Right || event->keyval == GDK_KP_Right
538                                 || event->keyval == GDK_Tab || event->keyval == GDK_KP_Tab
539                                 || event->keyval == GDK_Page_Up || event->keyval == GDK_KP_Page_Up
540                                 || event->keyval == GDK_Page_Down || event->keyval == GDK_KP_Page_Down
541                                 || event->keyval == GDK_Home || event->keyval == GDK_KP_Home
542                                 || event->keyval == GDK_End || event->keyval == GDK_KP_End)
543                                 return FALSE; /* Don't redirect these keys */
544                         gtk_widget_grab_focus(win->input_entry);
545                         gtk_editable_set_position(GTK_EDITABLE(win->input_entry), -1);
546                         gboolean retval = TRUE;
547                         g_signal_emit_by_name(win->input_entry, "key-press-event", event, &retval);
548                         return retval; /* Block this key event if the entry handled it */
549                 }
550         }
551         return FALSE;
552 }
553
554 /* Internal function: finish handling a line input request, for both text grid and text buffer windows. */
555 static int
556 write_to_window_buffer(winid_t win, const gchar *inserted_text)
557 {
558         int copycount = 0;
559
560     /* Convert the string from UTF-8 to Latin-1 or Unicode */
561     if(win->input_request_type == INPUT_REQUEST_LINE)
562     {
563         gsize bytes_written;
564         gchar *latin1 = convert_utf8_to_latin1(inserted_text, &bytes_written);
565
566         if(latin1 == NULL)
567             return 0;
568
569         /* Place input in the echo stream */
570         if(win->echo_stream != NULL)
571             glk_put_string_stream(win->echo_stream, latin1);
572
573         /* Copy the string (bytes_written does not include the NULL at the end) */
574         copycount = MIN(win->line_input_buffer_max_len, bytes_written);
575         memcpy(win->line_input_buffer, latin1, copycount);
576         g_free(latin1);
577     }
578     else if(win->input_request_type == INPUT_REQUEST_LINE_UNICODE)
579     {
580         glong items_written;
581         gunichar *unicode = convert_utf8_to_ucs4(inserted_text, &items_written);
582
583         if(unicode == NULL)
584             return 0;
585
586         /* Place input in the echo stream */
587         if(win->echo_stream != NULL)
588             glk_put_string_stream_uni(win->echo_stream, unicode);
589
590         /* Copy the string (but not the NULL at the end) */
591         copycount = MIN(win->line_input_buffer_max_len, items_written);
592         memcpy(win->line_input_buffer_unicode, unicode, copycount * sizeof(gunichar));
593         g_free(unicode);
594     }
595     else
596         WARNING("Wrong input request type");
597
598     win->input_request_type = INPUT_REQUEST_NONE;
599         return copycount;
600 }
601
602 /* Internal function: Retrieves the input of a TextBuffer window and stores it in the window buffer.
603  * Returns the number of characters written, suitable for inclusion in a line input event. */
604 static int
605 finish_text_buffer_line_input(winid_t win, gboolean emit_signal)
606 {
607         VALID_WINDOW(win, return 0);
608         g_return_val_if_fail(win->type == wintype_TextBuffer, 0);
609
610         GtkTextIter start_iter, end_iter, last_character;
611
612         GtkTextBuffer *window_buffer = gtk_text_view_get_buffer( GTK_TEXT_VIEW(win->widget) );
613         GtkTextMark *input_position = gtk_text_buffer_get_mark(window_buffer, "input_position");
614         gtk_text_buffer_get_iter_at_mark(window_buffer, &start_iter, input_position);
615         gtk_text_buffer_get_end_iter(window_buffer, &end_iter);
616         gtk_text_buffer_get_end_iter(window_buffer, &last_character);
617         gtk_text_iter_backward_cursor_position(&last_character);
618
619         gchar* last_char = gtk_text_buffer_get_text(window_buffer, &last_character, &end_iter, FALSE);
620
621         if( strchr(last_char, '\n') != NULL )
622                 gtk_text_iter_backward_cursor_position(&end_iter);
623
624         gchar* inserted_text = gtk_text_buffer_get_text(window_buffer, &start_iter, &end_iter, FALSE);
625
626         int chars_written = write_to_window_buffer(win, inserted_text);
627         if(emit_signal)
628         {
629                 ChimaraGlk *glk = CHIMARA_GLK(gtk_widget_get_ancestor(win->widget, CHIMARA_TYPE_GLK));
630                 g_assert(glk);
631                 g_signal_emit_by_name(glk, "line-input", win->rock, inserted_text);
632         }
633
634         /* Add the text to the window input history */
635         if(win->history_pos != NULL)
636         {
637                 g_free(win->history->data);
638                 win->history = g_list_delete_link(win->history, win->history);
639         }
640         if(*inserted_text != 0)
641                 win->history = g_list_prepend(win->history, g_strdup(inserted_text));
642
643         win->history_pos = NULL;
644
645         g_free(inserted_text);
646
647         return chars_written;
648 }
649
650 /* Internal function: Retrieves the input of a TextGrid window and stores it in the window buffer.
651  * Returns the number of characters written, suitable for inclusion in a line input event. */
652 static int
653 finish_text_grid_line_input(winid_t win, gboolean emit_signal)
654 {
655         VALID_WINDOW(win, return 0);
656         g_return_val_if_fail(win->type == wintype_TextGrid, 0);
657
658         GtkTextBuffer *buffer = gtk_text_view_get_buffer( GTK_TEXT_VIEW(win->widget) );
659
660         gchar *text = g_strdup( gtk_entry_get_text(GTK_ENTRY(win->input_entry)) );
661         /* Move the focus back into the text view */
662         gtk_widget_grab_focus(win->widget);
663         /* Remove entry widget from text view */
664         /* Should be ok even though this is the widget's own signal handler */
665         gtk_container_remove( GTK_CONTAINER(win->widget), GTK_WIDGET(win->input_entry) );
666         win->input_entry = NULL;
667         /* Delete the child anchor */
668         GtkTextIter start, end;
669         gtk_text_buffer_get_iter_at_child_anchor(buffer, &start, win->input_anchor);
670         end = start;
671         gtk_text_iter_forward_char(&end); /* Point after the child anchor */
672         gtk_text_buffer_delete(buffer, &start, &end);
673         win->input_anchor = NULL;
674
675     gchar *spaces = g_strnfill(win->input_length - g_utf8_strlen(text, -1), ' ');
676     gchar *text_to_insert = g_strconcat(text, spaces, NULL);
677         g_free(spaces);
678     gtk_text_buffer_insert(buffer, &start, text_to_insert, -1);
679     g_free(text_to_insert);
680
681     int chars_written = write_to_window_buffer(win, text);
682     if(emit_signal)
683     {
684                 ChimaraGlk *glk = CHIMARA_GLK(gtk_widget_get_ancestor(win->widget, CHIMARA_TYPE_GLK));
685                 g_assert(glk);
686                 g_signal_emit_by_name(glk, "line-input", win->rock, text);
687     }
688
689         /* Add the text to the window input history */
690         if(win->history_pos != NULL)
691         {
692                 g_free(win->history->data);
693                 win->history = g_list_delete_link(win->history, win->history);
694         }
695         if(*text != 0)
696                 win->history = g_list_prepend(win->history, g_strdup(text));
697         win->history_pos = NULL;
698
699         g_free(text);
700         return chars_written;
701 }
702
703 /* Internal function: Callback for signal insert-text on a text buffer window.
704 Runs after the default handler has already inserted the text.
705 FIXME: This function assumes that newline was the last character typed into the
706 window. That assumption is wrong if, for example, text containing a newline was
707 pasted into the window. */
708 void
709 after_window_insert_text(GtkTextBuffer *textbuffer, GtkTextIter *location, gchar *text, gint len, winid_t win)
710 {
711         GtkTextBuffer *window_buffer = gtk_text_view_get_buffer( GTK_TEXT_VIEW(win->widget) );
712
713         /* Set the history position to NULL and erase the text we were already editing */
714         if(win->history_pos != NULL)
715         {
716                 g_free(win->history->data);
717                 win->history = g_list_delete_link(win->history, win->history);
718                 win->history_pos = NULL;
719         }
720         if( strchr(text, '\n') != NULL )
721         {
722                 /* Remove signal handlers */
723                 g_signal_handler_block(window_buffer, win->insert_text_handler);
724                 g_signal_handler_block(win->widget, win->line_input_keypress_handler);
725
726                 /* Make the window uneditable again and retrieve the text that was input */
727         gtk_text_view_set_editable(GTK_TEXT_VIEW(win->widget), FALSE);
728
729         int chars_written = finish_text_buffer_line_input(win, TRUE);
730         ChimaraGlk *glk = CHIMARA_GLK(gtk_widget_get_ancestor(win->widget, CHIMARA_TYPE_GLK));
731                 event_throw(glk, evtype_LineInput, win, chars_written, 0);
732         }
733
734         /* Apply the 'input' style to the text that was entered */
735         GtkTextIter end_iter;
736         gtk_text_buffer_get_end_iter(window_buffer, &end_iter);
737         GtkTextIter input_iter;
738         GtkTextMark *input_position = gtk_text_buffer_get_mark(window_buffer, "input_position");
739         gtk_text_buffer_get_iter_at_mark(window_buffer, &input_iter, input_position);
740         gtk_text_buffer_apply_tag_by_name(window_buffer, "input", &input_iter, &end_iter);
741 }
742
743 /* Internal function: Callback for signal activate on the line input GtkEntry
744 in a text grid window. */
745 void
746 on_input_entry_activate(GtkEntry *input_entry, winid_t win)
747 {
748         g_signal_handler_block(win->widget, win->line_input_keypress_handler);
749
750         int chars_written = finish_text_grid_line_input(win, TRUE);
751         ChimaraGlk *glk = CHIMARA_GLK(gtk_widget_get_ancestor(win->widget, CHIMARA_TYPE_GLK));
752         event_throw(glk, evtype_LineInput, win, chars_written, 0);
753 }
754
755 /* Internal function: Callback for signal key-press-event on the line input
756 GtkEntry in a text grid window. */
757 gboolean
758 on_input_entry_key_press_event(GtkEntry *input_entry, GdkEventKey *event, winid_t win)
759 {
760         if(event->keyval == GDK_Up || event->keyval == GDK_KP_Up
761                 || event->keyval == GDK_Down || event->keyval == GDK_KP_Down)
762         {
763                 /* Prevent falling off the end of the history list */
764                 if( (event->keyval == GDK_Up || event->keyval == GDK_KP_Up)
765                         && win->history_pos && win->history_pos->next == NULL)
766                         return TRUE;
767                 if( (event->keyval == GDK_Down || event->keyval == GDK_KP_Down)
768                         && (win->history_pos == NULL || win->history_pos->prev == NULL) )
769                         return TRUE;
770
771                 if(win->history_pos == NULL)
772                 {
773                         const gchar *current_input = gtk_entry_get_text(input_entry);
774                         win->history = g_list_prepend(win->history, g_strdup(current_input));
775                         win->history_pos = win->history;
776                 }
777
778                 if(event->keyval == GDK_Up || event->keyval == GDK_KP_Up)
779                 {
780                         if(win->history_pos)
781                                 win->history_pos = g_list_next(win->history_pos);
782                         else
783                                 win->history_pos = win->history;
784                 }
785                 else /* down */
786                         win->history_pos = g_list_previous(win->history_pos);
787
788                 /* Insert the history item into the window */
789                 g_signal_handler_block(input_entry, win->line_input_entry_changed);
790                 gtk_entry_set_text(input_entry, win->history_pos->data);
791                 g_signal_handler_unblock(input_entry, win->line_input_entry_changed);
792                 return TRUE;
793         }
794         return FALSE;
795 }
796
797 void
798 on_input_entry_changed(GtkEditable *editable, winid_t win)
799 {
800         /* Set the history position to NULL and erase the text we were already editing */
801         if(win->history_pos != NULL)
802         {
803                 g_free(win->history->data);
804                 win->history = g_list_delete_link(win->history, win->history);
805                 win->history_pos = NULL;
806         }
807 }
808
809 glui32
810 keyval_to_glk_keycode(guint keyval, gboolean unicode)
811 {
812         glui32 keycode;
813         switch(keyval) {
814                 case GDK_Up:
815                 case GDK_KP_Up: return keycode_Up;
816                 case GDK_Down:
817                 case GDK_KP_Down: return keycode_Down;
818                 case GDK_Left:
819                 case GDK_KP_Left: return keycode_Left;
820                 case GDK_Right:
821                 case GDK_KP_Right: return keycode_Right;
822                 case GDK_Linefeed:
823                 case GDK_Return:
824                 case GDK_KP_Enter: return keycode_Return;
825                 case GDK_Delete:
826                 case GDK_BackSpace:
827                 case GDK_KP_Delete: return keycode_Delete;
828                 case GDK_Escape: return keycode_Escape;
829                 case GDK_Tab:
830                 case GDK_KP_Tab: return keycode_Tab;
831                 case GDK_Page_Up:
832                 case GDK_KP_Page_Up: return keycode_PageUp;
833                 case GDK_Page_Down:
834                 case GDK_KP_Page_Down: return keycode_PageDown;
835                 case GDK_Home:
836                 case GDK_KP_Home: return keycode_Home;
837                 case GDK_End:
838                 case GDK_KP_End: return keycode_End;
839                 case GDK_F1:
840                 case GDK_KP_F1: return keycode_Func1;
841                 case GDK_F2:
842                 case GDK_KP_F2: return keycode_Func2;
843                 case GDK_F3:
844                 case GDK_KP_F3: return keycode_Func3;
845                 case GDK_F4:
846                 case GDK_KP_F4: return keycode_Func4;
847                 case GDK_F5: return keycode_Func5;
848                 case GDK_F6: return keycode_Func6;
849                 case GDK_F7: return keycode_Func7;
850                 case GDK_F8: return keycode_Func8;
851                 case GDK_F9: return keycode_Func9;
852                 case GDK_F10: return keycode_Func10;
853                 case GDK_F11: return keycode_Func11;
854                 case GDK_F12: return keycode_Func12;
855                 default:
856                         keycode = gdk_keyval_to_unicode(keyval);
857                         /* If keycode is 0, then keyval was not recognized; also return
858                         unknown if Latin-1 input was requested and the character is not in
859                         Latin-1 */
860                         if(keycode == 0 || (!unicode && keycode > 255))
861                                 return keycode_Unknown;
862                         return keycode;
863         }
864 }
865
866 void
867 force_char_input_from_queue(winid_t win, event_t *event)
868 {
869         ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
870         guint keyval = GPOINTER_TO_UINT(g_async_queue_pop(glk_data->char_input_queue));
871
872         glk_cancel_char_event(win);
873
874         gdk_threads_enter();
875         ChimaraGlk *glk = CHIMARA_GLK(gtk_widget_get_ancestor(win->widget, CHIMARA_TYPE_GLK));
876         g_assert(glk);
877         g_signal_emit_by_name(glk, "char-input", win->rock, keyval);
878         gdk_threads_leave();
879
880         event->type = evtype_CharInput;
881         event->win = win;
882         event->val1 = keyval_to_glk_keycode(keyval, win->input_request_type == INPUT_REQUEST_CHARACTER_UNICODE);
883         event->val2 = 0;
884 }
885
886 void
887 force_line_input_from_queue(winid_t win, event_t *event)
888 {
889         ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
890         const gchar *text = g_async_queue_pop(glk_data->line_input_queue);
891         glui32 chars_written = 0;
892
893         gdk_threads_enter();
894         if(win->type == wintype_TextBuffer)
895         {
896                 GtkTextBuffer *buffer = gtk_text_view_get_buffer( GTK_TEXT_VIEW(win->widget) );
897                 GtkTextIter start, end;
898
899                 /* Remove signal handlers so the line input doesn't get picked up again */
900                 g_signal_handler_block(buffer, win->insert_text_handler);
901                 g_signal_handler_block(win->widget, win->line_input_keypress_handler);
902
903                 /* Erase any text that was already typed */
904                 GtkTextMark *input_position = gtk_text_buffer_get_mark(buffer, "input_position");
905                 gtk_text_buffer_get_iter_at_mark(buffer, &start, input_position);
906                 gtk_text_buffer_get_end_iter(buffer, &end);
907                 gtk_text_buffer_delete(buffer, &start, &end);
908
909                 /* Make the window uneditable again */
910                 gtk_text_view_set_editable(GTK_TEXT_VIEW(win->widget), FALSE);
911
912                 /* Insert the forced input into the window */
913                 gtk_text_buffer_get_end_iter(buffer, &end);
914                 gchar *text_to_insert = g_strconcat(text, "\n", NULL);
915                 gtk_text_buffer_insert_with_tags_by_name(buffer, &end, text_to_insert, -1, "input", NULL);
916                 chars_written = finish_text_buffer_line_input(win, TRUE);
917         }
918         else if(win->type == wintype_TextGrid)
919         {
920                 /* Remove signal handlers so the line input doesn't get picked up again */
921                 g_signal_handler_block(win->widget, win->char_input_keypress_handler);
922
923                 /* Insert the forced input into the window */
924                 gtk_entry_set_text(GTK_ENTRY(win->input_entry), text);
925                 chars_written = finish_text_grid_line_input(win, TRUE);
926         }
927         gdk_threads_leave();
928
929         event->type = evtype_LineInput;
930         event->win = win;
931         event->val1 = chars_written;
932         event->val2 = 0;
933 }
934
935 /*** Internal function: cancels any pending input requests on the window and presents a warning if not INPUT_REQUEST_NONE ***/
936 void
937 cancel_old_input_request(winid_t win)
938 {
939         switch(win->input_request_type) {
940         case INPUT_REQUEST_NONE:
941                 break; /* All is well */
942         case INPUT_REQUEST_CHARACTER:
943         case INPUT_REQUEST_CHARACTER_UNICODE:
944                 glk_cancel_char_event(win);
945                 WARNING("Cancelling pending char event");
946                 break;
947         case INPUT_REQUEST_LINE:
948         case INPUT_REQUEST_LINE_UNICODE:
949                 glk_cancel_line_event(win, NULL);
950                 WARNING("Cancelling pending line event");
951                 break;
952         default:
953                 WARNING("Could not cancel pending input request: unknown input request");
954         }
955 }