Merged from "branches/vim7.1".
[MacVim/jjgod.git] / src / gui_gtk_x11.c
blob523733926acac8c2b85b45ba02ed061b786bc70f
1 /* vi:set ts=8 sts=4 sw=4:
3 * VIM - Vi IMproved by Bram Moolenaar
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 */
11 * Porting to GTK+ was done by:
13 * (C) 1998,1999,2000 by Marcin Dalecki <martin@dalecki.de>
15 * With GREAT support and continuous encouragements by Andy Kahn and of
16 * course Bram Moolenaar!
18 * Support for GTK+ 2 was added by:
20 * (C) 2002,2003 Jason Hildebrand <jason@peaceworks.ca>
21 * Daniel Elstner <daniel.elstner@gmx.net>
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 # ifdef bindtextdomain_codeset
40 # undef bindtextdomain_codeset
41 # endif
42 # if defined(FEAT_GETTEXT) && !defined(ENABLE_NLS)
43 # define ENABLE_NLS /* so the texts in the dialog boxes are translated */
44 # endif
45 # include <gnome.h>
46 # include "version.h"
47 # ifdef HAVE_GTK2
48 /* missing prototype in bonobo-dock-item.h */
49 extern void bonobo_dock_item_set_behavior(BonoboDockItem *dock_item, BonoboDockItemBehavior beh);
50 # endif
51 #endif
53 #if !defined(FEAT_GUI_GTK) && defined(PROTO)
54 /* When generating prototypes we don't want syntax errors. */
55 # define GdkAtom int
56 # define GdkEventExpose int
57 # define GdkEventFocus int
58 # define GdkEventVisibility int
59 # define GdkEventProperty int
60 # define GtkContainer int
61 # define GtkTargetEntry int
62 # define GtkType int
63 # define GtkWidget int
64 # define gint int
65 # define gpointer int
66 # define guint int
67 # define GdkEventKey int
68 # define GdkEventSelection int
69 # define GtkSelectionData int
70 # define GdkEventMotion int
71 # define GdkEventButton int
72 # define GdkDragContext int
73 # define GdkEventConfigure int
74 # define GdkEventClient int
75 #else
76 # include <gdk/gdkkeysyms.h>
77 # include <gdk/gdk.h>
78 # ifdef WIN3264
79 # include <gdk/gdkwin32.h>
80 # else
81 # include <gdk/gdkx.h>
82 # endif
84 # include <gtk/gtk.h>
85 # include "gui_gtk_f.h"
86 #endif
88 #ifdef HAVE_X11_SUNKEYSYM_H
89 # include <X11/Sunkeysym.h>
90 #endif
93 * Easy-to-use macro for multihead support.
95 #ifdef HAVE_GTK_MULTIHEAD
96 # define GET_X_ATOM(atom) gdk_x11_atom_to_xatom_for_display( \
97 gtk_widget_get_display(gui.mainwin), atom)
98 #else
99 # define GET_X_ATOM(atom) ((Atom)(atom))
100 #endif
102 /* Selection type distinguishers */
103 enum
105 TARGET_TYPE_NONE,
106 TARGET_UTF8_STRING,
107 TARGET_STRING,
108 TARGET_COMPOUND_TEXT,
109 TARGET_TEXT,
110 TARGET_TEXT_URI_LIST,
111 TARGET_TEXT_PLAIN,
112 TARGET_VIM,
113 TARGET_VIMENC
117 * Table of selection targets supported by Vim.
118 * Note: Order matters, preferred types should come first.
120 static const GtkTargetEntry selection_targets[] =
122 {VIMENC_ATOM_NAME, 0, TARGET_VIMENC},
123 {VIM_ATOM_NAME, 0, TARGET_VIM},
124 #ifdef FEAT_MBYTE
125 {"UTF8_STRING", 0, TARGET_UTF8_STRING},
126 #endif
127 {"COMPOUND_TEXT", 0, TARGET_COMPOUND_TEXT},
128 {"TEXT", 0, TARGET_TEXT},
129 {"STRING", 0, TARGET_STRING}
131 #define N_SELECTION_TARGETS (sizeof(selection_targets) / sizeof(selection_targets[0]))
133 #ifdef FEAT_DND
135 * Table of DnD targets supported by Vim.
136 * Note: Order matters, preferred types should come first.
138 static const GtkTargetEntry dnd_targets[] =
140 {"text/uri-list", 0, TARGET_TEXT_URI_LIST},
141 # ifdef FEAT_MBYTE
142 {"UTF8_STRING", 0, TARGET_UTF8_STRING},
143 # endif
144 {"STRING", 0, TARGET_STRING},
145 {"text/plain", 0, TARGET_TEXT_PLAIN}
147 # define N_DND_TARGETS (sizeof(dnd_targets) / sizeof(dnd_targets[0]))
148 #endif
151 #ifdef HAVE_GTK2
153 * "Monospace" is a standard font alias that should be present
154 * on all proper Pango/fontconfig installations.
156 # define DEFAULT_FONT "Monospace 10"
158 #else /* !HAVE_GTK2 */
160 * This is the single only fixed width font in X11, which seems to be present
161 * on all servers and available in all the variants we need.
163 # define DEFAULT_FONT "-adobe-courier-medium-r-normal-*-14-*-*-*-m-*-*-*"
165 #endif /* !HAVE_GTK2 */
167 #if !(defined(FEAT_GUI_GNOME) && defined(FEAT_SESSION))
169 * Atoms used to communicate save-yourself from the X11 session manager. There
170 * is no need to move them into the GUI struct, since they should be constant.
172 static GdkAtom wm_protocols_atom = GDK_NONE;
173 static GdkAtom save_yourself_atom = GDK_NONE;
174 #endif
177 * Atoms used to control/reference X11 selections.
179 #ifdef FEAT_MBYTE
180 static GdkAtom utf8_string_atom = GDK_NONE;
181 #endif
182 #ifndef HAVE_GTK2
183 static GdkAtom compound_text_atom = GDK_NONE;
184 static GdkAtom text_atom = GDK_NONE;
185 #endif
186 static GdkAtom vim_atom = GDK_NONE; /* Vim's own special selection format */
187 #ifdef FEAT_MBYTE
188 static GdkAtom vimenc_atom = GDK_NONE; /* Vim's extended selection format */
189 #endif
192 * Keycodes recognized by vim.
193 * NOTE: when changing this, the table in gui_x11.c probably needs the same
194 * change!
196 static struct special_key
198 guint key_sym;
199 char_u code0;
200 char_u code1;
202 const special_keys[] =
204 {GDK_Up, 'k', 'u'},
205 {GDK_Down, 'k', 'd'},
206 {GDK_Left, 'k', 'l'},
207 {GDK_Right, 'k', 'r'},
208 {GDK_F1, 'k', '1'},
209 {GDK_F2, 'k', '2'},
210 {GDK_F3, 'k', '3'},
211 {GDK_F4, 'k', '4'},
212 {GDK_F5, 'k', '5'},
213 {GDK_F6, 'k', '6'},
214 {GDK_F7, 'k', '7'},
215 {GDK_F8, 'k', '8'},
216 {GDK_F9, 'k', '9'},
217 {GDK_F10, 'k', ';'},
218 {GDK_F11, 'F', '1'},
219 {GDK_F12, 'F', '2'},
220 {GDK_F13, 'F', '3'},
221 {GDK_F14, 'F', '4'},
222 {GDK_F15, 'F', '5'},
223 {GDK_F16, 'F', '6'},
224 {GDK_F17, 'F', '7'},
225 {GDK_F18, 'F', '8'},
226 {GDK_F19, 'F', '9'},
227 {GDK_F20, 'F', 'A'},
228 {GDK_F21, 'F', 'B'},
229 {GDK_Pause, 'F', 'B'}, /* Pause == F21 according to netbeans.txt */
230 {GDK_F22, 'F', 'C'},
231 {GDK_F23, 'F', 'D'},
232 {GDK_F24, 'F', 'E'},
233 {GDK_F25, 'F', 'F'},
234 {GDK_F26, 'F', 'G'},
235 {GDK_F27, 'F', 'H'},
236 {GDK_F28, 'F', 'I'},
237 {GDK_F29, 'F', 'J'},
238 {GDK_F30, 'F', 'K'},
239 {GDK_F31, 'F', 'L'},
240 {GDK_F32, 'F', 'M'},
241 {GDK_F33, 'F', 'N'},
242 {GDK_F34, 'F', 'O'},
243 {GDK_F35, 'F', 'P'},
244 #ifdef SunXK_F36
245 {SunXK_F36, 'F', 'Q'},
246 {SunXK_F37, 'F', 'R'},
247 #endif
248 {GDK_Help, '%', '1'},
249 {GDK_Undo, '&', '8'},
250 {GDK_BackSpace, 'k', 'b'},
251 {GDK_Insert, 'k', 'I'},
252 {GDK_Delete, 'k', 'D'},
253 {GDK_3270_BackTab, 'k', 'B'},
254 {GDK_Clear, 'k', 'C'},
255 {GDK_Home, 'k', 'h'},
256 {GDK_End, '@', '7'},
257 {GDK_Prior, 'k', 'P'},
258 {GDK_Next, 'k', 'N'},
259 {GDK_Print, '%', '9'},
260 /* Keypad keys: */
261 {GDK_KP_Left, 'k', 'l'},
262 {GDK_KP_Right, 'k', 'r'},
263 {GDK_KP_Up, 'k', 'u'},
264 {GDK_KP_Down, 'k', 'd'},
265 {GDK_KP_Insert, KS_EXTRA, (char_u)KE_KINS},
266 {GDK_KP_Delete, KS_EXTRA, (char_u)KE_KDEL},
267 {GDK_KP_Home, 'K', '1'},
268 {GDK_KP_End, 'K', '4'},
269 {GDK_KP_Prior, 'K', '3'}, /* page up */
270 {GDK_KP_Next, 'K', '5'}, /* page down */
272 {GDK_KP_Add, 'K', '6'},
273 {GDK_KP_Subtract, 'K', '7'},
274 {GDK_KP_Divide, 'K', '8'},
275 {GDK_KP_Multiply, 'K', '9'},
276 {GDK_KP_Enter, 'K', 'A'},
277 {GDK_KP_Decimal, 'K', 'B'},
279 {GDK_KP_0, 'K', 'C'},
280 {GDK_KP_1, 'K', 'D'},
281 {GDK_KP_2, 'K', 'E'},
282 {GDK_KP_3, 'K', 'F'},
283 {GDK_KP_4, 'K', 'G'},
284 {GDK_KP_5, 'K', 'H'},
285 {GDK_KP_6, 'K', 'I'},
286 {GDK_KP_7, 'K', 'J'},
287 {GDK_KP_8, 'K', 'K'},
288 {GDK_KP_9, 'K', 'L'},
290 /* End of list marker: */
291 {0, 0, 0}
295 * Flags for command line options table below.
297 #define ARG_FONT 1
298 #define ARG_GEOMETRY 2
299 #define ARG_REVERSE 3
300 #define ARG_NOREVERSE 4
301 #define ARG_BACKGROUND 5
302 #define ARG_FOREGROUND 6
303 #define ARG_ICONIC 7
304 #define ARG_ROLE 8
305 #define ARG_NETBEANS 9
306 #define ARG_XRM 10 /* ignored */
307 #define ARG_MENUFONT 11 /* ignored */
308 #define ARG_INDEX_MASK 0x00ff
309 #define ARG_HAS_VALUE 0x0100 /* a value is expected after the argument */
310 #define ARG_NEEDS_GUI 0x0200 /* need to initialize the GUI for this */
311 #define ARG_FOR_GTK 0x0400 /* argument is handled by GTK+ or GNOME */
312 #define ARG_COMPAT_LONG 0x0800 /* accept -foo but substitute with --foo */
313 #define ARG_KEEP 0x1000 /* don't remove argument from argv[] */
316 * This table holds all the X GUI command line options allowed. This includes
317 * the standard ones so that we can skip them when Vim is started without the
318 * GUI (but the GUI might start up later).
320 * When changing this, also update doc/gui_x11.txt and the usage message!!!
322 typedef struct
324 const char *name;
325 unsigned int flags;
327 cmdline_option_T;
329 static const cmdline_option_T cmdline_options[] =
331 /* We handle these options ourselves */
332 {"-fn", ARG_FONT|ARG_HAS_VALUE},
333 {"-font", ARG_FONT|ARG_HAS_VALUE},
334 {"-geom", ARG_GEOMETRY|ARG_HAS_VALUE},
335 {"-geometry", ARG_GEOMETRY|ARG_HAS_VALUE},
336 {"-rv", ARG_REVERSE},
337 {"-reverse", ARG_REVERSE},
338 {"+rv", ARG_NOREVERSE},
339 {"+reverse", ARG_NOREVERSE},
340 {"-bg", ARG_BACKGROUND|ARG_HAS_VALUE},
341 {"-background", ARG_BACKGROUND|ARG_HAS_VALUE},
342 {"-fg", ARG_FOREGROUND|ARG_HAS_VALUE},
343 {"-foreground", ARG_FOREGROUND|ARG_HAS_VALUE},
344 {"-iconic", ARG_ICONIC},
345 #ifdef HAVE_GTK2
346 {"--role", ARG_ROLE|ARG_HAS_VALUE},
347 #endif
348 #ifdef FEAT_NETBEANS_INTG
349 {"-nb", ARG_NETBEANS}, /* non-standard value format */
350 {"-xrm", ARG_XRM|ARG_HAS_VALUE}, /* not implemented */
351 {"-mf", ARG_MENUFONT|ARG_HAS_VALUE}, /* not implemented */
352 {"-menufont", ARG_MENUFONT|ARG_HAS_VALUE}, /* not implemented */
353 #endif
354 #if 0 /* not implemented; these arguments don't make sense for GTK+ */
355 {"-boldfont", ARG_HAS_VALUE},
356 {"-italicfont", ARG_HAS_VALUE},
357 {"-bw", ARG_HAS_VALUE},
358 {"-borderwidth", ARG_HAS_VALUE},
359 {"-sw", ARG_HAS_VALUE},
360 {"-scrollbarwidth", ARG_HAS_VALUE},
361 #endif
362 /* Arguments handled by GTK (and GNOME) internally. */
363 {"--g-fatal-warnings", ARG_FOR_GTK},
364 {"--gdk-debug", ARG_FOR_GTK|ARG_HAS_VALUE},
365 {"--gdk-no-debug", ARG_FOR_GTK|ARG_HAS_VALUE},
366 {"--gtk-debug", ARG_FOR_GTK|ARG_HAS_VALUE},
367 {"--gtk-no-debug", ARG_FOR_GTK|ARG_HAS_VALUE},
368 {"--gtk-module", ARG_FOR_GTK|ARG_HAS_VALUE},
369 {"--sync", ARG_FOR_GTK},
370 {"--display", ARG_FOR_GTK|ARG_HAS_VALUE|ARG_COMPAT_LONG},
371 {"--name", ARG_FOR_GTK|ARG_HAS_VALUE|ARG_COMPAT_LONG},
372 {"--class", ARG_FOR_GTK|ARG_HAS_VALUE|ARG_COMPAT_LONG},
373 #ifdef HAVE_GTK2
374 {"--screen", ARG_FOR_GTK|ARG_HAS_VALUE},
375 {"--gxid-host", ARG_FOR_GTK|ARG_HAS_VALUE},
376 {"--gxid-port", ARG_FOR_GTK|ARG_HAS_VALUE},
377 #else /* these don't seem to exist anymore */
378 {"--no-xshm", ARG_FOR_GTK},
379 {"--xim-preedit", ARG_FOR_GTK|ARG_HAS_VALUE},
380 {"--xim-status", ARG_FOR_GTK|ARG_HAS_VALUE},
381 {"--gxid_host", ARG_FOR_GTK|ARG_HAS_VALUE},
382 {"--gxid_port", ARG_FOR_GTK|ARG_HAS_VALUE},
383 #endif
384 #ifdef FEAT_GUI_GNOME
385 {"--load-modules", ARG_FOR_GTK|ARG_HAS_VALUE},
386 {"--sm-client-id", ARG_FOR_GTK|ARG_HAS_VALUE},
387 {"--sm-config-prefix", ARG_FOR_GTK|ARG_HAS_VALUE},
388 {"--sm-disable", ARG_FOR_GTK},
389 {"--oaf-ior-fd", ARG_FOR_GTK|ARG_HAS_VALUE},
390 {"--oaf-activate-iid", ARG_FOR_GTK|ARG_HAS_VALUE},
391 {"--oaf-private", ARG_FOR_GTK},
392 {"--enable-sound", ARG_FOR_GTK},
393 {"--disable-sound", ARG_FOR_GTK},
394 {"--espeaker", ARG_FOR_GTK|ARG_HAS_VALUE},
395 {"-?", ARG_FOR_GTK|ARG_NEEDS_GUI},
396 {"--help", ARG_FOR_GTK|ARG_NEEDS_GUI|ARG_KEEP},
397 {"--usage", ARG_FOR_GTK|ARG_NEEDS_GUI},
398 # if 0 /* conflicts with Vim's own --version argument */
399 {"--version", ARG_FOR_GTK|ARG_NEEDS_GUI},
400 # endif
401 {"--disable-crash-dialog", ARG_FOR_GTK},
402 #endif
403 {NULL, 0}
406 static int gui_argc = 0;
407 static char **gui_argv = NULL;
409 #ifdef HAVE_GTK2
410 static const char *role_argument = NULL;
411 #endif
412 #if defined(FEAT_GUI_GNOME) && defined(FEAT_SESSION)
413 static const char *restart_command = NULL;
414 #endif
415 static int found_iconic_arg = FALSE;
417 #ifdef FEAT_GUI_GNOME
419 * Can't use Gnome if --socketid given
421 static int using_gnome = 0;
422 #else
423 # define using_gnome 0
424 #endif
427 * Parse the GUI related command-line arguments. Any arguments used are
428 * deleted from argv, and *argc is decremented accordingly. This is called
429 * when vim is started, whether or not the GUI has been started.
431 void
432 gui_mch_prepare(int *argc, char **argv)
434 const cmdline_option_T *option;
435 int i = 0;
436 int len = 0;
438 #if defined(FEAT_GUI_GNOME) && defined(FEAT_SESSION)
440 * Determine the command used to invoke Vim, to be passed as restart
441 * command to the session manager. If argv[0] contains any directory
442 * components try building an absolute path, otherwise leave it as is.
444 restart_command = argv[0];
446 if (strchr(argv[0], G_DIR_SEPARATOR) != NULL)
448 char_u buf[MAXPATHL];
450 if (mch_FullName((char_u *)argv[0], buf, (int)sizeof(buf), TRUE) == OK)
451 /* Tiny leak; doesn't matter, and usually we don't even get here */
452 restart_command = (char *)vim_strsave(buf);
454 #endif
457 * Move all the entries in argv which are relevant to GTK+ and GNOME
458 * into gui_argv. Freed later in gui_mch_init().
460 gui_argc = 0;
461 gui_argv = (char **)alloc((unsigned)((*argc + 1) * sizeof(char *)));
463 g_return_if_fail(gui_argv != NULL);
465 gui_argv[gui_argc++] = argv[i++];
467 while (i < *argc)
469 /* Don't waste CPU cycles on non-option arguments. */
470 if (argv[i][0] != '-' && argv[i][0] != '+')
472 ++i;
473 continue;
476 /* Look for argv[i] in cmdline_options[] table. */
477 for (option = &cmdline_options[0]; option->name != NULL; ++option)
479 len = strlen(option->name);
481 if (strncmp(argv[i], option->name, len) == 0)
483 if (argv[i][len] == '\0')
484 break;
485 /* allow --foo=bar style */
486 if (argv[i][len] == '=' && (option->flags & ARG_HAS_VALUE))
487 break;
488 #ifdef FEAT_NETBEANS_INTG
489 /* darn, -nb has non-standard syntax */
490 if (vim_strchr((char_u *)":=", argv[i][len]) != NULL
491 && (option->flags & ARG_INDEX_MASK) == ARG_NETBEANS)
492 break;
493 #endif
495 else if ((option->flags & ARG_COMPAT_LONG)
496 && strcmp(argv[i], option->name + 1) == 0)
498 /* Replace the standard X arguments "-name" and "-display"
499 * with their GNU-style long option counterparts. */
500 argv[i] = (char *)option->name;
501 break;
504 if (option->name == NULL) /* no match */
506 ++i;
507 continue;
510 if (option->flags & ARG_FOR_GTK)
512 /* Move the argument into gui_argv, which
513 * will later be passed to gtk_init_check() */
514 gui_argv[gui_argc++] = argv[i];
516 else
518 char *value = NULL;
520 /* Extract the option's value if there is one.
521 * Accept both "--foo bar" and "--foo=bar" style. */
522 if (option->flags & ARG_HAS_VALUE)
524 if (argv[i][len] == '=')
525 value = &argv[i][len + 1];
526 else if (i + 1 < *argc && strcmp(argv[i + 1], "--") != 0)
527 value = argv[i + 1];
530 /* Check for options handled by Vim itself */
531 switch (option->flags & ARG_INDEX_MASK)
533 case ARG_REVERSE:
534 found_reverse_arg = TRUE;
535 break;
536 case ARG_NOREVERSE:
537 found_reverse_arg = FALSE;
538 break;
539 case ARG_FONT:
540 font_argument = value;
541 break;
542 case ARG_GEOMETRY:
543 if (value != NULL)
544 gui.geom = vim_strsave((char_u *)value);
545 break;
546 case ARG_BACKGROUND:
547 background_argument = value;
548 break;
549 case ARG_FOREGROUND:
550 foreground_argument = value;
551 break;
552 case ARG_ICONIC:
553 found_iconic_arg = TRUE;
554 break;
555 #ifdef HAVE_GTK2
556 case ARG_ROLE:
557 role_argument = value; /* used later in gui_mch_open() */
558 break;
559 #endif
560 #ifdef FEAT_NETBEANS_INTG
561 case ARG_NETBEANS:
562 ++usingNetbeans;
563 gui.dofork = FALSE; /* don't fork() when starting GUI */
564 netbeansArg = argv[i];
565 break;
566 #endif
567 default:
568 break;
572 /* These arguments make gnome_program_init() print a message and exit.
573 * Must start the GUI for this, otherwise ":gui" will exit later! */
574 if (option->flags & ARG_NEEDS_GUI)
575 gui.starting = TRUE;
577 if (option->flags & ARG_KEEP)
578 ++i;
579 else
581 /* Remove the flag from the argument vector. */
582 if (--*argc > i)
584 int n_strip = 1;
586 /* Move the argument's value as well, if there is one. */
587 if ((option->flags & ARG_HAS_VALUE)
588 && argv[i][len] != '='
589 && strcmp(argv[i + 1], "--") != 0)
591 ++n_strip;
592 --*argc;
593 if (option->flags & ARG_FOR_GTK)
594 gui_argv[gui_argc++] = argv[i + 1];
597 if (*argc > i)
598 mch_memmove(&argv[i], &argv[i + n_strip],
599 (*argc - i) * sizeof(char *));
601 argv[*argc] = NULL;
605 gui_argv[gui_argc] = NULL;
608 #if defined(EXITFREE) || defined(PROTO)
609 void
610 gui_mch_free_all()
612 vim_free(gui_argv);
614 #endif
617 * This should be maybe completely removed.
618 * Doesn't seem possible, since check_copy_area() relies on
619 * this information. --danielk
621 /*ARGSUSED*/
622 static gint
623 visibility_event(GtkWidget *widget, GdkEventVisibility *event, gpointer data)
625 gui.visibility = event->state;
627 * When we do an gdk_window_copy_area(), and the window is partially
628 * obscured, we want to receive an event to tell us whether it worked
629 * or not.
631 if (gui.text_gc != NULL)
632 gdk_gc_set_exposures(gui.text_gc,
633 gui.visibility != GDK_VISIBILITY_UNOBSCURED);
634 return FALSE;
638 * Redraw the corresponding portions of the screen.
640 /*ARGSUSED*/
641 static gint
642 expose_event(GtkWidget *widget, GdkEventExpose *event, gpointer data)
644 /* Skip this when the GUI isn't set up yet, will redraw later. */
645 if (gui.starting)
646 return FALSE;
648 out_flush(); /* make sure all output has been processed */
649 gui_redraw(event->area.x, event->area.y,
650 event->area.width, event->area.height);
652 /* Clear the border areas if needed */
653 if (event->area.x < FILL_X(0))
654 gdk_window_clear_area(gui.drawarea->window, 0, 0, FILL_X(0), 0);
655 if (event->area.y < FILL_Y(0))
656 gdk_window_clear_area(gui.drawarea->window, 0, 0, 0, FILL_Y(0));
657 if (event->area.x > FILL_X(Columns))
658 gdk_window_clear_area(gui.drawarea->window,
659 FILL_X((int)Columns), 0, 0, 0);
660 if (event->area.y > FILL_Y(Rows))
661 gdk_window_clear_area(gui.drawarea->window, 0, FILL_Y((int)Rows), 0, 0);
663 return FALSE;
666 #ifdef FEAT_CLIENTSERVER
668 * Handle changes to the "Comm" property
670 /*ARGSUSED2*/
671 static gint
672 property_event(GtkWidget *widget, GdkEventProperty *event, gpointer data)
674 if (event->type == GDK_PROPERTY_NOTIFY
675 && event->state == (int)GDK_PROPERTY_NEW_VALUE
676 && GDK_WINDOW_XWINDOW(event->window) == commWindow
677 && GET_X_ATOM(event->atom) == commProperty)
679 XEvent xev;
681 /* Translate to XLib */
682 xev.xproperty.type = PropertyNotify;
683 xev.xproperty.atom = commProperty;
684 xev.xproperty.window = commWindow;
685 xev.xproperty.state = PropertyNewValue;
686 serverEventProc(GDK_WINDOW_XDISPLAY(widget->window), &xev);
688 if (gtk_main_level() > 0)
689 gtk_main_quit();
691 return FALSE;
693 #endif
696 /****************************************************************************
697 * Focus handlers:
702 * This is a simple state machine:
703 * BLINK_NONE not blinking at all
704 * BLINK_OFF blinking, cursor is not shown
705 * BLINK_ON blinking, cursor is shown
708 #define BLINK_NONE 0
709 #define BLINK_OFF 1
710 #define BLINK_ON 2
712 static int blink_state = BLINK_NONE;
713 static long_u blink_waittime = 700;
714 static long_u blink_ontime = 400;
715 static long_u blink_offtime = 250;
716 static guint blink_timer = 0;
718 void
719 gui_mch_set_blinking(long waittime, long on, long off)
721 blink_waittime = waittime;
722 blink_ontime = on;
723 blink_offtime = off;
727 * Stop the cursor blinking. Show the cursor if it wasn't shown.
729 void
730 gui_mch_stop_blink(void)
732 if (blink_timer)
734 gtk_timeout_remove(blink_timer);
735 blink_timer = 0;
737 if (blink_state == BLINK_OFF)
738 gui_update_cursor(TRUE, FALSE);
739 blink_state = BLINK_NONE;
742 /*ARGSUSED*/
743 static gint
744 blink_cb(gpointer data)
746 if (blink_state == BLINK_ON)
748 gui_undraw_cursor();
749 blink_state = BLINK_OFF;
750 blink_timer = gtk_timeout_add((guint32)blink_offtime,
751 (GtkFunction) blink_cb, NULL);
753 else
755 gui_update_cursor(TRUE, FALSE);
756 blink_state = BLINK_ON;
757 blink_timer = gtk_timeout_add((guint32)blink_ontime,
758 (GtkFunction) blink_cb, NULL);
761 return FALSE; /* don't happen again */
765 * Start the cursor blinking. If it was already blinking, this restarts the
766 * waiting time and shows the cursor.
768 void
769 gui_mch_start_blink(void)
771 if (blink_timer)
772 gtk_timeout_remove(blink_timer);
773 /* Only switch blinking on if none of the times is zero */
774 if (blink_waittime && blink_ontime && blink_offtime && gui.in_focus)
776 blink_timer = gtk_timeout_add((guint32)blink_waittime,
777 (GtkFunction) blink_cb, NULL);
778 blink_state = BLINK_ON;
779 gui_update_cursor(TRUE, FALSE);
783 /*ARGSUSED*/
784 static gint
785 enter_notify_event(GtkWidget *widget, GdkEventCrossing *event, gpointer data)
787 if (blink_state == BLINK_NONE)
788 gui_mch_start_blink();
790 /* make sure keyboard input goes there */
791 if (gtk_socket_id == 0 || !GTK_WIDGET_HAS_FOCUS(gui.drawarea))
792 gtk_widget_grab_focus(gui.drawarea);
794 return FALSE;
797 /*ARGSUSED*/
798 static gint
799 leave_notify_event(GtkWidget *widget, GdkEventCrossing *event, gpointer data)
801 if (blink_state != BLINK_NONE)
802 gui_mch_stop_blink();
804 return FALSE;
807 /*ARGSUSED*/
808 static gint
809 focus_in_event(GtkWidget *widget, GdkEventFocus *event, gpointer data)
811 gui_focus_change(TRUE);
813 if (blink_state == BLINK_NONE)
814 gui_mch_start_blink();
816 /* make sure keyboard input goes to the draw area (if this is focus for a window) */
817 if (widget != gui.drawarea)
818 gtk_widget_grab_focus(gui.drawarea);
820 return TRUE;
823 /*ARGSUSED*/
824 static gint
825 focus_out_event(GtkWidget *widget, GdkEventFocus *event, gpointer data)
827 gui_focus_change(FALSE);
829 if (blink_state != BLINK_NONE)
830 gui_mch_stop_blink();
832 return TRUE;
836 #ifdef HAVE_GTK2
838 * Translate a GDK key value to UTF-8 independently of the current locale.
839 * The output is written to string, which must have room for at least 6 bytes
840 * plus the NUL terminator. Returns the length in bytes.
842 * This function is used in the GTK+ 2 GUI only. The GTK+ 1 code makes use
843 * of GdkEventKey::string instead. But event->string is evil; see here why:
844 * http://developer.gnome.org/doc/API/2.0/gdk/gdk-Event-Structures.html#GdkEventKey
846 static int
847 keyval_to_string(unsigned int keyval, unsigned int state, char_u *string)
849 int len;
850 guint32 uc;
852 uc = gdk_keyval_to_unicode(keyval);
853 if (uc != 0)
855 /* Check for CTRL-foo */
856 if ((state & GDK_CONTROL_MASK) && uc >= 0x20 && uc < 0x80)
858 /* These mappings look arbitrary at the first glance, but in fact
859 * resemble quite exactly the behaviour of the GTK+ 1.2 GUI on my
860 * machine. The only difference is BS vs. DEL for CTRL-8 (makes
861 * more sense and is consistent with usual terminal behaviour). */
862 if (uc >= '@')
863 string[0] = uc & 0x1F;
864 else if (uc == '2')
865 string[0] = NUL;
866 else if (uc >= '3' && uc <= '7')
867 string[0] = uc ^ 0x28;
868 else if (uc == '8')
869 string[0] = BS;
870 else if (uc == '?')
871 string[0] = DEL;
872 else
873 string[0] = uc;
874 len = 1;
876 else
878 /* Translate a normal key to UTF-8. This doesn't work for dead
879 * keys of course, you _have_ to use an input method for that. */
880 len = utf_char2bytes((int)uc, string);
883 else
885 /* Translate keys which are represented by ASCII control codes in Vim.
886 * There are only a few of those; most control keys are translated to
887 * special terminal-like control sequences. */
888 len = 1;
889 switch (keyval)
891 case GDK_Tab: case GDK_KP_Tab: case GDK_ISO_Left_Tab:
892 string[0] = TAB;
893 break;
894 case GDK_Linefeed:
895 string[0] = NL;
896 break;
897 case GDK_Return: case GDK_ISO_Enter: case GDK_3270_Enter:
898 string[0] = CAR;
899 break;
900 case GDK_Escape:
901 string[0] = ESC;
902 break;
903 default:
904 len = 0;
905 break;
908 string[len] = NUL;
910 return len;
912 #endif /* HAVE_GTK2 */
914 static int
915 modifiers_gdk2vim(guint state)
917 int modifiers = 0;
919 if (state & GDK_SHIFT_MASK)
920 modifiers |= MOD_MASK_SHIFT;
921 if (state & GDK_CONTROL_MASK)
922 modifiers |= MOD_MASK_CTRL;
923 if (state & GDK_MOD1_MASK)
924 modifiers |= MOD_MASK_ALT;
925 if (state & GDK_MOD4_MASK)
926 modifiers |= MOD_MASK_META;
928 return modifiers;
931 static int
932 modifiers_gdk2mouse(guint state)
934 int modifiers = 0;
936 if (state & GDK_SHIFT_MASK)
937 modifiers |= MOUSE_SHIFT;
938 if (state & GDK_CONTROL_MASK)
939 modifiers |= MOUSE_CTRL;
940 if (state & GDK_MOD1_MASK)
941 modifiers |= MOUSE_ALT;
943 return modifiers;
947 * Main keyboard handler:
949 /*ARGSUSED*/
950 static gint
951 key_press_event(GtkWidget *widget, GdkEventKey *event, gpointer data)
953 #ifdef HAVE_GTK2
954 /* 256 bytes is way over the top, but for safety let's reduce it only
955 * for GTK+ 2 where we know for sure how large the string might get.
956 * (That is, up to 6 bytes + NUL + CSI escapes + safety measure.) */
957 char_u string[32], string2[32];
958 #else
959 char_u string[256], string2[256];
960 #endif
961 guint key_sym;
962 int len;
963 int i;
964 int modifiers;
965 int key;
966 guint state;
967 char_u *s, *d;
969 key_sym = event->keyval;
970 state = event->state;
971 #ifndef HAVE_GTK2 /* deprecated */
972 len = event->length;
973 g_assert(len <= sizeof(string));
974 #endif
976 #ifndef HAVE_GTK2
978 * It appears as if we always want to consume a key-press (there currently
979 * aren't any 'return FALSE's), so we always do this: when running in a
980 * GtkPlug and not a window, we must prevent emission of the key_press
981 * EVENT from continuing (which is 'beyond' the level of stopping mere
982 * signals by returning FALSE), otherwise things like tab/cursor-keys are
983 * processed by the GtkPlug default handler, which moves input focus away
984 * from us!
985 * Note: This should no longer be necessary with GTK+ 2.
987 if (gtk_socket_id != 0)
988 gtk_signal_emit_stop_by_name(GTK_OBJECT(widget), "key_press_event");
989 #endif
991 #ifdef FEAT_XIM
992 if (xim_queue_key_press_event(event, TRUE))
993 return TRUE;
994 #endif
996 #ifdef FEAT_HANGULIN
997 if (key_sym == GDK_space && (state & GDK_SHIFT_MASK))
999 hangul_input_state_toggle();
1000 return TRUE;
1002 #endif
1004 #ifdef SunXK_F36
1006 * These keys have bogus lookup strings, and trapping them here is
1007 * easier than trying to XRebindKeysym() on them with every possible
1008 * combination of modifiers.
1010 if (key_sym == SunXK_F36 || key_sym == SunXK_F37)
1011 len = 0;
1012 else
1013 #endif
1015 #ifdef HAVE_GTK2
1016 len = keyval_to_string(key_sym, state, string2);
1018 /* Careful: convert_input() doesn't handle the NUL character.
1019 * No need to convert pure ASCII anyway, thus the len > 1 check. */
1020 if (len > 1 && input_conv.vc_type != CONV_NONE)
1021 len = convert_input(string2, len, sizeof(string2));
1023 s = string2;
1024 #else
1025 # ifdef FEAT_MBYTE
1026 if (input_conv.vc_type != CONV_NONE)
1028 mch_memmove(string2, event->string, len);
1029 len = convert_input(string2, len, sizeof(string2));
1030 s = string2;
1032 else
1033 # endif
1034 s = (char_u *)event->string;
1035 #endif
1037 d = string;
1038 for (i = 0; i < len; ++i)
1040 *d++ = s[i];
1041 if (d[-1] == CSI && d + 2 < string + sizeof(string))
1043 /* Turn CSI into K_CSI. */
1044 *d++ = KS_EXTRA;
1045 *d++ = (int)KE_CSI;
1048 len = d - string;
1051 /* Shift-Tab results in Left_Tab, but we want <S-Tab> */
1052 if (key_sym == GDK_ISO_Left_Tab)
1054 key_sym = GDK_Tab;
1055 state |= GDK_SHIFT_MASK;
1058 #ifndef HAVE_GTK2 /* for GTK+ 2, we handle this in keyval_to_string() */
1059 if ((key_sym == GDK_2 || key_sym == GDK_at) && (state & GDK_CONTROL_MASK))
1061 string[0] = NUL; /* CTRL-2 and CTRL-@ is NUL */
1062 len = 1;
1064 else if (len == 0 && (key_sym == GDK_space || key_sym == GDK_Tab))
1066 /* When there are modifiers, these keys get zero length; we need the
1067 * original key here to be able to add a modifier below. */
1068 string[0] = (key_sym & 0xff);
1069 len = 1;
1071 #endif
1073 #ifdef FEAT_MENU
1074 /* If there is a menu and 'wak' is "yes", or 'wak' is "menu" and the key
1075 * is a menu shortcut, we ignore everything with the ALT modifier. */
1076 if ((state & GDK_MOD1_MASK)
1077 && gui.menu_is_active
1078 && (*p_wak == 'y'
1079 || (*p_wak == 'm'
1080 && len == 1
1081 && gui_is_menu_shortcut(string[0]))))
1082 # ifdef HAVE_GTK2
1083 /* For GTK2 we return false to signify that we haven't handled the
1084 * keypress, so that gtk will handle the mnemonic or accelerator. */
1085 return FALSE;
1086 # else
1087 return TRUE;
1088 # endif
1089 #endif
1091 /* Check for Alt/Meta key (Mod1Mask), but not for a BS, DEL or character
1092 * that already has the 8th bit set.
1093 * Don't do this for <S-M-Tab>, that should become K_S_TAB with ALT.
1094 * Don't do this for double-byte encodings, it turns the char into a lead
1095 * byte. */
1096 if (len == 1
1097 && (state & GDK_MOD1_MASK)
1098 && !(key_sym == GDK_BackSpace || key_sym == GDK_Delete)
1099 && (string[0] & 0x80) == 0
1100 && !(key_sym == GDK_Tab && (state & GDK_SHIFT_MASK))
1101 #ifdef FEAT_MBYTE
1102 && !enc_dbcs
1103 #endif
1106 string[0] |= 0x80;
1107 state &= ~GDK_MOD1_MASK; /* don't use it again */
1108 #ifdef FEAT_MBYTE
1109 if (enc_utf8) /* convert to utf-8 */
1111 string[1] = string[0] & 0xbf;
1112 string[0] = ((unsigned)string[0] >> 6) + 0xc0;
1113 if (string[1] == CSI)
1115 string[2] = KS_EXTRA;
1116 string[3] = (int)KE_CSI;
1117 len = 4;
1119 else
1120 len = 2;
1122 #endif
1125 /* Check for special keys. Also do this when len == 1 (key has an ASCII
1126 * value) to detect backspace, delete and keypad keys. */
1127 if (len == 0 || len == 1)
1129 for (i = 0; special_keys[i].key_sym != 0; i++)
1131 if (special_keys[i].key_sym == key_sym)
1133 string[0] = CSI;
1134 string[1] = special_keys[i].code0;
1135 string[2] = special_keys[i].code1;
1136 len = -3;
1137 break;
1142 if (len == 0) /* Unrecognized key */
1143 return TRUE;
1145 #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK) && !defined(HAVE_GTK2)
1146 /* Cancel or type backspace. For GTK2, im_commit_cb() does the same. */
1147 preedit_start_col = MAXCOL;
1148 xim_changed_while_preediting = TRUE;
1149 #endif
1151 /* Special keys (and a few others) may have modifiers. Also when using a
1152 * double-byte encoding (can't set the 8th bit). */
1153 if (len == -3 || key_sym == GDK_space || key_sym == GDK_Tab
1154 || key_sym == GDK_Return || key_sym == GDK_Linefeed
1155 || key_sym == GDK_Escape || key_sym == GDK_KP_Tab
1156 || key_sym == GDK_ISO_Enter || key_sym == GDK_3270_Enter
1157 #ifdef FEAT_MBYTE
1158 || (enc_dbcs && len == 1 && (state & GDK_MOD1_MASK))
1159 #endif
1162 modifiers = modifiers_gdk2vim(state);
1165 * For some keys a shift modifier is translated into another key
1166 * code.
1168 if (len == -3)
1169 key = TO_SPECIAL(string[1], string[2]);
1170 else
1171 key = string[0];
1173 key = simplify_key(key, &modifiers);
1174 if (key == CSI)
1175 key = K_CSI;
1176 if (IS_SPECIAL(key))
1178 string[0] = CSI;
1179 string[1] = K_SECOND(key);
1180 string[2] = K_THIRD(key);
1181 len = 3;
1183 else
1185 string[0] = key;
1186 len = 1;
1189 if (modifiers != 0)
1191 string2[0] = CSI;
1192 string2[1] = KS_MODIFIER;
1193 string2[2] = modifiers;
1194 add_to_input_buf(string2, 3);
1198 if (len == 1 && ((string[0] == Ctrl_C && ctrl_c_interrupts)
1199 || (string[0] == intr_char && intr_char != Ctrl_C)))
1201 trash_input_buf();
1202 got_int = TRUE;
1205 add_to_input_buf(string, len);
1207 /* blank out the pointer if necessary */
1208 if (p_mh)
1209 gui_mch_mousehide(TRUE);
1211 if (gtk_main_level() > 0)
1212 gtk_main_quit();
1214 return TRUE;
1217 #if defined(FEAT_XIM) && defined(HAVE_GTK2)
1218 /*ARGSUSED0*/
1219 static gboolean
1220 key_release_event(GtkWidget *widget, GdkEventKey *event, gpointer data)
1223 * GTK+ 2 input methods may do fancy stuff on key release events too.
1224 * With the default IM for instance, you can enter any UCS code point
1225 * by holding down CTRL-SHIFT and typing hexadecimal digits.
1227 return xim_queue_key_press_event(event, FALSE);
1229 #endif
1232 /****************************************************************************
1233 * Selection handlers:
1236 /*ARGSUSED*/
1237 static gint
1238 selection_clear_event(GtkWidget *widget,
1239 GdkEventSelection *event,
1240 gpointer user_data)
1242 if (event->selection == clip_plus.gtk_sel_atom)
1243 clip_lose_selection(&clip_plus);
1244 else
1245 clip_lose_selection(&clip_star);
1247 if (gtk_main_level() > 0)
1248 gtk_main_quit();
1250 return TRUE;
1253 #define RS_NONE 0 /* selection_received_cb() not called yet */
1254 #define RS_OK 1 /* selection_received_cb() called and OK */
1255 #define RS_FAIL 2 /* selection_received_cb() called and failed */
1256 static int received_selection = RS_NONE;
1258 /*ARGSUSED*/
1259 static void
1260 selection_received_cb(GtkWidget *widget,
1261 GtkSelectionData *data,
1262 guint time_,
1263 gpointer user_data)
1265 VimClipboard *cbd;
1266 char_u *text;
1267 char_u *tmpbuf = NULL;
1268 #ifdef HAVE_GTK2
1269 guchar *tmpbuf_utf8 = NULL;
1270 #endif
1271 int len;
1272 int motion_type;
1274 if (data->selection == clip_plus.gtk_sel_atom)
1275 cbd = &clip_plus;
1276 else
1277 cbd = &clip_star;
1279 text = (char_u *)data->data;
1280 len = data->length;
1281 motion_type = MCHAR;
1283 if (text == NULL || len <= 0)
1285 received_selection = RS_FAIL;
1286 /* clip_free_selection(cbd); ??? */
1288 if (gtk_main_level() > 0)
1289 gtk_main_quit();
1291 return;
1294 if (data->type == vim_atom)
1296 motion_type = *text++;
1297 --len;
1300 #ifdef FEAT_MBYTE
1301 else if (data->type == vimenc_atom)
1303 char_u *enc;
1304 vimconv_T conv;
1306 motion_type = *text++;
1307 --len;
1309 enc = text;
1310 text += STRLEN(text) + 1;
1311 len -= text - enc;
1313 /* If the encoding of the text is different from 'encoding', attempt
1314 * converting it. */
1315 conv.vc_type = CONV_NONE;
1316 convert_setup(&conv, enc, p_enc);
1317 if (conv.vc_type != CONV_NONE)
1319 tmpbuf = string_convert(&conv, text, &len);
1320 if (tmpbuf != NULL)
1321 text = tmpbuf;
1322 convert_setup(&conv, NULL, NULL);
1325 #endif
1327 #ifdef HAVE_GTK2
1328 /* gtk_selection_data_get_text() handles all the nasty details
1329 * and targets and encodings etc. This rocks so hard. */
1330 else
1332 tmpbuf_utf8 = gtk_selection_data_get_text(data);
1333 if (tmpbuf_utf8 != NULL)
1335 len = STRLEN(tmpbuf_utf8);
1336 if (input_conv.vc_type != CONV_NONE)
1338 tmpbuf = string_convert(&input_conv, tmpbuf_utf8, &len);
1339 if (tmpbuf != NULL)
1340 text = tmpbuf;
1342 else
1343 text = tmpbuf_utf8;
1346 #else /* !HAVE_GTK2 */
1347 # ifdef FEAT_MBYTE
1348 else if (data->type == utf8_string_atom)
1350 vimconv_T conv;
1352 conv.vc_type = CONV_NONE;
1353 convert_setup(&conv, (char_u *)"utf-8", p_enc);
1355 if (conv.vc_type != CONV_NONE)
1357 tmpbuf = string_convert(&conv, text, &len);
1358 convert_setup(&conv, NULL, NULL);
1360 if (tmpbuf != NULL)
1361 text = tmpbuf;
1363 # endif
1364 else if (data->type == compound_text_atom || data->type == text_atom)
1366 char **list = NULL;
1367 int count;
1368 int i;
1369 unsigned tmplen = 0;
1371 count = gdk_text_property_to_text_list(data->type, data->format,
1372 data->data, data->length,
1373 &list);
1374 for (i = 0; i < count; ++i)
1375 tmplen += strlen(list[i]);
1377 tmpbuf = alloc(tmplen + 1);
1378 if (tmpbuf != NULL)
1380 tmpbuf[0] = NUL;
1381 for (i = 0; i < count; ++i)
1382 STRCAT(tmpbuf, list[i]);
1383 text = tmpbuf;
1384 len = tmplen;
1387 if (list != NULL)
1388 gdk_free_text_list(list);
1390 #endif /* !HAVE_GTK2 */
1392 clip_yank_selection(motion_type, text, (long)len, cbd);
1393 received_selection = RS_OK;
1394 vim_free(tmpbuf);
1395 #ifdef HAVE_GTK2
1396 g_free(tmpbuf_utf8);
1397 #endif
1399 if (gtk_main_level() > 0)
1400 gtk_main_quit();
1404 * Prepare our selection data for passing it to the external selection
1405 * client.
1407 /*ARGSUSED*/
1408 static void
1409 selection_get_cb(GtkWidget *widget,
1410 GtkSelectionData *selection_data,
1411 guint info,
1412 guint time_,
1413 gpointer user_data)
1415 char_u *string;
1416 char_u *tmpbuf;
1417 long_u tmplen;
1418 int length;
1419 int motion_type;
1420 GdkAtom type;
1421 VimClipboard *cbd;
1423 if (selection_data->selection == clip_plus.gtk_sel_atom)
1424 cbd = &clip_plus;
1425 else
1426 cbd = &clip_star;
1428 if (!cbd->owned)
1429 return; /* Shouldn't ever happen */
1431 if (info != (guint)TARGET_STRING
1432 #ifdef FEAT_MBYTE
1433 && info != (guint)TARGET_UTF8_STRING
1434 && info != (guint)TARGET_VIMENC
1435 #endif
1436 && info != (guint)TARGET_VIM
1437 && info != (guint)TARGET_COMPOUND_TEXT
1438 && info != (guint)TARGET_TEXT)
1439 return;
1441 /* get the selection from the '*'/'+' register */
1442 clip_get_selection(cbd);
1444 motion_type = clip_convert_selection(&string, &tmplen, cbd);
1445 if (motion_type < 0 || string == NULL)
1446 return;
1447 /* Due to int arguments we can't handle more than G_MAXINT. Also
1448 * reserve one extra byte for NUL or the motion type; just in case.
1449 * (Not that pasting 2G of text is ever going to work, but... ;-) */
1450 length = MIN(tmplen, (long_u)(G_MAXINT - 1));
1452 if (info == (guint)TARGET_VIM)
1454 tmpbuf = alloc((unsigned)length + 1);
1455 if (tmpbuf != NULL)
1457 tmpbuf[0] = motion_type;
1458 mch_memmove(tmpbuf + 1, string, (size_t)length);
1460 /* For our own format, the first byte contains the motion type */
1461 ++length;
1462 vim_free(string);
1463 string = tmpbuf;
1464 type = vim_atom;
1467 #ifdef FEAT_MBYTE
1468 else if (info == (guint)TARGET_VIMENC)
1470 int l = STRLEN(p_enc);
1472 /* contents: motion_type 'encoding' NUL text */
1473 tmpbuf = alloc((unsigned)length + l + 2);
1474 if (tmpbuf != NULL)
1476 tmpbuf[0] = motion_type;
1477 STRCPY(tmpbuf + 1, p_enc);
1478 mch_memmove(tmpbuf + l + 2, string, (size_t)length);
1480 length += l + 2;
1481 vim_free(string);
1482 string = tmpbuf;
1483 type = vimenc_atom;
1485 #endif
1487 #ifdef HAVE_GTK2
1488 /* gtk_selection_data_set_text() handles everything for us. This is
1489 * so easy and simple and cool, it'd be insane not to use it. */
1490 else
1492 if (output_conv.vc_type != CONV_NONE)
1494 tmpbuf = string_convert(&output_conv, string, &length);
1495 vim_free(string);
1496 if (tmpbuf == NULL)
1497 return;
1498 string = tmpbuf;
1500 /* Validate the string to avoid runtime warnings */
1501 if (g_utf8_validate((const char *)string, (gssize)length, NULL))
1503 gtk_selection_data_set_text(selection_data,
1504 (const char *)string, length);
1506 vim_free(string);
1507 return;
1509 #else /* !HAVE_GTK2 */
1510 # ifdef FEAT_MBYTE
1511 else if (info == (guint)TARGET_UTF8_STRING)
1513 vimconv_T conv;
1515 conv.vc_type = CONV_NONE;
1516 convert_setup(&conv, p_enc, (char_u *)"utf-8");
1518 if (conv.vc_type != CONV_NONE)
1520 tmpbuf = string_convert(&conv, string, &length);
1521 convert_setup(&conv, NULL, NULL);
1522 vim_free(string);
1523 string = tmpbuf;
1525 type = utf8_string_atom;
1527 # endif
1528 else if (info == (guint)TARGET_COMPOUND_TEXT
1529 || info == (guint)TARGET_TEXT)
1531 int format;
1533 /* Copy the string to ensure NUL-termination */
1534 tmpbuf = vim_strnsave(string, length);
1535 vim_free(string);
1536 if (tmpbuf != NULL)
1538 gdk_string_to_compound_text((const char *)tmpbuf,
1539 &type, &format, &string, &length);
1540 vim_free(tmpbuf);
1541 selection_data->type = type;
1542 selection_data->format = format;
1543 gtk_selection_data_set(selection_data, type, format, string, length);
1544 gdk_free_compound_text(string);
1546 return;
1548 else
1550 type = GDK_TARGET_STRING;
1552 #endif /* !HAVE_GTK2 */
1554 if (string != NULL)
1556 selection_data->type = selection_data->target;
1557 selection_data->format = 8; /* 8 bits per char */
1559 gtk_selection_data_set(selection_data, type, 8, string, length);
1560 vim_free(string);
1565 * Check if the GUI can be started. Called before gvimrc is sourced.
1566 * Return OK or FAIL.
1569 gui_mch_init_check(void)
1571 #ifndef HAVE_GTK2
1572 /* This is needed to make the locale handling consistent between the GUI
1573 * and the rest of VIM. */
1574 gtk_set_locale();
1575 #endif
1577 #ifdef FEAT_GUI_GNOME
1578 if (gtk_socket_id == 0)
1579 using_gnome = 1;
1580 #endif
1582 /* Don't use gtk_init() or gnome_init(), it exits on failure. */
1583 if (!gtk_init_check(&gui_argc, &gui_argv))
1585 gui.dying = TRUE;
1586 EMSG(_(e_opendisp));
1587 return FAIL;
1590 return OK;
1594 /****************************************************************************
1595 * Mouse handling callbacks
1599 static guint mouse_click_timer = 0;
1600 static int mouse_timed_out = TRUE;
1603 * Timer used to recognize multiple clicks of the mouse button
1605 static gint
1606 mouse_click_timer_cb(gpointer data)
1608 /* we don't use this information currently */
1609 int *timed_out = (int *) data;
1611 *timed_out = TRUE;
1612 return FALSE; /* don't happen again */
1615 static guint motion_repeat_timer = 0;
1616 static int motion_repeat_offset = FALSE;
1617 static gint motion_repeat_timer_cb(gpointer);
1619 static void
1620 process_motion_notify(int x, int y, GdkModifierType state)
1622 int button;
1623 int_u vim_modifiers;
1625 button = (state & (GDK_BUTTON1_MASK | GDK_BUTTON2_MASK |
1626 GDK_BUTTON3_MASK | GDK_BUTTON4_MASK |
1627 GDK_BUTTON5_MASK))
1628 ? MOUSE_DRAG : ' ';
1630 /* If our pointer is currently hidden, then we should show it. */
1631 gui_mch_mousehide(FALSE);
1633 /* Just moving the rodent above the drawing area without any button
1634 * being pressed. */
1635 if (button != MOUSE_DRAG)
1637 gui_mouse_moved(x, y);
1638 return;
1641 /* translate modifier coding between the main engine and GTK */
1642 vim_modifiers = modifiers_gdk2mouse(state);
1644 /* inform the editor engine about the occurrence of this event */
1645 gui_send_mouse_event(button, x, y, FALSE, vim_modifiers);
1647 if (gtk_main_level() > 0)
1648 gtk_main_quit();
1651 * Auto repeat timer handling.
1653 if (x < 0 || y < 0
1654 || x >= gui.drawarea->allocation.width
1655 || y >= gui.drawarea->allocation.height)
1658 int dx;
1659 int dy;
1660 int offshoot;
1661 int delay = 10;
1663 /* Calculate the maximal distance of the cursor from the drawing area.
1664 * (offshoot can't become negative here!).
1666 dx = x < 0 ? -x : x - gui.drawarea->allocation.width;
1667 dy = y < 0 ? -y : y - gui.drawarea->allocation.height;
1669 offshoot = dx > dy ? dx : dy;
1671 /* Make a linearly declaying timer delay with a threshold of 5 at a
1672 * distance of 127 pixels from the main window.
1674 * One could think endlessly about the most ergonomic variant here.
1675 * For example it could make sense to calculate the distance from the
1676 * drags start instead...
1678 * Maybe a parabolic interpolation would suite us better here too...
1680 if (offshoot > 127)
1682 /* 5 appears to be somehow near to my perceptual limits :-). */
1683 delay = 5;
1685 else
1687 delay = (130 * (127 - offshoot)) / 127 + 5;
1690 /* shoot again */
1691 if (!motion_repeat_timer)
1692 motion_repeat_timer = gtk_timeout_add((guint32)delay,
1693 motion_repeat_timer_cb, NULL);
1698 * Timer used to recognize multiple clicks of the mouse button.
1700 /*ARGSUSED0*/
1701 static gint
1702 motion_repeat_timer_cb(gpointer data)
1704 int x;
1705 int y;
1706 GdkModifierType state;
1708 gdk_window_get_pointer(gui.drawarea->window, &x, &y, &state);
1710 if (!(state & (GDK_BUTTON1_MASK | GDK_BUTTON2_MASK |
1711 GDK_BUTTON3_MASK | GDK_BUTTON4_MASK |
1712 GDK_BUTTON5_MASK)))
1714 motion_repeat_timer = 0;
1715 return FALSE;
1718 /* If there already is a mouse click in the input buffer, wait another
1719 * time (otherwise we would create a backlog of clicks) */
1720 if (vim_used_in_input_buf() > 10)
1721 return TRUE;
1723 motion_repeat_timer = 0;
1726 * Fake a motion event.
1727 * Trick: Pretend the mouse moved to the next character on every other
1728 * event, otherwise drag events will be discarded, because they are still
1729 * in the same character.
1731 if (motion_repeat_offset)
1732 x += gui.char_width;
1734 motion_repeat_offset = !motion_repeat_offset;
1735 process_motion_notify(x, y, state);
1737 /* Don't happen again. We will get reinstalled in the synthetic event
1738 * if needed -- thus repeating should still work. */
1739 return FALSE;
1742 /*ARGSUSED2*/
1743 static gint
1744 motion_notify_event(GtkWidget *widget, GdkEventMotion *event, gpointer data)
1746 if (event->is_hint)
1748 int x;
1749 int y;
1750 GdkModifierType state;
1752 gdk_window_get_pointer(widget->window, &x, &y, &state);
1753 process_motion_notify(x, y, state);
1755 else
1757 process_motion_notify((int)event->x, (int)event->y,
1758 (GdkModifierType)event->state);
1761 return TRUE; /* handled */
1766 * Mouse button handling. Note please that we are capturing multiple click's
1767 * by our own timeout mechanism instead of the one provided by GTK+ itself.
1768 * This is due to the way the generic VIM code is recognizing multiple clicks.
1770 /*ARGSUSED2*/
1771 static gint
1772 button_press_event(GtkWidget *widget, GdkEventButton *event, gpointer data)
1774 int button;
1775 int repeated_click = FALSE;
1776 int x, y;
1777 int_u vim_modifiers;
1779 /* Make sure we have focus now we've been selected */
1780 if (gtk_socket_id != 0 && !GTK_WIDGET_HAS_FOCUS(widget))
1781 gtk_widget_grab_focus(widget);
1784 * Don't let additional events about multiple clicks send by GTK to us
1785 * after the initial button press event confuse us.
1787 if (event->type != GDK_BUTTON_PRESS)
1788 return FALSE;
1790 x = event->x;
1791 y = event->y;
1793 /* Handle multiple clicks */
1794 if (!mouse_timed_out && mouse_click_timer)
1796 gtk_timeout_remove(mouse_click_timer);
1797 mouse_click_timer = 0;
1798 repeated_click = TRUE;
1801 mouse_timed_out = FALSE;
1802 mouse_click_timer = gtk_timeout_add((guint32)p_mouset,
1803 mouse_click_timer_cb, &mouse_timed_out);
1805 switch (event->button)
1807 case 1:
1808 button = MOUSE_LEFT;
1809 break;
1810 case 2:
1811 button = MOUSE_MIDDLE;
1812 break;
1813 case 3:
1814 button = MOUSE_RIGHT;
1815 break;
1816 #ifndef HAVE_GTK2
1817 case 4:
1818 button = MOUSE_4;
1819 break;
1820 case 5:
1821 button = MOUSE_5;
1822 break;
1823 #endif
1824 default:
1825 return FALSE; /* Unknown button */
1828 #ifdef FEAT_XIM
1829 /* cancel any preediting */
1830 if (im_is_preediting())
1831 xim_reset();
1832 #endif
1834 vim_modifiers = modifiers_gdk2mouse(event->state);
1836 gui_send_mouse_event(button, x, y, repeated_click, vim_modifiers);
1837 if (gtk_main_level() > 0)
1838 gtk_main_quit(); /* make sure the above will be handled immediately */
1840 return TRUE;
1843 #ifdef HAVE_GTK2
1845 * GTK+ 2 doesn't handle mouse buttons 4, 5, 6 and 7 the same way as GTK+ 1.
1846 * Instead, it abstracts scrolling via the new GdkEventScroll.
1848 /*ARGSUSED2*/
1849 static gboolean
1850 scroll_event(GtkWidget *widget, GdkEventScroll *event, gpointer data)
1852 int button;
1853 int_u vim_modifiers;
1855 if (gtk_socket_id != 0 && !GTK_WIDGET_HAS_FOCUS(widget))
1856 gtk_widget_grab_focus(widget);
1858 switch (event->direction)
1860 case GDK_SCROLL_UP:
1861 button = MOUSE_4;
1862 break;
1863 case GDK_SCROLL_DOWN:
1864 button = MOUSE_5;
1865 break;
1866 default: /* We don't care about left and right... Yet. */
1867 return FALSE;
1870 # ifdef FEAT_XIM
1871 /* cancel any preediting */
1872 if (im_is_preediting())
1873 xim_reset();
1874 # endif
1876 vim_modifiers = modifiers_gdk2mouse(event->state);
1878 gui_send_mouse_event(button, (int)event->x, (int)event->y,
1879 FALSE, vim_modifiers);
1881 if (gtk_main_level() > 0)
1882 gtk_main_quit(); /* make sure the above will be handled immediately */
1884 return TRUE;
1886 #endif /* HAVE_GTK2 */
1889 /*ARGSUSED*/
1890 static gint
1891 button_release_event(GtkWidget *widget, GdkEventButton *event, gpointer data)
1893 int x, y;
1894 int_u vim_modifiers;
1896 /* Remove any motion "machine gun" timers used for automatic further
1897 extension of allocation areas if outside of the applications window
1898 area .*/
1899 if (motion_repeat_timer)
1901 gtk_timeout_remove(motion_repeat_timer);
1902 motion_repeat_timer = 0;
1905 x = event->x;
1906 y = event->y;
1908 vim_modifiers = modifiers_gdk2mouse(event->state);
1910 gui_send_mouse_event(MOUSE_RELEASE, x, y, FALSE, vim_modifiers);
1911 if (gtk_main_level() > 0)
1912 gtk_main_quit(); /* make sure it will be handled immediately */
1914 return TRUE;
1918 #ifdef FEAT_DND
1919 /****************************************************************************
1920 * Drag aNd Drop support handlers.
1924 * Count how many items there may be and separate them with a NUL.
1925 * Apparently the items are separated with \r\n. This is not documented,
1926 * thus be careful not to go past the end. Also allow separation with
1927 * NUL characters.
1929 static int
1930 count_and_decode_uri_list(char_u *out, char_u *raw, int len)
1932 int i;
1933 char_u *p = out;
1934 int count = 0;
1936 for (i = 0; i < len; ++i)
1938 if (raw[i] == NUL || raw[i] == '\n' || raw[i] == '\r')
1940 if (p > out && p[-1] != NUL)
1942 ++count;
1943 *p++ = NUL;
1946 else if (raw[i] == '%' && i + 2 < len && hexhex2nr(raw + i + 1) > 0)
1948 *p++ = hexhex2nr(raw + i + 1);
1949 i += 2;
1951 else
1952 *p++ = raw[i];
1954 if (p > out && p[-1] != NUL)
1956 *p = NUL; /* last item didn't have \r or \n */
1957 ++count;
1959 return count;
1963 * Parse NUL separated "src" strings. Make it an array "outlist" form. On
1964 * this process, URI which protocol is not "file:" are removed. Return
1965 * length of array (less than "max").
1967 static int
1968 filter_uri_list(char_u **outlist, int max, char_u *src)
1970 int i, j;
1972 for (i = j = 0; i < max; ++i)
1974 outlist[i] = NULL;
1975 if (STRNCMP(src, "file:", 5) == 0)
1977 src += 5;
1978 if (STRNCMP(src, "//localhost", 11) == 0)
1979 src += 11;
1980 while (src[0] == '/' && src[1] == '/')
1981 ++src;
1982 outlist[j++] = vim_strsave(src);
1984 src += STRLEN(src) + 1;
1986 return j;
1989 static char_u **
1990 parse_uri_list(int *count, char_u *data, int len)
1992 int n = 0;
1993 char_u *tmp = NULL;
1994 char_u **array = NULL;;
1996 if (data != NULL && len > 0 && (tmp = (char_u *)alloc(len + 1)) != NULL)
1998 n = count_and_decode_uri_list(tmp, data, len);
1999 if (n > 0 && (array = (char_u **)alloc(n * sizeof(char_u *))) != NULL)
2000 n = filter_uri_list(array, n, tmp);
2002 vim_free(tmp);
2003 *count = n;
2004 return array;
2007 static void
2008 drag_handle_uri_list(GdkDragContext *context,
2009 GtkSelectionData *data,
2010 guint time_,
2011 GdkModifierType state,
2012 gint x,
2013 gint y)
2015 char_u **fnames;
2016 int nfiles = 0;
2018 fnames = parse_uri_list(&nfiles, data->data, data->length);
2020 if (fnames != NULL && nfiles > 0)
2022 int_u modifiers;
2024 gtk_drag_finish(context, TRUE, FALSE, time_); /* accept */
2026 modifiers = modifiers_gdk2mouse(state);
2028 gui_handle_drop(x, y, modifiers, fnames, nfiles);
2030 else
2031 vim_free(fnames);
2034 static void
2035 drag_handle_text(GdkDragContext *context,
2036 GtkSelectionData *data,
2037 guint time_,
2038 GdkModifierType state)
2040 char_u dropkey[6] = {CSI, KS_MODIFIER, 0, CSI, KS_EXTRA, (char_u)KE_DROP};
2041 char_u *text;
2042 int len;
2043 # ifdef FEAT_MBYTE
2044 char_u *tmpbuf = NULL;
2045 # endif
2047 text = data->data;
2048 len = data->length;
2050 # ifdef FEAT_MBYTE
2051 if (data->type == utf8_string_atom)
2053 # ifdef HAVE_GTK2
2054 if (input_conv.vc_type != CONV_NONE)
2055 tmpbuf = string_convert(&input_conv, text, &len);
2056 # else
2057 vimconv_T conv;
2059 conv.vc_type = CONV_NONE;
2060 convert_setup(&conv, (char_u *)"utf-8", p_enc);
2062 if (conv.vc_type != CONV_NONE)
2064 tmpbuf = string_convert(&conv, text, &len);
2065 convert_setup(&conv, NULL, NULL);
2067 # endif
2068 if (tmpbuf != NULL)
2069 text = tmpbuf;
2071 # endif /* FEAT_MBYTE */
2073 dnd_yank_drag_data(text, (long)len);
2074 gtk_drag_finish(context, TRUE, FALSE, time_); /* accept */
2075 # ifdef FEAT_MBYTE
2076 vim_free(tmpbuf);
2077 # endif
2079 dropkey[2] = modifiers_gdk2vim(state);
2081 if (dropkey[2] != 0)
2082 add_to_input_buf(dropkey, (int)sizeof(dropkey));
2083 else
2084 add_to_input_buf(dropkey + 3, (int)(sizeof(dropkey) - 3));
2086 if (gtk_main_level() > 0)
2087 gtk_main_quit();
2091 * DND receiver.
2093 /*ARGSUSED2*/
2094 static void
2095 drag_data_received_cb(GtkWidget *widget,
2096 GdkDragContext *context,
2097 gint x,
2098 gint y,
2099 GtkSelectionData *data,
2100 guint info,
2101 guint time_,
2102 gpointer user_data)
2104 GdkModifierType state;
2106 /* Guard against trash */
2107 if (data->data == NULL
2108 || data->length <= 0
2109 || data->format != 8
2110 || data->data[data->length] != '\0')
2112 gtk_drag_finish(context, FALSE, FALSE, time_);
2113 return;
2116 /* Get the current modifier state for proper distinguishment between
2117 * different operations later. */
2118 gdk_window_get_pointer(widget->window, NULL, NULL, &state);
2120 /* Not sure about the role of "text/plain" here... */
2121 if (info == (guint)TARGET_TEXT_URI_LIST)
2122 drag_handle_uri_list(context, data, time_, state, x, y);
2123 else
2124 drag_handle_text(context, data, time_, state);
2127 #endif /* FEAT_DND */
2130 #if defined(FEAT_GUI_GNOME) && defined(FEAT_SESSION)
2132 * GnomeClient interact callback. Check for unsaved buffers that cannot
2133 * be abandoned and pop up a dialog asking the user for confirmation if
2134 * necessary.
2136 /*ARGSUSED0*/
2137 static void
2138 sm_client_check_changed_any(GnomeClient *client,
2139 gint key,
2140 GnomeDialogType type,
2141 gpointer data)
2143 cmdmod_T save_cmdmod;
2144 gboolean shutdown_cancelled;
2146 save_cmdmod = cmdmod;
2148 # ifdef FEAT_BROWSE
2149 cmdmod.browse = TRUE;
2150 # endif
2151 # if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2152 cmdmod.confirm = TRUE;
2153 # endif
2155 * If there are changed buffers, present the user with
2156 * a dialog if possible, otherwise give an error message.
2158 shutdown_cancelled = check_changed_any(FALSE);
2160 exiting = FALSE;
2161 cmdmod = save_cmdmod;
2162 setcursor(); /* position the cursor */
2163 out_flush();
2165 * If the user hit the [Cancel] button the whole shutdown
2166 * will be cancelled. Wow, quite powerful feature (:
2168 gnome_interaction_key_return(key, shutdown_cancelled);
2172 * Generate a script that can be used to restore the current editing session.
2173 * Save the value of v:this_session before running :mksession in order to make
2174 * automagic session save fully transparent. Return TRUE on success.
2176 static int
2177 write_session_file(char_u *filename)
2179 char_u *escaped_filename;
2180 char *mksession_cmdline;
2181 unsigned int save_ssop_flags;
2182 int failed;
2185 * Build an ex command line to create a script that restores the current
2186 * session if executed. Escape the filename to avoid nasty surprises.
2188 escaped_filename = vim_strsave_escaped(filename, escape_chars);
2189 if (escaped_filename == NULL)
2190 return FALSE;
2191 mksession_cmdline = g_strconcat("mksession ", (char *)escaped_filename, NULL);
2192 vim_free(escaped_filename);
2194 * Use a reasonable hardcoded set of 'sessionoptions' flags to avoid
2195 * unpredictable effects when the session is saved automatically. Also,
2196 * we definitely need SSOP_GLOBALS to be able to restore v:this_session.
2197 * Don't use SSOP_BUFFERS to prevent the buffer list from becoming
2198 * enormously large if the GNOME session feature is used regularly.
2200 save_ssop_flags = ssop_flags;
2201 ssop_flags = (SSOP_BLANK|SSOP_CURDIR|SSOP_FOLDS|SSOP_GLOBALS
2202 |SSOP_HELP|SSOP_OPTIONS|SSOP_WINSIZE);
2204 do_cmdline_cmd((char_u *)"let Save_VV_this_session = v:this_session");
2205 failed = (do_cmdline_cmd((char_u *)mksession_cmdline) == FAIL);
2206 do_cmdline_cmd((char_u *)"let v:this_session = Save_VV_this_session");
2207 do_unlet((char_u *)"Save_VV_this_session", TRUE);
2209 ssop_flags = save_ssop_flags;
2210 g_free(mksession_cmdline);
2212 * Reopen the file and append a command to restore v:this_session,
2213 * as if this save never happened. This is to avoid conflicts with
2214 * the user's own sessions. FIXME: It's probably less hackish to add
2215 * a "stealth" flag to 'sessionoptions' -- gotta ask Bram.
2217 if (!failed)
2219 FILE *fd;
2221 fd = open_exfile(filename, TRUE, APPENDBIN);
2223 failed = (fd == NULL
2224 || put_line(fd, "let v:this_session = Save_VV_this_session") == FAIL
2225 || put_line(fd, "unlet Save_VV_this_session") == FAIL);
2227 if (fd != NULL && fclose(fd) != 0)
2228 failed = TRUE;
2230 if (failed)
2231 mch_remove(filename);
2234 return !failed;
2238 * "save_yourself" signal handler. Initiate an interaction to ask the user
2239 * for confirmation if necessary. Save the current editing session and tell
2240 * the session manager how to restart Vim.
2242 /*ARGSUSED1*/
2243 static gboolean
2244 sm_client_save_yourself(GnomeClient *client,
2245 gint phase,
2246 GnomeSaveStyle save_style,
2247 gboolean shutdown,
2248 GnomeInteractStyle interact_style,
2249 gboolean fast,
2250 gpointer data)
2252 static const char suffix[] = "-session.vim";
2253 char *session_file;
2254 unsigned int len;
2255 gboolean success;
2257 /* Always request an interaction if possible. check_changed_any()
2258 * won't actually show a dialog unless any buffers have been modified.
2259 * There doesn't seem to be an obvious way to check that without
2260 * automatically firing the dialog. Anyway, it works just fine. */
2261 if (interact_style == GNOME_INTERACT_ANY)
2262 gnome_client_request_interaction(client, GNOME_DIALOG_NORMAL,
2263 &sm_client_check_changed_any,
2264 NULL);
2265 out_flush();
2266 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
2268 /* The path is unique for each session save. We do neither know nor care
2269 * which session script will actually be used later. This decision is in
2270 * the domain of the session manager. */
2271 session_file = gnome_config_get_real_path(
2272 gnome_client_get_config_prefix(client));
2273 len = strlen(session_file);
2275 if (len > 0 && session_file[len-1] == G_DIR_SEPARATOR)
2276 --len; /* get rid of the superfluous trailing '/' */
2278 session_file = g_renew(char, session_file, len + sizeof(suffix));
2279 memcpy(session_file + len, suffix, sizeof(suffix));
2281 success = write_session_file((char_u *)session_file);
2283 if (success)
2285 const char *argv[8];
2286 int i;
2288 /* Tell the session manager how to wipe out the stored session data.
2289 * This isn't as dangerous as it looks, don't worry :) session_file
2290 * is a unique absolute filename. Usually it'll be something like
2291 * `/home/user/.gnome2/vim-XXXXXX-session.vim'. */
2292 i = 0;
2293 argv[i++] = "rm";
2294 argv[i++] = session_file;
2295 argv[i] = NULL;
2297 gnome_client_set_discard_command(client, i, (char **)argv);
2299 /* Tell the session manager how to restore the just saved session.
2300 * This is easily done thanks to Vim's -S option. Pass the -f flag
2301 * since there's no need to fork -- it might even cause confusion.
2302 * Also pass the window role to give the WM something to match on.
2303 * The role is set in gui_mch_open(), thus should _never_ be NULL. */
2304 i = 0;
2305 argv[i++] = restart_command;
2306 argv[i++] = "-f";
2307 argv[i++] = "-g";
2308 # ifdef HAVE_GTK2
2309 argv[i++] = "--role";
2310 argv[i++] = gtk_window_get_role(GTK_WINDOW(gui.mainwin));
2311 # endif
2312 argv[i++] = "-S";
2313 argv[i++] = session_file;
2314 argv[i] = NULL;
2316 gnome_client_set_restart_command(client, i, (char **)argv);
2317 gnome_client_set_clone_command(client, 0, NULL);
2320 g_free(session_file);
2322 return success;
2326 * Called when the session manager wants us to die. There isn't much to save
2327 * here since "save_yourself" has been emitted before (unless serious trouble
2328 * is happening).
2330 /*ARGSUSED0*/
2331 static void
2332 sm_client_die(GnomeClient *client, gpointer data)
2334 /* Don't write messages to the GUI anymore */
2335 full_screen = FALSE;
2337 vim_strncpy(IObuff,
2338 _("Vim: Received \"die\" request from session manager\n"),
2339 IOSIZE - 1);
2340 preserve_exit();
2344 * Connect our signal handlers to be notified on session save and shutdown.
2346 static void
2347 setup_save_yourself(void)
2349 GnomeClient *client;
2351 client = gnome_master_client();
2353 if (client != NULL)
2355 /* Must use the deprecated gtk_signal_connect() for compatibility
2356 * with GNOME 1. Arrgh, zombies! */
2357 gtk_signal_connect(GTK_OBJECT(client), "save_yourself",
2358 GTK_SIGNAL_FUNC(&sm_client_save_yourself), NULL);
2359 gtk_signal_connect(GTK_OBJECT(client), "die",
2360 GTK_SIGNAL_FUNC(&sm_client_die), NULL);
2364 #else /* !(FEAT_GUI_GNOME && FEAT_SESSION) */
2366 # ifdef USE_XSMP
2368 * GTK tells us that XSMP needs attention
2370 /*ARGSUSED*/
2371 static gboolean
2372 local_xsmp_handle_requests(source, condition, data)
2373 GIOChannel *source;
2374 GIOCondition condition;
2375 gpointer data;
2377 if (condition == G_IO_IN)
2379 /* Do stuff; maybe close connection */
2380 if (xsmp_handle_requests() == FAIL)
2381 g_io_channel_unref((GIOChannel *)data);
2382 return TRUE;
2384 /* Error */
2385 g_io_channel_unref((GIOChannel *)data);
2386 xsmp_close();
2387 return TRUE;
2389 # endif /* USE_XSMP */
2392 * Setup the WM_PROTOCOLS to indicate we want the WM_SAVE_YOURSELF event.
2393 * This is an ugly use of X functions. GTK doesn't offer an alternative.
2395 static void
2396 setup_save_yourself(void)
2398 Atom *existing_atoms = NULL;
2399 int count = 0;
2401 #ifdef USE_XSMP
2402 if (xsmp_icefd != -1)
2405 * Use XSMP is preference to legacy WM_SAVE_YOURSELF;
2406 * set up GTK IO monitor
2408 GIOChannel *g_io = g_io_channel_unix_new(xsmp_icefd);
2410 g_io_add_watch(g_io, G_IO_IN | G_IO_ERR | G_IO_HUP,
2411 local_xsmp_handle_requests, (gpointer)g_io);
2413 else
2414 #endif
2416 /* Fall back to old method */
2418 /* first get the existing value */
2419 if (XGetWMProtocols(GDK_WINDOW_XDISPLAY(gui.mainwin->window),
2420 GDK_WINDOW_XWINDOW(gui.mainwin->window),
2421 &existing_atoms, &count))
2423 Atom *new_atoms;
2424 Atom save_yourself_xatom;
2425 int i;
2427 save_yourself_xatom = GET_X_ATOM(save_yourself_atom);
2429 /* check if WM_SAVE_YOURSELF isn't there yet */
2430 for (i = 0; i < count; ++i)
2431 if (existing_atoms[i] == save_yourself_xatom)
2432 break;
2434 if (i == count)
2436 /* allocate an Atoms array which is one item longer */
2437 new_atoms = (Atom *)alloc((unsigned)((count + 1)
2438 * sizeof(Atom)));
2439 if (new_atoms != NULL)
2441 memcpy(new_atoms, existing_atoms, count * sizeof(Atom));
2442 new_atoms[count] = save_yourself_xatom;
2443 XSetWMProtocols(GDK_WINDOW_XDISPLAY(gui.mainwin->window),
2444 GDK_WINDOW_XWINDOW(gui.mainwin->window),
2445 new_atoms, count + 1);
2446 vim_free(new_atoms);
2449 XFree(existing_atoms);
2454 # ifdef HAVE_GTK2
2456 * Installing a global event filter seems to be the only way to catch
2457 * client messages of type WM_PROTOCOLS without overriding GDK's own
2458 * client message event filter. Well, that's still better than trying
2459 * to guess what the GDK filter had done if it had been invoked instead
2460 * (This is what we did for GTK+ 1.2, see below).
2462 * GTK2_FIXME: This doesn't seem to work. For some reason we never
2463 * receive WM_SAVE_YOURSELF even though everything is set up correctly.
2464 * I have the nasty feeling modern session managers just don't send this
2465 * deprecated message anymore. Addition: confirmed by several people.
2467 * The GNOME session support is much cooler anyway. Unlike this ugly
2468 * WM_SAVE_YOURSELF hack it actually stores the session... And yes,
2469 * it should work with KDE as well.
2471 /*ARGSUSED1*/
2472 static GdkFilterReturn
2473 global_event_filter(GdkXEvent *xev, GdkEvent *event, gpointer data)
2475 XEvent *xevent = (XEvent *)xev;
2477 if (xevent != NULL
2478 && xevent->type == ClientMessage
2479 && xevent->xclient.message_type == GET_X_ATOM(wm_protocols_atom)
2480 && xevent->xclient.data.l[0] == GET_X_ATOM(save_yourself_atom))
2482 out_flush();
2483 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
2485 * Set the window's WM_COMMAND property, to let the window manager
2486 * know we are done saving ourselves. We don't want to be
2487 * restarted, thus set argv to NULL.
2489 XSetCommand(GDK_WINDOW_XDISPLAY(gui.mainwin->window),
2490 GDK_WINDOW_XWINDOW(gui.mainwin->window),
2491 NULL, 0);
2492 return GDK_FILTER_REMOVE;
2495 return GDK_FILTER_CONTINUE;
2498 # else /* !HAVE_GTK2 */
2501 * GDK handler for X ClientMessage events.
2503 /*ARGSUSED2*/
2504 static GdkFilterReturn
2505 gdk_wm_protocols_filter(GdkXEvent *xev, GdkEvent *event, gpointer data)
2507 /* From example in gdkevents.c/gdk_wm_protocols_filter */
2508 XEvent *xevent = (XEvent *)xev;
2510 if (xevent != NULL)
2512 if (xevent->xclient.data.l[0] == GET_X_ATOM(save_yourself_atom))
2514 out_flush();
2515 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
2517 /* Set the window's WM_COMMAND property, to let the window manager
2518 * know we are done saving ourselves. We don't want to be
2519 * restarted, thus set argv to NULL. */
2520 XSetCommand(GDK_WINDOW_XDISPLAY(gui.mainwin->window),
2521 GDK_WINDOW_XWINDOW(gui.mainwin->window),
2522 NULL, 0);
2525 * Functionality from gdkevents.c/gdk_wm_protocols_filter;
2526 * Registering this filter apparently overrides the default GDK one,
2527 * so we need to perform its functionality. There seems no way to
2528 * register for WM_PROTOCOLS, and only process the WM_SAVE_YOURSELF
2529 * bit; it's all or nothing. Update: No, there is a way -- but it
2530 * only works with GTK+ 2 apparently. See above.
2532 else if (xevent->xclient.data.l[0] == GET_X_ATOM(gdk_wm_delete_window))
2534 event->any.type = GDK_DELETE;
2535 return GDK_FILTER_TRANSLATE;
2539 return GDK_FILTER_REMOVE;
2541 # endif /* !HAVE_GTK2 */
2543 #endif /* !(FEAT_GUI_GNOME && FEAT_SESSION) */
2547 * Setup the window icon & xcmdsrv comm after the main window has been realized.
2549 /*ARGSUSED*/
2550 static void
2551 mainwin_realize(GtkWidget *widget, gpointer data)
2553 /* If you get an error message here, you still need to unpack the runtime
2554 * archive! */
2555 #ifdef magick
2556 # undef magick
2557 #endif
2558 #ifdef HAVE_GTK2
2559 /* A bit hackish, but avoids casting later and allows optimization */
2560 # define static static const
2561 #endif
2562 #define magick vim32x32
2563 #include "../runtime/vim32x32.xpm"
2564 #undef magick
2565 #define magick vim16x16
2566 #include "../runtime/vim16x16.xpm"
2567 #undef magick
2568 #define magick vim48x48
2569 #include "../runtime/vim48x48.xpm"
2570 #undef magick
2571 #ifdef HAVE_GTK2
2572 # undef static
2573 #endif
2575 /* When started with "--echo-wid" argument, write window ID on stdout. */
2576 if (echo_wid_arg)
2578 printf("WID: %ld\n", (long)GDK_WINDOW_XWINDOW(gui.mainwin->window));
2579 fflush(stdout);
2582 if (vim_strchr(p_go, GO_ICON) != NULL)
2585 * Add an icon to the main window. For fun and convenience of the user.
2587 #ifdef HAVE_GTK2
2588 GList *icons = NULL;
2590 icons = g_list_prepend(icons, gdk_pixbuf_new_from_xpm_data(vim16x16));
2591 icons = g_list_prepend(icons, gdk_pixbuf_new_from_xpm_data(vim32x32));
2592 icons = g_list_prepend(icons, gdk_pixbuf_new_from_xpm_data(vim48x48));
2594 gtk_window_set_icon_list(GTK_WINDOW(gui.mainwin), icons);
2596 g_list_foreach(icons, (GFunc)&g_object_unref, NULL);
2597 g_list_free(icons);
2599 #else /* !HAVE_GTK2 */
2601 GdkPixmap *icon;
2602 GdkBitmap *icon_mask = NULL;
2603 char **magick = vim32x32;
2604 Display *xdisplay;
2605 Window root_window;
2606 XIconSize *size;
2607 int number_sizes;
2609 * Adjust the icon to the preferences of the actual window manager.
2610 * This is once again a workaround for a deficiency in GTK+ 1.2.
2612 xdisplay = GDK_WINDOW_XDISPLAY(gui.mainwin->window);
2613 root_window = XRootWindow(xdisplay, DefaultScreen(xdisplay));
2614 if (XGetIconSizes(xdisplay, root_window, &size, &number_sizes))
2616 if (number_sizes > 0)
2618 if (size->max_height >= 48 && size->max_height >= 48)
2619 magick = vim48x48;
2620 else if (size->max_height >= 32 && size->max_height >= 32)
2621 magick = vim32x32;
2622 else if (size->max_height >= 16 && size->max_height >= 16)
2623 magick = vim16x16;
2625 XFree(size);
2627 icon = gdk_pixmap_create_from_xpm_d(gui.mainwin->window,
2628 &icon_mask, NULL, magick);
2629 if (icon != NULL)
2630 /* Note: for some reason gdk_window_set_icon() doesn't acquire
2631 * a reference on the pixmap, thus we _have_ to leak it. */
2632 gdk_window_set_icon(gui.mainwin->window, NULL, icon, icon_mask);
2634 #endif /* !HAVE_GTK2 */
2637 #if !(defined(FEAT_GUI_GNOME) && defined(FEAT_SESSION))
2638 /* Register a handler for WM_SAVE_YOURSELF with GDK's low-level X I/F */
2639 # ifdef HAVE_GTK2
2640 gdk_window_add_filter(NULL, &global_event_filter, NULL);
2641 # else
2642 gdk_add_client_message_filter(wm_protocols_atom,
2643 &gdk_wm_protocols_filter, NULL);
2644 # endif
2645 #endif
2646 /* Setup to indicate to the window manager that we want to catch the
2647 * WM_SAVE_YOURSELF event. For GNOME, this connects to the session
2648 * manager instead. */
2649 #if defined(FEAT_GUI_GNOME) && defined(FEAT_SESSION)
2650 if (using_gnome)
2651 #endif
2652 setup_save_yourself();
2654 #ifdef FEAT_CLIENTSERVER
2655 if (serverName == NULL && serverDelayedStartName != NULL)
2657 /* This is a :gui command in a plain vim with no previous server */
2658 commWindow = GDK_WINDOW_XWINDOW(gui.mainwin->window);
2660 (void)serverRegisterName(GDK_WINDOW_XDISPLAY(gui.mainwin->window),
2661 serverDelayedStartName);
2663 else
2666 * Cannot handle "XLib-only" windows with gtk event routines, we'll
2667 * have to change the "server" registration to that of the main window
2668 * If we have not registered a name yet, remember the window
2670 serverChangeRegisteredWindow(GDK_WINDOW_XDISPLAY(gui.mainwin->window),
2671 GDK_WINDOW_XWINDOW(gui.mainwin->window));
2673 gtk_widget_add_events(gui.mainwin, GDK_PROPERTY_CHANGE_MASK);
2674 gtk_signal_connect(GTK_OBJECT(gui.mainwin), "property_notify_event",
2675 GTK_SIGNAL_FUNC(property_event), NULL);
2676 #endif
2679 static GdkCursor *
2680 create_blank_pointer(void)
2682 GdkWindow *root_window = NULL;
2683 GdkPixmap *blank_mask;
2684 GdkCursor *cursor;
2685 GdkColor color = { 0, 0, 0, 0 };
2686 char blank_data[] = { 0x0 };
2688 #ifdef HAVE_GTK_MULTIHEAD
2689 root_window = gtk_widget_get_root_window(gui.mainwin);
2690 #endif
2692 /* Create a pseudo blank pointer, which is in fact one pixel by one pixel
2693 * in size. */
2694 blank_mask = gdk_bitmap_create_from_data(root_window, blank_data, 1, 1);
2695 cursor = gdk_cursor_new_from_pixmap(blank_mask, blank_mask,
2696 &color, &color, 0, 0);
2697 gdk_bitmap_unref(blank_mask);
2699 return cursor;
2702 #ifdef HAVE_GTK_MULTIHEAD
2703 /*ARGSUSED1*/
2704 static void
2705 mainwin_screen_changed_cb(GtkWidget *widget,
2706 GdkScreen *previous_screen,
2707 gpointer data)
2709 if (!gtk_widget_has_screen(widget))
2710 return;
2713 * Recreate the invisible mouse cursor.
2715 if (gui.blank_pointer != NULL)
2716 gdk_cursor_unref(gui.blank_pointer);
2718 gui.blank_pointer = create_blank_pointer();
2720 if (gui.pointer_hidden && gui.drawarea->window != NULL)
2721 gdk_window_set_cursor(gui.drawarea->window, gui.blank_pointer);
2724 * Create a new PangoContext for this screen, and initialize it
2725 * with the current font if necessary.
2727 if (gui.text_context != NULL)
2728 g_object_unref(gui.text_context);
2730 gui.text_context = gtk_widget_create_pango_context(widget);
2731 pango_context_set_base_dir(gui.text_context, PANGO_DIRECTION_LTR);
2733 if (gui.norm_font != NULL)
2735 gui_mch_init_font(p_guifont, FALSE);
2736 gui_set_shellsize(FALSE, FALSE, RESIZE_BOTH);
2739 #endif /* HAVE_GTK_MULTIHEAD */
2742 * After the drawing area comes up, we calculate all colors and create the
2743 * dummy blank cursor.
2745 * Don't try to set any VIM scrollbar sizes anywhere here. I'm relying on the
2746 * fact that the main VIM engine doesn't take them into account anywhere.
2748 /*ARGSUSED1*/
2749 static void
2750 drawarea_realize_cb(GtkWidget *widget, gpointer data)
2752 GtkWidget *sbar;
2754 #ifdef FEAT_XIM
2755 xim_init();
2756 #endif
2757 gui_mch_new_colors();
2758 gui.text_gc = gdk_gc_new(gui.drawarea->window);
2760 gui.blank_pointer = create_blank_pointer();
2761 if (gui.pointer_hidden)
2762 gdk_window_set_cursor(widget->window, gui.blank_pointer);
2764 /* get the actual size of the scrollbars, if they are realized */
2765 sbar = firstwin->w_scrollbars[SBAR_LEFT].id;
2766 if (!sbar || (!gui.which_scrollbars[SBAR_LEFT]
2767 && firstwin->w_scrollbars[SBAR_RIGHT].id))
2768 sbar = firstwin->w_scrollbars[SBAR_RIGHT].id;
2769 if (sbar && GTK_WIDGET_REALIZED(sbar) && sbar->allocation.width)
2770 gui.scrollbar_width = sbar->allocation.width;
2772 sbar = gui.bottom_sbar.id;
2773 if (sbar && GTK_WIDGET_REALIZED(sbar) && sbar->allocation.height)
2774 gui.scrollbar_height = sbar->allocation.height;
2778 * Properly clean up on shutdown.
2780 /*ARGSUSED0*/
2781 static void
2782 drawarea_unrealize_cb(GtkWidget *widget, gpointer data)
2784 /* Don't write messages to the GUI anymore */
2785 full_screen = FALSE;
2787 #ifdef FEAT_XIM
2788 im_shutdown();
2789 #endif
2790 #ifdef HAVE_GTK2
2791 if (gui.ascii_glyphs != NULL)
2793 pango_glyph_string_free(gui.ascii_glyphs);
2794 gui.ascii_glyphs = NULL;
2796 if (gui.ascii_font != NULL)
2798 g_object_unref(gui.ascii_font);
2799 gui.ascii_font = NULL;
2801 g_object_unref(gui.text_context);
2802 gui.text_context = NULL;
2804 g_object_unref(gui.text_gc);
2805 gui.text_gc = NULL;
2807 gdk_cursor_unref(gui.blank_pointer);
2808 gui.blank_pointer = NULL;
2809 #else
2810 gdk_gc_unref(gui.text_gc);
2811 gui.text_gc = NULL;
2813 gdk_cursor_destroy(gui.blank_pointer);
2814 gui.blank_pointer = NULL;
2815 #endif
2818 /*ARGSUSED0*/
2819 static void
2820 drawarea_style_set_cb(GtkWidget *widget,
2821 GtkStyle *previous_style,
2822 gpointer data)
2824 gui_mch_new_colors();
2828 * Callback routine for the "delete_event" signal on the toplevel window.
2829 * Tries to vim gracefully, or refuses to exit with changed buffers.
2831 /*ARGSUSED*/
2832 static gint
2833 delete_event_cb(GtkWidget *widget, GdkEventAny *event, gpointer data)
2835 gui_shell_closed();
2836 return TRUE;
2839 #if defined(FEAT_MENU) || defined(FEAT_TOOLBAR) || defined(FEAT_GUI_TABLINE)
2840 static int
2841 get_item_dimensions(GtkWidget *widget, GtkOrientation orientation)
2843 GtkOrientation item_orientation = GTK_ORIENTATION_HORIZONTAL;
2845 #ifdef FEAT_GUI_GNOME
2846 if (using_gnome && widget != NULL)
2848 # ifdef HAVE_GTK2
2849 GtkWidget *parent;
2850 BonoboDockItem *dockitem;
2852 parent = gtk_widget_get_parent(widget);
2853 if (G_TYPE_FROM_INSTANCE(parent) == BONOBO_TYPE_DOCK_ITEM)
2855 /* Only menu & toolbar are dock items. Could tabline be?
2856 * Seem to be only the 2 defined in GNOME */
2857 widget = parent;
2858 dockitem = BONOBO_DOCK_ITEM(widget);
2860 if (dockitem == NULL || dockitem->is_floating)
2861 return 0;
2862 item_orientation = bonobo_dock_item_get_orientation(dockitem);
2864 # else
2865 GnomeDockItem *dockitem;
2867 widget = widget->parent;
2868 dockitem = GNOME_DOCK_ITEM(widget);
2870 if (dockitem == NULL || dockitem->is_floating)
2871 return 0;
2872 item_orientation = gnome_dock_item_get_orientation(dockitem);
2873 # endif
2875 #endif
2876 if (widget != NULL
2877 && item_orientation == orientation
2878 && GTK_WIDGET_REALIZED(widget)
2879 && GTK_WIDGET_VISIBLE(widget))
2881 if (orientation == GTK_ORIENTATION_HORIZONTAL)
2882 return widget->allocation.height;
2883 else
2884 return widget->allocation.width;
2886 return 0;
2888 #endif
2890 static int
2891 get_menu_tool_width(void)
2893 int width = 0;
2895 #ifdef FEAT_GUI_GNOME /* these are never vertical without GNOME */
2896 # ifdef FEAT_MENU
2897 width += get_item_dimensions(gui.menubar, GTK_ORIENTATION_VERTICAL);
2898 # endif
2899 # ifdef FEAT_TOOLBAR
2900 width += get_item_dimensions(gui.toolbar, GTK_ORIENTATION_VERTICAL);
2901 # endif
2902 # ifdef FEAT_GUI_TABLINE
2903 if (gui.tabline != NULL)
2904 width += get_item_dimensions(gui.tabline, GTK_ORIENTATION_VERTICAL);
2905 # endif
2906 #endif
2908 return width;
2911 static int
2912 get_menu_tool_height(void)
2914 int height = 0;
2916 #ifdef FEAT_MENU
2917 height += get_item_dimensions(gui.menubar, GTK_ORIENTATION_HORIZONTAL);
2918 #endif
2919 #ifdef FEAT_TOOLBAR
2920 height += get_item_dimensions(gui.toolbar, GTK_ORIENTATION_HORIZONTAL);
2921 #endif
2922 #ifdef FEAT_GUI_TABLINE
2923 if (gui.tabline != NULL)
2924 height += get_item_dimensions(gui.tabline, GTK_ORIENTATION_HORIZONTAL);
2925 #endif
2927 return height;
2930 /* This controls whether we can set the real window hints at
2931 * start-up when in a GtkPlug.
2932 * 0 = normal processing (default)
2933 * 1 = init. hints set, no-one's tried to reset since last check
2934 * 2 = init. hints set, attempt made to change hints
2936 static int init_window_hints_state = 0;
2938 static void
2939 update_window_manager_hints(int force_width, int force_height)
2941 static int old_width = 0;
2942 static int old_height = 0;
2943 static int old_min_width = 0;
2944 static int old_min_height = 0;
2945 static int old_char_width = 0;
2946 static int old_char_height = 0;
2948 int width;
2949 int height;
2950 int min_width;
2951 int min_height;
2953 /* At start-up, don't try to set the hints until the initial
2954 * values have been used (those that dictate our initial size)
2955 * Let forced (i.e., correct) values thruogh always.
2957 if (!(force_width && force_height) && init_window_hints_state > 0)
2959 /* Don't do it! */
2960 init_window_hints_state = 2;
2961 return;
2964 /* This also needs to be done when the main window isn't there yet,
2965 * otherwise the hints don't work. */
2966 width = gui_get_base_width();
2967 height = gui_get_base_height();
2968 # ifdef FEAT_MENU
2969 height += tabline_height() * gui.char_height;
2970 # endif
2971 # ifdef HAVE_GTK2
2972 width += get_menu_tool_width();
2973 height += get_menu_tool_height();
2974 # endif
2976 /* GtkSockets use GtkPlug's [gui,mainwin] min-size hints to determine
2977 * their actual widget size. When we set our size ourselves (e.g.,
2978 * 'set columns=' or init. -geom) we briefly set the min. to the size
2979 * we wish to be instead of the legitimate minimum so that we actually
2980 * resize correctly.
2982 if (force_width && force_height)
2984 min_width = force_width;
2985 min_height = force_height;
2987 else
2989 min_width = width + MIN_COLUMNS * gui.char_width;
2990 min_height = height + MIN_LINES * gui.char_height;
2993 /* Avoid an expose event when the size didn't change. */
2994 if (width != old_width
2995 || height != old_height
2996 || min_width != old_min_width
2997 || min_height != old_min_height
2998 || gui.char_width != old_char_width
2999 || gui.char_height != old_char_height)
3001 GdkGeometry geometry;
3002 GdkWindowHints geometry_mask;
3004 geometry.width_inc = gui.char_width;
3005 geometry.height_inc = gui.char_height;
3006 geometry.base_width = width;
3007 geometry.base_height = height;
3008 geometry.min_width = min_width;
3009 geometry.min_height = min_height;
3010 geometry_mask = GDK_HINT_BASE_SIZE|GDK_HINT_RESIZE_INC
3011 |GDK_HINT_MIN_SIZE;
3012 # ifdef HAVE_GTK2
3013 /* Using gui.formwin as geometry widget doesn't work as expected
3014 * with GTK+ 2 -- dunno why. Presumably all the resizing hacks
3015 * in Vim confuse GTK+. */
3016 gtk_window_set_geometry_hints(GTK_WINDOW(gui.mainwin), gui.mainwin,
3017 &geometry, geometry_mask);
3018 # else
3019 gtk_window_set_geometry_hints(GTK_WINDOW(gui.mainwin), gui.formwin,
3020 &geometry, geometry_mask);
3021 # endif
3022 old_width = width;
3023 old_height = height;
3024 old_min_width = min_width;
3025 old_min_height = min_height;
3026 old_char_width = gui.char_width;
3027 old_char_height = gui.char_height;
3031 #ifdef FEAT_TOOLBAR
3033 # ifdef HAVE_GTK2
3035 * This extra effort wouldn't be necessary if we only used stock icons in the
3036 * toolbar, as we do for all builtin icons. But user-defined toolbar icons
3037 * shouldn't be treated differently, thus we do need this.
3039 static void
3040 icon_size_changed_foreach(GtkWidget *widget, gpointer user_data)
3042 if (GTK_IS_IMAGE(widget))
3044 GtkImage *image = (GtkImage *)widget;
3046 /* User-defined icons are stored in a GtkIconSet */
3047 if (gtk_image_get_storage_type(image) == GTK_IMAGE_ICON_SET)
3049 GtkIconSet *icon_set;
3050 GtkIconSize icon_size;
3052 gtk_image_get_icon_set(image, &icon_set, &icon_size);
3053 icon_size = (GtkIconSize)(long)user_data;
3055 gtk_icon_set_ref(icon_set);
3056 gtk_image_set_from_icon_set(image, icon_set, icon_size);
3057 gtk_icon_set_unref(icon_set);
3060 else if (GTK_IS_CONTAINER(widget))
3062 gtk_container_foreach((GtkContainer *)widget,
3063 &icon_size_changed_foreach,
3064 user_data);
3067 # endif /* HAVE_GTK2 */
3069 static void
3070 set_toolbar_style(GtkToolbar *toolbar)
3072 GtkToolbarStyle style;
3073 # ifdef HAVE_GTK2
3074 GtkIconSize size;
3075 GtkIconSize oldsize;
3076 # endif
3078 # ifdef HAVE_GTK2
3079 if ((toolbar_flags & (TOOLBAR_TEXT | TOOLBAR_ICONS | TOOLBAR_HORIZ))
3080 == (TOOLBAR_TEXT | TOOLBAR_ICONS | TOOLBAR_HORIZ))
3081 style = GTK_TOOLBAR_BOTH_HORIZ;
3082 else
3083 # endif
3084 if ((toolbar_flags & (TOOLBAR_TEXT | TOOLBAR_ICONS))
3085 == (TOOLBAR_TEXT | TOOLBAR_ICONS))
3086 style = GTK_TOOLBAR_BOTH;
3087 else if (toolbar_flags & TOOLBAR_TEXT)
3088 style = GTK_TOOLBAR_TEXT;
3089 else
3090 style = GTK_TOOLBAR_ICONS;
3092 gtk_toolbar_set_style(toolbar, style);
3093 gtk_toolbar_set_tooltips(toolbar, (toolbar_flags & TOOLBAR_TOOLTIPS) != 0);
3095 # ifdef HAVE_GTK2
3096 switch (tbis_flags)
3098 case TBIS_TINY: size = GTK_ICON_SIZE_MENU; break;
3099 case TBIS_SMALL: size = GTK_ICON_SIZE_SMALL_TOOLBAR; break;
3100 case TBIS_MEDIUM: size = GTK_ICON_SIZE_BUTTON; break;
3101 case TBIS_LARGE: size = GTK_ICON_SIZE_LARGE_TOOLBAR; break;
3102 default: size = GTK_ICON_SIZE_INVALID; break;
3104 oldsize = gtk_toolbar_get_icon_size(toolbar);
3106 if (size == GTK_ICON_SIZE_INVALID)
3108 /* Let global user preferences decide the icon size. */
3109 gtk_toolbar_unset_icon_size(toolbar);
3110 size = gtk_toolbar_get_icon_size(toolbar);
3112 if (size != oldsize)
3114 gtk_container_foreach(GTK_CONTAINER(toolbar),
3115 &icon_size_changed_foreach,
3116 GINT_TO_POINTER((int)size));
3118 gtk_toolbar_set_icon_size(toolbar, size);
3119 # endif
3122 #endif /* FEAT_TOOLBAR */
3124 #if defined(FEAT_GUI_TABLINE) || defined(PROTO)
3125 static int ignore_tabline_evt = FALSE;
3126 static GtkWidget *tabline_menu;
3127 static GtkTooltips *tabline_tooltip;
3128 static int clicked_page; /* page clicked in tab line */
3131 * Handle selecting an item in the tab line popup menu.
3133 /*ARGSUSED*/
3134 static void
3135 tabline_menu_handler(GtkMenuItem *item, gpointer user_data)
3137 /* Add the string cmd into input buffer */
3138 send_tabline_menu_event(clicked_page, (int)(long)user_data);
3140 if (gtk_main_level() > 0)
3141 gtk_main_quit();
3144 static void
3145 add_tabline_menu_item(GtkWidget *menu, char_u *text, int resp)
3147 GtkWidget *item;
3148 char_u *utf_text;
3150 utf_text = CONVERT_TO_UTF8(text);
3151 item = gtk_menu_item_new_with_label((const char *)utf_text);
3152 gtk_widget_show(item);
3153 CONVERT_TO_UTF8_FREE(utf_text);
3155 gtk_container_add(GTK_CONTAINER(menu), item);
3156 gtk_signal_connect(GTK_OBJECT(item), "activate",
3157 GTK_SIGNAL_FUNC(tabline_menu_handler),
3158 (gpointer)resp);
3162 * Create a menu for the tab line.
3164 static GtkWidget *
3165 create_tabline_menu(void)
3167 GtkWidget *menu;
3169 menu = gtk_menu_new();
3170 add_tabline_menu_item(menu, (char_u *)_("Close"), TABLINE_MENU_CLOSE);
3171 add_tabline_menu_item(menu, (char_u *)_("New tab"), TABLINE_MENU_NEW);
3172 add_tabline_menu_item(menu, (char_u *)_("Open Tab..."), TABLINE_MENU_OPEN);
3174 return menu;
3177 static gboolean
3178 on_tabline_menu(GtkWidget *widget, GdkEvent *event)
3180 /* Was this button press event ? */
3181 if (event->type == GDK_BUTTON_PRESS)
3183 GdkEventButton *bevent = (GdkEventButton *)event;
3184 int x = bevent->x;
3185 int y = bevent->y;
3186 GtkWidget *tabwidget;
3187 GdkWindow *tabwin;
3189 /* When ignoring events return TRUE so that the selected page doesn't
3190 * change. */
3191 if (hold_gui_events
3192 # ifdef FEAT_CMDWIN
3193 || cmdwin_type != 0
3194 # endif
3196 return TRUE;
3198 tabwin = gdk_window_at_pointer(&x, &y);
3199 gdk_window_get_user_data(tabwin, (gpointer)&tabwidget);
3200 clicked_page = (int)(long)gtk_object_get_user_data(
3201 GTK_OBJECT(tabwidget));
3203 /* If the event was generated for 3rd button popup the menu. */
3204 if (bevent->button == 3)
3206 gtk_menu_popup(GTK_MENU(widget), NULL, NULL, NULL, NULL,
3207 bevent->button, bevent->time);
3208 /* We handled the event. */
3209 return TRUE;
3211 else if (bevent->button == 1)
3213 if (clicked_page == 0)
3215 /* Click after all tabs moves to next tab page. */
3216 if (send_tabline_event(0) && gtk_main_level() > 0)
3217 gtk_main_quit();
3219 #ifndef HAVE_GTK2
3220 else
3221 gtk_notebook_set_page(GTK_NOTEBOOK(gui.tabline),
3222 clicked_page - 1);
3223 #endif
3227 /* We didn't handle the event. */
3228 return FALSE;
3232 * Handle selecting one of the tabs.
3234 /*ARGSUSED*/
3235 static void
3236 on_select_tab(
3237 GtkNotebook *notebook,
3238 GtkNotebookPage *page,
3239 gint idx,
3240 gpointer data)
3242 if (!ignore_tabline_evt)
3244 if (send_tabline_event(idx + 1) && gtk_main_level() > 0)
3245 gtk_main_quit();
3249 #ifndef HAVE_GTK2
3250 static int showing_tabline = 0;
3251 #endif
3254 * Show or hide the tabline.
3256 void
3257 gui_mch_show_tabline(int showit)
3259 if (gui.tabline == NULL)
3260 return;
3262 #ifdef HAVE_GTK2
3263 /* gtk_notebook_get_show_tabs does not exist in gtk+-1.2.10 */
3264 if (!showit != !gtk_notebook_get_show_tabs(GTK_NOTEBOOK(gui.tabline)))
3265 #else
3266 if (!showit != !showing_tabline)
3267 #endif
3269 /* Note: this may cause a resize event */
3270 gtk_notebook_set_show_tabs(GTK_NOTEBOOK(gui.tabline), showit);
3271 update_window_manager_hints(0, 0);
3272 #ifndef HAVE_GTK2
3273 showing_tabline = showit;
3274 #endif
3275 if (showit)
3276 GTK_WIDGET_UNSET_FLAGS(GTK_WIDGET(gui.tabline), GTK_CAN_FOCUS);
3279 gui_mch_update();
3283 * Return TRUE when tabline is displayed.
3286 gui_mch_showing_tabline(void)
3288 return gui.tabline != NULL
3289 #ifdef HAVE_GTK2
3290 /* gtk_notebook_get_show_tabs does not exist in gtk+-1.2.10 */
3291 && gtk_notebook_get_show_tabs(GTK_NOTEBOOK(gui.tabline))
3292 #else
3293 && showing_tabline
3294 #endif
3299 * Update the labels of the tabline.
3301 void
3302 gui_mch_update_tabline(void)
3304 GtkWidget *page;
3305 GtkWidget *event_box;
3306 GtkWidget *label;
3307 tabpage_T *tp;
3308 int nr = 0;
3309 int tab_num;
3310 int curtabidx = 0;
3311 char_u *labeltext;
3313 if (gui.tabline == NULL)
3314 return;
3316 ignore_tabline_evt = TRUE;
3318 /* Add a label for each tab page. They all contain the same text area. */
3319 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next, ++nr)
3321 if (tp == curtab)
3322 curtabidx = nr;
3324 tab_num = nr + 1;
3326 page = gtk_notebook_get_nth_page(GTK_NOTEBOOK(gui.tabline), nr);
3327 if (page == NULL)
3329 /* Add notebook page */
3330 page = gtk_vbox_new(FALSE, 0);
3331 gtk_widget_show(page);
3332 event_box = gtk_event_box_new();
3333 gtk_widget_show(event_box);
3334 label = gtk_label_new("-Empty-");
3335 gtk_misc_set_padding(GTK_MISC(label), 2, 2);
3336 gtk_container_add(GTK_CONTAINER(event_box), label);
3337 gtk_widget_show(label);
3338 gtk_notebook_insert_page(GTK_NOTEBOOK(gui.tabline),
3339 page,
3340 event_box,
3341 nr++);
3344 event_box = gtk_notebook_get_tab_label(GTK_NOTEBOOK(gui.tabline), page);
3345 gtk_object_set_user_data(GTK_OBJECT(event_box), (gpointer)tab_num);
3346 label = GTK_BIN(event_box)->child;
3347 get_tabline_label(tp, FALSE);
3348 labeltext = CONVERT_TO_UTF8(NameBuff);
3349 gtk_label_set_text(GTK_LABEL(label), (const char *)labeltext);
3350 CONVERT_TO_UTF8_FREE(labeltext);
3352 get_tabline_label(tp, TRUE);
3353 labeltext = CONVERT_TO_UTF8(NameBuff);
3354 gtk_tooltips_set_tip(GTK_TOOLTIPS(tabline_tooltip), event_box,
3355 (const char *)labeltext, NULL);
3356 CONVERT_TO_UTF8_FREE(labeltext);
3359 /* Remove any old labels. */
3360 while (gtk_notebook_get_nth_page(GTK_NOTEBOOK(gui.tabline), nr) != NULL)
3361 gtk_notebook_remove_page(GTK_NOTEBOOK(gui.tabline), nr);
3363 if (gtk_notebook_current_page(GTK_NOTEBOOK(gui.tabline)) != curtabidx)
3364 gtk_notebook_set_page(GTK_NOTEBOOK(gui.tabline), curtabidx);
3366 /* Make sure everything is in place before drawing text. */
3367 gui_mch_update();
3369 ignore_tabline_evt = FALSE;
3373 * Set the current tab to "nr". First tab is 1.
3375 void
3376 gui_mch_set_curtab(nr)
3377 int nr;
3379 if (gui.tabline == NULL)
3380 return;
3382 ignore_tabline_evt = TRUE;
3383 if (gtk_notebook_current_page(GTK_NOTEBOOK(gui.tabline)) != nr - 1)
3384 gtk_notebook_set_page(GTK_NOTEBOOK(gui.tabline), nr - 1);
3385 ignore_tabline_evt = FALSE;
3388 #endif /* FEAT_GUI_TABLINE */
3391 * Initialize the GUI. Create all the windows, set up all the callbacks etc.
3392 * Returns OK for success, FAIL when the GUI can't be started.
3395 gui_mch_init(void)
3397 GtkWidget *vbox;
3399 #ifdef FEAT_GUI_GNOME
3400 /* Initialize the GNOME libraries. gnome_program_init()/gnome_init()
3401 * exits on failure, but that's a non-issue because we already called
3402 * gtk_init_check() in gui_mch_init_check(). */
3403 if (using_gnome)
3404 # ifdef HAVE_GTK2
3405 gnome_program_init(VIMPACKAGE, VIM_VERSION_SHORT,
3406 LIBGNOMEUI_MODULE, gui_argc, gui_argv, NULL);
3407 # else
3408 gnome_init(VIMPACKAGE, VIM_VERSION_SHORT, gui_argc, gui_argv);
3409 # endif
3410 #endif
3411 vim_free(gui_argv);
3412 gui_argv = NULL;
3414 #ifdef HAVE_GTK2
3415 # if GLIB_CHECK_VERSION(2,1,3)
3416 /* Set the human-readable application name */
3417 g_set_application_name("Vim");
3418 # endif
3420 * Force UTF-8 output no matter what the value of 'encoding' is.
3421 * did_set_string_option() in option.c prohibits changing 'termencoding'
3422 * to something else than UTF-8 if the GUI is in use.
3424 set_option_value((char_u *)"termencoding", 0L, (char_u *)"utf-8", 0);
3426 # ifdef FEAT_TOOLBAR
3427 gui_gtk_register_stock_icons();
3428 # endif
3429 /* FIXME: Need to install the classic icons and a gtkrc.classic file.
3430 * The hard part is deciding install locations and the Makefile magic. */
3431 # if 0
3432 gtk_rc_parse("gtkrc");
3433 # endif
3434 #endif
3436 /* Initialize values */
3437 gui.border_width = 2;
3438 gui.scrollbar_width = SB_DEFAULT_WIDTH;
3439 gui.scrollbar_height = SB_DEFAULT_WIDTH;
3440 /* LINTED: avoid warning: conversion to 'unsigned long' */
3441 gui.fgcolor = g_new0(GdkColor, 1);
3442 /* LINTED: avoid warning: conversion to 'unsigned long' */
3443 gui.bgcolor = g_new0(GdkColor, 1);
3444 /* LINTED: avoid warning: conversion to 'unsigned long' */
3445 gui.spcolor = g_new0(GdkColor, 1);
3447 /* Initialise atoms */
3448 #ifdef FEAT_MBYTE
3449 utf8_string_atom = gdk_atom_intern("UTF8_STRING", FALSE);
3450 #endif
3451 #ifndef HAVE_GTK2
3452 compound_text_atom = gdk_atom_intern("COMPOUND_TEXT", FALSE);
3453 text_atom = gdk_atom_intern("TEXT", FALSE);
3454 #endif
3456 /* Set default foreground and background colors. */
3457 gui.norm_pixel = gui.def_norm_pixel;
3458 gui.back_pixel = gui.def_back_pixel;
3460 if (gtk_socket_id != 0)
3462 GtkWidget *plug;
3464 /* Use GtkSocket from another app. */
3465 #ifdef HAVE_GTK_MULTIHEAD
3466 plug = gtk_plug_new_for_display(gdk_display_get_default(),
3467 gtk_socket_id);
3468 #else
3469 plug = gtk_plug_new(gtk_socket_id);
3470 #endif
3471 if (plug != NULL && GTK_PLUG(plug)->socket_window != NULL)
3473 gui.mainwin = plug;
3475 else
3477 g_warning("Connection to GTK+ socket (ID %u) failed",
3478 (unsigned int)gtk_socket_id);
3479 /* Pretend we never wanted it if it failed (get own window) */
3480 gtk_socket_id = 0;
3484 if (gtk_socket_id == 0)
3486 #ifdef FEAT_GUI_GNOME
3487 if (using_gnome)
3489 gui.mainwin = gnome_app_new("Vim", NULL);
3490 # ifdef USE_XSMP
3491 /* Use the GNOME save-yourself functionality now. */
3492 xsmp_close();
3493 # endif
3495 else
3496 #endif
3497 gui.mainwin = gtk_window_new(GTK_WINDOW_TOPLEVEL);
3500 gtk_widget_set_name(gui.mainwin, "vim-main-window");
3502 #ifdef HAVE_GTK2
3503 /* Create the PangoContext used for drawing all text. */
3504 gui.text_context = gtk_widget_create_pango_context(gui.mainwin);
3505 pango_context_set_base_dir(gui.text_context, PANGO_DIRECTION_LTR);
3506 #endif
3508 #ifndef HAVE_GTK2
3509 gtk_window_set_policy(GTK_WINDOW(gui.mainwin), TRUE, TRUE, TRUE);
3510 #endif
3511 gtk_container_border_width(GTK_CONTAINER(gui.mainwin), 0);
3512 gtk_widget_add_events(gui.mainwin, GDK_VISIBILITY_NOTIFY_MASK);
3514 gtk_signal_connect(GTK_OBJECT(gui.mainwin), "delete_event",
3515 GTK_SIGNAL_FUNC(&delete_event_cb), NULL);
3517 gtk_signal_connect(GTK_OBJECT(gui.mainwin), "realize",
3518 GTK_SIGNAL_FUNC(&mainwin_realize), NULL);
3519 #ifdef HAVE_GTK_MULTIHEAD
3520 g_signal_connect(G_OBJECT(gui.mainwin), "screen_changed",
3521 G_CALLBACK(&mainwin_screen_changed_cb), NULL);
3522 #endif
3523 #ifdef HAVE_GTK2
3524 gui.accel_group = gtk_accel_group_new();
3525 gtk_window_add_accel_group(GTK_WINDOW(gui.mainwin), gui.accel_group);
3526 #else
3527 gui.accel_group = gtk_accel_group_get_default();
3528 #endif
3530 /* A vertical box holds the menubar, toolbar and main text window. */
3531 vbox = gtk_vbox_new(FALSE, 0);
3533 #ifdef FEAT_GUI_GNOME
3534 if (using_gnome)
3536 # if defined(HAVE_GTK2) && defined(FEAT_MENU)
3537 /* automagically restore menubar/toolbar placement */
3538 gnome_app_enable_layout_config(GNOME_APP(gui.mainwin), TRUE);
3539 # endif
3540 gnome_app_set_contents(GNOME_APP(gui.mainwin), vbox);
3542 else
3543 #endif
3545 gtk_container_add(GTK_CONTAINER(gui.mainwin), vbox);
3546 gtk_widget_show(vbox);
3549 #ifdef FEAT_MENU
3551 * Create the menubar and handle
3553 gui.menubar = gtk_menu_bar_new();
3554 gtk_widget_set_name(gui.menubar, "vim-menubar");
3556 # ifdef HAVE_GTK2
3557 /* Avoid that GTK takes <F10> away from us. */
3559 GtkSettings *gtk_settings;
3561 gtk_settings = gtk_settings_get_for_screen(gdk_screen_get_default());
3562 g_object_set(gtk_settings, "gtk-menu-bar-accel", NULL, NULL);
3564 # endif
3567 # ifdef FEAT_GUI_GNOME
3568 if (using_gnome)
3570 # ifdef HAVE_GTK2
3571 BonoboDockItem *dockitem;
3573 gnome_app_set_menus(GNOME_APP(gui.mainwin), GTK_MENU_BAR(gui.menubar));
3574 dockitem = gnome_app_get_dock_item_by_name(GNOME_APP(gui.mainwin),
3575 GNOME_APP_MENUBAR_NAME);
3576 /* We don't want the menu to float. */
3577 bonobo_dock_item_set_behavior(dockitem,
3578 bonobo_dock_item_get_behavior(dockitem)
3579 | BONOBO_DOCK_ITEM_BEH_NEVER_FLOATING);
3580 gui.menubar_h = GTK_WIDGET(dockitem);
3581 # else
3582 gui.menubar_h = gnome_dock_item_new("VimMainMenu",
3583 GNOME_DOCK_ITEM_BEH_EXCLUSIVE |
3584 GNOME_DOCK_ITEM_BEH_NEVER_VERTICAL);
3585 gtk_container_add(GTK_CONTAINER(gui.menubar_h), gui.menubar);
3587 gnome_dock_add_item(GNOME_DOCK(GNOME_APP(gui.mainwin)->dock),
3588 GNOME_DOCK_ITEM(gui.menubar_h),
3589 GNOME_DOCK_TOP, /* placement */
3590 1, /* band_num */
3591 0, /* band_position */
3592 0, /* offset */
3593 TRUE);
3594 gtk_widget_show(gui.menubar);
3595 # endif
3597 else
3598 # endif /* FEAT_GUI_GNOME */
3600 /* Always show the menubar, otherwise <F10> doesn't work. It may be
3601 * disabled in gui_init() later. */
3602 gtk_widget_show(gui.menubar);
3603 gtk_box_pack_start(GTK_BOX(vbox), gui.menubar, FALSE, FALSE, 0);
3605 #endif /* FEAT_MENU */
3607 #ifdef FEAT_TOOLBAR
3609 * Create the toolbar and handle
3611 # ifdef HAVE_GTK2
3612 /* some aesthetics on the toolbar */
3613 gtk_rc_parse_string(
3614 "style \"vim-toolbar-style\" {\n"
3615 " GtkToolbar::button_relief = GTK_RELIEF_NONE\n"
3616 "}\n"
3617 "widget \"*.vim-toolbar\" style \"vim-toolbar-style\"\n");
3618 gui.toolbar = gtk_toolbar_new();
3619 gtk_widget_set_name(gui.toolbar, "vim-toolbar");
3620 # else
3621 gui.toolbar = gtk_toolbar_new(GTK_ORIENTATION_HORIZONTAL,
3622 GTK_TOOLBAR_ICONS);
3623 gtk_toolbar_set_button_relief(GTK_TOOLBAR(gui.toolbar), GTK_RELIEF_NONE);
3624 # endif
3625 set_toolbar_style(GTK_TOOLBAR(gui.toolbar));
3627 # ifdef FEAT_GUI_GNOME
3628 if (using_gnome)
3630 # ifdef HAVE_GTK2
3631 BonoboDockItem *dockitem;
3633 gnome_app_set_toolbar(GNOME_APP(gui.mainwin), GTK_TOOLBAR(gui.toolbar));
3634 dockitem = gnome_app_get_dock_item_by_name(GNOME_APP(gui.mainwin),
3635 GNOME_APP_TOOLBAR_NAME);
3636 gui.toolbar_h = GTK_WIDGET(dockitem);
3637 /* When the toolbar is floating it gets stuck. So long as that isn't
3638 * fixed let's disallow floating. */
3639 bonobo_dock_item_set_behavior(dockitem,
3640 bonobo_dock_item_get_behavior(dockitem)
3641 | BONOBO_DOCK_ITEM_BEH_NEVER_FLOATING);
3642 gtk_container_set_border_width(GTK_CONTAINER(gui.toolbar), 0);
3643 # else
3644 GtkWidget *dockitem;
3646 dockitem = gnome_dock_item_new("VimToolBar",
3647 GNOME_DOCK_ITEM_BEH_EXCLUSIVE);
3648 gtk_container_add(GTK_CONTAINER(dockitem), GTK_WIDGET(gui.toolbar));
3649 gui.toolbar_h = dockitem;
3651 gnome_dock_add_item(GNOME_DOCK(GNOME_APP(gui.mainwin)->dock),
3652 GNOME_DOCK_ITEM(dockitem),
3653 GNOME_DOCK_TOP, /* placement */
3654 1, /* band_num */
3655 1, /* band_position */
3656 0, /* offset */
3657 TRUE);
3658 gtk_container_border_width(GTK_CONTAINER(gui.toolbar), 2);
3659 gtk_widget_show(gui.toolbar);
3660 # endif
3662 else
3663 # endif /* FEAT_GUI_GNOME */
3665 # ifndef HAVE_GTK2
3666 gtk_container_border_width(GTK_CONTAINER(gui.toolbar), 1);
3667 # endif
3668 if (vim_strchr(p_go, GO_TOOLBAR) != NULL
3669 && (toolbar_flags & (TOOLBAR_TEXT | TOOLBAR_ICONS)))
3670 gtk_widget_show(gui.toolbar);
3671 gtk_box_pack_start(GTK_BOX(vbox), gui.toolbar, FALSE, FALSE, 0);
3673 #endif /* FEAT_TOOLBAR */
3675 #ifdef FEAT_GUI_TABLINE
3677 * Use a Notebook for the tab pages labels. The labels are hidden by
3678 * default.
3680 gui.tabline = gtk_notebook_new();
3681 gtk_widget_show(gui.tabline);
3682 gtk_box_pack_start(GTK_BOX(vbox), gui.tabline, FALSE, FALSE, 0);
3683 gtk_notebook_set_show_border(GTK_NOTEBOOK(gui.tabline), FALSE);
3684 gtk_notebook_set_show_tabs(GTK_NOTEBOOK(gui.tabline), FALSE);
3685 gtk_notebook_set_scrollable(GTK_NOTEBOOK(gui.tabline), TRUE);
3686 gtk_notebook_set_tab_border(GTK_NOTEBOOK(gui.tabline), FALSE);
3688 tabline_tooltip = gtk_tooltips_new();
3689 gtk_tooltips_enable(GTK_TOOLTIPS(tabline_tooltip));
3692 GtkWidget *page, *label, *event_box;
3694 /* Add the first tab. */
3695 page = gtk_vbox_new(FALSE, 0);
3696 gtk_widget_show(page);
3697 gtk_container_add(GTK_CONTAINER(gui.tabline), page);
3698 label = gtk_label_new("-Empty-");
3699 gtk_widget_show(label);
3700 event_box = gtk_event_box_new();
3701 gtk_widget_show(event_box);
3702 gtk_object_set_user_data(GTK_OBJECT(event_box), (gpointer)1);
3703 gtk_misc_set_padding(GTK_MISC(label), 2, 2);
3704 gtk_container_add(GTK_CONTAINER(event_box), label);
3705 gtk_notebook_set_tab_label(GTK_NOTEBOOK(gui.tabline), page, event_box);
3708 gtk_signal_connect(GTK_OBJECT(gui.tabline), "switch_page",
3709 GTK_SIGNAL_FUNC(on_select_tab), NULL);
3711 /* Create a popup menu for the tab line and connect it. */
3712 tabline_menu = create_tabline_menu();
3713 gtk_signal_connect_object(GTK_OBJECT(gui.tabline), "button_press_event",
3714 GTK_SIGNAL_FUNC(on_tabline_menu), GTK_OBJECT(tabline_menu));
3715 #endif
3717 gui.formwin = gtk_form_new();
3718 gtk_container_border_width(GTK_CONTAINER(gui.formwin), 0);
3719 gtk_widget_set_events(gui.formwin, GDK_EXPOSURE_MASK);
3721 gui.drawarea = gtk_drawing_area_new();
3723 /* Determine which events we will filter. */
3724 gtk_widget_set_events(gui.drawarea,
3725 GDK_EXPOSURE_MASK |
3726 GDK_ENTER_NOTIFY_MASK |
3727 GDK_LEAVE_NOTIFY_MASK |
3728 GDK_BUTTON_PRESS_MASK |
3729 GDK_BUTTON_RELEASE_MASK |
3730 #ifdef HAVE_GTK2
3731 GDK_SCROLL_MASK |
3732 #endif
3733 GDK_KEY_PRESS_MASK |
3734 GDK_KEY_RELEASE_MASK |
3735 GDK_POINTER_MOTION_MASK |
3736 GDK_POINTER_MOTION_HINT_MASK);
3738 gtk_widget_show(gui.drawarea);
3739 gtk_form_put(GTK_FORM(gui.formwin), gui.drawarea, 0, 0);
3740 gtk_widget_show(gui.formwin);
3741 gtk_box_pack_start(GTK_BOX(vbox), gui.formwin, TRUE, TRUE, 0);
3743 /* For GtkSockets, key-presses must go to the focus widget (drawarea)
3744 * and not the window. */
3745 gtk_signal_connect((gtk_socket_id == 0) ? GTK_OBJECT(gui.mainwin)
3746 : GTK_OBJECT(gui.drawarea),
3747 "key_press_event",
3748 GTK_SIGNAL_FUNC(key_press_event), NULL);
3749 #if defined(FEAT_XIM) && defined(HAVE_GTK2)
3750 /* Also forward key release events for the benefit of GTK+ 2 input
3751 * modules. Try CTRL-SHIFT-xdigits to enter a Unicode code point. */
3752 g_signal_connect((gtk_socket_id == 0) ? G_OBJECT(gui.mainwin)
3753 : G_OBJECT(gui.drawarea),
3754 "key_release_event",
3755 G_CALLBACK(&key_release_event), NULL);
3756 #endif
3757 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "realize",
3758 GTK_SIGNAL_FUNC(drawarea_realize_cb), NULL);
3759 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "unrealize",
3760 GTK_SIGNAL_FUNC(drawarea_unrealize_cb), NULL);
3762 gtk_signal_connect_after(GTK_OBJECT(gui.drawarea), "style_set",
3763 GTK_SIGNAL_FUNC(&drawarea_style_set_cb), NULL);
3765 gui.visibility = GDK_VISIBILITY_UNOBSCURED;
3767 #if !(defined(FEAT_GUI_GNOME) && defined(FEAT_SESSION))
3768 wm_protocols_atom = gdk_atom_intern("WM_PROTOCOLS", FALSE);
3769 save_yourself_atom = gdk_atom_intern("WM_SAVE_YOURSELF", FALSE);
3770 #endif
3772 if (gtk_socket_id != 0)
3773 /* make sure keybord input can go to the drawarea */
3774 GTK_WIDGET_SET_FLAGS(gui.drawarea, GTK_CAN_FOCUS);
3777 * Set clipboard specific atoms
3779 vim_atom = gdk_atom_intern(VIM_ATOM_NAME, FALSE);
3780 #ifdef FEAT_MBYTE
3781 vimenc_atom = gdk_atom_intern(VIMENC_ATOM_NAME, FALSE);
3782 #endif
3783 clip_star.gtk_sel_atom = GDK_SELECTION_PRIMARY;
3784 clip_plus.gtk_sel_atom = gdk_atom_intern("CLIPBOARD", FALSE);
3787 * Start out by adding the configured border width into the border offset.
3789 gui.border_offset = gui.border_width;
3791 gtk_signal_connect(GTK_OBJECT(gui.mainwin), "visibility_notify_event",
3792 GTK_SIGNAL_FUNC(visibility_event), NULL);
3793 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "expose_event",
3794 GTK_SIGNAL_FUNC(expose_event), NULL);
3797 * Only install these enter/leave callbacks when 'p' in 'guioptions'.
3798 * Only needed for some window managers.
3800 if (vim_strchr(p_go, GO_POINTER) != NULL)
3802 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "leave_notify_event",
3803 GTK_SIGNAL_FUNC(leave_notify_event), NULL);
3804 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "enter_notify_event",
3805 GTK_SIGNAL_FUNC(enter_notify_event), NULL);
3808 /* Real windows can get focus ... GtkPlug, being a mere container can't,
3809 * only its widgets. Arguably, this could be common code and we not use
3810 * the window focus at all, but let's be safe.
3812 if (gtk_socket_id == 0)
3814 gtk_signal_connect(GTK_OBJECT(gui.mainwin), "focus_out_event",
3815 GTK_SIGNAL_FUNC(focus_out_event), NULL);
3816 gtk_signal_connect(GTK_OBJECT(gui.mainwin), "focus_in_event",
3817 GTK_SIGNAL_FUNC(focus_in_event), NULL);
3819 else
3821 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "focus_out_event",
3822 GTK_SIGNAL_FUNC(focus_out_event), NULL);
3823 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "focus_in_event",
3824 GTK_SIGNAL_FUNC(focus_in_event), NULL);
3825 #ifdef FEAT_GUI_TABLINE
3826 gtk_signal_connect(GTK_OBJECT(gui.tabline), "focus_out_event",
3827 GTK_SIGNAL_FUNC(focus_out_event), NULL);
3828 gtk_signal_connect(GTK_OBJECT(gui.tabline), "focus_in_event",
3829 GTK_SIGNAL_FUNC(focus_in_event), NULL);
3830 #endif /* FEAT_GUI_TABLINE */
3833 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "motion_notify_event",
3834 GTK_SIGNAL_FUNC(motion_notify_event), NULL);
3835 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "button_press_event",
3836 GTK_SIGNAL_FUNC(button_press_event), NULL);
3837 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "button_release_event",
3838 GTK_SIGNAL_FUNC(button_release_event), NULL);
3839 #ifdef HAVE_GTK2
3840 g_signal_connect(G_OBJECT(gui.drawarea), "scroll_event",
3841 G_CALLBACK(&scroll_event), NULL);
3842 #endif
3845 * Add selection handler functions.
3847 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "selection_clear_event",
3848 GTK_SIGNAL_FUNC(selection_clear_event), NULL);
3849 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "selection_received",
3850 GTK_SIGNAL_FUNC(selection_received_cb), NULL);
3853 * Add selection targets for PRIMARY and CLIPBOARD selections.
3855 gtk_selection_add_targets(gui.drawarea,
3856 (GdkAtom)GDK_SELECTION_PRIMARY,
3857 selection_targets, N_SELECTION_TARGETS);
3858 gtk_selection_add_targets(gui.drawarea,
3859 (GdkAtom)clip_plus.gtk_sel_atom,
3860 selection_targets, N_SELECTION_TARGETS);
3862 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "selection_get",
3863 GTK_SIGNAL_FUNC(selection_get_cb), NULL);
3865 /* Pretend we don't have input focus, we will get an event if we do. */
3866 gui.in_focus = FALSE;
3868 return OK;
3871 #if (defined(FEAT_GUI_GNOME) && defined(FEAT_SESSION)) || defined(PROTO)
3873 * This is called from gui_start() after a fork() has been done.
3874 * We have to tell the session manager our new PID.
3876 void
3877 gui_mch_forked(void)
3879 if (using_gnome)
3881 GnomeClient *client;
3883 client = gnome_master_client();
3885 if (client != NULL)
3886 gnome_client_set_process_id(client, getpid());
3889 #endif /* FEAT_GUI_GNOME && FEAT_SESSION */
3892 * Called when the foreground or background color has been changed.
3893 * This used to change the graphics contexts directly but we are
3894 * currently manipulating them where desired.
3896 void
3897 gui_mch_new_colors(void)
3899 if (gui.drawarea != NULL && gui.drawarea->window != NULL)
3901 GdkColor color = { 0, 0, 0, 0 };
3903 color.pixel = gui.back_pixel;
3904 gdk_window_set_background(gui.drawarea->window, &color);
3909 * This signal informs us about the need to rearrange our sub-widgets.
3911 /*ARGSUSED*/
3912 static gint
3913 form_configure_event(GtkWidget *widget, GdkEventConfigure *event,
3914 gpointer data)
3916 int usable_height = event->height;
3918 /* When in a GtkPlug, we can't guarantee valid heights (as a round
3919 * no. of char-heights), so we have to manually sanitise them.
3920 * Widths seem to sort themselves out, don't ask me why.
3922 if (gtk_socket_id != 0)
3923 usable_height -= (gui.char_height - (gui.char_height/2)); /* sic. */
3925 gtk_form_freeze(GTK_FORM(gui.formwin));
3926 gui_resize_shell(event->width, usable_height);
3927 gtk_form_thaw(GTK_FORM(gui.formwin));
3929 return TRUE;
3933 * Function called when window already closed.
3934 * We can't do much more here than to trying to preserve what had been done,
3935 * since the window is already inevitably going away.
3937 /*ARGSUSED0*/
3938 static void
3939 mainwin_destroy_cb(GtkObject *object, gpointer data)
3941 /* Don't write messages to the GUI anymore */
3942 full_screen = FALSE;
3944 gui.mainwin = NULL;
3945 gui.drawarea = NULL;
3947 if (!exiting) /* only do anything if the destroy was unexpected */
3949 vim_strncpy(IObuff,
3950 (char_u *)_("Vim: Main window unexpectedly destroyed\n"),
3951 IOSIZE - 1);
3952 preserve_exit();
3958 * Bit of a hack to ensure we start GtkPlug windows with the correct window
3959 * hints (and thus the required size from -geom), but that after that we
3960 * put the hints back to normal (the actual minimum size) so we may
3961 * subsequently be resized smaller. GtkSocket (the parent end) uses the
3962 * plug's window 'min hints to set *it's* minimum size, but that's also the
3963 * only way we have of making ourselves bigger (by set lines/columns).
3964 * Thus set hints at start-up to ensure correct init. size, then a
3965 * second after the final attempt to reset the real minimum hinst (done by
3966 * scrollbar init.), actually do the standard hinst and stop the timer.
3967 * We'll not let the default hints be set while this timer's active.
3969 /*ARGSUSED*/
3970 static gboolean
3971 check_startup_plug_hints(gpointer data)
3973 if (init_window_hints_state == 1)
3975 /* Safe to use normal hints now */
3976 init_window_hints_state = 0;
3977 update_window_manager_hints(0, 0);
3978 return FALSE; /* stop timer */
3981 /* Keep on trying */
3982 init_window_hints_state = 1;
3983 return TRUE;
3988 * Open the GUI window which was created by a call to gui_mch_init().
3991 gui_mch_open(void)
3993 guicolor_T fg_pixel = INVALCOLOR;
3994 guicolor_T bg_pixel = INVALCOLOR;
3996 #ifdef HAVE_GTK2
3998 * Allow setting a window role on the command line, or invent one
3999 * if none was specified. This is mainly useful for GNOME session
4000 * support; allowing the WM to restore window placement.
4002 if (role_argument != NULL)
4004 gtk_window_set_role(GTK_WINDOW(gui.mainwin), role_argument);
4006 else
4008 char *role;
4010 /* Invent a unique-enough ID string for the role */
4011 role = g_strdup_printf("vim-%u-%u-%u",
4012 (unsigned)mch_get_pid(),
4013 (unsigned)g_random_int(),
4014 (unsigned)time(NULL));
4016 gtk_window_set_role(GTK_WINDOW(gui.mainwin), role);
4017 g_free(role);
4019 #endif
4021 if (gui_win_x != -1 && gui_win_y != -1)
4022 #ifdef HAVE_GTK2
4023 gtk_window_move(GTK_WINDOW(gui.mainwin), gui_win_x, gui_win_y);
4024 #else
4025 gtk_widget_set_uposition(gui.mainwin, gui_win_x, gui_win_y);
4026 #endif
4028 /* Determine user specified geometry, if present. */
4029 if (gui.geom != NULL)
4031 int mask;
4032 unsigned int w, h;
4033 int x = 0;
4034 int y = 0;
4036 mask = XParseGeometry((char *)gui.geom, &x, &y, &w, &h);
4038 if (mask & WidthValue)
4039 Columns = w;
4040 if (mask & HeightValue)
4042 if (p_window > h - 1 || !option_was_set((char_u *)"window"))
4043 p_window = h - 1;
4044 Rows = h;
4046 if (mask & (XValue | YValue))
4047 #ifdef HAVE_GTK2
4048 gtk_window_move(GTK_WINDOW(gui.mainwin), x, y);
4049 #else
4050 gtk_widget_set_uposition(gui.mainwin, x, y);
4051 #endif
4052 vim_free(gui.geom);
4053 gui.geom = NULL;
4055 /* From now until everyone's stopped trying to set the window hints
4056 * to their correct minimum values, stop them being set as we need
4057 * them to remain at our required size for the parent GtkSocket to
4058 * give us the right initial size.
4060 if (gtk_socket_id != 0 && (mask & WidthValue || mask & HeightValue))
4062 guint pixel_width = (guint)(gui_get_base_width() + Columns * gui.char_width);
4063 guint pixel_height = (guint)(gui_get_base_height() + Rows * gui.char_height);
4065 #ifdef HAVE_GTK2
4066 pixel_width += get_menu_tool_width();
4067 pixel_height += get_menu_tool_height();
4068 #endif
4070 update_window_manager_hints(pixel_width, pixel_height);
4071 init_window_hints_state = 1;
4072 g_timeout_add(1000, check_startup_plug_hints, NULL);
4076 gtk_form_set_size(GTK_FORM(gui.formwin),
4077 (guint)(gui_get_base_width() + Columns * gui.char_width),
4078 (guint)(gui_get_base_height() + Rows * gui.char_height));
4079 update_window_manager_hints(0, 0);
4081 if (foreground_argument != NULL)
4082 fg_pixel = gui_get_color((char_u *)foreground_argument);
4083 if (fg_pixel == INVALCOLOR)
4084 fg_pixel = gui_get_color((char_u *)"Black");
4086 if (background_argument != NULL)
4087 bg_pixel = gui_get_color((char_u *)background_argument);
4088 if (bg_pixel == INVALCOLOR)
4089 bg_pixel = gui_get_color((char_u *)"White");
4091 if (found_reverse_arg)
4093 gui.def_norm_pixel = bg_pixel;
4094 gui.def_back_pixel = fg_pixel;
4096 else
4098 gui.def_norm_pixel = fg_pixel;
4099 gui.def_back_pixel = bg_pixel;
4102 /* Get the colors from the "Normal" and "Menu" group (set in syntax.c or
4103 * in a vimrc file) */
4104 set_normal_colors();
4106 /* Check that none of the colors are the same as the background color */
4107 gui_check_colors();
4109 /* Get the colors for the highlight groups (gui_check_colors() might have
4110 * changed them). */
4111 highlight_gui_started(); /* re-init colors and fonts */
4113 gtk_signal_connect(GTK_OBJECT(gui.mainwin), "destroy",
4114 GTK_SIGNAL_FUNC(mainwin_destroy_cb), NULL);
4116 #ifdef FEAT_HANGULIN
4117 hangul_keyboard_set();
4118 #endif
4121 * Notify the fixed area about the need to resize the contents of the
4122 * gui.formwin, which we use for random positioning of the included
4123 * components.
4125 * We connect this signal deferred finally after anything is in place,
4126 * since this is intended to handle resizements coming from the window
4127 * manager upon us and should not interfere with what VIM is requesting
4128 * upon startup.
4130 gtk_signal_connect(GTK_OBJECT(gui.formwin), "configure_event",
4131 GTK_SIGNAL_FUNC(form_configure_event), NULL);
4133 #ifdef FEAT_DND
4135 * Set up for receiving DND items.
4137 gtk_drag_dest_set(gui.drawarea,
4138 GTK_DEST_DEFAULT_ALL,
4139 dnd_targets, N_DND_TARGETS,
4140 GDK_ACTION_COPY);
4142 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "drag_data_received",
4143 GTK_SIGNAL_FUNC(drag_data_received_cb), NULL);
4144 #endif
4146 #ifdef HAVE_GTK2
4147 /* With GTK+ 2, we need to iconify the window before calling show()
4148 * to avoid mapping the window for a short time. This is just as one
4149 * would expect it to work, but it's different in GTK+ 1. The funny
4150 * thing is that iconifying after show() _does_ work with GTK+ 1.
4151 * (BTW doing this in the "realize" handler makes no difference.) */
4152 if (found_iconic_arg && gtk_socket_id == 0)
4153 gui_mch_iconify();
4154 #endif
4157 #if defined(FEAT_GUI_GNOME) && defined(HAVE_GTK2) && defined(FEAT_MENU)
4158 unsigned long menu_handler = 0;
4159 # ifdef FEAT_TOOLBAR
4160 unsigned long tool_handler = 0;
4161 # endif
4163 * Urgh hackish :/ For some reason BonoboDockLayout always forces a
4164 * show when restoring the saved layout configuration. We can't just
4165 * hide the widgets again after gtk_widget_show(gui.mainwin) since it's
4166 * a toplevel window and thus will be realized immediately. Instead,
4167 * connect signal handlers to hide the widgets just after they've been
4168 * marked visible, but before the main window is realized.
4170 if (using_gnome && vim_strchr(p_go, GO_MENUS) == NULL)
4171 menu_handler = g_signal_connect_after(gui.menubar_h, "show",
4172 G_CALLBACK(&gtk_widget_hide),
4173 NULL);
4174 # ifdef FEAT_TOOLBAR
4175 if (using_gnome && vim_strchr(p_go, GO_TOOLBAR) == NULL
4176 && (toolbar_flags & (TOOLBAR_TEXT | TOOLBAR_ICONS)))
4177 tool_handler = g_signal_connect_after(gui.toolbar_h, "show",
4178 G_CALLBACK(&gtk_widget_hide),
4179 NULL);
4180 # endif
4181 #endif
4182 gtk_widget_show(gui.mainwin);
4184 #if defined(FEAT_GUI_GNOME) && defined(HAVE_GTK2) && defined(FEAT_MENU)
4185 if (menu_handler != 0)
4186 g_signal_handler_disconnect(gui.menubar_h, menu_handler);
4187 # ifdef FEAT_TOOLBAR
4188 if (tool_handler != 0)
4189 g_signal_handler_disconnect(gui.toolbar_h, tool_handler);
4190 # endif
4191 #endif
4194 #ifndef HAVE_GTK2
4195 /* With GTK+ 1, we need to iconify the window after calling show().
4196 * See the comment above for details. */
4197 if (found_iconic_arg && gtk_socket_id == 0)
4198 gui_mch_iconify();
4199 #endif
4201 return OK;
4205 /*ARGSUSED0*/
4206 void
4207 gui_mch_exit(int rc)
4209 if (gui.mainwin != NULL)
4210 gtk_widget_destroy(gui.mainwin);
4212 if (gtk_main_level() > 0)
4213 gtk_main_quit();
4217 * Get the position of the top left corner of the window.
4220 gui_mch_get_winpos(int *x, int *y)
4222 #ifdef HAVE_GTK2
4223 gtk_window_get_position(GTK_WINDOW(gui.mainwin), x, y);
4224 #else
4225 /* For some people this must be gdk_window_get_origin() for a correct
4226 * result. Where is the documentation! */
4227 gdk_window_get_root_origin(gui.mainwin->window, x, y);
4228 #endif
4229 return OK;
4233 * Set the position of the top left corner of the window to the given
4234 * coordinates.
4236 void
4237 gui_mch_set_winpos(int x, int y)
4239 #ifdef HAVE_GTK2
4240 gtk_window_move(GTK_WINDOW(gui.mainwin), x, y);
4241 #else
4242 gdk_window_move(gui.mainwin->window, x, y);
4243 #endif
4246 #ifdef HAVE_GTK2
4247 #if 0
4248 static int resize_idle_installed = FALSE;
4250 * Idle handler to force resize. Used by gui_mch_set_shellsize() to ensure
4251 * the shell size doesn't exceed the window size, i.e. if the window manager
4252 * ignored our size request. Usually this happens if the window is maximized.
4254 * FIXME: It'd be nice if we could find a little more orthodox solution.
4255 * See also the remark below in gui_mch_set_shellsize().
4257 * DISABLED: When doing ":set lines+=1" this function would first invoke
4258 * gui_resize_shell() with the old size, then the normal callback would
4259 * report the new size through form_configure_event(). That caused the window
4260 * layout to be messed up.
4262 /*ARGSUSED0*/
4263 static gboolean
4264 force_shell_resize_idle(gpointer data)
4266 if (gui.mainwin != NULL
4267 && GTK_WIDGET_REALIZED(gui.mainwin)
4268 && GTK_WIDGET_VISIBLE(gui.mainwin))
4270 int width;
4271 int height;
4273 gtk_window_get_size(GTK_WINDOW(gui.mainwin), &width, &height);
4275 width -= get_menu_tool_width();
4276 height -= get_menu_tool_height();
4278 gui_resize_shell(width, height);
4281 resize_idle_installed = FALSE;
4282 return FALSE; /* don't call me again */
4284 #endif
4285 #endif /* HAVE_GTK2 */
4288 * Set the windows size.
4290 /*ARGSUSED2*/
4291 void
4292 gui_mch_set_shellsize(int width, int height,
4293 int min_width, int min_height,
4294 int base_width, int base_height,
4295 int direction)
4297 #ifndef HAVE_GTK2
4298 /* Hack: When the form already is at the desired size, the window might
4299 * have been resized with the mouse. Force a resize by setting a
4300 * different size first. */
4301 if (GTK_FORM(gui.formwin)->width == width
4302 && GTK_FORM(gui.formwin)->height == height)
4304 gtk_form_set_size(GTK_FORM(gui.formwin), width + 1, height + 1);
4305 gui_mch_update();
4307 gtk_form_set_size(GTK_FORM(gui.formwin), width, height);
4308 #endif
4310 /* give GTK+ a chance to put all widget's into place */
4311 gui_mch_update();
4313 #ifndef HAVE_GTK2
4314 /* this will cause the proper resizement to happen too */
4315 update_window_manager_hints(0, 0);
4317 #else /* HAVE_GTK2 */
4318 /* this will cause the proper resizement to happen too */
4319 if (gtk_socket_id == 0)
4320 update_window_manager_hints(0, 0);
4322 /* With GTK+ 2, changing the size of the form widget doesn't resize
4323 * the window. So let's do it the other way around and resize the
4324 * main window instead. */
4325 width += get_menu_tool_width();
4326 height += get_menu_tool_height();
4328 if (gtk_socket_id == 0)
4329 gtk_window_resize(GTK_WINDOW(gui.mainwin), width, height);
4330 else
4331 update_window_manager_hints(width, height);
4333 #if 0
4334 if (!resize_idle_installed)
4336 g_idle_add_full(GDK_PRIORITY_EVENTS + 10,
4337 &force_shell_resize_idle, NULL, NULL);
4338 resize_idle_installed = TRUE;
4340 #endif
4342 * Wait until all events are processed to prevent a crash because the
4343 * real size of the drawing area doesn't reflect Vim's internal ideas.
4345 * This is a bit of a hack, since Vim is a terminal application with a GUI
4346 * on top, while the GUI expects to be the boss.
4348 gui_mch_update();
4349 #endif
4354 * The screen size is used to make sure the initial window doesn't get bigger
4355 * than the screen. This subtracts some room for menubar, toolbar and window
4356 * decorations.
4358 void
4359 gui_mch_get_screen_dimensions(int *screen_w, int *screen_h)
4361 #ifdef HAVE_GTK_MULTIHEAD
4362 GdkScreen* screen;
4364 if (gui.mainwin != NULL && gtk_widget_has_screen(gui.mainwin))
4365 screen = gtk_widget_get_screen(gui.mainwin);
4366 else
4367 screen = gdk_screen_get_default();
4369 *screen_w = gdk_screen_get_width(screen);
4370 *screen_h = gdk_screen_get_height(screen) - p_ghr;
4371 #else
4372 *screen_w = gdk_screen_width();
4373 /* Subtract 'guiheadroom' from the height to allow some room for the
4374 * window manager (task list and window title bar). */
4375 *screen_h = gdk_screen_height() - p_ghr;
4376 #endif
4379 * FIXME: dirty trick: Because the gui_get_base_height() doesn't include
4380 * the toolbar and menubar for GTK, we subtract them from the screen
4381 * hight, so that the window size can be made to fit on the screen.
4382 * This should be completely changed later.
4384 *screen_w -= get_menu_tool_width();
4385 *screen_h -= get_menu_tool_height();
4388 #if defined(FEAT_TITLE) || defined(PROTO)
4389 /*ARGSUSED*/
4390 void
4391 gui_mch_settitle(char_u *title, char_u *icon)
4393 # ifdef HAVE_GTK2
4394 if (title != NULL && output_conv.vc_type != CONV_NONE)
4395 title = string_convert(&output_conv, title, NULL);
4396 # endif
4398 gtk_window_set_title(GTK_WINDOW(gui.mainwin), (const char *)title);
4400 # ifdef HAVE_GTK2
4401 if (output_conv.vc_type != CONV_NONE)
4402 vim_free(title);
4403 # endif
4405 #endif /* FEAT_TITLE */
4407 #if defined(FEAT_MENU) || defined(PROTO)
4408 void
4409 gui_mch_enable_menu(int showit)
4411 GtkWidget *widget;
4413 # ifdef FEAT_GUI_GNOME
4414 if (using_gnome)
4415 widget = gui.menubar_h;
4416 else
4417 # endif
4418 widget = gui.menubar;
4420 /* Do not disable the menu while starting up, otherwise F10 doesn't work. */
4421 if (!showit != !GTK_WIDGET_VISIBLE(widget) && !gui.starting)
4423 if (showit)
4424 gtk_widget_show(widget);
4425 else
4426 gtk_widget_hide(widget);
4428 update_window_manager_hints(0, 0);
4431 #endif /* FEAT_MENU */
4433 #if defined(FEAT_TOOLBAR) || defined(PROTO)
4434 void
4435 gui_mch_show_toolbar(int showit)
4437 GtkWidget *widget;
4439 if (gui.toolbar == NULL)
4440 return;
4442 # ifdef FEAT_GUI_GNOME
4443 if (using_gnome)
4444 widget = gui.toolbar_h;
4445 else
4446 # endif
4447 widget = gui.toolbar;
4449 if (showit)
4450 set_toolbar_style(GTK_TOOLBAR(gui.toolbar));
4452 if (!showit != !GTK_WIDGET_VISIBLE(widget))
4454 if (showit)
4455 gtk_widget_show(widget);
4456 else
4457 gtk_widget_hide(widget);
4459 update_window_manager_hints(0, 0);
4462 #endif /* FEAT_TOOLBAR */
4464 #ifndef HAVE_GTK2
4466 * Get a font structure for highlighting.
4467 * "cbdata" is a pointer to the global gui structure.
4469 /*ARGSUSED*/
4470 static void
4471 font_sel_ok(GtkWidget *wgt, gpointer cbdata)
4473 gui_T *vw = (gui_T *)cbdata;
4474 GtkFontSelectionDialog *fs = (GtkFontSelectionDialog *)vw->fontdlg;
4476 if (vw->fontname)
4477 g_free(vw->fontname);
4479 vw->fontname = (char_u *)gtk_font_selection_dialog_get_font_name(fs);
4480 gtk_widget_hide(vw->fontdlg);
4481 if (gtk_main_level() > 0)
4482 gtk_main_quit();
4485 /*ARGSUSED*/
4486 static void
4487 font_sel_cancel(GtkWidget *wgt, gpointer cbdata)
4489 gui_T *vw = (gui_T *)cbdata;
4491 gtk_widget_hide(vw->fontdlg);
4492 if (gtk_main_level() > 0)
4493 gtk_main_quit();
4496 /*ARGSUSED*/
4497 static void
4498 font_sel_destroy(GtkWidget *wgt, gpointer cbdata)
4500 gui_T *vw = (gui_T *)cbdata;
4502 vw->fontdlg = NULL;
4503 if (gtk_main_level() > 0)
4504 gtk_main_quit();
4506 #endif /* !HAVE_GTK2 */
4508 #ifdef HAVE_GTK2
4510 * Check if a given font is a CJK font. This is done in a very crude manner. It
4511 * just see if U+04E00 for zh and ja and U+AC00 for ko are covered in a given
4512 * font. Consequently, this function cannot be used as a general purpose check
4513 * for CJK-ness for which fontconfig APIs should be used. This is only used by
4514 * gui_mch_init_font() to deal with 'CJK fixed width fonts'.
4516 static int
4517 is_cjk_font(PangoFontDescription *font_desc)
4519 static const char * const cjk_langs[] =
4520 {"zh_CN", "zh_TW", "zh_HK", "ja", "ko"};
4522 PangoFont *font;
4523 unsigned i;
4524 int is_cjk = FALSE;
4526 font = pango_context_load_font(gui.text_context, font_desc);
4528 if (font == NULL)
4529 return FALSE;
4531 for (i = 0; !is_cjk && i < G_N_ELEMENTS(cjk_langs); ++i)
4533 PangoCoverage *coverage;
4534 gunichar uc;
4536 coverage = pango_font_get_coverage(
4537 font, pango_language_from_string(cjk_langs[i]));
4539 if (coverage != NULL)
4541 uc = (cjk_langs[i][0] == 'k') ? 0xAC00 : 0x4E00;
4542 is_cjk = (pango_coverage_get(coverage, uc) == PANGO_COVERAGE_EXACT);
4543 pango_coverage_unref(coverage);
4547 g_object_unref(font);
4549 return is_cjk;
4551 #endif /* HAVE_GTK2 */
4554 * Adjust gui.char_height (after 'linespace' was changed).
4557 gui_mch_adjust_charheight(void)
4559 #ifdef HAVE_GTK2
4560 PangoFontMetrics *metrics;
4561 int ascent;
4562 int descent;
4564 metrics = pango_context_get_metrics(gui.text_context, gui.norm_font,
4565 pango_context_get_language(gui.text_context));
4566 ascent = pango_font_metrics_get_ascent(metrics);
4567 descent = pango_font_metrics_get_descent(metrics);
4569 pango_font_metrics_unref(metrics);
4571 gui.char_height = (ascent + descent + PANGO_SCALE - 1) / PANGO_SCALE
4572 + p_linespace;
4573 /* LINTED: avoid warning: bitwise operation on signed value */
4574 gui.char_ascent = PANGO_PIXELS(ascent + p_linespace * PANGO_SCALE / 2);
4576 #else /* !HAVE_GTK2 */
4578 gui.char_height = gui.current_font->ascent + gui.current_font->descent
4579 + p_linespace;
4580 gui.char_ascent = gui.current_font->ascent + p_linespace / 2;
4582 #endif /* !HAVE_GTK2 */
4584 /* A not-positive value of char_height may crash Vim. Only happens
4585 * if 'linespace' is negative (which does make sense sometimes). */
4586 gui.char_ascent = MAX(gui.char_ascent, 0);
4587 gui.char_height = MAX(gui.char_height, gui.char_ascent + 1);
4589 return OK;
4592 #if defined(FEAT_XFONTSET) || defined(PROTO)
4594 * Try to load the requested fontset.
4596 /*ARGSUSED2*/
4597 GuiFontset
4598 gui_mch_get_fontset(char_u *name, int report_error, int fixed_width)
4600 GdkFont *font;
4602 if (!gui.in_use || name == NULL)
4603 return NOFONT;
4605 font = gdk_fontset_load((gchar *)name);
4607 if (font == NULL)
4609 if (report_error)
4610 EMSG2(_(e_fontset), name);
4611 return NOFONT;
4613 /* TODO: check if the font is fixed width. */
4615 /* reference this font as being in use */
4616 gdk_font_ref(font);
4618 return (GuiFontset)font;
4620 #endif /* FEAT_XFONTSET */
4622 #ifndef HAVE_GTK2
4624 * Put up a font dialog and return the selected font name in allocated memory.
4625 * "oldval" is the previous value.
4626 * Return NULL when cancelled.
4628 char_u *
4629 gui_mch_font_dialog(char_u *oldval)
4631 char_u *fontname = NULL;
4633 if (!gui.fontdlg)
4635 GtkFontSelectionDialog *fsd = NULL;
4637 gui.fontdlg = gtk_font_selection_dialog_new(_("Font Selection"));
4638 fsd = GTK_FONT_SELECTION_DIALOG(gui.fontdlg);
4639 gtk_window_set_modal(GTK_WINDOW(gui.fontdlg), TRUE);
4640 gtk_window_set_transient_for(GTK_WINDOW(gui.fontdlg),
4641 GTK_WINDOW(gui.mainwin));
4642 gtk_signal_connect(GTK_OBJECT(gui.fontdlg), "destroy",
4643 GTK_SIGNAL_FUNC(font_sel_destroy), &gui);
4644 gtk_signal_connect(GTK_OBJECT(fsd->ok_button), "clicked",
4645 GTK_SIGNAL_FUNC(font_sel_ok), &gui);
4646 gtk_signal_connect(GTK_OBJECT(fsd->cancel_button), "clicked",
4647 GTK_SIGNAL_FUNC(font_sel_cancel), &gui);
4650 if (oldval != NULL && *oldval != NUL)
4651 gtk_font_selection_dialog_set_font_name(
4652 GTK_FONT_SELECTION_DIALOG(gui.fontdlg), (char *)oldval);
4654 if (gui.fontname)
4656 g_free(gui.fontname);
4657 gui.fontname = NULL;
4659 gtk_window_position(GTK_WINDOW(gui.fontdlg), GTK_WIN_POS_MOUSE);
4660 gtk_widget_show(gui.fontdlg);
4662 static gchar *spacings[] = {"c", "m", NULL};
4664 /* In GTK 1.2.3 this must be after the gtk_widget_show() call,
4665 * otherwise everything is blocked for ten seconds. */
4666 gtk_font_selection_dialog_set_filter(
4667 GTK_FONT_SELECTION_DIALOG(gui.fontdlg),
4668 GTK_FONT_FILTER_BASE,
4669 GTK_FONT_ALL, NULL, NULL,
4670 NULL, NULL, spacings, NULL);
4673 /* Wait for the font dialog to be closed. */
4674 while (gui.fontdlg && GTK_WIDGET_DRAWABLE(gui.fontdlg))
4675 gtk_main_iteration_do(TRUE);
4677 if (gui.fontname != NULL)
4679 /* Apparently some font names include a comma, need to escape that,
4680 * because in 'guifont' it separates names. */
4681 fontname = vim_strsave_escaped(gui.fontname, (char_u *)",");
4682 g_free(gui.fontname);
4683 gui.fontname = NULL;
4685 return fontname;
4687 #endif /* !HAVE_GTK2 */
4689 #ifdef HAVE_GTK2
4691 * Put up a font dialog and return the selected font name in allocated memory.
4692 * "oldval" is the previous value. Return NULL when cancelled.
4693 * This should probably go into gui_gtk.c. Hmm.
4694 * FIXME:
4695 * The GTK2 font selection dialog has no filtering API. So we could either
4696 * a) implement our own (possibly copying the code from somewhere else) or
4697 * b) just live with it.
4699 char_u *
4700 gui_mch_font_dialog(char_u *oldval)
4702 GtkWidget *dialog;
4703 int response;
4704 char_u *fontname = NULL;
4705 char_u *oldname;
4707 dialog = gtk_font_selection_dialog_new(NULL);
4709 gtk_window_set_transient_for(GTK_WINDOW(dialog), GTK_WINDOW(gui.mainwin));
4710 gtk_window_set_destroy_with_parent(GTK_WINDOW(dialog), TRUE);
4712 if (oldval != NULL && oldval[0] != NUL)
4714 if (output_conv.vc_type != CONV_NONE)
4715 oldname = string_convert(&output_conv, oldval, NULL);
4716 else
4717 oldname = oldval;
4719 /* Annoying bug in GTK (or Pango): if the font name does not include a
4720 * size, zero is used. Use default point size ten. */
4721 if (!vim_isdigit(oldname[STRLEN(oldname) - 1]))
4723 char_u *p = vim_strnsave(oldname, STRLEN(oldname) + 3);
4725 if (p != NULL)
4727 STRCPY(p + STRLEN(p), " 10");
4728 if (oldname != oldval)
4729 vim_free(oldname);
4730 oldname = p;
4734 gtk_font_selection_dialog_set_font_name(
4735 GTK_FONT_SELECTION_DIALOG(dialog), (const char *)oldname);
4737 if (oldname != oldval)
4738 vim_free(oldname);
4741 response = gtk_dialog_run(GTK_DIALOG(dialog));
4743 if (response == GTK_RESPONSE_OK)
4745 char *name;
4747 name = gtk_font_selection_dialog_get_font_name(
4748 GTK_FONT_SELECTION_DIALOG(dialog));
4749 if (name != NULL)
4751 char_u *p;
4753 /* Apparently some font names include a comma, need to escape
4754 * that, because in 'guifont' it separates names. */
4755 p = vim_strsave_escaped((char_u *)name, (char_u *)",");
4756 g_free(name);
4757 if (p != NULL && input_conv.vc_type != CONV_NONE)
4759 fontname = string_convert(&input_conv, p, NULL);
4760 vim_free(p);
4762 else
4763 fontname = p;
4767 if (response != GTK_RESPONSE_NONE)
4768 gtk_widget_destroy(dialog);
4770 return fontname;
4774 * Some monospace fonts don't support a bold weight, and fall back
4775 * silently to the regular weight. But this is no good since our text
4776 * drawing function can emulate bold by overstriking. So let's try
4777 * to detect whether bold weight is actually available and emulate it
4778 * otherwise.
4780 * Note that we don't need to check for italic style since Xft can
4781 * emulate italic on its own, provided you have a proper fontconfig
4782 * setup. We wouldn't be able to emulate it in Vim anyway.
4784 static void
4785 get_styled_font_variants(void)
4787 PangoFontDescription *bold_font_desc;
4788 PangoFont *plain_font;
4789 PangoFont *bold_font;
4791 gui.font_can_bold = FALSE;
4793 plain_font = pango_context_load_font(gui.text_context, gui.norm_font);
4795 if (plain_font == NULL)
4796 return;
4798 bold_font_desc = pango_font_description_copy_static(gui.norm_font);
4799 pango_font_description_set_weight(bold_font_desc, PANGO_WEIGHT_BOLD);
4801 bold_font = pango_context_load_font(gui.text_context, bold_font_desc);
4803 * The comparison relies on the unique handle nature of a PangoFont*,
4804 * i.e. it's assumed that a different PangoFont* won't refer to the
4805 * same font. Seems to work, and failing here isn't critical anyway.
4807 if (bold_font != NULL)
4809 gui.font_can_bold = (bold_font != plain_font);
4810 g_object_unref(bold_font);
4813 pango_font_description_free(bold_font_desc);
4814 g_object_unref(plain_font);
4817 #else /* !HAVE_GTK2 */
4820 * There is only one excuse I can give for the following attempt to manage font
4821 * styles:
4823 * I HATE THE BRAIN DEAD WAY X11 IS HANDLING FONTS (--mdcki)
4824 * (Me too. --danielk)
4826 static void
4827 get_styled_font_variants(char_u * font_name)
4829 char *chunk[32];
4830 char *sdup;
4831 char *tmp;
4832 int len, i;
4833 GuiFont *styled_font[3];
4835 styled_font[0] = &gui.bold_font;
4836 styled_font[1] = &gui.ital_font;
4837 styled_font[2] = &gui.boldital_font;
4839 /* First free whatever was freviously there. */
4840 for (i = 0; i < 3; ++i)
4841 if (*styled_font[i])
4843 gdk_font_unref(*styled_font[i]);
4844 *styled_font[i] = NULL;
4847 if ((sdup = g_strdup((const char *)font_name)) == NULL)
4848 return;
4850 /* split up the whole */
4851 i = 0;
4852 for (tmp = sdup; *tmp != '\0'; ++tmp)
4854 if (*tmp == '-')
4856 *tmp = '\0';
4858 if (i == 32)
4859 break;
4861 chunk[i] = tmp + 1;
4862 ++i;
4866 if (i == 14)
4868 GdkFont *font = NULL;
4869 const char *bold_chunk[3] = { "bold", NULL, "bold" };
4870 const char *italic_chunk[3] = { NULL, "o", "o" };
4872 /* font name was complete */
4873 len = strlen((const char *)font_name) + 32;
4875 for (i = 0; i < 3; ++i)
4877 char *styled_name;
4878 int j;
4880 styled_name = (char *)alloc(len);
4881 if (styled_name == NULL)
4883 g_free(sdup);
4884 return;
4887 *styled_name = '\0';
4889 for (j = 0; j < 14; ++j)
4891 strcat(styled_name, "-");
4892 if (j == 2 && bold_chunk[i] != NULL)
4893 strcat(styled_name, bold_chunk[i]);
4894 else if (j == 3 && italic_chunk[i] != NULL)
4895 strcat(styled_name, italic_chunk[i]);
4896 else
4897 strcat(styled_name, chunk[j]);
4900 font = gui_mch_get_font((char_u *)styled_name, FALSE);
4901 if (font != NULL)
4902 *styled_font[i] = font;
4904 vim_free(styled_name);
4908 g_free(sdup);
4910 #endif /* !HAVE_GTK2 */
4912 #ifdef HAVE_GTK2
4913 static PangoEngineShape *default_shape_engine = NULL;
4916 * Create a map from ASCII characters in the range [32,126] to glyphs
4917 * of the current font. This is used by gui_gtk2_draw_string() to skip
4918 * the itemize and shaping process for the most common case.
4920 static void
4921 ascii_glyph_table_init(void)
4923 char_u ascii_chars[128];
4924 PangoAttrList *attr_list;
4925 GList *item_list;
4926 int i;
4928 if (gui.ascii_glyphs != NULL)
4929 pango_glyph_string_free(gui.ascii_glyphs);
4930 if (gui.ascii_font != NULL)
4931 g_object_unref(gui.ascii_font);
4933 gui.ascii_glyphs = NULL;
4934 gui.ascii_font = NULL;
4936 /* For safety, fill in question marks for the control characters. */
4937 for (i = 0; i < 32; ++i)
4938 ascii_chars[i] = '?';
4939 for (; i < 127; ++i)
4940 ascii_chars[i] = i;
4941 ascii_chars[i] = '?';
4943 attr_list = pango_attr_list_new();
4944 item_list = pango_itemize(gui.text_context, (const char *)ascii_chars,
4945 0, sizeof(ascii_chars), attr_list, NULL);
4947 if (item_list != NULL && item_list->next == NULL) /* play safe */
4949 PangoItem *item;
4950 int width;
4952 item = (PangoItem *)item_list->data;
4953 width = gui.char_width * PANGO_SCALE;
4955 /* Remember the shape engine used for ASCII. */
4956 default_shape_engine = item->analysis.shape_engine;
4958 gui.ascii_font = item->analysis.font;
4959 g_object_ref(gui.ascii_font);
4961 gui.ascii_glyphs = pango_glyph_string_new();
4963 pango_shape((const char *)ascii_chars, sizeof(ascii_chars),
4964 &item->analysis, gui.ascii_glyphs);
4966 g_return_if_fail(gui.ascii_glyphs->num_glyphs == sizeof(ascii_chars));
4968 for (i = 0; i < gui.ascii_glyphs->num_glyphs; ++i)
4970 PangoGlyphGeometry *geom;
4972 geom = &gui.ascii_glyphs->glyphs[i].geometry;
4973 geom->x_offset += MAX(0, width - geom->width) / 2;
4974 geom->width = width;
4978 g_list_foreach(item_list, (GFunc)&pango_item_free, NULL);
4979 g_list_free(item_list);
4980 pango_attr_list_unref(attr_list);
4982 #endif /* HAVE_GTK2 */
4985 * Initialize Vim to use the font or fontset with the given name.
4986 * Return FAIL if the font could not be loaded, OK otherwise.
4988 /*ARGSUSED1*/
4990 gui_mch_init_font(char_u *font_name, int fontset)
4992 #ifdef HAVE_GTK2
4993 PangoFontDescription *font_desc;
4994 PangoLayout *layout;
4995 int width;
4997 /* If font_name is NULL, this means to use the default, which should
4998 * be present on all proper Pango/fontconfig installations. */
4999 if (font_name == NULL)
5000 font_name = (char_u *)DEFAULT_FONT;
5002 font_desc = gui_mch_get_font(font_name, FALSE);
5004 if (font_desc == NULL)
5005 return FAIL;
5007 gui_mch_free_font(gui.norm_font);
5008 gui.norm_font = font_desc;
5010 pango_context_set_font_description(gui.text_context, font_desc);
5012 layout = pango_layout_new(gui.text_context);
5013 pango_layout_set_text(layout, "MW", 2);
5014 pango_layout_get_size(layout, &width, NULL);
5016 * Set char_width to half the width obtained from pango_layout_get_size()
5017 * for CJK fixed_width/bi-width fonts. An unpatched version of Xft leads
5018 * Pango to use the same width for both non-CJK characters (e.g. Latin
5019 * letters and numbers) and CJK characters. This results in 's p a c e d
5020 * o u t' rendering when a CJK 'fixed width' font is used. To work around
5021 * that, divide the width returned by Pango by 2 if cjk_width is equal to
5022 * width for CJK fonts.
5024 * For related bugs, see:
5025 * http://bugzilla.gnome.org/show_bug.cgi?id=106618
5026 * http://bugzilla.gnome.org/show_bug.cgi?id=106624
5028 * With this, for all four of the following cases, Vim works fine:
5029 * guifont=CJK_fixed_width_font
5030 * guifont=Non_CJK_fixed_font
5031 * guifont=Non_CJK_fixed_font,CJK_Fixed_font
5032 * guifont=Non_CJK_fixed_font guifontwide=CJK_fixed_font
5034 if (is_cjk_font(gui.norm_font))
5036 int cjk_width;
5038 /* Measure the text extent of U+4E00 and U+4E8C */
5039 pango_layout_set_text(layout, "\344\270\200\344\272\214", -1);
5040 pango_layout_get_size(layout, &cjk_width, NULL);
5042 if (width == cjk_width) /* Xft not patched */
5043 width /= 2;
5045 g_object_unref(layout);
5047 gui.char_width = (width / 2 + PANGO_SCALE - 1) / PANGO_SCALE;
5049 /* A zero width may cause a crash. Happens for semi-invalid fontsets. */
5050 if (gui.char_width <= 0)
5051 gui.char_width = 8;
5053 gui_mch_adjust_charheight();
5055 /* Set the fontname, which will be used for information purposes */
5056 hl_set_font_name(font_name);
5058 get_styled_font_variants();
5059 ascii_glyph_table_init();
5061 /* Avoid unnecessary overhead if 'guifontwide' is equal to 'guifont'. */
5062 if (gui.wide_font != NULL
5063 && pango_font_description_equal(gui.norm_font, gui.wide_font))
5065 pango_font_description_free(gui.wide_font);
5066 gui.wide_font = NULL;
5069 #else /* !HAVE_GTK2 */
5071 GdkFont *font = NULL;
5073 # ifdef FEAT_XFONTSET
5074 /* Try loading a fontset. If this fails we try loading a normal font. */
5075 if (fontset && font_name != NULL)
5076 font = gui_mch_get_fontset(font_name, TRUE, TRUE);
5078 if (font == NULL)
5079 # endif
5081 /* If font_name is NULL, this means to use the default, which should
5082 * be present on all X11 servers. */
5083 if (font_name == NULL)
5084 font_name = (char_u *)DEFAULT_FONT;
5085 font = gui_mch_get_font(font_name, FALSE);
5088 if (font == NULL)
5089 return FAIL;
5091 gui_mch_free_font(gui.norm_font);
5092 # ifdef FEAT_XFONTSET
5093 gui_mch_free_fontset(gui.fontset);
5094 if (font->type == GDK_FONT_FONTSET)
5096 gui.norm_font = NOFONT;
5097 gui.fontset = (GuiFontset)font;
5098 /* Use two bytes, this works around the problem that the result would
5099 * be zero if no 8-bit font was found. */
5100 gui.char_width = gdk_string_width(font, "xW") / 2;
5102 else
5103 # endif
5105 gui.norm_font = font;
5106 # ifdef FEAT_XFONTSET
5107 gui.fontset = NOFONTSET;
5108 # endif
5109 gui.char_width = ((XFontStruct *)
5110 GDK_FONT_XFONT(font))->max_bounds.width;
5113 /* A zero width may cause a crash. Happens for semi-invalid fontsets. */
5114 if (gui.char_width <= 0)
5115 gui.char_width = 8;
5117 gui.char_height = font->ascent + font->descent + p_linespace;
5118 gui.char_ascent = font->ascent + p_linespace / 2;
5120 /* A not-positive value of char_height may crash Vim. Only happens
5121 * if 'linespace' is negative (which does make sense sometimes). */
5122 gui.char_ascent = MAX(gui.char_ascent, 0);
5123 gui.char_height = MAX(gui.char_height, gui.char_ascent + 1);
5125 /* Set the fontname, which will be used for information purposes */
5126 hl_set_font_name(font_name);
5128 if (font->type != GDK_FONT_FONTSET)
5129 get_styled_font_variants(font_name);
5131 /* Synchronize the fonts used in user input dialogs, since otherwise
5132 * search/replace will be esp. annoying in case of international font
5133 * usage.
5135 gui_gtk_synch_fonts();
5137 # ifdef FEAT_XIM
5138 /* Adjust input management behaviour to the capabilities of the new
5139 * fontset */
5140 xim_decide_input_style();
5141 if (xim_get_status_area_height())
5143 /* Status area is required. Just create the empty container so that
5144 * mainwin will allocate the extra space for status area. */
5145 GtkWidget *alignment = gtk_alignment_new((gfloat)0.5, (gfloat)0.5,
5146 (gfloat)1.0, (gfloat)1.0);
5148 gtk_widget_set_usize(alignment, 20, gui.char_height + 2);
5149 gtk_box_pack_end(GTK_BOX(GTK_BIN(gui.mainwin)->child),
5150 alignment, FALSE, FALSE, 0);
5151 gtk_widget_show(alignment);
5153 # endif
5154 #endif /* !HAVE_GTK2 */
5156 /* Preserve the logical dimensions of the screen. */
5157 update_window_manager_hints(0, 0);
5159 return OK;
5163 * Get a reference to the font "name".
5164 * Return zero for failure.
5166 GuiFont
5167 gui_mch_get_font(char_u *name, int report_error)
5169 #ifdef HAVE_GTK2
5170 PangoFontDescription *font;
5171 #else
5172 GdkFont *font;
5173 #endif
5175 /* can't do this when GUI is not running */
5176 if (!gui.in_use || name == NULL)
5177 return NULL;
5179 #ifdef HAVE_GTK2
5180 if (output_conv.vc_type != CONV_NONE)
5182 char_u *buf;
5184 buf = string_convert(&output_conv, name, NULL);
5185 if (buf != NULL)
5187 font = pango_font_description_from_string((const char *)buf);
5188 vim_free(buf);
5190 else
5191 font = NULL;
5193 else
5194 font = pango_font_description_from_string((const char *)name);
5196 if (font != NULL)
5198 PangoFont *real_font;
5200 /* pango_context_load_font() bails out if no font size is set */
5201 if (pango_font_description_get_size(font) <= 0)
5202 pango_font_description_set_size(font, 10 * PANGO_SCALE);
5204 real_font = pango_context_load_font(gui.text_context, font);
5206 if (real_font == NULL)
5208 pango_font_description_free(font);
5209 font = NULL;
5211 else
5212 g_object_unref(real_font);
5214 #else
5215 font = gdk_font_load((const gchar *)name);
5216 #endif
5218 if (font == NULL)
5220 if (report_error)
5221 EMSG2(_(e_font), name);
5222 return NULL;
5225 #ifdef HAVE_GTK2
5227 * The fixed-width check has been disabled for GTK+ 2. Rationale:
5229 * - The check tends to report false positives, particularly
5230 * in non-Latin locales or with old X fonts.
5231 * - Thanks to our fixed-width hack in gui_gtk2_draw_string(),
5232 * GTK+ 2 Vim is actually capable of displaying variable width
5233 * fonts. Those will just be spaced out like in AA xterm.
5234 * - Failing here for the default font causes GUI startup to fail
5235 * even with wiped out configuration files.
5236 * - The font dialog displays all fonts unfiltered, and it's rather
5237 * annoying if 95% of the listed fonts produce an error message.
5239 # if 0
5241 /* Check that this is a mono-spaced font. Naturally, this is a bit
5242 * hackish -- fixed-width isn't really suitable for i18n text :/ */
5243 PangoLayout *layout;
5244 unsigned int i;
5245 int last_width = -1;
5246 const char test_chars[] = { 'W', 'i', ',', 'x' }; /* arbitrary */
5248 layout = pango_layout_new(gui.text_context);
5249 pango_layout_set_font_description(layout, font);
5251 for (i = 0; i < G_N_ELEMENTS(test_chars); ++i)
5253 int width;
5255 pango_layout_set_text(layout, &test_chars[i], 1);
5256 pango_layout_get_size(layout, &width, NULL);
5258 if (last_width >= 0 && width != last_width)
5260 pango_font_description_free(font);
5261 font = NULL;
5262 break;
5265 last_width = width;
5268 g_object_unref(layout);
5270 # endif
5271 #else /* !HAVE_GTK2 */
5273 XFontStruct *xfont;
5275 /* reference this font as being in use */
5276 gdk_font_ref(font);
5278 /* Check that this is a mono-spaced font.
5280 xfont = (XFontStruct *) GDK_FONT_XFONT(font);
5282 if (xfont->max_bounds.width != xfont->min_bounds.width)
5284 gdk_font_unref(font);
5285 font = NULL;
5288 #endif /* !HAVE_GTK2 */
5290 #if !defined(HAVE_GTK2) || 0 /* disabled for GTK+ 2, see above */
5291 if (font == NULL && report_error)
5292 EMSG2(_(e_fontwidth), name);
5293 #endif
5295 return font;
5298 #if defined(FEAT_EVAL) || defined(PROTO)
5300 * Return the name of font "font" in allocated memory.
5302 /*ARGSUSED*/
5303 char_u *
5304 gui_mch_get_fontname(GuiFont font, char_u *name)
5306 # ifdef HAVE_GTK2
5307 if (font != NOFONT)
5309 char *pangoname = pango_font_description_to_string(font);
5311 if (pangoname != NULL)
5313 char_u *s = vim_strsave((char_u *)pangoname);
5315 g_free(pangoname);
5316 return s;
5319 # else
5320 /* Don't know how to get the name, return what we got. */
5321 if (name != NULL)
5322 return vim_strsave(name);
5323 # endif
5324 return NULL;
5326 #endif
5328 #if !defined(HAVE_GTK2) || defined(PROTO)
5330 * Set the current text font.
5331 * Since we create all GC on demand, we use just gui.current_font to
5332 * indicate the desired current font.
5334 void
5335 gui_mch_set_font(GuiFont font)
5337 gui.current_font = font;
5339 #endif
5341 #if defined(FEAT_XFONTSET) || defined(PROTO)
5343 * Set the current text fontset.
5345 void
5346 gui_mch_set_fontset(GuiFontset fontset)
5348 gui.current_font = fontset;
5350 #endif
5353 * If a font is not going to be used, free its structure.
5355 void
5356 gui_mch_free_font(GuiFont font)
5358 if (font != NOFONT)
5359 #ifdef HAVE_GTK2
5360 pango_font_description_free(font);
5361 #else
5362 gdk_font_unref(font);
5363 #endif
5366 #if defined(FEAT_XFONTSET) || defined(PROTO)
5368 * If a fontset is not going to be used, free its structure.
5370 void
5371 gui_mch_free_fontset(GuiFontset fontset)
5373 if (fontset != NOFONTSET)
5374 gdk_font_unref(fontset);
5376 #endif
5380 * Return the Pixel value (color) for the given color name. This routine was
5381 * pretty much taken from example code in the Silicon Graphics OSF/Motif
5382 * Programmer's Guide.
5383 * Return INVALCOLOR for error.
5385 guicolor_T
5386 gui_mch_get_color(char_u *name)
5388 /* A number of colors that some X11 systems don't have */
5389 static const char *const vimnames[][2] =
5391 {"LightRed", "#FFBBBB"},
5392 {"LightGreen", "#88FF88"},
5393 {"LightMagenta","#FFBBFF"},
5394 {"DarkCyan", "#008888"},
5395 {"DarkBlue", "#0000BB"},
5396 {"DarkRed", "#BB0000"},
5397 {"DarkMagenta", "#BB00BB"},
5398 {"DarkGrey", "#BBBBBB"},
5399 {"DarkYellow", "#BBBB00"},
5400 {"Gray10", "#1A1A1A"},
5401 {"Grey10", "#1A1A1A"},
5402 {"Gray20", "#333333"},
5403 {"Grey20", "#333333"},
5404 {"Gray30", "#4D4D4D"},
5405 {"Grey30", "#4D4D4D"},
5406 {"Gray40", "#666666"},
5407 {"Grey40", "#666666"},
5408 {"Gray50", "#7F7F7F"},
5409 {"Grey50", "#7F7F7F"},
5410 {"Gray60", "#999999"},
5411 {"Grey60", "#999999"},
5412 {"Gray70", "#B3B3B3"},
5413 {"Grey70", "#B3B3B3"},
5414 {"Gray80", "#CCCCCC"},
5415 {"Grey80", "#CCCCCC"},
5416 {"Gray90", "#E5E5E5"},
5417 {"Grey90", "#E5E5E5"},
5418 {NULL, NULL}
5421 if (!gui.in_use) /* can't do this when GUI not running */
5422 return INVALCOLOR;
5424 while (name != NULL)
5426 GdkColor color;
5427 int parsed;
5428 int i;
5430 parsed = gdk_color_parse((const char *)name, &color);
5432 #ifndef HAVE_GTK2 /* ohh, lovely GTK+ 2, eases our pain :) */
5434 * Since we have already called gtk_set_locale here the bugger
5435 * XParseColor will accept only explicit color names in the language
5436 * of the current locale. However this will interfere with:
5437 * 1. Vim's global startup files
5438 * 2. Explicit color names in .vimrc
5440 * Therefore we first try to parse the color in the current locale and
5441 * if it fails, we fall back to the portable "C" one.
5443 if (!parsed)
5445 char *current;
5447 current = setlocale(LC_ALL, NULL);
5448 if (current != NULL)
5450 char *saved;
5452 saved = g_strdup(current);
5453 setlocale(LC_ALL, "C");
5455 parsed = gdk_color_parse((const gchar *)name, &color);
5457 setlocale(LC_ALL, saved);
5458 gtk_set_locale();
5460 g_free(saved);
5463 #endif /* !HAVE_GTK2 */
5465 if (parsed)
5467 #ifdef HAVE_GTK2
5468 gdk_colormap_alloc_color(gtk_widget_get_colormap(gui.drawarea),
5469 &color, FALSE, TRUE);
5470 #else
5471 gdk_color_alloc(gtk_widget_get_colormap(gui.drawarea), &color);
5472 #endif
5473 return (guicolor_T)color.pixel;
5475 /* add a few builtin names and try again */
5476 for (i = 0; ; ++i)
5478 if (vimnames[i][0] == NULL)
5480 name = NULL;
5481 break;
5483 if (STRICMP(name, vimnames[i][0]) == 0)
5485 name = (char_u *)vimnames[i][1];
5486 break;
5491 return INVALCOLOR;
5495 * Set the current text foreground color.
5497 void
5498 gui_mch_set_fg_color(guicolor_T color)
5500 gui.fgcolor->pixel = (unsigned long)color;
5504 * Set the current text background color.
5506 void
5507 gui_mch_set_bg_color(guicolor_T color)
5509 gui.bgcolor->pixel = (unsigned long)color;
5513 * Set the current text special color.
5515 void
5516 gui_mch_set_sp_color(guicolor_T color)
5518 gui.spcolor->pixel = (unsigned long)color;
5521 #ifdef HAVE_GTK2
5523 * Function-like convenience macro for the sake of efficiency.
5525 #define INSERT_PANGO_ATTR(Attribute, AttrList, Start, End) \
5526 G_STMT_START{ \
5527 PangoAttribute *tmp_attr_; \
5528 tmp_attr_ = (Attribute); \
5529 tmp_attr_->start_index = (Start); \
5530 tmp_attr_->end_index = (End); \
5531 pango_attr_list_insert((AttrList), tmp_attr_); \
5532 }G_STMT_END
5534 static void
5535 apply_wide_font_attr(char_u *s, int len, PangoAttrList *attr_list)
5537 char_u *start = NULL;
5538 char_u *p;
5539 int uc;
5541 for (p = s; p < s + len; p += utf_byte2len(*p))
5543 uc = utf_ptr2char(p);
5545 if (start == NULL)
5547 if (uc >= 0x80 && utf_char2cells(uc) == 2)
5548 start = p;
5550 else if (uc < 0x80 /* optimization shortcut */
5551 || (utf_char2cells(uc) != 2 && !utf_iscomposing(uc)))
5553 INSERT_PANGO_ATTR(pango_attr_font_desc_new(gui.wide_font),
5554 attr_list, start - s, p - s);
5555 start = NULL;
5559 if (start != NULL)
5560 INSERT_PANGO_ATTR(pango_attr_font_desc_new(gui.wide_font),
5561 attr_list, start - s, len);
5564 static int
5565 count_cluster_cells(char_u *s, PangoItem *item,
5566 PangoGlyphString* glyphs, int i,
5567 int *cluster_width,
5568 int *last_glyph_rbearing)
5570 char_u *p;
5571 int next; /* glyph start index of next cluster */
5572 int start, end; /* string segment of current cluster */
5573 int width; /* real cluster width in Pango units */
5574 int uc;
5575 int cellcount = 0;
5577 width = glyphs->glyphs[i].geometry.width;
5579 for (next = i + 1; next < glyphs->num_glyphs; ++next)
5581 if (glyphs->glyphs[next].attr.is_cluster_start)
5582 break;
5583 else if (glyphs->glyphs[next].geometry.width > width)
5584 width = glyphs->glyphs[next].geometry.width;
5587 start = item->offset + glyphs->log_clusters[i];
5588 end = item->offset + ((next < glyphs->num_glyphs) ?
5589 glyphs->log_clusters[next] : item->length);
5591 for (p = s + start; p < s + end; p += utf_byte2len(*p))
5593 uc = utf_ptr2char(p);
5594 if (uc < 0x80)
5595 ++cellcount;
5596 else if (!utf_iscomposing(uc))
5597 cellcount += utf_char2cells(uc);
5600 if (last_glyph_rbearing != NULL
5601 && cellcount > 0 && next == glyphs->num_glyphs)
5603 PangoRectangle ink_rect;
5605 * If a certain combining mark had to be taken from a non-monospace
5606 * font, we have to compensate manually by adapting x_offset according
5607 * to the ink extents of the previous glyph.
5609 pango_font_get_glyph_extents(item->analysis.font,
5610 glyphs->glyphs[i].glyph,
5611 &ink_rect, NULL);
5613 if (PANGO_RBEARING(ink_rect) > 0)
5614 *last_glyph_rbearing = PANGO_RBEARING(ink_rect);
5617 if (cellcount > 0)
5618 *cluster_width = width;
5620 return cellcount;
5624 * If there are only combining characters in the cluster, we cannot just
5625 * change the width of the previous glyph since there is none. Therefore
5626 * some guesswork is needed.
5628 * If ink_rect.x is negative Pango apparently has taken care of the composing
5629 * by itself. Actually setting x_offset = 0 should be sufficient then, but due
5630 * to problems with composing from different fonts we still need to fine-tune
5631 * x_offset to avoid uglyness.
5633 * If ink_rect.x is not negative, force overstriking by pointing x_offset to
5634 * the position of the previous glyph. Apparently this happens only with old
5635 * X fonts which don't provide the special combining information needed by
5636 * Pango.
5638 static void
5639 setup_zero_width_cluster(PangoItem *item, PangoGlyphInfo *glyph,
5640 int last_cellcount, int last_cluster_width,
5641 int last_glyph_rbearing)
5643 PangoRectangle ink_rect;
5644 PangoRectangle logical_rect;
5645 int width;
5647 width = last_cellcount * gui.char_width * PANGO_SCALE;
5648 glyph->geometry.x_offset = -width + MAX(0, width - last_cluster_width) / 2;
5649 glyph->geometry.width = 0;
5651 pango_font_get_glyph_extents(item->analysis.font,
5652 glyph->glyph,
5653 &ink_rect, &logical_rect);
5654 if (ink_rect.x < 0)
5656 glyph->geometry.x_offset += last_glyph_rbearing;
5657 glyph->geometry.y_offset = logical_rect.height
5658 - (gui.char_height - p_linespace) * PANGO_SCALE;
5662 static void
5663 draw_glyph_string(int row, int col, int num_cells, int flags,
5664 PangoFont *font, PangoGlyphString *glyphs)
5666 if (!(flags & DRAW_TRANSP))
5668 gdk_gc_set_foreground(gui.text_gc, gui.bgcolor);
5670 gdk_draw_rectangle(gui.drawarea->window,
5671 gui.text_gc,
5672 TRUE,
5673 FILL_X(col),
5674 FILL_Y(row),
5675 num_cells * gui.char_width,
5676 gui.char_height);
5679 gdk_gc_set_foreground(gui.text_gc, gui.fgcolor);
5681 gdk_draw_glyphs(gui.drawarea->window,
5682 gui.text_gc,
5683 font,
5684 TEXT_X(col),
5685 TEXT_Y(row),
5686 glyphs);
5688 /* redraw the contents with an offset of 1 to emulate bold */
5689 if ((flags & DRAW_BOLD) && !gui.font_can_bold)
5690 gdk_draw_glyphs(gui.drawarea->window,
5691 gui.text_gc,
5692 font,
5693 TEXT_X(col) + 1,
5694 TEXT_Y(row),
5695 glyphs);
5698 #endif /* HAVE_GTK2 */
5701 * Draw underline and undercurl at the bottom of the character cell.
5703 static void
5704 draw_under(int flags, int row, int col, int cells)
5706 int i;
5707 int offset;
5708 const static int val[8] = {1, 0, 0, 0, 1, 2, 2, 2 };
5709 int y = FILL_Y(row + 1) - 1;
5711 /* Undercurl: draw curl at the bottom of the character cell. */
5712 if (flags & DRAW_UNDERC)
5714 gdk_gc_set_foreground(gui.text_gc, gui.spcolor);
5715 for (i = FILL_X(col); i < FILL_X(col + cells); ++i)
5717 offset = val[i % 8];
5718 gdk_draw_point(gui.drawarea->window, gui.text_gc, i, y - offset);
5720 gdk_gc_set_foreground(gui.text_gc, gui.fgcolor);
5723 /* Underline: draw a line at the bottom of the character cell. */
5724 if (flags & DRAW_UNDERL)
5726 /* When p_linespace is 0, overwrite the bottom row of pixels.
5727 * Otherwise put the line just below the character. */
5728 if (p_linespace > 1)
5729 y -= p_linespace - 1;
5730 gdk_draw_line(gui.drawarea->window, gui.text_gc,
5731 FILL_X(col), y,
5732 FILL_X(col + cells) - 1, y);
5736 #if defined(HAVE_GTK2) || defined(PROTO)
5738 gui_gtk2_draw_string(int row, int col, char_u *s, int len, int flags)
5740 GdkRectangle area; /* area for clip mask */
5741 PangoGlyphString *glyphs; /* glyphs of current item */
5742 int column_offset = 0; /* column offset in cells */
5743 int i;
5744 char_u *conv_buf = NULL; /* result of UTF-8 conversion */
5745 char_u *new_conv_buf;
5746 int convlen;
5747 char_u *sp, *bp;
5748 int plen;
5750 if (gui.text_context == NULL || gui.drawarea->window == NULL)
5751 return len;
5753 if (output_conv.vc_type != CONV_NONE)
5756 * Convert characters from 'encoding' to 'termencoding', which is set
5757 * to UTF-8 by gui_mch_init(). did_set_string_option() in option.c
5758 * prohibits changing this to something else than UTF-8 if the GUI is
5759 * in use.
5761 convlen = len;
5762 conv_buf = string_convert(&output_conv, s, &convlen);
5763 g_return_val_if_fail(conv_buf != NULL, len);
5765 /* Correct for differences in char width: some chars are
5766 * double-wide in 'encoding' but single-wide in utf-8. Add a space to
5767 * compensate for that. */
5768 for (sp = s, bp = conv_buf; sp < s + len && bp < conv_buf + convlen; )
5770 plen = utf_ptr2len(bp);
5771 if ((*mb_ptr2cells)(sp) == 2 && utf_ptr2cells(bp) == 1)
5773 new_conv_buf = alloc(convlen + 2);
5774 if (new_conv_buf == NULL)
5775 return len;
5776 plen += bp - conv_buf;
5777 mch_memmove(new_conv_buf, conv_buf, plen);
5778 new_conv_buf[plen] = ' ';
5779 mch_memmove(new_conv_buf + plen + 1, conv_buf + plen,
5780 convlen - plen + 1);
5781 vim_free(conv_buf);
5782 conv_buf = new_conv_buf;
5783 ++convlen;
5784 bp = conv_buf + plen;
5785 plen = 1;
5787 sp += (*mb_ptr2len)(sp);
5788 bp += plen;
5790 s = conv_buf;
5791 len = convlen;
5795 * Restrict all drawing to the current screen line in order to prevent
5796 * fuzzy font lookups from messing up the screen.
5798 area.x = gui.border_offset;
5799 area.y = FILL_Y(row);
5800 area.width = gui.num_cols * gui.char_width;
5801 area.height = gui.char_height;
5803 gdk_gc_set_clip_origin(gui.text_gc, 0, 0);
5804 gdk_gc_set_clip_rectangle(gui.text_gc, &area);
5806 glyphs = pango_glyph_string_new();
5809 * Optimization hack: If possible, skip the itemize and shaping process
5810 * for pure ASCII strings. This optimization is particularly effective
5811 * because Vim draws space characters to clear parts of the screen.
5813 if (!(flags & DRAW_ITALIC)
5814 && !((flags & DRAW_BOLD) && gui.font_can_bold)
5815 && gui.ascii_glyphs != NULL)
5817 char_u *p;
5819 for (p = s; p < s + len; ++p)
5820 if (*p & 0x80)
5821 goto not_ascii;
5823 pango_glyph_string_set_size(glyphs, len);
5825 for (i = 0; i < len; ++i)
5827 glyphs->glyphs[i] = gui.ascii_glyphs->glyphs[s[i]];
5828 glyphs->log_clusters[i] = i;
5831 draw_glyph_string(row, col, len, flags, gui.ascii_font, glyphs);
5833 column_offset = len;
5835 else
5836 not_ascii:
5838 PangoAttrList *attr_list;
5839 GList *item_list;
5840 int cluster_width;
5841 int last_glyph_rbearing;
5842 int cells = 0; /* cells occupied by current cluster */
5843 #if 0
5844 int monospace13 = STRICMP(p_guifont, "monospace 13") == 0;
5845 #endif
5847 /* Safety check: pango crashes when invoked with invalid utf-8
5848 * characters. */
5849 if (!utf_valid_string(s, s + len))
5851 column_offset = len;
5852 goto skipitall;
5855 /* original width of the current cluster */
5856 cluster_width = PANGO_SCALE * gui.char_width;
5858 /* right bearing of the last non-composing glyph */
5859 last_glyph_rbearing = PANGO_SCALE * gui.char_width;
5861 attr_list = pango_attr_list_new();
5863 /* If 'guifontwide' is set then use that for double-width characters.
5864 * Otherwise just go with 'guifont' and let Pango do its thing. */
5865 if (gui.wide_font != NULL)
5866 apply_wide_font_attr(s, len, attr_list);
5868 if ((flags & DRAW_BOLD) && gui.font_can_bold)
5869 INSERT_PANGO_ATTR(pango_attr_weight_new(PANGO_WEIGHT_BOLD),
5870 attr_list, 0, len);
5871 if (flags & DRAW_ITALIC)
5872 INSERT_PANGO_ATTR(pango_attr_style_new(PANGO_STYLE_ITALIC),
5873 attr_list, 0, len);
5875 * Break the text into segments with consistent directional level
5876 * and shaping engine. Pure Latin text needs only a single segment,
5877 * so there's no need to worry about the loop's efficiency. Better
5878 * try to optimize elsewhere, e.g. reducing exposes and stuff :)
5880 item_list = pango_itemize(gui.text_context,
5881 (const char *)s, 0, len, attr_list, NULL);
5883 while (item_list != NULL)
5885 PangoItem *item;
5886 int item_cells = 0; /* item length in cells */
5888 item = (PangoItem *)item_list->data;
5889 item_list = g_list_delete_link(item_list, item_list);
5891 * Increment the bidirectional embedding level by 1 if it is not
5892 * even. An odd number means the output will be RTL, but we don't
5893 * want that since Vim handles right-to-left text on its own. It
5894 * would probably be sufficient to just set level = 0, but you can
5895 * never know :)
5897 * Unfortunately we can't take advantage of Pango's ability to
5898 * render both LTR and RTL at the same time. In order to support
5899 * that, Vim's main screen engine would have to make use of Pango
5900 * functionality.
5902 item->analysis.level = (item->analysis.level + 1) & (~1U);
5904 /* HACK: Overrule the shape engine, we don't want shaping to be
5905 * done, because drawing the cursor would change the display. */
5906 item->analysis.shape_engine = default_shape_engine;
5908 pango_shape((const char *)s + item->offset, item->length,
5909 &item->analysis, glyphs);
5911 * Fixed-width hack: iterate over the array and assign a fixed
5912 * width to each glyph, thus overriding the choice made by the
5913 * shaping engine. We use utf_char2cells() to determine the
5914 * number of cells needed.
5916 * Also perform all kind of dark magic to get composing
5917 * characters right (and pretty too of course).
5919 for (i = 0; i < glyphs->num_glyphs; ++i)
5921 PangoGlyphInfo *glyph;
5923 glyph = &glyphs->glyphs[i];
5925 if (glyph->attr.is_cluster_start)
5927 int cellcount;
5929 cellcount = count_cluster_cells(
5930 s, item, glyphs, i, &cluster_width,
5931 (item_list != NULL) ? &last_glyph_rbearing : NULL);
5933 if (cellcount > 0)
5935 int width;
5937 width = cellcount * gui.char_width * PANGO_SCALE;
5938 glyph->geometry.x_offset +=
5939 MAX(0, width - cluster_width) / 2;
5940 glyph->geometry.width = width;
5942 else
5944 /* If there are only combining characters in the
5945 * cluster, we cannot just change the width of the
5946 * previous glyph since there is none. Therefore
5947 * some guesswork is needed. */
5948 setup_zero_width_cluster(item, glyph, cells,
5949 cluster_width,
5950 last_glyph_rbearing);
5953 item_cells += cellcount;
5954 cells = cellcount;
5956 else if (i > 0)
5958 int width;
5960 /* There is a previous glyph, so we deal with combining
5961 * characters the canonical way. That is, setting the
5962 * width of the previous glyph to 0. */
5963 glyphs->glyphs[i - 1].geometry.width = 0;
5964 width = cells * gui.char_width * PANGO_SCALE;
5965 glyph->geometry.x_offset +=
5966 MAX(0, width - cluster_width) / 2;
5967 #if 0
5968 /* Dirty hack: for "monospace 13" font there is a bug that
5969 * draws composing chars in the wrong position. Add
5970 * "width" to the offset to work around that. */
5971 if (monospace13)
5972 glyph->geometry.x_offset = width;
5973 #endif
5975 glyph->geometry.width = width;
5977 else /* i == 0 "cannot happen" */
5979 glyph->geometry.width = 0;
5983 /*** Aaaaand action! ***/
5984 draw_glyph_string(row, col + column_offset, item_cells,
5985 flags, item->analysis.font, glyphs);
5987 pango_item_free(item);
5989 column_offset += item_cells;
5992 pango_attr_list_unref(attr_list);
5995 skipitall:
5996 /* Draw underline and undercurl. */
5997 draw_under(flags, row, col, column_offset);
5999 pango_glyph_string_free(glyphs);
6000 vim_free(conv_buf);
6002 gdk_gc_set_clip_rectangle(gui.text_gc, NULL);
6004 return column_offset;
6006 #endif /* HAVE_GTK2 */
6008 #if !defined(HAVE_GTK2) || defined(PROTO)
6009 void
6010 gui_mch_draw_string(int row, int col, char_u *s, int len, int flags)
6012 static XChar2b *buf = NULL;
6013 static int buflen = 0;
6014 int is_wide;
6015 XChar2b *text;
6016 int textlen;
6017 XFontStruct *xfont;
6018 char_u *p;
6019 # ifdef FEAT_MBYTE
6020 unsigned c;
6021 # endif
6022 int width;
6024 if (gui.current_font == NULL || gui.drawarea->window == NULL)
6025 return;
6028 * Yeah yeah apparently the font support in GTK+ 1.2 only cares for either:
6029 * asians or 8-bit fonts. It is broken there, but no wonder the whole font
6030 * stuff is broken in X11 in first place. And the internationalization API
6031 * isn't something you would really like to use.
6034 xfont = (XFontStruct *)((GdkFontPrivate*)gui.current_font)->xfont;
6035 is_wide = ((xfont->min_byte1 != 0 || xfont->max_byte1 != 0)
6036 # ifdef FEAT_XFONTSET
6037 && gui.fontset == NOFONTSET
6038 # endif
6041 if (is_wide)
6043 /* Convert a byte sequence to 16 bit characters for the Gdk functions.
6044 * Need a buffer for the 16 bit characters. Keep it between calls,
6045 * because allocating it each time is slow. */
6046 if (buflen < len)
6048 XtFree((char *)buf);
6049 buf = (XChar2b *)XtMalloc(len * sizeof(XChar2b));
6050 buflen = len;
6053 p = s;
6054 textlen = 0;
6055 width = 0;
6056 while (p < s + len)
6058 # ifdef FEAT_MBYTE
6059 if (enc_utf8)
6061 c = utf_ptr2char(p);
6062 if (c >= 0x10000) /* show chars > 0xffff as ? */
6063 c = 0xbf;
6064 buf[textlen].byte1 = c >> 8;
6065 buf[textlen].byte2 = c;
6066 p += utf_ptr2len(p);
6067 width += utf_char2cells(c);
6069 else
6070 # endif
6072 buf[textlen].byte1 = '\0'; /* high eight bits */
6073 buf[textlen].byte2 = *p; /* low eight bits */
6074 ++p;
6075 ++width;
6077 ++textlen;
6079 text = buf;
6080 textlen = textlen * 2;
6082 else
6084 text = (XChar2b *)s;
6085 textlen = len;
6086 # ifdef FEAT_MBYTE
6087 if (has_mbyte)
6089 width = 0;
6090 for (p = s; p < s + len; p += (*mb_ptr2len)(p))
6091 width += (*mb_ptr2cells)(p);
6093 else
6094 # endif
6095 width = len;
6098 if (!(flags & DRAW_TRANSP))
6100 gdk_gc_set_foreground(gui.text_gc, gui.bgcolor);
6101 gdk_draw_rectangle(gui.drawarea->window,
6102 gui.text_gc,
6103 TRUE,
6104 FILL_X(col), FILL_Y(row),
6105 width * gui.char_width, gui.char_height);
6107 gdk_gc_set_foreground(gui.text_gc, gui.fgcolor);
6108 gdk_draw_text(gui.drawarea->window,
6109 gui.current_font,
6110 gui.text_gc,
6111 TEXT_X(col), TEXT_Y(row),
6112 (const gchar *)text, textlen);
6114 /* redraw the contents with an offset of 1 to emulate bold */
6115 if (flags & DRAW_BOLD)
6116 gdk_draw_text(gui.drawarea->window,
6117 gui.current_font,
6118 gui.text_gc,
6119 TEXT_X(col) + 1, TEXT_Y(row),
6120 (const gchar *)text, textlen);
6122 /* Draw underline and undercurl. */
6123 draw_under(flags, row, col, width);
6125 #endif /* !HAVE_GTK2 */
6128 * Return OK if the key with the termcap name "name" is supported.
6131 gui_mch_haskey(char_u *name)
6133 int i;
6135 for (i = 0; special_keys[i].key_sym != 0; i++)
6136 if (name[0] == special_keys[i].code0
6137 && name[1] == special_keys[i].code1)
6138 return OK;
6139 return FAIL;
6142 #if defined(FEAT_TITLE) \
6143 || (defined(FEAT_XIM) && !defined(HAVE_GTK2)) \
6144 || defined(PROTO)
6146 * Return the text window-id and display. Only required for X-based GUI's
6149 gui_get_x11_windis(Window *win, Display **dis)
6151 if (gui.mainwin != NULL && gui.mainwin->window != NULL)
6153 *dis = GDK_WINDOW_XDISPLAY(gui.mainwin->window);
6154 *win = GDK_WINDOW_XWINDOW(gui.mainwin->window);
6155 return OK;
6158 *dis = NULL;
6159 *win = 0;
6160 return FAIL;
6162 #endif
6164 #if defined(FEAT_CLIENTSERVER) \
6165 || (defined(FEAT_X11) && defined(FEAT_CLIPBOARD)) || defined(PROTO)
6167 Display *
6168 gui_mch_get_display(void)
6170 if (gui.mainwin != NULL && gui.mainwin->window != NULL)
6171 return GDK_WINDOW_XDISPLAY(gui.mainwin->window);
6172 else
6173 return NULL;
6175 #endif
6177 void
6178 gui_mch_beep(void)
6180 #ifdef HAVE_GTK_MULTIHEAD
6181 GdkDisplay *display;
6183 if (gui.mainwin != NULL && GTK_WIDGET_REALIZED(gui.mainwin))
6184 display = gtk_widget_get_display(gui.mainwin);
6185 else
6186 display = gdk_display_get_default();
6188 if (display != NULL)
6189 gdk_display_beep(display);
6190 #else
6191 gdk_beep();
6192 #endif
6195 void
6196 gui_mch_flash(int msec)
6198 GdkGCValues values;
6199 GdkGC *invert_gc;
6201 if (gui.drawarea->window == NULL)
6202 return;
6204 values.foreground.pixel = gui.norm_pixel ^ gui.back_pixel;
6205 values.background.pixel = gui.norm_pixel ^ gui.back_pixel;
6206 values.function = GDK_XOR;
6207 invert_gc = gdk_gc_new_with_values(gui.drawarea->window,
6208 &values,
6209 GDK_GC_FOREGROUND |
6210 GDK_GC_BACKGROUND |
6211 GDK_GC_FUNCTION);
6212 gdk_gc_set_exposures(invert_gc,
6213 gui.visibility != GDK_VISIBILITY_UNOBSCURED);
6215 * Do a visual beep by changing back and forth in some undetermined way,
6216 * the foreground and background colors. This is due to the fact that
6217 * there can't be really any prediction about the effects of XOR on
6218 * arbitrary X11 servers. However this seems to be enough for what we
6219 * intend it to do.
6221 gdk_draw_rectangle(gui.drawarea->window, invert_gc,
6222 TRUE,
6223 0, 0,
6224 FILL_X((int)Columns) + gui.border_offset,
6225 FILL_Y((int)Rows) + gui.border_offset);
6227 gui_mch_flush();
6228 ui_delay((long)msec, TRUE); /* wait so many msec */
6230 gdk_draw_rectangle(gui.drawarea->window, invert_gc,
6231 TRUE,
6232 0, 0,
6233 FILL_X((int)Columns) + gui.border_offset,
6234 FILL_Y((int)Rows) + gui.border_offset);
6236 gdk_gc_destroy(invert_gc);
6240 * Invert a rectangle from row r, column c, for nr rows and nc columns.
6242 void
6243 gui_mch_invert_rectangle(int r, int c, int nr, int nc)
6245 GdkGCValues values;
6246 GdkGC *invert_gc;
6248 if (gui.drawarea->window == NULL)
6249 return;
6251 values.foreground.pixel = gui.norm_pixel ^ gui.back_pixel;
6252 values.background.pixel = gui.norm_pixel ^ gui.back_pixel;
6253 values.function = GDK_XOR;
6254 invert_gc = gdk_gc_new_with_values(gui.drawarea->window,
6255 &values,
6256 GDK_GC_FOREGROUND |
6257 GDK_GC_BACKGROUND |
6258 GDK_GC_FUNCTION);
6259 gdk_gc_set_exposures(invert_gc, gui.visibility !=
6260 GDK_VISIBILITY_UNOBSCURED);
6261 gdk_draw_rectangle(gui.drawarea->window, invert_gc,
6262 TRUE,
6263 FILL_X(c), FILL_Y(r),
6264 (nc) * gui.char_width, (nr) * gui.char_height);
6265 gdk_gc_destroy(invert_gc);
6269 * Iconify the GUI window.
6271 void
6272 gui_mch_iconify(void)
6274 #ifdef HAVE_GTK2
6275 gtk_window_iconify(GTK_WINDOW(gui.mainwin));
6276 #else
6277 XIconifyWindow(GDK_WINDOW_XDISPLAY(gui.mainwin->window),
6278 GDK_WINDOW_XWINDOW(gui.mainwin->window),
6279 DefaultScreen(GDK_WINDOW_XDISPLAY(gui.mainwin->window)));
6280 #endif
6283 #if defined(FEAT_EVAL) || defined(PROTO)
6285 * Bring the Vim window to the foreground.
6287 void
6288 gui_mch_set_foreground(void)
6290 # ifdef HAVE_GTK2
6291 gtk_window_present(GTK_WINDOW(gui.mainwin));
6292 # else
6293 gdk_window_raise(gui.mainwin->window);
6294 # endif
6296 #endif
6299 * Draw a cursor without focus.
6301 void
6302 gui_mch_draw_hollow_cursor(guicolor_T color)
6304 int i = 1;
6306 if (gui.drawarea->window == NULL)
6307 return;
6309 gui_mch_set_fg_color(color);
6311 gdk_gc_set_foreground(gui.text_gc, gui.fgcolor);
6312 #ifdef FEAT_MBYTE
6313 if (mb_lefthalve(gui.row, gui.col))
6314 i = 2;
6315 #endif
6316 gdk_draw_rectangle(gui.drawarea->window, gui.text_gc,
6317 FALSE,
6318 FILL_X(gui.col), FILL_Y(gui.row),
6319 i * gui.char_width - 1, gui.char_height - 1);
6323 * Draw part of a cursor, "w" pixels wide, and "h" pixels high, using
6324 * color "color".
6326 void
6327 gui_mch_draw_part_cursor(int w, int h, guicolor_T color)
6329 if (gui.drawarea->window == NULL)
6330 return;
6332 gui_mch_set_fg_color(color);
6334 gdk_gc_set_foreground(gui.text_gc, gui.fgcolor);
6335 gdk_draw_rectangle(gui.drawarea->window, gui.text_gc,
6336 TRUE,
6337 #ifdef FEAT_RIGHTLEFT
6338 /* vertical line should be on the right of current point */
6339 CURSOR_BAR_RIGHT ? FILL_X(gui.col + 1) - w :
6340 #endif
6341 FILL_X(gui.col),
6342 FILL_Y(gui.row) + gui.char_height - h,
6343 w, h);
6348 * Catch up with any queued X11 events. This may put keyboard input into the
6349 * input buffer, call resize call-backs, trigger timers etc. If there is
6350 * nothing in the X11 event queue (& no timers pending), then we return
6351 * immediately.
6353 void
6354 gui_mch_update(void)
6356 while (gtk_events_pending() && !vim_is_input_buf_full())
6357 gtk_main_iteration_do(FALSE);
6360 static gint
6361 input_timer_cb(gpointer data)
6363 int *timed_out = (int *) data;
6365 /* Just inform the caller about the occurrence of it */
6366 *timed_out = TRUE;
6368 if (gtk_main_level() > 0)
6369 gtk_main_quit();
6371 return FALSE; /* don't happen again */
6374 #ifdef FEAT_SNIFF
6376 * Callback function, used when data is available on the SNiFF connection.
6378 /* ARGSUSED */
6379 static void
6380 sniff_request_cb(
6381 gpointer data,
6382 gint source_fd,
6383 GdkInputCondition condition)
6385 static char_u bytes[3] = {CSI, (int)KS_EXTRA, (int)KE_SNIFF};
6387 add_to_input_buf(bytes, 3);
6389 if (gtk_main_level() > 0)
6390 gtk_main_quit();
6392 #endif
6395 * GUI input routine called by gui_wait_for_chars(). Waits for a character
6396 * from the keyboard.
6397 * wtime == -1 Wait forever.
6398 * wtime == 0 This should never happen.
6399 * wtime > 0 Wait wtime milliseconds for a character.
6400 * Returns OK if a character was found to be available within the given time,
6401 * or FAIL otherwise.
6404 gui_mch_wait_for_chars(long wtime)
6406 int focus;
6407 guint timer;
6408 static int timed_out;
6409 #ifdef FEAT_SNIFF
6410 static int sniff_on = 0;
6411 static gint sniff_input_id = 0;
6412 #endif
6414 #ifdef FEAT_SNIFF
6415 if (sniff_on && !want_sniff_request)
6417 if (sniff_input_id)
6418 gdk_input_remove(sniff_input_id);
6419 sniff_on = 0;
6421 else if (!sniff_on && want_sniff_request)
6423 /* Add fd_from_sniff to watch for available data in main loop. */
6424 sniff_input_id = gdk_input_add(fd_from_sniff,
6425 GDK_INPUT_READ, sniff_request_cb, NULL);
6426 sniff_on = 1;
6428 #endif
6430 timed_out = FALSE;
6432 /* this timeout makes sure that we will return if no characters arrived in
6433 * time */
6435 if (wtime > 0)
6436 timer = gtk_timeout_add((guint32)wtime, input_timer_cb, &timed_out);
6437 else
6438 timer = 0;
6440 focus = gui.in_focus;
6444 /* Stop or start blinking when focus changes */
6445 if (gui.in_focus != focus)
6447 if (gui.in_focus)
6448 gui_mch_start_blink();
6449 else
6450 gui_mch_stop_blink();
6451 focus = gui.in_focus;
6455 * Loop in GTK+ processing until a timeout or input occurs.
6456 * Skip this if input is available anyway (can happen in rare
6457 * situations, sort of race condition).
6459 if (!input_available())
6460 gtk_main();
6462 /* Got char, return immediately */
6463 if (input_available())
6465 if (timer != 0 && !timed_out)
6466 gtk_timeout_remove(timer);
6467 return OK;
6469 } while (wtime < 0 || !timed_out);
6472 * Flush all eventually pending (drawing) events.
6474 gui_mch_update();
6476 return FAIL;
6480 /****************************************************************************
6481 * Output drawing routines.
6482 ****************************************************************************/
6485 /* Flush any output to the screen */
6486 void
6487 gui_mch_flush(void)
6489 #ifdef HAVE_GTK_MULTIHEAD
6490 if (gui.mainwin != NULL && GTK_WIDGET_REALIZED(gui.mainwin))
6491 gdk_display_sync(gtk_widget_get_display(gui.mainwin));
6492 #else
6493 gdk_flush(); /* historical misnomer: calls XSync(), not XFlush() */
6494 #endif
6495 #ifdef HAVE_GTK2
6496 /* This happens to actually do what gui_mch_flush() is supposed to do,
6497 * according to the comment above. */
6498 if (gui.drawarea != NULL && gui.drawarea->window != NULL)
6499 gdk_window_process_updates(gui.drawarea->window, FALSE);
6500 #endif
6504 * Clear a rectangular region of the screen from text pos (row1, col1) to
6505 * (row2, col2) inclusive.
6507 void
6508 gui_mch_clear_block(int row1, int col1, int row2, int col2)
6510 GdkColor color;
6512 if (gui.drawarea->window == NULL)
6513 return;
6515 color.pixel = gui.back_pixel;
6517 gdk_gc_set_foreground(gui.text_gc, &color);
6519 /* Clear one extra pixel at the far right, for when bold characters have
6520 * spilled over to the window border. */
6521 gdk_draw_rectangle(gui.drawarea->window, gui.text_gc, TRUE,
6522 FILL_X(col1), FILL_Y(row1),
6523 (col2 - col1 + 1) * gui.char_width
6524 + (col2 == Columns - 1),
6525 (row2 - row1 + 1) * gui.char_height);
6528 void
6529 gui_mch_clear_all(void)
6531 if (gui.drawarea->window != NULL)
6532 gdk_window_clear(gui.drawarea->window);
6536 * Redraw any text revealed by scrolling up/down.
6538 static void
6539 check_copy_area(void)
6541 GdkEvent *event;
6542 int expose_count;
6544 if (gui.visibility != GDK_VISIBILITY_PARTIAL)
6545 return;
6547 /* Avoid redrawing the cursor while scrolling or it'll end up where
6548 * we don't want it to be. I'm not sure if it's correct to call
6549 * gui_dont_update_cursor() at this point but it works as a quick
6550 * fix for now. */
6551 gui_dont_update_cursor();
6555 /* Wait to check whether the scroll worked or not. */
6556 event = gdk_event_get_graphics_expose(gui.drawarea->window);
6558 if (event == NULL)
6559 break; /* received NoExpose event */
6561 gui_redraw(event->expose.area.x, event->expose.area.y,
6562 event->expose.area.width, event->expose.area.height);
6564 expose_count = event->expose.count;
6565 gdk_event_free(event);
6567 while (expose_count > 0); /* more events follow */
6569 gui_can_update_cursor();
6573 * Delete the given number of lines from the given row, scrolling up any
6574 * text further down within the scroll region.
6576 void
6577 gui_mch_delete_lines(int row, int num_lines)
6579 if (gui.visibility == GDK_VISIBILITY_FULLY_OBSCURED)
6580 return; /* Can't see the window */
6582 gdk_gc_set_foreground(gui.text_gc, gui.fgcolor);
6583 gdk_gc_set_background(gui.text_gc, gui.bgcolor);
6585 /* copy one extra pixel, for when bold has spilled over */
6586 gdk_window_copy_area(gui.drawarea->window, gui.text_gc,
6587 FILL_X(gui.scroll_region_left), FILL_Y(row),
6588 gui.drawarea->window,
6589 FILL_X(gui.scroll_region_left),
6590 FILL_Y(row + num_lines),
6591 gui.char_width * (gui.scroll_region_right
6592 - gui.scroll_region_left + 1) + 1,
6593 gui.char_height * (gui.scroll_region_bot - row - num_lines + 1));
6595 gui_clear_block(gui.scroll_region_bot - num_lines + 1,
6596 gui.scroll_region_left,
6597 gui.scroll_region_bot, gui.scroll_region_right);
6598 check_copy_area();
6602 * Insert the given number of lines before the given row, scrolling down any
6603 * following text within the scroll region.
6605 void
6606 gui_mch_insert_lines(int row, int num_lines)
6608 if (gui.visibility == GDK_VISIBILITY_FULLY_OBSCURED)
6609 return; /* Can't see the window */
6611 gdk_gc_set_foreground(gui.text_gc, gui.fgcolor);
6612 gdk_gc_set_background(gui.text_gc, gui.bgcolor);
6614 /* copy one extra pixel, for when bold has spilled over */
6615 gdk_window_copy_area(gui.drawarea->window, gui.text_gc,
6616 FILL_X(gui.scroll_region_left), FILL_Y(row + num_lines),
6617 gui.drawarea->window,
6618 FILL_X(gui.scroll_region_left), FILL_Y(row),
6619 gui.char_width * (gui.scroll_region_right
6620 - gui.scroll_region_left + 1) + 1,
6621 gui.char_height * (gui.scroll_region_bot - row - num_lines + 1));
6623 gui_clear_block(row, gui.scroll_region_left,
6624 row + num_lines - 1, gui.scroll_region_right);
6625 check_copy_area();
6629 * X Selection stuff, for cutting and pasting text to other windows.
6631 void
6632 clip_mch_request_selection(VimClipboard *cbd)
6634 GdkAtom target;
6635 unsigned i;
6636 int nbytes;
6637 char_u *buffer;
6639 for (i = 0; i < N_SELECTION_TARGETS; ++i)
6641 received_selection = RS_NONE;
6642 target = gdk_atom_intern(selection_targets[i].target, FALSE);
6644 gtk_selection_convert(gui.drawarea,
6645 cbd->gtk_sel_atom, target,
6646 (guint32)GDK_CURRENT_TIME);
6648 while (received_selection == RS_NONE)
6649 gtk_main(); /* wait for selection_received_cb */
6651 if (received_selection != RS_FAIL)
6652 return;
6655 /* Final fallback position - use the X CUT_BUFFER0 store */
6656 nbytes = 0;
6657 buffer = (char_u *)XFetchBuffer(GDK_WINDOW_XDISPLAY(gui.mainwin->window),
6658 &nbytes, 0);
6659 if (nbytes > 0)
6661 /* Got something */
6662 clip_yank_selection(MCHAR, buffer, (long)nbytes, cbd);
6663 if (p_verbose > 0)
6665 verbose_enter();
6666 smsg((char_u *)_("Used CUT_BUFFER0 instead of empty selection"));
6667 verbose_leave();
6670 if (buffer != NULL)
6671 XFree(buffer);
6675 * Disown the selection.
6677 /*ARGSUSED*/
6678 void
6679 clip_mch_lose_selection(VimClipboard *cbd)
6681 /* WEIRD: when using NULL to actually disown the selection, we lose the
6682 * selection the first time we own it. */
6684 gtk_selection_owner_set(NULL, cbd->gtk_sel_atom, (guint32)GDK_CURRENT_TIME);
6685 gui_mch_update();
6690 * Own the selection and return OK if it worked.
6693 clip_mch_own_selection(VimClipboard *cbd)
6695 int success;
6697 success = gtk_selection_owner_set(gui.drawarea, cbd->gtk_sel_atom,
6698 (guint32)GDK_CURRENT_TIME);
6699 gui_mch_update();
6700 return (success) ? OK : FAIL;
6704 * Send the current selection to the clipboard. Do nothing for X because we
6705 * will fill in the selection only when requested by another app.
6707 /*ARGSUSED*/
6708 void
6709 clip_mch_set_selection(VimClipboard *cbd)
6714 #if defined(FEAT_MENU) || defined(PROTO)
6716 * Make a menu item appear either active or not active (grey or not grey).
6718 void
6719 gui_mch_menu_grey(vimmenu_T *menu, int grey)
6721 if (menu->id == NULL)
6722 return;
6724 if (menu_is_separator(menu->name))
6725 grey = TRUE;
6727 gui_mch_menu_hidden(menu, FALSE);
6728 /* Be clever about bitfields versus true booleans here! */
6729 if (!GTK_WIDGET_SENSITIVE(menu->id) == !grey)
6731 gtk_widget_set_sensitive(menu->id, !grey);
6732 gui_mch_update();
6737 * Make menu item hidden or not hidden.
6739 void
6740 gui_mch_menu_hidden(vimmenu_T *menu, int hidden)
6742 if (menu->id == 0)
6743 return;
6745 if (hidden)
6747 if (GTK_WIDGET_VISIBLE(menu->id))
6749 gtk_widget_hide(menu->id);
6750 gui_mch_update();
6753 else
6755 if (!GTK_WIDGET_VISIBLE(menu->id))
6757 gtk_widget_show(menu->id);
6758 gui_mch_update();
6764 * This is called after setting all the menus to grey/hidden or not.
6766 void
6767 gui_mch_draw_menubar(void)
6769 /* just make sure that the visual changes get effect immediately */
6770 gui_mch_update();
6772 #endif /* FEAT_MENU */
6775 * Scrollbar stuff.
6777 void
6778 gui_mch_enable_scrollbar(scrollbar_T *sb, int flag)
6780 if (sb->id == NULL)
6781 return;
6783 if (flag)
6784 gtk_widget_show(sb->id);
6785 else
6786 gtk_widget_hide(sb->id);
6788 update_window_manager_hints(0, 0);
6793 * Return the RGB value of a pixel as long.
6795 long_u
6796 gui_mch_get_rgb(guicolor_T pixel)
6798 GdkColor color;
6799 #ifndef HAVE_GTK2
6800 GdkColorContext *cc;
6802 cc = gdk_color_context_new(gtk_widget_get_visual(gui.drawarea),
6803 gtk_widget_get_colormap(gui.drawarea));
6804 color.pixel = pixel;
6805 gdk_color_context_query_color(cc, &color);
6807 gdk_color_context_free(cc);
6808 #else
6809 gdk_colormap_query_color(gtk_widget_get_colormap(gui.drawarea),
6810 (unsigned long)pixel, &color);
6811 #endif
6813 return (((unsigned)color.red & 0xff00) << 8)
6814 | ((unsigned)color.green & 0xff00)
6815 | (((unsigned)color.blue & 0xff00) >> 8);
6819 * Get current mouse coordinates in text window.
6821 void
6822 gui_mch_getmouse(int *x, int *y)
6824 gdk_window_get_pointer(gui.drawarea->window, x, y, NULL);
6827 void
6828 gui_mch_setmouse(int x, int y)
6830 /* Sorry for the Xlib call, but we can't avoid it, since there is no
6831 * internal GDK mechanism present to accomplish this. (and for good
6832 * reason...) */
6833 XWarpPointer(GDK_WINDOW_XDISPLAY(gui.drawarea->window),
6834 (Window)0, GDK_WINDOW_XWINDOW(gui.drawarea->window),
6835 0, 0, 0U, 0U, x, y);
6839 #ifdef FEAT_MOUSESHAPE
6840 /* The last set mouse pointer shape is remembered, to be used when it goes
6841 * from hidden to not hidden. */
6842 static int last_shape = 0;
6843 #endif
6846 * Use the blank mouse pointer or not.
6848 * hide: TRUE = use blank ptr, FALSE = use parent ptr
6850 void
6851 gui_mch_mousehide(int hide)
6853 if (gui.pointer_hidden != hide)
6855 gui.pointer_hidden = hide;
6856 if (gui.drawarea->window && gui.blank_pointer != NULL)
6858 if (hide)
6859 gdk_window_set_cursor(gui.drawarea->window, gui.blank_pointer);
6860 else
6861 #ifdef FEAT_MOUSESHAPE
6862 mch_set_mouse_shape(last_shape);
6863 #else
6864 gdk_window_set_cursor(gui.drawarea->window, NULL);
6865 #endif
6870 #if defined(FEAT_MOUSESHAPE) || defined(PROTO)
6872 /* Table for shape IDs. Keep in sync with the mshape_names[] table in
6873 * misc2.c! */
6874 static const int mshape_ids[] =
6876 GDK_LEFT_PTR, /* arrow */
6877 GDK_CURSOR_IS_PIXMAP, /* blank */
6878 GDK_XTERM, /* beam */
6879 GDK_SB_V_DOUBLE_ARROW, /* updown */
6880 GDK_SIZING, /* udsizing */
6881 GDK_SB_H_DOUBLE_ARROW, /* leftright */
6882 GDK_SIZING, /* lrsizing */
6883 GDK_WATCH, /* busy */
6884 GDK_X_CURSOR, /* no */
6885 GDK_CROSSHAIR, /* crosshair */
6886 GDK_HAND1, /* hand1 */
6887 GDK_HAND2, /* hand2 */
6888 GDK_PENCIL, /* pencil */
6889 GDK_QUESTION_ARROW, /* question */
6890 GDK_RIGHT_PTR, /* right-arrow */
6891 GDK_CENTER_PTR, /* up-arrow */
6892 GDK_LEFT_PTR /* last one */
6895 void
6896 mch_set_mouse_shape(int shape)
6898 int id;
6899 GdkCursor *c;
6901 if (gui.drawarea->window == NULL)
6902 return;
6904 if (shape == MSHAPE_HIDE || gui.pointer_hidden)
6905 gdk_window_set_cursor(gui.drawarea->window, gui.blank_pointer);
6906 else
6908 if (shape >= MSHAPE_NUMBERED)
6910 id = shape - MSHAPE_NUMBERED;
6911 if (id >= GDK_LAST_CURSOR)
6912 id = GDK_LEFT_PTR;
6913 else
6914 id &= ~1; /* they are always even (why?) */
6916 else if (shape < sizeof(mshape_ids) / sizeof(int))
6917 id = mshape_ids[shape];
6918 else
6919 return;
6920 # ifdef HAVE_GTK_MULTIHEAD
6921 c = gdk_cursor_new_for_display(
6922 gtk_widget_get_display(gui.drawarea), (GdkCursorType)id);
6923 # else
6924 c = gdk_cursor_new((GdkCursorType)id);
6925 # endif
6926 gdk_window_set_cursor(gui.drawarea->window, c);
6927 gdk_cursor_destroy(c); /* Unref, actually. Bloody GTK+ 1. */
6929 if (shape != MSHAPE_HIDE)
6930 last_shape = shape;
6932 #endif /* FEAT_MOUSESHAPE */
6935 #if defined(FEAT_SIGN_ICONS) || defined(PROTO)
6937 * Signs are currently always 2 chars wide. With GTK+ 2, the image will be
6938 * scaled down if the current font is not big enough, or scaled up if the image
6939 * size is less than 3/4 of the maximum sign size. With GTK+ 1, the pixmap
6940 * will be cut off if the current font is not big enough, or centered if it's
6941 * too small.
6943 # define SIGN_WIDTH (2 * gui.char_width)
6944 # define SIGN_HEIGHT (gui.char_height)
6945 # define SIGN_ASPECT ((double)SIGN_HEIGHT / (double)SIGN_WIDTH)
6947 # ifdef HAVE_GTK2
6949 void
6950 gui_mch_drawsign(int row, int col, int typenr)
6952 GdkPixbuf *sign;
6954 sign = (GdkPixbuf *)sign_get_image(typenr);
6956 if (sign != NULL && gui.drawarea != NULL && gui.drawarea->window != NULL)
6958 int width;
6959 int height;
6960 int xoffset;
6961 int yoffset;
6962 int need_scale;
6964 width = gdk_pixbuf_get_width(sign);
6965 height = gdk_pixbuf_get_height(sign);
6967 * Decide whether we need to scale. Allow one pixel of border
6968 * width to be cut off, in order to avoid excessive scaling for
6969 * tiny differences in font size.
6971 need_scale = (width > SIGN_WIDTH + 2
6972 || height > SIGN_HEIGHT + 2
6973 || (width < 3 * SIGN_WIDTH / 4
6974 && height < 3 * SIGN_HEIGHT / 4));
6975 if (need_scale)
6977 double aspect;
6979 /* Keep the original aspect ratio */
6980 aspect = (double)height / (double)width;
6981 width = (double)SIGN_WIDTH * SIGN_ASPECT / aspect;
6982 width = MIN(width, SIGN_WIDTH);
6983 height = (double)width * aspect;
6985 /* This doesn't seem to be worth caching, and doing so
6986 * would complicate the code quite a bit. */
6987 sign = gdk_pixbuf_scale_simple(sign, width, height,
6988 GDK_INTERP_BILINEAR);
6989 if (sign == NULL)
6990 return; /* out of memory */
6993 /* The origin is the upper-left corner of the pixmap. Therefore
6994 * these offset may become negative if the pixmap is smaller than
6995 * the 2x1 cells reserved for the sign icon. */
6996 xoffset = (width - SIGN_WIDTH) / 2;
6997 yoffset = (height - SIGN_HEIGHT) / 2;
6999 gdk_gc_set_foreground(gui.text_gc, gui.bgcolor);
7001 gdk_draw_rectangle(gui.drawarea->window,
7002 gui.text_gc,
7003 TRUE,
7004 FILL_X(col),
7005 FILL_Y(row),
7006 SIGN_WIDTH,
7007 SIGN_HEIGHT);
7009 # if GTK_CHECK_VERSION(2,1,1)
7010 gdk_draw_pixbuf(gui.drawarea->window,
7011 NULL,
7012 sign,
7013 MAX(0, xoffset),
7014 MAX(0, yoffset),
7015 FILL_X(col) - MIN(0, xoffset),
7016 FILL_Y(row) - MIN(0, yoffset),
7017 MIN(width, SIGN_WIDTH),
7018 MIN(height, SIGN_HEIGHT),
7019 GDK_RGB_DITHER_NORMAL,
7020 0, 0);
7021 # else
7022 gdk_pixbuf_render_to_drawable_alpha(sign,
7023 gui.drawarea->window,
7024 MAX(0, xoffset),
7025 MAX(0, yoffset),
7026 FILL_X(col) - MIN(0, xoffset),
7027 FILL_Y(row) - MIN(0, yoffset),
7028 MIN(width, SIGN_WIDTH),
7029 MIN(height, SIGN_HEIGHT),
7030 GDK_PIXBUF_ALPHA_BILEVEL,
7031 127,
7032 GDK_RGB_DITHER_NORMAL,
7033 0, 0);
7034 # endif
7035 if (need_scale)
7036 g_object_unref(sign);
7040 void *
7041 gui_mch_register_sign(char_u *signfile)
7043 if (signfile[0] != NUL && signfile[0] != '-' && gui.in_use)
7045 GdkPixbuf *sign;
7046 GError *error = NULL;
7047 char_u *message;
7049 sign = gdk_pixbuf_new_from_file((const char *)signfile, &error);
7051 if (error == NULL)
7052 return sign;
7054 message = (char_u *)error->message;
7056 if (message != NULL && input_conv.vc_type != CONV_NONE)
7057 message = string_convert(&input_conv, message, NULL);
7059 if (message != NULL)
7061 /* The error message is already translated and will be more
7062 * descriptive than anything we could possibly do ourselves. */
7063 EMSG2("E255: %s", message);
7065 if (input_conv.vc_type != CONV_NONE)
7066 vim_free(message);
7068 g_error_free(error);
7071 return NULL;
7074 void
7075 gui_mch_destroy_sign(void *sign)
7077 if (sign != NULL)
7078 g_object_unref(sign);
7081 # else /* !HAVE_GTK2 */
7083 typedef struct
7085 GdkPixmap *pixmap;
7086 GdkBitmap *mask;
7088 signicon_T;
7090 void
7091 gui_mch_drawsign(int row, int col, int typenr)
7093 signicon_T *sign;
7095 sign = (signicon_T *)sign_get_image(typenr);
7097 if (sign != NULL && sign->pixmap != NULL
7098 && gui.drawarea != NULL && gui.drawarea->window != NULL)
7100 int width;
7101 int height;
7102 int xoffset;
7103 int yoffset;
7105 gdk_window_get_size(sign->pixmap, &width, &height);
7107 /* The origin is the upper-left corner of the pixmap. Therefore
7108 * these offset may become negative if the pixmap is smaller than
7109 * the 2x1 cells reserved for the sign icon. */
7110 xoffset = (width - SIGN_WIDTH) / 2;
7111 yoffset = (height - SIGN_HEIGHT) / 2;
7113 gdk_gc_set_foreground(gui.text_gc, gui.bgcolor);
7115 gdk_draw_rectangle(gui.drawarea->window,
7116 gui.text_gc,
7117 TRUE,
7118 FILL_X(col),
7119 FILL_Y(row),
7120 SIGN_WIDTH,
7121 SIGN_HEIGHT);
7123 /* Set the clip mask for bilevel transparency */
7124 if (sign->mask != NULL)
7126 gdk_gc_set_clip_origin(gui.text_gc,
7127 FILL_X(col) - xoffset,
7128 FILL_Y(row) - yoffset);
7129 gdk_gc_set_clip_mask(gui.text_gc, sign->mask);
7132 gdk_draw_pixmap(gui.drawarea->window,
7133 gui.text_gc,
7134 sign->pixmap,
7135 MAX(0, xoffset),
7136 MAX(0, yoffset),
7137 FILL_X(col) - MIN(0, xoffset),
7138 FILL_Y(row) - MIN(0, yoffset),
7139 MIN(width, SIGN_WIDTH),
7140 MIN(height, SIGN_HEIGHT));
7142 gdk_gc_set_clip_mask(gui.text_gc, NULL);
7146 void *
7147 gui_mch_register_sign(char_u *signfile)
7149 signicon_T *sign = NULL;
7151 if (signfile[0] != NUL && signfile[0] != '-'
7152 && gui.drawarea != NULL && gui.drawarea->window != NULL)
7154 sign = (signicon_T *)alloc(sizeof(signicon_T));
7156 if (sign != NULL) /* NULL == OOM == "cannot really happen" */
7158 sign->mask = NULL;
7159 sign->pixmap = gdk_pixmap_colormap_create_from_xpm(
7160 gui.drawarea->window, NULL,
7161 &sign->mask, NULL,
7162 (const char *)signfile);
7164 if (sign->pixmap == NULL)
7166 vim_free(sign);
7167 sign = NULL;
7168 EMSG(_(e_signdata));
7172 return sign;
7175 void
7176 gui_mch_destroy_sign(void *sign)
7178 if (sign != NULL)
7180 signicon_T *signicon = (signicon_T *)sign;
7182 if (signicon->pixmap != NULL)
7183 gdk_pixmap_unref(signicon->pixmap);
7184 if (signicon->mask != NULL)
7185 gdk_bitmap_unref(signicon->mask);
7187 vim_free(signicon);
7190 # endif /* !HAVE_GTK2 */
7192 #endif /* FEAT_SIGN_ICONS */