summaryrefslogtreecommitdiff
path: root/src/sdtui.c
blob: 0c03ff54b94ec12ecf556a97b45c4de5d8fc3294 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
/*
 * StarDict terminal UI
 *
 * Copyright (c) 2013, Přemysl Janouch <p.janouch@gmail.com>
 * All rights reserved.
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#define _XOPEN_SOURCE_EXTENDED         /**< Yes, we want ncursesw. */

#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <stdarg.h>
#include <limits.h>
#include <string.h>

#include <glib.h>
#include <gio/gio.h>
#include <pango/pango.h>
#include <ncurses.h>
#include <glib/gi18n.h>

#include <unistd.h>
#include <poll.h>
#include <errno.h>
#include <signal.h>

#include "config.h"
#include "stardict.h"


#define KEY_SOH      1                 //!< Ctrl-A
#define KEY_STX      2                 //!< Ctrl-B
#define KEY_ENQ      5                 //!< Ctrl-E
#define KEY_ACK      6                 //!< Ctrl-F
#define KEY_VT      11                 //!< Ctrl-K
#define KEY_FF      12                 //!< Ctrl-L
#define KEY_SO      14                 //!< Ctrl-N
#define KEY_DLE     16                 //!< Ctrl-P
#define KEY_NAK     21                 //!< Ctrl-U
#define KEY_ETB     23                 //!< Ctrl-W

#define KEY_RETURN  13                 //!< Enter
#define KEY_ESCAPE  27                 //!< Esc

typedef enum {
	TERMINAL_UNKNOWN,                  //!< No extra handling
	TERMINAL_XTERM,                    //!< xterm and VTE extra keycodes
	TERMINAL_RXVT                      //!< rxvt extra keycodes
} TerminalType;                        //!< Type of the terminal

typedef enum {
	KEY_NOT_RECOGNISED,                //!< Not recognised

	KEY_CTRL_UP,                       //!< Ctrl + Up arrow
	KEY_CTRL_DOWN,                     //!< Ctrl + Down arrow
	KEY_CTRL_LEFT,                     //!< Ctrl + Left arrow
	KEY_CTRL_RIGHT,                    //!< Ctrl + Right arrow

	KEY_ALT_UP,                        //!< Alt + Up arrow
	KEY_ALT_DOWN,                      //!< Alt + Down arrow
	KEY_ALT_LEFT,                      //!< Alt + Left arrow
	KEY_ALT_RIGHT                      //!< Alt + Right arrow
} ExtraKeyCode;                        //!< Translated key codes above KEY_MAX

// --- Utilities ---------------------------------------------------------------

static int
poll_restart (struct pollfd *fds, nfds_t nfds, int timeout)
{
	int ret;
	do
		ret = poll (fds, nfds, timeout);
	while (ret == -1 && errno == EINTR);
	return ret;
}

/** Wrapper for curses event data. */
typedef struct curses_event            CursesEvent;

struct curses_event
{
	wint_t  code;
	guint   is_char : 1;
	MEVENT  mouse;
};

static gboolean
is_character_in_locale (wchar_t c)
{
	cchar_t cch;
	return setcchar (&cch, &c, A_NORMAL, 0, NULL) != ERR;
}

/** Translate key codes above KEY_MAX returned from ncurses into something
 *  meaningful, based on the terminal type.  The values have been obtained
 *  experimentally.  Some keycodes make ncurses return KEY_ESCAPE, even
 *  depending on actual terminal settings, thus this is not reliable at all.
 *  xterm/VTE seems to behave nicely, though.
 */
static guint
translate_extra_keycode (wchar_t code, TerminalType terminal)
{
	switch (terminal)
	{
	case TERMINAL_XTERM:
		switch (code)
		{
		case 565: return KEY_CTRL_UP;
		case 524: return KEY_CTRL_DOWN;
		case 544: return KEY_CTRL_LEFT;
		case 559: return KEY_CTRL_RIGHT;

		case 563: return KEY_ALT_UP;
		case 522: return KEY_ALT_DOWN;
		case 542: return KEY_ALT_LEFT;
		case 557: return KEY_ALT_RIGHT;
		}
		break;
	case TERMINAL_RXVT:
		switch (code)
		{
		case 521: return KEY_CTRL_UP;
		case 514: return KEY_CTRL_DOWN;
		}
		break;
	case TERMINAL_UNKNOWN:
		break;
	}
	return KEY_NOT_RECOGNISED;
}

