...and the rest of r8854.
[u/mdw/putty] / unix / gtkwin.c
1 /*
2 * gtkwin.c: the main code that runs a PuTTY terminal emulator and
3 * backend in a GTK window.
4 */
5
6 #define _GNU_SOURCE
7
8 #include <string.h>
9 #include <assert.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <signal.h>
13 #include <stdio.h>
14 #include <time.h>
15 #include <errno.h>
16 #include <fcntl.h>
17 #include <unistd.h>
18 #include <sys/types.h>
19 #include <sys/wait.h>
20 #include <gtk/gtk.h>
21 #include <gdk/gdkkeysyms.h>
22 #include <gdk/gdkx.h>
23 #include <X11/Xlib.h>
24 #include <X11/Xutil.h>
25 #include <X11/Xatom.h>
26
27 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
28
29 #include "putty.h"
30 #include "terminal.h"
31 #include "gtkfont.h"
32
33 #define CAT2(x,y) x ## y
34 #define CAT(x,y) CAT2(x,y)
35 #define ASSERT(x) enum {CAT(assertion_,__LINE__) = 1 / (x)}
36
37 /* Colours come in two flavours: configurable, and xterm-extended. */
38 #define NCFGCOLOURS (lenof(((Config *)0)->colours))
39 #define NEXTCOLOURS 240 /* 216 colour-cube plus 24 shades of grey */
40 #define NALLCOLOURS (NCFGCOLOURS + NEXTCOLOURS)
41
42 GdkAtom compound_text_atom, utf8_string_atom;
43
44 extern char **pty_argv; /* declared in pty.c */
45 extern int use_pty_argv;
46
47 /*
48 * Timers are global across all sessions (even if we were handling
49 * multiple sessions, which we aren't), so the current timer ID is
50 * a global variable.
51 */
52 static guint timer_id = 0;
53
54 struct gui_data {
55 GtkWidget *window, *area, *sbar;
56 GtkBox *hbox;
57 GtkAdjustment *sbar_adjust;
58 GtkWidget *menu, *specialsmenu, *specialsitem1, *specialsitem2,
59 *restartitem;
60 GtkWidget *sessionsmenu;
61 GdkPixmap *pixmap;
62 unifont *fonts[4]; /* normal, bold, wide, widebold */
63 int xpos, ypos, gotpos, gravity;
64 GdkCursor *rawcursor, *textcursor, *blankcursor, *waitcursor, *currcursor;
65 GdkColor cols[NALLCOLOURS];
66 GdkColormap *colmap;
67 wchar_t *pastein_data;
68 int direct_to_font;
69 int pastein_data_len;
70 char *pasteout_data, *pasteout_data_ctext, *pasteout_data_utf8;
71 int pasteout_data_len, pasteout_data_ctext_len, pasteout_data_utf8_len;
72 int font_width, font_height;
73 int width, height;
74 int ignore_sbar;
75 int mouseptr_visible;
76 int busy_status;
77 guint term_paste_idle_id;
78 guint term_exit_idle_id;
79 int alt_keycode;
80 int alt_digits;
81 char wintitle[sizeof(((Config *)0)->wintitle)];
82 char icontitle[sizeof(((Config *)0)->wintitle)];
83 int master_fd, master_func_id;
84 void *ldisc;
85 Backend *back;
86 void *backhandle;
87 Terminal *term;
88 void *logctx;
89 int exited;
90 struct unicode_data ucsdata;
91 Config cfg;
92 void *eventlogstuff;
93 char *progname, **gtkargvstart;
94 int ngtkargs;
95 guint32 input_event_time; /* Timestamp of the most recent input event. */
96 int reconfiguring;
97 };
98
99 struct draw_ctx {
100 GdkGC *gc;
101 struct gui_data *inst;
102 };
103
104 static int send_raw_mouse;
105
106 static char *app_name = "pterm";
107
108 static void start_backend(struct gui_data *inst);
109
110 char *x_get_default(const char *key)
111 {
112 return XGetDefault(GDK_DISPLAY(), app_name, key);
113 }
114
115 void connection_fatal(void *frontend, char *p, ...)
116 {
117 struct gui_data *inst = (struct gui_data *)frontend;
118
119 va_list ap;
120 char *msg;
121 va_start(ap, p);
122 msg = dupvprintf(p, ap);
123 va_end(ap);
124 inst->exited = TRUE;
125 fatal_message_box(inst->window, msg);
126 sfree(msg);
127 if (inst->cfg.close_on_exit == FORCE_ON)
128 cleanup_exit(1);
129 }
130
131 /*
132 * Default settings that are specific to pterm.
133 */
134 FontSpec platform_default_fontspec(const char *name)
135 {
136 FontSpec ret;
137 if (!strcmp(name, "Font"))
138 strcpy(ret.name, "server:fixed");
139 else
140 *ret.name = '\0';
141 return ret;
142 }
143
144 Filename platform_default_filename(const char *name)
145 {
146 Filename ret;
147 if (!strcmp(name, "LogFileName"))
148 strcpy(ret.path, "putty.log");
149 else
150 *ret.path = '\0';
151 return ret;
152 }
153
154 char *platform_default_s(const char *name)
155 {
156 if (!strcmp(name, "SerialLine"))
157 return dupstr("/dev/ttyS0");
158 return NULL;
159 }
160
161 int platform_default_i(const char *name, int def)
162 {
163 if (!strcmp(name, "CloseOnExit"))
164 return 2; /* maps to FORCE_ON after painful rearrangement :-( */
165 if (!strcmp(name, "WinNameAlways"))
166 return 0; /* X natively supports icon titles, so use 'em by default */
167 return def;
168 }
169
170 /* Dummy routine, only required in plink. */
171 void ldisc_update(void *frontend, int echo, int edit)
172 {
173 }
174
175 char *get_ttymode(void *frontend, const char *mode)
176 {
177 struct gui_data *inst = (struct gui_data *)frontend;
178 return term_get_ttymode(inst->term, mode);
179 }
180
181 int from_backend(void *frontend, int is_stderr, const char *data, int len)
182 {
183 struct gui_data *inst = (struct gui_data *)frontend;
184 return term_data(inst->term, is_stderr, data, len);
185 }
186
187 int from_backend_untrusted(void *frontend, const char *data, int len)
188 {
189 struct gui_data *inst = (struct gui_data *)frontend;
190 return term_data_untrusted(inst->term, data, len);
191 }
192
193 int get_userpass_input(prompts_t *p, unsigned char *in, int inlen)
194 {
195 struct gui_data *inst = (struct gui_data *)p->frontend;
196 int ret;
197 ret = cmdline_get_passwd_input(p, in, inlen);
198 if (ret == -1)
199 ret = term_get_userpass_input(inst->term, p, in, inlen);
200 return ret;
201 }
202
203 void logevent(void *frontend, const char *string)
204 {
205 struct gui_data *inst = (struct gui_data *)frontend;
206
207 log_eventlog(inst->logctx, string);
208
209 logevent_dlg(inst->eventlogstuff, string);
210 }
211
212 int font_dimension(void *frontend, int which)/* 0 for width, 1 for height */
213 {
214 struct gui_data *inst = (struct gui_data *)frontend;
215
216 if (which)
217 return inst->font_height;
218 else
219 return inst->font_width;
220 }
221
222 /*
223 * Translate a raw mouse button designation (LEFT, MIDDLE, RIGHT)
224 * into a cooked one (SELECT, EXTEND, PASTE).
225 *
226 * In Unix, this is not configurable; the X button arrangement is
227 * rock-solid across all applications, everyone has a three-button
228 * mouse or a means of faking it, and there is no need to switch
229 * buttons around at all.
230 */
231 static Mouse_Button translate_button(Mouse_Button button)
232 {
233 /* struct gui_data *inst = (struct gui_data *)frontend; */
234
235 if (button == MBT_LEFT)
236 return MBT_SELECT;
237 if (button == MBT_MIDDLE)
238 return MBT_PASTE;
239 if (button == MBT_RIGHT)
240 return MBT_EXTEND;
241 return 0; /* shouldn't happen */
242 }
243
244 /*
245 * Return the top-level GtkWindow associated with a particular
246 * front end instance.
247 */
248 void *get_window(void *frontend)
249 {
250 struct gui_data *inst = (struct gui_data *)frontend;
251 return inst->window;
252 }
253
254 /*
255 * Minimise or restore the window in response to a server-side
256 * request.
257 */
258 void set_iconic(void *frontend, int iconic)
259 {
260 /*
261 * GTK 1.2 doesn't know how to do this.
262 */
263 #if GTK_CHECK_VERSION(2,0,0)
264 struct gui_data *inst = (struct gui_data *)frontend;
265 if (iconic)
266 gtk_window_iconify(GTK_WINDOW(inst->window));
267 else
268 gtk_window_deiconify(GTK_WINDOW(inst->window));
269 #endif
270 }
271
272 /*
273 * Move the window in response to a server-side request.
274 */
275 void move_window(void *frontend, int x, int y)
276 {
277 struct gui_data *inst = (struct gui_data *)frontend;
278 /*
279 * I assume that when the GTK version of this call is available
280 * we should use it. Not sure how it differs from the GDK one,
281 * though.
282 */
283 #if GTK_CHECK_VERSION(2,0,0)
284 gtk_window_move(GTK_WINDOW(inst->window), x, y);
285 #else
286 gdk_window_move(inst->window->window, x, y);
287 #endif
288 }
289
290 /*
291 * Move the window to the top or bottom of the z-order in response
292 * to a server-side request.
293 */
294 void set_zorder(void *frontend, int top)
295 {
296 struct gui_data *inst = (struct gui_data *)frontend;
297 if (top)
298 gdk_window_raise(inst->window->window);
299 else
300 gdk_window_lower(inst->window->window);
301 }
302
303 /*
304 * Refresh the window in response to a server-side request.
305 */
306 void refresh_window(void *frontend)
307 {
308 struct gui_data *inst = (struct gui_data *)frontend;
309 term_invalidate(inst->term);
310 }
311
312 /*
313 * Maximise or restore the window in response to a server-side
314 * request.
315 */
316 void set_zoomed(void *frontend, int zoomed)
317 {
318 /*
319 * GTK 1.2 doesn't know how to do this.
320 */
321 #if GTK_CHECK_VERSION(2,0,0)
322 struct gui_data *inst = (struct gui_data *)frontend;
323 if (zoomed)
324 gtk_window_maximize(GTK_WINDOW(inst->window));
325 else
326 gtk_window_unmaximize(GTK_WINDOW(inst->window));
327 #endif
328 }
329
330 /*
331 * Report whether the window is iconic, for terminal reports.
332 */
333 int is_iconic(void *frontend)
334 {
335 struct gui_data *inst = (struct gui_data *)frontend;
336 return !gdk_window_is_viewable(inst->window->window);
337 }
338
339 /*
340 * Report the window's position, for terminal reports.
341 */
342 void get_window_pos(void *frontend, int *x, int *y)
343 {
344 struct gui_data *inst = (struct gui_data *)frontend;
345 /*
346 * I assume that when the GTK version of this call is available
347 * we should use it. Not sure how it differs from the GDK one,
348 * though.
349 */
350 #if GTK_CHECK_VERSION(2,0,0)
351 gtk_window_get_position(GTK_WINDOW(inst->window), x, y);
352 #else
353 gdk_window_get_position(inst->window->window, x, y);
354 #endif
355 }
356
357 /*
358 * Report the window's pixel size, for terminal reports.
359 */
360 void get_window_pixels(void *frontend, int *x, int *y)
361 {
362 struct gui_data *inst = (struct gui_data *)frontend;
363 /*
364 * I assume that when the GTK version of this call is available
365 * we should use it. Not sure how it differs from the GDK one,
366 * though.
367 */
368 #if GTK_CHECK_VERSION(2,0,0)
369 gtk_window_get_size(GTK_WINDOW(inst->window), x, y);
370 #else
371 gdk_window_get_size(inst->window->window, x, y);
372 #endif
373 }
374
375 /*
376 * Return the window or icon title.
377 */
378 char *get_window_title(void *frontend, int icon)
379 {
380 struct gui_data *inst = (struct gui_data *)frontend;
381 return icon ? inst->icontitle : inst->wintitle;
382 }
383
384 gint delete_window(GtkWidget *widget, GdkEvent *event, gpointer data)
385 {
386 struct gui_data *inst = (struct gui_data *)data;
387 if (!inst->exited && inst->cfg.warn_on_close) {
388 if (!reallyclose(inst))
389 return TRUE;
390 }
391 return FALSE;
392 }
393
394 static void update_mouseptr(struct gui_data *inst)
395 {
396 switch (inst->busy_status) {
397 case BUSY_NOT:
398 if (!inst->mouseptr_visible) {
399 gdk_window_set_cursor(inst->area->window, inst->blankcursor);
400 } else if (send_raw_mouse) {
401 gdk_window_set_cursor(inst->area->window, inst->rawcursor);
402 } else {
403 gdk_window_set_cursor(inst->area->window, inst->textcursor);
404 }
405 break;
406 case BUSY_WAITING: /* XXX can we do better? */
407 case BUSY_CPU:
408 /* We always display these cursors. */
409 gdk_window_set_cursor(inst->area->window, inst->waitcursor);
410 break;
411 default:
412 assert(0);
413 }
414 }
415
416 static void show_mouseptr(struct gui_data *inst, int show)
417 {
418 if (!inst->cfg.hide_mouseptr)
419 show = 1;
420 inst->mouseptr_visible = show;
421 update_mouseptr(inst);
422 }
423
424 void draw_backing_rect(struct gui_data *inst)
425 {
426 GdkGC *gc = gdk_gc_new(inst->area->window);
427 gdk_gc_set_foreground(gc, &inst->cols[258]); /* default background */
428 gdk_draw_rectangle(inst->pixmap, gc, 1, 0, 0,
429 inst->cfg.width * inst->font_width + 2*inst->cfg.window_border,
430 inst->cfg.height * inst->font_height + 2*inst->cfg.window_border);
431 gdk_gc_unref(gc);
432 }
433
434 gint configure_area(GtkWidget *widget, GdkEventConfigure *event, gpointer data)
435 {
436 struct gui_data *inst = (struct gui_data *)data;
437 int w, h, need_size = 0;
438
439 /*
440 * See if the terminal size has changed, in which case we must
441 * let the terminal know.
442 */
443 w = (event->width - 2*inst->cfg.window_border) / inst->font_width;
444 h = (event->height - 2*inst->cfg.window_border) / inst->font_height;
445 if (w != inst->width || h != inst->height) {
446 inst->cfg.width = inst->width = w;
447 inst->cfg.height = inst->height = h;
448 need_size = 1;
449 }
450
451 if (inst->pixmap) {
452 gdk_pixmap_unref(inst->pixmap);
453 inst->pixmap = NULL;
454 }
455
456 inst->pixmap = gdk_pixmap_new(widget->window,
457 (inst->cfg.width * inst->font_width +
458 2*inst->cfg.window_border),
459 (inst->cfg.height * inst->font_height +
460 2*inst->cfg.window_border), -1);
461
462 draw_backing_rect(inst);
463
464 if (need_size && inst->term) {
465 term_size(inst->term, h, w, inst->cfg.savelines);
466 }
467
468 if (inst->term)
469 term_invalidate(inst->term);
470
471 return TRUE;
472 }
473
474 gint expose_area(GtkWidget *widget, GdkEventExpose *event, gpointer data)
475 {
476 struct gui_data *inst = (struct gui_data *)data;
477
478 /*
479 * Pass the exposed rectangle to terminal.c, which will call us
480 * back to do the actual painting.
481 */
482 if (inst->pixmap) {
483 gdk_draw_pixmap(widget->window,
484 widget->style->fg_gc[GTK_WIDGET_STATE(widget)],
485 inst->pixmap,
486 event->area.x, event->area.y,
487 event->area.x, event->area.y,
488 event->area.width, event->area.height);
489 }
490 return TRUE;
491 }
492
493 #define KEY_PRESSED(k) \
494 (inst->keystate[(k) / 32] & (1 << ((k) % 32)))
495
496 gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data)
497 {
498 struct gui_data *inst = (struct gui_data *)data;
499 char output[256];
500 wchar_t ucsoutput[2];
501 int ucsval, start, end, special, output_charset, use_ucsoutput;
502
503 /* Remember the timestamp. */
504 inst->input_event_time = event->time;
505
506 /* By default, nothing is generated. */
507 end = start = 0;
508 special = use_ucsoutput = FALSE;
509 output_charset = CS_ISO8859_1;
510
511 /*
512 * If Alt is being released after typing an Alt+numberpad
513 * sequence, we should generate the code that was typed.
514 *
515 * Note that we only do this if more than one key was actually
516 * pressed - I don't think Alt+NumPad4 should be ^D or that
517 * Alt+NumPad3 should be ^C, for example. There's no serious
518 * inconvenience in having to type a zero before a single-digit
519 * character code.
520 */
521 if (event->type == GDK_KEY_RELEASE &&
522 (event->keyval == GDK_Meta_L || event->keyval == GDK_Alt_L ||
523 event->keyval == GDK_Meta_R || event->keyval == GDK_Alt_R) &&
524 inst->alt_keycode >= 0 && inst->alt_digits > 1) {
525 #ifdef KEY_DEBUGGING
526 printf("Alt key up, keycode = %d\n", inst->alt_keycode);
527 #endif
528 /*
529 * FIXME: we might usefully try to do something clever here
530 * about interpreting the generated key code in a way that's
531 * appropriate to the line code page.
532 */
533 output[0] = inst->alt_keycode;
534 end = 1;
535 goto done;
536 }
537
538 if (event->type == GDK_KEY_PRESS) {
539 #ifdef KEY_DEBUGGING
540 {
541 int i;
542 printf("keypress: keyval = %04x, state = %08x; string =",
543 event->keyval, event->state);
544 for (i = 0; event->string[i]; i++)
545 printf(" %02x", (unsigned char) event->string[i]);
546 printf("\n");
547 }
548 #endif
549
550 /*
551 * NYI: Compose key (!!! requires Unicode faff before even trying)
552 */
553
554 /*
555 * If Alt has just been pressed, we start potentially
556 * accumulating an Alt+numberpad code. We do this by
557 * setting alt_keycode to -1 (nothing yet but plausible).
558 */
559 if ((event->keyval == GDK_Meta_L || event->keyval == GDK_Alt_L ||
560 event->keyval == GDK_Meta_R || event->keyval == GDK_Alt_R)) {
561 inst->alt_keycode = -1;
562 inst->alt_digits = 0;
563 goto done; /* this generates nothing else */
564 }
565
566 /*
567 * If we're seeing a numberpad key press with Mod1 down,
568 * consider adding it to alt_keycode if that's sensible.
569 * Anything _else_ with Mod1 down cancels any possibility
570 * of an ALT keycode: we set alt_keycode to -2.
571 */
572 if ((event->state & GDK_MOD1_MASK) && inst->alt_keycode != -2) {
573 int digit = -1;
574 switch (event->keyval) {
575 case GDK_KP_0: case GDK_KP_Insert: digit = 0; break;
576 case GDK_KP_1: case GDK_KP_End: digit = 1; break;
577 case GDK_KP_2: case GDK_KP_Down: digit = 2; break;
578 case GDK_KP_3: case GDK_KP_Page_Down: digit = 3; break;
579 case GDK_KP_4: case GDK_KP_Left: digit = 4; break;
580 case GDK_KP_5: case GDK_KP_Begin: digit = 5; break;
581 case GDK_KP_6: case GDK_KP_Right: digit = 6; break;
582 case GDK_KP_7: case GDK_KP_Home: digit = 7; break;
583 case GDK_KP_8: case GDK_KP_Up: digit = 8; break;
584 case GDK_KP_9: case GDK_KP_Page_Up: digit = 9; break;
585 }
586 if (digit < 0)
587 inst->alt_keycode = -2; /* it's invalid */
588 else {
589 #ifdef KEY_DEBUGGING
590 printf("Adding digit %d to keycode %d", digit,
591 inst->alt_keycode);
592 #endif
593 if (inst->alt_keycode == -1)
594 inst->alt_keycode = digit; /* one-digit code */
595 else
596 inst->alt_keycode = inst->alt_keycode * 10 + digit;
597 inst->alt_digits++;
598 #ifdef KEY_DEBUGGING
599 printf(" gives new code %d\n", inst->alt_keycode);
600 #endif
601 /* Having used this digit, we now do nothing more with it. */
602 goto done;
603 }
604 }
605
606 /*
607 * Shift-PgUp and Shift-PgDn don't even generate keystrokes
608 * at all.
609 */
610 if (event->keyval == GDK_Page_Up && (event->state & GDK_SHIFT_MASK)) {
611 term_scroll(inst->term, 0, -inst->cfg.height/2);
612 return TRUE;
613 }
614 if (event->keyval == GDK_Page_Up && (event->state & GDK_CONTROL_MASK)) {
615 term_scroll(inst->term, 0, -1);
616 return TRUE;
617 }
618 if (event->keyval == GDK_Page_Down && (event->state & GDK_SHIFT_MASK)) {
619 term_scroll(inst->term, 0, +inst->cfg.height/2);
620 return TRUE;
621 }
622 if (event->keyval == GDK_Page_Down && (event->state & GDK_CONTROL_MASK)) {
623 term_scroll(inst->term, 0, +1);
624 return TRUE;
625 }
626
627 /*
628 * Neither does Shift-Ins.
629 */
630 if (event->keyval == GDK_Insert && (event->state & GDK_SHIFT_MASK)) {
631 request_paste(inst);
632 return TRUE;
633 }
634
635 special = FALSE;
636 use_ucsoutput = FALSE;
637
638 /* ALT+things gives leading Escape. */
639 output[0] = '\033';
640 #if !GTK_CHECK_VERSION(2,0,0)
641 /*
642 * In vanilla X, and hence also GDK 1.2, the string received
643 * as part of a keyboard event is assumed to be in
644 * ISO-8859-1. (Seems woefully shortsighted in i18n terms,
645 * but it's true: see the man page for XLookupString(3) for
646 * confirmation.)
647 */
648 output_charset = CS_ISO8859_1;
649 strncpy(output+1, event->string, lenof(output)-1);
650 #else
651 /*
652 * GDK 2.0 arranges to have done some translation for us: in
653 * GDK 2.0, event->string is encoded in the current locale.
654 *
655 * (However, it's also deprecated; we really ought to be
656 * using a GTKIMContext.)
657 *
658 * So we use the standard C library function mbstowcs() to
659 * convert from the current locale into Unicode; from there
660 * we can convert to whatever PuTTY is currently working in.
661 * (In fact I convert straight back to UTF-8 from
662 * wide-character Unicode, for the sake of simplicity: that
663 * way we can still use exactly the same code to manipulate
664 * the string, such as prefixing ESC.)
665 */
666 output_charset = CS_UTF8;
667 {
668 wchar_t widedata[32], *wp;
669 int wlen;
670 int ulen;
671
672 wlen = mb_to_wc(DEFAULT_CODEPAGE, 0,
673 event->string, strlen(event->string),
674 widedata, lenof(widedata)-1);
675
676 wp = widedata;
677 ulen = charset_from_unicode(&wp, &wlen, output+1, lenof(output)-2,
678 CS_UTF8, NULL, NULL, 0);
679 output[1+ulen] = '\0';
680 }
681 #endif
682
683 if (!output[1] &&
684 (ucsval = keysym_to_unicode(event->keyval)) >= 0) {
685 ucsoutput[0] = '\033';
686 ucsoutput[1] = ucsval;
687 use_ucsoutput = TRUE;
688 end = 2;
689 } else {
690 output[lenof(output)-1] = '\0';
691 end = strlen(output);
692 }
693 if (event->state & GDK_MOD1_MASK) {
694 start = 0;
695 if (end == 1) end = 0;
696 } else
697 start = 1;
698
699 /* Control-` is the same as Control-\ (unless gtk has a better idea) */
700 if (!output[1] && event->keyval == '`' &&
701 (event->state & GDK_CONTROL_MASK)) {
702 output[1] = '\x1C';
703 use_ucsoutput = FALSE;
704 end = 2;
705 }
706
707 /* Control-Break sends a Break special to the backend */
708 if (event->keyval == GDK_Break &&
709 (event->state & GDK_CONTROL_MASK)) {
710 if (inst->back)
711 inst->back->special(inst->backhandle, TS_BRK);
712 return TRUE;
713 }
714
715 /* We handle Return ourselves, because it needs to be flagged as
716 * special to ldisc. */
717 if (event->keyval == GDK_Return) {
718 output[1] = '\015';
719 use_ucsoutput = FALSE;
720 end = 2;
721 special = TRUE;
722 }
723
724 /* Control-2, Control-Space and Control-@ are NUL */
725 if (!output[1] &&
726 (event->keyval == ' ' || event->keyval == '2' ||
727 event->keyval == '@') &&
728 (event->state & (GDK_SHIFT_MASK |
729 GDK_CONTROL_MASK)) == GDK_CONTROL_MASK) {
730 output[1] = '\0';
731 use_ucsoutput = FALSE;
732 end = 2;
733 }
734
735 /* Control-Shift-Space is 160 (ISO8859 nonbreaking space) */
736 if (!output[1] && event->keyval == ' ' &&
737 (event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK)) ==
738 (GDK_SHIFT_MASK | GDK_CONTROL_MASK)) {
739 output[1] = '\240';
740 output_charset = CS_ISO8859_1;
741 use_ucsoutput = FALSE;
742 end = 2;
743 }
744
745 /* We don't let GTK tell us what Backspace is! We know better. */
746 if (event->keyval == GDK_BackSpace &&
747 !(event->state & GDK_SHIFT_MASK)) {
748 output[1] = inst->cfg.bksp_is_delete ? '\x7F' : '\x08';
749 use_ucsoutput = FALSE;
750 end = 2;
751 special = TRUE;
752 }
753 /* For Shift Backspace, do opposite of what is configured. */
754 if (event->keyval == GDK_BackSpace &&
755 (event->state & GDK_SHIFT_MASK)) {
756 output[1] = inst->cfg.bksp_is_delete ? '\x08' : '\x7F';
757 use_ucsoutput = FALSE;
758 end = 2;
759 special = TRUE;
760 }
761
762 /* Shift-Tab is ESC [ Z */
763 if (event->keyval == GDK_ISO_Left_Tab ||
764 (event->keyval == GDK_Tab && (event->state & GDK_SHIFT_MASK))) {
765 end = 1 + sprintf(output+1, "\033[Z");
766 use_ucsoutput = FALSE;
767 }
768 /* And normal Tab is Tab, if the keymap hasn't already told us.
769 * (Curiously, at least one version of the MacOS 10.5 X server
770 * doesn't translate Tab for us. */
771 if (event->keyval == GDK_Tab && end <= 1) {
772 output[1] = '\t';
773 end = 2;
774 }
775
776 /*
777 * NetHack keypad mode.
778 */
779 if (inst->cfg.nethack_keypad) {
780 char *keys = NULL;
781 switch (event->keyval) {
782 case GDK_KP_1: case GDK_KP_End: keys = "bB\002"; break;
783 case GDK_KP_2: case GDK_KP_Down: keys = "jJ\012"; break;
784 case GDK_KP_3: case GDK_KP_Page_Down: keys = "nN\016"; break;
785 case GDK_KP_4: case GDK_KP_Left: keys = "hH\010"; break;
786 case GDK_KP_5: case GDK_KP_Begin: keys = "..."; break;
787 case GDK_KP_6: case GDK_KP_Right: keys = "lL\014"; break;
788 case GDK_KP_7: case GDK_KP_Home: keys = "yY\031"; break;
789 case GDK_KP_8: case GDK_KP_Up: keys = "kK\013"; break;
790 case GDK_KP_9: case GDK_KP_Page_Up: keys = "uU\025"; break;
791 }
792 if (keys) {
793 end = 2;
794 if (event->state & GDK_CONTROL_MASK)
795 output[1] = keys[2];
796 else if (event->state & GDK_SHIFT_MASK)
797 output[1] = keys[1];
798 else
799 output[1] = keys[0];
800 use_ucsoutput = FALSE;
801 goto done;
802 }
803 }
804
805 /*
806 * Application keypad mode.
807 */
808 if (inst->term->app_keypad_keys && !inst->cfg.no_applic_k) {
809 int xkey = 0;
810 switch (event->keyval) {
811 case GDK_Num_Lock: xkey = 'P'; break;
812 case GDK_KP_Divide: xkey = 'Q'; break;
813 case GDK_KP_Multiply: xkey = 'R'; break;
814 case GDK_KP_Subtract: xkey = 'S'; break;
815 /*
816 * Keypad + is tricky. It covers a space that would
817 * be taken up on the VT100 by _two_ keys; so we
818 * let Shift select between the two. Worse still,
819 * in xterm function key mode we change which two...
820 */
821 case GDK_KP_Add:
822 if (inst->cfg.funky_type == FUNKY_XTERM) {
823 if (event->state & GDK_SHIFT_MASK)
824 xkey = 'l';
825 else
826 xkey = 'k';
827 } else if (event->state & GDK_SHIFT_MASK)
828 xkey = 'm';
829 else
830 xkey = 'l';
831 break;
832 case GDK_KP_Enter: xkey = 'M'; break;
833 case GDK_KP_0: case GDK_KP_Insert: xkey = 'p'; break;
834 case GDK_KP_1: case GDK_KP_End: xkey = 'q'; break;
835 case GDK_KP_2: case GDK_KP_Down: xkey = 'r'; break;
836 case GDK_KP_3: case GDK_KP_Page_Down: xkey = 's'; break;
837 case GDK_KP_4: case GDK_KP_Left: xkey = 't'; break;
838 case GDK_KP_5: case GDK_KP_Begin: xkey = 'u'; break;
839 case GDK_KP_6: case GDK_KP_Right: xkey = 'v'; break;
840 case GDK_KP_7: case GDK_KP_Home: xkey = 'w'; break;
841 case GDK_KP_8: case GDK_KP_Up: xkey = 'x'; break;
842 case GDK_KP_9: case GDK_KP_Page_Up: xkey = 'y'; break;
843 case GDK_KP_Decimal: case GDK_KP_Delete: xkey = 'n'; break;
844 }
845 if (xkey) {
846 if (inst->term->vt52_mode) {
847 if (xkey >= 'P' && xkey <= 'S')
848 end = 1 + sprintf(output+1, "\033%c", xkey);
849 else
850 end = 1 + sprintf(output+1, "\033?%c", xkey);
851 } else
852 end = 1 + sprintf(output+1, "\033O%c", xkey);
853 use_ucsoutput = FALSE;
854 goto done;
855 }
856 }
857
858 /*
859 * Next, all the keys that do tilde codes. (ESC '[' nn '~',
860 * for integer decimal nn.)
861 *
862 * We also deal with the weird ones here. Linux VCs replace F1
863 * to F5 by ESC [ [ A to ESC [ [ E. rxvt doesn't do _that_, but
864 * does replace Home and End (1~ and 4~) by ESC [ H and ESC O w
865 * respectively.
866 */
867 {
868 int code = 0;
869 switch (event->keyval) {
870 case GDK_F1:
871 code = (event->state & GDK_SHIFT_MASK ? 23 : 11);
872 break;
873 case GDK_F2:
874 code = (event->state & GDK_SHIFT_MASK ? 24 : 12);
875 break;
876 case GDK_F3:
877 code = (event->state & GDK_SHIFT_MASK ? 25 : 13);
878 break;
879 case GDK_F4:
880 code = (event->state & GDK_SHIFT_MASK ? 26 : 14);
881 break;
882 case GDK_F5:
883 code = (event->state & GDK_SHIFT_MASK ? 28 : 15);
884 break;
885 case GDK_F6:
886 code = (event->state & GDK_SHIFT_MASK ? 29 : 17);
887 break;
888 case GDK_F7:
889 code = (event->state & GDK_SHIFT_MASK ? 31 : 18);
890 break;
891 case GDK_F8:
892 code = (event->state & GDK_SHIFT_MASK ? 32 : 19);
893 break;
894 case GDK_F9:
895 code = (event->state & GDK_SHIFT_MASK ? 33 : 20);
896 break;
897 case GDK_F10:
898 code = (event->state & GDK_SHIFT_MASK ? 34 : 21);
899 break;
900 case GDK_F11:
901 code = 23;
902 break;
903 case GDK_F12:
904 code = 24;
905 break;
906 case GDK_F13:
907 code = 25;
908 break;
909 case GDK_F14:
910 code = 26;
911 break;
912 case GDK_F15:
913 code = 28;
914 break;
915 case GDK_F16:
916 code = 29;
917 break;
918 case GDK_F17:
919 code = 31;
920 break;
921 case GDK_F18:
922 code = 32;
923 break;
924 case GDK_F19:
925 code = 33;
926 break;
927 case GDK_F20:
928 code = 34;
929 break;
930 }
931 if (!(event->state & GDK_CONTROL_MASK)) switch (event->keyval) {
932 case GDK_Home: case GDK_KP_Home:
933 code = 1;
934 break;
935 case GDK_Insert: case GDK_KP_Insert:
936 code = 2;
937 break;
938 case GDK_Delete: case GDK_KP_Delete:
939 code = 3;
940 break;
941 case GDK_End: case GDK_KP_End:
942 code = 4;
943 break;
944 case GDK_Page_Up: case GDK_KP_Page_Up:
945 code = 5;
946 break;
947 case GDK_Page_Down: case GDK_KP_Page_Down:
948 code = 6;
949 break;
950 }
951 /* Reorder edit keys to physical order */
952 if (inst->cfg.funky_type == FUNKY_VT400 && code <= 6)
953 code = "\0\2\1\4\5\3\6"[code];
954
955 if (inst->term->vt52_mode && code > 0 && code <= 6) {
956 end = 1 + sprintf(output+1, "\x1B%c", " HLMEIG"[code]);
957 use_ucsoutput = FALSE;
958 goto done;
959 }
960
961 if (inst->cfg.funky_type == FUNKY_SCO && /* SCO function keys */
962 code >= 11 && code <= 34) {
963 char codes[] = "MNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@[\\]^_`{";
964 int index = 0;
965 switch (event->keyval) {
966 case GDK_F1: index = 0; break;
967 case GDK_F2: index = 1; break;
968 case GDK_F3: index = 2; break;
969 case GDK_F4: index = 3; break;
970 case GDK_F5: index = 4; break;
971 case GDK_F6: index = 5; break;
972 case GDK_F7: index = 6; break;
973 case GDK_F8: index = 7; break;
974 case GDK_F9: index = 8; break;
975 case GDK_F10: index = 9; break;
976 case GDK_F11: index = 10; break;
977 case GDK_F12: index = 11; break;
978 }
979 if (event->state & GDK_SHIFT_MASK) index += 12;
980 if (event->state & GDK_CONTROL_MASK) index += 24;
981 end = 1 + sprintf(output+1, "\x1B[%c", codes[index]);
982 use_ucsoutput = FALSE;
983 goto done;
984 }
985 if (inst->cfg.funky_type == FUNKY_SCO && /* SCO small keypad */
986 code >= 1 && code <= 6) {
987 char codes[] = "HL.FIG";
988 if (code == 3) {
989 output[1] = '\x7F';
990 end = 2;
991 } else {
992 end = 1 + sprintf(output+1, "\x1B[%c", codes[code-1]);
993 }
994 use_ucsoutput = FALSE;
995 goto done;
996 }
997 if ((inst->term->vt52_mode || inst->cfg.funky_type == FUNKY_VT100P) &&
998 code >= 11 && code <= 24) {
999 int offt = 0;
1000 if (code > 15)
1001 offt++;
1002 if (code > 21)
1003 offt++;
1004 if (inst->term->vt52_mode)
1005 end = 1 + sprintf(output+1,
1006 "\x1B%c", code + 'P' - 11 - offt);
1007 else
1008 end = 1 + sprintf(output+1,
1009 "\x1BO%c", code + 'P' - 11 - offt);
1010 use_ucsoutput = FALSE;
1011 goto done;
1012 }
1013 if (inst->cfg.funky_type == FUNKY_LINUX && code >= 11 && code <= 15) {
1014 end = 1 + sprintf(output+1, "\x1B[[%c", code + 'A' - 11);
1015 use_ucsoutput = FALSE;
1016 goto done;
1017 }
1018 if (inst->cfg.funky_type == FUNKY_XTERM && code >= 11 && code <= 14) {
1019 if (inst->term->vt52_mode)
1020 end = 1 + sprintf(output+1, "\x1B%c", code + 'P' - 11);
1021 else
1022 end = 1 + sprintf(output+1, "\x1BO%c", code + 'P' - 11);
1023 use_ucsoutput = FALSE;
1024 goto done;
1025 }
1026 if (inst->cfg.rxvt_homeend && (code == 1 || code == 4)) {
1027 end = 1 + sprintf(output+1, code == 1 ? "\x1B[H" : "\x1BOw");
1028 use_ucsoutput = FALSE;
1029 goto done;
1030 }
1031 if (code) {
1032 end = 1 + sprintf(output+1, "\x1B[%d~", code);
1033 use_ucsoutput = FALSE;
1034 goto done;
1035 }
1036 }
1037
1038 /*
1039 * Cursor keys. (This includes the numberpad cursor keys,
1040 * if we haven't already done them due to app keypad mode.)
1041 *
1042 * Here we also process un-numlocked un-appkeypadded KP5,
1043 * which sends ESC [ G.
1044 */
1045 {
1046 int xkey = 0;
1047 switch (event->keyval) {
1048 case GDK_Up: case GDK_KP_Up: xkey = 'A'; break;
1049 case GDK_Down: case GDK_KP_Down: xkey = 'B'; break;
1050 case GDK_Right: case GDK_KP_Right: xkey = 'C'; break;
1051 case GDK_Left: case GDK_KP_Left: xkey = 'D'; break;
1052 case GDK_Begin: case GDK_KP_Begin: xkey = 'G'; break;
1053 }
1054 if (xkey) {
1055 /*
1056 * The arrow keys normally do ESC [ A and so on. In
1057 * app cursor keys mode they do ESC O A instead.
1058 * Ctrl toggles the two modes.
1059 */
1060 if (inst->term->vt52_mode) {
1061 end = 1 + sprintf(output+1, "\033%c", xkey);
1062 } else if (!inst->term->app_cursor_keys ^
1063 !(event->state & GDK_CONTROL_MASK)) {
1064 end = 1 + sprintf(output+1, "\033O%c", xkey);
1065 } else {
1066 end = 1 + sprintf(output+1, "\033[%c", xkey);
1067 }
1068 use_ucsoutput = FALSE;
1069 goto done;
1070 }
1071 }
1072 goto done;
1073 }
1074
1075 done:
1076
1077 if (end-start > 0) {
1078 #ifdef KEY_DEBUGGING
1079 int i;
1080 printf("generating sequence:");
1081 for (i = start; i < end; i++)
1082 printf(" %02x", (unsigned char) output[i]);
1083 printf("\n");
1084 #endif
1085
1086 if (special) {
1087 /*
1088 * For special control characters, the character set
1089 * should never matter.
1090 */
1091 output[end] = '\0'; /* NUL-terminate */
1092 if (inst->ldisc)
1093 ldisc_send(inst->ldisc, output+start, -2, 1);
1094 } else if (!inst->direct_to_font) {
1095 if (!use_ucsoutput) {
1096 if (inst->ldisc)
1097 lpage_send(inst->ldisc, output_charset, output+start,
1098 end-start, 1);
1099 } else {
1100 /*
1101 * We generated our own Unicode key data from the
1102 * keysym, so use that instead.
1103 */
1104 if (inst->ldisc)
1105 luni_send(inst->ldisc, ucsoutput+start, end-start, 1);
1106 }
1107 } else {
1108 /*
1109 * In direct-to-font mode, we just send the string
1110 * exactly as we received it.
1111 */
1112 if (inst->ldisc)
1113 ldisc_send(inst->ldisc, output+start, end-start, 1);
1114 }
1115
1116 show_mouseptr(inst, 0);
1117 term_seen_key_event(inst->term);
1118 }
1119
1120 return TRUE;
1121 }
1122
1123 gboolean button_internal(struct gui_data *inst, guint32 timestamp,
1124 GdkEventType type, guint ebutton, guint state,
1125 gdouble ex, gdouble ey)
1126 {
1127 int shift, ctrl, alt, x, y, button, act;
1128
1129 /* Remember the timestamp. */
1130 inst->input_event_time = timestamp;
1131
1132 show_mouseptr(inst, 1);
1133
1134 if (ebutton == 4 && type == GDK_BUTTON_PRESS) {
1135 term_scroll(inst->term, 0, -5);
1136 return TRUE;
1137 }
1138 if (ebutton == 5 && type == GDK_BUTTON_PRESS) {
1139 term_scroll(inst->term, 0, +5);
1140 return TRUE;
1141 }
1142
1143 shift = state & GDK_SHIFT_MASK;
1144 ctrl = state & GDK_CONTROL_MASK;
1145 alt = state & GDK_MOD1_MASK;
1146
1147 if (ebutton == 3 && ctrl) {
1148 gtk_menu_popup(GTK_MENU(inst->menu), NULL, NULL, NULL, NULL,
1149 ebutton, timestamp);
1150 return TRUE;
1151 }
1152
1153 if (ebutton == 1)
1154 button = MBT_LEFT;
1155 else if (ebutton == 2)
1156 button = MBT_MIDDLE;
1157 else if (ebutton == 3)
1158 button = MBT_RIGHT;
1159 else
1160 return FALSE; /* don't even know what button! */
1161
1162 switch (type) {
1163 case GDK_BUTTON_PRESS: act = MA_CLICK; break;
1164 case GDK_BUTTON_RELEASE: act = MA_RELEASE; break;
1165 case GDK_2BUTTON_PRESS: act = MA_2CLK; break;
1166 case GDK_3BUTTON_PRESS: act = MA_3CLK; break;
1167 default: return FALSE; /* don't know this event type */
1168 }
1169
1170 if (send_raw_mouse && !(inst->cfg.mouse_override && shift) &&
1171 act != MA_CLICK && act != MA_RELEASE)
1172 return TRUE; /* we ignore these in raw mouse mode */
1173
1174 x = (ex - inst->cfg.window_border) / inst->font_width;
1175 y = (ey - inst->cfg.window_border) / inst->font_height;
1176
1177 term_mouse(inst->term, button, translate_button(button), act,
1178 x, y, shift, ctrl, alt);
1179
1180 return TRUE;
1181 }
1182
1183 gboolean button_event(GtkWidget *widget, GdkEventButton *event, gpointer data)
1184 {
1185 struct gui_data *inst = (struct gui_data *)data;
1186 return button_internal(inst, event->time, event->type, event->button,
1187 event->state, event->x, event->y);
1188 }
1189
1190 #if GTK_CHECK_VERSION(2,0,0)
1191 /*
1192 * In GTK 2, mouse wheel events have become a new type of event.
1193 * This handler translates them back into button-4 and button-5
1194 * presses so that I don't have to change my old code too much :-)
1195 */
1196 gboolean scroll_event(GtkWidget *widget, GdkEventScroll *event, gpointer data)
1197 {
1198 struct gui_data *inst = (struct gui_data *)data;
1199 guint button;
1200
1201 if (event->direction == GDK_SCROLL_UP)
1202 button = 4;
1203 else if (event->direction == GDK_SCROLL_DOWN)
1204 button = 5;
1205 else
1206 return FALSE;
1207
1208 return button_internal(inst, event->time, GDK_BUTTON_PRESS,
1209 button, event->state, event->x, event->y);
1210 }
1211 #endif
1212
1213 gint motion_event(GtkWidget *widget, GdkEventMotion *event, gpointer data)
1214 {
1215 struct gui_data *inst = (struct gui_data *)data;
1216 int shift, ctrl, alt, x, y, button;
1217
1218 /* Remember the timestamp. */
1219 inst->input_event_time = event->time;
1220
1221 show_mouseptr(inst, 1);
1222
1223 shift = event->state & GDK_SHIFT_MASK;
1224 ctrl = event->state & GDK_CONTROL_MASK;
1225 alt = event->state & GDK_MOD1_MASK;
1226 if (event->state & GDK_BUTTON1_MASK)
1227 button = MBT_LEFT;
1228 else if (event->state & GDK_BUTTON2_MASK)
1229 button = MBT_MIDDLE;
1230 else if (event->state & GDK_BUTTON3_MASK)
1231 button = MBT_RIGHT;
1232 else
1233 return FALSE; /* don't even know what button! */
1234
1235 x = (event->x - inst->cfg.window_border) / inst->font_width;
1236 y = (event->y - inst->cfg.window_border) / inst->font_height;
1237
1238 term_mouse(inst->term, button, translate_button(button), MA_DRAG,
1239 x, y, shift, ctrl, alt);
1240
1241 return TRUE;
1242 }
1243
1244 void frontend_keypress(void *handle)
1245 {
1246 struct gui_data *inst = (struct gui_data *)handle;
1247
1248 /*
1249 * If our child process has exited but not closed, terminate on
1250 * any keypress.
1251 */
1252 if (inst->exited)
1253 exit(0);
1254 }
1255
1256 static gint idle_exit_func(gpointer data)
1257 {
1258 struct gui_data *inst = (struct gui_data *)data;
1259 int exitcode;
1260
1261 if (!inst->exited &&
1262 (exitcode = inst->back->exitcode(inst->backhandle)) >= 0) {
1263 inst->exited = TRUE;
1264 if (inst->cfg.close_on_exit == FORCE_ON ||
1265 (inst->cfg.close_on_exit == AUTO && exitcode == 0))
1266 gtk_main_quit(); /* just go */
1267 if (inst->ldisc) {
1268 ldisc_free(inst->ldisc);
1269 inst->ldisc = NULL;
1270 }
1271 if (inst->back) {
1272 inst->back->free(inst->backhandle);
1273 inst->backhandle = NULL;
1274 inst->back = NULL;
1275 term_provide_resize_fn(inst->term, NULL, NULL);
1276 update_specials_menu(inst);
1277 }
1278 gtk_widget_set_sensitive(inst->restartitem, TRUE);
1279 }
1280
1281 gtk_idle_remove(inst->term_exit_idle_id);
1282 return TRUE;
1283 }
1284
1285 void notify_remote_exit(void *frontend)
1286 {
1287 struct gui_data *inst = (struct gui_data *)frontend;
1288
1289 inst->term_exit_idle_id = gtk_idle_add(idle_exit_func, inst);
1290 }
1291
1292 static gint timer_trigger(gpointer data)
1293 {
1294 long now = GPOINTER_TO_SIZE(data);
1295 long next;
1296 long ticks;
1297
1298 if (run_timers(now, &next)) {
1299 ticks = next - GETTICKCOUNT();
1300 timer_id = gtk_timeout_add(ticks > 0 ? ticks : 1, timer_trigger,
1301 GSIZE_TO_POINTER(next));
1302 }
1303
1304 /*
1305 * Never let a timer resume. If we need another one, we've
1306 * asked for it explicitly above.
1307 */
1308 return FALSE;
1309 }
1310
1311 void timer_change_notify(long next)
1312 {
1313 long ticks;
1314
1315 if (timer_id)
1316 gtk_timeout_remove(timer_id);
1317
1318 ticks = next - GETTICKCOUNT();
1319 if (ticks <= 0)
1320 ticks = 1; /* just in case */
1321
1322 timer_id = gtk_timeout_add(ticks, timer_trigger,
1323 GSIZE_TO_POINTER(next));
1324 }
1325
1326 void fd_input_func(gpointer data, gint sourcefd, GdkInputCondition condition)
1327 {
1328 /*
1329 * We must process exceptional notifications before ordinary
1330 * readability ones, or we may go straight past the urgent
1331 * marker.
1332 */
1333 if (condition & GDK_INPUT_EXCEPTION)
1334 select_result(sourcefd, 4);
1335 if (condition & GDK_INPUT_READ)
1336 select_result(sourcefd, 1);
1337 if (condition & GDK_INPUT_WRITE)
1338 select_result(sourcefd, 2);
1339 }
1340
1341 void destroy(GtkWidget *widget, gpointer data)
1342 {
1343 gtk_main_quit();
1344 }
1345
1346 gint focus_event(GtkWidget *widget, GdkEventFocus *event, gpointer data)
1347 {
1348 struct gui_data *inst = (struct gui_data *)data;
1349 term_set_focus(inst->term, event->in);
1350 term_update(inst->term);
1351 show_mouseptr(inst, 1);
1352 return FALSE;
1353 }
1354
1355 void set_busy_status(void *frontend, int status)
1356 {
1357 struct gui_data *inst = (struct gui_data *)frontend;
1358 inst->busy_status = status;
1359 update_mouseptr(inst);
1360 }
1361
1362 /*
1363 * set or clear the "raw mouse message" mode
1364 */
1365 void set_raw_mouse_mode(void *frontend, int activate)
1366 {
1367 struct gui_data *inst = (struct gui_data *)frontend;
1368 activate = activate && !inst->cfg.no_mouse_rep;
1369 send_raw_mouse = activate;
1370 update_mouseptr(inst);
1371 }
1372
1373 void request_resize(void *frontend, int w, int h)
1374 {
1375 struct gui_data *inst = (struct gui_data *)frontend;
1376 int large_x, large_y;
1377 int offset_x, offset_y;
1378 int area_x, area_y;
1379 GtkRequisition inner, outer;
1380
1381 /*
1382 * This is a heinous hack dreamed up by the gnome-terminal
1383 * people to get around a limitation in gtk. The problem is
1384 * that in order to set the size correctly we really need to be
1385 * calling gtk_window_resize - but that needs to know the size
1386 * of the _whole window_, not the drawing area. So what we do
1387 * is to set an artificially huge size request on the drawing
1388 * area, recompute the resulting size request on the window,
1389 * and look at the difference between the two. That gives us
1390 * the x and y offsets we need to translate drawing area size
1391 * into window size for real, and then we call
1392 * gtk_window_resize.
1393 */
1394
1395 /*
1396 * We start by retrieving the current size of the whole window.
1397 * Adding a bit to _that_ will give us a value we can use as a
1398 * bogus size request which guarantees to be bigger than the
1399 * current size of the drawing area.
1400 */
1401 get_window_pixels(inst, &large_x, &large_y);
1402 large_x += 32;
1403 large_y += 32;
1404
1405 #if GTK_CHECK_VERSION(2,0,0)
1406 gtk_widget_set_size_request(inst->area, large_x, large_y);
1407 #else
1408 gtk_widget_set_usize(inst->area, large_x, large_y);
1409 #endif
1410 gtk_widget_size_request(inst->area, &inner);
1411 gtk_widget_size_request(inst->window, &outer);
1412
1413 offset_x = outer.width - inner.width;
1414 offset_y = outer.height - inner.height;
1415
1416 area_x = inst->font_width * w + 2*inst->cfg.window_border;
1417 area_y = inst->font_height * h + 2*inst->cfg.window_border;
1418
1419 /*
1420 * Now we must set the size request on the drawing area back to
1421 * something sensible before we commit the real resize. Best
1422 * way to do this, I think, is to set it to what the size is
1423 * really going to end up being.
1424 */
1425 #if GTK_CHECK_VERSION(2,0,0)
1426 gtk_widget_set_size_request(inst->area, area_x, area_y);
1427 gtk_window_resize(GTK_WINDOW(inst->window),
1428 area_x + offset_x, area_y + offset_y);
1429 #else
1430 gtk_widget_set_usize(inst->area, area_x, area_y);
1431 gtk_drawing_area_size(GTK_DRAWING_AREA(inst->area), area_x, area_y);
1432 /*
1433 * I can no longer remember what this call to
1434 * gtk_container_dequeue_resize_handler is for. It was
1435 * introduced in r3092 with no comment, and the commit log
1436 * message was uninformative. I'm _guessing_ its purpose is to
1437 * prevent gratuitous resize processing on the window given
1438 * that we're about to resize it anyway, but I have no idea
1439 * why that's so incredibly vital.
1440 *
1441 * I've tried removing the call, and nothing seems to go
1442 * wrong. I've backtracked to r3092 and tried removing the
1443 * call there, and still nothing goes wrong. So I'm going to
1444 * adopt the working hypothesis that it's superfluous; I won't
1445 * actually remove it from the GTK 1.2 code, but I won't
1446 * attempt to replicate its functionality in the GTK 2 code
1447 * above.
1448 */
1449 gtk_container_dequeue_resize_handler(GTK_CONTAINER(inst->window));
1450 gdk_window_resize(inst->window->window,
1451 area_x + offset_x, area_y + offset_y);
1452 #endif
1453 }
1454
1455 static void real_palette_set(struct gui_data *inst, int n, int r, int g, int b)
1456 {
1457 gboolean success[1];
1458
1459 inst->cols[n].red = r * 0x0101;
1460 inst->cols[n].green = g * 0x0101;
1461 inst->cols[n].blue = b * 0x0101;
1462
1463 gdk_colormap_free_colors(inst->colmap, inst->cols + n, 1);
1464 gdk_colormap_alloc_colors(inst->colmap, inst->cols + n, 1,
1465 FALSE, TRUE, success);
1466 if (!success[0])
1467 g_error("%s: couldn't allocate colour %d (#%02x%02x%02x)\n", appname,
1468 n, r, g, b);
1469 }
1470
1471 void set_window_background(struct gui_data *inst)
1472 {
1473 if (inst->area && inst->area->window)
1474 gdk_window_set_background(inst->area->window, &inst->cols[258]);
1475 if (inst->window && inst->window->window)
1476 gdk_window_set_background(inst->window->window, &inst->cols[258]);
1477 }
1478
1479 void palette_set(void *frontend, int n, int r, int g, int b)
1480 {
1481 struct gui_data *inst = (struct gui_data *)frontend;
1482 if (n >= 16)
1483 n += 256 - 16;
1484 if (n > NALLCOLOURS)
1485 return;
1486 real_palette_set(inst, n, r, g, b);
1487 if (n == 258) {
1488 /* Default Background changed. Ensure space between text area and
1489 * window border is redrawn */
1490 set_window_background(inst);
1491 draw_backing_rect(inst);
1492 gtk_widget_queue_draw(inst->area);
1493 }
1494 }
1495
1496 void palette_reset(void *frontend)
1497 {
1498 struct gui_data *inst = (struct gui_data *)frontend;
1499 /* This maps colour indices in inst->cfg to those used in inst->cols. */
1500 static const int ww[] = {
1501 256, 257, 258, 259, 260, 261,
1502 0, 8, 1, 9, 2, 10, 3, 11,
1503 4, 12, 5, 13, 6, 14, 7, 15
1504 };
1505 gboolean success[NALLCOLOURS];
1506 int i;
1507
1508 assert(lenof(ww) == NCFGCOLOURS);
1509
1510 if (!inst->colmap) {
1511 inst->colmap = gdk_colormap_get_system();
1512 } else {
1513 gdk_colormap_free_colors(inst->colmap, inst->cols, NALLCOLOURS);
1514 }
1515
1516 for (i = 0; i < NCFGCOLOURS; i++) {
1517 inst->cols[ww[i]].red = inst->cfg.colours[i][0] * 0x0101;
1518 inst->cols[ww[i]].green = inst->cfg.colours[i][1] * 0x0101;
1519 inst->cols[ww[i]].blue = inst->cfg.colours[i][2] * 0x0101;
1520 }
1521
1522 for (i = 0; i < NEXTCOLOURS; i++) {
1523 if (i < 216) {
1524 int r = i / 36, g = (i / 6) % 6, b = i % 6;
1525 inst->cols[i+16].red = r ? r * 0x2828 + 0x3737 : 0;
1526 inst->cols[i+16].green = g ? g * 0x2828 + 0x3737 : 0;
1527 inst->cols[i+16].blue = b ? b * 0x2828 + 0x3737 : 0;
1528 } else {
1529 int shade = i - 216;
1530 shade = shade * 0x0a0a + 0x0808;
1531 inst->cols[i+16].red = inst->cols[i+16].green =
1532 inst->cols[i+16].blue = shade;
1533 }
1534 }
1535
1536 gdk_colormap_alloc_colors(inst->colmap, inst->cols, NALLCOLOURS,
1537 FALSE, TRUE, success);
1538 for (i = 0; i < NALLCOLOURS; i++) {
1539 if (!success[i])
1540 g_error("%s: couldn't allocate colour %d (#%02x%02x%02x)\n",
1541 appname, i, inst->cfg.colours[i][0],
1542 inst->cfg.colours[i][1], inst->cfg.colours[i][2]);
1543 }
1544
1545 /* Since Default Background may have changed, ensure that space
1546 * between text area and window border is refreshed. */
1547 set_window_background(inst);
1548 if (inst->area && inst->area->window) {
1549 draw_backing_rect(inst);
1550 gtk_widget_queue_draw(inst->area);
1551 }
1552 }
1553
1554 /* Ensure that all the cut buffers exist - according to the ICCCM, we must
1555 * do this before we start using cut buffers.
1556 */
1557 void init_cutbuffers()
1558 {
1559 unsigned char empty[] = "";
1560 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1561 XA_CUT_BUFFER0, XA_STRING, 8, PropModeAppend, empty, 0);
1562 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1563 XA_CUT_BUFFER1, XA_STRING, 8, PropModeAppend, empty, 0);
1564 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1565 XA_CUT_BUFFER2, XA_STRING, 8, PropModeAppend, empty, 0);
1566 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1567 XA_CUT_BUFFER3, XA_STRING, 8, PropModeAppend, empty, 0);
1568 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1569 XA_CUT_BUFFER4, XA_STRING, 8, PropModeAppend, empty, 0);
1570 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1571 XA_CUT_BUFFER5, XA_STRING, 8, PropModeAppend, empty, 0);
1572 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1573 XA_CUT_BUFFER6, XA_STRING, 8, PropModeAppend, empty, 0);
1574 XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1575 XA_CUT_BUFFER7, XA_STRING, 8, PropModeAppend, empty, 0);
1576 }
1577
1578 /* Store the data in a cut-buffer. */
1579 void store_cutbuffer(char * ptr, int len)
1580 {
1581 /* ICCCM says we must rotate the buffers before storing to buffer 0. */
1582 XRotateBuffers(GDK_DISPLAY(), 1);
1583 XStoreBytes(GDK_DISPLAY(), ptr, len);
1584 }
1585
1586 /* Retrieve data from a cut-buffer.
1587 * Returned data needs to be freed with XFree().
1588 */
1589 char * retrieve_cutbuffer(int * nbytes)
1590 {
1591 char * ptr;
1592 ptr = XFetchBytes(GDK_DISPLAY(), nbytes);
1593 if (*nbytes <= 0 && ptr != 0) {
1594 XFree(ptr);
1595 ptr = 0;
1596 }
1597 return ptr;
1598 }
1599
1600 void write_clip(void *frontend, wchar_t * data, int *attr, int len, int must_deselect)
1601 {
1602 struct gui_data *inst = (struct gui_data *)frontend;
1603 if (inst->pasteout_data)
1604 sfree(inst->pasteout_data);
1605 if (inst->pasteout_data_ctext)
1606 sfree(inst->pasteout_data_ctext);
1607 if (inst->pasteout_data_utf8)
1608 sfree(inst->pasteout_data_utf8);
1609
1610 /*
1611 * Set up UTF-8 and compound text paste data. This only happens
1612 * if we aren't in direct-to-font mode using the D800 hack.
1613 */
1614 if (!inst->direct_to_font) {
1615 wchar_t *tmp = data;
1616 int tmplen = len;
1617 XTextProperty tp;
1618 char *list[1];
1619
1620 inst->pasteout_data_utf8 = snewn(len*6, char);
1621 inst->pasteout_data_utf8_len = len*6;
1622 inst->pasteout_data_utf8_len =
1623 charset_from_unicode(&tmp, &tmplen, inst->pasteout_data_utf8,
1624 inst->pasteout_data_utf8_len,
1625 CS_UTF8, NULL, NULL, 0);
1626 if (inst->pasteout_data_utf8_len == 0) {
1627 sfree(inst->pasteout_data_utf8);
1628 inst->pasteout_data_utf8 = NULL;
1629 } else {
1630 inst->pasteout_data_utf8 =
1631 sresize(inst->pasteout_data_utf8,
1632 inst->pasteout_data_utf8_len + 1, char);
1633 inst->pasteout_data_utf8[inst->pasteout_data_utf8_len] = '\0';
1634 }
1635
1636 /*
1637 * Now let Xlib convert our UTF-8 data into compound text.
1638 */
1639 list[0] = inst->pasteout_data_utf8;
1640 if (Xutf8TextListToTextProperty(GDK_DISPLAY(), list, 1,
1641 XCompoundTextStyle, &tp) == 0) {
1642 inst->pasteout_data_ctext = snewn(tp.nitems+1, char);
1643 memcpy(inst->pasteout_data_ctext, tp.value, tp.nitems);
1644 inst->pasteout_data_ctext_len = tp.nitems;
1645 XFree(tp.value);
1646 } else {
1647 inst->pasteout_data_ctext = NULL;
1648 inst->pasteout_data_ctext_len = 0;
1649 }
1650 } else {
1651 inst->pasteout_data_utf8 = NULL;
1652 inst->pasteout_data_utf8_len = 0;
1653 inst->pasteout_data_ctext = NULL;
1654 inst->pasteout_data_ctext_len = 0;
1655 }
1656
1657 inst->pasteout_data = snewn(len*6, char);
1658 inst->pasteout_data_len = len*6;
1659 inst->pasteout_data_len = wc_to_mb(inst->ucsdata.line_codepage, 0,
1660 data, len, inst->pasteout_data,
1661 inst->pasteout_data_len,
1662 NULL, NULL, NULL);
1663 if (inst->pasteout_data_len == 0) {
1664 sfree(inst->pasteout_data);
1665 inst->pasteout_data = NULL;
1666 } else {
1667 inst->pasteout_data =
1668 sresize(inst->pasteout_data, inst->pasteout_data_len, char);
1669 }
1670
1671 store_cutbuffer(inst->pasteout_data, inst->pasteout_data_len);
1672
1673 if (gtk_selection_owner_set(inst->area, GDK_SELECTION_PRIMARY,
1674 inst->input_event_time)) {
1675 #if GTK_CHECK_VERSION(2,0,0)
1676 gtk_selection_clear_targets(inst->area, GDK_SELECTION_PRIMARY);
1677 #endif
1678 gtk_selection_add_target(inst->area, GDK_SELECTION_PRIMARY,
1679 GDK_SELECTION_TYPE_STRING, 1);
1680 if (inst->pasteout_data_ctext)
1681 gtk_selection_add_target(inst->area, GDK_SELECTION_PRIMARY,
1682 compound_text_atom, 1);
1683 if (inst->pasteout_data_utf8)
1684 gtk_selection_add_target(inst->area, GDK_SELECTION_PRIMARY,
1685 utf8_string_atom, 1);
1686 }
1687
1688 if (must_deselect)
1689 term_deselect(inst->term);
1690 }
1691
1692 void selection_get(GtkWidget *widget, GtkSelectionData *seldata,
1693 guint info, guint time_stamp, gpointer data)
1694 {
1695 struct gui_data *inst = (struct gui_data *)data;
1696 if (seldata->target == utf8_string_atom)
1697 gtk_selection_data_set(seldata, seldata->target, 8,
1698 (unsigned char *)inst->pasteout_data_utf8,
1699 inst->pasteout_data_utf8_len);
1700 else if (seldata->target == compound_text_atom)
1701 gtk_selection_data_set(seldata, seldata->target, 8,
1702 (unsigned char *)inst->pasteout_data_ctext,
1703 inst->pasteout_data_ctext_len);
1704 else
1705 gtk_selection_data_set(seldata, seldata->target, 8,
1706 (unsigned char *)inst->pasteout_data,
1707 inst->pasteout_data_len);
1708 }
1709
1710 gint selection_clear(GtkWidget *widget, GdkEventSelection *seldata,
1711 gpointer data)
1712 {
1713 struct gui_data *inst = (struct gui_data *)data;
1714
1715 term_deselect(inst->term);
1716 if (inst->pasteout_data)
1717 sfree(inst->pasteout_data);
1718 if (inst->pasteout_data_ctext)
1719 sfree(inst->pasteout_data_ctext);
1720 if (inst->pasteout_data_utf8)
1721 sfree(inst->pasteout_data_utf8);
1722 inst->pasteout_data = NULL;
1723 inst->pasteout_data_len = 0;
1724 inst->pasteout_data_ctext = NULL;
1725 inst->pasteout_data_ctext_len = 0;
1726 inst->pasteout_data_utf8 = NULL;
1727 inst->pasteout_data_utf8_len = 0;
1728 return TRUE;
1729 }
1730
1731 void request_paste(void *frontend)
1732 {
1733 struct gui_data *inst = (struct gui_data *)frontend;
1734 /*
1735 * In Unix, pasting is asynchronous: all we can do at the
1736 * moment is to call gtk_selection_convert(), and when the data
1737 * comes back _then_ we can call term_do_paste().
1738 */
1739
1740 if (!inst->direct_to_font) {
1741 /*
1742 * First we attempt to retrieve the selection as a UTF-8
1743 * string (which we will convert to the correct code page
1744 * before sending to the session, of course). If that
1745 * fails, selection_received() will be informed and will
1746 * fall back to an ordinary string.
1747 */
1748 gtk_selection_convert(inst->area, GDK_SELECTION_PRIMARY,
1749 utf8_string_atom,
1750 inst->input_event_time);
1751 } else {
1752 /*
1753 * If we're in direct-to-font mode, we disable UTF-8
1754 * pasting, and go straight to ordinary string data.
1755 */
1756 gtk_selection_convert(inst->area, GDK_SELECTION_PRIMARY,
1757 GDK_SELECTION_TYPE_STRING,
1758 inst->input_event_time);
1759 }
1760 }
1761
1762 gint idle_paste_func(gpointer data); /* forward ref */
1763
1764 void selection_received(GtkWidget *widget, GtkSelectionData *seldata,
1765 guint time, gpointer data)
1766 {
1767 struct gui_data *inst = (struct gui_data *)data;
1768 XTextProperty tp;
1769 char **list;
1770 char *text;
1771 int length, count, ret;
1772 int free_list_required = 0;
1773 int free_required = 0;
1774 int charset;
1775
1776 if (seldata->target == utf8_string_atom && seldata->length <= 0) {
1777 /*
1778 * Failed to get a UTF-8 selection string. Try compound
1779 * text next.
1780 */
1781 gtk_selection_convert(inst->area, GDK_SELECTION_PRIMARY,
1782 compound_text_atom,
1783 inst->input_event_time);
1784 return;
1785 }
1786
1787 if (seldata->target == compound_text_atom && seldata->length <= 0) {
1788 /*
1789 * Failed to get UTF-8 or compound text. Try an ordinary
1790 * string.
1791 */
1792 gtk_selection_convert(inst->area, GDK_SELECTION_PRIMARY,
1793 GDK_SELECTION_TYPE_STRING,
1794 inst->input_event_time);
1795 return;
1796 }
1797
1798 /*
1799 * If we have data, but it's not of a type we can deal with,
1800 * we have to ignore the data.
1801 */
1802 if (seldata->length > 0 &&
1803 seldata->type != GDK_SELECTION_TYPE_STRING &&
1804 seldata->type != compound_text_atom &&
1805 seldata->type != utf8_string_atom)
1806 return;
1807
1808 /*
1809 * If we have no data, try looking in a cut buffer.
1810 */
1811 if (seldata->length <= 0) {
1812 text = retrieve_cutbuffer(&length);
1813 if (length == 0)
1814 return;
1815 /* Xterm is rumoured to expect Latin-1, though I havn't checked the
1816 * source, so use that as a de-facto standard. */
1817 charset = CS_ISO8859_1;
1818 free_required = 1;
1819 } else {
1820 /*
1821 * Convert COMPOUND_TEXT into UTF-8.
1822 */
1823 if (seldata->type == compound_text_atom) {
1824 tp.value = seldata->data;
1825 tp.encoding = (Atom) seldata->type;
1826 tp.format = seldata->format;
1827 tp.nitems = seldata->length;
1828 ret = Xutf8TextPropertyToTextList(GDK_DISPLAY(), &tp,
1829 &list, &count);
1830 if (ret != 0 || count != 1) {
1831 /*
1832 * Compound text failed; fall back to STRING.
1833 */
1834 gtk_selection_convert(inst->area, GDK_SELECTION_PRIMARY,
1835 GDK_SELECTION_TYPE_STRING,
1836 inst->input_event_time);
1837 return;
1838 }
1839 text = list[0];
1840 length = strlen(list[0]);
1841 charset = CS_UTF8;
1842 free_list_required = 1;
1843 } else {
1844 text = (char *)seldata->data;
1845 length = seldata->length;
1846 charset = (seldata->type == utf8_string_atom ?
1847 CS_UTF8 : inst->ucsdata.line_codepage);
1848 }
1849 }
1850
1851 if (inst->pastein_data)
1852 sfree(inst->pastein_data);
1853
1854 inst->pastein_data = snewn(length, wchar_t);
1855 inst->pastein_data_len = length;
1856 inst->pastein_data_len =
1857 mb_to_wc(charset, 0, text, length,
1858 inst->pastein_data, inst->pastein_data_len);
1859
1860 term_do_paste(inst->term);
1861
1862 if (term_paste_pending(inst->term))
1863 inst->term_paste_idle_id = gtk_idle_add(idle_paste_func, inst);
1864
1865 if (free_list_required)
1866 XFreeStringList(list);
1867 if (free_required)
1868 XFree(text);
1869 }
1870
1871 gint idle_paste_func(gpointer data)
1872 {
1873 struct gui_data *inst = (struct gui_data *)data;
1874
1875 if (term_paste_pending(inst->term))
1876 term_paste(inst->term);
1877 else
1878 gtk_idle_remove(inst->term_paste_idle_id);
1879
1880 return TRUE;
1881 }
1882
1883
1884 void get_clip(void *frontend, wchar_t ** p, int *len)
1885 {
1886 struct gui_data *inst = (struct gui_data *)frontend;
1887
1888 if (p) {
1889 *p = inst->pastein_data;
1890 *len = inst->pastein_data_len;
1891 }
1892 }
1893
1894 static void set_window_titles(struct gui_data *inst)
1895 {
1896 /*
1897 * We must always call set_icon_name after calling set_title,
1898 * since set_title will write both names. Irritating, but such
1899 * is life.
1900 */
1901 gtk_window_set_title(GTK_WINDOW(inst->window), inst->wintitle);
1902 if (!inst->cfg.win_name_always)
1903 gdk_window_set_icon_name(inst->window->window, inst->icontitle);
1904 }
1905
1906 void set_title(void *frontend, char *title)
1907 {
1908 struct gui_data *inst = (struct gui_data *)frontend;
1909 strncpy(inst->wintitle, title, lenof(inst->wintitle));
1910 inst->wintitle[lenof(inst->wintitle)-1] = '\0';
1911 set_window_titles(inst);
1912 }
1913
1914 void set_icon(void *frontend, char *title)
1915 {
1916 struct gui_data *inst = (struct gui_data *)frontend;
1917 strncpy(inst->icontitle, title, lenof(inst->icontitle));
1918 inst->icontitle[lenof(inst->icontitle)-1] = '\0';
1919 set_window_titles(inst);
1920 }
1921
1922 void set_sbar(void *frontend, int total, int start, int page)
1923 {
1924 struct gui_data *inst = (struct gui_data *)frontend;
1925 if (!inst->cfg.scrollbar)
1926 return;
1927 inst->sbar_adjust->lower = 0;
1928 inst->sbar_adjust->upper = total;
1929 inst->sbar_adjust->value = start;
1930 inst->sbar_adjust->page_size = page;
1931 inst->sbar_adjust->step_increment = 1;
1932 inst->sbar_adjust->page_increment = page/2;
1933 inst->ignore_sbar = TRUE;
1934 gtk_adjustment_changed(inst->sbar_adjust);
1935 inst->ignore_sbar = FALSE;
1936 }
1937
1938 void scrollbar_moved(GtkAdjustment *adj, gpointer data)
1939 {
1940 struct gui_data *inst = (struct gui_data *)data;
1941
1942 if (!inst->cfg.scrollbar)
1943 return;
1944 if (!inst->ignore_sbar)
1945 term_scroll(inst->term, 1, (int)adj->value);
1946 }
1947
1948 void sys_cursor(void *frontend, int x, int y)
1949 {
1950 /*
1951 * This is meaningless under X.
1952 */
1953 }
1954
1955 /*
1956 * This is still called when mode==BELL_VISUAL, even though the
1957 * visual bell is handled entirely within terminal.c, because we
1958 * may want to perform additional actions on any kind of bell (for
1959 * example, taskbar flashing in Windows).
1960 */
1961 void do_beep(void *frontend, int mode)
1962 {
1963 if (mode == BELL_DEFAULT)
1964 gdk_beep();
1965 }
1966
1967 int char_width(Context ctx, int uc)
1968 {
1969 /*
1970 * Under X, any fixed-width font really _is_ fixed-width.
1971 * Double-width characters will be dealt with using a separate
1972 * font. For the moment we can simply return 1.
1973 *
1974 * FIXME: but is that also true of Pango?
1975 */
1976 return 1;
1977 }
1978
1979 Context get_ctx(void *frontend)
1980 {
1981 struct gui_data *inst = (struct gui_data *)frontend;
1982 struct draw_ctx *dctx;
1983
1984 if (!inst->area->window)
1985 return NULL;
1986
1987 dctx = snew(struct draw_ctx);
1988 dctx->inst = inst;
1989 dctx->gc = gdk_gc_new(inst->area->window);
1990 return dctx;
1991 }
1992
1993 void free_ctx(Context ctx)
1994 {
1995 struct draw_ctx *dctx = (struct draw_ctx *)ctx;
1996 /* struct gui_data *inst = dctx->inst; */
1997 GdkGC *gc = dctx->gc;
1998 gdk_gc_unref(gc);
1999 sfree(dctx);
2000 }
2001
2002 /*
2003 * Draw a line of text in the window, at given character
2004 * coordinates, in given attributes.
2005 *
2006 * We are allowed to fiddle with the contents of `text'.
2007 */
2008 void do_text_internal(Context ctx, int x, int y, wchar_t *text, int len,
2009 unsigned long attr, int lattr)
2010 {
2011 struct draw_ctx *dctx = (struct draw_ctx *)ctx;
2012 struct gui_data *inst = dctx->inst;
2013 GdkGC *gc = dctx->gc;
2014 int ncombining, combining;
2015 int nfg, nbg, t, fontid, shadow, rlen, widefactor, bold;
2016 int monochrome = gtk_widget_get_visual(inst->area)->depth == 1;
2017
2018 if (attr & TATTR_COMBINING) {
2019 ncombining = len;
2020 len = 1;
2021 } else
2022 ncombining = 1;
2023
2024 nfg = ((monochrome ? ATTR_DEFFG : (attr & ATTR_FGMASK)) >> ATTR_FGSHIFT);
2025 nbg = ((monochrome ? ATTR_DEFBG : (attr & ATTR_BGMASK)) >> ATTR_BGSHIFT);
2026 if (!!(attr & ATTR_REVERSE) ^ (monochrome && (attr & TATTR_ACTCURS))) {
2027 t = nfg;
2028 nfg = nbg;
2029 nbg = t;
2030 }
2031 if (inst->cfg.bold_colour && (attr & ATTR_BOLD)) {
2032 if (nfg < 16) nfg |= 8;
2033 else if (nfg >= 256) nfg |= 1;
2034 }
2035 if (inst->cfg.bold_colour && (attr & ATTR_BLINK)) {
2036 if (nbg < 16) nbg |= 8;
2037 else if (nbg >= 256) nbg |= 1;
2038 }
2039 if ((attr & TATTR_ACTCURS) && !monochrome) {
2040 nfg = 260;
2041 nbg = 261;
2042 }
2043
2044 fontid = shadow = 0;
2045
2046 if (attr & ATTR_WIDE) {
2047 widefactor = 2;
2048 fontid |= 2;
2049 } else {
2050 widefactor = 1;
2051 }
2052
2053 if ((attr & ATTR_BOLD) && !inst->cfg.bold_colour) {
2054 bold = 1;
2055 fontid |= 1;
2056 } else {
2057 bold = 0;
2058 }
2059
2060 if (!inst->fonts[fontid]) {
2061 int i;
2062 /*
2063 * Fall back through font ids with subsets of this one's
2064 * set bits, in order.
2065 */
2066 for (i = fontid; i-- > 0 ;) {
2067 if (i & ~fontid)
2068 continue; /* some other bit is set */
2069 if (inst->fonts[i]) {
2070 fontid = i;
2071 break;
2072 }
2073 }
2074 assert(inst->fonts[fontid]); /* we should at least have hit zero */
2075 }
2076
2077 if ((lattr & LATTR_MODE) != LATTR_NORM) {
2078 x *= 2;
2079 if (x >= inst->term->cols)
2080 return;
2081 if (x + len*2*widefactor > inst->term->cols)
2082 len = (inst->term->cols-x)/2/widefactor;/* trim to LH half */
2083 rlen = len * 2;
2084 } else
2085 rlen = len;
2086
2087 {
2088 GdkRectangle r;
2089
2090 r.x = x*inst->font_width+inst->cfg.window_border;
2091 r.y = y*inst->font_height+inst->cfg.window_border;
2092 r.width = rlen*widefactor*inst->font_width;
2093 r.height = inst->font_height;
2094 gdk_gc_set_clip_rectangle(gc, &r);
2095 }
2096
2097 gdk_gc_set_foreground(gc, &inst->cols[nbg]);
2098 gdk_draw_rectangle(inst->pixmap, gc, 1,
2099 x*inst->font_width+inst->cfg.window_border,
2100 y*inst->font_height+inst->cfg.window_border,
2101 rlen*widefactor*inst->font_width, inst->font_height);
2102
2103 gdk_gc_set_foreground(gc, &inst->cols[nfg]);
2104 {
2105 gchar *gcs;
2106
2107 /*
2108 * FIXME: this length is hardwired on the assumption that
2109 * conversions from wide to multibyte characters will
2110 * never generate more than 10 bytes for a single wide
2111 * character.
2112 */
2113 gcs = snewn(len*10+1, gchar);
2114
2115 for (combining = 0; combining < ncombining; combining++) {
2116 int mblen = wc_to_mb(inst->fonts[fontid]->real_charset, 0,
2117 text + combining, len, gcs, len*10+1, ".",
2118 NULL, NULL);
2119 unifont_draw_text(inst->pixmap, gc, inst->fonts[fontid],
2120 x*inst->font_width+inst->cfg.window_border,
2121 y*inst->font_height+inst->cfg.window_border+inst->fonts[0]->ascent,
2122 gcs, mblen, widefactor > 1, bold, inst->font_width);
2123 }
2124
2125 sfree(gcs);
2126 }
2127
2128 if (attr & ATTR_UNDER) {
2129 int uheight = inst->fonts[0]->ascent + 1;
2130 if (uheight >= inst->font_height)
2131 uheight = inst->font_height - 1;
2132 gdk_draw_line(inst->pixmap, gc, x*inst->font_width+inst->cfg.window_border,
2133 y*inst->font_height + uheight + inst->cfg.window_border,
2134 (x+len)*widefactor*inst->font_width-1+inst->cfg.window_border,
2135 y*inst->font_height + uheight + inst->cfg.window_border);
2136 }
2137
2138 if ((lattr & LATTR_MODE) != LATTR_NORM) {
2139 /*
2140 * I can't find any plausible StretchBlt equivalent in the
2141 * X server, so I'm going to do this the slow and painful
2142 * way. This will involve repeated calls to
2143 * gdk_draw_pixmap() to stretch the text horizontally. It's
2144 * O(N^2) in time and O(N) in network bandwidth, but you
2145 * try thinking of a better way. :-(
2146 */
2147 int i;
2148 for (i = 0; i < len * widefactor * inst->font_width; i++) {
2149 gdk_draw_pixmap(inst->pixmap, gc, inst->pixmap,
2150 x*inst->font_width+inst->cfg.window_border + 2*i,
2151 y*inst->font_height+inst->cfg.window_border,
2152 x*inst->font_width+inst->cfg.window_border + 2*i+1,
2153 y*inst->font_height+inst->cfg.window_border,
2154 len * widefactor * inst->font_width - i, inst->font_height);
2155 }
2156 len *= 2;
2157 if ((lattr & LATTR_MODE) != LATTR_WIDE) {
2158 int dt, db;
2159 /* Now stretch vertically, in the same way. */
2160 if ((lattr & LATTR_MODE) == LATTR_BOT)
2161 dt = 0, db = 1;
2162 else
2163 dt = 1, db = 0;
2164 for (i = 0; i < inst->font_height; i+=2) {
2165 gdk_draw_pixmap(inst->pixmap, gc, inst->pixmap,
2166 x*inst->font_width+inst->cfg.window_border,
2167 y*inst->font_height+inst->cfg.window_border+dt*i+db,
2168 x*inst->font_width+inst->cfg.window_border,
2169 y*inst->font_height+inst->cfg.window_border+dt*(i+1),
2170 len * widefactor * inst->font_width, inst->font_height-i-1);
2171 }
2172 }
2173 }
2174 }
2175
2176 void do_text(Context ctx, int x, int y, wchar_t *text, int len,
2177 unsigned long attr, int lattr)
2178 {
2179 struct draw_ctx *dctx = (struct draw_ctx *)ctx;
2180 struct gui_data *inst = dctx->inst;
2181 GdkGC *gc = dctx->gc;
2182 int widefactor;
2183
2184 do_text_internal(ctx, x, y, text, len, attr, lattr);
2185
2186 if (attr & ATTR_WIDE) {
2187 widefactor = 2;
2188 } else {
2189 widefactor = 1;
2190 }
2191
2192 if ((lattr & LATTR_MODE) != LATTR_NORM) {
2193 x *= 2;
2194 if (x >= inst->term->cols)
2195 return;
2196 if (x + len*2*widefactor > inst->term->cols)
2197 len = (inst->term->cols-x)/2/widefactor;/* trim to LH half */
2198 len *= 2;
2199 }
2200
2201 gdk_draw_pixmap(inst->area->window, gc, inst->pixmap,
2202 x*inst->font_width+inst->cfg.window_border,
2203 y*inst->font_height+inst->cfg.window_border,
2204 x*inst->font_width+inst->cfg.window_border,
2205 y*inst->font_height+inst->cfg.window_border,
2206 len*widefactor*inst->font_width, inst->font_height);
2207 }
2208
2209 void do_cursor(Context ctx, int x, int y, wchar_t *text, int len,
2210 unsigned long attr, int lattr)
2211 {
2212 struct draw_ctx *dctx = (struct draw_ctx *)ctx;
2213 struct gui_data *inst = dctx->inst;
2214 GdkGC *gc = dctx->gc;
2215
2216 int active, passive, widefactor;
2217
2218 if (attr & TATTR_PASCURS) {
2219 attr &= ~TATTR_PASCURS;
2220 passive = 1;
2221 } else
2222 passive = 0;
2223 if ((attr & TATTR_ACTCURS) && inst->cfg.cursor_type != 0) {
2224 attr &= ~TATTR_ACTCURS;
2225 active = 1;
2226 } else
2227 active = 0;
2228 do_text_internal(ctx, x, y, text, len, attr, lattr);
2229
2230 if (attr & TATTR_COMBINING)
2231 len = 1;
2232
2233 if (attr & ATTR_WIDE) {
2234 widefactor = 2;
2235 } else {
2236 widefactor = 1;
2237 }
2238
2239 if ((lattr & LATTR_MODE) != LATTR_NORM) {
2240 x *= 2;
2241 if (x >= inst->term->cols)
2242 return;
2243 if (x + len*2*widefactor > inst->term->cols)
2244 len = (inst->term->cols-x)/2/widefactor;/* trim to LH half */
2245 len *= 2;
2246 }
2247
2248 if (inst->cfg.cursor_type == 0) {
2249 /*
2250 * An active block cursor will already have been done by
2251 * the above do_text call, so we only need to do anything
2252 * if it's passive.
2253 */
2254 if (passive) {
2255 gdk_gc_set_foreground(gc, &inst->cols[261]);
2256 gdk_draw_rectangle(inst->pixmap, gc, 0,
2257 x*inst->font_width+inst->cfg.window_border,
2258 y*inst->font_height+inst->cfg.window_border,
2259 len*widefactor*inst->font_width-1, inst->font_height-1);
2260 }
2261 } else {
2262 int uheight;
2263 int startx, starty, dx, dy, length, i;
2264
2265 int char_width;
2266
2267 if ((attr & ATTR_WIDE) || (lattr & LATTR_MODE) != LATTR_NORM)
2268 char_width = 2*inst->font_width;
2269 else
2270 char_width = inst->font_width;
2271
2272 if (inst->cfg.cursor_type == 1) {
2273 uheight = inst->fonts[0]->ascent + 1;
2274 if (uheight >= inst->font_height)
2275 uheight = inst->font_height - 1;
2276
2277 startx = x * inst->font_width + inst->cfg.window_border;
2278 starty = y * inst->font_height + inst->cfg.window_border + uheight;
2279 dx = 1;
2280 dy = 0;
2281 length = len * widefactor * char_width;
2282 } else {
2283 int xadjust = 0;
2284 if (attr & TATTR_RIGHTCURS)
2285 xadjust = char_width - 1;
2286 startx = x * inst->font_width + inst->cfg.window_border + xadjust;
2287 starty = y * inst->font_height + inst->cfg.window_border;
2288 dx = 0;
2289 dy = 1;
2290 length = inst->font_height;
2291 }
2292
2293 gdk_gc_set_foreground(gc, &inst->cols[261]);
2294 if (passive) {
2295 for (i = 0; i < length; i++) {
2296 if (i % 2 == 0) {
2297 gdk_draw_point(inst->pixmap, gc, startx, starty);
2298 }
2299 startx += dx;
2300 starty += dy;
2301 }
2302 } else if (active) {
2303 gdk_draw_line(inst->pixmap, gc, startx, starty,
2304 startx + (length-1) * dx, starty + (length-1) * dy);
2305 } /* else no cursor (e.g., blinked off) */
2306 }
2307
2308 gdk_draw_pixmap(inst->area->window, gc, inst->pixmap,
2309 x*inst->font_width+inst->cfg.window_border,
2310 y*inst->font_height+inst->cfg.window_border,
2311 x*inst->font_width+inst->cfg.window_border,
2312 y*inst->font_height+inst->cfg.window_border,
2313 len*widefactor*inst->font_width, inst->font_height);
2314 }
2315
2316 GdkCursor *make_mouse_ptr(struct gui_data *inst, int cursor_val)
2317 {
2318 /*
2319 * Truly hideous hack: GTK doesn't allow us to set the mouse
2320 * cursor foreground and background colours unless we've _also_
2321 * created our own cursor from bitmaps. Therefore, I need to
2322 * load the `cursor' font and draw glyphs from it on to
2323 * pixmaps, in order to construct my cursors with the fg and bg
2324 * I want. This is a gross hack, but it's more self-contained
2325 * than linking in Xlib to find the X window handle to
2326 * inst->area and calling XRecolorCursor, and it's more
2327 * futureproof than hard-coding the shapes as bitmap arrays.
2328 */
2329 static GdkFont *cursor_font = NULL;
2330 GdkPixmap *source, *mask;
2331 GdkGC *gc;
2332 GdkColor cfg = { 0, 65535, 65535, 65535 };
2333 GdkColor cbg = { 0, 0, 0, 0 };
2334 GdkColor dfg = { 1, 65535, 65535, 65535 };
2335 GdkColor dbg = { 0, 0, 0, 0 };
2336 GdkCursor *ret;
2337 gchar text[2];
2338 gint lb, rb, wid, asc, desc, w, h, x, y;
2339
2340 if (cursor_val == -2) {
2341 gdk_font_unref(cursor_font);
2342 return NULL;
2343 }
2344
2345 if (cursor_val >= 0 && !cursor_font) {
2346 cursor_font = gdk_font_load("cursor");
2347 if (cursor_font)
2348 gdk_font_ref(cursor_font);
2349 }
2350
2351 /*
2352 * Get the text extent of the cursor in question. We use the
2353 * mask character for this, because it's typically slightly
2354 * bigger than the main character.
2355 */
2356 if (cursor_val >= 0) {
2357 text[1] = '\0';
2358 text[0] = (char)cursor_val + 1;
2359 gdk_string_extents(cursor_font, text, &lb, &rb, &wid, &asc, &desc);
2360 w = rb-lb; h = asc+desc; x = -lb; y = asc;
2361 } else {
2362 w = h = 1;
2363 x = y = 0;
2364 }
2365
2366 source = gdk_pixmap_new(NULL, w, h, 1);
2367 mask = gdk_pixmap_new(NULL, w, h, 1);
2368
2369 /*
2370 * Draw the mask character on the mask pixmap.
2371 */
2372 gc = gdk_gc_new(mask);
2373 gdk_gc_set_foreground(gc, &dbg);
2374 gdk_draw_rectangle(mask, gc, 1, 0, 0, w, h);
2375 if (cursor_val >= 0) {
2376 text[1] = '\0';
2377 text[0] = (char)cursor_val + 1;
2378 gdk_gc_set_foreground(gc, &dfg);
2379 gdk_draw_text(mask, cursor_font, gc, x, y, text, 1);
2380 }
2381 gdk_gc_unref(gc);
2382
2383 /*
2384 * Draw the main character on the source pixmap.
2385 */
2386 gc = gdk_gc_new(source);
2387 gdk_gc_set_foreground(gc, &dbg);
2388 gdk_draw_rectangle(source, gc, 1, 0, 0, w, h);
2389 if (cursor_val >= 0) {
2390 text[1] = '\0';
2391 text[0] = (char)cursor_val;
2392 gdk_gc_set_foreground(gc, &dfg);
2393 gdk_draw_text(source, cursor_font, gc, x, y, text, 1);
2394 }
2395 gdk_gc_unref(gc);
2396
2397 /*
2398 * Create the cursor.
2399 */
2400 ret = gdk_cursor_new_from_pixmap(source, mask, &cfg, &cbg, x, y);
2401
2402 /*
2403 * Clean up.
2404 */
2405 gdk_pixmap_unref(source);
2406 gdk_pixmap_unref(mask);
2407
2408 return ret;
2409 }
2410
2411 void modalfatalbox(char *p, ...)
2412 {
2413 va_list ap;
2414 fprintf(stderr, "FATAL ERROR: ");
2415 va_start(ap, p);
2416 vfprintf(stderr, p, ap);
2417 va_end(ap);
2418 fputc('\n', stderr);
2419 exit(1);
2420 }
2421
2422 void cmdline_error(char *p, ...)
2423 {
2424 va_list ap;
2425 fprintf(stderr, "%s: ", appname);
2426 va_start(ap, p);
2427 vfprintf(stderr, p, ap);
2428 va_end(ap);
2429 fputc('\n', stderr);
2430 exit(1);
2431 }
2432
2433 char *get_x_display(void *frontend)
2434 {
2435 return gdk_get_display();
2436 }
2437
2438 long get_windowid(void *frontend)
2439 {
2440 struct gui_data *inst = (struct gui_data *)frontend;
2441 return (long)GDK_WINDOW_XWINDOW(inst->area->window);
2442 }
2443
2444 static void help(FILE *fp) {
2445 if(fprintf(fp,
2446 "pterm option summary:\n"
2447 "\n"
2448 " --display DISPLAY Specify X display to use (note '--')\n"
2449 " -name PREFIX Prefix when looking up resources (default: pterm)\n"
2450 " -fn FONT Normal text font\n"
2451 " -fb FONT Bold text font\n"
2452 " -geometry GEOMETRY Position and size of window (size in characters)\n"
2453 " -sl LINES Number of lines of scrollback\n"
2454 " -fg COLOUR, -bg COLOUR Foreground/background colour\n"
2455 " -bfg COLOUR, -bbg COLOUR Foreground/background bold colour\n"
2456 " -cfg COLOUR, -bfg COLOUR Foreground/background cursor colour\n"
2457 " -T TITLE Window title\n"
2458 " -ut, +ut Do(default) or do not update utmp\n"
2459 " -ls, +ls Do(default) or do not make shell a login shell\n"
2460 " -sb, +sb Do(default) or do not display a scrollbar\n"
2461 " -log PATH Log all output to a file\n"
2462 " -nethack Map numeric keypad to hjklyubn direction keys\n"
2463 " -xrm RESOURCE-STRING Set an X resource\n"
2464 " -e COMMAND [ARGS...] Execute command (consumes all remaining args)\n"
2465 ) < 0 || fflush(fp) < 0) {
2466 perror("output error");
2467 exit(1);
2468 }
2469 }
2470
2471 int do_cmdline(int argc, char **argv, int do_everything, int *allow_launch,
2472 struct gui_data *inst, Config *cfg)
2473 {
2474 int err = 0;
2475 char *val;
2476
2477 /*
2478 * Macros to make argument handling easier. Note that because
2479 * they need to call `continue', they cannot be contained in
2480 * the usual do {...} while (0) wrapper to make them
2481 * syntactically single statements; hence it is not legal to
2482 * use one of these macros as an unbraced statement between
2483 * `if' and `else'.
2484 */
2485 #define EXPECTS_ARG { \
2486 if (--argc <= 0) { \
2487 err = 1; \
2488 fprintf(stderr, "%s: %s expects an argument\n", appname, p); \
2489 continue; \
2490 } else \
2491 val = *++argv; \
2492 }
2493 #define SECOND_PASS_ONLY { if (!do_everything) continue; }
2494
2495 while (--argc > 0) {
2496 char *p = *++argv;
2497 int ret;
2498
2499 /*
2500 * Shameless cheating. Debian requires all X terminal
2501 * emulators to support `-T title'; but
2502 * cmdline_process_param will eat -T (it means no-pty) and
2503 * complain that pterm doesn't support it. So, in pterm
2504 * only, we convert -T into -title.
2505 */
2506 if ((cmdline_tooltype & TOOLTYPE_NONNETWORK) &&
2507 !strcmp(p, "-T"))
2508 p = "-title";
2509
2510 ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
2511 do_everything ? 1 : -1, cfg);
2512
2513 if (ret == -2) {
2514 cmdline_error("option \"%s\" requires an argument", p);
2515 } else if (ret == 2) {
2516 --argc, ++argv; /* skip next argument */
2517 continue;
2518 } else if (ret == 1) {
2519 continue;
2520 }
2521
2522 if (!strcmp(p, "-fn") || !strcmp(p, "-font")) {
2523 EXPECTS_ARG;
2524 SECOND_PASS_ONLY;
2525 strncpy(cfg->font.name, val, sizeof(cfg->font.name));
2526 cfg->font.name[sizeof(cfg->font.name)-1] = '\0';
2527
2528 } else if (!strcmp(p, "-fb")) {
2529 EXPECTS_ARG;
2530 SECOND_PASS_ONLY;
2531 strncpy(cfg->boldfont.name, val, sizeof(cfg->boldfont.name));
2532 cfg->boldfont.name[sizeof(cfg->boldfont.name)-1] = '\0';
2533
2534 } else if (!strcmp(p, "-fw")) {
2535 EXPECTS_ARG;
2536 SECOND_PASS_ONLY;
2537 strncpy(cfg->widefont.name, val, sizeof(cfg->widefont.name));
2538 cfg->widefont.name[sizeof(cfg->widefont.name)-1] = '\0';
2539
2540 } else if (!strcmp(p, "-fwb")) {
2541 EXPECTS_ARG;
2542 SECOND_PASS_ONLY;
2543 strncpy(cfg->wideboldfont.name, val, sizeof(cfg->wideboldfont.name));
2544 cfg->wideboldfont.name[sizeof(cfg->wideboldfont.name)-1] = '\0';
2545
2546 } else if (!strcmp(p, "-cs")) {
2547 EXPECTS_ARG;
2548 SECOND_PASS_ONLY;
2549 strncpy(cfg->line_codepage, val, sizeof(cfg->line_codepage));
2550 cfg->line_codepage[sizeof(cfg->line_codepage)-1] = '\0';
2551
2552 } else if (!strcmp(p, "-geometry")) {
2553 int flags, x, y;
2554 unsigned int w, h;
2555 EXPECTS_ARG;
2556 SECOND_PASS_ONLY;
2557
2558 flags = XParseGeometry(val, &x, &y, &w, &h);
2559 if (flags & WidthValue)
2560 cfg->width = (int)w;
2561 if (flags & HeightValue)
2562 cfg->height = (int)h;
2563
2564 if (flags & (XValue | YValue)) {
2565 inst->xpos = x;
2566 inst->ypos = y;
2567 inst->gotpos = TRUE;
2568 inst->gravity = ((flags & XNegative ? 1 : 0) |
2569 (flags & YNegative ? 2 : 0));
2570 }
2571
2572 } else if (!strcmp(p, "-sl")) {
2573 EXPECTS_ARG;
2574 SECOND_PASS_ONLY;
2575 cfg->savelines = atoi(val);
2576
2577 } else if (!strcmp(p, "-fg") || !strcmp(p, "-bg") ||
2578 !strcmp(p, "-bfg") || !strcmp(p, "-bbg") ||
2579 !strcmp(p, "-cfg") || !strcmp(p, "-cbg")) {
2580 GdkColor col;
2581
2582 EXPECTS_ARG;
2583 SECOND_PASS_ONLY;
2584 if (!gdk_color_parse(val, &col)) {
2585 err = 1;
2586 fprintf(stderr, "%s: unable to parse colour \"%s\"\n",
2587 appname, val);
2588 } else {
2589 int index;
2590 index = (!strcmp(p, "-fg") ? 0 :
2591 !strcmp(p, "-bg") ? 2 :
2592 !strcmp(p, "-bfg") ? 1 :
2593 !strcmp(p, "-bbg") ? 3 :
2594 !strcmp(p, "-cfg") ? 4 :
2595 !strcmp(p, "-cbg") ? 5 : -1);
2596 assert(index != -1);
2597 cfg->colours[index][0] = col.red / 256;
2598 cfg->colours[index][1] = col.green / 256;
2599 cfg->colours[index][2] = col.blue / 256;
2600 }
2601
2602 } else if (use_pty_argv && !strcmp(p, "-e")) {
2603 /* This option swallows all further arguments. */
2604 if (!do_everything)
2605 break;
2606
2607 if (--argc > 0) {
2608 int i;
2609 pty_argv = snewn(argc+1, char *);
2610 ++argv;
2611 for (i = 0; i < argc; i++)
2612 pty_argv[i] = argv[i];
2613 pty_argv[argc] = NULL;
2614 break; /* finished command-line processing */
2615 } else
2616 err = 1, fprintf(stderr, "%s: -e expects an argument\n",
2617 appname);
2618
2619 } else if (!strcmp(p, "-title")) {
2620 EXPECTS_ARG;
2621 SECOND_PASS_ONLY;
2622 strncpy(cfg->wintitle, val, sizeof(cfg->wintitle));
2623 cfg->wintitle[sizeof(cfg->wintitle)-1] = '\0';
2624
2625 } else if (!strcmp(p, "-log")) {
2626 EXPECTS_ARG;
2627 SECOND_PASS_ONLY;
2628 strncpy(cfg->logfilename.path, val, sizeof(cfg->logfilename.path));
2629 cfg->logfilename.path[sizeof(cfg->logfilename.path)-1] = '\0';
2630 cfg->logtype = LGTYP_DEBUG;
2631
2632 } else if (!strcmp(p, "-ut-") || !strcmp(p, "+ut")) {
2633 SECOND_PASS_ONLY;
2634 cfg->stamp_utmp = 0;
2635
2636 } else if (!strcmp(p, "-ut")) {
2637 SECOND_PASS_ONLY;
2638 cfg->stamp_utmp = 1;
2639
2640 } else if (!strcmp(p, "-ls-") || !strcmp(p, "+ls")) {
2641 SECOND_PASS_ONLY;
2642 cfg->login_shell = 0;
2643
2644 } else if (!strcmp(p, "-ls")) {
2645 SECOND_PASS_ONLY;
2646 cfg->login_shell = 1;
2647
2648 } else if (!strcmp(p, "-nethack")) {
2649 SECOND_PASS_ONLY;
2650 cfg->nethack_keypad = 1;
2651
2652 } else if (!strcmp(p, "-sb-") || !strcmp(p, "+sb")) {
2653 SECOND_PASS_ONLY;
2654 cfg->scrollbar = 0;
2655
2656 } else if (!strcmp(p, "-sb")) {
2657 SECOND_PASS_ONLY;
2658 cfg->scrollbar = 0;
2659
2660 } else if (!strcmp(p, "-name")) {
2661 EXPECTS_ARG;
2662 app_name = val;
2663
2664 } else if (!strcmp(p, "-xrm")) {
2665 EXPECTS_ARG;
2666 provide_xrm_string(val);
2667
2668 } else if(!strcmp(p, "-help") || !strcmp(p, "--help")) {
2669 help(stdout);
2670 exit(0);
2671
2672 } else if (!strcmp(p, "-pgpfp")) {
2673 pgp_fingerprints();
2674 exit(1);
2675
2676 } else if(p[0] != '-' && (!do_everything ||
2677 process_nonoption_arg(p, cfg,
2678 allow_launch))) {
2679 /* do nothing */
2680
2681 } else {
2682 err = 1;
2683 fprintf(stderr, "%s: unrecognized option '%s'\n", appname, p);
2684 }
2685 }
2686
2687 return err;
2688 }
2689
2690 int uxsel_input_add(int fd, int rwx) {
2691 int flags = 0;
2692 if (rwx & 1) flags |= GDK_INPUT_READ;
2693 if (rwx & 2) flags |= GDK_INPUT_WRITE;
2694 if (rwx & 4) flags |= GDK_INPUT_EXCEPTION;
2695 assert(flags);
2696 return gdk_input_add(fd, flags, fd_input_func, NULL);
2697 }
2698
2699 void uxsel_input_remove(int id) {
2700 gdk_input_remove(id);
2701 }
2702
2703 void setup_fonts_ucs(struct gui_data *inst)
2704 {
2705 if (inst->fonts[0])
2706 unifont_destroy(inst->fonts[0]);
2707 if (inst->fonts[1])
2708 unifont_destroy(inst->fonts[1]);
2709 if (inst->fonts[2])
2710 unifont_destroy(inst->fonts[2]);
2711 if (inst->fonts[3])
2712 unifont_destroy(inst->fonts[3]);
2713
2714 inst->fonts[0] = unifont_create(inst->area, inst->cfg.font.name,
2715 FALSE, FALSE,
2716 inst->cfg.shadowboldoffset,
2717 inst->cfg.shadowbold);
2718 if (!inst->fonts[0]) {
2719 fprintf(stderr, "%s: unable to load font \"%s\"\n", appname,
2720 inst->cfg.font.name);
2721 exit(1);
2722 }
2723
2724 if (inst->cfg.shadowbold || !inst->cfg.boldfont.name[0]) {
2725 inst->fonts[1] = NULL;
2726 } else {
2727 inst->fonts[1] = unifont_create(inst->area, inst->cfg.boldfont.name,
2728 FALSE, TRUE,
2729 inst->cfg.shadowboldoffset,
2730 inst->cfg.shadowbold);
2731 if (!inst->fonts[1]) {
2732 fprintf(stderr, "%s: unable to load bold font \"%s\"\n", appname,
2733 inst->cfg.boldfont.name);
2734 exit(1);
2735 }
2736 }
2737
2738 if (inst->cfg.widefont.name[0]) {
2739 inst->fonts[2] = unifont_create(inst->area, inst->cfg.widefont.name,
2740 TRUE, FALSE,
2741 inst->cfg.shadowboldoffset,
2742 inst->cfg.shadowbold);
2743 if (!inst->fonts[2]) {
2744 fprintf(stderr, "%s: unable to load wide font \"%s\"\n", appname,
2745 inst->cfg.widefont.name);
2746 exit(1);
2747 }
2748 } else {
2749 inst->fonts[2] = NULL;
2750 }
2751
2752 if (inst->cfg.shadowbold || !inst->cfg.wideboldfont.name[0]) {
2753 inst->fonts[3] = NULL;
2754 } else {
2755 inst->fonts[3] = unifont_create(inst->area,
2756 inst->cfg.wideboldfont.name, TRUE,
2757 TRUE, inst->cfg.shadowboldoffset,
2758 inst->cfg.shadowbold);
2759 if (!inst->fonts[3]) {
2760 fprintf(stderr, "%s: unable to load wide bold font \"%s\"\n", appname,
2761 inst->cfg.boldfont.name);
2762 exit(1);
2763 }
2764 }
2765
2766 inst->font_width = inst->fonts[0]->width;
2767 inst->font_height = inst->fonts[0]->height;
2768
2769 inst->direct_to_font = init_ucs(&inst->ucsdata, inst->cfg.line_codepage,
2770 inst->cfg.utf8_override,
2771 inst->fonts[0]->public_charset,
2772 inst->cfg.vtmode);
2773 }
2774
2775 void set_geom_hints(struct gui_data *inst)
2776 {
2777 GdkGeometry geom;
2778 geom.min_width = inst->font_width + 2*inst->cfg.window_border;
2779 geom.min_height = inst->font_height + 2*inst->cfg.window_border;
2780 geom.max_width = geom.max_height = -1;
2781 geom.base_width = 2*inst->cfg.window_border;
2782 geom.base_height = 2*inst->cfg.window_border;
2783 geom.width_inc = inst->font_width;
2784 geom.height_inc = inst->font_height;
2785 geom.min_aspect = geom.max_aspect = 0;
2786 gtk_window_set_geometry_hints(GTK_WINDOW(inst->window), inst->area, &geom,
2787 GDK_HINT_MIN_SIZE | GDK_HINT_BASE_SIZE |
2788 GDK_HINT_RESIZE_INC);
2789 }
2790
2791 void clear_scrollback_menuitem(GtkMenuItem *item, gpointer data)
2792 {
2793 struct gui_data *inst = (struct gui_data *)data;
2794 term_clrsb(inst->term);
2795 }
2796
2797 void reset_terminal_menuitem(GtkMenuItem *item, gpointer data)
2798 {
2799 struct gui_data *inst = (struct gui_data *)data;
2800 term_pwron(inst->term, TRUE);
2801 if (inst->ldisc)
2802 ldisc_send(inst->ldisc, NULL, 0, 0);
2803 }
2804
2805 void copy_all_menuitem(GtkMenuItem *item, gpointer data)
2806 {
2807 struct gui_data *inst = (struct gui_data *)data;
2808 term_copyall(inst->term);
2809 }
2810
2811 void special_menuitem(GtkMenuItem *item, gpointer data)
2812 {
2813 struct gui_data *inst = (struct gui_data *)data;
2814 int code = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(item),
2815 "user-data"));
2816
2817 if (inst->back)
2818 inst->back->special(inst->backhandle, code);
2819 }
2820
2821 void about_menuitem(GtkMenuItem *item, gpointer data)
2822 {
2823 struct gui_data *inst = (struct gui_data *)data;
2824 about_box(inst->window);
2825 }
2826
2827 void event_log_menuitem(GtkMenuItem *item, gpointer data)
2828 {
2829 struct gui_data *inst = (struct gui_data *)data;
2830 showeventlog(inst->eventlogstuff, inst->window);
2831 }
2832
2833 void change_settings_menuitem(GtkMenuItem *item, gpointer data)
2834 {
2835 /* This maps colour indices in inst->cfg to those used in inst->cols. */
2836 static const int ww[] = {
2837 256, 257, 258, 259, 260, 261,
2838 0, 8, 1, 9, 2, 10, 3, 11,
2839 4, 12, 5, 13, 6, 14, 7, 15
2840 };
2841 struct gui_data *inst = (struct gui_data *)data;
2842 char *title = dupcat(appname, " Reconfiguration", NULL);
2843 Config cfg2, oldcfg;
2844 int i, need_size;
2845
2846 assert(lenof(ww) == NCFGCOLOURS);
2847
2848 if (inst->reconfiguring)
2849 return;
2850 else
2851 inst->reconfiguring = TRUE;
2852
2853 cfg2 = inst->cfg; /* structure copy */
2854
2855 if (do_config_box(title, &cfg2, 1,
2856 inst->back?inst->back->cfg_info(inst->backhandle):0)) {
2857
2858 oldcfg = inst->cfg; /* structure copy */
2859 inst->cfg = cfg2; /* structure copy */
2860
2861 /* Pass new config data to the logging module */
2862 log_reconfig(inst->logctx, &cfg2);
2863 /*
2864 * Flush the line discipline's edit buffer in the case
2865 * where local editing has just been disabled.
2866 */
2867 if (inst->ldisc)
2868 ldisc_send(inst->ldisc, NULL, 0, 0);
2869 /* Pass new config data to the terminal */
2870 term_reconfig(inst->term, &cfg2);
2871 /* Pass new config data to the back end */
2872 if (inst->back)
2873 inst->back->reconfig(inst->backhandle, &cfg2);
2874
2875 /*
2876 * Just setting inst->cfg is sufficient to cause colour
2877 * setting changes to appear on the next ESC]R palette
2878 * reset. But we should also check whether any colour
2879 * settings have been changed, and revert the ones that
2880 * have to the new default, on the assumption that the user
2881 * is most likely to want an immediate update.
2882 */
2883 for (i = 0; i < NCFGCOLOURS; i++) {
2884 if (oldcfg.colours[i][0] != cfg2.colours[i][0] ||
2885 oldcfg.colours[i][1] != cfg2.colours[i][1] ||
2886 oldcfg.colours[i][2] != cfg2.colours[i][2]) {
2887 real_palette_set(inst, ww[i], cfg2.colours[i][0],
2888 cfg2.colours[i][1],
2889 cfg2.colours[i][2]);
2890
2891 /*
2892 * If the default background has changed, we must
2893 * repaint the space in between the window border
2894 * and the text area.
2895 */
2896 if (i == 258) {
2897 set_window_background(inst);
2898 draw_backing_rect(inst);
2899 }
2900 }
2901 }
2902
2903 /*
2904 * If the scrollbar needs to be shown, hidden, or moved
2905 * from one end to the other of the window, do so now.
2906 */
2907 if (oldcfg.scrollbar != cfg2.scrollbar) {
2908 if (cfg2.scrollbar)
2909 gtk_widget_show(inst->sbar);
2910 else
2911 gtk_widget_hide(inst->sbar);
2912 }
2913 if (oldcfg.scrollbar_on_left != cfg2.scrollbar_on_left) {
2914 gtk_box_reorder_child(inst->hbox, inst->sbar,
2915 cfg2.scrollbar_on_left ? 0 : 1);
2916 }
2917
2918 /*
2919 * Change the window title, if required.
2920 */
2921 if (strcmp(oldcfg.wintitle, cfg2.wintitle))
2922 set_title(inst, cfg2.wintitle);
2923 set_window_titles(inst);
2924
2925 /*
2926 * Redo the whole tangled fonts and Unicode mess if
2927 * necessary.
2928 */
2929 if (strcmp(oldcfg.font.name, cfg2.font.name) ||
2930 strcmp(oldcfg.boldfont.name, cfg2.boldfont.name) ||
2931 strcmp(oldcfg.widefont.name, cfg2.widefont.name) ||
2932 strcmp(oldcfg.wideboldfont.name, cfg2.wideboldfont.name) ||
2933 strcmp(oldcfg.line_codepage, cfg2.line_codepage) ||
2934 oldcfg.vtmode != cfg2.vtmode ||
2935 oldcfg.shadowbold != cfg2.shadowbold) {
2936 setup_fonts_ucs(inst);
2937 need_size = 1;
2938 } else
2939 need_size = 0;
2940
2941 /*
2942 * Resize the window.
2943 */
2944 if (oldcfg.width != cfg2.width || oldcfg.height != cfg2.height ||
2945 oldcfg.window_border != cfg2.window_border || need_size) {
2946 set_geom_hints(inst);
2947 request_resize(inst, cfg2.width, cfg2.height);
2948 } else {
2949 /*
2950 * The above will have caused a call to term_size() for
2951 * us if it happened. If the user has fiddled with only
2952 * the scrollback size, the above will not have
2953 * happened and we will need an explicit term_size()
2954 * here.
2955 */
2956 if (oldcfg.savelines != cfg2.savelines)
2957 term_size(inst->term, inst->term->rows, inst->term->cols,
2958 cfg2.savelines);
2959 }
2960
2961 term_invalidate(inst->term);
2962
2963 /*
2964 * We do an explicit full redraw here to ensure the window
2965 * border has been redrawn as well as the text area.
2966 */
2967 gtk_widget_queue_draw(inst->area);
2968 }
2969 sfree(title);
2970 inst->reconfiguring = FALSE;
2971 }
2972
2973 void fork_and_exec_self(struct gui_data *inst, int fd_to_close, ...)
2974 {
2975 /*
2976 * Re-execing ourself is not an exact science under Unix. I do
2977 * the best I can by using /proc/self/exe if available and by
2978 * assuming argv[0] can be found on $PATH if not.
2979 *
2980 * Note that we also have to reconstruct the elements of the
2981 * original argv which gtk swallowed, since the user wants the
2982 * new session to appear on the same X display as the old one.
2983 */
2984 char **args;
2985 va_list ap;
2986 int i, n;
2987 int pid;
2988
2989 /*
2990 * Collect the arguments with which to re-exec ourself.
2991 */
2992 va_start(ap, fd_to_close);
2993 n = 2; /* progname and terminating NULL */
2994 n += inst->ngtkargs;
2995 while (va_arg(ap, char *) != NULL)
2996 n++;
2997 va_end(ap);
2998
2999 args = snewn(n, char *);
3000 args[0] = inst->progname;
3001 args[n-1] = NULL;
3002 for (i = 0; i < inst->ngtkargs; i++)
3003 args[i+1] = inst->gtkargvstart[i];
3004
3005 i++;
3006 va_start(ap, fd_to_close);
3007 while ((args[i++] = va_arg(ap, char *)) != NULL);
3008 va_end(ap);
3009
3010 assert(i == n);
3011
3012 /*
3013 * Do the double fork.
3014 */
3015 pid = fork();
3016 if (pid < 0) {
3017 perror("fork");
3018 return;
3019 }
3020
3021 if (pid == 0) {
3022 int pid2 = fork();
3023 if (pid2 < 0) {
3024 perror("fork");
3025 _exit(1);
3026 } else if (pid2 > 0) {
3027 /*
3028 * First child has successfully forked second child. My
3029 * Work Here Is Done. Note the use of _exit rather than
3030 * exit: the latter appears to cause destroy messages
3031 * to be sent to the X server. I suspect gtk uses
3032 * atexit.
3033 */
3034 _exit(0);
3035 }
3036
3037 /*
3038 * If we reach here, we are the second child, so we now
3039 * actually perform the exec.
3040 */
3041 if (fd_to_close >= 0)
3042 close(fd_to_close);
3043
3044 execv("/proc/self/exe", args);
3045 execvp(inst->progname, args);
3046 perror("exec");
3047 _exit(127);
3048
3049 } else {
3050 int status;
3051 waitpid(pid, &status, 0);
3052 }
3053
3054 }
3055
3056 void dup_session_menuitem(GtkMenuItem *item, gpointer gdata)
3057 {
3058 struct gui_data *inst = (struct gui_data *)gdata;
3059 /*
3060 * For this feature we must marshal cfg and (possibly) pty_argv
3061 * into a byte stream, create a pipe, and send this byte stream
3062 * to the child through the pipe.
3063 */
3064 int i, ret, size;
3065 char *data;
3066 char option[80];
3067 int pipefd[2];
3068
3069 if (pipe(pipefd) < 0) {
3070 perror("pipe");
3071 return;
3072 }
3073
3074 size = sizeof(inst->cfg);
3075 if (use_pty_argv && pty_argv) {
3076 for (i = 0; pty_argv[i]; i++)
3077 size += strlen(pty_argv[i]) + 1;
3078 }
3079
3080 data = snewn(size, char);
3081 memcpy(data, &inst->cfg, sizeof(inst->cfg));
3082 if (use_pty_argv && pty_argv) {
3083 int p = sizeof(inst->cfg);
3084 for (i = 0; pty_argv[i]; i++) {
3085 strcpy(data + p, pty_argv[i]);
3086 p += strlen(pty_argv[i]) + 1;
3087 }
3088 assert(p == size);
3089 }
3090
3091 sprintf(option, "---[%d,%d]", pipefd[0], size);
3092 fcntl(pipefd[0], F_SETFD, 0);
3093 fork_and_exec_self(inst, pipefd[1], option, NULL);
3094 close(pipefd[0]);
3095
3096 i = ret = 0;
3097 while (i < size && (ret = write(pipefd[1], data + i, size - i)) > 0)
3098 i += ret;
3099 if (ret < 0)
3100 perror("write to pipe");
3101 close(pipefd[1]);
3102 sfree(data);
3103 }
3104
3105 int read_dupsession_data(struct gui_data *inst, Config *cfg, char *arg)
3106 {
3107 int fd, i, ret, size;
3108 char *data;
3109
3110 if (sscanf(arg, "---[%d,%d]", &fd, &size) != 2) {
3111 fprintf(stderr, "%s: malformed magic argument `%s'\n", appname, arg);
3112 exit(1);
3113 }
3114
3115 data = snewn(size, char);
3116 i = ret = 0;
3117 while (i < size && (ret = read(fd, data + i, size - i)) > 0)
3118 i += ret;
3119 if (ret < 0) {
3120 perror("read from pipe");
3121 exit(1);
3122 } else if (i < size) {
3123 fprintf(stderr, "%s: unexpected EOF in Duplicate Session data\n",
3124 appname);
3125 exit(1);
3126 }
3127
3128 memcpy(cfg, data, sizeof(Config));
3129 if (use_pty_argv && size > sizeof(Config)) {
3130 int n = 0;
3131 i = sizeof(Config);
3132 while (i < size) {
3133 while (i < size && data[i]) i++;
3134 if (i >= size) {
3135 fprintf(stderr, "%s: malformed Duplicate Session data\n",
3136 appname);
3137 exit(1);
3138 }
3139 i++;
3140 n++;
3141 }
3142 pty_argv = snewn(n+1, char *);
3143 pty_argv[n] = NULL;
3144 n = 0;
3145 i = sizeof(Config);
3146 while (i < size) {
3147 char *p = data + i;
3148 while (i < size && data[i]) i++;
3149 assert(i < size);
3150 i++;
3151 pty_argv[n++] = dupstr(p);
3152 }
3153 }
3154
3155 return 0;
3156 }
3157
3158 void new_session_menuitem(GtkMenuItem *item, gpointer data)
3159 {
3160 struct gui_data *inst = (struct gui_data *)data;
3161
3162 fork_and_exec_self(inst, -1, NULL);
3163 }
3164
3165 void restart_session_menuitem(GtkMenuItem *item, gpointer data)
3166 {
3167 struct gui_data *inst = (struct gui_data *)data;
3168
3169 if (!inst->back) {
3170 logevent(inst, "----- Session restarted -----");
3171 term_pwron(inst->term, FALSE);
3172 start_backend(inst);
3173 inst->exited = FALSE;
3174 }
3175 }
3176
3177 void saved_session_menuitem(GtkMenuItem *item, gpointer data)
3178 {
3179 struct gui_data *inst = (struct gui_data *)data;
3180 char *str = (char *)gtk_object_get_data(GTK_OBJECT(item), "user-data");
3181
3182 fork_and_exec_self(inst, -1, "-load", str, NULL);
3183 }
3184
3185 void saved_session_freedata(GtkMenuItem *item, gpointer data)
3186 {
3187 char *str = (char *)gtk_object_get_data(GTK_OBJECT(item), "user-data");
3188
3189 sfree(str);
3190 }
3191
3192 static void update_savedsess_menu(GtkMenuItem *menuitem, gpointer data)
3193 {
3194 struct gui_data *inst = (struct gui_data *)data;
3195 struct sesslist sesslist;
3196 int i;
3197
3198 gtk_container_foreach(GTK_CONTAINER(inst->sessionsmenu),
3199 (GtkCallback)gtk_widget_destroy, NULL);
3200
3201 get_sesslist(&sesslist, TRUE);
3202 /* skip sesslist.sessions[0] == Default Settings */
3203 for (i = 1; i < sesslist.nsessions; i++) {
3204 GtkWidget *menuitem =
3205 gtk_menu_item_new_with_label(sesslist.sessions[i]);
3206 gtk_container_add(GTK_CONTAINER(inst->sessionsmenu), menuitem);
3207 gtk_widget_show(menuitem);
3208 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
3209 dupstr(sesslist.sessions[i]));
3210 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
3211 GTK_SIGNAL_FUNC(saved_session_menuitem),
3212 inst);
3213 gtk_signal_connect(GTK_OBJECT(menuitem), "destroy",
3214 GTK_SIGNAL_FUNC(saved_session_freedata),
3215 inst);
3216 }
3217 if (sesslist.nsessions <= 1) {
3218 GtkWidget *menuitem =
3219 gtk_menu_item_new_with_label("(No sessions)");
3220 gtk_widget_set_sensitive(menuitem, FALSE);
3221 gtk_container_add(GTK_CONTAINER(inst->sessionsmenu), menuitem);
3222 gtk_widget_show(menuitem);
3223 }
3224 get_sesslist(&sesslist, FALSE); /* free up */
3225 }
3226
3227 void set_window_icon(GtkWidget *window, const char *const *const *icon,
3228 int n_icon)
3229 {
3230 GdkPixmap *iconpm;
3231 GdkBitmap *iconmask;
3232 #if GTK_CHECK_VERSION(2,0,0)
3233 GList *iconlist;
3234 int n;
3235 #endif
3236
3237 if (!n_icon)
3238 return;
3239
3240 gtk_widget_realize(window);
3241 iconpm = gdk_pixmap_create_from_xpm_d(window->window, &iconmask,
3242 NULL, (gchar **)icon[0]);
3243 gdk_window_set_icon(window->window, NULL, iconpm, iconmask);
3244
3245 #if GTK_CHECK_VERSION(2,0,0)
3246 iconlist = NULL;
3247 for (n = 0; n < n_icon; n++) {
3248 iconlist =
3249 g_list_append(iconlist,
3250 gdk_pixbuf_new_from_xpm_data((const gchar **)
3251 icon[n]));
3252 }
3253 gdk_window_set_icon_list(window->window, iconlist);
3254 #endif
3255 }
3256
3257 void update_specials_menu(void *frontend)
3258 {
3259 struct gui_data *inst = (struct gui_data *)frontend;
3260
3261 const struct telnet_special *specials;
3262
3263 if (inst->back)
3264 specials = inst->back->get_specials(inst->backhandle);
3265 else
3266 specials = NULL;
3267
3268 /* I believe this disposes of submenus too. */
3269 gtk_container_foreach(GTK_CONTAINER(inst->specialsmenu),
3270 (GtkCallback)gtk_widget_destroy, NULL);
3271 if (specials) {
3272 int i;
3273 GtkWidget *menu = inst->specialsmenu;
3274 /* A lame "stack" for submenus that will do for now. */
3275 GtkWidget *saved_menu = NULL;
3276 int nesting = 1;
3277 for (i = 0; nesting > 0; i++) {
3278 GtkWidget *menuitem = NULL;
3279 switch (specials[i].code) {
3280 case TS_SUBMENU:
3281 assert (nesting < 2);
3282 saved_menu = menu; /* XXX lame stacking */
3283 menu = gtk_menu_new();
3284 menuitem = gtk_menu_item_new_with_label(specials[i].name);
3285 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), menu);
3286 gtk_container_add(GTK_CONTAINER(saved_menu), menuitem);
3287 gtk_widget_show(menuitem);
3288 menuitem = NULL;
3289 nesting++;
3290 break;
3291 case TS_EXITMENU:
3292 nesting--;
3293 if (nesting) {
3294 menu = saved_menu; /* XXX lame stacking */
3295 saved_menu = NULL;
3296 }
3297 break;
3298 case TS_SEP:
3299 menuitem = gtk_menu_item_new();
3300 break;
3301 default:
3302 menuitem = gtk_menu_item_new_with_label(specials[i].name);
3303 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
3304 GINT_TO_POINTER(specials[i].code));
3305 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
3306 GTK_SIGNAL_FUNC(special_menuitem), inst);
3307 break;
3308 }
3309 if (menuitem) {
3310 gtk_container_add(GTK_CONTAINER(menu), menuitem);
3311 gtk_widget_show(menuitem);
3312 }
3313 }
3314 gtk_widget_show(inst->specialsitem1);
3315 gtk_widget_show(inst->specialsitem2);
3316 } else {
3317 gtk_widget_hide(inst->specialsitem1);
3318 gtk_widget_hide(inst->specialsitem2);
3319 }
3320 }
3321
3322 static void start_backend(struct gui_data *inst)
3323 {
3324 extern Backend *select_backend(Config *cfg);
3325 char *realhost;
3326 const char *error;
3327
3328 inst->back = select_backend(&inst->cfg);
3329
3330 error = inst->back->init((void *)inst, &inst->backhandle,
3331 &inst->cfg, inst->cfg.host, inst->cfg.port,
3332 &realhost, inst->cfg.tcp_nodelay,
3333 inst->cfg.tcp_keepalives);
3334
3335 if (error) {
3336 char *msg = dupprintf("Unable to open connection to %s:\n%s",
3337 inst->cfg.host, error);
3338 inst->exited = TRUE;
3339 fatal_message_box(inst->window, msg);
3340 sfree(msg);
3341 exit(0);
3342 }
3343
3344 if (inst->cfg.wintitle[0]) {
3345 set_title(inst, inst->cfg.wintitle);
3346 set_icon(inst, inst->cfg.wintitle);
3347 } else {
3348 char *title = make_default_wintitle(realhost);
3349 set_title(inst, title);
3350 set_icon(inst, title);
3351 sfree(title);
3352 }
3353 sfree(realhost);
3354
3355 inst->back->provide_logctx(inst->backhandle, inst->logctx);
3356
3357 term_provide_resize_fn(inst->term, inst->back->size, inst->backhandle);
3358
3359 inst->ldisc =
3360 ldisc_create(&inst->cfg, inst->term, inst->back, inst->backhandle,
3361 inst);
3362
3363 gtk_widget_set_sensitive(inst->restartitem, FALSE);
3364 }
3365
3366 int pt_main(int argc, char **argv)
3367 {
3368 extern int cfgbox(Config *cfg);
3369 struct gui_data *inst;
3370
3371 /*
3372 * Create an instance structure and initialise to zeroes
3373 */
3374 inst = snew(struct gui_data);
3375 memset(inst, 0, sizeof(*inst));
3376 inst->alt_keycode = -1; /* this one needs _not_ to be zero */
3377 inst->busy_status = BUSY_NOT;
3378
3379 /* defer any child exit handling until we're ready to deal with
3380 * it */
3381 block_signal(SIGCHLD, 1);
3382
3383 inst->progname = argv[0];
3384 /*
3385 * Copy the original argv before letting gtk_init fiddle with
3386 * it. It will be required later.
3387 */
3388 {
3389 int i, oldargc;
3390 inst->gtkargvstart = snewn(argc-1, char *);
3391 for (i = 1; i < argc; i++)
3392 inst->gtkargvstart[i-1] = dupstr(argv[i]);
3393 oldargc = argc;
3394 gtk_init(&argc, &argv);
3395 inst->ngtkargs = oldargc - argc;
3396 }
3397
3398 if (argc > 1 && !strncmp(argv[1], "---", 3)) {
3399 read_dupsession_data(inst, &inst->cfg, argv[1]);
3400 /* Splatter this argument so it doesn't clutter a ps listing */
3401 memset(argv[1], 0, strlen(argv[1]));
3402 } else {
3403 /* By default, we bring up the config dialog, rather than launching
3404 * a session. This gets set to TRUE if something happens to change
3405 * that (e.g., a hostname is specified on the command-line). */
3406 int allow_launch = FALSE;
3407 if (do_cmdline(argc, argv, 0, &allow_launch, inst, &inst->cfg))
3408 exit(1); /* pre-defaults pass to get -class */
3409 do_defaults(NULL, &inst->cfg);
3410 if (do_cmdline(argc, argv, 1, &allow_launch, inst, &inst->cfg))
3411 exit(1); /* post-defaults, do everything */
3412
3413 cmdline_run_saved(&inst->cfg);
3414
3415 if (loaded_session)
3416 allow_launch = TRUE;
3417
3418 if ((!allow_launch || !cfg_launchable(&inst->cfg)) &&
3419 !cfgbox(&inst->cfg))
3420 exit(0); /* config box hit Cancel */
3421 }
3422
3423 if (!compound_text_atom)
3424 compound_text_atom = gdk_atom_intern("COMPOUND_TEXT", FALSE);
3425 if (!utf8_string_atom)
3426 utf8_string_atom = gdk_atom_intern("UTF8_STRING", FALSE);
3427
3428 inst->area = gtk_drawing_area_new();
3429
3430 setup_fonts_ucs(inst);
3431 init_cutbuffers();
3432
3433 inst->window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
3434
3435 /*
3436 * Set up the colour map.
3437 */
3438 palette_reset(inst);
3439
3440 inst->width = inst->cfg.width;
3441 inst->height = inst->cfg.height;
3442
3443 gtk_drawing_area_size(GTK_DRAWING_AREA(inst->area),
3444 inst->font_width * inst->cfg.width + 2*inst->cfg.window_border,
3445 inst->font_height * inst->cfg.height + 2*inst->cfg.window_border);
3446 inst->sbar_adjust = GTK_ADJUSTMENT(gtk_adjustment_new(0,0,0,0,0,0));
3447 inst->sbar = gtk_vscrollbar_new(inst->sbar_adjust);
3448 inst->hbox = GTK_BOX(gtk_hbox_new(FALSE, 0));
3449 /*
3450 * We always create the scrollbar; it remains invisible if
3451 * unwanted, so we can pop it up quickly if it suddenly becomes
3452 * desirable.
3453 */
3454 if (inst->cfg.scrollbar_on_left)
3455 gtk_box_pack_start(inst->hbox, inst->sbar, FALSE, FALSE, 0);
3456 gtk_box_pack_start(inst->hbox, inst->area, TRUE, TRUE, 0);
3457 if (!inst->cfg.scrollbar_on_left)
3458 gtk_box_pack_start(inst->hbox, inst->sbar, FALSE, FALSE, 0);
3459
3460 gtk_container_add(GTK_CONTAINER(inst->window), GTK_WIDGET(inst->hbox));
3461
3462 set_geom_hints(inst);
3463
3464 gtk_widget_show(inst->area);
3465 if (inst->cfg.scrollbar)
3466 gtk_widget_show(inst->sbar);
3467 else
3468 gtk_widget_hide(inst->sbar);
3469 gtk_widget_show(GTK_WIDGET(inst->hbox));
3470
3471 if (inst->gotpos) {
3472 int x = inst->xpos, y = inst->ypos;
3473 GtkRequisition req;
3474 gtk_widget_size_request(GTK_WIDGET(inst->window), &req);
3475 if (inst->gravity & 1) x += gdk_screen_width() - req.width;
3476 if (inst->gravity & 2) y += gdk_screen_height() - req.height;
3477 gtk_window_set_position(GTK_WINDOW(inst->window), GTK_WIN_POS_NONE);
3478 gtk_widget_set_uposition(GTK_WIDGET(inst->window), x, y);
3479 }
3480
3481 gtk_signal_connect(GTK_OBJECT(inst->window), "destroy",
3482 GTK_SIGNAL_FUNC(destroy), inst);
3483 gtk_signal_connect(GTK_OBJECT(inst->window), "delete_event",
3484 GTK_SIGNAL_FUNC(delete_window), inst);
3485 gtk_signal_connect(GTK_OBJECT(inst->window), "key_press_event",
3486 GTK_SIGNAL_FUNC(key_event), inst);
3487 gtk_signal_connect(GTK_OBJECT(inst->window), "key_release_event",
3488 GTK_SIGNAL_FUNC(key_event), inst);
3489 gtk_signal_connect(GTK_OBJECT(inst->window), "focus_in_event",
3490 GTK_SIGNAL_FUNC(focus_event), inst);
3491 gtk_signal_connect(GTK_OBJECT(inst->window), "focus_out_event",
3492 GTK_SIGNAL_FUNC(focus_event), inst);
3493 gtk_signal_connect(GTK_OBJECT(inst->area), "configure_event",
3494 GTK_SIGNAL_FUNC(configure_area), inst);
3495 gtk_signal_connect(GTK_OBJECT(inst->area), "expose_event",
3496 GTK_SIGNAL_FUNC(expose_area), inst);
3497 gtk_signal_connect(GTK_OBJECT(inst->area), "button_press_event",
3498 GTK_SIGNAL_FUNC(button_event), inst);
3499 gtk_signal_connect(GTK_OBJECT(inst->area), "button_release_event",
3500 GTK_SIGNAL_FUNC(button_event), inst);
3501 #if GTK_CHECK_VERSION(2,0,0)
3502 gtk_signal_connect(GTK_OBJECT(inst->area), "scroll_event",
3503 GTK_SIGNAL_FUNC(scroll_event), inst);
3504 #endif
3505 gtk_signal_connect(GTK_OBJECT(inst->area), "motion_notify_event",
3506 GTK_SIGNAL_FUNC(motion_event), inst);
3507 gtk_signal_connect(GTK_OBJECT(inst->area), "selection_received",
3508 GTK_SIGNAL_FUNC(selection_received), inst);
3509 gtk_signal_connect(GTK_OBJECT(inst->area), "selection_get",
3510 GTK_SIGNAL_FUNC(selection_get), inst);
3511 gtk_signal_connect(GTK_OBJECT(inst->area), "selection_clear_event",
3512 GTK_SIGNAL_FUNC(selection_clear), inst);
3513 if (inst->cfg.scrollbar)
3514 gtk_signal_connect(GTK_OBJECT(inst->sbar_adjust), "value_changed",
3515 GTK_SIGNAL_FUNC(scrollbar_moved), inst);
3516 gtk_widget_add_events(GTK_WIDGET(inst->area),
3517 GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK |
3518 GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK |
3519 GDK_POINTER_MOTION_MASK | GDK_BUTTON_MOTION_MASK);
3520
3521 {
3522 extern const char *const *const main_icon[];
3523 extern const int n_main_icon;
3524 set_window_icon(inst->window, main_icon, n_main_icon);
3525 }
3526
3527 gtk_widget_show(inst->window);
3528
3529 set_window_background(inst);
3530
3531 /*
3532 * Set up the Ctrl+rightclick context menu.
3533 */
3534 {
3535 GtkWidget *menuitem;
3536 char *s;
3537 extern const int use_event_log, new_session, saved_sessions;
3538
3539 inst->menu = gtk_menu_new();
3540
3541 #define MKMENUITEM(title, func) do { \
3542 menuitem = title ? gtk_menu_item_new_with_label(title) : \
3543 gtk_menu_item_new(); \
3544 gtk_container_add(GTK_CONTAINER(inst->menu), menuitem); \
3545 gtk_widget_show(menuitem); \
3546 if (func != NULL) \
3547 gtk_signal_connect(GTK_OBJECT(menuitem), "activate", \
3548 GTK_SIGNAL_FUNC(func), inst); \
3549 } while (0)
3550 if (new_session)
3551 MKMENUITEM("New Session...", new_session_menuitem);
3552 MKMENUITEM("Restart Session", restart_session_menuitem);
3553 inst->restartitem = menuitem;
3554 gtk_widget_set_sensitive(inst->restartitem, FALSE);
3555 MKMENUITEM("Duplicate Session", dup_session_menuitem);
3556 if (saved_sessions) {
3557 inst->sessionsmenu = gtk_menu_new();
3558 /* sessionsmenu will be updated when it's invoked */
3559 /* XXX is this the right way to do dynamic menus in Gtk? */
3560 MKMENUITEM("Saved Sessions", update_savedsess_menu);
3561 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem),
3562 inst->sessionsmenu);
3563 }
3564 MKMENUITEM(NULL, NULL);
3565 MKMENUITEM("Change Settings...", change_settings_menuitem);
3566 MKMENUITEM(NULL, NULL);
3567 if (use_event_log)
3568 MKMENUITEM("Event Log", event_log_menuitem);
3569 MKMENUITEM("Special Commands", NULL);
3570 inst->specialsmenu = gtk_menu_new();
3571 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), inst->specialsmenu);
3572 inst->specialsitem1 = menuitem;
3573 MKMENUITEM(NULL, NULL);
3574 inst->specialsitem2 = menuitem;
3575 gtk_widget_hide(inst->specialsitem1);
3576 gtk_widget_hide(inst->specialsitem2);
3577 MKMENUITEM("Clear Scrollback", clear_scrollback_menuitem);
3578 MKMENUITEM("Reset Terminal", reset_terminal_menuitem);
3579 MKMENUITEM("Copy All", copy_all_menuitem);
3580 MKMENUITEM(NULL, NULL);
3581 s = dupcat("About ", appname, NULL);
3582 MKMENUITEM(s, about_menuitem);
3583 sfree(s);
3584 #undef MKMENUITEM
3585 }
3586
3587 inst->textcursor = make_mouse_ptr(inst, GDK_XTERM);
3588 inst->rawcursor = make_mouse_ptr(inst, GDK_LEFT_PTR);
3589 inst->waitcursor = make_mouse_ptr(inst, GDK_WATCH);
3590 inst->blankcursor = make_mouse_ptr(inst, -1);
3591 make_mouse_ptr(inst, -2); /* clean up cursor font */
3592 inst->currcursor = inst->textcursor;
3593 show_mouseptr(inst, 1);
3594
3595 inst->eventlogstuff = eventlogstuff_new();
3596
3597 inst->term = term_init(&inst->cfg, &inst->ucsdata, inst);
3598 inst->logctx = log_init(inst, &inst->cfg);
3599 term_provide_logctx(inst->term, inst->logctx);
3600
3601 uxsel_init();
3602
3603 term_size(inst->term, inst->cfg.height, inst->cfg.width, inst->cfg.savelines);
3604
3605 start_backend(inst);
3606
3607 ldisc_send(inst->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
3608
3609 /* now we're reday to deal with the child exit handler being
3610 * called */
3611 block_signal(SIGCHLD, 0);
3612
3613 /*
3614 * Block SIGPIPE: if we attempt Duplicate Session or similar
3615 * and it falls over in some way, we certainly don't want
3616 * SIGPIPE terminating the main pterm/PuTTY. Note that we do
3617 * this _after_ (at least pterm) forks off its child process,
3618 * since the child wants SIGPIPE handled in the usual way.
3619 */
3620 block_signal(SIGPIPE, 1);
3621
3622 inst->exited = FALSE;
3623
3624 gtk_main();
3625
3626 return 0;
3627 }