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