/** Get the type of the terminal based on the TERM environment variable. */
static TerminalType
get_terminal_type (void)
{
	const gchar *term = g_getenv ("TERM");
	if (!term)  return TERMINAL_UNKNOWN;

	gchar term_copy[strcspn (term, "-") + 1];
	g_strlcpy (term_copy, term, sizeof term_copy);
	if (!strcmp (term_copy, "xterm"))  return TERMINAL_XTERM;
	if (!strcmp (term_copy, "rxvt"))   return TERMINAL_RXVT;
	return TERMINAL_UNKNOWN;
}

// --- Application -------------------------------------------------------------

/** Data relating to one entry within the dictionary. */
typedef struct view_entry               ViewEntry;
/** Encloses application data. */
typedef struct application              Application;

struct view_entry
{
	gchar   * word;                     //!< Word
	gchar  ** definitions;              //!< Word definition entries
	gsize     definitions_length;       //!< Length of the @a definitions array
};

struct application
{
	TerminalType    terminal_type;      //!< Type of the terminal
	GIConv          utf8_to_wchar;      //!< utf-8 -> wchar_t conversion
	GIConv          wchar_to_utf8;      //!< wchar_t -> utf-8 conversion

	StardictDict  * dict;               //!< The current dictionary
	guint           show_help : 1;      //!< Whether help can be shown

	guint32         top_position;       //!< Index of the topmost dict. entry
	guint           top_offset;         //!< Offset into the top entry
	guint           selected;           //!< Offset to the selected definition
	GPtrArray     * entries;            //!< ViewEntry's within the view

	gchar         * search_label;       //!< Text of the "Search" label
	GArray        * input;              //!< The current search input
	guint           input_pos;          //!< Cursor position within input
	gboolean        input_confirmed;    //!< Input has been confirmed

	gfloat          division;           //!< Position of the division column
};


/** Splits the entry and adds it to a pointer array. */
static void
view_entry_split_add (GPtrArray *out, const gchar *text)
{
	gchar **it, **tmp = g_strsplit (text, "\n", -1);
	for (it = tmp; *it; it++)
		if (**it)
			g_ptr_array_add (out, g_strdup (*it));
	g_strfreev (tmp);
}

/** Decomposes a dictionary entry into the format we want. */
static ViewEntry *
view_entry_new (StardictIterator *iterator)
{
	g_return_val_if_fail (stardict_iterator_is_valid (iterator), NULL);

	ViewEntry *ve = g_slice_alloc (sizeof *ve);
	GString *word = g_string_new (stardict_iterator_get_word (iterator));

	StardictEntry *entry = stardict_iterator_get_entry (iterator);
	g_return_val_if_fail (entry != NULL, NULL);

	GPtrArray *definitions = g_ptr_array_new ();
	const GList *fields = stardict_entry_get_fields (entry);
	gboolean found_anything_displayable = FALSE;
	while (fields)
	{
		const StardictEntryField *field = fields->data;
		switch (field->type)
		{
		case STARDICT_FIELD_MEANING:
			view_entry_split_add (definitions, field->data);
			found_anything_displayable = TRUE;
			break;
		case STARDICT_FIELD_PANGO:
		{
			char *text;
			if (!pango_parse_markup (field->data, -1,
				0, NULL, &text, NULL, NULL))
				text = g_strdup_printf ("<%s>", _("error in entry"));
			view_entry_split_add (definitions, text);
			found_anything_displayable = TRUE;
			g_free (text);
			break;
		}
		case STARDICT_FIELD_PHONETIC:
			g_string_append_printf (word, " /%s/", (const gchar *) field->data);
			break;
		default:
			// TODO support more of them
			break;
		}
		fields = fields->next;
	}
	g_object_unref (entry);

	if (!found_anything_displayable)
		g_ptr_array_add (definitions,
			g_strdup_printf ("<%s>", _("no usable field found")));

	ve->word = g_string_free (word, FALSE);
	ve->definitions_length = definitions->len;
	g_ptr_array_add (definitions, NULL);
	ve->definitions = (gchar **) g_ptr_array_free (definitions, FALSE);
	return ve;
}

