`nreverse' Grep hits before passing them to xref--convert-hits
[emacs.git] / src / gtkutil.c
blobe791e6ac317152804cdfa48c6db36e20ae0f4adc
1 /* Functions for creating and updating GTK widgets.
3 Copyright (C) 2003-2016 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 <http://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 #ifndef HAVE_GTK_WIDGET_SET_HAS_WINDOW
52 #define gtk_widget_set_has_window(w, b) \
53 (gtk_fixed_set_has_window (GTK_FIXED (w), b))
54 #endif
55 #ifndef HAVE_GTK_DIALOG_GET_ACTION_AREA
56 #define gtk_dialog_get_action_area(w) ((w)->action_area)
57 #define gtk_dialog_get_content_area(w) ((w)->vbox)
58 #endif
59 #ifndef HAVE_GTK_WIDGET_GET_SENSITIVE
60 #define gtk_widget_get_sensitive(w) (GTK_WIDGET_SENSITIVE (w))
61 #endif
62 #ifndef HAVE_GTK_ADJUSTMENT_GET_PAGE_SIZE
63 #define gtk_adjustment_set_page_size(w, s) ((w)->page_size = (s))
64 #define gtk_adjustment_set_page_increment(w, s) ((w)->page_increment = (s))
65 #define gtk_adjustment_get_step_increment(w) ((w)->step_increment)
66 #define gtk_adjustment_set_step_increment(w, s) ((w)->step_increment = (s))
67 #endif
68 #if GTK_CHECK_VERSION (2, 12, 0)
69 #define remove_submenu(w) gtk_menu_item_set_submenu ((w), NULL)
70 #else
71 #define remove_submenu(w) gtk_menu_item_remove_submenu ((w))
72 #endif
74 #if ! GTK_CHECK_VERSION (2, 14, 0)
75 #define gtk_adjustment_configure(adj, xvalue, xlower, \
76 xupper, xstep_increment, \
77 xpage_increment, xpagesize) \
78 do { \
79 adj->lower = xlower; \
80 adj->upper = xupper; \
81 adj->page_size = xpagesize; \
82 gtk_adjustment_set_value (adj, xvalue); \
83 adj->page_increment = xpage_increment; \
84 adj->step_increment = xstep_increment; \
85 } while (0)
86 #endif /* < Gtk+ 2.14 */
88 #ifdef HAVE_FREETYPE
89 #if GTK_CHECK_VERSION (3, 2, 0)
90 #define USE_NEW_GTK_FONT_CHOOSER 1
91 #else
92 #define USE_NEW_GTK_FONT_CHOOSER 0
93 #define gtk_font_chooser_dialog_new(x, y) \
94 gtk_font_selection_dialog_new (x)
95 #undef GTK_FONT_CHOOSER
96 #define GTK_FONT_CHOOSER(x) GTK_FONT_SELECTION_DIALOG (x)
97 #define gtk_font_chooser_set_font(x, y) \
98 gtk_font_selection_dialog_set_font_name (x, y)
99 #endif
100 #endif /* HAVE_FREETYPE */
102 #if GTK_CHECK_VERSION (3, 10, 0)
103 #define XG_TEXT_CANCEL "Cancel"
104 #define XG_TEXT_OK "OK"
105 #define XG_TEXT_OPEN "Open"
106 #else
107 #define XG_TEXT_CANCEL GTK_STOCK_CANCEL
108 #define XG_TEXT_OK GTK_STOCK_OK
109 #define XG_TEXT_OPEN GTK_STOCK_OPEN
110 #endif
112 #ifndef HAVE_GTK3
113 #ifdef USE_GTK_TOOLTIP
114 #define gdk_window_get_screen(w) gdk_drawable_get_screen (w)
115 #endif
116 #define gdk_window_get_geometry(w, a, b, c, d) \
117 gdk_window_get_geometry (w, a, b, c, d, 0)
118 #define gdk_x11_window_lookup_for_display(d, w) \
119 gdk_xid_table_lookup_for_display (d, w)
120 #define gtk_box_new(ori, spacing) \
121 ((ori) == GTK_ORIENTATION_HORIZONTAL \
122 ? gtk_hbox_new (FALSE, (spacing)) : gtk_vbox_new (FALSE, (spacing)))
123 #define gtk_scrollbar_new(ori, spacing) \
124 ((ori) == GTK_ORIENTATION_HORIZONTAL \
125 ? gtk_hscrollbar_new ((spacing)) : gtk_vscrollbar_new ((spacing)))
126 #ifndef GDK_KEY_g
127 #define GDK_KEY_g GDK_g
128 #endif
129 #endif /* HAVE_GTK3 */
131 #define XG_BIN_CHILD(x) gtk_bin_get_child (GTK_BIN (x))
133 static void update_theme_scrollbar_width (void);
134 static void update_theme_scrollbar_height (void);
136 #define TB_INFO_KEY "xg_frame_tb_info"
137 struct xg_frame_tb_info
139 Lisp_Object last_tool_bar;
140 Lisp_Object style;
141 int n_last_items;
142 int hmargin, vmargin;
143 GtkTextDirection dir;
147 /***********************************************************************
148 Display handling functions
149 ***********************************************************************/
151 /* Keep track of the default display, or NULL if there is none. Emacs
152 may close all its displays. */
154 static GdkDisplay *gdpy_def;
156 /* When the GTK widget W is to be created on a display for F that
157 is not the default display, set the display for W.
158 W can be a GtkMenu or a GtkWindow widget. */
160 static void
161 xg_set_screen (GtkWidget *w, struct frame *f)
163 if (FRAME_X_DISPLAY (f) != DEFAULT_GDK_DISPLAY ())
165 GdkDisplay *gdpy = gdk_x11_lookup_xdisplay (FRAME_X_DISPLAY (f));
166 GdkScreen *gscreen = gdk_display_get_default_screen (gdpy);
168 if (GTK_IS_MENU (w))
169 gtk_menu_set_screen (GTK_MENU (w), gscreen);
170 else
171 gtk_window_set_screen (GTK_WINDOW (w), gscreen);
176 /* Open a display named by DISPLAY_NAME. The display is returned in *DPY.
177 *DPY is set to NULL if the display can't be opened.
179 Returns non-zero if display could be opened, zero if display could not
180 be opened, and less than zero if the GTK version doesn't support
181 multiple displays. */
183 void
184 xg_display_open (char *display_name, Display **dpy)
186 GdkDisplay *gdpy;
188 unrequest_sigio (); // See comment in x_display_ok, xterm.c.
189 gdpy = gdk_display_open (display_name);
190 request_sigio ();
191 if (!gdpy_def && gdpy)
193 gdpy_def = gdpy;
194 gdk_display_manager_set_default_display (gdk_display_manager_get (),
195 gdpy);
198 *dpy = gdpy ? GDK_DISPLAY_XDISPLAY (gdpy) : NULL;
202 /* Close display DPY. */
204 void
205 xg_display_close (Display *dpy)
207 GdkDisplay *gdpy = gdk_x11_lookup_xdisplay (dpy);
209 /* If this is the default display, try to change it before closing.
210 If there is no other display to use, gdpy_def is set to NULL, and
211 the next call to xg_display_open resets the default display. */
212 if (gdk_display_get_default () == gdpy)
214 struct x_display_info *dpyinfo;
215 GdkDisplay *gdpy_new = NULL;
217 /* Find another display. */
218 for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
219 if (dpyinfo->display != dpy)
221 gdpy_new = gdk_x11_lookup_xdisplay (dpyinfo->display);
222 gdk_display_manager_set_default_display (gdk_display_manager_get (),
223 gdpy_new);
224 break;
226 gdpy_def = gdpy_new;
229 #if GTK_CHECK_VERSION (2, 0, 0) && ! GTK_CHECK_VERSION (2, 10, 0)
230 /* GTK 2.2-2.8 has a bug that makes gdk_display_close crash (bug
231 http://bugzilla.gnome.org/show_bug.cgi?id=85715). This way we
232 can continue running, but there will be memory leaks. */
233 g_object_run_dispose (G_OBJECT (gdpy));
234 #else
235 /* This seems to be fixed in GTK 2.10. */
236 gdk_display_close (gdpy);
237 #endif
241 /***********************************************************************
242 Utility functions
243 ***********************************************************************/
245 /* Create and return the cursor to be used for popup menus and
246 scroll bars on display DPY. */
248 GdkCursor *
249 xg_create_default_cursor (Display *dpy)
251 GdkDisplay *gdpy = gdk_x11_lookup_xdisplay (dpy);
252 return gdk_cursor_new_for_display (gdpy, GDK_LEFT_PTR);
255 /* Apply GMASK to GPIX and return a GdkPixbuf with an alpha channel. */
257 static GdkPixbuf *
258 xg_get_pixbuf_from_pix_and_mask (struct frame *f,
259 Pixmap pix,
260 Pixmap mask)
262 GdkPixbuf *icon_buf = 0;
263 int iunused;
264 Window wunused;
265 unsigned int width, height, depth, uunused;
267 if (FRAME_DISPLAY_INFO (f)->red_bits != 8)
268 return 0;
269 XGetGeometry (FRAME_X_DISPLAY (f), pix, &wunused, &iunused, &iunused,
270 &width, &height, &uunused, &depth);
271 if (depth != 24)
272 return 0;
273 XImage *xim = XGetImage (FRAME_X_DISPLAY (f), pix, 0, 0, width, height,
274 ~0, XYPixmap);
275 if (xim)
277 XImage *xmm = (! mask ? 0
278 : XGetImage (FRAME_X_DISPLAY (f), mask, 0, 0,
279 width, height, ~0, XYPixmap));
280 icon_buf = gdk_pixbuf_new (GDK_COLORSPACE_RGB, TRUE, 8, width, height);
281 if (icon_buf)
283 guchar *pixels = gdk_pixbuf_get_pixels (icon_buf);
284 int rowjunkwidth = gdk_pixbuf_get_rowstride (icon_buf) - width * 4;
285 for (int y = 0; y < height; y++, pixels += rowjunkwidth)
286 for (int x = 0; x < width; x++)
288 unsigned long rgb = XGetPixel (xim, x, y);
289 *pixels++ = (rgb >> 16) & 255;
290 *pixels++ = (rgb >> 8) & 255;
291 *pixels++ = rgb & 255;
292 *pixels++ = xmm && !XGetPixel (xmm, x, y) ? 0 : 255;
296 if (xmm)
297 XDestroyImage (xmm);
298 XDestroyImage (xim);
301 return icon_buf;
304 static Lisp_Object
305 file_for_image (Lisp_Object image)
307 Lisp_Object specified_file = Qnil;
308 Lisp_Object tail;
310 for (tail = XCDR (image);
311 NILP (specified_file) && CONSP (tail) && CONSP (XCDR (tail));
312 tail = XCDR (XCDR (tail)))
313 if (EQ (XCAR (tail), QCfile))
314 specified_file = XCAR (XCDR (tail));
316 return specified_file;
319 /* For the image defined in IMG, make and return a GtkImage. For displays with
320 8 planes or less we must make a GdkPixbuf and apply the mask manually.
321 Otherwise the highlighting and dimming the tool bar code in GTK does
322 will look bad. For display with more than 8 planes we just use the
323 pixmap and mask directly. For monochrome displays, GTK doesn't seem
324 able to use external pixmaps, it looks bad whatever we do.
325 The image is defined on the display where frame F is.
326 WIDGET is used to find the GdkColormap to use for the GdkPixbuf.
327 If OLD_WIDGET is NULL, a new widget is constructed and returned.
328 If OLD_WIDGET is not NULL, that widget is modified. */
330 static GtkWidget *
331 xg_get_image_for_pixmap (struct frame *f,
332 struct image *img,
333 GtkWidget *widget,
334 GtkImage *old_widget)
336 GdkPixbuf *icon_buf;
338 /* If we have a file, let GTK do all the image handling.
339 This seems to be the only way to make insensitive and activated icons
340 look good in all cases. */
341 Lisp_Object specified_file = file_for_image (img->spec);
342 Lisp_Object file;
344 /* We already loaded the image once before calling this
345 function, so this only fails if the image file has been removed.
346 In that case, use the pixmap already loaded. */
348 if (STRINGP (specified_file)
349 && STRINGP (file = x_find_image_file (specified_file)))
351 char *encoded_file = SSDATA (ENCODE_FILE (file));
352 if (! old_widget)
353 old_widget = GTK_IMAGE (gtk_image_new_from_file (encoded_file));
354 else
355 gtk_image_set_from_file (old_widget, encoded_file);
357 return GTK_WIDGET (old_widget);
360 /* No file, do the image handling ourselves. This will look very bad
361 on a monochrome display, and sometimes bad on all displays with
362 certain themes. */
364 /* This is a workaround to make icons look good on pseudo color
365 displays. Apparently GTK expects the images to have an alpha
366 channel. If they don't, insensitive and activated icons will
367 look bad. This workaround does not work on monochrome displays,
368 and is strictly not needed on true color/static color displays (i.e.
369 16 bits and higher). But we do it anyway so we get a pixbuf that is
370 not associated with the img->pixmap. The img->pixmap may be removed
371 by clearing the image cache and then the tool bar redraw fails, since
372 Gtk+ assumes the pixmap is always there. */
373 icon_buf = xg_get_pixbuf_from_pix_and_mask (f, img->pixmap, img->mask);
375 if (icon_buf)
377 if (! old_widget)
378 old_widget = GTK_IMAGE (gtk_image_new_from_pixbuf (icon_buf));
379 else
380 gtk_image_set_from_pixbuf (old_widget, icon_buf);
382 g_object_unref (G_OBJECT (icon_buf));
385 return GTK_WIDGET (old_widget);
389 /* Set CURSOR on W and all widgets W contain. We must do like this
390 for scroll bars and menu because they create widgets internally,
391 and it is those widgets that are visible. */
393 static void
394 xg_set_cursor (GtkWidget *w, GdkCursor *cursor)
396 GdkWindow *window = gtk_widget_get_window (w);
397 GList *children = gdk_window_peek_children (window);
399 gdk_window_set_cursor (window, cursor);
401 /* The scroll bar widget has more than one GDK window (had to look at
402 the source to figure this out), and there is no way to set cursor
403 on widgets in GTK. So we must set the cursor for all GDK windows.
404 Ditto for menus. */
406 for ( ; children; children = g_list_next (children))
407 gdk_window_set_cursor (GDK_WINDOW (children->data), cursor);
410 /* Insert NODE into linked LIST. */
412 static void
413 xg_list_insert (xg_list_node *list, xg_list_node *node)
415 xg_list_node *list_start = list->next;
417 if (list_start) list_start->prev = node;
418 node->next = list_start;
419 node->prev = 0;
420 list->next = node;
423 /* Remove NODE from linked LIST. */
425 static void
426 xg_list_remove (xg_list_node *list, xg_list_node *node)
428 xg_list_node *list_start = list->next;
429 if (node == list_start)
431 list->next = node->next;
432 if (list->next) list->next->prev = 0;
434 else
436 node->prev->next = node->next;
437 if (node->next) node->next->prev = node->prev;
441 /* Allocate and return a utf8 version of STR. If STR is already
442 utf8 or NULL, just return a copy of STR.
443 A new string is allocated and the caller must free the result
444 with g_free. */
446 static char *
447 get_utf8_string (const char *str)
449 char *utf8_str;
451 if (!str) return NULL;
453 /* If not UTF-8, try current locale. */
454 if (!g_utf8_validate (str, -1, NULL))
455 utf8_str = g_locale_to_utf8 (str, -1, 0, 0, 0);
456 else
457 return g_strdup (str);
459 if (!utf8_str)
461 /* Probably some control characters in str. Escape them. */
462 ptrdiff_t len;
463 ptrdiff_t nr_bad = 0;
464 gsize bytes_read;
465 gsize bytes_written;
466 unsigned char *p = (unsigned char *)str;
467 char *cp, *up;
468 GError *err = NULL;
470 while (! (cp = g_locale_to_utf8 ((char *)p, -1, &bytes_read,
471 &bytes_written, &err))
472 && err->code == G_CONVERT_ERROR_ILLEGAL_SEQUENCE)
474 ++nr_bad;
475 p += bytes_written+1;
476 g_error_free (err);
477 err = NULL;
480 if (err)
482 g_error_free (err);
483 err = NULL;
485 if (cp) g_free (cp);
487 len = strlen (str);
488 ptrdiff_t alloc;
489 if (INT_MULTIPLY_WRAPV (nr_bad, 4, &alloc)
490 || INT_ADD_WRAPV (len + 1, alloc, &alloc)
491 || SIZE_MAX < alloc)
492 memory_full (SIZE_MAX);
493 up = utf8_str = xmalloc (alloc);
494 p = (unsigned char *)str;
496 while (! (cp = g_locale_to_utf8 ((char *)p, -1, &bytes_read,
497 &bytes_written, &err))
498 && err->code == G_CONVERT_ERROR_ILLEGAL_SEQUENCE)
500 memcpy (up, p, bytes_written);
501 up += bytes_written;
502 up += sprintf (up, "\\%03o", p[bytes_written]);
503 p += bytes_written + 1;
504 g_error_free (err);
505 err = NULL;
508 if (cp)
510 strcpy (up, cp);
511 g_free (cp);
513 if (err)
515 g_error_free (err);
516 err = NULL;
519 return utf8_str;
522 /* Check for special colors used in face spec for region face.
523 The colors are fetched from the Gtk+ theme.
524 Return true if color was found, false if not. */
526 bool
527 xg_check_special_colors (struct frame *f,
528 const char *color_name,
529 XColor *color)
531 bool success_p = 0;
532 bool get_bg = strcmp ("gtk_selection_bg_color", color_name) == 0;
533 bool get_fg = !get_bg && strcmp ("gtk_selection_fg_color", color_name) == 0;
535 if (! FRAME_GTK_WIDGET (f) || ! (get_bg || get_fg))
536 return success_p;
538 block_input ();
540 #ifdef HAVE_GTK3
541 GtkStyleContext *gsty
542 = gtk_widget_get_style_context (FRAME_GTK_OUTER_WIDGET (f));
543 GdkRGBA col;
544 char buf[sizeof "rgb://rrrr/gggg/bbbb"];
545 int state = GTK_STATE_FLAG_SELECTED|GTK_STATE_FLAG_FOCUSED;
546 if (get_fg)
547 gtk_style_context_get_color (gsty, state, &col);
548 else
549 gtk_style_context_get_background_color (gsty, state, &col);
551 sprintf (buf, "rgb:%04x/%04x/%04x",
552 (unsigned) (col.red * 65535),
553 (unsigned) (col.green * 65535),
554 (unsigned) (col.blue * 65535));
555 success_p = x_parse_color (f, buf, color) != 0;
556 #else
557 GtkStyle *gsty = gtk_widget_get_style (FRAME_GTK_WIDGET (f));
558 GdkColor *grgb = get_bg
559 ? &gsty->bg[GTK_STATE_SELECTED]
560 : &gsty->fg[GTK_STATE_SELECTED];
562 color->red = grgb->red;
563 color->green = grgb->green;
564 color->blue = grgb->blue;
565 color->pixel = grgb->pixel;
566 success_p = 1;
567 #endif
570 unblock_input ();
571 return success_p;
576 /***********************************************************************
577 Tooltips
578 ***********************************************************************/
579 /* Gtk+ calls this callback when the parent of our tooltip dummy changes.
580 We use that to pop down the tooltip. This happens if Gtk+ for some
581 reason wants to change or hide the tooltip. */
583 #ifdef USE_GTK_TOOLTIP
585 static void
586 hierarchy_ch_cb (GtkWidget *widget,
587 GtkWidget *previous_toplevel,
588 gpointer user_data)
590 struct frame *f = user_data;
591 struct x_output *x = f->output_data.x;
592 GtkWidget *top = gtk_widget_get_toplevel (x->ttip_lbl);
594 if (! top || ! GTK_IS_WINDOW (top))
595 gtk_widget_hide (previous_toplevel);
598 /* Callback called when Gtk+ thinks a tooltip should be displayed.
599 We use it to get the tooltip window and the tooltip widget so
600 we can manipulate the ourselves.
602 Return FALSE ensures that the tooltip is not shown. */
604 static gboolean
605 qttip_cb (GtkWidget *widget,
606 gint xpos,
607 gint ypos,
608 gboolean keyboard_mode,
609 GtkTooltip *tooltip,
610 gpointer user_data)
612 struct frame *f = user_data;
613 struct x_output *x = f->output_data.x;
614 if (x->ttip_widget == NULL)
616 GtkWidget *p;
617 GList *list, *iter;
619 g_object_set (G_OBJECT (widget), "has-tooltip", FALSE, NULL);
620 x->ttip_widget = tooltip;
621 g_object_ref (G_OBJECT (tooltip));
622 x->ttip_lbl = gtk_label_new ("");
623 g_object_ref (G_OBJECT (x->ttip_lbl));
624 gtk_tooltip_set_custom (tooltip, x->ttip_lbl);
625 x->ttip_window = GTK_WINDOW (gtk_widget_get_toplevel (x->ttip_lbl));
627 /* Change stupid Gtk+ default line wrapping. */
628 p = gtk_widget_get_parent (x->ttip_lbl);
629 list = gtk_container_get_children (GTK_CONTAINER (p));
630 for (iter = list; iter; iter = g_list_next (iter))
632 GtkWidget *w = GTK_WIDGET (iter->data);
633 if (GTK_IS_LABEL (w))
634 gtk_label_set_line_wrap (GTK_LABEL (w), FALSE);
636 g_list_free (list);
638 /* ATK needs an empty title for some reason. */
639 gtk_window_set_title (x->ttip_window, "");
640 /* Realize so we can safely get screen later on. */
641 gtk_widget_realize (GTK_WIDGET (x->ttip_window));
642 gtk_widget_realize (x->ttip_lbl);
644 g_signal_connect (x->ttip_lbl, "hierarchy-changed",
645 G_CALLBACK (hierarchy_ch_cb), f);
647 return FALSE;
650 #endif /* USE_GTK_TOOLTIP */
652 /* Prepare a tooltip to be shown, i.e. calculate WIDTH and HEIGHT.
653 Return true if a system tooltip is available. */
655 bool
656 xg_prepare_tooltip (struct frame *f,
657 Lisp_Object string,
658 int *width,
659 int *height)
661 #ifndef USE_GTK_TOOLTIP
662 return 0;
663 #else
664 struct x_output *x = f->output_data.x;
665 GtkWidget *widget;
666 GdkWindow *gwin;
667 GdkScreen *screen;
668 GtkSettings *settings;
669 gboolean tt_enabled = TRUE;
670 GtkRequisition req;
671 Lisp_Object encoded_string;
673 if (!x->ttip_lbl) return 0;
675 block_input ();
676 encoded_string = ENCODE_UTF_8 (string);
677 widget = GTK_WIDGET (x->ttip_lbl);
678 gwin = gtk_widget_get_window (GTK_WIDGET (x->ttip_window));
679 screen = gdk_window_get_screen (gwin);
680 settings = gtk_settings_get_for_screen (screen);
681 g_object_get (settings, "gtk-enable-tooltips", &tt_enabled, NULL);
682 if (tt_enabled)
684 g_object_set (settings, "gtk-enable-tooltips", FALSE, NULL);
685 /* Record that we disabled it so it can be enabled again. */
686 g_object_set_data (G_OBJECT (x->ttip_window), "restore-tt",
687 (gpointer)f);
690 /* Prevent Gtk+ from hiding tooltip on mouse move and such. */
691 g_object_set_data (G_OBJECT
692 (gtk_widget_get_display (GTK_WIDGET (x->ttip_window))),
693 "gdk-display-current-tooltip", NULL);
695 /* Put our dummy widget in so we can get callbacks for unrealize and
696 hierarchy-changed. */
697 gtk_tooltip_set_custom (x->ttip_widget, widget);
698 gtk_tooltip_set_text (x->ttip_widget, SSDATA (encoded_string));
699 gtk_widget_get_preferred_size (GTK_WIDGET (x->ttip_window), NULL, &req);
700 if (width) *width = req.width;
701 if (height) *height = req.height;
703 unblock_input ();
705 return 1;
706 #endif /* USE_GTK_TOOLTIP */
709 /* Show the tooltip at ROOT_X and ROOT_Y.
710 xg_prepare_tooltip must have been called before this function. */
712 void
713 xg_show_tooltip (struct frame *f, int root_x, int root_y)
715 #ifdef USE_GTK_TOOLTIP
716 struct x_output *x = f->output_data.x;
717 if (x->ttip_window)
719 block_input ();
720 gtk_window_move (x->ttip_window, root_x, root_y);
721 gtk_widget_show_all (GTK_WIDGET (x->ttip_window));
722 unblock_input ();
724 #endif
727 /* Hide tooltip if shown. Do nothing if not shown.
728 Return true if tip was hidden, false if not (i.e. not using
729 system tooltips). */
731 bool
732 xg_hide_tooltip (struct frame *f)
734 bool ret = 0;
735 #ifdef USE_GTK_TOOLTIP
736 if (f->output_data.x->ttip_window)
738 GtkWindow *win = f->output_data.x->ttip_window;
739 block_input ();
740 gtk_widget_hide (GTK_WIDGET (win));
742 if (g_object_get_data (G_OBJECT (win), "restore-tt"))
744 GdkWindow *gwin = gtk_widget_get_window (GTK_WIDGET (win));
745 GdkScreen *screen = gdk_window_get_screen (gwin);
746 GtkSettings *settings = gtk_settings_get_for_screen (screen);
747 g_object_set (settings, "gtk-enable-tooltips", TRUE, NULL);
749 unblock_input ();
751 ret = 1;
753 #endif
754 return ret;
758 /***********************************************************************
759 General functions for creating widgets, resizing, events, e.t.c.
760 ***********************************************************************/
762 static void
763 my_log_handler (const gchar *log_domain, GLogLevelFlags log_level,
764 const gchar *msg, gpointer user_data)
766 if (!strstr (msg, "visible children"))
767 fprintf (stderr, "XX %s-WARNING **: %s\n", log_domain, msg);
770 /* Make a geometry string and pass that to GTK. It seems this is the
771 only way to get geometry position right if the user explicitly
772 asked for a position when starting Emacs.
773 F is the frame we shall set geometry for. */
775 static void
776 xg_set_geometry (struct frame *f)
778 if (f->size_hint_flags & (USPosition | PPosition))
780 int left = f->left_pos;
781 int xneg = f->size_hint_flags & XNegative;
782 int top = f->top_pos;
783 int yneg = f->size_hint_flags & YNegative;
784 char geom_str[sizeof "=x--" + 4 * INT_STRLEN_BOUND (int)];
785 guint id;
787 if (xneg)
788 left = -left;
789 if (yneg)
790 top = -top;
792 sprintf (geom_str, "=%dx%d%c%d%c%d",
793 FRAME_PIXEL_WIDTH (f),
794 FRAME_PIXEL_HEIGHT (f),
795 (xneg ? '-' : '+'), left,
796 (yneg ? '-' : '+'), top);
798 /* Silence warning about visible children. */
799 id = g_log_set_handler ("Gtk", G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
800 | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
802 if (!gtk_window_parse_geometry (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)),
803 geom_str))
804 fprintf (stderr, "Failed to parse: '%s'\n", geom_str);
806 g_log_remove_handler ("Gtk", id);
810 /* Clear under internal border if any. As we use a mix of Gtk+ and X calls
811 and use a GtkFixed widget, this doesn't happen automatically. */
813 void
814 xg_clear_under_internal_border (struct frame *f)
816 if (FRAME_INTERNAL_BORDER_WIDTH (f) > 0)
818 #ifndef USE_CAIRO
819 GtkWidget *wfixed = f->output_data.x->edit_widget;
821 gtk_widget_queue_draw (wfixed);
822 gdk_window_process_all_updates ();
823 #endif
824 x_clear_area (f, 0, 0,
825 FRAME_PIXEL_WIDTH (f), FRAME_INTERNAL_BORDER_WIDTH (f));
827 x_clear_area (f, 0, 0,
828 FRAME_INTERNAL_BORDER_WIDTH (f), FRAME_PIXEL_HEIGHT (f));
830 x_clear_area (f, 0,
831 FRAME_PIXEL_HEIGHT (f) - FRAME_INTERNAL_BORDER_WIDTH (f),
832 FRAME_PIXEL_WIDTH (f), FRAME_INTERNAL_BORDER_WIDTH (f));
834 x_clear_area (f,
835 FRAME_PIXEL_WIDTH (f) - FRAME_INTERNAL_BORDER_WIDTH (f),
836 0, FRAME_INTERNAL_BORDER_WIDTH (f), FRAME_PIXEL_HEIGHT (f));
840 static int
841 xg_get_gdk_scale (void)
843 const char *sscale = getenv ("GDK_SCALE");
845 if (sscale)
847 long scale = atol (sscale);
848 if (0 < scale)
849 return min (scale, INT_MAX);
852 return 1;
855 /* Function to handle resize of our frame. As we have a Gtk+ tool bar
856 and a Gtk+ menu bar, we get resize events for the edit part of the
857 frame only. We let Gtk+ deal with the Gtk+ parts.
858 F is the frame to resize.
859 PIXELWIDTH, PIXELHEIGHT is the new size in pixels. */
861 void
862 xg_frame_resized (struct frame *f, int pixelwidth, int pixelheight)
864 int width, height;
866 if (pixelwidth == -1 && pixelheight == -1)
868 if (FRAME_GTK_WIDGET (f) && gtk_widget_get_mapped (FRAME_GTK_WIDGET (f)))
869 gdk_window_get_geometry (gtk_widget_get_window (FRAME_GTK_WIDGET (f)),
870 0, 0, &pixelwidth, &pixelheight);
871 else
872 return;
875 width = FRAME_PIXEL_TO_TEXT_WIDTH (f, pixelwidth);
876 height = FRAME_PIXEL_TO_TEXT_HEIGHT (f, pixelheight);
878 frame_size_history_add
879 (f, Qxg_frame_resized, width, height, Qnil);
881 if (width != FRAME_TEXT_WIDTH (f)
882 || height != FRAME_TEXT_HEIGHT (f)
883 || pixelwidth != FRAME_PIXEL_WIDTH (f)
884 || pixelheight != FRAME_PIXEL_HEIGHT (f))
886 xg_clear_under_internal_border (f);
887 change_frame_size (f, width, height, 0, 1, 0, 1);
888 SET_FRAME_GARBAGED (f);
889 cancel_mouse_face (f);
893 /* Resize the outer window of frame F after changing the height.
894 COLUMNS/ROWS is the size the edit area shall have after the resize. */
896 void
897 xg_frame_set_char_size (struct frame *f, int width, int height)
899 int pixelwidth = FRAME_TEXT_TO_PIXEL_WIDTH (f, width);
900 int pixelheight = FRAME_TEXT_TO_PIXEL_HEIGHT (f, height);
901 Lisp_Object fullscreen = get_frame_param (f, Qfullscreen);
902 gint gwidth, gheight;
903 int totalheight
904 = pixelheight + FRAME_TOOLBAR_HEIGHT (f) + FRAME_MENUBAR_HEIGHT (f);
905 int totalwidth = pixelwidth + FRAME_TOOLBAR_WIDTH (f);
907 if (FRAME_PIXEL_HEIGHT (f) == 0)
908 return;
910 gtk_window_get_size (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)),
911 &gwidth, &gheight);
913 /* Do this before resize, as we don't know yet if we will be resized. */
914 xg_clear_under_internal_border (f);
916 if (FRAME_VISIBLE_P (f))
918 int scale = xg_get_gdk_scale ();
919 totalheight /= scale;
920 totalwidth /= scale;
923 x_wm_set_size_hint (f, 0, 0);
925 /* Resize the top level widget so rows and columns remain constant.
927 When the frame is fullheight and we only want to change the width
928 or it is fullwidth and we only want to change the height we should
929 be able to preserve the fullscreen property. However, due to the
930 fact that we have to send a resize request anyway, the window
931 manager will abolish it. At least the respective size should
932 remain unchanged but giving the frame back its normal size will
933 be broken ... */
934 if (EQ (fullscreen, Qfullwidth) && width == FRAME_TEXT_WIDTH (f))
936 frame_size_history_add
937 (f, Qxg_frame_set_char_size_1, width, height,
938 list2 (make_number (gheight), make_number (totalheight)));
940 gtk_window_resize (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)),
941 gwidth, totalheight);
943 else if (EQ (fullscreen, Qfullheight) && height == FRAME_TEXT_HEIGHT (f))
945 frame_size_history_add
946 (f, Qxg_frame_set_char_size_2, width, height,
947 list2 (make_number (gwidth), make_number (totalwidth)));
949 gtk_window_resize (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)),
950 totalwidth, gheight);
952 else
954 frame_size_history_add
955 (f, Qxg_frame_set_char_size_3, width, height,
956 list2 (make_number (totalwidth), make_number (totalheight)));
958 gtk_window_resize (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)),
959 totalwidth, totalheight);
960 fullscreen = Qnil;
963 SET_FRAME_GARBAGED (f);
964 cancel_mouse_face (f);
966 /* We can not call change_frame_size for a mapped frame,
967 we can not set pixel width/height either. The window manager may
968 override our resize request, XMonad does this all the time.
969 The best we can do is try to sync, so lisp code sees the updated
970 size as fast as possible.
971 For unmapped windows, we can set rows/cols. When
972 the frame is mapped again we will (hopefully) get the correct size. */
973 if (FRAME_VISIBLE_P (f))
975 /* Must call this to flush out events */
976 (void)gtk_events_pending ();
977 gdk_flush ();
978 x_wait_for_event (f, ConfigureNotify);
980 if (!NILP (fullscreen))
981 /* Try to restore fullscreen state. */
983 store_frame_param (f, Qfullscreen, fullscreen);
984 x_set_fullscreen (f, fullscreen, fullscreen);
987 else
988 adjust_frame_size (f, width, height, 5, 0, Qxg_frame_set_char_size);
992 /* Handle height/width changes (i.e. add/remove/move menu/toolbar).
993 The policy is to keep the number of editable lines. */
995 #if 0
996 static void
997 xg_height_or_width_changed (struct frame *f)
999 gtk_window_resize (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)),
1000 FRAME_TOTAL_PIXEL_WIDTH (f),
1001 FRAME_TOTAL_PIXEL_HEIGHT (f));
1002 f->output_data.x->hint_flags = 0;
1003 x_wm_set_size_hint (f, 0, 0);
1005 #endif
1007 /* Convert an X Window WSESC on display DPY to its corresponding GtkWidget.
1008 Must be done like this, because GtkWidget:s can have "hidden"
1009 X Window that aren't accessible.
1011 Return 0 if no widget match WDESC. */
1013 GtkWidget *
1014 xg_win_to_widget (Display *dpy, Window wdesc)
1016 gpointer gdkwin;
1017 GtkWidget *gwdesc = 0;
1019 block_input ();
1021 gdkwin = gdk_x11_window_lookup_for_display (gdk_x11_lookup_xdisplay (dpy),
1022 wdesc);
1023 if (gdkwin)
1025 GdkEvent event;
1026 event.any.window = gdkwin;
1027 event.any.type = GDK_NOTHING;
1028 gwdesc = gtk_get_event_widget (&event);
1031 unblock_input ();
1032 return gwdesc;
1035 /* Set the background of widget W to PIXEL. */
1037 static void
1038 xg_set_widget_bg (struct frame *f, GtkWidget *w, unsigned long pixel)
1040 #ifdef HAVE_GTK3
1041 GdkRGBA bg;
1042 XColor xbg;
1043 xbg.pixel = pixel;
1044 if (XQueryColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &xbg))
1046 bg.red = (double)xbg.red/65535.0;
1047 bg.green = (double)xbg.green/65535.0;
1048 bg.blue = (double)xbg.blue/65535.0;
1049 bg.alpha = 1.0;
1050 gtk_widget_override_background_color (w, GTK_STATE_FLAG_NORMAL, &bg);
1052 #else
1053 GdkColor bg;
1054 GdkColormap *map = gtk_widget_get_colormap (w);
1055 gdk_colormap_query_color (map, pixel, &bg);
1056 gtk_widget_modify_bg (FRAME_GTK_WIDGET (f), GTK_STATE_NORMAL, &bg);
1057 #endif
1060 /* Callback called when the gtk theme changes.
1061 We notify lisp code so it can fix faces used for region for example. */
1063 static void
1064 style_changed_cb (GObject *go,
1065 GParamSpec *spec,
1066 gpointer user_data)
1068 struct input_event event;
1069 GdkDisplay *gdpy = user_data;
1070 const char *display_name = gdk_display_get_name (gdpy);
1071 Display *dpy = GDK_DISPLAY_XDISPLAY (gdpy);
1073 EVENT_INIT (event);
1074 event.kind = CONFIG_CHANGED_EVENT;
1075 event.frame_or_window = build_string (display_name);
1076 /* Theme doesn't change often, so intern is called seldom. */
1077 event.arg = intern ("theme-name");
1078 kbd_buffer_store_event (&event);
1080 update_theme_scrollbar_width ();
1081 update_theme_scrollbar_height ();
1083 /* If scroll bar width changed, we need set the new size on all frames
1084 on this display. */
1085 if (dpy)
1087 Lisp_Object rest, frame;
1088 FOR_EACH_FRAME (rest, frame)
1090 struct frame *f = XFRAME (frame);
1091 if (FRAME_LIVE_P (f)
1092 && FRAME_X_P (f)
1093 && FRAME_X_DISPLAY (f) == dpy)
1095 x_set_scroll_bar_default_width (f);
1096 x_set_scroll_bar_default_height (f);
1097 xg_frame_set_char_size (f, FRAME_TEXT_WIDTH (f), FRAME_TEXT_HEIGHT (f));
1103 /* Called when a delete-event occurs on WIDGET. */
1105 static gboolean
1106 delete_cb (GtkWidget *widget,
1107 GdkEvent *event,
1108 gpointer user_data)
1110 return TRUE;
1113 /* Create and set up the GTK widgets for frame F.
1114 Return true if creation succeeded. */
1116 bool
1117 xg_create_frame_widgets (struct frame *f)
1119 GtkWidget *wtop;
1120 GtkWidget *wvbox, *whbox;
1121 GtkWidget *wfixed;
1122 #ifndef HAVE_GTK3
1123 GtkRcStyle *style;
1124 #endif
1125 char *title = 0;
1127 block_input ();
1129 if (FRAME_X_EMBEDDED_P (f))
1131 GdkDisplay *gdpy = gdk_x11_lookup_xdisplay (FRAME_X_DISPLAY (f));
1132 wtop = gtk_plug_new_for_display (gdpy, f->output_data.x->parent_desc);
1134 else
1135 wtop = gtk_window_new (GTK_WINDOW_TOPLEVEL);
1137 /* gtk_window_set_has_resize_grip is a Gtk+ 3.0 function but Ubuntu
1138 has backported it to Gtk+ 2.0 and they add the resize grip for
1139 Gtk+ 2.0 applications also. But it has a bug that makes Emacs loop
1140 forever, so disable the grip. */
1141 #if (! GTK_CHECK_VERSION (3, 0, 0) \
1142 && defined HAVE_GTK_WINDOW_SET_HAS_RESIZE_GRIP)
1143 gtk_window_set_has_resize_grip (GTK_WINDOW (wtop), FALSE);
1144 #endif
1146 xg_set_screen (wtop, f);
1148 wvbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 0);
1149 whbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0);
1150 gtk_box_set_homogeneous (GTK_BOX (wvbox), FALSE);
1151 gtk_box_set_homogeneous (GTK_BOX (whbox), FALSE);
1153 #ifdef HAVE_GTK3
1154 wfixed = emacs_fixed_new (f);
1155 #else
1156 wfixed = gtk_fixed_new ();
1157 #endif
1159 if (! wtop || ! wvbox || ! whbox || ! wfixed)
1161 if (wtop) gtk_widget_destroy (wtop);
1162 if (wvbox) gtk_widget_destroy (wvbox);
1163 if (whbox) gtk_widget_destroy (whbox);
1164 if (wfixed) gtk_widget_destroy (wfixed);
1166 unblock_input ();
1167 return 0;
1170 /* Use same names as the Xt port does. I.e. Emacs.pane.emacs by default */
1171 gtk_widget_set_name (wtop, EMACS_CLASS);
1172 gtk_widget_set_name (wvbox, "pane");
1173 gtk_widget_set_name (wfixed, SSDATA (Vx_resource_name));
1175 /* If this frame has a title or name, set it in the title bar. */
1176 if (! NILP (f->title))
1177 title = SSDATA (ENCODE_UTF_8 (f->title));
1178 else if (! NILP (f->name))
1179 title = SSDATA (ENCODE_UTF_8 (f->name));
1181 if (title) gtk_window_set_title (GTK_WINDOW (wtop), title);
1183 FRAME_GTK_OUTER_WIDGET (f) = wtop;
1184 FRAME_GTK_WIDGET (f) = wfixed;
1185 f->output_data.x->vbox_widget = wvbox;
1186 f->output_data.x->hbox_widget = whbox;
1188 gtk_widget_set_has_window (wfixed, TRUE);
1190 gtk_container_add (GTK_CONTAINER (wtop), wvbox);
1191 gtk_box_pack_start (GTK_BOX (wvbox), whbox, TRUE, TRUE, 0);
1192 gtk_box_pack_start (GTK_BOX (whbox), wfixed, TRUE, TRUE, 0);
1194 if (FRAME_EXTERNAL_TOOL_BAR (f))
1195 update_frame_tool_bar (f);
1197 /* We don't want this widget double buffered, because we draw on it
1198 with regular X drawing primitives, so from a GTK/GDK point of
1199 view, the widget is totally blank. When an expose comes, this
1200 will make the widget blank, and then Emacs redraws it. This flickers
1201 a lot, so we turn off double buffering. */
1202 gtk_widget_set_double_buffered (wfixed, FALSE);
1204 gtk_window_set_wmclass (GTK_WINDOW (wtop),
1205 SSDATA (Vx_resource_name),
1206 SSDATA (Vx_resource_class));
1208 /* Add callback to do nothing on WM_DELETE_WINDOW. The default in
1209 GTK is to destroy the widget. We want Emacs to do that instead. */
1210 g_signal_connect (G_OBJECT (wtop), "delete-event",
1211 G_CALLBACK (delete_cb), f);
1213 /* Convert our geometry parameters into a geometry string
1214 and specify it.
1215 GTK will itself handle calculating the real position this way. */
1216 xg_set_geometry (f);
1217 f->win_gravity
1218 = gtk_window_get_gravity (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
1220 gtk_widget_add_events (wfixed,
1221 GDK_POINTER_MOTION_MASK
1222 | GDK_EXPOSURE_MASK
1223 | GDK_BUTTON_PRESS_MASK
1224 | GDK_BUTTON_RELEASE_MASK
1225 | GDK_KEY_PRESS_MASK
1226 | GDK_ENTER_NOTIFY_MASK
1227 | GDK_LEAVE_NOTIFY_MASK
1228 | GDK_FOCUS_CHANGE_MASK
1229 | GDK_STRUCTURE_MASK
1230 | GDK_VISIBILITY_NOTIFY_MASK);
1232 /* Must realize the windows so the X window gets created. It is used
1233 by callers of this function. */
1234 gtk_widget_realize (wfixed);
1235 FRAME_X_WINDOW (f) = GTK_WIDGET_TO_X_WIN (wfixed);
1237 /* Since GTK clears its window by filling with the background color,
1238 we must keep X and GTK background in sync. */
1239 xg_set_widget_bg (f, wfixed, FRAME_BACKGROUND_PIXEL (f));
1241 #ifndef HAVE_GTK3
1242 /* Also, do not let any background pixmap to be set, this looks very
1243 bad as Emacs overwrites the background pixmap with its own idea
1244 of background color. */
1245 style = gtk_widget_get_modifier_style (wfixed);
1247 /* Must use g_strdup because gtk_widget_modify_style does g_free. */
1248 style->bg_pixmap_name[GTK_STATE_NORMAL] = g_strdup ("<none>");
1249 gtk_widget_modify_style (wfixed, style);
1250 #else
1251 gtk_widget_set_can_focus (wfixed, TRUE);
1252 gtk_window_set_resizable (GTK_WINDOW (wtop), TRUE);
1253 #endif
1255 #ifdef USE_GTK_TOOLTIP
1256 /* Steal a tool tip window we can move ourselves. */
1257 f->output_data.x->ttip_widget = 0;
1258 f->output_data.x->ttip_lbl = 0;
1259 f->output_data.x->ttip_window = 0;
1260 gtk_widget_set_tooltip_text (wtop, "Dummy text");
1261 g_signal_connect (wtop, "query-tooltip", G_CALLBACK (qttip_cb), f);
1262 #endif
1265 GdkScreen *screen = gtk_widget_get_screen (wtop);
1266 GtkSettings *gs = gtk_settings_get_for_screen (screen);
1267 /* Only connect this signal once per screen. */
1268 if (! g_signal_handler_find (G_OBJECT (gs),
1269 G_SIGNAL_MATCH_FUNC,
1270 0, 0, 0,
1271 (gpointer) G_CALLBACK (style_changed_cb),
1274 g_signal_connect (G_OBJECT (gs), "notify::gtk-theme-name",
1275 G_CALLBACK (style_changed_cb),
1276 gdk_screen_get_display (screen));
1280 unblock_input ();
1282 return 1;
1285 void
1286 xg_free_frame_widgets (struct frame *f)
1288 if (FRAME_GTK_OUTER_WIDGET (f))
1290 #ifdef USE_GTK_TOOLTIP
1291 struct x_output *x = f->output_data.x;
1292 #endif
1293 struct xg_frame_tb_info *tbinfo
1294 = g_object_get_data (G_OBJECT (FRAME_GTK_OUTER_WIDGET (f)),
1295 TB_INFO_KEY);
1296 if (tbinfo)
1297 xfree (tbinfo);
1299 gtk_widget_destroy (FRAME_GTK_OUTER_WIDGET (f));
1300 FRAME_X_WINDOW (f) = 0; /* Set to avoid XDestroyWindow in xterm.c */
1301 FRAME_GTK_OUTER_WIDGET (f) = 0;
1302 #ifdef USE_GTK_TOOLTIP
1303 if (x->ttip_lbl)
1304 gtk_widget_destroy (x->ttip_lbl);
1305 if (x->ttip_widget)
1306 g_object_unref (G_OBJECT (x->ttip_widget));
1307 #endif
1311 /* Set the normal size hints for the window manager, for frame F.
1312 FLAGS is the flags word to use--or 0 meaning preserve the flags
1313 that the window now has.
1314 If USER_POSITION, set the User Position
1315 flag (this is useful when FLAGS is 0). */
1317 void
1318 x_wm_set_size_hint (struct frame *f, long int flags, bool user_position)
1320 /* Must use GTK routines here, otherwise GTK resets the size hints
1321 to its own defaults. */
1322 GdkGeometry size_hints;
1323 gint hint_flags = 0;
1324 int base_width, base_height;
1325 int min_rows = 0, min_cols = 0;
1326 int win_gravity = f->win_gravity;
1327 Lisp_Object fs_state, frame;
1328 int scale = xg_get_gdk_scale ();
1330 /* Don't set size hints during initialization; that apparently leads
1331 to a race condition. See the thread at
1332 http://lists.gnu.org/archive/html/emacs-devel/2008-10/msg00033.html */
1333 if (NILP (Vafter_init_time) || !FRAME_GTK_OUTER_WIDGET (f))
1334 return;
1336 XSETFRAME (frame, f);
1337 fs_state = Fframe_parameter (frame, Qfullscreen);
1338 if ((EQ (fs_state, Qmaximized) || EQ (fs_state, Qfullboth)) &&
1339 (x_wm_supports (f, FRAME_DISPLAY_INFO (f)->Xatom_net_wm_state) ||
1340 x_wm_supports (f, FRAME_DISPLAY_INFO (f)->Xatom_net_wm_state_fullscreen)))
1342 /* Don't set hints when maximized or fullscreen. Apparently KWin and
1343 Gtk3 don't get along and the frame shrinks (!).
1345 return;
1348 if (flags)
1350 memset (&size_hints, 0, sizeof (size_hints));
1351 f->output_data.x->size_hints = size_hints;
1352 f->output_data.x->hint_flags = hint_flags;
1354 else
1355 flags = f->size_hint_flags;
1357 size_hints = f->output_data.x->size_hints;
1358 hint_flags = f->output_data.x->hint_flags;
1360 hint_flags |= GDK_HINT_RESIZE_INC | GDK_HINT_MIN_SIZE;
1361 size_hints.width_inc = frame_resize_pixelwise ? 1 : FRAME_COLUMN_WIDTH (f);
1362 size_hints.height_inc = frame_resize_pixelwise ? 1 : FRAME_LINE_HEIGHT (f);
1364 hint_flags |= GDK_HINT_BASE_SIZE;
1365 /* Use one row/col here so base_height/width does not become zero.
1366 Gtk+ and/or Unity on Ubuntu 12.04 can't handle it.
1367 Obviously this makes the row/col value displayed off by 1. */
1368 base_width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 1) + FRAME_TOOLBAR_WIDTH (f);
1369 base_height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 1)
1370 + FRAME_MENUBAR_HEIGHT (f) + FRAME_TOOLBAR_HEIGHT (f);
1372 if (min_cols > 0) --min_cols; /* We used one col in base_width = ... 1); */
1373 if (min_rows > 0) --min_rows; /* We used one row in base_height = ... 1); */
1375 size_hints.base_width = base_width;
1376 size_hints.base_height = base_height;
1377 size_hints.min_width = base_width + min_cols * FRAME_COLUMN_WIDTH (f);
1378 size_hints.min_height = base_height + min_rows * FRAME_LINE_HEIGHT (f);
1380 /* These currently have a one to one mapping with the X values, but I
1381 don't think we should rely on that. */
1382 hint_flags |= GDK_HINT_WIN_GRAVITY;
1383 size_hints.win_gravity = 0;
1384 if (win_gravity == NorthWestGravity)
1385 size_hints.win_gravity = GDK_GRAVITY_NORTH_WEST;
1386 else if (win_gravity == NorthGravity)
1387 size_hints.win_gravity = GDK_GRAVITY_NORTH;
1388 else if (win_gravity == NorthEastGravity)
1389 size_hints.win_gravity = GDK_GRAVITY_NORTH_EAST;
1390 else if (win_gravity == WestGravity)
1391 size_hints.win_gravity = GDK_GRAVITY_WEST;
1392 else if (win_gravity == CenterGravity)
1393 size_hints.win_gravity = GDK_GRAVITY_CENTER;
1394 else if (win_gravity == EastGravity)
1395 size_hints.win_gravity = GDK_GRAVITY_EAST;
1396 else if (win_gravity == SouthWestGravity)
1397 size_hints.win_gravity = GDK_GRAVITY_SOUTH_WEST;
1398 else if (win_gravity == SouthGravity)
1399 size_hints.win_gravity = GDK_GRAVITY_SOUTH;
1400 else if (win_gravity == SouthEastGravity)
1401 size_hints.win_gravity = GDK_GRAVITY_SOUTH_EAST;
1402 else if (win_gravity == StaticGravity)
1403 size_hints.win_gravity = GDK_GRAVITY_STATIC;
1405 if (user_position)
1407 hint_flags &= ~GDK_HINT_POS;
1408 hint_flags |= GDK_HINT_USER_POS;
1411 size_hints.base_width /= scale;
1412 size_hints.base_height /= scale;
1413 size_hints.width_inc /= scale;
1414 size_hints.height_inc /= scale;
1416 if (hint_flags != f->output_data.x->hint_flags
1417 || memcmp (&size_hints,
1418 &f->output_data.x->size_hints,
1419 sizeof (size_hints)) != 0)
1421 block_input ();
1422 gtk_window_set_geometry_hints (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)),
1423 NULL, &size_hints, hint_flags);
1424 f->output_data.x->size_hints = size_hints;
1425 f->output_data.x->hint_flags = hint_flags;
1426 unblock_input ();
1430 /* Change background color of a frame.
1431 Since GTK uses the background color to clear the window, we must
1432 keep the GTK and X colors in sync.
1433 F is the frame to change,
1434 BG is the pixel value to change to. */
1436 void
1437 xg_set_background_color (struct frame *f, unsigned long bg)
1439 if (FRAME_GTK_WIDGET (f))
1441 block_input ();
1442 xg_set_widget_bg (f, FRAME_GTK_WIDGET (f), FRAME_BACKGROUND_PIXEL (f));
1443 unblock_input ();
1448 /* Set the frame icon to ICON_PIXMAP/MASK. This must be done with GTK
1449 functions so GTK does not overwrite the icon. */
1451 void
1452 xg_set_frame_icon (struct frame *f, Pixmap icon_pixmap, Pixmap icon_mask)
1454 GdkPixbuf *gp = xg_get_pixbuf_from_pix_and_mask (f,
1455 icon_pixmap,
1456 icon_mask);
1457 if (gp)
1458 gtk_window_set_icon (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)), gp);
1463 /***********************************************************************
1464 Dialog functions
1465 ***********************************************************************/
1466 /* Return the dialog title to use for a dialog of type KEY.
1467 This is the encoding used by lwlib. We use the same for GTK. */
1469 static const char *
1470 get_dialog_title (char key)
1472 const char *title = "";
1474 switch (key) {
1475 case 'E': case 'e':
1476 title = "Error";
1477 break;
1479 case 'I': case 'i':
1480 title = "Information";
1481 break;
1483 case 'L': case 'l':
1484 title = "Prompt";
1485 break;
1487 case 'P': case 'p':
1488 title = "Prompt";
1489 break;
1491 case 'Q': case 'q':
1492 title = "Question";
1493 break;
1496 return title;
1499 /* Callback for dialogs that get WM_DELETE_WINDOW. We pop down
1500 the dialog, but return TRUE so the event does not propagate further
1501 in GTK. This prevents GTK from destroying the dialog widget automatically
1502 and we can always destroy the widget manually, regardless of how
1503 it was popped down (button press or WM_DELETE_WINDOW).
1504 W is the dialog widget.
1505 EVENT is the GdkEvent that represents WM_DELETE_WINDOW (not used).
1506 user_data is NULL (not used).
1508 Returns TRUE to end propagation of event. */
1510 static gboolean
1511 dialog_delete_callback (GtkWidget *w, GdkEvent *event, gpointer user_data)
1513 gtk_widget_unmap (w);
1514 return TRUE;
1517 /* Create a popup dialog window. See also xg_create_widget below.
1518 WV is a widget_value describing the dialog.
1519 SELECT_CB is the callback to use when a button has been pressed.
1520 DEACTIVATE_CB is the callback to use when the dialog pops down.
1522 Returns the GTK dialog widget. */
1524 static GtkWidget *
1525 create_dialog (widget_value *wv,
1526 GCallback select_cb,
1527 GCallback deactivate_cb)
1529 const char *title = get_dialog_title (wv->name[0]);
1530 int total_buttons = wv->name[1] - '0';
1531 int right_buttons = wv->name[4] - '0';
1532 int left_buttons;
1533 int button_nr = 0;
1534 int button_spacing = 10;
1535 GtkWidget *wdialog = gtk_dialog_new ();
1536 GtkDialog *wd = GTK_DIALOG (wdialog);
1537 widget_value *item;
1538 GtkWidget *whbox_down;
1540 /* If the number of buttons is greater than 4, make two rows of buttons
1541 instead. This looks better. */
1542 bool make_two_rows = total_buttons > 4;
1544 #if GTK_CHECK_VERSION (3, 12, 0)
1545 GtkBuilder *gbld = gtk_builder_new ();
1546 GObject *go = gtk_buildable_get_internal_child (GTK_BUILDABLE (wd),
1547 gbld,
1548 "action_area");
1549 GtkBox *cur_box = GTK_BOX (go);
1550 g_object_unref (G_OBJECT (gbld));
1551 #else
1552 GtkBox *cur_box = GTK_BOX (gtk_dialog_get_action_area (wd));
1553 #endif
1555 if (right_buttons == 0) right_buttons = total_buttons/2;
1556 left_buttons = total_buttons - right_buttons;
1558 gtk_window_set_title (GTK_WINDOW (wdialog), title);
1559 gtk_widget_set_name (wdialog, "emacs-dialog");
1562 if (make_two_rows)
1564 GtkWidget *wvbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, button_spacing);
1565 GtkWidget *whbox_up = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0);
1566 gtk_box_set_homogeneous (GTK_BOX (wvbox), TRUE);
1567 gtk_box_set_homogeneous (GTK_BOX (whbox_up), FALSE);
1568 whbox_down = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0);
1569 gtk_box_set_homogeneous (GTK_BOX (whbox_down), FALSE);
1571 gtk_box_pack_start (cur_box, wvbox, FALSE, FALSE, 0);
1572 gtk_box_pack_start (GTK_BOX (wvbox), whbox_up, FALSE, FALSE, 0);
1573 gtk_box_pack_start (GTK_BOX (wvbox), whbox_down, FALSE, FALSE, 0);
1575 cur_box = GTK_BOX (whbox_up);
1578 g_signal_connect (G_OBJECT (wdialog), "delete-event",
1579 G_CALLBACK (dialog_delete_callback), 0);
1581 if (deactivate_cb)
1583 g_signal_connect (G_OBJECT (wdialog), "close", deactivate_cb, 0);
1584 g_signal_connect (G_OBJECT (wdialog), "response", deactivate_cb, 0);
1587 for (item = wv->contents; item; item = item->next)
1589 char *utf8_label = get_utf8_string (item->value);
1590 GtkWidget *w;
1591 GtkRequisition req;
1593 if (item->name && strcmp (item->name, "message") == 0)
1595 GtkBox *wvbox = GTK_BOX (gtk_dialog_get_content_area (wd));
1596 /* This is the text part of the dialog. */
1597 w = gtk_label_new (utf8_label);
1598 gtk_box_pack_start (wvbox, gtk_label_new (""), FALSE, FALSE, 0);
1599 gtk_box_pack_start (wvbox, w, TRUE, TRUE, 0);
1600 #if GTK_CHECK_VERSION (3, 14, 0)
1601 gtk_widget_set_halign (w, GTK_ALIGN_START);
1602 gtk_widget_set_valign (w, GTK_ALIGN_CENTER);
1603 #else
1604 gtk_misc_set_alignment (GTK_MISC (w), 0.1, 0.5);
1605 #endif
1606 /* Try to make dialog look better. Must realize first so
1607 the widget can calculate the size it needs. */
1608 gtk_widget_realize (w);
1609 gtk_widget_get_preferred_size (w, NULL, &req);
1610 gtk_box_set_spacing (wvbox, req.height);
1611 if (item->value && strlen (item->value) > 0)
1612 button_spacing = 2*req.width/strlen (item->value);
1613 if (button_spacing < 10) button_spacing = 10;
1615 else
1617 /* This is one button to add to the dialog. */
1618 w = gtk_button_new_with_label (utf8_label);
1619 if (! item->enabled)
1620 gtk_widget_set_sensitive (w, FALSE);
1621 if (select_cb)
1622 g_signal_connect (G_OBJECT (w), "clicked",
1623 select_cb, item->call_data);
1625 gtk_box_pack_start (cur_box, w, TRUE, TRUE, button_spacing);
1626 if (++button_nr == left_buttons)
1628 if (make_two_rows)
1629 cur_box = GTK_BOX (whbox_down);
1633 if (utf8_label)
1634 g_free (utf8_label);
1637 return wdialog;
1640 struct xg_dialog_data
1642 GMainLoop *loop;
1643 int response;
1644 GtkWidget *w;
1645 guint timerid;
1648 /* Function that is called when the file or font dialogs pop down.
1649 W is the dialog widget, RESPONSE is the response code.
1650 USER_DATA is what we passed in to g_signal_connect. */
1652 static void
1653 xg_dialog_response_cb (GtkDialog *w,
1654 gint response,
1655 gpointer user_data)
1657 struct xg_dialog_data *dd = user_data;
1658 dd->response = response;
1659 g_main_loop_quit (dd->loop);
1663 /* Destroy the dialog. This makes it pop down. */
1665 static void
1666 pop_down_dialog (void *arg)
1668 struct xg_dialog_data *dd = arg;
1670 block_input ();
1671 if (dd->w) gtk_widget_destroy (dd->w);
1672 if (dd->timerid != 0) g_source_remove (dd->timerid);
1674 g_main_loop_quit (dd->loop);
1675 g_main_loop_unref (dd->loop);
1677 unblock_input ();
1680 /* If there are any emacs timers pending, add a timeout to main loop in DATA.
1681 We pass in DATA as gpointer* so we can use this as a callback. */
1683 static gboolean
1684 xg_maybe_add_timer (gpointer data)
1686 struct xg_dialog_data *dd = data;
1687 struct timespec next_time = timer_check ();
1689 dd->timerid = 0;
1691 if (timespec_valid_p (next_time))
1693 time_t s = next_time.tv_sec;
1694 int per_ms = TIMESPEC_RESOLUTION / 1000;
1695 int ms = (next_time.tv_nsec + per_ms - 1) / per_ms;
1696 if (s <= ((guint) -1 - ms) / 1000)
1697 dd->timerid = g_timeout_add (s * 1000 + ms, xg_maybe_add_timer, dd);
1699 return FALSE;
1703 /* Pops up a modal dialog W and waits for response.
1704 We don't use gtk_dialog_run because we want to process emacs timers.
1705 The dialog W is not destroyed when this function returns. */
1707 static int
1708 xg_dialog_run (struct frame *f, GtkWidget *w)
1710 ptrdiff_t count = SPECPDL_INDEX ();
1711 struct xg_dialog_data dd;
1713 xg_set_screen (w, f);
1714 gtk_window_set_transient_for (GTK_WINDOW (w),
1715 GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
1716 gtk_window_set_destroy_with_parent (GTK_WINDOW (w), TRUE);
1717 gtk_window_set_modal (GTK_WINDOW (w), TRUE);
1719 dd.loop = g_main_loop_new (NULL, FALSE);
1720 dd.response = GTK_RESPONSE_CANCEL;
1721 dd.w = w;
1722 dd.timerid = 0;
1724 g_signal_connect (G_OBJECT (w),
1725 "response",
1726 G_CALLBACK (xg_dialog_response_cb),
1727 &dd);
1728 /* Don't destroy the widget if closed by the window manager close button. */
1729 g_signal_connect (G_OBJECT (w), "delete-event", G_CALLBACK (gtk_true), NULL);
1730 gtk_widget_show (w);
1732 record_unwind_protect_ptr (pop_down_dialog, &dd);
1734 (void) xg_maybe_add_timer (&dd);
1735 g_main_loop_run (dd.loop);
1737 dd.w = 0;
1738 unbind_to (count, Qnil);
1740 return dd.response;
1744 /***********************************************************************
1745 File dialog functions
1746 ***********************************************************************/
1747 /* Return true if the old file selection dialog is being used. */
1749 bool
1750 xg_uses_old_file_dialog (void)
1752 #ifdef HAVE_GTK_FILE_SELECTION_NEW
1753 return x_gtk_use_old_file_dialog;
1754 #else
1755 return 0;
1756 #endif
1760 typedef char * (*xg_get_file_func) (GtkWidget *);
1762 /* Return the selected file for file chooser dialog W.
1763 The returned string must be free:d. */
1765 static char *
1766 xg_get_file_name_from_chooser (GtkWidget *w)
1768 return gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (w));
1771 /* Callback called when the "Show hidden files" toggle is pressed.
1772 WIDGET is the toggle widget, DATA is the file chooser dialog. */
1774 static void
1775 xg_toggle_visibility_cb (GtkWidget *widget, gpointer data)
1777 GtkFileChooser *dialog = GTK_FILE_CHOOSER (data);
1778 gboolean visible;
1779 g_object_get (G_OBJECT (dialog), "show-hidden", &visible, NULL);
1780 g_object_set (G_OBJECT (dialog), "show-hidden", !visible, NULL);
1784 /* Callback called when a property changes in a file chooser.
1785 GOBJECT is the file chooser dialog, ARG1 describes the property.
1786 USER_DATA is the toggle widget in the file chooser dialog.
1787 We use this to update the "Show hidden files" toggle when the user
1788 changes that property by right clicking in the file list. */
1790 static void
1791 xg_toggle_notify_cb (GObject *gobject, GParamSpec *arg1, gpointer user_data)
1793 if (strcmp (arg1->name, "show-hidden") == 0)
1795 GtkWidget *wtoggle = GTK_WIDGET (user_data);
1796 gboolean visible, toggle_on;
1798 g_object_get (G_OBJECT (gobject), "show-hidden", &visible, NULL);
1799 toggle_on = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (wtoggle));
1801 if (!!visible != !!toggle_on)
1803 gpointer cb = (gpointer) G_CALLBACK (xg_toggle_visibility_cb);
1804 g_signal_handlers_block_by_func (G_OBJECT (wtoggle), cb, gobject);
1805 gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (wtoggle), visible);
1806 g_signal_handlers_unblock_by_func (G_OBJECT (wtoggle), cb, gobject);
1808 x_gtk_show_hidden_files = visible;
1812 /* Read a file name from the user using a file chooser dialog.
1813 F is the current frame.
1814 PROMPT is a prompt to show to the user. May not be NULL.
1815 DEFAULT_FILENAME is a default selection to be displayed. May be NULL.
1816 If MUSTMATCH_P, the returned file name must be an existing
1817 file. (Actually, this only has cosmetic effects, the user can
1818 still enter a non-existing file.) *FUNC is set to a function that
1819 can be used to retrieve the selected file name from the returned widget.
1821 Returns the created widget. */
1823 static GtkWidget *
1824 xg_get_file_with_chooser (struct frame *f,
1825 char *prompt,
1826 char *default_filename,
1827 bool mustmatch_p, bool only_dir_p,
1828 xg_get_file_func *func)
1830 char msgbuf[1024];
1832 GtkWidget *filewin, *wtoggle, *wbox, *wmessage IF_LINT (= NULL);
1833 GtkWindow *gwin = GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f));
1834 GtkFileChooserAction action = (mustmatch_p ?
1835 GTK_FILE_CHOOSER_ACTION_OPEN :
1836 GTK_FILE_CHOOSER_ACTION_SAVE);
1838 if (only_dir_p)
1839 action = GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER;
1841 filewin = gtk_file_chooser_dialog_new (prompt, gwin, action,
1842 XG_TEXT_CANCEL, GTK_RESPONSE_CANCEL,
1843 (mustmatch_p || only_dir_p ?
1844 XG_TEXT_OPEN : XG_TEXT_OK),
1845 GTK_RESPONSE_OK,
1846 NULL);
1847 gtk_file_chooser_set_local_only (GTK_FILE_CHOOSER (filewin), TRUE);
1849 wbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 0);
1850 gtk_box_set_homogeneous (GTK_BOX (wbox), FALSE);
1851 gtk_widget_show (wbox);
1852 wtoggle = gtk_check_button_new_with_label ("Show hidden files.");
1854 if (x_gtk_show_hidden_files)
1856 g_object_set (G_OBJECT (filewin), "show-hidden", TRUE, NULL);
1857 gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (wtoggle), TRUE);
1859 gtk_widget_show (wtoggle);
1860 g_signal_connect (G_OBJECT (wtoggle), "clicked",
1861 G_CALLBACK (xg_toggle_visibility_cb), filewin);
1862 g_signal_connect (G_OBJECT (filewin), "notify",
1863 G_CALLBACK (xg_toggle_notify_cb), wtoggle);
1865 if (x_gtk_file_dialog_help_text)
1867 char *z = msgbuf;
1868 /* Gtk+ 2.10 has the file name text entry box integrated in the dialog.
1869 Show the C-l help text only for versions < 2.10. */
1870 if (gtk_check_version (2, 10, 0) && action != GTK_FILE_CHOOSER_ACTION_SAVE)
1871 z = stpcpy (z, "\nType C-l to display a file name text entry box.\n");
1872 strcpy (z, "\nIf you don't like this file selector, use the "
1873 "corresponding\nkey binding or customize "
1874 "use-file-dialog to turn it off.");
1876 wmessage = gtk_label_new (msgbuf);
1877 gtk_widget_show (wmessage);
1880 gtk_box_pack_start (GTK_BOX (wbox), wtoggle, FALSE, FALSE, 0);
1881 if (x_gtk_file_dialog_help_text)
1882 gtk_box_pack_start (GTK_BOX (wbox), wmessage, FALSE, FALSE, 0);
1883 gtk_file_chooser_set_extra_widget (GTK_FILE_CHOOSER (filewin), wbox);
1885 if (default_filename)
1887 Lisp_Object file;
1888 char *utf8_filename;
1890 file = build_string (default_filename);
1892 /* File chooser does not understand ~/... in the file name. It must be
1893 an absolute name starting with /. */
1894 if (default_filename[0] != '/')
1895 file = Fexpand_file_name (file, Qnil);
1897 utf8_filename = SSDATA (ENCODE_UTF_8 (file));
1898 if (! NILP (Ffile_directory_p (file)))
1899 gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (filewin),
1900 utf8_filename);
1901 else
1903 gtk_file_chooser_set_filename (GTK_FILE_CHOOSER (filewin),
1904 utf8_filename);
1905 if (action == GTK_FILE_CHOOSER_ACTION_SAVE)
1907 char *cp = strrchr (utf8_filename, '/');
1908 if (cp) ++cp;
1909 else cp = utf8_filename;
1910 gtk_file_chooser_set_current_name (GTK_FILE_CHOOSER (filewin), cp);
1915 *func = xg_get_file_name_from_chooser;
1916 return filewin;
1919 #ifdef HAVE_GTK_FILE_SELECTION_NEW
1921 /* Return the selected file for file selector dialog W.
1922 The returned string must be free:d. */
1924 static char *
1925 xg_get_file_name_from_selector (GtkWidget *w)
1927 GtkFileSelection *filesel = GTK_FILE_SELECTION (w);
1928 return xstrdup (gtk_file_selection_get_filename (filesel));
1931 /* Create a file selection dialog.
1932 F is the current frame.
1933 PROMPT is a prompt to show to the user. May not be NULL.
1934 DEFAULT_FILENAME is a default selection to be displayed. May be NULL.
1935 If MUSTMATCH_P, the returned file name must be an existing
1936 file. *FUNC is set to a function that can be used to retrieve the
1937 selected file name from the returned widget.
1939 Returns the created widget. */
1941 static GtkWidget *
1942 xg_get_file_with_selection (struct frame *f,
1943 char *prompt,
1944 char *default_filename,
1945 bool mustmatch_p, bool only_dir_p,
1946 xg_get_file_func *func)
1948 GtkWidget *filewin;
1949 GtkFileSelection *filesel;
1951 filewin = gtk_file_selection_new (prompt);
1952 filesel = GTK_FILE_SELECTION (filewin);
1954 if (default_filename)
1955 gtk_file_selection_set_filename (filesel, default_filename);
1957 if (mustmatch_p)
1959 /* The selection_entry part of filesel is not documented. */
1960 gtk_widget_set_sensitive (filesel->selection_entry, FALSE);
1961 gtk_file_selection_hide_fileop_buttons (filesel);
1964 *func = xg_get_file_name_from_selector;
1966 return filewin;
1968 #endif /* HAVE_GTK_FILE_SELECTION_NEW */
1970 /* Read a file name from the user using a file dialog, either the old
1971 file selection dialog, or the new file chooser dialog. Which to use
1972 depends on what the GTK version used has, and what the value of
1973 gtk-use-old-file-dialog.
1974 F is the current frame.
1975 PROMPT is a prompt to show to the user. May not be NULL.
1976 DEFAULT_FILENAME is a default selection to be displayed. May be NULL.
1977 If MUSTMATCH_P, the returned file name must be an existing
1978 file.
1980 Returns a file name or NULL if no file was selected.
1981 The returned string must be freed by the caller. */
1983 char *
1984 xg_get_file_name (struct frame *f,
1985 char *prompt,
1986 char *default_filename,
1987 bool mustmatch_p,
1988 bool only_dir_p)
1990 GtkWidget *w = 0;
1991 char *fn = 0;
1992 int filesel_done = 0;
1993 xg_get_file_func func;
1995 #ifdef HAVE_GTK_FILE_SELECTION_NEW
1997 if (xg_uses_old_file_dialog ())
1998 w = xg_get_file_with_selection (f, prompt, default_filename,
1999 mustmatch_p, only_dir_p, &func);
2000 else
2001 w = xg_get_file_with_chooser (f, prompt, default_filename,
2002 mustmatch_p, only_dir_p, &func);
2004 #else /* not HAVE_GTK_FILE_SELECTION_NEW */
2005 w = xg_get_file_with_chooser (f, prompt, default_filename,
2006 mustmatch_p, only_dir_p, &func);
2007 #endif /* not HAVE_GTK_FILE_SELECTION_NEW */
2009 gtk_widget_set_name (w, "emacs-filedialog");
2011 filesel_done = xg_dialog_run (f, w);
2012 if (filesel_done == GTK_RESPONSE_OK)
2013 fn = (*func) (w);
2015 gtk_widget_destroy (w);
2016 return fn;
2019 /***********************************************************************
2020 GTK font chooser
2021 ***********************************************************************/
2023 #ifdef HAVE_FREETYPE
2025 #if USE_NEW_GTK_FONT_CHOOSER
2027 #define XG_WEIGHT_TO_SYMBOL(w) \
2028 (w <= PANGO_WEIGHT_THIN ? Qextra_light \
2029 : w <= PANGO_WEIGHT_ULTRALIGHT ? Qlight \
2030 : w <= PANGO_WEIGHT_LIGHT ? Qsemi_light \
2031 : w < PANGO_WEIGHT_MEDIUM ? Qnormal \
2032 : w <= PANGO_WEIGHT_SEMIBOLD ? Qsemi_bold \
2033 : w <= PANGO_WEIGHT_BOLD ? Qbold \
2034 : w <= PANGO_WEIGHT_HEAVY ? Qextra_bold \
2035 : Qultra_bold)
2037 #define XG_STYLE_TO_SYMBOL(s) \
2038 (s == PANGO_STYLE_OBLIQUE ? Qoblique \
2039 : s == PANGO_STYLE_ITALIC ? Qitalic \
2040 : Qnormal)
2042 #endif /* USE_NEW_GTK_FONT_CHOOSER */
2045 static char *x_last_font_name;
2047 /* Pop up a GTK font selector and return the name of the font the user
2048 selects, as a C string. The returned font name follows GTK's own
2049 format:
2051 `FAMILY [VALUE1 VALUE2] SIZE'
2053 This can be parsed using font_parse_fcname in font.c.
2054 DEFAULT_NAME, if non-zero, is the default font name. */
2056 Lisp_Object
2057 xg_get_font (struct frame *f, const char *default_name)
2059 GtkWidget *w;
2060 int done = 0;
2061 Lisp_Object font = Qnil;
2063 w = gtk_font_chooser_dialog_new
2064 ("Pick a font", GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
2066 if (default_name)
2068 /* Convert fontconfig names to Gtk names, i.e. remove - before
2069 number */
2070 char *p = strrchr (default_name, '-');
2071 if (p)
2073 char *ep = p+1;
2074 while (c_isdigit (*ep))
2075 ++ep;
2076 if (*ep == '\0') *p = ' ';
2079 else if (x_last_font_name)
2080 default_name = x_last_font_name;
2082 if (default_name)
2083 gtk_font_chooser_set_font (GTK_FONT_CHOOSER (w), default_name);
2085 gtk_widget_set_name (w, "emacs-fontdialog");
2086 done = xg_dialog_run (f, w);
2087 if (done == GTK_RESPONSE_OK)
2089 #if USE_NEW_GTK_FONT_CHOOSER
2090 /* Use the GTK3 font chooser. */
2091 PangoFontDescription *desc
2092 = gtk_font_chooser_get_font_desc (GTK_FONT_CHOOSER (w));
2094 if (desc)
2096 const char *name = pango_font_description_get_family (desc);
2097 gint size = pango_font_description_get_size (desc);
2098 PangoWeight weight = pango_font_description_get_weight (desc);
2099 PangoStyle style = pango_font_description_get_style (desc);
2101 #ifdef USE_CAIRO
2102 #define FONT_TYPE_WANTED (Qftcr)
2103 #else
2104 #define FONT_TYPE_WANTED (Qxft)
2105 #endif
2106 font = CALLN (Ffont_spec,
2107 QCname, build_string (name),
2108 QCsize, make_float (pango_units_to_double (size)),
2109 QCweight, XG_WEIGHT_TO_SYMBOL (weight),
2110 QCslant, XG_STYLE_TO_SYMBOL (style),
2111 QCtype,
2112 FONT_TYPE_WANTED);
2114 pango_font_description_free (desc);
2115 dupstring (&x_last_font_name, name);
2118 #else /* Use old font selector, which just returns the font name. */
2120 char *font_name
2121 = gtk_font_selection_dialog_get_font_name (GTK_FONT_CHOOSER (w));
2123 if (font_name)
2125 font = build_string (font_name);
2126 g_free (x_last_font_name);
2127 x_last_font_name = font_name;
2129 #endif /* USE_NEW_GTK_FONT_CHOOSER */
2132 gtk_widget_destroy (w);
2133 return font;
2135 #endif /* HAVE_FREETYPE */
2139 /***********************************************************************
2140 Menu functions.
2141 ***********************************************************************/
2143 /* The name of menu items that can be used for customization. Since GTK
2144 RC files are very crude and primitive, we have to set this on all
2145 menu item names so a user can easily customize menu items. */
2147 #define MENU_ITEM_NAME "emacs-menuitem"
2150 /* Linked list of all allocated struct xg_menu_cb_data. Used for marking
2151 during GC. The next member points to the items. */
2152 static xg_list_node xg_menu_cb_list;
2154 /* Linked list of all allocated struct xg_menu_item_cb_data. Used for marking
2155 during GC. The next member points to the items. */
2156 static xg_list_node xg_menu_item_cb_list;
2158 /* Allocate and initialize CL_DATA if NULL, otherwise increase ref_count.
2159 F is the frame CL_DATA will be initialized for.
2160 HIGHLIGHT_CB is the callback to call when entering/leaving menu items.
2162 The menu bar and all sub menus under the menu bar in a frame
2163 share the same structure, hence the reference count.
2165 Returns CL_DATA if CL_DATA is not NULL, or a pointer to a newly
2166 allocated xg_menu_cb_data if CL_DATA is NULL. */
2168 static xg_menu_cb_data *
2169 make_cl_data (xg_menu_cb_data *cl_data, struct frame *f, GCallback highlight_cb)
2171 if (! cl_data)
2173 cl_data = xmalloc (sizeof *cl_data);
2174 cl_data->f = f;
2175 cl_data->menu_bar_vector = f->menu_bar_vector;
2176 cl_data->menu_bar_items_used = f->menu_bar_items_used;
2177 cl_data->highlight_cb = highlight_cb;
2178 cl_data->ref_count = 0;
2180 xg_list_insert (&xg_menu_cb_list, &cl_data->ptrs);
2183 cl_data->ref_count++;
2185 return cl_data;
2188 /* Update CL_DATA with values from frame F and with HIGHLIGHT_CB.
2189 HIGHLIGHT_CB is the callback to call when entering/leaving menu items.
2191 When the menu bar is updated, menu items may have been added and/or
2192 removed, so menu_bar_vector and menu_bar_items_used change. We must
2193 then update CL_DATA since it is used to determine which menu
2194 item that is invoked in the menu.
2195 HIGHLIGHT_CB could change, there is no check that the same
2196 function is given when modifying a menu bar as was given when
2197 creating the menu bar. */
2199 static void
2200 update_cl_data (xg_menu_cb_data *cl_data,
2201 struct frame *f,
2202 GCallback highlight_cb)
2204 if (cl_data)
2206 cl_data->f = f;
2207 cl_data->menu_bar_vector = f->menu_bar_vector;
2208 cl_data->menu_bar_items_used = f->menu_bar_items_used;
2209 cl_data->highlight_cb = highlight_cb;
2213 /* Decrease reference count for CL_DATA.
2214 If reference count is zero, free CL_DATA. */
2216 static void
2217 unref_cl_data (xg_menu_cb_data *cl_data)
2219 if (cl_data && cl_data->ref_count > 0)
2221 cl_data->ref_count--;
2222 if (cl_data->ref_count == 0)
2224 xg_list_remove (&xg_menu_cb_list, &cl_data->ptrs);
2225 xfree (cl_data);
2230 /* Function that marks all lisp data during GC. */
2232 void
2233 xg_mark_data (void)
2235 xg_list_node *iter;
2236 Lisp_Object rest, frame;
2238 for (iter = xg_menu_cb_list.next; iter; iter = iter->next)
2239 mark_object (((xg_menu_cb_data *) iter)->menu_bar_vector);
2241 for (iter = xg_menu_item_cb_list.next; iter; iter = iter->next)
2243 xg_menu_item_cb_data *cb_data = (xg_menu_item_cb_data *) iter;
2245 if (! NILP (cb_data->help))
2246 mark_object (cb_data->help);
2249 FOR_EACH_FRAME (rest, frame)
2251 struct frame *f = XFRAME (frame);
2253 if (FRAME_X_P (f) && FRAME_GTK_OUTER_WIDGET (f))
2255 struct xg_frame_tb_info *tbinfo
2256 = g_object_get_data (G_OBJECT (FRAME_GTK_OUTER_WIDGET (f)),
2257 TB_INFO_KEY);
2258 if (tbinfo)
2260 mark_object (tbinfo->last_tool_bar);
2261 mark_object (tbinfo->style);
2268 /* Callback called when a menu item is destroyed. Used to free data.
2269 W is the widget that is being destroyed (not used).
2270 CLIENT_DATA points to the xg_menu_item_cb_data associated with the W. */
2272 static void
2273 menuitem_destroy_callback (GtkWidget *w, gpointer client_data)
2275 if (client_data)
2277 xg_menu_item_cb_data *data = client_data;
2278 xg_list_remove (&xg_menu_item_cb_list, &data->ptrs);
2279 xfree (data);
2283 /* Callback called when the pointer enters/leaves a menu item.
2284 W is the parent of the menu item.
2285 EVENT is either an enter event or leave event.
2286 CLIENT_DATA is not used.
2288 Returns FALSE to tell GTK to keep processing this event. */
2290 static gboolean
2291 menuitem_highlight_callback (GtkWidget *w,
2292 GdkEventCrossing *event,
2293 gpointer client_data)
2295 GdkEvent ev;
2296 GtkWidget *subwidget;
2297 xg_menu_item_cb_data *data;
2299 ev.crossing = *event;
2300 subwidget = gtk_get_event_widget (&ev);
2301 data = g_object_get_data (G_OBJECT (subwidget), XG_ITEM_DATA);
2302 if (data)
2304 if (! NILP (data->help) && data->cl_data->highlight_cb)
2306 gpointer call_data = event->type == GDK_LEAVE_NOTIFY ? 0 : data;
2307 GtkCallback func = (GtkCallback) data->cl_data->highlight_cb;
2308 (*func) (subwidget, call_data);
2312 return FALSE;
2315 /* Callback called when a menu is destroyed. Used to free data.
2316 W is the widget that is being destroyed (not used).
2317 CLIENT_DATA points to the xg_menu_cb_data associated with W. */
2319 static void
2320 menu_destroy_callback (GtkWidget *w, gpointer client_data)
2322 unref_cl_data (client_data);
2325 /* Make a GTK widget that contains both UTF8_LABEL and UTF8_KEY (both
2326 must be non-NULL) and can be inserted into a menu item.
2328 Returns the GtkHBox. */
2330 static GtkWidget *
2331 make_widget_for_menu_item (const char *utf8_label, const char *utf8_key)
2333 GtkWidget *wlbl;
2334 GtkWidget *wkey;
2335 GtkWidget *wbox;
2337 wbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0);
2338 gtk_box_set_homogeneous (GTK_BOX (wbox), FALSE);
2339 wlbl = gtk_label_new (utf8_label);
2340 wkey = gtk_label_new (utf8_key);
2342 #if GTK_CHECK_VERSION (3, 14, 0)
2343 gtk_widget_set_halign (wlbl, GTK_ALIGN_START);
2344 gtk_widget_set_valign (wlbl, GTK_ALIGN_CENTER);
2345 gtk_widget_set_halign (wkey, GTK_ALIGN_START);
2346 gtk_widget_set_valign (wkey, GTK_ALIGN_CENTER);
2347 #else
2348 gtk_misc_set_alignment (GTK_MISC (wlbl), 0.0, 0.5);
2349 gtk_misc_set_alignment (GTK_MISC (wkey), 0.0, 0.5);
2350 #endif
2351 gtk_box_pack_start (GTK_BOX (wbox), wlbl, TRUE, TRUE, 0);
2352 gtk_box_pack_start (GTK_BOX (wbox), wkey, FALSE, FALSE, 0);
2354 gtk_widget_set_name (wlbl, MENU_ITEM_NAME);
2355 gtk_widget_set_name (wkey, MENU_ITEM_NAME);
2356 gtk_widget_set_name (wbox, MENU_ITEM_NAME);
2358 return wbox;
2361 /* Make and return a menu item widget with the key to the right.
2362 UTF8_LABEL is the text for the menu item (GTK uses UTF8 internally).
2363 UTF8_KEY is the text representing the key binding.
2364 ITEM is the widget_value describing the menu item.
2366 GROUP is an in/out parameter. If the menu item to be created is not
2367 part of any radio menu group, *GROUP contains NULL on entry and exit.
2368 If the menu item to be created is part of a radio menu group, on entry
2369 *GROUP contains the group to use, or NULL if this is the first item
2370 in the group. On exit, *GROUP contains the radio item group.
2372 Unfortunately, keys don't line up as nicely as in Motif,
2373 but the MacOS X version doesn't either, so I guess that is OK. */
2375 static GtkWidget *
2376 make_menu_item (const char *utf8_label,
2377 const char *utf8_key,
2378 widget_value *item,
2379 GSList **group)
2381 GtkWidget *w;
2382 GtkWidget *wtoadd = 0;
2384 /* It has been observed that some menu items have a NULL name field.
2385 This will lead to this function being called with a NULL utf8_label.
2386 GTK crashes on that so we set a blank label. Why there is a NULL
2387 name remains to be investigated. */
2388 if (! utf8_label) utf8_label = " ";
2390 if (utf8_key)
2391 wtoadd = make_widget_for_menu_item (utf8_label, utf8_key);
2393 if (item->button_type == BUTTON_TYPE_TOGGLE)
2395 *group = NULL;
2396 if (utf8_key) w = gtk_check_menu_item_new ();
2397 else w = gtk_check_menu_item_new_with_label (utf8_label);
2398 gtk_check_menu_item_set_active (GTK_CHECK_MENU_ITEM (w), item->selected);
2400 else if (item->button_type == BUTTON_TYPE_RADIO)
2402 if (utf8_key) w = gtk_radio_menu_item_new (*group);
2403 else w = gtk_radio_menu_item_new_with_label (*group, utf8_label);
2404 *group = gtk_radio_menu_item_get_group (GTK_RADIO_MENU_ITEM (w));
2405 if (item->selected)
2406 gtk_check_menu_item_set_active (GTK_CHECK_MENU_ITEM (w), TRUE);
2408 else
2410 *group = NULL;
2411 if (utf8_key) w = gtk_menu_item_new ();
2412 else w = gtk_menu_item_new_with_label (utf8_label);
2415 if (wtoadd) gtk_container_add (GTK_CONTAINER (w), wtoadd);
2416 if (! item->enabled) gtk_widget_set_sensitive (w, FALSE);
2418 return w;
2421 /* Create a menu item widget, and connect the callbacks.
2422 ITEM describes the menu item.
2423 F is the frame the created menu belongs to.
2424 SELECT_CB is the callback to use when a menu item is selected.
2425 HIGHLIGHT_CB is the callback to call when entering/leaving menu items.
2426 CL_DATA points to the callback data to be used for this menu.
2427 GROUP is an in/out parameter. If the menu item to be created is not
2428 part of any radio menu group, *GROUP contains NULL on entry and exit.
2429 If the menu item to be created is part of a radio menu group, on entry
2430 *GROUP contains the group to use, or NULL if this is the first item
2431 in the group. On exit, *GROUP contains the radio item group.
2433 Returns the created GtkWidget. */
2435 static GtkWidget *
2436 xg_create_one_menuitem (widget_value *item,
2437 struct frame *f,
2438 GCallback select_cb,
2439 GCallback highlight_cb,
2440 xg_menu_cb_data *cl_data,
2441 GSList **group)
2443 char *utf8_label;
2444 char *utf8_key;
2445 GtkWidget *w;
2446 xg_menu_item_cb_data *cb_data;
2448 utf8_label = get_utf8_string (item->name);
2449 utf8_key = get_utf8_string (item->key);
2451 w = make_menu_item (utf8_label, utf8_key, item, group);
2453 if (utf8_label) g_free (utf8_label);
2454 if (utf8_key) g_free (utf8_key);
2456 cb_data = xmalloc (sizeof *cb_data);
2458 xg_list_insert (&xg_menu_item_cb_list, &cb_data->ptrs);
2460 cb_data->select_id = 0;
2461 cb_data->help = item->help;
2462 cb_data->cl_data = cl_data;
2463 cb_data->call_data = item->call_data;
2465 g_signal_connect (G_OBJECT (w),
2466 "destroy",
2467 G_CALLBACK (menuitem_destroy_callback),
2468 cb_data);
2470 /* Put cb_data in widget, so we can get at it when modifying menubar */
2471 g_object_set_data (G_OBJECT (w), XG_ITEM_DATA, cb_data);
2473 /* final item, not a submenu */
2474 if (item->call_data && ! item->contents)
2476 if (select_cb)
2477 cb_data->select_id
2478 = g_signal_connect (G_OBJECT (w), "activate", select_cb, cb_data);
2481 return w;
2484 /* Create a full menu tree specified by DATA.
2485 F is the frame the created menu belongs to.
2486 SELECT_CB is the callback to use when a menu item is selected.
2487 DEACTIVATE_CB is the callback to use when a sub menu is not shown anymore.
2488 HIGHLIGHT_CB is the callback to call when entering/leaving menu items.
2489 If POP_UP_P, create a popup menu.
2490 If MENU_BAR_P, create a menu bar.
2491 TOPMENU is the topmost GtkWidget that others shall be placed under.
2492 It may be NULL, in that case we create the appropriate widget
2493 (menu bar or menu item depending on POP_UP_P and MENU_BAR_P)
2494 CL_DATA is the callback data we shall use for this menu, or NULL
2495 if we haven't set the first callback yet.
2496 NAME is the name to give to the top level menu if this function
2497 creates it. May be NULL to not set any name.
2499 Returns the top level GtkWidget. This is TOPLEVEL if TOPLEVEL is
2500 not NULL.
2502 This function calls itself to create submenus. */
2504 static GtkWidget *
2505 create_menus (widget_value *data,
2506 struct frame *f,
2507 GCallback select_cb,
2508 GCallback deactivate_cb,
2509 GCallback highlight_cb,
2510 bool pop_up_p,
2511 bool menu_bar_p,
2512 GtkWidget *topmenu,
2513 xg_menu_cb_data *cl_data,
2514 const char *name)
2516 widget_value *item;
2517 GtkWidget *wmenu = topmenu;
2518 GSList *group = NULL;
2520 if (! topmenu)
2522 if (! menu_bar_p)
2524 wmenu = gtk_menu_new ();
2525 xg_set_screen (wmenu, f);
2526 /* Connect this to the menu instead of items so we get enter/leave for
2527 disabled items also. TODO: Still does not get enter/leave for
2528 disabled items in detached menus. */
2529 g_signal_connect (G_OBJECT (wmenu),
2530 "enter-notify-event",
2531 G_CALLBACK (menuitem_highlight_callback),
2532 NULL);
2533 g_signal_connect (G_OBJECT (wmenu),
2534 "leave-notify-event",
2535 G_CALLBACK (menuitem_highlight_callback),
2536 NULL);
2538 else
2540 wmenu = gtk_menu_bar_new ();
2541 /* Set width of menu bar to a small value so it doesn't enlarge
2542 a small initial frame size. The width will be set to the
2543 width of the frame later on when it is added to a container.
2544 height -1: Natural height. */
2545 gtk_widget_set_size_request (wmenu, 1, -1);
2548 /* Put cl_data on the top menu for easier access. */
2549 cl_data = make_cl_data (cl_data, f, highlight_cb);
2550 g_object_set_data (G_OBJECT (wmenu), XG_FRAME_DATA, (gpointer)cl_data);
2551 g_signal_connect (G_OBJECT (wmenu), "destroy",
2552 G_CALLBACK (menu_destroy_callback), cl_data);
2554 if (name)
2555 gtk_widget_set_name (wmenu, name);
2557 if (deactivate_cb)
2558 g_signal_connect (G_OBJECT (wmenu),
2559 "selection-done", deactivate_cb, 0);
2562 for (item = data; item; item = item->next)
2564 GtkWidget *w;
2566 if (pop_up_p && !item->contents && !item->call_data
2567 && !menu_separator_name_p (item->name))
2569 char *utf8_label;
2570 /* A title for a popup. We do the same as GTK does when
2571 creating titles, but it does not look good. */
2572 group = NULL;
2573 utf8_label = get_utf8_string (item->name);
2575 w = gtk_menu_item_new_with_label (utf8_label);
2576 gtk_widget_set_sensitive (w, FALSE);
2577 if (utf8_label) g_free (utf8_label);
2579 else if (menu_separator_name_p (item->name))
2581 group = NULL;
2582 /* GTK only have one separator type. */
2583 w = gtk_separator_menu_item_new ();
2585 else
2587 w = xg_create_one_menuitem (item,
2589 item->contents ? 0 : select_cb,
2590 highlight_cb,
2591 cl_data,
2592 &group);
2594 /* Create a possibly empty submenu for menu bar items, since some
2595 themes don't highlight items correctly without it. */
2596 if (item->contents || menu_bar_p)
2598 GtkWidget *submenu = create_menus (item->contents,
2600 select_cb,
2601 deactivate_cb,
2602 highlight_cb,
2606 cl_data,
2608 gtk_menu_item_set_submenu (GTK_MENU_ITEM (w), submenu);
2612 gtk_menu_shell_append (GTK_MENU_SHELL (wmenu), w);
2613 gtk_widget_set_name (w, MENU_ITEM_NAME);
2616 return wmenu;
2619 /* Create a menubar, popup menu or dialog, depending on the TYPE argument.
2620 TYPE can be "menubar", "popup" for popup menu, or "dialog" for a dialog
2621 with some text and buttons.
2622 F is the frame the created item belongs to.
2623 NAME is the name to use for the top widget.
2624 VAL is a widget_value structure describing items to be created.
2625 SELECT_CB is the callback to use when a menu item is selected or
2626 a dialog button is pressed.
2627 DEACTIVATE_CB is the callback to use when an item is deactivated.
2628 For a menu, when a sub menu is not shown anymore, for a dialog it is
2629 called when the dialog is popped down.
2630 HIGHLIGHT_CB is the callback to call when entering/leaving menu items.
2632 Returns the widget created. */
2634 GtkWidget *
2635 xg_create_widget (const char *type, const char *name, struct frame *f,
2636 widget_value *val, GCallback select_cb,
2637 GCallback deactivate_cb, GCallback highlight_cb)
2639 GtkWidget *w = 0;
2640 bool menu_bar_p = strcmp (type, "menubar") == 0;
2641 bool pop_up_p = strcmp (type, "popup") == 0;
2643 if (strcmp (type, "dialog") == 0)
2645 w = create_dialog (val, select_cb, deactivate_cb);
2646 xg_set_screen (w, f);
2647 gtk_window_set_transient_for (GTK_WINDOW (w),
2648 GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
2649 gtk_window_set_destroy_with_parent (GTK_WINDOW (w), TRUE);
2650 gtk_widget_set_name (w, "emacs-dialog");
2651 gtk_window_set_modal (GTK_WINDOW (w), TRUE);
2653 else if (menu_bar_p || pop_up_p)
2655 w = create_menus (val->contents,
2657 select_cb,
2658 deactivate_cb,
2659 highlight_cb,
2660 pop_up_p,
2661 menu_bar_p,
2664 name);
2666 /* Set the cursor to an arrow for popup menus when they are mapped.
2667 This is done by default for menu bar menus. */
2668 if (pop_up_p)
2670 /* Must realize so the GdkWindow inside the widget is created. */
2671 gtk_widget_realize (w);
2672 xg_set_cursor (w, FRAME_DISPLAY_INFO (f)->xg_cursor);
2675 else
2677 fprintf (stderr, "bad type in xg_create_widget: %s, doing nothing\n",
2678 type);
2681 return w;
2684 /* Return the label for menu item WITEM. */
2686 static const char *
2687 xg_get_menu_item_label (GtkMenuItem *witem)
2689 GtkLabel *wlabel = GTK_LABEL (XG_BIN_CHILD (witem));
2690 return gtk_label_get_label (wlabel);
2693 /* Return true if the menu item WITEM has the text LABEL. */
2695 static bool
2696 xg_item_label_same_p (GtkMenuItem *witem, const char *label)
2698 bool is_same = 0;
2699 char *utf8_label = get_utf8_string (label);
2700 const char *old_label = witem ? xg_get_menu_item_label (witem) : 0;
2702 if (! old_label && ! utf8_label)
2703 is_same = 1;
2704 else if (old_label && utf8_label)
2705 is_same = strcmp (utf8_label, old_label) == 0;
2707 if (utf8_label) g_free (utf8_label);
2709 return is_same;
2712 /* Destroy widgets in LIST. */
2714 static void
2715 xg_destroy_widgets (GList *list)
2717 GList *iter;
2719 for (iter = list; iter; iter = g_list_next (iter))
2721 GtkWidget *w = GTK_WIDGET (iter->data);
2723 /* Destroying the widget will remove it from the container it is in. */
2724 gtk_widget_destroy (w);
2728 /* Update the top level names in MENUBAR (i.e. not submenus).
2729 F is the frame the menu bar belongs to.
2730 *LIST is a list with the current menu bar names (menu item widgets).
2731 ITER is the item within *LIST that shall be updated.
2732 POS is the numerical position, starting at 0, of ITER in *LIST.
2733 VAL describes what the menu bar shall look like after the update.
2734 SELECT_CB is the callback to use when a menu item is selected.
2735 HIGHLIGHT_CB is the callback to call when entering/leaving menu items.
2736 CL_DATA points to the callback data to be used for this menu bar.
2738 This function calls itself to walk through the menu bar names. */
2740 static void
2741 xg_update_menubar (GtkWidget *menubar,
2742 struct frame *f,
2743 GList **list,
2744 GList *iter,
2745 int pos,
2746 widget_value *val,
2747 GCallback select_cb,
2748 GCallback deactivate_cb,
2749 GCallback highlight_cb,
2750 xg_menu_cb_data *cl_data)
2752 if (! iter && ! val)
2753 return;
2754 else if (iter && ! val)
2756 /* Item(s) have been removed. Remove all remaining items. */
2757 xg_destroy_widgets (iter);
2759 /* Add a blank entry so the menubar doesn't collapse to nothing. */
2760 gtk_menu_shell_insert (GTK_MENU_SHELL (menubar),
2761 gtk_menu_item_new_with_label (""),
2763 /* All updated. */
2764 val = 0;
2765 iter = 0;
2767 else if (! iter && val)
2769 /* Item(s) added. Add all new items in one call. */
2770 create_menus (val, f, select_cb, deactivate_cb, highlight_cb,
2771 0, 1, menubar, cl_data, 0);
2773 /* All updated. */
2774 val = 0;
2775 iter = 0;
2777 /* Below this neither iter or val is NULL */
2778 else if (xg_item_label_same_p (GTK_MENU_ITEM (iter->data), val->name))
2780 /* This item is still the same, check next item. */
2781 val = val->next;
2782 iter = g_list_next (iter);
2783 ++pos;
2785 else /* This item is changed. */
2787 GtkMenuItem *witem = GTK_MENU_ITEM (iter->data);
2788 GtkMenuItem *witem2 = 0;
2789 bool val_in_menubar = 0;
2790 bool iter_in_new_menubar = 0;
2791 GList *iter2;
2792 widget_value *cur;
2794 /* See if the changed entry (val) is present later in the menu bar */
2795 for (iter2 = iter;
2796 iter2 && ! val_in_menubar;
2797 iter2 = g_list_next (iter2))
2799 witem2 = GTK_MENU_ITEM (iter2->data);
2800 val_in_menubar = xg_item_label_same_p (witem2, val->name);
2803 /* See if the current entry (iter) is present later in the
2804 specification for the new menu bar. */
2805 for (cur = val; cur && ! iter_in_new_menubar; cur = cur->next)
2806 iter_in_new_menubar = xg_item_label_same_p (witem, cur->name);
2808 if (val_in_menubar && ! iter_in_new_menubar)
2810 int nr = pos;
2812 /* This corresponds to:
2813 Current: A B C
2814 New: A C
2815 Remove B. */
2817 g_object_ref (G_OBJECT (witem));
2818 gtk_container_remove (GTK_CONTAINER (menubar), GTK_WIDGET (witem));
2819 gtk_widget_destroy (GTK_WIDGET (witem));
2821 /* Must get new list since the old changed. */
2822 g_list_free (*list);
2823 *list = iter = gtk_container_get_children (GTK_CONTAINER (menubar));
2824 while (nr-- > 0) iter = g_list_next (iter);
2826 else if (! val_in_menubar && ! iter_in_new_menubar)
2828 /* This corresponds to:
2829 Current: A B C
2830 New: A X C
2831 Rename B to X. This might seem to be a strange thing to do,
2832 since if there is a menu under B it will be totally wrong for X.
2833 But consider editing a C file. Then there is a C-mode menu
2834 (corresponds to B above).
2835 If then doing C-x C-f the minibuf menu (X above) replaces the
2836 C-mode menu. When returning from the minibuffer, we get
2837 back the C-mode menu. Thus we do:
2838 Rename B to X (C-mode to minibuf menu)
2839 Rename X to B (minibuf to C-mode menu).
2840 If the X menu hasn't been invoked, the menu under B
2841 is up to date when leaving the minibuffer. */
2842 GtkLabel *wlabel = GTK_LABEL (XG_BIN_CHILD (witem));
2843 char *utf8_label = get_utf8_string (val->name);
2845 /* GTK menu items don't notice when their labels have been
2846 changed from underneath them, so we have to explicitly
2847 use g_object_notify to tell listeners (e.g., a GMenuModel
2848 bridge that might be loaded) that the item's label has
2849 changed. */
2850 gtk_label_set_text (wlabel, utf8_label);
2851 #if GTK_CHECK_VERSION (2, 16, 0)
2852 g_object_notify (G_OBJECT (witem), "label");
2853 #endif
2854 if (utf8_label) g_free (utf8_label);
2855 iter = g_list_next (iter);
2856 val = val->next;
2857 ++pos;
2859 else if (! val_in_menubar && iter_in_new_menubar)
2861 /* This corresponds to:
2862 Current: A B C
2863 New: A X B C
2864 Insert X. */
2866 int nr = pos;
2867 GSList *group = 0;
2868 GtkWidget *w = xg_create_one_menuitem (val,
2870 select_cb,
2871 highlight_cb,
2872 cl_data,
2873 &group);
2875 /* Create a possibly empty submenu for menu bar items, since some
2876 themes don't highlight items correctly without it. */
2877 GtkWidget *submenu = create_menus (NULL, f,
2878 select_cb, deactivate_cb,
2879 highlight_cb,
2880 0, 0, 0, cl_data, 0);
2882 gtk_widget_set_name (w, MENU_ITEM_NAME);
2883 gtk_menu_shell_insert (GTK_MENU_SHELL (menubar), w, pos);
2884 gtk_menu_item_set_submenu (GTK_MENU_ITEM (w), submenu);
2886 g_list_free (*list);
2887 *list = iter = gtk_container_get_children (GTK_CONTAINER (menubar));
2888 while (nr-- > 0) iter = g_list_next (iter);
2889 iter = g_list_next (iter);
2890 val = val->next;
2891 ++pos;
2893 else /* if (val_in_menubar && iter_in_new_menubar) */
2895 int nr = pos;
2896 /* This corresponds to:
2897 Current: A B C
2898 New: A C B
2899 Move C before B */
2901 g_object_ref (G_OBJECT (witem2));
2902 gtk_container_remove (GTK_CONTAINER (menubar), GTK_WIDGET (witem2));
2903 gtk_menu_shell_insert (GTK_MENU_SHELL (menubar),
2904 GTK_WIDGET (witem2), pos);
2905 g_object_unref (G_OBJECT (witem2));
2907 g_list_free (*list);
2908 *list = iter = gtk_container_get_children (GTK_CONTAINER (menubar));
2909 while (nr-- > 0) iter = g_list_next (iter);
2910 if (iter) iter = g_list_next (iter);
2911 val = val->next;
2912 ++pos;
2916 /* Update the rest of the menu bar. */
2917 xg_update_menubar (menubar, f, list, iter, pos, val,
2918 select_cb, deactivate_cb, highlight_cb, cl_data);
2921 /* Update the menu item W so it corresponds to VAL.
2922 SELECT_CB is the callback to use when a menu item is selected.
2923 HIGHLIGHT_CB is the callback to call when entering/leaving menu items.
2924 CL_DATA is the data to set in the widget for menu invocation. */
2926 static void
2927 xg_update_menu_item (widget_value *val,
2928 GtkWidget *w,
2929 GCallback select_cb,
2930 GCallback highlight_cb,
2931 xg_menu_cb_data *cl_data)
2933 GtkWidget *wchild;
2934 GtkLabel *wlbl = 0;
2935 GtkLabel *wkey = 0;
2936 char *utf8_label;
2937 char *utf8_key;
2938 const char *old_label = 0;
2939 const char *old_key = 0;
2940 xg_menu_item_cb_data *cb_data;
2941 bool label_changed = false;
2943 wchild = XG_BIN_CHILD (w);
2944 utf8_label = get_utf8_string (val->name);
2945 utf8_key = get_utf8_string (val->key);
2947 /* See if W is a menu item with a key. See make_menu_item above. */
2948 if (GTK_IS_BOX (wchild))
2950 GList *list = gtk_container_get_children (GTK_CONTAINER (wchild));
2952 wlbl = GTK_LABEL (list->data);
2953 wkey = GTK_LABEL (list->next->data);
2954 g_list_free (list);
2956 if (! utf8_key)
2958 /* Remove the key and keep just the label. */
2959 g_object_ref (G_OBJECT (wlbl));
2960 gtk_container_remove (GTK_CONTAINER (w), wchild);
2961 gtk_container_add (GTK_CONTAINER (w), GTK_WIDGET (wlbl));
2962 g_object_unref (G_OBJECT (wlbl));
2963 wkey = 0;
2967 else /* Just a label. */
2969 wlbl = GTK_LABEL (wchild);
2971 /* Check if there is now a key. */
2972 if (utf8_key)
2974 GtkWidget *wtoadd = make_widget_for_menu_item (utf8_label, utf8_key);
2975 GList *list = gtk_container_get_children (GTK_CONTAINER (wtoadd));
2977 wlbl = GTK_LABEL (list->data);
2978 wkey = GTK_LABEL (list->next->data);
2979 g_list_free (list);
2981 gtk_container_remove (GTK_CONTAINER (w), wchild);
2982 gtk_container_add (GTK_CONTAINER (w), wtoadd);
2986 if (wkey) old_key = gtk_label_get_label (wkey);
2987 if (wlbl) old_label = gtk_label_get_label (wlbl);
2989 if (wkey && utf8_key && (! old_key || strcmp (utf8_key, old_key) != 0))
2991 label_changed = true;
2992 gtk_label_set_text (wkey, utf8_key);
2995 if (! old_label || strcmp (utf8_label, old_label) != 0)
2997 label_changed = true;
2998 gtk_label_set_text (wlbl, utf8_label);
3001 if (utf8_key) g_free (utf8_key);
3002 if (utf8_label) g_free (utf8_label);
3004 if (! val->enabled && gtk_widget_get_sensitive (w))
3005 gtk_widget_set_sensitive (w, FALSE);
3006 else if (val->enabled && ! gtk_widget_get_sensitive (w))
3007 gtk_widget_set_sensitive (w, TRUE);
3009 cb_data = g_object_get_data (G_OBJECT (w), XG_ITEM_DATA);
3010 if (cb_data)
3012 cb_data->call_data = val->call_data;
3013 cb_data->help = val->help;
3014 cb_data->cl_data = cl_data;
3016 /* We assume the callback functions don't change. */
3017 if (val->call_data && ! val->contents)
3019 /* This item shall have a select callback. */
3020 if (! cb_data->select_id)
3021 cb_data->select_id
3022 = g_signal_connect (G_OBJECT (w), "activate",
3023 select_cb, cb_data);
3025 else if (cb_data->select_id)
3027 g_signal_handler_disconnect (w, cb_data->select_id);
3028 cb_data->select_id = 0;
3032 #if GTK_CHECK_VERSION (2, 16, 0)
3033 if (label_changed) /* See comment in xg_update_menubar. */
3034 g_object_notify (G_OBJECT (w), "label");
3035 #endif
3038 /* Update the toggle menu item W so it corresponds to VAL. */
3040 static void
3041 xg_update_toggle_item (widget_value *val, GtkWidget *w)
3043 gtk_check_menu_item_set_active (GTK_CHECK_MENU_ITEM (w), val->selected);
3046 /* Update the radio menu item W so it corresponds to VAL. */
3048 static void
3049 xg_update_radio_item (widget_value *val, GtkWidget *w)
3051 gtk_check_menu_item_set_active (GTK_CHECK_MENU_ITEM (w), val->selected);
3054 /* Update the sub menu SUBMENU and all its children so it corresponds to VAL.
3055 SUBMENU may be NULL, in that case a new menu is created.
3056 F is the frame the menu bar belongs to.
3057 VAL describes the contents of the menu bar.
3058 SELECT_CB is the callback to use when a menu item is selected.
3059 DEACTIVATE_CB is the callback to use when a sub menu is not shown anymore.
3060 HIGHLIGHT_CB is the callback to call when entering/leaving menu items.
3061 CL_DATA is the call back data to use for any newly created items.
3063 Returns the updated submenu widget, that is SUBMENU unless SUBMENU
3064 was NULL. */
3066 static GtkWidget *
3067 xg_update_submenu (GtkWidget *submenu,
3068 struct frame *f,
3069 widget_value *val,
3070 GCallback select_cb,
3071 GCallback deactivate_cb,
3072 GCallback highlight_cb,
3073 xg_menu_cb_data *cl_data)
3075 GtkWidget *newsub = submenu;
3076 GList *list = 0;
3077 GList *iter;
3078 widget_value *cur;
3079 GList *first_radio = 0;
3081 if (submenu)
3082 list = gtk_container_get_children (GTK_CONTAINER (submenu));
3084 for (cur = val, iter = list;
3085 cur && iter;
3086 iter = g_list_next (iter), cur = cur->next)
3088 GtkWidget *w = GTK_WIDGET (iter->data);
3090 /* Remember first radio button in a group. If we get a mismatch in
3091 a radio group we must rebuild the whole group so that the connections
3092 in GTK becomes correct. */
3093 if (cur->button_type == BUTTON_TYPE_RADIO && ! first_radio)
3094 first_radio = iter;
3095 else if (cur->button_type != BUTTON_TYPE_RADIO
3096 && ! GTK_IS_RADIO_MENU_ITEM (w))
3097 first_radio = 0;
3099 if (GTK_IS_SEPARATOR_MENU_ITEM (w))
3101 if (! menu_separator_name_p (cur->name))
3102 break;
3104 else if (GTK_IS_CHECK_MENU_ITEM (w))
3106 if (cur->button_type != BUTTON_TYPE_TOGGLE)
3107 break;
3108 xg_update_toggle_item (cur, w);
3109 xg_update_menu_item (cur, w, select_cb, highlight_cb, cl_data);
3111 else if (GTK_IS_RADIO_MENU_ITEM (w))
3113 if (cur->button_type != BUTTON_TYPE_RADIO)
3114 break;
3115 xg_update_radio_item (cur, w);
3116 xg_update_menu_item (cur, w, select_cb, highlight_cb, cl_data);
3118 else if (GTK_IS_MENU_ITEM (w))
3120 GtkMenuItem *witem = GTK_MENU_ITEM (w);
3121 GtkWidget *sub;
3123 if (cur->button_type != BUTTON_TYPE_NONE ||
3124 menu_separator_name_p (cur->name))
3125 break;
3127 xg_update_menu_item (cur, w, select_cb, highlight_cb, cl_data);
3129 sub = gtk_menu_item_get_submenu (witem);
3130 if (sub && ! cur->contents)
3132 /* Not a submenu anymore. */
3133 g_object_ref (G_OBJECT (sub));
3134 remove_submenu (witem);
3135 gtk_widget_destroy (sub);
3137 else if (cur->contents)
3139 GtkWidget *nsub;
3141 nsub = xg_update_submenu (sub, f, cur->contents,
3142 select_cb, deactivate_cb,
3143 highlight_cb, cl_data);
3145 /* If this item just became a submenu, we must set it. */
3146 if (nsub != sub)
3147 gtk_menu_item_set_submenu (witem, nsub);
3150 else
3152 /* Structural difference. Remove everything from here and down
3153 in SUBMENU. */
3154 break;
3158 /* Remove widgets from first structural change. */
3159 if (iter)
3161 /* If we are adding new menu items below, we must remove from
3162 first radio button so that radio groups become correct. */
3163 if (cur && first_radio) xg_destroy_widgets (first_radio);
3164 else xg_destroy_widgets (iter);
3167 if (cur)
3169 /* More items added. Create them. */
3170 newsub = create_menus (cur,
3172 select_cb,
3173 deactivate_cb,
3174 highlight_cb,
3177 submenu,
3178 cl_data,
3182 if (list) g_list_free (list);
3184 return newsub;
3187 /* Update the MENUBAR.
3188 F is the frame the menu bar belongs to.
3189 VAL describes the contents of the menu bar.
3190 If DEEP_P, rebuild all but the top level menu names in
3191 the MENUBAR. If DEEP_P is zero, just rebuild the names in the menubar.
3192 SELECT_CB is the callback to use when a menu item is selected.
3193 DEACTIVATE_CB is the callback to use when a sub menu is not shown anymore.
3194 HIGHLIGHT_CB is the callback to call when entering/leaving menu items. */
3196 void
3197 xg_modify_menubar_widgets (GtkWidget *menubar, struct frame *f,
3198 widget_value *val, bool deep_p,
3199 GCallback select_cb, GCallback deactivate_cb,
3200 GCallback highlight_cb)
3202 xg_menu_cb_data *cl_data;
3203 GList *list = gtk_container_get_children (GTK_CONTAINER (menubar));
3205 if (! list) return;
3207 cl_data = g_object_get_data (G_OBJECT (menubar), XG_FRAME_DATA);
3209 xg_update_menubar (menubar, f, &list, list, 0, val->contents,
3210 select_cb, deactivate_cb, highlight_cb, cl_data);
3212 if (deep_p)
3214 widget_value *cur;
3216 /* Update all sub menus.
3217 We must keep the submenus (GTK menu item widgets) since the
3218 X Window in the XEvent that activates the menu are those widgets. */
3220 /* Update cl_data, menu_item things in F may have changed. */
3221 update_cl_data (cl_data, f, highlight_cb);
3223 for (cur = val->contents; cur; cur = cur->next)
3225 GList *iter;
3226 GtkWidget *sub = 0;
3227 GtkWidget *newsub;
3228 GtkMenuItem *witem = 0;
3230 /* Find sub menu that corresponds to val and update it. */
3231 for (iter = list ; iter; iter = g_list_next (iter))
3233 witem = GTK_MENU_ITEM (iter->data);
3234 if (xg_item_label_same_p (witem, cur->name))
3236 sub = gtk_menu_item_get_submenu (witem);
3237 break;
3241 newsub = xg_update_submenu (sub,
3243 cur->contents,
3244 select_cb,
3245 deactivate_cb,
3246 highlight_cb,
3247 cl_data);
3248 /* sub may still be NULL. If we just updated non deep and added
3249 a new menu bar item, it has no sub menu yet. So we set the
3250 newly created sub menu under witem. */
3251 if (newsub != sub && witem != 0)
3253 xg_set_screen (newsub, f);
3254 gtk_menu_item_set_submenu (witem, newsub);
3259 g_list_free (list);
3260 gtk_widget_show_all (menubar);
3263 /* Callback called when the menu bar W is mapped.
3264 Used to find the height of the menu bar if we didn't get it
3265 after showing the widget. */
3267 static void
3268 menubar_map_cb (GtkWidget *w, gpointer user_data)
3270 GtkRequisition req;
3271 struct frame *f = user_data;
3272 gtk_widget_get_preferred_size (w, NULL, &req);
3273 if (FRAME_MENUBAR_HEIGHT (f) != req.height)
3275 FRAME_MENUBAR_HEIGHT (f) = req.height;
3276 adjust_frame_size (f, -1, -1, 2, 0, Qmenu_bar_lines);
3280 /* Recompute all the widgets of frame F, when the menu bar has been
3281 changed. */
3283 void
3284 xg_update_frame_menubar (struct frame *f)
3286 struct x_output *x = f->output_data.x;
3287 GtkRequisition req;
3289 if (!x->menubar_widget || gtk_widget_get_mapped (x->menubar_widget))
3290 return;
3292 if (x->menubar_widget && gtk_widget_get_parent (x->menubar_widget))
3293 return; /* Already done this, happens for frames created invisible. */
3295 block_input ();
3297 gtk_box_pack_start (GTK_BOX (x->vbox_widget), x->menubar_widget,
3298 FALSE, FALSE, 0);
3299 gtk_box_reorder_child (GTK_BOX (x->vbox_widget), x->menubar_widget, 0);
3301 g_signal_connect (x->menubar_widget, "map", G_CALLBACK (menubar_map_cb), f);
3302 gtk_widget_show_all (x->menubar_widget);
3303 gtk_widget_get_preferred_size (x->menubar_widget, NULL, &req);
3305 if (FRAME_MENUBAR_HEIGHT (f) != req.height)
3307 FRAME_MENUBAR_HEIGHT (f) = req.height;
3308 adjust_frame_size (f, -1, -1, 2, 0, Qmenu_bar_lines);
3310 unblock_input ();
3313 /* Get rid of the menu bar of frame F, and free its storage.
3314 This is used when deleting a frame, and when turning off the menu bar. */
3316 void
3317 free_frame_menubar (struct frame *f)
3319 struct x_output *x = f->output_data.x;
3321 if (x->menubar_widget)
3323 block_input ();
3325 gtk_container_remove (GTK_CONTAINER (x->vbox_widget), x->menubar_widget);
3326 /* The menubar and its children shall be deleted when removed from
3327 the container. */
3328 x->menubar_widget = 0;
3329 FRAME_MENUBAR_HEIGHT (f) = 0;
3330 adjust_frame_size (f, -1, -1, 2, 0, Qmenu_bar_lines);
3331 unblock_input ();
3335 bool
3336 xg_event_is_for_menubar (struct frame *f, const XEvent *event)
3338 struct x_output *x = f->output_data.x;
3339 GList *iter;
3340 GdkRectangle rec;
3341 GList *list;
3342 GdkDisplay *gdpy;
3343 GdkWindow *gw;
3344 GdkEvent gevent;
3345 GtkWidget *gwdesc;
3347 if (! x->menubar_widget) return 0;
3349 if (! (event->xbutton.x >= 0
3350 && event->xbutton.x < FRAME_PIXEL_WIDTH (f)
3351 && event->xbutton.y >= 0
3352 && event->xbutton.y < FRAME_MENUBAR_HEIGHT (f)
3353 && event->xbutton.same_screen))
3354 return 0;
3356 gdpy = gdk_x11_lookup_xdisplay (FRAME_X_DISPLAY (f));
3357 gw = gdk_x11_window_lookup_for_display (gdpy, event->xbutton.window);
3358 if (! gw) return 0;
3359 gevent.any.window = gw;
3360 gevent.any.type = GDK_NOTHING;
3361 gwdesc = gtk_get_event_widget (&gevent);
3362 if (! gwdesc) return 0;
3363 if (! GTK_IS_MENU_BAR (gwdesc)
3364 && ! GTK_IS_MENU_ITEM (gwdesc)
3365 && ! gtk_widget_is_ancestor (x->menubar_widget, gwdesc))
3366 return 0;
3368 list = gtk_container_get_children (GTK_CONTAINER (x->menubar_widget));
3369 if (! list) return 0;
3370 rec.x = event->xbutton.x;
3371 rec.y = event->xbutton.y;
3372 rec.width = 1;
3373 rec.height = 1;
3375 for (iter = list ; iter; iter = g_list_next (iter))
3377 GtkWidget *w = GTK_WIDGET (iter->data);
3378 if (gtk_widget_get_mapped (w) && gtk_widget_intersect (w, &rec, NULL))
3379 break;
3381 g_list_free (list);
3382 return iter != 0;
3387 /***********************************************************************
3388 Scroll bar functions
3389 ***********************************************************************/
3392 /* Setting scroll bar values invokes the callback. Use this variable
3393 to indicate that callback should do nothing. */
3395 bool xg_ignore_gtk_scrollbar;
3397 /* Width and height of scroll bars for the current theme. */
3398 static int scroll_bar_width_for_theme;
3399 static int scroll_bar_height_for_theme;
3401 /* Xlib's `Window' fits in 32 bits. But we want to store pointers, and they
3402 may be larger than 32 bits. Keep a mapping from integer index to widget
3403 pointers to get around the 32 bit limitation. */
3405 static struct
3407 GtkWidget **widgets;
3408 ptrdiff_t max_size;
3409 ptrdiff_t used;
3410 } id_to_widget;
3412 /* Grow this much every time we need to allocate more */
3414 #define ID_TO_WIDGET_INCR 32
3416 /* Store the widget pointer W in id_to_widget and return the integer index. */
3418 static ptrdiff_t
3419 xg_store_widget_in_map (GtkWidget *w)
3421 ptrdiff_t i;
3423 if (id_to_widget.max_size == id_to_widget.used)
3425 ptrdiff_t new_size;
3426 if (TYPE_MAXIMUM (Window) - ID_TO_WIDGET_INCR < id_to_widget.max_size)
3427 memory_full (SIZE_MAX);
3429 new_size = id_to_widget.max_size + ID_TO_WIDGET_INCR;
3430 id_to_widget.widgets = xnrealloc (id_to_widget.widgets,
3431 new_size, sizeof (GtkWidget *));
3433 for (i = id_to_widget.max_size; i < new_size; ++i)
3434 id_to_widget.widgets[i] = 0;
3435 id_to_widget.max_size = new_size;
3438 /* Just loop over the array and find a free place. After all,
3439 how many scroll bars are we creating? Should be a small number.
3440 The check above guarantees we will find a free place. */
3441 for (i = 0; i < id_to_widget.max_size; ++i)
3443 if (! id_to_widget.widgets[i])
3445 id_to_widget.widgets[i] = w;
3446 ++id_to_widget.used;
3448 return i;
3452 /* Should never end up here */
3453 emacs_abort ();
3456 /* Remove pointer at IDX from id_to_widget.
3457 Called when scroll bar is destroyed. */
3459 static void
3460 xg_remove_widget_from_map (ptrdiff_t idx)
3462 if (idx < id_to_widget.max_size && id_to_widget.widgets[idx] != 0)
3464 id_to_widget.widgets[idx] = 0;
3465 --id_to_widget.used;
3469 /* Get the widget pointer at IDX from id_to_widget. */
3471 static GtkWidget *
3472 xg_get_widget_from_map (ptrdiff_t idx)
3474 if (idx < id_to_widget.max_size && id_to_widget.widgets[idx] != 0)
3475 return id_to_widget.widgets[idx];
3477 return 0;
3480 static void
3481 update_theme_scrollbar_width (void)
3483 #ifdef HAVE_GTK3
3484 GtkAdjustment *vadj;
3485 #else
3486 GtkObject *vadj;
3487 #endif
3488 GtkWidget *wscroll;
3489 int w = 0, b = 0;
3491 vadj = gtk_adjustment_new (XG_SB_MIN, XG_SB_MIN, XG_SB_MAX, 0.1, 0.1, 0.1);
3492 wscroll = gtk_scrollbar_new (GTK_ORIENTATION_VERTICAL, GTK_ADJUSTMENT (vadj));
3493 g_object_ref_sink (G_OBJECT (wscroll));
3494 gtk_widget_style_get (wscroll, "slider-width", &w, "trough-border", &b, NULL);
3495 gtk_widget_destroy (wscroll);
3496 g_object_unref (G_OBJECT (wscroll));
3497 w += 2*b;
3498 #ifndef HAVE_GTK3
3499 if (w < 16) w = 16;
3500 #endif
3501 scroll_bar_width_for_theme = w;
3504 static void
3505 update_theme_scrollbar_height (void)
3507 #ifdef HAVE_GTK3
3508 GtkAdjustment *hadj;
3509 #else
3510 GtkObject *hadj;
3511 #endif
3512 GtkWidget *wscroll;
3513 int w = 0, b = 0;
3515 hadj = gtk_adjustment_new (YG_SB_MIN, YG_SB_MIN, YG_SB_MAX, 0.1, 0.1, 0.1);
3516 wscroll = gtk_scrollbar_new (GTK_ORIENTATION_HORIZONTAL, GTK_ADJUSTMENT (hadj));
3517 g_object_ref_sink (G_OBJECT (wscroll));
3518 gtk_widget_style_get (wscroll, "slider-width", &w, "trough-border", &b, NULL);
3519 gtk_widget_destroy (wscroll);
3520 g_object_unref (G_OBJECT (wscroll));
3521 w += 2*b;
3522 if (w < 12) w = 12;
3523 scroll_bar_height_for_theme = w;
3527 xg_get_default_scrollbar_width (void)
3529 return scroll_bar_width_for_theme * xg_get_gdk_scale ();
3533 xg_get_default_scrollbar_height (void)
3535 /* Apparently there's no default height for themes. */
3536 return scroll_bar_width_for_theme * xg_get_gdk_scale ();
3539 /* Return the scrollbar id for X Window WID on display DPY.
3540 Return -1 if WID not in id_to_widget. */
3542 ptrdiff_t
3543 xg_get_scroll_id_for_window (Display *dpy, Window wid)
3545 ptrdiff_t idx;
3546 GtkWidget *w;
3548 w = xg_win_to_widget (dpy, wid);
3550 if (w)
3552 for (idx = 0; idx < id_to_widget.max_size; ++idx)
3553 if (id_to_widget.widgets[idx] == w)
3554 return idx;
3557 return -1;
3560 /* Callback invoked when scroll bar WIDGET is destroyed.
3561 DATA is the index into id_to_widget for WIDGET.
3562 We free pointer to last scroll bar values here and remove the index. */
3564 static void
3565 xg_gtk_scroll_destroy (GtkWidget *widget, gpointer data)
3567 intptr_t id = (intptr_t) data;
3568 xg_remove_widget_from_map (id);
3571 /* Create a scroll bar widget for frame F. Store the scroll bar
3572 in BAR.
3573 SCROLL_CALLBACK is the callback to invoke when the value of the
3574 bar changes.
3575 END_CALLBACK is the callback to invoke when scrolling ends.
3576 SCROLL_BAR_NAME is the name we use for the scroll bar. Can be used
3577 to set resources for the widget. */
3579 void
3580 xg_create_scroll_bar (struct frame *f,
3581 struct scroll_bar *bar,
3582 GCallback scroll_callback,
3583 GCallback end_callback,
3584 const char *scroll_bar_name)
3586 GtkWidget *wscroll;
3587 GtkWidget *webox;
3588 intptr_t scroll_id;
3589 #ifdef HAVE_GTK3
3590 GtkAdjustment *vadj;
3591 #else
3592 GtkObject *vadj;
3593 #endif
3595 /* Page, step increment values are not so important here, they
3596 will be corrected in x_set_toolkit_scroll_bar_thumb. */
3597 vadj = gtk_adjustment_new (XG_SB_MIN, XG_SB_MIN, XG_SB_MAX,
3598 0.1, 0.1, 0.1);
3600 wscroll = gtk_scrollbar_new (GTK_ORIENTATION_VERTICAL, GTK_ADJUSTMENT (vadj));
3601 webox = gtk_event_box_new ();
3602 gtk_widget_set_name (wscroll, scroll_bar_name);
3603 #ifndef HAVE_GTK3
3604 gtk_range_set_update_policy (GTK_RANGE (wscroll), GTK_UPDATE_CONTINUOUS);
3605 #endif
3606 g_object_set_data (G_OBJECT (wscroll), XG_FRAME_DATA, (gpointer)f);
3608 scroll_id = xg_store_widget_in_map (wscroll);
3610 g_signal_connect (G_OBJECT (wscroll),
3611 "destroy",
3612 G_CALLBACK (xg_gtk_scroll_destroy),
3613 (gpointer) scroll_id);
3614 g_signal_connect (G_OBJECT (wscroll),
3615 "change-value",
3616 scroll_callback,
3617 (gpointer) bar);
3618 g_signal_connect (G_OBJECT (wscroll),
3619 "button-release-event",
3620 end_callback,
3621 (gpointer) bar);
3623 /* The scroll bar widget does not draw on a window of its own. Instead
3624 it draws on the parent window, in this case the edit widget. So
3625 whenever the edit widget is cleared, the scroll bar needs to redraw
3626 also, which causes flicker. Put an event box between the edit widget
3627 and the scroll bar, so the scroll bar instead draws itself on the
3628 event box window. */
3629 gtk_fixed_put (GTK_FIXED (f->output_data.x->edit_widget), webox, -1, -1);
3630 gtk_container_add (GTK_CONTAINER (webox), wscroll);
3633 /* Set the cursor to an arrow. */
3634 xg_set_cursor (webox, FRAME_DISPLAY_INFO (f)->xg_cursor);
3636 bar->x_window = scroll_id;
3637 bar->horizontal = 0;
3640 /* Create a horizontal scroll bar widget for frame F. Store the scroll
3641 bar in BAR. SCROLL_CALLBACK is the callback to invoke when the value
3642 of the bar changes. END_CALLBACK is the callback to invoke when
3643 scrolling ends. SCROLL_BAR_NAME is the name we use for the scroll
3644 bar. Can be used to set resources for the widget. */
3646 void
3647 xg_create_horizontal_scroll_bar (struct frame *f,
3648 struct scroll_bar *bar,
3649 GCallback scroll_callback,
3650 GCallback end_callback,
3651 const char *scroll_bar_name)
3653 GtkWidget *wscroll;
3654 GtkWidget *webox;
3655 intptr_t scroll_id;
3656 #ifdef HAVE_GTK3
3657 GtkAdjustment *hadj;
3658 #else
3659 GtkObject *hadj;
3660 #endif
3662 /* Page, step increment values are not so important here, they
3663 will be corrected in x_set_toolkit_scroll_bar_thumb. */
3664 hadj = gtk_adjustment_new (YG_SB_MIN, YG_SB_MIN, YG_SB_MAX,
3665 0.1, 0.1, 0.1);
3667 wscroll = gtk_scrollbar_new (GTK_ORIENTATION_HORIZONTAL, GTK_ADJUSTMENT (hadj));
3668 webox = gtk_event_box_new ();
3669 gtk_widget_set_name (wscroll, scroll_bar_name);
3670 #ifndef HAVE_GTK3
3671 gtk_range_set_update_policy (GTK_RANGE (wscroll), GTK_UPDATE_CONTINUOUS);
3672 #endif
3673 g_object_set_data (G_OBJECT (wscroll), XG_FRAME_DATA, (gpointer)f);
3675 scroll_id = xg_store_widget_in_map (wscroll);
3677 g_signal_connect (G_OBJECT (wscroll),
3678 "destroy",
3679 G_CALLBACK (xg_gtk_scroll_destroy),
3680 (gpointer) scroll_id);
3681 g_signal_connect (G_OBJECT (wscroll),
3682 "change-value",
3683 scroll_callback,
3684 (gpointer) bar);
3685 g_signal_connect (G_OBJECT (wscroll),
3686 "button-release-event",
3687 end_callback,
3688 (gpointer) bar);
3690 /* The scroll bar widget does not draw on a window of its own. Instead
3691 it draws on the parent window, in this case the edit widget. So
3692 whenever the edit widget is cleared, the scroll bar needs to redraw
3693 also, which causes flicker. Put an event box between the edit widget
3694 and the scroll bar, so the scroll bar instead draws itself on the
3695 event box window. */
3696 gtk_fixed_put (GTK_FIXED (f->output_data.x->edit_widget), webox, -1, -1);
3697 gtk_container_add (GTK_CONTAINER (webox), wscroll);
3700 /* Set the cursor to an arrow. */
3701 xg_set_cursor (webox, FRAME_DISPLAY_INFO (f)->xg_cursor);
3703 bar->x_window = scroll_id;
3704 bar->horizontal = 1;
3707 /* Remove the scroll bar represented by SCROLLBAR_ID from the frame F. */
3709 void
3710 xg_remove_scroll_bar (struct frame *f, ptrdiff_t scrollbar_id)
3712 GtkWidget *w = xg_get_widget_from_map (scrollbar_id);
3713 if (w)
3715 GtkWidget *wparent = gtk_widget_get_parent (w);
3716 gtk_widget_destroy (w);
3717 gtk_widget_destroy (wparent);
3718 SET_FRAME_GARBAGED (f);
3722 /* Update the position of the vertical scroll bar represented by SCROLLBAR_ID
3723 in frame F.
3724 TOP/LEFT are the new pixel positions where the bar shall appear.
3725 WIDTH, HEIGHT is the size in pixels the bar shall have. */
3727 void
3728 xg_update_scrollbar_pos (struct frame *f,
3729 ptrdiff_t scrollbar_id,
3730 int top,
3731 int left,
3732 int width,
3733 int height)
3735 GtkWidget *wscroll = xg_get_widget_from_map (scrollbar_id);
3736 if (wscroll)
3738 GtkWidget *wfixed = f->output_data.x->edit_widget;
3739 GtkWidget *wparent = gtk_widget_get_parent (wscroll);
3740 gint msl;
3741 int scale = xg_get_gdk_scale ();
3743 top /= scale;
3744 left /= scale;
3745 height /= scale;
3746 left -= (scale - 1) * ((width / scale) >> 1);
3748 /* Clear out old position. */
3749 int oldx = -1, oldy = -1, oldw, oldh;
3750 if (gtk_widget_get_parent (wparent) == wfixed)
3752 gtk_container_child_get (GTK_CONTAINER (wfixed), wparent,
3753 "x", &oldx, "y", &oldy, NULL);
3754 gtk_widget_get_size_request (wscroll, &oldw, &oldh);
3757 /* Move and resize to new values. */
3758 gtk_fixed_move (GTK_FIXED (wfixed), wparent, left, top);
3759 gtk_widget_style_get (wscroll, "min-slider-length", &msl, NULL);
3760 if (msl > height)
3762 /* No room. Hide scroll bar as some themes output a warning if
3763 the height is less than the min size. */
3764 gtk_widget_hide (wparent);
3765 gtk_widget_hide (wscroll);
3767 else
3769 gtk_widget_show_all (wparent);
3770 gtk_widget_set_size_request (wscroll, width, height);
3772 #ifndef USE_CAIRO
3773 gtk_widget_queue_draw (wfixed);
3774 gdk_window_process_all_updates ();
3775 #endif
3776 if (oldx != -1 && oldw > 0 && oldh > 0)
3778 /* Clear under old scroll bar position. This must be done after
3779 the gtk_widget_queue_draw and gdk_window_process_all_updates
3780 above. */
3781 oldw += (scale - 1) * oldw;
3782 oldx -= (scale - 1) * oldw;
3783 x_clear_area (f, oldx, oldy, oldw, oldh);
3786 /* GTK does not redraw until the main loop is entered again, but
3787 if there are no X events pending we will not enter it. So we sync
3788 here to get some events. */
3790 x_sync (f);
3791 SET_FRAME_GARBAGED (f);
3792 cancel_mouse_face (f);
3797 /* Update the position of the horizontal scroll bar represented by SCROLLBAR_ID
3798 in frame F.
3799 TOP/LEFT are the new pixel positions where the bar shall appear.
3800 WIDTH, HEIGHT is the size in pixels the bar shall have. */
3802 void
3803 xg_update_horizontal_scrollbar_pos (struct frame *f,
3804 ptrdiff_t scrollbar_id,
3805 int top,
3806 int left,
3807 int width,
3808 int height)
3811 GtkWidget *wscroll = xg_get_widget_from_map (scrollbar_id);
3813 if (wscroll)
3815 GtkWidget *wfixed = f->output_data.x->edit_widget;
3816 GtkWidget *wparent = gtk_widget_get_parent (wscroll);
3817 gint msl;
3819 /* Clear out old position. */
3820 int oldx = -1, oldy = -1, oldw, oldh;
3821 if (gtk_widget_get_parent (wparent) == wfixed)
3823 gtk_container_child_get (GTK_CONTAINER (wfixed), wparent,
3824 "x", &oldx, "y", &oldy, NULL);
3825 gtk_widget_get_size_request (wscroll, &oldw, &oldh);
3828 /* Move and resize to new values. */
3829 gtk_fixed_move (GTK_FIXED (wfixed), wparent, left, top);
3830 gtk_widget_style_get (wscroll, "min-slider-length", &msl, NULL);
3831 if (msl > width)
3833 /* No room. Hide scroll bar as some themes output a warning if
3834 the width is less than the min size. */
3835 gtk_widget_hide (wparent);
3836 gtk_widget_hide (wscroll);
3838 else
3840 gtk_widget_show_all (wparent);
3841 gtk_widget_set_size_request (wscroll, width, height);
3843 gtk_widget_queue_draw (wfixed);
3844 gdk_window_process_all_updates ();
3845 if (oldx != -1 && oldw > 0 && oldh > 0)
3846 /* Clear under old scroll bar position. This must be done after
3847 the gtk_widget_queue_draw and gdk_window_process_all_updates
3848 above. */
3849 x_clear_area (f,
3850 oldx, oldy, oldw, oldh);
3852 /* GTK does not redraw until the main loop is entered again, but
3853 if there are no X events pending we will not enter it. So we sync
3854 here to get some events. */
3856 x_sync (f);
3857 SET_FRAME_GARBAGED (f);
3858 cancel_mouse_face (f);
3863 /* Get the current value of the range, truncated to an integer. */
3865 static int
3866 int_gtk_range_get_value (GtkRange *range)
3868 return gtk_range_get_value (range);
3872 /* Set the thumb size and position of scroll bar BAR. We are currently
3873 displaying PORTION out of a whole WHOLE, and our position POSITION. */
3875 void
3876 xg_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar,
3877 int portion,
3878 int position,
3879 int whole)
3881 GtkWidget *wscroll = xg_get_widget_from_map (bar->x_window);
3883 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
3885 if (wscroll && bar->dragging == -1)
3887 GtkAdjustment *adj;
3888 gdouble shown;
3889 gdouble top;
3890 int size, value;
3891 int old_size;
3892 int new_step;
3893 bool changed = 0;
3895 adj = gtk_range_get_adjustment (GTK_RANGE (wscroll));
3897 if (scroll_bar_adjust_thumb_portion_p)
3899 /* We do the same as for MOTIF in xterm.c, use 30 chars per
3900 line rather than the real portion value. This makes the
3901 thumb less likely to resize and that looks better. */
3902 portion = WINDOW_TOTAL_LINES (XWINDOW (bar->window)) * 30;
3904 /* When the thumb is at the bottom, position == whole.
3905 So we need to increase `whole' to make space for the thumb. */
3906 whole += portion;
3909 if (whole <= 0)
3910 top = 0, shown = 1;
3911 else
3913 top = (gdouble) position / whole;
3914 shown = (gdouble) portion / whole;
3917 size = clip_to_bounds (1, shown * XG_SB_RANGE, XG_SB_RANGE);
3918 value = clip_to_bounds (XG_SB_MIN, top * XG_SB_RANGE, XG_SB_MAX - size);
3920 /* Assume all lines are of equal size. */
3921 new_step = size / max (1, FRAME_LINES (f));
3923 old_size = gtk_adjustment_get_page_size (adj);
3924 if (old_size != size)
3926 int old_step = gtk_adjustment_get_step_increment (adj);
3927 if (old_step != new_step)
3929 gtk_adjustment_set_page_size (adj, size);
3930 gtk_adjustment_set_step_increment (adj, new_step);
3931 /* Assume a page increment is about 95% of the page size */
3932 gtk_adjustment_set_page_increment (adj, size - size / 20);
3933 changed = 1;
3937 if (changed || int_gtk_range_get_value (GTK_RANGE (wscroll)) != value)
3939 block_input ();
3941 /* gtk_range_set_value invokes the callback. Set
3942 ignore_gtk_scrollbar to make the callback do nothing */
3943 xg_ignore_gtk_scrollbar = 1;
3945 if (int_gtk_range_get_value (GTK_RANGE (wscroll)) != value)
3946 gtk_range_set_value (GTK_RANGE (wscroll), (gdouble)value);
3947 else if (changed)
3948 gtk_adjustment_changed (adj);
3950 xg_ignore_gtk_scrollbar = 0;
3952 unblock_input ();
3957 /* Set the thumb size and position of horizontal scroll bar BAR. We are
3958 currently displaying PORTION out of a whole WHOLE, and our position
3959 POSITION. */
3960 void
3961 xg_set_toolkit_horizontal_scroll_bar_thumb (struct scroll_bar *bar,
3962 int portion,
3963 int position,
3964 int whole)
3966 GtkWidget *wscroll = xg_get_widget_from_map (bar->x_window);
3968 if (wscroll && bar->dragging == -1)
3970 GtkAdjustment *adj;
3971 int lower = 0;
3972 int upper = max (whole - 1, 0);
3973 int pagesize = min (upper, max (portion, 0));
3974 int value = max (0, min (position, upper - pagesize));
3975 /* These should be set to something more <portion, whole>
3976 related. */
3977 int page_increment = 4;
3978 int step_increment = 1;
3980 block_input ();
3981 adj = gtk_range_get_adjustment (GTK_RANGE (wscroll));
3982 gtk_adjustment_configure (adj, (gdouble) value, (gdouble) lower,
3983 (gdouble) upper, (gdouble) step_increment,
3984 (gdouble) page_increment, (gdouble) pagesize);
3985 gtk_adjustment_changed (adj);
3986 unblock_input ();
3990 /* Return true if EVENT is for a scroll bar in frame F.
3991 When the same X window is used for several Gtk+ widgets, we cannot
3992 say for sure based on the X window alone if an event is for the
3993 frame. This function does additional checks. */
3995 bool
3996 xg_event_is_for_scrollbar (struct frame *f, const XEvent *event)
3998 bool retval = 0;
4000 if (f && event->type == ButtonPress && event->xbutton.button < 4)
4002 /* Check if press occurred outside the edit widget. */
4003 GdkDisplay *gdpy = gdk_x11_lookup_xdisplay (FRAME_X_DISPLAY (f));
4004 GdkWindow *gwin;
4005 #ifdef HAVE_GTK3
4006 GdkDevice *gdev = gdk_device_manager_get_client_pointer
4007 (gdk_display_get_device_manager (gdpy));
4008 gwin = gdk_device_get_window_at_position (gdev, NULL, NULL);
4009 #else
4010 gwin = gdk_display_get_window_at_pointer (gdpy, NULL, NULL);
4011 #endif
4012 retval = gwin != gtk_widget_get_window (f->output_data.x->edit_widget);
4014 else if (f
4015 && ((event->type == ButtonRelease && event->xbutton.button < 4)
4016 || event->type == MotionNotify))
4018 /* If we are releasing or moving the scroll bar, it has the grab. */
4019 GtkWidget *w = gtk_grab_get_current ();
4020 retval = w != 0 && GTK_IS_SCROLLBAR (w);
4023 return retval;
4027 /***********************************************************************
4028 Printing
4029 ***********************************************************************/
4030 #ifdef USE_CAIRO
4031 static GtkPrintSettings *print_settings = NULL;
4032 static GtkPageSetup *page_setup = NULL;
4034 void
4035 xg_page_setup_dialog (void)
4037 GtkPageSetup *new_page_setup = NULL;
4039 if (print_settings == NULL)
4040 print_settings = gtk_print_settings_new ();
4041 new_page_setup = gtk_print_run_page_setup_dialog (NULL, page_setup,
4042 print_settings);
4043 if (page_setup)
4044 g_object_unref (page_setup);
4045 page_setup = new_page_setup;
4048 Lisp_Object
4049 xg_get_page_setup (void)
4051 Lisp_Object orientation_symbol;
4053 if (page_setup == NULL)
4054 page_setup = gtk_page_setup_new ();
4056 switch (gtk_page_setup_get_orientation (page_setup))
4058 case GTK_PAGE_ORIENTATION_PORTRAIT:
4059 orientation_symbol = Qportrait;
4060 break;
4061 case GTK_PAGE_ORIENTATION_LANDSCAPE:
4062 orientation_symbol = Qlandscape;
4063 break;
4064 case GTK_PAGE_ORIENTATION_REVERSE_PORTRAIT:
4065 orientation_symbol = Qreverse_portrait;
4066 break;
4067 case GTK_PAGE_ORIENTATION_REVERSE_LANDSCAPE:
4068 orientation_symbol = Qreverse_landscape;
4069 break;
4070 default:
4071 eassume (false);
4074 return listn (CONSTYPE_HEAP, 7,
4075 Fcons (Qorientation, orientation_symbol),
4076 #define MAKE_FLOAT_PAGE_SETUP(f) make_float (f (page_setup, GTK_UNIT_POINTS))
4077 Fcons (Qwidth,
4078 MAKE_FLOAT_PAGE_SETUP (gtk_page_setup_get_page_width)),
4079 Fcons (Qheight,
4080 MAKE_FLOAT_PAGE_SETUP (gtk_page_setup_get_page_height)),
4081 Fcons (Qleft_margin,
4082 MAKE_FLOAT_PAGE_SETUP (gtk_page_setup_get_left_margin)),
4083 Fcons (Qright_margin,
4084 MAKE_FLOAT_PAGE_SETUP (gtk_page_setup_get_right_margin)),
4085 Fcons (Qtop_margin,
4086 MAKE_FLOAT_PAGE_SETUP (gtk_page_setup_get_top_margin)),
4087 Fcons (Qbottom_margin,
4088 MAKE_FLOAT_PAGE_SETUP (gtk_page_setup_get_bottom_margin))
4089 #undef MAKE_FLOAT_PAGE_SETUP
4093 static void
4094 draw_page (GtkPrintOperation *operation, GtkPrintContext *context,
4095 gint page_nr, gpointer user_data)
4097 Lisp_Object frames = *((Lisp_Object *) user_data);
4098 struct frame *f = XFRAME (Fnth (make_number (page_nr), frames));
4099 cairo_t *cr = gtk_print_context_get_cairo_context (context);
4101 x_cr_draw_frame (cr, f);
4104 void
4105 xg_print_frames_dialog (Lisp_Object frames)
4107 GtkPrintOperation *print;
4108 GtkPrintOperationResult res;
4110 print = gtk_print_operation_new ();
4111 if (print_settings != NULL)
4112 gtk_print_operation_set_print_settings (print, print_settings);
4113 if (page_setup != NULL)
4114 gtk_print_operation_set_default_page_setup (print, page_setup);
4115 gtk_print_operation_set_n_pages (print, XINT (Flength (frames)));
4116 g_signal_connect (print, "draw-page", G_CALLBACK (draw_page), &frames);
4117 res = gtk_print_operation_run (print, GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG,
4118 NULL, NULL);
4119 if (res == GTK_PRINT_OPERATION_RESULT_APPLY)
4121 if (print_settings != NULL)
4122 g_object_unref (print_settings);
4123 print_settings =
4124 g_object_ref (gtk_print_operation_get_print_settings (print));
4126 g_object_unref (print);
4129 #endif /* USE_CAIRO */
4133 /***********************************************************************
4134 Tool bar functions
4135 ***********************************************************************/
4136 /* The key for the data we put in the GtkImage widgets. The data is
4137 the image used by Emacs. We use this to see if we need to update
4138 the GtkImage with a new image. */
4139 #define XG_TOOL_BAR_IMAGE_DATA "emacs-tool-bar-image"
4141 /* The key for storing the latest modifiers so the activate callback can
4142 get them. */
4143 #define XG_TOOL_BAR_LAST_MODIFIER "emacs-tool-bar-modifier"
4145 /* The key for the data we put in the GtkImage widgets. The data is
4146 the stock name used by Emacs. We use this to see if we need to update
4147 the GtkImage with a new image. */
4148 #define XG_TOOL_BAR_STOCK_NAME "emacs-tool-bar-stock-name"
4150 /* As above, but this is used for named theme widgets, as opposed to
4151 stock items. */
4152 #define XG_TOOL_BAR_ICON_NAME "emacs-tool-bar-icon-name"
4154 /* Callback function invoked when a tool bar item is pressed.
4155 W is the button widget in the tool bar that got pressed,
4156 CLIENT_DATA is an integer that is the index of the button in the
4157 tool bar. 0 is the first button. */
4159 static gboolean
4160 xg_tool_bar_button_cb (GtkWidget *widget,
4161 GdkEventButton *event,
4162 gpointer user_data)
4164 intptr_t state = event->state;
4165 gpointer ptr = (gpointer) state;
4166 g_object_set_data (G_OBJECT (widget), XG_TOOL_BAR_LAST_MODIFIER, ptr);
4167 return FALSE;
4171 /* Callback function invoked when a tool bar item is pressed.
4172 W is the button widget in the tool bar that got pressed,
4173 CLIENT_DATA is an integer that is the index of the button in the
4174 tool bar. 0 is the first button. */
4176 static void
4177 xg_tool_bar_callback (GtkWidget *w, gpointer client_data)
4179 intptr_t idx = (intptr_t) client_data;
4180 gpointer gmod = g_object_get_data (G_OBJECT (w), XG_TOOL_BAR_LAST_MODIFIER);
4181 intptr_t mod = (intptr_t) gmod;
4183 struct frame *f = g_object_get_data (G_OBJECT (w), XG_FRAME_DATA);
4184 Lisp_Object key, frame;
4185 struct input_event event;
4186 EVENT_INIT (event);
4188 if (! f || ! f->n_tool_bar_items || NILP (f->tool_bar_items))
4189 return;
4191 idx *= TOOL_BAR_ITEM_NSLOTS;
4193 key = AREF (f->tool_bar_items, idx + TOOL_BAR_ITEM_KEY);
4194 XSETFRAME (frame, f);
4196 /* We generate two events here. The first one is to set the prefix
4197 to `(tool_bar)', see keyboard.c. */
4198 event.kind = TOOL_BAR_EVENT;
4199 event.frame_or_window = frame;
4200 event.arg = frame;
4201 kbd_buffer_store_event (&event);
4203 event.kind = TOOL_BAR_EVENT;
4204 event.frame_or_window = frame;
4205 event.arg = key;
4206 /* Convert between the modifier bits GDK uses and the modifier bits
4207 Emacs uses. This assumes GDK and X masks are the same, which they are when
4208 this is written. */
4209 event.modifiers = x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO (f), mod);
4210 kbd_buffer_store_event (&event);
4212 /* Return focus to the frame after we have clicked on a detached
4213 tool bar button. */
4214 x_focus_frame (f);
4217 static GtkWidget *
4218 xg_get_tool_bar_widgets (GtkWidget *vb, GtkWidget **wimage)
4220 GList *clist = gtk_container_get_children (GTK_CONTAINER (vb));
4221 GtkWidget *c1 = clist->data;
4222 GtkWidget *c2 = clist->next ? clist->next->data : NULL;
4224 *wimage = GTK_IS_IMAGE (c1) ? c1 : c2;
4225 g_list_free (clist);
4226 return GTK_IS_LABEL (c1) ? c1 : c2;
4230 /* This callback is called when the mouse enters or leaves a tool bar item.
4231 It is used for displaying and hiding the help text.
4232 W is the tool bar item, a button.
4233 EVENT is either an enter event or leave event.
4234 CLIENT_DATA is an integer that is the index of the button in the
4235 tool bar. 0 is the first button.
4237 Returns FALSE to tell GTK to keep processing this event. */
4239 static gboolean
4240 xg_tool_bar_help_callback (GtkWidget *w,
4241 GdkEventCrossing *event,
4242 gpointer client_data)
4244 intptr_t idx = (intptr_t) client_data;
4245 struct frame *f = g_object_get_data (G_OBJECT (w), XG_FRAME_DATA);
4246 Lisp_Object help, frame;
4248 if (! f || ! f->n_tool_bar_items || NILP (f->tool_bar_items))
4249 return FALSE;
4251 if (event->type == GDK_ENTER_NOTIFY)
4253 idx *= TOOL_BAR_ITEM_NSLOTS;
4254 help = AREF (f->tool_bar_items, idx + TOOL_BAR_ITEM_HELP);
4256 if (NILP (help))
4257 help = AREF (f->tool_bar_items, idx + TOOL_BAR_ITEM_CAPTION);
4259 else
4260 help = Qnil;
4262 XSETFRAME (frame, f);
4263 kbd_buffer_store_help_event (frame, help);
4265 return FALSE;
4269 /* This callback is called when a tool bar item shall be redrawn.
4270 It modifies the expose event so that the GtkImage widget redraws the
4271 whole image. This to overcome a bug that makes GtkImage draw the image
4272 in the wrong place when it tries to redraw just a part of the image.
4273 W is the GtkImage to be redrawn.
4274 EVENT is the expose event for W.
4275 CLIENT_DATA is unused.
4277 Returns FALSE to tell GTK to keep processing this event. */
4279 #ifndef HAVE_GTK3
4280 static gboolean
4281 xg_tool_bar_item_expose_callback (GtkWidget *w,
4282 GdkEventExpose *event,
4283 gpointer client_data)
4285 gint width, height;
4287 gdk_drawable_get_size (event->window, &width, &height);
4288 event->area.x -= width > event->area.width ? width-event->area.width : 0;
4289 event->area.y -= height > event->area.height ? height-event->area.height : 0;
4291 event->area.x = max (0, event->area.x);
4292 event->area.y = max (0, event->area.y);
4294 event->area.width = max (width, event->area.width);
4295 event->area.height = max (height, event->area.height);
4297 return FALSE;
4299 #endif
4301 #ifdef HAVE_GTK_ORIENTABLE_SET_ORIENTATION
4302 #define toolbar_set_orientation(w, o) \
4303 gtk_orientable_set_orientation (GTK_ORIENTABLE (w), o)
4304 #else
4305 #define toolbar_set_orientation(w, o) \
4306 gtk_toolbar_set_orientation (GTK_TOOLBAR (w), o)
4307 #endif
4309 /* Attach a tool bar to frame F. */
4311 static void
4312 xg_pack_tool_bar (struct frame *f, Lisp_Object pos)
4314 struct x_output *x = f->output_data.x;
4315 bool into_hbox = EQ (pos, Qleft) || EQ (pos, Qright);
4316 GtkWidget *top_widget = x->toolbar_widget;
4318 toolbar_set_orientation (x->toolbar_widget,
4319 into_hbox
4320 ? GTK_ORIENTATION_VERTICAL
4321 : GTK_ORIENTATION_HORIZONTAL);
4323 if (into_hbox)
4325 gtk_box_pack_start (GTK_BOX (x->hbox_widget), top_widget,
4326 FALSE, FALSE, 0);
4328 if (EQ (pos, Qleft))
4329 gtk_box_reorder_child (GTK_BOX (x->hbox_widget),
4330 top_widget,
4332 x->toolbar_in_hbox = true;
4334 else
4336 bool vbox_pos = x->menubar_widget != 0;
4337 gtk_box_pack_start (GTK_BOX (x->vbox_widget), top_widget,
4338 FALSE, FALSE, 0);
4340 if (EQ (pos, Qtop))
4341 gtk_box_reorder_child (GTK_BOX (x->vbox_widget),
4342 top_widget,
4343 vbox_pos);
4344 x->toolbar_in_hbox = false;
4346 x->toolbar_is_packed = true;
4349 static bool xg_update_tool_bar_sizes (struct frame *f);
4351 static void
4352 tb_size_cb (GtkWidget *widget,
4353 GdkRectangle *allocation,
4354 gpointer user_data)
4356 /* When tool bar is created it has one preferred size. But when size is
4357 allocated between widgets, it may get another. So we must update
4358 size hints if tool bar size changes. Seen on Fedora 18 at least. */
4359 struct frame *f = user_data;
4361 if (xg_update_tool_bar_sizes (f))
4363 frame_size_history_add (f, Qtb_size_cb, 0, 0, Qnil);
4364 adjust_frame_size (f, -1, -1, 5, 0, Qtool_bar_lines);
4368 /* Create a tool bar for frame F. */
4370 static void
4371 xg_create_tool_bar (struct frame *f)
4373 struct x_output *x = f->output_data.x;
4374 #if GTK_CHECK_VERSION (3, 3, 6)
4375 GtkStyleContext *gsty;
4376 #endif
4377 struct xg_frame_tb_info *tbinfo
4378 = g_object_get_data (G_OBJECT (FRAME_GTK_OUTER_WIDGET (f)),
4379 TB_INFO_KEY);
4380 if (! tbinfo)
4382 tbinfo = xmalloc (sizeof (*tbinfo));
4383 tbinfo->last_tool_bar = Qnil;
4384 tbinfo->style = Qnil;
4385 tbinfo->hmargin = tbinfo->vmargin = 0;
4386 tbinfo->dir = GTK_TEXT_DIR_NONE;
4387 tbinfo->n_last_items = 0;
4388 g_object_set_data (G_OBJECT (FRAME_GTK_OUTER_WIDGET (f)),
4389 TB_INFO_KEY,
4390 tbinfo);
4393 x->toolbar_widget = gtk_toolbar_new ();
4395 gtk_widget_set_name (x->toolbar_widget, "emacs-toolbar");
4397 gtk_toolbar_set_style (GTK_TOOLBAR (x->toolbar_widget), GTK_TOOLBAR_ICONS);
4398 toolbar_set_orientation (x->toolbar_widget, GTK_ORIENTATION_HORIZONTAL);
4399 g_signal_connect (x->toolbar_widget, "size-allocate",
4400 G_CALLBACK (tb_size_cb), f);
4401 #if GTK_CHECK_VERSION (3, 3, 6)
4402 gsty = gtk_widget_get_style_context (x->toolbar_widget);
4403 gtk_style_context_add_class (gsty, "primary-toolbar");
4404 #endif
4408 #define PROP(IDX) AREF (f->tool_bar_items, i * TOOL_BAR_ITEM_NSLOTS + (IDX))
4410 /* Find the right-to-left image named by RTL in the tool bar images for F.
4411 Returns IMAGE if RTL is not found. */
4413 static Lisp_Object
4414 find_rtl_image (struct frame *f, Lisp_Object image, Lisp_Object rtl)
4416 int i;
4417 Lisp_Object file, rtl_name;
4419 rtl_name = Ffile_name_nondirectory (rtl);
4421 for (i = 0; i < f->n_tool_bar_items; ++i)
4423 Lisp_Object rtl_image = PROP (TOOL_BAR_ITEM_IMAGES);
4424 if (!NILP (file = file_for_image (rtl_image)))
4426 file = call1 (intern ("file-name-sans-extension"),
4427 Ffile_name_nondirectory (file));
4428 if (! NILP (Fequal (file, rtl_name)))
4430 image = rtl_image;
4431 break;
4436 return image;
4439 static GtkToolItem *
4440 xg_make_tool_item (struct frame *f,
4441 GtkWidget *wimage,
4442 GtkWidget **wbutton,
4443 const char *label,
4444 int i, bool horiz, bool text_image)
4446 GtkToolItem *ti = gtk_tool_item_new ();
4447 GtkWidget *vb = gtk_box_new (horiz
4448 ? GTK_ORIENTATION_HORIZONTAL
4449 : GTK_ORIENTATION_VERTICAL,
4451 GtkWidget *wb = gtk_button_new ();
4452 /* The eventbox is here so we can have tooltips on disabled items. */
4453 GtkWidget *weventbox = gtk_event_box_new ();
4454 #if GTK_CHECK_VERSION (3, 3, 6)
4455 GtkCssProvider *css_prov = gtk_css_provider_new ();
4456 GtkStyleContext *gsty;
4458 gtk_css_provider_load_from_data (css_prov,
4459 "GtkEventBox {"
4460 " background-color: transparent;"
4461 "}",
4462 -1, NULL);
4464 gsty = gtk_widget_get_style_context (weventbox);
4465 gtk_style_context_add_provider (gsty,
4466 GTK_STYLE_PROVIDER (css_prov),
4467 GTK_STYLE_PROVIDER_PRIORITY_USER);
4468 g_object_unref (css_prov);
4469 #endif
4471 gtk_box_set_homogeneous (GTK_BOX (vb), FALSE);
4473 if (wimage && !text_image)
4474 gtk_box_pack_start (GTK_BOX (vb), wimage, TRUE, TRUE, 0);
4475 if (label)
4476 gtk_box_pack_start (GTK_BOX (vb), gtk_label_new (label), TRUE, TRUE, 0);
4477 if (wimage && text_image)
4478 gtk_box_pack_start (GTK_BOX (vb), wimage, TRUE, TRUE, 0);
4480 gtk_button_set_focus_on_click (GTK_BUTTON (wb), FALSE);
4481 gtk_button_set_relief (GTK_BUTTON (wb), GTK_RELIEF_NONE);
4482 gtk_container_add (GTK_CONTAINER (wb), vb);
4483 gtk_container_add (GTK_CONTAINER (weventbox), wb);
4484 gtk_container_add (GTK_CONTAINER (ti), weventbox);
4486 if (wimage || label)
4488 intptr_t ii = i;
4489 gpointer gi = (gpointer) ii;
4491 g_signal_connect (G_OBJECT (wb), "clicked",
4492 G_CALLBACK (xg_tool_bar_callback),
4493 gi);
4495 g_object_set_data (G_OBJECT (weventbox), XG_FRAME_DATA, (gpointer)f);
4497 #ifndef HAVE_GTK3
4498 /* Catch expose events to overcome an annoying redraw bug, see
4499 comment for xg_tool_bar_item_expose_callback. */
4500 g_signal_connect (G_OBJECT (ti),
4501 "expose-event",
4502 G_CALLBACK (xg_tool_bar_item_expose_callback),
4504 #endif
4505 gtk_tool_item_set_homogeneous (ti, FALSE);
4507 /* Callback to save modifier mask (Shift/Control, etc). GTK makes
4508 no distinction based on modifiers in the activate callback,
4509 so we have to do it ourselves. */
4510 g_signal_connect (wb, "button-release-event",
4511 G_CALLBACK (xg_tool_bar_button_cb),
4512 NULL);
4514 g_object_set_data (G_OBJECT (wb), XG_FRAME_DATA, (gpointer)f);
4516 /* Use enter/leave notify to show help. We use the events
4517 rather than the GtkButton specific signals "enter" and
4518 "leave", so we can have only one callback. The event
4519 will tell us what kind of event it is. */
4520 g_signal_connect (G_OBJECT (weventbox),
4521 "enter-notify-event",
4522 G_CALLBACK (xg_tool_bar_help_callback),
4523 gi);
4524 g_signal_connect (G_OBJECT (weventbox),
4525 "leave-notify-event",
4526 G_CALLBACK (xg_tool_bar_help_callback),
4527 gi);
4530 if (wbutton) *wbutton = wb;
4532 return ti;
4535 static bool
4536 is_box_type (GtkWidget *vb, bool is_horizontal)
4538 #ifdef HAVE_GTK3
4539 bool ret = 0;
4540 if (GTK_IS_BOX (vb))
4542 GtkOrientation ori = gtk_orientable_get_orientation (GTK_ORIENTABLE (vb));
4543 ret = (ori == GTK_ORIENTATION_HORIZONTAL && is_horizontal)
4544 || (ori == GTK_ORIENTATION_VERTICAL && ! is_horizontal);
4546 return ret;
4547 #else
4548 return is_horizontal ? GTK_IS_VBOX (vb) : GTK_IS_HBOX (vb);
4549 #endif
4553 static bool
4554 xg_tool_item_stale_p (GtkWidget *wbutton, const char *stock_name,
4555 const char *icon_name, const struct image *img,
4556 const char *label, bool horiz)
4558 gpointer old;
4559 GtkWidget *wimage;
4560 GtkWidget *vb = XG_BIN_CHILD (wbutton);
4561 GtkWidget *wlbl = xg_get_tool_bar_widgets (vb, &wimage);
4563 /* Check if the tool icon matches. */
4564 if (stock_name && wimage)
4566 old = g_object_get_data (G_OBJECT (wimage),
4567 XG_TOOL_BAR_STOCK_NAME);
4568 if (!old || strcmp (old, stock_name))
4569 return 1;
4571 else if (icon_name && wimage)
4573 old = g_object_get_data (G_OBJECT (wimage),
4574 XG_TOOL_BAR_ICON_NAME);
4575 if (!old || strcmp (old, icon_name))
4576 return 1;
4578 else if (wimage)
4580 gpointer gold_img = g_object_get_data (G_OBJECT (wimage),
4581 XG_TOOL_BAR_IMAGE_DATA);
4582 Pixmap old_img = (Pixmap) gold_img;
4583 if (old_img != img->pixmap)
4584 return 1;
4587 /* Check button configuration and label. */
4588 if (is_box_type (vb, horiz)
4589 || (label ? (wlbl == NULL) : (wlbl != NULL)))
4590 return 1;
4592 /* Ensure label is correct. */
4593 if (label && wlbl)
4594 gtk_label_set_text (GTK_LABEL (wlbl), label);
4595 return 0;
4598 static bool
4599 xg_update_tool_bar_sizes (struct frame *f)
4601 struct x_output *x = f->output_data.x;
4602 GtkRequisition req;
4603 int nl = 0, nr = 0, nt = 0, nb = 0;
4604 GtkWidget *top_widget = x->toolbar_widget;
4606 gtk_widget_get_preferred_size (GTK_WIDGET (top_widget), NULL, &req);
4607 if (x->toolbar_in_hbox)
4609 int pos;
4610 gtk_container_child_get (GTK_CONTAINER (x->hbox_widget),
4611 top_widget,
4612 "position", &pos, NULL);
4613 if (pos == 0) nl = req.width;
4614 else nr = req.width;
4616 else
4618 int pos;
4619 gtk_container_child_get (GTK_CONTAINER (x->vbox_widget),
4620 top_widget,
4621 "position", &pos, NULL);
4622 if (pos == 0 || (pos == 1 && x->menubar_widget)) nt = req.height;
4623 else nb = req.height;
4626 if (nl != FRAME_TOOLBAR_LEFT_WIDTH (f)
4627 || nr != FRAME_TOOLBAR_RIGHT_WIDTH (f)
4628 || nt != FRAME_TOOLBAR_TOP_HEIGHT (f)
4629 || nb != FRAME_TOOLBAR_BOTTOM_HEIGHT (f))
4631 FRAME_TOOLBAR_RIGHT_WIDTH (f) = FRAME_TOOLBAR_LEFT_WIDTH (f)
4632 = FRAME_TOOLBAR_TOP_HEIGHT (f) = FRAME_TOOLBAR_BOTTOM_HEIGHT (f) = 0;
4633 FRAME_TOOLBAR_LEFT_WIDTH (f) = nl;
4634 FRAME_TOOLBAR_RIGHT_WIDTH (f) = nr;
4635 FRAME_TOOLBAR_TOP_HEIGHT (f) = nt;
4636 FRAME_TOOLBAR_BOTTOM_HEIGHT (f) = nb;
4638 return true;
4640 else
4641 return false;
4644 static char *
4645 find_icon_from_name (char *name,
4646 GtkIconTheme *icon_theme,
4647 char **icon_name)
4649 #if ! GTK_CHECK_VERSION (3, 10, 0)
4650 GtkStockItem stock_item;
4651 #endif
4653 if (name[0] == 'n' && name[1] == ':')
4655 *icon_name = name + 2;
4656 name = NULL;
4658 if (! gtk_icon_theme_has_icon (icon_theme, *icon_name))
4659 *icon_name = NULL;
4662 #if ! GTK_CHECK_VERSION (3, 10, 0)
4663 else if (gtk_stock_lookup (name, &stock_item))
4664 *icon_name = NULL;
4665 #endif
4666 else if (gtk_icon_theme_has_icon (icon_theme, name))
4668 *icon_name = name;
4669 name = NULL;
4671 else
4673 name = NULL;
4674 *icon_name = NULL;
4677 return name;
4681 /* Update the tool bar for frame F. Add new buttons and remove old. */
4683 void
4684 update_frame_tool_bar (struct frame *f)
4686 int i, j;
4687 struct x_output *x = f->output_data.x;
4688 int hmargin = 0, vmargin = 0;
4689 GtkToolbar *wtoolbar;
4690 GtkToolItem *ti;
4691 GtkTextDirection dir;
4692 Lisp_Object style;
4693 bool text_image, horiz;
4694 struct xg_frame_tb_info *tbinfo;
4695 GdkScreen *screen;
4696 GtkIconTheme *icon_theme;
4699 if (! FRAME_GTK_WIDGET (f))
4700 return;
4702 block_input ();
4704 if (RANGED_INTEGERP (1, Vtool_bar_button_margin, INT_MAX))
4706 hmargin = XFASTINT (Vtool_bar_button_margin);
4707 vmargin = XFASTINT (Vtool_bar_button_margin);
4709 else if (CONSP (Vtool_bar_button_margin))
4711 if (RANGED_INTEGERP (1, XCAR (Vtool_bar_button_margin), INT_MAX))
4712 hmargin = XFASTINT (XCAR (Vtool_bar_button_margin));
4714 if (RANGED_INTEGERP (1, XCDR (Vtool_bar_button_margin), INT_MAX))
4715 vmargin = XFASTINT (XCDR (Vtool_bar_button_margin));
4718 /* The natural size (i.e. when GTK uses 0 as margin) looks best,
4719 so take DEFAULT_TOOL_BAR_BUTTON_MARGIN to mean "default for GTK",
4720 i.e. zero. This means that margins less than
4721 DEFAULT_TOOL_BAR_BUTTON_MARGIN has no effect. */
4722 hmargin = max (0, hmargin - DEFAULT_TOOL_BAR_BUTTON_MARGIN);
4723 vmargin = max (0, vmargin - DEFAULT_TOOL_BAR_BUTTON_MARGIN);
4725 if (! x->toolbar_widget)
4726 xg_create_tool_bar (f);
4728 wtoolbar = GTK_TOOLBAR (x->toolbar_widget);
4729 dir = gtk_widget_get_direction (GTK_WIDGET (wtoolbar));
4731 style = Ftool_bar_get_system_style ();
4732 screen = gtk_widget_get_screen (GTK_WIDGET (wtoolbar));
4733 icon_theme = gtk_icon_theme_get_for_screen (screen);
4735 /* Are we up to date? */
4736 tbinfo = g_object_get_data (G_OBJECT (FRAME_GTK_OUTER_WIDGET (f)),
4737 TB_INFO_KEY);
4739 if (! NILP (tbinfo->last_tool_bar) && ! NILP (f->tool_bar_items)
4740 && tbinfo->n_last_items == f->n_tool_bar_items
4741 && tbinfo->hmargin == hmargin && tbinfo->vmargin == vmargin
4742 && tbinfo->dir == dir
4743 && ! NILP (Fequal (tbinfo->style, style))
4744 && ! NILP (Fequal (tbinfo->last_tool_bar, f->tool_bar_items)))
4746 unblock_input ();
4747 return;
4750 tbinfo->last_tool_bar = f->tool_bar_items;
4751 tbinfo->n_last_items = f->n_tool_bar_items;
4752 tbinfo->style = style;
4753 tbinfo->hmargin = hmargin;
4754 tbinfo->vmargin = vmargin;
4755 tbinfo->dir = dir;
4757 text_image = EQ (style, Qtext_image_horiz);
4758 horiz = EQ (style, Qboth_horiz) || text_image;
4760 for (i = j = 0; i < f->n_tool_bar_items; ++i)
4762 bool enabled_p = !NILP (PROP (TOOL_BAR_ITEM_ENABLED_P));
4763 bool selected_p = !NILP (PROP (TOOL_BAR_ITEM_SELECTED_P));
4764 int idx;
4765 ptrdiff_t img_id;
4766 int icon_size = 0;
4767 struct image *img = NULL;
4768 Lisp_Object image;
4769 Lisp_Object stock = Qnil;
4770 char *stock_name = NULL;
4771 char *icon_name = NULL;
4772 Lisp_Object rtl;
4773 GtkWidget *wbutton = NULL;
4774 Lisp_Object specified_file;
4775 bool vert_only = ! NILP (PROP (TOOL_BAR_ITEM_VERT_ONLY));
4776 const char *label
4777 = (EQ (style, Qimage) || (vert_only && horiz)) ? NULL
4778 : STRINGP (PROP (TOOL_BAR_ITEM_LABEL))
4779 ? SSDATA (PROP (TOOL_BAR_ITEM_LABEL))
4780 : "";
4782 ti = gtk_toolbar_get_nth_item (GTK_TOOLBAR (wtoolbar), j);
4784 /* If this is a separator, use a gtk separator item. */
4785 if (EQ (PROP (TOOL_BAR_ITEM_TYPE), Qt))
4787 if (ti == NULL || !GTK_IS_SEPARATOR_TOOL_ITEM (ti))
4789 if (ti)
4790 gtk_container_remove (GTK_CONTAINER (wtoolbar),
4791 GTK_WIDGET (ti));
4792 ti = gtk_separator_tool_item_new ();
4793 gtk_toolbar_insert (GTK_TOOLBAR (wtoolbar), ti, j);
4795 j++;
4796 continue;
4799 /* Otherwise, the tool-bar item is an ordinary button. */
4801 if (ti && GTK_IS_SEPARATOR_TOOL_ITEM (ti))
4803 gtk_container_remove (GTK_CONTAINER (wtoolbar), GTK_WIDGET (ti));
4804 ti = NULL;
4807 if (ti) wbutton = XG_BIN_CHILD (XG_BIN_CHILD (ti));
4809 /* Ignore invalid image specifications. */
4810 image = PROP (TOOL_BAR_ITEM_IMAGES);
4811 if (!valid_image_p (image))
4813 if (ti)
4814 gtk_container_remove (GTK_CONTAINER (wtoolbar),
4815 GTK_WIDGET (ti));
4816 continue;
4819 specified_file = file_for_image (image);
4820 if (!NILP (specified_file) && !NILP (Ffboundp (Qx_gtk_map_stock)))
4821 stock = call1 (Qx_gtk_map_stock, specified_file);
4823 if (CONSP (stock))
4825 Lisp_Object tem;
4826 for (tem = stock; CONSP (tem); tem = XCDR (tem))
4827 if (! NILP (tem) && STRINGP (XCAR (tem)))
4829 stock_name = find_icon_from_name (SSDATA (XCAR (tem)),
4830 icon_theme,
4831 &icon_name);
4832 if (stock_name || icon_name) break;
4835 else if (STRINGP (stock))
4837 stock_name = find_icon_from_name (SSDATA (stock),
4838 icon_theme,
4839 &icon_name);
4842 if (stock_name || icon_name)
4843 icon_size = gtk_toolbar_get_icon_size (wtoolbar);
4845 if (stock_name == NULL && icon_name == NULL)
4847 /* No stock image, or stock item not known. Try regular
4848 image. If image is a vector, choose it according to the
4849 button state. */
4850 if (dir == GTK_TEXT_DIR_RTL
4851 && !NILP (rtl = PROP (TOOL_BAR_ITEM_RTL_IMAGE))
4852 && STRINGP (rtl))
4853 image = find_rtl_image (f, image, rtl);
4855 if (VECTORP (image))
4857 if (enabled_p)
4858 idx = (selected_p
4859 ? TOOL_BAR_IMAGE_ENABLED_SELECTED
4860 : TOOL_BAR_IMAGE_ENABLED_DESELECTED);
4861 else
4862 idx = (selected_p
4863 ? TOOL_BAR_IMAGE_DISABLED_SELECTED
4864 : TOOL_BAR_IMAGE_DISABLED_DESELECTED);
4866 eassert (ASIZE (image) >= idx);
4867 image = AREF (image, idx);
4869 else
4870 idx = -1;
4872 img_id = lookup_image (f, image);
4873 img = IMAGE_FROM_ID (f, img_id);
4874 prepare_image_for_display (f, img);
4876 if (img->load_failed_p || img->pixmap == None)
4878 if (ti)
4879 gtk_container_remove (GTK_CONTAINER (wtoolbar),
4880 GTK_WIDGET (ti));
4881 continue;
4885 /* If there is an existing widget, check if it's stale; if so,
4886 remove it and make a new tool item from scratch. */
4887 if (ti && xg_tool_item_stale_p (wbutton, stock_name, icon_name,
4888 img, label, horiz))
4890 gtk_container_remove (GTK_CONTAINER (wtoolbar),
4891 GTK_WIDGET (ti));
4892 ti = NULL;
4895 if (ti == NULL)
4897 GtkWidget *w;
4899 /* Save the image so we can see if an update is needed the
4900 next time we call xg_tool_item_match_p. */
4901 if (EQ (style, Qtext))
4902 w = NULL;
4903 else if (stock_name)
4906 #if GTK_CHECK_VERSION (3, 10, 0)
4907 w = gtk_image_new_from_icon_name (stock_name, icon_size);
4908 #else
4909 w = gtk_image_new_from_stock (stock_name, icon_size);
4910 #endif
4911 g_object_set_data_full (G_OBJECT (w), XG_TOOL_BAR_STOCK_NAME,
4912 (gpointer) xstrdup (stock_name),
4913 (GDestroyNotify) xfree);
4915 else if (icon_name)
4917 w = gtk_image_new_from_icon_name (icon_name, icon_size);
4918 g_object_set_data_full (G_OBJECT (w), XG_TOOL_BAR_ICON_NAME,
4919 (gpointer) xstrdup (icon_name),
4920 (GDestroyNotify) xfree);
4922 else
4924 w = xg_get_image_for_pixmap (f, img, x->widget, NULL);
4925 g_object_set_data (G_OBJECT (w), XG_TOOL_BAR_IMAGE_DATA,
4926 (gpointer)img->pixmap);
4929 #if GTK_CHECK_VERSION (3, 14, 0)
4930 if (w)
4932 gtk_widget_set_margin_start (w, hmargin);
4933 gtk_widget_set_margin_end (w, hmargin);
4934 gtk_widget_set_margin_top (w, vmargin);
4935 gtk_widget_set_margin_bottom (w, vmargin);
4937 #else
4938 if (w) gtk_misc_set_padding (GTK_MISC (w), hmargin, vmargin);
4939 #endif
4940 ti = xg_make_tool_item (f, w, &wbutton, label, i, horiz, text_image);
4941 gtk_toolbar_insert (GTK_TOOLBAR (wtoolbar), ti, j);
4944 #undef PROP
4946 gtk_widget_set_sensitive (wbutton, enabled_p);
4947 j++;
4950 /* Remove buttons not longer needed. */
4953 ti = gtk_toolbar_get_nth_item (GTK_TOOLBAR (wtoolbar), j);
4954 if (ti)
4955 gtk_container_remove (GTK_CONTAINER (wtoolbar), GTK_WIDGET (ti));
4956 } while (ti != NULL);
4958 if (f->n_tool_bar_items != 0)
4960 if (! x->toolbar_is_packed)
4961 xg_pack_tool_bar (f, FRAME_TOOL_BAR_POSITION (f));
4962 gtk_widget_show_all (x->toolbar_widget);
4963 if (xg_update_tool_bar_sizes (f))
4965 int inhibit
4966 = ((f->after_make_frame
4967 && !f->tool_bar_resized
4968 && (EQ (frame_inhibit_implied_resize, Qt)
4969 || (CONSP (frame_inhibit_implied_resize)
4970 && !NILP (Fmemq (Qtool_bar_lines,
4971 frame_inhibit_implied_resize))))
4972 /* This will probably fail to DTRT in the
4973 fullheight/-width cases. */
4974 && NILP (get_frame_param (f, Qfullscreen)))
4976 : 2);
4978 frame_size_history_add (f, Qupdate_frame_tool_bar, 0, 0, Qnil);
4979 adjust_frame_size (f, -1, -1, inhibit, 0, Qtool_bar_lines);
4981 f->tool_bar_resized = f->tool_bar_redisplayed;
4984 unblock_input ();
4987 /* Deallocate all resources for the tool bar on frame F.
4988 Remove the tool bar. */
4990 void
4991 free_frame_tool_bar (struct frame *f)
4993 struct x_output *x = f->output_data.x;
4995 if (x->toolbar_widget)
4997 struct xg_frame_tb_info *tbinfo;
4998 GtkWidget *top_widget = x->toolbar_widget;
5000 block_input ();
5001 if (x->toolbar_is_packed)
5003 if (x->toolbar_in_hbox)
5004 gtk_container_remove (GTK_CONTAINER (x->hbox_widget),
5005 top_widget);
5006 else
5007 gtk_container_remove (GTK_CONTAINER (x->vbox_widget),
5008 top_widget);
5010 else
5011 gtk_widget_destroy (x->toolbar_widget);
5013 x->toolbar_widget = 0;
5014 x->toolbar_widget = 0;
5015 x->toolbar_is_packed = false;
5016 FRAME_TOOLBAR_TOP_HEIGHT (f) = FRAME_TOOLBAR_BOTTOM_HEIGHT (f) = 0;
5017 FRAME_TOOLBAR_LEFT_WIDTH (f) = FRAME_TOOLBAR_RIGHT_WIDTH (f) = 0;
5019 tbinfo = g_object_get_data (G_OBJECT (FRAME_GTK_OUTER_WIDGET (f)),
5020 TB_INFO_KEY);
5021 if (tbinfo)
5023 xfree (tbinfo);
5024 g_object_set_data (G_OBJECT (FRAME_GTK_OUTER_WIDGET (f)),
5025 TB_INFO_KEY,
5026 NULL);
5029 frame_size_history_add (f, Qfree_frame_tool_bar, 0, 0, Qnil);
5030 adjust_frame_size (f, -1, -1, 2, 0, Qtool_bar_lines);
5032 unblock_input ();
5036 void
5037 xg_change_toolbar_position (struct frame *f, Lisp_Object pos)
5039 struct x_output *x = f->output_data.x;
5040 GtkWidget *top_widget = x->toolbar_widget;
5042 if (! x->toolbar_widget || ! top_widget)
5043 return;
5045 block_input ();
5046 g_object_ref (top_widget);
5047 if (x->toolbar_is_packed)
5049 if (x->toolbar_in_hbox)
5050 gtk_container_remove (GTK_CONTAINER (x->hbox_widget),
5051 top_widget);
5052 else
5053 gtk_container_remove (GTK_CONTAINER (x->vbox_widget),
5054 top_widget);
5057 xg_pack_tool_bar (f, pos);
5058 g_object_unref (top_widget);
5060 if (xg_update_tool_bar_sizes (f))
5062 frame_size_history_add (f, Qxg_change_toolbar_position, 0, 0, Qnil);
5063 adjust_frame_size (f, -1, -1, 2, 0, Qtool_bar_lines);
5067 unblock_input ();
5072 /***********************************************************************
5073 Initializing
5074 ***********************************************************************/
5075 void
5076 xg_initialize (void)
5078 GtkBindingSet *binding_set;
5079 GtkSettings *settings;
5081 #if HAVE_XFT
5082 /* Work around a bug with corrupted data if libXft gets unloaded. This way
5083 we keep it permanently linked in. */
5084 XftInit (0);
5085 #endif
5087 gdpy_def = NULL;
5088 xg_ignore_gtk_scrollbar = 0;
5089 xg_menu_cb_list.prev = xg_menu_cb_list.next =
5090 xg_menu_item_cb_list.prev = xg_menu_item_cb_list.next = 0;
5092 id_to_widget.max_size = id_to_widget.used = 0;
5093 id_to_widget.widgets = 0;
5095 settings = gtk_settings_get_for_screen (gdk_display_get_default_screen
5096 (gdk_display_get_default ()));
5097 /* Remove F10 as a menu accelerator, it does not mix well with Emacs key
5098 bindings. It doesn't seem to be any way to remove properties,
5099 so we set it to "" which in means "no key". */
5100 gtk_settings_set_string_property (settings,
5101 "gtk-menu-bar-accel",
5103 EMACS_CLASS);
5105 /* Make GTK text input widgets use Emacs style keybindings. This is
5106 Emacs after all. */
5107 gtk_settings_set_string_property (settings,
5108 "gtk-key-theme-name",
5109 "Emacs",
5110 EMACS_CLASS);
5112 /* Make dialogs close on C-g. Since file dialog inherits from
5113 dialog, this works for them also. */
5114 binding_set = gtk_binding_set_by_class (g_type_class_ref (GTK_TYPE_DIALOG));
5115 gtk_binding_entry_add_signal (binding_set, GDK_KEY_g, GDK_CONTROL_MASK,
5116 "close", 0);
5118 /* Make menus close on C-g. */
5119 binding_set = gtk_binding_set_by_class (g_type_class_ref
5120 (GTK_TYPE_MENU_SHELL));
5121 gtk_binding_entry_add_signal (binding_set, GDK_KEY_g, GDK_CONTROL_MASK,
5122 "cancel", 0);
5123 update_theme_scrollbar_width ();
5124 update_theme_scrollbar_height ();
5126 #ifdef HAVE_FREETYPE
5127 x_last_font_name = NULL;
5128 #endif
5131 #endif /* USE_GTK */