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