/** Release resources associated with the view entry. */
static void
view_entry_free (ViewEntry *ve)
{
	g_free (ve->word);
	g_strfreev (ve->definitions);
	g_slice_free1 (sizeof *ve, ve);
}

/** Reload view items. */
static void
app_reload_view (Application *self)
{
	if (self->entries->len != 0)
		g_ptr_array_remove_range (self->entries, 0, self->entries->len);

	gint remains = LINES - 1 + self->top_offset;
	StardictIterator *iterator =
		stardict_iterator_new (self->dict, self->top_position);
	while (remains > 0 && stardict_iterator_is_valid (iterator))
	{
		ViewEntry *entry = view_entry_new (iterator);
		remains -= entry->definitions_length;
		g_ptr_array_add (self->entries, entry);
		stardict_iterator_next (iterator);
	}
	g_object_unref (iterator);
}

/** Initialize the application core. */
static void
app_init (Application *self, const gchar *filename)
{
	GError *error = NULL;
	self->dict = stardict_dict_new (filename, &error);
	if (!self->dict)
	{
		g_printerr ("%s: %s\n", _("Error loading dictionary"), error->message);
		exit (EXIT_FAILURE);
	}

	self->terminal_type = get_terminal_type ();
	self->show_help = TRUE;

	self->top_position = 0;
	self->top_offset = 0;
	self->selected = 0;
	self->entries = g_ptr_array_new_with_free_func
		((GDestroyNotify) view_entry_free);

	self->search_label = g_strdup_printf ("%s: ", _("Search"));

	self->input = g_array_new (TRUE, FALSE, sizeof (gunichar));
	self->input_pos = 0;
	self->input_confirmed = FALSE;

	self->division = 0.5;

	self->wchar_to_utf8 = g_iconv_open ("utf-8//translit", "wchar_t");
	self->utf8_to_wchar = g_iconv_open ("wchar_t//translit", "utf-8");

	app_reload_view (self);
}

/** Free any resources used by the application. */
static void
app_destroy (Application *self)
{
	g_object_unref (self->dict);
	g_ptr_array_free (self->entries, TRUE);
	g_free (self->search_label);
	g_array_free (self->input, TRUE);

	g_iconv_close (self->wchar_to_utf8);
	g_iconv_close (self->utf8_to_wchar);
}

/** Write the given utf-8 string padded with spaces.
 *  @param[in] n  The number of characters to write, or -1 for the whole string.
 *  @return The number of wide characters written.
 */
static gsize
app_add_utf8_string (Application *self, const gchar *str, int n)
{
	wchar_t *wide_str = (wchar_t *) g_convert_with_iconv
		(str, -1, self->utf8_to_wchar, NULL, NULL, NULL);
	g_return_val_if_fail (wide_str != NULL, 0);

	ssize_t wide_len = wcslen (wide_str);
	wchar_t padding = L' ', error = L'?', ellipsis = L'…';

	if (n < 0)
		n = wide_len;

	if (wide_len > n)
	{
		if (is_character_in_locale (ellipsis) && n > 0)
			wide_str[n - 1] = ellipsis;
		else if (n >= 3)
		{
			wide_str[n - 1] = L'.';
			wide_str[n - 2] = L'.';
			wide_str[n - 3] = L'.';
		}
	}

	gint i;
	cchar_t cch;
	for (i = 0; i < n; i++)
	{
		if (setcchar (&cch, (i < wide_len ? &wide_str[i] : &padding),
			A_NORMAL, 0, NULL) == ERR)
			setcchar (&cch, &error, A_NORMAL, 0, NULL);
		add_wch (&cch);
	}

	g_free (wide_str);
	return n;
}

