blob: 6d6d55d0950b0f05af15e3cfa502d424cc617210 [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * Porting to GTK+ was done by:
12 *
13 * (C) 1998,1999,2000 by Marcin Dalecki <dalecki@evision.ag>
14 *
15 * With GREAT support and continuous encouragements by Andy Kahn and of
16 * course Bram Moolenaar!
17 *
18 * Support for GTK+ 2 was added by:
19 *
20 * (C) 2002,2003 Jason Hildebrand <jason@peaceworks.ca>
21 * Daniel Elstner <daniel.elstner@gmx.net>
22 */
23
24#include "vim.h"
25#ifdef FEAT_GUI_GNOME
26/* Gnome redefines _() and N_(). Grrr... */
27# ifdef _
28# undef _
29# endif
30# ifdef N_
31# undef N_
32# endif
33# ifdef textdomain
34# undef textdomain
35# endif
36# ifdef bindtextdomain
37# undef bindtextdomain
38# endif
39# if defined(FEAT_GETTEXT) && !defined(ENABLE_NLS)
40# define ENABLE_NLS /* so the texts in the dialog boxes are translated */
41# endif
42# include <gnome.h>
43# include "version.h"
44#endif
45
46#if !defined(FEAT_GUI_GTK) && defined(PROTO)
47/* When generating prototypes we don't want syntax errors. */
48# define GdkAtom int
49# define GdkEventExpose int
50# define GdkEventFocus int
51# define GdkEventVisibility int
52# define GdkEventProperty int
53# define GtkContainer int
54# define GtkTargetEntry int
55# define GtkType int
56# define GtkWidget int
57# define gint int
58# define gpointer int
59# define guint int
60# define GdkEventKey int
61# define GdkEventSelection int
62# define GtkSelectionData int
63# define GdkEventMotion int
64# define GdkEventButton int
65# define GdkDragContext int
66# define GdkEventConfigure int
67# define GdkEventClient int
68#else
69# include <gdk/gdkkeysyms.h>
70# include <gdk/gdk.h>
71# ifdef WIN3264
72# include <gdk/gdkwin32.h>
73# else
74# include <gdk/gdkx.h>
75# endif
76
77# include <gtk/gtk.h>
78# include "gui_gtk_f.h"
79#endif
80
81#ifdef HAVE_X11_SUNKEYSYM_H
82# include <X11/Sunkeysym.h>
83#endif
84
85/*
86 * Easy-to-use macro for multihead support.
87 */
88#ifdef HAVE_GTK_MULTIHEAD
89# define GET_X_ATOM(atom) gdk_x11_atom_to_xatom_for_display( \
90 gtk_widget_get_display(gui.mainwin), atom)
91#else
92# define GET_X_ATOM(atom) ((Atom)(atom))
93#endif
94
95/* Selection type distinguishers */
96enum
97{
98 TARGET_TYPE_NONE,
99 TARGET_UTF8_STRING,
100 TARGET_STRING,
101 TARGET_COMPOUND_TEXT,
102 TARGET_TEXT,
103 TARGET_TEXT_URI_LIST,
104 TARGET_TEXT_PLAIN,
105 TARGET_VIM,
106 TARGET_VIMENC
107};
108
109/*
110 * Table of selection targets supported by Vim.
111 * Note: Order matters, preferred types should come first.
112 */
113static const GtkTargetEntry selection_targets[] =
114{
115 {VIMENC_ATOM_NAME, 0, TARGET_VIMENC},
116 {VIM_ATOM_NAME, 0, TARGET_VIM},
117#ifdef FEAT_MBYTE
118 {"UTF8_STRING", 0, TARGET_UTF8_STRING},
119#endif
120 {"COMPOUND_TEXT", 0, TARGET_COMPOUND_TEXT},
121 {"TEXT", 0, TARGET_TEXT},
122 {"STRING", 0, TARGET_STRING}
123};
124#define N_SELECTION_TARGETS (sizeof(selection_targets) / sizeof(selection_targets[0]))
125
126#ifdef FEAT_DND
127/*
128 * Table of DnD targets supported by Vim.
129 * Note: Order matters, preferred types should come first.
130 */
131static const GtkTargetEntry dnd_targets[] =
132{
133 {"text/uri-list", 0, TARGET_TEXT_URI_LIST},
134# ifdef FEAT_MBYTE
135 {"UTF8_STRING", 0, TARGET_UTF8_STRING},
136# endif
137 {"STRING", 0, TARGET_STRING},
138 {"text/plain", 0, TARGET_TEXT_PLAIN}
139};
140# define N_DND_TARGETS (sizeof(dnd_targets) / sizeof(dnd_targets[0]))
141#endif
142
143
144#ifdef HAVE_GTK2
145/*
146 * "Monospace" is a standard font alias that should be present
147 * on all proper Pango/fontconfig installations.
148 */
149# define DEFAULT_FONT "Monospace 10"
150
151#else /* !HAVE_GTK2 */
152/*
153 * This is the single only fixed width font in X11, which seems to be present
154 * on all servers and available in all the variants we need.
155 */
156# define DEFAULT_FONT "-adobe-courier-medium-r-normal-*-14-*-*-*-m-*-*-*"
157
158#endif /* !HAVE_GTK2 */
159
160#if !(defined(FEAT_GUI_GNOME) && defined(FEAT_SESSION))
161/*
162 * Atoms used to communicate save-yourself from the X11 session manager. There
163 * is no need to move them into the GUI struct, since they should be constant.
164 */
165static GdkAtom wm_protocols_atom = GDK_NONE;
166static GdkAtom save_yourself_atom = GDK_NONE;
167#endif
168
169/*
170 * Atoms used to control/reference X11 selections.
171 */
172#ifdef FEAT_MBYTE
173static GdkAtom utf8_string_atom = GDK_NONE;
174#endif
175#ifndef HAVE_GTK2
176static GdkAtom compound_text_atom = GDK_NONE;
177static GdkAtom text_atom = GDK_NONE;
178#endif
179static GdkAtom vim_atom = GDK_NONE; /* Vim's own special selection format */
180#ifdef FEAT_MBYTE
181static GdkAtom vimenc_atom = GDK_NONE; /* Vim's extended selection format */
182#endif
183
184/*
185 * Keycodes recognized by vim.
186 * NOTE: when changing this, the table in gui_x11.c probably needs the same
187 * change!
188 */
189static struct special_key
190{
191 guint key_sym;
192 char_u code0;
193 char_u code1;
194}
195const special_keys[] =
196{
197 {GDK_Up, 'k', 'u'},
198 {GDK_Down, 'k', 'd'},
199 {GDK_Left, 'k', 'l'},
200 {GDK_Right, 'k', 'r'},
201 {GDK_F1, 'k', '1'},
202 {GDK_F2, 'k', '2'},
203 {GDK_F3, 'k', '3'},
204 {GDK_F4, 'k', '4'},
205 {GDK_F5, 'k', '5'},
206 {GDK_F6, 'k', '6'},
207 {GDK_F7, 'k', '7'},
208 {GDK_F8, 'k', '8'},
209 {GDK_F9, 'k', '9'},
210 {GDK_F10, 'k', ';'},
211 {GDK_F11, 'F', '1'},
212 {GDK_F12, 'F', '2'},
213 {GDK_F13, 'F', '3'},
214 {GDK_F14, 'F', '4'},
215 {GDK_F15, 'F', '5'},
216 {GDK_F16, 'F', '6'},
217 {GDK_F17, 'F', '7'},
218 {GDK_F18, 'F', '8'},
219 {GDK_F19, 'F', '9'},
220 {GDK_F20, 'F', 'A'},
221 {GDK_F21, 'F', 'B'},
222 {GDK_Pause, 'F', 'B'}, /* Pause == F21 according to netbeans.txt */
223 {GDK_F22, 'F', 'C'},
224 {GDK_F23, 'F', 'D'},
225 {GDK_F24, 'F', 'E'},
226 {GDK_F25, 'F', 'F'},
227 {GDK_F26, 'F', 'G'},
228 {GDK_F27, 'F', 'H'},
229 {GDK_F28, 'F', 'I'},
230 {GDK_F29, 'F', 'J'},
231 {GDK_F30, 'F', 'K'},
232 {GDK_F31, 'F', 'L'},
233 {GDK_F32, 'F', 'M'},
234 {GDK_F33, 'F', 'N'},
235 {GDK_F34, 'F', 'O'},
236 {GDK_F35, 'F', 'P'},
237#ifdef SunXK_F36
238 {SunXK_F36, 'F', 'Q'},
239 {SunXK_F37, 'F', 'R'},
240#endif
241 {GDK_Help, '%', '1'},
242 {GDK_Undo, '&', '8'},
243 {GDK_BackSpace, 'k', 'b'},
244 {GDK_Insert, 'k', 'I'},
245 {GDK_Delete, 'k', 'D'},
246 {GDK_3270_BackTab, 'k', 'B'},
247 {GDK_Clear, 'k', 'C'},
248 {GDK_Home, 'k', 'h'},
249 {GDK_End, '@', '7'},
250 {GDK_Prior, 'k', 'P'},
251 {GDK_Next, 'k', 'N'},
252 {GDK_Print, '%', '9'},
253 /* Keypad keys: */
254 {GDK_KP_Left, 'k', 'l'},
255 {GDK_KP_Right, 'k', 'r'},
256 {GDK_KP_Up, 'k', 'u'},
257 {GDK_KP_Down, 'k', 'd'},
258 {GDK_KP_Insert, KS_EXTRA, (char_u)KE_KINS},
259 {GDK_KP_Delete, KS_EXTRA, (char_u)KE_KDEL},
260 {GDK_KP_Home, 'K', '1'},
261 {GDK_KP_End, 'K', '4'},
262 {GDK_KP_Prior, 'K', '3'}, /* page up */
263 {GDK_KP_Next, 'K', '5'}, /* page down */
264
265 {GDK_KP_Add, 'K', '6'},
266 {GDK_KP_Subtract, 'K', '7'},
267 {GDK_KP_Divide, 'K', '8'},
268 {GDK_KP_Multiply, 'K', '9'},
269 {GDK_KP_Enter, 'K', 'A'},
270 {GDK_KP_Decimal, 'K', 'B'},
271
272 {GDK_KP_0, 'K', 'C'},
273 {GDK_KP_1, 'K', 'D'},
274 {GDK_KP_2, 'K', 'E'},
275 {GDK_KP_3, 'K', 'F'},
276 {GDK_KP_4, 'K', 'G'},
277 {GDK_KP_5, 'K', 'H'},
278 {GDK_KP_6, 'K', 'I'},
279 {GDK_KP_7, 'K', 'J'},
280 {GDK_KP_8, 'K', 'K'},
281 {GDK_KP_9, 'K', 'L'},
282
283 /* End of list marker: */
284 {0, 0, 0}
285};
286
287/*
288 * Flags for command line options table below.
289 */
290#define ARG_FONT 1
291#define ARG_GEOMETRY 2
292#define ARG_REVERSE 3
293#define ARG_NOREVERSE 4
294#define ARG_BACKGROUND 5
295#define ARG_FOREGROUND 6
296#define ARG_ICONIC 7
297#define ARG_ROLE 8
298#define ARG_NETBEANS 9
299#define ARG_XRM 10 /* ignored */
300#define ARG_MENUFONT 11 /* ignored */
301#define ARG_INDEX_MASK 0x00ff
302#define ARG_HAS_VALUE 0x0100 /* a value is expected after the argument */
303#define ARG_NEEDS_GUI 0x0200 /* need to initialize the GUI for this */
304#define ARG_FOR_GTK 0x0400 /* argument is handled by GTK+ or GNOME */
305#define ARG_COMPAT_LONG 0x0800 /* accept -foo but substitute with --foo */
306#define ARG_KEEP 0x1000 /* don't remove argument from argv[] */
307
308/*
309 * This table holds all the X GUI command line options allowed. This includes
310 * the standard ones so that we can skip them when Vim is started without the
311 * GUI (but the GUI might start up later).
312 *
313 * When changing this, also update doc/gui_x11.txt and the usage message!!!
314 */
315typedef struct
316{
317 const char *name;
318 unsigned int flags;
319}
320cmdline_option_T;
321
322static const cmdline_option_T cmdline_options[] =
323{
324 /* We handle these options ourselves */
325 {"-fn", ARG_FONT|ARG_HAS_VALUE},
326 {"-font", ARG_FONT|ARG_HAS_VALUE},
327 {"-geom", ARG_GEOMETRY|ARG_HAS_VALUE},
328 {"-geometry", ARG_GEOMETRY|ARG_HAS_VALUE},
329 {"-rv", ARG_REVERSE},
330 {"-reverse", ARG_REVERSE},
331 {"+rv", ARG_NOREVERSE},
332 {"+reverse", ARG_NOREVERSE},
333 {"-bg", ARG_BACKGROUND|ARG_HAS_VALUE},
334 {"-background", ARG_BACKGROUND|ARG_HAS_VALUE},
335 {"-fg", ARG_FOREGROUND|ARG_HAS_VALUE},
336 {"-foreground", ARG_FOREGROUND|ARG_HAS_VALUE},
337 {"-iconic", ARG_ICONIC},
338#ifdef HAVE_GTK2
339 {"--role", ARG_ROLE|ARG_HAS_VALUE},
340#endif
341#ifdef FEAT_NETBEANS_INTG
342 {"-nb", ARG_NETBEANS}, /* non-standard value format */
343 {"-xrm", ARG_XRM|ARG_HAS_VALUE}, /* not implemented */
344 {"-mf", ARG_MENUFONT|ARG_HAS_VALUE}, /* not implemented */
345 {"-menufont", ARG_MENUFONT|ARG_HAS_VALUE}, /* not implemented */
346#endif
347#if 0 /* not implemented; these arguments don't make sense for GTK+ */
348 {"-boldfont", ARG_HAS_VALUE},
349 {"-italicfont", ARG_HAS_VALUE},
350 {"-bw", ARG_HAS_VALUE},
351 {"-borderwidth", ARG_HAS_VALUE},
352 {"-sw", ARG_HAS_VALUE},
353 {"-scrollbarwidth", ARG_HAS_VALUE},
354#endif
355 /* Arguments handled by GTK (and GNOME) internally. */
356 {"--g-fatal-warnings", ARG_FOR_GTK},
357 {"--gdk-debug", ARG_FOR_GTK|ARG_HAS_VALUE},
358 {"--gdk-no-debug", ARG_FOR_GTK|ARG_HAS_VALUE},
359 {"--gtk-debug", ARG_FOR_GTK|ARG_HAS_VALUE},
360 {"--gtk-no-debug", ARG_FOR_GTK|ARG_HAS_VALUE},
361 {"--gtk-module", ARG_FOR_GTK|ARG_HAS_VALUE},
362 {"--sync", ARG_FOR_GTK},
363 {"--display", ARG_FOR_GTK|ARG_HAS_VALUE|ARG_COMPAT_LONG},
364 {"--name", ARG_FOR_GTK|ARG_HAS_VALUE|ARG_COMPAT_LONG},
365 {"--class", ARG_FOR_GTK|ARG_HAS_VALUE|ARG_COMPAT_LONG},
366#ifdef HAVE_GTK2
367 {"--screen", ARG_FOR_GTK|ARG_HAS_VALUE},
368 {"--gxid-host", ARG_FOR_GTK|ARG_HAS_VALUE},
369 {"--gxid-port", ARG_FOR_GTK|ARG_HAS_VALUE},
370#else /* these don't seem to exist anymore */
371 {"--no-xshm", ARG_FOR_GTK},
372 {"--xim-preedit", ARG_FOR_GTK|ARG_HAS_VALUE},
373 {"--xim-status", ARG_FOR_GTK|ARG_HAS_VALUE},
374 {"--gxid_host", ARG_FOR_GTK|ARG_HAS_VALUE},
375 {"--gxid_port", ARG_FOR_GTK|ARG_HAS_VALUE},
376#endif
377#ifdef FEAT_GUI_GNOME
378 {"--load-modules", ARG_FOR_GTK|ARG_HAS_VALUE},
379 {"--sm-client-id", ARG_FOR_GTK|ARG_HAS_VALUE},
380 {"--sm-config-prefix", ARG_FOR_GTK|ARG_HAS_VALUE},
381 {"--sm-disable", ARG_FOR_GTK},
382 {"--oaf-ior-fd", ARG_FOR_GTK|ARG_HAS_VALUE},
383 {"--oaf-activate-iid", ARG_FOR_GTK|ARG_HAS_VALUE},
384 {"--oaf-private", ARG_FOR_GTK},
385 {"--enable-sound", ARG_FOR_GTK},
386 {"--disable-sound", ARG_FOR_GTK},
387 {"--espeaker", ARG_FOR_GTK|ARG_HAS_VALUE},
388 {"-?", ARG_FOR_GTK|ARG_NEEDS_GUI},
389 {"--help", ARG_FOR_GTK|ARG_NEEDS_GUI|ARG_KEEP},
390 {"--usage", ARG_FOR_GTK|ARG_NEEDS_GUI},
391# if 0 /* conflicts with Vim's own --version argument */
392 {"--version", ARG_FOR_GTK|ARG_NEEDS_GUI},
393# endif
394 {"--disable-crash-dialog", ARG_FOR_GTK},
395#endif
396 {NULL, 0}
397};
398
399static int gui_argc = 0;
400static char **gui_argv = NULL;
401
402#ifdef HAVE_GTK2
403static const char *role_argument = NULL;
404#endif
405#if defined(FEAT_GUI_GNOME) && defined(FEAT_SESSION)
406static const char *restart_command = NULL;
407#endif
408static int found_iconic_arg = FALSE;
409
410#ifdef FEAT_GUI_GNOME
411/*
412 * Can't use Gnome if --socketid given
413 */
414static int using_gnome = 0;
415#else
416# define using_gnome 0
417#endif
418
419/*
420 * Parse the GUI related command-line arguments. Any arguments used are
421 * deleted from argv, and *argc is decremented accordingly. This is called
422 * when vim is started, whether or not the GUI has been started.
423 */
424 void
425gui_mch_prepare(int *argc, char **argv)
426{
427 const cmdline_option_T *option;
428 int i = 0;
429 int len = 0;
430
431#if defined(FEAT_GUI_GNOME) && defined(FEAT_SESSION)
432 /*
433 * Determine the command used to invoke Vim, to be passed as restart
434 * command to the session manager. If argv[0] contains any directory
435 * components try building an absolute path, otherwise leave it as is.
436 */
437 restart_command = argv[0];
438
439 if (strchr(argv[0], G_DIR_SEPARATOR) != NULL)
440 {
441 char_u buf[MAXPATHL];
442
443 if (mch_FullName((char_u *)argv[0], buf, (int)sizeof(buf), TRUE) == OK)
444 /* Tiny leak; doesn't matter, and usually we don't even get here */
445 restart_command = (char *)vim_strsave(buf);
446 }
447#endif
448
449 /*
450 * Move all the entries in argv which are relevant to GTK+ and GNOME
451 * into gui_argv. Freed later in gui_mch_init().
452 */
453 gui_argc = 0;
454 gui_argv = (char **)alloc((unsigned)((*argc + 1) * sizeof(char *)));
455
456 g_return_if_fail(gui_argv != NULL);
457
458 gui_argv[gui_argc++] = argv[i++];
459
460 while (i < *argc)
461 {
462 /* Don't waste CPU cycles on non-option arguments. */
463 if (argv[i][0] != '-' && argv[i][0] != '+')
464 {
465 ++i;
466 continue;
467 }
468
469 /* Look for argv[i] in cmdline_options[] table. */
470 for (option = &cmdline_options[0]; option->name != NULL; ++option)
471 {
472 len = strlen(option->name);
473
474 if (strncmp(argv[i], option->name, len) == 0)
475 {
476 if (argv[i][len] == '\0')
477 break;
478 /* allow --foo=bar style */
479 if (argv[i][len] == '=' && (option->flags & ARG_HAS_VALUE))
480 break;
481#ifdef FEAT_NETBEANS_INTG
482 /* darn, -nb has non-standard syntax */
483 if (vim_strchr((char_u *)":=", argv[i][len]) != NULL
484 && (option->flags & ARG_INDEX_MASK) == ARG_NETBEANS)
485 break;
486#endif
487 }
488 else if ((option->flags & ARG_COMPAT_LONG)
489 && strcmp(argv[i], option->name + 1) == 0)
490 {
491 /* Replace the standard X arguments "-name" and "-display"
492 * with their GNU-style long option counterparts. */
493 argv[i] = (char *)option->name;
494 break;
495 }
496 }
497 if (option->name == NULL) /* no match */
498 {
499 ++i;
500 continue;
501 }
502
503 if (option->flags & ARG_FOR_GTK)
504 {
505 /* Move the argument into gui_argv, which
506 * will later be passed to gtk_init_check() */
507 gui_argv[gui_argc++] = argv[i];
508 }
509 else
510 {
511 char *value = NULL;
512
513 /* Extract the option's value if there is one.
514 * Accept both "--foo bar" and "--foo=bar" style. */
515 if (option->flags & ARG_HAS_VALUE)
516 {
517 if (argv[i][len] == '=')
518 value = &argv[i][len + 1];
519 else if (i + 1 < *argc && strcmp(argv[i + 1], "--") != 0)
520 value = argv[i + 1];
521 }
522
523 /* Check for options handled by Vim itself */
524 switch (option->flags & ARG_INDEX_MASK)
525 {
526 case ARG_REVERSE:
527 found_reverse_arg = TRUE;
528 break;
529 case ARG_NOREVERSE:
530 found_reverse_arg = FALSE;
531 break;
532 case ARG_FONT:
533 font_argument = value;
534 break;
535 case ARG_GEOMETRY:
536 if (value != NULL)
537 gui.geom = vim_strsave((char_u *)value);
538 break;
539 case ARG_BACKGROUND:
540 background_argument = value;
541 break;
542 case ARG_FOREGROUND:
543 foreground_argument = value;
544 break;
545 case ARG_ICONIC:
546 found_iconic_arg = TRUE;
547 break;
548#ifdef HAVE_GTK2
549 case ARG_ROLE:
550 role_argument = value; /* used later in gui_mch_open() */
551 break;
552#endif
553#ifdef FEAT_NETBEANS_INTG
554 case ARG_NETBEANS:
555 ++usingNetbeans;
556 gui.dofork = FALSE; /* don't fork() when starting GUI */
557 netbeansArg = argv[i];
558 break;
559#endif
560 default:
561 break;
562 }
563 }
564
565 /* These arguments make gnome_program_init() print a message and exit.
566 * Must start the GUI for this, otherwise ":gui" will exit later! */
567 if (option->flags & ARG_NEEDS_GUI)
568 gui.starting = TRUE;
569
570 if (option->flags & ARG_KEEP)
571 ++i;
572 else
573 {
574 /* Remove the flag from the argument vector. */
575 if (--*argc > i)
576 {
577 int n_strip = 1;
578
579 /* Move the argument's value as well, if there is one. */
580 if ((option->flags & ARG_HAS_VALUE)
581 && argv[i][len] != '='
582 && strcmp(argv[i + 1], "--") != 0)
583 {
584 ++n_strip;
585 --*argc;
586 if (option->flags & ARG_FOR_GTK)
587 gui_argv[gui_argc++] = argv[i + 1];
588 }
589
590 if (*argc > i)
591 mch_memmove(&argv[i], &argv[i + n_strip],
592 (*argc - i) * sizeof(char *));
593 }
594 argv[*argc] = NULL;
595 }
596 }
597
598 gui_argv[gui_argc] = NULL;
599}
600
601/*
602 * This should be maybe completely removed.
603 * Doesn't seem possible, since check_copy_area() relies on
604 * this information. --danielk
605 */
606/*ARGSUSED*/
607 static gint
608visibility_event(GtkWidget *widget, GdkEventVisibility *event, gpointer data)
609{
610 gui.visibility = event->state;
611 /*
612 * When we do an gdk_window_copy_area(), and the window is partially
613 * obscured, we want to receive an event to tell us whether it worked
614 * or not.
615 */
616 if (gui.text_gc != NULL)
617 gdk_gc_set_exposures(gui.text_gc,
618 gui.visibility != GDK_VISIBILITY_UNOBSCURED);
619 return FALSE;
620}
621
622/*
623 * Redraw the corresponding portions of the screen.
624 */
625/*ARGSUSED*/
626 static gint
627expose_event(GtkWidget *widget, GdkEventExpose *event, gpointer data)
628{
629 /* Skip this when the GUI isn't set up yet, will redraw later. */
630 if (gui.starting)
631 return FALSE;
632
633 out_flush(); /* make sure all output has been processed */
634 gui_redraw(event->area.x, event->area.y,
635 event->area.width, event->area.height);
636
637 /* Clear the border areas if needed */
638 if (event->area.x < FILL_X(0))
639 gdk_window_clear_area(gui.drawarea->window, 0, 0, FILL_X(0), 0);
640 if (event->area.y < FILL_Y(0))
641 gdk_window_clear_area(gui.drawarea->window, 0, 0, 0, FILL_Y(0));
642 if (event->area.x > FILL_X(Columns))
643 gdk_window_clear_area(gui.drawarea->window,
644 FILL_X((int)Columns), 0, 0, 0);
645 if (event->area.y > FILL_Y(Rows))
646 gdk_window_clear_area(gui.drawarea->window, 0, FILL_Y((int)Rows), 0, 0);
647
648 return FALSE;
649}
650
651#ifdef FEAT_CLIENTSERVER
652/*
653 * Handle changes to the "Comm" property
654 */
655/*ARGSUSED2*/
656 static gint
657property_event(GtkWidget *widget, GdkEventProperty *event, gpointer data)
658{
659 if (event->type == GDK_PROPERTY_NOTIFY
660 && event->state == (int)GDK_PROPERTY_NEW_VALUE
661 && GDK_WINDOW_XWINDOW(event->window) == commWindow
662 && GET_X_ATOM(event->atom) == commProperty)
663 {
664 XEvent xev;
665
666 /* Translate to XLib */
667 xev.xproperty.type = PropertyNotify;
668 xev.xproperty.atom = commProperty;
669 xev.xproperty.window = commWindow;
670 xev.xproperty.state = PropertyNewValue;
671 serverEventProc(GDK_WINDOW_XDISPLAY(widget->window), &xev);
672
673 if (gtk_main_level() > 0)
674 gtk_main_quit();
675 }
676 return FALSE;
677}
678#endif
679
680
681/****************************************************************************
682 * Focus handlers:
683 */
684
685
686/*
687 * This is a simple state machine:
688 * BLINK_NONE not blinking at all
689 * BLINK_OFF blinking, cursor is not shown
690 * BLINK_ON blinking, cursor is shown
691 */
692
693#define BLINK_NONE 0
694#define BLINK_OFF 1
695#define BLINK_ON 2
696
697static int blink_state = BLINK_NONE;
698static long_u blink_waittime = 700;
699static long_u blink_ontime = 400;
700static long_u blink_offtime = 250;
701static guint blink_timer = 0;
702
703 void
704gui_mch_set_blinking(long waittime, long on, long off)
705{
706 blink_waittime = waittime;
707 blink_ontime = on;
708 blink_offtime = off;
709}
710
711/*
712 * Stop the cursor blinking. Show the cursor if it wasn't shown.
713 */
714 void
715gui_mch_stop_blink(void)
716{
717 if (blink_timer)
718 {
719 gtk_timeout_remove(blink_timer);
720 blink_timer = 0;
721 }
722 if (blink_state == BLINK_OFF)
723 gui_update_cursor(TRUE, FALSE);
724 blink_state = BLINK_NONE;
725}
726
727/*ARGSUSED*/
728 static gint
729blink_cb(gpointer data)
730{
731 if (blink_state == BLINK_ON)
732 {
733 gui_undraw_cursor();
734 blink_state = BLINK_OFF;
735 blink_timer = gtk_timeout_add((guint32)blink_offtime,
736 (GtkFunction) blink_cb, NULL);
737 }
738 else
739 {
740 gui_update_cursor(TRUE, FALSE);
741 blink_state = BLINK_ON;
742 blink_timer = gtk_timeout_add((guint32)blink_ontime,
743 (GtkFunction) blink_cb, NULL);
744 }
745
746 return FALSE; /* don't happen again */
747}
748
749/*
750 * Start the cursor blinking. If it was already blinking, this restarts the
751 * waiting time and shows the cursor.
752 */
753 void
754gui_mch_start_blink(void)
755{
756 if (blink_timer)
757 gtk_timeout_remove(blink_timer);
758 /* Only switch blinking on if none of the times is zero */
759 if (blink_waittime && blink_ontime && blink_offtime && gui.in_focus)
760 {
761 blink_timer = gtk_timeout_add((guint32)blink_waittime,
762 (GtkFunction) blink_cb, NULL);
763 blink_state = BLINK_ON;
764 gui_update_cursor(TRUE, FALSE);
765 }
766}
767
768/*ARGSUSED*/
769 static gint
770enter_notify_event(GtkWidget *widget, GdkEventCrossing *event, gpointer data)
771{
772 if (blink_state == BLINK_NONE)
773 gui_mch_start_blink();
774
775 /* make sure keyboard input goes there */
776 if (gtk_socket_id == 0 || !GTK_WIDGET_HAS_FOCUS(gui.drawarea))
777 gtk_widget_grab_focus(gui.drawarea);
778
779 return FALSE;
780}
781
782/*ARGSUSED*/
783 static gint
784leave_notify_event(GtkWidget *widget, GdkEventCrossing *event, gpointer data)
785{
786 if (blink_state != BLINK_NONE)
787 gui_mch_stop_blink();
788
789 return FALSE;
790}
791
792/*ARGSUSED*/
793 static gint
794focus_in_event(GtkWidget *widget, GdkEventFocus *event, gpointer data)
795{
796 gui_focus_change(TRUE);
797
798 if (blink_state == BLINK_NONE)
799 gui_mch_start_blink();
800
801 /* make sure keyboard input goes there */
802 if (gtk_socket_id == 0)
803 gtk_widget_grab_focus(gui.drawarea);
804
805 return TRUE;
806}
807
808/*ARGSUSED*/
809 static gint
810focus_out_event(GtkWidget *widget, GdkEventFocus *event, gpointer data)
811{
812 gui_focus_change(FALSE);
813
814 if (blink_state != BLINK_NONE)
815 gui_mch_stop_blink();
816
817 return TRUE;
818}
819
820
821#ifdef HAVE_GTK2
822/*
823 * Translate a GDK key value to UTF-8 independently of the current locale.
824 * The output is written to string, which must have room for at least 6 bytes
825 * plus the NUL terminator. Returns the length in bytes.
826 *
827 * This function is used in the GTK+ 2 GUI only. The GTK+ 1 code makes use
828 * of GdkEventKey::string instead. But event->string is evil; see here why:
829 * http://developer.gnome.org/doc/API/2.0/gdk/gdk-Event-Structures.html#GdkEventKey
830 */
831 static int
832keyval_to_string(unsigned int keyval, unsigned int state, char_u *string)
833{
834 int len;
835 guint32 uc;
836
837 uc = gdk_keyval_to_unicode(keyval);
838 if (uc != 0)
839 {
840 /* Check for CTRL-foo */
841 if ((state & GDK_CONTROL_MASK) && uc >= 0x20 && uc < 0x80)
842 {
843 /* These mappings look arbitrary at the first glance, but in fact
844 * resemble quite exactly the behaviour of the GTK+ 1.2 GUI on my
845 * machine. The only difference is BS vs. DEL for CTRL-8 (makes
846 * more sense and is consistent with usual terminal behaviour). */
847 if (uc >= '@')
848 string[0] = uc & 0x1F;
849 else if (uc == '2')
850 string[0] = NUL;
851 else if (uc >= '3' && uc <= '7')
852 string[0] = uc ^ 0x28;
853 else if (uc == '8')
854 string[0] = BS;
855 else if (uc == '?')
856 string[0] = DEL;
857 else
858 string[0] = uc;
859 len = 1;
860 }
861 else
862 {
863 /* Translate a normal key to UTF-8. This doesn't work for dead
864 * keys of course, you _have_ to use an input method for that. */
865 len = utf_char2bytes((int)uc, string);
866 }
867 }
868 else
869 {
870 /* Translate keys which are represented by ASCII control codes in Vim.
871 * There are only a few of those; most control keys are translated to
872 * special terminal-like control sequences. */
873 len = 1;
874 switch (keyval)
875 {
876 case GDK_Tab: case GDK_KP_Tab: case GDK_ISO_Left_Tab:
877 string[0] = TAB;
878 break;
879 case GDK_Linefeed:
880 string[0] = NL;
881 break;
882 case GDK_Return: case GDK_ISO_Enter: case GDK_3270_Enter:
883 string[0] = CAR;
884 break;
885 case GDK_Escape:
886 string[0] = ESC;
887 break;
888 default:
889 len = 0;
890 break;
891 }
892 }
893 string[len] = NUL;
894
895 return len;
896}
897#endif /* HAVE_GTK2 */
898
899/*
900 * Main keyboard handler:
901 */
902/*ARGSUSED*/
903 static gint
904key_press_event(GtkWidget *widget, GdkEventKey *event, gpointer data)
905{
906#ifdef HAVE_GTK2
907 /* 256 bytes is way over the top, but for safety let's reduce it only
908 * for GTK+ 2 where we know for sure how large the string might get.
909 * (That is, up to 6 bytes + NUL + CSI escapes + safety measure.) */
910 char_u string[32], string2[32];
911#else
912 char_u string[256], string2[256];
913#endif
914 guint key_sym;
915 int len;
916 int i;
917 int modifiers;
918 int key;
919 guint state;
920 char_u *s, *d;
921
922 key_sym = event->keyval;
923 state = event->state;
924#ifndef HAVE_GTK2 /* deprecated */
925 len = event->length;
926 g_assert(len <= sizeof(string));
927#endif
928
929#ifndef HAVE_GTK2
930 /*
931 * It appears as if we always want to consume a key-press (there currently
932 * aren't any 'return FALSE's), so we always do this: when running in a
933 * GtkPlug and not a window, we must prevent emission of the key_press
934 * EVENT from continuing (which is 'beyond' the level of stopping mere
935 * signals by returning FALSE), otherwise things like tab/cursor-keys are
936 * processed by the GtkPlug default handler, which moves input focus away
937 * from us!
938 * Note: This should no longer be necessary with GTK+ 2.
939 */
940 if (gtk_socket_id != 0)
941 gtk_signal_emit_stop_by_name(GTK_OBJECT(widget), "key_press_event");
942#endif
943
944#ifdef FEAT_XIM
945 if (xim_queue_key_press_event(event, TRUE))
946 return TRUE;
947#endif
948
949#ifdef FEAT_HANGULIN
950 if (key_sym == GDK_space && (state & GDK_SHIFT_MASK))
951 {
952 hangul_input_state_toggle();
953 return TRUE;
954 }
955#endif
956
957#ifdef SunXK_F36
958 /*
959 * These keys have bogus lookup strings, and trapping them here is
960 * easier than trying to XRebindKeysym() on them with every possible
961 * combination of modifiers.
962 */
963 if (key_sym == SunXK_F36 || key_sym == SunXK_F37)
964 len = 0;
965 else
966#endif
967 {
968#ifdef HAVE_GTK2
969 len = keyval_to_string(key_sym, state, string2);
970
971 /* Careful: convert_input() doesn't handle the NUL character.
972 * No need to convert pure ASCII anyway, thus the len > 1 check. */
973 if (len > 1 && input_conv.vc_type != CONV_NONE)
974 len = convert_input(string2, len, sizeof(string2));
975
976 s = string2;
977#else
978# ifdef FEAT_MBYTE
979 if (input_conv.vc_type != CONV_NONE)
980 {
981 mch_memmove(string2, event->string, len);
982 len = convert_input(string2, len, sizeof(string2));
983 s = string2;
984 }
985 else
986# endif
987 s = (char_u *)event->string;
988#endif
989
990 d = string;
991 for (i = 0; i < len; ++i)
992 {
993 *d++ = s[i];
994 if (d[-1] == CSI && d + 2 < string + sizeof(string))
995 {
996 /* Turn CSI into K_CSI. */
997 *d++ = KS_EXTRA;
998 *d++ = (int)KE_CSI;
999 }
1000 }
1001 len = d - string;
1002 }
1003
1004 /* Shift-Tab results in Left_Tab, but we want <S-Tab> */
1005 if (key_sym == GDK_ISO_Left_Tab)
1006 {
1007 key_sym = GDK_Tab;
1008 state |= GDK_SHIFT_MASK;
1009 }
1010
1011#ifndef HAVE_GTK2 /* for GTK+ 2, we handle this in keyval_to_string() */
1012 if ((key_sym == GDK_2 || key_sym == GDK_at) && (state & GDK_CONTROL_MASK))
1013 {
1014 string[0] = NUL; /* CTRL-2 and CTRL-@ is NUL */
1015 len = 1;
1016 }
1017 else if (len == 0 && (key_sym == GDK_space || key_sym == GDK_Tab))
1018 {
1019 /* When there are modifiers, these keys get zero length; we need the
1020 * original key here to be able to add a modifier below. */
1021 string[0] = (key_sym & 0xff);
1022 len = 1;
1023 }
1024#endif
1025
1026#ifdef FEAT_MENU
1027 /* If there is a menu and 'wak' is "yes", or 'wak' is "menu" and the key
1028 * is a menu shortcut, we ignore everything with the ALT modifier. */
1029 if ((state & GDK_MOD1_MASK)
1030 && gui.menu_is_active
1031 && (*p_wak == 'y'
1032 || (*p_wak == 'm'
1033 && len == 1
1034 && gui_is_menu_shortcut(string[0]))))
1035# ifdef HAVE_GTK2
1036 /* For GTK2 we return false to signify that we haven't handled the
1037 * keypress, so that gtk will handle the mnemonic or accelerator. */
1038 return FALSE;
1039# else
1040 return TRUE;
1041# endif
1042#endif
1043
1044 /* Check for Alt/Meta key (Mod1Mask), but not for a BS, DEL or character
1045 * that already has the 8th bit set.
1046 * Don't do this for <S-M-Tab>, that should become K_S_TAB with ALT.
1047 * Don't do this for double-byte encodings, it turns the char into a lead
1048 * byte. */
1049 if (len == 1
1050 && (state & GDK_MOD1_MASK)
1051 && !(key_sym == GDK_BackSpace || key_sym == GDK_Delete)
1052 && (string[0] & 0x80) == 0
1053 && !(key_sym == GDK_Tab && (state & GDK_SHIFT_MASK))
1054#ifdef FEAT_MBYTE
1055 && !enc_dbcs
1056#endif
1057 )
1058 {
1059 string[0] |= 0x80;
1060 state &= ~GDK_MOD1_MASK; /* don't use it again */
1061#ifdef FEAT_MBYTE
1062 if (enc_utf8) /* convert to utf-8 */
1063 {
1064 string[1] = string[0] & 0xbf;
1065 string[0] = ((unsigned)string[0] >> 6) + 0xc0;
1066 if (string[1] == CSI)
1067 {
1068 string[2] = KS_EXTRA;
1069 string[3] = (int)KE_CSI;
1070 len = 4;
1071 }
1072 else
1073 len = 2;
1074 }
1075#endif
1076 }
1077
1078 /* Check for special keys. Also do this when len == 1 (key has an ASCII
1079 * value) to detect backspace, delete and keypad keys. */
1080 if (len == 0 || len == 1)
1081 {
1082 for (i = 0; special_keys[i].key_sym != 0; i++)
1083 {
1084 if (special_keys[i].key_sym == key_sym)
1085 {
1086 string[0] = CSI;
1087 string[1] = special_keys[i].code0;
1088 string[2] = special_keys[i].code1;
1089 len = -3;
1090 break;
1091 }
1092 }
1093 }
1094
1095 if (len == 0) /* Unrecognized key */
1096 return TRUE;
1097
1098#if defined(FEAT_XIM) && defined(FEAT_GUI_GTK) && !defined(HAVE_GTK2)
1099 /* Cancel or type backspace. For GTK2, im_commit_cb() does the same. */
1100 preedit_start_col = MAXCOL;
1101 xim_changed_while_preediting = TRUE;
1102#endif
1103
1104 /* Special keys (and a few others) may have modifiers. Also when using a
1105 * double-byte encoding (can't set the 8th bit). */
1106 if (len == -3 || key_sym == GDK_space || key_sym == GDK_Tab
1107 || key_sym == GDK_Return || key_sym == GDK_Linefeed
1108 || key_sym == GDK_Escape || key_sym == GDK_KP_Tab
1109 || key_sym == GDK_ISO_Enter || key_sym == GDK_3270_Enter
1110#ifdef FEAT_MBYTE
1111 || (enc_dbcs && len == 1 && (state & GDK_MOD1_MASK))
1112#endif
1113 )
1114 {
1115 modifiers = 0;
1116 if (state & GDK_SHIFT_MASK)
1117 modifiers |= MOD_MASK_SHIFT;
1118 if (state & GDK_CONTROL_MASK)
1119 modifiers |= MOD_MASK_CTRL;
1120 if (state & GDK_MOD1_MASK)
1121 modifiers |= MOD_MASK_ALT;
1122
1123 /*
1124 * For some keys a shift modifier is translated into another key
1125 * code.
1126 */
1127 if (len == -3)
1128 key = TO_SPECIAL(string[1], string[2]);
1129 else
1130 key = string[0];
1131
1132 key = simplify_key(key, &modifiers);
1133 if (key == CSI)
1134 key = K_CSI;
1135 if (IS_SPECIAL(key))
1136 {
1137 string[0] = CSI;
1138 string[1] = K_SECOND(key);
1139 string[2] = K_THIRD(key);
1140 len = 3;
1141 }
1142 else
1143 {
1144 string[0] = key;
1145 len = 1;
1146 }
1147
1148 if (modifiers != 0)
1149 {
1150 string2[0] = CSI;
1151 string2[1] = KS_MODIFIER;
1152 string2[2] = modifiers;
1153 add_to_input_buf(string2, 3);
1154 }
1155 }
1156
1157 if (len == 1 && ((string[0] == Ctrl_C && ctrl_c_interrupts)
1158 || (string[0] == intr_char && intr_char != Ctrl_C)))
1159 {
1160 trash_input_buf();
1161 got_int = TRUE;
1162 }
1163
1164 add_to_input_buf(string, len);
1165
1166 /* blank out the pointer if necessary */
1167 if (p_mh)
1168 gui_mch_mousehide(TRUE);
1169
1170 if (gtk_main_level() > 0)
1171 gtk_main_quit();
1172
1173 return TRUE;
1174}
1175
1176#if defined(FEAT_XIM) && defined(HAVE_GTK2)
1177/*ARGSUSED0*/
1178 static gboolean
1179key_release_event(GtkWidget *widget, GdkEventKey *event, gpointer data)
1180{
1181 /*
1182 * GTK+ 2 input methods may do fancy stuff on key release events too.
1183 * With the default IM for instance, you can enter any UCS code point
1184 * by holding down CTRL-SHIFT and typing hexadecimal digits.
1185 */
1186 return xim_queue_key_press_event(event, FALSE);
1187}
1188#endif
1189
1190
1191/****************************************************************************
1192 * Selection handlers:
1193 */
1194
1195/*ARGSUSED*/
1196 static gint
1197selection_clear_event(GtkWidget *widget,
1198 GdkEventSelection *event,
1199 gpointer user_data)
1200{
1201 if (event->selection == clip_plus.gtk_sel_atom)
1202 clip_lose_selection(&clip_plus);
1203 else
1204 clip_lose_selection(&clip_star);
1205
1206 if (gtk_main_level() > 0)
1207 gtk_main_quit();
1208
1209 return TRUE;
1210}
1211
1212#define RS_NONE 0 /* selection_received_cb() not called yet */
1213#define RS_OK 1 /* selection_received_cb() called and OK */
1214#define RS_FAIL 2 /* selection_received_cb() called and failed */
1215static int received_selection = RS_NONE;
1216
1217/*ARGSUSED*/
1218 static void
1219selection_received_cb(GtkWidget *widget,
1220 GtkSelectionData *data,
1221 guint time_,
1222 gpointer user_data)
1223{
1224 VimClipboard *cbd;
1225 char_u *text;
1226 char_u *tmpbuf = NULL;
1227#ifdef HAVE_GTK2
1228 guchar *tmpbuf_utf8 = NULL;
1229#endif
1230 int len;
1231 int motion_type;
1232
1233 if (data->selection == clip_plus.gtk_sel_atom)
1234 cbd = &clip_plus;
1235 else
1236 cbd = &clip_star;
1237
1238 text = (char_u *)data->data;
1239 len = data->length;
1240 motion_type = MCHAR;
1241
1242 if (text == NULL || len <= 0)
1243 {
1244 received_selection = RS_FAIL;
1245 /* clip_free_selection(cbd); ??? */
1246
1247 if (gtk_main_level() > 0)
1248 gtk_main_quit();
1249
1250 return;
1251 }
1252
1253 if (data->type == vim_atom)
1254 {
1255 motion_type = *text++;
1256 --len;
1257 }
1258
1259#ifdef FEAT_MBYTE
1260 else if (data->type == vimenc_atom)
1261 {
1262 char_u *enc;
1263 vimconv_T conv;
1264
1265 motion_type = *text++;
1266 --len;
1267
1268 enc = text;
1269 text += STRLEN(text) + 1;
1270 len -= text - enc;
1271
1272 /* If the encoding of the text is different from 'encoding', attempt
1273 * converting it. */
1274 conv.vc_type = CONV_NONE;
1275 convert_setup(&conv, enc, p_enc);
1276 if (conv.vc_type != CONV_NONE)
1277 {
1278 tmpbuf = string_convert(&conv, text, &len);
1279 if (tmpbuf != NULL)
1280 text = tmpbuf;
1281 convert_setup(&conv, NULL, NULL);
1282 }
1283 }
1284#endif
1285
1286#ifdef HAVE_GTK2
1287 /* gtk_selection_data_get_text() handles all the nasty details
1288 * and targets and encodings etc. This rocks so hard. */
1289 else
1290 {
1291 tmpbuf_utf8 = gtk_selection_data_get_text(data);
1292 if (tmpbuf_utf8 != NULL)
1293 {
1294 len = STRLEN(tmpbuf_utf8);
1295 if (input_conv.vc_type != CONV_NONE)
1296 {
1297 tmpbuf = string_convert(&input_conv, tmpbuf_utf8, &len);
1298 if (tmpbuf != NULL)
1299 text = tmpbuf;
1300 }
1301 else
1302 text = tmpbuf_utf8;
1303 }
1304 }
1305#else /* !HAVE_GTK2 */
1306# ifdef FEAT_MBYTE
1307 else if (data->type == utf8_string_atom)
1308 {
1309 vimconv_T conv;
1310
1311 conv.vc_type = CONV_NONE;
1312 convert_setup(&conv, (char_u *)"utf-8", p_enc);
1313
1314 if (conv.vc_type != CONV_NONE)
1315 {
1316 tmpbuf = string_convert(&conv, text, &len);
1317 convert_setup(&conv, NULL, NULL);
1318 }
1319 if (tmpbuf != NULL)
1320 text = tmpbuf;
1321 }
1322# endif
1323 else if (data->type == compound_text_atom || data->type == text_atom)
1324 {
1325 char **list = NULL;
1326 int count;
1327 int i;
1328 unsigned tmplen = 0;
1329
1330 count = gdk_text_property_to_text_list(data->type, data->format,
1331 data->data, data->length,
1332 &list);
1333 for (i = 0; i < count; ++i)
1334 tmplen += strlen(list[i]);
1335
1336 tmpbuf = alloc(tmplen + 1);
1337 if (tmpbuf != NULL)
1338 {
1339 tmpbuf[0] = NUL;
1340 for (i = 0; i < count; ++i)
1341 STRCAT(tmpbuf, list[i]);
1342 text = tmpbuf;
1343 len = tmplen;
1344 }
1345
1346 if (list != NULL)
1347 gdk_free_text_list(list);
1348 }
1349#endif /* !HAVE_GTK2 */
1350
1351 clip_yank_selection(motion_type, text, (long)len, cbd);
1352 received_selection = RS_OK;
1353 vim_free(tmpbuf);
1354#ifdef HAVE_GTK2
1355 g_free(tmpbuf_utf8);
1356#endif
1357
1358 if (gtk_main_level() > 0)
1359 gtk_main_quit();
1360}
1361
1362/*
1363 * Prepare our selection data for passing it to the external selection
1364 * client.
1365 */
1366/*ARGSUSED*/
1367 static void
1368selection_get_cb(GtkWidget *widget,
1369 GtkSelectionData *selection_data,
1370 guint info,
1371 guint time_,
1372 gpointer user_data)
1373{
1374 char_u *string;
1375 char_u *tmpbuf;
1376 long_u tmplen;
1377 int length;
1378 int motion_type;
1379 GdkAtom type;
1380 VimClipboard *cbd;
1381
1382 if (selection_data->selection == clip_plus.gtk_sel_atom)
1383 cbd = &clip_plus;
1384 else
1385 cbd = &clip_star;
1386
1387 if (!cbd->owned)
1388 return; /* Shouldn't ever happen */
1389
1390 if (info != (guint)TARGET_STRING
1391#ifdef FEAT_MBYTE
1392 && info != (guint)TARGET_UTF8_STRING
1393 && info != (guint)TARGET_VIMENC
1394#endif
1395 && info != (guint)TARGET_VIM
1396 && info != (guint)TARGET_COMPOUND_TEXT
1397 && info != (guint)TARGET_TEXT)
1398 return;
1399
1400 /* get the selection from the '*'/'+' register */
1401 clip_get_selection(cbd);
1402
1403 motion_type = clip_convert_selection(&string, &tmplen, cbd);
1404 if (motion_type < 0 || string == NULL)
1405 return;
1406 /* Due to int arguments we can't handle more than G_MAXINT. Also
1407 * reserve one extra byte for NUL or the motion type; just in case.
1408 * (Not that pasting 2G of text is ever going to work, but... ;-) */
1409 length = MIN(tmplen, (long_u)(G_MAXINT - 1));
1410
1411 if (info == (guint)TARGET_VIM)
1412 {
1413 tmpbuf = alloc((unsigned)length + 1);
1414 if (tmpbuf != NULL)
1415 {
1416 tmpbuf[0] = motion_type;
1417 mch_memmove(tmpbuf + 1, string, (size_t)length);
1418 }
1419 /* For our own format, the first byte contains the motion type */
1420 ++length;
1421 vim_free(string);
1422 string = tmpbuf;
1423 type = vim_atom;
1424 }
1425
1426#ifdef FEAT_MBYTE
1427 else if (info == (guint)TARGET_VIMENC)
1428 {
1429 int l = STRLEN(p_enc);
1430
1431 /* contents: motion_type 'encoding' NUL text */
1432 tmpbuf = alloc((unsigned)length + l + 2);
1433 if (tmpbuf != NULL)
1434 {
1435 tmpbuf[0] = motion_type;
1436 STRCPY(tmpbuf + 1, p_enc);
1437 mch_memmove(tmpbuf + l + 2, string, (size_t)length);
1438 }
1439 length += l + 2;
1440 vim_free(string);
1441 string = tmpbuf;
1442 type = vimenc_atom;
1443 }
1444#endif
1445
1446#ifdef HAVE_GTK2
1447 /* gtk_selection_data_set_text() handles everything for us. This is
1448 * so easy and simple and cool, it'd be insane not to use it. */
1449 else
1450 {
1451 if (output_conv.vc_type != CONV_NONE)
1452 {
1453 tmpbuf = string_convert(&output_conv, string, &length);
1454 vim_free(string);
1455 if (tmpbuf == NULL)
1456 return;
1457 string = tmpbuf;
1458 }
1459 /* Validate the string to avoid runtime warnings */
1460 if (g_utf8_validate((const char *)string, (gssize)length, NULL))
1461 {
1462 gtk_selection_data_set_text(selection_data,
1463 (const char *)string, length);
1464 }
1465 vim_free(string);
1466 return;
1467 }
1468#else /* !HAVE_GTK2 */
1469# ifdef FEAT_MBYTE
1470 else if (info == (guint)TARGET_UTF8_STRING)
1471 {
1472 vimconv_T conv;
1473
1474 conv.vc_type = CONV_NONE;
1475 convert_setup(&conv, p_enc, (char_u *)"utf-8");
1476
1477 if (conv.vc_type != CONV_NONE)
1478 {
1479 tmpbuf = string_convert(&conv, string, &length);
1480 convert_setup(&conv, NULL, NULL);
1481 vim_free(string);
1482 string = tmpbuf;
1483 }
1484 type = utf8_string_atom;
1485 }
1486# endif
1487 else if (info == (guint)TARGET_COMPOUND_TEXT
1488 || info == (guint)TARGET_TEXT)
1489 {
1490 int format;
1491
1492 /* Copy the string to ensure NUL-termination */
1493 tmpbuf = vim_strnsave(string, length);
1494 vim_free(string);
1495 if (tmpbuf != NULL)
1496 {
1497 gdk_string_to_compound_text((const char *)tmpbuf,
1498 &type, &format, &string, &length);
1499 vim_free(tmpbuf);
1500 selection_data->type = type;
1501 selection_data->format = format;
1502 gtk_selection_data_set(selection_data, type, format, string, length);
1503 gdk_free_compound_text(string);
1504 }
1505 return;
1506 }
1507 else
1508 {
1509 type = GDK_TARGET_STRING;
1510 }
1511#endif /* !HAVE_GTK2 */
1512
1513 if (string != NULL)
1514 {
1515 selection_data->type = selection_data->target;
1516 selection_data->format = 8; /* 8 bits per char */
1517
1518 gtk_selection_data_set(selection_data, type, 8, string, length);
1519 vim_free(string);
1520 }
1521}
1522
1523/*
1524 * Check if the GUI can be started. Called before gvimrc is sourced.
1525 * Return OK or FAIL.
1526 */
1527 int
1528gui_mch_init_check(void)
1529{
1530#ifndef HAVE_GTK2
1531 /* This is needed to make the locale handling consistant between the GUI
1532 * and the rest of VIM. */
1533 gtk_set_locale();
1534#endif
1535
1536#ifdef FEAT_GUI_GNOME
1537 if (gtk_socket_id == 0)
1538 using_gnome = 1;
1539#endif
1540
1541 /* Don't use gtk_init() or gnome_init(), it exits on failure. */
1542 if (!gtk_init_check(&gui_argc, &gui_argv))
1543 {
1544 gui.dying = TRUE;
1545 EMSG(_(e_opendisp));
1546 return FAIL;
1547 }
1548
1549 return OK;
1550}
1551
1552
1553/****************************************************************************
1554 * Mouse handling callbacks
1555 */
1556
1557
1558static guint mouse_click_timer = 0;
1559static int mouse_timed_out = TRUE;
1560
1561/*
1562 * Timer used to recognize multiple clicks of the mouse button
1563 */
1564 static gint
1565mouse_click_timer_cb(gpointer data)
1566{
1567 /* we don't use this information currently */
1568 int *timed_out = (int *) data;
1569
1570 *timed_out = TRUE;
1571 return FALSE; /* don't happen again */
1572}
1573
1574static guint motion_repeat_timer = 0;
1575static int motion_repeat_offset = FALSE;
1576static gint motion_repeat_timer_cb(gpointer);
1577
1578 static void
1579process_motion_notify(int x, int y, GdkModifierType state)
1580{
1581 int button;
1582 int_u vim_modifiers;
1583
1584 button = (state & (GDK_BUTTON1_MASK | GDK_BUTTON2_MASK |
1585 GDK_BUTTON3_MASK | GDK_BUTTON4_MASK |
1586 GDK_BUTTON5_MASK))
1587 ? MOUSE_DRAG : ' ';
1588
1589 /* If our pointer is currently hidden, then we should show it. */
1590 gui_mch_mousehide(FALSE);
1591
1592 /* Just moving the rodent above the drawing area without any button
1593 * being pressed. */
1594 if (button != MOUSE_DRAG)
1595 {
1596 gui_mouse_moved(x, y);
1597 return;
1598 }
1599
1600 /* translate modifier coding between the main engine and GTK */
1601 vim_modifiers = 0x0;
1602 if (state & GDK_SHIFT_MASK)
1603 vim_modifiers |= MOUSE_SHIFT;
1604 if (state & GDK_CONTROL_MASK)
1605 vim_modifiers |= MOUSE_CTRL;
1606 if (state & GDK_MOD1_MASK)
1607 vim_modifiers |= MOUSE_ALT;
1608
1609 /* inform the editor engine about the occurence of this event */
1610 gui_send_mouse_event(button, x, y, FALSE, vim_modifiers);
1611
1612 if (gtk_main_level() > 0)
1613 gtk_main_quit();
1614
1615 /*
1616 * Auto repeat timer handling.
1617 */
1618 if (x < 0 || y < 0
1619 || x >= gui.drawarea->allocation.width
1620 || y >= gui.drawarea->allocation.height)
1621 {
1622
1623 int dx;
1624 int dy;
1625 int offshoot;
1626 int delay = 10;
1627
1628 /* Calculate the maximal distance of the cursor from the drawing area.
1629 * (offshoot can't become negative here!).
1630 */
1631 dx = x < 0 ? -x : x - gui.drawarea->allocation.width;
1632 dy = y < 0 ? -y : y - gui.drawarea->allocation.height;
1633
1634 offshoot = dx > dy ? dx : dy;
1635
1636 /* Make a linearly declaying timer delay with a threshold of 5 at a
1637 * distance of 127 pixels from the main window.
1638 *
1639 * One could think endlessly about the most ergonomic variant here.
1640 * For example it could make sense to calculate the distance from the
1641 * drags start instead...
1642 *
1643 * Maybe a parabolic interpolation would suite us better here too...
1644 */
1645 if (offshoot > 127)
1646 {
1647 /* 5 appears to be somehow near to my perceptual limits :-). */
1648 delay = 5;
1649 }
1650 else
1651 {
1652 delay = (130 * (127 - offshoot)) / 127 + 5;
1653 }
1654
1655 /* shoot again */
1656 if (!motion_repeat_timer)
1657 motion_repeat_timer = gtk_timeout_add((guint32)delay,
1658 motion_repeat_timer_cb, NULL);
1659 }
1660}
1661
1662/*
1663 * Timer used to recognize multiple clicks of the mouse button.
1664 */
1665/*ARGSUSED0*/
1666 static gint
1667motion_repeat_timer_cb(gpointer data)
1668{
1669 int x;
1670 int y;
1671 GdkModifierType state;
1672
1673 gdk_window_get_pointer(gui.drawarea->window, &x, &y, &state);
1674
1675 if (!(state & (GDK_BUTTON1_MASK | GDK_BUTTON2_MASK |
1676 GDK_BUTTON3_MASK | GDK_BUTTON4_MASK |
1677 GDK_BUTTON5_MASK)))
1678 {
1679 motion_repeat_timer = 0;
1680 return FALSE;
1681 }
1682
1683 /* If there already is a mouse click in the input buffer, wait another
1684 * time (otherwise we would create a backlog of clicks) */
1685 if (vim_used_in_input_buf() > 10)
1686 return TRUE;
1687
1688 motion_repeat_timer = 0;
1689
1690 /*
1691 * Fake a motion event.
1692 * Trick: Pretend the mouse moved to the next character on every other
1693 * event, otherwise drag events will be discarded, because they are still
1694 * in the same character.
1695 */
1696 if (motion_repeat_offset)
1697 x += gui.char_width;
1698
1699 motion_repeat_offset = !motion_repeat_offset;
1700 process_motion_notify(x, y, state);
1701
1702 /* Don't happen again. We will get reinstalled in the synthetic event
1703 * if needed -- thus repeating should still work. */
1704 return FALSE;
1705}
1706
1707/*ARGSUSED2*/
1708 static gint
1709motion_notify_event(GtkWidget *widget, GdkEventMotion *event, gpointer data)
1710{
1711 if (event->is_hint)
1712 {
1713 int x;
1714 int y;
1715 GdkModifierType state;
1716
1717 gdk_window_get_pointer(widget->window, &x, &y, &state);
1718 process_motion_notify(x, y, state);
1719 }
1720 else
1721 {
1722 process_motion_notify((int)event->x, (int)event->y,
1723 (GdkModifierType)event->state);
1724 }
1725
1726 return TRUE; /* handled */
1727}
1728
1729
1730/*
1731 * Mouse button handling. Note please that we are capturing multiple click's
1732 * by our own timeout mechanism instead of the one provided by GTK+ itself.
1733 * This is due to the way the generic VIM code is recognizing multiple clicks.
1734 */
1735/*ARGSUSED2*/
1736 static gint
1737button_press_event(GtkWidget *widget, GdkEventButton *event, gpointer data)
1738{
1739 int button;
1740 int repeated_click = FALSE;
1741 int x, y;
1742 int_u vim_modifiers;
1743
1744 /* Make sure we have focus now we've been selected */
1745 if (gtk_socket_id != 0 && !GTK_WIDGET_HAS_FOCUS(widget))
1746 gtk_widget_grab_focus(widget);
1747
1748 /*
1749 * Don't let additional events about multiple clicks send by GTK to us
1750 * after the initial button press event confuse us.
1751 */
1752 if (event->type != GDK_BUTTON_PRESS)
1753 return FALSE;
1754
1755 x = event->x;
1756 y = event->y;
1757
1758 /* Handle multiple clicks */
1759 if (!mouse_timed_out && mouse_click_timer)
1760 {
1761 gtk_timeout_remove(mouse_click_timer);
1762 mouse_click_timer = 0;
1763 repeated_click = TRUE;
1764 }
1765
1766 mouse_timed_out = FALSE;
1767 mouse_click_timer = gtk_timeout_add((guint32)p_mouset,
1768 mouse_click_timer_cb, &mouse_timed_out);
1769
1770 switch (event->button)
1771 {
1772 case 1:
1773 button = MOUSE_LEFT;
1774 break;
1775 case 2:
1776 button = MOUSE_MIDDLE;
1777 break;
1778 case 3:
1779 button = MOUSE_RIGHT;
1780 break;
1781#ifndef HAVE_GTK2
1782 case 4:
1783 button = MOUSE_4;
1784 break;
1785 case 5:
1786 button = MOUSE_5;
1787 break;
1788#endif
1789 default:
1790 return FALSE; /* Unknown button */
1791 }
1792
1793#ifdef FEAT_XIM
1794 /* cancel any preediting */
1795 if (im_is_preediting())
1796 xim_reset();
1797#endif
1798
1799 vim_modifiers = 0x0;
1800 if (event->state & GDK_SHIFT_MASK)
1801 vim_modifiers |= MOUSE_SHIFT;
1802 if (event->state & GDK_CONTROL_MASK)
1803 vim_modifiers |= MOUSE_CTRL;
1804 if (event->state & GDK_MOD1_MASK)
1805 vim_modifiers |= MOUSE_ALT;
1806
1807 gui_send_mouse_event(button, x, y, repeated_click, vim_modifiers);
1808 if (gtk_main_level() > 0)
1809 gtk_main_quit(); /* make sure the above will be handled immediately */
1810
1811 return TRUE;
1812}
1813
1814#ifdef HAVE_GTK2
1815/*
1816 * GTK+ 2 doesn't handle mouse buttons 4, 5, 6 and 7 the same way as GTK+ 1.
1817 * Instead, it abstracts scrolling via the new GdkEventScroll.
1818 */
1819/*ARGSUSED2*/
1820 static gboolean
1821scroll_event(GtkWidget *widget, GdkEventScroll *event, gpointer data)
1822{
1823 int button;
1824 int_u vim_modifiers = 0;
1825
1826 if (gtk_socket_id != 0 && !GTK_WIDGET_HAS_FOCUS(widget))
1827 gtk_widget_grab_focus(widget);
1828
1829 switch (event->direction)
1830 {
1831 case GDK_SCROLL_UP:
1832 button = MOUSE_4;
1833 break;
1834 case GDK_SCROLL_DOWN:
1835 button = MOUSE_5;
1836 break;
1837 default: /* We don't care about left and right... Yet. */
1838 return FALSE;
1839 }
1840
1841# ifdef FEAT_XIM
1842 /* cancel any preediting */
1843 if (im_is_preediting())
1844 xim_reset();
1845# endif
1846
1847 if (event->state & GDK_SHIFT_MASK)
1848 vim_modifiers |= MOUSE_SHIFT;
1849 if (event->state & GDK_CONTROL_MASK)
1850 vim_modifiers |= MOUSE_CTRL;
1851 if (event->state & GDK_MOD1_MASK)
1852 vim_modifiers |= MOUSE_ALT;
1853
1854 gui_send_mouse_event(button, (int)event->x, (int)event->y,
1855 FALSE, vim_modifiers);
1856
1857 if (gtk_main_level() > 0)
1858 gtk_main_quit(); /* make sure the above will be handled immediately */
1859
1860 return TRUE;
1861}
1862#endif /* HAVE_GTK2 */
1863
1864
1865/*ARGSUSED*/
1866 static gint
1867button_release_event(GtkWidget *widget, GdkEventButton *event, gpointer data)
1868{
1869 int x, y;
1870 int_u vim_modifiers;
1871
1872 /* Remove any motion "machine gun" timers used for automatic further
1873 extension of allocation areas if outside of the applications window
1874 area .*/
1875 if (motion_repeat_timer)
1876 {
1877 gtk_timeout_remove(motion_repeat_timer);
1878 motion_repeat_timer = 0;
1879 }
1880
1881 x = event->x;
1882 y = event->y;
1883
1884 vim_modifiers = 0x0;
1885 if (event->state & GDK_SHIFT_MASK)
1886 vim_modifiers |= MOUSE_SHIFT;
1887 if (event->state & GDK_CONTROL_MASK)
1888 vim_modifiers |= MOUSE_CTRL;
1889 if (event->state & GDK_MOD1_MASK)
1890 vim_modifiers |= MOUSE_ALT;
1891
1892 gui_send_mouse_event(MOUSE_RELEASE, x, y, FALSE, vim_modifiers);
1893 if (gtk_main_level() > 0)
1894 gtk_main_quit(); /* make sure it will be handled immediately */
1895
1896 return TRUE;
1897}
1898
1899
1900#ifdef FEAT_DND
1901/****************************************************************************
1902 * Drag aNd Drop support handlers.
1903 */
1904
1905/*
1906 * Count how many items there may be and separate them with a NUL.
1907 * Apparently the items are separated with \r\n. This is not documented,
1908 * thus be careful not to go past the end. Also allow separation with
1909 * NUL characters.
1910 */
1911 static int
1912count_and_decode_uri_list(char_u *out, char_u *raw, int len)
1913{
1914 int i;
1915 char_u *p = out;
1916 int count = 0;
1917
1918 for (i = 0; i < len; ++i)
1919 {
1920 if (raw[i] == NUL || raw[i] == '\n' || raw[i] == '\r')
1921 {
1922 if (p > out && p[-1] != NUL)
1923 {
1924 ++count;
1925 *p++ = NUL;
1926 }
1927 }
1928 else if (raw[i] == '%' && i + 2 < len && hexhex2nr(raw + i + 1) > 0)
1929 {
1930 *p++ = hexhex2nr(raw + i + 1);
1931 i += 2;
1932 }
1933 else
1934 *p++ = raw[i];
1935 }
1936 if (p > out && p[-1] != NUL)
1937 {
1938 *p = NUL; /* last item didn't have \r or \n */
1939 ++count;
1940 }
1941 return count;
1942}
1943
1944/*
1945 * Parse NUL separated "src" strings. Make it an array "outlist" form. On
1946 * this process, URI which protocol is not "file:" are removed. Return
1947 * length of array (less than "max").
1948 */
1949 static int
1950filter_uri_list(char_u **outlist, int max, char_u *src)
1951{
1952 int i, j;
1953
1954 for (i = j = 0; i < max; ++i)
1955 {
1956 outlist[i] = NULL;
1957 if (STRNCMP(src, "file:", 5) == 0)
1958 {
1959 src += 5;
1960 if (STRNCMP(src, "//localhost", 11) == 0)
1961 src += 11;
1962 while (src[0] == '/' && src[1] == '/')
1963 ++src;
1964 outlist[j++] = vim_strsave(src);
1965 }
1966 src += STRLEN(src) + 1;
1967 }
1968 return j;
1969}
1970
1971 static char_u **
1972parse_uri_list(int *count, char_u *data, int len)
1973{
1974 int n = 0;
1975 char_u *tmp = NULL;
1976 char_u **array = NULL;;
1977
1978 if (data != NULL && len > 0 && (tmp = (char_u *)alloc(len + 1)) != NULL)
1979 {
1980 n = count_and_decode_uri_list(tmp, data, len);
1981 if (n > 0 && (array = (char_u **)alloc(n * sizeof(char_u *))) != NULL)
1982 n = filter_uri_list(array, n, tmp);
1983 }
1984 vim_free(tmp);
1985 *count = n;
1986 return array;
1987}
1988
1989 static void
1990drag_handle_uri_list(GdkDragContext *context,
1991 GtkSelectionData *data,
1992 guint time_,
1993 GdkModifierType state,
1994 gint x,
1995 gint y)
1996{
1997 char_u **fnames;
1998 int nfiles = 0;
1999
2000 fnames = parse_uri_list(&nfiles, data->data, data->length);
2001
2002 if (fnames != NULL && nfiles > 0)
2003 {
2004 int_u modifiers = 0;
2005
2006 gtk_drag_finish(context, TRUE, FALSE, time_); /* accept */
2007
2008 if (state & GDK_SHIFT_MASK)
2009 modifiers |= MOUSE_SHIFT;
2010 if (state & GDK_CONTROL_MASK)
2011 modifiers |= MOUSE_CTRL;
2012 if (state & GDK_MOD1_MASK)
2013 modifiers |= MOUSE_ALT;
2014
2015 gui_handle_drop(x, y, modifiers, fnames, nfiles);
2016 }
2017}
2018
2019 static void
2020drag_handle_text(GdkDragContext *context,
2021 GtkSelectionData *data,
2022 guint time_,
2023 GdkModifierType state)
2024{
2025 char_u dropkey[6] = {CSI, KS_MODIFIER, 0, CSI, KS_EXTRA, (char_u)KE_DROP};
2026 char_u *text;
2027 int len;
2028# ifdef FEAT_MBYTE
2029 char_u *tmpbuf = NULL;
2030# endif
2031
2032 text = data->data;
2033 len = data->length;
2034
2035# ifdef FEAT_MBYTE
2036 if (data->type == utf8_string_atom)
2037 {
2038# ifdef HAVE_GTK2
2039 if (input_conv.vc_type != CONV_NONE)
2040 tmpbuf = string_convert(&input_conv, text, &len);
2041# else
2042 vimconv_T conv;
2043
2044 conv.vc_type = CONV_NONE;
2045 convert_setup(&conv, (char_u *)"utf-8", p_enc);
2046
2047 if (conv.vc_type != CONV_NONE)
2048 {
2049 tmpbuf = string_convert(&conv, text, &len);
2050 convert_setup(&conv, NULL, NULL);
2051 }
2052# endif
2053 if (tmpbuf != NULL)
2054 text = tmpbuf;
2055 }
2056# endif /* FEAT_MBYTE */
2057
2058 dnd_yank_drag_data(text, (long)len);
2059 gtk_drag_finish(context, TRUE, FALSE, time_); /* accept */
2060# ifdef FEAT_MBYTE
2061 vim_free(tmpbuf);
2062# endif
2063
2064 if (state & GDK_SHIFT_MASK)
2065 dropkey[2] |= MOD_MASK_SHIFT;
2066 if (state & GDK_CONTROL_MASK)
2067 dropkey[2] |= MOD_MASK_CTRL;
2068 if (state & GDK_MOD1_MASK)
2069 dropkey[2] |= MOD_MASK_ALT;
2070
2071 if (dropkey[2] != 0)
2072 add_to_input_buf(dropkey, (int)sizeof(dropkey));
2073 else
2074 add_to_input_buf(dropkey + 3, (int)(sizeof(dropkey) - 3));
2075
2076 if (gtk_main_level() > 0)
2077 gtk_main_quit();
2078}
2079
2080/*
2081 * DND receiver.
2082 */
2083/*ARGSUSED2*/
2084 static void
2085drag_data_received_cb(GtkWidget *widget,
2086 GdkDragContext *context,
2087 gint x,
2088 gint y,
2089 GtkSelectionData *data,
2090 guint info,
2091 guint time_,
2092 gpointer user_data)
2093{
2094 GdkModifierType state;
2095
2096 /* Guard against trash */
2097 if (data->data == NULL
2098 || data->length <= 0
2099 || data->format != 8
2100 || data->data[data->length] != '\0')
2101 {
2102 gtk_drag_finish(context, FALSE, FALSE, time_);
2103 return;
2104 }
2105
2106 /* Get the current modifier state for proper distinguishment between
2107 * different operations later. */
2108 gdk_window_get_pointer(widget->window, NULL, NULL, &state);
2109
2110 /* Not sure about the role of "text/plain" here... */
2111 if (info == (guint)TARGET_TEXT_URI_LIST)
2112 drag_handle_uri_list(context, data, time_, state, x, y);
2113 else
2114 drag_handle_text(context, data, time_, state);
2115
2116}
2117#endif /* FEAT_DND */
2118
2119
2120#if defined(FEAT_GUI_GNOME) && defined(FEAT_SESSION)
2121/*
2122 * GnomeClient interact callback. Check for unsaved buffers that cannot
2123 * be abandoned and pop up a dialog asking the user for confirmation if
2124 * necessary.
2125 */
2126/*ARGSUSED0*/
2127 static void
2128sm_client_check_changed_any(GnomeClient *client,
2129 gint key,
2130 GnomeDialogType type,
2131 gpointer data)
2132{
2133 cmdmod_T save_cmdmod;
2134 gboolean shutdown_cancelled;
2135
2136 save_cmdmod = cmdmod;
2137
2138# ifdef FEAT_BROWSE
2139 cmdmod.browse = TRUE;
2140# endif
2141# if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2142 cmdmod.confirm = TRUE;
2143# endif
2144 /*
2145 * If there are changed buffers, present the user with
2146 * a dialog if possible, otherwise give an error message.
2147 */
2148 shutdown_cancelled = check_changed_any(FALSE);
2149
2150 exiting = FALSE;
2151 cmdmod = save_cmdmod;
2152 setcursor(); /* position the cursor */
2153 out_flush();
2154 /*
2155 * If the user hit the [Cancel] button the whole shutdown
2156 * will be cancelled. Wow, quite powerful feature (:
2157 */
2158 gnome_interaction_key_return(key, shutdown_cancelled);
2159}
2160
2161/*
2162 * Generate a script that can be used to restore the current editing session.
2163 * Save the value of v:this_session before running :mksession in order to make
2164 * automagic session save fully transparent. Return TRUE on success.
2165 */
2166 static int
2167write_session_file(char_u *filename)
2168{
2169 char_u *escaped_filename;
2170 char *mksession_cmdline;
2171 unsigned int save_ssop_flags;
2172 int failed;
2173
2174 /*
2175 * Build an ex command line to create a script that restores the current
2176 * session if executed. Escape the filename to avoid nasty surprises.
2177 */
2178 escaped_filename = vim_strsave_escaped(filename, escape_chars);
2179 if (escaped_filename == NULL)
2180 return FALSE;
2181 mksession_cmdline = g_strconcat("mksession ", (char *)escaped_filename, NULL);
2182 vim_free(escaped_filename);
2183 /*
2184 * Use a reasonable hardcoded set of 'sessionoptions' flags to avoid
2185 * unpredictable effects when the session is saved automatically. Also,
2186 * we definitely need SSOP_GLOBALS to be able to restore v:this_session.
2187 * Don't use SSOP_BUFFERS to prevent the buffer list from becoming
2188 * enormously large if the GNOME session feature is used regularly.
2189 */
2190 save_ssop_flags = ssop_flags;
2191 ssop_flags = (SSOP_BLANK|SSOP_CURDIR|SSOP_FOLDS|SSOP_GLOBALS
2192 |SSOP_HELP|SSOP_OPTIONS|SSOP_WINSIZE);
2193
2194 do_cmdline_cmd((char_u *)"let Save_VV_this_session = v:this_session");
2195 failed = (do_cmdline_cmd((char_u *)mksession_cmdline) == FAIL);
2196 do_cmdline_cmd((char_u *)"let v:this_session = Save_VV_this_session");
2197 do_unlet((char_u *)"Save_VV_this_session");
2198
2199 ssop_flags = save_ssop_flags;
2200 g_free(mksession_cmdline);
2201 /*
2202 * Reopen the file and append a command to restore v:this_session,
2203 * as if this save never happened. This is to avoid conflicts with
2204 * the user's own sessions. FIXME: It's probably less hackish to add
2205 * a "stealth" flag to 'sessionoptions' -- gotta ask Bram.
2206 */
2207 if (!failed)
2208 {
2209 FILE *fd;
2210
2211 fd = open_exfile(filename, TRUE, APPENDBIN);
2212
2213 failed = (fd == NULL
2214 || put_line(fd, "let v:this_session = Save_VV_this_session") == FAIL
2215 || put_line(fd, "unlet Save_VV_this_session") == FAIL);
2216
2217 if (fd != NULL && fclose(fd) != 0)
2218 failed = TRUE;
2219
2220 if (failed)
2221 mch_remove(filename);
2222 }
2223
2224 return !failed;
2225}
2226
2227/*
2228 * "save_yourself" signal handler. Initiate an interaction to ask the user
2229 * for confirmation if necessary. Save the current editing session and tell
2230 * the session manager how to restart Vim.
2231 */
2232/*ARGSUSED1*/
2233 static gboolean
2234sm_client_save_yourself(GnomeClient *client,
2235 gint phase,
2236 GnomeSaveStyle save_style,
2237 gboolean shutdown,
2238 GnomeInteractStyle interact_style,
2239 gboolean fast,
2240 gpointer data)
2241{
2242 static const char suffix[] = "-session.vim";
2243 char *session_file;
2244 unsigned int len;
2245 gboolean success;
2246
2247 /* Always request an interaction if possible. check_changed_any()
2248 * won't actually show a dialog unless any buffers have been modified.
2249 * There doesn't seem to be an obvious way to check that without
2250 * automatically firing the dialog. Anyway, it works just fine. */
2251 if (interact_style == GNOME_INTERACT_ANY)
2252 gnome_client_request_interaction(client, GNOME_DIALOG_NORMAL,
2253 &sm_client_check_changed_any,
2254 NULL);
2255 out_flush();
2256 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
2257
2258 /* The path is unique for each session save. We do neither know nor care
2259 * which session script will actually be used later. This decision is in
2260 * the domain of the session manager. */
2261 session_file = gnome_config_get_real_path(
2262 gnome_client_get_config_prefix(client));
2263 len = strlen(session_file);
2264
2265 if (len > 0 && session_file[len-1] == G_DIR_SEPARATOR)
2266 --len; /* get rid of the superfluous trailing '/' */
2267
2268 session_file = g_renew(char, session_file, len + sizeof(suffix));
2269 memcpy(session_file + len, suffix, sizeof(suffix));
2270
2271 success = write_session_file((char_u *)session_file);
2272
2273 if (success)
2274 {
2275 const char *argv[8];
2276 int i;
2277
2278 /* Tell the session manager how to wipe out the stored session data.
2279 * This isn't as dangerous as it looks, don't worry :) session_file
2280 * is a unique absolute filename. Usually it'll be something like
2281 * `/home/user/.gnome2/vim-XXXXXX-session.vim'. */
2282 i = 0;
2283 argv[i++] = "rm";
2284 argv[i++] = session_file;
2285 argv[i] = NULL;
2286
2287 gnome_client_set_discard_command(client, i, (char **)argv);
2288
2289 /* Tell the session manager how to restore the just saved session.
2290 * This is easily done thanks to Vim's -S option. Pass the -f flag
2291 * since there's no need to fork -- it might even cause confusion.
2292 * Also pass the window role to give the WM something to match on.
2293 * The role is set in gui_mch_open(), thus should _never_ be NULL. */
2294 i = 0;
2295 argv[i++] = restart_command;
2296 argv[i++] = "-f";
2297 argv[i++] = "-g";
2298# ifdef HAVE_GTK2
2299 argv[i++] = "--role";
2300 argv[i++] = gtk_window_get_role(GTK_WINDOW(gui.mainwin));
2301# endif
2302 argv[i++] = "-S";
2303 argv[i++] = session_file;
2304 argv[i] = NULL;
2305
2306 gnome_client_set_restart_command(client, i, (char **)argv);
2307 gnome_client_set_clone_command(client, 0, NULL);
2308 }
2309
2310 g_free(session_file);
2311
2312 return success;
2313}
2314
2315/*
2316 * Called when the session manager wants us to die. There isn't much to save
2317 * here since "save_yourself" has been emitted before (unless serious trouble
2318 * is happening).
2319 */
2320/*ARGSUSED0*/
2321 static void
2322sm_client_die(GnomeClient *client, gpointer data)
2323{
2324 /* Don't write messages to the GUI anymore */
2325 full_screen = FALSE;
2326
2327 STRNCPY(IObuff, _("Vim: Received \"die\" request from session manager\n"),
2328 IOSIZE);
2329 IObuff[IOSIZE - 1] = NUL;
2330 preserve_exit();
2331}
2332
2333/*
2334 * Connect our signal handlers to be notified on session save and shutdown.
2335 */
2336 static void
2337setup_save_yourself(void)
2338{
2339 GnomeClient *client;
2340
2341 client = gnome_master_client();
2342
2343 if (client != NULL)
2344 {
2345 /* Must use the deprecated gtk_signal_connect() for compatibility
2346 * with GNOME 1. Arrgh, zombies! */
2347 gtk_signal_connect(GTK_OBJECT(client), "save_yourself",
2348 GTK_SIGNAL_FUNC(&sm_client_save_yourself), NULL);
2349 gtk_signal_connect(GTK_OBJECT(client), "die",
2350 GTK_SIGNAL_FUNC(&sm_client_die), NULL);
2351 }
2352}
2353
2354#else /* !(FEAT_GUI_GNOME && FEAT_SESSION) */
2355
2356# ifdef USE_XSMP
2357/*
2358 * GTK tells us that XSMP needs attention
2359 */
2360/*ARGSUSED*/
2361 static gboolean
2362local_xsmp_handle_requests(source, condition, data)
2363 GIOChannel *source;
2364 GIOCondition condition;
2365 gpointer data;
2366{
2367 if (condition == G_IO_IN)
2368 {
2369 /* Do stuff; maybe close connection */
2370 if (xsmp_handle_requests() == FAIL)
2371 g_io_channel_unref((GIOChannel *)data);
2372 return TRUE;
2373 }
2374 /* Error */
2375 g_io_channel_unref((GIOChannel *)data);
2376 xsmp_close();
2377 return TRUE;
2378}
2379# endif /* USE_XSMP */
2380
2381/*
2382 * Setup the WM_PROTOCOLS to indicate we want the WM_SAVE_YOURSELF event.
2383 * This is an ugly use of X functions. GTK doesn't offer an alternative.
2384 */
2385 static void
2386setup_save_yourself(void)
2387{
2388 Atom *existing_atoms = NULL;
2389 int count = 0;
2390
2391#ifdef USE_XSMP
2392 if (xsmp_icefd != -1)
2393 {
2394 /*
2395 * Use XSMP is preference to legacy WM_SAVE_YOURSELF;
2396 * set up GTK IO monitor
2397 */
2398 GIOChannel *g_io = g_io_channel_unix_new(xsmp_icefd);
2399
2400 g_io_add_watch(g_io, G_IO_IN | G_IO_ERR | G_IO_HUP,
2401 local_xsmp_handle_requests, (gpointer)g_io);
2402 }
2403 else
2404#endif
2405 {
2406 /* Fall back to old method */
2407
2408 /* first get the existing value */
2409 if (XGetWMProtocols(GDK_WINDOW_XDISPLAY(gui.mainwin->window),
2410 GDK_WINDOW_XWINDOW(gui.mainwin->window),
2411 &existing_atoms, &count))
2412 {
2413 Atom *new_atoms;
2414 Atom save_yourself_xatom;
2415 int i;
2416
2417 save_yourself_xatom = GET_X_ATOM(save_yourself_atom);
2418
2419 /* check if WM_SAVE_YOURSELF isn't there yet */
2420 for (i = 0; i < count; ++i)
2421 if (existing_atoms[i] == save_yourself_xatom)
2422 break;
2423
2424 if (i == count)
2425 {
2426 /* allocate an Atoms array which is one item longer */
2427 new_atoms = (Atom *)alloc((unsigned)((count + 1)
2428 * sizeof(Atom)));
2429 if (new_atoms != NULL)
2430 {
2431 memcpy(new_atoms, existing_atoms, count * sizeof(Atom));
2432 new_atoms[count] = save_yourself_xatom;
2433 XSetWMProtocols(GDK_WINDOW_XDISPLAY(gui.mainwin->window),
2434 GDK_WINDOW_XWINDOW(gui.mainwin->window),
2435 new_atoms, count + 1);
2436 vim_free(new_atoms);
2437 }
2438 }
2439 XFree(existing_atoms);
2440 }
2441 }
2442}
2443
2444# ifdef HAVE_GTK2
2445/*
2446 * Installing a global event filter seems to be the only way to catch
2447 * client messages of type WM_PROTOCOLS without overriding GDK's own
2448 * client message event filter. Well, that's still better than trying
2449 * to guess what the GDK filter had done if it had been invoked instead
2450 * (This is what we did for GTK+ 1.2, see below).
2451 *
2452 * GTK2_FIXME: This doesn't seem to work. For some reason we never
2453 * receive WM_SAVE_YOURSELF even though everything is set up correctly.
2454 * I have the nasty feeling modern session managers just don't send this
2455 * deprecated message anymore. Addition: confirmed by several people.
2456 *
2457 * The GNOME session support is much cooler anyway. Unlike this ugly
2458 * WM_SAVE_YOURSELF hack it actually stores the session... And yes,
2459 * it should work with KDE as well.
2460 */
2461/*ARGSUSED1*/
2462 static GdkFilterReturn
2463global_event_filter(GdkXEvent *xev, GdkEvent *event, gpointer data)
2464{
2465 XEvent *xevent = (XEvent *)xev;
2466
2467 if (xevent != NULL
2468 && xevent->type == ClientMessage
2469 && xevent->xclient.message_type == GET_X_ATOM(wm_protocols_atom)
2470 && xevent->xclient.data.l[0] == GET_X_ATOM(save_yourself_atom))
2471 {
2472 out_flush();
2473 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
2474 /*
2475 * Set the window's WM_COMMAND property, to let the window manager
2476 * know we are done saving ourselves. We don't want to be
2477 * restarted, thus set argv to NULL.
2478 */
2479 XSetCommand(GDK_WINDOW_XDISPLAY(gui.mainwin->window),
2480 GDK_WINDOW_XWINDOW(gui.mainwin->window),
2481 NULL, 0);
2482 return GDK_FILTER_REMOVE;
2483 }
2484
2485 return GDK_FILTER_CONTINUE;
2486}
2487
2488# else /* !HAVE_GTK2 */
2489
2490/*
2491 * GDK handler for X ClientMessage events.
2492 */
2493/*ARGSUSED2*/
2494 static GdkFilterReturn
2495gdk_wm_protocols_filter(GdkXEvent *xev, GdkEvent *event, gpointer data)
2496{
2497 /* From example in gdkevents.c/gdk_wm_protocols_filter */
2498 XEvent *xevent = (XEvent *)xev;
2499
2500 if (xevent != NULL)
2501 {
2502 if (xevent->xclient.data.l[0] == GET_X_ATOM(save_yourself_atom))
2503 {
2504 out_flush();
2505 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
2506
2507 /* Set the window's WM_COMMAND property, to let the window manager
2508 * know we are done saving ourselves. We don't want to be
2509 * restarted, thus set argv to NULL. */
2510 XSetCommand(GDK_WINDOW_XDISPLAY(gui.mainwin->window),
2511 GDK_WINDOW_XWINDOW(gui.mainwin->window),
2512 NULL, 0);
2513 }
2514 /*
2515 * Functionality from gdkevents.c/gdk_wm_protocols_filter;
2516 * Registering this filter apparently overrides the default GDK one,
2517 * so we need to perform its functionality. There seems no way to
2518 * register for WM_PROTOCOLS, and only process the WM_SAVE_YOURSELF
2519 * bit; it's all or nothing. Update: No, there is a way -- but it
2520 * only works with GTK+ 2 apparently. See above.
2521 */
2522 else if (xevent->xclient.data.l[0] == GET_X_ATOM(gdk_wm_delete_window))
2523 {
2524 event->any.type = GDK_DELETE;
2525 return GDK_FILTER_TRANSLATE;
2526 }
2527 }
2528
2529 return GDK_FILTER_REMOVE;
2530}
2531# endif /* !HAVE_GTK2 */
2532
2533#endif /* !(FEAT_GUI_GNOME && FEAT_SESSION) */
2534
2535
2536/*
2537 * Setup the window icon & xcmdsrv comm after the main window has been realized.
2538 */
2539/*ARGSUSED*/
2540 static void
2541mainwin_realize(GtkWidget *widget, gpointer data)
2542{
2543/* If you get an error message here, you still need to unpack the runtime
2544 * archive! */
2545#ifdef magick
2546# undef magick
2547#endif
2548#ifdef HAVE_GTK2
2549 /* A bit hackish, but avoids casting later and allows optimization */
2550# define static static const
2551#endif
2552#define magick vim32x32
2553#include "../runtime/vim32x32.xpm"
2554#undef magick
2555#define magick vim16x16
2556#include "../runtime/vim16x16.xpm"
2557#undef magick
2558#define magick vim48x48
2559#include "../runtime/vim48x48.xpm"
2560#undef magick
2561#ifdef HAVE_GTK2
2562# undef static
2563#endif
2564
2565 /* When started with "--echo-wid" argument, write window ID on stdout. */
2566 if (echo_wid_arg)
2567 {
2568 printf("WID: %ld\n", (long)GDK_WINDOW_XWINDOW(gui.mainwin->window));
2569 fflush(stdout);
2570 }
2571
2572 if (vim_strchr(p_go, GO_ICON) != NULL)
2573 {
2574 /*
2575 * Add an icon to the main window. For fun and convenience of the user.
2576 */
2577#ifdef HAVE_GTK2
2578 GList *icons = NULL;
2579
2580 icons = g_list_prepend(icons, gdk_pixbuf_new_from_xpm_data(vim16x16));
2581 icons = g_list_prepend(icons, gdk_pixbuf_new_from_xpm_data(vim32x32));
2582 icons = g_list_prepend(icons, gdk_pixbuf_new_from_xpm_data(vim48x48));
2583
2584 gtk_window_set_icon_list(GTK_WINDOW(gui.mainwin), icons);
2585
2586 g_list_foreach(icons, (GFunc)&g_object_unref, NULL);
2587 g_list_free(icons);
2588
2589#else /* !HAVE_GTK2 */
2590
2591 GdkPixmap *icon;
2592 GdkBitmap *icon_mask = NULL;
2593 char **magick = vim32x32;
2594 Display *xdisplay;
2595 Window root_window;
2596 XIconSize *size;
2597 int number_sizes;
2598 /*
2599 * Adjust the icon to the preferences of the actual window manager.
2600 * This is once again a workaround for a defficiency in GTK+ 1.2.
2601 */
2602 xdisplay = GDK_WINDOW_XDISPLAY(gui.mainwin->window);
2603 root_window = XRootWindow(xdisplay, DefaultScreen(xdisplay));
2604 if (XGetIconSizes(xdisplay, root_window, &size, &number_sizes))
2605 {
2606 if (number_sizes > 0)
2607 {
2608 if (size->max_height >= 48 && size->max_height >= 48)
2609 magick = vim48x48;
2610 else if (size->max_height >= 32 && size->max_height >= 32)
2611 magick = vim32x32;
2612 else if (size->max_height >= 16 && size->max_height >= 16)
2613 magick = vim16x16;
2614 }
2615 XFree(size);
2616 }
2617 icon = gdk_pixmap_create_from_xpm_d(gui.mainwin->window,
2618 &icon_mask, NULL, magick);
2619 if (icon != NULL)
2620 /* Note: for some reason gdk_window_set_icon() doesn't acquire
2621 * a reference on the pixmap, thus we _have_ to leak it. */
2622 gdk_window_set_icon(gui.mainwin->window, NULL, icon, icon_mask);
2623
2624#endif /* !HAVE_GTK2 */
2625 }
2626
2627#if !(defined(FEAT_GUI_GNOME) && defined(FEAT_SESSION))
2628 /* Register a handler for WM_SAVE_YOURSELF with GDK's low-level X I/F */
2629# ifdef HAVE_GTK2
2630 gdk_window_add_filter(NULL, &global_event_filter, NULL);
2631# else
2632 gdk_add_client_message_filter(wm_protocols_atom,
2633 &gdk_wm_protocols_filter, NULL);
2634# endif
2635#endif
2636 /* Setup to indicate to the window manager that we want to catch the
2637 * WM_SAVE_YOURSELF event. For GNOME, this connects to the session
2638 * manager instead. */
2639#if defined(FEAT_GUI_GNOME) && defined(FEAT_SESSION)
2640 if (using_gnome)
2641#endif
2642 setup_save_yourself();
2643
2644#ifdef FEAT_CLIENTSERVER
2645 if (serverName == NULL && serverDelayedStartName != NULL)
2646 {
2647 /* This is a :gui command in a plain vim with no previous server */
2648 commWindow = GDK_WINDOW_XWINDOW(gui.mainwin->window);
2649
2650 (void)serverRegisterName(GDK_WINDOW_XDISPLAY(gui.mainwin->window),
2651 serverDelayedStartName);
2652 }
2653 else
2654 {
2655 /*
2656 * Cannot handle "XLib-only" windows with gtk event routines, we'll
2657 * have to change the "server" registration to that of the main window
2658 * If we have not registered a name yet, remember the window
2659 */
2660 serverChangeRegisteredWindow(GDK_WINDOW_XDISPLAY(gui.mainwin->window),
2661 GDK_WINDOW_XWINDOW(gui.mainwin->window));
2662 }
2663 gtk_widget_add_events(gui.mainwin, GDK_PROPERTY_CHANGE_MASK);
2664 gtk_signal_connect(GTK_OBJECT(gui.mainwin), "property_notify_event",
2665 GTK_SIGNAL_FUNC(property_event), NULL);
2666#endif
2667}
2668
2669 static GdkCursor *
2670create_blank_pointer(void)
2671{
2672 GdkWindow *root_window = NULL;
2673 GdkPixmap *blank_mask;
2674 GdkCursor *cursor;
2675 GdkColor color = { 0, 0, 0, 0 };
2676 char blank_data[] = { 0x0 };
2677
2678#ifdef HAVE_GTK_MULTIHEAD
2679 root_window = gtk_widget_get_root_window(gui.mainwin);
2680#endif
2681
2682 /* Create a pseudo blank pointer, which is in fact one pixel by one pixel
2683 * in size. */
2684 blank_mask = gdk_bitmap_create_from_data(root_window, blank_data, 1, 1);
2685 cursor = gdk_cursor_new_from_pixmap(blank_mask, blank_mask,
2686 &color, &color, 0, 0);
2687 gdk_bitmap_unref(blank_mask);
2688
2689 return cursor;
2690}
2691
2692#ifdef HAVE_GTK_MULTIHEAD
2693/*ARGSUSED1*/
2694 static void
2695mainwin_screen_changed_cb(GtkWidget *widget,
2696 GdkScreen *previous_screen,
2697 gpointer data)
2698{
2699 if (!gtk_widget_has_screen(widget))
2700 return;
2701
2702 /*
2703 * Recreate the invisble mouse cursor.
2704 */
2705 if (gui.blank_pointer != NULL)
2706 gdk_cursor_unref(gui.blank_pointer);
2707
2708 gui.blank_pointer = create_blank_pointer();
2709
2710 if (gui.pointer_hidden && gui.drawarea->window != NULL)
2711 gdk_window_set_cursor(gui.drawarea->window, gui.blank_pointer);
2712
2713 /*
2714 * Create a new PangoContext for this screen, and initialize it
2715 * with the current font if necessary.
2716 */
2717 if (gui.text_context != NULL)
2718 g_object_unref(gui.text_context);
2719
2720 gui.text_context = gtk_widget_create_pango_context(widget);
2721 pango_context_set_base_dir(gui.text_context, PANGO_DIRECTION_LTR);
2722
2723 if (gui.norm_font != NULL)
2724 {
2725 gui_mch_init_font(p_guifont, 0);
2726 gui_set_shellsize(FALSE, FALSE);
2727 }
2728}
2729#endif /* HAVE_GTK_MULTIHEAD */
2730
2731/*
2732 * After the drawing area comes up, we calculate all colors and create the
2733 * dummy blank cursor.
2734 *
2735 * Don't try to set any VIM scrollbar sizes anywhere here. I'm relying on the
2736 * fact that the main VIM engine doesn't take them into account anywhere.
2737 */
2738/*ARGSUSED1*/
2739 static void
2740drawarea_realize_cb(GtkWidget *widget, gpointer data)
2741{
2742 GtkWidget *sbar;
2743
2744#ifdef FEAT_XIM
2745 xim_init();
2746#endif
2747 gui_mch_new_colors();
2748 gui.text_gc = gdk_gc_new(gui.drawarea->window);
2749
2750 gui.blank_pointer = create_blank_pointer();
2751 if (gui.pointer_hidden)
2752 gdk_window_set_cursor(widget->window, gui.blank_pointer);
2753
2754 /* get the actual size of the scrollbars, if they are realized */
2755 sbar = firstwin->w_scrollbars[SBAR_LEFT].id;
2756 if (!sbar || (!gui.which_scrollbars[SBAR_LEFT]
2757 && firstwin->w_scrollbars[SBAR_RIGHT].id))
2758 sbar = firstwin->w_scrollbars[SBAR_RIGHT].id;
2759 if (sbar && GTK_WIDGET_REALIZED(sbar) && sbar->allocation.width)
2760 gui.scrollbar_width = sbar->allocation.width;
2761
2762 sbar = gui.bottom_sbar.id;
2763 if (sbar && GTK_WIDGET_REALIZED(sbar) && sbar->allocation.height)
2764 gui.scrollbar_height = sbar->allocation.height;
2765}
2766
2767/*
2768 * Properly clean up on shutdown.
2769 */
2770/*ARGSUSED0*/
2771 static void
2772drawarea_unrealize_cb(GtkWidget *widget, gpointer data)
2773{
2774 /* Don't write messages to the GUI anymore */
2775 full_screen = FALSE;
2776
2777#ifdef FEAT_XIM
2778 im_shutdown();
2779#endif
2780#ifdef HAVE_GTK2
2781 if (gui.ascii_glyphs != NULL)
2782 {
2783 pango_glyph_string_free(gui.ascii_glyphs);
2784 gui.ascii_glyphs = NULL;
2785 }
2786 if (gui.ascii_font != NULL)
2787 {
2788 g_object_unref(gui.ascii_font);
2789 gui.ascii_font = NULL;
2790 }
2791 g_object_unref(gui.text_context);
2792 gui.text_context = NULL;
2793
2794 g_object_unref(gui.text_gc);
2795 gui.text_gc = NULL;
2796
2797 gdk_cursor_unref(gui.blank_pointer);
2798 gui.blank_pointer = NULL;
2799#else
2800 gdk_gc_unref(gui.text_gc);
2801 gui.text_gc = NULL;
2802
2803 gdk_cursor_destroy(gui.blank_pointer);
2804 gui.blank_pointer = NULL;
2805#endif
2806}
2807
2808/*ARGSUSED0*/
2809 static void
2810drawarea_style_set_cb(GtkWidget *widget,
2811 GtkStyle *previous_style,
2812 gpointer data)
2813{
2814 gui_mch_new_colors();
2815}
2816
2817/*
2818 * Callback routine for the "delete_event" signal on the toplevel window.
2819 * Tries to vim gracefully, or refuses to exit with changed buffers.
2820 */
2821/*ARGSUSED*/
2822 static gint
2823delete_event_cb(GtkWidget *widget, GdkEventAny *event, gpointer data)
2824{
2825 gui_shell_closed();
2826 return TRUE;
2827}
2828
2829#ifdef FEAT_TOOLBAR
2830
2831# ifdef HAVE_GTK2
2832/*
2833 * This extra effort wouldn't be necessary if we only used stock icons in the
2834 * toolbar, as we do for all builtin icons. But user-defined toolbar icons
2835 * shouldn't be treated differently, thus we do need this.
2836 */
2837 static void
2838icon_size_changed_foreach(GtkWidget *widget, gpointer user_data)
2839{
2840 if (GTK_IS_IMAGE(widget))
2841 {
2842 GtkImage *image = (GtkImage *)widget;
2843
2844 /* User-defined icons are stored in a GtkIconSet */
2845 if (gtk_image_get_storage_type(image) == GTK_IMAGE_ICON_SET)
2846 {
2847 GtkIconSet *icon_set;
2848 GtkIconSize icon_size;
2849
2850 gtk_image_get_icon_set(image, &icon_set, &icon_size);
2851 icon_size = (GtkIconSize)(long)user_data;
2852
2853 gtk_icon_set_ref(icon_set);
2854 gtk_image_set_from_icon_set(image, icon_set, icon_size);
2855 gtk_icon_set_unref(icon_set);
2856 }
2857 }
2858 else if (GTK_IS_CONTAINER(widget))
2859 {
2860 gtk_container_foreach((GtkContainer *)widget,
2861 &icon_size_changed_foreach,
2862 user_data);
2863 }
2864}
2865# endif /* HAVE_GTK2 */
2866
2867 static void
2868set_toolbar_style(GtkToolbar *toolbar)
2869{
2870 GtkToolbarStyle style;
2871# ifdef HAVE_GTK2
2872 GtkIconSize size;
2873 GtkIconSize oldsize;
2874# endif
2875
2876# ifdef HAVE_GTK2
2877 if ((toolbar_flags & (TOOLBAR_TEXT | TOOLBAR_ICONS | TOOLBAR_HORIZ))
2878 == (TOOLBAR_TEXT | TOOLBAR_ICONS | TOOLBAR_HORIZ))
2879 style = GTK_TOOLBAR_BOTH_HORIZ;
2880 else
2881# endif
2882 if ((toolbar_flags & (TOOLBAR_TEXT | TOOLBAR_ICONS))
2883 == (TOOLBAR_TEXT | TOOLBAR_ICONS))
2884 style = GTK_TOOLBAR_BOTH;
2885 else if (toolbar_flags & TOOLBAR_TEXT)
2886 style = GTK_TOOLBAR_TEXT;
2887 else
2888 style = GTK_TOOLBAR_ICONS;
2889
2890 gtk_toolbar_set_style(toolbar, style);
2891 gtk_toolbar_set_tooltips(toolbar, (toolbar_flags & TOOLBAR_TOOLTIPS) != 0);
2892
2893# ifdef HAVE_GTK2
2894 switch (tbis_flags)
2895 {
2896 case TBIS_TINY: size = GTK_ICON_SIZE_MENU; break;
2897 case TBIS_SMALL: size = GTK_ICON_SIZE_SMALL_TOOLBAR; break;
2898 case TBIS_MEDIUM: size = GTK_ICON_SIZE_BUTTON; break;
2899 case TBIS_LARGE: size = GTK_ICON_SIZE_LARGE_TOOLBAR; break;
2900 default: size = GTK_ICON_SIZE_INVALID; break;
2901 }
2902 oldsize = gtk_toolbar_get_icon_size(toolbar);
2903
2904 if (size == GTK_ICON_SIZE_INVALID)
2905 {
2906 /* Let global user preferences decide the icon size. */
2907 gtk_toolbar_unset_icon_size(toolbar);
2908 size = gtk_toolbar_get_icon_size(toolbar);
2909 }
2910 if (size != oldsize)
2911 {
2912 gtk_container_foreach(GTK_CONTAINER(toolbar),
2913 &icon_size_changed_foreach,
2914 GINT_TO_POINTER((int)size));
2915 }
2916 gtk_toolbar_set_icon_size(toolbar, size);
2917# endif
2918}
2919
2920#endif /* FEAT_TOOLBAR */
2921
2922/*
2923 * Initialize the GUI. Create all the windows, set up all the callbacks etc.
2924 * Returns OK for success, FAIL when the GUI can't be started.
2925 */
2926 int
2927gui_mch_init(void)
2928{
2929 GtkWidget *vbox;
2930
2931#ifdef FEAT_GUI_GNOME
2932 /* Initialize the GNOME libraries. gnome_program_init()/gnome_init()
2933 * exits on failure, but that's a non-issue because we already called
2934 * gtk_init_check() in gui_mch_init_check(). */
2935 if (using_gnome)
2936# ifdef HAVE_GTK2
2937 gnome_program_init(VIMPACKAGE, VIM_VERSION_SHORT,
2938 LIBGNOMEUI_MODULE, gui_argc, gui_argv, NULL);
2939# else
2940 gnome_init(VIMPACKAGE, VIM_VERSION_SHORT, gui_argc, gui_argv);
2941# endif
2942#endif
2943 vim_free(gui_argv);
2944 gui_argv = NULL;
2945
2946#ifdef HAVE_GTK2
2947# if GLIB_CHECK_VERSION(2,1,3)
2948 /* Set the human-readable application name */
2949 g_set_application_name("Vim");
2950# endif
2951 /*
2952 * Force UTF-8 output no matter what the value of 'encoding' is.
2953 * did_set_string_option() in option.c prohibits changing 'termencoding'
2954 * to something else than UTF-8 if the GUI is in use.
2955 */
2956 set_option_value((char_u *)"termencoding", 0L, (char_u *)"utf-8", 0);
2957
2958# ifdef FEAT_TOOLBAR
2959 gui_gtk_register_stock_icons();
2960# endif
2961 /* FIXME: Need to install the classic icons and a gtkrc.classic file.
2962 * The hard part is deciding install locations and the Makefile magic. */
2963# if 0
2964 gtk_rc_parse("gtkrc");
2965# endif
2966#endif
2967
2968 /* Initialize values */
2969 gui.border_width = 2;
2970 gui.scrollbar_width = SB_DEFAULT_WIDTH;
2971 gui.scrollbar_height = SB_DEFAULT_WIDTH;
2972 gui.fgcolor = g_new0(GdkColor, 1);
2973 gui.bgcolor = g_new0(GdkColor, 1);
2974
2975 /* Initialise atoms */
2976#ifdef FEAT_MBYTE
2977 utf8_string_atom = gdk_atom_intern("UTF8_STRING", FALSE);
2978#endif
2979#ifndef HAVE_GTK2
2980 compound_text_atom = gdk_atom_intern("COMPOUND_TEXT", FALSE);
2981 text_atom = gdk_atom_intern("TEXT", FALSE);
2982#endif
2983
2984 /* Set default foreground and background colors. */
2985 gui.norm_pixel = gui.def_norm_pixel;
2986 gui.back_pixel = gui.def_back_pixel;
2987
2988 if (gtk_socket_id != 0)
2989 {
2990 GtkWidget *plug;
2991
2992 /* Use GtkSocket from another app. */
2993#ifdef HAVE_GTK_MULTIHEAD
2994 plug = gtk_plug_new_for_display(gdk_display_get_default(),
2995 gtk_socket_id);
2996#else
2997 plug = gtk_plug_new(gtk_socket_id);
2998#endif
2999 if (plug != NULL && GTK_PLUG(plug)->socket_window != NULL)
3000 {
3001 gui.mainwin = plug;
3002 }
3003 else
3004 {
3005 g_warning("Connection to GTK+ socket (ID %u) failed",
3006 (unsigned int)gtk_socket_id);
3007 /* Pretend we never wanted it if it failed (get own window) */
3008 gtk_socket_id = 0;
3009 }
3010 }
3011
3012 if (gtk_socket_id == 0)
3013 {
3014#ifdef FEAT_GUI_GNOME
3015 if (using_gnome)
3016 {
3017 gui.mainwin = gnome_app_new("Vim", NULL);
3018# ifdef USE_XSMP
3019 /* Use the GNOME save-yourself functionality now. */
3020 xsmp_close();
3021# endif
3022 }
3023 else
3024#endif
3025 gui.mainwin = gtk_window_new(GTK_WINDOW_TOPLEVEL);
3026 }
3027
3028 gtk_widget_set_name(gui.mainwin, "vim-main-window");
3029
3030#ifdef HAVE_GTK2
3031 /* Create the PangoContext used for drawing all text. */
3032 gui.text_context = gtk_widget_create_pango_context(gui.mainwin);
3033 pango_context_set_base_dir(gui.text_context, PANGO_DIRECTION_LTR);
3034#endif
3035
3036#ifndef HAVE_GTK2
3037 gtk_window_set_policy(GTK_WINDOW(gui.mainwin), TRUE, TRUE, TRUE);
3038#endif
3039 gtk_container_border_width(GTK_CONTAINER(gui.mainwin), 0);
3040 gtk_widget_add_events(gui.mainwin, GDK_VISIBILITY_NOTIFY_MASK);
3041
3042 gtk_signal_connect(GTK_OBJECT(gui.mainwin), "delete_event",
3043 GTK_SIGNAL_FUNC(&delete_event_cb), NULL);
3044
3045 gtk_signal_connect(GTK_OBJECT(gui.mainwin), "realize",
3046 GTK_SIGNAL_FUNC(&mainwin_realize), NULL);
3047#ifdef HAVE_GTK_MULTIHEAD
3048 g_signal_connect(G_OBJECT(gui.mainwin), "screen_changed",
3049 G_CALLBACK(&mainwin_screen_changed_cb), NULL);
3050#endif
3051#ifdef HAVE_GTK2
3052 gui.accel_group = gtk_accel_group_new();
3053 gtk_window_add_accel_group(GTK_WINDOW(gui.mainwin), gui.accel_group);
3054#else
3055 gui.accel_group = gtk_accel_group_get_default();
3056#endif
3057
3058 vbox = gtk_vbox_new(FALSE, 0);
3059
3060#ifdef FEAT_GUI_GNOME
3061 if (using_gnome)
3062 {
3063# if defined(HAVE_GTK2) && defined(FEAT_MENU)
3064 /* automagically restore menubar/toolbar placement */
3065 gnome_app_enable_layout_config(GNOME_APP(gui.mainwin), TRUE);
3066# endif
3067 gnome_app_set_contents(GNOME_APP(gui.mainwin), vbox);
3068 }
3069 else
3070#endif
3071 {
3072 gtk_container_add(GTK_CONTAINER(gui.mainwin), vbox);
3073 gtk_widget_show(vbox);
3074 }
3075
3076#ifdef FEAT_MENU
3077 /*
3078 * Create the menubar and handle
3079 */
3080 gui.menubar = gtk_menu_bar_new();
3081 gtk_widget_set_name(gui.menubar, "vim-menubar");
3082
3083# ifdef FEAT_GUI_GNOME
3084 if (using_gnome)
3085 {
3086# ifdef HAVE_GTK2
3087 BonoboDockItem *dockitem;
3088
3089 gnome_app_set_menus(GNOME_APP(gui.mainwin), GTK_MENU_BAR(gui.menubar));
3090 dockitem = gnome_app_get_dock_item_by_name(GNOME_APP(gui.mainwin),
3091 GNOME_APP_MENUBAR_NAME);
3092 gui.menubar_h = GTK_WIDGET(dockitem);
3093# else
3094 gui.menubar_h = gnome_dock_item_new("VimMainMenu",
3095 GNOME_DOCK_ITEM_BEH_EXCLUSIVE |
3096 GNOME_DOCK_ITEM_BEH_NEVER_VERTICAL);
3097 gtk_container_add(GTK_CONTAINER(gui.menubar_h), gui.menubar);
3098
3099 gnome_dock_add_item(GNOME_DOCK(GNOME_APP(gui.mainwin)->dock),
3100 GNOME_DOCK_ITEM(gui.menubar_h),
3101 GNOME_DOCK_TOP, /* placement */
3102 1, /* band_num */
3103 0, /* band_position */
3104 0, /* offset */
3105 TRUE);
3106 gtk_widget_show(gui.menubar);
3107# endif
3108 }
3109 else
3110# endif /* FEAT_GUI_GNOME */
3111 {
3112 if (vim_strchr(p_go, GO_MENUS) != NULL)
3113 gtk_widget_show(gui.menubar);
3114 gtk_box_pack_start(GTK_BOX(vbox), gui.menubar, FALSE, FALSE, 0);
3115 }
3116#endif /* FEAT_MENU */
3117
3118#ifdef FEAT_TOOLBAR
3119 /*
3120 * Create the toolbar and handle
3121 */
3122# ifdef HAVE_GTK2
3123 /* some aesthetics on the toolbar */
3124 gtk_rc_parse_string(
3125 "style \"vim-toolbar-style\" {\n"
3126 " GtkToolbar::button_relief = GTK_RELIEF_NONE\n"
3127 "}\n"
3128 "widget \"*.vim-toolbar\" style \"vim-toolbar-style\"\n");
3129 gui.toolbar = gtk_toolbar_new();
3130 gtk_widget_set_name(gui.toolbar, "vim-toolbar");
3131# else
3132 gui.toolbar = gtk_toolbar_new(GTK_ORIENTATION_HORIZONTAL,
3133 GTK_TOOLBAR_ICONS);
3134 gtk_toolbar_set_button_relief(GTK_TOOLBAR(gui.toolbar), GTK_RELIEF_NONE);
3135# endif
3136 set_toolbar_style(GTK_TOOLBAR(gui.toolbar));
3137
3138# ifdef FEAT_GUI_GNOME
3139 if (using_gnome)
3140 {
3141# ifdef HAVE_GTK2
3142 BonoboDockItem *dockitem;
3143
3144 gnome_app_set_toolbar(GNOME_APP(gui.mainwin), GTK_TOOLBAR(gui.toolbar));
3145 dockitem = gnome_app_get_dock_item_by_name(GNOME_APP(gui.mainwin),
3146 GNOME_APP_TOOLBAR_NAME);
3147 gui.toolbar_h = GTK_WIDGET(dockitem);
3148 gtk_container_set_border_width(GTK_CONTAINER(gui.toolbar), 0);
3149# else
3150 GtkWidget *dockitem;
3151
3152 dockitem = gnome_dock_item_new("VimToolBar",
3153 GNOME_DOCK_ITEM_BEH_EXCLUSIVE);
3154 gtk_container_add(GTK_CONTAINER(dockitem), GTK_WIDGET(gui.toolbar));
3155 gui.toolbar_h = dockitem;
3156
3157 gnome_dock_add_item(GNOME_DOCK(GNOME_APP(gui.mainwin)->dock),
3158 GNOME_DOCK_ITEM(dockitem),
3159 GNOME_DOCK_TOP, /* placement */
3160 1, /* band_num */
3161 1, /* band_position */
3162 0, /* offset */
3163 TRUE);
3164 gtk_container_border_width(GTK_CONTAINER(gui.toolbar), 2);
3165 gtk_widget_show(gui.toolbar);
3166# endif
3167 }
3168 else
3169# endif /* FEAT_GUI_GNOME */
3170 {
3171# ifndef HAVE_GTK2
3172 gtk_container_border_width(GTK_CONTAINER(gui.toolbar), 1);
3173# endif
3174 if (vim_strchr(p_go, GO_TOOLBAR) != NULL
3175 && (toolbar_flags & (TOOLBAR_TEXT | TOOLBAR_ICONS)))
3176 gtk_widget_show(gui.toolbar);
3177 gtk_box_pack_start(GTK_BOX(vbox), gui.toolbar, FALSE, FALSE, 0);
3178 }
3179#endif /* FEAT_TOOLBAR */
3180
3181 gui.formwin = gtk_form_new();
3182 gtk_container_border_width(GTK_CONTAINER(gui.formwin), 0);
3183 gtk_widget_set_events(gui.formwin, GDK_EXPOSURE_MASK);
3184
3185 gui.drawarea = gtk_drawing_area_new();
3186
3187 /* Determine which events we will filter. */
3188 gtk_widget_set_events(gui.drawarea,
3189 GDK_EXPOSURE_MASK |
3190 GDK_ENTER_NOTIFY_MASK |
3191 GDK_LEAVE_NOTIFY_MASK |
3192 GDK_BUTTON_PRESS_MASK |
3193 GDK_BUTTON_RELEASE_MASK |
3194#ifdef HAVE_GTK2
3195 GDK_SCROLL_MASK |
3196#endif
3197 GDK_KEY_PRESS_MASK |
3198 GDK_KEY_RELEASE_MASK |
3199 GDK_POINTER_MOTION_MASK |
3200 GDK_POINTER_MOTION_HINT_MASK);
3201
3202 gtk_widget_show(gui.drawarea);
3203 gtk_form_put(GTK_FORM(gui.formwin), gui.drawarea, 0, 0);
3204 gtk_widget_show(gui.formwin);
3205 gtk_box_pack_start(GTK_BOX(vbox), gui.formwin, TRUE, TRUE, 0);
3206
3207 /* For GtkSockets, key-presses must go to the focus widget (drawarea)
3208 * and not the window. */
3209 gtk_signal_connect((gtk_socket_id == 0) ? GTK_OBJECT(gui.mainwin)
3210 : GTK_OBJECT(gui.drawarea),
3211 "key_press_event",
3212 GTK_SIGNAL_FUNC(key_press_event), NULL);
3213#if defined(FEAT_XIM) && defined(HAVE_GTK2)
3214 /* Also forward key release events for the benefit of GTK+ 2 input
3215 * modules. Try CTRL-SHIFT-xdigits to enter a Unicode code point. */
3216 g_signal_connect((gtk_socket_id == 0) ? G_OBJECT(gui.mainwin)
3217 : G_OBJECT(gui.drawarea),
3218 "key_release_event",
3219 G_CALLBACK(&key_release_event), NULL);
3220#endif
3221 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "realize",
3222 GTK_SIGNAL_FUNC(drawarea_realize_cb), NULL);
3223 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "unrealize",
3224 GTK_SIGNAL_FUNC(drawarea_unrealize_cb), NULL);
3225
3226 gtk_signal_connect_after(GTK_OBJECT(gui.drawarea), "style_set",
3227 GTK_SIGNAL_FUNC(&drawarea_style_set_cb), NULL);
3228
3229 gui.visibility = GDK_VISIBILITY_UNOBSCURED;
3230
3231#if !(defined(FEAT_GUI_GNOME) && defined(FEAT_SESSION))
3232 wm_protocols_atom = gdk_atom_intern("WM_PROTOCOLS", FALSE);
3233 save_yourself_atom = gdk_atom_intern("WM_SAVE_YOURSELF", FALSE);
3234#endif
3235
3236 if (gtk_socket_id != 0)
3237 /* make sure keybord input can go to the drawarea */
3238 GTK_WIDGET_SET_FLAGS(gui.drawarea, GTK_CAN_FOCUS);
3239
3240 /*
3241 * Set clipboard specific atoms
3242 */
3243 vim_atom = gdk_atom_intern(VIM_ATOM_NAME, FALSE);
3244#ifdef FEAT_MBYTE
3245 vimenc_atom = gdk_atom_intern(VIMENC_ATOM_NAME, FALSE);
3246#endif
3247 clip_star.gtk_sel_atom = GDK_SELECTION_PRIMARY;
3248 clip_plus.gtk_sel_atom = gdk_atom_intern("CLIPBOARD", FALSE);
3249
3250 /*
3251 * Start out by adding the configured border width into the border offset.
3252 */
3253 gui.border_offset = gui.border_width;
3254
3255 gtk_signal_connect(GTK_OBJECT(gui.mainwin), "visibility_notify_event",
3256 GTK_SIGNAL_FUNC(visibility_event), NULL);
3257 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "expose_event",
3258 GTK_SIGNAL_FUNC(expose_event), NULL);
3259
3260 /*
3261 * Only install these enter/leave callbacks when 'p' in 'guioptions'.
3262 * Only needed for some window managers.
3263 */
3264 if (vim_strchr(p_go, GO_POINTER) != NULL)
3265 {
3266 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "leave_notify_event",
3267 GTK_SIGNAL_FUNC(leave_notify_event), NULL);
3268 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "enter_notify_event",
3269 GTK_SIGNAL_FUNC(enter_notify_event), NULL);
3270 }
3271
3272 gtk_signal_connect(GTK_OBJECT(gui.mainwin), "focus_out_event",
3273 GTK_SIGNAL_FUNC(focus_out_event), NULL);
3274 gtk_signal_connect(GTK_OBJECT(gui.mainwin), "focus_in_event",
3275 GTK_SIGNAL_FUNC(focus_in_event), NULL);
3276
3277 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "motion_notify_event",
3278 GTK_SIGNAL_FUNC(motion_notify_event), NULL);
3279 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "button_press_event",
3280 GTK_SIGNAL_FUNC(button_press_event), NULL);
3281 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "button_release_event",
3282 GTK_SIGNAL_FUNC(button_release_event), NULL);
3283#ifdef HAVE_GTK2
3284 g_signal_connect(G_OBJECT(gui.drawarea), "scroll_event",
3285 G_CALLBACK(&scroll_event), NULL);
3286#endif
3287
3288 /*
3289 * Add selection handler functions.
3290 */
3291 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "selection_clear_event",
3292 GTK_SIGNAL_FUNC(selection_clear_event), NULL);
3293 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "selection_received",
3294 GTK_SIGNAL_FUNC(selection_received_cb), NULL);
3295
3296 /*
3297 * Add selection targets for PRIMARY and CLIPBOARD selections.
3298 */
3299 gtk_selection_add_targets(gui.drawarea,
3300 (GdkAtom)GDK_SELECTION_PRIMARY,
3301 selection_targets, N_SELECTION_TARGETS);
3302 gtk_selection_add_targets(gui.drawarea,
3303 (GdkAtom)clip_plus.gtk_sel_atom,
3304 selection_targets, N_SELECTION_TARGETS);
3305
3306 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "selection_get",
3307 GTK_SIGNAL_FUNC(selection_get_cb), NULL);
3308
3309 /* Pretend we don't have input focus, we will get an event if we do. */
3310 gui.in_focus = FALSE;
3311
Bram Moolenaar071d4272004-06-13 20:20:40 +00003312 return OK;
3313}
3314
3315#if (defined(FEAT_GUI_GNOME) && defined(FEAT_SESSION)) || defined(PROTO)
3316/*
3317 * This is called from gui_start() after a fork() has been done.
3318 * We have to tell the session manager our new PID.
3319 */
3320 void
3321gui_mch_forked(void)
3322{
3323 if (using_gnome)
3324 {
3325 GnomeClient *client;
3326
3327 client = gnome_master_client();
3328
3329 if (client != NULL)
3330 gnome_client_set_process_id(client, getpid());
3331 }
3332}
3333#endif /* FEAT_GUI_GNOME && FEAT_SESSION */
3334
3335/*
3336 * Called when the foreground or background color has been changed.
3337 * This used to change the graphics contexts directly but we are
3338 * currently manipulating them where desired.
3339 */
3340 void
3341gui_mch_new_colors(void)
3342{
3343 if (gui.drawarea != NULL && gui.drawarea->window != NULL)
3344 {
3345 GdkColor color = { 0, 0, 0, 0 };
3346
3347 color.pixel = gui.back_pixel;
3348 gdk_window_set_background(gui.drawarea->window, &color);
3349 }
3350}
3351
3352#if defined(FEAT_MENU) || defined(FEAT_TOOLBAR)
3353 static int
3354get_item_dimensions(GtkWidget *widget, GtkOrientation orientation)
3355{
3356 GtkOrientation item_orientation = GTK_ORIENTATION_HORIZONTAL;
3357
3358#ifdef FEAT_GUI_GNOME
3359 if (using_gnome && widget != NULL)
3360 {
3361# ifdef HAVE_GTK2
3362 BonoboDockItem *dockitem;
3363
3364 widget = gtk_widget_get_parent(widget);
3365 dockitem = BONOBO_DOCK_ITEM(widget);
3366
3367 if (dockitem == NULL || dockitem->is_floating)
3368 return 0;
3369 item_orientation = bonobo_dock_item_get_orientation(dockitem);
3370# else
3371 GnomeDockItem *dockitem;
3372
3373 widget = widget->parent;
3374 dockitem = GNOME_DOCK_ITEM(widget);
3375
3376 if (dockitem == NULL || dockitem->is_floating)
3377 return 0;
3378 item_orientation = gnome_dock_item_get_orientation(dockitem);
3379# endif
3380 }
3381#endif
3382 if (widget != NULL
3383 && item_orientation == orientation
3384 && GTK_WIDGET_REALIZED(widget)
3385 && GTK_WIDGET_VISIBLE(widget))
3386 {
3387 if (orientation == GTK_ORIENTATION_HORIZONTAL)
3388 return widget->allocation.height;
3389 else
3390 return widget->allocation.width;
3391 }
3392 return 0;
3393}
3394#endif
3395
3396 static int
3397get_menu_tool_width(void)
3398{
3399 int width = 0;
3400
3401#ifdef FEAT_GUI_GNOME /* these are never vertical without GNOME */
3402# ifdef FEAT_MENU
3403 width += get_item_dimensions(gui.menubar, GTK_ORIENTATION_VERTICAL);
3404# endif
3405# ifdef FEAT_TOOLBAR
3406 width += get_item_dimensions(gui.toolbar, GTK_ORIENTATION_VERTICAL);
3407# endif
3408#endif
3409
3410 return width;
3411}
3412
3413 static int
3414get_menu_tool_height(void)
3415{
3416 int height = 0;
3417
3418#ifdef FEAT_MENU
3419 height += get_item_dimensions(gui.menubar, GTK_ORIENTATION_HORIZONTAL);
3420#endif
3421#ifdef FEAT_TOOLBAR
3422 height += get_item_dimensions(gui.toolbar, GTK_ORIENTATION_HORIZONTAL);
3423#endif
3424
3425 return height;
3426}
3427
3428 static void
3429update_window_manager_hints(void)
3430{
3431 static int old_width = 0;
3432 static int old_height = 0;
3433 static int old_char_width = 0;
3434 static int old_char_height = 0;
3435
3436 int width;
3437 int height;
3438
3439 /* This also needs to be done when the main window isn't there yet,
3440 * otherwise the hints don't work. */
3441 width = gui_get_base_width();
3442 height = gui_get_base_height();
3443# ifdef HAVE_GTK2
3444 width += get_menu_tool_width();
3445 height += get_menu_tool_height();
3446# endif
3447
3448 /* Avoid an expose event when the size didn't change. */
3449 if (width != old_width
3450 || height != old_height
3451 || gui.char_width != old_char_width
3452 || gui.char_height != old_char_height)
3453 {
3454 GdkGeometry geometry;
3455 GdkWindowHints geometry_mask;
3456
3457 geometry.width_inc = gui.char_width;
3458 geometry.height_inc = gui.char_height;
3459 geometry.base_width = width;
3460 geometry.base_height = height;
3461 geometry.min_width = width + MIN_COLUMNS * gui.char_width;
3462 geometry.min_height = height + MIN_LINES * gui.char_height;
3463 geometry_mask = GDK_HINT_BASE_SIZE|GDK_HINT_RESIZE_INC
3464 |GDK_HINT_MIN_SIZE;
3465# ifdef HAVE_GTK2
3466 /* Using gui.formwin as geometry widget doesn't work as expected
3467 * with GTK+ 2 -- dunno why. Presumably all the resizing hacks
3468 * in Vim confuse GTK+. */
3469 gtk_window_set_geometry_hints(GTK_WINDOW(gui.mainwin), gui.mainwin,
3470 &geometry, geometry_mask);
3471# else
3472 gtk_window_set_geometry_hints(GTK_WINDOW(gui.mainwin), gui.formwin,
3473 &geometry, geometry_mask);
3474# endif
3475 old_width = width;
3476 old_height = height;
3477 old_char_width = gui.char_width;
3478 old_char_height = gui.char_height;
3479 }
3480}
3481
3482/*
3483 * This signal informs us about the need to rearrange our sub-widgets.
3484 */
3485/*ARGSUSED*/
3486 static gint
3487form_configure_event(GtkWidget *widget, GdkEventConfigure *event,
3488 gpointer data)
3489{
3490 gtk_form_freeze(GTK_FORM(gui.formwin));
3491 gui_resize_shell(event->width, event->height);
3492 gtk_form_thaw(GTK_FORM(gui.formwin));
3493
3494 return TRUE;
3495}
3496
3497/*
3498 * Function called when window already closed.
3499 * We can't do much more here than to trying to preserve what had been done,
3500 * since the window is already inevitably going away.
3501 */
3502/*ARGSUSED0*/
3503 static void
3504mainwin_destroy_cb(GtkObject *object, gpointer data)
3505{
3506 /* Don't write messages to the GUI anymore */
3507 full_screen = FALSE;
3508
3509 gui.mainwin = NULL;
3510 gui.drawarea = NULL;
3511
3512 if (!exiting) /* only do anything if the destroy was unexpected */
3513 {
3514 STRNCPY(IObuff, _("Vim: Main window unexpectedly destroyed\n"),
3515 IOSIZE);
3516 IObuff[IOSIZE - 1] = NUL;
3517 preserve_exit();
3518 }
3519}
3520
3521/*
3522 * Open the GUI window which was created by a call to gui_mch_init().
3523 */
3524 int
3525gui_mch_open(void)
3526{
3527 guicolor_T fg_pixel = INVALCOLOR;
3528 guicolor_T bg_pixel = INVALCOLOR;
3529
3530#ifdef HAVE_GTK2
3531 /*
3532 * Allow setting a window role on the command line, or invent one
3533 * if none was specified. This is mainly useful for GNOME session
3534 * support; allowing the WM to restore window placement.
3535 */
3536 if (role_argument != NULL)
3537 {
3538 gtk_window_set_role(GTK_WINDOW(gui.mainwin), role_argument);
3539 }
3540 else
3541 {
3542 char *role;
3543
3544 /* Invent a unique-enough ID string for the role */
3545 role = g_strdup_printf("vim-%u-%u-%u",
3546 (unsigned)mch_get_pid(),
3547 (unsigned)g_random_int(),
3548 (unsigned)time(NULL));
3549
3550 gtk_window_set_role(GTK_WINDOW(gui.mainwin), role);
3551 g_free(role);
3552 }
3553#endif
3554
3555 if (gui_win_x != -1 && gui_win_y != -1)
3556#ifdef HAVE_GTK2
3557 gtk_window_move(GTK_WINDOW(gui.mainwin), gui_win_x, gui_win_y);
3558#else
3559 gtk_widget_set_uposition(gui.mainwin, gui_win_x, gui_win_y);
3560#endif
3561
3562 /* Determine user specified geometry, if present. */
3563 if (gui.geom != NULL)
3564 {
3565 int mask;
3566 unsigned int w, h;
3567 int x = 0;
3568 int y = 0;
3569
3570 mask = XParseGeometry((char *)gui.geom, &x, &y, &w, &h);
3571
3572 if (mask & WidthValue)
3573 Columns = w;
3574 if (mask & HeightValue)
3575 Rows = h;
3576 if (mask & (XValue | YValue))
3577#ifdef HAVE_GTK2
3578 gtk_window_move(GTK_WINDOW(gui.mainwin), x, y);
3579#else
3580 gtk_widget_set_uposition(gui.mainwin, x, y);
3581#endif
3582 vim_free(gui.geom);
3583 gui.geom = NULL;
3584 }
3585
3586 gtk_form_set_size(GTK_FORM(gui.formwin),
3587 (guint)(gui_get_base_width() + Columns * gui.char_width),
3588 (guint)(gui_get_base_height() + Rows * gui.char_height));
3589 update_window_manager_hints();
3590
3591 if (foreground_argument != NULL)
3592 fg_pixel = gui_get_color((char_u *)foreground_argument);
3593 if (fg_pixel == INVALCOLOR)
3594 fg_pixel = gui_get_color((char_u *)"Black");
3595
3596 if (background_argument != NULL)
3597 bg_pixel = gui_get_color((char_u *)background_argument);
3598 if (bg_pixel == INVALCOLOR)
3599 bg_pixel = gui_get_color((char_u *)"White");
3600
3601 if (found_reverse_arg)
3602 {
3603 gui.def_norm_pixel = bg_pixel;
3604 gui.def_back_pixel = fg_pixel;
3605 }
3606 else
3607 {
3608 gui.def_norm_pixel = fg_pixel;
3609 gui.def_back_pixel = bg_pixel;
3610 }
3611
3612 /* Get the colors from the "Normal" and "Menu" group (set in syntax.c or
3613 * in a vimrc file) */
3614 set_normal_colors();
3615
3616 /* Check that none of the colors are the same as the background color */
3617 gui_check_colors();
3618
3619 /* Get the colors for the highlight groups (gui_check_colors() might have
3620 * changed them). */
3621 highlight_gui_started(); /* re-init colors and fonts */
3622
3623 gtk_signal_connect(GTK_OBJECT(gui.mainwin), "destroy",
3624 GTK_SIGNAL_FUNC(mainwin_destroy_cb), NULL);
3625
3626#ifdef FEAT_HANGULIN
3627 hangul_keyboard_set();
3628#endif
3629
3630 /*
3631 * Notify the fixed area about the need to resize the contents of the
3632 * gui.formwin, which we use for random positioning of the included
3633 * components.
3634 *
3635 * We connect this signal deferred finally after anything is in place,
3636 * since this is intended to handle resizements coming from the window
3637 * manager upon us and should not interfere with what VIM is requesting
3638 * upon startup.
3639 */
3640 gtk_signal_connect(GTK_OBJECT(gui.formwin), "configure_event",
3641 GTK_SIGNAL_FUNC(form_configure_event), NULL);
3642
3643#ifdef FEAT_DND
3644 /*
3645 * Set up for receiving DND items.
3646 */
3647 gtk_drag_dest_set(gui.drawarea,
3648 GTK_DEST_DEFAULT_ALL,
3649 dnd_targets, N_DND_TARGETS,
3650 GDK_ACTION_COPY);
3651
3652 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "drag_data_received",
3653 GTK_SIGNAL_FUNC(drag_data_received_cb), NULL);
3654#endif
3655
3656#ifdef HAVE_GTK2
3657 /* With GTK+ 2, we need to iconify the window before calling show()
3658 * to avoid mapping the window for a short time. This is just as one
3659 * would expect it to work, but it's different in GTK+ 1. The funny
3660 * thing is that iconifying after show() _does_ work with GTK+ 1.
3661 * (BTW doing this in the "realize" handler makes no difference.) */
3662 if (found_iconic_arg && gtk_socket_id == 0)
3663 gui_mch_iconify();
3664#endif
3665
3666 {
3667#if defined(FEAT_GUI_GNOME) && defined(HAVE_GTK2) && defined(FEAT_MENU)
3668 unsigned long menu_handler = 0;
3669# ifdef FEAT_TOOLBAR
3670 unsigned long tool_handler = 0;
3671# endif
3672 /*
3673 * Urgh hackish :/ For some reason BonoboDockLayout always forces a
3674 * show when restoring the saved layout configuration. We can't just
3675 * hide the widgets again after gtk_widget_show(gui.mainwin) since it's
3676 * a toplevel window and thus will be realized immediately. Instead,
3677 * connect signal handlers to hide the widgets just after they've been
3678 * marked visible, but before the main window is realized.
3679 */
3680 if (using_gnome && vim_strchr(p_go, GO_MENUS) == NULL)
3681 menu_handler = g_signal_connect_after(gui.menubar_h, "show",
3682 G_CALLBACK(&gtk_widget_hide),
3683 NULL);
3684# ifdef FEAT_TOOLBAR
3685 if (using_gnome && vim_strchr(p_go, GO_TOOLBAR) == NULL
3686 && (toolbar_flags & (TOOLBAR_TEXT | TOOLBAR_ICONS)))
3687 tool_handler = g_signal_connect_after(gui.toolbar_h, "show",
3688 G_CALLBACK(&gtk_widget_hide),
3689 NULL);
3690# endif
3691#endif
3692 gtk_widget_show(gui.mainwin);
3693
3694#if defined(FEAT_GUI_GNOME) && defined(HAVE_GTK2) && defined(FEAT_MENU)
3695 if (menu_handler != 0)
3696 g_signal_handler_disconnect(gui.menubar_h, menu_handler);
3697# ifdef FEAT_TOOLBAR
3698 if (tool_handler != 0)
3699 g_signal_handler_disconnect(gui.toolbar_h, tool_handler);
3700# endif
3701#endif
3702 }
3703
3704#ifndef HAVE_GTK2
3705 /* With GTK+ 1, we need to iconify the window after calling show().
3706 * See the comment above for details. */
3707 if (found_iconic_arg && gtk_socket_id == 0)
3708 gui_mch_iconify();
3709#endif
3710
3711 return OK;
3712}
3713
3714
3715/*ARGSUSED0*/
3716 void
3717gui_mch_exit(int rc)
3718{
3719 if (gui.mainwin != NULL)
3720 gtk_widget_destroy(gui.mainwin);
3721
3722 if (gtk_main_level() > 0)
3723 gtk_main_quit();
3724}
3725
3726/*
3727 * Get the position of the top left corner of the window.
3728 */
3729 int
3730gui_mch_get_winpos(int *x, int *y)
3731{
3732#ifdef HAVE_GTK2
3733 gtk_window_get_position(GTK_WINDOW(gui.mainwin), x, y);
3734#else
3735 /* For some people this must be gdk_window_get_origin() for a correct
3736 * result. Where is the documentation! */
3737 gdk_window_get_root_origin(gui.mainwin->window, x, y);
3738#endif
3739 return OK;
3740}
3741
3742/*
3743 * Set the position of the top left corner of the window to the given
3744 * coordinates.
3745 */
3746 void
3747gui_mch_set_winpos(int x, int y)
3748{
3749#ifdef HAVE_GTK2
3750 gtk_window_move(GTK_WINDOW(gui.mainwin), x, y);
3751#else
3752 gdk_window_move(gui.mainwin->window, x, y);
3753#endif
3754}
3755
3756#ifdef HAVE_GTK2
3757#if 0
3758static int resize_idle_installed = FALSE;
3759/*
3760 * Idle handler to force resize. Used by gui_mch_set_shellsize() to ensure
3761 * the shell size doesn't exceed the window size, i.e. if the window manager
3762 * ignored our size request. Usually this happens if the window is maximized.
3763 *
3764 * FIXME: It'd be nice if we could find a little more orthodox solution.
3765 * See also the remark below in gui_mch_set_shellsize().
3766 *
3767 * DISABLED: When doing ":set lines+=1" this function would first invoke
3768 * gui_resize_shell() with the old size, then the normal callback would
3769 * report the new size through form_configure_event(). That caused the window
3770 * layout to be messed up.
3771 */
3772/*ARGSUSED0*/
3773 static gboolean
3774force_shell_resize_idle(gpointer data)
3775{
3776 if (gui.mainwin != NULL
3777 && GTK_WIDGET_REALIZED(gui.mainwin)
3778 && GTK_WIDGET_VISIBLE(gui.mainwin))
3779 {
3780 int width;
3781 int height;
3782
3783 gtk_window_get_size(GTK_WINDOW(gui.mainwin), &width, &height);
3784
3785 width -= get_menu_tool_width();
3786 height -= get_menu_tool_height();
3787
3788 gui_resize_shell(width, height);
3789 }
3790
3791 resize_idle_installed = FALSE;
3792 return FALSE; /* don't call me again */
3793}
3794#endif
3795#endif /* HAVE_GTK2 */
3796
3797/*
3798 * Set the windows size.
3799 */
3800/*ARGSUSED2*/
3801 void
3802gui_mch_set_shellsize(int width, int height,
3803 int min_width, int min_height,
3804 int base_width, int base_height)
3805{
3806#ifndef HAVE_GTK2
3807 /* Hack: When the form already is at the desired size, the window might
3808 * have been resized with the mouse. Force a resize by setting a
3809 * different size first. */
3810 if (GTK_FORM(gui.formwin)->width == width
3811 && GTK_FORM(gui.formwin)->height == height)
3812 {
3813 gtk_form_set_size(GTK_FORM(gui.formwin), width + 1, height + 1);
3814 gui_mch_update();
3815 }
3816 gtk_form_set_size(GTK_FORM(gui.formwin), width, height);
3817#endif
3818
3819 /* give GTK+ a chance to put all widget's into place */
3820 gui_mch_update();
3821
3822 /* this will cause the proper resizement to happen too */
3823 update_window_manager_hints();
3824
3825#ifdef HAVE_GTK2
3826 /* With GTK+ 2, changing the size of the form widget doesn't resize
3827 * the window. So lets do it the other way around and resize the
3828 * main window instead. */
3829 width += get_menu_tool_width();
3830 height += get_menu_tool_height();
3831
3832 gtk_window_resize(GTK_WINDOW(gui.mainwin), width, height);
3833
3834#if 0
3835 if (!resize_idle_installed)
3836 {
3837 g_idle_add_full(GDK_PRIORITY_EVENTS + 10,
3838 &force_shell_resize_idle, NULL, NULL);
3839 resize_idle_installed = TRUE;
3840 }
3841#endif
3842 /*
3843 * Wait until all events are processed to prevent a crash because the
3844 * real size of the drawing area doesn't reflect Vim's internal ideas.
3845 *
3846 * This is a bit of a hack, since Vim is a terminal application with a GUI
3847 * on top, while the GUI expects to be the boss.
3848 */
3849 gui_mch_update();
3850#endif
3851}
3852
3853
3854/*
3855 * The screen size is used to make sure the initial window doesn't get bigger
3856 * than the screen. This subtracts some room for menubar, toolbar and window
3857 * decorations.
3858 */
3859 void
3860gui_mch_get_screen_dimensions(int *screen_w, int *screen_h)
3861{
3862#ifdef HAVE_GTK_MULTIHEAD
3863 GdkScreen* screen;
3864
3865 if (gui.mainwin != NULL && gtk_widget_has_screen(gui.mainwin))
3866 screen = gtk_widget_get_screen(gui.mainwin);
3867 else
3868 screen = gdk_screen_get_default();
3869
3870 *screen_w = gdk_screen_get_width(screen);
3871 *screen_h = gdk_screen_get_height(screen) - p_ghr;
3872#else
3873 *screen_w = gdk_screen_width();
3874 /* Subtract 'guiheadroom' from the height to allow some room for the
3875 * window manager (task list and window title bar). */
3876 *screen_h = gdk_screen_height() - p_ghr;
3877#endif
3878
3879 /*
3880 * FIXME: dirty trick: Because the gui_get_base_height() doesn't include
3881 * the toolbar and menubar for GTK, we subtract them from the screen
3882 * hight, so that the window size can be made to fit on the screen.
3883 * This should be completely changed later.
3884 */
3885 *screen_w -= get_menu_tool_width();
3886 *screen_h -= get_menu_tool_height();
3887}
3888
3889#if defined(FEAT_TITLE) || defined(PROTO)
3890/*ARGSUSED*/
3891 void
3892gui_mch_settitle(char_u *title, char_u *icon)
3893{
3894# ifdef HAVE_GTK2
3895 if (title != NULL && output_conv.vc_type != CONV_NONE)
3896 title = string_convert(&output_conv, title, NULL);
3897# endif
3898
3899 gtk_window_set_title(GTK_WINDOW(gui.mainwin), (const char *)title);
3900
3901# ifdef HAVE_GTK2
3902 if (output_conv.vc_type != CONV_NONE)
3903 vim_free(title);
3904# endif
3905}
3906#endif /* FEAT_TITLE */
3907
3908#if defined(FEAT_MENU) || defined(PROTO)
3909 void
3910gui_mch_enable_menu(int showit)
3911{
3912 GtkWidget *widget;
3913
3914# ifdef FEAT_GUI_GNOME
3915 if (using_gnome)
3916 widget = gui.menubar_h;
3917 else
3918# endif
3919 widget = gui.menubar;
3920
3921 if (!showit != !GTK_WIDGET_VISIBLE(widget))
3922 {
3923 if (showit)
3924 gtk_widget_show(widget);
3925 else
3926 gtk_widget_hide(widget);
3927
3928 update_window_manager_hints();
3929 }
3930}
3931#endif /* FEAT_MENU */
3932
3933#if defined(FEAT_TOOLBAR) || defined(PROTO)
3934 void
3935gui_mch_show_toolbar(int showit)
3936{
3937 GtkWidget *widget;
3938
3939 if (gui.toolbar == NULL)
3940 return;
3941
3942# ifdef FEAT_GUI_GNOME
3943 if (using_gnome)
3944 widget = gui.toolbar_h;
3945 else
3946# endif
3947 widget = gui.toolbar;
3948
3949 if (showit)
3950 set_toolbar_style(GTK_TOOLBAR(gui.toolbar));
3951
3952 if (!showit != !GTK_WIDGET_VISIBLE(widget))
3953 {
3954 if (showit)
3955 gtk_widget_show(widget);
3956 else
3957 gtk_widget_hide(widget);
3958
3959 update_window_manager_hints();
3960 }
3961}
3962#endif /* FEAT_TOOLBAR */
3963
3964#ifndef HAVE_GTK2
3965/*
3966 * Get a font structure for highlighting.
3967 * "cbdata" is a pointer to the global gui structure.
3968 */
3969/*ARGSUSED*/
3970 static void
3971font_sel_ok(GtkWidget *wgt, gpointer cbdata)
3972{
3973 gui_T *vw = (gui_T *)cbdata;
3974 GtkFontSelectionDialog *fs = (GtkFontSelectionDialog *)vw->fontdlg;
3975
3976 if (vw->fontname)
3977 g_free(vw->fontname);
3978
3979 vw->fontname = (char_u *)gtk_font_selection_dialog_get_font_name(fs);
3980 gtk_widget_hide(vw->fontdlg);
3981 if (gtk_main_level() > 0)
3982 gtk_main_quit();
3983}
3984
3985/*ARGSUSED*/
3986 static void
3987font_sel_cancel(GtkWidget *wgt, gpointer cbdata)
3988{
3989 gui_T *vw = (gui_T *)cbdata;
3990
3991 gtk_widget_hide(vw->fontdlg);
3992 if (gtk_main_level() > 0)
3993 gtk_main_quit();
3994}
3995
3996/*ARGSUSED*/
3997 static void
3998font_sel_destroy(GtkWidget *wgt, gpointer cbdata)
3999{
4000 gui_T *vw = (gui_T *)cbdata;
4001
4002 vw->fontdlg = NULL;
4003 if (gtk_main_level() > 0)
4004 gtk_main_quit();
4005}
4006#endif /* !HAVE_GTK2 */
4007
4008#ifdef HAVE_GTK2
4009/*
4010 * Check if a given font is a CJK font. This is done in a very crude manner. It
4011 * just see if U+04E00 for zh and ja and U+AC00 for ko are covered in a given
4012 * font. Consequently, this function cannot be used as a general purpose check
4013 * for CJK-ness for which fontconfig APIs should be used. This is only used by
4014 * gui_mch_init_font() to deal with 'CJK fixed width fonts'.
4015 */
4016 static int
4017is_cjk_font(PangoFontDescription *font_desc)
4018{
4019 static const char * const cjk_langs[] =
4020 {"zh_CN", "zh_TW", "zh_HK", "ja", "ko"};
4021
4022 PangoFont *font;
4023 unsigned i;
4024 int is_cjk = FALSE;
4025
4026 font = pango_context_load_font(gui.text_context, font_desc);
4027
4028 if (font == NULL)
4029 return FALSE;
4030
4031 for (i = 0; !is_cjk && i < G_N_ELEMENTS(cjk_langs); ++i)
4032 {
4033 PangoCoverage *coverage;
4034 gunichar uc;
4035
4036 coverage = pango_font_get_coverage(
4037 font, pango_language_from_string(cjk_langs[i]));
4038
4039 if (coverage != NULL)
4040 {
4041 uc = (cjk_langs[i][0] == 'k') ? 0xAC00 : 0x4E00;
4042 is_cjk = (pango_coverage_get(coverage, uc) == PANGO_COVERAGE_EXACT);
4043 pango_coverage_unref(coverage);
4044 }
4045 }
4046
4047 g_object_unref(font);
4048
4049 return is_cjk;
4050}
4051#endif /* HAVE_GTK2 */
4052
4053 int
4054gui_mch_adjust_charsize(void)
4055{
4056#ifdef HAVE_GTK2
4057 PangoFontMetrics *metrics;
4058 int ascent;
4059 int descent;
4060
4061 metrics = pango_context_get_metrics(gui.text_context, gui.norm_font,
4062 pango_context_get_language(gui.text_context));
4063 ascent = pango_font_metrics_get_ascent(metrics);
4064 descent = pango_font_metrics_get_descent(metrics);
4065
4066 pango_font_metrics_unref(metrics);
4067
4068 gui.char_height = (ascent + descent + PANGO_SCALE - 1) / PANGO_SCALE
4069 + p_linespace;
4070 gui.char_ascent = PANGO_PIXELS(ascent + p_linespace * PANGO_SCALE / 2);
4071
4072#else /* !HAVE_GTK2 */
4073
4074 gui.char_height = gui.current_font->ascent + gui.current_font->descent
4075 + p_linespace;
4076 gui.char_ascent = gui.current_font->ascent + p_linespace / 2;
4077
4078#endif /* !HAVE_GTK2 */
4079
4080 /* A not-positive value of char_height may crash Vim. Only happens
4081 * if 'linespace' is negative (which does make sense sometimes). */
4082 gui.char_ascent = MAX(gui.char_ascent, 0);
4083 gui.char_height = MAX(gui.char_height, gui.char_ascent + 1);
4084
4085 return OK;
4086}
4087
4088#if defined(FEAT_XFONTSET) || defined(PROTO)
4089/*
4090 * Try to load the requested fontset.
4091 */
4092/*ARGSUSED2*/
4093 GuiFontset
4094gui_mch_get_fontset(char_u *name, int report_error, int fixed_width)
4095{
4096 GdkFont *font;
4097
4098 if (!gui.in_use || name == NULL)
4099 return NOFONT;
4100
4101 font = gdk_fontset_load((gchar *)name);
4102
4103 if (font == NULL)
4104 {
4105 if (report_error)
4106 EMSG2(_(e_fontset), name);
4107 return NOFONT;
4108 }
4109 /* TODO: check if the font is fixed width. */
4110
4111 /* reference this font as being in use */
4112 gdk_font_ref(font);
4113
4114 return (GuiFontset)font;
4115}
4116#endif /* FEAT_XFONTSET */
4117
4118#ifndef HAVE_GTK2
4119/*
4120 * Put up a font dialog and return the selected font name in allocated memory.
4121 * "oldval" is the previous value.
4122 * Return NULL when cancelled.
4123 */
4124 char_u *
4125gui_mch_font_dialog(char_u *oldval)
4126{
4127 char_u *fontname = NULL;
4128
4129 if (!gui.fontdlg)
4130 {
4131 GtkFontSelectionDialog *fsd = NULL;
4132
4133 gui.fontdlg = gtk_font_selection_dialog_new(_("Font Selection"));
4134 fsd = GTK_FONT_SELECTION_DIALOG(gui.fontdlg);
4135 gtk_window_set_modal(GTK_WINDOW(gui.fontdlg), TRUE);
4136 gtk_window_set_transient_for(GTK_WINDOW(gui.fontdlg),
4137 GTK_WINDOW(gui.mainwin));
4138 gtk_signal_connect(GTK_OBJECT(gui.fontdlg), "destroy",
4139 GTK_SIGNAL_FUNC(font_sel_destroy), &gui);
4140 gtk_signal_connect(GTK_OBJECT(fsd->ok_button), "clicked",
4141 GTK_SIGNAL_FUNC(font_sel_ok), &gui);
4142 gtk_signal_connect(GTK_OBJECT(fsd->cancel_button), "clicked",
4143 GTK_SIGNAL_FUNC(font_sel_cancel), &gui);
4144 }
4145
4146 if (oldval != NULL && *oldval != NUL)
4147 gtk_font_selection_dialog_set_font_name(
4148 GTK_FONT_SELECTION_DIALOG(gui.fontdlg), (char *)oldval);
4149
4150 if (gui.fontname)
4151 {
4152 g_free(gui.fontname);
4153 gui.fontname = NULL;
4154 }
4155 gtk_window_position(GTK_WINDOW(gui.fontdlg), GTK_WIN_POS_MOUSE);
4156 gtk_widget_show(gui.fontdlg);
4157 {
4158 static gchar *spacings[] = {"c", "m", NULL};
4159
4160 /* In GTK 1.2.3 this must be after the gtk_widget_show() call,
4161 * otherwise everything is blocked for ten seconds. */
4162 gtk_font_selection_dialog_set_filter(
4163 GTK_FONT_SELECTION_DIALOG(gui.fontdlg),
4164 GTK_FONT_FILTER_BASE,
4165 GTK_FONT_ALL, NULL, NULL,
4166 NULL, NULL, spacings, NULL);
4167 }
4168
4169 /* Wait for the font dialog to be closed. */
4170 while (gui.fontdlg && GTK_WIDGET_DRAWABLE(gui.fontdlg))
4171 gtk_main_iteration_do(TRUE);
4172
4173 if (gui.fontname != NULL)
4174 {
4175 fontname = vim_strsave(gui.fontname);
4176 g_free(gui.fontname);
4177 gui.fontname = NULL;
4178 }
4179 return fontname;
4180}
4181#endif /* !HAVE_GTK2 */
4182
4183#ifdef HAVE_GTK2
4184/*
4185 * Put up a font dialog and return the selected font name in allocated memory.
4186 * "oldval" is the previous value. Return NULL when cancelled.
4187 * This should probably go into gui_gtk.c. Hmm.
4188 * FIXME:
4189 * The GTK2 font selection dialog has no filtering API. So we could either
4190 * a) implement our own (possibly copying the code from somewhere else) or
4191 * b) just live with it.
4192 */
4193 char_u *
4194gui_mch_font_dialog(char_u *oldval)
4195{
4196 GtkWidget *dialog;
4197 int response;
4198 char_u *fontname = NULL;
4199 char_u *oldname;
4200
4201 dialog = gtk_font_selection_dialog_new(NULL);
4202
4203 gtk_window_set_transient_for(GTK_WINDOW(dialog), GTK_WINDOW(gui.mainwin));
4204 gtk_window_set_destroy_with_parent(GTK_WINDOW(dialog), TRUE);
4205
4206 if (oldval != NULL && oldval[0] != NUL)
4207 {
4208 if (output_conv.vc_type != CONV_NONE)
4209 oldname = string_convert(&output_conv, oldval, NULL);
4210 else
4211 oldname = oldval;
4212
4213 /* Annoying bug in GTK (or Pango): if the font name does not include a
4214 * size, zero is used. Use default point size ten. */
4215 if (!vim_isdigit(oldname[STRLEN(oldname) - 1]))
4216 {
4217 char_u *p = vim_strnsave(oldname, STRLEN(oldname) + 3);
4218
4219 if (p != NULL)
4220 {
4221 STRCPY(p + STRLEN(p), " 10");
4222 if (oldname != oldval)
4223 vim_free(oldname);
4224 oldname = p;
4225 }
4226 }
4227
4228 gtk_font_selection_dialog_set_font_name(
4229 GTK_FONT_SELECTION_DIALOG(dialog), (const char *)oldname);
4230
4231 if (oldname != oldval)
4232 vim_free(oldval);
4233 }
4234
4235 response = gtk_dialog_run(GTK_DIALOG(dialog));
4236
4237 if (response == GTK_RESPONSE_OK)
4238 {
4239 char *name;
4240
4241 name = gtk_font_selection_dialog_get_font_name(
4242 GTK_FONT_SELECTION_DIALOG(dialog));
4243 if (name != NULL)
4244 {
4245 if (input_conv.vc_type != CONV_NONE)
4246 fontname = string_convert(&input_conv, (char_u *)name, NULL);
4247 else
4248 fontname = vim_strsave((char_u *)name);
4249 g_free(name);
4250 }
4251 }
4252
4253 if (response != GTK_RESPONSE_NONE)
4254 gtk_widget_destroy(dialog);
4255
4256 return fontname;
4257}
4258
4259/*
4260 * Some monospace fonts don't support a bold weight, and fall back
4261 * silently to the regular weight. But this is no good since our text
4262 * drawing function can emulate bold by overstriking. So let's try
4263 * to detect whether bold weight is actually available and emulate it
4264 * otherwise.
4265 *
4266 * Note that we don't need to check for italic style since Xft can
4267 * emulate italic on its own, provided you have a proper fontconfig
4268 * setup. We wouldn't be able to emulate it in Vim anyway.
4269 */
4270 static void
4271get_styled_font_variants(void)
4272{
4273 PangoFontDescription *bold_font_desc;
4274 PangoFont *plain_font;
4275 PangoFont *bold_font;
4276
4277 gui.font_can_bold = FALSE;
4278
4279 plain_font = pango_context_load_font(gui.text_context, gui.norm_font);
4280
4281 if (plain_font == NULL)
4282 return;
4283
4284 bold_font_desc = pango_font_description_copy_static(gui.norm_font);
4285 pango_font_description_set_weight(bold_font_desc, PANGO_WEIGHT_BOLD);
4286
4287 bold_font = pango_context_load_font(gui.text_context, bold_font_desc);
4288 /*
4289 * The comparison relies on the unique handle nature of a PangoFont*,
4290 * i.e. it's assumed that a different PangoFont* won't refer to the
4291 * same font. Seems to work, and failing here isn't critical anyway.
4292 */
4293 if (bold_font != NULL)
4294 {
4295 gui.font_can_bold = (bold_font != plain_font);
4296 g_object_unref(bold_font);
4297 }
4298
4299 pango_font_description_free(bold_font_desc);
4300 g_object_unref(plain_font);
4301}
4302
4303#else /* !HAVE_GTK2 */
4304
4305/*
4306 * There is only one excuse I can give for the following attempt to manage font
4307 * styles:
4308 *
4309 * I HATE THE BRAIN DEAD WAY X11 IS HANDLING FONTS (--mdcki)
4310 * (Me too. --danielk)
4311 */
4312 static void
4313get_styled_font_variants(char_u * font_name)
4314{
4315 char *chunk[32];
4316 char *sdup;
4317 char *tmp;
4318 int len, i;
4319 GuiFont *styled_font[3];
4320
4321 styled_font[0] = &gui.bold_font;
4322 styled_font[1] = &gui.ital_font;
4323 styled_font[2] = &gui.boldital_font;
4324
4325 /* First free whatever was freviously there. */
4326 for (i = 0; i < 3; ++i)
4327 if (*styled_font[i])
4328 {
4329 gdk_font_unref(*styled_font[i]);
4330 *styled_font[i] = NULL;
4331 }
4332
4333 if ((sdup = g_strdup((const char *)font_name)) == NULL)
4334 return;
4335
4336 /* split up the whole */
4337 i = 0;
4338 for (tmp = sdup; *tmp != '\0'; ++tmp)
4339 {
4340 if (*tmp == '-')
4341 {
4342 *tmp = '\0';
4343
4344 if (i == 32)
4345 break;
4346
4347 chunk[i] = tmp + 1;
4348 ++i;
4349 }
4350 }
4351
4352 if (i == 14)
4353 {
4354 GdkFont *font = NULL;
4355 const char *bold_chunk[3] = { "bold", NULL, "bold" };
4356 const char *italic_chunk[3] = { NULL, "o", "o" };
4357
4358 /* font name was complete */
4359 len = strlen((const char *)font_name) + 32;
4360
4361 for (i = 0; i < 3; ++i)
4362 {
4363 char *styled_name;
4364 int j;
4365
4366 styled_name = (char *)alloc(len);
4367 if (styled_name == NULL)
4368 {
4369 g_free(sdup);
4370 return;
4371 }
4372
4373 *styled_name = '\0';
4374
4375 for (j = 0; j < 14; ++j)
4376 {
4377 strcat(styled_name, "-");
4378 if (j == 2 && bold_chunk[i] != NULL)
4379 strcat(styled_name, bold_chunk[i]);
4380 else if (j == 3 && italic_chunk[i] != NULL)
4381 strcat(styled_name, italic_chunk[i]);
4382 else
4383 strcat(styled_name, chunk[j]);
4384 }
4385
4386 font = gui_mch_get_font((char_u *)styled_name, FALSE);
4387 if (font != NULL)
4388 *styled_font[i] = font;
4389
4390 vim_free(styled_name);
4391 }
4392 }
4393
4394 g_free(sdup);
4395}
4396#endif /* !HAVE_GTK2 */
4397
4398#ifdef HAVE_GTK2
4399static PangoEngineShape *default_shape_engine = NULL;
4400
4401/*
4402 * Create a map from ASCII characters in the range [32,126] to glyphs
4403 * of the current font. This is used by gui_gtk2_draw_string() to skip
4404 * the itemize and shaping process for the most common case.
4405 */
4406 static void
4407ascii_glyph_table_init(void)
4408{
4409 char_u ascii_chars[128];
4410 PangoAttrList *attr_list;
4411 GList *item_list;
4412 int i;
4413
4414 if (gui.ascii_glyphs != NULL)
4415 pango_glyph_string_free(gui.ascii_glyphs);
4416 if (gui.ascii_font != NULL)
4417 g_object_unref(gui.ascii_font);
4418
4419 gui.ascii_glyphs = NULL;
4420 gui.ascii_font = NULL;
4421
4422 /* For safety, fill in question marks for the control characters. */
4423 for (i = 0; i < 32; ++i)
4424 ascii_chars[i] = '?';
4425 for (; i < 127; ++i)
4426 ascii_chars[i] = i;
4427 ascii_chars[i] = '?';
4428
4429 attr_list = pango_attr_list_new();
4430 item_list = pango_itemize(gui.text_context, (const char *)ascii_chars,
4431 0, sizeof(ascii_chars), attr_list, NULL);
4432
4433 if (item_list != NULL && item_list->next == NULL) /* play safe */
4434 {
4435 PangoItem *item;
4436 int width;
4437
4438 item = (PangoItem *)item_list->data;
4439 width = gui.char_width * PANGO_SCALE;
4440
4441 /* Remember the shape engine used for ASCII. */
4442 default_shape_engine = item->analysis.shape_engine;
4443
4444 gui.ascii_font = item->analysis.font;
4445 g_object_ref(gui.ascii_font);
4446
4447 gui.ascii_glyphs = pango_glyph_string_new();
4448
4449 pango_shape((const char *)ascii_chars, sizeof(ascii_chars),
4450 &item->analysis, gui.ascii_glyphs);
4451
4452 g_return_if_fail(gui.ascii_glyphs->num_glyphs == sizeof(ascii_chars));
4453
4454 for (i = 0; i < gui.ascii_glyphs->num_glyphs; ++i)
4455 {
4456 PangoGlyphGeometry *geom;
4457
4458 geom = &gui.ascii_glyphs->glyphs[i].geometry;
4459 geom->x_offset += MAX(0, width - geom->width) / 2;
4460 geom->width = width;
4461 }
4462 }
4463
4464 g_list_foreach(item_list, (GFunc)&pango_item_free, NULL);
4465 g_list_free(item_list);
4466 pango_attr_list_unref(attr_list);
4467}
4468#endif /* HAVE_GTK2 */
4469
4470/*
4471 * Initialize Vim to use the font or fontset with the given name.
4472 * Return FAIL if the font could not be loaded, OK otherwise.
4473 */
4474/*ARGSUSED1*/
4475 int
4476gui_mch_init_font(char_u *font_name, int fontset)
4477{
4478#ifdef HAVE_GTK2
4479 PangoFontDescription *font_desc;
4480 PangoLayout *layout;
4481 int width;
4482
4483 /* If font_name is NULL, this means to use the default, which should
4484 * be present on all proper Pango/fontconfig installations. */
4485 if (font_name == NULL)
4486 font_name = (char_u *)DEFAULT_FONT;
4487
4488 font_desc = gui_mch_get_font(font_name, FALSE);
4489
4490 if (font_desc == NULL)
4491 return FAIL;
4492
4493 gui_mch_free_font(gui.norm_font);
4494 gui.norm_font = font_desc;
4495
4496 pango_context_set_font_description(gui.text_context, font_desc);
4497
4498 layout = pango_layout_new(gui.text_context);
4499 pango_layout_set_text(layout, "MW", 2);
4500 pango_layout_get_size(layout, &width, NULL);
4501 /*
4502 * Set char_width to half the width obtained from pango_layout_get_size()
4503 * for CJK fixed_width/bi-width fonts. An unpatched version of Xft leads
4504 * Pango to use the same width for both non-CJK characters (e.g. Latin
4505 * letters and numbers) and CJK characters. This results in 's p a c e d
4506 * o u t' rendering when a CJK 'fixed width' font is used. To work around
4507 * that, divide the width returned by Pango by 2 if cjk_width is equal to
4508 * width for CJK fonts.
4509 *
4510 * For related bugs, see:
4511 * http://bugzilla.gnome.org/show_bug.cgi?id=106618
4512 * http://bugzilla.gnome.org/show_bug.cgi?id=106624
4513 *
4514 * With this, for all four of the following cases, Vim works fine:
4515 * guifont=CJK_fixed_width_font
4516 * guifont=Non_CJK_fixed_font
4517 * guifont=Non_CJK_fixed_font,CJK_Fixed_font
4518 * guifont=Non_CJK_fixed_font guifontwide=CJK_fixed_font
4519 */
4520 if (is_cjk_font(gui.norm_font))
4521 {
4522 int cjk_width;
4523
4524 /* Measure the text extent of U+4E00 and U+4E8C */
4525 pango_layout_set_text(layout, "\344\270\200\344\272\214", -1);
4526 pango_layout_get_size(layout, &cjk_width, NULL);
4527
4528 if (width == cjk_width) /* Xft not patched */
4529 width /= 2;
4530 }
4531 g_object_unref(layout);
4532
4533 gui.char_width = (width / 2 + PANGO_SCALE - 1) / PANGO_SCALE;
4534
4535 /* A zero width may cause a crash. Happens for semi-invalid fontsets. */
4536 if (gui.char_width <= 0)
4537 gui.char_width = 8;
4538
4539 gui_mch_adjust_charsize();
4540
4541 /* Set the fontname, which will be used for information purposes */
4542 hl_set_font_name(font_name);
4543
4544 get_styled_font_variants();
4545 ascii_glyph_table_init();
4546
4547 /* Avoid unnecessary overhead if 'guifontwide' is equal to 'guifont'. */
4548 if (gui.wide_font != NULL
4549 && pango_font_description_equal(gui.norm_font, gui.wide_font))
4550 {
4551 pango_font_description_free(gui.wide_font);
4552 gui.wide_font = NULL;
4553 }
4554
4555#else /* !HAVE_GTK2 */
4556
4557 GdkFont *font = NULL;
4558
4559# ifdef FEAT_XFONTSET
4560 /* Try loading a fontset. If this fails we try loading a normal font. */
4561 if (fontset && font_name != NULL)
4562 font = gui_mch_get_fontset(font_name, TRUE, TRUE);
4563
4564 if (font == NULL)
4565# endif
4566 {
4567 /* If font_name is NULL, this means to use the default, which should
4568 * be present on all X11 servers. */
4569 if (font_name == NULL)
4570 font_name = (char_u *)DEFAULT_FONT;
4571 font = gui_mch_get_font(font_name, FALSE);
4572 }
4573
4574 if (font == NULL)
4575 return FAIL;
4576
4577 gui_mch_free_font(gui.norm_font);
4578# ifdef FEAT_XFONTSET
4579 gui_mch_free_fontset(gui.fontset);
4580 if (font->type == GDK_FONT_FONTSET)
4581 {
4582 gui.norm_font = NOFONT;
4583 gui.fontset = (GuiFontset)font;
4584 /* Use two bytes, this works around the problem that the result would
4585 * be zero if no 8-bit font was found. */
4586 gui.char_width = gdk_string_width(font, "xW") / 2;
4587 }
4588 else
4589# endif
4590 {
4591 gui.norm_font = font;
4592# ifdef FEAT_XFONTSET
4593 gui.fontset = NOFONTSET;
4594# endif
4595 gui.char_width = ((XFontStruct *)
4596 GDK_FONT_XFONT(font))->max_bounds.width;
4597 }
4598
4599 /* A zero width may cause a crash. Happens for semi-invalid fontsets. */
4600 if (gui.char_width <= 0)
4601 gui.char_width = 8;
4602
4603 gui.char_height = font->ascent + font->descent + p_linespace;
4604 gui.char_ascent = font->ascent + p_linespace / 2;
4605
4606 /* A not-positive value of char_height may crash Vim. Only happens
4607 * if 'linespace' is negative (which does make sense sometimes). */
4608 gui.char_ascent = MAX(gui.char_ascent, 0);
4609 gui.char_height = MAX(gui.char_height, gui.char_ascent + 1);
4610
4611 /* Set the fontname, which will be used for information purposes */
4612 hl_set_font_name(font_name);
4613
4614 if (font->type != GDK_FONT_FONTSET)
4615 get_styled_font_variants(font_name);
4616
4617 /* Synchronize the fonts used in user input dialogs, since otherwise
4618 * search/replace will be esp. annoying in case of international font
4619 * usage.
4620 */
4621 gui_gtk_synch_fonts();
4622
4623# ifdef FEAT_XIM
4624 /* Adjust input management behaviour to the capabilities of the new
4625 * fontset */
4626 xim_decide_input_style();
4627 if (xim_get_status_area_height())
4628 {
4629 /* Status area is required. Just create the empty container so that
4630 * mainwin will allocate the extra space for status area. */
4631 GtkWidget *alignment = gtk_alignment_new((gfloat)0.5, (gfloat)0.5,
4632 (gfloat)1.0, (gfloat)1.0);
4633
4634 gtk_widget_set_usize(alignment, 20, gui.char_height + 2);
4635 gtk_box_pack_end(GTK_BOX(GTK_BIN(gui.mainwin)->child),
4636 alignment, FALSE, FALSE, 0);
4637 gtk_widget_show(alignment);
4638 }
4639# endif
4640#endif /* !HAVE_GTK2 */
4641
4642 /* Preserve the logical dimensions of the screen. */
4643 update_window_manager_hints();
4644
4645 return OK;
4646}
4647
4648/*
4649 * Get a reference to the font "name".
4650 * Return zero for failure.
4651 */
4652 GuiFont
4653gui_mch_get_font(char_u *name, int report_error)
4654{
4655#ifdef HAVE_GTK2
4656 PangoFontDescription *font;
4657#else
4658 GdkFont *font;
4659#endif
4660
4661 /* can't do this when GUI is not running */
4662 if (!gui.in_use || name == NULL)
4663 return NULL;
4664
4665#ifdef HAVE_GTK2
4666 if (output_conv.vc_type != CONV_NONE)
4667 {
4668 char_u *buf;
4669
4670 buf = string_convert(&output_conv, name, NULL);
4671 if (buf != NULL)
4672 {
4673 font = pango_font_description_from_string((const char *)buf);
4674 vim_free(buf);
4675 }
4676 else
4677 font = NULL;
4678 }
4679 else
4680 font = pango_font_description_from_string((const char *)name);
4681
4682 if (font != NULL)
4683 {
4684 PangoFont *real_font;
4685
4686 /* pango_context_load_font() bails out if no font size is set */
4687 if (pango_font_description_get_size(font) <= 0)
4688 pango_font_description_set_size(font, 10 * PANGO_SCALE);
4689
4690 real_font = pango_context_load_font(gui.text_context, font);
4691
4692 if (real_font == NULL)
4693 {
4694 pango_font_description_free(font);
4695 font = NULL;
4696 }
4697 else
4698 g_object_unref(real_font);
4699 }
4700#else
4701 font = gdk_font_load((const gchar *)name);
4702#endif
4703
4704 if (font == NULL)
4705 {
4706 if (report_error)
4707 EMSG2(_(e_font), name);
4708 return NULL;
4709 }
4710
4711#ifdef HAVE_GTK2
4712 /*
4713 * The fixed-width check has been disabled for GTK+ 2. Rationale:
4714 *
4715 * - The check tends to report false positives, particularly
4716 * in non-Latin locales or with old X fonts.
4717 * - Thanks to our fixed-width hack in gui_gtk2_draw_string(),
4718 * GTK+ 2 Vim is actually capable of displaying variable width
4719 * fonts. Those will just be spaced out like in AA xterm.
4720 * - Failing here for the default font causes GUI startup to fail
4721 * even with wiped out configuration files.
4722 * - The font dialog displays all fonts unfiltered, and it's rather
4723 * annoying if 95% of the listed fonts produce an error message.
4724 */
4725# if 0
4726 {
4727 /* Check that this is a mono-spaced font. Naturally, this is a bit
4728 * hackish -- fixed-width isn't really suitable for i18n text :/ */
4729 PangoLayout *layout;
4730 unsigned int i;
4731 int last_width = -1;
4732 const char test_chars[] = { 'W', 'i', ',', 'x' }; /* arbitrary */
4733
4734 layout = pango_layout_new(gui.text_context);
4735 pango_layout_set_font_description(layout, font);
4736
4737 for (i = 0; i < G_N_ELEMENTS(test_chars); ++i)
4738 {
4739 int width;
4740
4741 pango_layout_set_text(layout, &test_chars[i], 1);
4742 pango_layout_get_size(layout, &width, NULL);
4743
4744 if (last_width >= 0 && width != last_width)
4745 {
4746 pango_font_description_free(font);
4747 font = NULL;
4748 break;
4749 }
4750
4751 last_width = width;
4752 }
4753
4754 g_object_unref(layout);
4755 }
4756# endif
4757#else /* !HAVE_GTK2 */
4758 {
4759 XFontStruct *xfont;
4760
4761 /* reference this font as being in use */
4762 gdk_font_ref(font);
4763
4764 /* Check that this is a mono-spaced font.
4765 */
4766 xfont = (XFontStruct *) GDK_FONT_XFONT(font);
4767
4768 if (xfont->max_bounds.width != xfont->min_bounds.width)
4769 {
4770 gdk_font_unref(font);
4771 font = NULL;
4772 }
4773 }
4774#endif /* !HAVE_GTK2 */
4775
4776#if !defined(HAVE_GTK2) || 0 /* disabled for GTK+ 2, see above */
4777 if (font == NULL && report_error)
4778 EMSG2(_(e_fontwidth), name);
4779#endif
4780
4781 return font;
4782}
4783
4784#if !defined(HAVE_GTK2) || defined(PROTO)
4785/*
4786 * Set the current text font.
4787 * Since we create all GC on demand, we use just gui.current_font to
4788 * indicate the desired current font.
4789 */
4790 void
4791gui_mch_set_font(GuiFont font)
4792{
4793 gui.current_font = font;
4794}
4795#endif
4796
4797#if defined(FEAT_XFONTSET) || defined(PROTO)
4798/*
4799 * Set the current text fontset.
4800 */
4801 void
4802gui_mch_set_fontset(GuiFontset fontset)
4803{
4804 gui.current_font = fontset;
4805}
4806#endif
4807
4808/*
4809 * If a font is not going to be used, free its structure.
4810 */
4811 void
4812gui_mch_free_font(GuiFont font)
4813{
4814 if (font != NOFONT)
4815#ifdef HAVE_GTK2
4816 pango_font_description_free(font);
4817#else
4818 gdk_font_unref(font);
4819#endif
4820}
4821
4822#if defined(FEAT_XFONTSET) || defined(PROTO)
4823/*
4824 * If a fontset is not going to be used, free its structure.
4825 */
4826 void
4827gui_mch_free_fontset(GuiFontset fontset)
4828{
4829 if (fontset != NOFONTSET)
4830 gdk_font_unref(fontset);
4831}
4832#endif
4833
4834
4835/*
4836 * Return the Pixel value (color) for the given color name. This routine was
4837 * pretty much taken from example code in the Silicon Graphics OSF/Motif
4838 * Programmer's Guide.
4839 * Return INVALCOLOR for error.
4840 */
4841 guicolor_T
4842gui_mch_get_color(char_u *name)
4843{
4844 /* A number of colors that some X11 systems don't have */
4845 static const char *const vimnames[][2] =
4846 {
4847 {"LightRed", "#FFBBBB"},
4848 {"LightGreen", "#88FF88"},
4849 {"LightMagenta", "#FFBBFF"},
4850 {"DarkCyan", "#008888"},
4851 {"DarkBlue", "#0000BB"},
4852 {"DarkRed", "#BB0000"},
4853 {"DarkMagenta", "#BB00BB"},
4854 {"DarkGrey", "#BBBBBB"},
4855 {"DarkYellow", "#BBBB00"},
4856 {NULL, NULL}
4857 };
4858
4859 if (!gui.in_use) /* can't do this when GUI not running */
4860 return INVALCOLOR;
4861
4862 while (name != NULL)
4863 {
4864 GdkColor color;
4865 int parsed;
4866 int i;
4867
4868 parsed = gdk_color_parse((const char *)name, &color);
4869
4870#ifndef HAVE_GTK2 /* ohh, lovely GTK+ 2, eases our pain :) */
4871 /*
4872 * Since we have already called gtk_set_locale here the bugger
4873 * XParseColor will accept only explicit color names in the language
4874 * of the current locale. However this will interferre with:
4875 * 1. Vim's global startup files
4876 * 2. Explicit color names in .vimrc
4877 *
4878 * Therefore we first try to parse the color in the current locale and
4879 * if it fails, we fall back to the portable "C" one.
4880 */
4881 if (!parsed)
4882 {
4883 char *current;
4884
4885 current = setlocale(LC_ALL, NULL);
4886 if (current != NULL)
4887 {
4888 char *saved;
4889
4890 saved = g_strdup(current);
4891 setlocale(LC_ALL, "C");
4892
4893 parsed = gdk_color_parse((const gchar *)name, &color);
4894
4895 setlocale(LC_ALL, saved);
4896 gtk_set_locale();
4897
4898 g_free(saved);
4899 }
4900 }
4901#endif /* !HAVE_GTK2 */
4902
4903 if (parsed)
4904 {
4905#ifdef HAVE_GTK2
4906 gdk_colormap_alloc_color(gtk_widget_get_colormap(gui.drawarea),
4907 &color, FALSE, TRUE);
4908#else
4909 gdk_color_alloc(gtk_widget_get_colormap(gui.drawarea), &color);
4910#endif
4911 return (guicolor_T)color.pixel;
4912 }
4913 /* add a few builtin names and try again */
4914 for (i = 0; ; ++i)
4915 {
4916 if (vimnames[i][0] == NULL)
4917 {
4918 name = NULL;
4919 break;
4920 }
4921 if (STRICMP(name, vimnames[i][0]) == 0)
4922 {
4923 name = (char_u *)vimnames[i][1];
4924 break;
4925 }
4926 }
4927 }
4928
4929 return INVALCOLOR;
4930}
4931
4932/*
4933 * Set the current text foreground color.
4934 */
4935 void
4936gui_mch_set_fg_color(guicolor_T color)
4937{
4938 gui.fgcolor->pixel = (unsigned long)color;
4939}
4940
4941/*
4942 * Set the current text background color.
4943 */
4944 void
4945gui_mch_set_bg_color(guicolor_T color)
4946{
4947 gui.bgcolor->pixel = (unsigned long)color;
4948}
4949
4950#ifdef HAVE_GTK2
4951/*
4952 * Function-like convenience macro for the sake of efficiency.
4953 */
4954#define INSERT_PANGO_ATTR(Attribute, AttrList, Start, End) \
4955 G_STMT_START{ \
4956 PangoAttribute *tmp_attr_; \
4957 tmp_attr_ = (Attribute); \
4958 tmp_attr_->start_index = (Start); \
4959 tmp_attr_->end_index = (End); \
4960 pango_attr_list_insert((AttrList), tmp_attr_); \
4961 }G_STMT_END
4962
4963 static void
4964apply_wide_font_attr(char_u *s, int len, PangoAttrList *attr_list)
4965{
4966 char_u *start = NULL;
4967 char_u *p;
4968 int uc;
4969
4970 for (p = s; p < s + len; p += utf_byte2len(*p))
4971 {
4972 uc = utf_ptr2char(p);
4973
4974 if (start == NULL)
4975 {
4976 if (uc >= 0x80 && utf_char2cells(uc) == 2)
4977 start = p;
4978 }
4979 else if (uc < 0x80 /* optimization shortcut */
4980 || (utf_char2cells(uc) != 2 && !utf_iscomposing(uc)))
4981 {
4982 INSERT_PANGO_ATTR(pango_attr_font_desc_new(gui.wide_font),
4983 attr_list, start - s, p - s);
4984 start = NULL;
4985 }
4986 }
4987
4988 if (start != NULL)
4989 INSERT_PANGO_ATTR(pango_attr_font_desc_new(gui.wide_font),
4990 attr_list, start - s, len);
4991}
4992
4993 static int
4994count_cluster_cells(char_u *s, PangoItem *item,
4995 PangoGlyphString* glyphs, int i,
4996 int *cluster_width,
4997 int *last_glyph_rbearing)
4998{
4999 char_u *p;
5000 int next; /* glyph start index of next cluster */
5001 int start, end; /* string segment of current cluster */
5002 int width; /* real cluster width in Pango units */
5003 int uc;
5004 int cellcount = 0;
5005
5006 width = glyphs->glyphs[i].geometry.width;
5007
5008 for (next = i + 1; next < glyphs->num_glyphs; ++next)
5009 {
5010 if (glyphs->glyphs[next].attr.is_cluster_start)
5011 break;
5012 else if (glyphs->glyphs[next].geometry.width > width)
5013 width = glyphs->glyphs[next].geometry.width;
5014 }
5015
5016 start = item->offset + glyphs->log_clusters[i];
5017 end = item->offset + ((next < glyphs->num_glyphs) ?
5018 glyphs->log_clusters[next] : item->length);
5019
5020 for (p = s + start; p < s + end; p += utf_byte2len(*p))
5021 {
5022 uc = utf_ptr2char(p);
5023 if (uc < 0x80)
5024 ++cellcount;
5025 else if (!utf_iscomposing(uc))
5026 cellcount += utf_char2cells(uc);
5027 }
5028
5029 if (last_glyph_rbearing != NULL
5030 && cellcount > 0 && next == glyphs->num_glyphs)
5031 {
5032 PangoRectangle ink_rect;
5033 /*
5034 * If a certain combining mark had to be taken from a non-monospace
5035 * font, we have to compensate manually by adapting x_offset according
5036 * to the ink extents of the previous glyph.
5037 */
5038 pango_font_get_glyph_extents(item->analysis.font,
5039 glyphs->glyphs[i].glyph,
5040 &ink_rect, NULL);
5041
5042 if (PANGO_RBEARING(ink_rect) > 0)
5043 *last_glyph_rbearing = PANGO_RBEARING(ink_rect);
5044 }
5045
5046 if (cellcount > 0)
5047 *cluster_width = width;
5048
5049 return cellcount;
5050}
5051
5052/*
5053 * If there are only combining characters in the cluster, we cannot just
5054 * change the width of the previous glyph since there is none. Therefore
5055 * some guesswork is needed.
5056 *
5057 * If ink_rect.x is negative Pango apparently has taken care of the composing
5058 * by itself. Actually setting x_offset = 0 should be sufficient then, but due
5059 * to problems with composing from different fonts we still need to fine-tune
5060 * x_offset to avoid uglyness.
5061 *
5062 * If ink_rect.x is not negative, force overstriking by pointing x_offset to
5063 * the position of the previous glyph. Apparently this happens only with old
5064 * X fonts which don't provide the special combining information needed by
5065 * Pango.
5066 */
5067 static void
5068setup_zero_width_cluster(PangoItem *item, PangoGlyphInfo *glyph,
5069 int last_cellcount, int last_cluster_width,
5070 int last_glyph_rbearing)
5071{
5072 PangoRectangle ink_rect;
5073 PangoRectangle logical_rect;
5074 int width;
5075
5076 width = last_cellcount * gui.char_width * PANGO_SCALE;
5077 glyph->geometry.x_offset = -width + MAX(0, width - last_cluster_width) / 2;
5078 glyph->geometry.width = 0;
5079
5080 pango_font_get_glyph_extents(item->analysis.font,
5081 glyph->glyph,
5082 &ink_rect, &logical_rect);
5083 if (ink_rect.x < 0)
5084 {
5085 glyph->geometry.x_offset += last_glyph_rbearing;
5086 glyph->geometry.y_offset = logical_rect.height
5087 - (gui.char_height - p_linespace) * PANGO_SCALE;
5088 }
5089}
5090
5091 static void
5092draw_glyph_string(int row, int col, int num_cells, int flags,
5093 PangoFont *font, PangoGlyphString *glyphs)
5094{
5095 if (!(flags & DRAW_TRANSP))
5096 {
5097 gdk_gc_set_foreground(gui.text_gc, gui.bgcolor);
5098
5099 gdk_draw_rectangle(gui.drawarea->window,
5100 gui.text_gc,
5101 TRUE,
5102 FILL_X(col),
5103 FILL_Y(row),
5104 num_cells * gui.char_width,
5105 gui.char_height);
5106 }
5107
5108 gdk_gc_set_foreground(gui.text_gc, gui.fgcolor);
5109
5110 gdk_draw_glyphs(gui.drawarea->window,
5111 gui.text_gc,
5112 font,
5113 TEXT_X(col),
5114 TEXT_Y(row),
5115 glyphs);
5116
5117 /* redraw the contents with an offset of 1 to emulate bold */
5118 if ((flags & DRAW_BOLD) && !gui.font_can_bold)
5119 gdk_draw_glyphs(gui.drawarea->window,
5120 gui.text_gc,
5121 font,
5122 TEXT_X(col) + 1,
5123 TEXT_Y(row),
5124 glyphs);
5125}
5126
5127#endif /* HAVE_GTK2 */
5128
5129#if defined(HAVE_GTK2) || defined(PROTO)
5130 int
5131gui_gtk2_draw_string(int row, int col, char_u *s, int len, int flags)
5132{
5133 GdkRectangle area; /* area for clip mask */
5134 PangoGlyphString *glyphs; /* glyphs of current item */
5135 int column_offset = 0; /* column offset in cells */
5136 int i;
5137 char_u *conv_buf = NULL; /* result of UTF-8 conversion */
5138 char_u *new_conv_buf;
5139 int convlen;
5140 char_u *sp, *bp;
5141 int plen;
5142
5143 if (gui.text_context == NULL || gui.drawarea->window == NULL)
5144 return len;
5145
5146 if (output_conv.vc_type != CONV_NONE)
5147 {
5148 /*
5149 * Convert characters from 'encoding' to 'termencoding', which is set
5150 * to UTF-8 by gui_mch_init(). did_set_string_option() in option.c
5151 * prohibits changing this to something else than UTF-8 if the GUI is
5152 * in use.
5153 */
5154 convlen = len;
5155 conv_buf = string_convert(&output_conv, s, &convlen);
5156 g_return_val_if_fail(conv_buf != NULL, len);
5157
5158 /* Correct for differences in char width: some chars are
5159 * double-wide in 'encoding' but single-wide in utf-8. Add a space to
5160 * compensate for that. */
5161 for (sp = s, bp = conv_buf; sp < s + len && bp < conv_buf + convlen; )
5162 {
5163 plen = utf_ptr2len_check(bp);
5164 if ((*mb_ptr2cells)(sp) == 2 && utf_ptr2cells(bp) == 1)
5165 {
5166 new_conv_buf = alloc(convlen + 2);
5167 if (new_conv_buf == NULL)
5168 return len;
5169 plen += bp - conv_buf;
5170 mch_memmove(new_conv_buf, conv_buf, plen);
5171 new_conv_buf[plen] = ' ';
5172 mch_memmove(new_conv_buf + plen + 1, conv_buf + plen,
5173 convlen - plen + 1);
5174 vim_free(conv_buf);
5175 conv_buf = new_conv_buf;
5176 ++convlen;
5177 bp = conv_buf + plen;
5178 plen = 1;
5179 }
5180 sp += (*mb_ptr2len_check)(sp);
5181 bp += plen;
5182 }
5183 s = conv_buf;
5184 len = convlen;
5185 }
5186
5187 /*
5188 * Restrict all drawing to the current screen line in order to prevent
5189 * fuzzy font lookups from messing up the screen.
5190 */
5191 area.x = gui.border_offset;
5192 area.y = FILL_Y(row);
5193 area.width = gui.num_cols * gui.char_width;
5194 area.height = gui.char_height;
5195
5196 gdk_gc_set_clip_origin(gui.text_gc, 0, 0);
5197 gdk_gc_set_clip_rectangle(gui.text_gc, &area);
5198
5199 glyphs = pango_glyph_string_new();
5200
5201 /*
5202 * Optimization hack: If possible, skip the itemize and shaping process
5203 * for pure ASCII strings. This optimization is particularly effective
5204 * because Vim draws space characters to clear parts of the screen.
5205 */
5206 if (!(flags & DRAW_ITALIC)
5207 && !((flags & DRAW_BOLD) && gui.font_can_bold)
5208 && gui.ascii_glyphs != NULL)
5209 {
5210 char_u *p;
5211
5212 for (p = s; p < s + len; ++p)
5213 if (*p & 0x80)
5214 goto not_ascii;
5215
5216 pango_glyph_string_set_size(glyphs, len);
5217
5218 for (i = 0; i < len; ++i)
5219 {
5220 glyphs->glyphs[i] = gui.ascii_glyphs->glyphs[s[i]];
5221 glyphs->log_clusters[i] = i;
5222 }
5223
5224 draw_glyph_string(row, col, len, flags, gui.ascii_font, glyphs);
5225
5226 column_offset = len;
5227 }
5228 else
5229not_ascii:
5230 {
5231 PangoAttrList *attr_list;
5232 GList *item_list;
5233 int cluster_width;
5234 int last_glyph_rbearing;
5235 int cells = 0; /* cells occupied by current cluster */
5236
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005237 /* Safety check: pango crashes when invoked with invalid utf-8
5238 * characters. */
5239 if (!utf_valid_string(s, s + len))
5240 {
5241 column_offset = len;
5242 goto skipitall;
5243 }
5244
Bram Moolenaar071d4272004-06-13 20:20:40 +00005245 /* original width of the current cluster */
5246 cluster_width = PANGO_SCALE * gui.char_width;
5247
5248 /* right bearing of the last non-composing glyph */
5249 last_glyph_rbearing = PANGO_SCALE * gui.char_width;
5250
5251 attr_list = pango_attr_list_new();
5252
5253 /* If 'guifontwide' is set then use that for double-width characters.
5254 * Otherwise just go with 'guifont' and let Pango do its thing. */
5255 if (gui.wide_font != NULL)
5256 apply_wide_font_attr(s, len, attr_list);
5257
5258 if ((flags & DRAW_BOLD) && gui.font_can_bold)
5259 INSERT_PANGO_ATTR(pango_attr_weight_new(PANGO_WEIGHT_BOLD),
5260 attr_list, 0, len);
5261 if (flags & DRAW_ITALIC)
5262 INSERT_PANGO_ATTR(pango_attr_style_new(PANGO_STYLE_ITALIC),
5263 attr_list, 0, len);
5264 /*
5265 * Break the text into segments with consistent directional level
5266 * and shaping engine. Pure Latin text needs only a single segment,
5267 * so there's no need to worry about the loop's efficiency. Better
5268 * try to optimize elsewhere, e.g. reducing exposes and stuff :)
5269 */
5270 item_list = pango_itemize(gui.text_context,
5271 (const char *)s, 0, len, attr_list, NULL);
5272
5273 while (item_list != NULL)
5274 {
5275 PangoItem *item;
5276 int item_cells = 0; /* item length in cells */
5277
5278 item = (PangoItem *)item_list->data;
5279 item_list = g_list_delete_link(item_list, item_list);
5280 /*
5281 * Increment the bidirectional embedding level by 1 if it is not
5282 * even. An odd number means the output will be RTL, but we don't
5283 * want that since Vim handles right-to-left text on its own. It
5284 * would probably be sufficient to just set level = 0, but you can
5285 * never know :)
5286 *
5287 * Unfortunately we can't take advantage of Pango's ability to
5288 * render both LTR and RTL at the same time. In order to support
5289 * that, Vim's main screen engine would have to make use of Pango
5290 * functionality.
5291 */
5292 item->analysis.level = (item->analysis.level + 1) & (~1U);
5293
5294 /* HACK: Overrule the shape engine, we don't want shaping to be
5295 * done, because drawing the cursor would change the display. */
5296 item->analysis.shape_engine = default_shape_engine;
5297
5298 pango_shape((const char *)s + item->offset, item->length,
5299 &item->analysis, glyphs);
5300 /*
5301 * Fixed-width hack: iterate over the array and assign a fixed
5302 * width to each glyph, thus overriding the choice made by the
5303 * shaping engine. We use utf_char2cells() to determine the
5304 * number of cells needed.
5305 *
5306 * Also perform all kind of dark magic to get composing
5307 * characters right (and pretty too of course).
5308 */
5309 for (i = 0; i < glyphs->num_glyphs; ++i)
5310 {
5311 PangoGlyphInfo *glyph;
5312
5313 glyph = &glyphs->glyphs[i];
5314
5315 if (glyph->attr.is_cluster_start)
5316 {
5317 int cellcount;
5318
5319 cellcount = count_cluster_cells(
5320 s, item, glyphs, i, &cluster_width,
5321 (item_list != NULL) ? &last_glyph_rbearing : NULL);
5322
5323 if (cellcount > 0)
5324 {
5325 int width;
5326
5327 width = cellcount * gui.char_width * PANGO_SCALE;
5328 glyph->geometry.x_offset +=
5329 MAX(0, width - cluster_width) / 2;
5330 glyph->geometry.width = width;
5331 }
5332 else
5333 {
5334 /* If there are only combining characters in the
5335 * cluster, we cannot just change the width of the
5336 * previous glyph since there is none. Therefore
5337 * some guesswork is needed. */
5338 setup_zero_width_cluster(item, glyph, cells,
5339 cluster_width,
5340 last_glyph_rbearing);
5341 }
5342
5343 item_cells += cellcount;
5344 cells = cellcount;
5345 }
5346 else if (i > 0)
5347 {
5348 int width;
5349
5350 /* There is a previous glyph, so we deal with combining
5351 * characters the canonical way. That is, setting the
5352 * width of the previous glyph to 0. */
5353 glyphs->glyphs[i - 1].geometry.width = 0;
5354
5355 width = cells * gui.char_width * PANGO_SCALE;
5356 glyph->geometry.x_offset +=
5357 MAX(0, width - cluster_width) / 2;
5358 glyph->geometry.width = width;
5359 }
5360 else /* i == 0 "cannot happen" */
5361 {
5362 glyph->geometry.width = 0;
5363 }
5364 }
5365
5366 /*** Aaaaand action! ***/
5367 draw_glyph_string(row, col + column_offset, item_cells,
5368 flags, item->analysis.font, glyphs);
5369
5370 pango_item_free(item);
5371
5372 column_offset += item_cells;
5373 }
5374
5375 pango_attr_list_unref(attr_list);
5376 }
5377
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005378skipitall:
Bram Moolenaar071d4272004-06-13 20:20:40 +00005379 if (flags & DRAW_UNDERL)
5380 gdk_draw_line(gui.drawarea->window,
5381 gui.text_gc,
5382 FILL_X(col),
5383 FILL_Y(row + 1) - 1,
5384 FILL_X(col + column_offset) - 1,
5385 FILL_Y(row + 1) - 1);
5386
5387 pango_glyph_string_free(glyphs);
5388 vim_free(conv_buf);
5389
5390 gdk_gc_set_clip_rectangle(gui.text_gc, NULL);
5391
5392 return column_offset;
5393}
5394#endif /* HAVE_GTK2 */
5395
5396#if !defined(HAVE_GTK2) || defined(PROTO)
5397 void
5398gui_mch_draw_string(int row, int col, char_u *s, int len, int flags)
5399{
5400 static XChar2b *buf = NULL;
5401 static int buflen = 0;
5402 int is_wide;
5403 XChar2b *text;
5404 int textlen;
5405 XFontStruct *xfont;
5406 char_u *p;
5407# ifdef FEAT_MBYTE
5408 unsigned c;
5409# endif
5410 int width;
5411
5412 if (gui.current_font == NULL || gui.drawarea->window == NULL)
5413 return;
5414
5415 /*
5416 * Yeah yeah apparently the font support in GTK+ 1.2 only cares for either:
5417 * asians or 8-bit fonts. It is broken there, but no wonder the whole font
5418 * stuff is broken in X11 in first place. And the internationalization API
5419 * isn't something you would really like to use.
5420 */
5421
5422 xfont = (XFontStruct *)((GdkFontPrivate*)gui.current_font)->xfont;
5423 is_wide = ((xfont->min_byte1 != 0 || xfont->max_byte1 != 0)
5424# ifdef FEAT_XFONTSET
5425 && gui.fontset == NOFONTSET
5426# endif
5427 );
5428
5429 if (is_wide)
5430 {
5431 /* Convert a byte sequence to 16 bit characters for the Gdk functions.
5432 * Need a buffer for the 16 bit characters. Keep it between calls,
5433 * because allocating it each time is slow. */
5434 if (buflen < len)
5435 {
5436 XtFree((char *)buf);
5437 buf = (XChar2b *)XtMalloc(len * sizeof(XChar2b));
5438 buflen = len;
5439 }
5440
5441 p = s;
5442 textlen = 0;
5443 width = 0;
5444 while (p < s + len)
5445 {
5446# ifdef FEAT_MBYTE
5447 if (enc_utf8)
5448 {
5449 c = utf_ptr2char(p);
5450 if (c >= 0x10000) /* show chars > 0xffff as ? */
5451 c = 0xbf;
5452 buf[textlen].byte1 = c >> 8;
5453 buf[textlen].byte2 = c;
5454 p += utf_ptr2len_check(p);
5455 width += utf_char2cells(c);
5456 }
5457 else
5458# endif
5459 {
5460 buf[textlen].byte1 = '\0'; /* high eight bits */
5461 buf[textlen].byte2 = *p; /* low eight bits */
5462 ++p;
5463 ++width;
5464 }
5465 ++textlen;
5466 }
5467 text = buf;
5468 textlen = textlen * 2;
5469 }
5470 else
5471 {
5472 text = (XChar2b *)s;
5473 textlen = len;
5474# ifdef FEAT_MBYTE
5475 if (has_mbyte)
5476 {
5477 width = 0;
5478 for (p = s; p < s + len; p += (*mb_ptr2len_check)(p))
5479 width += (*mb_ptr2cells)(p);
5480 }
5481 else
5482# endif
5483 width = len;
5484 }
5485
5486 if (!(flags & DRAW_TRANSP))
5487 {
5488 gdk_gc_set_foreground(gui.text_gc, gui.bgcolor);
5489 gdk_draw_rectangle(gui.drawarea->window,
5490 gui.text_gc,
5491 TRUE,
5492 FILL_X(col), FILL_Y(row),
5493 width * gui.char_width, gui.char_height);
5494 }
5495 gdk_gc_set_foreground(gui.text_gc, gui.fgcolor);
5496 gdk_draw_text(gui.drawarea->window,
5497 gui.current_font,
5498 gui.text_gc,
5499 TEXT_X(col), TEXT_Y(row),
5500 (const gchar *)text, textlen);
5501
5502 /* redraw the contents with an offset of 1 to emulate bold */
5503 if (flags & DRAW_BOLD)
5504 gdk_draw_text(gui.drawarea->window,
5505 gui.current_font,
5506 gui.text_gc,
5507 TEXT_X(col) + 1, TEXT_Y(row),
5508 (const gchar *)text, textlen);
5509
5510 if (flags & DRAW_UNDERL)
5511 {
5512 gdk_draw_line(gui.drawarea->window,
5513 gui.text_gc, FILL_X(col),
5514 FILL_Y(row + 1) - 1, FILL_X(col + width) - 1, FILL_Y(row + 1) - 1);
5515 }
5516}
5517#endif /* !HAVE_GTK2 */
5518
5519/*
5520 * Return OK if the key with the termcap name "name" is supported.
5521 */
5522 int
5523gui_mch_haskey(char_u *name)
5524{
5525 int i;
5526
5527 for (i = 0; special_keys[i].key_sym != 0; i++)
5528 if (name[0] == special_keys[i].code0
5529 && name[1] == special_keys[i].code1)
5530 return OK;
5531 return FAIL;
5532}
5533
5534#if defined(FEAT_TITLE) \
5535 || (defined(FEAT_XIM) && !defined(HAVE_GTK2)) \
5536 || defined(PROTO)
5537/*
5538 * Return the text window-id and display. Only required for X-based GUI's
5539 */
5540 int
5541gui_get_x11_windis(Window *win, Display **dis)
5542{
5543 if (gui.mainwin != NULL && gui.mainwin->window != NULL)
5544 {
5545 *dis = GDK_WINDOW_XDISPLAY(gui.mainwin->window);
5546 *win = GDK_WINDOW_XWINDOW(gui.mainwin->window);
5547 return OK;
5548 }
5549
5550 *dis = NULL;
5551 *win = 0;
5552 return FAIL;
5553}
5554#endif
5555
5556#if defined(FEAT_CLIENTSERVER) \
5557 || (defined(FEAT_X11) && defined(FEAT_CLIPBOARD)) || defined(PROTO)
5558
5559 Display *
5560gui_mch_get_display(void)
5561{
5562 if (gui.mainwin != NULL && gui.mainwin->window != NULL)
5563 return GDK_WINDOW_XDISPLAY(gui.mainwin->window);
5564 else
5565 return NULL;
5566}
5567#endif
5568
5569 void
5570gui_mch_beep(void)
5571{
5572#ifdef HAVE_GTK_MULTIHEAD
5573 GdkDisplay *display;
5574
5575 if (gui.mainwin != NULL && GTK_WIDGET_REALIZED(gui.mainwin))
5576 display = gtk_widget_get_display(gui.mainwin);
5577 else
5578 display = gdk_display_get_default();
5579
5580 if (display != NULL)
5581 gdk_display_beep(display);
5582#else
5583 gdk_beep();
5584#endif
5585}
5586
5587 void
5588gui_mch_flash(int msec)
5589{
5590 GdkGCValues values;
5591 GdkGC *invert_gc;
5592
5593 if (gui.drawarea->window == NULL)
5594 return;
5595
5596 values.foreground.pixel = gui.norm_pixel ^ gui.back_pixel;
5597 values.background.pixel = gui.norm_pixel ^ gui.back_pixel;
5598 values.function = GDK_XOR;
5599 invert_gc = gdk_gc_new_with_values(gui.drawarea->window,
5600 &values,
5601 GDK_GC_FOREGROUND |
5602 GDK_GC_BACKGROUND |
5603 GDK_GC_FUNCTION);
5604 gdk_gc_set_exposures(invert_gc,
5605 gui.visibility != GDK_VISIBILITY_UNOBSCURED);
5606 /*
5607 * Do a visual beep by changing back and forth in some undetermined way,
5608 * the foreground and background colors. This is due to the fact that
5609 * there can't be really any prediction about the effects of XOR on
5610 * arbitrary X11 servers. However this seems to be enough for what we
5611 * intend it to do.
5612 */
5613 gdk_draw_rectangle(gui.drawarea->window, invert_gc,
5614 TRUE,
5615 0, 0,
5616 FILL_X((int)Columns) + gui.border_offset,
5617 FILL_Y((int)Rows) + gui.border_offset);
5618
5619 gui_mch_flush();
5620 ui_delay((long)msec, TRUE); /* wait so many msec */
5621
5622 gdk_draw_rectangle(gui.drawarea->window, invert_gc,
5623 TRUE,
5624 0, 0,
5625 FILL_X((int)Columns) + gui.border_offset,
5626 FILL_Y((int)Rows) + gui.border_offset);
5627
5628 gdk_gc_destroy(invert_gc);
5629}
5630
5631/*
5632 * Invert a rectangle from row r, column c, for nr rows and nc columns.
5633 */
5634 void
5635gui_mch_invert_rectangle(int r, int c, int nr, int nc)
5636{
5637 GdkGCValues values;
5638 GdkGC *invert_gc;
5639 GdkColor foreground;
5640 GdkColor background;
5641
5642 if (gui.drawarea->window == NULL)
5643 return;
5644
5645 foreground.pixel = gui.norm_pixel ^ gui.back_pixel;
5646 background.pixel = gui.norm_pixel ^ gui.back_pixel;
5647
5648 values.foreground = foreground;
5649 values.background = background;
5650 values.function = GDK_XOR;
5651 invert_gc = gdk_gc_new_with_values(gui.drawarea->window,
5652 &values,
5653 GDK_GC_FOREGROUND |
5654 GDK_GC_BACKGROUND |
5655 GDK_GC_FUNCTION);
5656 gdk_gc_set_exposures(invert_gc, gui.visibility != GDK_VISIBILITY_UNOBSCURED);
5657 gdk_draw_rectangle(gui.drawarea->window, invert_gc,
5658 TRUE,
5659 FILL_X(c), FILL_Y(r),
5660 (nc) * gui.char_width, (nr) * gui.char_height);
5661 gdk_gc_destroy(invert_gc);
5662}
5663
5664/*
5665 * Iconify the GUI window.
5666 */
5667 void
5668gui_mch_iconify(void)
5669{
5670#ifdef HAVE_GTK2
5671 gtk_window_iconify(GTK_WINDOW(gui.mainwin));
5672#else
5673 XIconifyWindow(GDK_WINDOW_XDISPLAY(gui.mainwin->window),
5674 GDK_WINDOW_XWINDOW(gui.mainwin->window),
5675 DefaultScreen(GDK_WINDOW_XDISPLAY(gui.mainwin->window)));
5676#endif
5677}
5678
5679#if defined(FEAT_EVAL) || defined(PROTO)
5680/*
5681 * Bring the Vim window to the foreground.
5682 */
5683 void
5684gui_mch_set_foreground(void)
5685{
5686# ifdef HAVE_GTK2
5687 gtk_window_present(GTK_WINDOW(gui.mainwin));
5688# else
5689 gdk_window_raise(gui.mainwin->window);
5690# endif
5691}
5692#endif
5693
5694/*
5695 * Draw a cursor without focus.
5696 */
5697 void
5698gui_mch_draw_hollow_cursor(guicolor_T color)
5699{
5700 int i = 1;
5701
5702 if (gui.drawarea->window == NULL)
5703 return;
5704
5705 gui_mch_set_fg_color(color);
5706
5707 gdk_gc_set_foreground(gui.text_gc, gui.fgcolor);
5708#ifdef FEAT_MBYTE
5709 if (mb_lefthalve(gui.row, gui.col))
5710 i = 2;
5711#endif
5712 gdk_draw_rectangle(gui.drawarea->window, gui.text_gc,
5713 FALSE,
5714 FILL_X(gui.col), FILL_Y(gui.row),
5715 i * gui.char_width - 1, gui.char_height - 1);
5716}
5717
5718/*
5719 * Draw part of a cursor, "w" pixels wide, and "h" pixels high, using
5720 * color "color".
5721 */
5722 void
5723gui_mch_draw_part_cursor(int w, int h, guicolor_T color)
5724{
5725 if (gui.drawarea->window == NULL)
5726 return;
5727
5728 gui_mch_set_fg_color(color);
5729
5730 gdk_gc_set_foreground(gui.text_gc, gui.fgcolor);
5731 gdk_draw_rectangle(gui.drawarea->window, gui.text_gc,
5732 TRUE,
5733#ifdef FEAT_RIGHTLEFT
5734 /* vertical line should be on the right of current point */
5735 CURSOR_BAR_RIGHT ? FILL_X(gui.col + 1) - w :
5736#endif
5737 FILL_X(gui.col),
5738 FILL_Y(gui.row) + gui.char_height - h,
5739 w, h);
5740}
5741
5742
5743/*
5744 * Catch up with any queued X11 events. This may put keyboard input into the
5745 * input buffer, call resize call-backs, trigger timers etc. If there is
5746 * nothing in the X11 event queue (& no timers pending), then we return
5747 * immediately.
5748 */
5749 void
5750gui_mch_update(void)
5751{
5752 while (gtk_events_pending() && !vim_is_input_buf_full())
5753 gtk_main_iteration_do(FALSE);
5754}
5755
5756 static gint
5757input_timer_cb(gpointer data)
5758{
5759 int *timed_out = (int *) data;
5760
5761 /* Just inform the caller about the occurence of it */
5762 *timed_out = TRUE;
5763
5764 if (gtk_main_level() > 0)
5765 gtk_main_quit();
5766
5767 return FALSE; /* don't happen again */
5768}
5769
5770#ifdef FEAT_SNIFF
5771/*
5772 * Callback function, used when data is available on the SNiFF connection.
5773 */
5774/* ARGSUSED */
5775 static void
5776sniff_request_cb(
5777 gpointer data,
5778 gint source_fd,
5779 GdkInputCondition condition)
5780{
5781 static char_u bytes[3] = {CSI, (int)KS_EXTRA, (int)KE_SNIFF};
5782
5783 add_to_input_buf(bytes, 3);
5784
5785 if (gtk_main_level() > 0)
5786 gtk_main_quit();
5787}
5788#endif
5789
5790/*
5791 * GUI input routine called by gui_wait_for_chars(). Waits for a character
5792 * from the keyboard.
5793 * wtime == -1 Wait forever.
5794 * wtime == 0 This should never happen.
5795 * wtime > 0 Wait wtime milliseconds for a character.
5796 * Returns OK if a character was found to be available within the given time,
5797 * or FAIL otherwise.
5798 */
5799 int
5800gui_mch_wait_for_chars(long wtime)
5801{
5802 int focus;
5803 guint timer;
5804 static int timed_out;
5805#ifdef FEAT_SNIFF
5806 static int sniff_on = 0;
5807 static gint sniff_input_id = 0;
5808#endif
5809
5810#ifdef FEAT_SNIFF
5811 if (sniff_on && !want_sniff_request)
5812 {
5813 if (sniff_input_id)
5814 gdk_input_remove(sniff_input_id);
5815 sniff_on = 0;
5816 }
5817 else if (!sniff_on && want_sniff_request)
5818 {
5819 /* Add fd_from_sniff to watch for available data in main loop. */
5820 sniff_input_id = gdk_input_add(fd_from_sniff,
5821 GDK_INPUT_READ, sniff_request_cb, NULL);
5822 sniff_on = 1;
5823 }
5824#endif
5825
5826 timed_out = FALSE;
5827
5828 /* this timeout makes sure that we will return if no characters arrived in
5829 * time */
5830
5831 if (wtime > 0)
5832 timer = gtk_timeout_add((guint32)wtime, input_timer_cb, &timed_out);
5833 else
5834 timer = 0;
5835
5836 focus = gui.in_focus;
5837
5838 do
5839 {
5840 /* Stop or start blinking when focus changes */
5841 if (gui.in_focus != focus)
5842 {
5843 if (gui.in_focus)
5844 gui_mch_start_blink();
5845 else
5846 gui_mch_stop_blink();
5847 focus = gui.in_focus;
5848 }
5849
5850 /*
5851 * Loop in GTK+ processing until a timeout or input occurs.
Bram Moolenaard4755bb2004-09-02 19:12:26 +00005852 * Skip this if input is available anyway (can happen in rare
5853 * situations, sort of race condition).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005854 */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00005855 if (!input_available())
5856 gtk_main();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005857
5858 /* Got char, return immediately */
5859 if (input_available())
5860 {
5861 if (timer != 0 && !timed_out)
5862 gtk_timeout_remove(timer);
5863 return OK;
5864 }
5865 } while (wtime < 0 || !timed_out);
5866
5867 /*
5868 * Flush all eventually pending (drawing) events.
5869 */
5870 gui_mch_update();
5871
5872 return FAIL;
5873}
5874
5875
5876/****************************************************************************
5877 * Output drawing routines.
5878 ****************************************************************************/
5879
5880
5881/* Flush any output to the screen */
5882 void
5883gui_mch_flush(void)
5884{
5885#ifdef HAVE_GTK_MULTIHEAD
5886 if (gui.mainwin != NULL && GTK_WIDGET_REALIZED(gui.mainwin))
5887 gdk_display_sync(gtk_widget_get_display(gui.mainwin));
5888#else
5889 gdk_flush(); /* historical misnomer: calls XSync(), not XFlush() */
5890#endif
5891#ifdef HAVE_GTK2
5892 /* This happens to actually do what gui_mch_flush() is supposed to do,
5893 * according to the comment above. */
5894 if (gui.drawarea != NULL && gui.drawarea->window != NULL)
5895 gdk_window_process_updates(gui.drawarea->window, FALSE);
5896#endif
5897}
5898
5899/*
5900 * Clear a rectangular region of the screen from text pos (row1, col1) to
5901 * (row2, col2) inclusive.
5902 */
5903 void
5904gui_mch_clear_block(int row1, int col1, int row2, int col2)
5905{
5906 GdkColor color;
5907
5908 if (gui.drawarea->window == NULL)
5909 return;
5910
5911 color.pixel = gui.back_pixel;
5912
5913 gdk_gc_set_foreground(gui.text_gc, &color);
5914
5915 /* Clear one extra pixel at the far right, for when bold characters have
5916 * spilled over to the window border. */
5917 gdk_draw_rectangle(gui.drawarea->window, gui.text_gc, TRUE,
5918 FILL_X(col1), FILL_Y(row1),
5919 (col2 - col1 + 1) * gui.char_width
5920 + (col2 == Columns - 1),
5921 (row2 - row1 + 1) * gui.char_height);
5922}
5923
5924 void
5925gui_mch_clear_all(void)
5926{
5927 if (gui.drawarea->window != NULL)
5928 gdk_window_clear(gui.drawarea->window);
5929}
5930
5931/*
5932 * Redraw any text revealed by scrolling up/down.
5933 */
5934 static void
5935check_copy_area(void)
5936{
5937 GdkEvent *event;
5938 int expose_count;
5939
5940 if (gui.visibility != GDK_VISIBILITY_PARTIAL)
5941 return;
5942
5943 /* Avoid redrawing the cursor while scrolling or it'll end up where
5944 * we don't want it to be. I'm not sure if it's correct to call
5945 * gui_dont_update_cursor() at this point but it works as a quick
5946 * fix for now. */
5947 gui_dont_update_cursor();
5948
5949 do
5950 {
5951 /* Wait to check whether the scroll worked or not. */
5952 event = gdk_event_get_graphics_expose(gui.drawarea->window);
5953
5954 if (event == NULL)
5955 break; /* received NoExpose event */
5956
5957 gui_redraw(event->expose.area.x, event->expose.area.y,
5958 event->expose.area.width, event->expose.area.height);
5959
5960 expose_count = event->expose.count;
5961 gdk_event_free(event);
5962 }
5963 while (expose_count > 0); /* more events follow */
5964
5965 gui_can_update_cursor();
5966}
5967
5968/*
5969 * Delete the given number of lines from the given row, scrolling up any
5970 * text further down within the scroll region.
5971 */
5972 void
5973gui_mch_delete_lines(int row, int num_lines)
5974{
5975 if (gui.visibility == GDK_VISIBILITY_FULLY_OBSCURED)
5976 return; /* Can't see the window */
5977
5978 gdk_gc_set_foreground(gui.text_gc, gui.fgcolor);
5979 gdk_gc_set_background(gui.text_gc, gui.bgcolor);
5980
5981 /* copy one extra pixel, for when bold has spilled over */
5982 gdk_window_copy_area(gui.drawarea->window, gui.text_gc,
5983 FILL_X(gui.scroll_region_left), FILL_Y(row),
5984 gui.drawarea->window,
5985 FILL_X(gui.scroll_region_left),
5986 FILL_Y(row + num_lines),
5987 gui.char_width * (gui.scroll_region_right
5988 - gui.scroll_region_left + 1) + 1,
5989 gui.char_height * (gui.scroll_region_bot - row - num_lines + 1));
5990
5991 gui_clear_block(gui.scroll_region_bot - num_lines + 1,
5992 gui.scroll_region_left,
5993 gui.scroll_region_bot, gui.scroll_region_right);
5994 check_copy_area();
5995}
5996
5997/*
5998 * Insert the given number of lines before the given row, scrolling down any
5999 * following text within the scroll region.
6000 */
6001 void
6002gui_mch_insert_lines(int row, int num_lines)
6003{
6004 if (gui.visibility == GDK_VISIBILITY_FULLY_OBSCURED)
6005 return; /* Can't see the window */
6006
6007 gdk_gc_set_foreground(gui.text_gc, gui.fgcolor);
6008 gdk_gc_set_background(gui.text_gc, gui.bgcolor);
6009
6010 /* copy one extra pixel, for when bold has spilled over */
6011 gdk_window_copy_area(gui.drawarea->window, gui.text_gc,
6012 FILL_X(gui.scroll_region_left), FILL_Y(row + num_lines),
6013 gui.drawarea->window,
6014 FILL_X(gui.scroll_region_left), FILL_Y(row),
6015 gui.char_width * (gui.scroll_region_right
6016 - gui.scroll_region_left + 1) + 1,
6017 gui.char_height * (gui.scroll_region_bot - row - num_lines + 1));
6018
6019 gui_clear_block(row, gui.scroll_region_left,
6020 row + num_lines - 1, gui.scroll_region_right);
6021 check_copy_area();
6022}
6023
6024/*
6025 * X Selection stuff, for cutting and pasting text to other windows.
6026 */
6027 void
6028clip_mch_request_selection(VimClipboard *cbd)
6029{
6030 GdkAtom target;
6031 unsigned i;
6032 int nbytes;
6033 char_u *buffer;
6034
6035 for (i = 0; i < N_SELECTION_TARGETS; ++i)
6036 {
6037 received_selection = RS_NONE;
6038 target = gdk_atom_intern(selection_targets[i].target, FALSE);
6039
6040 gtk_selection_convert(gui.drawarea,
6041 cbd->gtk_sel_atom, target,
6042 (guint32)GDK_CURRENT_TIME);
6043
6044 while (received_selection == RS_NONE)
6045 gtk_main(); /* wait for selection_received_cb */
6046
6047 if (received_selection != RS_FAIL)
6048 return;
6049 }
6050
6051 /* Final fallback position - use the X CUT_BUFFER0 store */
6052 nbytes = 0;
6053 buffer = (char_u *)XFetchBuffer(GDK_WINDOW_XDISPLAY(gui.mainwin->window),
6054 &nbytes, 0);
6055 if (nbytes > 0)
6056 {
6057 /* Got something */
6058 clip_yank_selection(MCHAR, buffer, (long)nbytes, cbd);
6059 if (p_verbose > 0)
6060 smsg((char_u *)_("Used CUT_BUFFER0 instead of empty selection"));
6061 }
6062 if (buffer != NULL)
6063 XFree(buffer);
6064}
6065
6066/*
6067 * Disown the selection.
6068 */
6069/*ARGSUSED*/
6070 void
6071clip_mch_lose_selection(VimClipboard *cbd)
6072{
6073 /* WEIRD: when using NULL to actually disown the selection, we lose the
6074 * selection the first time we own it. */
6075 /*
6076 gtk_selection_owner_set(NULL, cbd->gtk_sel_atom, (guint32)GDK_CURRENT_TIME);
6077 gui_mch_update();
6078 */
6079}
6080
6081/*
6082 * Own the selection and return OK if it worked.
6083 */
6084 int
6085clip_mch_own_selection(VimClipboard *cbd)
6086{
6087 int success;
6088
6089 success = gtk_selection_owner_set(gui.drawarea, cbd->gtk_sel_atom,
6090 (guint32)GDK_CURRENT_TIME);
6091 gui_mch_update();
6092 return (success) ? OK : FAIL;
6093}
6094
6095/*
6096 * Send the current selection to the clipboard. Do nothing for X because we
6097 * will fill in the selection only when requested by another app.
6098 */
6099/*ARGSUSED*/
6100 void
6101clip_mch_set_selection(VimClipboard *cbd)
6102{
6103}
6104
6105
6106#if defined(FEAT_MENU) || defined(PROTO)
6107/*
6108 * Make a menu item appear either active or not active (grey or not grey).
6109 */
6110 void
6111gui_mch_menu_grey(vimmenu_T *menu, int grey)
6112{
6113 if (menu->id == NULL)
6114 return;
6115
6116 if (menu_is_separator(menu->name))
6117 grey = TRUE;
6118
6119 gui_mch_menu_hidden(menu, FALSE);
6120 /* Be clever about bitfields versus true booleans here! */
6121 if (!GTK_WIDGET_SENSITIVE(menu->id) == !grey)
6122 {
6123 gtk_widget_set_sensitive(menu->id, !grey);
6124 gui_mch_update();
6125 }
6126}
6127
6128/*
6129 * Make menu item hidden or not hidden.
6130 */
6131 void
6132gui_mch_menu_hidden(vimmenu_T *menu, int hidden)
6133{
6134 if (menu->id == 0)
6135 return;
6136
6137 if (hidden)
6138 {
6139 if (GTK_WIDGET_VISIBLE(menu->id))
6140 {
6141 gtk_widget_hide(menu->id);
6142 gui_mch_update();
6143 }
6144 }
6145 else
6146 {
6147 if (!GTK_WIDGET_VISIBLE(menu->id))
6148 {
6149 gtk_widget_show(menu->id);
6150 gui_mch_update();
6151 }
6152 }
6153}
6154
6155/*
6156 * This is called after setting all the menus to grey/hidden or not.
6157 */
6158 void
6159gui_mch_draw_menubar(void)
6160{
6161 /* just make sure that the visual changes get effect immediately */
6162 gui_mch_update();
6163}
6164#endif /* FEAT_MENU */
6165
6166/*
6167 * Scrollbar stuff.
6168 */
6169 void
6170gui_mch_enable_scrollbar(scrollbar_T *sb, int flag)
6171{
6172 if (sb->id == NULL)
6173 return;
6174
6175 if (flag)
6176 gtk_widget_show(sb->id);
6177 else
6178 gtk_widget_hide(sb->id);
6179
6180 update_window_manager_hints();
6181}
6182
6183
6184/*
6185 * Return the RGB value of a pixel as long.
6186 */
6187 long_u
6188gui_mch_get_rgb(guicolor_T pixel)
6189{
6190 GdkColor color;
6191#ifndef HAVE_GTK2
6192 GdkColorContext *cc;
6193
6194 cc = gdk_color_context_new(gtk_widget_get_visual(gui.drawarea),
6195 gtk_widget_get_colormap(gui.drawarea));
6196 color.pixel = pixel;
6197 gdk_color_context_query_color(cc, &color);
6198
6199 gdk_color_context_free(cc);
6200#else
6201 gdk_colormap_query_color(gtk_widget_get_colormap(gui.drawarea),
6202 (unsigned long)pixel, &color);
6203#endif
6204
6205 return (((unsigned)color.red & 0xff00) << 8)
6206 | ((unsigned)color.green & 0xff00)
6207 | (((unsigned)color.blue & 0xff00) >> 8);
6208}
6209
6210/*
6211 * Get current y mouse coordinate in text window.
6212 * Return -1 when unknown.
6213 */
6214 int
6215gui_mch_get_mouse_x(void)
6216{
6217 int win_x;
6218
6219 gdk_window_get_pointer(gui.drawarea->window, &win_x, NULL, NULL);
6220 return win_x;
6221}
6222
6223 int
6224gui_mch_get_mouse_y(void)
6225{
6226 int win_y;
6227
6228 gdk_window_get_pointer(gui.drawarea->window, NULL, &win_y, NULL);
6229 return win_y;
6230}
6231
6232 void
6233gui_mch_setmouse(int x, int y)
6234{
6235 /* Sorry for the Xlib call, but we can't avoid it, since there is no
6236 * internal GDK mechanism present to accomplish this. (and for good
6237 * reason...) */
6238 XWarpPointer(GDK_WINDOW_XDISPLAY(gui.drawarea->window),
6239 (Window)0, GDK_WINDOW_XWINDOW(gui.drawarea->window),
6240 0, 0, 0U, 0U, x, y);
6241}
6242
6243
6244#ifdef FEAT_MOUSESHAPE
6245/* The last set mouse pointer shape is remembered, to be used when it goes
6246 * from hidden to not hidden. */
6247static int last_shape = 0;
6248#endif
6249
6250/*
6251 * Use the blank mouse pointer or not.
6252 *
6253 * hide: TRUE = use blank ptr, FALSE = use parent ptr
6254 */
6255 void
6256gui_mch_mousehide(int hide)
6257{
6258 if (gui.pointer_hidden != hide)
6259 {
6260 gui.pointer_hidden = hide;
6261 if (gui.drawarea->window && gui.blank_pointer != NULL)
6262 {
6263 if (hide)
6264 gdk_window_set_cursor(gui.drawarea->window, gui.blank_pointer);
6265 else
6266#ifdef FEAT_MOUSESHAPE
6267 mch_set_mouse_shape(last_shape);
6268#else
6269 gdk_window_set_cursor(gui.drawarea->window, NULL);
6270#endif
6271 }
6272 }
6273}
6274
6275#if defined(FEAT_MOUSESHAPE) || defined(PROTO)
6276
6277/* Table for shape IDs. Keep in sync with the mshape_names[] table in
6278 * misc2.c! */
6279static const int mshape_ids[] =
6280{
6281 GDK_LEFT_PTR, /* arrow */
6282 GDK_CURSOR_IS_PIXMAP, /* blank */
6283 GDK_XTERM, /* beam */
6284 GDK_SB_V_DOUBLE_ARROW, /* updown */
6285 GDK_SIZING, /* udsizing */
6286 GDK_SB_H_DOUBLE_ARROW, /* leftright */
6287 GDK_SIZING, /* lrsizing */
6288 GDK_WATCH, /* busy */
6289 GDK_X_CURSOR, /* no */
6290 GDK_CROSSHAIR, /* crosshair */
6291 GDK_HAND1, /* hand1 */
6292 GDK_HAND2, /* hand2 */
6293 GDK_PENCIL, /* pencil */
6294 GDK_QUESTION_ARROW, /* question */
6295 GDK_RIGHT_PTR, /* right-arrow */
6296 GDK_CENTER_PTR, /* up-arrow */
6297 GDK_LEFT_PTR /* last one */
6298};
6299
6300 void
6301mch_set_mouse_shape(int shape)
6302{
6303 int id;
6304 GdkCursor *c;
6305
6306 if (gui.drawarea->window == NULL)
6307 return;
6308
6309 if (shape == MSHAPE_HIDE || gui.pointer_hidden)
6310 gdk_window_set_cursor(gui.drawarea->window, gui.blank_pointer);
6311 else
6312 {
6313 if (shape >= MSHAPE_NUMBERED)
6314 {
6315 id = shape - MSHAPE_NUMBERED;
6316 if (id >= GDK_LAST_CURSOR)
6317 id = GDK_LEFT_PTR;
6318 else
6319 id &= ~1; /* they are always even (why?) */
6320 }
6321 else
6322 id = mshape_ids[shape];
6323# ifdef HAVE_GTK_MULTIHEAD
6324 c = gdk_cursor_new_for_display(
6325 gtk_widget_get_display(gui.drawarea), id);
6326# else
6327 c = gdk_cursor_new(id);
6328# endif
6329 gdk_window_set_cursor(gui.drawarea->window, c);
6330 gdk_cursor_destroy(c); /* Unref, actually. Bloody GTK+ 1. */
6331 }
6332 if (shape != MSHAPE_HIDE)
6333 last_shape = shape;
6334}
6335#endif /* FEAT_MOUSESHAPE */
6336
6337
6338#if defined(FEAT_SIGN_ICONS) || defined(PROTO)
6339/*
6340 * Signs are currently always 2 chars wide. With GTK+ 2, the image will be
6341 * scaled down if the current font is not big enough, or scaled up if the image
6342 * size is less than 3/4 of the maximum sign size. With GTK+ 1, the pixmap
6343 * will be cut off if the current font is not big enough, or centered if it's
6344 * too small.
6345 */
6346# define SIGN_WIDTH (2 * gui.char_width)
6347# define SIGN_HEIGHT (gui.char_height)
6348# define SIGN_ASPECT ((double)SIGN_HEIGHT / (double)SIGN_WIDTH)
6349
6350# ifdef HAVE_GTK2
6351
6352 void
6353gui_mch_drawsign(int row, int col, int typenr)
6354{
6355 GdkPixbuf *sign;
6356
6357 sign = (GdkPixbuf *)sign_get_image(typenr);
6358
6359 if (sign != NULL && gui.drawarea != NULL && gui.drawarea->window != NULL)
6360 {
6361 int width;
6362 int height;
6363 int xoffset;
6364 int yoffset;
6365 int need_scale;
6366
6367 width = gdk_pixbuf_get_width(sign);
6368 height = gdk_pixbuf_get_height(sign);
6369 /*
6370 * Decide whether we need to scale. Allow one pixel of border
6371 * width to be cut off, in order to avoid excessive scaling for
6372 * tiny differences in font size.
6373 */
6374 need_scale = (width > SIGN_WIDTH + 2
6375 || height > SIGN_HEIGHT + 2
6376 || (width < 3 * SIGN_WIDTH / 4
6377 && height < 3 * SIGN_HEIGHT / 4));
6378 if (need_scale)
6379 {
6380 double aspect;
6381
6382 /* Keep the original aspect ratio */
6383 aspect = (double)height / (double)width;
6384 width = (double)SIGN_WIDTH * SIGN_ASPECT / aspect;
6385 width = MIN(width, SIGN_WIDTH);
6386 height = (double)width * aspect;
6387
6388 /* This doesn't seem to be worth caching, and doing so
6389 * would complicate the code quite a bit. */
6390 sign = gdk_pixbuf_scale_simple(sign, width, height,
6391 GDK_INTERP_BILINEAR);
6392 if (sign == NULL)
6393 return; /* out of memory */
6394 }
6395
6396 /* The origin is the upper-left corner of the pixmap. Therefore
6397 * these offset may become negative if the pixmap is smaller than
6398 * the 2x1 cells reserved for the sign icon. */
6399 xoffset = (width - SIGN_WIDTH) / 2;
6400 yoffset = (height - SIGN_HEIGHT) / 2;
6401
6402 gdk_gc_set_foreground(gui.text_gc, gui.bgcolor);
6403
6404 gdk_draw_rectangle(gui.drawarea->window,
6405 gui.text_gc,
6406 TRUE,
6407 FILL_X(col),
6408 FILL_Y(row),
6409 SIGN_WIDTH,
6410 SIGN_HEIGHT);
6411
6412# if GTK_CHECK_VERSION(2,1,1)
6413 gdk_draw_pixbuf(gui.drawarea->window,
6414 NULL,
6415 sign,
6416 MAX(0, xoffset),
6417 MAX(0, yoffset),
6418 FILL_X(col) - MIN(0, xoffset),
6419 FILL_Y(row) - MIN(0, yoffset),
6420 MIN(width, SIGN_WIDTH),
6421 MIN(height, SIGN_HEIGHT),
6422 GDK_RGB_DITHER_NORMAL,
6423 0, 0);
6424# else
6425 gdk_pixbuf_render_to_drawable_alpha(sign,
6426 gui.drawarea->window,
6427 MAX(0, xoffset),
6428 MAX(0, yoffset),
6429 FILL_X(col) - MIN(0, xoffset),
6430 FILL_Y(row) - MIN(0, yoffset),
6431 MIN(width, SIGN_WIDTH),
6432 MIN(height, SIGN_HEIGHT),
6433 GDK_PIXBUF_ALPHA_BILEVEL,
6434 127,
6435 GDK_RGB_DITHER_NORMAL,
6436 0, 0);
6437# endif
6438 if (need_scale)
6439 g_object_unref(sign);
6440 }
6441}
6442
6443 void *
6444gui_mch_register_sign(char_u *signfile)
6445{
6446 if (signfile[0] != NUL && signfile[0] != '-' && gui.in_use)
6447 {
6448 GdkPixbuf *sign;
6449 GError *error = NULL;
6450 char_u *message;
6451
6452 sign = gdk_pixbuf_new_from_file((const char *)signfile, &error);
6453
6454 if (error == NULL)
6455 return sign;
6456
6457 message = (char_u *)error->message;
6458
6459 if (message != NULL && input_conv.vc_type != CONV_NONE)
6460 message = string_convert(&input_conv, message, NULL);
6461
6462 if (message != NULL)
6463 {
6464 /* The error message is already translated and will be more
6465 * descriptive than anything we could possibly do ourselves. */
6466 EMSG2("E255: %s", message);
6467
6468 if (input_conv.vc_type != CONV_NONE)
6469 vim_free(message);
6470 }
6471 g_error_free(error);
6472 }
6473
6474 return NULL;
6475}
6476
6477 void
6478gui_mch_destroy_sign(void *sign)
6479{
6480 if (sign != NULL)
6481 g_object_unref(sign);
6482}
6483
6484# else /* !HAVE_GTK2 */
6485
6486typedef struct
6487{
6488 GdkPixmap *pixmap;
6489 GdkBitmap *mask;
6490}
6491signicon_T;
6492
6493 void
6494gui_mch_drawsign(int row, int col, int typenr)
6495{
6496 signicon_T *sign;
6497
6498 sign = (signicon_T *)sign_get_image(typenr);
6499
6500 if (sign != NULL && sign->pixmap != NULL
6501 && gui.drawarea != NULL && gui.drawarea->window != NULL)
6502 {
6503 int width;
6504 int height;
6505 int xoffset;
6506 int yoffset;
6507
6508 gdk_window_get_size(sign->pixmap, &width, &height);
6509
6510 /* The origin is the upper-left corner of the pixmap. Therefore
6511 * these offset may become negative if the pixmap is smaller than
6512 * the 2x1 cells reserved for the sign icon. */
6513 xoffset = (width - SIGN_WIDTH) / 2;
6514 yoffset = (height - SIGN_HEIGHT) / 2;
6515
6516 gdk_gc_set_foreground(gui.text_gc, gui.bgcolor);
6517
6518 gdk_draw_rectangle(gui.drawarea->window,
6519 gui.text_gc,
6520 TRUE,
6521 FILL_X(col),
6522 FILL_Y(row),
6523 SIGN_WIDTH,
6524 SIGN_HEIGHT);
6525
6526 /* Set the clip mask for bilevel transparency */
6527 if (sign->mask != NULL)
6528 {
6529 gdk_gc_set_clip_origin(gui.text_gc,
6530 FILL_X(col) - xoffset,
6531 FILL_Y(row) - yoffset);
6532 gdk_gc_set_clip_mask(gui.text_gc, sign->mask);
6533 }
6534
6535 gdk_draw_pixmap(gui.drawarea->window,
6536 gui.text_gc,
6537 sign->pixmap,
6538 MAX(0, xoffset),
6539 MAX(0, yoffset),
6540 FILL_X(col) - MIN(0, xoffset),
6541 FILL_Y(row) - MIN(0, yoffset),
6542 MIN(width, SIGN_WIDTH),
6543 MIN(height, SIGN_HEIGHT));
6544
6545 gdk_gc_set_clip_mask(gui.text_gc, NULL);
6546 }
6547}
6548
6549 void *
6550gui_mch_register_sign(char_u *signfile)
6551{
6552 signicon_T *sign = NULL;
6553
6554 if (signfile[0] != NUL && signfile[0] != '-'
6555 && gui.drawarea != NULL && gui.drawarea->window != NULL)
6556 {
6557 sign = (signicon_T *)alloc(sizeof(signicon_T));
6558
6559 if (sign != NULL) /* NULL == OOM == "cannot really happen" */
6560 {
6561 sign->mask = NULL;
6562 sign->pixmap = gdk_pixmap_colormap_create_from_xpm(
6563 gui.drawarea->window, NULL,
6564 &sign->mask, NULL,
6565 (const char *)signfile);
6566
6567 if (sign->pixmap == NULL)
6568 {
6569 vim_free(sign);
6570 sign = NULL;
6571 EMSG(_(e_signdata));
6572 }
6573 }
6574 }
6575 return sign;
6576}
6577
6578 void
6579gui_mch_destroy_sign(void *sign)
6580{
6581 if (sign != NULL)
6582 {
6583 signicon_T *signicon = (signicon_T *)sign;
6584
6585 if (signicon->pixmap != NULL)
6586 gdk_pixmap_unref(signicon->pixmap);
6587 if (signicon->mask != NULL)
6588 gdk_bitmap_unref(signicon->mask);
6589
6590 vim_free(signicon);
6591 }
6592}
6593# endif /* !HAVE_GTK2 */
6594
6595#endif /* FEAT_SIGN_ICONS */
6596