; * src/gtkutil.c (xg_check_special_colors): Add another GTK+ FIXME.
[emacs.git] / src / gtkutil.c
blob9f05524738bc0b2900296eed93abb017af222b99
1 /* Functions for creating and updating GTK widgets.
3 Copyright (C) 2003-2017 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or (at
10 your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>. */
20 #include <config.h>
22 #ifdef USE_GTK
23 #include <float.h>
24 #include <stdio.h>
26 #include <c-ctype.h>
28 #include "lisp.h"
29 #include "dispextern.h"
30 #include "frame.h"
31 #include "systime.h"
32 #include "xterm.h"
33 #include "blockinput.h"
34 #include "window.h"
35 #include "gtkutil.h"
36 #include "termhooks.h"
37 #include "keyboard.h"
38 #include "coding.h"
40 #include <gdk/gdkkeysyms.h>
42 #ifdef HAVE_XFT
43 #include <X11/Xft/Xft.h>
44 #endif
46 #ifdef HAVE_GTK3
47 #include <gtk/gtkx.h>
48 #include "emacsgtkfixed.h"
49 #endif
51 #ifdef HAVE_XDBE
52 #include <X11/extensions/Xdbe.h>
53 #endif
55 #ifndef HAVE_GTK_WIDGET_SET_HAS_WINDOW
56 #define gtk_widget_set_has_window(w, b) \
57 (gtk_fixed_set_has_window (GTK_FIXED (w), b))
58 #endif
59 #ifndef HAVE_GTK_DIALOG_GET_ACTION_AREA
60 #define gtk_dialog_get_action_area(w) ((w)->action_area)
61 #define gtk_dialog_get_content_area(w) ((w)->vbox)
62 #endif
63 #ifndef HAVE_GTK_WIDGET_GET_SENSITIVE
64 #define gtk_widget_get_sensitive(w) (GTK_WIDGET_SENSITIVE (w))
65 #endif
66 #ifndef HAVE_GTK_ADJUSTMENT_GET_PAGE_SIZE
67 #define gtk_adjustment_set_page_size(w, s) ((w)->page_size = (s))
68 #define gtk_adjustment_set_page_increment(w, s) ((w)->page_increment = (s))
69 #define gtk_adjustment_get_step_increment(w) ((w)->step_increment)
70 #define gtk_adjustment_set_step_increment(w, s) ((w)->step_increment = (s))
71 #endif
72 #if GTK_CHECK_VERSION (2, 12, 0)
73 #define remove_submenu(w) gtk_menu_item_set_submenu ((w), NULL)
74 #else
75 #define remove_submenu(w) gtk_menu_item_remove_submenu ((w))
76 #endif
78 #if ! GTK_CHECK_VERSION (2, 14, 0)
79 #define gtk_adjustment_configure(adj, xvalue, xlower, \
80 xupper, xstep_increment, \
81 xpage_increment, xpagesize) \
82 do { \
83 adj->lower = xlower; \
84 adj->upper = xupper; \
85 adj->page_size = xpagesize; \
86 gtk_adjustment_set_value (adj, xvalue); \
87 adj->page_increment = xpage_increment; \
88 adj->step_increment = xstep_increment; \
89 } while (0)
90 #endif /* < Gtk+ 2.14 */
92 #ifdef HAVE_FREETYPE
93 #if GTK_CHECK_VERSION (3, 2, 0)
94 #define USE_NEW_GTK_FONT_CHOOSER 1
95 #else
96 #define USE_NEW_GTK_FONT_CHOOSER 0
97 #define gtk_font_chooser_dialog_new(x, y) \
98 gtk_font_selection_dialog_new (x)
99 #undef GTK_FONT_CHOOSER
100 #define GTK_FONT_CHOOSER(x) GTK_FONT_SELECTION_DIALOG (x)
101 #define gtk_font_chooser_set_font(x, y) \
102 gtk_font_selection_dialog_set_font_name (x, y)
103 #endif
104 #endif /* HAVE_FREETYPE */
106 #if GTK_CHECK_VERSION (3, 10, 0)
107 #define XG_TEXT_CANCEL "Cancel"
108 #define XG_TEXT_OK "OK"
109 #define XG_TEXT_OPEN "Open"
110 #else
111 #define XG_TEXT_CANCEL GTK_STOCK_CANCEL
112 #define XG_TEXT_OK GTK_STOCK_OK
113 #define XG_TEXT_OPEN GTK_STOCK_OPEN
114 #endif
116 #ifndef HAVE_GTK3
117 #ifdef USE_GTK_TOOLTIP
118 #define gdk_window_get_screen(w) gdk_drawable_get_screen (w)
119 #endif
120 #define gdk_window_get_geometry(w, a, b, c, d) \
121 gdk_window_get_geometry (w, a, b, c, d, 0)
122 #define gdk_x11_window_lookup_for_display(d, w) \
123 gdk_xid_table_lookup_for_display (d, w)
124 #define gtk_box_new(ori, spacing) \
125 ((ori) == GTK_ORIENTATION_HORIZONTAL \
126 ? gtk_hbox_new (FALSE, (spacing)) : gtk_vbox_new (FALSE, (spacing)))
127 #define gtk_scrollbar_new(ori, spacing) \
128 ((ori) == GTK_ORIENTATION_HORIZONTAL \
129 ? gtk_hscrollbar_new ((spacing)) : gtk_vscrollbar_new ((spacing)))
130 #ifndef GDK_KEY_g
131 #define GDK_KEY_g GDK_g
132 #endif
133 #endif /* HAVE_GTK3 */
135 #define XG_BIN_CHILD(x) gtk_bin_get_child (GTK_BIN (x))
137 static void update_theme_scrollbar_width (void);
138 static void update_theme_scrollbar_height (void);
140 #define TB_INFO_KEY "xg_frame_tb_info"
141 struct xg_frame_tb_info
143 Lisp_Object last_tool_bar;
144 Lisp_Object style;
145 int n_last_items;
146 int hmargin, vmargin;
147 GtkTextDirection dir;
150 static GtkWidget * xg_get_widget_from_map (ptrdiff_t idx);
153 /***********************************************************************
154 Display handling functions
155 ***********************************************************************/
157 /* Keep track of the default display, or NULL if there is none. Emacs
158 may close all its displays. */
160 static GdkDisplay *gdpy_def;
162 /* When the GTK widget W is to be created on a display for F that
163 is not the default display, set the display for W.
164 W can be a GtkMenu or a GtkWindow widget. */
166 static void
167 xg_set_screen (GtkWidget *w, struct frame *f)
169 if (FRAME_X_DISPLAY (f) != DEFAULT_GDK_DISPLAY ())
171 GdkDisplay *gdpy = gdk_x11_lookup_xdisplay (FRAME_X_DISPLAY (f));
172 GdkScreen *gscreen = gdk_display_get_default_screen (gdpy);
174 if (GTK_IS_MENU (w))
175 gtk_menu_set_screen (GTK_MENU (w), gscreen);
176 else
177 gtk_window_set_screen (GTK_WINDOW (w), gscreen);
182 /* Open a display named by DISPLAY_NAME. The display is returned in *DPY.
183 *DPY is set to NULL if the display can't be opened.
185 Returns non-zero if display could be opened, zero if display could not
186 be opened, and less than zero if the GTK version doesn't support
187 multiple displays. */
189 void
190 xg_display_open (char *display_name, Display **dpy)
192 GdkDisplay *gdpy;
194 unrequest_sigio (); /* See comment in x_display_ok, xterm.c. */
195 gdpy = gdk_display_open (display_name);
196 request_sigio ();
197 if (!gdpy_def && gdpy)
199 gdpy_def = gdpy;
200 gdk_display_manager_set_default_display (gdk_display_manager_get (),
201 gdpy);
204 *dpy = gdpy ? GDK_DISPLAY_XDISPLAY (gdpy) : NULL;
207 /* Scaling/HiDPI functions. */
208 static int
209 xg_get_gdk_scale (void)
211 const char *sscale = getenv ("GDK_SCALE");
213 if (sscale)
215 long scale = atol (sscale);
216 if (0 < scale)
217 return min (scale, INT_MAX);
220 return 1;
224 xg_get_scale (struct frame *f)
226 #if GTK_CHECK_VERSION (3, 10, 0)
227 if (FRAME_GTK_WIDGET (f))
228 return gtk_widget_get_scale_factor (FRAME_GTK_WIDGET (f));
229 #endif
230 return xg_get_gdk_scale ();
233 /* Close display DPY. */
235 void
236 xg_display_close (Display *dpy)
238 GdkDisplay *gdpy = gdk_x11_lookup_xdisplay (dpy);
240 /* If this is the default display, try to change it before closing.
241 If there is no other display to use, gdpy_def is set to NULL, and
242 the next call to xg_display_open resets the default display. */
243 if (gdk_display_get_default () == gdpy)
245 struct x_display_info *dpyinfo;
246 GdkDisplay *gdpy_new = NULL;
248 /* Find another display. */
249 for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
250 if (dpyinfo->display != dpy)
252 gdpy_new = gdk_x11_lookup_xdisplay (dpyinfo->display);
253 gdk_display_manager_set_default_display (gdk_display_manager_get (),
254 gdpy_new);
255 break;
257 gdpy_def = gdpy_new;
260 #if GTK_CHECK_VERSION (2, 0, 0) && ! GTK_CHECK_VERSION (2, 10, 0)
261 /* GTK 2.2-2.8 has a bug that makes gdk_display_close crash (bug
262 http://bugzilla.gnome.org/show_bug.cgi?id=85715). This way we
263 can continue running, but there will be memory leaks. */
264 g_object_run_dispose (G_OBJECT (gdpy));
265 #else
266 /* This seems to be fixed in GTK 2.10. */
267 gdk_display_close (gdpy);
268 #endif
272 /***********************************************************************
273 Utility functions
274 ***********************************************************************/
276 /* Create and return the cursor to be used for popup menus and
277 scroll bars on display DPY. */
279 GdkCursor *
280 xg_create_default_cursor (Display *dpy)
282 GdkDisplay *gdpy = gdk_x11_lookup_xdisplay (dpy);
283 return gdk_cursor_new_for_display (gdpy, GDK_LEFT_PTR);
286 /* Apply GMASK to GPIX and return a GdkPixbuf with an alpha channel. */
288 static GdkPixbuf *
289 xg_get_pixbuf_from_pix_and_mask (struct frame *f,
290 Pixmap pix,
291 Pixmap mask)
293 GdkPixbuf *icon_buf = 0;
294 int iunused;
295 Window wunused;
296 unsigned int width, height, depth, uunused;
298 if (FRAME_DISPLAY_INFO (f)->red_bits != 8)
299 return 0;
300 XGetGeometry (FRAME_X_DISPLAY (f), pix, &wunused, &iunused, &iunused,
301 &width, &height, &uunused, &depth);
302 if (depth != 24)
303 return 0;
304 XImage *xim = XGetImage (FRAME_X_DISPLAY (f), pix, 0, 0, width, height,
305 ~0, XYPixmap);
306 if (xim)
308 XImage *xmm = (! mask ? 0
309 : XGetImage (FRAME_X_DISPLAY (f), mask, 0, 0,
310 width, height, ~0, XYPixmap));
311 icon_buf = gdk_pixbuf_new (GDK_COLORSPACE_RGB, TRUE, 8, width, height);
312 if (icon_buf)
314 guchar *pixels = gdk_pixbuf_get_pixels (icon_buf);
315 int rowjunkwidth = gdk_pixbuf_get_rowstride (icon_buf) - width * 4;
316 for (int y = 0; y < height; y++, pixels += rowjunkwidth)
317 for (int x = 0; x < width; x++)
319 unsigned long rgb = XGetPixel (xim, x, y);
320 *pixels++ = (rgb >> 16) & 255;
321 *pixels++ = (rgb >> 8) & 255;
322 *pixels++ = rgb & 255;
323 *pixels++ = xmm && !XGetPixel (xmm, x, y) ? 0 : 255;
327 if (xmm)
328 XDestroyImage (xmm);
329 XDestroyImage (xim);
332 return icon_buf;
335 static Lisp_Object
336 file_for_image (Lisp_Object image)
338 Lisp_Object specified_file = Qnil;
339 Lisp_Object tail;
341 for (tail = XCDR (image);
342 NILP (specified_file) && CONSP (tail) && CONSP (XCDR (tail));
343 tail = XCDR (XCDR (tail)))
344 if (EQ (XCAR (tail), QCfile))
345 specified_file = XCAR (XCDR (tail));
347 return specified_file;
350 /* For the image defined in IMG, make and return a GtkImage. For displays with
351 8 planes or less we must make a GdkPixbuf and apply the mask manually.
352 Otherwise the highlighting and dimming the tool bar code in GTK does
353 will look bad. For display with more than 8 planes we just use the
354 pixmap and mask directly. For monochrome displays, GTK doesn't seem
355 able to use external pixmaps, it looks bad whatever we do.
356 The image is defined on the display where frame F is.
357 WIDGET is used to find the GdkColormap to use for the GdkPixbuf.
358 If OLD_WIDGET is NULL, a new widget is constructed and returned.
359 If OLD_WIDGET is not NULL, that widget is modified. */
361 static GtkWidget *
362 xg_get_image_for_pixmap (struct frame *f,
363 struct image *img,
364 GtkWidget *widget,
365 GtkImage *old_widget)
367 GdkPixbuf *icon_buf;
369 /* If we have a file, let GTK do all the image handling.
370 This seems to be the only way to make insensitive and activated icons
371 look good in all cases. */
372 Lisp_Object specified_file = file_for_image (img->spec);
373 Lisp_Object file;
375 /* We already loaded the image once before calling this
376 function, so this only fails if the image file has been removed.
377 In that case, use the pixmap already loaded. */
379 if (STRINGP (specified_file)
380 && STRINGP (file = x_find_image_file (specified_file)))
382 char *encoded_file = SSDATA (ENCODE_FILE (file));
383 if (! old_widget)
384 old_widget = GTK_IMAGE (gtk_image_new_from_file (encoded_file));
385 else
386 gtk_image_set_from_file (old_widget, encoded_file);
388 return GTK_WIDGET (old_widget);
391 /* No file, do the image handling ourselves. This will look very bad
392 on a monochrome display, and sometimes bad on all displays with
393 certain themes. */
395 /* This is a workaround to make icons look good on pseudo color
396 displays. Apparently GTK expects the images to have an alpha
397 channel. If they don't, insensitive and activated icons will
398 look bad. This workaround does not work on monochrome displays,
399 and is strictly not needed on true color/static color displays (i.e.
400 16 bits and higher). But we do it anyway so we get a pixbuf that is
401 not associated with the img->pixmap. The img->pixmap may be removed
402 by clearing the image cache and then the tool bar redraw fails, since
403 Gtk+ assumes the pixmap is always there. */
404 icon_buf = xg_get_pixbuf_from_pix_and_mask (f, img->pixmap, img->mask);
406 if (icon_buf)
408 if (! old_widget)
409 old_widget = GTK_IMAGE (gtk_image_new_from_pixbuf (icon_buf));
410 else
411 gtk_image_set_from_pixbuf (old_widget, icon_buf);
413 g_object_unref (G_OBJECT (icon_buf));
416 return GTK_WIDGET (old_widget);
420 /* Set CURSOR on W and all widgets W contain. We must do like this
421 for scroll bars and menu because they create widgets internally,
422 and it is those widgets that are visible. */
424 static void
425 xg_set_cursor (GtkWidget *w, GdkCursor *cursor)
427 GdkWindow *window = gtk_widget_get_window (w);
428 GList *children = gdk_window_peek_children (window);
430 gdk_window_set_cursor (window, cursor);
432 /* The scroll bar widget has more than one GDK window (had to look at
433 the source to figure this out), and there is no way to set cursor
434 on widgets in GTK. So we must set the cursor for all GDK windows.
435 Ditto for menus. */
437 for ( ; children; children = g_list_next (children))
438 gdk_window_set_cursor (GDK_WINDOW (children->data), cursor);
441 /* Insert NODE into linked LIST. */
443 static void
444 xg_list_insert (xg_list_node *list, xg_list_node *node)
446 xg_list_node *list_start = list->next;
448 if (list_start) list_start->prev = node;
449 node->next = list_start;
450 node->prev = 0;
451 list->next = node;
454 /* Remove NODE from linked LIST. */
456 static void
457 xg_list_remove (xg_list_node *list, xg_list_node *node)
459 xg_list_node *list_start = list->next;
460 if (node == list_start)
462 list->next = node->next;
463 if (list->next) list->next->prev = 0;
465 else
467 node->prev->next = node->next;
468 if (node->next) node->next->prev = node->prev;
472 /* Allocate and return a utf8 version of STR. If STR is already
473 utf8 or NULL, just return a copy of STR.
474 A new string is allocated and the caller must free the result
475 with g_free. */
477 static char *
478 get_utf8_string (const char *str)
480 char *utf8_str;
482 if (!str) return NULL;
484 /* If not UTF-8, try current locale. */
485 if (!g_utf8_validate (str, -1, NULL))
486 utf8_str = g_locale_to_utf8 (str, -1, 0, 0, 0);
487 else
488 return g_strdup (str);
490 if (!utf8_str)
492 /* Probably some control characters in str. Escape them. */
493 ptrdiff_t len;
494 ptrdiff_t nr_bad = 0;
495 gsize bytes_read;
496 gsize bytes_written;
497 unsigned char *p = (unsigned char *)str;
498 char *cp, *up;
499 GError *err = NULL;
501 while (! (cp = g_locale_to_utf8 ((char *)p, -1, &bytes_read,
502 &bytes_written, &err))
503 && err->code == G_CONVERT_ERROR_ILLEGAL_SEQUENCE)
505 ++nr_bad;
506 p += bytes_written+1;
507 g_error_free (err);
508 err = NULL;
511 if (err)
513 g_error_free (err);
514 err = NULL;
516 if (cp) g_free (cp);
518 len = strlen (str);
519 ptrdiff_t alloc;
520 if (INT_MULTIPLY_WRAPV (nr_bad, 4, &alloc)
521 || INT_ADD_WRAPV (len + 1, alloc, &alloc)
522 || SIZE_MAX < alloc)
523 memory_full (SIZE_MAX);
524 up = utf8_str = xmalloc (alloc);
525 p = (unsigned char *)str;
527 while (! (cp = g_locale_to_utf8 ((char *)p, -1, &bytes_read,
528 &bytes_written, &err))
529 && err->code == G_CONVERT_ERROR_ILLEGAL_SEQUENCE)
531 memcpy (up, p, bytes_written);
532 up += bytes_written;
533 up += sprintf (up, "\\%03o", p[bytes_written]);
534 p += bytes_written + 1;
535 g_error_free (err);
536 err = NULL;
539 if (cp)
541 strcpy (up, cp);
542 g_free (cp);
544 if (err)
546 g_error_free (err);
547 err = NULL;
550 return utf8_str;
553 /* Check for special colors used in face spec for region face.
554 The colors are fetched from the Gtk+ theme.
555 Return true if color was found, false if not. */
557 bool
558 xg_check_special_colors (struct frame *f,
559 const char *color_name,
560 XColor *color)
562 bool success_p = 0;
563 bool get_bg = strcmp ("gtk_selection_bg_color", color_name) == 0;
564 bool get_fg = !get_bg && strcmp ("gtk_selection_fg_color", color_name) == 0;
566 if (! FRAME_GTK_WIDGET (f) || ! (get_bg || get_fg))
567 return success_p;
569 block_input ();
571 #ifdef HAVE_GTK3
572 GtkStyleContext *gsty
573 = gtk_widget_get_style_context (FRAME_GTK_OUTER_WIDGET (f));
574 GdkRGBA col;
575 char buf[sizeof "rgb://rrrr/gggg/bbbb"];
576 int state = GTK_STATE_FLAG_SELECTED|GTK_STATE_FLAG_FOCUSED;
577 if (get_fg)
578 gtk_style_context_get_color (gsty, state, &col);
579 else
580 /* FIXME: gtk_style_context_get_background_color is deprecated
581 in GTK+ 3.16. New versions of GTK+ don’t use the concept of
582 a single background color any more, so we shouldn’t query for
583 it. */
584 gtk_style_context_get_background_color (gsty, state, &col);
586 unsigned short
587 r = col.red * 65535,
588 g = col.green * 65535,
589 b = col.blue * 65535;
590 sprintf (buf, "rgb:%04x/%04x/%04x", r, g, b);
591 success_p = x_parse_color (f, buf, color) != 0;
592 #else
593 GtkStyle *gsty = gtk_widget_get_style (FRAME_GTK_WIDGET (f));
594 GdkColor *grgb = get_bg
595 ? &gsty->bg[GTK_STATE_SELECTED]
596 : &gsty->fg[GTK_STATE_SELECTED];
598 color->red = grgb->red;
599 color->green = grgb->green;
600 color->blue = grgb->blue;
601 color->pixel = grgb->pixel;
602 success_p = 1;
603 #endif
606 unblock_input ();
607 return success_p;
612 /***********************************************************************
613 Tooltips
614 ***********************************************************************/
615 /* Gtk+ calls this callback when the parent of our tooltip dummy changes.
616 We use that to pop down the tooltip. This happens if Gtk+ for some
617 reason wants to change or hide the tooltip. */
619 #ifdef USE_GTK_TOOLTIP
621 static void
622 hierarchy_ch_cb (GtkWidget *widget,
623 GtkWidget *previous_toplevel,
624 gpointer user_data)
626 struct frame *f = user_data;
627 struct x_output *x = f->output_data.x;
628 GtkWidget *top = gtk_widget_get_toplevel (x->ttip_lbl);
630 if (! top || ! GTK_IS_WINDOW (top))
631 gtk_widget_hide (previous_toplevel);
634 /* Callback called when Gtk+ thinks a tooltip should be displayed.
635 We use it to get the tooltip window and the tooltip widget so
636 we can manipulate the ourselves.
638 Return FALSE ensures that the tooltip is not shown. */
640 static gboolean
641 qttip_cb (GtkWidget *widget,
642 gint xpos,
643 gint ypos,
644 gboolean keyboard_mode,
645 GtkTooltip *tooltip,
646 gpointer user_data)
648 struct frame *f = user_data;
649 struct x_output *x = f->output_data.x;
650 if (x->ttip_widget == NULL)
652 GtkWidget *p;
653 GList *list, *iter;
655 g_object_set (G_OBJECT (widget), "has-tooltip", FALSE, NULL);
656 x->ttip_widget = tooltip;
657 g_object_ref (G_OBJECT (tooltip));
658 x->ttip_lbl = gtk_label_new ("");
659 g_object_ref (G_OBJECT (x->ttip_lbl));
660 gtk_tooltip_set_custom (tooltip, x->ttip_lbl);
661 x->ttip_window = GTK_WINDOW (gtk_widget_get_toplevel (x->ttip_lbl));
663 /* Change stupid Gtk+ default line wrapping. */
664 p = gtk_widget_get_parent (x->ttip_lbl);
665 list = gtk_container_get_children (GTK_CONTAINER (p));
666 for (iter = list; iter; iter = g_list_next (iter))
668 GtkWidget *w = GTK_WIDGET (iter->data);
669 if (GTK_IS_LABEL (w))
670 gtk_label_set_line_wrap (GTK_LABEL (w), FALSE);
672 g_list_free (list);
674 /* ATK needs an empty title for some reason. */
675 gtk_window_set_title (x->ttip_window, "");
676 /* Realize so we can safely get screen later on. */
677 gtk_widget_realize (GTK_WIDGET (x->ttip_window));
678 gtk_widget_realize (x->ttip_lbl);
680 g_signal_connect (x->ttip_lbl, "hierarchy-changed",
681 G_CALLBACK (hierarchy_ch_cb), f);
683 return FALSE;
686 #endif /* USE_GTK_TOOLTIP */
688 /* Prepare a tooltip to be shown, i.e. calculate WIDTH and HEIGHT.
689 Return true if a system tooltip is available. */
691 bool
692 xg_prepare_tooltip (struct frame *f,
693 Lisp_Object string,
694 int *width,
695 int *height)
697 #ifndef USE_GTK_TOOLTIP
698 return 0;
699 #else
700 struct x_output *x = f->output_data.x;
701 GtkWidget *widget;
702 GdkWindow *gwin;
703 GdkScreen *screen;
704 GtkSettings *settings;
705 gboolean tt_enabled = TRUE;
706 GtkRequisition req;
707 Lisp_Object encoded_string;
709 if (!x->ttip_lbl) return 0;
711 block_input ();
712 encoded_string = ENCODE_UTF_8 (string);
713 widget = GTK_WIDGET (x->ttip_lbl);
714 gwin = gtk_widget_get_window (GTK_WIDGET (x->ttip_window));
715 screen = gdk_window_get_screen (gwin);
716 settings = gtk_settings_get_for_screen (screen);
717 g_object_get (settings, "gtk-enable-tooltips", &tt_enabled, NULL);
718 if (tt_enabled)
720 g_object_set (settings, "gtk-enable-tooltips", FALSE, NULL);
721 /* Record that we disabled it so it can be enabled again. */
722 g_object_set_data (G_OBJECT (x->ttip_window), "restore-tt",
723 (gpointer)f);
726 /* Prevent Gtk+ from hiding tooltip on mouse move and such. */
727 g_object_set_data (G_OBJECT
728 (gtk_widget_get_display (GTK_WIDGET (x->ttip_window))),
729 "gdk-display-current-tooltip", NULL);
731 /* Put our dummy widget in so we can get callbacks for unrealize and
732 hierarchy-changed. */
733 gtk_tooltip_set_custom (x->ttip_widget, widget);
734 gtk_tooltip_set_text (x->ttip_widget, SSDATA (encoded_string));
735 gtk_widget_get_preferred_size (GTK_WIDGET (x->ttip_window), NULL, &req);
736 if (width) *width = req.width;
737 if (height) *height = req.height;
739 unblock_input ();
741 return 1;
742 #endif /* USE_GTK_TOOLTIP */
745 /* Show the tooltip at ROOT_X and ROOT_Y.
746 xg_prepare_tooltip must have been called before this function. */
748 void
749 xg_show_tooltip (struct frame *f, int root_x, int root_y)
751 #ifdef USE_GTK_TOOLTIP
752 struct x_output *x = f->output_data.x;
753 if (x->ttip_window)
755 block_input ();
756 gtk_window_move (x->ttip_window, root_x / xg_get_scale (f),
757 root_y / xg_get_scale (f));
758 gtk_widget_show_all (GTK_WIDGET (x->ttip_window));
759 unblock_input ();
761 #endif
764 /* Hide tooltip if shown. Do nothing if not shown.
765 Return true if tip was hidden, false if not (i.e. not using
766 system tooltips). */
768 bool
769 xg_hide_tooltip (struct frame *f)
771 bool ret = 0;
772 #ifdef USE_GTK_TOOLTIP
773 if (f->output_data.x->ttip_window)
775 GtkWindow *win = f->output_data.x->ttip_window;
776 block_input ();
777 gtk_widget_hide (GTK_WIDGET (win));
779 if (g_object_get_data (G_OBJECT (win), "restore-tt"))
781 GdkWindow *gwin = gtk_widget_get_window (GTK_WIDGET (win));
782 GdkScreen *screen = gdk_window_get_screen (gwin);
783 GtkSettings *settings = gtk_settings_get_for_screen (screen);
784 g_object_set (settings, "gtk-enable-tooltips", TRUE, NULL);
786 unblock_input ();
788 ret = 1;
790 #endif
791 return ret;
795 /***********************************************************************
796 General functions for creating widgets, resizing, events, e.t.c.
797 ***********************************************************************/
799 #if ! GTK_CHECK_VERSION (3, 22, 0)
800 static void
801 my_log_handler (const gchar *log_domain, GLogLevelFlags log_level,
802 const gchar *msg, gpointer user_data)
804 if (!strstr (msg, "visible children"))
805 fprintf (stderr, "XX %s-WARNING **: %s\n", log_domain, msg);
807 #endif
809 /* Make a geometry string and pass that to GTK. It seems this is the
810 only way to get geometry position right if the user explicitly
811 asked for a position when starting Emacs.
812 F is the frame we shall set geometry for. */
814 static void
815 xg_set_geometry (struct frame *f)
817 if (f->size_hint_flags & (USPosition | PPosition))
819 #if ! GTK_CHECK_VERSION (3, 22, 0)
820 if (x_gtk_use_window_move)
822 #endif
823 /* Handle negative positions without consulting
824 gtk_window_parse_geometry (Bug#25851). The position will
825 be off by scrollbar width + window manager decorations. */
826 if (f->size_hint_flags & XNegative)
827 f->left_pos = (x_display_pixel_width (FRAME_DISPLAY_INFO (f))
828 - FRAME_PIXEL_WIDTH (f) + f->left_pos);
830 if (f->size_hint_flags & YNegative)
831 f->top_pos = (x_display_pixel_height (FRAME_DISPLAY_INFO (f))
832 - FRAME_PIXEL_HEIGHT (f) + f->top_pos);
834 gtk_window_move (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)),
835 f->left_pos, f->top_pos);
837 /* Reset size hint flags. */
838 f->size_hint_flags &= ~ (XNegative | YNegative);
839 # if ! GTK_CHECK_VERSION (3, 22, 0)
841 else
843 int left = f->left_pos;
844 int xneg = f->size_hint_flags & XNegative;
845 int top = f->top_pos;
846 int yneg = f->size_hint_flags & YNegative;
847 char geom_str[sizeof "=x--" + 4 * INT_STRLEN_BOUND (int)];
848 guint id;
850 if (xneg)
851 left = -left;
852 if (yneg)
853 top = -top;
855 sprintf (geom_str, "=%dx%d%c%d%c%d",
856 FRAME_PIXEL_WIDTH (f),
857 FRAME_PIXEL_HEIGHT (f),
858 (xneg ? '-' : '+'), left,
859 (yneg ? '-' : '+'), top);
861 /* Silence warning about visible children. */
862 id = g_log_set_handler ("Gtk", G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
863 | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
865 if (!gtk_window_parse_geometry (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)),
866 geom_str))
867 fprintf (stderr, "Failed to parse: '%s'\n", geom_str);
869 g_log_remove_handler ("Gtk", id);
871 #endif
875 /* Function to handle resize of our frame. As we have a Gtk+ tool bar
876 and a Gtk+ menu bar, we get resize events for the edit part of the
877 frame only. We let Gtk+ deal with the Gtk+ parts.
878 F is the frame to resize.
879 PIXELWIDTH, PIXELHEIGHT is the new size in pixels. */
881 void
882 xg_frame_resized (struct frame *f, int pixelwidth, int pixelheight)
884 int width, height;
886 if (pixelwidth == -1 && pixelheight == -1)
888 if (FRAME_GTK_WIDGET (f) && gtk_widget_get_mapped (FRAME_GTK_WIDGET (f)))
889 gdk_window_get_geometry (gtk_widget_get_window (FRAME_GTK_WIDGET (f)),
890 0, 0, &pixelwidth, &pixelheight);
891 else
892 return;
895 width = FRAME_PIXEL_TO_TEXT_WIDTH (f, pixelwidth);
896 height = FRAME_PIXEL_TO_TEXT_HEIGHT (f, pixelheight);
898 frame_size_history_add
899 (f, Qxg_frame_resized, width, height, Qnil);
901 if (width != FRAME_TEXT_WIDTH (f)
902 || height != FRAME_TEXT_HEIGHT (f)
903 || pixelwidth != FRAME_PIXEL_WIDTH (f)
904 || pixelheight != FRAME_PIXEL_HEIGHT (f))
906 x_clear_under_internal_border (f);
907 change_frame_size (f, width, height, 0, 1, 0, 1);
908 SET_FRAME_GARBAGED (f);
909 cancel_mouse_face (f);
913 /* Resize the outer window of frame F after changing the height.
914 COLUMNS/ROWS is the size the edit area shall have after the resize. */
916 void
917 xg_frame_set_char_size (struct frame *f, int width, int height)
919 int pixelwidth = FRAME_TEXT_TO_PIXEL_WIDTH (f, width);
920 int pixelheight = FRAME_TEXT_TO_PIXEL_HEIGHT (f, height);
921 Lisp_Object fullscreen = get_frame_param (f, Qfullscreen);
922 gint gwidth, gheight;
923 int totalheight
924 = pixelheight + FRAME_TOOLBAR_HEIGHT (f) + FRAME_MENUBAR_HEIGHT (f);
925 int totalwidth = pixelwidth + FRAME_TOOLBAR_WIDTH (f);
927 if (FRAME_PIXEL_HEIGHT (f) == 0)
928 return;
930 gtk_window_get_size (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)),
931 &gwidth, &gheight);
933 /* Do this before resize, as we don't know yet if we will be resized. */
934 x_clear_under_internal_border (f);
936 totalheight /= xg_get_scale (f);
937 totalwidth /= xg_get_scale (f);
939 x_wm_set_size_hint (f, 0, 0);
941 /* Resize the top level widget so rows and columns remain constant.
943 When the frame is fullheight and we only want to change the width
944 or it is fullwidth and we only want to change the height we should
945 be able to preserve the fullscreen property. However, due to the
946 fact that we have to send a resize request anyway, the window
947 manager will abolish it. At least the respective size should
948 remain unchanged but giving the frame back its normal size will
949 be broken ... */
950 if (EQ (fullscreen, Qfullwidth) && width == FRAME_TEXT_WIDTH (f))
952 frame_size_history_add
953 (f, Qxg_frame_set_char_size_1, width, height,
954 list2 (make_number (gheight), make_number (totalheight)));
956 gtk_window_resize (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)),
957 gwidth, totalheight);
959 else if (EQ (fullscreen, Qfullheight) && height == FRAME_TEXT_HEIGHT (f))
961 frame_size_history_add
962 (f, Qxg_frame_set_char_size_2, width, height,
963 list2 (make_number (gwidth), make_number (totalwidth)));
965 gtk_window_resize (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)),
966 totalwidth, gheight);
968 else
970 frame_size_history_add
971 (f, Qxg_frame_set_char_size_3, width, height,
972 list2 (make_number (totalwidth), make_number (totalheight)));
974 gtk_window_resize (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)),
975 totalwidth, totalheight);
976 fullscreen = Qnil;
979 SET_FRAME_GARBAGED (f);
980 cancel_mouse_face (f);
982 /* We can not call change_frame_size for a mapped frame,
983 we can not set pixel width/height either. The window manager may
984 override our resize request, XMonad does this all the time.
985 The best we can do is try to sync, so lisp code sees the updated
986 size as fast as possible.
987 For unmapped windows, we can set rows/cols. When
988 the frame is mapped again we will (hopefully) get the correct size. */
989 if (FRAME_VISIBLE_P (f))
991 /* Must call this to flush out events */
992 (void)gtk_events_pending ();
993 gdk_flush ();
994 x_wait_for_event (f, ConfigureNotify);
996 if (!NILP (fullscreen))
997 /* Try to restore fullscreen state. */
999 store_frame_param (f, Qfullscreen, fullscreen);
1000 x_set_fullscreen (f, fullscreen, fullscreen);
1003 else
1004 adjust_frame_size (f, width, height, 5, 0, Qxg_frame_set_char_size);
1008 /* Handle height/width changes (i.e. add/remove/move menu/toolbar).
1009 The policy is to keep the number of editable lines. */
1011 #if 0
1012 static void
1013 xg_height_or_width_changed (struct frame *f)
1015 gtk_window_resize (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)),
1016 FRAME_TOTAL_PIXEL_WIDTH (f),
1017 FRAME_TOTAL_PIXEL_HEIGHT (f));
1018 f->output_data.x->hint_flags = 0;
1019 x_wm_set_size_hint (f, 0, 0);
1021 #endif
1023 /* Convert an X Window WSESC on display DPY to its corresponding GtkWidget.
1024 Must be done like this, because GtkWidget:s can have "hidden"
1025 X Window that aren't accessible.
1027 Return 0 if no widget match WDESC. */
1029 GtkWidget *
1030 xg_win_to_widget (Display *dpy, Window wdesc)
1032 gpointer gdkwin;
1033 GtkWidget *gwdesc = 0;
1035 block_input ();
1037 gdkwin = gdk_x11_window_lookup_for_display (gdk_x11_lookup_xdisplay (dpy),
1038 wdesc);
1039 if (gdkwin)
1041 GdkEvent event;
1042 event.any.window = gdkwin;
1043 event.any.type = GDK_NOTHING;
1044 gwdesc = gtk_get_event_widget (&event);
1047 unblock_input ();
1048 return gwdesc;
1051 /* Set the background of widget W to PIXEL. */
1053 static void
1054 xg_set_widget_bg (struct frame *f, GtkWidget *w, unsigned long pixel)
1056 #ifdef HAVE_GTK3
1057 GdkRGBA bg;
1058 XColor xbg;
1059 xbg.pixel = pixel;
1060 if (XQueryColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &xbg))
1062 bg.red = (double)xbg.red/65535.0;
1063 bg.green = (double)xbg.green/65535.0;
1064 bg.blue = (double)xbg.blue/65535.0;
1065 bg.alpha = 1.0;
1066 gtk_widget_override_background_color (w, GTK_STATE_FLAG_NORMAL, &bg);
1068 #else
1069 GdkColor bg;
1070 GdkColormap *map = gtk_widget_get_colormap (w);
1071 gdk_colormap_query_color (map, pixel, &bg);
1072 gtk_widget_modify_bg (FRAME_GTK_WIDGET (f), GTK_STATE_NORMAL, &bg);
1073 #endif
1076 /* Callback called when the gtk theme changes.
1077 We notify lisp code so it can fix faces used for region for example. */
1079 static void
1080 style_changed_cb (GObject *go,
1081 GParamSpec *spec,
1082 gpointer user_data)
1084 struct input_event event;
1085 GdkDisplay *gdpy = user_data;
1086 const char *display_name = gdk_display_get_name (gdpy);
1087 Display *dpy = GDK_DISPLAY_XDISPLAY (gdpy);
1089 EVENT_INIT (event);
1090 event.kind = CONFIG_CHANGED_EVENT;
1091 event.frame_or_window = build_string (display_name);
1092 /* Theme doesn't change often, so intern is called seldom. */
1093 event.arg = intern ("theme-name");
1094 kbd_buffer_store_event (&event);
1096 update_theme_scrollbar_width ();
1097 update_theme_scrollbar_height ();
1099 /* If scroll bar width changed, we need set the new size on all frames
1100 on this display. */
1101 if (dpy)
1103 Lisp_Object rest, frame;
1104 FOR_EACH_FRAME (rest, frame)
1106 struct frame *f = XFRAME (frame);
1107 if (FRAME_LIVE_P (f)
1108 && FRAME_X_P (f)
1109 && FRAME_X_DISPLAY (f) == dpy)
1111 x_set_scroll_bar_default_width (f);
1112 x_set_scroll_bar_default_height (f);
1113 xg_frame_set_char_size (f, FRAME_TEXT_WIDTH (f), FRAME_TEXT_HEIGHT (f));
1119 /* Called when a delete-event occurs on WIDGET. */
1121 static gboolean
1122 delete_cb (GtkWidget *widget,
1123 GdkEvent *event,
1124 gpointer user_data)
1126 return TRUE;
1129 /* Create and set up the GTK widgets for frame F.
1130 Return true if creation succeeded. */
1132 bool
1133 xg_create_frame_widgets (struct frame *f)
1135 GtkWidget *wtop;
1136 GtkWidget *wvbox, *whbox;
1137 GtkWidget *wfixed;
1138 #ifndef HAVE_GTK3
1139 GtkRcStyle *style;
1140 #endif
1141 char *title = 0;
1143 block_input ();
1145 if (FRAME_X_EMBEDDED_P (f))
1147 GdkDisplay *gdpy = gdk_x11_lookup_xdisplay (FRAME_X_DISPLAY (f));
1148 wtop = gtk_plug_new_for_display (gdpy, f->output_data.x->parent_desc);
1150 else
1151 wtop = gtk_window_new (GTK_WINDOW_TOPLEVEL);
1153 /* gtk_window_set_has_resize_grip is a Gtk+ 3.0 function but Ubuntu
1154 has backported it to Gtk+ 2.0 and they add the resize grip for
1155 Gtk+ 2.0 applications also. But it has a bug that makes Emacs loop
1156 forever, so disable the grip. */
1157 #if (! GTK_CHECK_VERSION (3, 0, 0) \
1158 && defined HAVE_GTK_WINDOW_SET_HAS_RESIZE_GRIP)
1159 gtk_window_set_has_resize_grip (GTK_WINDOW (wtop), FALSE);
1160 #endif
1162 xg_set_screen (wtop, f);
1164 wvbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 0);
1165 whbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0);
1166 gtk_box_set_homogeneous (GTK_BOX (wvbox), FALSE);
1167 gtk_box_set_homogeneous (GTK_BOX (whbox), FALSE);
1169 #ifdef HAVE_GTK3
1170 wfixed = emacs_fixed_new (f);
1171 #else
1172 wfixed = gtk_fixed_new ();
1173 #endif
1175 if (! wtop || ! wvbox || ! whbox || ! wfixed)
1177 if (wtop) gtk_widget_destroy (wtop);
1178 if (wvbox) gtk_widget_destroy (wvbox);
1179 if (whbox) gtk_widget_destroy (whbox);
1180 if (wfixed) gtk_widget_destroy (wfixed);
1182 unblock_input ();
1183 return 0;
1186 /* Use same names as the Xt port does. I.e. Emacs.pane.emacs by default */
1187 gtk_widget_set_name (wtop, EMACS_CLASS);
1188 gtk_widget_set_name (wvbox, "pane");
1189 gtk_widget_set_name (wfixed, SSDATA (Vx_resource_name));
1191 /* If this frame has a title or name, set it in the title bar. */
1192 if (! NILP (f->title))
1193 title = SSDATA (ENCODE_UTF_8 (f->title));
1194 else if (! NILP (f->name))
1195 title = SSDATA (ENCODE_UTF_8 (f->name));
1197 if (title)
1198 gtk_window_set_title (GTK_WINDOW (wtop), title);
1200 if (FRAME_UNDECORATED (f))
1202 gtk_window_set_decorated (GTK_WINDOW (wtop), FALSE);
1203 store_frame_param (f, Qundecorated, Qt);
1206 FRAME_GTK_OUTER_WIDGET (f) = wtop;
1207 FRAME_GTK_WIDGET (f) = wfixed;
1208 f->output_data.x->vbox_widget = wvbox;
1209 f->output_data.x->hbox_widget = whbox;
1211 gtk_widget_set_has_window (wfixed, TRUE);
1213 gtk_container_add (GTK_CONTAINER (wtop), wvbox);
1214 gtk_box_pack_start (GTK_BOX (wvbox), whbox, TRUE, TRUE, 0);
1215 gtk_box_pack_start (GTK_BOX (whbox), wfixed, TRUE, TRUE, 0);
1217 if (FRAME_EXTERNAL_TOOL_BAR (f))
1218 update_frame_tool_bar (f);
1220 /* We don't want this widget double buffered, because we draw on it
1221 with regular X drawing primitives, so from a GTK/GDK point of
1222 view, the widget is totally blank. When an expose comes, this
1223 will make the widget blank, and then Emacs redraws it. This flickers
1224 a lot, so we turn off double buffering.
1225 FIXME: gtk_widget_set_double_buffered is deprecated and might stop
1226 working in the future. We need to migrate away from combining
1227 X and GTK+ drawing to a pure GTK+ build. */
1228 gtk_widget_set_double_buffered (wfixed, FALSE);
1230 gtk_window_set_wmclass (GTK_WINDOW (wtop),
1231 SSDATA (Vx_resource_name),
1232 SSDATA (Vx_resource_class));
1234 /* Add callback to do nothing on WM_DELETE_WINDOW. The default in
1235 GTK is to destroy the widget. We want Emacs to do that instead. */
1236 g_signal_connect (G_OBJECT (wtop), "delete-event",
1237 G_CALLBACK (delete_cb), f);
1239 /* Convert our geometry parameters into a geometry string
1240 and specify it.
1241 GTK will itself handle calculating the real position this way. */
1242 xg_set_geometry (f);
1243 f->win_gravity
1244 = gtk_window_get_gravity (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
1246 gtk_widget_add_events (wfixed,
1247 GDK_POINTER_MOTION_MASK
1248 | GDK_EXPOSURE_MASK
1249 | GDK_BUTTON_PRESS_MASK
1250 | GDK_BUTTON_RELEASE_MASK
1251 | GDK_KEY_PRESS_MASK
1252 | GDK_ENTER_NOTIFY_MASK
1253 | GDK_LEAVE_NOTIFY_MASK
1254 | GDK_FOCUS_CHANGE_MASK
1255 | GDK_STRUCTURE_MASK
1256 | GDK_VISIBILITY_NOTIFY_MASK);
1258 /* Must realize the windows so the X window gets created. It is used
1259 by callers of this function. */
1260 gtk_widget_realize (wfixed);
1261 FRAME_X_WINDOW (f) = GTK_WIDGET_TO_X_WIN (wfixed);
1262 initial_set_up_x_back_buffer (f);
1264 /* Since GTK clears its window by filling with the background color,
1265 we must keep X and GTK background in sync. */
1266 xg_set_widget_bg (f, wfixed, FRAME_BACKGROUND_PIXEL (f));
1268 #ifndef HAVE_GTK3
1269 /* Also, do not let any background pixmap to be set, this looks very
1270 bad as Emacs overwrites the background pixmap with its own idea
1271 of background color. */
1272 style = gtk_widget_get_modifier_style (wfixed);
1274 /* Must use g_strdup because gtk_widget_modify_style does g_free. */
1275 style->bg_pixmap_name[GTK_STATE_NORMAL] = g_strdup ("<none>");
1276 gtk_widget_modify_style (wfixed, style);
1277 #else
1278 gtk_widget_set_can_focus (wfixed, TRUE);
1279 gtk_window_set_resizable (GTK_WINDOW (wtop), TRUE);
1280 #endif
1282 if (FRAME_OVERRIDE_REDIRECT (f))
1284 GdkWindow *gwin = gtk_widget_get_window (wtop);
1286 if (gwin)
1287 gdk_window_set_override_redirect (gwin, TRUE);
1290 #ifdef USE_GTK_TOOLTIP
1291 /* Steal a tool tip window we can move ourselves. */
1292 f->output_data.x->ttip_widget = 0;
1293 f->output_data.x->ttip_lbl = 0;
1294 f->output_data.x->ttip_window = 0;
1295 gtk_widget_set_tooltip_text (wtop, "Dummy text");
1296 g_signal_connect (wtop, "query-tooltip", G_CALLBACK (qttip_cb), f);
1297 #endif
1300 GdkScreen *screen = gtk_widget_get_screen (wtop);
1301 GtkSettings *gs = gtk_settings_get_for_screen (screen);
1302 /* Only connect this signal once per screen. */
1303 if (! g_signal_handler_find (G_OBJECT (gs),
1304 G_SIGNAL_MATCH_FUNC,
1305 0, 0, 0,
1306 (gpointer) G_CALLBACK (style_changed_cb),
1309 g_signal_connect (G_OBJECT (gs), "notify::gtk-theme-name",
1310 G_CALLBACK (style_changed_cb),
1311 gdk_screen_get_display (screen));
1315 unblock_input ();
1317 return 1;
1320 void
1321 xg_free_frame_widgets (struct frame *f)
1323 if (FRAME_GTK_OUTER_WIDGET (f))
1325 #ifdef USE_GTK_TOOLTIP
1326 struct x_output *x = f->output_data.x;
1327 #endif
1328 struct xg_frame_tb_info *tbinfo
1329 = g_object_get_data (G_OBJECT (FRAME_GTK_OUTER_WIDGET (f)),
1330 TB_INFO_KEY);
1331 if (tbinfo)
1332 xfree (tbinfo);
1334 /* x_free_frame_resources should have taken care of it */
1335 eassert (!FRAME_X_DOUBLE_BUFFERED_P (f));
1336 gtk_widget_destroy (FRAME_GTK_OUTER_WIDGET (f));
1337 FRAME_X_WINDOW (f) = 0; /* Set to avoid XDestroyWindow in xterm.c */
1338 FRAME_X_RAW_DRAWABLE (f) = 0;
1339 FRAME_GTK_OUTER_WIDGET (f) = 0;
1340 #ifdef USE_GTK_TOOLTIP
1341 if (x->ttip_lbl)
1342 gtk_widget_destroy (x->ttip_lbl);
1343 if (x->ttip_widget)
1344 g_object_unref (G_OBJECT (x->ttip_widget));
1345 #endif
1349 /* Set the normal size hints for the window manager, for frame F.
1350 FLAGS is the flags word to use--or 0 meaning preserve the flags
1351 that the window now has.
1352 If USER_POSITION, set the User Position
1353 flag (this is useful when FLAGS is 0). */
1355 void
1356 x_wm_set_size_hint (struct frame *f, long int flags, bool user_position)
1358 /* Must use GTK routines here, otherwise GTK resets the size hints
1359 to its own defaults. */
1360 GdkGeometry size_hints;
1361 gint hint_flags = 0;
1362 int base_width, base_height;
1363 int min_rows = 0, min_cols = 0;
1364 int win_gravity = f->win_gravity;
1365 Lisp_Object fs_state, frame;
1366 int scale = xg_get_scale (f);
1368 /* Don't set size hints during initialization; that apparently leads
1369 to a race condition. See the thread at
1370 http://lists.gnu.org/archive/html/emacs-devel/2008-10/msg00033.html */
1371 if (NILP (Vafter_init_time)
1372 || !FRAME_GTK_OUTER_WIDGET (f)
1373 || FRAME_PARENT_FRAME (f))
1374 return;
1376 XSETFRAME (frame, f);
1377 fs_state = Fframe_parameter (frame, Qfullscreen);
1378 if ((EQ (fs_state, Qmaximized) || EQ (fs_state, Qfullboth)) &&
1379 (x_wm_supports (f, FRAME_DISPLAY_INFO (f)->Xatom_net_wm_state) ||
1380 x_wm_supports (f, FRAME_DISPLAY_INFO (f)->Xatom_net_wm_state_fullscreen)))
1382 /* Don't set hints when maximized or fullscreen. Apparently KWin and
1383 Gtk3 don't get along and the frame shrinks (!).
1385 return;
1388 if (flags)
1390 memset (&size_hints, 0, sizeof (size_hints));
1391 f->output_data.x->size_hints = size_hints;
1392 f->output_data.x->hint_flags = hint_flags;
1394 else
1395 flags = f->size_hint_flags;
1397 size_hints = f->output_data.x->size_hints;
1398 hint_flags = f->output_data.x->hint_flags;
1400 hint_flags |= GDK_HINT_RESIZE_INC | GDK_HINT_MIN_SIZE;
1401 size_hints.width_inc = frame_resize_pixelwise ? 1 : FRAME_COLUMN_WIDTH (f);
1402 size_hints.height_inc = frame_resize_pixelwise ? 1 : FRAME_LINE_HEIGHT (f);
1404 hint_flags |= GDK_HINT_BASE_SIZE;
1405 /* Use one row/col here so base_height/width does not become zero.
1406 Gtk+ and/or Unity on Ubuntu 12.04 can't handle it.
1407 Obviously this makes the row/col value displayed off by 1. */
1408 base_width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 1) + FRAME_TOOLBAR_WIDTH (f);
1409 base_height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 1)
1410 + FRAME_MENUBAR_HEIGHT (f) + FRAME_TOOLBAR_HEIGHT (f);
1412 if (min_cols > 0) --min_cols; /* We used one col in base_width = ... 1); */
1413 if (min_rows > 0) --min_rows; /* We used one row in base_height = ... 1); */
1415 size_hints.base_width = base_width;
1416 size_hints.base_height = base_height;
1417 size_hints.min_width = base_width + min_cols * FRAME_COLUMN_WIDTH (f);
1418 size_hints.min_height = base_height + min_rows * FRAME_LINE_HEIGHT (f);
1420 /* These currently have a one to one mapping with the X values, but I
1421 don't think we should rely on that. */
1422 hint_flags |= GDK_HINT_WIN_GRAVITY;
1423 size_hints.win_gravity = 0;
1424 if (win_gravity == NorthWestGravity)
1425 size_hints.win_gravity = GDK_GRAVITY_NORTH_WEST;
1426 else if (win_gravity == NorthGravity)
1427 size_hints.win_gravity = GDK_GRAVITY_NORTH;
1428 else if (win_gravity == NorthEastGravity)
1429 size_hints.win_gravity = GDK_GRAVITY_NORTH_EAST;
1430 else if (win_gravity == WestGravity)
1431 size_hints.win_gravity = GDK_GRAVITY_WEST;
1432 else if (win_gravity == CenterGravity)
1433 size_hints.win_gravity = GDK_GRAVITY_CENTER;
1434 else if (win_gravity == EastGravity)
1435 size_hints.win_gravity = GDK_GRAVITY_EAST;
1436 else if (win_gravity == SouthWestGravity)
1437 size_hints.win_gravity = GDK_GRAVITY_SOUTH_WEST;
1438 else if (win_gravity == SouthGravity)
1439 size_hints.win_gravity = GDK_GRAVITY_SOUTH;
1440 else if (win_gravity == SouthEastGravity)
1441 size_hints.win_gravity = GDK_GRAVITY_SOUTH_EAST;
1442 else if (win_gravity == StaticGravity)
1443 size_hints.win_gravity = GDK_GRAVITY_STATIC;
1445 if (x_gtk_use_window_move)
1447 if (flags & PPosition) hint_flags |= GDK_HINT_POS;
1448 if (flags & USPosition) hint_flags |= GDK_HINT_USER_POS;
1449 if (flags & USSize) hint_flags |= GDK_HINT_USER_SIZE;
1452 if (user_position)
1454 hint_flags &= ~GDK_HINT_POS;
1455 hint_flags |= GDK_HINT_USER_POS;
1458 size_hints.base_width /= scale;
1459 size_hints.base_height /= scale;
1460 size_hints.width_inc /= scale;
1461 size_hints.height_inc /= scale;
1463 if (hint_flags != f->output_data.x->hint_flags
1464 || memcmp (&size_hints,
1465 &f->output_data.x->size_hints,
1466 sizeof (size_hints)) != 0)
1468 block_input ();
1469 gtk_window_set_geometry_hints (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)),
1470 NULL, &size_hints, hint_flags);
1471 f->output_data.x->size_hints = size_hints;
1472 f->output_data.x->hint_flags = hint_flags;
1473 unblock_input ();
1477 /* Change background color of a frame.
1478 Since GTK uses the background color to clear the window, we must
1479 keep the GTK and X colors in sync.
1480 F is the frame to change,
1481 BG is the pixel value to change to. */
1483 void
1484 xg_set_background_color (struct frame *f, unsigned long bg)
1486 if (FRAME_GTK_WIDGET (f))
1488 block_input ();
1489 xg_set_widget_bg (f, FRAME_GTK_WIDGET (f), FRAME_BACKGROUND_PIXEL (f));
1491 Lisp_Object bar;
1492 for (bar = FRAME_SCROLL_BARS (f);
1493 !NILP (bar);
1494 bar = XSCROLL_BAR (bar)->next)
1496 GtkWidget *scrollbar =
1497 xg_get_widget_from_map (XSCROLL_BAR (bar)->x_window);
1498 GtkWidget *webox = gtk_widget_get_parent (scrollbar);
1499 xg_set_widget_bg (f, webox, FRAME_BACKGROUND_PIXEL (f));
1502 unblock_input ();
1506 /* Change the frame's decoration (title bar + resize borders). This
1507 might not work with all window managers. */
1508 void
1509 xg_set_undecorated (struct frame *f, Lisp_Object undecorated)
1511 if (FRAME_GTK_WIDGET (f))
1513 block_input ();
1514 gtk_window_set_decorated (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)),
1515 NILP (undecorated) ? TRUE : FALSE);
1516 unblock_input ();
1521 /* Restack F1 below F2, above if ABOVE_FLAG is true. This might not
1522 work with all window managers. */
1523 void
1524 xg_frame_restack (struct frame *f1, struct frame *f2, bool above_flag)
1526 #if GTK_CHECK_VERSION (2, 18, 0)
1527 block_input ();
1528 if (FRAME_GTK_OUTER_WIDGET (f1) && FRAME_GTK_OUTER_WIDGET (f2))
1530 GdkWindow *gwin1 = gtk_widget_get_window (FRAME_GTK_OUTER_WIDGET (f1));
1531 GdkWindow *gwin2 = gtk_widget_get_window (FRAME_GTK_OUTER_WIDGET (f2));
1532 Lisp_Object frame1, frame2;
1534 XSETFRAME (frame1, f1);
1535 XSETFRAME (frame2, f2);
1537 gdk_window_restack (gwin1, gwin2, above_flag);
1538 x_sync (f1);
1540 unblock_input ();
1541 #endif
1545 /* Don't show frame in taskbar, don't ALT-TAB to it. */
1546 void
1547 xg_set_skip_taskbar (struct frame *f, Lisp_Object skip_taskbar)
1549 block_input ();
1550 if (FRAME_GTK_WIDGET (f))
1551 gdk_window_set_skip_taskbar_hint
1552 (gtk_widget_get_window (FRAME_GTK_OUTER_WIDGET (f)),
1553 NILP (skip_taskbar) ? FALSE : TRUE);
1554 unblock_input ();
1558 /* Don't give frame focus. */
1559 void
1560 xg_set_no_focus_on_map (struct frame *f, Lisp_Object no_focus_on_map)
1562 block_input ();
1563 if (FRAME_GTK_WIDGET (f))
1565 GtkWindow *gwin = GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f));
1566 gboolean g_no_focus_on_map = NILP (no_focus_on_map) ? TRUE : FALSE;
1568 gtk_window_set_focus_on_map (gwin, g_no_focus_on_map);
1570 unblock_input ();
1574 void
1575 xg_set_no_accept_focus (struct frame *f, Lisp_Object no_accept_focus)
1577 block_input ();
1578 if (FRAME_GTK_WIDGET (f))
1580 GtkWindow *gwin = GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f));
1581 gboolean g_no_accept_focus = NILP (no_accept_focus) ? TRUE : FALSE;
1583 gtk_window_set_accept_focus (gwin, g_no_accept_focus);
1585 unblock_input ();
1588 void
1589 xg_set_override_redirect (struct frame *f, Lisp_Object override_redirect)
1591 block_input ();
1593 if (FRAME_GTK_OUTER_WIDGET (f))
1595 GdkWindow *gwin = gtk_widget_get_window (FRAME_GTK_OUTER_WIDGET (f));
1597 gdk_window_set_override_redirect (gwin, NILP (override_redirect) ? FALSE : TRUE);
1600 unblock_input ();
1603 /* Set the frame icon to ICON_PIXMAP/MASK. This must be done with GTK
1604 functions so GTK does not overwrite the icon. */
1606 void
1607 xg_set_frame_icon (struct frame *f, Pixmap icon_pixmap, Pixmap icon_mask)
1609 GdkPixbuf *gp = xg_get_pixbuf_from_pix_and_mask (f,
1610 icon_pixmap,
1611 icon_mask);
1612 if (gp)
1613 gtk_window_set_icon (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)), gp);
1618 /***********************************************************************
1619 Dialog functions
1620 ***********************************************************************/
1621 /* Return the dialog title to use for a dialog of type KEY.
1622 This is the encoding used by lwlib. We use the same for GTK. */
1624 static const char *
1625 get_dialog_title (char key)
1627 const char *title = "";
1629 switch (key) {
1630 case 'E': case 'e':
1631 title = "Error";
1632 break;
1634 case 'I': case 'i':
1635 title = "Information";
1636 break;
1638 case 'L': case 'l':
1639 title = "Prompt";
1640 break;
1642 case 'P': case 'p':
1643 title = "Prompt";
1644 break;
1646 case 'Q': case 'q':
1647 title = "Question";
1648 break;
1651 return title;
1654 /* Callback for dialogs that get WM_DELETE_WINDOW. We pop down
1655 the dialog, but return TRUE so the event does not propagate further
1656 in GTK. This prevents GTK from destroying the dialog widget automatically
1657 and we can always destroy the widget manually, regardless of how
1658 it was popped down (button press or WM_DELETE_WINDOW).
1659 W is the dialog widget.
1660 EVENT is the GdkEvent that represents WM_DELETE_WINDOW (not used).
1661 user_data is NULL (not used).
1663 Returns TRUE to end propagation of event. */
1665 static gboolean
1666 dialog_delete_callback (GtkWidget *w, GdkEvent *event, gpointer user_data)
1668 gtk_widget_unmap (w);
1669 return TRUE;
1672 /* Create a popup dialog window. See also xg_create_widget below.
1673 WV is a widget_value describing the dialog.
1674 SELECT_CB is the callback to use when a button has been pressed.
1675 DEACTIVATE_CB is the callback to use when the dialog pops down.
1677 Returns the GTK dialog widget. */
1679 static GtkWidget *
1680 create_dialog (widget_value *wv,
1681 GCallback select_cb,
1682 GCallback deactivate_cb)
1684 const char *title = get_dialog_title (wv->name[0]);
1685 int total_buttons = wv->name[1] - '0';
1686 int right_buttons = wv->name[4] - '0';
1687 int left_buttons;
1688 int button_nr = 0;
1689 int button_spacing = 10;
1690 GtkWidget *wdialog = gtk_dialog_new ();
1691 GtkDialog *wd = GTK_DIALOG (wdialog);
1692 widget_value *item;
1693 GtkWidget *whbox_down;
1695 /* If the number of buttons is greater than 4, make two rows of buttons
1696 instead. This looks better. */
1697 bool make_two_rows = total_buttons > 4;
1699 #if GTK_CHECK_VERSION (3, 12, 0)
1700 GtkBuilder *gbld = gtk_builder_new ();
1701 GObject *go = gtk_buildable_get_internal_child (GTK_BUILDABLE (wd),
1702 gbld,
1703 "action_area");
1704 GtkBox *cur_box = GTK_BOX (go);
1705 g_object_unref (G_OBJECT (gbld));
1706 #else
1707 GtkBox *cur_box = GTK_BOX (gtk_dialog_get_action_area (wd));
1708 #endif
1710 if (right_buttons == 0) right_buttons = total_buttons/2;
1711 left_buttons = total_buttons - right_buttons;
1713 gtk_window_set_title (GTK_WINDOW (wdialog), title);
1714 gtk_widget_set_name (wdialog, "emacs-dialog");
1717 if (make_two_rows)
1719 GtkWidget *wvbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, button_spacing);
1720 GtkWidget *whbox_up = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0);
1721 gtk_box_set_homogeneous (GTK_BOX (wvbox), TRUE);
1722 gtk_box_set_homogeneous (GTK_BOX (whbox_up), FALSE);
1723 whbox_down = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0);
1724 gtk_box_set_homogeneous (GTK_BOX (whbox_down), FALSE);
1726 gtk_box_pack_start (cur_box, wvbox, FALSE, FALSE, 0);
1727 gtk_box_pack_start (GTK_BOX (wvbox), whbox_up, FALSE, FALSE, 0);
1728 gtk_box_pack_start (GTK_BOX (wvbox), whbox_down, FALSE, FALSE, 0);
1730 cur_box = GTK_BOX (whbox_up);
1733 g_signal_connect (G_OBJECT (wdialog), "delete-event",
1734 G_CALLBACK (dialog_delete_callback), 0);
1736 if (deactivate_cb)
1738 g_signal_connect (G_OBJECT (wdialog), "close", deactivate_cb, 0);
1739 g_signal_connect (G_OBJECT (wdialog), "response", deactivate_cb, 0);
1742 for (item = wv->contents; item; item = item->next)
1744 char *utf8_label = get_utf8_string (item->value);
1745 GtkWidget *w;
1746 GtkRequisition req;
1748 if (item->name && strcmp (item->name, "message") == 0)
1750 GtkBox *wvbox = GTK_BOX (gtk_dialog_get_content_area (wd));
1751 /* This is the text part of the dialog. */
1752 w = gtk_label_new (utf8_label);
1753 gtk_box_pack_start (wvbox, gtk_label_new (""), FALSE, FALSE, 0);
1754 gtk_box_pack_start (wvbox, w, TRUE, TRUE, 0);
1755 #if GTK_CHECK_VERSION (3, 14, 0)
1756 gtk_widget_set_halign (w, GTK_ALIGN_START);
1757 gtk_widget_set_valign (w, GTK_ALIGN_CENTER);
1758 #else
1759 gtk_misc_set_alignment (GTK_MISC (w), 0.1, 0.5);
1760 #endif
1761 /* Try to make dialog look better. Must realize first so
1762 the widget can calculate the size it needs. */
1763 gtk_widget_realize (w);
1764 gtk_widget_get_preferred_size (w, NULL, &req);
1765 gtk_box_set_spacing (wvbox, req.height);
1766 if (item->value && strlen (item->value) > 0)
1767 button_spacing = 2*req.width/strlen (item->value);
1768 if (button_spacing < 10) button_spacing = 10;
1770 else
1772 /* This is one button to add to the dialog. */
1773 w = gtk_button_new_with_label (utf8_label);
1774 if (! item->enabled)
1775 gtk_widget_set_sensitive (w, FALSE);
1776 if (select_cb)
1777 g_signal_connect (G_OBJECT (w), "clicked",
1778 select_cb, item->call_data);
1780 gtk_box_pack_start (cur_box, w, TRUE, TRUE, button_spacing);
1781 if (++button_nr == left_buttons)
1783 if (make_two_rows)
1784 cur_box = GTK_BOX (whbox_down);
1788 if (utf8_label)
1789 g_free (utf8_label);
1792 return wdialog;
1795 struct xg_dialog_data
1797 GMainLoop *loop;
1798 int response;
1799 GtkWidget *w;
1800 guint timerid;
1803 /* Function that is called when the file or font dialogs pop down.
1804 W is the dialog widget, RESPONSE is the response code.
1805 USER_DATA is what we passed in to g_signal_connect. */
1807 static void
1808 xg_dialog_response_cb (GtkDialog *w,
1809 gint response,
1810 gpointer user_data)
1812 struct xg_dialog_data *dd = user_data;
1813 dd->response = response;
1814 g_main_loop_quit (dd->loop);
1818 /* Destroy the dialog. This makes it pop down. */
1820 static void
1821 pop_down_dialog (void *arg)
1823 struct xg_dialog_data *dd = arg;
1825 block_input ();
1826 if (dd->w) gtk_widget_destroy (dd->w);
1827 if (dd->timerid != 0) g_source_remove (dd->timerid);
1829 g_main_loop_quit (dd->loop);
1830 g_main_loop_unref (dd->loop);
1832 unblock_input ();
1835 /* If there are any emacs timers pending, add a timeout to main loop in DATA.
1836 Pass DATA as gpointer so we can use this as a callback. */
1838 static gboolean
1839 xg_maybe_add_timer (gpointer data)
1841 struct xg_dialog_data *dd = data;
1842 struct timespec next_time = timer_check ();
1844 dd->timerid = 0;
1846 if (timespec_valid_p (next_time))
1848 time_t s = next_time.tv_sec;
1849 int per_ms = TIMESPEC_RESOLUTION / 1000;
1850 int ms = (next_time.tv_nsec + per_ms - 1) / per_ms;
1851 if (s <= ((guint) -1 - ms) / 1000)
1852 dd->timerid = g_timeout_add (s * 1000 + ms, xg_maybe_add_timer, dd);
1854 return FALSE;
1858 /* Pops up a modal dialog W and waits for response.
1859 We don't use gtk_dialog_run because we want to process emacs timers.
1860 The dialog W is not destroyed when this function returns. */
1862 static int
1863 xg_dialog_run (struct frame *f, GtkWidget *w)
1865 ptrdiff_t count = SPECPDL_INDEX ();
1866 struct xg_dialog_data dd;
1868 xg_set_screen (w, f);
1869 gtk_window_set_transient_for (GTK_WINDOW (w),
1870 GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
1871 gtk_window_set_destroy_with_parent (GTK_WINDOW (w), TRUE);
1872 gtk_window_set_modal (GTK_WINDOW (w), TRUE);
1874 dd.loop = g_main_loop_new (NULL, FALSE);
1875 dd.response = GTK_RESPONSE_CANCEL;
1876 dd.w = w;
1877 dd.timerid = 0;
1879 g_signal_connect (G_OBJECT (w),
1880 "response",
1881 G_CALLBACK (xg_dialog_response_cb),
1882 &dd);
1883 /* Don't destroy the widget if closed by the window manager close button. */
1884 g_signal_connect (G_OBJECT (w), "delete-event", G_CALLBACK (gtk_true), NULL);
1885 gtk_widget_show (w);
1887 record_unwind_protect_ptr (pop_down_dialog, &dd);
1889 (void) xg_maybe_add_timer (&dd);
1890 g_main_loop_run (dd.loop);
1892 dd.w = 0;
1893 unbind_to (count, Qnil);
1895 return dd.response;
1899 /***********************************************************************
1900 File dialog functions
1901 ***********************************************************************/
1902 /* Return true if the old file selection dialog is being used. */
1904 bool
1905 xg_uses_old_file_dialog (void)
1907 #ifdef HAVE_GTK_FILE_SELECTION_NEW
1908 return x_gtk_use_old_file_dialog;
1909 #else
1910 return 0;
1911 #endif
1915 typedef char * (*xg_get_file_func) (GtkWidget *);
1917 /* Return the selected file for file chooser dialog W.
1918 The returned string must be free:d. */
1920 static char *
1921 xg_get_file_name_from_chooser (GtkWidget *w)
1923 return gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (w));
1926 /* Callback called when the "Show hidden files" toggle is pressed.
1927 WIDGET is the toggle widget, DATA is the file chooser dialog. */
1929 static void
1930 xg_toggle_visibility_cb (GtkWidget *widget, gpointer data)
1932 GtkFileChooser *dialog = GTK_FILE_CHOOSER (data);
1933 gboolean visible;
1934 g_object_get (G_OBJECT (dialog), "show-hidden", &visible, NULL);
1935 g_object_set (G_OBJECT (dialog), "show-hidden", !visible, NULL);
1939 /* Callback called when a property changes in a file chooser.
1940 GOBJECT is the file chooser dialog, ARG1 describes the property.
1941 USER_DATA is the toggle widget in the file chooser dialog.
1942 We use this to update the "Show hidden files" toggle when the user
1943 changes that property by right clicking in the file list. */
1945 static void
1946 xg_toggle_notify_cb (GObject *gobject, GParamSpec *arg1, gpointer user_data)
1948 if (strcmp (arg1->name, "show-hidden") == 0)
1950 GtkWidget *wtoggle = GTK_WIDGET (user_data);
1951 gboolean visible, toggle_on;
1953 g_object_get (G_OBJECT (gobject), "show-hidden", &visible, NULL);
1954 toggle_on = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (wtoggle));
1956 if (!!visible != !!toggle_on)
1958 gpointer cb = (gpointer) G_CALLBACK (xg_toggle_visibility_cb);
1959 g_signal_handlers_block_by_func (G_OBJECT (wtoggle), cb, gobject);
1960 gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (wtoggle), visible);
1961 g_signal_handlers_unblock_by_func (G_OBJECT (wtoggle), cb, gobject);
1963 x_gtk_show_hidden_files = visible;
1967 /* Read a file name from the user using a file chooser dialog.
1968 F is the current frame.
1969 PROMPT is a prompt to show to the user. May not be NULL.
1970 DEFAULT_FILENAME is a default selection to be displayed. May be NULL.
1971 If MUSTMATCH_P, the returned file name must be an existing
1972 file. (Actually, this only has cosmetic effects, the user can
1973 still enter a non-existing file.) *FUNC is set to a function that
1974 can be used to retrieve the selected file name from the returned widget.
1976 Returns the created widget. */
1978 static GtkWidget *
1979 xg_get_file_with_chooser (struct frame *f,
1980 char *prompt,
1981 char *default_filename,
1982 bool mustmatch_p, bool only_dir_p,
1983 xg_get_file_func *func)
1985 char msgbuf[1024];
1987 GtkWidget *filewin, *wtoggle, *wbox;
1988 GtkWidget *wmessage UNINIT;
1989 GtkWindow *gwin = GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f));
1990 GtkFileChooserAction action = (mustmatch_p ?
1991 GTK_FILE_CHOOSER_ACTION_OPEN :
1992 GTK_FILE_CHOOSER_ACTION_SAVE);
1994 if (only_dir_p)
1995 action = GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER;
1997 filewin = gtk_file_chooser_dialog_new (prompt, gwin, action,
1998 XG_TEXT_CANCEL, GTK_RESPONSE_CANCEL,
1999 (mustmatch_p || only_dir_p ?
2000 XG_TEXT_OPEN : XG_TEXT_OK),
2001 GTK_RESPONSE_OK,
2002 NULL);
2003 gtk_file_chooser_set_local_only (GTK_FILE_CHOOSER (filewin), TRUE);
2005 wbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 0);
2006 gtk_box_set_homogeneous (GTK_BOX (wbox), FALSE);
2007 gtk_widget_show (wbox);
2008 wtoggle = gtk_check_button_new_with_label ("Show hidden files.");
2010 if (x_gtk_show_hidden_files)
2012 g_object_set (G_OBJECT (filewin), "show-hidden", TRUE, NULL);
2013 gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (wtoggle), TRUE);
2015 gtk_widget_show (wtoggle);
2016 g_signal_connect (G_OBJECT (wtoggle), "clicked",
2017 G_CALLBACK (xg_toggle_visibility_cb), filewin);
2018 g_signal_connect (G_OBJECT (filewin), "notify",
2019 G_CALLBACK (xg_toggle_notify_cb), wtoggle);
2021 if (x_gtk_file_dialog_help_text)
2023 char *z = msgbuf;
2024 /* Gtk+ 2.10 has the file name text entry box integrated in the dialog.
2025 Show the C-l help text only for versions < 2.10. */
2026 if (gtk_check_version (2, 10, 0) && action != GTK_FILE_CHOOSER_ACTION_SAVE)
2027 z = stpcpy (z, "\nType C-l to display a file name text entry box.\n");
2028 strcpy (z, "\nIf you don't like this file selector, use the "
2029 "corresponding\nkey binding or customize "
2030 "use-file-dialog to turn it off.");
2032 wmessage = gtk_label_new (msgbuf);
2033 gtk_widget_show (wmessage);
2036 gtk_box_pack_start (GTK_BOX (wbox), wtoggle, FALSE, FALSE, 0);
2037 if (x_gtk_file_dialog_help_text)
2038 gtk_box_pack_start (GTK_BOX (wbox), wmessage, FALSE, FALSE, 0);
2039 gtk_file_chooser_set_extra_widget (GTK_FILE_CHOOSER (filewin), wbox);
2041 if (default_filename)
2043 Lisp_Object file;
2044 char *utf8_filename;
2046 file = build_string (default_filename);
2048 /* File chooser does not understand ~/... in the file name. It must be
2049 an absolute name starting with /. */
2050 if (default_filename[0] != '/')
2051 file = Fexpand_file_name (file, Qnil);
2053 utf8_filename = SSDATA (ENCODE_UTF_8 (file));
2054 if (! NILP (Ffile_directory_p (file)))
2055 gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (filewin),
2056 utf8_filename);
2057 else
2059 gtk_file_chooser_set_filename (GTK_FILE_CHOOSER (filewin),
2060 utf8_filename);
2061 if (action == GTK_FILE_CHOOSER_ACTION_SAVE)
2063 char *cp = strrchr (utf8_filename, '/');
2064 if (cp) ++cp;
2065 else cp = utf8_filename;
2066 gtk_file_chooser_set_current_name (GTK_FILE_CHOOSER (filewin), cp);
2071 *func = xg_get_file_name_from_chooser;
2072 return filewin;
2075 #ifdef HAVE_GTK_FILE_SELECTION_NEW
2077 /* Return the selected file for file selector dialog W.
2078 The returned string must be free:d. */
2080 static char *
2081 xg_get_file_name_from_selector (GtkWidget *w)
2083 GtkFileSelection *filesel = GTK_FILE_SELECTION (w);
2084 return xstrdup (gtk_file_selection_get_filename (filesel));
2087 /* Create a file selection dialog.
2088 F is the current frame.
2089 PROMPT is a prompt to show to the user. May not be NULL.
2090 DEFAULT_FILENAME is a default selection to be displayed. May be NULL.
2091 If MUSTMATCH_P, the returned file name must be an existing
2092 file. *FUNC is set to a function that can be used to retrieve the
2093 selected file name from the returned widget.
2095 Returns the created widget. */
2097 static GtkWidget *
2098 xg_get_file_with_selection (struct frame *f,
2099 char *prompt,
2100 char *default_filename,
2101 bool mustmatch_p, bool only_dir_p,
2102 xg_get_file_func *func)
2104 GtkWidget *filewin;
2105 GtkFileSelection *filesel;
2107 filewin = gtk_file_selection_new (prompt);
2108 filesel = GTK_FILE_SELECTION (filewin);
2110 if (default_filename)
2111 gtk_file_selection_set_filename (filesel, default_filename);
2113 if (mustmatch_p)
2115 /* The selection_entry part of filesel is not documented. */
2116 gtk_widget_set_sensitive (filesel->selection_entry, FALSE);
2117 gtk_file_selection_hide_fileop_buttons (filesel);
2120 *func = xg_get_file_name_from_selector;
2122 return filewin;
2124 #endif /* HAVE_GTK_FILE_SELECTION_NEW */
2126 /* Read a file name from the user using a file dialog, either the old
2127 file selection dialog, or the new file chooser dialog. Which to use
2128 depends on what the GTK version used has, and what the value of
2129 gtk-use-old-file-dialog.
2130 F is the current frame.
2131 PROMPT is a prompt to show to the user. May not be NULL.
2132 DEFAULT_FILENAME is a default selection to be displayed. May be NULL.
2133 If MUSTMATCH_P, the returned file name must be an existing
2134 file.
2136 Returns a file name or NULL if no file was selected.
2137 The returned string must be freed by the caller. */
2139 char *
2140 xg_get_file_name (struct frame *f,
2141 char *prompt,
2142 char *default_filename,
2143 bool mustmatch_p,
2144 bool only_dir_p)
2146 GtkWidget *w = 0;
2147 char *fn = 0;
2148 int filesel_done = 0;
2149 xg_get_file_func func;
2151 #ifdef HAVE_GTK_FILE_SELECTION_NEW
2153 if (xg_uses_old_file_dialog ())
2154 w = xg_get_file_with_selection (f, prompt, default_filename,
2155 mustmatch_p, only_dir_p, &func);
2156 else
2157 w = xg_get_file_with_chooser (f, prompt, default_filename,
2158 mustmatch_p, only_dir_p, &func);
2160 #else /* not HAVE_GTK_FILE_SELECTION_NEW */
2161 w = xg_get_file_with_chooser (f, prompt, default_filename,
2162 mustmatch_p, only_dir_p, &func);
2163 #endif /* not HAVE_GTK_FILE_SELECTION_NEW */
2165 gtk_widget_set_name (w, "emacs-filedialog");
2167 filesel_done = xg_dialog_run (f, w);
2168 if (filesel_done == GTK_RESPONSE_OK)
2169 fn = (*func) (w);
2171 gtk_widget_destroy (w);
2172 return fn;
2175 /***********************************************************************
2176 GTK font chooser
2177 ***********************************************************************/
2179 #ifdef HAVE_FREETYPE
2181 #if USE_NEW_GTK_FONT_CHOOSER
2183 #define XG_WEIGHT_TO_SYMBOL(w) \
2184 (w <= PANGO_WEIGHT_THIN ? Qextra_light \
2185 : w <= PANGO_WEIGHT_ULTRALIGHT ? Qlight \
2186 : w <= PANGO_WEIGHT_LIGHT ? Qsemi_light \
2187 : w < PANGO_WEIGHT_MEDIUM ? Qnormal \
2188 : w <= PANGO_WEIGHT_SEMIBOLD ? Qsemi_bold \
2189 : w <= PANGO_WEIGHT_BOLD ? Qbold \
2190 : w <= PANGO_WEIGHT_HEAVY ? Qextra_bold \
2191 : Qultra_bold)
2193 #define XG_STYLE_TO_SYMBOL(s) \
2194 (s == PANGO_STYLE_OBLIQUE ? Qoblique \
2195 : s == PANGO_STYLE_ITALIC ? Qitalic \
2196 : Qnormal)
2198 #endif /* USE_NEW_GTK_FONT_CHOOSER */
2201 static char *x_last_font_name;
2203 /* Pop up a GTK font selector and return the name of the font the user
2204 selects, as a C string. The returned font name follows GTK's own
2205 format:
2207 `FAMILY [VALUE1 VALUE2] SIZE'
2209 This can be parsed using font_parse_fcname in font.c.
2210 DEFAULT_NAME, if non-zero, is the default font name. */
2212 Lisp_Object
2213 xg_get_font (struct frame *f, const char *default_name)
2215 GtkWidget *w;
2216 int done = 0;
2217 Lisp_Object font = Qnil;
2219 w = gtk_font_chooser_dialog_new
2220 ("Pick a font", GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
2222 if (default_name)
2224 /* Convert fontconfig names to Gtk names, i.e. remove - before
2225 number */
2226 char *p = strrchr (default_name, '-');
2227 if (p)
2229 char *ep = p+1;
2230 while (c_isdigit (*ep))
2231 ++ep;
2232 if (*ep == '\0') *p = ' ';
2235 else if (x_last_font_name)
2236 default_name = x_last_font_name;
2238 if (default_name)
2239 gtk_font_chooser_set_font (GTK_FONT_CHOOSER (w), default_name);
2241 gtk_widget_set_name (w, "emacs-fontdialog");
2242 done = xg_dialog_run (f, w);
2243 if (done == GTK_RESPONSE_OK)
2245 #if USE_NEW_GTK_FONT_CHOOSER
2246 /* Use the GTK3 font chooser. */
2247 PangoFontDescription *desc
2248 = gtk_font_chooser_get_font_desc (GTK_FONT_CHOOSER (w));
2250 if (desc)
2252 const char *name = pango_font_description_get_family (desc);
2253 gint size = pango_font_description_get_size (desc);
2254 PangoWeight weight = pango_font_description_get_weight (desc);
2255 PangoStyle style = pango_font_description_get_style (desc);
2257 #ifdef USE_CAIRO
2258 #define FONT_TYPE_WANTED (Qftcr)
2259 #else
2260 #define FONT_TYPE_WANTED (Qxft)
2261 #endif
2262 font = CALLN (Ffont_spec,
2263 QCname, build_string (name),
2264 QCsize, make_float (pango_units_to_double (size)),
2265 QCweight, XG_WEIGHT_TO_SYMBOL (weight),
2266 QCslant, XG_STYLE_TO_SYMBOL (style),
2267 QCtype,
2268 FONT_TYPE_WANTED);
2270 pango_font_description_free (desc);
2271 dupstring (&x_last_font_name, name);
2274 #else /* Use old font selector, which just returns the font name. */
2276 char *font_name
2277 = gtk_font_selection_dialog_get_font_name (GTK_FONT_CHOOSER (w));
2279 if (font_name)
2281 font = build_string (font_name);
2282 g_free (x_last_font_name);
2283 x_last_font_name = font_name;
2285 #endif /* USE_NEW_GTK_FONT_CHOOSER */
2288 gtk_widget_destroy (w);
2289 return font;
2291 #endif /* HAVE_FREETYPE */
2295 /***********************************************************************
2296 Menu functions.
2297 ***********************************************************************/
2299 /* The name of menu items that can be used for customization. Since GTK
2300 RC files are very crude and primitive, we have to set this on all
2301 menu item names so a user can easily customize menu items. */
2303 #define MENU_ITEM_NAME "emacs-menuitem"
2306 /* Linked list of all allocated struct xg_menu_cb_data. Used for marking
2307 during GC. The next member points to the items. */
2308 static xg_list_node xg_menu_cb_list;
2310 /* Linked list of all allocated struct xg_menu_item_cb_data. Used for marking
2311 during GC. The next member points to the items. */
2312 static xg_list_node xg_menu_item_cb_list;
2314 /* Allocate and initialize CL_DATA if NULL, otherwise increase ref_count.
2315 F is the frame CL_DATA will be initialized for.
2316 HIGHLIGHT_CB is the callback to call when entering/leaving menu items.
2318 The menu bar and all sub menus under the menu bar in a frame
2319 share the same structure, hence the reference count.
2321 Returns CL_DATA if CL_DATA is not NULL, or a pointer to a newly
2322 allocated xg_menu_cb_data if CL_DATA is NULL. */
2324 static xg_menu_cb_data *
2325 make_cl_data (xg_menu_cb_data *cl_data, struct frame *f, GCallback highlight_cb)
2327 if (! cl_data)
2329 cl_data = xmalloc (sizeof *cl_data);
2330 cl_data->f = f;
2331 cl_data->menu_bar_vector = f->menu_bar_vector;
2332 cl_data->menu_bar_items_used = f->menu_bar_items_used;
2333 cl_data->highlight_cb = highlight_cb;
2334 cl_data->ref_count = 0;
2336 xg_list_insert (&xg_menu_cb_list, &cl_data->ptrs);
2339 cl_data->ref_count++;
2341 return cl_data;
2344 /* Update CL_DATA with values from frame F and with HIGHLIGHT_CB.
2345 HIGHLIGHT_CB is the callback to call when entering/leaving menu items.
2347 When the menu bar is updated, menu items may have been added and/or
2348 removed, so menu_bar_vector and menu_bar_items_used change. We must
2349 then update CL_DATA since it is used to determine which menu
2350 item that is invoked in the menu.
2351 HIGHLIGHT_CB could change, there is no check that the same
2352 function is given when modifying a menu bar as was given when
2353 creating the menu bar. */
2355 static void
2356 update_cl_data (xg_menu_cb_data *cl_data,
2357 struct frame *f,
2358 GCallback highlight_cb)
2360 if (cl_data)
2362 cl_data->f = f;
2363 cl_data->menu_bar_vector = f->menu_bar_vector;
2364 cl_data->menu_bar_items_used = f->menu_bar_items_used;
2365 cl_data->highlight_cb = highlight_cb;
2369 /* Decrease reference count for CL_DATA.
2370 If reference count is zero, free CL_DATA. */
2372 static void
2373 unref_cl_data (xg_menu_cb_data *cl_data)
2375 if (cl_data && cl_data->ref_count > 0)
2377 cl_data->ref_count--;
2378 if (cl_data->ref_count == 0)
2380 xg_list_remove (&xg_menu_cb_list, &cl_data->ptrs);
2381 xfree (cl_data);
2386 /* Function that marks all lisp data during GC. */
2388 void
2389 xg_mark_data (void)
2391 xg_list_node *iter;
2392 Lisp_Object rest, frame;
2394 for (iter = xg_menu_cb_list.next; iter; iter = iter->next)
2395 mark_object (((xg_menu_cb_data *) iter)->menu_bar_vector);
2397 for (iter = xg_menu_item_cb_list.next; iter; iter = iter->next)
2399 xg_menu_item_cb_data *cb_data = (xg_menu_item_cb_data *) iter;
2401 if (! NILP (cb_data->help))
2402 mark_object (cb_data->help);
2405 FOR_EACH_FRAME (rest, frame)
2407 struct frame *f = XFRAME (frame);
2409 if (FRAME_X_P (f) && FRAME_GTK_OUTER_WIDGET (f))
2411 struct xg_frame_tb_info *tbinfo
2412 = g_object_get_data (G_OBJECT (FRAME_GTK_OUTER_WIDGET (f)),
2413 TB_INFO_KEY);
2414 if (tbinfo)
2416 mark_object (tbinfo->last_tool_bar);
2417 mark_object (tbinfo->style);
2423 /* Callback called when a menu item is destroyed. Used to free data.
2424 W is the widget that is being destroyed (not used).
2425 CLIENT_DATA points to the xg_menu_item_cb_data associated with the W. */
2427 static void
2428 menuitem_destroy_callback (GtkWidget *w, gpointer client_data)
2430 if (client_data)
2432 xg_menu_item_cb_data *data = client_data;
2433 xg_list_remove (&xg_menu_item_cb_list, &data->ptrs);
2434 xfree (data);
2438 /* Callback called when the pointer enters/leaves a menu item.
2439 W is the parent of the menu item.
2440 EVENT is either an enter event or leave event.
2441 CLIENT_DATA is not used.
2443 Returns FALSE to tell GTK to keep processing this event. */
2445 static gboolean
2446 menuitem_highlight_callback (GtkWidget *w,
2447 GdkEventCrossing *event,
2448 gpointer client_data)
2450 GdkEvent ev;
2451 GtkWidget *subwidget;
2452 xg_menu_item_cb_data *data;
2454 ev.crossing = *event;
2455 subwidget = gtk_get_event_widget (&ev);
2456 data = g_object_get_data (G_OBJECT (subwidget), XG_ITEM_DATA);
2457 if (data)
2459 if (! NILP (data->help) && data->cl_data->highlight_cb)
2461 gpointer call_data = event->type == GDK_LEAVE_NOTIFY ? 0 : data;
2462 GtkCallback func = (GtkCallback) data->cl_data->highlight_cb;
2463 (*func) (subwidget, call_data);
2467 return FALSE;
2470 /* Callback called when a menu is destroyed. Used to free data.
2471 W is the widget that is being destroyed (not used).
2472 CLIENT_DATA points to the xg_menu_cb_data associated with W. */
2474 static void
2475 menu_destroy_callback (GtkWidget *w, gpointer client_data)
2477 unref_cl_data (client_data);
2480 /* Make a GTK widget that contains both UTF8_LABEL and UTF8_KEY (both
2481 must be non-NULL) and can be inserted into a menu item.
2483 Returns the GtkHBox. */
2485 static GtkWidget *
2486 make_widget_for_menu_item (const char *utf8_label, const char *utf8_key)
2488 GtkWidget *wlbl;
2489 GtkWidget *wkey;
2490 GtkWidget *wbox;
2492 wbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0);
2493 gtk_box_set_homogeneous (GTK_BOX (wbox), FALSE);
2494 wlbl = gtk_label_new (utf8_label);
2495 wkey = gtk_label_new (utf8_key);
2497 #if GTK_CHECK_VERSION (3, 14, 0)
2498 gtk_widget_set_halign (wlbl, GTK_ALIGN_START);
2499 gtk_widget_set_valign (wlbl, GTK_ALIGN_CENTER);
2500 gtk_widget_set_halign (wkey, GTK_ALIGN_START);
2501 gtk_widget_set_valign (wkey, GTK_ALIGN_CENTER);
2502 #else
2503 gtk_misc_set_alignment (GTK_MISC (wlbl), 0.0, 0.5);
2504 gtk_misc_set_alignment (GTK_MISC (wkey), 0.0, 0.5);
2505 #endif
2506 gtk_box_pack_start (GTK_BOX (wbox), wlbl, TRUE, TRUE, 0);
2507 gtk_box_pack_start (GTK_BOX (wbox), wkey, FALSE, FALSE, 0);
2509 gtk_widget_set_name (wlbl, MENU_ITEM_NAME);
2510 gtk_widget_set_name (wkey, MENU_ITEM_NAME);
2511 gtk_widget_set_name (wbox, MENU_ITEM_NAME);
2513 return wbox;
2516 /* Make and return a menu item widget with the key to the right.
2517 UTF8_LABEL is the text for the menu item (GTK uses UTF8 internally).
2518 UTF8_KEY is the text representing the key binding.
2519 ITEM is the widget_value describing the menu item.
2521 GROUP is an in/out parameter. If the menu item to be created is not
2522 part of any radio menu group, *GROUP contains NULL on entry and exit.
2523 If the menu item to be created is part of a radio menu group, on entry
2524 *GROUP contains the group to use, or NULL if this is the first item
2525 in the group. On exit, *GROUP contains the radio item group.
2527 Unfortunately, keys don't line up as nicely as in Motif,
2528 but the macOS version doesn't either, so I guess that is OK. */
2530 static GtkWidget *
2531 make_menu_item (const char *utf8_label,
2532 const char *utf8_key,
2533 widget_value *item,
2534 GSList **group)
2536 GtkWidget *w;
2537 GtkWidget *wtoadd = 0;
2539 /* It has been observed that some menu items have a NULL name field.
2540 This will lead to this function being called with a NULL utf8_label.
2541 GTK crashes on that so we set a blank label. Why there is a NULL
2542 name remains to be investigated. */
2543 if (! utf8_label) utf8_label = " ";
2545 if (utf8_key)
2546 wtoadd = make_widget_for_menu_item (utf8_label, utf8_key);
2548 if (item->button_type == BUTTON_TYPE_TOGGLE)
2550 *group = NULL;
2551 if (utf8_key) w = gtk_check_menu_item_new ();
2552 else w = gtk_check_menu_item_new_with_label (utf8_label);
2553 gtk_check_menu_item_set_active (GTK_CHECK_MENU_ITEM (w), item->selected);
2555 else if (item->button_type == BUTTON_TYPE_RADIO)
2557 if (utf8_key) w = gtk_radio_menu_item_new (*group);
2558 else w = gtk_radio_menu_item_new_with_label (*group, utf8_label);
2559 *group = gtk_radio_menu_item_get_group (GTK_RADIO_MENU_ITEM (w));
2560 if (item->selected)
2561 gtk_check_menu_item_set_active (GTK_CHECK_MENU_ITEM (w), TRUE);
2563 else
2565 *group = NULL;
2566 if (utf8_key) w = gtk_menu_item_new ();
2567 else w = gtk_menu_item_new_with_label (utf8_label);
2570 if (wtoadd) gtk_container_add (GTK_CONTAINER (w), wtoadd);
2571 if (! item->enabled) gtk_widget_set_sensitive (w, FALSE);
2573 return w;
2576 /* Create a menu item widget, and connect the callbacks.
2577 ITEM describes the menu item.
2578 F is the frame the created menu belongs to.
2579 SELECT_CB is the callback to use when a menu item is selected.
2580 HIGHLIGHT_CB is the callback to call when entering/leaving menu items.
2581 CL_DATA points to the callback data to be used for this menu.
2582 GROUP is an in/out parameter. If the menu item to be created is not
2583 part of any radio menu group, *GROUP contains NULL on entry and exit.
2584 If the menu item to be created is part of a radio menu group, on entry
2585 *GROUP contains the group to use, or NULL if this is the first item
2586 in the group. On exit, *GROUP contains the radio item group.
2588 Returns the created GtkWidget. */
2590 static GtkWidget *
2591 xg_create_one_menuitem (widget_value *item,
2592 struct frame *f,
2593 GCallback select_cb,
2594 GCallback highlight_cb,
2595 xg_menu_cb_data *cl_data,
2596 GSList **group)
2598 char *utf8_label;
2599 char *utf8_key;
2600 GtkWidget *w;
2601 xg_menu_item_cb_data *cb_data;
2603 utf8_label = get_utf8_string (item->name);
2604 utf8_key = get_utf8_string (item->key);
2606 w = make_menu_item (utf8_label, utf8_key, item, group);
2608 if (utf8_label) g_free (utf8_label);
2609 if (utf8_key) g_free (utf8_key);
2611 cb_data = xmalloc (sizeof *cb_data);
2613 xg_list_insert (&xg_menu_item_cb_list, &cb_data->ptrs);
2615 cb_data->select_id = 0;
2616 cb_data->help = item->help;
2617 cb_data->cl_data = cl_data;
2618 cb_data->call_data = item->call_data;
2620 g_signal_connect (G_OBJECT (w),
2621 "destroy",
2622 G_CALLBACK (menuitem_destroy_callback),
2623 cb_data);
2625 /* Put cb_data in widget, so we can get at it when modifying menubar */
2626 g_object_set_data (G_OBJECT (w), XG_ITEM_DATA, cb_data);
2628 /* final item, not a submenu */
2629 if (item->call_data && ! item->contents)
2631 if (select_cb)
2632 cb_data->select_id
2633 = g_signal_connect (G_OBJECT (w), "activate", select_cb, cb_data);
2636 return w;
2639 /* Create a full menu tree specified by DATA.
2640 F is the frame the created menu belongs to.
2641 SELECT_CB is the callback to use when a menu item is selected.
2642 DEACTIVATE_CB is the callback to use when a sub menu is not shown anymore.
2643 HIGHLIGHT_CB is the callback to call when entering/leaving menu items.
2644 If POP_UP_P, create a popup menu.
2645 If MENU_BAR_P, create a menu bar.
2646 TOPMENU is the topmost GtkWidget that others shall be placed under.
2647 It may be NULL, in that case we create the appropriate widget
2648 (menu bar or menu item depending on POP_UP_P and MENU_BAR_P)
2649 CL_DATA is the callback data we shall use for this menu, or NULL
2650 if we haven't set the first callback yet.
2651 NAME is the name to give to the top level menu if this function
2652 creates it. May be NULL to not set any name.
2654 Returns the top level GtkWidget. This is TOPLEVEL if TOPLEVEL is
2655 not NULL.
2657 This function calls itself to create submenus. */
2659 static GtkWidget *
2660 create_menus (widget_value *data,
2661 struct frame *f,
2662 GCallback select_cb,
2663 GCallback deactivate_cb,
2664 GCallback highlight_cb,
2665 bool pop_up_p,
2666 bool menu_bar_p,
2667 GtkWidget *topmenu,
2668 xg_menu_cb_data *cl_data,
2669 const char *name)
2671 widget_value *item;
2672 GtkWidget *wmenu = topmenu;
2673 GSList *group = NULL;
2675 if (! topmenu)
2677 if (! menu_bar_p)
2679 wmenu = gtk_menu_new ();
2680 xg_set_screen (wmenu, f);
2681 /* Connect this to the menu instead of items so we get enter/leave for
2682 disabled items also. TODO: Still does not get enter/leave for
2683 disabled items in detached menus. */
2684 g_signal_connect (G_OBJECT (wmenu),
2685 "enter-notify-event",
2686 G_CALLBACK (menuitem_highlight_callback),
2687 NULL);
2688 g_signal_connect (G_OBJECT (wmenu),
2689 "leave-notify-event",
2690 G_CALLBACK (menuitem_highlight_callback),
2691 NULL);
2693 else
2695 wmenu = gtk_menu_bar_new ();
2696 /* Set width of menu bar to a small value so it doesn't enlarge
2697 a small initial frame size. The width will be set to the
2698 width of the frame later on when it is added to a container.
2699 height -1: Natural height. */
2700 gtk_widget_set_size_request (wmenu, 1, -1);
2703 /* Put cl_data on the top menu for easier access. */
2704 cl_data = make_cl_data (cl_data, f, highlight_cb);
2705 g_object_set_data (G_OBJECT (wmenu), XG_FRAME_DATA, (gpointer)cl_data);
2706 g_signal_connect (G_OBJECT (wmenu), "destroy",
2707 G_CALLBACK (menu_destroy_callback), cl_data);
2709 if (name)
2710 gtk_widget_set_name (wmenu, name);
2712 if (deactivate_cb)
2713 g_signal_connect (G_OBJECT (wmenu),
2714 "selection-done", deactivate_cb, 0);
2717 for (item = data; item; item = item->next)
2719 GtkWidget *w;
2721 if (pop_up_p && !item->contents && !item->call_data
2722 && !menu_separator_name_p (item->name))
2724 char *utf8_label;
2725 /* A title for a popup. We do the same as GTK does when
2726 creating titles, but it does not look good. */
2727 group = NULL;
2728 utf8_label = get_utf8_string (item->name);
2730 w = gtk_menu_item_new_with_label (utf8_label);
2731 gtk_widget_set_sensitive (w, FALSE);
2732 if (utf8_label) g_free (utf8_label);
2734 else if (menu_separator_name_p (item->name))
2736 group = NULL;
2737 /* GTK only have one separator type. */
2738 w = gtk_separator_menu_item_new ();
2740 else
2742 w = xg_create_one_menuitem (item,
2744 item->contents ? 0 : select_cb,
2745 highlight_cb,
2746 cl_data,
2747 &group);
2749 /* Create a possibly empty submenu for menu bar items, since some
2750 themes don't highlight items correctly without it. */
2751 if (item->contents || menu_bar_p)
2753 GtkWidget *submenu = create_menus (item->contents,
2755 select_cb,
2756 deactivate_cb,
2757 highlight_cb,
2761 cl_data,
2763 gtk_menu_item_set_submenu (GTK_MENU_ITEM (w), submenu);
2767 gtk_menu_shell_append (GTK_MENU_SHELL (wmenu), w);
2768 gtk_widget_set_name (w, MENU_ITEM_NAME);
2771 return wmenu;
2774 /* Create a menubar, popup menu or dialog, depending on the TYPE argument.
2775 TYPE can be "menubar", "popup" for popup menu, or "dialog" for a dialog
2776 with some text and buttons.
2777 F is the frame the created item belongs to.
2778 NAME is the name to use for the top widget.
2779 VAL is a widget_value structure describing items to be created.
2780 SELECT_CB is the callback to use when a menu item is selected or
2781 a dialog button is pressed.
2782 DEACTIVATE_CB is the callback to use when an item is deactivated.
2783 For a menu, when a sub menu is not shown anymore, for a dialog it is
2784 called when the dialog is popped down.
2785 HIGHLIGHT_CB is the callback to call when entering/leaving menu items.
2787 Returns the widget created. */
2789 GtkWidget *
2790 xg_create_widget (const char *type, const char *name, struct frame *f,
2791 widget_value *val, GCallback select_cb,
2792 GCallback deactivate_cb, GCallback highlight_cb)
2794 GtkWidget *w = 0;
2795 bool menu_bar_p = strcmp (type, "menubar") == 0;
2796 bool pop_up_p = strcmp (type, "popup") == 0;
2798 if (strcmp (type, "dialog") == 0)
2800 w = create_dialog (val, select_cb, deactivate_cb);
2801 xg_set_screen (w, f);
2802 gtk_window_set_transient_for (GTK_WINDOW (w),
2803 GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
2804 gtk_window_set_destroy_with_parent (GTK_WINDOW (w), TRUE);
2805 gtk_widget_set_name (w, "emacs-dialog");
2806 gtk_window_set_modal (GTK_WINDOW (w), TRUE);
2808 else if (menu_bar_p || pop_up_p)
2810 w = create_menus (val->contents,
2812 select_cb,
2813 deactivate_cb,
2814 highlight_cb,
2815 pop_up_p,
2816 menu_bar_p,
2819 name);
2821 /* Set the cursor to an arrow for popup menus when they are mapped.
2822 This is done by default for menu bar menus. */
2823 if (pop_up_p)
2825 /* Must realize so the GdkWindow inside the widget is created. */
2826 gtk_widget_realize (w);
2827 xg_set_cursor (w, FRAME_DISPLAY_INFO (f)->xg_cursor);
2830 else
2832 fprintf (stderr, "bad type in xg_create_widget: %s, doing nothing\n",
2833 type);
2836 return w;
2839 /* Return the label for menu item WITEM. */
2841 static const char *
2842 xg_get_menu_item_label (GtkMenuItem *witem)
2844 GtkLabel *wlabel = GTK_LABEL (XG_BIN_CHILD (witem));
2845 return gtk_label_get_label (wlabel);
2848 /* Return true if the menu item WITEM has the text LABEL. */
2850 static bool
2851 xg_item_label_same_p (GtkMenuItem *witem, const char *label)
2853 bool is_same = 0;
2854 char *utf8_label = get_utf8_string (label);
2855 const char *old_label = witem ? xg_get_menu_item_label (witem) : 0;
2857 if (! old_label && ! utf8_label)
2858 is_same = 1;
2859 else if (old_label && utf8_label)
2860 is_same = strcmp (utf8_label, old_label) == 0;
2862 if (utf8_label) g_free (utf8_label);
2864 return is_same;
2867 /* Destroy widgets in LIST. */
2869 static void
2870 xg_destroy_widgets (GList *list)
2872 GList *iter;
2874 for (iter = list; iter; iter = g_list_next (iter))
2876 GtkWidget *w = GTK_WIDGET (iter->data);
2878 /* Destroying the widget will remove it from the container it is in. */
2879 gtk_widget_destroy (w);
2883 /* Update the top level names in MENUBAR (i.e. not submenus).
2884 F is the frame the menu bar belongs to.
2885 *LIST is a list with the current menu bar names (menu item widgets).
2886 ITER is the item within *LIST that shall be updated.
2887 POS is the numerical position, starting at 0, of ITER in *LIST.
2888 VAL describes what the menu bar shall look like after the update.
2889 SELECT_CB is the callback to use when a menu item is selected.
2890 HIGHLIGHT_CB is the callback to call when entering/leaving menu items.
2891 CL_DATA points to the callback data to be used for this menu bar.
2893 This function calls itself to walk through the menu bar names. */
2895 static void
2896 xg_update_menubar (GtkWidget *menubar,
2897 struct frame *f,
2898 GList **list,
2899 GList *iter,
2900 int pos,
2901 widget_value *val,
2902 GCallback select_cb,
2903 GCallback deactivate_cb,
2904 GCallback highlight_cb,
2905 xg_menu_cb_data *cl_data)
2907 if (! iter && ! val)
2908 return;
2909 else if (iter && ! val)
2911 /* Item(s) have been removed. Remove all remaining items. */
2912 xg_destroy_widgets (iter);
2914 /* Add a blank entry so the menubar doesn't collapse to nothing. */
2915 gtk_menu_shell_insert (GTK_MENU_SHELL (menubar),
2916 gtk_menu_item_new_with_label (""),
2918 /* All updated. */
2919 val = 0;
2920 iter = 0;
2922 else if (! iter && val)
2924 /* Item(s) added. Add all new items in one call. */
2925 create_menus (val, f, select_cb, deactivate_cb, highlight_cb,
2926 0, 1, menubar, cl_data, 0);
2928 /* All updated. */
2929 val = 0;
2930 iter = 0;
2932 /* Below this neither iter or val is NULL */
2933 else if (xg_item_label_same_p (GTK_MENU_ITEM (iter->data), val->name))
2935 /* This item is still the same, check next item. */
2936 val = val->next;
2937 iter = g_list_next (iter);
2938 ++pos;
2940 else /* This item is changed. */
2942 GtkMenuItem *witem = GTK_MENU_ITEM (iter->data);
2943 GtkMenuItem *witem2 = 0;
2944 bool val_in_menubar = 0;
2945 bool iter_in_new_menubar = 0;
2946 GList *iter2;
2947 widget_value *cur;
2949 /* See if the changed entry (val) is present later in the menu bar */
2950 for (iter2 = iter;
2951 iter2 && ! val_in_menubar;
2952 iter2 = g_list_next (iter2))
2954 witem2 = GTK_MENU_ITEM (iter2->data);
2955 val_in_menubar = xg_item_label_same_p (witem2, val->name);
2958 /* See if the current entry (iter) is present later in the
2959 specification for the new menu bar. */
2960 for (cur = val; cur && ! iter_in_new_menubar; cur = cur->next)
2961 iter_in_new_menubar = xg_item_label_same_p (witem, cur->name);
2963 if (val_in_menubar && ! iter_in_new_menubar)
2965 int nr = pos;
2967 /* This corresponds to:
2968 Current: A B C
2969 New: A C
2970 Remove B. */
2972 g_object_ref (G_OBJECT (witem));
2973 gtk_container_remove (GTK_CONTAINER (menubar), GTK_WIDGET (witem));
2974 gtk_widget_destroy (GTK_WIDGET (witem));
2976 /* Must get new list since the old changed. */
2977 g_list_free (*list);
2978 *list = iter = gtk_container_get_children (GTK_CONTAINER (menubar));
2979 while (nr-- > 0) iter = g_list_next (iter);
2981 else if (! val_in_menubar && ! iter_in_new_menubar)
2983 /* This corresponds to:
2984 Current: A B C
2985 New: A X C
2986 Rename B to X. This might seem to be a strange thing to do,
2987 since if there is a menu under B it will be totally wrong for X.
2988 But consider editing a C file. Then there is a C-mode menu
2989 (corresponds to B above).
2990 If then doing C-x C-f the minibuf menu (X above) replaces the
2991 C-mode menu. When returning from the minibuffer, we get
2992 back the C-mode menu. Thus we do:
2993 Rename B to X (C-mode to minibuf menu)
2994 Rename X to B (minibuf to C-mode menu).
2995 If the X menu hasn't been invoked, the menu under B
2996 is up to date when leaving the minibuffer. */
2997 GtkLabel *wlabel = GTK_LABEL (XG_BIN_CHILD (witem));
2998 char *utf8_label = get_utf8_string (val->name);
3000 /* GTK menu items don't notice when their labels have been
3001 changed from underneath them, so we have to explicitly
3002 use g_object_notify to tell listeners (e.g., a GMenuModel
3003 bridge that might be loaded) that the item's label has
3004 changed. */
3005 gtk_label_set_text (wlabel, utf8_label);
3006 #if GTK_CHECK_VERSION (2, 16, 0)
3007 g_object_notify (G_OBJECT (witem), "label");
3008 #endif
3009 if (utf8_label) g_free (utf8_label);
3010 iter = g_list_next (iter);
3011 val = val->next;
3012 ++pos;
3014 else if (! val_in_menubar && iter_in_new_menubar)
3016 /* This corresponds to:
3017 Current: A B C
3018 New: A X B C
3019 Insert X. */
3021 int nr = pos;
3022 GSList *group = 0;
3023 GtkWidget *w = xg_create_one_menuitem (val,
3025 select_cb,
3026 highlight_cb,
3027 cl_data,
3028 &group);
3030 /* Create a possibly empty submenu for menu bar items, since some
3031 themes don't highlight items correctly without it. */
3032 GtkWidget *submenu = create_menus (NULL, f,
3033 select_cb, deactivate_cb,
3034 highlight_cb,
3035 0, 0, 0, cl_data, 0);
3037 gtk_widget_set_name (w, MENU_ITEM_NAME);
3038 gtk_menu_shell_insert (GTK_MENU_SHELL (menubar), w, pos);
3039 gtk_menu_item_set_submenu (GTK_MENU_ITEM (w), submenu);
3041 g_list_free (*list);
3042 *list = iter = gtk_container_get_children (GTK_CONTAINER (menubar));
3043 while (nr-- > 0) iter = g_list_next (iter);
3044 iter = g_list_next (iter);
3045 val = val->next;
3046 ++pos;
3048 else /* if (val_in_menubar && iter_in_new_menubar) */
3050 int nr = pos;
3051 /* This corresponds to:
3052 Current: A B C
3053 New: A C B
3054 Move C before B */
3056 g_object_ref (G_OBJECT (witem2));
3057 gtk_container_remove (GTK_CONTAINER (menubar), GTK_WIDGET (witem2));
3058 gtk_menu_shell_insert (GTK_MENU_SHELL (menubar),
3059 GTK_WIDGET (witem2), pos);
3060 g_object_unref (G_OBJECT (witem2));
3062 g_list_free (*list);
3063 *list = iter = gtk_container_get_children (GTK_CONTAINER (menubar));
3064 while (nr-- > 0) iter = g_list_next (iter);
3065 if (iter) iter = g_list_next (iter);
3066 val = val->next;
3067 ++pos;
3071 /* Update the rest of the menu bar. */
3072 xg_update_menubar (menubar, f, list, iter, pos, val,
3073 select_cb, deactivate_cb, highlight_cb, cl_data);
3076 /* Update the menu item W so it corresponds to VAL.
3077 SELECT_CB is the callback to use when a menu item is selected.
3078 HIGHLIGHT_CB is the callback to call when entering/leaving menu items.
3079 CL_DATA is the data to set in the widget for menu invocation. */
3081 static void
3082 xg_update_menu_item (widget_value *val,
3083 GtkWidget *w,
3084 GCallback select_cb,
3085 GCallback highlight_cb,
3086 xg_menu_cb_data *cl_data)
3088 GtkWidget *wchild;
3089 GtkLabel *wlbl = 0;
3090 GtkLabel *wkey = 0;
3091 char *utf8_label;
3092 char *utf8_key;
3093 const char *old_label = 0;
3094 const char *old_key = 0;
3095 xg_menu_item_cb_data *cb_data;
3096 bool label_changed = false;
3098 wchild = XG_BIN_CHILD (w);
3099 utf8_label = get_utf8_string (val->name);
3100 utf8_key = get_utf8_string (val->key);
3102 /* See if W is a menu item with a key. See make_menu_item above. */
3103 if (GTK_IS_BOX (wchild))
3105 GList *list = gtk_container_get_children (GTK_CONTAINER (wchild));
3107 wlbl = GTK_LABEL (list->data);
3108 wkey = GTK_LABEL (list->next->data);
3109 g_list_free (list);
3111 if (! utf8_key)
3113 /* Remove the key and keep just the label. */
3114 g_object_ref (G_OBJECT (wlbl));
3115 gtk_container_remove (GTK_CONTAINER (w), wchild);
3116 gtk_container_add (GTK_CONTAINER (w), GTK_WIDGET (wlbl));
3117 g_object_unref (G_OBJECT (wlbl));
3118 wkey = 0;
3122 else /* Just a label. */
3124 wlbl = GTK_LABEL (wchild);
3126 /* Check if there is now a key. */
3127 if (utf8_key)
3129 GtkWidget *wtoadd = make_widget_for_menu_item (utf8_label, utf8_key);
3130 GList *list = gtk_container_get_children (GTK_CONTAINER (wtoadd));
3132 wlbl = GTK_LABEL (list->data);
3133 wkey = GTK_LABEL (list->next->data);
3134 g_list_free (list);
3136 gtk_container_remove (GTK_CONTAINER (w), wchild);
3137 gtk_container_add (GTK_CONTAINER (w), wtoadd);
3141 if (wkey) old_key = gtk_label_get_label (wkey);
3142 if (wlbl) old_label = gtk_label_get_label (wlbl);
3144 if (wkey && utf8_key && (! old_key || strcmp (utf8_key, old_key) != 0))
3146 label_changed = true;
3147 gtk_label_set_text (wkey, utf8_key);
3150 if (! old_label || strcmp (utf8_label, old_label) != 0)
3152 label_changed = true;
3153 gtk_label_set_text (wlbl, utf8_label);
3156 if (utf8_key) g_free (utf8_key);
3157 if (utf8_label) g_free (utf8_label);
3159 if (! val->enabled && gtk_widget_get_sensitive (w))
3160 gtk_widget_set_sensitive (w, FALSE);
3161 else if (val->enabled && ! gtk_widget_get_sensitive (w))
3162 gtk_widget_set_sensitive (w, TRUE);
3164 cb_data = g_object_get_data (G_OBJECT (w), XG_ITEM_DATA);
3165 if (cb_data)
3167 cb_data->call_data = val->call_data;
3168 cb_data->help = val->help;
3169 cb_data->cl_data = cl_data;
3171 /* We assume the callback functions don't change. */
3172 if (val->call_data && ! val->contents)
3174 /* This item shall have a select callback. */
3175 if (! cb_data->select_id)
3176 cb_data->select_id
3177 = g_signal_connect (G_OBJECT (w), "activate",
3178 select_cb, cb_data);
3180 else if (cb_data->select_id)
3182 g_signal_handler_disconnect (w, cb_data->select_id);
3183 cb_data->select_id = 0;
3187 #if GTK_CHECK_VERSION (2, 16, 0)
3188 if (label_changed) /* See comment in xg_update_menubar. */
3189 g_object_notify (G_OBJECT (w), "label");
3190 #endif
3193 /* Update the toggle menu item W so it corresponds to VAL. */
3195 static void
3196 xg_update_toggle_item (widget_value *val, GtkWidget *w)
3198 gtk_check_menu_item_set_active (GTK_CHECK_MENU_ITEM (w), val->selected);
3201 /* Update the radio menu item W so it corresponds to VAL. */
3203 static void
3204 xg_update_radio_item (widget_value *val, GtkWidget *w)
3206 gtk_check_menu_item_set_active (GTK_CHECK_MENU_ITEM (w), val->selected);
3209 /* Update the sub menu SUBMENU and all its children so it corresponds to VAL.
3210 SUBMENU may be NULL, in that case a new menu is created.
3211 F is the frame the menu bar belongs to.
3212 VAL describes the contents of the menu bar.
3213 SELECT_CB is the callback to use when a menu item is selected.
3214 DEACTIVATE_CB is the callback to use when a sub menu is not shown anymore.
3215 HIGHLIGHT_CB is the callback to call when entering/leaving menu items.
3216 CL_DATA is the call back data to use for any newly created items.
3218 Returns the updated submenu widget, that is SUBMENU unless SUBMENU
3219 was NULL. */
3221 static GtkWidget *
3222 xg_update_submenu (GtkWidget *submenu,
3223 struct frame *f,
3224 widget_value *val,
3225 GCallback select_cb,
3226 GCallback deactivate_cb,
3227 GCallback highlight_cb,
3228 xg_menu_cb_data *cl_data)
3230 GtkWidget *newsub = submenu;
3231 GList *list = 0;
3232 GList *iter;
3233 widget_value *cur;
3234 GList *first_radio = 0;
3236 if (submenu)
3237 list = gtk_container_get_children (GTK_CONTAINER (submenu));
3239 for (cur = val, iter = list;
3240 cur && iter;
3241 iter = g_list_next (iter), cur = cur->next)
3243 GtkWidget *w = GTK_WIDGET (iter->data);
3245 /* Remember first radio button in a group. If we get a mismatch in
3246 a radio group we must rebuild the whole group so that the connections
3247 in GTK becomes correct. */
3248 if (cur->button_type == BUTTON_TYPE_RADIO && ! first_radio)
3249 first_radio = iter;
3250 else if (cur->button_type != BUTTON_TYPE_RADIO
3251 && ! GTK_IS_RADIO_MENU_ITEM (w))
3252 first_radio = 0;
3254 if (GTK_IS_SEPARATOR_MENU_ITEM (w))
3256 if (! menu_separator_name_p (cur->name))
3257 break;
3259 else if (GTK_IS_CHECK_MENU_ITEM (w))
3261 if (cur->button_type != BUTTON_TYPE_TOGGLE)
3262 break;
3263 xg_update_toggle_item (cur, w);
3264 xg_update_menu_item (cur, w, select_cb, highlight_cb, cl_data);
3266 else if (GTK_IS_RADIO_MENU_ITEM (w))
3268 if (cur->button_type != BUTTON_TYPE_RADIO)
3269 break;
3270 xg_update_radio_item (cur, w);
3271 xg_update_menu_item (cur, w, select_cb, highlight_cb, cl_data);
3273 else if (GTK_IS_MENU_ITEM (w))
3275 GtkMenuItem *witem = GTK_MENU_ITEM (w);
3276 GtkWidget *sub;
3278 if (cur->button_type != BUTTON_TYPE_NONE ||
3279 menu_separator_name_p (cur->name))
3280 break;
3282 xg_update_menu_item (cur, w, select_cb, highlight_cb, cl_data);
3284 sub = gtk_menu_item_get_submenu (witem);
3285 if (sub && ! cur->contents)
3287 /* Not a submenu anymore. */
3288 g_object_ref (G_OBJECT (sub));
3289 remove_submenu (witem);
3290 gtk_widget_destroy (sub);
3292 else if (cur->contents)
3294 GtkWidget *nsub;
3296 nsub = xg_update_submenu (sub, f, cur->contents,
3297 select_cb, deactivate_cb,
3298 highlight_cb, cl_data);
3300 /* If this item just became a submenu, we must set it. */
3301 if (nsub != sub)
3302 gtk_menu_item_set_submenu (witem, nsub);
3305 else
3307 /* Structural difference. Remove everything from here and down
3308 in SUBMENU. */
3309 break;
3313 /* Remove widgets from first structural change. */
3314 if (iter)
3316 /* If we are adding new menu items below, we must remove from
3317 first radio button so that radio groups become correct. */
3318 if (cur && first_radio) xg_destroy_widgets (first_radio);
3319 else xg_destroy_widgets (iter);
3322 if (cur)
3324 /* More items added. Create them. */
3325 newsub = create_menus (cur,
3327 select_cb,
3328 deactivate_cb,
3329 highlight_cb,
3332 submenu,
3333 cl_data,
3337 if (list) g_list_free (list);
3339 return newsub;
3342 /* Update the MENUBAR.
3343 F is the frame the menu bar belongs to.
3344 VAL describes the contents of the menu bar.
3345 If DEEP_P, rebuild all but the top level menu names in
3346 the MENUBAR. If DEEP_P is zero, just rebuild the names in the menubar.
3347 SELECT_CB is the callback to use when a menu item is selected.
3348 DEACTIVATE_CB is the callback to use when a sub menu is not shown anymore.
3349 HIGHLIGHT_CB is the callback to call when entering/leaving menu items. */
3351 void
3352 xg_modify_menubar_widgets (GtkWidget *menubar, struct frame *f,
3353 widget_value *val, bool deep_p,
3354 GCallback select_cb, GCallback deactivate_cb,
3355 GCallback highlight_cb)
3357 xg_menu_cb_data *cl_data;
3358 GList *list = gtk_container_get_children (GTK_CONTAINER (menubar));
3360 if (! list) return;
3362 cl_data = g_object_get_data (G_OBJECT (menubar), XG_FRAME_DATA);
3364 xg_update_menubar (menubar, f, &list, list, 0, val->contents,
3365 select_cb, deactivate_cb, highlight_cb, cl_data);
3367 if (deep_p)
3369 widget_value *cur;
3371 /* Update all sub menus.
3372 We must keep the submenus (GTK menu item widgets) since the
3373 X Window in the XEvent that activates the menu are those widgets. */
3375 /* Update cl_data, menu_item things in F may have changed. */
3376 update_cl_data (cl_data, f, highlight_cb);
3378 for (cur = val->contents; cur; cur = cur->next)
3380 GList *iter;
3381 GtkWidget *sub = 0;
3382 GtkWidget *newsub;
3383 GtkMenuItem *witem = 0;
3385 /* Find sub menu that corresponds to val and update it. */
3386 for (iter = list ; iter; iter = g_list_next (iter))
3388 witem = GTK_MENU_ITEM (iter->data);
3389 if (xg_item_label_same_p (witem, cur->name))
3391 sub = gtk_menu_item_get_submenu (witem);
3392 break;
3396 newsub = xg_update_submenu (sub,
3398 cur->contents,
3399 select_cb,
3400 deactivate_cb,
3401 highlight_cb,
3402 cl_data);
3403 /* sub may still be NULL. If we just updated non deep and added
3404 a new menu bar item, it has no sub menu yet. So we set the
3405 newly created sub menu under witem. */
3406 if (newsub != sub && witem != 0)
3408 xg_set_screen (newsub, f);
3409 gtk_menu_item_set_submenu (witem, newsub);
3414 g_list_free (list);
3415 gtk_widget_show_all (menubar);
3418 /* Callback called when the menu bar W is mapped.
3419 Used to find the height of the menu bar if we didn't get it
3420 after showing the widget. */
3422 static void
3423 menubar_map_cb (GtkWidget *w, gpointer user_data)
3425 GtkRequisition req;
3426 struct frame *f = user_data;
3427 gtk_widget_get_preferred_size (w, NULL, &req);
3428 if (FRAME_MENUBAR_HEIGHT (f) != req.height)
3430 FRAME_MENUBAR_HEIGHT (f) = req.height;
3431 adjust_frame_size (f, -1, -1, 2, 0, Qmenu_bar_lines);
3435 /* Recompute all the widgets of frame F, when the menu bar has been
3436 changed. */
3438 void
3439 xg_update_frame_menubar (struct frame *f)
3441 struct x_output *x = f->output_data.x;
3442 GtkRequisition req;
3444 if (!x->menubar_widget || gtk_widget_get_mapped (x->menubar_widget))
3445 return;
3447 if (x->menubar_widget && gtk_widget_get_parent (x->menubar_widget))
3448 return; /* Already done this, happens for frames created invisible. */
3450 block_input ();
3452 gtk_box_pack_start (GTK_BOX (x->vbox_widget), x->menubar_widget,
3453 FALSE, FALSE, 0);
3454 gtk_box_reorder_child (GTK_BOX (x->vbox_widget), x->menubar_widget, 0);
3456 g_signal_connect (x->menubar_widget, "map", G_CALLBACK (menubar_map_cb), f);
3457 gtk_widget_show_all (x->menubar_widget);
3458 gtk_widget_get_preferred_size (x->menubar_widget, NULL, &req);
3460 if (FRAME_MENUBAR_HEIGHT (f) != req.height)
3462 FRAME_MENUBAR_HEIGHT (f) = req.height;
3463 adjust_frame_size (f, -1, -1, 2, 0, Qmenu_bar_lines);
3465 unblock_input ();
3468 /* Get rid of the menu bar of frame F, and free its storage.
3469 This is used when deleting a frame, and when turning off the menu bar. */
3471 void
3472 free_frame_menubar (struct frame *f)
3474 struct x_output *x = f->output_data.x;
3476 if (x->menubar_widget)
3478 block_input ();
3480 gtk_container_remove (GTK_CONTAINER (x->vbox_widget), x->menubar_widget);
3481 /* The menubar and its children shall be deleted when removed from
3482 the container. */
3483 x->menubar_widget = 0;
3484 FRAME_MENUBAR_HEIGHT (f) = 0;
3485 adjust_frame_size (f, -1, -1, 2, 0, Qmenu_bar_lines);
3486 unblock_input ();
3490 bool
3491 xg_event_is_for_menubar (struct frame *f, const XEvent *event)
3493 struct x_output *x = f->output_data.x;
3494 GList *iter;
3495 GdkRectangle rec;
3496 GList *list;
3497 GdkDisplay *gdpy;
3498 GdkWindow *gw;
3499 GdkEvent gevent;
3500 GtkWidget *gwdesc;
3502 if (! x->menubar_widget) return 0;
3504 if (! (event->xbutton.x >= 0
3505 && event->xbutton.x < FRAME_PIXEL_WIDTH (f)
3506 && event->xbutton.y >= 0
3507 && event->xbutton.y < FRAME_MENUBAR_HEIGHT (f)
3508 && event->xbutton.same_screen))
3509 return 0;
3511 gdpy = gdk_x11_lookup_xdisplay (FRAME_X_DISPLAY (f));
3512 gw = gdk_x11_window_lookup_for_display (gdpy, event->xbutton.window);
3513 if (! gw) return 0;
3514 gevent.any.window = gw;
3515 gevent.any.type = GDK_NOTHING;
3516 gwdesc = gtk_get_event_widget (&gevent);
3517 if (! gwdesc) return 0;
3518 if (! GTK_IS_MENU_BAR (gwdesc)
3519 && ! GTK_IS_MENU_ITEM (gwdesc)
3520 && ! gtk_widget_is_ancestor (x->menubar_widget, gwdesc))
3521 return 0;
3523 list = gtk_container_get_children (GTK_CONTAINER (x->menubar_widget));
3524 if (! list) return 0;
3525 rec.x = event->xbutton.x;
3526 rec.y = event->xbutton.y;
3527 rec.width = 1;
3528 rec.height = 1;
3530 for (iter = list ; iter; iter = g_list_next (iter))
3532 GtkWidget *w = GTK_WIDGET (iter->data);
3533 if (gtk_widget_get_mapped (w) && gtk_widget_intersect (w, &rec, NULL))
3534 break;
3536 g_list_free (list);
3537 return iter != 0;
3542 /***********************************************************************
3543 Scroll bar functions
3544 ***********************************************************************/
3547 /* Setting scroll bar values invokes the callback. Use this variable
3548 to indicate that callback should do nothing. */
3550 bool xg_ignore_gtk_scrollbar;
3552 /* Width and height of scroll bars for the current theme. */
3553 static int scroll_bar_width_for_theme;
3554 static int scroll_bar_height_for_theme;
3556 /* Xlib's `Window' fits in 32 bits. But we want to store pointers, and they
3557 may be larger than 32 bits. Keep a mapping from integer index to widget
3558 pointers to get around the 32 bit limitation. */
3560 static struct
3562 GtkWidget **widgets;
3563 ptrdiff_t max_size;
3564 ptrdiff_t used;
3565 } id_to_widget;
3567 /* Grow this much every time we need to allocate more */
3569 #define ID_TO_WIDGET_INCR 32
3571 /* Store the widget pointer W in id_to_widget and return the integer index. */
3573 static ptrdiff_t
3574 xg_store_widget_in_map (GtkWidget *w)
3576 ptrdiff_t i;
3578 if (id_to_widget.max_size == id_to_widget.used)
3580 ptrdiff_t new_size;
3581 if (TYPE_MAXIMUM (Window) - ID_TO_WIDGET_INCR < id_to_widget.max_size)
3582 memory_full (SIZE_MAX);
3584 new_size = id_to_widget.max_size + ID_TO_WIDGET_INCR;
3585 id_to_widget.widgets = xnrealloc (id_to_widget.widgets,
3586 new_size, sizeof (GtkWidget *));
3588 for (i = id_to_widget.max_size; i < new_size; ++i)
3589 id_to_widget.widgets[i] = 0;
3590 id_to_widget.max_size = new_size;
3593 /* Just loop over the array and find a free place. After all,
3594 how many scroll bars are we creating? Should be a small number.
3595 The check above guarantees we will find a free place. */
3596 for (i = 0; i < id_to_widget.max_size; ++i)
3598 if (! id_to_widget.widgets[i])
3600 id_to_widget.widgets[i] = w;
3601 ++id_to_widget.used;
3603 return i;
3607 /* Should never end up here */
3608 emacs_abort ();
3611 /* Remove pointer at IDX from id_to_widget.
3612 Called when scroll bar is destroyed. */
3614 static void
3615 xg_remove_widget_from_map (ptrdiff_t idx)
3617 if (idx < id_to_widget.max_size && id_to_widget.widgets[idx] != 0)
3619 id_to_widget.widgets[idx] = 0;
3620 --id_to_widget.used;
3624 /* Get the widget pointer at IDX from id_to_widget. */
3626 static GtkWidget *
3627 xg_get_widget_from_map (ptrdiff_t idx)
3629 if (idx < id_to_widget.max_size && id_to_widget.widgets[idx] != 0)
3630 return id_to_widget.widgets[idx];
3632 return 0;
3635 static void
3636 update_theme_scrollbar_width (void)
3638 #ifdef HAVE_GTK3
3639 GtkAdjustment *vadj;
3640 #else
3641 GtkObject *vadj;
3642 #endif
3643 GtkWidget *wscroll;
3644 int w = 0, b = 0;
3646 vadj = gtk_adjustment_new (XG_SB_MIN, XG_SB_MIN, XG_SB_MAX, 0.1, 0.1, 0.1);
3647 wscroll = gtk_scrollbar_new (GTK_ORIENTATION_VERTICAL, GTK_ADJUSTMENT (vadj));
3648 g_object_ref_sink (G_OBJECT (wscroll));
3649 gtk_widget_style_get (wscroll, "slider-width", &w, "trough-border", &b, NULL);
3650 gtk_widget_destroy (wscroll);
3651 g_object_unref (G_OBJECT (wscroll));
3652 w += 2*b;
3653 #ifndef HAVE_GTK3
3654 if (w < 16) w = 16;
3655 #endif
3656 scroll_bar_width_for_theme = w;
3659 static void
3660 update_theme_scrollbar_height (void)
3662 #ifdef HAVE_GTK3
3663 GtkAdjustment *hadj;
3664 #else
3665 GtkObject *hadj;
3666 #endif
3667 GtkWidget *wscroll;
3668 int w = 0, b = 0;
3670 hadj = gtk_adjustment_new (YG_SB_MIN, YG_SB_MIN, YG_SB_MAX, 0.1, 0.1, 0.1);
3671 wscroll = gtk_scrollbar_new (GTK_ORIENTATION_HORIZONTAL, GTK_ADJUSTMENT (hadj));
3672 g_object_ref_sink (G_OBJECT (wscroll));
3673 gtk_widget_style_get (wscroll, "slider-width", &w, "trough-border", &b, NULL);
3674 gtk_widget_destroy (wscroll);
3675 g_object_unref (G_OBJECT (wscroll));
3676 w += 2*b;
3677 if (w < 12) w = 12;
3678 scroll_bar_height_for_theme = w;
3682 xg_get_default_scrollbar_width (struct frame *f)
3684 return scroll_bar_width_for_theme * xg_get_scale (f);
3688 xg_get_default_scrollbar_height (struct frame *f)
3690 /* Apparently there's no default height for themes. */
3691 return scroll_bar_width_for_theme * xg_get_scale (f);
3694 /* Return the scrollbar id for X Window WID on display DPY.
3695 Return -1 if WID not in id_to_widget. */
3697 ptrdiff_t
3698 xg_get_scroll_id_for_window (Display *dpy, Window wid)
3700 ptrdiff_t idx;
3701 GtkWidget *w;
3703 w = xg_win_to_widget (dpy, wid);
3705 if (w)
3707 for (idx = 0; idx < id_to_widget.max_size; ++idx)
3708 if (id_to_widget.widgets[idx] == w)
3709 return idx;
3712 return -1;
3715 /* Callback invoked when scroll bar WIDGET is destroyed.
3716 DATA is the index into id_to_widget for WIDGET.
3717 We free pointer to last scroll bar values here and remove the index. */
3719 static void
3720 xg_gtk_scroll_destroy (GtkWidget *widget, gpointer data)
3722 intptr_t id = (intptr_t) data;
3723 xg_remove_widget_from_map (id);
3726 static void
3727 xg_finish_scroll_bar_creation (struct frame *f,
3728 GtkWidget *wscroll,
3729 struct scroll_bar *bar,
3730 GCallback scroll_callback,
3731 GCallback end_callback,
3732 const char *scroll_bar_name)
3734 GtkWidget *webox = gtk_event_box_new ();
3736 gtk_widget_set_name (wscroll, scroll_bar_name);
3737 #ifndef HAVE_GTK3
3738 gtk_range_set_update_policy (GTK_RANGE (wscroll), GTK_UPDATE_CONTINUOUS);
3739 #endif
3740 g_object_set_data (G_OBJECT (wscroll), XG_FRAME_DATA, (gpointer)f);
3742 ptrdiff_t scroll_id = xg_store_widget_in_map (wscroll);
3744 g_signal_connect (G_OBJECT (wscroll),
3745 "destroy",
3746 G_CALLBACK (xg_gtk_scroll_destroy),
3747 (gpointer) scroll_id);
3748 g_signal_connect (G_OBJECT (wscroll),
3749 "change-value",
3750 scroll_callback,
3751 (gpointer) bar);
3752 g_signal_connect (G_OBJECT (wscroll),
3753 "button-release-event",
3754 end_callback,
3755 (gpointer) bar);
3757 /* The scroll bar widget does not draw on a window of its own. Instead
3758 it draws on the parent window, in this case the edit widget. So
3759 whenever the edit widget is cleared, the scroll bar needs to redraw
3760 also, which causes flicker. Put an event box between the edit widget
3761 and the scroll bar, so the scroll bar instead draws itself on the
3762 event box window. */
3763 gtk_fixed_put (GTK_FIXED (f->output_data.x->edit_widget), webox, -1, -1);
3764 gtk_container_add (GTK_CONTAINER (webox), wscroll);
3766 xg_set_widget_bg (f, webox, FRAME_BACKGROUND_PIXEL (f));
3768 /* N.B. The event box doesn't become a real X11 window until we ask
3769 for its XID via GTK_WIDGET_TO_X_WIN. If the event box is not a
3770 real X window, it and its scroll-bar child try to draw on the
3771 Emacs main window, which we draw over using Xlib. */
3772 gtk_widget_realize (webox);
3773 GTK_WIDGET_TO_X_WIN (webox);
3775 /* Set the cursor to an arrow. */
3776 xg_set_cursor (webox, FRAME_DISPLAY_INFO (f)->xg_cursor);
3778 bar->x_window = scroll_id;
3781 /* Create a scroll bar widget for frame F. Store the scroll bar
3782 in BAR.
3783 SCROLL_CALLBACK is the callback to invoke when the value of the
3784 bar changes.
3785 END_CALLBACK is the callback to invoke when scrolling ends.
3786 SCROLL_BAR_NAME is the name we use for the scroll bar. Can be used
3787 to set resources for the widget. */
3789 void
3790 xg_create_scroll_bar (struct frame *f,
3791 struct scroll_bar *bar,
3792 GCallback scroll_callback,
3793 GCallback end_callback,
3794 const char *scroll_bar_name)
3796 GtkWidget *wscroll;
3797 #ifdef HAVE_GTK3
3798 GtkAdjustment *vadj;
3799 #else
3800 GtkObject *vadj;
3801 #endif
3803 /* Page, step increment values are not so important here, they
3804 will be corrected in x_set_toolkit_scroll_bar_thumb. */
3805 vadj = gtk_adjustment_new (XG_SB_MIN, XG_SB_MIN, XG_SB_MAX,
3806 0.1, 0.1, 0.1);
3808 wscroll = gtk_scrollbar_new (GTK_ORIENTATION_VERTICAL, GTK_ADJUSTMENT (vadj));
3810 xg_finish_scroll_bar_creation (f, wscroll, bar, scroll_callback,
3811 end_callback, scroll_bar_name);
3812 bar->horizontal = 0;
3815 /* Create a horizontal scroll bar widget for frame F. Store the scroll
3816 bar in BAR. SCROLL_CALLBACK is the callback to invoke when the value
3817 of the bar changes. END_CALLBACK is the callback to invoke when
3818 scrolling ends. SCROLL_BAR_NAME is the name we use for the scroll
3819 bar. Can be used to set resources for the widget. */
3821 void
3822 xg_create_horizontal_scroll_bar (struct frame *f,
3823 struct scroll_bar *bar,
3824 GCallback scroll_callback,
3825 GCallback end_callback,
3826 const char *scroll_bar_name)
3828 GtkWidget *wscroll;
3829 #ifdef HAVE_GTK3
3830 GtkAdjustment *hadj;
3831 #else
3832 GtkObject *hadj;
3833 #endif
3835 /* Page, step increment values are not so important here, they
3836 will be corrected in x_set_toolkit_scroll_bar_thumb. */
3837 hadj = gtk_adjustment_new (YG_SB_MIN, YG_SB_MIN, YG_SB_MAX,
3838 0.1, 0.1, 0.1);
3840 wscroll = gtk_scrollbar_new (GTK_ORIENTATION_HORIZONTAL, GTK_ADJUSTMENT (hadj));
3842 xg_finish_scroll_bar_creation (f, wscroll, bar, scroll_callback,
3843 end_callback, scroll_bar_name);
3844 bar->horizontal = 1;
3847 /* Remove the scroll bar represented by SCROLLBAR_ID from the frame F. */
3849 void
3850 xg_remove_scroll_bar (struct frame *f, ptrdiff_t scrollbar_id)
3852 GtkWidget *w = xg_get_widget_from_map (scrollbar_id);
3853 if (w)
3855 GtkWidget *wparent = gtk_widget_get_parent (w);
3856 gtk_widget_destroy (w);
3857 gtk_widget_destroy (wparent);
3858 SET_FRAME_GARBAGED (f);
3862 /* Update the position of the vertical scroll bar represented by SCROLLBAR_ID
3863 in frame F.
3864 TOP/LEFT are the new pixel positions where the bar shall appear.
3865 WIDTH, HEIGHT is the size in pixels the bar shall have. */
3867 void
3868 xg_update_scrollbar_pos (struct frame *f,
3869 ptrdiff_t scrollbar_id,
3870 int top,
3871 int left,
3872 int width,
3873 int height)
3875 GtkWidget *wscroll = xg_get_widget_from_map (scrollbar_id);
3876 if (wscroll)
3878 GtkWidget *wfixed = f->output_data.x->edit_widget;
3879 GtkWidget *wparent = gtk_widget_get_parent (wscroll);
3880 gint msl;
3881 int scale = xg_get_scale (f);
3883 top /= scale;
3884 left /= scale;
3885 height /= scale;
3886 left -= (scale - 1) * ((width / scale) >> 1);
3888 /* Clear out old position. */
3889 int oldx = -1, oldy = -1, oldw, oldh;
3890 if (gtk_widget_get_parent (wparent) == wfixed)
3892 gtk_container_child_get (GTK_CONTAINER (wfixed), wparent,
3893 "x", &oldx, "y", &oldy, NULL);
3894 gtk_widget_get_size_request (wscroll, &oldw, &oldh);
3897 /* Move and resize to new values. */
3898 gtk_fixed_move (GTK_FIXED (wfixed), wparent, left, top);
3899 gtk_widget_style_get (wscroll, "min-slider-length", &msl, NULL);
3900 bool hidden = height < msl;
3901 if (hidden)
3903 /* No room. Hide scroll bar as some themes output a warning if
3904 the height is less than the min size. */
3905 gtk_widget_hide (wparent);
3906 gtk_widget_hide (wscroll);
3908 else
3910 gtk_widget_show_all (wparent);
3911 gtk_widget_set_size_request (wscroll, width, height);
3913 if (oldx != -1 && oldw > 0 && oldh > 0)
3915 /* Clear under old scroll bar position. */
3916 oldw += (scale - 1) * oldw;
3917 oldx -= (scale - 1) * oldw;
3918 x_clear_area (f, oldx, oldy, oldw, oldh);
3921 if (!hidden)
3923 GtkWidget *scrollbar = xg_get_widget_from_map (scrollbar_id);
3924 GtkWidget *webox = gtk_widget_get_parent (scrollbar);
3926 /* Don't obscure any child frames. */
3927 XLowerWindow (FRAME_X_DISPLAY (f), GTK_WIDGET_TO_X_WIN (webox));
3930 /* GTK does not redraw until the main loop is entered again, but
3931 if there are no X events pending we will not enter it. So we sync
3932 here to get some events. */
3934 x_sync (f);
3935 SET_FRAME_GARBAGED (f);
3936 cancel_mouse_face (f);
3941 /* Update the position of the horizontal scroll bar represented by SCROLLBAR_ID
3942 in frame F.
3943 TOP/LEFT are the new pixel positions where the bar shall appear.
3944 WIDTH, HEIGHT is the size in pixels the bar shall have. */
3946 void
3947 xg_update_horizontal_scrollbar_pos (struct frame *f,
3948 ptrdiff_t scrollbar_id,
3949 int top,
3950 int left,
3951 int width,
3952 int height)
3955 GtkWidget *wscroll = xg_get_widget_from_map (scrollbar_id);
3957 if (wscroll)
3959 GtkWidget *wfixed = f->output_data.x->edit_widget;
3960 GtkWidget *wparent = gtk_widget_get_parent (wscroll);
3961 gint msl;
3963 /* Clear out old position. */
3964 int oldx = -1, oldy = -1, oldw, oldh;
3965 if (gtk_widget_get_parent (wparent) == wfixed)
3967 gtk_container_child_get (GTK_CONTAINER (wfixed), wparent,
3968 "x", &oldx, "y", &oldy, NULL);
3969 gtk_widget_get_size_request (wscroll, &oldw, &oldh);
3972 /* Move and resize to new values. */
3973 gtk_fixed_move (GTK_FIXED (wfixed), wparent, left, top);
3974 gtk_widget_style_get (wscroll, "min-slider-length", &msl, NULL);
3975 if (msl > width)
3977 /* No room. Hide scroll bar as some themes output a warning if
3978 the width is less than the min size. */
3979 gtk_widget_hide (wparent);
3980 gtk_widget_hide (wscroll);
3982 else
3984 gtk_widget_show_all (wparent);
3985 gtk_widget_set_size_request (wscroll, width, height);
3987 if (oldx != -1 && oldw > 0 && oldh > 0)
3988 /* Clear under old scroll bar position. */
3989 x_clear_area (f, oldx, oldy, oldw, oldh);
3991 /* GTK does not redraw until the main loop is entered again, but
3992 if there are no X events pending we will not enter it. So we sync
3993 here to get some events. */
3996 GtkWidget *scrollbar =
3997 xg_get_widget_from_map (scrollbar_id);
3998 GtkWidget *webox = gtk_widget_get_parent (scrollbar);
4000 /* Don't obscure any child frames. */
4001 XLowerWindow (FRAME_X_DISPLAY (f), GTK_WIDGET_TO_X_WIN (webox));
4004 x_sync (f);
4005 SET_FRAME_GARBAGED (f);
4006 cancel_mouse_face (f);
4011 /* Get the current value of the range, truncated to an integer. */
4013 static int
4014 int_gtk_range_get_value (GtkRange *range)
4016 return gtk_range_get_value (range);
4020 /* Set the thumb size and position of scroll bar BAR. We are currently
4021 displaying PORTION out of a whole WHOLE, and our position POSITION. */
4023 void
4024 xg_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar,
4025 int portion,
4026 int position,
4027 int whole)
4029 GtkWidget *wscroll = xg_get_widget_from_map (bar->x_window);
4031 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
4033 if (wscroll && bar->dragging == -1)
4035 GtkAdjustment *adj;
4036 gdouble shown;
4037 gdouble top;
4038 int size, value;
4039 int old_size;
4040 int new_step;
4041 bool changed = 0;
4043 adj = gtk_range_get_adjustment (GTK_RANGE (wscroll));
4045 if (scroll_bar_adjust_thumb_portion_p)
4047 /* We do the same as for MOTIF in xterm.c, use 30 chars per
4048 line rather than the real portion value. This makes the
4049 thumb less likely to resize and that looks better. */
4050 portion = WINDOW_TOTAL_LINES (XWINDOW (bar->window)) * 30;
4052 /* When the thumb is at the bottom, position == whole.
4053 So we need to increase `whole' to make space for the thumb. */
4054 whole += portion;
4057 if (whole <= 0)
4058 top = 0, shown = 1;
4059 else
4061 top = (gdouble) position / whole;
4062 shown = (gdouble) portion / whole;
4065 size = clip_to_bounds (1, shown * XG_SB_RANGE, XG_SB_RANGE);
4066 value = clip_to_bounds (XG_SB_MIN, top * XG_SB_RANGE, XG_SB_MAX - size);
4068 /* Assume all lines are of equal size. */
4069 new_step = size / max (1, FRAME_LINES (f));
4071 old_size = gtk_adjustment_get_page_size (adj);
4072 if (old_size != size)
4074 int old_step = gtk_adjustment_get_step_increment (adj);
4075 if (old_step != new_step)
4077 gtk_adjustment_set_page_size (adj, size);
4078 gtk_adjustment_set_step_increment (adj, new_step);
4079 /* Assume a page increment is about 95% of the page size */
4080 gtk_adjustment_set_page_increment (adj, size - size / 20);
4081 changed = 1;
4085 if (changed || int_gtk_range_get_value (GTK_RANGE (wscroll)) != value)
4087 block_input ();
4089 /* gtk_range_set_value invokes the callback. Set
4090 ignore_gtk_scrollbar to make the callback do nothing */
4091 xg_ignore_gtk_scrollbar = 1;
4093 if (int_gtk_range_get_value (GTK_RANGE (wscroll)) != value)
4094 gtk_range_set_value (GTK_RANGE (wscroll), (gdouble)value);
4095 else if (changed)
4096 gtk_adjustment_changed (adj);
4098 xg_ignore_gtk_scrollbar = 0;
4100 unblock_input ();
4105 /* Set the thumb size and position of horizontal scroll bar BAR. We are
4106 currently displaying PORTION out of a whole WHOLE, and our position
4107 POSITION. */
4108 void
4109 xg_set_toolkit_horizontal_scroll_bar_thumb (struct scroll_bar *bar,
4110 int portion,
4111 int position,
4112 int whole)
4114 GtkWidget *wscroll = xg_get_widget_from_map (bar->x_window);
4116 if (wscroll && bar->dragging == -1)
4118 GtkAdjustment *adj;
4119 int lower = 0;
4120 int upper = max (whole - 1, 0);
4121 int pagesize = min (upper, max (portion, 0));
4122 int value = max (0, min (position, upper - pagesize));
4123 /* These should be set to something more <portion, whole>
4124 related. */
4125 int page_increment = 4;
4126 int step_increment = 1;
4128 block_input ();
4129 adj = gtk_range_get_adjustment (GTK_RANGE (wscroll));
4130 gtk_adjustment_configure (adj, (gdouble) value, (gdouble) lower,
4131 (gdouble) upper, (gdouble) step_increment,
4132 (gdouble) page_increment, (gdouble) pagesize);
4133 gtk_adjustment_changed (adj);
4134 unblock_input ();
4138 /* Return true if EVENT is for a scroll bar in frame F.
4139 When the same X window is used for several Gtk+ widgets, we cannot
4140 say for sure based on the X window alone if an event is for the
4141 frame. This function does additional checks. */
4143 bool
4144 xg_event_is_for_scrollbar (struct frame *f, const XEvent *event)
4146 bool retval = 0;
4148 if (f && event->type == ButtonPress && event->xbutton.button < 4)
4150 /* Check if press occurred outside the edit widget. */
4151 GdkDisplay *gdpy = gdk_x11_lookup_xdisplay (FRAME_X_DISPLAY (f));
4152 GdkWindow *gwin;
4153 #ifdef HAVE_GTK3
4154 #if GTK_CHECK_VERSION (3, 20, 0)
4155 GdkDevice *gdev
4156 = gdk_seat_get_pointer (gdk_display_get_default_seat (gdpy));
4157 #else
4158 GdkDevice *gdev = gdk_device_manager_get_client_pointer
4159 (gdk_display_get_device_manager (gdpy));
4160 #endif
4161 gwin = gdk_device_get_window_at_position (gdev, NULL, NULL);
4162 #else
4163 gwin = gdk_display_get_window_at_pointer (gdpy, NULL, NULL);
4164 #endif
4165 retval = gwin != gtk_widget_get_window (f->output_data.x->edit_widget);
4167 else if (f
4168 && ((event->type == ButtonRelease && event->xbutton.button < 4)
4169 || event->type == MotionNotify))
4171 /* If we are releasing or moving the scroll bar, it has the grab. */
4172 GtkWidget *w = gtk_grab_get_current ();
4173 retval = w != 0 && GTK_IS_SCROLLBAR (w);
4176 return retval;
4180 /***********************************************************************
4181 Printing
4182 ***********************************************************************/
4183 #ifdef USE_CAIRO
4184 static GtkPrintSettings *print_settings = NULL;
4185 static GtkPageSetup *page_setup = NULL;
4187 void
4188 xg_page_setup_dialog (void)
4190 GtkPageSetup *new_page_setup = NULL;
4192 if (print_settings == NULL)
4193 print_settings = gtk_print_settings_new ();
4194 new_page_setup = gtk_print_run_page_setup_dialog (NULL, page_setup,
4195 print_settings);
4196 if (page_setup)
4197 g_object_unref (page_setup);
4198 page_setup = new_page_setup;
4201 Lisp_Object
4202 xg_get_page_setup (void)
4204 Lisp_Object orientation_symbol;
4206 if (page_setup == NULL)
4207 page_setup = gtk_page_setup_new ();
4209 switch (gtk_page_setup_get_orientation (page_setup))
4211 case GTK_PAGE_ORIENTATION_PORTRAIT:
4212 orientation_symbol = Qportrait;
4213 break;
4214 case GTK_PAGE_ORIENTATION_LANDSCAPE:
4215 orientation_symbol = Qlandscape;
4216 break;
4217 case GTK_PAGE_ORIENTATION_REVERSE_PORTRAIT:
4218 orientation_symbol = Qreverse_portrait;
4219 break;
4220 case GTK_PAGE_ORIENTATION_REVERSE_LANDSCAPE:
4221 orientation_symbol = Qreverse_landscape;
4222 break;
4223 default:
4224 eassume (false);
4227 return listn (CONSTYPE_HEAP, 7,
4228 Fcons (Qorientation, orientation_symbol),
4229 #define MAKE_FLOAT_PAGE_SETUP(f) make_float (f (page_setup, GTK_UNIT_POINTS))
4230 Fcons (Qwidth,
4231 MAKE_FLOAT_PAGE_SETUP (gtk_page_setup_get_page_width)),
4232 Fcons (Qheight,
4233 MAKE_FLOAT_PAGE_SETUP (gtk_page_setup_get_page_height)),
4234 Fcons (Qleft_margin,
4235 MAKE_FLOAT_PAGE_SETUP (gtk_page_setup_get_left_margin)),
4236 Fcons (Qright_margin,
4237 MAKE_FLOAT_PAGE_SETUP (gtk_page_setup_get_right_margin)),
4238 Fcons (Qtop_margin,
4239 MAKE_FLOAT_PAGE_SETUP (gtk_page_setup_get_top_margin)),
4240 Fcons (Qbottom_margin,
4241 MAKE_FLOAT_PAGE_SETUP (gtk_page_setup_get_bottom_margin))
4242 #undef MAKE_FLOAT_PAGE_SETUP
4246 static void
4247 draw_page (GtkPrintOperation *operation, GtkPrintContext *context,
4248 gint page_nr, gpointer user_data)
4250 Lisp_Object frames = *((Lisp_Object *) user_data);
4251 struct frame *f = XFRAME (Fnth (make_number (page_nr), frames));
4252 cairo_t *cr = gtk_print_context_get_cairo_context (context);
4254 x_cr_draw_frame (cr, f);
4257 void
4258 xg_print_frames_dialog (Lisp_Object frames)
4260 GtkPrintOperation *print;
4261 GtkPrintOperationResult res;
4263 print = gtk_print_operation_new ();
4264 if (print_settings != NULL)
4265 gtk_print_operation_set_print_settings (print, print_settings);
4266 if (page_setup != NULL)
4267 gtk_print_operation_set_default_page_setup (print, page_setup);
4268 gtk_print_operation_set_n_pages (print, XINT (Flength (frames)));
4269 g_signal_connect (print, "draw-page", G_CALLBACK (draw_page), &frames);
4270 res = gtk_print_operation_run (print, GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG,
4271 NULL, NULL);
4272 if (res == GTK_PRINT_OPERATION_RESULT_APPLY)
4274 if (print_settings != NULL)
4275 g_object_unref (print_settings);
4276 print_settings =
4277 g_object_ref (gtk_print_operation_get_print_settings (print));
4279 g_object_unref (print);
4282 #endif /* USE_CAIRO */
4286 /***********************************************************************
4287 Tool bar functions
4288 ***********************************************************************/
4289 /* The key for the data we put in the GtkImage widgets. The data is
4290 the image used by Emacs. We use this to see if we need to update
4291 the GtkImage with a new image. */
4292 #define XG_TOOL_BAR_IMAGE_DATA "emacs-tool-bar-image"
4294 /* The key for storing the latest modifiers so the activate callback can
4295 get them. */
4296 #define XG_TOOL_BAR_LAST_MODIFIER "emacs-tool-bar-modifier"
4298 /* The key for the data we put in the GtkImage widgets. The data is
4299 the stock name used by Emacs. We use this to see if we need to update
4300 the GtkImage with a new image. */
4301 #define XG_TOOL_BAR_STOCK_NAME "emacs-tool-bar-stock-name"
4303 /* As above, but this is used for named theme widgets, as opposed to
4304 stock items. */
4305 #define XG_TOOL_BAR_ICON_NAME "emacs-tool-bar-icon-name"
4307 /* Callback function invoked when a tool bar item is pressed.
4308 W is the button widget in the tool bar that got pressed,
4309 CLIENT_DATA is an integer that is the index of the button in the
4310 tool bar. 0 is the first button. */
4312 static gboolean
4313 xg_tool_bar_button_cb (GtkWidget *widget,
4314 GdkEventButton *event,
4315 gpointer user_data)
4317 intptr_t state = event->state;
4318 gpointer ptr = (gpointer) state;
4319 g_object_set_data (G_OBJECT (widget), XG_TOOL_BAR_LAST_MODIFIER, ptr);
4320 return FALSE;
4324 /* Callback function invoked when a tool bar item is pressed.
4325 W is the button widget in the tool bar that got pressed,
4326 CLIENT_DATA is an integer that is the index of the button in the
4327 tool bar. 0 is the first button. */
4329 static void
4330 xg_tool_bar_callback (GtkWidget *w, gpointer client_data)
4332 intptr_t idx = (intptr_t) client_data;
4333 gpointer gmod = g_object_get_data (G_OBJECT (w), XG_TOOL_BAR_LAST_MODIFIER);
4334 intptr_t mod = (intptr_t) gmod;
4336 struct frame *f = g_object_get_data (G_OBJECT (w), XG_FRAME_DATA);
4337 Lisp_Object key, frame;
4338 struct input_event event;
4339 EVENT_INIT (event);
4341 if (! f || ! f->n_tool_bar_items || NILP (f->tool_bar_items))
4342 return;
4344 idx *= TOOL_BAR_ITEM_NSLOTS;
4346 key = AREF (f->tool_bar_items, idx + TOOL_BAR_ITEM_KEY);
4347 XSETFRAME (frame, f);
4349 /* We generate two events here. The first one is to set the prefix
4350 to `(tool_bar)', see keyboard.c. */
4351 event.kind = TOOL_BAR_EVENT;
4352 event.frame_or_window = frame;
4353 event.arg = frame;
4354 kbd_buffer_store_event (&event);
4356 event.kind = TOOL_BAR_EVENT;
4357 event.frame_or_window = frame;
4358 event.arg = key;
4359 /* Convert between the modifier bits GDK uses and the modifier bits
4360 Emacs uses. This assumes GDK and X masks are the same, which they are when
4361 this is written. */
4362 event.modifiers = x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO (f), mod);
4363 kbd_buffer_store_event (&event);
4365 /* Return focus to the frame after we have clicked on a detached
4366 tool bar button. */
4367 x_focus_frame (f, false);
4370 static GtkWidget *
4371 xg_get_tool_bar_widgets (GtkWidget *vb, GtkWidget **wimage)
4373 GList *clist = gtk_container_get_children (GTK_CONTAINER (vb));
4374 GtkWidget *c1 = clist->data;
4375 GtkWidget *c2 = clist->next ? clist->next->data : NULL;
4377 *wimage = GTK_IS_IMAGE (c1) ? c1 : c2;
4378 g_list_free (clist);
4379 return GTK_IS_LABEL (c1) ? c1 : c2;
4383 /* This callback is called when the mouse enters or leaves a tool bar item.
4384 It is used for displaying and hiding the help text.
4385 W is the tool bar item, a button.
4386 EVENT is either an enter event or leave event.
4387 CLIENT_DATA is an integer that is the index of the button in the
4388 tool bar. 0 is the first button.
4390 Returns FALSE to tell GTK to keep processing this event. */
4392 static gboolean
4393 xg_tool_bar_help_callback (GtkWidget *w,
4394 GdkEventCrossing *event,
4395 gpointer client_data)
4397 intptr_t idx = (intptr_t) client_data;
4398 struct frame *f = g_object_get_data (G_OBJECT (w), XG_FRAME_DATA);
4399 Lisp_Object help, frame;
4401 if (! f || ! f->n_tool_bar_items || NILP (f->tool_bar_items))
4402 return FALSE;
4404 if (event->type == GDK_ENTER_NOTIFY)
4406 idx *= TOOL_BAR_ITEM_NSLOTS;
4407 help = AREF (f->tool_bar_items, idx + TOOL_BAR_ITEM_HELP);
4409 if (NILP (help))
4410 help = AREF (f->tool_bar_items, idx + TOOL_BAR_ITEM_CAPTION);
4412 else
4413 help = Qnil;
4415 XSETFRAME (frame, f);
4416 kbd_buffer_store_help_event (frame, help);
4418 return FALSE;
4422 /* This callback is called when a tool bar item shall be redrawn.
4423 It modifies the expose event so that the GtkImage widget redraws the
4424 whole image. This to overcome a bug that makes GtkImage draw the image
4425 in the wrong place when it tries to redraw just a part of the image.
4426 W is the GtkImage to be redrawn.
4427 EVENT is the expose event for W.
4428 CLIENT_DATA is unused.
4430 Returns FALSE to tell GTK to keep processing this event. */
4432 #ifndef HAVE_GTK3
4433 static gboolean
4434 xg_tool_bar_item_expose_callback (GtkWidget *w,
4435 GdkEventExpose *event,
4436 gpointer client_data)
4438 gint width, height;
4440 gdk_drawable_get_size (event->window, &width, &height);
4441 event->area.x -= width > event->area.width ? width-event->area.width : 0;
4442 event->area.y -= height > event->area.height ? height-event->area.height : 0;
4444 event->area.x = max (0, event->area.x);
4445 event->area.y = max (0, event->area.y);
4447 event->area.width = max (width, event->area.width);
4448 event->area.height = max (height, event->area.height);
4450 return FALSE;
4452 #endif
4454 #ifdef HAVE_GTK_ORIENTABLE_SET_ORIENTATION
4455 #define toolbar_set_orientation(w, o) \
4456 gtk_orientable_set_orientation (GTK_ORIENTABLE (w), o)
4457 #else
4458 #define toolbar_set_orientation(w, o) \
4459 gtk_toolbar_set_orientation (GTK_TOOLBAR (w), o)
4460 #endif
4462 /* Attach a tool bar to frame F. */
4464 static void
4465 xg_pack_tool_bar (struct frame *f, Lisp_Object pos)
4467 struct x_output *x = f->output_data.x;
4468 bool into_hbox = EQ (pos, Qleft) || EQ (pos, Qright);
4469 GtkWidget *top_widget = x->toolbar_widget;
4471 toolbar_set_orientation (x->toolbar_widget,
4472 into_hbox
4473 ? GTK_ORIENTATION_VERTICAL
4474 : GTK_ORIENTATION_HORIZONTAL);
4476 if (into_hbox)
4478 gtk_box_pack_start (GTK_BOX (x->hbox_widget), top_widget,
4479 FALSE, FALSE, 0);
4481 if (EQ (pos, Qleft))
4482 gtk_box_reorder_child (GTK_BOX (x->hbox_widget),
4483 top_widget,
4485 x->toolbar_in_hbox = true;
4487 else
4489 bool vbox_pos = x->menubar_widget != 0;
4490 gtk_box_pack_start (GTK_BOX (x->vbox_widget), top_widget,
4491 FALSE, FALSE, 0);
4493 if (EQ (pos, Qtop))
4494 gtk_box_reorder_child (GTK_BOX (x->vbox_widget),
4495 top_widget,
4496 vbox_pos);
4497 x->toolbar_in_hbox = false;
4499 x->toolbar_is_packed = true;
4502 static bool xg_update_tool_bar_sizes (struct frame *f);
4504 static void
4505 tb_size_cb (GtkWidget *widget,
4506 GdkRectangle *allocation,
4507 gpointer user_data)
4509 /* When tool bar is created it has one preferred size. But when size is
4510 allocated between widgets, it may get another. So we must update
4511 size hints if tool bar size changes. Seen on Fedora 18 at least. */
4512 struct frame *f = user_data;
4514 if (xg_update_tool_bar_sizes (f))
4516 frame_size_history_add (f, Qtb_size_cb, 0, 0, Qnil);
4517 adjust_frame_size (f, -1, -1, 5, 0, Qtool_bar_lines);
4521 /* Create a tool bar for frame F. */
4523 static void
4524 xg_create_tool_bar (struct frame *f)
4526 struct x_output *x = f->output_data.x;
4527 #if GTK_CHECK_VERSION (3, 3, 6)
4528 GtkStyleContext *gsty;
4529 #endif
4530 struct xg_frame_tb_info *tbinfo
4531 = g_object_get_data (G_OBJECT (FRAME_GTK_OUTER_WIDGET (f)),
4532 TB_INFO_KEY);
4533 if (! tbinfo)
4535 tbinfo = xmalloc (sizeof (*tbinfo));
4536 tbinfo->last_tool_bar = Qnil;
4537 tbinfo->style = Qnil;
4538 tbinfo->hmargin = tbinfo->vmargin = 0;
4539 tbinfo->dir = GTK_TEXT_DIR_NONE;
4540 tbinfo->n_last_items = 0;
4541 g_object_set_data (G_OBJECT (FRAME_GTK_OUTER_WIDGET (f)),
4542 TB_INFO_KEY,
4543 tbinfo);
4546 x->toolbar_widget = gtk_toolbar_new ();
4548 gtk_widget_set_name (x->toolbar_widget, "emacs-toolbar");
4550 gtk_toolbar_set_style (GTK_TOOLBAR (x->toolbar_widget), GTK_TOOLBAR_ICONS);
4551 toolbar_set_orientation (x->toolbar_widget, GTK_ORIENTATION_HORIZONTAL);
4552 g_signal_connect (x->toolbar_widget, "size-allocate",
4553 G_CALLBACK (tb_size_cb), f);
4554 #if GTK_CHECK_VERSION (3, 3, 6)
4555 gsty = gtk_widget_get_style_context (x->toolbar_widget);
4556 gtk_style_context_add_class (gsty, "primary-toolbar");
4557 #endif
4561 #define PROP(IDX) AREF (f->tool_bar_items, i * TOOL_BAR_ITEM_NSLOTS + (IDX))
4563 /* Find the right-to-left image named by RTL in the tool bar images for F.
4564 Returns IMAGE if RTL is not found. */
4566 static Lisp_Object
4567 find_rtl_image (struct frame *f, Lisp_Object image, Lisp_Object rtl)
4569 int i;
4570 Lisp_Object file, rtl_name;
4572 rtl_name = Ffile_name_nondirectory (rtl);
4574 for (i = 0; i < f->n_tool_bar_items; ++i)
4576 Lisp_Object rtl_image = PROP (TOOL_BAR_ITEM_IMAGES);
4577 if (!NILP (file = file_for_image (rtl_image)))
4579 file = call1 (intern ("file-name-sans-extension"),
4580 Ffile_name_nondirectory (file));
4581 if (! NILP (Fequal (file, rtl_name)))
4583 image = rtl_image;
4584 break;
4589 return image;
4592 static GtkToolItem *
4593 xg_make_tool_item (struct frame *f,
4594 GtkWidget *wimage,
4595 GtkWidget **wbutton,
4596 const char *label,
4597 int i, bool horiz, bool text_image)
4599 GtkToolItem *ti = gtk_tool_item_new ();
4600 GtkWidget *vb = gtk_box_new (horiz
4601 ? GTK_ORIENTATION_HORIZONTAL
4602 : GTK_ORIENTATION_VERTICAL,
4604 GtkWidget *wb = gtk_button_new ();
4605 /* The eventbox is here so we can have tooltips on disabled items. */
4606 GtkWidget *weventbox = gtk_event_box_new ();
4607 #if GTK_CHECK_VERSION (3, 3, 6)
4608 GtkCssProvider *css_prov = gtk_css_provider_new ();
4609 GtkStyleContext *gsty;
4611 gtk_css_provider_load_from_data (css_prov,
4612 "GtkEventBox {"
4613 " background-color: transparent;"
4614 "}",
4615 -1, NULL);
4617 gsty = gtk_widget_get_style_context (weventbox);
4618 gtk_style_context_add_provider (gsty,
4619 GTK_STYLE_PROVIDER (css_prov),
4620 GTK_STYLE_PROVIDER_PRIORITY_USER);
4621 g_object_unref (css_prov);
4622 #endif
4624 gtk_box_set_homogeneous (GTK_BOX (vb), FALSE);
4626 if (wimage && !text_image)
4627 gtk_box_pack_start (GTK_BOX (vb), wimage, TRUE, TRUE, 0);
4628 if (label)
4629 gtk_box_pack_start (GTK_BOX (vb), gtk_label_new (label), TRUE, TRUE, 0);
4630 if (wimage && text_image)
4631 gtk_box_pack_start (GTK_BOX (vb), wimage, TRUE, TRUE, 0);
4633 #if GTK_CHECK_VERSION (3, 20, 0)
4634 gtk_widget_set_focus_on_click (wb, FALSE);
4635 #else
4636 gtk_button_set_focus_on_click (GTK_BUTTON (wb), FALSE);
4637 #endif
4638 gtk_button_set_relief (GTK_BUTTON (wb), GTK_RELIEF_NONE);
4639 gtk_container_add (GTK_CONTAINER (wb), vb);
4640 gtk_container_add (GTK_CONTAINER (weventbox), wb);
4641 gtk_container_add (GTK_CONTAINER (ti), weventbox);
4643 if (wimage || label)
4645 intptr_t ii = i;
4646 gpointer gi = (gpointer) ii;
4648 g_signal_connect (G_OBJECT (wb), "clicked",
4649 G_CALLBACK (xg_tool_bar_callback),
4650 gi);
4652 g_object_set_data (G_OBJECT (weventbox), XG_FRAME_DATA, (gpointer)f);
4654 #ifndef HAVE_GTK3
4655 /* Catch expose events to overcome an annoying redraw bug, see
4656 comment for xg_tool_bar_item_expose_callback. */
4657 g_signal_connect (G_OBJECT (ti),
4658 "expose-event",
4659 G_CALLBACK (xg_tool_bar_item_expose_callback),
4661 #endif
4662 gtk_tool_item_set_homogeneous (ti, FALSE);
4664 /* Callback to save modifier mask (Shift/Control, etc). GTK makes
4665 no distinction based on modifiers in the activate callback,
4666 so we have to do it ourselves. */
4667 g_signal_connect (wb, "button-release-event",
4668 G_CALLBACK (xg_tool_bar_button_cb),
4669 NULL);
4671 g_object_set_data (G_OBJECT (wb), XG_FRAME_DATA, (gpointer)f);
4673 /* Use enter/leave notify to show help. We use the events
4674 rather than the GtkButton specific signals "enter" and
4675 "leave", so we can have only one callback. The event
4676 will tell us what kind of event it is. */
4677 g_signal_connect (G_OBJECT (weventbox),
4678 "enter-notify-event",
4679 G_CALLBACK (xg_tool_bar_help_callback),
4680 gi);
4681 g_signal_connect (G_OBJECT (weventbox),
4682 "leave-notify-event",
4683 G_CALLBACK (xg_tool_bar_help_callback),
4684 gi);
4687 if (wbutton) *wbutton = wb;
4689 return ti;
4692 static bool
4693 is_box_type (GtkWidget *vb, bool is_horizontal)
4695 #ifdef HAVE_GTK3
4696 bool ret = 0;
4697 if (GTK_IS_BOX (vb))
4699 GtkOrientation ori = gtk_orientable_get_orientation (GTK_ORIENTABLE (vb));
4700 ret = (ori == GTK_ORIENTATION_HORIZONTAL && is_horizontal)
4701 || (ori == GTK_ORIENTATION_VERTICAL && ! is_horizontal);
4703 return ret;
4704 #else
4705 return is_horizontal ? GTK_IS_VBOX (vb) : GTK_IS_HBOX (vb);
4706 #endif
4710 static bool
4711 xg_tool_item_stale_p (GtkWidget *wbutton, const char *stock_name,
4712 const char *icon_name, const struct image *img,
4713 const char *label, bool horiz)
4715 gpointer old;
4716 GtkWidget *wimage;
4717 GtkWidget *vb = XG_BIN_CHILD (wbutton);
4718 GtkWidget *wlbl = xg_get_tool_bar_widgets (vb, &wimage);
4720 /* Check if the tool icon matches. */
4721 if (stock_name && wimage)
4723 old = g_object_get_data (G_OBJECT (wimage),
4724 XG_TOOL_BAR_STOCK_NAME);
4725 if (!old || strcmp (old, stock_name))
4726 return 1;
4728 else if (icon_name && wimage)
4730 old = g_object_get_data (G_OBJECT (wimage),
4731 XG_TOOL_BAR_ICON_NAME);
4732 if (!old || strcmp (old, icon_name))
4733 return 1;
4735 else if (wimage)
4737 gpointer gold_img = g_object_get_data (G_OBJECT (wimage),
4738 XG_TOOL_BAR_IMAGE_DATA);
4739 Pixmap old_img = (Pixmap) gold_img;
4740 if (old_img != img->pixmap)
4741 return 1;
4744 /* Check button configuration and label. */
4745 if (is_box_type (vb, horiz)
4746 || (label ? (wlbl == NULL) : (wlbl != NULL)))
4747 return 1;
4749 /* Ensure label is correct. */
4750 if (label && wlbl)
4751 gtk_label_set_text (GTK_LABEL (wlbl), label);
4752 return 0;
4755 static bool
4756 xg_update_tool_bar_sizes (struct frame *f)
4758 struct x_output *x = f->output_data.x;
4759 GtkRequisition req;
4760 int nl = 0, nr = 0, nt = 0, nb = 0;
4761 GtkWidget *top_widget = x->toolbar_widget;
4763 gtk_widget_get_preferred_size (GTK_WIDGET (top_widget), NULL, &req);
4764 if (x->toolbar_in_hbox)
4766 int pos;
4767 gtk_container_child_get (GTK_CONTAINER (x->hbox_widget),
4768 top_widget,
4769 "position", &pos, NULL);
4770 if (pos == 0) nl = req.width;
4771 else nr = req.width;
4773 else
4775 int pos;
4776 gtk_container_child_get (GTK_CONTAINER (x->vbox_widget),
4777 top_widget,
4778 "position", &pos, NULL);
4779 if (pos == 0 || (pos == 1 && x->menubar_widget)) nt = req.height;
4780 else nb = req.height;
4783 if (nl != FRAME_TOOLBAR_LEFT_WIDTH (f)
4784 || nr != FRAME_TOOLBAR_RIGHT_WIDTH (f)
4785 || nt != FRAME_TOOLBAR_TOP_HEIGHT (f)
4786 || nb != FRAME_TOOLBAR_BOTTOM_HEIGHT (f))
4788 FRAME_TOOLBAR_RIGHT_WIDTH (f) = FRAME_TOOLBAR_LEFT_WIDTH (f)
4789 = FRAME_TOOLBAR_TOP_HEIGHT (f) = FRAME_TOOLBAR_BOTTOM_HEIGHT (f) = 0;
4790 FRAME_TOOLBAR_LEFT_WIDTH (f) = nl;
4791 FRAME_TOOLBAR_RIGHT_WIDTH (f) = nr;
4792 FRAME_TOOLBAR_TOP_HEIGHT (f) = nt;
4793 FRAME_TOOLBAR_BOTTOM_HEIGHT (f) = nb;
4795 return true;
4797 else
4798 return false;
4801 static char *
4802 find_icon_from_name (char *name,
4803 GtkIconTheme *icon_theme,
4804 char **icon_name)
4806 #if ! GTK_CHECK_VERSION (3, 10, 0)
4807 GtkStockItem stock_item;
4808 #endif
4810 if (name[0] == 'n' && name[1] == ':')
4812 *icon_name = name + 2;
4813 name = NULL;
4815 if (! gtk_icon_theme_has_icon (icon_theme, *icon_name))
4816 *icon_name = NULL;
4819 #if ! GTK_CHECK_VERSION (3, 10, 0)
4820 else if (gtk_stock_lookup (name, &stock_item))
4821 *icon_name = NULL;
4822 #endif
4823 else if (gtk_icon_theme_has_icon (icon_theme, name))
4825 *icon_name = name;
4826 name = NULL;
4828 else
4830 name = NULL;
4831 *icon_name = NULL;
4834 return name;
4838 /* Update the tool bar for frame F. Add new buttons and remove old. */
4840 void
4841 update_frame_tool_bar (struct frame *f)
4843 int i, j;
4844 struct x_output *x = f->output_data.x;
4845 int hmargin = 0, vmargin = 0;
4846 GtkToolbar *wtoolbar;
4847 GtkToolItem *ti;
4848 GtkTextDirection dir;
4849 Lisp_Object style;
4850 bool text_image, horiz;
4851 struct xg_frame_tb_info *tbinfo;
4852 GdkScreen *screen;
4853 GtkIconTheme *icon_theme;
4856 if (! FRAME_GTK_WIDGET (f))
4857 return;
4859 block_input ();
4861 if (RANGED_INTEGERP (1, Vtool_bar_button_margin, INT_MAX))
4863 hmargin = XFASTINT (Vtool_bar_button_margin);
4864 vmargin = XFASTINT (Vtool_bar_button_margin);
4866 else if (CONSP (Vtool_bar_button_margin))
4868 if (RANGED_INTEGERP (1, XCAR (Vtool_bar_button_margin), INT_MAX))
4869 hmargin = XFASTINT (XCAR (Vtool_bar_button_margin));
4871 if (RANGED_INTEGERP (1, XCDR (Vtool_bar_button_margin), INT_MAX))
4872 vmargin = XFASTINT (XCDR (Vtool_bar_button_margin));
4875 /* The natural size (i.e. when GTK uses 0 as margin) looks best,
4876 so take DEFAULT_TOOL_BAR_BUTTON_MARGIN to mean "default for GTK",
4877 i.e. zero. This means that margins less than
4878 DEFAULT_TOOL_BAR_BUTTON_MARGIN has no effect. */
4879 hmargin = max (0, hmargin - DEFAULT_TOOL_BAR_BUTTON_MARGIN);
4880 vmargin = max (0, vmargin - DEFAULT_TOOL_BAR_BUTTON_MARGIN);
4882 if (! x->toolbar_widget)
4883 xg_create_tool_bar (f);
4885 wtoolbar = GTK_TOOLBAR (x->toolbar_widget);
4886 dir = gtk_widget_get_direction (GTK_WIDGET (wtoolbar));
4888 style = Ftool_bar_get_system_style ();
4889 screen = gtk_widget_get_screen (GTK_WIDGET (wtoolbar));
4890 icon_theme = gtk_icon_theme_get_for_screen (screen);
4892 /* Are we up to date? */
4893 tbinfo = g_object_get_data (G_OBJECT (FRAME_GTK_OUTER_WIDGET (f)),
4894 TB_INFO_KEY);
4896 if (! NILP (tbinfo->last_tool_bar) && ! NILP (f->tool_bar_items)
4897 && tbinfo->n_last_items == f->n_tool_bar_items
4898 && tbinfo->hmargin == hmargin && tbinfo->vmargin == vmargin
4899 && tbinfo->dir == dir
4900 && ! NILP (Fequal (tbinfo->style, style))
4901 && ! NILP (Fequal (tbinfo->last_tool_bar, f->tool_bar_items)))
4903 unblock_input ();
4904 return;
4907 tbinfo->last_tool_bar = f->tool_bar_items;
4908 tbinfo->n_last_items = f->n_tool_bar_items;
4909 tbinfo->style = style;
4910 tbinfo->hmargin = hmargin;
4911 tbinfo->vmargin = vmargin;
4912 tbinfo->dir = dir;
4914 text_image = EQ (style, Qtext_image_horiz);
4915 horiz = EQ (style, Qboth_horiz) || text_image;
4917 for (i = j = 0; i < f->n_tool_bar_items; ++i)
4919 bool enabled_p = !NILP (PROP (TOOL_BAR_ITEM_ENABLED_P));
4920 bool selected_p = !NILP (PROP (TOOL_BAR_ITEM_SELECTED_P));
4921 int idx;
4922 ptrdiff_t img_id;
4923 int icon_size = 0;
4924 struct image *img = NULL;
4925 Lisp_Object image;
4926 Lisp_Object stock = Qnil;
4927 char *stock_name = NULL;
4928 char *icon_name = NULL;
4929 Lisp_Object rtl;
4930 GtkWidget *wbutton = NULL;
4931 Lisp_Object specified_file;
4932 bool vert_only = ! NILP (PROP (TOOL_BAR_ITEM_VERT_ONLY));
4933 const char *label
4934 = (EQ (style, Qimage) || (vert_only && horiz)) ? NULL
4935 : STRINGP (PROP (TOOL_BAR_ITEM_LABEL))
4936 ? SSDATA (PROP (TOOL_BAR_ITEM_LABEL))
4937 : "";
4939 ti = gtk_toolbar_get_nth_item (GTK_TOOLBAR (wtoolbar), j);
4941 /* If this is a separator, use a gtk separator item. */
4942 if (EQ (PROP (TOOL_BAR_ITEM_TYPE), Qt))
4944 if (ti == NULL || !GTK_IS_SEPARATOR_TOOL_ITEM (ti))
4946 if (ti)
4947 gtk_container_remove (GTK_CONTAINER (wtoolbar),
4948 GTK_WIDGET (ti));
4949 ti = gtk_separator_tool_item_new ();
4950 gtk_toolbar_insert (GTK_TOOLBAR (wtoolbar), ti, j);
4952 j++;
4953 continue;
4956 /* Otherwise, the tool-bar item is an ordinary button. */
4958 if (ti && GTK_IS_SEPARATOR_TOOL_ITEM (ti))
4960 gtk_container_remove (GTK_CONTAINER (wtoolbar), GTK_WIDGET (ti));
4961 ti = NULL;
4964 if (ti) wbutton = XG_BIN_CHILD (XG_BIN_CHILD (ti));
4966 /* Ignore invalid image specifications. */
4967 image = PROP (TOOL_BAR_ITEM_IMAGES);
4968 if (!valid_image_p (image))
4970 if (ti)
4971 gtk_container_remove (GTK_CONTAINER (wtoolbar),
4972 GTK_WIDGET (ti));
4973 continue;
4976 specified_file = file_for_image (image);
4977 if (!NILP (specified_file) && !NILP (Ffboundp (Qx_gtk_map_stock)))
4978 stock = call1 (Qx_gtk_map_stock, specified_file);
4980 if (CONSP (stock))
4982 Lisp_Object tem;
4983 for (tem = stock; CONSP (tem); tem = XCDR (tem))
4984 if (! NILP (tem) && STRINGP (XCAR (tem)))
4986 stock_name = find_icon_from_name (SSDATA (XCAR (tem)),
4987 icon_theme,
4988 &icon_name);
4989 if (stock_name || icon_name) break;
4992 else if (STRINGP (stock))
4994 stock_name = find_icon_from_name (SSDATA (stock),
4995 icon_theme,
4996 &icon_name);
4999 if (stock_name || icon_name)
5000 icon_size = gtk_toolbar_get_icon_size (wtoolbar);
5002 if (stock_name == NULL && icon_name == NULL)
5004 /* No stock image, or stock item not known. Try regular
5005 image. If image is a vector, choose it according to the
5006 button state. */
5007 if (dir == GTK_TEXT_DIR_RTL
5008 && !NILP (rtl = PROP (TOOL_BAR_ITEM_RTL_IMAGE))
5009 && STRINGP (rtl))
5010 image = find_rtl_image (f, image, rtl);
5012 if (VECTORP (image))
5014 if (enabled_p)
5015 idx = (selected_p
5016 ? TOOL_BAR_IMAGE_ENABLED_SELECTED
5017 : TOOL_BAR_IMAGE_ENABLED_DESELECTED);
5018 else
5019 idx = (selected_p
5020 ? TOOL_BAR_IMAGE_DISABLED_SELECTED
5021 : TOOL_BAR_IMAGE_DISABLED_DESELECTED);
5023 eassert (ASIZE (image) >= idx);
5024 image = AREF (image, idx);
5026 else
5027 idx = -1;
5029 img_id = lookup_image (f, image);
5030 img = IMAGE_FROM_ID (f, img_id);
5031 prepare_image_for_display (f, img);
5033 if (img->load_failed_p || img->pixmap == None)
5035 if (ti)
5036 gtk_container_remove (GTK_CONTAINER (wtoolbar),
5037 GTK_WIDGET (ti));
5038 continue;
5042 /* If there is an existing widget, check if it's stale; if so,
5043 remove it and make a new tool item from scratch. */
5044 if (ti && xg_tool_item_stale_p (wbutton, stock_name, icon_name,
5045 img, label, horiz))
5047 gtk_container_remove (GTK_CONTAINER (wtoolbar),
5048 GTK_WIDGET (ti));
5049 ti = NULL;
5052 if (ti == NULL)
5054 GtkWidget *w;
5056 /* Save the image so we can see if an update is needed the
5057 next time we call xg_tool_item_match_p. */
5058 if (EQ (style, Qtext))
5059 w = NULL;
5060 else if (stock_name)
5063 #if GTK_CHECK_VERSION (3, 10, 0)
5064 w = gtk_image_new_from_icon_name (stock_name, icon_size);
5065 #else
5066 w = gtk_image_new_from_stock (stock_name, icon_size);
5067 #endif
5068 g_object_set_data_full (G_OBJECT (w), XG_TOOL_BAR_STOCK_NAME,
5069 (gpointer) xstrdup (stock_name),
5070 (GDestroyNotify) xfree);
5072 else if (icon_name)
5074 w = gtk_image_new_from_icon_name (icon_name, icon_size);
5075 g_object_set_data_full (G_OBJECT (w), XG_TOOL_BAR_ICON_NAME,
5076 (gpointer) xstrdup (icon_name),
5077 (GDestroyNotify) xfree);
5079 else
5081 w = xg_get_image_for_pixmap (f, img, x->widget, NULL);
5082 g_object_set_data (G_OBJECT (w), XG_TOOL_BAR_IMAGE_DATA,
5083 (gpointer)img->pixmap);
5086 #if GTK_CHECK_VERSION (3, 14, 0)
5087 if (w)
5089 gtk_widget_set_margin_start (w, hmargin);
5090 gtk_widget_set_margin_end (w, hmargin);
5091 gtk_widget_set_margin_top (w, vmargin);
5092 gtk_widget_set_margin_bottom (w, vmargin);
5094 #else
5095 if (w) gtk_misc_set_padding (GTK_MISC (w), hmargin, vmargin);
5096 #endif
5097 ti = xg_make_tool_item (f, w, &wbutton, label, i, horiz, text_image);
5098 gtk_toolbar_insert (GTK_TOOLBAR (wtoolbar), ti, j);
5101 #undef PROP
5103 gtk_widget_set_sensitive (wbutton, enabled_p);
5104 j++;
5107 /* Remove buttons not longer needed. */
5110 ti = gtk_toolbar_get_nth_item (GTK_TOOLBAR (wtoolbar), j);
5111 if (ti)
5112 gtk_container_remove (GTK_CONTAINER (wtoolbar), GTK_WIDGET (ti));
5113 } while (ti != NULL);
5115 if (f->n_tool_bar_items != 0)
5117 if (! x->toolbar_is_packed)
5118 xg_pack_tool_bar (f, FRAME_TOOL_BAR_POSITION (f));
5119 gtk_widget_show_all (x->toolbar_widget);
5120 if (xg_update_tool_bar_sizes (f))
5122 int inhibit
5123 = ((f->after_make_frame
5124 && !f->tool_bar_resized
5125 && (EQ (frame_inhibit_implied_resize, Qt)
5126 || (CONSP (frame_inhibit_implied_resize)
5127 && !NILP (Fmemq (Qtool_bar_lines,
5128 frame_inhibit_implied_resize))))
5129 /* This will probably fail to DTRT in the
5130 fullheight/-width cases. */
5131 && NILP (get_frame_param (f, Qfullscreen)))
5133 : 2);
5135 frame_size_history_add (f, Qupdate_frame_tool_bar, 0, 0, Qnil);
5136 adjust_frame_size (f, -1, -1, inhibit, 0, Qtool_bar_lines);
5138 f->tool_bar_resized = f->tool_bar_redisplayed;
5141 unblock_input ();
5144 /* Deallocate all resources for the tool bar on frame F.
5145 Remove the tool bar. */
5147 void
5148 free_frame_tool_bar (struct frame *f)
5150 struct x_output *x = f->output_data.x;
5152 if (x->toolbar_widget)
5154 struct xg_frame_tb_info *tbinfo;
5155 GtkWidget *top_widget = x->toolbar_widget;
5157 block_input ();
5158 if (x->toolbar_is_packed)
5160 if (x->toolbar_in_hbox)
5161 gtk_container_remove (GTK_CONTAINER (x->hbox_widget),
5162 top_widget);
5163 else
5164 gtk_container_remove (GTK_CONTAINER (x->vbox_widget),
5165 top_widget);
5167 else
5168 gtk_widget_destroy (x->toolbar_widget);
5170 x->toolbar_widget = 0;
5171 x->toolbar_widget = 0;
5172 x->toolbar_is_packed = false;
5173 FRAME_TOOLBAR_TOP_HEIGHT (f) = FRAME_TOOLBAR_BOTTOM_HEIGHT (f) = 0;
5174 FRAME_TOOLBAR_LEFT_WIDTH (f) = FRAME_TOOLBAR_RIGHT_WIDTH (f) = 0;
5176 tbinfo = g_object_get_data (G_OBJECT (FRAME_GTK_OUTER_WIDGET (f)),
5177 TB_INFO_KEY);
5178 if (tbinfo)
5180 xfree (tbinfo);
5181 g_object_set_data (G_OBJECT (FRAME_GTK_OUTER_WIDGET (f)),
5182 TB_INFO_KEY,
5183 NULL);
5186 frame_size_history_add (f, Qfree_frame_tool_bar, 0, 0, Qnil);
5187 adjust_frame_size (f, -1, -1, 2, 0, Qtool_bar_lines);
5189 unblock_input ();
5193 void
5194 xg_change_toolbar_position (struct frame *f, Lisp_Object pos)
5196 struct x_output *x = f->output_data.x;
5197 GtkWidget *top_widget = x->toolbar_widget;
5199 if (! x->toolbar_widget || ! top_widget)
5200 return;
5202 block_input ();
5203 g_object_ref (top_widget);
5204 if (x->toolbar_is_packed)
5206 if (x->toolbar_in_hbox)
5207 gtk_container_remove (GTK_CONTAINER (x->hbox_widget),
5208 top_widget);
5209 else
5210 gtk_container_remove (GTK_CONTAINER (x->vbox_widget),
5211 top_widget);
5214 xg_pack_tool_bar (f, pos);
5215 g_object_unref (top_widget);
5217 if (xg_update_tool_bar_sizes (f))
5219 frame_size_history_add (f, Qxg_change_toolbar_position, 0, 0, Qnil);
5220 adjust_frame_size (f, -1, -1, 2, 0, Qtool_bar_lines);
5224 unblock_input ();
5229 /***********************************************************************
5230 Initializing
5231 ***********************************************************************/
5232 void
5233 xg_initialize (void)
5235 GtkBindingSet *binding_set;
5236 GtkSettings *settings;
5238 #if HAVE_XFT
5239 /* Work around a bug with corrupted data if libXft gets unloaded. This way
5240 we keep it permanently linked in. */
5241 XftInit (0);
5242 #endif
5244 gdpy_def = NULL;
5245 xg_ignore_gtk_scrollbar = 0;
5246 xg_menu_cb_list.prev = xg_menu_cb_list.next =
5247 xg_menu_item_cb_list.prev = xg_menu_item_cb_list.next = 0;
5249 id_to_widget.max_size = id_to_widget.used = 0;
5250 id_to_widget.widgets = 0;
5252 settings = gtk_settings_get_for_screen (gdk_display_get_default_screen
5253 (gdk_display_get_default ()));
5254 #if ! GTK_CHECK_VERSION (3, 10, 0)
5255 /* Remove F10 as a menu accelerator, it does not mix well with Emacs key
5256 bindings. It doesn't seem to be any way to remove properties,
5257 so we set it to "" which in means "no key". */
5258 gtk_settings_set_string_property (settings,
5259 "gtk-menu-bar-accel",
5261 EMACS_CLASS);
5262 #endif
5264 /* Make GTK text input widgets use Emacs style keybindings. This is
5265 Emacs after all. */
5266 #if GTK_CHECK_VERSION (3, 16, 0)
5267 g_object_set (settings, "gtk-key-theme-name", "Emacs", NULL);
5268 #else
5269 gtk_settings_set_string_property (settings,
5270 "gtk-key-theme-name",
5271 "Emacs",
5272 EMACS_CLASS);
5273 #endif
5275 /* Make dialogs close on C-g. Since file dialog inherits from
5276 dialog, this works for them also. */
5277 binding_set = gtk_binding_set_by_class (g_type_class_ref (GTK_TYPE_DIALOG));
5278 gtk_binding_entry_add_signal (binding_set, GDK_KEY_g, GDK_CONTROL_MASK,
5279 "close", 0);
5281 /* Make menus close on C-g. */
5282 binding_set = gtk_binding_set_by_class (g_type_class_ref
5283 (GTK_TYPE_MENU_SHELL));
5284 gtk_binding_entry_add_signal (binding_set, GDK_KEY_g, GDK_CONTROL_MASK,
5285 "cancel", 0);
5286 update_theme_scrollbar_width ();
5287 update_theme_scrollbar_height ();
5289 #ifdef HAVE_FREETYPE
5290 x_last_font_name = NULL;
5291 #endif
5294 #endif /* USE_GTK */