/** Render the top bar. */
static void
app_redraw_top (Application *self)
{
	mvwhline (stdscr, 0, 0, A_UNDERLINE, COLS);
	attrset (A_UNDERLINE);
	gsize indent = app_add_utf8_string (self, self->search_label, -1);

	gchar *input_utf8 = g_ucs4_to_utf8
		((gunichar *) self->input->data, -1, NULL, NULL, NULL);
	g_return_if_fail (input_utf8 != NULL);

	if (self->input_confirmed)
		attron (A_BOLD);
	app_add_utf8_string (self, input_utf8, COLS - indent);
	g_free (input_utf8);

	move (0, indent + self->input_pos);
	refresh ();
}

/** Computes width for the left column. */
static guint
app_get_left_column_width (Application *self)
{
	gint width = COLS * self->division + 0.5;
	if (width < 1)
		width = 1;
	else if (width > COLS - 2)
		width = COLS - 2;
	return width;
}

/** Display a message in the view area. */
static void
app_show_message (Application *self, const gchar *lines[], gsize len)
{
	gint top = (LINES - 1 - len) / 2;

	gint i;
	for (i = 0; i < top; i++)
	{
		move (1 + i, 0);
		clrtoeol ();
	}

	attrset (0);
	while (len-- && i < LINES - 1)
	{
		move (1 + i, 0);
		clrtoeol ();

		gint x = (COLS - g_utf8_strlen (*lines, -1)) / 2;
		if (x < 0)
			x = 0;

		move (1 + i, x);
		app_add_utf8_string (self, *lines, COLS - x);

		lines++;
		i++;
	}

	clrtobot ();
	refresh ();
}

/** Show some information about the program. */
static void
app_show_help (Application *self)
{
	const gchar *lines[] =
	{
		PROJECT_NAME " " PROJECT_VERSION,
		_("Terminal UI for StarDict dictionaries"),
		"Copyright (c) 2013, Přemysl Janouch",
		"",
		_("Type to search")
	};

	app_show_message (self, lines, G_N_ELEMENTS (lines));
}

/** Redraw the dictionary view. */
static void
app_redraw_view (Application *self)
{
	if (self->show_help)
	{
		app_show_help (self);
		return;
	}

	move (1, 0);

	guint i, k = self->top_offset, shown = 0;
	for (i = 0; i < self->entries->len; i++)
	{
		ViewEntry *ve = g_ptr_array_index (self->entries, i);
		for (; k < ve->definitions_length; k++)
		{
			int attrs = 0;
			if (shown == self->selected)          attrs |= A_REVERSE;
			if (k + 1 == ve->definitions_length)  attrs |= A_UNDERLINE;
			attrset (attrs);

			guint left_width = app_get_left_column_width (self);
			app_add_utf8_string (self, ve->word, left_width);
			addwstr (L" ");
			app_add_utf8_string (self,
				ve->definitions[k], COLS - left_width - 1);

			if ((gint) ++shown == LINES - 1)
				goto done;
		}

		k = 0;
	}

done:
	attrset (0);
	clrtobot ();
	refresh ();
}

/** Just prepends a new view entry into the entries array. */
static ViewEntry *
prepend_entry (Application *self, guint32 position)
{
	StardictIterator *iterator = stardict_iterator_new (self->dict, position);
	ViewEntry *ve = view_entry_new (iterator);
	g_object_unref (iterator);

	g_ptr_array_add (self->entries, NULL);
	memmove (self->entries->pdata + 1, self->entries->pdata,
		sizeof ve * (self->entries->len - 1));
	return g_ptr_array_index (self->entries, 0) = ve;
}

/** Just appends a new view entry to the entries array. */
static ViewEntry *
append_entry (Application *self, guint32 position)
{
	ViewEntry *ve = NULL;
	StardictIterator *iterator = stardict_iterator_new
		(self->dict, position);
	if (stardict_iterator_is_valid (iterator))
	{
		ve = view_entry_new (iterator);
		g_ptr_array_add (self->entries, ve);
	}
	g_object_unref (iterator);
	return ve;
}

