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