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