/** Counts the number of definitions available for seeing. */
static guint
app_count_view_items (Application *self)
{
	guint i, n_definitions = 0;
	for (i = 0; i < self->entries->len; i++)
	{
		ViewEntry *entry = g_ptr_array_index (self->entries, i);
		n_definitions += entry->definitions_length;
	}
	return n_definitions;
}

/** Scroll up @a n entries. */
static gboolean
app_scroll_up (Application *self, guint n)
{
	gboolean success = TRUE;
	guint n_definitions = app_count_view_items (self);
	while (n--)
	{
		if (self->top_offset > 0)
		{
			self->top_offset--;
			continue;
		}

		/* We've reached the top */
		if (self->top_position == 0)
		{
			success = FALSE;
			break;
		}

		ViewEntry *ve = prepend_entry (self, --self->top_position);
		self->top_offset = ve->definitions_length - 1;
		n_definitions += ve->definitions_length;

		/* Remove the last entry if not shown */
		ViewEntry *last_entry =
			g_ptr_array_index (self->entries, self->entries->len - 1);
		if ((gint) (n_definitions - self->top_offset
			- last_entry->definitions_length) >= LINES - 1)
		{
			n_definitions -= last_entry->definitions_length;
			g_ptr_array_remove_index_fast
				(self->entries, self->entries->len - 1);
		}
	}

	app_redraw_view (self);
	return success;
}

/** Scroll down @a n entries. */
static gboolean
app_scroll_down (Application *self, guint n)
{
	gboolean success = TRUE;
	guint n_definitions = app_count_view_items (self);
	while (n--)
	{
		if (self->entries->len == 0)
		{
			success = FALSE;
			break;
		}

		ViewEntry *first_entry = g_ptr_array_index (self->entries, 0);
		if (self->top_offset < first_entry->definitions_length - 1)
			self->top_offset++;
		else
		{
			n_definitions -= first_entry->definitions_length;
			g_ptr_array_remove_index (self->entries, 0);
			self->top_position++;
			self->top_offset = 0;
		}

		if ((gint) (n_definitions - self->top_offset) < LINES - 1)
		{
			ViewEntry *ve = append_entry (self,
				self->top_position + self->entries->len);
			if (ve != NULL)
				n_definitions += ve->definitions_length;
		}
	}

	/* Fix cursor to not point below the view items */
	if (self->selected >= n_definitions - self->top_offset)
		self->selected  = n_definitions - self->top_offset - 1;

	app_redraw_view (self);
	return success;
}

/** Moves the selection one entry up. */
static gboolean
app_one_entry_up (Application *self)
{
	if (self->selected == 0 && self->top_offset == 0)
	{
		if (self->top_position == 0)
			return FALSE;
		prepend_entry (self, --self->top_position);
	}

	// Find the last entry that starts above the selection
	gint first = -self->top_offset;
	guint i;
	for (i = 0; i < self->entries->len; i++)
	{
		ViewEntry *ve = g_ptr_array_index (self->entries, i);
		gint new_first = first + ve->definitions_length;
		if (new_first >= (gint) self->selected)
			break;
		first = new_first;
	}

	if (first < 0)
	{
		self->selected = 0;
		app_scroll_up (self, -first);
	}
	else
	{
		self->selected = first;
		app_redraw_view (self);
	}
	return TRUE;
}

/** Moves the selection one entry down. */
static void
app_one_entry_down (Application *self)
{
	// Find the first entry that starts below the selection
	gint first = -self->top_offset;
	guint i;
	for (i = 0; i < self->entries->len; i++)
	{
		ViewEntry *ve = g_ptr_array_index (self->entries, i);
		first += ve->definitions_length;
		if (first > (gint) self->selected)
			break;
	}

	if (first > LINES - 2)
	{
		self->selected = LINES - 2;
		app_scroll_down (self, first - (LINES - 2));
	}
	else
	{
		self->selected = first;
		app_redraw_view (self);
	}
}

/** Redraw everything. */
static void
app_redraw (Application *self)
{
	app_redraw_view (self);
	app_redraw_top (self);
}

