]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - unix/pterm.c
d4b8f4d30e707790cdc2d24931b3b558e930c53a
[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 #include <string.h>
7 #include <assert.h>
8 #include <stdlib.h>
9 #include <stdio.h>
10 #include <time.h>
11 #include <errno.h>
12 #include <fcntl.h>
13 #include <unistd.h>
14 #include <gtk/gtk.h>
15 #include <gdk/gdkkeysyms.h>
16
17 #define PUTTY_DO_GLOBALS               /* actually _define_ globals */
18 #include "putty.h"
19
20 #define CAT2(x,y) x ## y
21 #define CAT(x,y) CAT2(x,y)
22 #define ASSERT(x) enum {CAT(assertion_,__LINE__) = 1 / (x)}
23
24 #define NCOLOURS (lenof(((Config *)0)->colours))
25
26 struct gui_data {
27     GtkWidget *window, *area, *sbar;
28     GtkBox *hbox;
29     GtkAdjustment *sbar_adjust;
30     GdkPixmap *pixmap;
31     GdkFont *fonts[2];                 /* normal and bold (for now!) */
32     GdkCursor *rawcursor, *textcursor, *blankcursor, *currcursor;
33     GdkColor cols[NCOLOURS];
34     GdkColormap *colmap;
35     wchar_t *pastein_data;
36     int pastein_data_len;
37     char *pasteout_data;
38     int pasteout_data_len;
39     int font_width, font_height;
40     int ignore_sbar;
41     int mouseptr_visible;
42     guint term_paste_idle_id;
43     GdkAtom compound_text_atom;
44     char wintitle[sizeof(((Config *)0)->wintitle)];
45     char icontitle[sizeof(((Config *)0)->wintitle)];
46 };
47
48 static struct gui_data the_inst;
49 static struct gui_data *inst = &the_inst;   /* so we always write `inst->' */
50 static int send_raw_mouse;
51
52 void ldisc_update(int echo, int edit)
53 {
54     /*
55      * This is a stub in pterm. If I ever produce a Unix
56      * command-line ssh/telnet/rlogin client (i.e. a port of plink)
57      * then it will require some termios manoeuvring analogous to
58      * that in the Windows plink.c, but here it's meaningless.
59      */
60 }
61
62 int askappend(char *filename)
63 {
64     /*
65      * Logging in an xterm-alike is liable to be something you only
66      * do at serious diagnostic need. Hence, I'm going to take the
67      * easy option for now and assume we always want to overwrite
68      * log files. I can always make it properly configurable later.
69      */
70     return 2;
71 }
72
73 void logevent(char *string)
74 {
75     /*
76      * This is not a very helpful function: events are logged
77      * pretty much exclusively by the back end, and our pty back
78      * end is self-contained. So we need do nothing.
79      */
80 }
81
82 /*
83  * Translate a raw mouse button designation (LEFT, MIDDLE, RIGHT)
84  * into a cooked one (SELECT, EXTEND, PASTE).
85  * 
86  * In Unix, this is not configurable; the X button arrangement is
87  * rock-solid across all applications, everyone has a three-button
88  * mouse or a means of faking it, and there is no need to switch
89  * buttons around at all.
90  */
91 Mouse_Button translate_button(Mouse_Button button)
92 {
93     if (button == MBT_LEFT)
94         return MBT_SELECT;
95     if (button == MBT_MIDDLE)
96         return MBT_PASTE;
97     if (button == MBT_RIGHT)
98         return MBT_EXTEND;
99     return 0;                          /* shouldn't happen */
100 }
101
102 /*
103  * Minimise or restore the window in response to a server-side
104  * request.
105  */
106 void set_iconic(int iconic)
107 {
108     /*
109      * GTK 1.2 doesn't know how to do this.
110      */
111 #if GTK_CHECK_VERSION(2,0,0)
112     if (iconic)
113         gtk_window_iconify(GTK_WINDOW(inst->window));
114     else
115         gtk_window_deiconify(GTK_WINDOW(inst->window));
116 #endif
117 }
118
119 /*
120  * Move the window in response to a server-side request.
121  */
122 void move_window(int x, int y)
123 {
124     /*
125      * I assume that when the GTK version of this call is available
126      * we should use it. Not sure how it differs from the GDK one,
127      * though.
128      */
129 #if GTK_CHECK_VERSION(2,0,0)
130     gtk_window_move(GTK_WINDOW(inst->window), x, y);
131 #else
132     gdk_window_move(inst->window->window, x, y);
133 #endif
134 }
135
136 /*
137  * Move the window to the top or bottom of the z-order in response
138  * to a server-side request.
139  */
140 void set_zorder(int top)
141 {
142     if (top)
143         gdk_window_raise(inst->window->window);
144     else
145         gdk_window_lower(inst->window->window);
146 }
147
148 /*
149  * Refresh the window in response to a server-side request.
150  */
151 void refresh_window(void)
152 {
153     term_invalidate();
154 }
155
156 /*
157  * Maximise or restore the window in response to a server-side
158  * request.
159  */
160 void set_zoomed(int zoomed)
161 {
162     /*
163      * GTK 1.2 doesn't know how to do this.
164      */
165 #if GTK_CHECK_VERSION(2,0,0)
166     if (iconic)
167         gtk_window_maximize(GTK_WINDOW(inst->window));
168     else
169         gtk_window_unmaximize(GTK_WINDOW(inst->window));
170 #endif
171 }
172
173 /*
174  * Report whether the window is iconic, for terminal reports.
175  */
176 int is_iconic(void)
177 {
178     return !gdk_window_is_viewable(inst->window->window);
179 }
180
181 /*
182  * Report the window's position, for terminal reports.
183  */
184 void get_window_pos(int *x, int *y)
185 {
186     /*
187      * I assume that when the GTK version of this call is available
188      * we should use it. Not sure how it differs from the GDK one,
189      * though.
190      */
191 #if GTK_CHECK_VERSION(2,0,0)
192     gtk_window_get_position(GTK_WINDOW(inst->window), x, y);
193 #else
194     gdk_window_get_position(inst->window->window, x, y);
195 #endif
196 }
197
198 /*
199  * Report the window's pixel size, for terminal reports.
200  */
201 void get_window_pixels(int *x, int *y)
202 {
203     /*
204      * I assume that when the GTK version of this call is available
205      * we should use it. Not sure how it differs from the GDK one,
206      * though.
207      */
208 #if GTK_CHECK_VERSION(2,0,0)
209     gtk_window_get_size(GTK_WINDOW(inst->window), x, y);
210 #else
211     gdk_window_get_size(inst->window->window, x, y);
212 #endif
213 }
214
215 /*
216  * Return the window or icon title.
217  */
218 char *get_window_title(int icon)
219 {
220     return icon ? inst->wintitle : inst->icontitle;
221 }
222
223 gint delete_window(GtkWidget *widget, GdkEvent *event, gpointer data)
224 {
225     /*
226      * We could implement warn-on-close here if we really wanted
227      * to.
228      */
229     return FALSE;
230 }
231
232 void show_mouseptr(int show)
233 {
234     if (!cfg.hide_mouseptr)
235         show = 1;
236     if (show)
237         gdk_window_set_cursor(inst->area->window, inst->currcursor);
238     else
239         gdk_window_set_cursor(inst->area->window, inst->blankcursor);
240     inst->mouseptr_visible = show;
241 }
242
243 gint configure_area(GtkWidget *widget, GdkEventConfigure *event, gpointer data)
244 {
245     struct gui_data *inst = (struct gui_data *)data;
246     int w, h, need_size = 0;
247
248 printf("configure %d x %d\n", event->width, event->height);
249     w = (event->width - 2*cfg.window_border) / inst->font_width;
250     h = (event->height - 2*cfg.window_border) / inst->font_height;
251 printf("        = %d x %d\n", w, h);
252
253     if (w != cfg.width || h != cfg.height) {
254         if (inst->pixmap) {
255             gdk_pixmap_unref(inst->pixmap);
256             inst->pixmap = NULL;
257         }
258         cfg.width = w;
259         cfg.height = h;
260         need_size = 1;
261 printf("need size\n");
262     }
263     if (!inst->pixmap) {
264         GdkGC *gc;
265
266         inst->pixmap = gdk_pixmap_new(widget->window,
267                                       (cfg.width * inst->font_width +
268                                        2*cfg.window_border),
269                                       (cfg.height * inst->font_height +
270                                        2*cfg.window_border), -1);
271
272         gc = gdk_gc_new(inst->area->window);
273         gdk_gc_set_foreground(gc, &inst->cols[18]);   /* default background */
274         gdk_draw_rectangle(inst->pixmap, gc, 1, 0, 0,
275                            cfg.width * inst->font_width + 2*cfg.window_border,
276                            cfg.height * inst->font_height + 2*cfg.window_border);
277         gdk_gc_unref(gc);
278     }
279
280     if (need_size) {
281         term_size(h, w, cfg.savelines);
282     }
283
284     return TRUE;
285 }
286
287 gint expose_area(GtkWidget *widget, GdkEventExpose *event, gpointer data)
288 {
289     /* struct gui_data *inst = (struct gui_data *)data; */
290
291     /*
292      * Pass the exposed rectangle to terminal.c, which will call us
293      * back to do the actual painting.
294      */
295     if (inst->pixmap) {
296         gdk_draw_pixmap(widget->window,
297                         widget->style->fg_gc[GTK_WIDGET_STATE(widget)],
298                         inst->pixmap,
299                         event->area.x, event->area.y,
300                         event->area.x, event->area.y,
301                         event->area.width, event->area.height);
302     }
303     return TRUE;
304 }
305
306 #define KEY_PRESSED(k) \
307     (inst->keystate[(k) / 32] & (1 << ((k) % 32)))
308
309 gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data)
310 {
311     /* struct gui_data *inst = (struct gui_data *)data; */
312     char output[32];
313     int start, end;
314
315     if (event->type == GDK_KEY_PRESS) {
316 #ifdef KEY_DEBUGGING
317         {
318             int i;
319             printf("keypress: keyval = %04x, state = %08x; string =",
320                    event->keyval, event->state);
321             for (i = 0; event->string[i]; i++)
322                 printf(" %02x", (unsigned char) event->string[i]);
323             printf("\n");
324         }
325 #endif
326
327         /*
328          * NYI:
329          *  - alt+numpad
330          *  - Compose key (!!! requires Unicode faff before even trying)
331          */
332
333         /*
334          * Shift-PgUp and Shift-PgDn don't even generate keystrokes
335          * at all.
336          */
337         if (event->keyval == GDK_Page_Up && (event->state & GDK_SHIFT_MASK)) {
338             term_scroll(0, -cfg.height/2);
339             return TRUE;
340         }
341         if (event->keyval == GDK_Page_Down && (event->state & GDK_SHIFT_MASK)) {
342             term_scroll(0, +cfg.height/2);
343             return TRUE;
344         }
345
346         /*
347          * Neither does Shift-Ins.
348          */
349         if (event->keyval == GDK_Insert && (event->state & GDK_SHIFT_MASK)) {
350             request_paste();
351             return TRUE;
352         }
353
354         /* ALT+things gives leading Escape. */
355         output[0] = '\033';
356         strncpy(output+1, event->string, 31);
357         output[31] = '\0';
358         end = strlen(output);
359         if (event->state & GDK_MOD1_MASK)
360             start = 0;
361         else
362             start = 1;
363
364         /* Control-` is the same as Control-\ (unless gtk has a better idea) */
365         if (!event->string[0] && event->keyval == '`' &&
366             (event->state & GDK_CONTROL_MASK)) {
367             output[1] = '\x1C';
368             end = 2;
369         }
370
371         /* Control-Break is the same as Control-C */
372         if (event->keyval == GDK_Break &&
373             (event->state & GDK_CONTROL_MASK)) {
374             output[1] = '\003';
375             end = 2;
376         }
377
378         /* Control-2, Control-Space and Control-@ are NUL */
379         if (!event->string[0] &&
380             (event->keyval == ' ' || event->keyval == '2' ||
381              event->keyval == '@') &&
382             (event->state & (GDK_SHIFT_MASK |
383                              GDK_CONTROL_MASK)) == GDK_CONTROL_MASK) {
384             output[1] = '\0';
385             end = 2;
386         }
387
388         /* Control-Shift-Space is 160 (ISO8859 nonbreaking space) */
389         if (!event->string[0] && event->keyval == ' ' &&
390             (event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK)) ==
391             (GDK_SHIFT_MASK | GDK_CONTROL_MASK)) {
392             output[1] = '\240';
393             end = 2;
394         }
395
396         /* We don't let GTK tell us what Backspace is! We know better. */
397         if (event->keyval == GDK_BackSpace &&
398             !(event->state & GDK_SHIFT_MASK)) {
399             output[1] = cfg.bksp_is_delete ? '\x7F' : '\x08';
400             end = 2;
401         }
402
403         /* Shift-Tab is ESC [ Z */
404         if (event->keyval == GDK_ISO_Left_Tab ||
405             (event->keyval == GDK_Tab && (event->state & GDK_SHIFT_MASK))) {
406             end = 1 + sprintf(output+1, "\033[Z");
407         }
408
409         /*
410          * NetHack keypad mode.
411          */
412         if (cfg.nethack_keypad) {
413             char *keys = NULL;
414             switch (event->keyval) {
415               case GDK_KP_1: case GDK_KP_End: keys = "bB"; break;
416               case GDK_KP_2: case GDK_KP_Down: keys = "jJ"; break;
417               case GDK_KP_3: case GDK_KP_Page_Down: keys = "nN"; break;
418               case GDK_KP_4: case GDK_KP_Left: keys = "hH"; break;
419               case GDK_KP_5: case GDK_KP_Begin: keys = ".."; break;
420               case GDK_KP_6: case GDK_KP_Right: keys = "lL"; break;
421               case GDK_KP_7: case GDK_KP_Home: keys = "yY"; break;
422               case GDK_KP_8: case GDK_KP_Up: keys = "kK"; break;
423               case GDK_KP_9: case GDK_KP_Page_Up: keys = "uU"; break;
424             }
425             if (keys) {
426                 end = 2;
427                 if (event->state & GDK_SHIFT_MASK)
428                     output[1] = keys[1];
429                 else
430                     output[1] = keys[0];
431                 goto done;
432             }
433         }
434
435         /*
436          * Application keypad mode.
437          */
438         if (app_keypad_keys && !cfg.no_applic_k) {
439             int xkey = 0;
440             switch (event->keyval) {
441               case GDK_Num_Lock: xkey = 'P'; break;
442               case GDK_KP_Divide: xkey = 'Q'; break;
443               case GDK_KP_Multiply: xkey = 'R'; break;
444               case GDK_KP_Subtract: xkey = 'S'; break;
445                 /*
446                  * Keypad + is tricky. It covers a space that would
447                  * be taken up on the VT100 by _two_ keys; so we
448                  * let Shift select between the two. Worse still,
449                  * in xterm function key mode we change which two...
450                  */
451               case GDK_KP_Add:
452                 if (cfg.funky_type == 2) {
453                     if (event->state & GDK_SHIFT_MASK)
454                         xkey = 'l';
455                     else
456                         xkey = 'k';
457                 } else if (event->state & GDK_SHIFT_MASK)
458                         xkey = 'm';
459                 else
460                     xkey = 'l';
461                 break;
462               case GDK_KP_Enter: xkey = 'M'; break;
463               case GDK_KP_0: case GDK_KP_Insert: xkey = 'p'; break;
464               case GDK_KP_1: case GDK_KP_End: xkey = 'q'; break;
465               case GDK_KP_2: case GDK_KP_Down: xkey = 'r'; break;
466               case GDK_KP_3: case GDK_KP_Page_Down: xkey = 's'; break;
467               case GDK_KP_4: case GDK_KP_Left: xkey = 't'; break;
468               case GDK_KP_5: case GDK_KP_Begin: xkey = 'u'; break;
469               case GDK_KP_6: case GDK_KP_Right: xkey = 'v'; break;
470               case GDK_KP_7: case GDK_KP_Home: xkey = 'w'; break;
471               case GDK_KP_8: case GDK_KP_Up: xkey = 'x'; break;
472               case GDK_KP_9: case GDK_KP_Page_Up: xkey = 'y'; break;
473               case GDK_KP_Decimal: case GDK_KP_Delete: xkey = 'n'; break;
474             }
475             if (xkey) {
476                 if (vt52_mode) {
477                     if (xkey >= 'P' && xkey <= 'S')
478                         end = 1 + sprintf(output+1, "\033%c", xkey);
479                     else
480                         end = 1 + sprintf(output+1, "\033?%c", xkey);
481                 } else
482                     end = 1 + sprintf(output+1, "\033O%c", xkey);
483                 goto done;
484             }
485         }
486
487         /*
488          * Next, all the keys that do tilde codes. (ESC '[' nn '~',
489          * for integer decimal nn.)
490          *
491          * We also deal with the weird ones here. Linux VCs replace F1
492          * to F5 by ESC [ [ A to ESC [ [ E. rxvt doesn't do _that_, but
493          * does replace Home and End (1~ and 4~) by ESC [ H and ESC O w
494          * respectively.
495          */
496         {
497             int code = 0;
498             switch (event->keyval) {
499               case GDK_F1:
500                 code = (event->state & GDK_SHIFT_MASK ? 23 : 11);
501                 break;
502               case GDK_F2:
503                 code = (event->state & GDK_SHIFT_MASK ? 24 : 12);
504                 break;
505               case GDK_F3:
506                 code = (event->state & GDK_SHIFT_MASK ? 25 : 13);
507                 break;
508               case GDK_F4:
509                 code = (event->state & GDK_SHIFT_MASK ? 26 : 14);
510                 break;
511               case GDK_F5:
512                 code = (event->state & GDK_SHIFT_MASK ? 28 : 15);
513                 break;
514               case GDK_F6:
515                 code = (event->state & GDK_SHIFT_MASK ? 29 : 17);
516                 break;
517               case GDK_F7:
518                 code = (event->state & GDK_SHIFT_MASK ? 31 : 18);
519                 break;
520               case GDK_F8:
521                 code = (event->state & GDK_SHIFT_MASK ? 32 : 19);
522                 break;
523               case GDK_F9:
524                 code = (event->state & GDK_SHIFT_MASK ? 33 : 20);
525                 break;
526               case GDK_F10:
527                 code = (event->state & GDK_SHIFT_MASK ? 34 : 21);
528                 break;
529               case GDK_F11:
530                 code = 23;
531                 break;
532               case GDK_F12:
533                 code = 24;
534                 break;
535               case GDK_F13:
536                 code = 25;
537                 break;
538               case GDK_F14:
539                 code = 26;
540                 break;
541               case GDK_F15:
542                 code = 28;
543                 break;
544               case GDK_F16:
545                 code = 29;
546                 break;
547               case GDK_F17:
548                 code = 31;
549                 break;
550               case GDK_F18:
551                 code = 32;
552                 break;
553               case GDK_F19:
554                 code = 33;
555                 break;
556               case GDK_F20:
557                 code = 34;
558                 break;
559             }
560             if (!(event->state & GDK_CONTROL_MASK)) switch (event->keyval) {
561               case GDK_Home: case GDK_KP_Home:
562                 code = 1;
563                 break;
564               case GDK_Insert: case GDK_KP_Insert:
565                 code = 2;
566                 break;
567               case GDK_Delete: case GDK_KP_Delete:
568                 code = 3;
569                 break;
570               case GDK_End: case GDK_KP_End:
571                 code = 4;
572                 break;
573               case GDK_Page_Up: case GDK_KP_Page_Up:
574                 code = 5;
575                 break;
576               case GDK_Page_Down: case GDK_KP_Page_Down:
577                 code = 6;
578                 break;
579             }
580             /* Reorder edit keys to physical order */
581             if (cfg.funky_type == 3 && code <= 6)
582                 code = "\0\2\1\4\5\3\6"[code];
583
584             if (vt52_mode && code > 0 && code <= 6) {
585                 end = 1 + sprintf(output+1, "\x1B%c", " HLMEIG"[code]);
586                 goto done;
587             }
588
589             if (cfg.funky_type == 5 &&     /* SCO function keys */
590                 code >= 11 && code <= 34) {
591                 char codes[] = "MNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@[\\]^_`{";
592                 int index = 0;
593                 switch (event->keyval) {
594                   case GDK_F1: index = 0; break;
595                   case GDK_F2: index = 1; break;
596                   case GDK_F3: index = 2; break;
597                   case GDK_F4: index = 3; break;
598                   case GDK_F5: index = 4; break;
599                   case GDK_F6: index = 5; break;
600                   case GDK_F7: index = 6; break;
601                   case GDK_F8: index = 7; break;
602                   case GDK_F9: index = 8; break;
603                   case GDK_F10: index = 9; break;
604                   case GDK_F11: index = 10; break;
605                   case GDK_F12: index = 11; break;
606                 }
607                 if (event->state & GDK_SHIFT_MASK) index += 12;
608                 if (event->state & GDK_CONTROL_MASK) index += 24;
609                 end = 1 + sprintf(output+1, "\x1B[%c", codes[index]);
610                 goto done;
611             }
612             if (cfg.funky_type == 5 &&     /* SCO small keypad */
613                 code >= 1 && code <= 6) {
614                 char codes[] = "HL.FIG";
615                 if (code == 3) {
616                     output[1] = '\x7F';
617                     end = 2;
618                 } else {
619                     end = 1 + sprintf(output+1, "\x1B[%c", codes[code-1]);
620                 }
621                 goto done;
622             }
623             if ((vt52_mode || cfg.funky_type == 4) && code >= 11 && code <= 24) {
624                 int offt = 0;
625                 if (code > 15)
626                     offt++;
627                 if (code > 21)
628                     offt++;
629                 if (vt52_mode)
630                     end = 1 + sprintf(output+1,
631                                       "\x1B%c", code + 'P' - 11 - offt);
632                 else
633                     end = 1 + sprintf(output+1,
634                                       "\x1BO%c", code + 'P' - 11 - offt);
635                 goto done;
636             }
637             if (cfg.funky_type == 1 && code >= 11 && code <= 15) {
638                 end = 1 + sprintf(output+1, "\x1B[[%c", code + 'A' - 11);
639                 goto done;
640             }
641             if (cfg.funky_type == 2 && code >= 11 && code <= 14) {
642                 if (vt52_mode)
643                     end = 1 + sprintf(output+1, "\x1B%c", code + 'P' - 11);
644                 else
645                     end = 1 + sprintf(output+1, "\x1BO%c", code + 'P' - 11);
646                 goto done;
647             }
648             if (cfg.rxvt_homeend && (code == 1 || code == 4)) {
649                 end = 1 + sprintf(output+1, code == 1 ? "\x1B[H" : "\x1BOw");
650                 goto done;
651             }
652             if (code) {
653                 end = 1 + sprintf(output+1, "\x1B[%d~", code);
654                 goto done;
655             }
656         }
657
658         /*
659          * Cursor keys. (This includes the numberpad cursor keys,
660          * if we haven't already done them due to app keypad mode.)
661          * 
662          * Here we also process un-numlocked un-appkeypadded KP5,
663          * which sends ESC [ G.
664          */
665         {
666             int xkey = 0;
667             switch (event->keyval) {
668               case GDK_Up: case GDK_KP_Up: xkey = 'A'; break;
669               case GDK_Down: case GDK_KP_Down: xkey = 'B'; break;
670               case GDK_Right: case GDK_KP_Right: xkey = 'C'; break;
671               case GDK_Left: case GDK_KP_Left: xkey = 'D'; break;
672               case GDK_Begin: case GDK_KP_Begin: xkey = 'G'; break;
673             }
674             if (xkey) {
675                 /*
676                  * The arrow keys normally do ESC [ A and so on. In
677                  * app cursor keys mode they do ESC O A instead.
678                  * Ctrl toggles the two modes.
679                  */
680                 if (vt52_mode) {
681                     end = 1 + sprintf(output+1, "\033%c", xkey);
682                 } else if (!app_cursor_keys ^
683                            !(event->state & GDK_CONTROL_MASK)) {
684                     end = 1 + sprintf(output+1, "\033O%c", xkey);
685                 } else {                    
686                     end = 1 + sprintf(output+1, "\033[%c", xkey);
687                 }
688                 goto done;
689             }
690         }
691
692         done:
693
694 #ifdef KEY_DEBUGGING
695         {
696             int i;
697             printf("generating sequence:");
698             for (i = start; i < end; i++)
699                 printf(" %02x", (unsigned char) output[i]);
700             printf("\n");
701         }
702 #endif
703         if (end-start > 0) {
704             ldisc_send(output+start, end-start, 1);
705             show_mouseptr(0);
706             term_out();
707         }
708     }
709
710     return TRUE;
711 }
712
713 gint button_event(GtkWidget *widget, GdkEventButton *event, gpointer data)
714 {
715     struct gui_data *inst = (struct gui_data *)data;
716     int shift, ctrl, alt, x, y, button, act;
717
718     show_mouseptr(1);
719
720     shift = event->state & GDK_SHIFT_MASK;
721     ctrl = event->state & GDK_CONTROL_MASK;
722     alt = event->state & GDK_MOD1_MASK;
723     if (event->button == 1)
724         button = MBT_LEFT;
725     else if (event->button == 2)
726         button = MBT_MIDDLE;
727     else if (event->button == 3)
728         button = MBT_RIGHT;
729     else
730         return FALSE;                  /* don't even know what button! */
731
732     switch (event->type) {
733       case GDK_BUTTON_PRESS: act = MA_CLICK; break;
734       case GDK_BUTTON_RELEASE: act = MA_RELEASE; break;
735       case GDK_2BUTTON_PRESS: act = MA_2CLK; break;
736       case GDK_3BUTTON_PRESS: act = MA_3CLK; break;
737       default: return FALSE;           /* don't know this event type */
738     }
739
740     if (send_raw_mouse && !(cfg.mouse_override && shift) &&
741         act != MA_CLICK && act != MA_RELEASE)
742         return TRUE;                   /* we ignore these in raw mouse mode */
743
744     x = (event->x - cfg.window_border) / inst->font_width;
745     y = (event->y - cfg.window_border) / inst->font_height;
746
747     term_mouse(button, act, x, y, shift, ctrl, alt);
748
749     return TRUE;
750 }
751
752 gint motion_event(GtkWidget *widget, GdkEventMotion *event, gpointer data)
753 {
754     struct gui_data *inst = (struct gui_data *)data;
755     int shift, ctrl, alt, x, y, button;
756
757     show_mouseptr(1);
758
759     shift = event->state & GDK_SHIFT_MASK;
760     ctrl = event->state & GDK_CONTROL_MASK;
761     alt = event->state & GDK_MOD1_MASK;
762     if (event->state & GDK_BUTTON1_MASK)
763         button = MBT_LEFT;
764     else if (event->state & GDK_BUTTON2_MASK)
765         button = MBT_MIDDLE;
766     else if (event->state & GDK_BUTTON3_MASK)
767         button = MBT_RIGHT;
768     else
769         return FALSE;                  /* don't even know what button! */
770
771     x = (event->x - cfg.window_border) / inst->font_width;
772     y = (event->y - cfg.window_border) / inst->font_height;
773
774     term_mouse(button, MA_DRAG, x, y, shift, ctrl, alt);
775
776     return TRUE;
777 }
778
779 gint timer_func(gpointer data)
780 {
781     /* struct gui_data *inst = (struct gui_data *)data; */
782     extern int pty_child_is_dead();  /* declared in pty.c */
783
784     if (pty_child_is_dead()) {
785         /*
786          * The primary child process died. We could keep the
787          * terminal open for remaining subprocesses to output to,
788          * but conventional wisdom seems to feel that that's the
789          * Wrong Thing for an xterm-alike, so we bail out now. This
790          * would be easy enough to change or make configurable if
791          * necessary.
792          */
793         exit(0);
794     }
795
796     term_update();
797     return TRUE;
798 }
799
800 void pty_input_func(gpointer data, gint sourcefd, GdkInputCondition condition)
801 {
802     /* struct gui_data *inst = (struct gui_data *)data; */
803     char buf[4096];
804     int ret;
805
806     ret = read(sourcefd, buf, sizeof(buf));
807
808     /*
809      * Clean termination condition is that either ret == 0, or ret
810      * < 0 and errno == EIO. Not sure why the latter, but it seems
811      * to happen. Boo.
812      */
813     if (ret == 0 || (ret < 0 && errno == EIO)) {
814         exit(0);
815     }
816
817     if (ret < 0) {
818         perror("read pty master");
819         exit(1);
820     }
821     if (ret > 0)
822         from_backend(0, buf, ret);
823     term_out();
824 }
825
826 void destroy(GtkWidget *widget, gpointer data)
827 {
828     gtk_main_quit();
829 }
830
831 gint focus_event(GtkWidget *widget, GdkEventFocus *event, gpointer data)
832 {
833     has_focus = event->in;
834     term_out();
835     term_update();
836     show_mouseptr(1);
837     return FALSE;
838 }
839
840 /*
841  * set or clear the "raw mouse message" mode
842  */
843 void set_raw_mouse_mode(int activate)
844 {
845     activate = activate && !cfg.no_mouse_rep;
846     send_raw_mouse = activate;
847     if (send_raw_mouse)
848         inst->currcursor = inst->rawcursor;
849     else
850         inst->currcursor = inst->textcursor;
851     show_mouseptr(inst->mouseptr_visible);
852 }
853
854 void request_resize(int w, int h)
855 {
856     gtk_drawing_area_size(GTK_DRAWING_AREA(inst->area),
857                           inst->font_width * w + 2*cfg.window_border,
858                           inst->font_height * h + 2*cfg.window_border);
859 }
860
861 void real_palette_set(int n, int r, int g, int b)
862 {
863     gboolean success[1];
864
865     inst->cols[n].red = r * 0x0101;
866     inst->cols[n].green = g * 0x0101;
867     inst->cols[n].blue = b * 0x0101;
868
869     gdk_colormap_alloc_colors(inst->colmap, inst->cols + n, 1,
870                               FALSE, FALSE, success);
871     if (!success[0])
872         g_error("pterm: couldn't allocate colour %d (#%02x%02x%02x)\n",
873                 n, r, g, b);
874 }
875
876 void palette_set(int n, int r, int g, int b)
877 {
878     static const int first[21] = {
879         0, 2, 4, 6, 8, 10, 12, 14,
880         1, 3, 5, 7, 9, 11, 13, 15,
881         16, 17, 18, 20, 22
882     };
883     real_palette_set(first[n], r, g, b);
884     if (first[n] >= 18)
885         real_palette_set(first[n] + 1, r, g, b);
886 }
887
888 void palette_reset(void)
889 {
890     /* This maps colour indices in cfg to those used in inst->cols. */
891     static const int ww[] = {
892         6, 7, 8, 9, 10, 11, 12, 13,
893         14, 15, 16, 17, 18, 19, 20, 21,
894         0, 1, 2, 3, 4, 5
895     };
896     gboolean success[NCOLOURS];
897     int i;
898
899     assert(lenof(ww) == NCOLOURS);
900
901     if (!inst->colmap) {
902         inst->colmap = gdk_colormap_get_system();
903     } else {
904         gdk_colormap_free_colors(inst->colmap, inst->cols, NCOLOURS);
905     }
906
907     for (i = 0; i < NCOLOURS; i++) {
908         inst->cols[i].red = cfg.colours[ww[i]][0] * 0x0101;
909         inst->cols[i].green = cfg.colours[ww[i]][1] * 0x0101;
910         inst->cols[i].blue = cfg.colours[ww[i]][2] * 0x0101;
911     }
912
913     gdk_colormap_alloc_colors(inst->colmap, inst->cols, NCOLOURS,
914                               FALSE, FALSE, success);
915     for (i = 0; i < NCOLOURS; i++) {
916         if (!success[i])
917             g_error("pterm: couldn't allocate colour %d (#%02x%02x%02x)\n",
918                     i, cfg.colours[i][0], cfg.colours[i][1], cfg.colours[i][2]);
919     }
920 }
921
922 void write_clip(wchar_t * data, int len, int must_deselect)
923 {
924     if (inst->pasteout_data)
925         sfree(inst->pasteout_data);
926     inst->pasteout_data = smalloc(len);
927     inst->pasteout_data_len = len;
928     wc_to_mb(0, 0, data, len, inst->pasteout_data, inst->pasteout_data_len,
929              NULL, NULL);
930
931     if (gtk_selection_owner_set(inst->area, GDK_SELECTION_PRIMARY,
932                                 GDK_CURRENT_TIME)) {
933         gtk_selection_add_target(inst->area, GDK_SELECTION_PRIMARY,
934                                  GDK_SELECTION_TYPE_STRING, 1);
935         gtk_selection_add_target(inst->area, GDK_SELECTION_PRIMARY,
936                                  inst->compound_text_atom, 1);
937     }
938 }
939
940 void selection_get(GtkWidget *widget, GtkSelectionData *seldata,
941                    guint info, guint time_stamp, gpointer data)
942 {
943     gtk_selection_data_set(seldata, GDK_SELECTION_TYPE_STRING, 8,
944                            inst->pasteout_data, inst->pasteout_data_len);
945 }
946
947 gint selection_clear(GtkWidget *widget, GdkEventSelection *seldata,
948                      gpointer data)
949 {
950     term_deselect();
951     if (inst->pasteout_data)
952         sfree(inst->pasteout_data);
953     inst->pasteout_data = NULL;
954     inst->pasteout_data_len = 0;
955     return TRUE;
956 }
957
958 void request_paste(void)
959 {
960     /*
961      * In Unix, pasting is asynchronous: all we can do at the
962      * moment is to call gtk_selection_convert(), and when the data
963      * comes back _then_ we can call term_do_paste().
964      */
965     gtk_selection_convert(inst->area, GDK_SELECTION_PRIMARY,
966                           GDK_SELECTION_TYPE_STRING, GDK_CURRENT_TIME);
967 }
968
969 gint idle_paste_func(gpointer data);   /* forward ref */
970
971 void selection_received(GtkWidget *widget, GtkSelectionData *seldata,
972                         gpointer data)
973 {
974     if (seldata->length <= 0 ||
975         seldata->type != GDK_SELECTION_TYPE_STRING)
976         return;                        /* Nothing happens. */
977
978     if (inst->pastein_data)
979         sfree(inst->pastein_data);
980
981     inst->pastein_data = smalloc(seldata->length * sizeof(wchar_t));
982     inst->pastein_data_len = seldata->length;
983     mb_to_wc(0, 0, seldata->data, seldata->length,
984              inst->pastein_data, inst->pastein_data_len);
985
986     term_do_paste();
987
988     if (term_paste_pending())
989         inst->term_paste_idle_id = gtk_idle_add(idle_paste_func, inst);
990 }
991
992 gint idle_paste_func(gpointer data)
993 {
994     struct gui_data *inst = (struct gui_data *)data;
995
996     if (term_paste_pending())
997         term_paste();
998     else
999         gtk_idle_remove(inst->term_paste_idle_id);
1000
1001     return TRUE;
1002 }
1003
1004
1005 void get_clip(wchar_t ** p, int *len)
1006 {
1007     if (p) {
1008         *p = inst->pastein_data;
1009         *len = inst->pastein_data_len;
1010     }
1011 }
1012
1013 void set_title(char *title)
1014 {
1015     strncpy(inst->wintitle, title, lenof(inst->wintitle));
1016     inst->wintitle[lenof(inst->wintitle)-1] = '\0';
1017     gtk_window_set_title(GTK_WINDOW(inst->window), inst->wintitle);
1018 }
1019
1020 void set_icon(char *title)
1021 {
1022     strncpy(inst->icontitle, title, lenof(inst->icontitle));
1023     inst->icontitle[lenof(inst->icontitle)-1] = '\0';
1024     gdk_window_set_icon_name(inst->window->window, inst->icontitle);
1025 }
1026
1027 void set_sbar(int total, int start, int page)
1028 {
1029     if (!cfg.scrollbar)
1030         return;
1031     inst->sbar_adjust->lower = 0;
1032     inst->sbar_adjust->upper = total;
1033     inst->sbar_adjust->value = start;
1034     inst->sbar_adjust->page_size = page;
1035     inst->sbar_adjust->step_increment = 1;
1036     inst->sbar_adjust->page_increment = page/2;
1037     inst->ignore_sbar = TRUE;
1038     gtk_adjustment_changed(inst->sbar_adjust);
1039     inst->ignore_sbar = FALSE;
1040 }
1041
1042 void scrollbar_moved(GtkAdjustment *adj, gpointer data)
1043 {
1044     if (!cfg.scrollbar)
1045         return;
1046     if (!inst->ignore_sbar)
1047         term_scroll(1, (int)adj->value);
1048 }
1049
1050 void sys_cursor(int x, int y)
1051 {
1052     /*
1053      * This is meaningless under X.
1054      */
1055 }
1056
1057 void beep(int mode)
1058 {
1059     gdk_beep();
1060 }
1061
1062 int CharWidth(Context ctx, int uc)
1063 {
1064     /*
1065      * Under X, any fixed-width font really _is_ fixed-width.
1066      * Double-width characters will be dealt with using a separate
1067      * font. For the moment we can simply return 1.
1068      */
1069     return 1;
1070 }
1071
1072 Context get_ctx(void)
1073 {
1074     GdkGC *gc;
1075     if (!inst->area->window)
1076         return NULL;
1077     gc = gdk_gc_new(inst->area->window);
1078     return gc;
1079 }
1080
1081 void free_ctx(Context ctx)
1082 {
1083     GdkGC *gc = (GdkGC *)ctx;
1084     gdk_gc_unref(gc);
1085 }
1086
1087 /*
1088  * Draw a line of text in the window, at given character
1089  * coordinates, in given attributes.
1090  *
1091  * We are allowed to fiddle with the contents of `text'.
1092  */
1093 void do_text(Context ctx, int x, int y, char *text, int len,
1094              unsigned long attr, int lattr)
1095 {
1096     int nfg, nbg, t;
1097     GdkGC *gc = (GdkGC *)ctx;
1098
1099     /*
1100      * NYI:
1101      *  - Unicode, code pages, and ATTR_WIDE for CJK support.
1102      *  - cursor shapes other than block
1103      *  - shadow bolding
1104      */
1105
1106     nfg = 2 * ((attr & ATTR_FGMASK) >> ATTR_FGSHIFT);
1107     nbg = 2 * ((attr & ATTR_BGMASK) >> ATTR_BGSHIFT);
1108     if (attr & ATTR_REVERSE) {
1109         t = nfg;
1110         nfg = nbg;
1111         nbg = t;
1112     }
1113     if (cfg.bold_colour && (attr & ATTR_BOLD))
1114         nfg++;
1115     if (cfg.bold_colour && (attr & ATTR_BLINK))
1116         nbg++;
1117     if (attr & TATTR_ACTCURS) {
1118         nfg = NCOLOURS-2;
1119         nbg = NCOLOURS-1;
1120     }
1121
1122     if (lattr != LATTR_NORM) {
1123         x *= 2;
1124         if (x >= cols)
1125             return;
1126         if (x + len*2 > cols)
1127             len = (cols-x)/2;          /* trim to LH half */
1128     }
1129
1130     gdk_gc_set_foreground(gc, &inst->cols[nbg]);
1131     gdk_draw_rectangle(inst->pixmap, gc, 1,
1132                        x*inst->font_width+cfg.window_border,
1133                        y*inst->font_height+cfg.window_border,
1134                        len*inst->font_width, inst->font_height);
1135
1136     gdk_gc_set_foreground(gc, &inst->cols[nfg]);
1137     gdk_draw_text(inst->pixmap, inst->fonts[0], gc,
1138                   x*inst->font_width+cfg.window_border,
1139                   y*inst->font_height+cfg.window_border+inst->fonts[0]->ascent,
1140                   text, len);
1141
1142     if (attr & ATTR_UNDER) {
1143         int uheight = inst->fonts[0]->ascent + 1;
1144         if (uheight >= inst->font_height)
1145             uheight = inst->font_height - 1;
1146         gdk_draw_line(inst->pixmap, gc, x*inst->font_width+cfg.window_border,
1147                       y*inst->font_height + uheight + cfg.window_border,
1148                       (x+len)*inst->font_width-1+cfg.window_border,
1149                       y*inst->font_height + uheight + cfg.window_border);
1150     }
1151
1152     if (lattr != LATTR_NORM) {
1153         /*
1154          * I can't find any plausible StretchBlt equivalent in the
1155          * X server, so I'm going to do this the slow and painful
1156          * way. This will involve repeated calls to
1157          * gdk_draw_pixmap() to stretch the text horizontally. It's
1158          * O(N^2) in time and O(N) in network bandwidth, but you
1159          * try thinking of a better way. :-(
1160          */
1161         int i;
1162         for (i = 0; i < len * inst->font_width; i++) {
1163             gdk_draw_pixmap(inst->pixmap, gc, inst->pixmap,
1164                             x*inst->font_width+cfg.window_border + 2*i,
1165                             y*inst->font_height+cfg.window_border,
1166                             x*inst->font_width+cfg.window_border + 2*i+1,
1167                             y*inst->font_height+cfg.window_border,
1168                             len * inst->font_width - i, inst->font_height);
1169         }
1170         len *= 2;
1171         if (lattr != LATTR_WIDE) {
1172             int dt, db;
1173             /* Now stretch vertically, in the same way. */
1174             if (lattr == LATTR_BOT)
1175                 dt = 0, db = 1;
1176             else
1177                 dt = 1, db = 0;
1178             for (i = 0; i < inst->font_height; i+=2) {
1179                 gdk_draw_pixmap(inst->pixmap, gc, inst->pixmap,
1180                                 x*inst->font_width+cfg.window_border,
1181                                 y*inst->font_height+cfg.window_border+dt*i+db,
1182                                 x*inst->font_width+cfg.window_border,
1183                                 y*inst->font_height+cfg.window_border+dt*(i+1),
1184                                 len * inst->font_width, inst->font_height-i-1);
1185             }
1186         }
1187         len *= 2;
1188     }
1189
1190     gdk_draw_pixmap(inst->area->window, gc, inst->pixmap,
1191                     x*inst->font_width+cfg.window_border,
1192                     y*inst->font_height+cfg.window_border,
1193                     x*inst->font_width+cfg.window_border,
1194                     y*inst->font_height+cfg.window_border,
1195                     len*inst->font_width, inst->font_height);
1196 }
1197
1198 void do_cursor(Context ctx, int x, int y, char *text, int len,
1199                unsigned long attr, int lattr)
1200 {
1201     int passive;
1202     GdkGC *gc = (GdkGC *)ctx;
1203
1204     /*
1205      * NYI: cursor shapes other than block
1206      */
1207     if (attr & TATTR_PASCURS) {
1208         attr &= ~TATTR_PASCURS;
1209         passive = 1;
1210     } else
1211         passive = 0;
1212     do_text(ctx, x, y, text, len, attr, lattr);
1213     if (passive) {
1214         gdk_gc_set_foreground(gc, &inst->cols[NCOLOURS-1]);
1215         gdk_draw_rectangle(inst->pixmap, gc, 0,
1216                            x*inst->font_width+cfg.window_border,
1217                            y*inst->font_height+cfg.window_border,
1218                            len*inst->font_width-1, inst->font_height-1);
1219         gdk_draw_pixmap(inst->area->window, gc, inst->pixmap,
1220                         x*inst->font_width+cfg.window_border,
1221                         y*inst->font_height+cfg.window_border,
1222                         x*inst->font_width+cfg.window_border,
1223                         y*inst->font_height+cfg.window_border,
1224                         len*inst->font_width, inst->font_height);
1225     }
1226 }
1227
1228 GdkCursor *make_mouse_ptr(int cursor_val)
1229 {
1230     /*
1231      * Truly hideous hack: GTK doesn't allow us to set the mouse
1232      * cursor foreground and background colours unless we've _also_
1233      * created our own cursor from bitmaps. Therefore, I need to
1234      * load the `cursor' font and draw glyphs from it on to
1235      * pixmaps, in order to construct my cursors with the fg and bg
1236      * I want. This is a gross hack, but it's more self-contained
1237      * than linking in Xlib to find the X window handle to
1238      * inst->area and calling XRecolorCursor, and it's more
1239      * futureproof than hard-coding the shapes as bitmap arrays.
1240      */
1241     static GdkFont *cursor_font = NULL;
1242     GdkPixmap *source, *mask;
1243     GdkGC *gc;
1244     GdkColor cfg = { 0, 65535, 65535, 65535 };
1245     GdkColor cbg = { 0, 0, 0, 0 };
1246     GdkColor dfg = { 1, 65535, 65535, 65535 };
1247     GdkColor dbg = { 0, 0, 0, 0 };
1248     GdkCursor *ret;
1249     gchar text[2];
1250     gint lb, rb, wid, asc, desc, w, h, x, y;
1251
1252     if (cursor_val == -2) {
1253         gdk_font_unref(cursor_font);
1254         return NULL;
1255     }
1256
1257     if (cursor_val >= 0 && !cursor_font)
1258         cursor_font = gdk_font_load("cursor");
1259
1260     /*
1261      * Get the text extent of the cursor in question. We use the
1262      * mask character for this, because it's typically slightly
1263      * bigger than the main character.
1264      */
1265     if (cursor_val >= 0) {
1266         text[1] = '\0';
1267         text[0] = (char)cursor_val + 1;
1268         gdk_string_extents(cursor_font, text, &lb, &rb, &wid, &asc, &desc);
1269         w = rb-lb; h = asc+desc; x = -lb; y = asc;
1270     } else {
1271         w = h = 1;
1272         x = y = 0;
1273     }
1274
1275     source = gdk_pixmap_new(NULL, w, h, 1);
1276     mask = gdk_pixmap_new(NULL, w, h, 1);
1277
1278     /*
1279      * Draw the mask character on the mask pixmap.
1280      */
1281     gc = gdk_gc_new(mask);
1282     gdk_gc_set_foreground(gc, &dbg);
1283     gdk_draw_rectangle(mask, gc, 1, 0, 0, w, h);
1284     if (cursor_val >= 0) {
1285         text[1] = '\0';
1286         text[0] = (char)cursor_val + 1;
1287         gdk_gc_set_foreground(gc, &dfg);
1288         gdk_draw_text(mask, cursor_font, gc, x, y, text, 1);
1289     }
1290     gdk_gc_unref(gc);
1291
1292     /*
1293      * Draw the main character on the source pixmap.
1294      */
1295     gc = gdk_gc_new(source);
1296     gdk_gc_set_foreground(gc, &dbg);
1297     gdk_draw_rectangle(source, gc, 1, 0, 0, w, h);
1298     if (cursor_val >= 0) {
1299         text[1] = '\0';
1300         text[0] = (char)cursor_val;
1301         gdk_gc_set_foreground(gc, &dfg);
1302         gdk_draw_text(source, cursor_font, gc, x, y, text, 1);
1303     }
1304     gdk_gc_unref(gc);
1305
1306     /*
1307      * Create the cursor.
1308      */
1309     ret = gdk_cursor_new_from_pixmap(source, mask, &cfg, &cbg, x, y);
1310
1311     /*
1312      * Clean up.
1313      */
1314     gdk_pixmap_unref(source);
1315     gdk_pixmap_unref(mask);
1316
1317     return ret;
1318 }
1319
1320 void modalfatalbox(char *p, ...)
1321 {
1322     va_list ap;
1323     fprintf(stderr, "FATAL ERROR: ");
1324     va_start(ap, p);
1325     vfprintf(stderr, p, ap);
1326     va_end(ap);
1327     fputc('\n', stderr);
1328     exit(1);
1329 }
1330
1331 char *get_x_display(void)
1332 {
1333     return gdk_get_display();
1334 }
1335
1336 int main(int argc, char **argv)
1337 {
1338     extern int pty_master_fd;          /* declared in pty.c */
1339     extern char **pty_argv;            /* declared in pty.c */
1340     int err = 0;
1341
1342     gtk_init(&argc, &argv);
1343
1344     do_defaults(NULL, &cfg);
1345
1346     while (--argc > 0) {
1347         char *p = *++argv;
1348         if (!strcmp(p, "-fn")) {
1349             if (--argc > 0) {
1350                 strncpy(cfg.font, *++argv, sizeof(cfg.font));
1351                 cfg.font[sizeof(cfg.font)-1] = '\0';
1352             } else
1353                 err = 1, fprintf(stderr, "pterm: -fn expects an argument\n");
1354         }
1355         if (!strcmp(p, "-e")) {
1356             if (--argc > 0) {
1357                 int i;
1358                 pty_argv = smalloc((argc+1) * sizeof(char *));
1359                 ++argv;
1360                 for (i = 0; i < argc; i++)
1361                     pty_argv[i] = argv[i];
1362                 pty_argv[argc] = NULL;
1363                 break;                 /* finished command-line processing */
1364             } else
1365                 err = 1, fprintf(stderr, "pterm: -e expects an argument\n");
1366         }
1367         if (!strcmp(p, "-T")) {
1368             if (--argc > 0) {
1369                 strncpy(cfg.wintitle, *++argv, sizeof(cfg.wintitle));
1370                 cfg.wintitle[sizeof(cfg.wintitle)-1] = '\0';
1371             } else
1372                 err = 1, fprintf(stderr, "pterm: -T expects an argument\n");
1373         }
1374         if (!strcmp(p, "-log")) {
1375             if (--argc > 0) {
1376                 strncpy(cfg.logfilename, *++argv, sizeof(cfg.logfilename));
1377                 cfg.logfilename[sizeof(cfg.logfilename)-1] = '\0';
1378                 cfg.logtype = LGTYP_DEBUG;
1379             } else
1380                 err = 1, fprintf(stderr, "pterm: -log expects an argument\n");
1381         }
1382         if (!strcmp(p, "-hide")) {
1383             cfg.hide_mouseptr = 1;
1384         }
1385         if (!strcmp(p, "-ut-")) {
1386             cfg.stamp_utmp = 0;
1387         }
1388         if (!strcmp(p, "-ls-")) {
1389             cfg.login_shell = 0;
1390         }
1391         if (!strcmp(p, "-nethack")) {
1392             cfg.nethack_keypad = 1;
1393         }
1394         if (!strcmp(p, "-sb-")) {
1395             cfg.scrollbar = 0;
1396         }
1397     }
1398
1399     inst->fonts[0] = gdk_font_load(cfg.font);
1400     inst->fonts[1] = NULL;             /* FIXME: what about bold font? */
1401     inst->font_width = gdk_char_width(inst->fonts[0], ' ');
1402     inst->font_height = inst->fonts[0]->ascent + inst->fonts[0]->descent;
1403
1404     inst->compound_text_atom = gdk_atom_intern("COMPOUND_TEXT", FALSE);
1405
1406     init_ucs();
1407
1408     inst->window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1409
1410     if (cfg.wintitle[0])
1411         set_title(cfg.wintitle);
1412     else
1413         set_title("pterm");
1414
1415     /*
1416      * Set up the colour map.
1417      */
1418     palette_reset();
1419
1420     inst->area = gtk_drawing_area_new();
1421     gtk_drawing_area_size(GTK_DRAWING_AREA(inst->area),
1422                           inst->font_width * cfg.width + 2*cfg.window_border,
1423                           inst->font_height * cfg.height + 2*cfg.window_border);
1424     if (cfg.scrollbar) {
1425         inst->sbar_adjust = GTK_ADJUSTMENT(gtk_adjustment_new(0,0,0,0,0,0));
1426         inst->sbar = gtk_vscrollbar_new(inst->sbar_adjust);
1427     }
1428     inst->hbox = GTK_BOX(gtk_hbox_new(FALSE, 0));
1429     gtk_box_pack_start(inst->hbox, inst->area, TRUE, TRUE, 0);
1430     if (cfg.scrollbar)
1431         gtk_box_pack_start(inst->hbox, inst->sbar, FALSE, FALSE, 0);
1432
1433     gtk_window_set_policy(GTK_WINDOW(inst->window), FALSE, TRUE, TRUE);
1434
1435     gtk_container_add(GTK_CONTAINER(inst->window), GTK_WIDGET(inst->hbox));
1436
1437     {
1438         GdkGeometry geom;
1439         geom.min_width = inst->font_width + 2*cfg.window_border;
1440         geom.min_height = inst->font_height + 2*cfg.window_border;
1441         geom.max_width = geom.max_height = -1;
1442         geom.base_width = 2*cfg.window_border;
1443         geom.base_height = 2*cfg.window_border;
1444         geom.width_inc = inst->font_width;
1445         geom.height_inc = inst->font_height;
1446         geom.min_aspect = geom.max_aspect = 0;
1447         gtk_window_set_geometry_hints(GTK_WINDOW(inst->window), inst->area, &geom,
1448                                       GDK_HINT_MIN_SIZE | GDK_HINT_BASE_SIZE |
1449                                       GDK_HINT_RESIZE_INC);
1450     }
1451
1452     gtk_signal_connect(GTK_OBJECT(inst->window), "destroy",
1453                        GTK_SIGNAL_FUNC(destroy), inst);
1454     gtk_signal_connect(GTK_OBJECT(inst->window), "delete_event",
1455                        GTK_SIGNAL_FUNC(delete_window), inst);
1456     gtk_signal_connect(GTK_OBJECT(inst->window), "key_press_event",
1457                        GTK_SIGNAL_FUNC(key_event), inst);
1458     gtk_signal_connect(GTK_OBJECT(inst->window), "focus_in_event",
1459                        GTK_SIGNAL_FUNC(focus_event), inst);
1460     gtk_signal_connect(GTK_OBJECT(inst->window), "focus_out_event",
1461                        GTK_SIGNAL_FUNC(focus_event), inst);
1462     gtk_signal_connect(GTK_OBJECT(inst->area), "configure_event",
1463                        GTK_SIGNAL_FUNC(configure_area), inst);
1464     gtk_signal_connect(GTK_OBJECT(inst->area), "expose_event",
1465                        GTK_SIGNAL_FUNC(expose_area), inst);
1466     gtk_signal_connect(GTK_OBJECT(inst->area), "button_press_event",
1467                        GTK_SIGNAL_FUNC(button_event), inst);
1468     gtk_signal_connect(GTK_OBJECT(inst->area), "button_release_event",
1469                        GTK_SIGNAL_FUNC(button_event), inst);
1470     gtk_signal_connect(GTK_OBJECT(inst->area), "motion_notify_event",
1471                        GTK_SIGNAL_FUNC(motion_event), inst);
1472     gtk_signal_connect(GTK_OBJECT(inst->area), "selection_received",
1473                        GTK_SIGNAL_FUNC(selection_received), inst);
1474     gtk_signal_connect(GTK_OBJECT(inst->area), "selection_get",
1475                        GTK_SIGNAL_FUNC(selection_get), inst);
1476     gtk_signal_connect(GTK_OBJECT(inst->area), "selection_clear_event",
1477                        GTK_SIGNAL_FUNC(selection_clear), inst);
1478     if (cfg.scrollbar)
1479         gtk_signal_connect(GTK_OBJECT(inst->sbar_adjust), "value_changed",
1480                            GTK_SIGNAL_FUNC(scrollbar_moved), inst);
1481     gtk_timeout_add(20, timer_func, inst);
1482     gtk_widget_add_events(GTK_WIDGET(inst->area),
1483                           GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK |
1484                           GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK |
1485                           GDK_POINTER_MOTION_MASK | GDK_BUTTON_MOTION_MASK);
1486
1487     gtk_widget_show(inst->area);
1488     if (cfg.scrollbar)
1489         gtk_widget_show(inst->sbar);
1490     gtk_widget_show(GTK_WIDGET(inst->hbox));
1491     gtk_widget_show(inst->window);
1492
1493     inst->textcursor = make_mouse_ptr(GDK_XTERM);
1494     inst->rawcursor = make_mouse_ptr(GDK_LEFT_PTR);
1495     inst->blankcursor = make_mouse_ptr(-1);
1496     make_mouse_ptr(-2);                /* clean up cursor font */
1497     inst->currcursor = inst->textcursor;
1498     show_mouseptr(1);
1499
1500     back = &pty_backend;
1501     back->init(NULL, 0, NULL, 0);
1502
1503     gdk_input_add(pty_master_fd, GDK_INPUT_READ, pty_input_func, inst);
1504
1505     term_init();
1506     term_size(cfg.height, cfg.width, cfg.savelines);
1507
1508     gtk_main();
1509
1510     return 0;
1511 }