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