/** Search for the current entry. */
static void
app_search_for_entry (Application *self)
{
	gchar *input_utf8 = g_ucs4_to_utf8
		((gunichar *) self->input->data, -1, NULL, NULL, NULL);
	g_return_if_fail (input_utf8 != NULL);

	StardictIterator *iterator =
		stardict_dict_search (self->dict, input_utf8, NULL);
	g_free (input_utf8);

	self->top_position = stardict_iterator_get_offset (iterator);
	self->top_offset = 0;
	self->selected = 0;
	g_object_unref (iterator);

	app_reload_view (self);
	app_redraw_view (self);
}

#define SAVE_CURSOR                 \
	int last_x, last_y;             \
	getyx (stdscr, last_y, last_x);

#define RESTORE_CURSOR              \
	move (last_y, last_x);          \
	refresh ();

/** Process input above KEY_MAX. */
static gboolean
app_process_extra_code (Application *self, CursesEvent *event)
{
	SAVE_CURSOR
	switch (translate_extra_keycode (event->code, self->terminal_type))
	{
	case KEY_CTRL_UP:
		app_one_entry_up (self);
		RESTORE_CURSOR
		break;
	case KEY_CTRL_DOWN:
		app_one_entry_down (self);
		RESTORE_CURSOR
		break;

	case KEY_ALT_LEFT:
		self->division = (app_get_left_column_width (self) - 1.) / COLS;
		app_redraw_view (self);
		RESTORE_CURSOR
		break;
	case KEY_ALT_RIGHT:
		self->division = (app_get_left_column_width (self) + 1.) / COLS;
		app_redraw_view (self);
		RESTORE_CURSOR
		break;
	}
	return TRUE;
}

/** Process input that's not a character. */
static gboolean
app_process_nonchar_code (Application *self, CursesEvent *event)
{
	SAVE_CURSOR
	switch (event->code)
	{
	case KEY_RESIZE:
	{
		app_reload_view (self);

		guint n_visible = app_count_view_items (self) - self->top_offset;
		if ((gint) n_visible > LINES - 1)
			n_visible = LINES - 1;

		if (self->selected >= n_visible)
		{
			app_scroll_down (self, self->selected - n_visible + 1);
			self->selected = n_visible - 1;
		}

		app_redraw (self);
		break;
	}
	case KEY_MOUSE:
		if (!(event->mouse.bstate & BUTTON1_PRESSED))
			break;

		if (event->mouse.y == 0)
		{
			gsize label_len = g_utf8_strlen (self->search_label, -1);
			gint pos = event->mouse.x - label_len;
			if (pos >= 0)
			{
				self->input_pos = MIN ((guint) pos, self->input->len);
				move (0, label_len + self->input_pos);
				refresh ();
			}
		}
		else if (event->mouse.y <= (int)
			(app_count_view_items (self) - self->top_offset))
		{
			self->selected = event->mouse.y - 1;
			app_redraw_view (self);
			RESTORE_CURSOR
		}
		break;

	case KEY_UP:
		if (self->selected > 0)
		{
			self->selected--;
			app_redraw_view (self);
		}
		else
			app_scroll_up (self, 1);
		RESTORE_CURSOR
		break;
	case KEY_DOWN:
		if ((gint) self->selected < LINES - 2 &&
			self->selected < app_count_view_items (self) - self->top_offset - 1)
		{
			self->selected++;
			app_redraw_view (self);
		}
		else
			app_scroll_down (self, 1);
		RESTORE_CURSOR
		break;
	case KEY_PPAGE:
		app_scroll_up (self, LINES - 1);
		// FIXME selection
		RESTORE_CURSOR
		break;
	case KEY_NPAGE:
		app_scroll_down (self, LINES - 1);
		// FIXME selection
		RESTORE_CURSOR
		break;

	case KEY_HOME:
		self->input_pos = 0;
		app_redraw_top (self);
		break;
	case KEY_END:
		self->input_pos = self->input->len;
		app_redraw_top (self);
		break;
	case KEY_LEFT:
		if (self->input_pos > 0)
		{
			self->input_pos--;
			app_redraw_top (self);
		}
		break;
	case KEY_RIGHT:
		if (self->input_pos < self->input->len)
		{
			self->input_pos++;
			app_redraw_top (self);
		}
		break;
	case KEY_BACKSPACE:
		if (self->input_pos > 0)
		{
			g_array_remove_index (self->input, --self->input_pos);
			app_search_for_entry (self);
			app_redraw_top (self);
		}
		break;
	case KEY_DC:
		if (self->input_pos < self->input->len)
		{
			g_array_remove_index (self->input, self->input_pos);
			app_search_for_entry (self);
			app_redraw_top (self);
		}
		break;

	default:
		return app_process_extra_code (self, event);
	}
	return TRUE;
}

