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