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