/** Process input events from ncurses. */
static gboolean
app_process_curses_event (Application *self, CursesEvent *event)
{
	if (!event->is_char)
		return app_process_nonchar_code (self, event);

	switch (event->code)
	{
	case KEY_ESCAPE:
		return FALSE;
	case KEY_RETURN:
		self->input_confirmed = TRUE;
		app_redraw_top (self);
		break;

	case KEY_FF:  // Ctrl-L -- redraw everything
		clear ();
		app_redraw (self);
		break;

	case KEY_STX: // Ctrl-B -- back
	case KEY_ACK: // Ctrl-F -- forward
	case KEY_DLE: // Ctrl-P -- previous
	case KEY_SO:  // Ctrl-N -- next
		// TODO map this to something useful
		break;

	case KEY_SOH: // Ctrl-A -- move to the start of line
		self->input_pos = 0;
		app_redraw_top (self);
		break;
	case KEY_ENQ: // Ctrl-E -- move to the end of line
		self->input_pos = self->input->len;
		app_redraw_top (self);
		break;
	case KEY_VT:  // Ctrl-K -- delete until the end of line
		if (self->input_pos < self->input->len)
		{
			g_array_remove_range (self->input,
				self->input_pos, self->input->len - self->input_pos);
			app_search_for_entry (self);
			app_redraw_top (self);
		}
		return TRUE;
	case KEY_ETB: // Ctrl-W -- delete word before cursor
	{
		if (self->input_pos == 0)
			return TRUE;

		gint i = self->input_pos;
		while (i)
			if (g_array_index (self->input, gunichar, --i) != L' ')
				break;
		while (i--)
			if (g_array_index (self->input, gunichar,   i) == L' ')
				break;

		i++;
		g_array_remove_range (self->input, i, self->input_pos - i);
		self->input_pos = i;

		app_search_for_entry (self);
		app_redraw_top (self);
		return TRUE;
	}
	case KEY_NAK: // Ctrl-U -- delete everything before the cursor
		if (self->input->len != 0)
		{
			g_array_remove_range (self->input, 0, self->input_pos);
			self->input_pos = 0;

			app_search_for_entry (self);
			app_redraw_top (self);
		}
		return TRUE;
	}

	wchar_t code = event->code;
	gchar *letter = g_convert_with_iconv ((gchar *) &code, sizeof code,
		self->wchar_to_utf8, NULL, NULL, NULL);
	g_return_val_if_fail (letter != NULL, FALSE);

	gunichar c = g_utf8_get_char (letter);
	if (g_unichar_isprint (c))
	{
		self->show_help = FALSE;

		if (self->input_confirmed)
		{
			if (self->input->len != 0)
				g_array_remove_range (self->input, 0, self->input->len);
			self->input_pos = 0;
			self->input_confirmed = FALSE;
		}

		g_array_insert_val (self->input, self->input_pos++, c);
		app_search_for_entry (self);
		app_redraw_top (self);
	}
	g_free (letter);

	return TRUE;
}

// --- SIGWINCH ----------------------------------------------------------------

static int g_winch_pipe[2];            /**< SIGWINCH signalling pipe. */
static void (*g_old_winch_handler) (int);

static void
winch_handler (int signum)
{
	/* Call the ncurses handler. */
	if (g_old_winch_handler)
		g_old_winch_handler (signum);

	/* And wake up the poll() call. */
	write (g_winch_pipe[1], "x", 1);
}

