]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - unix/pterm.c
First draft of Unicode support in pterm. It's pretty complete: it
[PuTTY.git] / unix / pterm.c
1 /*
2  * pterm - a fusion of the PuTTY terminal emulator with a Unix pty
3  * back end, all running as a GTK application. Wish me luck.
4  */
5
6 #define _GNU_SOURCE
7
8 #include <string.h>
9 #include <assert.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <signal.h>
13 #include <stdio.h>
14 #include <time.h>
15 #include <errno.h>
16 #include <fcntl.h>
17 #include <unistd.h>
18 #include <sys/types.h>
19 #include <sys/wait.h>
20 #include <gtk/gtk.h>
21 #include <gdk/gdkkeysyms.h>
22 #include <gdk/gdkx.h>
23 #include <X11/Xlib.h>
24 #include <X11/Xutil.h>
25
26 #define PUTTY_DO_GLOBALS               /* actually _define_ globals */
27
28 #include "putty.h"
29 #include "terminal.h"
30
31 #define CAT2(x,y) x ## y
32 #define CAT(x,y) CAT2(x,y)
33 #define ASSERT(x) enum {CAT(assertion_,__LINE__) = 1 / (x)}
34
35 #define NCOLOURS (lenof(((Config *)0)->colours))
36
37 struct gui_data {
38     GtkWidget *window, *area, *sbar;
39     GtkBox *hbox;
40     GtkAdjustment *sbar_adjust;
41     GdkPixmap *pixmap;
42     GdkFont *fonts[2];                 /* normal and bold (for now!) */
43     struct {
44         int charset;
45         int is_wide;
46     } fontinfo[2];
47     GdkCursor *rawcursor, *textcursor, *blankcursor, *currcursor;
48     GdkColor cols[NCOLOURS];
49     GdkColormap *colmap;
50     wchar_t *pastein_data;
51     int pastein_data_len;
52     char *pasteout_data, *pasteout_data_utf8;
53     int pasteout_data_len, pasteout_data_utf8_len;
54     int font_width, font_height;
55     int ignore_sbar;
56     int mouseptr_visible;
57     guint term_paste_idle_id;
58     GdkAtom compound_text_atom, utf8_string_atom;
59     int alt_keycode;
60     int alt_digits;
61     char wintitle[sizeof(((Config *)0)->wintitle)];
62     char icontitle[sizeof(((Config *)0)->wintitle)];
63     int master_fd, master_func_id, exited;
64     void *ldisc;
65     Backend *back;
66     void *backhandle;
67     Terminal *term;
68     void *logctx;
69 };
70
71 struct draw_ctx {
72     GdkGC *gc;
73     struct gui_data *inst;
74 };
75
76 static int send_raw_mouse;
77
78 static char *app_name = "pterm";
79
80 char *x_get_default(char *key)
81 {
82     return XGetDefault(GDK_DISPLAY(), app_name, key);
83 }
84
85 void ldisc_update(void *frontend, int echo, int edit)
86 {
87     /*
88      * This is a stub in pterm. If I ever produce a Unix
89      * command-line ssh/telnet/rlogin client (i.e. a port of plink)
90      * then it will require some termios manoeuvring analogous to
91      * that in the Windows plink.c, but here it's meaningless.
92      */
93 }
94
95 int askappend(void *frontend, char *filename)
96 {
97     /*
98      * Logging in an xterm-alike is liable to be something you only
99      * do at serious diagnostic need. Hence, I'm going to take the
100      * easy option for now and assume we always want to overwrite
101      * log files. I can always make it properly configurable later.
102      */
103     return 2;
104 }
105
106 void logevent(void *frontend, char *string)
107 {
108     /*
109      * This is not a very helpful function: events are logged
110      * pretty much exclusively by the back end, and our pty back
111      * end is self-contained. So we need do nothing.
112      */
113 }
114
115 int font_dimension(void *frontend, int which)/* 0 for width, 1 for height */
116 {
117     struct gui_data *inst = (struct gui_data *)frontend;
118
119     if (which)
120         return inst->font_height;
121     else
122         return inst->font_width;
123 }
124
125 /*
126  * Translate a raw mouse button designation (LEFT, MIDDLE, RIGHT)
127  * into a cooked one (SELECT, EXTEND, PASTE).
128  * 
129  * In Unix, this is not configurable; the X button arrangement is
130  * rock-solid across all applications, everyone has a three-button
131  * mouse or a means of faking it, and there is no need to switch
132  * buttons around at all.
133  */
134 Mouse_Button translate_button(void *frontend, Mouse_Button button)
135 {
136     /* struct gui_data *inst = (struct gui_data *)frontend; */
137
138     if (button == MBT_LEFT)
139         return MBT_SELECT;
140     if (button == MBT_MIDDLE)
141         return MBT_PASTE;
142     if (button == MBT_RIGHT)
143         return MBT_EXTEND;
144     return 0;                          /* shouldn't happen */
145 }
146
147 /*
148  * Minimise or restore the window in response to a server-side
149  * request.
150  */
151 void set_iconic(void *frontend, int iconic)
152 {
153     /*
154      * GTK 1.2 doesn't know how to do this.
155      */
156 #if GTK_CHECK_VERSION(2,0,0)
157     struct gui_data *inst = (struct gui_data *)frontend;
158     if (iconic)
159         gtk_window_iconify(GTK_WINDOW(inst->window));
160     else
161         gtk_window_deiconify(GTK_WINDOW(inst->window));
162 #endif
163 }
164
165 /*
166  * Move the window in response to a server-side request.
167  */
168 void move_window(void *frontend, int x, int y)
169 {
170     struct gui_data *inst = (struct gui_data *)frontend;
171     /*
172      * I assume that when the GTK version of this call is available
173      * we should use it. Not sure how it differs from the GDK one,
174      * though.
175      */
176 #if GTK_CHECK_VERSION(2,0,0)
177     gtk_window_move(GTK_WINDOW(inst->window), x, y);
178 #else
179     gdk_window_move(inst->window->window, x, y);
180 #endif
181 }
182
183 /*
184  * Move the window to the top or bottom of the z-order in response
185  * to a server-side request.
186  */
187 void set_zorder(void *frontend, int top)
188 {
189     struct gui_data *inst = (struct gui_data *)frontend;
190     if (top)
191         gdk_window_raise(inst->window->window);
192     else
193         gdk_window_lower(inst->window->window);
194 }
195
196 /*
197  * Refresh the window in response to a server-side request.
198  */
199 void refresh_window(void *frontend)
200 {
201     struct gui_data *inst = (struct gui_data *)frontend;
202     term_invalidate(inst->term);
203 }
204
205 /*
206  * Maximise or restore the window in response to a server-side
207  * request.
208  */
209 void set_zoomed(void *frontend, int zoomed)
210 {
211     /*
212      * GTK 1.2 doesn't know how to do this.
213      */
214 #if GTK_CHECK_VERSION(2,0,0)
215     struct gui_data *inst = (struct gui_data *)frontend;
216     if (iconic)
217         gtk_window_maximize(GTK_WINDOW(inst->window));
218     else
219         gtk_window_unmaximize(GTK_WINDOW(inst->window));
220 #endif
221 }
222
223 /*
224  * Report whether the window is iconic, for terminal reports.
225  */
226 int is_iconic(void *frontend)
227 {
228     struct gui_data *inst = (struct gui_data *)frontend;
229     return !gdk_window_is_viewable(inst->window->window);
230 }
231
232 /*
233  * Report the window's position, for terminal reports.
234  */
235 void get_window_pos(void *frontend, int *x, int *y)
236 {
237     struct gui_data *inst = (struct gui_data *)frontend;
238     /*
239      * I assume that when the GTK version of this call is available
240      * we should use it. Not sure how it differs from the GDK one,
241      * though.
242      */
243 #if GTK_CHECK_VERSION(2,0,0)
244     gtk_window_get_position(GTK_WINDOW(inst->window), x, y);
245 #else
246     gdk_window_get_position(inst->window->window, x, y);
247 #endif
248 }
249
250 /*
251  * Report the window's pixel size, for terminal reports.
252  */
253 void get_window_pixels(void *frontend, int *x, int *y)
254 {
255     struct gui_data *inst = (struct gui_data *)frontend;
256     /*
257      * I assume that when the GTK version of this call is available
258      * we should use it. Not sure how it differs from the GDK one,
259      * though.
260      */
261 #if GTK_CHECK_VERSION(2,0,0)
262     gtk_window_get_size(GTK_WINDOW(inst->window), x, y);
263 #else
264     gdk_window_get_size(inst->window->window, x, y);
265 #endif
266 }
267
268 /*
269  * Return the window or icon title.
270  */
271 char *get_window_title(void *frontend, int icon)
272 {
273     struct gui_data *inst = (struct gui_data *)frontend;
274     return icon ? inst->wintitle : inst->icontitle;
275 }
276
277 gint delete_window(GtkWidget *widget, GdkEvent *event, gpointer data)
278 {
279     /*
280      * We could implement warn-on-close here if we really wanted
281      * to.
282      */
283     return FALSE;
284 }
285
286 static void show_mouseptr(struct gui_data *inst, int show)
287 {
288     if (!cfg.hide_mouseptr)
289         show = 1;
290     if (show)
291         gdk_window_set_cursor(inst->area->window, inst->currcursor);
292     else
293         gdk_window_set_cursor(inst->area->window, inst->blankcursor);
294     inst->mouseptr_visible = show;
295 }
296
297 gint configure_area(GtkWidget *widget, GdkEventConfigure *event, gpointer data)
298 {
299     struct gui_data *inst = (struct gui_data *)data;
300     int w, h, need_size = 0;
301
302     w = (event->width - 2*cfg.window_border) / inst->font_width;
303     h = (event->height - 2*cfg.window_border) / inst->font_height;
304
305     if (w != cfg.width || h != cfg.height) {
306         if (inst->pixmap) {
307             gdk_pixmap_unref(inst->pixmap);
308             inst->pixmap = NULL;
309         }
310         cfg.width = w;
311         cfg.height = h;
312         need_size = 1;
313     }
314     if (!inst->pixmap) {
315         GdkGC *gc;
316
317         inst->pixmap = gdk_pixmap_new(widget->window,
318                                       (cfg.width * inst->font_width +
319                                        2*cfg.window_border),
320                                       (cfg.height * inst->font_height +
321                                        2*cfg.window_border), -1);
322
323         gc = gdk_gc_new(inst->area->window);
324         gdk_gc_set_foreground(gc, &inst->cols[18]);   /* default background */
325         gdk_draw_rectangle(inst->pixmap, gc, 1, 0, 0,
326                            cfg.width * inst->font_width + 2*cfg.window_border,
327                            cfg.height * inst->font_height + 2*cfg.window_border);
328         gdk_gc_unref(gc);
329     }
330
331     if (need_size) {
332         term_size(inst->term, h, w, cfg.savelines);
333     }
334
335     return TRUE;
336 }
337
338 gint expose_area(GtkWidget *widget, GdkEventExpose *event, gpointer data)
339 {
340     struct gui_data *inst = (struct gui_data *)data;
341
342     /*
343      * Pass the exposed rectangle to terminal.c, which will call us
344      * back to do the actual painting.
345      */
346     if (inst->pixmap) {
347         gdk_draw_pixmap(widget->window,
348                         widget->style->fg_gc[GTK_WIDGET_STATE(widget)],
349                         inst->pixmap,
350                         event->area.x, event->area.y,
351                         event->area.x, event->area.y,
352                         event->area.width, event->area.height);
353     }
354     return TRUE;
355 }
356
357 #define KEY_PRESSED(k) \
358     (inst->keystate[(k) / 32] & (1 << ((k) % 32)))
359
360 gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data)
361 {
362     struct gui_data *inst = (struct gui_data *)data;
363     char output[32];
364     int start, end;
365
366     /* By default, nothing is generated. */
367     end = start = 0;
368
369     /*
370      * If Alt is being released after typing an Alt+numberpad
371      * sequence, we should generate the code that was typed.
372      * 
373      * Note that we only do this if more than one key was actually
374      * pressed - I don't think Alt+NumPad4 should be ^D or that
375      * Alt+NumPad3 should be ^C, for example. There's no serious
376      * inconvenience in having to type a zero before a single-digit
377      * character code.
378      */
379     if (event->type == GDK_KEY_RELEASE &&
380         (event->keyval == GDK_Meta_L || event->keyval == GDK_Alt_L ||
381          event->keyval == GDK_Meta_R || event->keyval == GDK_Alt_R) &&
382         inst->alt_keycode >= 0 && inst->alt_digits > 1) {
383 #ifdef KEY_DEBUGGING
384         printf("Alt key up, keycode = %d\n", inst->alt_keycode);
385 #endif
386         output[0] = inst->alt_keycode;
387         end = 1;
388         goto done;
389     }
390
391     if (event->type == GDK_KEY_PRESS) {
392 #ifdef KEY_DEBUGGING
393         {
394             int i;
395             printf("keypress: keyval = %04x, state = %08x; string =",
396                    event->keyval, event->state);
397             for (i = 0; event->string[i]; i++)
398                 printf(" %02x", (unsigned char) event->string[i]);
399             printf("\n");
400         }
401 #endif
402
403         /*
404          * NYI: Compose key (!!! requires Unicode faff before even trying)
405          */
406
407         /*
408          * If Alt has just been pressed, we start potentially
409          * accumulating an Alt+numberpad code. We do this by
410          * setting alt_keycode to -1 (nothing yet but plausible).
411          */
412         if ((event->keyval == GDK_Meta_L || event->keyval == GDK_Alt_L ||
413              event->keyval == GDK_Meta_R || event->keyval == GDK_Alt_R)) {
414             inst->alt_keycode = -1;
415             inst->alt_digits = 0;
416             goto done;                 /* this generates nothing else */
417         }
418
419         /*
420          * If we're seeing a numberpad key press with Mod1 down,
421          * consider adding it to alt_keycode if that's sensible.
422          * Anything _else_ with Mod1 down cancels any possibility
423          * of an ALT keycode: we set alt_keycode to -2.
424          */
425         if ((event->state & GDK_MOD1_MASK) && inst->alt_keycode != -2) {
426             int digit = -1;
427             switch (event->keyval) {
428               case GDK_KP_0: case GDK_KP_Insert: digit = 0; break;
429               case GDK_KP_1: case GDK_KP_End: digit = 1; break;
430               case GDK_KP_2: case GDK_KP_Down: digit = 2; break;
431               case GDK_KP_3: case GDK_KP_Page_Down: digit = 3; break;
432               case GDK_KP_4: case GDK_KP_Left: digit = 4; break;
433               case GDK_KP_5: case GDK_KP_Begin: digit = 5; break;
434               case GDK_KP_6: case GDK_KP_Right: digit = 6; break;
435               case GDK_KP_7: case GDK_KP_Home: digit = 7; break;
436               case GDK_KP_8: case GDK_KP_Up: digit = 8; break;
437               case GDK_KP_9: case GDK_KP_Page_Up: digit = 9; break;
438             }
439             if (digit < 0)
440                 inst->alt_keycode = -2;   /* it's invalid */
441             else {
442 #ifdef KEY_DEBUGGING
443                 printf("Adding digit %d to keycode %d", digit,
444                        inst->alt_keycode);
445 #endif
446                 if (inst->alt_keycode == -1)
447                     inst->alt_keycode = digit;   /* one-digit code */
448                 else
449                     inst->alt_keycode = inst->alt_keycode * 10 + digit;
450                 inst->alt_digits++;
451 #ifdef KEY_DEBUGGING
452                 printf(" gives new code %d\n", inst->alt_keycode);
453 #endif
454                 /* Having used this digit, we now do nothing more with it. */
455                 goto done;
456             }
457         }
458
459         /*
460          * Shift-PgUp and Shift-PgDn don't even generate keystrokes
461          * at all.
462          */
463         if (event->keyval == GDK_Page_Up && (event->state & GDK_SHIFT_MASK)) {
464             term_scroll(inst->term, 0, -cfg.height/2);
465             return TRUE;
466         }
467         if (event->keyval == GDK_Page_Down && (event->state & GDK_SHIFT_MASK)) {
468             term_scroll(inst->term, 0, +cfg.height/2);
469             return TRUE;
470         }
471
472         /*
473          * Neither does Shift-Ins.
474          */
475         if (event->keyval == GDK_Insert && (event->state & GDK_SHIFT_MASK)) {
476             request_paste(inst);
477             return TRUE;
478         }
479
480         /* ALT+things gives leading Escape. */
481         output[0] = '\033';
482         strncpy(output+1, event->string, 31);
483         output[31] = '\0';
484         end = strlen(output);
485         if (event->state & GDK_MOD1_MASK) {
486             start = 0;
487             if (end == 1) end = 0;
488         } else
489             start = 1;
490
491         /* Control-` is the same as Control-\ (unless gtk has a better idea) */
492         if (!event->string[0] && event->keyval == '`' &&
493             (event->state & GDK_CONTROL_MASK)) {
494             output[1] = '\x1C';
495             end = 2;
496         }
497
498         /* Control-Break is the same as Control-C */
499         if (event->keyval == GDK_Break &&
500             (event->state & GDK_CONTROL_MASK)) {
501             output[1] = '\003';
502             end = 2;
503         }
504
505         /* Control-2, Control-Space and Control-@ are NUL */
506         if (!event->string[0] &&
507             (event->keyval == ' ' || event->keyval == '2' ||
508              event->keyval == '@') &&
509             (event->state & (GDK_SHIFT_MASK |
510                              GDK_CONTROL_MASK)) == GDK_CONTROL_MASK) {
511             output[1] = '\0';
512             end = 2;
513         }
514
515         /* Control-Shift-Space is 160 (ISO8859 nonbreaking space) */
516         if (!event->string[0] && event->keyval == ' ' &&
517             (event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK)) ==
518             (GDK_SHIFT_MASK | GDK_CONTROL_MASK)) {
519             output[1] = '\240';
520             end = 2;
521         }
522
523         /* We don't let GTK tell us what Backspace is! We know better. */
524         if (event->keyval == GDK_BackSpace &&
525             !(event->state & GDK_SHIFT_MASK)) {
526             output[1] = cfg.bksp_is_delete ? '\x7F' : '\x08';
527             end = 2;
528         }
529         /* For Shift Backspace, do opposite of what is configured. */
530         if (event->keyval == GDK_BackSpace &&
531             (event->state & GDK_SHIFT_MASK)) {
532             output[1] = cfg.bksp_is_delete ? '\x08' : '\x7F';
533             end = 2;
534         }
535
536         /* Shift-Tab is ESC [ Z */
537         if (event->keyval == GDK_ISO_Left_Tab ||
538             (event->keyval == GDK_Tab && (event->state & GDK_SHIFT_MASK))) {
539             end = 1 + sprintf(output+1, "\033[Z");
540         }
541
542         /*
543          * NetHack keypad mode.
544          */
545         if (cfg.nethack_keypad) {
546             char *keys = NULL;
547             switch (event->keyval) {
548               case GDK_KP_1: case GDK_KP_End: keys = "bB"; break;
549               case GDK_KP_2: case GDK_KP_Down: keys = "jJ"; break;
550               case GDK_KP_3: case GDK_KP_Page_Down: keys = "nN"; break;
551               case GDK_KP_4: case GDK_KP_Left: keys = "hH"; break;
552               case GDK_KP_5: case GDK_KP_Begin: keys = ".."; break;
553               case GDK_KP_6: case GDK_KP_Right: keys = "lL"; break;
554               case GDK_KP_7: case GDK_KP_Home: keys = "yY"; break;
555               case GDK_KP_8: case GDK_KP_Up: keys = "kK"; break;
556               case GDK_KP_9: case GDK_KP_Page_Up: keys = "uU"; break;
557             }
558             if (keys) {
559                 end = 2;
560                 if (event->state & GDK_SHIFT_MASK)
561                     output[1] = keys[1];
562                 else
563                     output[1] = keys[0];
564                 goto done;
565             }
566         }
567
568         /*
569          * Application keypad mode.
570          */
571         if (inst->term->app_keypad_keys && !cfg.no_applic_k) {
572             int xkey = 0;
573             switch (event->keyval) {
574               case GDK_Num_Lock: xkey = 'P'; break;
575               case GDK_KP_Divide: xkey = 'Q'; break;
576               case GDK_KP_Multiply: xkey = 'R'; break;
577               case GDK_KP_Subtract: xkey = 'S'; break;
578                 /*
579                  * Keypad + is tricky. It covers a space that would
580                  * be taken up on the VT100 by _two_ keys; so we
581                  * let Shift select between the two. Worse still,
582                  * in xterm function key mode we change which two...
583                  */
584               case GDK_KP_Add:
585                 if (cfg.funky_type == 2) {
586                     if (event->state & GDK_SHIFT_MASK)
587                         xkey = 'l';
588                     else
589                         xkey = 'k';
590                 } else if (event->state & GDK_SHIFT_MASK)
591                         xkey = 'm';
592                 else
593                     xkey = 'l';
594                 break;
595               case GDK_KP_Enter: xkey = 'M'; break;
596               case GDK_KP_0: case GDK_KP_Insert: xkey = 'p'; break;
597               case GDK_KP_1: case GDK_KP_End: xkey = 'q'; break;
598               case GDK_KP_2: case GDK_KP_Down: xkey = 'r'; break;
599               case GDK_KP_3: case GDK_KP_Page_Down: xkey = 's'; break;
600               case GDK_KP_4: case GDK_KP_Left: xkey = 't'; break;
601               case GDK_KP_5: case GDK_KP_Begin: xkey = 'u'; break;
602               case GDK_KP_6: case GDK_KP_Right: xkey = 'v'; break;
603               case GDK_KP_7: case GDK_KP_Home: xkey = 'w'; break;
604               case GDK_KP_8: case GDK_KP_Up: xkey = 'x'; break;
605               case GDK_KP_9: case GDK_KP_Page_Up: xkey = 'y'; break;
606               case GDK_KP_Decimal: case GDK_KP_Delete: xkey = 'n'; break;
607             }
608             if (xkey) {
609                 if (inst->term->vt52_mode) {
610                     if (xkey >= 'P' && xkey <= 'S')
611                         end = 1 + sprintf(output+1, "\033%c", xkey);
612                     else
613                         end = 1 + sprintf(output+1, "\033?%c", xkey);
614                 } else
615                     end = 1 + sprintf(output+1, "\033O%c", xkey);
616                 goto done;
617             }
618         }
619
620         /*
621          * Next, all the keys that do tilde codes. (ESC '[' nn '~',
622          * for integer decimal nn.)
623          *
624          * We also deal with the weird ones here. Linux VCs replace F1
625          * to F5 by ESC [ [ A to ESC [ [ E. rxvt doesn't do _that_, but
626          * does replace Home and End (1~ and 4~) by ESC [ H and ESC O w
627          * respectively.
628          */
629         {
630             int code = 0;
631             switch (event->keyval) {
632               case GDK_F1:
633                 code = (event->state & GDK_SHIFT_MASK ? 23 : 11);
634                 break;
635               case GDK_F2:
636                 code = (event->state & GDK_SHIFT_MASK ? 24 : 12);
637                 break;
638               case GDK_F3:
639                 code = (event->state & GDK_SHIFT_MASK ? 25 : 13);
640                 break;
641               case GDK_F4:
642                 code = (event->state & GDK_SHIFT_MASK ? 26 : 14);
643                 break;
644               case GDK_F5:
645                 code = (event->state & GDK_SHIFT_MASK ? 28 : 15);
646                 break;
647               case GDK_F6:
648                 code = (event->state & GDK_SHIFT_MASK ? 29 : 17);
649                 break;
650               case GDK_F7:
651                 code = (event->state & GDK_SHIFT_MASK ? 31 : 18);
652                 break;
653               case GDK_F8:
654                 code = (event->state & GDK_SHIFT_MASK ? 32 : 19);
655                 break;
656               case GDK_F9:
657                 code = (event->state & GDK_SHIFT_MASK ? 33 : 20);
658                 break;
659               case GDK_F10:
660                 code = (event->state & GDK_SHIFT_MASK ? 34 : 21);
661                 break;
662               case GDK_F11:
663                 code = 23;
664                 break;
665               case GDK_F12:
666                 code = 24;
667                 break;
668               case GDK_F13:
669                 code = 25;
670                 break;
671               case GDK_F14:
672                 code = 26;
673                 break;
674               case GDK_F15:
675                 code = 28;
676                 break;
677               case GDK_F16:
678                 code = 29;
679                 break;
680               case GDK_F17:
681                 code = 31;
682                 break;
683               case GDK_F18:
684                 code = 32;
685                 break;
686               case GDK_F19:
687                 code = 33;
688                 break;
689               case GDK_F20:
690                 code = 34;
691                 break;
692             }
693             if (!(event->state & GDK_CONTROL_MASK)) switch (event->keyval) {
694               case GDK_Home: case GDK_KP_Home:
695                 code = 1;
696                 break;
697               case GDK_Insert: case GDK_KP_Insert:
698                 code = 2;
699                 break;
700               case GDK_Delete: case GDK_KP_Delete:
701                 code = 3;
702                 break;
703               case GDK_End: case GDK_KP_End:
704                 code = 4;
705                 break;
706               case GDK_Page_Up: case GDK_KP_Page_Up:
707                 code = 5;
708                 break;
709               case GDK_Page_Down: case GDK_KP_Page_Down:
710                 code = 6;
711                 break;
712             }
713             /* Reorder edit keys to physical order */
714             if (cfg.funky_type == 3 && code <= 6)
715                 code = "\0\2\1\4\5\3\6"[code];
716
717             if (inst->term->vt52_mode && code > 0 && code <= 6) {
718                 end = 1 + sprintf(output+1, "\x1B%c", " HLMEIG"[code]);
719                 goto done;
720             }
721
722             if (cfg.funky_type == 5 &&     /* SCO function keys */
723                 code >= 11 && code <= 34) {
724                 char codes[] = "MNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@[\\]^_`{";
725                 int index = 0;
726                 switch (event->keyval) {
727                   case GDK_F1: index = 0; break;
728                   case GDK_F2: index = 1; break;
729                   case GDK_F3: index = 2; break;
730                   case GDK_F4: index = 3; break;
731                   case GDK_F5: index = 4; break;
732                   case GDK_F6: index = 5; break;
733                   case GDK_F7: index = 6; break;
734                   case GDK_F8: index = 7; break;
735                   case GDK_F9: index = 8; break;
736                   case GDK_F10: index = 9; break;
737                   case GDK_F11: index = 10; break;
738                   case GDK_F12: index = 11; break;
739                 }
740                 if (event->state & GDK_SHIFT_MASK) index += 12;
741                 if (event->state & GDK_CONTROL_MASK) index += 24;
742                 end = 1 + sprintf(output+1, "\x1B[%c", codes[index]);
743                 goto done;
744             }
745             if (cfg.funky_type == 5 &&     /* SCO small keypad */
746                 code >= 1 && code <= 6) {
747                 char codes[] = "HL.FIG";
748                 if (code == 3) {
749                     output[1] = '\x7F';
750                     end = 2;
751                 } else {
752                     end = 1 + sprintf(output+1, "\x1B[%c", codes[code-1]);
753                 }
754                 goto done;
755             }
756             if ((inst->term->vt52_mode || cfg.funky_type == 4) &&
757                 code >= 11 && code <= 24) {
758                 int offt = 0;
759                 if (code > 15)
760                     offt++;
761                 if (code > 21)
762                     offt++;
763                 if (inst->term->vt52_mode)
764                     end = 1 + sprintf(output+1,
765                                       "\x1B%c", code + 'P' - 11 - offt);
766                 else
767                     end = 1 + sprintf(output+1,
768                                       "\x1BO%c", code + 'P' - 11 - offt);
769                 goto done;
770             }
771             if (cfg.funky_type == 1 && code >= 11 && code <= 15) {
772                 end = 1 + sprintf(output+1, "\x1B[[%c", code + 'A' - 11);
773                 goto done;
774             }
775             if (cfg.funky_type == 2 && code >= 11 && code <= 14) {
776                 if (inst->term->vt52_mode)
777                     end = 1 + sprintf(output+1, "\x1B%c", code + 'P' - 11);
778                 else
779                     end = 1 + sprintf(output+1, "\x1BO%c", code + 'P' - 11);
780                 goto done;
781             }
782             if (cfg.rxvt_homeend && (code == 1 || code == 4)) {
783                 end = 1 + sprintf(output+1, code == 1 ? "\x1B[H" : "\x1BOw");
784                 goto done;
785             }
786             if (code) {
787                 end = 1 + sprintf(output+1, "\x1B[%d~", code);
788                 goto done;
789             }
790         }
791
792         /*
793          * Cursor keys. (This includes the numberpad cursor keys,
794          * if we haven't already done them due to app keypad mode.)
795          * 
796          * Here we also process un-numlocked un-appkeypadded KP5,
797          * which sends ESC [ G.
798          */
799         {
800             int xkey = 0;
801             switch (event->keyval) {
802               case GDK_Up: case GDK_KP_Up: xkey = 'A'; break;
803               case GDK_Down: case GDK_KP_Down: xkey = 'B'; break;
804               case GDK_Right: case GDK_KP_Right: xkey = 'C'; break;
805               case GDK_Left: case GDK_KP_Left: xkey = 'D'; break;
806               case GDK_Begin: case GDK_KP_Begin: xkey = 'G'; break;
807             }
808             if (xkey) {
809                 /*
810                  * The arrow keys normally do ESC [ A and so on. In
811                  * app cursor keys mode they do ESC O A instead.
812                  * Ctrl toggles the two modes.
813                  */
814                 if (inst->term->vt52_mode) {
815                     end = 1 + sprintf(output+1, "\033%c", xkey);
816                 } else if (!inst->term->app_cursor_keys ^
817                            !(event->state & GDK_CONTROL_MASK)) {
818                     end = 1 + sprintf(output+1, "\033O%c", xkey);
819                 } else {                    
820                     end = 1 + sprintf(output+1, "\033[%c", xkey);
821                 }
822                 goto done;
823             }
824         }
825         goto done;
826     }
827
828     done:
829
830     if (end-start > 0) {
831 #ifdef KEY_DEBUGGING
832         int i;
833         printf("generating sequence:");
834         for (i = start; i < end; i++)
835             printf(" %02x", (unsigned char) output[i]);
836         printf("\n");
837 #endif
838
839         /*
840          * The stuff we've just generated is assumed to be
841          * ISO-8859-1! This sounds insane, but `man XLookupString'
842          * agrees: strings of this type returned from the X server
843          * are hardcoded to 8859-1. Strictly speaking we should be
844          * doing this using some sort of GtkIMContext, which (if
845          * we're lucky) would give us our data directly in Unicode;
846          * but that's not supported in GTK 1.2 as far as I can
847          * tell, and it's poorly documented even in 2.0, so it'll
848          * have to wait.
849          */
850         lpage_send(inst->ldisc, CS_ISO8859_1, output+start, end-start, 1);
851
852         show_mouseptr(inst, 0);
853         term_seen_key_event(inst->term);
854         term_out(inst->term);
855     }
856
857     return TRUE;
858 }
859
860 gint button_event(GtkWidget *widget, GdkEventButton *event, gpointer data)
861 {
862     struct gui_data *inst = (struct gui_data *)data;
863     int shift, ctrl, alt, x, y, button, act;
864
865     show_mouseptr(inst, 1);
866
867     if (event->button == 4 && event->type == GDK_BUTTON_PRESS) {
868         term_scroll(inst->term, 0, -5);
869         return TRUE;
870     }
871     if (event->button == 5 && event->type == GDK_BUTTON_PRESS) {
872         term_scroll(inst->term, 0, +5);
873         return TRUE;
874     }
875
876     shift = event->state & GDK_SHIFT_MASK;
877     ctrl = event->state & GDK_CONTROL_MASK;
878     alt = event->state & GDK_MOD1_MASK;
879     if (event->button == 1)
880         button = MBT_LEFT;
881     else if (event->button == 2)
882         button = MBT_MIDDLE;
883     else if (event->button == 3)
884         button = MBT_RIGHT;
885     else
886         return FALSE;                  /* don't even know what button! */
887
888     switch (event->type) {
889       case GDK_BUTTON_PRESS: act = MA_CLICK; break;
890       case GDK_BUTTON_RELEASE: act = MA_RELEASE; break;
891       case GDK_2BUTTON_PRESS: act = MA_2CLK; break;
892       case GDK_3BUTTON_PRESS: act = MA_3CLK; break;
893       default: return FALSE;           /* don't know this event type */
894     }
895
896     if (send_raw_mouse && !(cfg.mouse_override && shift) &&
897         act != MA_CLICK && act != MA_RELEASE)
898         return TRUE;                   /* we ignore these in raw mouse mode */
899
900     x = (event->x - cfg.window_border) / inst->font_width;
901     y = (event->y - cfg.window_border) / inst->font_height;
902
903     term_mouse(inst->term, button, act, x, y, shift, ctrl, alt);
904
905     return TRUE;
906 }
907
908 gint motion_event(GtkWidget *widget, GdkEventMotion *event, gpointer data)
909 {
910     struct gui_data *inst = (struct gui_data *)data;
911     int shift, ctrl, alt, x, y, button;
912
913     show_mouseptr(inst, 1);
914
915     shift = event->state & GDK_SHIFT_MASK;
916     ctrl = event->state & GDK_CONTROL_MASK;
917     alt = event->state & GDK_MOD1_MASK;
918     if (event->state & GDK_BUTTON1_MASK)
919         button = MBT_LEFT;
920     else if (event->state & GDK_BUTTON2_MASK)
921         button = MBT_MIDDLE;
922     else if (event->state & GDK_BUTTON3_MASK)
923         button = MBT_RIGHT;
924     else
925         return FALSE;                  /* don't even know what button! */
926
927     x = (event->x - cfg.window_border) / inst->font_width;
928     y = (event->y - cfg.window_border) / inst->font_height;
929
930     term_mouse(inst->term, button, MA_DRAG, x, y, shift, ctrl, alt);
931
932     return TRUE;
933 }
934
935 void done_with_pty(struct gui_data *inst)
936 {
937     extern void pty_close(void);
938
939     if (inst->master_fd >= 0) {
940         pty_close();
941         inst->master_fd = -1;
942         gtk_input_remove(inst->master_func_id);
943     }
944
945     if (!inst->exited && inst->back->exitcode(inst->backhandle) >= 0) {
946         int exitcode = inst->back->exitcode(inst->backhandle);
947         int clean;
948
949         clean = WIFEXITED(exitcode) && (WEXITSTATUS(exitcode) == 0);
950
951         /*
952          * Terminate now, if the Close On Exit setting is
953          * appropriate.
954          */
955         if (cfg.close_on_exit == COE_ALWAYS ||
956             (cfg.close_on_exit == COE_NORMAL && clean))
957             exit(0);
958
959         /*
960          * Otherwise, output an indication that the session has
961          * closed.
962          */
963         {
964             char message[512];
965             if (WIFEXITED(exitcode))
966                 sprintf(message, "\r\n[pterm: process terminated with exit"
967                         " code %d]\r\n", WEXITSTATUS(exitcode));
968             else if (WIFSIGNALED(exitcode))
969 #ifdef HAVE_NO_STRSIGNAL
970                 sprintf(message, "\r\n[pterm: process terminated on signal"
971                         " %d]\r\n", WTERMSIG(exitcode));
972 #else
973                 sprintf(message, "\r\n[pterm: process terminated on signal"
974                         " %d (%.400s)]\r\n", WTERMSIG(exitcode),
975                         strsignal(WTERMSIG(exitcode)));
976 #endif
977             from_backend((void *)inst->term, 0, message, strlen(message));
978         }
979         inst->exited = 1;
980     }
981 }
982
983 void frontend_keypress(void *handle)
984 {
985     struct gui_data *inst = (struct gui_data *)handle;
986
987     /*
988      * If our child process has exited but not closed, terminate on
989      * any keypress.
990      */
991     if (inst->exited)
992         exit(0);
993 }
994
995 gint timer_func(gpointer data)
996 {
997     struct gui_data *inst = (struct gui_data *)data;
998
999     if (inst->back->exitcode(inst->backhandle) >= 0) {
1000         /*
1001          * The primary child process died. We could keep the
1002          * terminal open for remaining subprocesses to output to,
1003          * but conventional wisdom seems to feel that that's the
1004          * Wrong Thing for an xterm-alike, so we bail out now
1005          * (though we don't necessarily _close_ the window,
1006          * depending on the state of Close On Exit). This would be
1007          * easy enough to change or make configurable if necessary.
1008          */
1009         done_with_pty(inst);
1010     }
1011
1012     term_update(inst->term);
1013     term_blink(inst->term, 0);
1014     return TRUE;
1015 }
1016
1017 void pty_input_func(gpointer data, gint sourcefd, GdkInputCondition condition)
1018 {
1019     struct gui_data *inst = (struct gui_data *)data;
1020     char buf[4096];
1021     int ret;
1022
1023     ret = read(sourcefd, buf, sizeof(buf));
1024
1025     /*
1026      * Clean termination condition is that either ret == 0, or ret
1027      * < 0 and errno == EIO. Not sure why the latter, but it seems
1028      * to happen. Boo.
1029      */
1030     if (ret == 0 || (ret < 0 && errno == EIO)) {
1031         done_with_pty(inst);
1032     } else if (ret < 0) {
1033         perror("read pty master");
1034         exit(1);
1035     } else if (ret > 0)
1036         from_backend(inst->term, 0, buf, ret);
1037     term_blink(inst->term, 1);
1038     term_out(inst->term);
1039 }
1040
1041 void destroy(GtkWidget *widget, gpointer data)
1042 {
1043     gtk_main_quit();
1044 }
1045
1046 gint focus_event(GtkWidget *widget, GdkEventFocus *event, gpointer data)
1047 {
1048     struct gui_data *inst = (struct gui_data *)data;
1049     inst->term->has_focus = event->in;
1050     term_out(inst->term);
1051     term_update(inst->term);
1052     show_mouseptr(inst, 1);
1053     return FALSE;
1054 }
1055
1056 /*
1057  * set or clear the "raw mouse message" mode
1058  */
1059 void set_raw_mouse_mode(void *frontend, int activate)
1060 {
1061     struct gui_data *inst = (struct gui_data *)frontend;
1062     activate = activate && !cfg.no_mouse_rep;
1063     send_raw_mouse = activate;
1064     if (send_raw_mouse)
1065         inst->currcursor = inst->rawcursor;
1066     else
1067         inst->currcursor = inst->textcursor;
1068     show_mouseptr(inst, inst->mouseptr_visible);
1069 }
1070
1071 void request_resize(void *frontend, int w, int h)
1072 {
1073     struct gui_data *inst = (struct gui_data *)frontend;
1074     int large_x, large_y;
1075     int offset_x, offset_y;
1076     int area_x, area_y;
1077     GtkRequisition inner, outer;
1078
1079     /*
1080      * This is a heinous hack dreamed up by the gnome-terminal
1081      * people to get around a limitation in gtk. The problem is
1082      * that in order to set the size correctly we really need to be
1083      * calling gtk_window_resize - but that needs to know the size
1084      * of the _whole window_, not the drawing area. So what we do
1085      * is to set an artificially huge size request on the drawing
1086      * area, recompute the resulting size request on the window,
1087      * and look at the difference between the two. That gives us
1088      * the x and y offsets we need to translate drawing area size
1089      * into window size for real, and then we call
1090      * gtk_window_resize.
1091      */
1092
1093     /*
1094      * We start by retrieving the current size of the whole window.
1095      * Adding a bit to _that_ will give us a value we can use as a
1096      * bogus size request which guarantees to be bigger than the
1097      * current size of the drawing area.
1098      */
1099     get_window_pixels(inst, &large_x, &large_y);
1100     large_x += 32;
1101     large_y += 32;
1102
1103 #if GTK_CHECK_VERSION(2,0,0)
1104     gtk_widget_set_size_request(inst->area, large_x, large_y);
1105 #else
1106     gtk_widget_set_usize(inst->area, large_x, large_y);
1107 #endif
1108     gtk_widget_size_request(inst->area, &inner);
1109     gtk_widget_size_request(inst->window, &outer);
1110
1111     offset_x = outer.width - inner.width;
1112     offset_y = outer.height - inner.height;
1113
1114     area_x = inst->font_width * w + 2*cfg.window_border;
1115     area_y = inst->font_height * h + 2*cfg.window_border;
1116
1117     /*
1118      * Now we must set the size request on the drawing area back to
1119      * something sensible before we commit the real resize. Best
1120      * way to do this, I think, is to set it to what the size is
1121      * really going to end up being.
1122      */
1123 #if GTK_CHECK_VERSION(2,0,0)
1124     gtk_widget_set_size_request(inst->area, area_x, area_y);
1125 #else
1126     gtk_widget_set_usize(inst->area, area_x, area_y);
1127 #endif
1128
1129 #if GTK_CHECK_VERSION(2,0,0)
1130     gtk_window_resize(GTK_WINDOW(inst->window),
1131                       area_x + offset_x, area_y + offset_y);
1132 #else
1133     gdk_window_resize(inst->window->window,
1134                       area_x + offset_x, area_y + offset_y);
1135 #endif
1136 }
1137
1138 static void real_palette_set(struct gui_data *inst, int n, int r, int g, int b)
1139 {
1140     gboolean success[1];
1141
1142     inst->cols[n].red = r * 0x0101;
1143     inst->cols[n].green = g * 0x0101;
1144     inst->cols[n].blue = b * 0x0101;
1145
1146     gdk_colormap_alloc_colors(inst->colmap, inst->cols + n, 1,
1147                               FALSE, FALSE, success);
1148     if (!success[0])
1149         g_error("pterm: couldn't allocate colour %d (#%02x%02x%02x)\n",
1150                 n, r, g, b);
1151 }
1152
1153 void set_window_background(struct gui_data *inst)
1154 {
1155     if (inst->area && inst->area->window)
1156         gdk_window_set_background(inst->area->window, &inst->cols[18]);
1157     if (inst->window && inst->window->window)
1158         gdk_window_set_background(inst->window->window, &inst->cols[18]);
1159 }
1160
1161 void palette_set(void *frontend, int n, int r, int g, int b)
1162 {
1163     struct gui_data *inst = (struct gui_data *)frontend;
1164     static const int first[21] = {
1165         0, 2, 4, 6, 8, 10, 12, 14,
1166         1, 3, 5, 7, 9, 11, 13, 15,
1167         16, 17, 18, 20, 22
1168     };
1169     real_palette_set(inst, first[n], r, g, b);
1170     if (first[n] >= 18)
1171         real_palette_set(inst, first[n] + 1, r, g, b);
1172     if (first[n] == 18)
1173         set_window_background(inst);
1174 }
1175
1176 void palette_reset(void *frontend)
1177 {
1178     struct gui_data *inst = (struct gui_data *)frontend;
1179     /* This maps colour indices in cfg to those used in inst->cols. */
1180     static const int ww[] = {
1181         6, 7, 8, 9, 10, 11, 12, 13,
1182         14, 15, 16, 17, 18, 19, 20, 21,
1183         0, 1, 2, 3, 4, 5
1184     };
1185     gboolean success[NCOLOURS];
1186     int i;
1187
1188     assert(lenof(ww) == NCOLOURS);
1189
1190     if (!inst->colmap) {
1191         inst->colmap = gdk_colormap_get_system();
1192     } else {
1193         gdk_colormap_free_colors(inst->colmap, inst->cols, NCOLOURS);
1194     }
1195
1196     for (i = 0; i < NCOLOURS; i++) {
1197         inst->cols[i].red = cfg.colours[ww[i]][0] * 0x0101;
1198         inst->cols[i].green = cfg.colours[ww[i]][1] * 0x0101;
1199         inst->cols[i].blue = cfg.colours[ww[i]][2] * 0x0101;
1200     }
1201
1202     gdk_colormap_alloc_colors(inst->colmap, inst->cols, NCOLOURS,
1203                               FALSE, FALSE, success);
1204     for (i = 0; i < NCOLOURS; i++) {
1205         if (!success[i])
1206             g_error("pterm: couldn't allocate colour %d (#%02x%02x%02x)\n",
1207                     i, cfg.colours[i][0], cfg.colours[i][1], cfg.colours[i][2]);
1208     }
1209
1210     set_window_background(inst);
1211 }
1212
1213 void write_clip(void *frontend, wchar_t * data, int len, int must_deselect)
1214 {
1215     struct gui_data *inst = (struct gui_data *)frontend;
1216     if (inst->pasteout_data)
1217         sfree(inst->pasteout_data);
1218     if (inst->pasteout_data_utf8)
1219         sfree(inst->pasteout_data_utf8);
1220
1221     inst->pasteout_data_utf8 = smalloc(len*6);
1222     inst->pasteout_data_utf8_len = len*6;
1223     {
1224         wchar_t *tmp = data;
1225         int tmplen = len;
1226         inst->pasteout_data_utf8_len =
1227             charset_from_unicode(&tmp, &tmplen, inst->pasteout_data_utf8,
1228                                  inst->pasteout_data_utf8_len,
1229                                  CS_UTF8, NULL, NULL, 0);
1230         inst->pasteout_data_utf8 =
1231             srealloc(inst->pasteout_data_utf8, inst->pasteout_data_utf8_len);
1232     }
1233
1234     inst->pasteout_data = smalloc(len);
1235     inst->pasteout_data_len = len;
1236     wc_to_mb(line_codepage, 0, data, len,
1237              inst->pasteout_data, inst->pasteout_data_len,
1238              NULL, NULL);
1239
1240     if (gtk_selection_owner_set(inst->area, GDK_SELECTION_PRIMARY,
1241                                 GDK_CURRENT_TIME)) {
1242         gtk_selection_add_target(inst->area, GDK_SELECTION_PRIMARY,
1243                                  GDK_SELECTION_TYPE_STRING, 1);
1244         gtk_selection_add_target(inst->area, GDK_SELECTION_PRIMARY,
1245                                  inst->compound_text_atom, 1);
1246         gtk_selection_add_target(inst->area, GDK_SELECTION_PRIMARY,
1247                                  inst->utf8_string_atom, 1);
1248     }
1249 }
1250
1251 void selection_get(GtkWidget *widget, GtkSelectionData *seldata,
1252                    guint info, guint time_stamp, gpointer data)
1253 {
1254     struct gui_data *inst = (struct gui_data *)data;
1255     if (seldata->target == inst->utf8_string_atom)
1256         gtk_selection_data_set(seldata, seldata->target, 8,
1257                                inst->pasteout_data_utf8,
1258                                inst->pasteout_data_utf8_len);
1259     else
1260         gtk_selection_data_set(seldata, seldata->target, 8,
1261                                inst->pasteout_data, inst->pasteout_data_len);
1262 }
1263
1264 gint selection_clear(GtkWidget *widget, GdkEventSelection *seldata,
1265                      gpointer data)
1266 {
1267     struct gui_data *inst = (struct gui_data *)data;
1268     term_deselect(inst->term);
1269     if (inst->pasteout_data)
1270         sfree(inst->pasteout_data);
1271     if (inst->pasteout_data_utf8)
1272         sfree(inst->pasteout_data_utf8);
1273     inst->pasteout_data = NULL;
1274     inst->pasteout_data_len = 0;
1275     inst->pasteout_data_utf8 = NULL;
1276     inst->pasteout_data_utf8_len = 0;
1277     return TRUE;
1278 }
1279
1280 void request_paste(void *frontend)
1281 {
1282     struct gui_data *inst = (struct gui_data *)frontend;
1283     /*
1284      * In Unix, pasting is asynchronous: all we can do at the
1285      * moment is to call gtk_selection_convert(), and when the data
1286      * comes back _then_ we can call term_do_paste().
1287      */
1288
1289     /*
1290      * First we attempt to retrieve the selection as a UTF-8 string
1291      * (which we will convert to the correct code page before
1292      * sending to the session, of course). If that fails,
1293      * selection_received() will be informed and will fall back to
1294      * an ordinary string.
1295      */
1296     gtk_selection_convert(inst->area, GDK_SELECTION_PRIMARY,
1297                           inst->utf8_string_atom, GDK_CURRENT_TIME);
1298 }
1299
1300 gint idle_paste_func(gpointer data);   /* forward ref */
1301
1302 void selection_received(GtkWidget *widget, GtkSelectionData *seldata,
1303                         guint time, gpointer data)
1304 {
1305     struct gui_data *inst = (struct gui_data *)data;
1306
1307     if (seldata->target == inst->utf8_string_atom && seldata->length <= 0) {
1308         /*
1309          * Failed to get a UTF-8 selection string. Try an ordinary
1310          * string.
1311          */
1312         gtk_selection_convert(inst->area, GDK_SELECTION_PRIMARY,
1313                               GDK_SELECTION_TYPE_STRING, GDK_CURRENT_TIME);
1314         return;
1315     }
1316
1317     /*
1318      * Any other failure should just go foom.
1319      */
1320     if (seldata->length <= 0 ||
1321         (seldata->type != GDK_SELECTION_TYPE_STRING &&
1322          seldata->type != inst->utf8_string_atom))
1323         return;                        /* Nothing happens. */
1324
1325     if (inst->pastein_data)
1326         sfree(inst->pastein_data);
1327
1328     inst->pastein_data = smalloc(seldata->length * sizeof(wchar_t));
1329     inst->pastein_data_len = seldata->length;
1330     inst->pastein_data_len =
1331         mb_to_wc((seldata->type == inst->utf8_string_atom ?
1332                   CS_UTF8 : line_codepage),
1333                  0, seldata->data, seldata->length,
1334                  inst->pastein_data, inst->pastein_data_len);
1335
1336     term_do_paste(inst->term);
1337
1338     if (term_paste_pending(inst->term))
1339         inst->term_paste_idle_id = gtk_idle_add(idle_paste_func, inst);
1340 }
1341
1342 gint idle_paste_func(gpointer data)
1343 {
1344     struct gui_data *inst = (struct gui_data *)data;
1345
1346     if (term_paste_pending(inst->term))
1347         term_paste(inst->term);
1348     else
1349         gtk_idle_remove(inst->term_paste_idle_id);
1350
1351     return TRUE;
1352 }
1353
1354
1355 void get_clip(void *frontend, wchar_t ** p, int *len)
1356 {
1357     struct gui_data *inst = (struct gui_data *)frontend;
1358
1359     if (p) {
1360         *p = inst->pastein_data;
1361         *len = inst->pastein_data_len;
1362     }
1363 }
1364
1365 void set_title(void *frontend, char *title)
1366 {
1367     struct gui_data *inst = (struct gui_data *)frontend;
1368     strncpy(inst->wintitle, title, lenof(inst->wintitle));
1369     inst->wintitle[lenof(inst->wintitle)-1] = '\0';
1370     gtk_window_set_title(GTK_WINDOW(inst->window), inst->wintitle);
1371 }
1372
1373 void set_icon(void *frontend, char *title)
1374 {
1375     struct gui_data *inst = (struct gui_data *)frontend;
1376     strncpy(inst->icontitle, title, lenof(inst->icontitle));
1377     inst->icontitle[lenof(inst->icontitle)-1] = '\0';
1378     gdk_window_set_icon_name(inst->window->window, inst->icontitle);
1379 }
1380
1381 void set_sbar(void *frontend, int total, int start, int page)
1382 {
1383     struct gui_data *inst = (struct gui_data *)frontend;
1384     if (!cfg.scrollbar)
1385         return;
1386     inst->sbar_adjust->lower = 0;
1387     inst->sbar_adjust->upper = total;
1388     inst->sbar_adjust->value = start;
1389     inst->sbar_adjust->page_size = page;
1390     inst->sbar_adjust->step_increment = 1;
1391     inst->sbar_adjust->page_increment = page/2;
1392     inst->ignore_sbar = TRUE;
1393     gtk_adjustment_changed(inst->sbar_adjust);
1394     inst->ignore_sbar = FALSE;
1395 }
1396
1397 void scrollbar_moved(GtkAdjustment *adj, gpointer data)
1398 {
1399     struct gui_data *inst = (struct gui_data *)data;
1400
1401     if (!cfg.scrollbar)
1402         return;
1403     if (!inst->ignore_sbar)
1404         term_scroll(inst->term, 1, (int)adj->value);
1405 }
1406
1407 void sys_cursor(void *frontend, int x, int y)
1408 {
1409     /*
1410      * This is meaningless under X.
1411      */
1412 }
1413
1414 /*
1415  * This is still called when mode==BELL_VISUAL, even though the
1416  * visual bell is handled entirely within terminal.c, because we
1417  * may want to perform additional actions on any kind of bell (for
1418  * example, taskbar flashing in Windows).
1419  */
1420 void beep(void *frontend, int mode)
1421 {
1422     if (mode != BELL_VISUAL)
1423         gdk_beep();
1424 }
1425
1426 int char_width(Context ctx, int uc)
1427 {
1428     /*
1429      * Under X, any fixed-width font really _is_ fixed-width.
1430      * Double-width characters will be dealt with using a separate
1431      * font. For the moment we can simply return 1.
1432      */
1433     return 1;
1434 }
1435
1436 Context get_ctx(void *frontend)
1437 {
1438     struct gui_data *inst = (struct gui_data *)frontend;
1439     struct draw_ctx *dctx;
1440
1441     if (!inst->area->window)
1442         return NULL;
1443
1444     dctx = smalloc(sizeof(*dctx));
1445     dctx->inst = inst;
1446     dctx->gc = gdk_gc_new(inst->area->window);
1447     return dctx;
1448 }
1449
1450 void free_ctx(Context ctx)
1451 {
1452     struct draw_ctx *dctx = (struct draw_ctx *)ctx;
1453     /* struct gui_data *inst = dctx->inst; */
1454     GdkGC *gc = dctx->gc;
1455     gdk_gc_unref(gc);
1456     sfree(dctx);
1457 }
1458
1459 /*
1460  * Draw a line of text in the window, at given character
1461  * coordinates, in given attributes.
1462  *
1463  * We are allowed to fiddle with the contents of `text'.
1464  */
1465 void do_text_internal(Context ctx, int x, int y, char *text, int len,
1466                       unsigned long attr, int lattr)
1467 {
1468     struct draw_ctx *dctx = (struct draw_ctx *)ctx;
1469     struct gui_data *inst = dctx->inst;
1470     GdkGC *gc = dctx->gc;
1471
1472     int nfg, nbg, t, fontid, shadow, rlen;
1473
1474     /*
1475      * NYI:
1476      *  - Unicode, code pages, and ATTR_WIDE for CJK support.
1477      */
1478
1479     nfg = 2 * ((attr & ATTR_FGMASK) >> ATTR_FGSHIFT);
1480     nbg = 2 * ((attr & ATTR_BGMASK) >> ATTR_BGSHIFT);
1481     if (attr & ATTR_REVERSE) {
1482         t = nfg;
1483         nfg = nbg;
1484         nbg = t;
1485     }
1486     if (cfg.bold_colour && (attr & ATTR_BOLD))
1487         nfg++;
1488     if (cfg.bold_colour && (attr & ATTR_BLINK))
1489         nbg++;
1490     if (attr & TATTR_ACTCURS) {
1491         nfg = NCOLOURS-2;
1492         nbg = NCOLOURS-1;
1493     }
1494
1495     fontid = shadow = 0;
1496     if ((attr & ATTR_BOLD) && !cfg.bold_colour) {
1497         if (inst->fonts[1])
1498             fontid = 1;
1499         else
1500             shadow = 1;
1501     }
1502
1503     if (lattr != LATTR_NORM) {
1504         x *= 2;
1505         if (x >= inst->term->cols)
1506             return;
1507         if (x + len*2 > inst->term->cols)
1508             len = (inst->term->cols-x)/2;    /* trim to LH half */
1509         rlen = len * 2;
1510     } else
1511         rlen = len;
1512
1513     {
1514         GdkRectangle r;
1515
1516         r.x = x*inst->font_width+cfg.window_border;
1517         r.y = y*inst->font_height+cfg.window_border;
1518         r.width = rlen*inst->font_width;
1519         r.height = inst->font_height;
1520         gdk_gc_set_clip_rectangle(gc, &r);
1521     }
1522
1523     gdk_gc_set_foreground(gc, &inst->cols[nbg]);
1524     gdk_draw_rectangle(inst->pixmap, gc, 1,
1525                        x*inst->font_width+cfg.window_border,
1526                        y*inst->font_height+cfg.window_border,
1527                        rlen*inst->font_width, inst->font_height);
1528
1529     gdk_gc_set_foreground(gc, &inst->cols[nfg]);
1530     {
1531         GdkWChar *gwcs;
1532         gchar *gcs;
1533         wchar_t *wcs;
1534         int i;
1535
1536         wcs = smalloc(sizeof(wchar_t) * (len+1));
1537         for (i = 0; i < len; i++) {
1538             wcs[i] = (wchar_t) ((attr & CSET_MASK) + (text[i] & CHAR_MASK));
1539         }
1540
1541         if (inst->fontinfo[fontid].is_wide) {
1542             gwcs = smalloc(sizeof(GdkWChar) * (len+1));
1543             /*
1544              * FIXME: when we have a wide-char equivalent of
1545              * from_unicode, use it instead of this.
1546              */
1547             for (i = 0; i <= len; i++)
1548                 gwcs[i] = wcs[i];
1549             gdk_draw_text_wc(inst->pixmap, inst->fonts[fontid], gc,
1550                              x*inst->font_width+cfg.window_border,
1551                              y*inst->font_height+cfg.window_border+inst->fonts[0]->ascent,
1552                              gwcs, len*2);
1553             sfree(gwcs);
1554         } else {
1555             wchar_t *wcstmp = wcs;
1556             int lentmp = len;
1557             gcs = smalloc(sizeof(GdkWChar) * (len+1));
1558             charset_from_unicode(&wcstmp, &lentmp, gcs, len,
1559                                  inst->fontinfo[fontid].charset,
1560                                  NULL, ".", 1);
1561             gdk_draw_text(inst->pixmap, inst->fonts[fontid], gc,
1562                           x*inst->font_width+cfg.window_border,
1563                           y*inst->font_height+cfg.window_border+inst->fonts[0]->ascent,
1564                           gcs, len);
1565             sfree(gcs);
1566         }
1567         sfree(wcs);
1568     }
1569
1570     if (shadow) {
1571         gdk_draw_text(inst->pixmap, inst->fonts[fontid], gc,
1572                       x*inst->font_width+cfg.window_border + cfg.shadowboldoffset,
1573                       y*inst->font_height+cfg.window_border+inst->fonts[0]->ascent,
1574                       text, len);
1575     }
1576
1577     if (attr & ATTR_UNDER) {
1578         int uheight = inst->fonts[0]->ascent + 1;
1579         if (uheight >= inst->font_height)
1580             uheight = inst->font_height - 1;
1581         gdk_draw_line(inst->pixmap, gc, x*inst->font_width+cfg.window_border,
1582                       y*inst->font_height + uheight + cfg.window_border,
1583                       (x+len)*inst->font_width-1+cfg.window_border,
1584                       y*inst->font_height + uheight + cfg.window_border);
1585     }
1586
1587     if (lattr != LATTR_NORM) {
1588         /*
1589          * I can't find any plausible StretchBlt equivalent in the
1590          * X server, so I'm going to do this the slow and painful
1591          * way. This will involve repeated calls to
1592          * gdk_draw_pixmap() to stretch the text horizontally. It's
1593          * O(N^2) in time and O(N) in network bandwidth, but you
1594          * try thinking of a better way. :-(
1595          */
1596         int i;
1597         for (i = 0; i < len * inst->font_width; i++) {
1598             gdk_draw_pixmap(inst->pixmap, gc, inst->pixmap,
1599                             x*inst->font_width+cfg.window_border + 2*i,
1600                             y*inst->font_height+cfg.window_border,
1601                             x*inst->font_width+cfg.window_border + 2*i+1,
1602                             y*inst->font_height+cfg.window_border,
1603                             len * inst->font_width - i, inst->font_height);
1604         }
1605         len *= 2;
1606         if (lattr != LATTR_WIDE) {
1607             int dt, db;
1608             /* Now stretch vertically, in the same way. */
1609             if (lattr == LATTR_BOT)
1610                 dt = 0, db = 1;
1611             else
1612                 dt = 1, db = 0;
1613             for (i = 0; i < inst->font_height; i+=2) {
1614                 gdk_draw_pixmap(inst->pixmap, gc, inst->pixmap,
1615                                 x*inst->font_width+cfg.window_border,
1616                                 y*inst->font_height+cfg.window_border+dt*i+db,
1617                                 x*inst->font_width+cfg.window_border,
1618                                 y*inst->font_height+cfg.window_border+dt*(i+1),
1619                                 len * inst->font_width, inst->font_height-i-1);
1620             }
1621         }
1622     }
1623 }
1624
1625 void do_text(Context ctx, int x, int y, char *text, int len,
1626              unsigned long attr, int lattr)
1627 {
1628     struct draw_ctx *dctx = (struct draw_ctx *)ctx;
1629     struct gui_data *inst = dctx->inst;
1630     GdkGC *gc = dctx->gc;
1631
1632     do_text_internal(ctx, x, y, text, len, attr, lattr);
1633
1634     if (lattr != LATTR_NORM) {
1635         x *= 2;
1636         if (x >= inst->term->cols)
1637             return;
1638         if (x + len*2 > inst->term->cols)
1639             len = (inst->term->cols-x)/2;    /* trim to LH half */
1640         len *= 2;
1641     }
1642
1643     gdk_draw_pixmap(inst->area->window, gc, inst->pixmap,
1644                     x*inst->font_width+cfg.window_border,
1645                     y*inst->font_height+cfg.window_border,
1646                     x*inst->font_width+cfg.window_border,
1647                     y*inst->font_height+cfg.window_border,
1648                     len*inst->font_width, inst->font_height);
1649 }
1650
1651 void do_cursor(Context ctx, int x, int y, char *text, int len,
1652                unsigned long attr, int lattr)
1653 {
1654     struct draw_ctx *dctx = (struct draw_ctx *)ctx;
1655     struct gui_data *inst = dctx->inst;
1656     GdkGC *gc = dctx->gc;
1657
1658     int passive;
1659
1660     if (attr & TATTR_PASCURS) {
1661         attr &= ~TATTR_PASCURS;
1662         passive = 1;
1663     } else
1664         passive = 0;
1665     if ((attr & TATTR_ACTCURS) && cfg.cursor_type != 0) {
1666         attr &= ~TATTR_ACTCURS;
1667     }
1668     do_text_internal(ctx, x, y, text, len, attr, lattr);
1669
1670     if (lattr != LATTR_NORM) {
1671         x *= 2;
1672         if (x >= inst->term->cols)
1673             return;
1674         if (x + len*2 > inst->term->cols)
1675             len = (inst->term->cols-x)/2;    /* trim to LH half */
1676         len *= 2;
1677     }
1678
1679     if (cfg.cursor_type == 0) {
1680         /*
1681          * An active block cursor will already have been done by
1682          * the above do_text call, so we only need to do anything
1683          * if it's passive.
1684          */
1685         if (passive) {
1686             gdk_gc_set_foreground(gc, &inst->cols[NCOLOURS-1]);
1687             gdk_draw_rectangle(inst->pixmap, gc, 0,
1688                                x*inst->font_width+cfg.window_border,
1689                                y*inst->font_height+cfg.window_border,
1690                                len*inst->font_width-1, inst->font_height-1);
1691         }
1692     } else {
1693         int uheight;
1694         int startx, starty, dx, dy, length, i;
1695
1696         int char_width;
1697
1698         if ((attr & ATTR_WIDE) || lattr != LATTR_NORM)
1699             char_width = 2*inst->font_width;
1700         else
1701             char_width = inst->font_width;
1702
1703         if (cfg.cursor_type == 1) {
1704             uheight = inst->fonts[0]->ascent + 1;
1705             if (uheight >= inst->font_height)
1706                 uheight = inst->font_height - 1;
1707
1708             startx = x * inst->font_width + cfg.window_border;
1709             starty = y * inst->font_height + cfg.window_border + uheight;
1710             dx = 1;
1711             dy = 0;
1712             length = len * char_width;
1713         } else {
1714             int xadjust = 0;
1715             if (attr & TATTR_RIGHTCURS)
1716                 xadjust = char_width - 1;
1717             startx = x * inst->font_width + cfg.window_border + xadjust;
1718             starty = y * inst->font_height + cfg.window_border;
1719             dx = 0;
1720             dy = 1;
1721             length = inst->font_height;
1722         }
1723
1724         gdk_gc_set_foreground(gc, &inst->cols[NCOLOURS-1]);
1725         if (passive) {
1726             for (i = 0; i < length; i++) {
1727                 if (i % 2 == 0) {
1728                     gdk_draw_point(inst->pixmap, gc, startx, starty);
1729                 }
1730                 startx += dx;
1731                 starty += dy;
1732             }
1733         } else {
1734             gdk_draw_line(inst->pixmap, gc, startx, starty,
1735                           startx + (length-1) * dx, starty + (length-1) * dy);
1736         }
1737     }
1738
1739     gdk_draw_pixmap(inst->area->window, gc, inst->pixmap,
1740                     x*inst->font_width+cfg.window_border,
1741                     y*inst->font_height+cfg.window_border,
1742                     x*inst->font_width+cfg.window_border,
1743                     y*inst->font_height+cfg.window_border,
1744                     len*inst->font_width, inst->font_height);
1745 }
1746
1747 GdkCursor *make_mouse_ptr(struct gui_data *inst, int cursor_val)
1748 {
1749     /*
1750      * Truly hideous hack: GTK doesn't allow us to set the mouse
1751      * cursor foreground and background colours unless we've _also_
1752      * created our own cursor from bitmaps. Therefore, I need to
1753      * load the `cursor' font and draw glyphs from it on to
1754      * pixmaps, in order to construct my cursors with the fg and bg
1755      * I want. This is a gross hack, but it's more self-contained
1756      * than linking in Xlib to find the X window handle to
1757      * inst->area and calling XRecolorCursor, and it's more
1758      * futureproof than hard-coding the shapes as bitmap arrays.
1759      */
1760     static GdkFont *cursor_font = NULL;
1761     GdkPixmap *source, *mask;
1762     GdkGC *gc;
1763     GdkColor cfg = { 0, 65535, 65535, 65535 };
1764     GdkColor cbg = { 0, 0, 0, 0 };
1765     GdkColor dfg = { 1, 65535, 65535, 65535 };
1766     GdkColor dbg = { 0, 0, 0, 0 };
1767     GdkCursor *ret;
1768     gchar text[2];
1769     gint lb, rb, wid, asc, desc, w, h, x, y;
1770
1771     if (cursor_val == -2) {
1772         gdk_font_unref(cursor_font);
1773         return NULL;
1774     }
1775
1776     if (cursor_val >= 0 && !cursor_font)
1777         cursor_font = gdk_font_load("cursor");
1778
1779     /*
1780      * Get the text extent of the cursor in question. We use the
1781      * mask character for this, because it's typically slightly
1782      * bigger than the main character.
1783      */
1784     if (cursor_val >= 0) {
1785         text[1] = '\0';
1786         text[0] = (char)cursor_val + 1;
1787         gdk_string_extents(cursor_font, text, &lb, &rb, &wid, &asc, &desc);
1788         w = rb-lb; h = asc+desc; x = -lb; y = asc;
1789     } else {
1790         w = h = 1;
1791         x = y = 0;
1792     }
1793
1794     source = gdk_pixmap_new(NULL, w, h, 1);
1795     mask = gdk_pixmap_new(NULL, w, h, 1);
1796
1797     /*
1798      * Draw the mask character on the mask pixmap.
1799      */
1800     gc = gdk_gc_new(mask);
1801     gdk_gc_set_foreground(gc, &dbg);
1802     gdk_draw_rectangle(mask, gc, 1, 0, 0, w, h);
1803     if (cursor_val >= 0) {
1804         text[1] = '\0';
1805         text[0] = (char)cursor_val + 1;
1806         gdk_gc_set_foreground(gc, &dfg);
1807         gdk_draw_text(mask, cursor_font, gc, x, y, text, 1);
1808     }
1809     gdk_gc_unref(gc);
1810
1811     /*
1812      * Draw the main character on the source pixmap.
1813      */
1814     gc = gdk_gc_new(source);
1815     gdk_gc_set_foreground(gc, &dbg);
1816     gdk_draw_rectangle(source, gc, 1, 0, 0, w, h);
1817     if (cursor_val >= 0) {
1818         text[1] = '\0';
1819         text[0] = (char)cursor_val;
1820         gdk_gc_set_foreground(gc, &dfg);
1821         gdk_draw_text(source, cursor_font, gc, x, y, text, 1);
1822     }
1823     gdk_gc_unref(gc);
1824
1825     /*
1826      * Create the cursor.
1827      */
1828     ret = gdk_cursor_new_from_pixmap(source, mask, &cfg, &cbg, x, y);
1829
1830     /*
1831      * Clean up.
1832      */
1833     gdk_pixmap_unref(source);
1834     gdk_pixmap_unref(mask);
1835
1836     return ret;
1837 }
1838
1839 void modalfatalbox(char *p, ...)
1840 {
1841     va_list ap;
1842     fprintf(stderr, "FATAL ERROR: ");
1843     va_start(ap, p);
1844     vfprintf(stderr, p, ap);
1845     va_end(ap);
1846     fputc('\n', stderr);
1847     exit(1);
1848 }
1849
1850 char *get_x_display(void *frontend)
1851 {
1852     return gdk_get_display();
1853 }
1854
1855 static void help(FILE *fp) {
1856     if(fprintf(fp,
1857 "pterm option summary:\n"
1858 "\n"
1859 "  --display DISPLAY         Specify X display to use (note '--')\n"
1860 "  -name PREFIX              Prefix when looking up resources (default: pterm)\n"
1861 "  -fn FONT                  Normal text font\n"
1862 "  -fb FONT                  Bold text font\n"
1863 "  -geometry WIDTHxHEIGHT    Size of terminal in characters\n"
1864 "  -sl LINES                 Number of lines of scrollback\n"
1865 "  -fg COLOUR, -bg COLOUR    Foreground/background colour\n"
1866 "  -bfg COLOUR, -bbg COLOUR  Foreground/background bold colour\n"
1867 "  -cfg COLOUR, -bfg COLOUR  Foreground/background cursor colour\n"
1868 "  -T TITLE                  Window title\n"
1869 "  -ut, +ut                  Do(default) or do not update utmp\n"
1870 "  -ls, +ls                  Do(default) or do not make shell a login shell\n"
1871 "  -sb, +sb                  Do(default) or do not display a scrollbar\n"
1872 "  -log PATH                 Log all output to a file\n"
1873 "  -nethack                  Map numeric keypad to hjklyubn direction keys\n"
1874 "  -xrm RESOURCE-STRING      Set an X resource\n"
1875 "  -e COMMAND [ARGS...]      Execute command (consumes all remaining args)\n"
1876          ) < 0 || fflush(fp) < 0) {
1877         perror("output error");
1878         exit(1);
1879     }
1880 }
1881
1882 int do_cmdline(int argc, char **argv, int do_everything)
1883 {
1884     int err = 0;
1885     extern char **pty_argv;            /* declared in pty.c */
1886
1887     /*
1888      * Macros to make argument handling easier. Note that because
1889      * they need to call `continue', they cannot be contained in
1890      * the usual do {...} while (0) wrapper to make them
1891      * syntactically single statements; hence it is not legal to
1892      * use one of these macros as an unbraced statement between
1893      * `if' and `else'.
1894      */
1895 #define EXPECTS_ARG { \
1896     if (--argc <= 0) { \
1897         err = 1; \
1898         fprintf(stderr, "pterm: %s expects an argument\n", p); \
1899         continue; \
1900     } else \
1901         val = *++argv; \
1902 }
1903 #define SECOND_PASS_ONLY { if (!do_everything) continue; }
1904
1905     /*
1906      * TODO:
1907      * 
1908      * finish -geometry
1909      */
1910
1911     char *val;
1912     while (--argc > 0) {
1913         char *p = *++argv;
1914         if (!strcmp(p, "-fn") || !strcmp(p, "-font")) {
1915             EXPECTS_ARG;
1916             SECOND_PASS_ONLY;
1917             strncpy(cfg.font, val, sizeof(cfg.font));
1918             cfg.font[sizeof(cfg.font)-1] = '\0';
1919
1920         } else if (!strcmp(p, "-fb")) {
1921             EXPECTS_ARG;
1922             SECOND_PASS_ONLY;
1923             strncpy(cfg.boldfont, val, sizeof(cfg.boldfont));
1924             cfg.boldfont[sizeof(cfg.boldfont)-1] = '\0';
1925
1926         } else if (!strcmp(p, "-cs")) {
1927             EXPECTS_ARG;
1928             SECOND_PASS_ONLY;
1929             strncpy(cfg.line_codepage, val, sizeof(cfg.line_codepage));
1930             cfg.line_codepage[sizeof(cfg.line_codepage)-1] = '\0';
1931
1932         } else if (!strcmp(p, "-geometry")) {
1933             int flags, x, y, w, h;
1934             EXPECTS_ARG;
1935             SECOND_PASS_ONLY;
1936
1937             flags = XParseGeometry(val, &x, &y, &w, &h);
1938             if (flags & WidthValue)
1939                 cfg.width = w;
1940             if (flags & HeightValue)
1941                 cfg.height = h;
1942
1943             /*
1944              * Apparently setting the initial window position is
1945              * difficult in GTK 1.2. Not entirely sure why this
1946              * should be. 2.0 has gtk_window_parse_geometry(),
1947              * which would help... For the moment, though, I can't
1948              * be bothered with this.
1949              */
1950
1951         } else if (!strcmp(p, "-sl")) {
1952             EXPECTS_ARG;
1953             SECOND_PASS_ONLY;
1954             cfg.savelines = atoi(val);
1955
1956         } else if (!strcmp(p, "-fg") || !strcmp(p, "-bg") ||
1957                    !strcmp(p, "-bfg") || !strcmp(p, "-bbg") ||
1958                    !strcmp(p, "-cfg") || !strcmp(p, "-cbg")) {
1959             GdkColor col;
1960
1961             EXPECTS_ARG;
1962             SECOND_PASS_ONLY;
1963             if (!gdk_color_parse(val, &col)) {
1964                 err = 1;
1965                 fprintf(stderr, "pterm: unable to parse colour \"%s\"\n", val);
1966             } else {
1967                 int index;
1968                 index = (!strcmp(p, "-fg") ? 0 :
1969                          !strcmp(p, "-bg") ? 2 :
1970                          !strcmp(p, "-bfg") ? 1 :
1971                          !strcmp(p, "-bbg") ? 3 :
1972                          !strcmp(p, "-cfg") ? 4 :
1973                          !strcmp(p, "-cbg") ? 5 : -1);
1974                 assert(index != -1);
1975                 cfg.colours[index][0] = col.red / 256;
1976                 cfg.colours[index][1] = col.green / 256;
1977                 cfg.colours[index][2] = col.blue / 256;
1978             }
1979
1980         } else if (!strcmp(p, "-e")) {
1981             /* This option swallows all further arguments. */
1982             if (!do_everything)
1983                 break;
1984
1985             if (--argc > 0) {
1986                 int i;
1987                 pty_argv = smalloc((argc+1) * sizeof(char *));
1988                 ++argv;
1989                 for (i = 0; i < argc; i++)
1990                     pty_argv[i] = argv[i];
1991                 pty_argv[argc] = NULL;
1992                 break;                 /* finished command-line processing */
1993             } else
1994                 err = 1, fprintf(stderr, "pterm: -e expects an argument\n");
1995
1996         } else if (!strcmp(p, "-T")) {
1997             EXPECTS_ARG;
1998             SECOND_PASS_ONLY;
1999             strncpy(cfg.wintitle, val, sizeof(cfg.wintitle));
2000             cfg.wintitle[sizeof(cfg.wintitle)-1] = '\0';
2001
2002         } else if (!strcmp(p, "-log")) {
2003             EXPECTS_ARG;
2004             SECOND_PASS_ONLY;
2005             strncpy(cfg.logfilename, val, sizeof(cfg.logfilename));
2006             cfg.logfilename[sizeof(cfg.logfilename)-1] = '\0';
2007             cfg.logtype = LGTYP_DEBUG;
2008
2009         } else if (!strcmp(p, "-ut-") || !strcmp(p, "+ut")) {
2010             SECOND_PASS_ONLY;
2011             cfg.stamp_utmp = 0;
2012
2013         } else if (!strcmp(p, "-ut")) {
2014             SECOND_PASS_ONLY;
2015             cfg.stamp_utmp = 1;
2016
2017         } else if (!strcmp(p, "-ls-") || !strcmp(p, "+ls")) {
2018             SECOND_PASS_ONLY;
2019             cfg.login_shell = 0;
2020
2021         } else if (!strcmp(p, "-ls")) {
2022             SECOND_PASS_ONLY;
2023             cfg.login_shell = 1;
2024
2025         } else if (!strcmp(p, "-nethack")) {
2026             SECOND_PASS_ONLY;
2027             cfg.nethack_keypad = 1;
2028
2029         } else if (!strcmp(p, "-sb-") || !strcmp(p, "+sb")) {
2030             SECOND_PASS_ONLY;
2031             cfg.scrollbar = 0;
2032
2033         } else if (!strcmp(p, "-sb")) {
2034             SECOND_PASS_ONLY;
2035             cfg.scrollbar = 0;
2036
2037         } else if (!strcmp(p, "-name")) {
2038             EXPECTS_ARG;
2039             app_name = val;
2040
2041         } else if (!strcmp(p, "-xrm")) {
2042             EXPECTS_ARG;
2043             provide_xrm_string(val);
2044
2045         } else if(!strcmp(p, "-help") || !strcmp(p, "--help")) {
2046             help(stdout);
2047             exit(0);
2048             
2049         } else {
2050             err = 1;
2051             fprintf(stderr, "pterm: unrecognized option '%s'\n", p);
2052         }
2053     }
2054
2055     return err;
2056 }
2057
2058 static void block_signal(int sig, int block_it) {
2059   sigset_t ss;
2060
2061   sigemptyset(&ss);
2062   sigaddset(&ss, sig);
2063   if(sigprocmask(block_it ? SIG_BLOCK : SIG_UNBLOCK, &ss, 0) < 0) {
2064     perror("sigprocmask");
2065     exit(1);
2066   }
2067 }
2068
2069 static void set_font_info(struct gui_data *inst, int fontid)
2070 {
2071     GdkFont *font = inst->fonts[fontid];
2072     XFontStruct *xfs = GDK_FONT_XFONT(font);
2073     Display *disp = GDK_FONT_XDISPLAY(font);
2074     Atom charset_registry, charset_encoding;
2075     unsigned long registry_ret, encoding_ret;
2076     charset_registry = XInternAtom(disp, "CHARSET_REGISTRY", False);
2077     charset_encoding = XInternAtom(disp, "CHARSET_ENCODING", False);
2078     inst->fontinfo[fontid].charset = CS_NONE;
2079     inst->fontinfo[fontid].is_wide = 0;
2080     if (XGetFontProperty(xfs, charset_registry, &registry_ret) &&
2081         XGetFontProperty(xfs, charset_encoding, &encoding_ret)) {
2082         char *reg, *enc;
2083         reg = XGetAtomName(disp, (Atom)registry_ret);
2084         enc = XGetAtomName(disp, (Atom)encoding_ret);
2085         if (reg && enc) {
2086             char *encoding = dupcat(reg, "-", enc, NULL);
2087             inst->fontinfo[fontid].charset = charset_from_xenc(encoding);
2088             /* FIXME: when libcharset supports wide encodings fix this. */
2089             if (!strcasecmp(encoding, "iso10646-1"))
2090                 inst->fontinfo[fontid].is_wide = 1;
2091
2092             /*
2093              * Hack for X line-drawing characters: if the primary
2094              * font is encoded as ISO-8859-anything, and has valid
2095              * glyphs in the first 32 char positions, it is assumed
2096              * that those glyphs are the VT100 line-drawing
2097              * character set.
2098              * 
2099              * Actually, we'll hack even harder by only checking
2100              * position 0x19 (vertical line, VT100 linedrawing
2101              * `x'). Then we can check it easily by seeing if the
2102              * ascent and descent differ.
2103              */
2104             if (inst->fontinfo[fontid].charset == CS_ISO8859_1) {
2105                 int lb, rb, wid, asc, desc;
2106                 gchar text[2];
2107
2108                 text[1] = '\0';
2109                 text[0] = '\x12';
2110                 gdk_string_extents(inst->fonts[fontid], text,
2111                                    &lb, &rb, &wid, &asc, &desc);
2112                 if (asc != desc)
2113                     inst->fontinfo[fontid].charset = CS_ISO8859_1_X11;
2114             }
2115
2116             /*
2117              * FIXME: this is a hack. Currently fonts with
2118              * incomprehensible encodings are dealt with by
2119              * pretending they're 8859-1. It's ugly, but it's good
2120              * enough to stop things crashing. Should do something
2121              * better here.
2122              */
2123             if (inst->fontinfo[fontid].charset == CS_NONE)
2124                 inst->fontinfo[fontid].charset = CS_ISO8859_1;
2125
2126             sfree(encoding);
2127         }
2128     }
2129 }
2130
2131 int main(int argc, char **argv)
2132 {
2133     extern int pty_master_fd;          /* declared in pty.c */
2134     extern void pty_pre_init(void);    /* declared in pty.c */
2135     struct gui_data *inst;
2136
2137     /* defer any child exit handling until we're ready to deal with
2138      * it */
2139     block_signal(SIGCHLD, 1);
2140
2141     pty_pre_init();
2142
2143     gtk_init(&argc, &argv);
2144
2145     if (do_cmdline(argc, argv, 0))     /* pre-defaults pass to get -class */
2146         exit(1);
2147     do_defaults(NULL, &cfg);
2148     if (do_cmdline(argc, argv, 1))     /* post-defaults, do everything */
2149         exit(1);
2150
2151     /*
2152      * Create an instance structure and initialise to zeroes
2153      */
2154     inst = smalloc(sizeof(*inst));
2155     memset(inst, 0, sizeof(*inst));
2156     inst->alt_keycode = -1;            /* this one needs _not_ to be zero */
2157
2158     inst->fonts[0] = gdk_font_load(cfg.font);
2159     if (!inst->fonts[0]) {
2160         fprintf(stderr, "pterm: unable to load font \"%s\"\n", cfg.font);
2161         exit(1);
2162     }
2163     set_font_info(inst, 0);
2164     if (cfg.boldfont[0]) {
2165         inst->fonts[1] = gdk_font_load(cfg.boldfont);
2166         if (!inst->fonts[1]) {
2167             fprintf(stderr, "pterm: unable to load bold font \"%s\"\n",
2168                     cfg.boldfont);
2169             exit(1);
2170         }
2171         set_font_info(inst, 1);
2172     } else
2173         inst->fonts[1] = NULL;
2174
2175     inst->font_width = gdk_char_width(inst->fonts[0], ' ');
2176     inst->font_height = inst->fonts[0]->ascent + inst->fonts[0]->descent;
2177
2178     inst->compound_text_atom = gdk_atom_intern("COMPOUND_TEXT", FALSE);
2179     inst->utf8_string_atom = gdk_atom_intern("UTF8_STRING", FALSE);
2180
2181     init_ucs();
2182
2183     inst->window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
2184
2185     if (cfg.wintitle[0])
2186         set_title(inst, cfg.wintitle);
2187     else
2188         set_title(inst, "pterm");
2189
2190     /*
2191      * Set up the colour map.
2192      */
2193     palette_reset(inst);
2194
2195     inst->area = gtk_drawing_area_new();
2196     gtk_drawing_area_size(GTK_DRAWING_AREA(inst->area),
2197                           inst->font_width * cfg.width + 2*cfg.window_border,
2198                           inst->font_height * cfg.height + 2*cfg.window_border);
2199     if (cfg.scrollbar) {
2200         inst->sbar_adjust = GTK_ADJUSTMENT(gtk_adjustment_new(0,0,0,0,0,0));
2201         inst->sbar = gtk_vscrollbar_new(inst->sbar_adjust);
2202     }
2203     inst->hbox = GTK_BOX(gtk_hbox_new(FALSE, 0));
2204     if (cfg.scrollbar) {
2205         if (cfg.scrollbar_on_left)
2206             gtk_box_pack_start(inst->hbox, inst->sbar, FALSE, FALSE, 0);
2207         else
2208             gtk_box_pack_end(inst->hbox, inst->sbar, FALSE, FALSE, 0);
2209     }
2210     gtk_box_pack_start(inst->hbox, inst->area, TRUE, TRUE, 0);
2211
2212     gtk_container_add(GTK_CONTAINER(inst->window), GTK_WIDGET(inst->hbox));
2213
2214     {
2215         GdkGeometry geom;
2216         geom.min_width = inst->font_width + 2*cfg.window_border;
2217         geom.min_height = inst->font_height + 2*cfg.window_border;
2218         geom.max_width = geom.max_height = -1;
2219         geom.base_width = 2*cfg.window_border;
2220         geom.base_height = 2*cfg.window_border;
2221         geom.width_inc = inst->font_width;
2222         geom.height_inc = inst->font_height;
2223         geom.min_aspect = geom.max_aspect = 0;
2224         gtk_window_set_geometry_hints(GTK_WINDOW(inst->window), inst->area, &geom,
2225                                       GDK_HINT_MIN_SIZE | GDK_HINT_BASE_SIZE |
2226                                       GDK_HINT_RESIZE_INC);
2227     }
2228
2229     gtk_signal_connect(GTK_OBJECT(inst->window), "destroy",
2230                        GTK_SIGNAL_FUNC(destroy), inst);
2231     gtk_signal_connect(GTK_OBJECT(inst->window), "delete_event",
2232                        GTK_SIGNAL_FUNC(delete_window), inst);
2233     gtk_signal_connect(GTK_OBJECT(inst->window), "key_press_event",
2234                        GTK_SIGNAL_FUNC(key_event), inst);
2235     gtk_signal_connect(GTK_OBJECT(inst->window), "key_release_event",
2236                        GTK_SIGNAL_FUNC(key_event), inst);
2237     gtk_signal_connect(GTK_OBJECT(inst->window), "focus_in_event",
2238                        GTK_SIGNAL_FUNC(focus_event), inst);
2239     gtk_signal_connect(GTK_OBJECT(inst->window), "focus_out_event",
2240                        GTK_SIGNAL_FUNC(focus_event), inst);
2241     gtk_signal_connect(GTK_OBJECT(inst->area), "configure_event",
2242                        GTK_SIGNAL_FUNC(configure_area), inst);
2243     gtk_signal_connect(GTK_OBJECT(inst->area), "expose_event",
2244                        GTK_SIGNAL_FUNC(expose_area), inst);
2245     gtk_signal_connect(GTK_OBJECT(inst->area), "button_press_event",
2246                        GTK_SIGNAL_FUNC(button_event), inst);
2247     gtk_signal_connect(GTK_OBJECT(inst->area), "button_release_event",
2248                        GTK_SIGNAL_FUNC(button_event), inst);
2249     gtk_signal_connect(GTK_OBJECT(inst->area), "motion_notify_event",
2250                        GTK_SIGNAL_FUNC(motion_event), inst);
2251     gtk_signal_connect(GTK_OBJECT(inst->area), "selection_received",
2252                        GTK_SIGNAL_FUNC(selection_received), inst);
2253     gtk_signal_connect(GTK_OBJECT(inst->area), "selection_get",
2254                        GTK_SIGNAL_FUNC(selection_get), inst);
2255     gtk_signal_connect(GTK_OBJECT(inst->area), "selection_clear_event",
2256                        GTK_SIGNAL_FUNC(selection_clear), inst);
2257     if (cfg.scrollbar)
2258         gtk_signal_connect(GTK_OBJECT(inst->sbar_adjust), "value_changed",
2259                            GTK_SIGNAL_FUNC(scrollbar_moved), inst);
2260     gtk_timeout_add(20, timer_func, inst);
2261     gtk_widget_add_events(GTK_WIDGET(inst->area),
2262                           GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK |
2263                           GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK |
2264                           GDK_POINTER_MOTION_MASK | GDK_BUTTON_MOTION_MASK);
2265
2266     gtk_widget_show(inst->area);
2267     if (cfg.scrollbar)
2268         gtk_widget_show(inst->sbar);
2269     gtk_widget_show(GTK_WIDGET(inst->hbox));
2270     gtk_widget_show(inst->window);
2271
2272     set_window_background(inst);
2273
2274     inst->textcursor = make_mouse_ptr(inst, GDK_XTERM);
2275     inst->rawcursor = make_mouse_ptr(inst, GDK_LEFT_PTR);
2276     inst->blankcursor = make_mouse_ptr(inst, -1);
2277     make_mouse_ptr(inst, -2);          /* clean up cursor font */
2278     inst->currcursor = inst->textcursor;
2279     show_mouseptr(inst, 1);
2280
2281     inst->term = term_init(&cfg, inst);
2282     inst->logctx = log_init(inst);
2283     term_provide_logctx(inst->term, inst->logctx);
2284
2285     inst->back = &pty_backend;
2286     inst->back->init((void *)inst->term, &inst->backhandle, NULL, 0, NULL, 0);
2287     inst->back->provide_logctx(inst->backhandle, inst->logctx);
2288
2289     term_provide_resize_fn(inst->term, inst->back->size, inst->backhandle);
2290
2291     term_size(inst->term, cfg.height, cfg.width, cfg.savelines);
2292
2293     inst->ldisc =
2294         ldisc_create(&cfg, inst->term, inst->back, inst->backhandle, inst);
2295     ldisc_send(inst->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
2296
2297     inst->master_fd = pty_master_fd;
2298     inst->exited = FALSE;
2299     inst->master_func_id = gdk_input_add(pty_master_fd, GDK_INPUT_READ,
2300                                          pty_input_func, inst);
2301
2302     /* now we're reday to deal with the child exit handler being
2303      * called */
2304     block_signal(SIGCHLD, 0);
2305     
2306     gtk_main();
2307
2308     return 0;
2309 }