Changed DiffText and Constant highlight groups
[MacVim/jjgod.git] / src / gui_gtk_x11.c
blob3235f40d567e0c1c8d1f02a20ff0fa9b816415db
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 bind_textdomain_codeset
40 # undef bind_textdomain_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
817 * window) */
818 if (widget != gui.drawarea)
819 gtk_widget_grab_focus(gui.drawarea);
821 /* make sure the input buffer is read */
822 if (gtk_main_level() > 0)
823 gtk_main_quit();
825 return TRUE;
828 /*ARGSUSED*/
829 static gint
830 focus_out_event(GtkWidget *widget, GdkEventFocus *event, gpointer data)
832 gui_focus_change(FALSE);
834 if (blink_state != BLINK_NONE)
835 gui_mch_stop_blink();
837 /* make sure the input buffer is read */
838 if (gtk_main_level() > 0)
839 gtk_main_quit();
841 return TRUE;
845 #ifdef HAVE_GTK2
847 * Translate a GDK key value to UTF-8 independently of the current locale.
848 * The output is written to string, which must have room for at least 6 bytes
849 * plus the NUL terminator. Returns the length in bytes.
851 * This function is used in the GTK+ 2 GUI only. The GTK+ 1 code makes use
852 * of GdkEventKey::string instead. But event->string is evil; see here why:
853 * http://developer.gnome.org/doc/API/2.0/gdk/gdk-Event-Structures.html#GdkEventKey
855 static int
856 keyval_to_string(unsigned int keyval, unsigned int state, char_u *string)
858 int len;
859 guint32 uc;
861 uc = gdk_keyval_to_unicode(keyval);
862 if (uc != 0)
864 /* Check for CTRL-foo */
865 if ((state & GDK_CONTROL_MASK) && uc >= 0x20 && uc < 0x80)
867 /* These mappings look arbitrary at the first glance, but in fact
868 * resemble quite exactly the behaviour of the GTK+ 1.2 GUI on my
869 * machine. The only difference is BS vs. DEL for CTRL-8 (makes
870 * more sense and is consistent with usual terminal behaviour). */
871 if (uc >= '@')
872 string[0] = uc & 0x1F;
873 else if (uc == '2')
874 string[0] = NUL;
875 else if (uc >= '3' && uc <= '7')
876 string[0] = uc ^ 0x28;
877 else if (uc == '8')
878 string[0] = BS;
879 else if (uc == '?')
880 string[0] = DEL;
881 else
882 string[0] = uc;
883 len = 1;
885 else
887 /* Translate a normal key to UTF-8. This doesn't work for dead
888 * keys of course, you _have_ to use an input method for that. */
889 len = utf_char2bytes((int)uc, string);
892 else
894 /* Translate keys which are represented by ASCII control codes in Vim.
895 * There are only a few of those; most control keys are translated to
896 * special terminal-like control sequences. */
897 len = 1;
898 switch (keyval)
900 case GDK_Tab: case GDK_KP_Tab: case GDK_ISO_Left_Tab:
901 string[0] = TAB;
902 break;
903 case GDK_Linefeed:
904 string[0] = NL;
905 break;
906 case GDK_Return: case GDK_ISO_Enter: case GDK_3270_Enter:
907 string[0] = CAR;
908 break;
909 case GDK_Escape:
910 string[0] = ESC;
911 break;
912 default:
913 len = 0;
914 break;
917 string[len] = NUL;
919 return len;
921 #endif /* HAVE_GTK2 */
923 static int
924 modifiers_gdk2vim(guint state)
926 int modifiers = 0;
928 if (state & GDK_SHIFT_MASK)
929 modifiers |= MOD_MASK_SHIFT;
930 if (state & GDK_CONTROL_MASK)
931 modifiers |= MOD_MASK_CTRL;
932 if (state & GDK_MOD1_MASK)
933 modifiers |= MOD_MASK_ALT;
934 if (state & GDK_MOD4_MASK)
935 modifiers |= MOD_MASK_META;
937 return modifiers;
940 static int
941 modifiers_gdk2mouse(guint state)
943 int modifiers = 0;
945 if (state & GDK_SHIFT_MASK)
946 modifiers |= MOUSE_SHIFT;
947 if (state & GDK_CONTROL_MASK)
948 modifiers |= MOUSE_CTRL;
949 if (state & GDK_MOD1_MASK)
950 modifiers |= MOUSE_ALT;
952 return modifiers;
956 * Main keyboard handler:
958 /*ARGSUSED*/
959 static gint
960 key_press_event(GtkWidget *widget, GdkEventKey *event, gpointer data)
962 #ifdef HAVE_GTK2
963 /* 256 bytes is way over the top, but for safety let's reduce it only
964 * for GTK+ 2 where we know for sure how large the string might get.
965 * (That is, up to 6 bytes + NUL + CSI escapes + safety measure.) */
966 char_u string[32], string2[32];
967 #else
968 char_u string[256], string2[256];
969 #endif
970 guint key_sym;
971 int len;
972 int i;
973 int modifiers;
974 int key;
975 guint state;
976 char_u *s, *d;
978 key_sym = event->keyval;
979 state = event->state;
980 #ifndef HAVE_GTK2 /* deprecated */
981 len = event->length;
982 g_assert(len <= sizeof(string));
983 #endif
985 #ifndef HAVE_GTK2
987 * It appears as if we always want to consume a key-press (there currently
988 * aren't any 'return FALSE's), so we always do this: when running in a
989 * GtkPlug and not a window, we must prevent emission of the key_press
990 * EVENT from continuing (which is 'beyond' the level of stopping mere
991 * signals by returning FALSE), otherwise things like tab/cursor-keys are
992 * processed by the GtkPlug default handler, which moves input focus away
993 * from us!
994 * Note: This should no longer be necessary with GTK+ 2.
996 if (gtk_socket_id != 0)
997 gtk_signal_emit_stop_by_name(GTK_OBJECT(widget), "key_press_event");
998 #endif
1000 #ifdef FEAT_XIM
1001 if (xim_queue_key_press_event(event, TRUE))
1002 return TRUE;
1003 #endif
1005 #ifdef FEAT_HANGULIN
1006 if (key_sym == GDK_space && (state & GDK_SHIFT_MASK))
1008 hangul_input_state_toggle();
1009 return TRUE;
1011 #endif
1013 #ifdef SunXK_F36
1015 * These keys have bogus lookup strings, and trapping them here is
1016 * easier than trying to XRebindKeysym() on them with every possible
1017 * combination of modifiers.
1019 if (key_sym == SunXK_F36 || key_sym == SunXK_F37)
1020 len = 0;
1021 else
1022 #endif
1024 #ifdef HAVE_GTK2
1025 len = keyval_to_string(key_sym, state, string2);
1027 /* Careful: convert_input() doesn't handle the NUL character.
1028 * No need to convert pure ASCII anyway, thus the len > 1 check. */
1029 if (len > 1 && input_conv.vc_type != CONV_NONE)
1030 len = convert_input(string2, len, sizeof(string2));
1032 s = string2;
1033 #else
1034 # ifdef FEAT_MBYTE
1035 if (input_conv.vc_type != CONV_NONE)
1037 mch_memmove(string2, event->string, len);
1038 len = convert_input(string2, len, sizeof(string2));
1039 s = string2;
1041 else
1042 # endif
1043 s = (char_u *)event->string;
1044 #endif
1046 d = string;
1047 for (i = 0; i < len; ++i)
1049 *d++ = s[i];
1050 if (d[-1] == CSI && d + 2 < string + sizeof(string))
1052 /* Turn CSI into K_CSI. */
1053 *d++ = KS_EXTRA;
1054 *d++ = (int)KE_CSI;
1057 len = d - string;
1060 /* Shift-Tab results in Left_Tab, but we want <S-Tab> */
1061 if (key_sym == GDK_ISO_Left_Tab)
1063 key_sym = GDK_Tab;
1064 state |= GDK_SHIFT_MASK;
1067 #ifndef HAVE_GTK2 /* for GTK+ 2, we handle this in keyval_to_string() */
1068 if ((key_sym == GDK_2 || key_sym == GDK_at) && (state & GDK_CONTROL_MASK))
1070 string[0] = NUL; /* CTRL-2 and CTRL-@ is NUL */
1071 len = 1;
1073 else if (len == 0 && (key_sym == GDK_space || key_sym == GDK_Tab))
1075 /* When there are modifiers, these keys get zero length; we need the
1076 * original key here to be able to add a modifier below. */
1077 string[0] = (key_sym & 0xff);
1078 len = 1;
1080 #endif
1082 #ifdef FEAT_MENU
1083 /* If there is a menu and 'wak' is "yes", or 'wak' is "menu" and the key
1084 * is a menu shortcut, we ignore everything with the ALT modifier. */
1085 if ((state & GDK_MOD1_MASK)
1086 && gui.menu_is_active
1087 && (*p_wak == 'y'
1088 || (*p_wak == 'm'
1089 && len == 1
1090 && gui_is_menu_shortcut(string[0]))))
1091 # ifdef HAVE_GTK2
1092 /* For GTK2 we return false to signify that we haven't handled the
1093 * keypress, so that gtk will handle the mnemonic or accelerator. */
1094 return FALSE;
1095 # else
1096 return TRUE;
1097 # endif
1098 #endif
1100 /* Check for Alt/Meta key (Mod1Mask), but not for a BS, DEL or character
1101 * that already has the 8th bit set.
1102 * Don't do this for <S-M-Tab>, that should become K_S_TAB with ALT.
1103 * Don't do this for double-byte encodings, it turns the char into a lead
1104 * byte. */
1105 if (len == 1
1106 && (state & GDK_MOD1_MASK)
1107 && !(key_sym == GDK_BackSpace || key_sym == GDK_Delete)
1108 && (string[0] & 0x80) == 0
1109 && !(key_sym == GDK_Tab && (state & GDK_SHIFT_MASK))
1110 #ifdef FEAT_MBYTE
1111 && !enc_dbcs
1112 #endif
1115 string[0] |= 0x80;
1116 state &= ~GDK_MOD1_MASK; /* don't use it again */
1117 #ifdef FEAT_MBYTE
1118 if (enc_utf8) /* convert to utf-8 */
1120 string[1] = string[0] & 0xbf;
1121 string[0] = ((unsigned)string[0] >> 6) + 0xc0;
1122 if (string[1] == CSI)
1124 string[2] = KS_EXTRA;
1125 string[3] = (int)KE_CSI;
1126 len = 4;
1128 else
1129 len = 2;
1131 #endif
1134 /* Check for special keys. Also do this when len == 1 (key has an ASCII
1135 * value) to detect backspace, delete and keypad keys. */
1136 if (len == 0 || len == 1)
1138 for (i = 0; special_keys[i].key_sym != 0; i++)
1140 if (special_keys[i].key_sym == key_sym)
1142 string[0] = CSI;
1143 string[1] = special_keys[i].code0;
1144 string[2] = special_keys[i].code1;
1145 len = -3;
1146 break;
1151 if (len == 0) /* Unrecognized key */
1152 return TRUE;
1154 #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK) && !defined(HAVE_GTK2)
1155 /* Cancel or type backspace. For GTK2, im_commit_cb() does the same. */
1156 preedit_start_col = MAXCOL;
1157 xim_changed_while_preediting = TRUE;
1158 #endif
1160 /* Special keys (and a few others) may have modifiers. Also when using a
1161 * double-byte encoding (can't set the 8th bit). */
1162 if (len == -3 || key_sym == GDK_space || key_sym == GDK_Tab
1163 || key_sym == GDK_Return || key_sym == GDK_Linefeed
1164 || key_sym == GDK_Escape || key_sym == GDK_KP_Tab
1165 || key_sym == GDK_ISO_Enter || key_sym == GDK_3270_Enter
1166 #ifdef FEAT_MBYTE
1167 || (enc_dbcs && len == 1 && (state & GDK_MOD1_MASK))
1168 #endif
1171 modifiers = modifiers_gdk2vim(state);
1174 * For some keys a shift modifier is translated into another key
1175 * code.
1177 if (len == -3)
1178 key = TO_SPECIAL(string[1], string[2]);
1179 else
1180 key = string[0];
1182 key = simplify_key(key, &modifiers);
1183 if (key == CSI)
1184 key = K_CSI;
1185 if (IS_SPECIAL(key))
1187 string[0] = CSI;
1188 string[1] = K_SECOND(key);
1189 string[2] = K_THIRD(key);
1190 len = 3;
1192 else
1194 string[0] = key;
1195 len = 1;
1198 if (modifiers != 0)
1200 string2[0] = CSI;
1201 string2[1] = KS_MODIFIER;
1202 string2[2] = modifiers;
1203 add_to_input_buf(string2, 3);
1207 if (len == 1 && ((string[0] == Ctrl_C && ctrl_c_interrupts)
1208 || (string[0] == intr_char && intr_char != Ctrl_C)))
1210 trash_input_buf();
1211 got_int = TRUE;
1214 add_to_input_buf(string, len);
1216 /* blank out the pointer if necessary */
1217 if (p_mh)
1218 gui_mch_mousehide(TRUE);
1220 if (gtk_main_level() > 0)
1221 gtk_main_quit();
1223 return TRUE;
1226 #if defined(FEAT_XIM) && defined(HAVE_GTK2)
1227 /*ARGSUSED0*/
1228 static gboolean
1229 key_release_event(GtkWidget *widget, GdkEventKey *event, gpointer data)
1232 * GTK+ 2 input methods may do fancy stuff on key release events too.
1233 * With the default IM for instance, you can enter any UCS code point
1234 * by holding down CTRL-SHIFT and typing hexadecimal digits.
1236 return xim_queue_key_press_event(event, FALSE);
1238 #endif
1241 /****************************************************************************
1242 * Selection handlers:
1245 /*ARGSUSED*/
1246 static gint
1247 selection_clear_event(GtkWidget *widget,
1248 GdkEventSelection *event,
1249 gpointer user_data)
1251 if (event->selection == clip_plus.gtk_sel_atom)
1252 clip_lose_selection(&clip_plus);
1253 else
1254 clip_lose_selection(&clip_star);
1256 if (gtk_main_level() > 0)
1257 gtk_main_quit();
1259 return TRUE;
1262 #define RS_NONE 0 /* selection_received_cb() not called yet */
1263 #define RS_OK 1 /* selection_received_cb() called and OK */
1264 #define RS_FAIL 2 /* selection_received_cb() called and failed */
1265 static int received_selection = RS_NONE;
1267 /*ARGSUSED*/
1268 static void
1269 selection_received_cb(GtkWidget *widget,
1270 GtkSelectionData *data,
1271 guint time_,
1272 gpointer user_data)
1274 VimClipboard *cbd;
1275 char_u *text;
1276 char_u *tmpbuf = NULL;
1277 #ifdef HAVE_GTK2
1278 guchar *tmpbuf_utf8 = NULL;
1279 #endif
1280 int len;
1281 int motion_type;
1283 if (data->selection == clip_plus.gtk_sel_atom)
1284 cbd = &clip_plus;
1285 else
1286 cbd = &clip_star;
1288 text = (char_u *)data->data;
1289 len = data->length;
1290 motion_type = MCHAR;
1292 if (text == NULL || len <= 0)
1294 received_selection = RS_FAIL;
1295 /* clip_free_selection(cbd); ??? */
1297 if (gtk_main_level() > 0)
1298 gtk_main_quit();
1300 return;
1303 if (data->type == vim_atom)
1305 motion_type = *text++;
1306 --len;
1309 #ifdef FEAT_MBYTE
1310 else if (data->type == vimenc_atom)
1312 char_u *enc;
1313 vimconv_T conv;
1315 motion_type = *text++;
1316 --len;
1318 enc = text;
1319 text += STRLEN(text) + 1;
1320 len -= text - enc;
1322 /* If the encoding of the text is different from 'encoding', attempt
1323 * converting it. */
1324 conv.vc_type = CONV_NONE;
1325 convert_setup(&conv, enc, p_enc);
1326 if (conv.vc_type != CONV_NONE)
1328 tmpbuf = string_convert(&conv, text, &len);
1329 if (tmpbuf != NULL)
1330 text = tmpbuf;
1331 convert_setup(&conv, NULL, NULL);
1334 #endif
1336 #ifdef HAVE_GTK2
1337 /* gtk_selection_data_get_text() handles all the nasty details
1338 * and targets and encodings etc. This rocks so hard. */
1339 else
1341 tmpbuf_utf8 = gtk_selection_data_get_text(data);
1342 if (tmpbuf_utf8 != NULL)
1344 len = STRLEN(tmpbuf_utf8);
1345 if (input_conv.vc_type != CONV_NONE)
1347 tmpbuf = string_convert(&input_conv, tmpbuf_utf8, &len);
1348 if (tmpbuf != NULL)
1349 text = tmpbuf;
1351 else
1352 text = tmpbuf_utf8;
1355 #else /* !HAVE_GTK2 */
1356 # ifdef FEAT_MBYTE
1357 else if (data->type == utf8_string_atom)
1359 vimconv_T conv;
1361 conv.vc_type = CONV_NONE;
1362 convert_setup(&conv, (char_u *)"utf-8", p_enc);
1364 if (conv.vc_type != CONV_NONE)
1366 tmpbuf = string_convert(&conv, text, &len);
1367 convert_setup(&conv, NULL, NULL);
1369 if (tmpbuf != NULL)
1370 text = tmpbuf;
1372 # endif
1373 else if (data->type == compound_text_atom || data->type == text_atom)
1375 char **list = NULL;
1376 int count;
1377 int i;
1378 unsigned tmplen = 0;
1380 count = gdk_text_property_to_text_list(data->type, data->format,
1381 data->data, data->length,
1382 &list);
1383 for (i = 0; i < count; ++i)
1384 tmplen += strlen(list[i]);
1386 tmpbuf = alloc(tmplen + 1);
1387 if (tmpbuf != NULL)
1389 tmpbuf[0] = NUL;
1390 for (i = 0; i < count; ++i)
1391 STRCAT(tmpbuf, list[i]);
1392 text = tmpbuf;
1393 len = tmplen;
1396 if (list != NULL)
1397 gdk_free_text_list(list);
1399 #endif /* !HAVE_GTK2 */
1401 clip_yank_selection(motion_type, text, (long)len, cbd);
1402 received_selection = RS_OK;
1403 vim_free(tmpbuf);
1404 #ifdef HAVE_GTK2
1405 g_free(tmpbuf_utf8);
1406 #endif
1408 if (gtk_main_level() > 0)
1409 gtk_main_quit();
1413 * Prepare our selection data for passing it to the external selection
1414 * client.
1416 /*ARGSUSED*/
1417 static void
1418 selection_get_cb(GtkWidget *widget,
1419 GtkSelectionData *selection_data,
1420 guint info,
1421 guint time_,
1422 gpointer user_data)
1424 char_u *string;
1425 char_u *tmpbuf;
1426 long_u tmplen;
1427 int length;
1428 int motion_type;
1429 GdkAtom type;
1430 VimClipboard *cbd;
1432 if (selection_data->selection == clip_plus.gtk_sel_atom)
1433 cbd = &clip_plus;
1434 else
1435 cbd = &clip_star;
1437 if (!cbd->owned)
1438 return; /* Shouldn't ever happen */
1440 if (info != (guint)TARGET_STRING
1441 #ifdef FEAT_MBYTE
1442 && info != (guint)TARGET_UTF8_STRING
1443 && info != (guint)TARGET_VIMENC
1444 #endif
1445 && info != (guint)TARGET_VIM
1446 && info != (guint)TARGET_COMPOUND_TEXT
1447 && info != (guint)TARGET_TEXT)
1448 return;
1450 /* get the selection from the '*'/'+' register */
1451 clip_get_selection(cbd);
1453 motion_type = clip_convert_selection(&string, &tmplen, cbd);
1454 if (motion_type < 0 || string == NULL)
1455 return;
1456 /* Due to int arguments we can't handle more than G_MAXINT. Also
1457 * reserve one extra byte for NUL or the motion type; just in case.
1458 * (Not that pasting 2G of text is ever going to work, but... ;-) */
1459 length = MIN(tmplen, (long_u)(G_MAXINT - 1));
1461 if (info == (guint)TARGET_VIM)
1463 tmpbuf = alloc((unsigned)length + 1);
1464 if (tmpbuf != NULL)
1466 tmpbuf[0] = motion_type;
1467 mch_memmove(tmpbuf + 1, string, (size_t)length);
1469 /* For our own format, the first byte contains the motion type */
1470 ++length;
1471 vim_free(string);
1472 string = tmpbuf;
1473 type = vim_atom;
1476 #ifdef FEAT_MBYTE
1477 else if (info == (guint)TARGET_VIMENC)
1479 int l = STRLEN(p_enc);
1481 /* contents: motion_type 'encoding' NUL text */
1482 tmpbuf = alloc((unsigned)length + l + 2);
1483 if (tmpbuf != NULL)
1485 tmpbuf[0] = motion_type;
1486 STRCPY(tmpbuf + 1, p_enc);
1487 mch_memmove(tmpbuf + l + 2, string, (size_t)length);
1489 length += l + 2;
1490 vim_free(string);
1491 string = tmpbuf;
1492 type = vimenc_atom;
1494 #endif
1496 #ifdef HAVE_GTK2
1497 /* gtk_selection_data_set_text() handles everything for us. This is
1498 * so easy and simple and cool, it'd be insane not to use it. */
1499 else
1501 if (output_conv.vc_type != CONV_NONE)
1503 tmpbuf = string_convert(&output_conv, string, &length);
1504 vim_free(string);
1505 if (tmpbuf == NULL)
1506 return;
1507 string = tmpbuf;
1509 /* Validate the string to avoid runtime warnings */
1510 if (g_utf8_validate((const char *)string, (gssize)length, NULL))
1512 gtk_selection_data_set_text(selection_data,
1513 (const char *)string, length);
1515 vim_free(string);
1516 return;
1518 #else /* !HAVE_GTK2 */
1519 # ifdef FEAT_MBYTE
1520 else if (info == (guint)TARGET_UTF8_STRING)
1522 vimconv_T conv;
1524 conv.vc_type = CONV_NONE;
1525 convert_setup(&conv, p_enc, (char_u *)"utf-8");
1527 if (conv.vc_type != CONV_NONE)
1529 tmpbuf = string_convert(&conv, string, &length);
1530 convert_setup(&conv, NULL, NULL);
1531 vim_free(string);
1532 string = tmpbuf;
1534 type = utf8_string_atom;
1536 # endif
1537 else if (info == (guint)TARGET_COMPOUND_TEXT
1538 || info == (guint)TARGET_TEXT)
1540 int format;
1542 /* Copy the string to ensure NUL-termination */
1543 tmpbuf = vim_strnsave(string, length);
1544 vim_free(string);
1545 if (tmpbuf != NULL)
1547 gdk_string_to_compound_text((const char *)tmpbuf,
1548 &type, &format, &string, &length);
1549 vim_free(tmpbuf);
1550 selection_data->type = type;
1551 selection_data->format = format;
1552 gtk_selection_data_set(selection_data, type, format, string, length);
1553 gdk_free_compound_text(string);
1555 return;
1557 else
1559 type = GDK_TARGET_STRING;
1561 #endif /* !HAVE_GTK2 */
1563 if (string != NULL)
1565 selection_data->type = selection_data->target;
1566 selection_data->format = 8; /* 8 bits per char */
1568 gtk_selection_data_set(selection_data, type, 8, string, length);
1569 vim_free(string);
1574 * Check if the GUI can be started. Called before gvimrc is sourced.
1575 * Return OK or FAIL.
1578 gui_mch_init_check(void)
1580 #ifndef HAVE_GTK2
1581 /* This is needed to make the locale handling consistent between the GUI
1582 * and the rest of VIM. */
1583 gtk_set_locale();
1584 #endif
1586 #ifdef FEAT_GUI_GNOME
1587 if (gtk_socket_id == 0)
1588 using_gnome = 1;
1589 #endif
1591 /* Don't use gtk_init() or gnome_init(), it exits on failure. */
1592 if (!gtk_init_check(&gui_argc, &gui_argv))
1594 gui.dying = TRUE;
1595 EMSG(_(e_opendisp));
1596 return FAIL;
1599 return OK;
1603 /****************************************************************************
1604 * Mouse handling callbacks
1608 static guint mouse_click_timer = 0;
1609 static int mouse_timed_out = TRUE;
1612 * Timer used to recognize multiple clicks of the mouse button
1614 static gint
1615 mouse_click_timer_cb(gpointer data)
1617 /* we don't use this information currently */
1618 int *timed_out = (int *) data;
1620 *timed_out = TRUE;
1621 return FALSE; /* don't happen again */
1624 static guint motion_repeat_timer = 0;
1625 static int motion_repeat_offset = FALSE;
1626 static gint motion_repeat_timer_cb(gpointer);
1628 static void
1629 process_motion_notify(int x, int y, GdkModifierType state)
1631 int button;
1632 int_u vim_modifiers;
1634 button = (state & (GDK_BUTTON1_MASK | GDK_BUTTON2_MASK |
1635 GDK_BUTTON3_MASK | GDK_BUTTON4_MASK |
1636 GDK_BUTTON5_MASK))
1637 ? MOUSE_DRAG : ' ';
1639 /* If our pointer is currently hidden, then we should show it. */
1640 gui_mch_mousehide(FALSE);
1642 /* Just moving the rodent above the drawing area without any button
1643 * being pressed. */
1644 if (button != MOUSE_DRAG)
1646 gui_mouse_moved(x, y);
1647 return;
1650 /* translate modifier coding between the main engine and GTK */
1651 vim_modifiers = modifiers_gdk2mouse(state);
1653 /* inform the editor engine about the occurrence of this event */
1654 gui_send_mouse_event(button, x, y, FALSE, vim_modifiers);
1656 if (gtk_main_level() > 0)
1657 gtk_main_quit();
1660 * Auto repeat timer handling.
1662 if (x < 0 || y < 0
1663 || x >= gui.drawarea->allocation.width
1664 || y >= gui.drawarea->allocation.height)
1667 int dx;
1668 int dy;
1669 int offshoot;
1670 int delay = 10;
1672 /* Calculate the maximal distance of the cursor from the drawing area.
1673 * (offshoot can't become negative here!).
1675 dx = x < 0 ? -x : x - gui.drawarea->allocation.width;
1676 dy = y < 0 ? -y : y - gui.drawarea->allocation.height;
1678 offshoot = dx > dy ? dx : dy;
1680 /* Make a linearly declaying timer delay with a threshold of 5 at a
1681 * distance of 127 pixels from the main window.
1683 * One could think endlessly about the most ergonomic variant here.
1684 * For example it could make sense to calculate the distance from the
1685 * drags start instead...
1687 * Maybe a parabolic interpolation would suite us better here too...
1689 if (offshoot > 127)
1691 /* 5 appears to be somehow near to my perceptual limits :-). */
1692 delay = 5;
1694 else
1696 delay = (130 * (127 - offshoot)) / 127 + 5;
1699 /* shoot again */
1700 if (!motion_repeat_timer)
1701 motion_repeat_timer = gtk_timeout_add((guint32)delay,
1702 motion_repeat_timer_cb, NULL);
1707 * Timer used to recognize multiple clicks of the mouse button.
1709 /*ARGSUSED0*/
1710 static gint
1711 motion_repeat_timer_cb(gpointer data)
1713 int x;
1714 int y;
1715 GdkModifierType state;
1717 gdk_window_get_pointer(gui.drawarea->window, &x, &y, &state);
1719 if (!(state & (GDK_BUTTON1_MASK | GDK_BUTTON2_MASK |
1720 GDK_BUTTON3_MASK | GDK_BUTTON4_MASK |
1721 GDK_BUTTON5_MASK)))
1723 motion_repeat_timer = 0;
1724 return FALSE;
1727 /* If there already is a mouse click in the input buffer, wait another
1728 * time (otherwise we would create a backlog of clicks) */
1729 if (vim_used_in_input_buf() > 10)
1730 return TRUE;
1732 motion_repeat_timer = 0;
1735 * Fake a motion event.
1736 * Trick: Pretend the mouse moved to the next character on every other
1737 * event, otherwise drag events will be discarded, because they are still
1738 * in the same character.
1740 if (motion_repeat_offset)
1741 x += gui.char_width;
1743 motion_repeat_offset = !motion_repeat_offset;
1744 process_motion_notify(x, y, state);
1746 /* Don't happen again. We will get reinstalled in the synthetic event
1747 * if needed -- thus repeating should still work. */
1748 return FALSE;
1751 /*ARGSUSED2*/
1752 static gint
1753 motion_notify_event(GtkWidget *widget, GdkEventMotion *event, gpointer data)
1755 if (event->is_hint)
1757 int x;
1758 int y;
1759 GdkModifierType state;
1761 gdk_window_get_pointer(widget->window, &x, &y, &state);
1762 process_motion_notify(x, y, state);
1764 else
1766 process_motion_notify((int)event->x, (int)event->y,
1767 (GdkModifierType)event->state);
1770 return TRUE; /* handled */
1775 * Mouse button handling. Note please that we are capturing multiple click's
1776 * by our own timeout mechanism instead of the one provided by GTK+ itself.
1777 * This is due to the way the generic VIM code is recognizing multiple clicks.
1779 /*ARGSUSED2*/
1780 static gint
1781 button_press_event(GtkWidget *widget, GdkEventButton *event, gpointer data)
1783 int button;
1784 int repeated_click = FALSE;
1785 int x, y;
1786 int_u vim_modifiers;
1788 /* Make sure we have focus now we've been selected */
1789 if (gtk_socket_id != 0 && !GTK_WIDGET_HAS_FOCUS(widget))
1790 gtk_widget_grab_focus(widget);
1793 * Don't let additional events about multiple clicks send by GTK to us
1794 * after the initial button press event confuse us.
1796 if (event->type != GDK_BUTTON_PRESS)
1797 return FALSE;
1799 x = event->x;
1800 y = event->y;
1802 /* Handle multiple clicks */
1803 if (!mouse_timed_out && mouse_click_timer)
1805 gtk_timeout_remove(mouse_click_timer);
1806 mouse_click_timer = 0;
1807 repeated_click = TRUE;
1810 mouse_timed_out = FALSE;
1811 mouse_click_timer = gtk_timeout_add((guint32)p_mouset,
1812 mouse_click_timer_cb, &mouse_timed_out);
1814 switch (event->button)
1816 case 1:
1817 button = MOUSE_LEFT;
1818 break;
1819 case 2:
1820 button = MOUSE_MIDDLE;
1821 break;
1822 case 3:
1823 button = MOUSE_RIGHT;
1824 break;
1825 #ifndef HAVE_GTK2
1826 case 4:
1827 button = MOUSE_4;
1828 break;
1829 case 5:
1830 button = MOUSE_5;
1831 break;
1832 #endif
1833 default:
1834 return FALSE; /* Unknown button */
1837 #ifdef FEAT_XIM
1838 /* cancel any preediting */
1839 if (im_is_preediting())
1840 xim_reset();
1841 #endif
1843 vim_modifiers = modifiers_gdk2mouse(event->state);
1845 gui_send_mouse_event(button, x, y, repeated_click, vim_modifiers);
1846 if (gtk_main_level() > 0)
1847 gtk_main_quit(); /* make sure the above will be handled immediately */
1849 return TRUE;
1852 #ifdef HAVE_GTK2
1854 * GTK+ 2 doesn't handle mouse buttons 4, 5, 6 and 7 the same way as GTK+ 1.
1855 * Instead, it abstracts scrolling via the new GdkEventScroll.
1857 /*ARGSUSED2*/
1858 static gboolean
1859 scroll_event(GtkWidget *widget, GdkEventScroll *event, gpointer data)
1861 int button;
1862 int_u vim_modifiers;
1864 if (gtk_socket_id != 0 && !GTK_WIDGET_HAS_FOCUS(widget))
1865 gtk_widget_grab_focus(widget);
1867 switch (event->direction)
1869 case GDK_SCROLL_UP:
1870 button = MOUSE_4;
1871 break;
1872 case GDK_SCROLL_DOWN:
1873 button = MOUSE_5;
1874 break;
1875 default: /* We don't care about left and right... Yet. */
1876 return FALSE;
1879 # ifdef FEAT_XIM
1880 /* cancel any preediting */
1881 if (im_is_preediting())
1882 xim_reset();
1883 # endif
1885 vim_modifiers = modifiers_gdk2mouse(event->state);
1887 gui_send_mouse_event(button, (int)event->x, (int)event->y,
1888 FALSE, vim_modifiers);
1890 if (gtk_main_level() > 0)
1891 gtk_main_quit(); /* make sure the above will be handled immediately */
1893 return TRUE;
1895 #endif /* HAVE_GTK2 */
1898 /*ARGSUSED*/
1899 static gint
1900 button_release_event(GtkWidget *widget, GdkEventButton *event, gpointer data)
1902 int x, y;
1903 int_u vim_modifiers;
1905 /* Remove any motion "machine gun" timers used for automatic further
1906 extension of allocation areas if outside of the applications window
1907 area .*/
1908 if (motion_repeat_timer)
1910 gtk_timeout_remove(motion_repeat_timer);
1911 motion_repeat_timer = 0;
1914 x = event->x;
1915 y = event->y;
1917 vim_modifiers = modifiers_gdk2mouse(event->state);
1919 gui_send_mouse_event(MOUSE_RELEASE, x, y, FALSE, vim_modifiers);
1920 if (gtk_main_level() > 0)
1921 gtk_main_quit(); /* make sure it will be handled immediately */
1923 return TRUE;
1927 #ifdef FEAT_DND
1928 /****************************************************************************
1929 * Drag aNd Drop support handlers.
1933 * Count how many items there may be and separate them with a NUL.
1934 * Apparently the items are separated with \r\n. This is not documented,
1935 * thus be careful not to go past the end. Also allow separation with
1936 * NUL characters.
1938 static int
1939 count_and_decode_uri_list(char_u *out, char_u *raw, int len)
1941 int i;
1942 char_u *p = out;
1943 int count = 0;
1945 for (i = 0; i < len; ++i)
1947 if (raw[i] == NUL || raw[i] == '\n' || raw[i] == '\r')
1949 if (p > out && p[-1] != NUL)
1951 ++count;
1952 *p++ = NUL;
1955 else if (raw[i] == '%' && i + 2 < len && hexhex2nr(raw + i + 1) > 0)
1957 *p++ = hexhex2nr(raw + i + 1);
1958 i += 2;
1960 else
1961 *p++ = raw[i];
1963 if (p > out && p[-1] != NUL)
1965 *p = NUL; /* last item didn't have \r or \n */
1966 ++count;
1968 return count;
1972 * Parse NUL separated "src" strings. Make it an array "outlist" form. On
1973 * this process, URI which protocol is not "file:" are removed. Return
1974 * length of array (less than "max").
1976 static int
1977 filter_uri_list(char_u **outlist, int max, char_u *src)
1979 int i, j;
1981 for (i = j = 0; i < max; ++i)
1983 outlist[i] = NULL;
1984 if (STRNCMP(src, "file:", 5) == 0)
1986 src += 5;
1987 if (STRNCMP(src, "//localhost", 11) == 0)
1988 src += 11;
1989 while (src[0] == '/' && src[1] == '/')
1990 ++src;
1991 outlist[j++] = vim_strsave(src);
1993 src += STRLEN(src) + 1;
1995 return j;
1998 static char_u **
1999 parse_uri_list(int *count, char_u *data, int len)
2001 int n = 0;
2002 char_u *tmp = NULL;
2003 char_u **array = NULL;;
2005 if (data != NULL && len > 0 && (tmp = (char_u *)alloc(len + 1)) != NULL)
2007 n = count_and_decode_uri_list(tmp, data, len);
2008 if (n > 0 && (array = (char_u **)alloc(n * sizeof(char_u *))) != NULL)
2009 n = filter_uri_list(array, n, tmp);
2011 vim_free(tmp);
2012 *count = n;
2013 return array;
2016 static void
2017 drag_handle_uri_list(GdkDragContext *context,
2018 GtkSelectionData *data,
2019 guint time_,
2020 GdkModifierType state,
2021 gint x,
2022 gint y)
2024 char_u **fnames;
2025 int nfiles = 0;
2027 fnames = parse_uri_list(&nfiles, data->data, data->length);
2029 if (fnames != NULL && nfiles > 0)
2031 int_u modifiers;
2033 gtk_drag_finish(context, TRUE, FALSE, time_); /* accept */
2035 modifiers = modifiers_gdk2mouse(state);
2037 gui_handle_drop(x, y, modifiers, fnames, nfiles);
2039 else
2040 vim_free(fnames);
2043 static void
2044 drag_handle_text(GdkDragContext *context,
2045 GtkSelectionData *data,
2046 guint time_,
2047 GdkModifierType state)
2049 char_u dropkey[6] = {CSI, KS_MODIFIER, 0, CSI, KS_EXTRA, (char_u)KE_DROP};
2050 char_u *text;
2051 int len;
2052 # ifdef FEAT_MBYTE
2053 char_u *tmpbuf = NULL;
2054 # endif
2056 text = data->data;
2057 len = data->length;
2059 # ifdef FEAT_MBYTE
2060 if (data->type == utf8_string_atom)
2062 # ifdef HAVE_GTK2
2063 if (input_conv.vc_type != CONV_NONE)
2064 tmpbuf = string_convert(&input_conv, text, &len);
2065 # else
2066 vimconv_T conv;
2068 conv.vc_type = CONV_NONE;
2069 convert_setup(&conv, (char_u *)"utf-8", p_enc);
2071 if (conv.vc_type != CONV_NONE)
2073 tmpbuf = string_convert(&conv, text, &len);
2074 convert_setup(&conv, NULL, NULL);
2076 # endif
2077 if (tmpbuf != NULL)
2078 text = tmpbuf;
2080 # endif /* FEAT_MBYTE */
2082 dnd_yank_drag_data(text, (long)len);
2083 gtk_drag_finish(context, TRUE, FALSE, time_); /* accept */
2084 # ifdef FEAT_MBYTE
2085 vim_free(tmpbuf);
2086 # endif
2088 dropkey[2] = modifiers_gdk2vim(state);
2090 if (dropkey[2] != 0)
2091 add_to_input_buf(dropkey, (int)sizeof(dropkey));
2092 else
2093 add_to_input_buf(dropkey + 3, (int)(sizeof(dropkey) - 3));
2095 if (gtk_main_level() > 0)
2096 gtk_main_quit();
2100 * DND receiver.
2102 /*ARGSUSED2*/
2103 static void
2104 drag_data_received_cb(GtkWidget *widget,
2105 GdkDragContext *context,
2106 gint x,
2107 gint y,
2108 GtkSelectionData *data,
2109 guint info,
2110 guint time_,
2111 gpointer user_data)
2113 GdkModifierType state;
2115 /* Guard against trash */
2116 if (data->data == NULL
2117 || data->length <= 0
2118 || data->format != 8
2119 || data->data[data->length] != '\0')
2121 gtk_drag_finish(context, FALSE, FALSE, time_);
2122 return;
2125 /* Get the current modifier state for proper distinguishment between
2126 * different operations later. */
2127 gdk_window_get_pointer(widget->window, NULL, NULL, &state);
2129 /* Not sure about the role of "text/plain" here... */
2130 if (info == (guint)TARGET_TEXT_URI_LIST)
2131 drag_handle_uri_list(context, data, time_, state, x, y);
2132 else
2133 drag_handle_text(context, data, time_, state);
2136 #endif /* FEAT_DND */
2139 #if defined(FEAT_GUI_GNOME) && defined(FEAT_SESSION)
2141 * GnomeClient interact callback. Check for unsaved buffers that cannot
2142 * be abandoned and pop up a dialog asking the user for confirmation if
2143 * necessary.
2145 /*ARGSUSED0*/
2146 static void
2147 sm_client_check_changed_any(GnomeClient *client,
2148 gint key,
2149 GnomeDialogType type,
2150 gpointer data)
2152 cmdmod_T save_cmdmod;
2153 gboolean shutdown_cancelled;
2155 save_cmdmod = cmdmod;
2157 # ifdef FEAT_BROWSE
2158 cmdmod.browse = TRUE;
2159 # endif
2160 # if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2161 cmdmod.confirm = TRUE;
2162 # endif
2164 * If there are changed buffers, present the user with
2165 * a dialog if possible, otherwise give an error message.
2167 shutdown_cancelled = check_changed_any(FALSE);
2169 exiting = FALSE;
2170 cmdmod = save_cmdmod;
2171 setcursor(); /* position the cursor */
2172 out_flush();
2174 * If the user hit the [Cancel] button the whole shutdown
2175 * will be cancelled. Wow, quite powerful feature (:
2177 gnome_interaction_key_return(key, shutdown_cancelled);
2181 * Generate a script that can be used to restore the current editing session.
2182 * Save the value of v:this_session before running :mksession in order to make
2183 * automagic session save fully transparent. Return TRUE on success.
2185 static int
2186 write_session_file(char_u *filename)
2188 char_u *escaped_filename;
2189 char *mksession_cmdline;
2190 unsigned int save_ssop_flags;
2191 int failed;
2194 * Build an ex command line to create a script that restores the current
2195 * session if executed. Escape the filename to avoid nasty surprises.
2197 escaped_filename = vim_strsave_escaped(filename, escape_chars);
2198 if (escaped_filename == NULL)
2199 return FALSE;
2200 mksession_cmdline = g_strconcat("mksession ", (char *)escaped_filename,
2201 NULL);
2202 vim_free(escaped_filename);
2205 * Use a reasonable hardcoded set of 'sessionoptions' flags to avoid
2206 * unpredictable effects when the session is saved automatically. Also,
2207 * we definitely need SSOP_GLOBALS to be able to restore v:this_session.
2208 * Don't use SSOP_BUFFERS to prevent the buffer list from becoming
2209 * enormously large if the GNOME session feature is used regularly.
2211 save_ssop_flags = ssop_flags;
2212 ssop_flags = (SSOP_BLANK|SSOP_CURDIR|SSOP_FOLDS|SSOP_GLOBALS
2213 |SSOP_HELP|SSOP_OPTIONS|SSOP_WINSIZE|SSOP_TABPAGES);
2215 do_cmdline_cmd((char_u *)"let Save_VV_this_session = v:this_session");
2216 failed = (do_cmdline_cmd((char_u *)mksession_cmdline) == FAIL);
2217 do_cmdline_cmd((char_u *)"let v:this_session = Save_VV_this_session");
2218 do_unlet((char_u *)"Save_VV_this_session", TRUE);
2220 ssop_flags = save_ssop_flags;
2221 g_free(mksession_cmdline);
2223 * Reopen the file and append a command to restore v:this_session,
2224 * as if this save never happened. This is to avoid conflicts with
2225 * the user's own sessions. FIXME: It's probably less hackish to add
2226 * a "stealth" flag to 'sessionoptions' -- gotta ask Bram.
2228 if (!failed)
2230 FILE *fd;
2232 fd = open_exfile(filename, TRUE, APPENDBIN);
2234 failed = (fd == NULL
2235 || put_line(fd, "let v:this_session = Save_VV_this_session") == FAIL
2236 || put_line(fd, "unlet Save_VV_this_session") == FAIL);
2238 if (fd != NULL && fclose(fd) != 0)
2239 failed = TRUE;
2241 if (failed)
2242 mch_remove(filename);
2245 return !failed;
2249 * "save_yourself" signal handler. Initiate an interaction to ask the user
2250 * for confirmation if necessary. Save the current editing session and tell
2251 * the session manager how to restart Vim.
2253 /*ARGSUSED1*/
2254 static gboolean
2255 sm_client_save_yourself(GnomeClient *client,
2256 gint phase,
2257 GnomeSaveStyle save_style,
2258 gboolean shutdown,
2259 GnomeInteractStyle interact_style,
2260 gboolean fast,
2261 gpointer data)
2263 static const char suffix[] = "-session.vim";
2264 char *session_file;
2265 unsigned int len;
2266 gboolean success;
2268 /* Always request an interaction if possible. check_changed_any()
2269 * won't actually show a dialog unless any buffers have been modified.
2270 * There doesn't seem to be an obvious way to check that without
2271 * automatically firing the dialog. Anyway, it works just fine. */
2272 if (interact_style == GNOME_INTERACT_ANY)
2273 gnome_client_request_interaction(client, GNOME_DIALOG_NORMAL,
2274 &sm_client_check_changed_any,
2275 NULL);
2276 out_flush();
2277 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
2279 /* The path is unique for each session save. We do neither know nor care
2280 * which session script will actually be used later. This decision is in
2281 * the domain of the session manager. */
2282 session_file = gnome_config_get_real_path(
2283 gnome_client_get_config_prefix(client));
2284 len = strlen(session_file);
2286 if (len > 0 && session_file[len-1] == G_DIR_SEPARATOR)
2287 --len; /* get rid of the superfluous trailing '/' */
2289 session_file = g_renew(char, session_file, len + sizeof(suffix));
2290 memcpy(session_file + len, suffix, sizeof(suffix));
2292 success = write_session_file((char_u *)session_file);
2294 if (success)
2296 const char *argv[8];
2297 int i;
2299 /* Tell the session manager how to wipe out the stored session data.
2300 * This isn't as dangerous as it looks, don't worry :) session_file
2301 * is a unique absolute filename. Usually it'll be something like
2302 * `/home/user/.gnome2/vim-XXXXXX-session.vim'. */
2303 i = 0;
2304 argv[i++] = "rm";
2305 argv[i++] = session_file;
2306 argv[i] = NULL;
2308 gnome_client_set_discard_command(client, i, (char **)argv);
2310 /* Tell the session manager how to restore the just saved session.
2311 * This is easily done thanks to Vim's -S option. Pass the -f flag
2312 * since there's no need to fork -- it might even cause confusion.
2313 * Also pass the window role to give the WM something to match on.
2314 * The role is set in gui_mch_open(), thus should _never_ be NULL. */
2315 i = 0;
2316 argv[i++] = restart_command;
2317 argv[i++] = "-f";
2318 argv[i++] = "-g";
2319 # ifdef HAVE_GTK2
2320 argv[i++] = "--role";
2321 argv[i++] = gtk_window_get_role(GTK_WINDOW(gui.mainwin));
2322 # endif
2323 argv[i++] = "-S";
2324 argv[i++] = session_file;
2325 argv[i] = NULL;
2327 gnome_client_set_restart_command(client, i, (char **)argv);
2328 gnome_client_set_clone_command(client, 0, NULL);
2331 g_free(session_file);
2333 return success;
2337 * Called when the session manager wants us to die. There isn't much to save
2338 * here since "save_yourself" has been emitted before (unless serious trouble
2339 * is happening).
2341 /*ARGSUSED0*/
2342 static void
2343 sm_client_die(GnomeClient *client, gpointer data)
2345 /* Don't write messages to the GUI anymore */
2346 full_screen = FALSE;
2348 vim_strncpy(IObuff,
2349 _("Vim: Received \"die\" request from session manager\n"),
2350 IOSIZE - 1);
2351 preserve_exit();
2355 * Connect our signal handlers to be notified on session save and shutdown.
2357 static void
2358 setup_save_yourself(void)
2360 GnomeClient *client;
2362 client = gnome_master_client();
2364 if (client != NULL)
2366 /* Must use the deprecated gtk_signal_connect() for compatibility
2367 * with GNOME 1. Arrgh, zombies! */
2368 gtk_signal_connect(GTK_OBJECT(client), "save_yourself",
2369 GTK_SIGNAL_FUNC(&sm_client_save_yourself), NULL);
2370 gtk_signal_connect(GTK_OBJECT(client), "die",
2371 GTK_SIGNAL_FUNC(&sm_client_die), NULL);
2375 #else /* !(FEAT_GUI_GNOME && FEAT_SESSION) */
2377 # ifdef USE_XSMP
2379 * GTK tells us that XSMP needs attention
2381 /*ARGSUSED*/
2382 static gboolean
2383 local_xsmp_handle_requests(source, condition, data)
2384 GIOChannel *source;
2385 GIOCondition condition;
2386 gpointer data;
2388 if (condition == G_IO_IN)
2390 /* Do stuff; maybe close connection */
2391 if (xsmp_handle_requests() == FAIL)
2392 g_io_channel_unref((GIOChannel *)data);
2393 return TRUE;
2395 /* Error */
2396 g_io_channel_unref((GIOChannel *)data);
2397 xsmp_close();
2398 return TRUE;
2400 # endif /* USE_XSMP */
2403 * Setup the WM_PROTOCOLS to indicate we want the WM_SAVE_YOURSELF event.
2404 * This is an ugly use of X functions. GTK doesn't offer an alternative.
2406 static void
2407 setup_save_yourself(void)
2409 Atom *existing_atoms = NULL;
2410 int count = 0;
2412 #ifdef USE_XSMP
2413 if (xsmp_icefd != -1)
2416 * Use XSMP is preference to legacy WM_SAVE_YOURSELF;
2417 * set up GTK IO monitor
2419 GIOChannel *g_io = g_io_channel_unix_new(xsmp_icefd);
2421 g_io_add_watch(g_io, G_IO_IN | G_IO_ERR | G_IO_HUP,
2422 local_xsmp_handle_requests, (gpointer)g_io);
2424 else
2425 #endif
2427 /* Fall back to old method */
2429 /* first get the existing value */
2430 if (XGetWMProtocols(GDK_WINDOW_XDISPLAY(gui.mainwin->window),
2431 GDK_WINDOW_XWINDOW(gui.mainwin->window),
2432 &existing_atoms, &count))
2434 Atom *new_atoms;
2435 Atom save_yourself_xatom;
2436 int i;
2438 save_yourself_xatom = GET_X_ATOM(save_yourself_atom);
2440 /* check if WM_SAVE_YOURSELF isn't there yet */
2441 for (i = 0; i < count; ++i)
2442 if (existing_atoms[i] == save_yourself_xatom)
2443 break;
2445 if (i == count)
2447 /* allocate an Atoms array which is one item longer */
2448 new_atoms = (Atom *)alloc((unsigned)((count + 1)
2449 * sizeof(Atom)));
2450 if (new_atoms != NULL)
2452 memcpy(new_atoms, existing_atoms, count * sizeof(Atom));
2453 new_atoms[count] = save_yourself_xatom;
2454 XSetWMProtocols(GDK_WINDOW_XDISPLAY(gui.mainwin->window),
2455 GDK_WINDOW_XWINDOW(gui.mainwin->window),
2456 new_atoms, count + 1);
2457 vim_free(new_atoms);
2460 XFree(existing_atoms);
2465 # ifdef HAVE_GTK2
2467 * Installing a global event filter seems to be the only way to catch
2468 * client messages of type WM_PROTOCOLS without overriding GDK's own
2469 * client message event filter. Well, that's still better than trying
2470 * to guess what the GDK filter had done if it had been invoked instead
2471 * (This is what we did for GTK+ 1.2, see below).
2473 * GTK2_FIXME: This doesn't seem to work. For some reason we never
2474 * receive WM_SAVE_YOURSELF even though everything is set up correctly.
2475 * I have the nasty feeling modern session managers just don't send this
2476 * deprecated message anymore. Addition: confirmed by several people.
2478 * The GNOME session support is much cooler anyway. Unlike this ugly
2479 * WM_SAVE_YOURSELF hack it actually stores the session... And yes,
2480 * it should work with KDE as well.
2482 /*ARGSUSED1*/
2483 static GdkFilterReturn
2484 global_event_filter(GdkXEvent *xev, GdkEvent *event, gpointer data)
2486 XEvent *xevent = (XEvent *)xev;
2488 if (xevent != NULL
2489 && xevent->type == ClientMessage
2490 && xevent->xclient.message_type == GET_X_ATOM(wm_protocols_atom)
2491 && xevent->xclient.data.l[0] == GET_X_ATOM(save_yourself_atom))
2493 out_flush();
2494 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
2496 * Set the window's WM_COMMAND property, to let the window manager
2497 * know we are done saving ourselves. We don't want to be
2498 * restarted, thus set argv to NULL.
2500 XSetCommand(GDK_WINDOW_XDISPLAY(gui.mainwin->window),
2501 GDK_WINDOW_XWINDOW(gui.mainwin->window),
2502 NULL, 0);
2503 return GDK_FILTER_REMOVE;
2506 return GDK_FILTER_CONTINUE;
2509 # else /* !HAVE_GTK2 */
2512 * GDK handler for X ClientMessage events.
2514 /*ARGSUSED2*/
2515 static GdkFilterReturn
2516 gdk_wm_protocols_filter(GdkXEvent *xev, GdkEvent *event, gpointer data)
2518 /* From example in gdkevents.c/gdk_wm_protocols_filter */
2519 XEvent *xevent = (XEvent *)xev;
2521 if (xevent != NULL)
2523 if (xevent->xclient.data.l[0] == GET_X_ATOM(save_yourself_atom))
2525 out_flush();
2526 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
2528 /* Set the window's WM_COMMAND property, to let the window manager
2529 * know we are done saving ourselves. We don't want to be
2530 * restarted, thus set argv to NULL. */
2531 XSetCommand(GDK_WINDOW_XDISPLAY(gui.mainwin->window),
2532 GDK_WINDOW_XWINDOW(gui.mainwin->window),
2533 NULL, 0);
2536 * Functionality from gdkevents.c/gdk_wm_protocols_filter;
2537 * Registering this filter apparently overrides the default GDK one,
2538 * so we need to perform its functionality. There seems no way to
2539 * register for WM_PROTOCOLS, and only process the WM_SAVE_YOURSELF
2540 * bit; it's all or nothing. Update: No, there is a way -- but it
2541 * only works with GTK+ 2 apparently. See above.
2543 else if (xevent->xclient.data.l[0] == GET_X_ATOM(gdk_wm_delete_window))
2545 event->any.type = GDK_DELETE;
2546 return GDK_FILTER_TRANSLATE;
2550 return GDK_FILTER_REMOVE;
2552 # endif /* !HAVE_GTK2 */
2554 #endif /* !(FEAT_GUI_GNOME && FEAT_SESSION) */
2558 * Setup the window icon & xcmdsrv comm after the main window has been realized.
2560 /*ARGSUSED*/
2561 static void
2562 mainwin_realize(GtkWidget *widget, gpointer data)
2564 /* If you get an error message here, you still need to unpack the runtime
2565 * archive! */
2566 #ifdef magick
2567 # undef magick
2568 #endif
2569 #ifdef HAVE_GTK2
2570 /* A bit hackish, but avoids casting later and allows optimization */
2571 # define static static const
2572 #endif
2573 #define magick vim32x32
2574 #include "../runtime/vim32x32.xpm"
2575 #undef magick
2576 #define magick vim16x16
2577 #include "../runtime/vim16x16.xpm"
2578 #undef magick
2579 #define magick vim48x48
2580 #include "../runtime/vim48x48.xpm"
2581 #undef magick
2582 #ifdef HAVE_GTK2
2583 # undef static
2584 #endif
2586 /* When started with "--echo-wid" argument, write window ID on stdout. */
2587 if (echo_wid_arg)
2589 printf("WID: %ld\n", (long)GDK_WINDOW_XWINDOW(gui.mainwin->window));
2590 fflush(stdout);
2593 if (vim_strchr(p_go, GO_ICON) != NULL)
2596 * Add an icon to the main window. For fun and convenience of the user.
2598 #ifdef HAVE_GTK2
2599 GList *icons = NULL;
2601 icons = g_list_prepend(icons, gdk_pixbuf_new_from_xpm_data(vim16x16));
2602 icons = g_list_prepend(icons, gdk_pixbuf_new_from_xpm_data(vim32x32));
2603 icons = g_list_prepend(icons, gdk_pixbuf_new_from_xpm_data(vim48x48));
2605 gtk_window_set_icon_list(GTK_WINDOW(gui.mainwin), icons);
2607 g_list_foreach(icons, (GFunc)&g_object_unref, NULL);
2608 g_list_free(icons);
2610 #else /* !HAVE_GTK2 */
2612 GdkPixmap *icon;
2613 GdkBitmap *icon_mask = NULL;
2614 char **magick = vim32x32;
2615 Display *xdisplay;
2616 Window root_window;
2617 XIconSize *size;
2618 int number_sizes;
2620 * Adjust the icon to the preferences of the actual window manager.
2621 * This is once again a workaround for a deficiency in GTK+ 1.2.
2623 xdisplay = GDK_WINDOW_XDISPLAY(gui.mainwin->window);
2624 root_window = XRootWindow(xdisplay, DefaultScreen(xdisplay));
2625 if (XGetIconSizes(xdisplay, root_window, &size, &number_sizes))
2627 if (number_sizes > 0)
2629 if (size->max_height >= 48 && size->max_height >= 48)
2630 magick = vim48x48;
2631 else if (size->max_height >= 32 && size->max_height >= 32)
2632 magick = vim32x32;
2633 else if (size->max_height >= 16 && size->max_height >= 16)
2634 magick = vim16x16;
2636 XFree(size);
2638 icon = gdk_pixmap_create_from_xpm_d(gui.mainwin->window,
2639 &icon_mask, NULL, magick);
2640 if (icon != NULL)
2641 /* Note: for some reason gdk_window_set_icon() doesn't acquire
2642 * a reference on the pixmap, thus we _have_ to leak it. */
2643 gdk_window_set_icon(gui.mainwin->window, NULL, icon, icon_mask);
2645 #endif /* !HAVE_GTK2 */
2648 #if !(defined(FEAT_GUI_GNOME) && defined(FEAT_SESSION))
2649 /* Register a handler for WM_SAVE_YOURSELF with GDK's low-level X I/F */
2650 # ifdef HAVE_GTK2
2651 gdk_window_add_filter(NULL, &global_event_filter, NULL);
2652 # else
2653 gdk_add_client_message_filter(wm_protocols_atom,
2654 &gdk_wm_protocols_filter, NULL);
2655 # endif
2656 #endif
2657 /* Setup to indicate to the window manager that we want to catch the
2658 * WM_SAVE_YOURSELF event. For GNOME, this connects to the session
2659 * manager instead. */
2660 #if defined(FEAT_GUI_GNOME) && defined(FEAT_SESSION)
2661 if (using_gnome)
2662 #endif
2663 setup_save_yourself();
2665 #ifdef FEAT_CLIENTSERVER
2666 if (serverName == NULL && serverDelayedStartName != NULL)
2668 /* This is a :gui command in a plain vim with no previous server */
2669 commWindow = GDK_WINDOW_XWINDOW(gui.mainwin->window);
2671 (void)serverRegisterName(GDK_WINDOW_XDISPLAY(gui.mainwin->window),
2672 serverDelayedStartName);
2674 else
2677 * Cannot handle "XLib-only" windows with gtk event routines, we'll
2678 * have to change the "server" registration to that of the main window
2679 * If we have not registered a name yet, remember the window
2681 serverChangeRegisteredWindow(GDK_WINDOW_XDISPLAY(gui.mainwin->window),
2682 GDK_WINDOW_XWINDOW(gui.mainwin->window));
2684 gtk_widget_add_events(gui.mainwin, GDK_PROPERTY_CHANGE_MASK);
2685 gtk_signal_connect(GTK_OBJECT(gui.mainwin), "property_notify_event",
2686 GTK_SIGNAL_FUNC(property_event), NULL);
2687 #endif
2690 static GdkCursor *
2691 create_blank_pointer(void)
2693 GdkWindow *root_window = NULL;
2694 GdkPixmap *blank_mask;
2695 GdkCursor *cursor;
2696 GdkColor color = { 0, 0, 0, 0 };
2697 char blank_data[] = { 0x0 };
2699 #ifdef HAVE_GTK_MULTIHEAD
2700 root_window = gtk_widget_get_root_window(gui.mainwin);
2701 #endif
2703 /* Create a pseudo blank pointer, which is in fact one pixel by one pixel
2704 * in size. */
2705 blank_mask = gdk_bitmap_create_from_data(root_window, blank_data, 1, 1);
2706 cursor = gdk_cursor_new_from_pixmap(blank_mask, blank_mask,
2707 &color, &color, 0, 0);
2708 gdk_bitmap_unref(blank_mask);
2710 return cursor;
2713 #ifdef HAVE_GTK_MULTIHEAD
2714 /*ARGSUSED1*/
2715 static void
2716 mainwin_screen_changed_cb(GtkWidget *widget,
2717 GdkScreen *previous_screen,
2718 gpointer data)
2720 if (!gtk_widget_has_screen(widget))
2721 return;
2724 * Recreate the invisible mouse cursor.
2726 if (gui.blank_pointer != NULL)
2727 gdk_cursor_unref(gui.blank_pointer);
2729 gui.blank_pointer = create_blank_pointer();
2731 if (gui.pointer_hidden && gui.drawarea->window != NULL)
2732 gdk_window_set_cursor(gui.drawarea->window, gui.blank_pointer);
2735 * Create a new PangoContext for this screen, and initialize it
2736 * with the current font if necessary.
2738 if (gui.text_context != NULL)
2739 g_object_unref(gui.text_context);
2741 gui.text_context = gtk_widget_create_pango_context(widget);
2742 pango_context_set_base_dir(gui.text_context, PANGO_DIRECTION_LTR);
2744 if (gui.norm_font != NULL)
2746 gui_mch_init_font(p_guifont, FALSE);
2747 gui_set_shellsize(FALSE, FALSE, RESIZE_BOTH);
2750 #endif /* HAVE_GTK_MULTIHEAD */
2753 * After the drawing area comes up, we calculate all colors and create the
2754 * dummy blank cursor.
2756 * Don't try to set any VIM scrollbar sizes anywhere here. I'm relying on the
2757 * fact that the main VIM engine doesn't take them into account anywhere.
2759 /*ARGSUSED1*/
2760 static void
2761 drawarea_realize_cb(GtkWidget *widget, gpointer data)
2763 GtkWidget *sbar;
2765 #ifdef FEAT_XIM
2766 xim_init();
2767 #endif
2768 gui_mch_new_colors();
2769 gui.text_gc = gdk_gc_new(gui.drawarea->window);
2771 gui.blank_pointer = create_blank_pointer();
2772 if (gui.pointer_hidden)
2773 gdk_window_set_cursor(widget->window, gui.blank_pointer);
2775 /* get the actual size of the scrollbars, if they are realized */
2776 sbar = firstwin->w_scrollbars[SBAR_LEFT].id;
2777 if (!sbar || (!gui.which_scrollbars[SBAR_LEFT]
2778 && firstwin->w_scrollbars[SBAR_RIGHT].id))
2779 sbar = firstwin->w_scrollbars[SBAR_RIGHT].id;
2780 if (sbar && GTK_WIDGET_REALIZED(sbar) && sbar->allocation.width)
2781 gui.scrollbar_width = sbar->allocation.width;
2783 sbar = gui.bottom_sbar.id;
2784 if (sbar && GTK_WIDGET_REALIZED(sbar) && sbar->allocation.height)
2785 gui.scrollbar_height = sbar->allocation.height;
2789 * Properly clean up on shutdown.
2791 /*ARGSUSED0*/
2792 static void
2793 drawarea_unrealize_cb(GtkWidget *widget, gpointer data)
2795 /* Don't write messages to the GUI anymore */
2796 full_screen = FALSE;
2798 #ifdef FEAT_XIM
2799 im_shutdown();
2800 #endif
2801 #ifdef HAVE_GTK2
2802 if (gui.ascii_glyphs != NULL)
2804 pango_glyph_string_free(gui.ascii_glyphs);
2805 gui.ascii_glyphs = NULL;
2807 if (gui.ascii_font != NULL)
2809 g_object_unref(gui.ascii_font);
2810 gui.ascii_font = NULL;
2812 g_object_unref(gui.text_context);
2813 gui.text_context = NULL;
2815 g_object_unref(gui.text_gc);
2816 gui.text_gc = NULL;
2818 gdk_cursor_unref(gui.blank_pointer);
2819 gui.blank_pointer = NULL;
2820 #else
2821 gdk_gc_unref(gui.text_gc);
2822 gui.text_gc = NULL;
2824 gdk_cursor_destroy(gui.blank_pointer);
2825 gui.blank_pointer = NULL;
2826 #endif
2829 /*ARGSUSED0*/
2830 static void
2831 drawarea_style_set_cb(GtkWidget *widget,
2832 GtkStyle *previous_style,
2833 gpointer data)
2835 gui_mch_new_colors();
2839 * Callback routine for the "delete_event" signal on the toplevel window.
2840 * Tries to vim gracefully, or refuses to exit with changed buffers.
2842 /*ARGSUSED*/
2843 static gint
2844 delete_event_cb(GtkWidget *widget, GdkEventAny *event, gpointer data)
2846 gui_shell_closed();
2847 return TRUE;
2850 #if defined(FEAT_MENU) || defined(FEAT_TOOLBAR) || defined(FEAT_GUI_TABLINE)
2851 static int
2852 get_item_dimensions(GtkWidget *widget, GtkOrientation orientation)
2854 GtkOrientation item_orientation = GTK_ORIENTATION_HORIZONTAL;
2856 #ifdef FEAT_GUI_GNOME
2857 if (using_gnome && widget != NULL)
2859 # ifdef HAVE_GTK2
2860 GtkWidget *parent;
2861 BonoboDockItem *dockitem;
2863 parent = gtk_widget_get_parent(widget);
2864 if (G_TYPE_FROM_INSTANCE(parent) == BONOBO_TYPE_DOCK_ITEM)
2866 /* Only menu & toolbar are dock items. Could tabline be?
2867 * Seem to be only the 2 defined in GNOME */
2868 widget = parent;
2869 dockitem = BONOBO_DOCK_ITEM(widget);
2871 if (dockitem == NULL || dockitem->is_floating)
2872 return 0;
2873 item_orientation = bonobo_dock_item_get_orientation(dockitem);
2875 # else
2876 GnomeDockItem *dockitem;
2878 widget = widget->parent;
2879 dockitem = GNOME_DOCK_ITEM(widget);
2881 if (dockitem == NULL || dockitem->is_floating)
2882 return 0;
2883 item_orientation = gnome_dock_item_get_orientation(dockitem);
2884 # endif
2886 #endif
2887 if (widget != NULL
2888 && item_orientation == orientation
2889 && GTK_WIDGET_REALIZED(widget)
2890 && GTK_WIDGET_VISIBLE(widget))
2892 if (orientation == GTK_ORIENTATION_HORIZONTAL)
2893 return widget->allocation.height;
2894 else
2895 return widget->allocation.width;
2897 return 0;
2899 #endif
2901 static int
2902 get_menu_tool_width(void)
2904 int width = 0;
2906 #ifdef FEAT_GUI_GNOME /* these are never vertical without GNOME */
2907 # ifdef FEAT_MENU
2908 width += get_item_dimensions(gui.menubar, GTK_ORIENTATION_VERTICAL);
2909 # endif
2910 # ifdef FEAT_TOOLBAR
2911 width += get_item_dimensions(gui.toolbar, GTK_ORIENTATION_VERTICAL);
2912 # endif
2913 # ifdef FEAT_GUI_TABLINE
2914 if (gui.tabline != NULL)
2915 width += get_item_dimensions(gui.tabline, GTK_ORIENTATION_VERTICAL);
2916 # endif
2917 #endif
2919 return width;
2922 static int
2923 get_menu_tool_height(void)
2925 int height = 0;
2927 #ifdef FEAT_MENU
2928 height += get_item_dimensions(gui.menubar, GTK_ORIENTATION_HORIZONTAL);
2929 #endif
2930 #ifdef FEAT_TOOLBAR
2931 height += get_item_dimensions(gui.toolbar, GTK_ORIENTATION_HORIZONTAL);
2932 #endif
2933 #ifdef FEAT_GUI_TABLINE
2934 if (gui.tabline != NULL)
2935 height += get_item_dimensions(gui.tabline, GTK_ORIENTATION_HORIZONTAL);
2936 #endif
2938 return height;
2941 /* This controls whether we can set the real window hints at
2942 * start-up when in a GtkPlug.
2943 * 0 = normal processing (default)
2944 * 1 = init. hints set, no-one's tried to reset since last check
2945 * 2 = init. hints set, attempt made to change hints
2947 static int init_window_hints_state = 0;
2949 static void
2950 update_window_manager_hints(int force_width, int force_height)
2952 static int old_width = 0;
2953 static int old_height = 0;
2954 static int old_min_width = 0;
2955 static int old_min_height = 0;
2956 static int old_char_width = 0;
2957 static int old_char_height = 0;
2959 int width;
2960 int height;
2961 int min_width;
2962 int min_height;
2964 /* At start-up, don't try to set the hints until the initial
2965 * values have been used (those that dictate our initial size)
2966 * Let forced (i.e., correct) values thruogh always.
2968 if (!(force_width && force_height) && init_window_hints_state > 0)
2970 /* Don't do it! */
2971 init_window_hints_state = 2;
2972 return;
2975 /* This also needs to be done when the main window isn't there yet,
2976 * otherwise the hints don't work. */
2977 width = gui_get_base_width();
2978 height = gui_get_base_height();
2979 # ifdef FEAT_MENU
2980 height += tabline_height() * gui.char_height;
2981 # endif
2982 # ifdef HAVE_GTK2
2983 width += get_menu_tool_width();
2984 height += get_menu_tool_height();
2985 # endif
2987 /* GtkSockets use GtkPlug's [gui,mainwin] min-size hints to determine
2988 * their actual widget size. When we set our size ourselves (e.g.,
2989 * 'set columns=' or init. -geom) we briefly set the min. to the size
2990 * we wish to be instead of the legitimate minimum so that we actually
2991 * resize correctly.
2993 if (force_width && force_height)
2995 min_width = force_width;
2996 min_height = force_height;
2998 else
3000 min_width = width + MIN_COLUMNS * gui.char_width;
3001 min_height = height + MIN_LINES * gui.char_height;
3004 /* Avoid an expose event when the size didn't change. */
3005 if (width != old_width
3006 || height != old_height
3007 || min_width != old_min_width
3008 || min_height != old_min_height
3009 || gui.char_width != old_char_width
3010 || gui.char_height != old_char_height)
3012 GdkGeometry geometry;
3013 GdkWindowHints geometry_mask;
3015 geometry.width_inc = gui.char_width;
3016 geometry.height_inc = gui.char_height;
3017 geometry.base_width = width;
3018 geometry.base_height = height;
3019 geometry.min_width = min_width;
3020 geometry.min_height = min_height;
3021 geometry_mask = GDK_HINT_BASE_SIZE|GDK_HINT_RESIZE_INC
3022 |GDK_HINT_MIN_SIZE;
3023 # ifdef HAVE_GTK2
3024 /* Using gui.formwin as geometry widget doesn't work as expected
3025 * with GTK+ 2 -- dunno why. Presumably all the resizing hacks
3026 * in Vim confuse GTK+. */
3027 gtk_window_set_geometry_hints(GTK_WINDOW(gui.mainwin), gui.mainwin,
3028 &geometry, geometry_mask);
3029 # else
3030 gtk_window_set_geometry_hints(GTK_WINDOW(gui.mainwin), gui.formwin,
3031 &geometry, geometry_mask);
3032 # endif
3033 old_width = width;
3034 old_height = height;
3035 old_min_width = min_width;
3036 old_min_height = min_height;
3037 old_char_width = gui.char_width;
3038 old_char_height = gui.char_height;
3042 #ifdef FEAT_TOOLBAR
3044 # ifdef HAVE_GTK2
3046 * This extra effort wouldn't be necessary if we only used stock icons in the
3047 * toolbar, as we do for all builtin icons. But user-defined toolbar icons
3048 * shouldn't be treated differently, thus we do need this.
3050 static void
3051 icon_size_changed_foreach(GtkWidget *widget, gpointer user_data)
3053 if (GTK_IS_IMAGE(widget))
3055 GtkImage *image = (GtkImage *)widget;
3057 /* User-defined icons are stored in a GtkIconSet */
3058 if (gtk_image_get_storage_type(image) == GTK_IMAGE_ICON_SET)
3060 GtkIconSet *icon_set;
3061 GtkIconSize icon_size;
3063 gtk_image_get_icon_set(image, &icon_set, &icon_size);
3064 icon_size = (GtkIconSize)(long)user_data;
3066 gtk_icon_set_ref(icon_set);
3067 gtk_image_set_from_icon_set(image, icon_set, icon_size);
3068 gtk_icon_set_unref(icon_set);
3071 else if (GTK_IS_CONTAINER(widget))
3073 gtk_container_foreach((GtkContainer *)widget,
3074 &icon_size_changed_foreach,
3075 user_data);
3078 # endif /* HAVE_GTK2 */
3080 static void
3081 set_toolbar_style(GtkToolbar *toolbar)
3083 GtkToolbarStyle style;
3084 # ifdef HAVE_GTK2
3085 GtkIconSize size;
3086 GtkIconSize oldsize;
3087 # endif
3089 # ifdef HAVE_GTK2
3090 if ((toolbar_flags & (TOOLBAR_TEXT | TOOLBAR_ICONS | TOOLBAR_HORIZ))
3091 == (TOOLBAR_TEXT | TOOLBAR_ICONS | TOOLBAR_HORIZ))
3092 style = GTK_TOOLBAR_BOTH_HORIZ;
3093 else
3094 # endif
3095 if ((toolbar_flags & (TOOLBAR_TEXT | TOOLBAR_ICONS))
3096 == (TOOLBAR_TEXT | TOOLBAR_ICONS))
3097 style = GTK_TOOLBAR_BOTH;
3098 else if (toolbar_flags & TOOLBAR_TEXT)
3099 style = GTK_TOOLBAR_TEXT;
3100 else
3101 style = GTK_TOOLBAR_ICONS;
3103 gtk_toolbar_set_style(toolbar, style);
3104 gtk_toolbar_set_tooltips(toolbar, (toolbar_flags & TOOLBAR_TOOLTIPS) != 0);
3106 # ifdef HAVE_GTK2
3107 switch (tbis_flags)
3109 case TBIS_TINY: size = GTK_ICON_SIZE_MENU; break;
3110 case TBIS_SMALL: size = GTK_ICON_SIZE_SMALL_TOOLBAR; break;
3111 case TBIS_MEDIUM: size = GTK_ICON_SIZE_BUTTON; break;
3112 case TBIS_LARGE: size = GTK_ICON_SIZE_LARGE_TOOLBAR; break;
3113 default: size = GTK_ICON_SIZE_INVALID; break;
3115 oldsize = gtk_toolbar_get_icon_size(toolbar);
3117 if (size == GTK_ICON_SIZE_INVALID)
3119 /* Let global user preferences decide the icon size. */
3120 gtk_toolbar_unset_icon_size(toolbar);
3121 size = gtk_toolbar_get_icon_size(toolbar);
3123 if (size != oldsize)
3125 gtk_container_foreach(GTK_CONTAINER(toolbar),
3126 &icon_size_changed_foreach,
3127 GINT_TO_POINTER((int)size));
3129 gtk_toolbar_set_icon_size(toolbar, size);
3130 # endif
3133 #endif /* FEAT_TOOLBAR */
3135 #if defined(FEAT_GUI_TABLINE) || defined(PROTO)
3136 static int ignore_tabline_evt = FALSE;
3137 static GtkWidget *tabline_menu;
3138 static GtkTooltips *tabline_tooltip;
3139 static int clicked_page; /* page clicked in tab line */
3142 * Handle selecting an item in the tab line popup menu.
3144 /*ARGSUSED*/
3145 static void
3146 tabline_menu_handler(GtkMenuItem *item, gpointer user_data)
3148 /* Add the string cmd into input buffer */
3149 send_tabline_menu_event(clicked_page, (int)(long)user_data);
3151 if (gtk_main_level() > 0)
3152 gtk_main_quit();
3155 static void
3156 add_tabline_menu_item(GtkWidget *menu, char_u *text, int resp)
3158 GtkWidget *item;
3159 char_u *utf_text;
3161 utf_text = CONVERT_TO_UTF8(text);
3162 item = gtk_menu_item_new_with_label((const char *)utf_text);
3163 gtk_widget_show(item);
3164 CONVERT_TO_UTF8_FREE(utf_text);
3166 gtk_container_add(GTK_CONTAINER(menu), item);
3167 gtk_signal_connect(GTK_OBJECT(item), "activate",
3168 GTK_SIGNAL_FUNC(tabline_menu_handler),
3169 (gpointer)resp);
3173 * Create a menu for the tab line.
3175 static GtkWidget *
3176 create_tabline_menu(void)
3178 GtkWidget *menu;
3180 menu = gtk_menu_new();
3181 add_tabline_menu_item(menu, (char_u *)_("Close"), TABLINE_MENU_CLOSE);
3182 add_tabline_menu_item(menu, (char_u *)_("New tab"), TABLINE_MENU_NEW);
3183 add_tabline_menu_item(menu, (char_u *)_("Open Tab..."), TABLINE_MENU_OPEN);
3185 return menu;
3188 static gboolean
3189 on_tabline_menu(GtkWidget *widget, GdkEvent *event)
3191 /* Was this button press event ? */
3192 if (event->type == GDK_BUTTON_PRESS)
3194 GdkEventButton *bevent = (GdkEventButton *)event;
3195 int x = bevent->x;
3196 int y = bevent->y;
3197 GtkWidget *tabwidget;
3198 GdkWindow *tabwin;
3200 /* When ignoring events return TRUE so that the selected page doesn't
3201 * change. */
3202 if (hold_gui_events
3203 # ifdef FEAT_CMDWIN
3204 || cmdwin_type != 0
3205 # endif
3207 return TRUE;
3209 tabwin = gdk_window_at_pointer(&x, &y);
3210 gdk_window_get_user_data(tabwin, (gpointer)&tabwidget);
3211 clicked_page = (int)(long)gtk_object_get_user_data(
3212 GTK_OBJECT(tabwidget));
3214 /* If the event was generated for 3rd button popup the menu. */
3215 if (bevent->button == 3)
3217 gtk_menu_popup(GTK_MENU(widget), NULL, NULL, NULL, NULL,
3218 bevent->button, bevent->time);
3219 /* We handled the event. */
3220 return TRUE;
3222 else if (bevent->button == 1)
3224 if (clicked_page == 0)
3226 /* Click after all tabs moves to next tab page. When "x" is
3227 * small guess it's the left button. */
3228 if (send_tabline_event(x < 50 ? -1 : 0) && gtk_main_level() > 0)
3229 gtk_main_quit();
3231 #ifndef HAVE_GTK2
3232 else
3233 gtk_notebook_set_page(GTK_NOTEBOOK(gui.tabline),
3234 clicked_page - 1);
3235 #endif
3239 /* We didn't handle the event. */
3240 return FALSE;
3244 * Handle selecting one of the tabs.
3246 /*ARGSUSED*/
3247 static void
3248 on_select_tab(
3249 GtkNotebook *notebook,
3250 GtkNotebookPage *page,
3251 gint idx,
3252 gpointer data)
3254 if (!ignore_tabline_evt)
3256 if (send_tabline_event(idx + 1) && gtk_main_level() > 0)
3257 gtk_main_quit();
3261 #ifndef HAVE_GTK2
3262 static int showing_tabline = 0;
3263 #endif
3266 * Show or hide the tabline.
3268 void
3269 gui_mch_show_tabline(int showit)
3271 if (gui.tabline == NULL)
3272 return;
3274 #ifdef HAVE_GTK2
3275 /* gtk_notebook_get_show_tabs does not exist in gtk+-1.2.10 */
3276 if (!showit != !gtk_notebook_get_show_tabs(GTK_NOTEBOOK(gui.tabline)))
3277 #else
3278 if (!showit != !showing_tabline)
3279 #endif
3281 /* Note: this may cause a resize event */
3282 gtk_notebook_set_show_tabs(GTK_NOTEBOOK(gui.tabline), showit);
3283 update_window_manager_hints(0, 0);
3284 #ifndef HAVE_GTK2
3285 showing_tabline = showit;
3286 #endif
3287 if (showit)
3288 GTK_WIDGET_UNSET_FLAGS(GTK_WIDGET(gui.tabline), GTK_CAN_FOCUS);
3291 gui_mch_update();
3295 * Return TRUE when tabline is displayed.
3298 gui_mch_showing_tabline(void)
3300 return gui.tabline != NULL
3301 #ifdef HAVE_GTK2
3302 /* gtk_notebook_get_show_tabs does not exist in gtk+-1.2.10 */
3303 && gtk_notebook_get_show_tabs(GTK_NOTEBOOK(gui.tabline))
3304 #else
3305 && showing_tabline
3306 #endif
3311 * Update the labels of the tabline.
3313 void
3314 gui_mch_update_tabline(void)
3316 GtkWidget *page;
3317 GtkWidget *event_box;
3318 GtkWidget *label;
3319 tabpage_T *tp;
3320 int nr = 0;
3321 int tab_num;
3322 int curtabidx = 0;
3323 char_u *labeltext;
3325 if (gui.tabline == NULL)
3326 return;
3328 ignore_tabline_evt = TRUE;
3330 /* Add a label for each tab page. They all contain the same text area. */
3331 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next, ++nr)
3333 if (tp == curtab)
3334 curtabidx = nr;
3336 tab_num = nr + 1;
3338 page = gtk_notebook_get_nth_page(GTK_NOTEBOOK(gui.tabline), nr);
3339 if (page == NULL)
3341 /* Add notebook page */
3342 page = gtk_vbox_new(FALSE, 0);
3343 gtk_widget_show(page);
3344 event_box = gtk_event_box_new();
3345 gtk_widget_show(event_box);
3346 label = gtk_label_new("-Empty-");
3347 gtk_misc_set_padding(GTK_MISC(label), 2, 2);
3348 gtk_container_add(GTK_CONTAINER(event_box), label);
3349 gtk_widget_show(label);
3350 gtk_notebook_insert_page(GTK_NOTEBOOK(gui.tabline),
3351 page,
3352 event_box,
3353 nr++);
3356 event_box = gtk_notebook_get_tab_label(GTK_NOTEBOOK(gui.tabline), page);
3357 gtk_object_set_user_data(GTK_OBJECT(event_box), (gpointer)tab_num);
3358 label = GTK_BIN(event_box)->child;
3359 get_tabline_label(tp, FALSE);
3360 labeltext = CONVERT_TO_UTF8(NameBuff);
3361 gtk_label_set_text(GTK_LABEL(label), (const char *)labeltext);
3362 CONVERT_TO_UTF8_FREE(labeltext);
3364 get_tabline_label(tp, TRUE);
3365 labeltext = CONVERT_TO_UTF8(NameBuff);
3366 gtk_tooltips_set_tip(GTK_TOOLTIPS(tabline_tooltip), event_box,
3367 (const char *)labeltext, NULL);
3368 CONVERT_TO_UTF8_FREE(labeltext);
3371 /* Remove any old labels. */
3372 while (gtk_notebook_get_nth_page(GTK_NOTEBOOK(gui.tabline), nr) != NULL)
3373 gtk_notebook_remove_page(GTK_NOTEBOOK(gui.tabline), nr);
3375 if (gtk_notebook_current_page(GTK_NOTEBOOK(gui.tabline)) != curtabidx)
3376 gtk_notebook_set_page(GTK_NOTEBOOK(gui.tabline), curtabidx);
3378 /* Make sure everything is in place before drawing text. */
3379 gui_mch_update();
3381 ignore_tabline_evt = FALSE;
3385 * Set the current tab to "nr". First tab is 1.
3387 void
3388 gui_mch_set_curtab(nr)
3389 int nr;
3391 if (gui.tabline == NULL)
3392 return;
3394 ignore_tabline_evt = TRUE;
3395 if (gtk_notebook_current_page(GTK_NOTEBOOK(gui.tabline)) != nr - 1)
3396 gtk_notebook_set_page(GTK_NOTEBOOK(gui.tabline), nr - 1);
3397 ignore_tabline_evt = FALSE;
3400 #endif /* FEAT_GUI_TABLINE */
3403 * Initialize the GUI. Create all the windows, set up all the callbacks etc.
3404 * Returns OK for success, FAIL when the GUI can't be started.
3407 gui_mch_init(void)
3409 GtkWidget *vbox;
3411 #ifdef FEAT_GUI_GNOME
3412 /* Initialize the GNOME libraries. gnome_program_init()/gnome_init()
3413 * exits on failure, but that's a non-issue because we already called
3414 * gtk_init_check() in gui_mch_init_check(). */
3415 if (using_gnome)
3416 # ifdef HAVE_GTK2
3417 gnome_program_init(VIMPACKAGE, VIM_VERSION_SHORT,
3418 LIBGNOMEUI_MODULE, gui_argc, gui_argv, NULL);
3419 # else
3420 gnome_init(VIMPACKAGE, VIM_VERSION_SHORT, gui_argc, gui_argv);
3421 # endif
3422 #endif
3423 vim_free(gui_argv);
3424 gui_argv = NULL;
3426 #ifdef HAVE_GTK2
3427 # if GLIB_CHECK_VERSION(2,1,3)
3428 /* Set the human-readable application name */
3429 g_set_application_name("Vim");
3430 # endif
3432 * Force UTF-8 output no matter what the value of 'encoding' is.
3433 * did_set_string_option() in option.c prohibits changing 'termencoding'
3434 * to something else than UTF-8 if the GUI is in use.
3436 set_option_value((char_u *)"termencoding", 0L, (char_u *)"utf-8", 0);
3438 # ifdef FEAT_TOOLBAR
3439 gui_gtk_register_stock_icons();
3440 # endif
3441 /* FIXME: Need to install the classic icons and a gtkrc.classic file.
3442 * The hard part is deciding install locations and the Makefile magic. */
3443 # if 0
3444 gtk_rc_parse("gtkrc");
3445 # endif
3446 #endif
3448 /* Initialize values */
3449 gui.border_width = 2;
3450 gui.scrollbar_width = SB_DEFAULT_WIDTH;
3451 gui.scrollbar_height = SB_DEFAULT_WIDTH;
3452 /* LINTED: avoid warning: conversion to 'unsigned long' */
3453 gui.fgcolor = g_new0(GdkColor, 1);
3454 /* LINTED: avoid warning: conversion to 'unsigned long' */
3455 gui.bgcolor = g_new0(GdkColor, 1);
3456 /* LINTED: avoid warning: conversion to 'unsigned long' */
3457 gui.spcolor = g_new0(GdkColor, 1);
3459 /* Initialise atoms */
3460 #ifdef FEAT_MBYTE
3461 utf8_string_atom = gdk_atom_intern("UTF8_STRING", FALSE);
3462 #endif
3463 #ifndef HAVE_GTK2
3464 compound_text_atom = gdk_atom_intern("COMPOUND_TEXT", FALSE);
3465 text_atom = gdk_atom_intern("TEXT", FALSE);
3466 #endif
3468 /* Set default foreground and background colors. */
3469 gui.norm_pixel = gui.def_norm_pixel;
3470 gui.back_pixel = gui.def_back_pixel;
3472 if (gtk_socket_id != 0)
3474 GtkWidget *plug;
3476 /* Use GtkSocket from another app. */
3477 #ifdef HAVE_GTK_MULTIHEAD
3478 plug = gtk_plug_new_for_display(gdk_display_get_default(),
3479 gtk_socket_id);
3480 #else
3481 plug = gtk_plug_new(gtk_socket_id);
3482 #endif
3483 if (plug != NULL && GTK_PLUG(plug)->socket_window != NULL)
3485 gui.mainwin = plug;
3487 else
3489 g_warning("Connection to GTK+ socket (ID %u) failed",
3490 (unsigned int)gtk_socket_id);
3491 /* Pretend we never wanted it if it failed (get own window) */
3492 gtk_socket_id = 0;
3496 if (gtk_socket_id == 0)
3498 #ifdef FEAT_GUI_GNOME
3499 if (using_gnome)
3501 gui.mainwin = gnome_app_new("Vim", NULL);
3502 # ifdef USE_XSMP
3503 /* Use the GNOME save-yourself functionality now. */
3504 xsmp_close();
3505 # endif
3507 else
3508 #endif
3509 gui.mainwin = gtk_window_new(GTK_WINDOW_TOPLEVEL);
3512 gtk_widget_set_name(gui.mainwin, "vim-main-window");
3514 #ifdef HAVE_GTK2
3515 /* Create the PangoContext used for drawing all text. */
3516 gui.text_context = gtk_widget_create_pango_context(gui.mainwin);
3517 pango_context_set_base_dir(gui.text_context, PANGO_DIRECTION_LTR);
3518 #endif
3520 #ifndef HAVE_GTK2
3521 gtk_window_set_policy(GTK_WINDOW(gui.mainwin), TRUE, TRUE, TRUE);
3522 #endif
3523 gtk_container_border_width(GTK_CONTAINER(gui.mainwin), 0);
3524 gtk_widget_add_events(gui.mainwin, GDK_VISIBILITY_NOTIFY_MASK);
3526 gtk_signal_connect(GTK_OBJECT(gui.mainwin), "delete_event",
3527 GTK_SIGNAL_FUNC(&delete_event_cb), NULL);
3529 gtk_signal_connect(GTK_OBJECT(gui.mainwin), "realize",
3530 GTK_SIGNAL_FUNC(&mainwin_realize), NULL);
3531 #ifdef HAVE_GTK_MULTIHEAD
3532 g_signal_connect(G_OBJECT(gui.mainwin), "screen_changed",
3533 G_CALLBACK(&mainwin_screen_changed_cb), NULL);
3534 #endif
3535 #ifdef HAVE_GTK2
3536 gui.accel_group = gtk_accel_group_new();
3537 gtk_window_add_accel_group(GTK_WINDOW(gui.mainwin), gui.accel_group);
3538 #else
3539 gui.accel_group = gtk_accel_group_get_default();
3540 #endif
3542 /* A vertical box holds the menubar, toolbar and main text window. */
3543 vbox = gtk_vbox_new(FALSE, 0);
3545 #ifdef FEAT_GUI_GNOME
3546 if (using_gnome)
3548 # if defined(HAVE_GTK2) && defined(FEAT_MENU)
3549 /* automagically restore menubar/toolbar placement */
3550 gnome_app_enable_layout_config(GNOME_APP(gui.mainwin), TRUE);
3551 # endif
3552 gnome_app_set_contents(GNOME_APP(gui.mainwin), vbox);
3554 else
3555 #endif
3557 gtk_container_add(GTK_CONTAINER(gui.mainwin), vbox);
3558 gtk_widget_show(vbox);
3561 #ifdef FEAT_MENU
3563 * Create the menubar and handle
3565 gui.menubar = gtk_menu_bar_new();
3566 gtk_widget_set_name(gui.menubar, "vim-menubar");
3568 # ifdef HAVE_GTK2
3569 /* Avoid that GTK takes <F10> away from us. */
3571 GtkSettings *gtk_settings;
3573 gtk_settings = gtk_settings_get_for_screen(gdk_screen_get_default());
3574 g_object_set(gtk_settings, "gtk-menu-bar-accel", NULL, NULL);
3576 # endif
3579 # ifdef FEAT_GUI_GNOME
3580 if (using_gnome)
3582 # ifdef HAVE_GTK2
3583 BonoboDockItem *dockitem;
3585 gnome_app_set_menus(GNOME_APP(gui.mainwin), GTK_MENU_BAR(gui.menubar));
3586 dockitem = gnome_app_get_dock_item_by_name(GNOME_APP(gui.mainwin),
3587 GNOME_APP_MENUBAR_NAME);
3588 /* We don't want the menu to float. */
3589 bonobo_dock_item_set_behavior(dockitem,
3590 bonobo_dock_item_get_behavior(dockitem)
3591 | BONOBO_DOCK_ITEM_BEH_NEVER_FLOATING);
3592 gui.menubar_h = GTK_WIDGET(dockitem);
3593 # else
3594 gui.menubar_h = gnome_dock_item_new("VimMainMenu",
3595 GNOME_DOCK_ITEM_BEH_EXCLUSIVE |
3596 GNOME_DOCK_ITEM_BEH_NEVER_VERTICAL);
3597 gtk_container_add(GTK_CONTAINER(gui.menubar_h), gui.menubar);
3599 gnome_dock_add_item(GNOME_DOCK(GNOME_APP(gui.mainwin)->dock),
3600 GNOME_DOCK_ITEM(gui.menubar_h),
3601 GNOME_DOCK_TOP, /* placement */
3602 1, /* band_num */
3603 0, /* band_position */
3604 0, /* offset */
3605 TRUE);
3606 gtk_widget_show(gui.menubar);
3607 # endif
3609 else
3610 # endif /* FEAT_GUI_GNOME */
3612 /* Always show the menubar, otherwise <F10> doesn't work. It may be
3613 * disabled in gui_init() later. */
3614 gtk_widget_show(gui.menubar);
3615 gtk_box_pack_start(GTK_BOX(vbox), gui.menubar, FALSE, FALSE, 0);
3617 #endif /* FEAT_MENU */
3619 #ifdef FEAT_TOOLBAR
3621 * Create the toolbar and handle
3623 # ifdef HAVE_GTK2
3624 /* some aesthetics on the toolbar */
3625 gtk_rc_parse_string(
3626 "style \"vim-toolbar-style\" {\n"
3627 " GtkToolbar::button_relief = GTK_RELIEF_NONE\n"
3628 "}\n"
3629 "widget \"*.vim-toolbar\" style \"vim-toolbar-style\"\n");
3630 gui.toolbar = gtk_toolbar_new();
3631 gtk_widget_set_name(gui.toolbar, "vim-toolbar");
3632 # else
3633 gui.toolbar = gtk_toolbar_new(GTK_ORIENTATION_HORIZONTAL,
3634 GTK_TOOLBAR_ICONS);
3635 gtk_toolbar_set_button_relief(GTK_TOOLBAR(gui.toolbar), GTK_RELIEF_NONE);
3636 # endif
3637 set_toolbar_style(GTK_TOOLBAR(gui.toolbar));
3639 # ifdef FEAT_GUI_GNOME
3640 if (using_gnome)
3642 # ifdef HAVE_GTK2
3643 BonoboDockItem *dockitem;
3645 gnome_app_set_toolbar(GNOME_APP(gui.mainwin), GTK_TOOLBAR(gui.toolbar));
3646 dockitem = gnome_app_get_dock_item_by_name(GNOME_APP(gui.mainwin),
3647 GNOME_APP_TOOLBAR_NAME);
3648 gui.toolbar_h = GTK_WIDGET(dockitem);
3649 /* When the toolbar is floating it gets stuck. So long as that isn't
3650 * fixed let's disallow floating. */
3651 bonobo_dock_item_set_behavior(dockitem,
3652 bonobo_dock_item_get_behavior(dockitem)
3653 | BONOBO_DOCK_ITEM_BEH_NEVER_FLOATING);
3654 gtk_container_set_border_width(GTK_CONTAINER(gui.toolbar), 0);
3655 # else
3656 GtkWidget *dockitem;
3658 dockitem = gnome_dock_item_new("VimToolBar",
3659 GNOME_DOCK_ITEM_BEH_EXCLUSIVE);
3660 gtk_container_add(GTK_CONTAINER(dockitem), GTK_WIDGET(gui.toolbar));
3661 gui.toolbar_h = dockitem;
3663 gnome_dock_add_item(GNOME_DOCK(GNOME_APP(gui.mainwin)->dock),
3664 GNOME_DOCK_ITEM(dockitem),
3665 GNOME_DOCK_TOP, /* placement */
3666 1, /* band_num */
3667 1, /* band_position */
3668 0, /* offset */
3669 TRUE);
3670 gtk_container_border_width(GTK_CONTAINER(gui.toolbar), 2);
3671 gtk_widget_show(gui.toolbar);
3672 # endif
3674 else
3675 # endif /* FEAT_GUI_GNOME */
3677 # ifndef HAVE_GTK2
3678 gtk_container_border_width(GTK_CONTAINER(gui.toolbar), 1);
3679 # endif
3680 if (vim_strchr(p_go, GO_TOOLBAR) != NULL
3681 && (toolbar_flags & (TOOLBAR_TEXT | TOOLBAR_ICONS)))
3682 gtk_widget_show(gui.toolbar);
3683 gtk_box_pack_start(GTK_BOX(vbox), gui.toolbar, FALSE, FALSE, 0);
3685 #endif /* FEAT_TOOLBAR */
3687 #ifdef FEAT_GUI_TABLINE
3689 * Use a Notebook for the tab pages labels. The labels are hidden by
3690 * default.
3692 gui.tabline = gtk_notebook_new();
3693 gtk_widget_show(gui.tabline);
3694 gtk_box_pack_start(GTK_BOX(vbox), gui.tabline, FALSE, FALSE, 0);
3695 gtk_notebook_set_show_border(GTK_NOTEBOOK(gui.tabline), FALSE);
3696 gtk_notebook_set_show_tabs(GTK_NOTEBOOK(gui.tabline), FALSE);
3697 gtk_notebook_set_scrollable(GTK_NOTEBOOK(gui.tabline), TRUE);
3698 gtk_notebook_set_tab_border(GTK_NOTEBOOK(gui.tabline), FALSE);
3700 tabline_tooltip = gtk_tooltips_new();
3701 gtk_tooltips_enable(GTK_TOOLTIPS(tabline_tooltip));
3704 GtkWidget *page, *label, *event_box;
3706 /* Add the first tab. */
3707 page = gtk_vbox_new(FALSE, 0);
3708 gtk_widget_show(page);
3709 gtk_container_add(GTK_CONTAINER(gui.tabline), page);
3710 label = gtk_label_new("-Empty-");
3711 gtk_widget_show(label);
3712 event_box = gtk_event_box_new();
3713 gtk_widget_show(event_box);
3714 gtk_object_set_user_data(GTK_OBJECT(event_box), (gpointer)1);
3715 gtk_misc_set_padding(GTK_MISC(label), 2, 2);
3716 gtk_container_add(GTK_CONTAINER(event_box), label);
3717 gtk_notebook_set_tab_label(GTK_NOTEBOOK(gui.tabline), page, event_box);
3720 gtk_signal_connect(GTK_OBJECT(gui.tabline), "switch_page",
3721 GTK_SIGNAL_FUNC(on_select_tab), NULL);
3723 /* Create a popup menu for the tab line and connect it. */
3724 tabline_menu = create_tabline_menu();
3725 gtk_signal_connect_object(GTK_OBJECT(gui.tabline), "button_press_event",
3726 GTK_SIGNAL_FUNC(on_tabline_menu), GTK_OBJECT(tabline_menu));
3727 #endif
3729 gui.formwin = gtk_form_new();
3730 gtk_container_border_width(GTK_CONTAINER(gui.formwin), 0);
3731 gtk_widget_set_events(gui.formwin, GDK_EXPOSURE_MASK);
3733 gui.drawarea = gtk_drawing_area_new();
3735 /* Determine which events we will filter. */
3736 gtk_widget_set_events(gui.drawarea,
3737 GDK_EXPOSURE_MASK |
3738 GDK_ENTER_NOTIFY_MASK |
3739 GDK_LEAVE_NOTIFY_MASK |
3740 GDK_BUTTON_PRESS_MASK |
3741 GDK_BUTTON_RELEASE_MASK |
3742 #ifdef HAVE_GTK2
3743 GDK_SCROLL_MASK |
3744 #endif
3745 GDK_KEY_PRESS_MASK |
3746 GDK_KEY_RELEASE_MASK |
3747 GDK_POINTER_MOTION_MASK |
3748 GDK_POINTER_MOTION_HINT_MASK);
3750 gtk_widget_show(gui.drawarea);
3751 gtk_form_put(GTK_FORM(gui.formwin), gui.drawarea, 0, 0);
3752 gtk_widget_show(gui.formwin);
3753 gtk_box_pack_start(GTK_BOX(vbox), gui.formwin, TRUE, TRUE, 0);
3755 /* For GtkSockets, key-presses must go to the focus widget (drawarea)
3756 * and not the window. */
3757 gtk_signal_connect((gtk_socket_id == 0) ? GTK_OBJECT(gui.mainwin)
3758 : GTK_OBJECT(gui.drawarea),
3759 "key_press_event",
3760 GTK_SIGNAL_FUNC(key_press_event), NULL);
3761 #if defined(FEAT_XIM) && defined(HAVE_GTK2)
3762 /* Also forward key release events for the benefit of GTK+ 2 input
3763 * modules. Try CTRL-SHIFT-xdigits to enter a Unicode code point. */
3764 g_signal_connect((gtk_socket_id == 0) ? G_OBJECT(gui.mainwin)
3765 : G_OBJECT(gui.drawarea),
3766 "key_release_event",
3767 G_CALLBACK(&key_release_event), NULL);
3768 #endif
3769 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "realize",
3770 GTK_SIGNAL_FUNC(drawarea_realize_cb), NULL);
3771 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "unrealize",
3772 GTK_SIGNAL_FUNC(drawarea_unrealize_cb), NULL);
3774 gtk_signal_connect_after(GTK_OBJECT(gui.drawarea), "style_set",
3775 GTK_SIGNAL_FUNC(&drawarea_style_set_cb), NULL);
3777 gui.visibility = GDK_VISIBILITY_UNOBSCURED;
3779 #if !(defined(FEAT_GUI_GNOME) && defined(FEAT_SESSION))
3780 wm_protocols_atom = gdk_atom_intern("WM_PROTOCOLS", FALSE);
3781 save_yourself_atom = gdk_atom_intern("WM_SAVE_YOURSELF", FALSE);
3782 #endif
3784 if (gtk_socket_id != 0)
3785 /* make sure keybord input can go to the drawarea */
3786 GTK_WIDGET_SET_FLAGS(gui.drawarea, GTK_CAN_FOCUS);
3789 * Set clipboard specific atoms
3791 vim_atom = gdk_atom_intern(VIM_ATOM_NAME, FALSE);
3792 #ifdef FEAT_MBYTE
3793 vimenc_atom = gdk_atom_intern(VIMENC_ATOM_NAME, FALSE);
3794 #endif
3795 clip_star.gtk_sel_atom = GDK_SELECTION_PRIMARY;
3796 clip_plus.gtk_sel_atom = gdk_atom_intern("CLIPBOARD", FALSE);
3799 * Start out by adding the configured border width into the border offset.
3801 gui.border_offset = gui.border_width;
3803 gtk_signal_connect(GTK_OBJECT(gui.mainwin), "visibility_notify_event",
3804 GTK_SIGNAL_FUNC(visibility_event), NULL);
3805 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "expose_event",
3806 GTK_SIGNAL_FUNC(expose_event), NULL);
3809 * Only install these enter/leave callbacks when 'p' in 'guioptions'.
3810 * Only needed for some window managers.
3812 if (vim_strchr(p_go, GO_POINTER) != NULL)
3814 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "leave_notify_event",
3815 GTK_SIGNAL_FUNC(leave_notify_event), NULL);
3816 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "enter_notify_event",
3817 GTK_SIGNAL_FUNC(enter_notify_event), NULL);
3820 /* Real windows can get focus ... GtkPlug, being a mere container can't,
3821 * only its widgets. Arguably, this could be common code and we not use
3822 * the window focus at all, but let's be safe.
3824 if (gtk_socket_id == 0)
3826 gtk_signal_connect(GTK_OBJECT(gui.mainwin), "focus_out_event",
3827 GTK_SIGNAL_FUNC(focus_out_event), NULL);
3828 gtk_signal_connect(GTK_OBJECT(gui.mainwin), "focus_in_event",
3829 GTK_SIGNAL_FUNC(focus_in_event), NULL);
3831 else
3833 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "focus_out_event",
3834 GTK_SIGNAL_FUNC(focus_out_event), NULL);
3835 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "focus_in_event",
3836 GTK_SIGNAL_FUNC(focus_in_event), NULL);
3837 #ifdef FEAT_GUI_TABLINE
3838 gtk_signal_connect(GTK_OBJECT(gui.tabline), "focus_out_event",
3839 GTK_SIGNAL_FUNC(focus_out_event), NULL);
3840 gtk_signal_connect(GTK_OBJECT(gui.tabline), "focus_in_event",
3841 GTK_SIGNAL_FUNC(focus_in_event), NULL);
3842 #endif /* FEAT_GUI_TABLINE */
3845 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "motion_notify_event",
3846 GTK_SIGNAL_FUNC(motion_notify_event), NULL);
3847 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "button_press_event",
3848 GTK_SIGNAL_FUNC(button_press_event), NULL);
3849 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "button_release_event",
3850 GTK_SIGNAL_FUNC(button_release_event), NULL);
3851 #ifdef HAVE_GTK2
3852 g_signal_connect(G_OBJECT(gui.drawarea), "scroll_event",
3853 G_CALLBACK(&scroll_event), NULL);
3854 #endif
3857 * Add selection handler functions.
3859 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "selection_clear_event",
3860 GTK_SIGNAL_FUNC(selection_clear_event), NULL);
3861 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "selection_received",
3862 GTK_SIGNAL_FUNC(selection_received_cb), NULL);
3865 * Add selection targets for PRIMARY and CLIPBOARD selections.
3867 gtk_selection_add_targets(gui.drawarea,
3868 (GdkAtom)GDK_SELECTION_PRIMARY,
3869 selection_targets, N_SELECTION_TARGETS);
3870 gtk_selection_add_targets(gui.drawarea,
3871 (GdkAtom)clip_plus.gtk_sel_atom,
3872 selection_targets, N_SELECTION_TARGETS);
3874 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "selection_get",
3875 GTK_SIGNAL_FUNC(selection_get_cb), NULL);
3877 /* Pretend we don't have input focus, we will get an event if we do. */
3878 gui.in_focus = FALSE;
3880 return OK;
3883 #if (defined(FEAT_GUI_GNOME) && defined(FEAT_SESSION)) || defined(PROTO)
3885 * This is called from gui_start() after a fork() has been done.
3886 * We have to tell the session manager our new PID.
3888 void
3889 gui_mch_forked(void)
3891 if (using_gnome)
3893 GnomeClient *client;
3895 client = gnome_master_client();
3897 if (client != NULL)
3898 gnome_client_set_process_id(client, getpid());
3901 #endif /* FEAT_GUI_GNOME && FEAT_SESSION */
3904 * Called when the foreground or background color has been changed.
3905 * This used to change the graphics contexts directly but we are
3906 * currently manipulating them where desired.
3908 void
3909 gui_mch_new_colors(void)
3911 if (gui.drawarea != NULL && gui.drawarea->window != NULL)
3913 GdkColor color = { 0, 0, 0, 0 };
3915 color.pixel = gui.back_pixel;
3916 gdk_window_set_background(gui.drawarea->window, &color);
3921 * This signal informs us about the need to rearrange our sub-widgets.
3923 /*ARGSUSED*/
3924 static gint
3925 form_configure_event(GtkWidget *widget, GdkEventConfigure *event,
3926 gpointer data)
3928 int usable_height = event->height;
3930 /* When in a GtkPlug, we can't guarantee valid heights (as a round
3931 * no. of char-heights), so we have to manually sanitise them.
3932 * Widths seem to sort themselves out, don't ask me why.
3934 if (gtk_socket_id != 0)
3935 usable_height -= (gui.char_height - (gui.char_height/2)); /* sic. */
3937 gtk_form_freeze(GTK_FORM(gui.formwin));
3938 gui_resize_shell(event->width, usable_height);
3939 gtk_form_thaw(GTK_FORM(gui.formwin));
3941 return TRUE;
3945 * Function called when window already closed.
3946 * We can't do much more here than to trying to preserve what had been done,
3947 * since the window is already inevitably going away.
3949 /*ARGSUSED0*/
3950 static void
3951 mainwin_destroy_cb(GtkObject *object, gpointer data)
3953 /* Don't write messages to the GUI anymore */
3954 full_screen = FALSE;
3956 gui.mainwin = NULL;
3957 gui.drawarea = NULL;
3959 if (!exiting) /* only do anything if the destroy was unexpected */
3961 vim_strncpy(IObuff,
3962 (char_u *)_("Vim: Main window unexpectedly destroyed\n"),
3963 IOSIZE - 1);
3964 preserve_exit();
3970 * Bit of a hack to ensure we start GtkPlug windows with the correct window
3971 * hints (and thus the required size from -geom), but that after that we
3972 * put the hints back to normal (the actual minimum size) so we may
3973 * subsequently be resized smaller. GtkSocket (the parent end) uses the
3974 * plug's window 'min hints to set *it's* minimum size, but that's also the
3975 * only way we have of making ourselves bigger (by set lines/columns).
3976 * Thus set hints at start-up to ensure correct init. size, then a
3977 * second after the final attempt to reset the real minimum hinst (done by
3978 * scrollbar init.), actually do the standard hinst and stop the timer.
3979 * We'll not let the default hints be set while this timer's active.
3981 /*ARGSUSED*/
3982 static gboolean
3983 check_startup_plug_hints(gpointer data)
3985 if (init_window_hints_state == 1)
3987 /* Safe to use normal hints now */
3988 init_window_hints_state = 0;
3989 update_window_manager_hints(0, 0);
3990 return FALSE; /* stop timer */
3993 /* Keep on trying */
3994 init_window_hints_state = 1;
3995 return TRUE;
4000 * Open the GUI window which was created by a call to gui_mch_init().
4003 gui_mch_open(void)
4005 guicolor_T fg_pixel = INVALCOLOR;
4006 guicolor_T bg_pixel = INVALCOLOR;
4008 #ifdef HAVE_GTK2
4010 * Allow setting a window role on the command line, or invent one
4011 * if none was specified. This is mainly useful for GNOME session
4012 * support; allowing the WM to restore window placement.
4014 if (role_argument != NULL)
4016 gtk_window_set_role(GTK_WINDOW(gui.mainwin), role_argument);
4018 else
4020 char *role;
4022 /* Invent a unique-enough ID string for the role */
4023 role = g_strdup_printf("vim-%u-%u-%u",
4024 (unsigned)mch_get_pid(),
4025 (unsigned)g_random_int(),
4026 (unsigned)time(NULL));
4028 gtk_window_set_role(GTK_WINDOW(gui.mainwin), role);
4029 g_free(role);
4031 #endif
4033 if (gui_win_x != -1 && gui_win_y != -1)
4034 #ifdef HAVE_GTK2
4035 gtk_window_move(GTK_WINDOW(gui.mainwin), gui_win_x, gui_win_y);
4036 #else
4037 gtk_widget_set_uposition(gui.mainwin, gui_win_x, gui_win_y);
4038 #endif
4040 /* Determine user specified geometry, if present. */
4041 if (gui.geom != NULL)
4043 int mask;
4044 unsigned int w, h;
4045 int x = 0;
4046 int y = 0;
4047 guint pixel_width;
4048 guint pixel_height;
4050 mask = XParseGeometry((char *)gui.geom, &x, &y, &w, &h);
4052 if (mask & WidthValue)
4053 Columns = w;
4054 if (mask & HeightValue)
4056 if (p_window > h - 1 || !option_was_set((char_u *)"window"))
4057 p_window = h - 1;
4058 Rows = h;
4061 pixel_width = (guint)(gui_get_base_width() + Columns * gui.char_width);
4062 pixel_height = (guint)(gui_get_base_height() + Rows * gui.char_height);
4064 #ifdef HAVE_GTK2
4065 pixel_width += get_menu_tool_width();
4066 pixel_height += get_menu_tool_height();
4067 #endif
4069 if (mask & (XValue | YValue))
4071 int w, h;
4072 gui_mch_get_screen_dimensions(&w, &h);
4073 h += p_ghr + get_menu_tool_height();
4074 w += get_menu_tool_width();
4075 if (mask & XNegative)
4076 x += w - pixel_width;
4077 if (mask & YNegative)
4078 y += h - pixel_height;
4079 #ifdef HAVE_GTK2
4080 gtk_window_move(GTK_WINDOW(gui.mainwin), x, y);
4081 #else
4082 gtk_widget_set_uposition(gui.mainwin, x, y);
4083 #endif
4085 vim_free(gui.geom);
4086 gui.geom = NULL;
4088 /* From now until everyone's stopped trying to set the window hints
4089 * to their correct minimum values, stop them being set as we need
4090 * them to remain at our required size for the parent GtkSocket to
4091 * give us the right initial size.
4093 if (gtk_socket_id != 0 && (mask & WidthValue || mask & HeightValue))
4095 update_window_manager_hints(pixel_width, pixel_height);
4096 init_window_hints_state = 1;
4097 g_timeout_add(1000, check_startup_plug_hints, NULL);
4101 gtk_form_set_size(GTK_FORM(gui.formwin),
4102 (guint)(gui_get_base_width() + Columns * gui.char_width),
4103 (guint)(gui_get_base_height() + Rows * gui.char_height));
4104 update_window_manager_hints(0, 0);
4106 if (foreground_argument != NULL)
4107 fg_pixel = gui_get_color((char_u *)foreground_argument);
4108 if (fg_pixel == INVALCOLOR)
4109 fg_pixel = gui_get_color((char_u *)"Black");
4111 if (background_argument != NULL)
4112 bg_pixel = gui_get_color((char_u *)background_argument);
4113 if (bg_pixel == INVALCOLOR)
4114 bg_pixel = gui_get_color((char_u *)"White");
4116 if (found_reverse_arg)
4118 gui.def_norm_pixel = bg_pixel;
4119 gui.def_back_pixel = fg_pixel;
4121 else
4123 gui.def_norm_pixel = fg_pixel;
4124 gui.def_back_pixel = bg_pixel;
4127 /* Get the colors from the "Normal" and "Menu" group (set in syntax.c or
4128 * in a vimrc file) */
4129 set_normal_colors();
4131 /* Check that none of the colors are the same as the background color */
4132 gui_check_colors();
4134 /* Get the colors for the highlight groups (gui_check_colors() might have
4135 * changed them). */
4136 highlight_gui_started(); /* re-init colors and fonts */
4138 gtk_signal_connect(GTK_OBJECT(gui.mainwin), "destroy",
4139 GTK_SIGNAL_FUNC(mainwin_destroy_cb), NULL);
4141 #ifdef FEAT_HANGULIN
4142 hangul_keyboard_set();
4143 #endif
4146 * Notify the fixed area about the need to resize the contents of the
4147 * gui.formwin, which we use for random positioning of the included
4148 * components.
4150 * We connect this signal deferred finally after anything is in place,
4151 * since this is intended to handle resizements coming from the window
4152 * manager upon us and should not interfere with what VIM is requesting
4153 * upon startup.
4155 gtk_signal_connect(GTK_OBJECT(gui.formwin), "configure_event",
4156 GTK_SIGNAL_FUNC(form_configure_event), NULL);
4158 #ifdef FEAT_DND
4160 * Set up for receiving DND items.
4162 gtk_drag_dest_set(gui.drawarea,
4163 GTK_DEST_DEFAULT_ALL,
4164 dnd_targets, N_DND_TARGETS,
4165 GDK_ACTION_COPY);
4167 gtk_signal_connect(GTK_OBJECT(gui.drawarea), "drag_data_received",
4168 GTK_SIGNAL_FUNC(drag_data_received_cb), NULL);
4169 #endif
4171 #ifdef HAVE_GTK2
4172 /* With GTK+ 2, we need to iconify the window before calling show()
4173 * to avoid mapping the window for a short time. This is just as one
4174 * would expect it to work, but it's different in GTK+ 1. The funny
4175 * thing is that iconifying after show() _does_ work with GTK+ 1.
4176 * (BTW doing this in the "realize" handler makes no difference.) */
4177 if (found_iconic_arg && gtk_socket_id == 0)
4178 gui_mch_iconify();
4179 #endif
4182 #if defined(FEAT_GUI_GNOME) && defined(HAVE_GTK2) && defined(FEAT_MENU)
4183 unsigned long menu_handler = 0;
4184 # ifdef FEAT_TOOLBAR
4185 unsigned long tool_handler = 0;
4186 # endif
4188 * Urgh hackish :/ For some reason BonoboDockLayout always forces a
4189 * show when restoring the saved layout configuration. We can't just
4190 * hide the widgets again after gtk_widget_show(gui.mainwin) since it's
4191 * a toplevel window and thus will be realized immediately. Instead,
4192 * connect signal handlers to hide the widgets just after they've been
4193 * marked visible, but before the main window is realized.
4195 if (using_gnome && vim_strchr(p_go, GO_MENUS) == NULL)
4196 menu_handler = g_signal_connect_after(gui.menubar_h, "show",
4197 G_CALLBACK(&gtk_widget_hide),
4198 NULL);
4199 # ifdef FEAT_TOOLBAR
4200 if (using_gnome && vim_strchr(p_go, GO_TOOLBAR) == NULL
4201 && (toolbar_flags & (TOOLBAR_TEXT | TOOLBAR_ICONS)))
4202 tool_handler = g_signal_connect_after(gui.toolbar_h, "show",
4203 G_CALLBACK(&gtk_widget_hide),
4204 NULL);
4205 # endif
4206 #endif
4207 gtk_widget_show(gui.mainwin);
4209 #if defined(FEAT_GUI_GNOME) && defined(HAVE_GTK2) && defined(FEAT_MENU)
4210 if (menu_handler != 0)
4211 g_signal_handler_disconnect(gui.menubar_h, menu_handler);
4212 # ifdef FEAT_TOOLBAR
4213 if (tool_handler != 0)
4214 g_signal_handler_disconnect(gui.toolbar_h, tool_handler);
4215 # endif
4216 #endif
4219 #ifndef HAVE_GTK2
4220 /* With GTK+ 1, we need to iconify the window after calling show().
4221 * See the comment above for details. */
4222 if (found_iconic_arg && gtk_socket_id == 0)
4223 gui_mch_iconify();
4224 #endif
4226 return OK;
4230 /*ARGSUSED0*/
4231 void
4232 gui_mch_exit(int rc)
4234 if (gui.mainwin != NULL)
4235 gtk_widget_destroy(gui.mainwin);
4237 if (gtk_main_level() > 0)
4238 gtk_main_quit();
4242 * Get the position of the top left corner of the window.
4245 gui_mch_get_winpos(int *x, int *y)
4247 #ifdef HAVE_GTK2
4248 gtk_window_get_position(GTK_WINDOW(gui.mainwin), x, y);
4249 #else
4250 /* For some people this must be gdk_window_get_origin() for a correct
4251 * result. Where is the documentation! */
4252 gdk_window_get_root_origin(gui.mainwin->window, x, y);
4253 #endif
4254 return OK;
4258 * Set the position of the top left corner of the window to the given
4259 * coordinates.
4261 void
4262 gui_mch_set_winpos(int x, int y)
4264 #ifdef HAVE_GTK2
4265 gtk_window_move(GTK_WINDOW(gui.mainwin), x, y);
4266 #else
4267 gdk_window_move(gui.mainwin->window, x, y);
4268 #endif
4271 #ifdef HAVE_GTK2
4272 #if 0
4273 static int resize_idle_installed = FALSE;
4275 * Idle handler to force resize. Used by gui_mch_set_shellsize() to ensure
4276 * the shell size doesn't exceed the window size, i.e. if the window manager
4277 * ignored our size request. Usually this happens if the window is maximized.
4279 * FIXME: It'd be nice if we could find a little more orthodox solution.
4280 * See also the remark below in gui_mch_set_shellsize().
4282 * DISABLED: When doing ":set lines+=1" this function would first invoke
4283 * gui_resize_shell() with the old size, then the normal callback would
4284 * report the new size through form_configure_event(). That caused the window
4285 * layout to be messed up.
4287 /*ARGSUSED0*/
4288 static gboolean
4289 force_shell_resize_idle(gpointer data)
4291 if (gui.mainwin != NULL
4292 && GTK_WIDGET_REALIZED(gui.mainwin)
4293 && GTK_WIDGET_VISIBLE(gui.mainwin))
4295 int width;
4296 int height;
4298 gtk_window_get_size(GTK_WINDOW(gui.mainwin), &width, &height);
4300 width -= get_menu_tool_width();
4301 height -= get_menu_tool_height();
4303 gui_resize_shell(width, height);
4306 resize_idle_installed = FALSE;
4307 return FALSE; /* don't call me again */
4309 #endif
4310 #endif /* HAVE_GTK2 */
4313 * Set the windows size.
4315 /*ARGSUSED2*/
4316 void
4317 gui_mch_set_shellsize(int width, int height,
4318 int min_width, int min_height,
4319 int base_width, int base_height,
4320 int direction)
4322 #ifndef HAVE_GTK2
4323 /* Hack: When the form already is at the desired size, the window might
4324 * have been resized with the mouse. Force a resize by setting a
4325 * different size first. */
4326 if (GTK_FORM(gui.formwin)->width == width
4327 && GTK_FORM(gui.formwin)->height == height)
4329 gtk_form_set_size(GTK_FORM(gui.formwin), width + 1, height + 1);
4330 gui_mch_update();
4332 gtk_form_set_size(GTK_FORM(gui.formwin), width, height);
4333 #endif
4335 /* give GTK+ a chance to put all widget's into place */
4336 gui_mch_update();
4338 #ifndef HAVE_GTK2
4339 /* this will cause the proper resizement to happen too */
4340 update_window_manager_hints(0, 0);
4342 #else /* HAVE_GTK2 */
4343 /* this will cause the proper resizement to happen too */
4344 if (gtk_socket_id == 0)
4345 update_window_manager_hints(0, 0);
4347 /* With GTK+ 2, changing the size of the form widget doesn't resize
4348 * the window. So let's do it the other way around and resize the
4349 * main window instead. */
4350 width += get_menu_tool_width();
4351 height += get_menu_tool_height();
4353 if (gtk_socket_id == 0)
4354 gtk_window_resize(GTK_WINDOW(gui.mainwin), width, height);
4355 else
4356 update_window_manager_hints(width, height);
4358 #if 0
4359 if (!resize_idle_installed)
4361 g_idle_add_full(GDK_PRIORITY_EVENTS + 10,
4362 &force_shell_resize_idle, NULL, NULL);
4363 resize_idle_installed = TRUE;
4365 #endif
4367 * Wait until all events are processed to prevent a crash because the
4368 * real size of the drawing area doesn't reflect Vim's internal ideas.
4370 * This is a bit of a hack, since Vim is a terminal application with a GUI
4371 * on top, while the GUI expects to be the boss.
4373 gui_mch_update();
4374 #endif
4379 * The screen size is used to make sure the initial window doesn't get bigger
4380 * than the screen. This subtracts some room for menubar, toolbar and window
4381 * decorations.
4383 void
4384 gui_mch_get_screen_dimensions(int *screen_w, int *screen_h)
4386 #ifdef HAVE_GTK_MULTIHEAD
4387 GdkScreen* screen;
4389 if (gui.mainwin != NULL && gtk_widget_has_screen(gui.mainwin))
4390 screen = gtk_widget_get_screen(gui.mainwin);
4391 else
4392 screen = gdk_screen_get_default();
4394 *screen_w = gdk_screen_get_width(screen);
4395 *screen_h = gdk_screen_get_height(screen) - p_ghr;
4396 #else
4397 *screen_w = gdk_screen_width();
4398 /* Subtract 'guiheadroom' from the height to allow some room for the
4399 * window manager (task list and window title bar). */
4400 *screen_h = gdk_screen_height() - p_ghr;
4401 #endif
4404 * FIXME: dirty trick: Because the gui_get_base_height() doesn't include
4405 * the toolbar and menubar for GTK, we subtract them from the screen
4406 * hight, so that the window size can be made to fit on the screen.
4407 * This should be completely changed later.
4409 *screen_w -= get_menu_tool_width();
4410 *screen_h -= get_menu_tool_height();
4413 #if defined(FEAT_TITLE) || defined(PROTO)
4414 /*ARGSUSED*/
4415 void
4416 gui_mch_settitle(char_u *title, char_u *icon)
4418 # ifdef HAVE_GTK2
4419 if (title != NULL && output_conv.vc_type != CONV_NONE)
4420 title = string_convert(&output_conv, title, NULL);
4421 # endif
4423 gtk_window_set_title(GTK_WINDOW(gui.mainwin), (const char *)title);
4425 # ifdef HAVE_GTK2
4426 if (output_conv.vc_type != CONV_NONE)
4427 vim_free(title);
4428 # endif
4430 #endif /* FEAT_TITLE */
4432 #if defined(FEAT_MENU) || defined(PROTO)
4433 void
4434 gui_mch_enable_menu(int showit)
4436 GtkWidget *widget;
4438 # ifdef FEAT_GUI_GNOME
4439 if (using_gnome)
4440 widget = gui.menubar_h;
4441 else
4442 # endif
4443 widget = gui.menubar;
4445 /* Do not disable the menu while starting up, otherwise F10 doesn't work. */
4446 if (!showit != !GTK_WIDGET_VISIBLE(widget) && !gui.starting)
4448 if (showit)
4449 gtk_widget_show(widget);
4450 else
4451 gtk_widget_hide(widget);
4453 update_window_manager_hints(0, 0);
4456 #endif /* FEAT_MENU */
4458 #if defined(FEAT_TOOLBAR) || defined(PROTO)
4459 void
4460 gui_mch_show_toolbar(int showit)
4462 GtkWidget *widget;
4464 if (gui.toolbar == NULL)
4465 return;
4467 # ifdef FEAT_GUI_GNOME
4468 if (using_gnome)
4469 widget = gui.toolbar_h;
4470 else
4471 # endif
4472 widget = gui.toolbar;
4474 if (showit)
4475 set_toolbar_style(GTK_TOOLBAR(gui.toolbar));
4477 if (!showit != !GTK_WIDGET_VISIBLE(widget))
4479 if (showit)
4480 gtk_widget_show(widget);
4481 else
4482 gtk_widget_hide(widget);
4484 update_window_manager_hints(0, 0);
4487 #endif /* FEAT_TOOLBAR */
4489 #ifndef HAVE_GTK2
4491 * Get a font structure for highlighting.
4492 * "cbdata" is a pointer to the global gui structure.
4494 /*ARGSUSED*/
4495 static void
4496 font_sel_ok(GtkWidget *wgt, gpointer cbdata)
4498 gui_T *vw = (gui_T *)cbdata;
4499 GtkFontSelectionDialog *fs = (GtkFontSelectionDialog *)vw->fontdlg;
4501 if (vw->fontname)
4502 g_free(vw->fontname);
4504 vw->fontname = (char_u *)gtk_font_selection_dialog_get_font_name(fs);
4505 gtk_widget_hide(vw->fontdlg);
4506 if (gtk_main_level() > 0)
4507 gtk_main_quit();
4510 /*ARGSUSED*/
4511 static void
4512 font_sel_cancel(GtkWidget *wgt, gpointer cbdata)
4514 gui_T *vw = (gui_T *)cbdata;
4516 gtk_widget_hide(vw->fontdlg);
4517 if (gtk_main_level() > 0)
4518 gtk_main_quit();
4521 /*ARGSUSED*/
4522 static void
4523 font_sel_destroy(GtkWidget *wgt, gpointer cbdata)
4525 gui_T *vw = (gui_T *)cbdata;
4527 vw->fontdlg = NULL;
4528 if (gtk_main_level() > 0)
4529 gtk_main_quit();
4531 #endif /* !HAVE_GTK2 */
4533 #ifdef HAVE_GTK2
4535 * Check if a given font is a CJK font. This is done in a very crude manner. It
4536 * just see if U+04E00 for zh and ja and U+AC00 for ko are covered in a given
4537 * font. Consequently, this function cannot be used as a general purpose check
4538 * for CJK-ness for which fontconfig APIs should be used. This is only used by
4539 * gui_mch_init_font() to deal with 'CJK fixed width fonts'.
4541 static int
4542 is_cjk_font(PangoFontDescription *font_desc)
4544 static const char * const cjk_langs[] =
4545 {"zh_CN", "zh_TW", "zh_HK", "ja", "ko"};
4547 PangoFont *font;
4548 unsigned i;
4549 int is_cjk = FALSE;
4551 font = pango_context_load_font(gui.text_context, font_desc);
4553 if (font == NULL)
4554 return FALSE;
4556 for (i = 0; !is_cjk && i < G_N_ELEMENTS(cjk_langs); ++i)
4558 PangoCoverage *coverage;
4559 gunichar uc;
4561 coverage = pango_font_get_coverage(
4562 font, pango_language_from_string(cjk_langs[i]));
4564 if (coverage != NULL)
4566 uc = (cjk_langs[i][0] == 'k') ? 0xAC00 : 0x4E00;
4567 is_cjk = (pango_coverage_get(coverage, uc) == PANGO_COVERAGE_EXACT);
4568 pango_coverage_unref(coverage);
4572 g_object_unref(font);
4574 return is_cjk;
4576 #endif /* HAVE_GTK2 */
4579 * Adjust gui.char_height (after 'linespace' was changed).
4582 gui_mch_adjust_charheight(void)
4584 #ifdef HAVE_GTK2
4585 PangoFontMetrics *metrics;
4586 int ascent;
4587 int descent;
4589 metrics = pango_context_get_metrics(gui.text_context, gui.norm_font,
4590 pango_context_get_language(gui.text_context));
4591 ascent = pango_font_metrics_get_ascent(metrics);
4592 descent = pango_font_metrics_get_descent(metrics);
4594 pango_font_metrics_unref(metrics);
4596 gui.char_height = (ascent + descent + PANGO_SCALE - 1) / PANGO_SCALE
4597 + p_linespace;
4598 /* LINTED: avoid warning: bitwise operation on signed value */
4599 gui.char_ascent = PANGO_PIXELS(ascent + p_linespace * PANGO_SCALE / 2);
4601 #else /* !HAVE_GTK2 */
4603 gui.char_height = gui.current_font->ascent + gui.current_font->descent
4604 + p_linespace;
4605 gui.char_ascent = gui.current_font->ascent + p_linespace / 2;
4607 #endif /* !HAVE_GTK2 */
4609 /* A not-positive value of char_height may crash Vim. Only happens
4610 * if 'linespace' is negative (which does make sense sometimes). */
4611 gui.char_ascent = MAX(gui.char_ascent, 0);
4612 gui.char_height = MAX(gui.char_height, gui.char_ascent + 1);
4614 return OK;
4617 #if defined(FEAT_XFONTSET) || defined(PROTO)
4619 * Try to load the requested fontset.
4621 /*ARGSUSED2*/
4622 GuiFontset
4623 gui_mch_get_fontset(char_u *name, int report_error, int fixed_width)
4625 GdkFont *font;
4627 if (!gui.in_use || name == NULL)
4628 return NOFONT;
4630 font = gdk_fontset_load((gchar *)name);
4632 if (font == NULL)
4634 if (report_error)
4635 EMSG2(_(e_fontset), name);
4636 return NOFONT;
4638 /* TODO: check if the font is fixed width. */
4640 /* reference this font as being in use */
4641 gdk_font_ref(font);
4643 return (GuiFontset)font;
4645 #endif /* FEAT_XFONTSET */
4647 #ifndef HAVE_GTK2
4649 * Put up a font dialog and return the selected font name in allocated memory.
4650 * "oldval" is the previous value.
4651 * Return NULL when cancelled.
4653 char_u *
4654 gui_mch_font_dialog(char_u *oldval)
4656 char_u *fontname = NULL;
4658 if (!gui.fontdlg)
4660 GtkFontSelectionDialog *fsd = NULL;
4662 gui.fontdlg = gtk_font_selection_dialog_new(_("Font Selection"));
4663 fsd = GTK_FONT_SELECTION_DIALOG(gui.fontdlg);
4664 gtk_window_set_modal(GTK_WINDOW(gui.fontdlg), TRUE);
4665 gtk_window_set_transient_for(GTK_WINDOW(gui.fontdlg),
4666 GTK_WINDOW(gui.mainwin));
4667 gtk_signal_connect(GTK_OBJECT(gui.fontdlg), "destroy",
4668 GTK_SIGNAL_FUNC(font_sel_destroy), &gui);
4669 gtk_signal_connect(GTK_OBJECT(fsd->ok_button), "clicked",
4670 GTK_SIGNAL_FUNC(font_sel_ok), &gui);
4671 gtk_signal_connect(GTK_OBJECT(fsd->cancel_button), "clicked",
4672 GTK_SIGNAL_FUNC(font_sel_cancel), &gui);
4675 if (oldval != NULL && *oldval != NUL)
4676 gtk_font_selection_dialog_set_font_name(
4677 GTK_FONT_SELECTION_DIALOG(gui.fontdlg), (char *)oldval);
4679 if (gui.fontname)
4681 g_free(gui.fontname);
4682 gui.fontname = NULL;
4684 gtk_window_position(GTK_WINDOW(gui.fontdlg), GTK_WIN_POS_MOUSE);
4685 gtk_widget_show(gui.fontdlg);
4687 static gchar *spacings[] = {"c", "m", NULL};
4689 /* In GTK 1.2.3 this must be after the gtk_widget_show() call,
4690 * otherwise everything is blocked for ten seconds. */
4691 gtk_font_selection_dialog_set_filter(
4692 GTK_FONT_SELECTION_DIALOG(gui.fontdlg),
4693 GTK_FONT_FILTER_BASE,
4694 GTK_FONT_ALL, NULL, NULL,
4695 NULL, NULL, spacings, NULL);
4698 /* Wait for the font dialog to be closed. */
4699 while (gui.fontdlg && GTK_WIDGET_DRAWABLE(gui.fontdlg))
4700 gtk_main_iteration_do(TRUE);
4702 if (gui.fontname != NULL)
4704 /* Apparently some font names include a comma, need to escape that,
4705 * because in 'guifont' it separates names. */
4706 fontname = vim_strsave_escaped(gui.fontname, (char_u *)",");
4707 g_free(gui.fontname);
4708 gui.fontname = NULL;
4710 return fontname;
4712 #endif /* !HAVE_GTK2 */
4714 #ifdef HAVE_GTK2
4716 * Put up a font dialog and return the selected font name in allocated memory.
4717 * "oldval" is the previous value. Return NULL when cancelled.
4718 * This should probably go into gui_gtk.c. Hmm.
4719 * FIXME:
4720 * The GTK2 font selection dialog has no filtering API. So we could either
4721 * a) implement our own (possibly copying the code from somewhere else) or
4722 * b) just live with it.
4724 char_u *
4725 gui_mch_font_dialog(char_u *oldval)
4727 GtkWidget *dialog;
4728 int response;
4729 char_u *fontname = NULL;
4730 char_u *oldname;
4732 dialog = gtk_font_selection_dialog_new(NULL);
4734 gtk_window_set_transient_for(GTK_WINDOW(dialog), GTK_WINDOW(gui.mainwin));
4735 gtk_window_set_destroy_with_parent(GTK_WINDOW(dialog), TRUE);
4737 if (oldval != NULL && oldval[0] != NUL)
4739 if (output_conv.vc_type != CONV_NONE)
4740 oldname = string_convert(&output_conv, oldval, NULL);
4741 else
4742 oldname = oldval;
4744 /* Annoying bug in GTK (or Pango): if the font name does not include a
4745 * size, zero is used. Use default point size ten. */
4746 if (!vim_isdigit(oldname[STRLEN(oldname) - 1]))
4748 char_u *p = vim_strnsave(oldname, STRLEN(oldname) + 3);
4750 if (p != NULL)
4752 STRCPY(p + STRLEN(p), " 10");
4753 if (oldname != oldval)
4754 vim_free(oldname);
4755 oldname = p;
4759 gtk_font_selection_dialog_set_font_name(
4760 GTK_FONT_SELECTION_DIALOG(dialog), (const char *)oldname);
4762 if (oldname != oldval)
4763 vim_free(oldname);
4766 response = gtk_dialog_run(GTK_DIALOG(dialog));
4768 if (response == GTK_RESPONSE_OK)
4770 char *name;
4772 name = gtk_font_selection_dialog_get_font_name(
4773 GTK_FONT_SELECTION_DIALOG(dialog));
4774 if (name != NULL)
4776 char_u *p;
4778 /* Apparently some font names include a comma, need to escape
4779 * that, because in 'guifont' it separates names. */
4780 p = vim_strsave_escaped((char_u *)name, (char_u *)",");
4781 g_free(name);
4782 if (p != NULL && input_conv.vc_type != CONV_NONE)
4784 fontname = string_convert(&input_conv, p, NULL);
4785 vim_free(p);
4787 else
4788 fontname = p;
4792 if (response != GTK_RESPONSE_NONE)
4793 gtk_widget_destroy(dialog);
4795 return fontname;
4799 * Some monospace fonts don't support a bold weight, and fall back
4800 * silently to the regular weight. But this is no good since our text
4801 * drawing function can emulate bold by overstriking. So let's try
4802 * to detect whether bold weight is actually available and emulate it
4803 * otherwise.
4805 * Note that we don't need to check for italic style since Xft can
4806 * emulate italic on its own, provided you have a proper fontconfig
4807 * setup. We wouldn't be able to emulate it in Vim anyway.
4809 static void
4810 get_styled_font_variants(void)
4812 PangoFontDescription *bold_font_desc;
4813 PangoFont *plain_font;
4814 PangoFont *bold_font;
4816 gui.font_can_bold = FALSE;
4818 plain_font = pango_context_load_font(gui.text_context, gui.norm_font);
4820 if (plain_font == NULL)
4821 return;
4823 bold_font_desc = pango_font_description_copy_static(gui.norm_font);
4824 pango_font_description_set_weight(bold_font_desc, PANGO_WEIGHT_BOLD);
4826 bold_font = pango_context_load_font(gui.text_context, bold_font_desc);
4828 * The comparison relies on the unique handle nature of a PangoFont*,
4829 * i.e. it's assumed that a different PangoFont* won't refer to the
4830 * same font. Seems to work, and failing here isn't critical anyway.
4832 if (bold_font != NULL)
4834 gui.font_can_bold = (bold_font != plain_font);
4835 g_object_unref(bold_font);
4838 pango_font_description_free(bold_font_desc);
4839 g_object_unref(plain_font);
4842 #else /* !HAVE_GTK2 */
4845 * There is only one excuse I can give for the following attempt to manage font
4846 * styles:
4848 * I HATE THE BRAIN DEAD WAY X11 IS HANDLING FONTS (--mdcki)
4849 * (Me too. --danielk)
4851 static void
4852 get_styled_font_variants(char_u * font_name)
4854 char *chunk[32];
4855 char *sdup;
4856 char *tmp;
4857 int len, i;
4858 GuiFont *styled_font[3];
4860 styled_font[0] = &gui.bold_font;
4861 styled_font[1] = &gui.ital_font;
4862 styled_font[2] = &gui.boldital_font;
4864 /* First free whatever was freviously there. */
4865 for (i = 0; i < 3; ++i)
4866 if (*styled_font[i])
4868 gdk_font_unref(*styled_font[i]);
4869 *styled_font[i] = NULL;
4872 if ((sdup = g_strdup((const char *)font_name)) == NULL)
4873 return;
4875 /* split up the whole */
4876 i = 0;
4877 for (tmp = sdup; *tmp != '\0'; ++tmp)
4879 if (*tmp == '-')
4881 *tmp = '\0';
4883 if (i == 32)
4884 break;
4886 chunk[i] = tmp + 1;
4887 ++i;
4891 if (i == 14)
4893 GdkFont *font = NULL;
4894 const char *bold_chunk[3] = { "bold", NULL, "bold" };
4895 const char *italic_chunk[3] = { NULL, "o", "o" };
4897 /* font name was complete */
4898 len = strlen((const char *)font_name) + 32;
4900 for (i = 0; i < 3; ++i)
4902 char *styled_name;
4903 int j;
4905 styled_name = (char *)alloc(len);
4906 if (styled_name == NULL)
4908 g_free(sdup);
4909 return;
4912 *styled_name = '\0';
4914 for (j = 0; j < 14; ++j)
4916 strcat(styled_name, "-");
4917 if (j == 2 && bold_chunk[i] != NULL)
4918 strcat(styled_name, bold_chunk[i]);
4919 else if (j == 3 && italic_chunk[i] != NULL)
4920 strcat(styled_name, italic_chunk[i]);
4921 else
4922 strcat(styled_name, chunk[j]);
4925 font = gui_mch_get_font((char_u *)styled_name, FALSE);
4926 if (font != NULL)
4927 *styled_font[i] = font;
4929 vim_free(styled_name);
4933 g_free(sdup);
4935 #endif /* !HAVE_GTK2 */
4937 #ifdef HAVE_GTK2
4938 static PangoEngineShape *default_shape_engine = NULL;
4941 * Create a map from ASCII characters in the range [32,126] to glyphs
4942 * of the current font. This is used by gui_gtk2_draw_string() to skip
4943 * the itemize and shaping process for the most common case.
4945 static void
4946 ascii_glyph_table_init(void)
4948 char_u ascii_chars[128];
4949 PangoAttrList *attr_list;
4950 GList *item_list;
4951 int i;
4953 if (gui.ascii_glyphs != NULL)
4954 pango_glyph_string_free(gui.ascii_glyphs);
4955 if (gui.ascii_font != NULL)
4956 g_object_unref(gui.ascii_font);
4958 gui.ascii_glyphs = NULL;
4959 gui.ascii_font = NULL;
4961 /* For safety, fill in question marks for the control characters. */
4962 for (i = 0; i < 32; ++i)
4963 ascii_chars[i] = '?';
4964 for (; i < 127; ++i)
4965 ascii_chars[i] = i;
4966 ascii_chars[i] = '?';
4968 attr_list = pango_attr_list_new();
4969 item_list = pango_itemize(gui.text_context, (const char *)ascii_chars,
4970 0, sizeof(ascii_chars), attr_list, NULL);
4972 if (item_list != NULL && item_list->next == NULL) /* play safe */
4974 PangoItem *item;
4975 int width;
4977 item = (PangoItem *)item_list->data;
4978 width = gui.char_width * PANGO_SCALE;
4980 /* Remember the shape engine used for ASCII. */
4981 default_shape_engine = item->analysis.shape_engine;
4983 gui.ascii_font = item->analysis.font;
4984 g_object_ref(gui.ascii_font);
4986 gui.ascii_glyphs = pango_glyph_string_new();
4988 pango_shape((const char *)ascii_chars, sizeof(ascii_chars),
4989 &item->analysis, gui.ascii_glyphs);
4991 g_return_if_fail(gui.ascii_glyphs->num_glyphs == sizeof(ascii_chars));
4993 for (i = 0; i < gui.ascii_glyphs->num_glyphs; ++i)
4995 PangoGlyphGeometry *geom;
4997 geom = &gui.ascii_glyphs->glyphs[i].geometry;
4998 geom->x_offset += MAX(0, width - geom->width) / 2;
4999 geom->width = width;
5003 g_list_foreach(item_list, (GFunc)&pango_item_free, NULL);
5004 g_list_free(item_list);
5005 pango_attr_list_unref(attr_list);
5007 #endif /* HAVE_GTK2 */
5010 * Initialize Vim to use the font or fontset with the given name.
5011 * Return FAIL if the font could not be loaded, OK otherwise.
5013 /*ARGSUSED1*/
5015 gui_mch_init_font(char_u *font_name, int fontset)
5017 #ifdef HAVE_GTK2
5018 PangoFontDescription *font_desc;
5019 PangoLayout *layout;
5020 int width;
5022 /* If font_name is NULL, this means to use the default, which should
5023 * be present on all proper Pango/fontconfig installations. */
5024 if (font_name == NULL)
5025 font_name = (char_u *)DEFAULT_FONT;
5027 font_desc = gui_mch_get_font(font_name, FALSE);
5029 if (font_desc == NULL)
5030 return FAIL;
5032 gui_mch_free_font(gui.norm_font);
5033 gui.norm_font = font_desc;
5035 pango_context_set_font_description(gui.text_context, font_desc);
5037 layout = pango_layout_new(gui.text_context);
5038 pango_layout_set_text(layout, "MW", 2);
5039 pango_layout_get_size(layout, &width, NULL);
5041 * Set char_width to half the width obtained from pango_layout_get_size()
5042 * for CJK fixed_width/bi-width fonts. An unpatched version of Xft leads
5043 * Pango to use the same width for both non-CJK characters (e.g. Latin
5044 * letters and numbers) and CJK characters. This results in 's p a c e d
5045 * o u t' rendering when a CJK 'fixed width' font is used. To work around
5046 * that, divide the width returned by Pango by 2 if cjk_width is equal to
5047 * width for CJK fonts.
5049 * For related bugs, see:
5050 * http://bugzilla.gnome.org/show_bug.cgi?id=106618
5051 * http://bugzilla.gnome.org/show_bug.cgi?id=106624
5053 * With this, for all four of the following cases, Vim works fine:
5054 * guifont=CJK_fixed_width_font
5055 * guifont=Non_CJK_fixed_font
5056 * guifont=Non_CJK_fixed_font,CJK_Fixed_font
5057 * guifont=Non_CJK_fixed_font guifontwide=CJK_fixed_font
5059 if (is_cjk_font(gui.norm_font))
5061 int cjk_width;
5063 /* Measure the text extent of U+4E00 and U+4E8C */
5064 pango_layout_set_text(layout, "\344\270\200\344\272\214", -1);
5065 pango_layout_get_size(layout, &cjk_width, NULL);
5067 if (width == cjk_width) /* Xft not patched */
5068 width /= 2;
5070 g_object_unref(layout);
5072 gui.char_width = (width / 2 + PANGO_SCALE - 1) / PANGO_SCALE;
5074 /* A zero width may cause a crash. Happens for semi-invalid fontsets. */
5075 if (gui.char_width <= 0)
5076 gui.char_width = 8;
5078 gui_mch_adjust_charheight();
5080 /* Set the fontname, which will be used for information purposes */
5081 hl_set_font_name(font_name);
5083 get_styled_font_variants();
5084 ascii_glyph_table_init();
5086 /* Avoid unnecessary overhead if 'guifontwide' is equal to 'guifont'. */
5087 if (gui.wide_font != NULL
5088 && pango_font_description_equal(gui.norm_font, gui.wide_font))
5090 pango_font_description_free(gui.wide_font);
5091 gui.wide_font = NULL;
5094 #else /* !HAVE_GTK2 */
5096 GdkFont *font = NULL;
5098 # ifdef FEAT_XFONTSET
5099 /* Try loading a fontset. If this fails we try loading a normal font. */
5100 if (fontset && font_name != NULL)
5101 font = gui_mch_get_fontset(font_name, TRUE, TRUE);
5103 if (font == NULL)
5104 # endif
5106 /* If font_name is NULL, this means to use the default, which should
5107 * be present on all X11 servers. */
5108 if (font_name == NULL)
5109 font_name = (char_u *)DEFAULT_FONT;
5110 font = gui_mch_get_font(font_name, FALSE);
5113 if (font == NULL)
5114 return FAIL;
5116 gui_mch_free_font(gui.norm_font);
5117 # ifdef FEAT_XFONTSET
5118 gui_mch_free_fontset(gui.fontset);
5119 if (font->type == GDK_FONT_FONTSET)
5121 gui.norm_font = NOFONT;
5122 gui.fontset = (GuiFontset)font;
5123 /* Use two bytes, this works around the problem that the result would
5124 * be zero if no 8-bit font was found. */
5125 gui.char_width = gdk_string_width(font, "xW") / 2;
5127 else
5128 # endif
5130 gui.norm_font = font;
5131 # ifdef FEAT_XFONTSET
5132 gui.fontset = NOFONTSET;
5133 # endif
5134 gui.char_width = ((XFontStruct *)
5135 GDK_FONT_XFONT(font))->max_bounds.width;
5138 /* A zero width may cause a crash. Happens for semi-invalid fontsets. */
5139 if (gui.char_width <= 0)
5140 gui.char_width = 8;
5142 gui.char_height = font->ascent + font->descent + p_linespace;
5143 gui.char_ascent = font->ascent + p_linespace / 2;
5145 /* A not-positive value of char_height may crash Vim. Only happens
5146 * if 'linespace' is negative (which does make sense sometimes). */
5147 gui.char_ascent = MAX(gui.char_ascent, 0);
5148 gui.char_height = MAX(gui.char_height, gui.char_ascent + 1);
5150 /* Set the fontname, which will be used for information purposes */
5151 hl_set_font_name(font_name);
5153 if (font->type != GDK_FONT_FONTSET)
5154 get_styled_font_variants(font_name);
5156 /* Synchronize the fonts used in user input dialogs, since otherwise
5157 * search/replace will be esp. annoying in case of international font
5158 * usage.
5160 gui_gtk_synch_fonts();
5162 # ifdef FEAT_XIM
5163 /* Adjust input management behaviour to the capabilities of the new
5164 * fontset */
5165 xim_decide_input_style();
5166 if (xim_get_status_area_height())
5168 /* Status area is required. Just create the empty container so that
5169 * mainwin will allocate the extra space for status area. */
5170 GtkWidget *alignment = gtk_alignment_new((gfloat)0.5, (gfloat)0.5,
5171 (gfloat)1.0, (gfloat)1.0);
5173 gtk_widget_set_usize(alignment, 20, gui.char_height + 2);
5174 gtk_box_pack_end(GTK_BOX(GTK_BIN(gui.mainwin)->child),
5175 alignment, FALSE, FALSE, 0);
5176 gtk_widget_show(alignment);
5178 # endif
5179 #endif /* !HAVE_GTK2 */
5181 /* Preserve the logical dimensions of the screen. */
5182 update_window_manager_hints(0, 0);
5184 return OK;
5188 * Get a reference to the font "name".
5189 * Return zero for failure.
5191 GuiFont
5192 gui_mch_get_font(char_u *name, int report_error)
5194 #ifdef HAVE_GTK2
5195 PangoFontDescription *font;
5196 #else
5197 GdkFont *font;
5198 #endif
5200 /* can't do this when GUI is not running */
5201 if (!gui.in_use || name == NULL)
5202 return NULL;
5204 #ifdef HAVE_GTK2
5205 if (output_conv.vc_type != CONV_NONE)
5207 char_u *buf;
5209 buf = string_convert(&output_conv, name, NULL);
5210 if (buf != NULL)
5212 font = pango_font_description_from_string((const char *)buf);
5213 vim_free(buf);
5215 else
5216 font = NULL;
5218 else
5219 font = pango_font_description_from_string((const char *)name);
5221 if (font != NULL)
5223 PangoFont *real_font;
5225 /* pango_context_load_font() bails out if no font size is set */
5226 if (pango_font_description_get_size(font) <= 0)
5227 pango_font_description_set_size(font, 10 * PANGO_SCALE);
5229 real_font = pango_context_load_font(gui.text_context, font);
5231 if (real_font == NULL)
5233 pango_font_description_free(font);
5234 font = NULL;
5236 else
5237 g_object_unref(real_font);
5239 #else
5240 font = gdk_font_load((const gchar *)name);
5241 #endif
5243 if (font == NULL)
5245 if (report_error)
5246 EMSG2(_(e_font), name);
5247 return NULL;
5250 #ifdef HAVE_GTK2
5252 * The fixed-width check has been disabled for GTK+ 2. Rationale:
5254 * - The check tends to report false positives, particularly
5255 * in non-Latin locales or with old X fonts.
5256 * - Thanks to our fixed-width hack in gui_gtk2_draw_string(),
5257 * GTK+ 2 Vim is actually capable of displaying variable width
5258 * fonts. Those will just be spaced out like in AA xterm.
5259 * - Failing here for the default font causes GUI startup to fail
5260 * even with wiped out configuration files.
5261 * - The font dialog displays all fonts unfiltered, and it's rather
5262 * annoying if 95% of the listed fonts produce an error message.
5264 # if 0
5266 /* Check that this is a mono-spaced font. Naturally, this is a bit
5267 * hackish -- fixed-width isn't really suitable for i18n text :/ */
5268 PangoLayout *layout;
5269 unsigned int i;
5270 int last_width = -1;
5271 const char test_chars[] = { 'W', 'i', ',', 'x' }; /* arbitrary */
5273 layout = pango_layout_new(gui.text_context);
5274 pango_layout_set_font_description(layout, font);
5276 for (i = 0; i < G_N_ELEMENTS(test_chars); ++i)
5278 int width;
5280 pango_layout_set_text(layout, &test_chars[i], 1);
5281 pango_layout_get_size(layout, &width, NULL);
5283 if (last_width >= 0 && width != last_width)
5285 pango_font_description_free(font);
5286 font = NULL;
5287 break;
5290 last_width = width;
5293 g_object_unref(layout);
5295 # endif
5296 #else /* !HAVE_GTK2 */
5298 XFontStruct *xfont;
5300 /* reference this font as being in use */
5301 gdk_font_ref(font);
5303 /* Check that this is a mono-spaced font.
5305 xfont = (XFontStruct *) GDK_FONT_XFONT(font);
5307 if (xfont->max_bounds.width != xfont->min_bounds.width)
5309 gdk_font_unref(font);
5310 font = NULL;
5313 #endif /* !HAVE_GTK2 */
5315 #if !defined(HAVE_GTK2) || 0 /* disabled for GTK+ 2, see above */
5316 if (font == NULL && report_error)
5317 EMSG2(_(e_fontwidth), name);
5318 #endif
5320 return font;
5323 #if defined(FEAT_EVAL) || defined(PROTO)
5325 * Return the name of font "font" in allocated memory.
5327 /*ARGSUSED*/
5328 char_u *
5329 gui_mch_get_fontname(GuiFont font, char_u *name)
5331 # ifdef HAVE_GTK2
5332 if (font != NOFONT)
5334 char *pangoname = pango_font_description_to_string(font);
5336 if (pangoname != NULL)
5338 char_u *s = vim_strsave((char_u *)pangoname);
5340 g_free(pangoname);
5341 return s;
5344 # else
5345 /* Don't know how to get the name, return what we got. */
5346 if (name != NULL)
5347 return vim_strsave(name);
5348 # endif
5349 return NULL;
5351 #endif
5353 #if !defined(HAVE_GTK2) || defined(PROTO)
5355 * Set the current text font.
5356 * Since we create all GC on demand, we use just gui.current_font to
5357 * indicate the desired current font.
5359 void
5360 gui_mch_set_font(GuiFont font)
5362 gui.current_font = font;
5364 #endif
5366 #if defined(FEAT_XFONTSET) || defined(PROTO)
5368 * Set the current text fontset.
5370 void
5371 gui_mch_set_fontset(GuiFontset fontset)
5373 gui.current_font = fontset;
5375 #endif
5378 * If a font is not going to be used, free its structure.
5380 void
5381 gui_mch_free_font(GuiFont font)
5383 if (font != NOFONT)
5384 #ifdef HAVE_GTK2
5385 pango_font_description_free(font);
5386 #else
5387 gdk_font_unref(font);
5388 #endif
5391 #if defined(FEAT_XFONTSET) || defined(PROTO)
5393 * If a fontset is not going to be used, free its structure.
5395 void
5396 gui_mch_free_fontset(GuiFontset fontset)
5398 if (fontset != NOFONTSET)
5399 gdk_font_unref(fontset);
5401 #endif
5405 * Return the Pixel value (color) for the given color name. This routine was
5406 * pretty much taken from example code in the Silicon Graphics OSF/Motif
5407 * Programmer's Guide.
5408 * Return INVALCOLOR for error.
5410 guicolor_T
5411 gui_mch_get_color(char_u *name)
5413 /* A number of colors that some X11 systems don't have */
5414 static const char *const vimnames[][2] =
5416 {"LightRed", "#FFBBBB"},
5417 {"LightGreen", "#88FF88"},
5418 {"LightMagenta","#FFBBFF"},
5419 {"DarkCyan", "#008888"},
5420 {"DarkBlue", "#0000BB"},
5421 {"DarkRed", "#BB0000"},
5422 {"DarkMagenta", "#BB00BB"},
5423 {"DarkGrey", "#BBBBBB"},
5424 {"DarkYellow", "#BBBB00"},
5425 {"Gray10", "#1A1A1A"},
5426 {"Grey10", "#1A1A1A"},
5427 {"Gray20", "#333333"},
5428 {"Grey20", "#333333"},
5429 {"Gray30", "#4D4D4D"},
5430 {"Grey30", "#4D4D4D"},
5431 {"Gray40", "#666666"},
5432 {"Grey40", "#666666"},
5433 {"Gray50", "#7F7F7F"},
5434 {"Grey50", "#7F7F7F"},
5435 {"Gray60", "#999999"},
5436 {"Grey60", "#999999"},
5437 {"Gray70", "#B3B3B3"},
5438 {"Grey70", "#B3B3B3"},
5439 {"Gray80", "#CCCCCC"},
5440 {"Grey80", "#CCCCCC"},
5441 {"Gray90", "#E5E5E5"},
5442 {"Grey90", "#E5E5E5"},
5443 {NULL, NULL}
5446 if (!gui.in_use) /* can't do this when GUI not running */
5447 return INVALCOLOR;
5449 while (name != NULL)
5451 GdkColor color;
5452 int parsed;
5453 int i;
5455 parsed = gdk_color_parse((const char *)name, &color);
5457 #ifndef HAVE_GTK2 /* ohh, lovely GTK+ 2, eases our pain :) */
5459 * Since we have already called gtk_set_locale here the bugger
5460 * XParseColor will accept only explicit color names in the language
5461 * of the current locale. However this will interfere with:
5462 * 1. Vim's global startup files
5463 * 2. Explicit color names in .vimrc
5465 * Therefore we first try to parse the color in the current locale and
5466 * if it fails, we fall back to the portable "C" one.
5468 if (!parsed)
5470 char *current;
5472 current = setlocale(LC_ALL, NULL);
5473 if (current != NULL)
5475 char *saved;
5477 saved = g_strdup(current);
5478 setlocale(LC_ALL, "C");
5480 parsed = gdk_color_parse((const gchar *)name, &color);
5482 setlocale(LC_ALL, saved);
5483 gtk_set_locale();
5485 g_free(saved);
5488 #endif /* !HAVE_GTK2 */
5490 if (parsed)
5492 #ifdef HAVE_GTK2
5493 gdk_colormap_alloc_color(gtk_widget_get_colormap(gui.drawarea),
5494 &color, FALSE, TRUE);
5495 #else
5496 gdk_color_alloc(gtk_widget_get_colormap(gui.drawarea), &color);
5497 #endif
5498 return (guicolor_T)color.pixel;
5500 /* add a few builtin names and try again */
5501 for (i = 0; ; ++i)
5503 if (vimnames[i][0] == NULL)
5505 name = NULL;
5506 break;
5508 if (STRICMP(name, vimnames[i][0]) == 0)
5510 name = (char_u *)vimnames[i][1];
5511 break;
5516 return INVALCOLOR;
5520 * Set the current text foreground color.
5522 void
5523 gui_mch_set_fg_color(guicolor_T color)
5525 gui.fgcolor->pixel = (unsigned long)color;
5529 * Set the current text background color.
5531 void
5532 gui_mch_set_bg_color(guicolor_T color)
5534 gui.bgcolor->pixel = (unsigned long)color;
5538 * Set the current text special color.
5540 void
5541 gui_mch_set_sp_color(guicolor_T color)
5543 gui.spcolor->pixel = (unsigned long)color;
5546 #ifdef HAVE_GTK2
5548 * Function-like convenience macro for the sake of efficiency.
5550 #define INSERT_PANGO_ATTR(Attribute, AttrList, Start, End) \
5551 G_STMT_START{ \
5552 PangoAttribute *tmp_attr_; \
5553 tmp_attr_ = (Attribute); \
5554 tmp_attr_->start_index = (Start); \
5555 tmp_attr_->end_index = (End); \
5556 pango_attr_list_insert((AttrList), tmp_attr_); \
5557 }G_STMT_END
5559 static void
5560 apply_wide_font_attr(char_u *s, int len, PangoAttrList *attr_list)
5562 char_u *start = NULL;
5563 char_u *p;
5564 int uc;
5566 for (p = s; p < s + len; p += utf_byte2len(*p))
5568 uc = utf_ptr2char(p);
5570 if (start == NULL)
5572 if (uc >= 0x80 && utf_char2cells(uc) == 2)
5573 start = p;
5575 else if (uc < 0x80 /* optimization shortcut */
5576 || (utf_char2cells(uc) != 2 && !utf_iscomposing(uc)))
5578 INSERT_PANGO_ATTR(pango_attr_font_desc_new(gui.wide_font),
5579 attr_list, start - s, p - s);
5580 start = NULL;
5584 if (start != NULL)
5585 INSERT_PANGO_ATTR(pango_attr_font_desc_new(gui.wide_font),
5586 attr_list, start - s, len);
5589 static int
5590 count_cluster_cells(char_u *s, PangoItem *item,
5591 PangoGlyphString* glyphs, int i,
5592 int *cluster_width,
5593 int *last_glyph_rbearing)
5595 char_u *p;
5596 int next; /* glyph start index of next cluster */
5597 int start, end; /* string segment of current cluster */
5598 int width; /* real cluster width in Pango units */
5599 int uc;
5600 int cellcount = 0;
5602 width = glyphs->glyphs[i].geometry.width;
5604 for (next = i + 1; next < glyphs->num_glyphs; ++next)
5606 if (glyphs->glyphs[next].attr.is_cluster_start)
5607 break;
5608 else if (glyphs->glyphs[next].geometry.width > width)
5609 width = glyphs->glyphs[next].geometry.width;
5612 start = item->offset + glyphs->log_clusters[i];
5613 end = item->offset + ((next < glyphs->num_glyphs) ?
5614 glyphs->log_clusters[next] : item->length);
5616 for (p = s + start; p < s + end; p += utf_byte2len(*p))
5618 uc = utf_ptr2char(p);
5619 if (uc < 0x80)
5620 ++cellcount;
5621 else if (!utf_iscomposing(uc))
5622 cellcount += utf_char2cells(uc);
5625 if (last_glyph_rbearing != NULL
5626 && cellcount > 0 && next == glyphs->num_glyphs)
5628 PangoRectangle ink_rect;
5630 * If a certain combining mark had to be taken from a non-monospace
5631 * font, we have to compensate manually by adapting x_offset according
5632 * to the ink extents of the previous glyph.
5634 pango_font_get_glyph_extents(item->analysis.font,
5635 glyphs->glyphs[i].glyph,
5636 &ink_rect, NULL);
5638 if (PANGO_RBEARING(ink_rect) > 0)
5639 *last_glyph_rbearing = PANGO_RBEARING(ink_rect);
5642 if (cellcount > 0)
5643 *cluster_width = width;
5645 return cellcount;
5649 * If there are only combining characters in the cluster, we cannot just
5650 * change the width of the previous glyph since there is none. Therefore
5651 * some guesswork is needed.
5653 * If ink_rect.x is negative Pango apparently has taken care of the composing
5654 * by itself. Actually setting x_offset = 0 should be sufficient then, but due
5655 * to problems with composing from different fonts we still need to fine-tune
5656 * x_offset to avoid uglyness.
5658 * If ink_rect.x is not negative, force overstriking by pointing x_offset to
5659 * the position of the previous glyph. Apparently this happens only with old
5660 * X fonts which don't provide the special combining information needed by
5661 * Pango.
5663 static void
5664 setup_zero_width_cluster(PangoItem *item, PangoGlyphInfo *glyph,
5665 int last_cellcount, int last_cluster_width,
5666 int last_glyph_rbearing)
5668 PangoRectangle ink_rect;
5669 PangoRectangle logical_rect;
5670 int width;
5672 width = last_cellcount * gui.char_width * PANGO_SCALE;
5673 glyph->geometry.x_offset = -width + MAX(0, width - last_cluster_width) / 2;
5674 glyph->geometry.width = 0;
5676 pango_font_get_glyph_extents(item->analysis.font,
5677 glyph->glyph,
5678 &ink_rect, &logical_rect);
5679 if (ink_rect.x < 0)
5681 glyph->geometry.x_offset += last_glyph_rbearing;
5682 glyph->geometry.y_offset = logical_rect.height
5683 - (gui.char_height - p_linespace) * PANGO_SCALE;
5687 static void
5688 draw_glyph_string(int row, int col, int num_cells, int flags,
5689 PangoFont *font, PangoGlyphString *glyphs)
5691 if (!(flags & DRAW_TRANSP))
5693 gdk_gc_set_foreground(gui.text_gc, gui.bgcolor);
5695 gdk_draw_rectangle(gui.drawarea->window,
5696 gui.text_gc,
5697 TRUE,
5698 FILL_X(col),
5699 FILL_Y(row),
5700 num_cells * gui.char_width,
5701 gui.char_height);
5704 gdk_gc_set_foreground(gui.text_gc, gui.fgcolor);
5706 gdk_draw_glyphs(gui.drawarea->window,
5707 gui.text_gc,
5708 font,
5709 TEXT_X(col),
5710 TEXT_Y(row),
5711 glyphs);
5713 /* redraw the contents with an offset of 1 to emulate bold */
5714 if ((flags & DRAW_BOLD) && !gui.font_can_bold)
5715 gdk_draw_glyphs(gui.drawarea->window,
5716 gui.text_gc,
5717 font,
5718 TEXT_X(col) + 1,
5719 TEXT_Y(row),
5720 glyphs);
5723 #endif /* HAVE_GTK2 */
5726 * Draw underline and undercurl at the bottom of the character cell.
5728 static void
5729 draw_under(int flags, int row, int col, int cells)
5731 int i;
5732 int offset;
5733 const static int val[8] = {1, 0, 0, 0, 1, 2, 2, 2 };
5734 int y = FILL_Y(row + 1) - 1;
5736 /* Undercurl: draw curl at the bottom of the character cell. */
5737 if (flags & DRAW_UNDERC)
5739 gdk_gc_set_foreground(gui.text_gc, gui.spcolor);
5740 for (i = FILL_X(col); i < FILL_X(col + cells); ++i)
5742 offset = val[i % 8];
5743 gdk_draw_point(gui.drawarea->window, gui.text_gc, i, y - offset);
5745 gdk_gc_set_foreground(gui.text_gc, gui.fgcolor);
5748 /* Underline: draw a line at the bottom of the character cell. */
5749 if (flags & DRAW_UNDERL)
5751 /* When p_linespace is 0, overwrite the bottom row of pixels.
5752 * Otherwise put the line just below the character. */
5753 if (p_linespace > 1)
5754 y -= p_linespace - 1;
5755 gdk_draw_line(gui.drawarea->window, gui.text_gc,
5756 FILL_X(col), y,
5757 FILL_X(col + cells) - 1, y);
5761 #if defined(HAVE_GTK2) || defined(PROTO)
5763 gui_gtk2_draw_string(int row, int col, char_u *s, int len, int flags)
5765 GdkRectangle area; /* area for clip mask */
5766 PangoGlyphString *glyphs; /* glyphs of current item */
5767 int column_offset = 0; /* column offset in cells */
5768 int i;
5769 char_u *conv_buf = NULL; /* result of UTF-8 conversion */
5770 char_u *new_conv_buf;
5771 int convlen;
5772 char_u *sp, *bp;
5773 int plen;
5775 if (gui.text_context == NULL || gui.drawarea->window == NULL)
5776 return len;
5778 if (output_conv.vc_type != CONV_NONE)
5781 * Convert characters from 'encoding' to 'termencoding', which is set
5782 * to UTF-8 by gui_mch_init(). did_set_string_option() in option.c
5783 * prohibits changing this to something else than UTF-8 if the GUI is
5784 * in use.
5786 convlen = len;
5787 conv_buf = string_convert(&output_conv, s, &convlen);
5788 g_return_val_if_fail(conv_buf != NULL, len);
5790 /* Correct for differences in char width: some chars are
5791 * double-wide in 'encoding' but single-wide in utf-8. Add a space to
5792 * compensate for that. */
5793 for (sp = s, bp = conv_buf; sp < s + len && bp < conv_buf + convlen; )
5795 plen = utf_ptr2len(bp);
5796 if ((*mb_ptr2cells)(sp) == 2 && utf_ptr2cells(bp) == 1)
5798 new_conv_buf = alloc(convlen + 2);
5799 if (new_conv_buf == NULL)
5800 return len;
5801 plen += bp - conv_buf;
5802 mch_memmove(new_conv_buf, conv_buf, plen);
5803 new_conv_buf[plen] = ' ';
5804 mch_memmove(new_conv_buf + plen + 1, conv_buf + plen,
5805 convlen - plen + 1);
5806 vim_free(conv_buf);
5807 conv_buf = new_conv_buf;
5808 ++convlen;
5809 bp = conv_buf + plen;
5810 plen = 1;
5812 sp += (*mb_ptr2len)(sp);
5813 bp += plen;
5815 s = conv_buf;
5816 len = convlen;
5820 * Restrict all drawing to the current screen line in order to prevent
5821 * fuzzy font lookups from messing up the screen.
5823 area.x = gui.border_offset;
5824 area.y = FILL_Y(row);
5825 area.width = gui.num_cols * gui.char_width;
5826 area.height = gui.char_height;
5828 gdk_gc_set_clip_origin(gui.text_gc, 0, 0);
5829 gdk_gc_set_clip_rectangle(gui.text_gc, &area);
5831 glyphs = pango_glyph_string_new();
5834 * Optimization hack: If possible, skip the itemize and shaping process
5835 * for pure ASCII strings. This optimization is particularly effective
5836 * because Vim draws space characters to clear parts of the screen.
5838 if (!(flags & DRAW_ITALIC)
5839 && !((flags & DRAW_BOLD) && gui.font_can_bold)
5840 && gui.ascii_glyphs != NULL)
5842 char_u *p;
5844 for (p = s; p < s + len; ++p)
5845 if (*p & 0x80)
5846 goto not_ascii;
5848 pango_glyph_string_set_size(glyphs, len);
5850 for (i = 0; i < len; ++i)
5852 glyphs->glyphs[i] = gui.ascii_glyphs->glyphs[s[i]];
5853 glyphs->log_clusters[i] = i;
5856 draw_glyph_string(row, col, len, flags, gui.ascii_font, glyphs);
5858 column_offset = len;
5860 else
5861 not_ascii:
5863 PangoAttrList *attr_list;
5864 GList *item_list;
5865 int cluster_width;
5866 int last_glyph_rbearing;
5867 int cells = 0; /* cells occupied by current cluster */
5868 #if 0
5869 int monospace13 = STRICMP(p_guifont, "monospace 13") == 0;
5870 #endif
5872 /* Safety check: pango crashes when invoked with invalid utf-8
5873 * characters. */
5874 if (!utf_valid_string(s, s + len))
5876 column_offset = len;
5877 goto skipitall;
5880 /* original width of the current cluster */
5881 cluster_width = PANGO_SCALE * gui.char_width;
5883 /* right bearing of the last non-composing glyph */
5884 last_glyph_rbearing = PANGO_SCALE * gui.char_width;
5886 attr_list = pango_attr_list_new();
5888 /* If 'guifontwide' is set then use that for double-width characters.
5889 * Otherwise just go with 'guifont' and let Pango do its thing. */
5890 if (gui.wide_font != NULL)
5891 apply_wide_font_attr(s, len, attr_list);
5893 if ((flags & DRAW_BOLD) && gui.font_can_bold)
5894 INSERT_PANGO_ATTR(pango_attr_weight_new(PANGO_WEIGHT_BOLD),
5895 attr_list, 0, len);
5896 if (flags & DRAW_ITALIC)
5897 INSERT_PANGO_ATTR(pango_attr_style_new(PANGO_STYLE_ITALIC),
5898 attr_list, 0, len);
5900 * Break the text into segments with consistent directional level
5901 * and shaping engine. Pure Latin text needs only a single segment,
5902 * so there's no need to worry about the loop's efficiency. Better
5903 * try to optimize elsewhere, e.g. reducing exposes and stuff :)
5905 item_list = pango_itemize(gui.text_context,
5906 (const char *)s, 0, len, attr_list, NULL);
5908 while (item_list != NULL)
5910 PangoItem *item;
5911 int item_cells = 0; /* item length in cells */
5913 item = (PangoItem *)item_list->data;
5914 item_list = g_list_delete_link(item_list, item_list);
5916 * Increment the bidirectional embedding level by 1 if it is not
5917 * even. An odd number means the output will be RTL, but we don't
5918 * want that since Vim handles right-to-left text on its own. It
5919 * would probably be sufficient to just set level = 0, but you can
5920 * never know :)
5922 * Unfortunately we can't take advantage of Pango's ability to
5923 * render both LTR and RTL at the same time. In order to support
5924 * that, Vim's main screen engine would have to make use of Pango
5925 * functionality.
5927 item->analysis.level = (item->analysis.level + 1) & (~1U);
5929 /* HACK: Overrule the shape engine, we don't want shaping to be
5930 * done, because drawing the cursor would change the display. */
5931 item->analysis.shape_engine = default_shape_engine;
5933 pango_shape((const char *)s + item->offset, item->length,
5934 &item->analysis, glyphs);
5936 * Fixed-width hack: iterate over the array and assign a fixed
5937 * width to each glyph, thus overriding the choice made by the
5938 * shaping engine. We use utf_char2cells() to determine the
5939 * number of cells needed.
5941 * Also perform all kind of dark magic to get composing
5942 * characters right (and pretty too of course).
5944 for (i = 0; i < glyphs->num_glyphs; ++i)
5946 PangoGlyphInfo *glyph;
5948 glyph = &glyphs->glyphs[i];
5950 if (glyph->attr.is_cluster_start)
5952 int cellcount;
5954 cellcount = count_cluster_cells(
5955 s, item, glyphs, i, &cluster_width,
5956 (item_list != NULL) ? &last_glyph_rbearing : NULL);
5958 if (cellcount > 0)
5960 int width;
5962 width = cellcount * gui.char_width * PANGO_SCALE;
5963 glyph->geometry.x_offset +=
5964 MAX(0, width - cluster_width) / 2;
5965 glyph->geometry.width = width;
5967 else
5969 /* If there are only combining characters in the
5970 * cluster, we cannot just change the width of the
5971 * previous glyph since there is none. Therefore
5972 * some guesswork is needed. */
5973 setup_zero_width_cluster(item, glyph, cells,
5974 cluster_width,
5975 last_glyph_rbearing);
5978 item_cells += cellcount;
5979 cells = cellcount;
5981 else if (i > 0)
5983 int width;
5985 /* There is a previous glyph, so we deal with combining
5986 * characters the canonical way. That is, setting the
5987 * width of the previous glyph to 0. */
5988 glyphs->glyphs[i - 1].geometry.width = 0;
5989 width = cells * gui.char_width * PANGO_SCALE;
5990 glyph->geometry.x_offset +=
5991 MAX(0, width - cluster_width) / 2;
5992 #if 0
5993 /* Dirty hack: for "monospace 13" font there is a bug that
5994 * draws composing chars in the wrong position. Add
5995 * "width" to the offset to work around that. */
5996 if (monospace13)
5997 glyph->geometry.x_offset = width;
5998 #endif
6000 glyph->geometry.width = width;
6002 else /* i == 0 "cannot happen" */
6004 glyph->geometry.width = 0;
6008 /*** Aaaaand action! ***/
6009 draw_glyph_string(row, col + column_offset, item_cells,
6010 flags, item->analysis.font, glyphs);
6012 pango_item_free(item);
6014 column_offset += item_cells;
6017 pango_attr_list_unref(attr_list);
6020 skipitall:
6021 /* Draw underline and undercurl. */
6022 draw_under(flags, row, col, column_offset);
6024 pango_glyph_string_free(glyphs);
6025 vim_free(conv_buf);
6027 gdk_gc_set_clip_rectangle(gui.text_gc, NULL);
6029 return column_offset;
6031 #endif /* HAVE_GTK2 */
6033 #if !defined(HAVE_GTK2) || defined(PROTO)
6034 void
6035 gui_mch_draw_string(int row, int col, char_u *s, int len, int flags)
6037 static XChar2b *buf = NULL;
6038 static int buflen = 0;
6039 int is_wide;
6040 XChar2b *text;
6041 int textlen;
6042 XFontStruct *xfont;
6043 char_u *p;
6044 # ifdef FEAT_MBYTE
6045 unsigned c;
6046 # endif
6047 int width;
6049 if (gui.current_font == NULL || gui.drawarea->window == NULL)
6050 return;
6053 * Yeah yeah apparently the font support in GTK+ 1.2 only cares for either:
6054 * asians or 8-bit fonts. It is broken there, but no wonder the whole font
6055 * stuff is broken in X11 in first place. And the internationalization API
6056 * isn't something you would really like to use.
6059 xfont = (XFontStruct *)((GdkFontPrivate*)gui.current_font)->xfont;
6060 is_wide = ((xfont->min_byte1 != 0 || xfont->max_byte1 != 0)
6061 # ifdef FEAT_XFONTSET
6062 && gui.fontset == NOFONTSET
6063 # endif
6066 if (is_wide)
6068 /* Convert a byte sequence to 16 bit characters for the Gdk functions.
6069 * Need a buffer for the 16 bit characters. Keep it between calls,
6070 * because allocating it each time is slow. */
6071 if (buflen < len)
6073 XtFree((char *)buf);
6074 buf = (XChar2b *)XtMalloc(len * sizeof(XChar2b));
6075 buflen = len;
6078 p = s;
6079 textlen = 0;
6080 width = 0;
6081 while (p < s + len)
6083 # ifdef FEAT_MBYTE
6084 if (enc_utf8)
6086 c = utf_ptr2char(p);
6087 if (c >= 0x10000) /* show chars > 0xffff as ? */
6088 c = 0xbf;
6089 buf[textlen].byte1 = c >> 8;
6090 buf[textlen].byte2 = c;
6091 p += utf_ptr2len(p);
6092 width += utf_char2cells(c);
6094 else
6095 # endif
6097 buf[textlen].byte1 = '\0'; /* high eight bits */
6098 buf[textlen].byte2 = *p; /* low eight bits */
6099 ++p;
6100 ++width;
6102 ++textlen;
6104 text = buf;
6105 textlen = textlen * 2;
6107 else
6109 text = (XChar2b *)s;
6110 textlen = len;
6111 # ifdef FEAT_MBYTE
6112 if (has_mbyte)
6114 width = 0;
6115 for (p = s; p < s + len; p += (*mb_ptr2len)(p))
6116 width += (*mb_ptr2cells)(p);
6118 else
6119 # endif
6120 width = len;
6123 if (!(flags & DRAW_TRANSP))
6125 gdk_gc_set_foreground(gui.text_gc, gui.bgcolor);
6126 gdk_draw_rectangle(gui.drawarea->window,
6127 gui.text_gc,
6128 TRUE,
6129 FILL_X(col), FILL_Y(row),
6130 width * gui.char_width, gui.char_height);
6132 gdk_gc_set_foreground(gui.text_gc, gui.fgcolor);
6133 gdk_draw_text(gui.drawarea->window,
6134 gui.current_font,
6135 gui.text_gc,
6136 TEXT_X(col), TEXT_Y(row),
6137 (const gchar *)text, textlen);
6139 /* redraw the contents with an offset of 1 to emulate bold */
6140 if (flags & DRAW_BOLD)
6141 gdk_draw_text(gui.drawarea->window,
6142 gui.current_font,
6143 gui.text_gc,
6144 TEXT_X(col) + 1, TEXT_Y(row),
6145 (const gchar *)text, textlen);
6147 /* Draw underline and undercurl. */
6148 draw_under(flags, row, col, width);
6150 #endif /* !HAVE_GTK2 */
6153 * Return OK if the key with the termcap name "name" is supported.
6156 gui_mch_haskey(char_u *name)
6158 int i;
6160 for (i = 0; special_keys[i].key_sym != 0; i++)
6161 if (name[0] == special_keys[i].code0
6162 && name[1] == special_keys[i].code1)
6163 return OK;
6164 return FAIL;
6167 #if defined(FEAT_TITLE) \
6168 || (defined(FEAT_XIM) && !defined(HAVE_GTK2)) \
6169 || defined(PROTO)
6171 * Return the text window-id and display. Only required for X-based GUI's
6174 gui_get_x11_windis(Window *win, Display **dis)
6176 if (gui.mainwin != NULL && gui.mainwin->window != NULL)
6178 *dis = GDK_WINDOW_XDISPLAY(gui.mainwin->window);
6179 *win = GDK_WINDOW_XWINDOW(gui.mainwin->window);
6180 return OK;
6183 *dis = NULL;
6184 *win = 0;
6185 return FAIL;
6187 #endif
6189 #if defined(FEAT_CLIENTSERVER) \
6190 || (defined(FEAT_X11) && defined(FEAT_CLIPBOARD)) || defined(PROTO)
6192 Display *
6193 gui_mch_get_display(void)
6195 if (gui.mainwin != NULL && gui.mainwin->window != NULL)
6196 return GDK_WINDOW_XDISPLAY(gui.mainwin->window);
6197 else
6198 return NULL;
6200 #endif
6202 void
6203 gui_mch_beep(void)
6205 #ifdef HAVE_GTK_MULTIHEAD
6206 GdkDisplay *display;
6208 if (gui.mainwin != NULL && GTK_WIDGET_REALIZED(gui.mainwin))
6209 display = gtk_widget_get_display(gui.mainwin);
6210 else
6211 display = gdk_display_get_default();
6213 if (display != NULL)
6214 gdk_display_beep(display);
6215 #else
6216 gdk_beep();
6217 #endif
6220 void
6221 gui_mch_flash(int msec)
6223 GdkGCValues values;
6224 GdkGC *invert_gc;
6226 if (gui.drawarea->window == NULL)
6227 return;
6229 values.foreground.pixel = gui.norm_pixel ^ gui.back_pixel;
6230 values.background.pixel = gui.norm_pixel ^ gui.back_pixel;
6231 values.function = GDK_XOR;
6232 invert_gc = gdk_gc_new_with_values(gui.drawarea->window,
6233 &values,
6234 GDK_GC_FOREGROUND |
6235 GDK_GC_BACKGROUND |
6236 GDK_GC_FUNCTION);
6237 gdk_gc_set_exposures(invert_gc,
6238 gui.visibility != GDK_VISIBILITY_UNOBSCURED);
6240 * Do a visual beep by changing back and forth in some undetermined way,
6241 * the foreground and background colors. This is due to the fact that
6242 * there can't be really any prediction about the effects of XOR on
6243 * arbitrary X11 servers. However this seems to be enough for what we
6244 * intend it to do.
6246 gdk_draw_rectangle(gui.drawarea->window, invert_gc,
6247 TRUE,
6248 0, 0,
6249 FILL_X((int)Columns) + gui.border_offset,
6250 FILL_Y((int)Rows) + gui.border_offset);
6252 gui_mch_flush();
6253 ui_delay((long)msec, TRUE); /* wait so many msec */
6255 gdk_draw_rectangle(gui.drawarea->window, invert_gc,
6256 TRUE,
6257 0, 0,
6258 FILL_X((int)Columns) + gui.border_offset,
6259 FILL_Y((int)Rows) + gui.border_offset);
6261 gdk_gc_destroy(invert_gc);
6265 * Invert a rectangle from row r, column c, for nr rows and nc columns.
6267 void
6268 gui_mch_invert_rectangle(int r, int c, int nr, int nc)
6270 GdkGCValues values;
6271 GdkGC *invert_gc;
6273 if (gui.drawarea->window == NULL)
6274 return;
6276 values.foreground.pixel = gui.norm_pixel ^ gui.back_pixel;
6277 values.background.pixel = gui.norm_pixel ^ gui.back_pixel;
6278 values.function = GDK_XOR;
6279 invert_gc = gdk_gc_new_with_values(gui.drawarea->window,
6280 &values,
6281 GDK_GC_FOREGROUND |
6282 GDK_GC_BACKGROUND |
6283 GDK_GC_FUNCTION);
6284 gdk_gc_set_exposures(invert_gc, gui.visibility !=
6285 GDK_VISIBILITY_UNOBSCURED);
6286 gdk_draw_rectangle(gui.drawarea->window, invert_gc,
6287 TRUE,
6288 FILL_X(c), FILL_Y(r),
6289 (nc) * gui.char_width, (nr) * gui.char_height);
6290 gdk_gc_destroy(invert_gc);
6294 * Iconify the GUI window.
6296 void
6297 gui_mch_iconify(void)
6299 #ifdef HAVE_GTK2
6300 gtk_window_iconify(GTK_WINDOW(gui.mainwin));
6301 #else
6302 XIconifyWindow(GDK_WINDOW_XDISPLAY(gui.mainwin->window),
6303 GDK_WINDOW_XWINDOW(gui.mainwin->window),
6304 DefaultScreen(GDK_WINDOW_XDISPLAY(gui.mainwin->window)));
6305 #endif
6308 #if defined(FEAT_EVAL) || defined(PROTO)
6310 * Bring the Vim window to the foreground.
6312 void
6313 gui_mch_set_foreground(void)
6315 # ifdef HAVE_GTK2
6316 gtk_window_present(GTK_WINDOW(gui.mainwin));
6317 # else
6318 gdk_window_raise(gui.mainwin->window);
6319 # endif
6321 #endif
6324 * Draw a cursor without focus.
6326 void
6327 gui_mch_draw_hollow_cursor(guicolor_T color)
6329 int i = 1;
6331 if (gui.drawarea->window == NULL)
6332 return;
6334 gui_mch_set_fg_color(color);
6336 gdk_gc_set_foreground(gui.text_gc, gui.fgcolor);
6337 #ifdef FEAT_MBYTE
6338 if (mb_lefthalve(gui.row, gui.col))
6339 i = 2;
6340 #endif
6341 gdk_draw_rectangle(gui.drawarea->window, gui.text_gc,
6342 FALSE,
6343 FILL_X(gui.col), FILL_Y(gui.row),
6344 i * gui.char_width - 1, gui.char_height - 1);
6348 * Draw part of a cursor, "w" pixels wide, and "h" pixels high, using
6349 * color "color".
6351 void
6352 gui_mch_draw_part_cursor(int w, int h, guicolor_T color)
6354 if (gui.drawarea->window == NULL)
6355 return;
6357 gui_mch_set_fg_color(color);
6359 gdk_gc_set_foreground(gui.text_gc, gui.fgcolor);
6360 gdk_draw_rectangle(gui.drawarea->window, gui.text_gc,
6361 TRUE,
6362 #ifdef FEAT_RIGHTLEFT
6363 /* vertical line should be on the right of current point */
6364 CURSOR_BAR_RIGHT ? FILL_X(gui.col + 1) - w :
6365 #endif
6366 FILL_X(gui.col),
6367 FILL_Y(gui.row) + gui.char_height - h,
6368 w, h);
6373 * Catch up with any queued X11 events. This may put keyboard input into the
6374 * input buffer, call resize call-backs, trigger timers etc. If there is
6375 * nothing in the X11 event queue (& no timers pending), then we return
6376 * immediately.
6378 void
6379 gui_mch_update(void)
6381 while (gtk_events_pending() && !vim_is_input_buf_full())
6382 gtk_main_iteration_do(FALSE);
6385 static gint
6386 input_timer_cb(gpointer data)
6388 int *timed_out = (int *) data;
6390 /* Just inform the caller about the occurrence of it */
6391 *timed_out = TRUE;
6393 if (gtk_main_level() > 0)
6394 gtk_main_quit();
6396 return FALSE; /* don't happen again */
6399 #ifdef FEAT_SNIFF
6401 * Callback function, used when data is available on the SNiFF connection.
6403 /* ARGSUSED */
6404 static void
6405 sniff_request_cb(
6406 gpointer data,
6407 gint source_fd,
6408 GdkInputCondition condition)
6410 static char_u bytes[3] = {CSI, (int)KS_EXTRA, (int)KE_SNIFF};
6412 add_to_input_buf(bytes, 3);
6414 if (gtk_main_level() > 0)
6415 gtk_main_quit();
6417 #endif
6420 * GUI input routine called by gui_wait_for_chars(). Waits for a character
6421 * from the keyboard.
6422 * wtime == -1 Wait forever.
6423 * wtime == 0 This should never happen.
6424 * wtime > 0 Wait wtime milliseconds for a character.
6425 * Returns OK if a character was found to be available within the given time,
6426 * or FAIL otherwise.
6429 gui_mch_wait_for_chars(long wtime)
6431 int focus;
6432 guint timer;
6433 static int timed_out;
6434 #ifdef FEAT_SNIFF
6435 static int sniff_on = 0;
6436 static gint sniff_input_id = 0;
6437 #endif
6439 #ifdef FEAT_SNIFF
6440 if (sniff_on && !want_sniff_request)
6442 if (sniff_input_id)
6443 gdk_input_remove(sniff_input_id);
6444 sniff_on = 0;
6446 else if (!sniff_on && want_sniff_request)
6448 /* Add fd_from_sniff to watch for available data in main loop. */
6449 sniff_input_id = gdk_input_add(fd_from_sniff,
6450 GDK_INPUT_READ, sniff_request_cb, NULL);
6451 sniff_on = 1;
6453 #endif
6455 timed_out = FALSE;
6457 /* this timeout makes sure that we will return if no characters arrived in
6458 * time */
6460 if (wtime > 0)
6461 timer = gtk_timeout_add((guint32)wtime, input_timer_cb, &timed_out);
6462 else
6463 timer = 0;
6465 focus = gui.in_focus;
6469 /* Stop or start blinking when focus changes */
6470 if (gui.in_focus != focus)
6472 if (gui.in_focus)
6473 gui_mch_start_blink();
6474 else
6475 gui_mch_stop_blink();
6476 focus = gui.in_focus;
6480 * Loop in GTK+ processing until a timeout or input occurs.
6481 * Skip this if input is available anyway (can happen in rare
6482 * situations, sort of race condition).
6484 if (!input_available())
6485 gtk_main();
6487 /* Got char, return immediately */
6488 if (input_available())
6490 if (timer != 0 && !timed_out)
6491 gtk_timeout_remove(timer);
6492 return OK;
6494 } while (wtime < 0 || !timed_out);
6497 * Flush all eventually pending (drawing) events.
6499 gui_mch_update();
6501 return FAIL;
6505 /****************************************************************************
6506 * Output drawing routines.
6507 ****************************************************************************/
6510 /* Flush any output to the screen */
6511 void
6512 gui_mch_flush(void)
6514 #ifdef HAVE_GTK_MULTIHEAD
6515 if (gui.mainwin != NULL && GTK_WIDGET_REALIZED(gui.mainwin))
6516 gdk_display_sync(gtk_widget_get_display(gui.mainwin));
6517 #else
6518 gdk_flush(); /* historical misnomer: calls XSync(), not XFlush() */
6519 #endif
6520 #ifdef HAVE_GTK2
6521 /* This happens to actually do what gui_mch_flush() is supposed to do,
6522 * according to the comment above. */
6523 if (gui.drawarea != NULL && gui.drawarea->window != NULL)
6524 gdk_window_process_updates(gui.drawarea->window, FALSE);
6525 #endif
6529 * Clear a rectangular region of the screen from text pos (row1, col1) to
6530 * (row2, col2) inclusive.
6532 void
6533 gui_mch_clear_block(int row1, int col1, int row2, int col2)
6535 GdkColor color;
6537 if (gui.drawarea->window == NULL)
6538 return;
6540 color.pixel = gui.back_pixel;
6542 gdk_gc_set_foreground(gui.text_gc, &color);
6544 /* Clear one extra pixel at the far right, for when bold characters have
6545 * spilled over to the window border. */
6546 gdk_draw_rectangle(gui.drawarea->window, gui.text_gc, TRUE,
6547 FILL_X(col1), FILL_Y(row1),
6548 (col2 - col1 + 1) * gui.char_width
6549 + (col2 == Columns - 1),
6550 (row2 - row1 + 1) * gui.char_height);
6553 void
6554 gui_mch_clear_all(void)
6556 if (gui.drawarea->window != NULL)
6557 gdk_window_clear(gui.drawarea->window);
6561 * Redraw any text revealed by scrolling up/down.
6563 static void
6564 check_copy_area(void)
6566 GdkEvent *event;
6567 int expose_count;
6569 if (gui.visibility != GDK_VISIBILITY_PARTIAL)
6570 return;
6572 /* Avoid redrawing the cursor while scrolling or it'll end up where
6573 * we don't want it to be. I'm not sure if it's correct to call
6574 * gui_dont_update_cursor() at this point but it works as a quick
6575 * fix for now. */
6576 gui_dont_update_cursor();
6580 /* Wait to check whether the scroll worked or not. */
6581 event = gdk_event_get_graphics_expose(gui.drawarea->window);
6583 if (event == NULL)
6584 break; /* received NoExpose event */
6586 gui_redraw(event->expose.area.x, event->expose.area.y,
6587 event->expose.area.width, event->expose.area.height);
6589 expose_count = event->expose.count;
6590 gdk_event_free(event);
6592 while (expose_count > 0); /* more events follow */
6594 gui_can_update_cursor();
6598 * Delete the given number of lines from the given row, scrolling up any
6599 * text further down within the scroll region.
6601 void
6602 gui_mch_delete_lines(int row, int num_lines)
6604 if (gui.visibility == GDK_VISIBILITY_FULLY_OBSCURED)
6605 return; /* Can't see the window */
6607 gdk_gc_set_foreground(gui.text_gc, gui.fgcolor);
6608 gdk_gc_set_background(gui.text_gc, gui.bgcolor);
6610 /* copy one extra pixel, for when bold has spilled over */
6611 gdk_window_copy_area(gui.drawarea->window, gui.text_gc,
6612 FILL_X(gui.scroll_region_left), FILL_Y(row),
6613 gui.drawarea->window,
6614 FILL_X(gui.scroll_region_left),
6615 FILL_Y(row + num_lines),
6616 gui.char_width * (gui.scroll_region_right
6617 - gui.scroll_region_left + 1) + 1,
6618 gui.char_height * (gui.scroll_region_bot - row - num_lines + 1));
6620 gui_clear_block(gui.scroll_region_bot - num_lines + 1,
6621 gui.scroll_region_left,
6622 gui.scroll_region_bot, gui.scroll_region_right);
6623 check_copy_area();
6627 * Insert the given number of lines before the given row, scrolling down any
6628 * following text within the scroll region.
6630 void
6631 gui_mch_insert_lines(int row, int num_lines)
6633 if (gui.visibility == GDK_VISIBILITY_FULLY_OBSCURED)
6634 return; /* Can't see the window */
6636 gdk_gc_set_foreground(gui.text_gc, gui.fgcolor);
6637 gdk_gc_set_background(gui.text_gc, gui.bgcolor);
6639 /* copy one extra pixel, for when bold has spilled over */
6640 gdk_window_copy_area(gui.drawarea->window, gui.text_gc,
6641 FILL_X(gui.scroll_region_left), FILL_Y(row + num_lines),
6642 gui.drawarea->window,
6643 FILL_X(gui.scroll_region_left), FILL_Y(row),
6644 gui.char_width * (gui.scroll_region_right
6645 - gui.scroll_region_left + 1) + 1,
6646 gui.char_height * (gui.scroll_region_bot - row - num_lines + 1));
6648 gui_clear_block(row, gui.scroll_region_left,
6649 row + num_lines - 1, gui.scroll_region_right);
6650 check_copy_area();
6654 * X Selection stuff, for cutting and pasting text to other windows.
6656 void
6657 clip_mch_request_selection(VimClipboard *cbd)
6659 GdkAtom target;
6660 unsigned i;
6661 int nbytes;
6662 char_u *buffer;
6664 for (i = 0; i < N_SELECTION_TARGETS; ++i)
6666 received_selection = RS_NONE;
6667 target = gdk_atom_intern(selection_targets[i].target, FALSE);
6669 gtk_selection_convert(gui.drawarea,
6670 cbd->gtk_sel_atom, target,
6671 (guint32)GDK_CURRENT_TIME);
6673 while (received_selection == RS_NONE)
6674 gtk_main(); /* wait for selection_received_cb */
6676 if (received_selection != RS_FAIL)
6677 return;
6680 /* Final fallback position - use the X CUT_BUFFER0 store */
6681 nbytes = 0;
6682 buffer = (char_u *)XFetchBuffer(GDK_WINDOW_XDISPLAY(gui.mainwin->window),
6683 &nbytes, 0);
6684 if (nbytes > 0)
6686 /* Got something */
6687 clip_yank_selection(MCHAR, buffer, (long)nbytes, cbd);
6688 if (p_verbose > 0)
6690 verbose_enter();
6691 smsg((char_u *)_("Used CUT_BUFFER0 instead of empty selection"));
6692 verbose_leave();
6695 if (buffer != NULL)
6696 XFree(buffer);
6700 * Disown the selection.
6702 /*ARGSUSED*/
6703 void
6704 clip_mch_lose_selection(VimClipboard *cbd)
6706 /* WEIRD: when using NULL to actually disown the selection, we lose the
6707 * selection the first time we own it. */
6709 gtk_selection_owner_set(NULL, cbd->gtk_sel_atom, (guint32)GDK_CURRENT_TIME);
6710 gui_mch_update();
6715 * Own the selection and return OK if it worked.
6718 clip_mch_own_selection(VimClipboard *cbd)
6720 int success;
6722 success = gtk_selection_owner_set(gui.drawarea, cbd->gtk_sel_atom,
6723 (guint32)GDK_CURRENT_TIME);
6724 gui_mch_update();
6725 return (success) ? OK : FAIL;
6729 * Send the current selection to the clipboard. Do nothing for X because we
6730 * will fill in the selection only when requested by another app.
6732 /*ARGSUSED*/
6733 void
6734 clip_mch_set_selection(VimClipboard *cbd)
6739 #if defined(FEAT_MENU) || defined(PROTO)
6741 * Make a menu item appear either active or not active (grey or not grey).
6743 void
6744 gui_mch_menu_grey(vimmenu_T *menu, int grey)
6746 if (menu->id == NULL)
6747 return;
6749 if (menu_is_separator(menu->name))
6750 grey = TRUE;
6752 gui_mch_menu_hidden(menu, FALSE);
6753 /* Be clever about bitfields versus true booleans here! */
6754 if (!GTK_WIDGET_SENSITIVE(menu->id) == !grey)
6756 gtk_widget_set_sensitive(menu->id, !grey);
6757 gui_mch_update();
6762 * Make menu item hidden or not hidden.
6764 void
6765 gui_mch_menu_hidden(vimmenu_T *menu, int hidden)
6767 if (menu->id == 0)
6768 return;
6770 if (hidden)
6772 if (GTK_WIDGET_VISIBLE(menu->id))
6774 gtk_widget_hide(menu->id);
6775 gui_mch_update();
6778 else
6780 if (!GTK_WIDGET_VISIBLE(menu->id))
6782 gtk_widget_show(menu->id);
6783 gui_mch_update();
6789 * This is called after setting all the menus to grey/hidden or not.
6791 void
6792 gui_mch_draw_menubar(void)
6794 /* just make sure that the visual changes get effect immediately */
6795 gui_mch_update();
6797 #endif /* FEAT_MENU */
6800 * Scrollbar stuff.
6802 void
6803 gui_mch_enable_scrollbar(scrollbar_T *sb, int flag)
6805 if (sb->id == NULL)
6806 return;
6808 if (flag)
6809 gtk_widget_show(sb->id);
6810 else
6811 gtk_widget_hide(sb->id);
6813 update_window_manager_hints(0, 0);
6818 * Return the RGB value of a pixel as long.
6820 long_u
6821 gui_mch_get_rgb(guicolor_T pixel)
6823 GdkColor color;
6824 #ifndef HAVE_GTK2
6825 GdkColorContext *cc;
6827 cc = gdk_color_context_new(gtk_widget_get_visual(gui.drawarea),
6828 gtk_widget_get_colormap(gui.drawarea));
6829 color.pixel = pixel;
6830 gdk_color_context_query_color(cc, &color);
6832 gdk_color_context_free(cc);
6833 #else
6834 gdk_colormap_query_color(gtk_widget_get_colormap(gui.drawarea),
6835 (unsigned long)pixel, &color);
6836 #endif
6838 return (((unsigned)color.red & 0xff00) << 8)
6839 | ((unsigned)color.green & 0xff00)
6840 | (((unsigned)color.blue & 0xff00) >> 8);
6844 * Get current mouse coordinates in text window.
6846 void
6847 gui_mch_getmouse(int *x, int *y)
6849 gdk_window_get_pointer(gui.drawarea->window, x, y, NULL);
6852 void
6853 gui_mch_setmouse(int x, int y)
6855 /* Sorry for the Xlib call, but we can't avoid it, since there is no
6856 * internal GDK mechanism present to accomplish this. (and for good
6857 * reason...) */
6858 XWarpPointer(GDK_WINDOW_XDISPLAY(gui.drawarea->window),
6859 (Window)0, GDK_WINDOW_XWINDOW(gui.drawarea->window),
6860 0, 0, 0U, 0U, x, y);
6864 #ifdef FEAT_MOUSESHAPE
6865 /* The last set mouse pointer shape is remembered, to be used when it goes
6866 * from hidden to not hidden. */
6867 static int last_shape = 0;
6868 #endif
6871 * Use the blank mouse pointer or not.
6873 * hide: TRUE = use blank ptr, FALSE = use parent ptr
6875 void
6876 gui_mch_mousehide(int hide)
6878 if (gui.pointer_hidden != hide)
6880 gui.pointer_hidden = hide;
6881 if (gui.drawarea->window && gui.blank_pointer != NULL)
6883 if (hide)
6884 gdk_window_set_cursor(gui.drawarea->window, gui.blank_pointer);
6885 else
6886 #ifdef FEAT_MOUSESHAPE
6887 mch_set_mouse_shape(last_shape);
6888 #else
6889 gdk_window_set_cursor(gui.drawarea->window, NULL);
6890 #endif
6895 #if defined(FEAT_MOUSESHAPE) || defined(PROTO)
6897 /* Table for shape IDs. Keep in sync with the mshape_names[] table in
6898 * misc2.c! */
6899 static const int mshape_ids[] =
6901 GDK_LEFT_PTR, /* arrow */
6902 GDK_CURSOR_IS_PIXMAP, /* blank */
6903 GDK_XTERM, /* beam */
6904 GDK_SB_V_DOUBLE_ARROW, /* updown */
6905 GDK_SIZING, /* udsizing */
6906 GDK_SB_H_DOUBLE_ARROW, /* leftright */
6907 GDK_SIZING, /* lrsizing */
6908 GDK_WATCH, /* busy */
6909 GDK_X_CURSOR, /* no */
6910 GDK_CROSSHAIR, /* crosshair */
6911 GDK_HAND1, /* hand1 */
6912 GDK_HAND2, /* hand2 */
6913 GDK_PENCIL, /* pencil */
6914 GDK_QUESTION_ARROW, /* question */
6915 GDK_RIGHT_PTR, /* right-arrow */
6916 GDK_CENTER_PTR, /* up-arrow */
6917 GDK_LEFT_PTR /* last one */
6920 void
6921 mch_set_mouse_shape(int shape)
6923 int id;
6924 GdkCursor *c;
6926 if (gui.drawarea->window == NULL)
6927 return;
6929 if (shape == MSHAPE_HIDE || gui.pointer_hidden)
6930 gdk_window_set_cursor(gui.drawarea->window, gui.blank_pointer);
6931 else
6933 if (shape >= MSHAPE_NUMBERED)
6935 id = shape - MSHAPE_NUMBERED;
6936 if (id >= GDK_LAST_CURSOR)
6937 id = GDK_LEFT_PTR;
6938 else
6939 id &= ~1; /* they are always even (why?) */
6941 else if (shape < sizeof(mshape_ids) / sizeof(int))
6942 id = mshape_ids[shape];
6943 else
6944 return;
6945 # ifdef HAVE_GTK_MULTIHEAD
6946 c = gdk_cursor_new_for_display(
6947 gtk_widget_get_display(gui.drawarea), (GdkCursorType)id);
6948 # else
6949 c = gdk_cursor_new((GdkCursorType)id);
6950 # endif
6951 gdk_window_set_cursor(gui.drawarea->window, c);
6952 gdk_cursor_destroy(c); /* Unref, actually. Bloody GTK+ 1. */
6954 if (shape != MSHAPE_HIDE)
6955 last_shape = shape;
6957 #endif /* FEAT_MOUSESHAPE */
6960 #if defined(FEAT_SIGN_ICONS) || defined(PROTO)
6962 * Signs are currently always 2 chars wide. With GTK+ 2, the image will be
6963 * scaled down if the current font is not big enough, or scaled up if the image
6964 * size is less than 3/4 of the maximum sign size. With GTK+ 1, the pixmap
6965 * will be cut off if the current font is not big enough, or centered if it's
6966 * too small.
6968 # define SIGN_WIDTH (2 * gui.char_width)
6969 # define SIGN_HEIGHT (gui.char_height)
6970 # define SIGN_ASPECT ((double)SIGN_HEIGHT / (double)SIGN_WIDTH)
6972 # ifdef HAVE_GTK2
6974 void
6975 gui_mch_drawsign(int row, int col, int typenr)
6977 GdkPixbuf *sign;
6979 sign = (GdkPixbuf *)sign_get_image(typenr);
6981 if (sign != NULL && gui.drawarea != NULL && gui.drawarea->window != NULL)
6983 int width;
6984 int height;
6985 int xoffset;
6986 int yoffset;
6987 int need_scale;
6989 width = gdk_pixbuf_get_width(sign);
6990 height = gdk_pixbuf_get_height(sign);
6992 * Decide whether we need to scale. Allow one pixel of border
6993 * width to be cut off, in order to avoid excessive scaling for
6994 * tiny differences in font size.
6996 need_scale = (width > SIGN_WIDTH + 2
6997 || height > SIGN_HEIGHT + 2
6998 || (width < 3 * SIGN_WIDTH / 4
6999 && height < 3 * SIGN_HEIGHT / 4));
7000 if (need_scale)
7002 double aspect;
7004 /* Keep the original aspect ratio */
7005 aspect = (double)height / (double)width;
7006 width = (double)SIGN_WIDTH * SIGN_ASPECT / aspect;
7007 width = MIN(width, SIGN_WIDTH);
7008 height = (double)width * aspect;
7010 /* This doesn't seem to be worth caching, and doing so
7011 * would complicate the code quite a bit. */
7012 sign = gdk_pixbuf_scale_simple(sign, width, height,
7013 GDK_INTERP_BILINEAR);
7014 if (sign == NULL)
7015 return; /* out of memory */
7018 /* The origin is the upper-left corner of the pixmap. Therefore
7019 * these offset may become negative if the pixmap is smaller than
7020 * the 2x1 cells reserved for the sign icon. */
7021 xoffset = (width - SIGN_WIDTH) / 2;
7022 yoffset = (height - SIGN_HEIGHT) / 2;
7024 gdk_gc_set_foreground(gui.text_gc, gui.bgcolor);
7026 gdk_draw_rectangle(gui.drawarea->window,
7027 gui.text_gc,
7028 TRUE,
7029 FILL_X(col),
7030 FILL_Y(row),
7031 SIGN_WIDTH,
7032 SIGN_HEIGHT);
7034 # if GTK_CHECK_VERSION(2,1,1)
7035 gdk_draw_pixbuf(gui.drawarea->window,
7036 NULL,
7037 sign,
7038 MAX(0, xoffset),
7039 MAX(0, yoffset),
7040 FILL_X(col) - MIN(0, xoffset),
7041 FILL_Y(row) - MIN(0, yoffset),
7042 MIN(width, SIGN_WIDTH),
7043 MIN(height, SIGN_HEIGHT),
7044 GDK_RGB_DITHER_NORMAL,
7045 0, 0);
7046 # else
7047 gdk_pixbuf_render_to_drawable_alpha(sign,
7048 gui.drawarea->window,
7049 MAX(0, xoffset),
7050 MAX(0, yoffset),
7051 FILL_X(col) - MIN(0, xoffset),
7052 FILL_Y(row) - MIN(0, yoffset),
7053 MIN(width, SIGN_WIDTH),
7054 MIN(height, SIGN_HEIGHT),
7055 GDK_PIXBUF_ALPHA_BILEVEL,
7056 127,
7057 GDK_RGB_DITHER_NORMAL,
7058 0, 0);
7059 # endif
7060 if (need_scale)
7061 g_object_unref(sign);
7065 void *
7066 gui_mch_register_sign(char_u *signfile)
7068 if (signfile[0] != NUL && signfile[0] != '-' && gui.in_use)
7070 GdkPixbuf *sign;
7071 GError *error = NULL;
7072 char_u *message;
7074 sign = gdk_pixbuf_new_from_file((const char *)signfile, &error);
7076 if (error == NULL)
7077 return sign;
7079 message = (char_u *)error->message;
7081 if (message != NULL && input_conv.vc_type != CONV_NONE)
7082 message = string_convert(&input_conv, message, NULL);
7084 if (message != NULL)
7086 /* The error message is already translated and will be more
7087 * descriptive than anything we could possibly do ourselves. */
7088 EMSG2("E255: %s", message);
7090 if (input_conv.vc_type != CONV_NONE)
7091 vim_free(message);
7093 g_error_free(error);
7096 return NULL;
7099 void
7100 gui_mch_destroy_sign(void *sign)
7102 if (sign != NULL)
7103 g_object_unref(sign);
7106 # else /* !HAVE_GTK2 */
7108 typedef struct
7110 GdkPixmap *pixmap;
7111 GdkBitmap *mask;
7113 signicon_T;
7115 void
7116 gui_mch_drawsign(int row, int col, int typenr)
7118 signicon_T *sign;
7120 sign = (signicon_T *)sign_get_image(typenr);
7122 if (sign != NULL && sign->pixmap != NULL
7123 && gui.drawarea != NULL && gui.drawarea->window != NULL)
7125 int width;
7126 int height;
7127 int xoffset;
7128 int yoffset;
7130 gdk_window_get_size(sign->pixmap, &width, &height);
7132 /* The origin is the upper-left corner of the pixmap. Therefore
7133 * these offset may become negative if the pixmap is smaller than
7134 * the 2x1 cells reserved for the sign icon. */
7135 xoffset = (width - SIGN_WIDTH) / 2;
7136 yoffset = (height - SIGN_HEIGHT) / 2;
7138 gdk_gc_set_foreground(gui.text_gc, gui.bgcolor);
7140 gdk_draw_rectangle(gui.drawarea->window,
7141 gui.text_gc,
7142 TRUE,
7143 FILL_X(col),
7144 FILL_Y(row),
7145 SIGN_WIDTH,
7146 SIGN_HEIGHT);
7148 /* Set the clip mask for bilevel transparency */
7149 if (sign->mask != NULL)
7151 gdk_gc_set_clip_origin(gui.text_gc,
7152 FILL_X(col) - xoffset,
7153 FILL_Y(row) - yoffset);
7154 gdk_gc_set_clip_mask(gui.text_gc, sign->mask);
7157 gdk_draw_pixmap(gui.drawarea->window,
7158 gui.text_gc,
7159 sign->pixmap,
7160 MAX(0, xoffset),
7161 MAX(0, yoffset),
7162 FILL_X(col) - MIN(0, xoffset),
7163 FILL_Y(row) - MIN(0, yoffset),
7164 MIN(width, SIGN_WIDTH),
7165 MIN(height, SIGN_HEIGHT));
7167 gdk_gc_set_clip_mask(gui.text_gc, NULL);
7171 void *
7172 gui_mch_register_sign(char_u *signfile)
7174 signicon_T *sign = NULL;
7176 if (signfile[0] != NUL && signfile[0] != '-'
7177 && gui.drawarea != NULL && gui.drawarea->window != NULL)
7179 sign = (signicon_T *)alloc(sizeof(signicon_T));
7181 if (sign != NULL) /* NULL == OOM == "cannot really happen" */
7183 sign->mask = NULL;
7184 sign->pixmap = gdk_pixmap_colormap_create_from_xpm(
7185 gui.drawarea->window, NULL,
7186 &sign->mask, NULL,
7187 (const char *)signfile);
7189 if (sign->pixmap == NULL)
7191 vim_free(sign);
7192 sign = NULL;
7193 EMSG(_(e_signdata));
7197 return sign;
7200 void
7201 gui_mch_destroy_sign(void *sign)
7203 if (sign != NULL)
7205 signicon_T *signicon = (signicon_T *)sign;
7207 if (signicon->pixmap != NULL)
7208 gdk_pixmap_unref(signicon->pixmap);
7209 if (signicon->mask != NULL)
7210 gdk_bitmap_unref(signicon->mask);
7212 vim_free(signicon);
7215 # endif /* !HAVE_GTK2 */
7217 #endif /* FEAT_SIGN_ICONS */