static void
install_winch_handler (void)
{
	struct sigaction act, oldact;

	act.sa_handler = winch_handler;
	act.sa_flags = SA_RESTART;
	sigemptyset (&act.sa_mask);
	sigaction (SIGWINCH, &act, &oldact);

	/* Save the ncurses handler. */
	if (oldact.sa_handler != SIG_DFL
	 && oldact.sa_handler != SIG_IGN)
		g_old_winch_handler = oldact.sa_handler;
}

// --- Initialisation, event handling ------------------------------------------

Application g_application;

static gboolean
process_stdin_input (void)
{
	CursesEvent event;
	int sta;

	while ((sta = get_wch (&event.code)) != ERR)
	{
		event.is_char = (sta == OK);
		if (sta == KEY_CODE_YES && event.code == KEY_MOUSE
			&& getmouse (&event.mouse) == ERR)
			abort ();
		if (!app_process_curses_event (&g_application, &event))
			return FALSE;
	}

	return TRUE;
}

static gboolean
process_winch_input (int fd)
{
	char c;

	read (fd, &c, 1);
	return process_stdin_input ();
}

int
main (int argc, char *argv[])
{
G_GNUC_BEGIN_IGNORE_DEPRECATIONS
	if (glib_check_version (2, 36, 0))
		g_type_init ();
G_GNUC_END_IGNORE_DEPRECATIONS

	gboolean show_version = FALSE;
	GOptionEntry entries[] =
	{
		{ "version", 0, G_OPTION_FLAG_IN_MAIN,
		  G_OPTION_ARG_NONE, &show_version,
		  N_("Output version information and exit"), NULL },
		{ NULL }
	};

	if (!setlocale (LC_ALL, ""))
		g_printerr ("%s: %s\n", _("Warning"), _("failed to set the locale"));

	bindtextdomain (GETTEXT_PACKAGE, GETTEXT_DIRNAME);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
	textdomain (GETTEXT_PACKAGE);

	GError *error = NULL;
	GOptionContext *ctx = g_option_context_new
		(N_("dictionary.ifo - StarDict terminal UI"));
	g_option_context_add_main_entries (ctx, entries, GETTEXT_PACKAGE);
	g_option_context_set_translation_domain (ctx, GETTEXT_PACKAGE);
	if (!g_option_context_parse (ctx, &argc, &argv, &error))
	{
		g_printerr ("%s: %s: %s\n", _("Error"), _("option parsing failed"),
			error->message);
		exit (EXIT_FAILURE);
	}

	if (show_version)
	{
		g_print (PROJECT_NAME " " PROJECT_VERSION "\n");
		exit (EXIT_SUCCESS);
	}

	if (argc != 2)
	{
		gchar *help = g_option_context_get_help (ctx, TRUE, FALSE);
		g_printerr ("%s", help);
		g_free (help);
		exit (EXIT_FAILURE);
	}

	g_option_context_free (ctx);

	app_init (&g_application, argv[1]);

	if (!initscr ()
	 || cbreak () == ERR
	 || noecho () == ERR
	 || nonl () == ERR)
		abort ();

	keypad (stdscr, TRUE);                /* Enable character processing. */
	nodelay (stdscr, TRUE);               /* Don't block on get_wch(). */

	mousemask (ALL_MOUSE_EVENTS, NULL);   /* Register mouse events. */
	mouseinterval (0);

	if (pipe (g_winch_pipe) == -1)
		abort ();
	install_winch_handler ();

	app_redraw (&g_application);

	/* Message loop. */
	struct pollfd pollfd[2];

	pollfd[0].fd = fileno (stdin);
	pollfd[0].events = POLLIN;
	pollfd[1].fd = g_winch_pipe[0];
	pollfd[1].events = POLLIN;

	while (TRUE)
	{
		if (poll_restart (pollfd, 3, -1) == -1)
			abort ();

		if ((pollfd[0].revents & POLLIN)
		 && !process_stdin_input ())
			break;
		if ((pollfd[1].revents & POLLIN)
		 && !process_winch_input (pollfd[1].fd))
			break;
	}

	endwin ();
	app_destroy (&g_application);

	if (close (g_winch_pipe[0]) == -1
	 || close (g_winch_pipe[1]) == -1)
		abort ();

	return 0;
}