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