Avoid kill-emacs-hook errors hanging batch mode
[emacs.git] / src / xterm.c
blob0a2068d7f3016b8b44bdb6d34e5f9445d0521eb3
1 /* X Communication module for terminals which understand the X protocol.
3 Copyright (C) 1989, 1993-2018 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or (at
10 your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>. */
20 /* New display code by Gerd Moellmann <gerd@gnu.org>. */
21 /* Xt features made by Fred Pierresteguy. */
23 #include <config.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <math.h>
28 #include "lisp.h"
29 #include "blockinput.h"
31 /* This may include sys/types.h, and that somehow loses
32 if this is not done before the other system files. */
33 #include "xterm.h"
34 #include <X11/cursorfont.h>
36 /* If we have Xfixes extension, use it for pointer blanking. */
37 #ifdef HAVE_XFIXES
38 #include <X11/extensions/Xfixes.h>
39 #endif
41 /* Using Xft implies that XRender is available. */
42 #ifdef HAVE_XFT
43 #include <X11/extensions/Xrender.h>
44 #endif
46 #ifdef HAVE_XDBE
47 #include <X11/extensions/Xdbe.h>
48 #endif
50 /* Load sys/types.h if not already loaded.
51 In some systems loading it twice is suicidal. */
52 #ifndef makedev
53 #include <sys/types.h>
54 #endif /* makedev */
56 #include <sys/ioctl.h>
58 #include "systime.h"
60 #include <fcntl.h>
61 #include <errno.h>
62 #include <sys/stat.h>
63 #include "character.h"
64 #include "coding.h"
65 #include "composite.h"
66 #include "frame.h"
67 #include "dispextern.h"
68 #include "xwidget.h"
69 #include "fontset.h"
70 #include "termhooks.h"
71 #include "termopts.h"
72 #include "termchar.h"
73 #include "emacs-icon.h"
74 #include "buffer.h"
75 #include "window.h"
76 #include "keyboard.h"
77 #include "atimer.h"
78 #include "font.h"
79 #include "xsettings.h"
80 #include "sysselect.h"
81 #include "menu.h"
83 #ifdef USE_X_TOOLKIT
84 #include <X11/Shell.h>
85 #endif
87 #include <unistd.h>
89 #ifdef USE_GTK
90 #include "gtkutil.h"
91 #ifdef HAVE_GTK3
92 #include <X11/Xproto.h>
93 #endif
94 #endif
96 #if defined (USE_LUCID) || defined (USE_MOTIF)
97 #include "../lwlib/xlwmenu.h"
98 #endif
100 #ifdef USE_X_TOOLKIT
102 /* Include toolkit specific headers for the scroll bar widget. */
104 #ifdef USE_TOOLKIT_SCROLL_BARS
105 #if defined USE_MOTIF
106 #include <Xm/Xm.h> /* For LESSTIF_VERSION */
107 #include <Xm/ScrollBar.h>
108 #else /* !USE_MOTIF i.e. use Xaw */
110 #ifdef HAVE_XAW3D
111 #include <X11/Xaw3d/Simple.h>
112 #include <X11/Xaw3d/Scrollbar.h>
113 #include <X11/Xaw3d/ThreeD.h>
114 #else /* !HAVE_XAW3D */
115 #include <X11/Xaw/Simple.h>
116 #include <X11/Xaw/Scrollbar.h>
117 #endif /* !HAVE_XAW3D */
118 #ifndef XtNpickTop
119 #define XtNpickTop "pickTop"
120 #endif /* !XtNpickTop */
121 #endif /* !USE_MOTIF */
122 #endif /* USE_TOOLKIT_SCROLL_BARS */
124 #endif /* USE_X_TOOLKIT */
126 #ifdef USE_X_TOOLKIT
127 #include "widget.h"
128 #ifndef XtNinitialState
129 #define XtNinitialState "initialState"
130 #endif
131 #endif
133 #include "bitmaps/gray.xbm"
135 #ifdef HAVE_XKB
136 #include <X11/XKBlib.h>
137 #endif
139 /* Default to using XIM if available. */
140 #ifdef USE_XIM
141 bool use_xim = true;
142 #else
143 bool use_xim = false; /* configure --without-xim */
144 #endif
146 /* Non-zero means that a HELP_EVENT has been generated since Emacs
147 start. */
149 static bool any_help_event_p;
151 /* This is a chain of structures for all the X displays currently in
152 use. */
154 struct x_display_info *x_display_list;
156 #ifdef USE_X_TOOLKIT
158 /* The application context for Xt use. */
159 XtAppContext Xt_app_con;
160 static String Xt_default_resources[] = {0};
162 /* Non-zero means user is interacting with a toolkit scroll bar. */
163 static bool toolkit_scroll_bar_interaction;
165 #endif /* USE_X_TOOLKIT */
167 /* Non-zero timeout value means ignore next mouse click if it arrives
168 before that timeout elapses (i.e. as part of the same sequence of
169 events resulting from clicking on a frame to select it). */
171 static Time ignore_next_mouse_click_timeout;
173 /* Used locally within XTread_socket. */
175 static int x_noop_count;
177 #ifdef USE_GTK
178 /* The name of the Emacs icon file. */
179 static Lisp_Object xg_default_icon_file;
180 #endif
182 /* Some functions take this as char *, not const char *. */
183 static char emacs_class[] = EMACS_CLASS;
185 enum xembed_info
187 XEMBED_MAPPED = 1 << 0
190 enum xembed_message
192 XEMBED_EMBEDDED_NOTIFY = 0,
193 XEMBED_WINDOW_ACTIVATE = 1,
194 XEMBED_WINDOW_DEACTIVATE = 2,
195 XEMBED_REQUEST_FOCUS = 3,
196 XEMBED_FOCUS_IN = 4,
197 XEMBED_FOCUS_OUT = 5,
198 XEMBED_FOCUS_NEXT = 6,
199 XEMBED_FOCUS_PREV = 7,
201 XEMBED_MODALITY_ON = 10,
202 XEMBED_MODALITY_OFF = 11,
203 XEMBED_REGISTER_ACCELERATOR = 12,
204 XEMBED_UNREGISTER_ACCELERATOR = 13,
205 XEMBED_ACTIVATE_ACCELERATOR = 14
208 static void x_free_cr_resources (struct frame *);
209 static bool x_alloc_nearest_color_1 (Display *, Colormap, XColor *);
210 static void x_raise_frame (struct frame *);
211 static void x_lower_frame (struct frame *);
212 static int x_io_error_quitter (Display *);
213 static struct terminal *x_create_terminal (struct x_display_info *);
214 static void x_frame_rehighlight (struct x_display_info *);
216 static void x_clip_to_row (struct window *, struct glyph_row *,
217 enum glyph_row_area, GC);
218 static struct scroll_bar *x_window_to_scroll_bar (Display *, Window, int);
219 static void x_scroll_bar_report_motion (struct frame **, Lisp_Object *,
220 enum scroll_bar_part *,
221 Lisp_Object *, Lisp_Object *,
222 Time *);
223 static void x_horizontal_scroll_bar_report_motion (struct frame **, Lisp_Object *,
224 enum scroll_bar_part *,
225 Lisp_Object *, Lisp_Object *,
226 Time *);
227 static bool x_handle_net_wm_state (struct frame *, const XPropertyEvent *);
228 static void x_check_fullscreen (struct frame *);
229 static void x_check_expected_move (struct frame *, int, int);
230 static void x_sync_with_move (struct frame *, int, int, bool);
231 static int handle_one_xevent (struct x_display_info *,
232 const XEvent *, int *,
233 struct input_event *);
234 #if ! (defined USE_X_TOOLKIT || defined USE_MOTIF) && defined USE_GTK
235 static int x_dispatch_event (XEvent *, Display *);
236 #endif
237 static void x_wm_set_window_state (struct frame *, int);
238 static void x_wm_set_icon_pixmap (struct frame *, ptrdiff_t);
239 static void x_initialize (void);
241 static bool get_current_wm_state (struct frame *, Window, int *, bool *);
243 /* Flush display of frame F. */
245 static void
246 x_flush (struct frame *f)
248 eassert (f && FRAME_X_P (f));
249 /* Don't call XFlush when it is not safe to redisplay; the X
250 connection may be broken. */
251 if (!NILP (Vinhibit_redisplay))
252 return;
254 block_input ();
255 XFlush (FRAME_X_DISPLAY (f));
256 unblock_input ();
260 /* Remove calls to XFlush by defining XFlush to an empty replacement.
261 Calls to XFlush should be unnecessary because the X output buffer
262 is flushed automatically as needed by calls to XPending,
263 XNextEvent, or XWindowEvent according to the XFlush man page.
264 XTread_socket calls XPending. Removing XFlush improves
265 performance. */
267 #define XFlush(DISPLAY) (void) 0
270 /***********************************************************************
271 Debugging
272 ***********************************************************************/
274 #if false
276 /* This is a function useful for recording debugging information about
277 the sequence of occurrences in this file. */
279 struct record
281 char *locus;
282 int type;
285 struct record event_record[100];
287 int event_record_index;
289 void
290 record_event (char *locus, int type)
292 if (event_record_index == ARRAYELTS (event_record))
293 event_record_index = 0;
295 event_record[event_record_index].locus = locus;
296 event_record[event_record_index].type = type;
297 event_record_index++;
300 #endif
302 #ifdef USE_CAIRO
304 #define FRAME_CR_CONTEXT(f) ((f)->output_data.x->cr_context)
305 #define FRAME_CR_SURFACE(f) ((f)->output_data.x->cr_surface)
307 static struct x_gc_ext_data *
308 x_gc_get_ext_data (struct frame *f, GC gc, int create_if_not_found_p)
310 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
311 XEDataObject object;
312 XExtData **head, *ext_data;
314 object.gc = gc;
315 head = XEHeadOfExtensionList (object);
316 ext_data = XFindOnExtensionList (head, dpyinfo->ext_codes->extension);
317 if (ext_data == NULL)
319 if (!create_if_not_found_p)
320 return NULL;
321 else
323 ext_data = xzalloc (sizeof (*ext_data));
324 ext_data->number = dpyinfo->ext_codes->extension;
325 ext_data->private_data = xzalloc (sizeof (struct x_gc_ext_data));
326 XAddToExtensionList (head, ext_data);
329 return (struct x_gc_ext_data *) ext_data->private_data;
332 static void
333 x_extension_initialize (struct x_display_info *dpyinfo)
335 XExtCodes *ext_codes = XAddExtension (dpyinfo->display);
337 dpyinfo->ext_codes = ext_codes;
340 static void
341 x_cr_destroy_surface (struct frame *f)
343 if (FRAME_CR_SURFACE (f))
345 cairo_t *cr = FRAME_CR_CONTEXT (f);
346 cairo_surface_destroy (FRAME_CR_SURFACE (f));
347 FRAME_CR_SURFACE (f) = 0;
348 if (cr) cairo_destroy (cr);
349 FRAME_CR_CONTEXT (f) = NULL;
353 cairo_t *
354 x_begin_cr_clip (struct frame *f, GC gc)
356 cairo_t *cr = FRAME_CR_CONTEXT (f);
358 if (!cr)
361 if (! FRAME_CR_SURFACE (f))
363 cairo_surface_t *surface;
364 surface = cairo_xlib_surface_create (FRAME_X_DISPLAY (f),
365 FRAME_X_DRAWABLE (f),
366 FRAME_DISPLAY_INFO (f)->visual,
367 FRAME_PIXEL_WIDTH (f),
368 FRAME_PIXEL_HEIGHT (f));
369 cr = cairo_create (surface);
370 cairo_surface_destroy (surface);
372 else
373 cr = cairo_create (FRAME_CR_SURFACE (f));
374 FRAME_CR_CONTEXT (f) = cr;
376 cairo_save (cr);
378 if (gc)
380 struct x_gc_ext_data *gc_ext = x_gc_get_ext_data (f, gc, 0);
382 if (gc_ext && gc_ext->n_clip_rects)
384 int i;
386 for (i = 0; i < gc_ext->n_clip_rects; i++)
387 cairo_rectangle (cr, gc_ext->clip_rects[i].x,
388 gc_ext->clip_rects[i].y,
389 gc_ext->clip_rects[i].width,
390 gc_ext->clip_rects[i].height);
391 cairo_clip (cr);
395 return cr;
398 void
399 x_end_cr_clip (struct frame *f)
401 cairo_restore (FRAME_CR_CONTEXT (f));
404 void
405 x_set_cr_source_with_gc_foreground (struct frame *f, GC gc)
407 XGCValues xgcv;
408 XColor color;
410 XGetGCValues (FRAME_X_DISPLAY (f), gc, GCForeground, &xgcv);
411 color.pixel = xgcv.foreground;
412 x_query_color (f, &color);
413 cairo_set_source_rgb (FRAME_CR_CONTEXT (f), color.red / 65535.0,
414 color.green / 65535.0, color.blue / 65535.0);
417 void
418 x_set_cr_source_with_gc_background (struct frame *f, GC gc)
420 XGCValues xgcv;
421 XColor color;
423 XGetGCValues (FRAME_X_DISPLAY (f), gc, GCBackground, &xgcv);
424 color.pixel = xgcv.background;
425 x_query_color (f, &color);
426 cairo_set_source_rgb (FRAME_CR_CONTEXT (f), color.red / 65535.0,
427 color.green / 65535.0, color.blue / 65535.0);
430 /* Fringe bitmaps. */
432 static int max_fringe_bmp = 0;
433 static cairo_pattern_t **fringe_bmp = 0;
435 static void
436 x_cr_define_fringe_bitmap (int which, unsigned short *bits, int h, int wd)
438 int i, stride;
439 cairo_surface_t *surface;
440 unsigned char *data;
441 cairo_pattern_t *pattern;
443 if (which >= max_fringe_bmp)
445 i = max_fringe_bmp;
446 max_fringe_bmp = which + 20;
447 fringe_bmp = (cairo_pattern_t **) xrealloc (fringe_bmp, max_fringe_bmp * sizeof (cairo_pattern_t *));
448 while (i < max_fringe_bmp)
449 fringe_bmp[i++] = 0;
452 block_input ();
454 surface = cairo_image_surface_create (CAIRO_FORMAT_A1, wd, h);
455 stride = cairo_image_surface_get_stride (surface);
456 data = cairo_image_surface_get_data (surface);
458 for (i = 0; i < h; i++)
460 *((unsigned short *) data) = bits[i];
461 data += stride;
464 cairo_surface_mark_dirty (surface);
465 pattern = cairo_pattern_create_for_surface (surface);
466 cairo_surface_destroy (surface);
468 unblock_input ();
470 fringe_bmp[which] = pattern;
473 static void
474 x_cr_destroy_fringe_bitmap (int which)
476 if (which >= max_fringe_bmp)
477 return;
479 if (fringe_bmp[which])
481 block_input ();
482 cairo_pattern_destroy (fringe_bmp[which]);
483 unblock_input ();
485 fringe_bmp[which] = 0;
488 static void
489 x_cr_draw_image (struct frame *f, GC gc, cairo_pattern_t *image,
490 int src_x, int src_y, int width, int height,
491 int dest_x, int dest_y, bool overlay_p)
493 cairo_t *cr;
494 cairo_matrix_t matrix;
495 cairo_surface_t *surface;
496 cairo_format_t format;
498 cr = x_begin_cr_clip (f, gc);
499 if (overlay_p)
500 cairo_rectangle (cr, dest_x, dest_y, width, height);
501 else
503 x_set_cr_source_with_gc_background (f, gc);
504 cairo_rectangle (cr, dest_x, dest_y, width, height);
505 cairo_fill_preserve (cr);
507 cairo_clip (cr);
508 cairo_matrix_init_translate (&matrix, src_x - dest_x, src_y - dest_y);
509 cairo_pattern_set_matrix (image, &matrix);
510 cairo_pattern_get_surface (image, &surface);
511 format = cairo_image_surface_get_format (surface);
512 if (format != CAIRO_FORMAT_A8 && format != CAIRO_FORMAT_A1)
514 cairo_set_source (cr, image);
515 cairo_fill (cr);
517 else
519 x_set_cr_source_with_gc_foreground (f, gc);
520 cairo_mask (cr, image);
522 x_end_cr_clip (f);
525 void
526 x_cr_draw_frame (cairo_t *cr, struct frame *f)
528 int width, height;
530 width = FRAME_PIXEL_WIDTH (f);
531 height = FRAME_PIXEL_HEIGHT (f);
533 x_free_cr_resources (f);
534 FRAME_CR_CONTEXT (f) = cr;
535 x_clear_area (f, 0, 0, width, height);
536 expose_frame (f, 0, 0, width, height);
537 FRAME_CR_CONTEXT (f) = NULL;
540 static cairo_status_t
541 x_cr_accumulate_data (void *closure, const unsigned char *data,
542 unsigned int length)
544 Lisp_Object *acc = (Lisp_Object *) closure;
546 *acc = Fcons (make_unibyte_string ((char const *) data, length), *acc);
548 return CAIRO_STATUS_SUCCESS;
551 static void
552 x_cr_destroy (Lisp_Object arg)
554 cairo_t *cr = (cairo_t *) XSAVE_POINTER (arg, 0);
556 block_input ();
557 cairo_destroy (cr);
558 unblock_input ();
561 Lisp_Object
562 x_cr_export_frames (Lisp_Object frames, cairo_surface_type_t surface_type)
564 struct frame *f;
565 cairo_surface_t *surface;
566 cairo_t *cr;
567 int width, height;
568 void (*surface_set_size_func) (cairo_surface_t *, double, double) = NULL;
569 Lisp_Object acc = Qnil;
570 ptrdiff_t count = SPECPDL_INDEX ();
572 specbind (Qredisplay_dont_pause, Qt);
573 redisplay_preserve_echo_area (31);
575 f = XFRAME (XCAR (frames));
576 frames = XCDR (frames);
577 width = FRAME_PIXEL_WIDTH (f);
578 height = FRAME_PIXEL_HEIGHT (f);
580 block_input ();
581 #ifdef CAIRO_HAS_PDF_SURFACE
582 if (surface_type == CAIRO_SURFACE_TYPE_PDF)
584 surface = cairo_pdf_surface_create_for_stream (x_cr_accumulate_data, &acc,
585 width, height);
586 surface_set_size_func = cairo_pdf_surface_set_size;
588 else
589 #endif
590 #ifdef CAIRO_HAS_PNG_FUNCTIONS
591 if (surface_type == CAIRO_SURFACE_TYPE_IMAGE)
592 surface = cairo_image_surface_create (CAIRO_FORMAT_RGB24, width, height);
593 else
594 #endif
595 #ifdef CAIRO_HAS_PS_SURFACE
596 if (surface_type == CAIRO_SURFACE_TYPE_PS)
598 surface = cairo_ps_surface_create_for_stream (x_cr_accumulate_data, &acc,
599 width, height);
600 surface_set_size_func = cairo_ps_surface_set_size;
602 else
603 #endif
604 #ifdef CAIRO_HAS_SVG_SURFACE
605 if (surface_type == CAIRO_SURFACE_TYPE_SVG)
606 surface = cairo_svg_surface_create_for_stream (x_cr_accumulate_data, &acc,
607 width, height);
608 else
609 #endif
610 abort ();
612 cr = cairo_create (surface);
613 cairo_surface_destroy (surface);
614 record_unwind_protect (x_cr_destroy, make_save_ptr (cr));
616 while (1)
618 x_free_cr_resources (f);
619 FRAME_CR_CONTEXT (f) = cr;
620 x_clear_area (f, 0, 0, width, height);
621 expose_frame (f, 0, 0, width, height);
622 FRAME_CR_CONTEXT (f) = NULL;
624 if (NILP (frames))
625 break;
627 cairo_surface_show_page (surface);
628 f = XFRAME (XCAR (frames));
629 frames = XCDR (frames);
630 width = FRAME_PIXEL_WIDTH (f);
631 height = FRAME_PIXEL_HEIGHT (f);
632 if (surface_set_size_func)
633 (*surface_set_size_func) (surface, width, height);
635 unblock_input ();
636 maybe_quit ();
637 block_input ();
640 #ifdef CAIRO_HAS_PNG_FUNCTIONS
641 if (surface_type == CAIRO_SURFACE_TYPE_IMAGE)
643 cairo_surface_flush (surface);
644 cairo_surface_write_to_png_stream (surface, x_cr_accumulate_data, &acc);
646 #endif
647 unblock_input ();
649 unbind_to (count, Qnil);
651 return CALLN (Fapply, intern ("concat"), Fnreverse (acc));
654 #endif /* USE_CAIRO */
656 static void
657 x_free_cr_resources (struct frame *f)
659 #ifdef USE_CAIRO
660 if (f == NULL)
662 Lisp_Object rest, frame;
663 FOR_EACH_FRAME (rest, frame)
664 if (FRAME_X_P (XFRAME (frame)))
665 x_free_cr_resources (XFRAME (frame));
667 else
669 cairo_t *cr = FRAME_CR_CONTEXT (f);
671 if (cr)
673 cairo_surface_t *surface = cairo_get_target (cr);
675 if (cairo_surface_get_type (surface) == CAIRO_SURFACE_TYPE_XLIB)
677 cairo_destroy (cr);
678 FRAME_CR_CONTEXT (f) = NULL;
682 #endif
685 static void
686 x_set_clip_rectangles (struct frame *f, GC gc, XRectangle *rectangles, int n)
688 XSetClipRectangles (FRAME_X_DISPLAY (f), gc, 0, 0, rectangles, n, Unsorted);
689 #ifdef USE_CAIRO
690 eassert (n >= 0 && n <= MAX_CLIP_RECTS);
693 struct x_gc_ext_data *gc_ext = x_gc_get_ext_data (f, gc, 1);
695 gc_ext->n_clip_rects = n;
696 memcpy (gc_ext->clip_rects, rectangles, sizeof (XRectangle) * n);
698 #endif
701 static void
702 x_reset_clip_rectangles (struct frame *f, GC gc)
704 XSetClipMask (FRAME_X_DISPLAY (f), gc, None);
705 #ifdef USE_CAIRO
707 struct x_gc_ext_data *gc_ext = x_gc_get_ext_data (f, gc, 0);
709 if (gc_ext)
710 gc_ext->n_clip_rects = 0;
712 #endif
715 static void
716 x_fill_rectangle (struct frame *f, GC gc, int x, int y, int width, int height)
718 #ifdef USE_CAIRO
719 cairo_t *cr;
721 cr = x_begin_cr_clip (f, gc);
722 x_set_cr_source_with_gc_foreground (f, gc);
723 cairo_rectangle (cr, x, y, width, height);
724 cairo_fill (cr);
725 x_end_cr_clip (f);
726 #else
727 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_DRAWABLE (f),
728 gc, x, y, width, height);
729 #endif
732 static void
733 x_draw_rectangle (struct frame *f, GC gc, int x, int y, int width, int height)
735 #ifdef USE_CAIRO
736 cairo_t *cr;
738 cr = x_begin_cr_clip (f, gc);
739 x_set_cr_source_with_gc_foreground (f, gc);
740 cairo_rectangle (cr, x + 0.5, y + 0.5, width, height);
741 cairo_set_line_width (cr, 1);
742 cairo_stroke (cr);
743 x_end_cr_clip (f);
744 #else
745 XDrawRectangle (FRAME_X_DISPLAY (f), FRAME_X_DRAWABLE (f),
746 gc, x, y, width, height);
747 #endif
750 static void
751 x_clear_window (struct frame *f)
753 #ifdef USE_CAIRO
754 cairo_t *cr;
756 cr = x_begin_cr_clip (f, NULL);
757 x_set_cr_source_with_gc_background (f, f->output_data.x->normal_gc);
758 cairo_paint (cr);
759 x_end_cr_clip (f);
760 #else
761 if (FRAME_X_DOUBLE_BUFFERED_P (f))
762 x_clear_area (f, 0, 0, FRAME_PIXEL_WIDTH (f), FRAME_PIXEL_HEIGHT (f));
763 else
764 XClearWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
765 #endif
768 #ifdef USE_CAIRO
769 static void
770 x_fill_trapezoid_for_relief (struct frame *f, GC gc, int x, int y,
771 int width, int height, int top_p)
773 cairo_t *cr;
775 cr = x_begin_cr_clip (f, gc);
776 x_set_cr_source_with_gc_foreground (f, gc);
777 cairo_move_to (cr, top_p ? x : x + height, y);
778 cairo_line_to (cr, x, y + height);
779 cairo_line_to (cr, top_p ? x + width - height : x + width, y + height);
780 cairo_line_to (cr, x + width, y);
781 cairo_fill (cr);
782 x_end_cr_clip (f);
785 enum corners
787 CORNER_BOTTOM_RIGHT, /* 0 -> pi/2 */
788 CORNER_BOTTOM_LEFT, /* pi/2 -> pi */
789 CORNER_TOP_LEFT, /* pi -> 3pi/2 */
790 CORNER_TOP_RIGHT, /* 3pi/2 -> 2pi */
791 CORNER_LAST
794 static void
795 x_erase_corners_for_relief (struct frame *f, GC gc, int x, int y,
796 int width, int height,
797 double radius, double margin, int corners)
799 cairo_t *cr;
800 int i;
802 cr = x_begin_cr_clip (f, gc);
803 x_set_cr_source_with_gc_background (f, gc);
804 for (i = 0; i < CORNER_LAST; i++)
805 if (corners & (1 << i))
807 double xm, ym, xc, yc;
809 if (i == CORNER_TOP_LEFT || i == CORNER_BOTTOM_LEFT)
810 xm = x - margin, xc = xm + radius;
811 else
812 xm = x + width + margin, xc = xm - radius;
813 if (i == CORNER_TOP_LEFT || i == CORNER_TOP_RIGHT)
814 ym = y - margin, yc = ym + radius;
815 else
816 ym = y + height + margin, yc = ym - radius;
818 cairo_move_to (cr, xm, ym);
819 cairo_arc (cr, xc, yc, radius, i * M_PI_2, (i + 1) * M_PI_2);
821 cairo_clip (cr);
822 cairo_rectangle (cr, x, y, width, height);
823 cairo_fill (cr);
824 x_end_cr_clip (f);
827 static void
828 x_draw_horizontal_wave (struct frame *f, GC gc, int x, int y,
829 int width, int height, int wave_length)
831 cairo_t *cr;
832 double dx = wave_length, dy = height - 1;
833 int xoffset, n;
835 cr = x_begin_cr_clip (f, gc);
836 x_set_cr_source_with_gc_foreground (f, gc);
837 cairo_rectangle (cr, x, y, width, height);
838 cairo_clip (cr);
840 if (x >= 0)
842 xoffset = x % (wave_length * 2);
843 if (xoffset == 0)
844 xoffset = wave_length * 2;
846 else
847 xoffset = x % (wave_length * 2) + wave_length * 2;
848 n = (width + xoffset) / wave_length + 1;
849 if (xoffset > wave_length)
851 xoffset -= wave_length;
852 --n;
853 y += height - 1;
854 dy = -dy;
857 cairo_move_to (cr, x - xoffset + 0.5, y + 0.5);
858 while (--n >= 0)
860 cairo_rel_line_to (cr, dx, dy);
861 dy = -dy;
863 cairo_set_line_width (cr, 1);
864 cairo_stroke (cr);
865 x_end_cr_clip (f);
867 #endif
870 /* Return the struct x_display_info corresponding to DPY. */
872 struct x_display_info *
873 x_display_info_for_display (Display *dpy)
875 struct x_display_info *dpyinfo;
877 for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
878 if (dpyinfo->display == dpy)
879 return dpyinfo;
881 return 0;
884 static Window
885 x_find_topmost_parent (struct frame *f)
887 struct x_output *x = f->output_data.x;
888 Window win = None, wi = x->parent_desc;
889 Display *dpy = FRAME_X_DISPLAY (f);
891 while (wi != FRAME_DISPLAY_INFO (f)->root_window)
893 Window root;
894 Window *children;
895 unsigned int nchildren;
897 win = wi;
898 if (XQueryTree (dpy, win, &root, &wi, &children, &nchildren))
899 XFree (children);
900 else
901 break;
904 return win;
907 #define OPAQUE 0xffffffff
909 void
910 x_set_frame_alpha (struct frame *f)
912 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
913 Display *dpy = FRAME_X_DISPLAY (f);
914 Window win = FRAME_OUTER_WINDOW (f);
915 double alpha = 1.0;
916 double alpha_min = 1.0;
917 unsigned long opac;
918 Window parent;
920 if (dpyinfo->x_highlight_frame == f)
921 alpha = f->alpha[0];
922 else
923 alpha = f->alpha[1];
925 if (FLOATP (Vframe_alpha_lower_limit))
926 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
927 else if (INTEGERP (Vframe_alpha_lower_limit))
928 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
930 if (alpha < 0.0)
931 return;
932 else if (alpha > 1.0)
933 alpha = 1.0;
934 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
935 alpha = alpha_min;
937 opac = alpha * OPAQUE;
939 x_catch_errors (dpy);
941 /* If there is a parent from the window manager, put the property there
942 also, to work around broken window managers that fail to do that.
943 Do this unconditionally as this function is called on reparent when
944 alpha has not changed on the frame. */
946 if (!FRAME_PARENT_FRAME (f))
948 parent = x_find_topmost_parent (f);
949 if (parent != None)
950 XChangeProperty (dpy, parent, dpyinfo->Xatom_net_wm_window_opacity,
951 XA_CARDINAL, 32, PropModeReplace,
952 (unsigned char *) &opac, 1);
955 /* return unless necessary */
957 unsigned char *data;
958 Atom actual;
959 int rc, format;
960 unsigned long n, left;
962 rc = XGetWindowProperty (dpy, win, dpyinfo->Xatom_net_wm_window_opacity,
963 0, 1, False, XA_CARDINAL,
964 &actual, &format, &n, &left,
965 &data);
967 if (rc == Success && actual != None)
969 unsigned long value = *(unsigned long *)data;
970 XFree (data);
971 if (value == opac)
973 x_uncatch_errors ();
974 return;
979 XChangeProperty (dpy, win, dpyinfo->Xatom_net_wm_window_opacity,
980 XA_CARDINAL, 32, PropModeReplace,
981 (unsigned char *) &opac, 1);
982 x_uncatch_errors ();
985 /***********************************************************************
986 Starting and ending an update
987 ***********************************************************************/
989 /* Start an update of frame F. This function is installed as a hook
990 for update_begin, i.e. it is called when update_begin is called.
991 This function is called prior to calls to x_update_window_begin for
992 each window being updated. Currently, there is nothing to do here
993 because all interesting stuff is done on a window basis. */
995 static void
996 x_update_begin (struct frame *f)
998 #ifdef USE_CAIRO
999 if (FRAME_TOOLTIP_P (f) && !FRAME_VISIBLE_P (f))
1000 return;
1002 if (! FRAME_CR_SURFACE (f))
1004 int width, height;
1005 #ifdef USE_GTK
1006 if (FRAME_GTK_WIDGET (f))
1008 GdkWindow *w = gtk_widget_get_window (FRAME_GTK_WIDGET (f));
1009 width = gdk_window_get_width (w);
1010 height = gdk_window_get_height (w);
1012 else
1013 #endif
1015 width = FRAME_PIXEL_WIDTH (f);
1016 height = FRAME_PIXEL_HEIGHT (f);
1017 if (! FRAME_EXTERNAL_TOOL_BAR (f))
1018 height += FRAME_TOOL_BAR_HEIGHT (f);
1019 if (! FRAME_EXTERNAL_MENU_BAR (f))
1020 height += FRAME_MENU_BAR_HEIGHT (f);
1023 if (width > 0 && height > 0)
1025 block_input();
1026 FRAME_CR_SURFACE (f) = cairo_image_surface_create
1027 (CAIRO_FORMAT_ARGB32, width, height);
1028 unblock_input();
1031 #endif /* USE_CAIRO */
1034 /* Start update of window W. */
1036 static void
1037 x_update_window_begin (struct window *w)
1039 struct frame *f = XFRAME (WINDOW_FRAME (w));
1040 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1042 w->output_cursor = w->cursor;
1044 block_input ();
1046 if (f == hlinfo->mouse_face_mouse_frame)
1048 /* Don't do highlighting for mouse motion during the update. */
1049 hlinfo->mouse_face_defer = true;
1051 /* If F needs to be redrawn, simply forget about any prior mouse
1052 highlighting. */
1053 if (FRAME_GARBAGED_P (f))
1054 hlinfo->mouse_face_window = Qnil;
1057 unblock_input ();
1061 /* Draw a vertical window border from (x,y0) to (x,y1) */
1063 static void
1064 x_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
1066 struct frame *f = XFRAME (WINDOW_FRAME (w));
1067 struct face *face;
1069 face = FACE_FROM_ID_OR_NULL (f, VERTICAL_BORDER_FACE_ID);
1070 if (face)
1071 XSetForeground (FRAME_X_DISPLAY (f), f->output_data.x->normal_gc,
1072 face->foreground);
1074 #ifdef USE_CAIRO
1075 x_fill_rectangle (f, f->output_data.x->normal_gc, x, y0, 1, y1 - y0);
1076 #else
1077 XDrawLine (FRAME_X_DISPLAY (f), FRAME_X_DRAWABLE (f),
1078 f->output_data.x->normal_gc, x, y0, x, y1);
1079 #endif
1082 /* Draw a window divider from (x0,y0) to (x1,y1) */
1084 static void
1085 x_draw_window_divider (struct window *w, int x0, int x1, int y0, int y1)
1087 struct frame *f = XFRAME (WINDOW_FRAME (w));
1088 struct face *face = FACE_FROM_ID_OR_NULL (f, WINDOW_DIVIDER_FACE_ID);
1089 struct face *face_first
1090 = FACE_FROM_ID_OR_NULL (f, WINDOW_DIVIDER_FIRST_PIXEL_FACE_ID);
1091 struct face *face_last
1092 = FACE_FROM_ID_OR_NULL (f, WINDOW_DIVIDER_LAST_PIXEL_FACE_ID);
1093 unsigned long color = face ? face->foreground : FRAME_FOREGROUND_PIXEL (f);
1094 unsigned long color_first = (face_first
1095 ? face_first->foreground
1096 : FRAME_FOREGROUND_PIXEL (f));
1097 unsigned long color_last = (face_last
1098 ? face_last->foreground
1099 : FRAME_FOREGROUND_PIXEL (f));
1100 Display *display = FRAME_X_DISPLAY (f);
1102 if ((y1 - y0 > x1 - x0) && (x1 - x0 >= 3))
1103 /* A vertical divider, at least three pixels wide: Draw first and
1104 last pixels differently. */
1106 XSetForeground (display, f->output_data.x->normal_gc, color_first);
1107 x_fill_rectangle (f, f->output_data.x->normal_gc,
1108 x0, y0, 1, y1 - y0);
1109 XSetForeground (display, f->output_data.x->normal_gc, color);
1110 x_fill_rectangle (f, f->output_data.x->normal_gc,
1111 x0 + 1, y0, x1 - x0 - 2, y1 - y0);
1112 XSetForeground (display, f->output_data.x->normal_gc, color_last);
1113 x_fill_rectangle (f, f->output_data.x->normal_gc,
1114 x1 - 1, y0, 1, y1 - y0);
1116 else if ((x1 - x0 > y1 - y0) && (y1 - y0 >= 3))
1117 /* A horizontal divider, at least three pixels high: Draw first and
1118 last pixels differently. */
1120 XSetForeground (display, f->output_data.x->normal_gc, color_first);
1121 x_fill_rectangle (f, f->output_data.x->normal_gc,
1122 x0, y0, x1 - x0, 1);
1123 XSetForeground (display, f->output_data.x->normal_gc, color);
1124 x_fill_rectangle (f, f->output_data.x->normal_gc,
1125 x0, y0 + 1, x1 - x0, y1 - y0 - 2);
1126 XSetForeground (display, f->output_data.x->normal_gc, color_last);
1127 x_fill_rectangle (f, f->output_data.x->normal_gc,
1128 x0, y1 - 1, x1 - x0, 1);
1130 else
1132 /* In any other case do not draw the first and last pixels
1133 differently. */
1134 XSetForeground (display, f->output_data.x->normal_gc, color);
1135 x_fill_rectangle (f, f->output_data.x->normal_gc,
1136 x0, y0, x1 - x0, y1 - y0);
1140 /* End update of window W.
1142 Draw vertical borders between horizontally adjacent windows, and
1143 display W's cursor if CURSOR_ON_P is non-zero.
1145 MOUSE_FACE_OVERWRITTEN_P non-zero means that some row containing
1146 glyphs in mouse-face were overwritten. In that case we have to
1147 make sure that the mouse-highlight is properly redrawn.
1149 W may be a menu bar pseudo-window in case we don't have X toolkit
1150 support. Such windows don't have a cursor, so don't display it
1151 here. */
1153 static void
1154 x_update_window_end (struct window *w, bool cursor_on_p,
1155 bool mouse_face_overwritten_p)
1157 if (!w->pseudo_window_p)
1159 block_input ();
1161 if (cursor_on_p)
1162 display_and_set_cursor (w, true,
1163 w->output_cursor.hpos, w->output_cursor.vpos,
1164 w->output_cursor.x, w->output_cursor.y);
1166 if (draw_window_fringes (w, true))
1168 if (WINDOW_RIGHT_DIVIDER_WIDTH (w))
1169 x_draw_right_divider (w);
1170 else
1171 x_draw_vertical_border (w);
1174 unblock_input ();
1177 /* If a row with mouse-face was overwritten, arrange for
1178 XTframe_up_to_date to redisplay the mouse highlight. */
1179 if (mouse_face_overwritten_p)
1181 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (XFRAME (w->frame));
1183 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
1184 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
1185 hlinfo->mouse_face_window = Qnil;
1189 /* Show the frame back buffer. If frame is double-buffered,
1190 atomically publish to the user's screen graphics updates made since
1191 the last call to show_back_buffer. */
1192 static void
1193 show_back_buffer (struct frame *f)
1195 block_input ();
1196 if (FRAME_X_DOUBLE_BUFFERED_P (f))
1198 #ifdef HAVE_XDBE
1199 XdbeSwapInfo swap_info;
1200 memset (&swap_info, 0, sizeof (swap_info));
1201 swap_info.swap_window = FRAME_X_WINDOW (f);
1202 swap_info.swap_action = XdbeCopied;
1203 XdbeSwapBuffers (FRAME_X_DISPLAY (f), &swap_info, 1);
1204 #else
1205 eassert (!"should have back-buffer only with XDBE");
1206 #endif
1208 FRAME_X_NEED_BUFFER_FLIP (f) = false;
1209 unblock_input ();
1212 /* Updates back buffer and flushes changes to display. Called from
1213 minibuf read code. Note that we display the back buffer even if
1214 buffer flipping is blocked. */
1215 static void
1216 x_flip_and_flush (struct frame *f)
1218 block_input ();
1219 if (FRAME_X_NEED_BUFFER_FLIP (f))
1220 show_back_buffer (f);
1221 x_flush (f);
1222 unblock_input ();
1225 /* End update of frame F. This function is installed as a hook in
1226 update_end. */
1228 static void
1229 x_update_end (struct frame *f)
1231 /* Mouse highlight may be displayed again. */
1232 MOUSE_HL_INFO (f)->mouse_face_defer = false;
1234 #ifdef USE_CAIRO
1235 if (FRAME_CR_SURFACE (f))
1237 cairo_t *cr = 0;
1238 block_input();
1239 #if defined (USE_GTK) && defined (HAVE_GTK3)
1240 if (FRAME_GTK_WIDGET (f))
1242 GdkWindow *w = gtk_widget_get_window (FRAME_GTK_WIDGET (f));
1243 cr = gdk_cairo_create (w);
1245 else
1246 #endif
1248 cairo_surface_t *surface;
1249 int width = FRAME_PIXEL_WIDTH (f);
1250 int height = FRAME_PIXEL_HEIGHT (f);
1251 if (! FRAME_EXTERNAL_TOOL_BAR (f))
1252 height += FRAME_TOOL_BAR_HEIGHT (f);
1253 if (! FRAME_EXTERNAL_MENU_BAR (f))
1254 height += FRAME_MENU_BAR_HEIGHT (f);
1255 surface = cairo_xlib_surface_create (FRAME_X_DISPLAY (f),
1256 FRAME_X_DRAWABLE (f),
1257 FRAME_DISPLAY_INFO (f)->visual,
1258 width,
1259 height);
1260 cr = cairo_create (surface);
1261 cairo_surface_destroy (surface);
1264 cairo_set_source_surface (cr, FRAME_CR_SURFACE (f), 0, 0);
1265 cairo_paint (cr);
1266 cairo_destroy (cr);
1267 unblock_input ();
1269 #endif
1271 #ifndef XFlush
1272 block_input ();
1273 XFlush (FRAME_X_DISPLAY (f));
1274 unblock_input ();
1275 #endif
1278 /* This function is called from various places in xdisp.c
1279 whenever a complete update has been performed. */
1281 static void
1282 XTframe_up_to_date (struct frame *f)
1284 eassert (FRAME_X_P (f));
1285 block_input ();
1286 FRAME_MOUSE_UPDATE (f);
1287 if (!buffer_flipping_blocked_p () && FRAME_X_NEED_BUFFER_FLIP (f))
1288 show_back_buffer (f);
1289 unblock_input ();
1292 static void
1293 XTbuffer_flipping_unblocked_hook (struct frame *f)
1295 if (FRAME_X_NEED_BUFFER_FLIP (f))
1296 show_back_buffer (f);
1300 * x_clear_under_internal_border:
1302 * Clear area of frame F's internal border. If the internal border face
1303 * of F has been specified (is not null), fill the area with that face.
1305 void
1306 x_clear_under_internal_border (struct frame *f)
1308 if (FRAME_INTERNAL_BORDER_WIDTH (f) > 0)
1310 int border = FRAME_INTERNAL_BORDER_WIDTH (f);
1311 int width = FRAME_PIXEL_WIDTH (f);
1312 int height = FRAME_PIXEL_HEIGHT (f);
1313 #ifdef USE_GTK
1314 int margin = 0;
1315 #else
1316 int margin = FRAME_TOP_MARGIN_HEIGHT (f);
1317 #endif
1318 struct face *face = FACE_FROM_ID_OR_NULL (f, INTERNAL_BORDER_FACE_ID);
1320 block_input ();
1322 if (face)
1324 unsigned long color = face->background;
1325 Display *display = FRAME_X_DISPLAY (f);
1326 GC gc = f->output_data.x->normal_gc;
1328 XSetForeground (display, gc, color);
1329 x_fill_rectangle (f, gc, 0, margin, width, border);
1330 x_fill_rectangle (f, gc, 0, 0, border, height);
1331 x_fill_rectangle (f, gc, width - border, 0, border, height);
1332 x_fill_rectangle (f, gc, 0, height - border, width, border);
1333 XSetForeground (display, gc, FRAME_FOREGROUND_PIXEL (f));
1335 else
1337 x_clear_area (f, 0, 0, border, height);
1338 x_clear_area (f, 0, margin, width, border);
1339 x_clear_area (f, width - border, 0, border, height);
1340 x_clear_area (f, 0, height - border, width, border);
1343 unblock_input ();
1347 /* Draw truncation mark bitmaps, continuation mark bitmaps, overlay
1348 arrow bitmaps, or clear the fringes if no bitmaps are required
1349 before DESIRED_ROW is made current. This function is called from
1350 update_window_line only if it is known that there are differences
1351 between bitmaps to be drawn between current row and DESIRED_ROW. */
1353 static void
1354 x_after_update_window_line (struct window *w, struct glyph_row *desired_row)
1356 eassert (w);
1358 if (!desired_row->mode_line_p && !w->pseudo_window_p)
1359 desired_row->redraw_fringe_bitmaps_p = true;
1361 #ifdef USE_X_TOOLKIT
1362 /* When a window has disappeared, make sure that no rest of
1363 full-width rows stays visible in the internal border. Could
1364 check here if updated window is the leftmost/rightmost window,
1365 but I guess it's not worth doing since vertically split windows
1366 are almost never used, internal border is rarely set, and the
1367 overhead is very small. */
1369 struct frame *f;
1370 int width, height;
1372 if (windows_or_buffers_changed
1373 && desired_row->full_width_p
1374 && (f = XFRAME (w->frame),
1375 width = FRAME_INTERNAL_BORDER_WIDTH (f),
1376 width != 0)
1377 && (height = desired_row->visible_height,
1378 height > 0))
1380 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
1381 struct face *face = FACE_FROM_ID_OR_NULL (f, INTERNAL_BORDER_FACE_ID);
1383 block_input ();
1384 if (face)
1386 unsigned long color = face->background;
1387 Display *display = FRAME_X_DISPLAY (f);
1388 GC gc = f->output_data.x->normal_gc;
1390 XSetForeground (display, gc, color);
1391 x_fill_rectangle (f, gc, 0, y, width, height);
1392 x_fill_rectangle (f, gc, FRAME_PIXEL_WIDTH (f) - width, y,
1393 width, height);
1394 XSetForeground (display, gc, FRAME_FOREGROUND_PIXEL (f));
1396 else
1398 x_clear_area (f, 0, y, width, height);
1399 x_clear_area (f, FRAME_PIXEL_WIDTH (f) - width, y, width, height);
1401 unblock_input ();
1404 #endif
1407 static void
1408 x_draw_fringe_bitmap (struct window *w, struct glyph_row *row, struct draw_fringe_bitmap_params *p)
1410 struct frame *f = XFRAME (WINDOW_FRAME (w));
1411 Display *display = FRAME_X_DISPLAY (f);
1412 GC gc = f->output_data.x->normal_gc;
1413 struct face *face = p->face;
1415 /* Must clip because of partially visible lines. */
1416 x_clip_to_row (w, row, ANY_AREA, gc);
1418 if (p->bx >= 0 && !p->overlay_p)
1420 /* In case the same realized face is used for fringes and
1421 for something displayed in the text (e.g. face `region' on
1422 mono-displays, the fill style may have been changed to
1423 FillSolid in x_draw_glyph_string_background. */
1424 if (face->stipple)
1425 XSetFillStyle (display, face->gc, FillOpaqueStippled);
1426 else
1427 XSetForeground (display, face->gc, face->background);
1429 x_fill_rectangle (f, face->gc, p->bx, p->by, p->nx, p->ny);
1431 if (!face->stipple)
1432 XSetForeground (display, face->gc, face->foreground);
1435 #ifdef USE_CAIRO
1436 if (p->which && p->which < max_fringe_bmp)
1438 XGCValues gcv;
1440 XGetGCValues (display, gc, GCForeground | GCBackground, &gcv);
1441 XSetForeground (display, gc, (p->cursor_p
1442 ? (p->overlay_p ? face->background
1443 : f->output_data.x->cursor_pixel)
1444 : face->foreground));
1445 XSetBackground (display, gc, face->background);
1446 x_cr_draw_image (f, gc, fringe_bmp[p->which], 0, p->dh,
1447 p->wd, p->h, p->x, p->y, p->overlay_p);
1448 XSetForeground (display, gc, gcv.foreground);
1449 XSetBackground (display, gc, gcv.background);
1451 #else /* not USE_CAIRO */
1452 if (p->which)
1454 Drawable drawable = FRAME_X_DRAWABLE (f);
1455 char *bits;
1456 Pixmap pixmap, clipmask = (Pixmap) 0;
1457 int depth = DefaultDepthOfScreen (FRAME_X_SCREEN (f));
1458 XGCValues gcv;
1460 if (p->wd > 8)
1461 bits = (char *) (p->bits + p->dh);
1462 else
1463 bits = (char *) p->bits + p->dh;
1465 /* Draw the bitmap. I believe these small pixmaps can be cached
1466 by the server. */
1467 pixmap = XCreatePixmapFromBitmapData (display, drawable, bits, p->wd, p->h,
1468 (p->cursor_p
1469 ? (p->overlay_p ? face->background
1470 : f->output_data.x->cursor_pixel)
1471 : face->foreground),
1472 face->background, depth);
1474 if (p->overlay_p)
1476 clipmask = XCreatePixmapFromBitmapData (display,
1477 FRAME_DISPLAY_INFO (f)->root_window,
1478 bits, p->wd, p->h,
1479 1, 0, 1);
1480 gcv.clip_mask = clipmask;
1481 gcv.clip_x_origin = p->x;
1482 gcv.clip_y_origin = p->y;
1483 XChangeGC (display, gc, GCClipMask | GCClipXOrigin | GCClipYOrigin, &gcv);
1486 XCopyArea (display, pixmap, drawable, gc, 0, 0,
1487 p->wd, p->h, p->x, p->y);
1488 XFreePixmap (display, pixmap);
1490 if (p->overlay_p)
1492 gcv.clip_mask = (Pixmap) 0;
1493 XChangeGC (display, gc, GCClipMask, &gcv);
1494 XFreePixmap (display, clipmask);
1497 #endif /* not USE_CAIRO */
1499 x_reset_clip_rectangles (f, gc);
1502 /***********************************************************************
1503 Glyph display
1504 ***********************************************************************/
1508 static void x_set_glyph_string_clipping (struct glyph_string *);
1509 static void x_set_glyph_string_gc (struct glyph_string *);
1510 static void x_draw_glyph_string_foreground (struct glyph_string *);
1511 static void x_draw_composite_glyph_string_foreground (struct glyph_string *);
1512 static void x_draw_glyph_string_box (struct glyph_string *);
1513 static void x_draw_glyph_string (struct glyph_string *);
1514 static _Noreturn void x_delete_glyphs (struct frame *, int);
1515 static void x_compute_glyph_string_overhangs (struct glyph_string *);
1516 static void x_set_cursor_gc (struct glyph_string *);
1517 static void x_set_mode_line_face_gc (struct glyph_string *);
1518 static void x_set_mouse_face_gc (struct glyph_string *);
1519 static bool x_alloc_lighter_color (struct frame *, Display *, Colormap,
1520 unsigned long *, double, int);
1521 static void x_setup_relief_color (struct frame *, struct relief *,
1522 double, int, unsigned long);
1523 static void x_setup_relief_colors (struct glyph_string *);
1524 static void x_draw_image_glyph_string (struct glyph_string *);
1525 static void x_draw_image_relief (struct glyph_string *);
1526 static void x_draw_image_foreground (struct glyph_string *);
1527 static void x_draw_image_foreground_1 (struct glyph_string *, Pixmap);
1528 static void x_clear_glyph_string_rect (struct glyph_string *, int,
1529 int, int, int);
1530 static void x_draw_relief_rect (struct frame *, int, int, int, int,
1531 int, bool, bool, bool, bool, bool,
1532 XRectangle *);
1533 static void x_draw_box_rect (struct glyph_string *, int, int, int, int,
1534 int, bool, bool, XRectangle *);
1535 static void x_scroll_bar_clear (struct frame *);
1537 #ifdef GLYPH_DEBUG
1538 static void x_check_font (struct frame *, struct font *);
1539 #endif
1542 /* Set S->gc to a suitable GC for drawing glyph string S in cursor
1543 face. */
1545 static void
1546 x_set_cursor_gc (struct glyph_string *s)
1548 if (s->font == FRAME_FONT (s->f)
1549 && s->face->background == FRAME_BACKGROUND_PIXEL (s->f)
1550 && s->face->foreground == FRAME_FOREGROUND_PIXEL (s->f)
1551 && !s->cmp)
1552 s->gc = s->f->output_data.x->cursor_gc;
1553 else
1555 /* Cursor on non-default face: must merge. */
1556 XGCValues xgcv;
1557 unsigned long mask;
1559 xgcv.background = s->f->output_data.x->cursor_pixel;
1560 xgcv.foreground = s->face->background;
1562 /* If the glyph would be invisible, try a different foreground. */
1563 if (xgcv.foreground == xgcv.background)
1564 xgcv.foreground = s->face->foreground;
1565 if (xgcv.foreground == xgcv.background)
1566 xgcv.foreground = s->f->output_data.x->cursor_foreground_pixel;
1567 if (xgcv.foreground == xgcv.background)
1568 xgcv.foreground = s->face->foreground;
1570 /* Make sure the cursor is distinct from text in this face. */
1571 if (xgcv.background == s->face->background
1572 && xgcv.foreground == s->face->foreground)
1574 xgcv.background = s->face->foreground;
1575 xgcv.foreground = s->face->background;
1578 IF_DEBUG (x_check_font (s->f, s->font));
1579 xgcv.graphics_exposures = False;
1580 mask = GCForeground | GCBackground | GCGraphicsExposures;
1582 if (FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc)
1583 XChangeGC (s->display, FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc,
1584 mask, &xgcv);
1585 else
1586 FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc
1587 = XCreateGC (s->display, FRAME_X_DRAWABLE (s->f), mask, &xgcv);
1589 s->gc = FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc;
1594 /* Set up S->gc of glyph string S for drawing text in mouse face. */
1596 static void
1597 x_set_mouse_face_gc (struct glyph_string *s)
1599 int face_id;
1600 struct face *face;
1602 /* What face has to be used last for the mouse face? */
1603 face_id = MOUSE_HL_INFO (s->f)->mouse_face_face_id;
1604 face = FACE_FROM_ID_OR_NULL (s->f, face_id);
1605 if (face == NULL)
1606 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
1608 if (s->first_glyph->type == CHAR_GLYPH)
1609 face_id = FACE_FOR_CHAR (s->f, face, s->first_glyph->u.ch, -1, Qnil);
1610 else
1611 face_id = FACE_FOR_CHAR (s->f, face, 0, -1, Qnil);
1612 s->face = FACE_FROM_ID (s->f, face_id);
1613 prepare_face_for_display (s->f, s->face);
1615 if (s->font == s->face->font)
1616 s->gc = s->face->gc;
1617 else
1619 /* Otherwise construct scratch_cursor_gc with values from FACE
1620 except for FONT. */
1621 XGCValues xgcv;
1622 unsigned long mask;
1624 xgcv.background = s->face->background;
1625 xgcv.foreground = s->face->foreground;
1626 xgcv.graphics_exposures = False;
1627 mask = GCForeground | GCBackground | GCGraphicsExposures;
1629 if (FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc)
1630 XChangeGC (s->display, FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc,
1631 mask, &xgcv);
1632 else
1633 FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc
1634 = XCreateGC (s->display, FRAME_X_DRAWABLE (s->f), mask, &xgcv);
1636 s->gc = FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc;
1639 eassert (s->gc != 0);
1643 /* Set S->gc of glyph string S to a GC suitable for drawing a mode line.
1644 Faces to use in the mode line have already been computed when the
1645 matrix was built, so there isn't much to do, here. */
1647 static void
1648 x_set_mode_line_face_gc (struct glyph_string *s)
1650 s->gc = s->face->gc;
1654 /* Set S->gc of glyph string S for drawing that glyph string. Set
1655 S->stippled_p to a non-zero value if the face of S has a stipple
1656 pattern. */
1658 static void
1659 x_set_glyph_string_gc (struct glyph_string *s)
1661 prepare_face_for_display (s->f, s->face);
1663 if (s->hl == DRAW_NORMAL_TEXT)
1665 s->gc = s->face->gc;
1666 s->stippled_p = s->face->stipple != 0;
1668 else if (s->hl == DRAW_INVERSE_VIDEO)
1670 x_set_mode_line_face_gc (s);
1671 s->stippled_p = s->face->stipple != 0;
1673 else if (s->hl == DRAW_CURSOR)
1675 x_set_cursor_gc (s);
1676 s->stippled_p = false;
1678 else if (s->hl == DRAW_MOUSE_FACE)
1680 x_set_mouse_face_gc (s);
1681 s->stippled_p = s->face->stipple != 0;
1683 else if (s->hl == DRAW_IMAGE_RAISED
1684 || s->hl == DRAW_IMAGE_SUNKEN)
1686 s->gc = s->face->gc;
1687 s->stippled_p = s->face->stipple != 0;
1689 else
1690 emacs_abort ();
1692 /* GC must have been set. */
1693 eassert (s->gc != 0);
1697 /* Set clipping for output of glyph string S. S may be part of a mode
1698 line or menu if we don't have X toolkit support. */
1700 static void
1701 x_set_glyph_string_clipping (struct glyph_string *s)
1703 XRectangle *r = s->clip;
1704 int n = get_glyph_string_clip_rects (s, r, 2);
1706 if (n > 0)
1707 x_set_clip_rectangles (s->f, s->gc, r, n);
1708 s->num_clips = n;
1712 /* Set SRC's clipping for output of glyph string DST. This is called
1713 when we are drawing DST's left_overhang or right_overhang only in
1714 the area of SRC. */
1716 static void
1717 x_set_glyph_string_clipping_exactly (struct glyph_string *src, struct glyph_string *dst)
1719 XRectangle r;
1721 r.x = src->x;
1722 r.width = src->width;
1723 r.y = src->y;
1724 r.height = src->height;
1725 dst->clip[0] = r;
1726 dst->num_clips = 1;
1727 x_set_clip_rectangles (dst->f, dst->gc, &r, 1);
1731 /* RIF:
1732 Compute left and right overhang of glyph string S. */
1734 static void
1735 x_compute_glyph_string_overhangs (struct glyph_string *s)
1737 if (s->cmp == NULL
1738 && (s->first_glyph->type == CHAR_GLYPH
1739 || s->first_glyph->type == COMPOSITE_GLYPH))
1741 struct font_metrics metrics;
1743 if (s->first_glyph->type == CHAR_GLYPH)
1745 unsigned *code = alloca (sizeof (unsigned) * s->nchars);
1746 struct font *font = s->font;
1747 int i;
1749 for (i = 0; i < s->nchars; i++)
1750 code[i] = (s->char2b[i].byte1 << 8) | s->char2b[i].byte2;
1751 font->driver->text_extents (font, code, s->nchars, &metrics);
1753 else
1755 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1757 composition_gstring_width (gstring, s->cmp_from, s->cmp_to, &metrics);
1759 s->right_overhang = (metrics.rbearing > metrics.width
1760 ? metrics.rbearing - metrics.width : 0);
1761 s->left_overhang = metrics.lbearing < 0 ? - metrics.lbearing : 0;
1763 else if (s->cmp)
1765 s->right_overhang = s->cmp->rbearing - s->cmp->pixel_width;
1766 s->left_overhang = - s->cmp->lbearing;
1771 /* Fill rectangle X, Y, W, H with background color of glyph string S. */
1773 static void
1774 x_clear_glyph_string_rect (struct glyph_string *s, int x, int y, int w, int h)
1776 XGCValues xgcv;
1777 XGetGCValues (s->display, s->gc, GCForeground | GCBackground, &xgcv);
1778 XSetForeground (s->display, s->gc, xgcv.background);
1779 x_fill_rectangle (s->f, s->gc, x, y, w, h);
1780 XSetForeground (s->display, s->gc, xgcv.foreground);
1784 /* Draw the background of glyph_string S. If S->background_filled_p
1785 is non-zero don't draw it. FORCE_P non-zero means draw the
1786 background even if it wouldn't be drawn normally. This is used
1787 when a string preceding S draws into the background of S, or S
1788 contains the first component of a composition. */
1790 static void
1791 x_draw_glyph_string_background (struct glyph_string *s, bool force_p)
1793 /* Nothing to do if background has already been drawn or if it
1794 shouldn't be drawn in the first place. */
1795 if (!s->background_filled_p)
1797 int box_line_width = max (s->face->box_line_width, 0);
1799 if (s->stippled_p)
1801 /* Fill background with a stipple pattern. */
1802 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
1803 x_fill_rectangle (s->f, s->gc, s->x,
1804 s->y + box_line_width,
1805 s->background_width,
1806 s->height - 2 * box_line_width);
1807 XSetFillStyle (s->display, s->gc, FillSolid);
1808 s->background_filled_p = true;
1810 else if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
1811 /* When xdisp.c ignores FONT_HEIGHT, we cannot trust
1812 font dimensions, since the actual glyphs might be
1813 much smaller. So in that case we always clear the
1814 rectangle with background color. */
1815 || FONT_TOO_HIGH (s->font)
1816 || s->font_not_found_p
1817 || s->extends_to_end_of_line_p
1818 || force_p)
1820 x_clear_glyph_string_rect (s, s->x, s->y + box_line_width,
1821 s->background_width,
1822 s->height - 2 * box_line_width);
1823 s->background_filled_p = true;
1829 /* Draw the foreground of glyph string S. */
1831 static void
1832 x_draw_glyph_string_foreground (struct glyph_string *s)
1834 int i, x;
1836 /* If first glyph of S has a left box line, start drawing the text
1837 of S to the right of that box line. */
1838 if (s->face->box != FACE_NO_BOX
1839 && s->first_glyph->left_box_line_p)
1840 x = s->x + eabs (s->face->box_line_width);
1841 else
1842 x = s->x;
1844 /* Draw characters of S as rectangles if S's font could not be
1845 loaded. */
1846 if (s->font_not_found_p)
1848 for (i = 0; i < s->nchars; ++i)
1850 struct glyph *g = s->first_glyph + i;
1851 x_draw_rectangle (s->f,
1852 s->gc, x, s->y, g->pixel_width - 1,
1853 s->height - 1);
1854 x += g->pixel_width;
1857 else
1859 struct font *font = s->font;
1860 int boff = font->baseline_offset;
1861 int y;
1863 if (font->vertical_centering)
1864 boff = VCENTER_BASELINE_OFFSET (font, s->f) - boff;
1866 y = s->ybase - boff;
1867 if (s->for_overlaps
1868 || (s->background_filled_p && s->hl != DRAW_CURSOR))
1869 font->driver->draw (s, 0, s->nchars, x, y, false);
1870 else
1871 font->driver->draw (s, 0, s->nchars, x, y, true);
1872 if (s->face->overstrike)
1873 font->driver->draw (s, 0, s->nchars, x + 1, y, false);
1877 /* Draw the foreground of composite glyph string S. */
1879 static void
1880 x_draw_composite_glyph_string_foreground (struct glyph_string *s)
1882 int i, j, x;
1883 struct font *font = s->font;
1885 /* If first glyph of S has a left box line, start drawing the text
1886 of S to the right of that box line. */
1887 if (s->face && s->face->box != FACE_NO_BOX
1888 && s->first_glyph->left_box_line_p)
1889 x = s->x + eabs (s->face->box_line_width);
1890 else
1891 x = s->x;
1893 /* S is a glyph string for a composition. S->cmp_from is the index
1894 of the first character drawn for glyphs of this composition.
1895 S->cmp_from == 0 means we are drawing the very first character of
1896 this composition. */
1898 /* Draw a rectangle for the composition if the font for the very
1899 first character of the composition could not be loaded. */
1900 if (s->font_not_found_p)
1902 if (s->cmp_from == 0)
1903 x_draw_rectangle (s->f, s->gc, x, s->y,
1904 s->width - 1, s->height - 1);
1906 else if (! s->first_glyph->u.cmp.automatic)
1908 int y = s->ybase;
1910 for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
1911 /* TAB in a composition means display glyphs with padding
1912 space on the left or right. */
1913 if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
1915 int xx = x + s->cmp->offsets[j * 2];
1916 int yy = y - s->cmp->offsets[j * 2 + 1];
1918 font->driver->draw (s, j, j + 1, xx, yy, false);
1919 if (s->face->overstrike)
1920 font->driver->draw (s, j, j + 1, xx + 1, yy, false);
1923 else
1925 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1926 Lisp_Object glyph;
1927 int y = s->ybase;
1928 int width = 0;
1930 for (i = j = s->cmp_from; i < s->cmp_to; i++)
1932 glyph = LGSTRING_GLYPH (gstring, i);
1933 if (NILP (LGLYPH_ADJUSTMENT (glyph)))
1934 width += LGLYPH_WIDTH (glyph);
1935 else
1937 int xoff, yoff, wadjust;
1939 if (j < i)
1941 font->driver->draw (s, j, i, x, y, false);
1942 if (s->face->overstrike)
1943 font->driver->draw (s, j, i, x + 1, y, false);
1944 x += width;
1946 xoff = LGLYPH_XOFF (glyph);
1947 yoff = LGLYPH_YOFF (glyph);
1948 wadjust = LGLYPH_WADJUST (glyph);
1949 font->driver->draw (s, i, i + 1, x + xoff, y + yoff, false);
1950 if (s->face->overstrike)
1951 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff,
1952 false);
1953 x += wadjust;
1954 j = i + 1;
1955 width = 0;
1958 if (j < i)
1960 font->driver->draw (s, j, i, x, y, false);
1961 if (s->face->overstrike)
1962 font->driver->draw (s, j, i, x + 1, y, false);
1968 /* Draw the foreground of glyph string S for glyphless characters. */
1970 static void
1971 x_draw_glyphless_glyph_string_foreground (struct glyph_string *s)
1973 struct glyph *glyph = s->first_glyph;
1974 XChar2b char2b[8];
1975 int x, i, j;
1977 /* If first glyph of S has a left box line, start drawing the text
1978 of S to the right of that box line. */
1979 if (s->face && s->face->box != FACE_NO_BOX
1980 && s->first_glyph->left_box_line_p)
1981 x = s->x + eabs (s->face->box_line_width);
1982 else
1983 x = s->x;
1985 s->char2b = char2b;
1987 for (i = 0; i < s->nchars; i++, glyph++)
1989 char buf[7], *str = NULL;
1990 int len = glyph->u.glyphless.len;
1992 if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_ACRONYM)
1994 if (len > 0
1995 && CHAR_TABLE_P (Vglyphless_char_display)
1996 && (CHAR_TABLE_EXTRA_SLOTS (XCHAR_TABLE (Vglyphless_char_display))
1997 >= 1))
1999 Lisp_Object acronym
2000 = (! glyph->u.glyphless.for_no_font
2001 ? CHAR_TABLE_REF (Vglyphless_char_display,
2002 glyph->u.glyphless.ch)
2003 : XCHAR_TABLE (Vglyphless_char_display)->extras[0]);
2004 if (STRINGP (acronym))
2005 str = SSDATA (acronym);
2008 else if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_HEX_CODE)
2010 unsigned int ch = glyph->u.glyphless.ch;
2011 eassume (ch <= MAX_CHAR);
2012 sprintf (buf, "%0*X", ch < 0x10000 ? 4 : 6, ch);
2013 str = buf;
2016 if (str)
2018 int upper_len = (len + 1) / 2;
2019 unsigned code;
2021 /* It is assured that all LEN characters in STR is ASCII. */
2022 for (j = 0; j < len; j++)
2024 code = s->font->driver->encode_char (s->font, str[j]);
2025 STORE_XCHAR2B (char2b + j, code >> 8, code & 0xFF);
2027 s->font->driver->draw (s, 0, upper_len,
2028 x + glyph->slice.glyphless.upper_xoff,
2029 s->ybase + glyph->slice.glyphless.upper_yoff,
2030 false);
2031 s->font->driver->draw (s, upper_len, len,
2032 x + glyph->slice.glyphless.lower_xoff,
2033 s->ybase + glyph->slice.glyphless.lower_yoff,
2034 false);
2036 if (glyph->u.glyphless.method != GLYPHLESS_DISPLAY_THIN_SPACE)
2037 x_draw_rectangle (s->f, s->gc,
2038 x, s->ybase - glyph->ascent,
2039 glyph->pixel_width - 1,
2040 glyph->ascent + glyph->descent - 1);
2041 x += glyph->pixel_width;
2045 #ifdef USE_X_TOOLKIT
2047 #ifdef USE_LUCID
2049 /* Return the frame on which widget WIDGET is used.. Abort if frame
2050 cannot be determined. */
2052 static struct frame *
2053 x_frame_of_widget (Widget widget)
2055 struct x_display_info *dpyinfo;
2056 Lisp_Object tail, frame;
2057 struct frame *f;
2059 dpyinfo = x_display_info_for_display (XtDisplay (widget));
2061 /* Find the top-level shell of the widget. Note that this function
2062 can be called when the widget is not yet realized, so XtWindow
2063 (widget) == 0. That's the reason we can't simply use
2064 x_any_window_to_frame. */
2065 while (!XtIsTopLevelShell (widget))
2066 widget = XtParent (widget);
2068 /* Look for a frame with that top-level widget. Allocate the color
2069 on that frame to get the right gamma correction value. */
2070 FOR_EACH_FRAME (tail, frame)
2072 f = XFRAME (frame);
2073 if (FRAME_X_P (f)
2074 && f->output_data.nothing != 1
2075 && FRAME_DISPLAY_INFO (f) == dpyinfo
2076 && f->output_data.x->widget == widget)
2077 return f;
2079 emacs_abort ();
2082 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
2083 or DELTA. Try a color with RGB values multiplied by FACTOR first.
2084 If this produces the same color as PIXEL, try a color where all RGB
2085 values have DELTA added. Return the allocated color in *PIXEL.
2086 DISPLAY is the X display, CMAP is the colormap to operate on.
2087 Value is true if successful. */
2089 bool
2090 x_alloc_lighter_color_for_widget (Widget widget, Display *display, Colormap cmap,
2091 unsigned long *pixel, double factor, int delta)
2093 struct frame *f = x_frame_of_widget (widget);
2094 return x_alloc_lighter_color (f, display, cmap, pixel, factor, delta);
2097 #endif /* USE_LUCID */
2100 /* Structure specifying which arguments should be passed by Xt to
2101 cvt_string_to_pixel. We want the widget's screen and colormap. */
2103 static XtConvertArgRec cvt_string_to_pixel_args[] =
2105 {XtWidgetBaseOffset, (XtPointer) offsetof (WidgetRec, core.screen),
2106 sizeof (Screen *)},
2107 {XtWidgetBaseOffset, (XtPointer) offsetof (WidgetRec, core.colormap),
2108 sizeof (Colormap)}
2112 /* The address of this variable is returned by
2113 cvt_string_to_pixel. */
2115 static Pixel cvt_string_to_pixel_value;
2118 /* Convert a color name to a pixel color.
2120 DPY is the display we are working on.
2122 ARGS is an array of *NARGS XrmValue structures holding additional
2123 information about the widget for which the conversion takes place.
2124 The contents of this array are determined by the specification
2125 in cvt_string_to_pixel_args.
2127 FROM is a pointer to an XrmValue which points to the color name to
2128 convert. TO is an XrmValue in which to return the pixel color.
2130 CLOSURE_RET is a pointer to user-data, in which we record if
2131 we allocated the color or not.
2133 Value is True if successful, False otherwise. */
2135 static Boolean
2136 cvt_string_to_pixel (Display *dpy, XrmValue *args, Cardinal *nargs,
2137 XrmValue *from, XrmValue *to,
2138 XtPointer *closure_ret)
2140 Screen *screen;
2141 Colormap cmap;
2142 Pixel pixel;
2143 String color_name;
2144 XColor color;
2146 if (*nargs != 2)
2148 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
2149 "wrongParameters", "cvt_string_to_pixel",
2150 "XtToolkitError",
2151 "Screen and colormap args required", NULL, NULL);
2152 return False;
2155 screen = *(Screen **) args[0].addr;
2156 cmap = *(Colormap *) args[1].addr;
2157 color_name = (String) from->addr;
2159 if (strcmp (color_name, XtDefaultBackground) == 0)
2161 *closure_ret = (XtPointer) False;
2162 pixel = WhitePixelOfScreen (screen);
2164 else if (strcmp (color_name, XtDefaultForeground) == 0)
2166 *closure_ret = (XtPointer) False;
2167 pixel = BlackPixelOfScreen (screen);
2169 else if (XParseColor (dpy, cmap, color_name, &color)
2170 && x_alloc_nearest_color_1 (dpy, cmap, &color))
2172 pixel = color.pixel;
2173 *closure_ret = (XtPointer) True;
2175 else
2177 String params[1];
2178 Cardinal nparams = 1;
2180 params[0] = color_name;
2181 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
2182 "badValue", "cvt_string_to_pixel",
2183 "XtToolkitError", "Invalid color '%s'",
2184 params, &nparams);
2185 return False;
2188 if (to->addr != NULL)
2190 if (to->size < sizeof (Pixel))
2192 to->size = sizeof (Pixel);
2193 return False;
2196 *(Pixel *) to->addr = pixel;
2198 else
2200 cvt_string_to_pixel_value = pixel;
2201 to->addr = (XtPointer) &cvt_string_to_pixel_value;
2204 to->size = sizeof (Pixel);
2205 return True;
2209 /* Free a pixel color which was previously allocated via
2210 cvt_string_to_pixel. This is registered as the destructor
2211 for this type of resource via XtSetTypeConverter.
2213 APP is the application context in which we work.
2215 TO is a pointer to an XrmValue holding the color to free.
2216 CLOSURE is the value we stored in CLOSURE_RET for this color
2217 in cvt_string_to_pixel.
2219 ARGS and NARGS are like for cvt_string_to_pixel. */
2221 static void
2222 cvt_pixel_dtor (XtAppContext app, XrmValuePtr to, XtPointer closure, XrmValuePtr args,
2223 Cardinal *nargs)
2225 if (*nargs != 2)
2227 XtAppWarningMsg (app, "wrongParameters", "cvt_pixel_dtor",
2228 "XtToolkitError",
2229 "Screen and colormap arguments required",
2230 NULL, NULL);
2232 else if (closure != NULL)
2234 /* We did allocate the pixel, so free it. */
2235 Screen *screen = *(Screen **) args[0].addr;
2236 Colormap cmap = *(Colormap *) args[1].addr;
2237 x_free_dpy_colors (DisplayOfScreen (screen), screen, cmap,
2238 (Pixel *) to->addr, 1);
2243 #endif /* USE_X_TOOLKIT */
2246 /* Value is an array of XColor structures for the contents of the
2247 color map of display DPY. Set *NCELLS to the size of the array.
2248 Note that this probably shouldn't be called for large color maps,
2249 say a 24-bit TrueColor map. */
2251 static const XColor *
2252 x_color_cells (Display *dpy, int *ncells)
2254 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
2255 eassume (dpyinfo);
2257 if (dpyinfo->color_cells == NULL)
2259 Screen *screen = dpyinfo->screen;
2260 int ncolor_cells = XDisplayCells (dpy, XScreenNumberOfScreen (screen));
2261 int i;
2263 dpyinfo->color_cells = xnmalloc (ncolor_cells,
2264 sizeof *dpyinfo->color_cells);
2265 dpyinfo->ncolor_cells = ncolor_cells;
2267 for (i = 0; i < ncolor_cells; ++i)
2268 dpyinfo->color_cells[i].pixel = i;
2270 XQueryColors (dpy, dpyinfo->cmap,
2271 dpyinfo->color_cells, ncolor_cells);
2274 *ncells = dpyinfo->ncolor_cells;
2275 return dpyinfo->color_cells;
2279 /* On frame F, translate pixel colors to RGB values for the NCOLORS
2280 colors in COLORS. Use cached information, if available. */
2282 void
2283 x_query_colors (struct frame *f, XColor *colors, int ncolors)
2285 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2287 if (dpyinfo->red_bits > 0)
2289 /* For TrueColor displays, we can decompose the RGB value
2290 directly. */
2291 int i;
2292 unsigned int rmult, gmult, bmult;
2293 unsigned int rmask, gmask, bmask;
2295 rmask = (1 << dpyinfo->red_bits) - 1;
2296 gmask = (1 << dpyinfo->green_bits) - 1;
2297 bmask = (1 << dpyinfo->blue_bits) - 1;
2298 /* If we're widening, for example, 8 bits in the pixel value to
2299 16 bits for the separate-color representation, we want to
2300 extrapolate the lower bits based on those bits available --
2301 in other words, we'd like 0xff to become 0xffff instead of
2302 the 0xff00 we'd get by just zero-filling the lower bits.
2304 We generate a 32-bit scaled-up value and shift it, in case
2305 the bit count doesn't divide 16 evenly (e.g., when dealing
2306 with a 3-3-2 bit RGB display), to get more of the lower bits
2307 correct.
2309 Should we cache the multipliers in dpyinfo? Maybe
2310 special-case the 8-8-8 common case? */
2311 rmult = 0xffffffff / rmask;
2312 gmult = 0xffffffff / gmask;
2313 bmult = 0xffffffff / bmask;
2315 for (i = 0; i < ncolors; ++i)
2317 unsigned int r, g, b;
2318 unsigned long pixel = colors[i].pixel;
2320 r = (pixel >> dpyinfo->red_offset) & rmask;
2321 g = (pixel >> dpyinfo->green_offset) & gmask;
2322 b = (pixel >> dpyinfo->blue_offset) & bmask;
2324 colors[i].red = (r * rmult) >> 16;
2325 colors[i].green = (g * gmult) >> 16;
2326 colors[i].blue = (b * bmult) >> 16;
2328 return;
2331 if (dpyinfo->color_cells)
2333 int i;
2334 for (i = 0; i < ncolors; ++i)
2336 unsigned long pixel = colors[i].pixel;
2337 eassert (pixel < dpyinfo->ncolor_cells);
2338 eassert (dpyinfo->color_cells[pixel].pixel == pixel);
2339 colors[i] = dpyinfo->color_cells[pixel];
2341 return;
2344 XQueryColors (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), colors, ncolors);
2348 /* On frame F, translate pixel color to RGB values for the color in
2349 COLOR. Use cached information, if available. */
2351 void
2352 x_query_color (struct frame *f, XColor *color)
2354 x_query_colors (f, color, 1);
2358 /* On frame F, translate the color name to RGB values. Use cached
2359 information, if possible.
2361 Note that there is currently no way to clean old entries out of the
2362 cache. However, it is limited to names in the server's database,
2363 and names we've actually looked up; list-colors-display is probably
2364 the most color-intensive case we're likely to hit. */
2366 Status x_parse_color (struct frame *f, const char *color_name,
2367 XColor *color)
2369 Display *dpy = FRAME_X_DISPLAY (f);
2370 Colormap cmap = FRAME_X_COLORMAP (f);
2371 struct color_name_cache_entry *cache_entry;
2373 if (color_name[0] == '#')
2375 /* The hex form is parsed directly by XParseColor without
2376 talking to the X server. No need for caching. */
2377 return XParseColor (dpy, cmap, color_name, color);
2380 for (cache_entry = FRAME_DISPLAY_INFO (f)->color_names; cache_entry;
2381 cache_entry = cache_entry->next)
2383 if (!xstrcasecmp(cache_entry->name, color_name))
2385 *color = cache_entry->rgb;
2386 return 1;
2390 if (XParseColor (dpy, cmap, color_name, color) == 0)
2391 /* No caching of negative results, currently. */
2392 return 0;
2394 cache_entry = xzalloc (sizeof *cache_entry);
2395 cache_entry->rgb = *color;
2396 cache_entry->name = xstrdup (color_name);
2397 cache_entry->next = FRAME_DISPLAY_INFO (f)->color_names;
2398 FRAME_DISPLAY_INFO (f)->color_names = cache_entry;
2399 return 1;
2403 /* Allocate the color COLOR->pixel on DISPLAY, colormap CMAP. If an
2404 exact match can't be allocated, try the nearest color available.
2405 Value is true if successful. Set *COLOR to the color
2406 allocated. */
2408 static bool
2409 x_alloc_nearest_color_1 (Display *dpy, Colormap cmap, XColor *color)
2411 bool rc;
2413 rc = XAllocColor (dpy, cmap, color) != 0;
2414 if (rc == 0)
2416 /* If we got to this point, the colormap is full, so we're going
2417 to try to get the next closest color. The algorithm used is
2418 a least-squares matching, which is what X uses for closest
2419 color matching with StaticColor visuals. */
2420 int nearest, i;
2421 int max_color_delta = 255;
2422 int max_delta = 3 * max_color_delta;
2423 int nearest_delta = max_delta + 1;
2424 int ncells;
2425 const XColor *cells = x_color_cells (dpy, &ncells);
2427 for (nearest = i = 0; i < ncells; ++i)
2429 int dred = (color->red >> 8) - (cells[i].red >> 8);
2430 int dgreen = (color->green >> 8) - (cells[i].green >> 8);
2431 int dblue = (color->blue >> 8) - (cells[i].blue >> 8);
2432 int delta = dred * dred + dgreen * dgreen + dblue * dblue;
2434 if (delta < nearest_delta)
2436 nearest = i;
2437 nearest_delta = delta;
2441 color->red = cells[nearest].red;
2442 color->green = cells[nearest].green;
2443 color->blue = cells[nearest].blue;
2444 rc = XAllocColor (dpy, cmap, color) != 0;
2446 else
2448 /* If allocation succeeded, and the allocated pixel color is not
2449 equal to a cached pixel color recorded earlier, there was a
2450 change in the colormap, so clear the color cache. */
2451 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
2452 eassume (dpyinfo);
2454 if (dpyinfo->color_cells)
2456 XColor *cached_color = &dpyinfo->color_cells[color->pixel];
2457 if (cached_color->red != color->red
2458 || cached_color->blue != color->blue
2459 || cached_color->green != color->green)
2461 xfree (dpyinfo->color_cells);
2462 dpyinfo->color_cells = NULL;
2463 dpyinfo->ncolor_cells = 0;
2468 #ifdef DEBUG_X_COLORS
2469 if (rc)
2470 register_color (color->pixel);
2471 #endif /* DEBUG_X_COLORS */
2473 return rc;
2477 /* Allocate the color COLOR->pixel on frame F, colormap CMAP, after
2478 gamma correction. If an exact match can't be allocated, try the
2479 nearest color available. Value is true if successful. Set *COLOR
2480 to the color allocated. */
2482 bool
2483 x_alloc_nearest_color (struct frame *f, Colormap cmap, XColor *color)
2485 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2487 gamma_correct (f, color);
2489 if (dpyinfo->red_bits > 0)
2491 color->pixel = x_make_truecolor_pixel (dpyinfo,
2492 color->red,
2493 color->green,
2494 color->blue);
2495 return true;
2498 return x_alloc_nearest_color_1 (FRAME_X_DISPLAY (f), cmap, color);
2502 /* Allocate color PIXEL on frame F. PIXEL must already be allocated.
2503 It's necessary to do this instead of just using PIXEL directly to
2504 get color reference counts right. */
2506 unsigned long
2507 x_copy_color (struct frame *f, unsigned long pixel)
2509 XColor color;
2511 /* If display has an immutable color map, freeing colors is not
2512 necessary and some servers don't allow it. Since we won't free a
2513 color once we've allocated it, we don't need to re-allocate it to
2514 maintain the server's reference count. */
2515 if (!x_mutable_colormap (FRAME_X_VISUAL (f)))
2516 return pixel;
2518 color.pixel = pixel;
2519 block_input ();
2520 /* The color could still be found in the color_cells array. */
2521 x_query_color (f, &color);
2522 XAllocColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &color);
2523 unblock_input ();
2524 #ifdef DEBUG_X_COLORS
2525 register_color (pixel);
2526 #endif
2527 return color.pixel;
2531 /* Brightness beyond which a color won't have its highlight brightness
2532 boosted.
2534 Nominally, highlight colors for `3d' faces are calculated by
2535 brightening an object's color by a constant scale factor, but this
2536 doesn't yield good results for dark colors, so for colors who's
2537 brightness is less than this value (on a scale of 0-65535) have an
2538 use an additional additive factor.
2540 The value here is set so that the default menu-bar/mode-line color
2541 (grey75) will not have its highlights changed at all. */
2542 #define HIGHLIGHT_COLOR_DARK_BOOST_LIMIT 48000
2545 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
2546 or DELTA. Try a color with RGB values multiplied by FACTOR first.
2547 If this produces the same color as PIXEL, try a color where all RGB
2548 values have DELTA added. Return the allocated color in *PIXEL.
2549 DISPLAY is the X display, CMAP is the colormap to operate on.
2550 Value is non-zero if successful. */
2552 static bool
2553 x_alloc_lighter_color (struct frame *f, Display *display, Colormap cmap,
2554 unsigned long *pixel, double factor, int delta)
2556 XColor color, new;
2557 long bright;
2558 bool success_p;
2560 /* Get RGB color values. */
2561 color.pixel = *pixel;
2562 x_query_color (f, &color);
2564 /* Change RGB values by specified FACTOR. Avoid overflow! */
2565 eassert (factor >= 0);
2566 new.red = min (0xffff, factor * color.red);
2567 new.green = min (0xffff, factor * color.green);
2568 new.blue = min (0xffff, factor * color.blue);
2570 /* Calculate brightness of COLOR. */
2571 bright = (2 * color.red + 3 * color.green + color.blue) / 6;
2573 /* We only boost colors that are darker than
2574 HIGHLIGHT_COLOR_DARK_BOOST_LIMIT. */
2575 if (bright < HIGHLIGHT_COLOR_DARK_BOOST_LIMIT)
2576 /* Make an additive adjustment to NEW, because it's dark enough so
2577 that scaling by FACTOR alone isn't enough. */
2579 /* How far below the limit this color is (0 - 1, 1 being darker). */
2580 double dimness = 1 - (double)bright / HIGHLIGHT_COLOR_DARK_BOOST_LIMIT;
2581 /* The additive adjustment. */
2582 int min_delta = delta * dimness * factor / 2;
2584 if (factor < 1)
2586 new.red = max (0, new.red - min_delta);
2587 new.green = max (0, new.green - min_delta);
2588 new.blue = max (0, new.blue - min_delta);
2590 else
2592 new.red = min (0xffff, min_delta + new.red);
2593 new.green = min (0xffff, min_delta + new.green);
2594 new.blue = min (0xffff, min_delta + new.blue);
2598 /* Try to allocate the color. */
2599 success_p = x_alloc_nearest_color (f, cmap, &new);
2600 if (success_p)
2602 if (new.pixel == *pixel)
2604 /* If we end up with the same color as before, try adding
2605 delta to the RGB values. */
2606 x_free_colors (f, &new.pixel, 1);
2608 new.red = min (0xffff, delta + color.red);
2609 new.green = min (0xffff, delta + color.green);
2610 new.blue = min (0xffff, delta + color.blue);
2611 success_p = x_alloc_nearest_color (f, cmap, &new);
2613 else
2614 success_p = true;
2615 *pixel = new.pixel;
2618 return success_p;
2622 /* Set up the foreground color for drawing relief lines of glyph
2623 string S. RELIEF is a pointer to a struct relief containing the GC
2624 with which lines will be drawn. Use a color that is FACTOR or
2625 DELTA lighter or darker than the relief's background which is found
2626 in S->f->output_data.x->relief_background. If such a color cannot
2627 be allocated, use DEFAULT_PIXEL, instead. */
2629 static void
2630 x_setup_relief_color (struct frame *f, struct relief *relief, double factor,
2631 int delta, unsigned long default_pixel)
2633 XGCValues xgcv;
2634 struct x_output *di = f->output_data.x;
2635 unsigned long mask = GCForeground | GCLineWidth | GCGraphicsExposures;
2636 unsigned long pixel;
2637 unsigned long background = di->relief_background;
2638 Colormap cmap = FRAME_X_COLORMAP (f);
2639 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2640 Display *dpy = FRAME_X_DISPLAY (f);
2642 xgcv.graphics_exposures = False;
2643 xgcv.line_width = 1;
2645 /* Free previously allocated color. The color cell will be reused
2646 when it has been freed as many times as it was allocated, so this
2647 doesn't affect faces using the same colors. */
2648 if (relief->gc && relief->pixel != -1)
2650 x_free_colors (f, &relief->pixel, 1);
2651 relief->pixel = -1;
2654 /* Allocate new color. */
2655 xgcv.foreground = default_pixel;
2656 pixel = background;
2657 if (dpyinfo->n_planes != 1
2658 && x_alloc_lighter_color (f, dpy, cmap, &pixel, factor, delta))
2659 xgcv.foreground = relief->pixel = pixel;
2661 if (relief->gc == 0)
2663 xgcv.stipple = dpyinfo->gray;
2664 mask |= GCStipple;
2665 relief->gc = XCreateGC (dpy, FRAME_X_DRAWABLE (f), mask, &xgcv);
2667 else
2668 XChangeGC (dpy, relief->gc, mask, &xgcv);
2672 /* Set up colors for the relief lines around glyph string S. */
2674 static void
2675 x_setup_relief_colors (struct glyph_string *s)
2677 struct x_output *di = s->f->output_data.x;
2678 unsigned long color;
2680 if (s->face->use_box_color_for_shadows_p)
2681 color = s->face->box_color;
2682 else if (s->first_glyph->type == IMAGE_GLYPH
2683 && s->img->pixmap
2684 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2685 color = IMAGE_BACKGROUND (s->img, s->f, 0);
2686 else
2688 XGCValues xgcv;
2690 /* Get the background color of the face. */
2691 XGetGCValues (s->display, s->gc, GCBackground, &xgcv);
2692 color = xgcv.background;
2695 if (di->white_relief.gc == 0
2696 || color != di->relief_background)
2698 di->relief_background = color;
2699 x_setup_relief_color (s->f, &di->white_relief, 1.2, 0x8000,
2700 WHITE_PIX_DEFAULT (s->f));
2701 x_setup_relief_color (s->f, &di->black_relief, 0.6, 0x4000,
2702 BLACK_PIX_DEFAULT (s->f));
2707 /* Draw a relief on frame F inside the rectangle given by LEFT_X,
2708 TOP_Y, RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the relief
2709 to draw, it must be >= 0. RAISED_P means draw a raised
2710 relief. LEFT_P means draw a relief on the left side of
2711 the rectangle. RIGHT_P means draw a relief on the right
2712 side of the rectangle. CLIP_RECT is the clipping rectangle to use
2713 when drawing. */
2715 static void
2716 x_draw_relief_rect (struct frame *f,
2717 int left_x, int top_y, int right_x, int bottom_y,
2718 int width, bool raised_p, bool top_p, bool bot_p,
2719 bool left_p, bool right_p,
2720 XRectangle *clip_rect)
2722 #ifdef USE_CAIRO
2723 GC top_left_gc, bottom_right_gc;
2724 int corners = 0;
2726 if (raised_p)
2728 top_left_gc = f->output_data.x->white_relief.gc;
2729 bottom_right_gc = f->output_data.x->black_relief.gc;
2731 else
2733 top_left_gc = f->output_data.x->black_relief.gc;
2734 bottom_right_gc = f->output_data.x->white_relief.gc;
2737 x_set_clip_rectangles (f, top_left_gc, clip_rect, 1);
2738 x_set_clip_rectangles (f, bottom_right_gc, clip_rect, 1);
2740 if (left_p)
2742 x_fill_rectangle (f, top_left_gc, left_x, top_y,
2743 width, bottom_y + 1 - top_y);
2744 if (top_p)
2745 corners |= 1 << CORNER_TOP_LEFT;
2746 if (bot_p)
2747 corners |= 1 << CORNER_BOTTOM_LEFT;
2749 if (right_p)
2751 x_fill_rectangle (f, bottom_right_gc, right_x + 1 - width, top_y,
2752 width, bottom_y + 1 - top_y);
2753 if (top_p)
2754 corners |= 1 << CORNER_TOP_RIGHT;
2755 if (bot_p)
2756 corners |= 1 << CORNER_BOTTOM_RIGHT;
2758 if (top_p)
2760 if (!right_p)
2761 x_fill_rectangle (f, top_left_gc, left_x, top_y,
2762 right_x + 1 - left_x, width);
2763 else
2764 x_fill_trapezoid_for_relief (f, top_left_gc, left_x, top_y,
2765 right_x + 1 - left_x, width, 1);
2767 if (bot_p)
2769 if (!left_p)
2770 x_fill_rectangle (f, bottom_right_gc, left_x, bottom_y + 1 - width,
2771 right_x + 1 - left_x, width);
2772 else
2773 x_fill_trapezoid_for_relief (f, bottom_right_gc,
2774 left_x, bottom_y + 1 - width,
2775 right_x + 1 - left_x, width, 0);
2777 if (left_p && width != 1)
2778 x_fill_rectangle (f, bottom_right_gc, left_x, top_y,
2779 1, bottom_y + 1 - top_y);
2780 if (top_p && width != 1)
2781 x_fill_rectangle (f, bottom_right_gc, left_x, top_y,
2782 right_x + 1 - left_x, 1);
2783 if (corners)
2785 XSetBackground (FRAME_X_DISPLAY (f), top_left_gc,
2786 FRAME_BACKGROUND_PIXEL (f));
2787 x_erase_corners_for_relief (f, top_left_gc, left_x, top_y,
2788 right_x - left_x + 1, bottom_y - top_y + 1,
2789 6, 1, corners);
2792 x_reset_clip_rectangles (f, top_left_gc);
2793 x_reset_clip_rectangles (f, bottom_right_gc);
2794 #else
2795 Display *dpy = FRAME_X_DISPLAY (f);
2796 Drawable drawable = FRAME_X_DRAWABLE (f);
2797 int i;
2798 GC gc;
2800 if (raised_p)
2801 gc = f->output_data.x->white_relief.gc;
2802 else
2803 gc = f->output_data.x->black_relief.gc;
2804 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
2806 /* This code is more complicated than it has to be, because of two
2807 minor hacks to make the boxes look nicer: (i) if width > 1, draw
2808 the outermost line using the black relief. (ii) Omit the four
2809 corner pixels. */
2811 /* Top. */
2812 if (top_p)
2814 if (width == 1)
2815 XDrawLine (dpy, drawable, gc,
2816 left_x + left_p, top_y,
2817 right_x + !right_p, top_y);
2819 for (i = 1; i < width; ++i)
2820 XDrawLine (dpy, drawable, gc,
2821 left_x + i * left_p, top_y + i,
2822 right_x + 1 - i * right_p, top_y + i);
2825 /* Left. */
2826 if (left_p)
2828 if (width == 1)
2829 XDrawLine (dpy, drawable, gc, left_x, top_y + 1, left_x, bottom_y);
2831 x_clear_area(f, left_x, top_y, 1, 1);
2832 x_clear_area(f, left_x, bottom_y, 1, 1);
2834 for (i = (width > 1 ? 1 : 0); i < width; ++i)
2835 XDrawLine (dpy, drawable, gc,
2836 left_x + i, top_y + (i + 1) * top_p,
2837 left_x + i, bottom_y + 1 - (i + 1) * bot_p);
2840 XSetClipMask (dpy, gc, None);
2841 if (raised_p)
2842 gc = f->output_data.x->black_relief.gc;
2843 else
2844 gc = f->output_data.x->white_relief.gc;
2845 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
2847 if (width > 1)
2849 /* Outermost top line. */
2850 if (top_p)
2851 XDrawLine (dpy, drawable, gc,
2852 left_x + left_p, top_y,
2853 right_x + !right_p, top_y);
2855 /* Outermost left line. */
2856 if (left_p)
2857 XDrawLine (dpy, drawable, gc, left_x, top_y + 1, left_x, bottom_y);
2860 /* Bottom. */
2861 if (bot_p)
2863 XDrawLine (dpy, drawable, gc,
2864 left_x + left_p, bottom_y,
2865 right_x + !right_p, bottom_y);
2866 for (i = 1; i < width; ++i)
2867 XDrawLine (dpy, drawable, gc,
2868 left_x + i * left_p, bottom_y - i,
2869 right_x + 1 - i * right_p, bottom_y - i);
2872 /* Right. */
2873 if (right_p)
2875 x_clear_area(f, right_x, top_y, 1, 1);
2876 x_clear_area(f, right_x, bottom_y, 1, 1);
2877 for (i = 0; i < width; ++i)
2878 XDrawLine (dpy, drawable, gc,
2879 right_x - i, top_y + (i + 1) * top_p,
2880 right_x - i, bottom_y + 1 - (i + 1) * bot_p);
2883 x_reset_clip_rectangles (f, gc);
2885 #endif
2889 /* Draw a box on frame F inside the rectangle given by LEFT_X, TOP_Y,
2890 RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the lines to
2891 draw, it must be >= 0. LEFT_P means draw a line on the
2892 left side of the rectangle. RIGHT_P means draw a line
2893 on the right side of the rectangle. CLIP_RECT is the clipping
2894 rectangle to use when drawing. */
2896 static void
2897 x_draw_box_rect (struct glyph_string *s,
2898 int left_x, int top_y, int right_x, int bottom_y, int width,
2899 bool left_p, bool right_p, XRectangle *clip_rect)
2901 XGCValues xgcv;
2903 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2904 XSetForeground (s->display, s->gc, s->face->box_color);
2905 x_set_clip_rectangles (s->f, s->gc, clip_rect, 1);
2907 /* Top. */
2908 x_fill_rectangle (s->f, s->gc,
2909 left_x, top_y, right_x - left_x + 1, width);
2911 /* Left. */
2912 if (left_p)
2913 x_fill_rectangle (s->f, s->gc,
2914 left_x, top_y, width, bottom_y - top_y + 1);
2916 /* Bottom. */
2917 x_fill_rectangle (s->f, s->gc,
2918 left_x, bottom_y - width + 1, right_x - left_x + 1, width);
2920 /* Right. */
2921 if (right_p)
2922 x_fill_rectangle (s->f, s->gc,
2923 right_x - width + 1, top_y, width, bottom_y - top_y + 1);
2925 XSetForeground (s->display, s->gc, xgcv.foreground);
2926 x_reset_clip_rectangles (s->f, s->gc);
2930 /* Draw a box around glyph string S. */
2932 static void
2933 x_draw_glyph_string_box (struct glyph_string *s)
2935 int width, left_x, right_x, top_y, bottom_y, last_x;
2936 bool raised_p, left_p, right_p;
2937 struct glyph *last_glyph;
2938 XRectangle clip_rect;
2940 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2941 ? WINDOW_RIGHT_EDGE_X (s->w)
2942 : window_box_right (s->w, s->area));
2944 /* The glyph that may have a right box line. */
2945 last_glyph = (s->cmp || s->img
2946 ? s->first_glyph
2947 : s->first_glyph + s->nchars - 1);
2949 width = eabs (s->face->box_line_width);
2950 raised_p = s->face->box == FACE_RAISED_BOX;
2951 left_x = s->x;
2952 right_x = (s->row->full_width_p && s->extends_to_end_of_line_p
2953 ? last_x - 1
2954 : min (last_x, s->x + s->background_width) - 1);
2955 top_y = s->y;
2956 bottom_y = top_y + s->height - 1;
2958 left_p = (s->first_glyph->left_box_line_p
2959 || (s->hl == DRAW_MOUSE_FACE
2960 && (s->prev == NULL
2961 || s->prev->hl != s->hl)));
2962 right_p = (last_glyph->right_box_line_p
2963 || (s->hl == DRAW_MOUSE_FACE
2964 && (s->next == NULL
2965 || s->next->hl != s->hl)));
2967 get_glyph_string_clip_rect (s, &clip_rect);
2969 if (s->face->box == FACE_SIMPLE_BOX)
2970 x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
2971 left_p, right_p, &clip_rect);
2972 else
2974 x_setup_relief_colors (s);
2975 x_draw_relief_rect (s->f, left_x, top_y, right_x, bottom_y,
2976 width, raised_p, true, true, left_p, right_p,
2977 &clip_rect);
2982 /* Draw foreground of image glyph string S. */
2984 static void
2985 x_draw_image_foreground (struct glyph_string *s)
2987 int x = s->x;
2988 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2990 /* If first glyph of S has a left box line, start drawing it to the
2991 right of that line. */
2992 if (s->face->box != FACE_NO_BOX
2993 && s->first_glyph->left_box_line_p
2994 && s->slice.x == 0)
2995 x += eabs (s->face->box_line_width);
2997 /* If there is a margin around the image, adjust x- and y-position
2998 by that margin. */
2999 if (s->slice.x == 0)
3000 x += s->img->hmargin;
3001 if (s->slice.y == 0)
3002 y += s->img->vmargin;
3004 if (s->img->pixmap)
3006 if (s->img->mask)
3008 /* We can't set both a clip mask and use XSetClipRectangles
3009 because the latter also sets a clip mask. We also can't
3010 trust on the shape extension to be available
3011 (XShapeCombineRegion). So, compute the rectangle to draw
3012 manually. */
3013 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
3014 | GCFunction);
3015 XGCValues xgcv;
3016 XRectangle clip_rect, image_rect, r;
3018 xgcv.clip_mask = s->img->mask;
3019 xgcv.clip_x_origin = x;
3020 xgcv.clip_y_origin = y;
3021 xgcv.function = GXcopy;
3022 XChangeGC (s->display, s->gc, mask, &xgcv);
3024 get_glyph_string_clip_rect (s, &clip_rect);
3025 image_rect.x = x;
3026 image_rect.y = y;
3027 image_rect.width = s->slice.width;
3028 image_rect.height = s->slice.height;
3029 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
3030 XCopyArea (s->display, s->img->pixmap,
3031 FRAME_X_DRAWABLE (s->f), s->gc,
3032 s->slice.x + r.x - x, s->slice.y + r.y - y,
3033 r.width, r.height, r.x, r.y);
3035 else
3037 XRectangle clip_rect, image_rect, r;
3039 get_glyph_string_clip_rect (s, &clip_rect);
3040 image_rect.x = x;
3041 image_rect.y = y;
3042 image_rect.width = s->slice.width;
3043 image_rect.height = s->slice.height;
3044 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
3045 XCopyArea (s->display, s->img->pixmap,
3046 FRAME_X_DRAWABLE (s->f), s->gc,
3047 s->slice.x + r.x - x, s->slice.y + r.y - y,
3048 r.width, r.height, r.x, r.y);
3050 /* When the image has a mask, we can expect that at
3051 least part of a mouse highlight or a block cursor will
3052 be visible. If the image doesn't have a mask, make
3053 a block cursor visible by drawing a rectangle around
3054 the image. I believe it's looking better if we do
3055 nothing here for mouse-face. */
3056 if (s->hl == DRAW_CURSOR)
3058 int relief = eabs (s->img->relief);
3059 x_draw_rectangle (s->f, s->gc,
3060 x - relief, y - relief,
3061 s->slice.width + relief*2 - 1,
3062 s->slice.height + relief*2 - 1);
3066 else
3067 /* Draw a rectangle if image could not be loaded. */
3068 x_draw_rectangle (s->f, s->gc, x, y,
3069 s->slice.width - 1, s->slice.height - 1);
3073 /* Draw a relief around the image glyph string S. */
3075 static void
3076 x_draw_image_relief (struct glyph_string *s)
3078 int x1, y1, thick;
3079 bool raised_p, top_p, bot_p, left_p, right_p;
3080 int extra_x, extra_y;
3081 XRectangle r;
3082 int x = s->x;
3083 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
3085 /* If first glyph of S has a left box line, start drawing it to the
3086 right of that line. */
3087 if (s->face->box != FACE_NO_BOX
3088 && s->first_glyph->left_box_line_p
3089 && s->slice.x == 0)
3090 x += eabs (s->face->box_line_width);
3092 /* If there is a margin around the image, adjust x- and y-position
3093 by that margin. */
3094 if (s->slice.x == 0)
3095 x += s->img->hmargin;
3096 if (s->slice.y == 0)
3097 y += s->img->vmargin;
3099 if (s->hl == DRAW_IMAGE_SUNKEN
3100 || s->hl == DRAW_IMAGE_RAISED)
3102 thick = tool_bar_button_relief >= 0 ? tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3103 raised_p = s->hl == DRAW_IMAGE_RAISED;
3105 else
3107 thick = eabs (s->img->relief);
3108 raised_p = s->img->relief > 0;
3111 x1 = x + s->slice.width - 1;
3112 y1 = y + s->slice.height - 1;
3114 extra_x = extra_y = 0;
3115 if (s->face->id == TOOL_BAR_FACE_ID)
3117 if (CONSP (Vtool_bar_button_margin)
3118 && INTEGERP (XCAR (Vtool_bar_button_margin))
3119 && INTEGERP (XCDR (Vtool_bar_button_margin)))
3121 extra_x = XINT (XCAR (Vtool_bar_button_margin));
3122 extra_y = XINT (XCDR (Vtool_bar_button_margin));
3124 else if (INTEGERP (Vtool_bar_button_margin))
3125 extra_x = extra_y = XINT (Vtool_bar_button_margin);
3128 top_p = bot_p = left_p = right_p = false;
3130 if (s->slice.x == 0)
3131 x -= thick + extra_x, left_p = true;
3132 if (s->slice.y == 0)
3133 y -= thick + extra_y, top_p = true;
3134 if (s->slice.x + s->slice.width == s->img->width)
3135 x1 += thick + extra_x, right_p = true;
3136 if (s->slice.y + s->slice.height == s->img->height)
3137 y1 += thick + extra_y, bot_p = true;
3139 x_setup_relief_colors (s);
3140 get_glyph_string_clip_rect (s, &r);
3141 x_draw_relief_rect (s->f, x, y, x1, y1, thick, raised_p,
3142 top_p, bot_p, left_p, right_p, &r);
3146 /* Draw the foreground of image glyph string S to PIXMAP. */
3148 static void
3149 x_draw_image_foreground_1 (struct glyph_string *s, Pixmap pixmap)
3151 int x = 0;
3152 int y = s->ybase - s->y - image_ascent (s->img, s->face, &s->slice);
3154 /* If first glyph of S has a left box line, start drawing it to the
3155 right of that line. */
3156 if (s->face->box != FACE_NO_BOX
3157 && s->first_glyph->left_box_line_p
3158 && s->slice.x == 0)
3159 x += eabs (s->face->box_line_width);
3161 /* If there is a margin around the image, adjust x- and y-position
3162 by that margin. */
3163 if (s->slice.x == 0)
3164 x += s->img->hmargin;
3165 if (s->slice.y == 0)
3166 y += s->img->vmargin;
3168 if (s->img->pixmap)
3170 if (s->img->mask)
3172 /* We can't set both a clip mask and use XSetClipRectangles
3173 because the latter also sets a clip mask. We also can't
3174 trust on the shape extension to be available
3175 (XShapeCombineRegion). So, compute the rectangle to draw
3176 manually. */
3177 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
3178 | GCFunction);
3179 XGCValues xgcv;
3181 xgcv.clip_mask = s->img->mask;
3182 xgcv.clip_x_origin = x - s->slice.x;
3183 xgcv.clip_y_origin = y - s->slice.y;
3184 xgcv.function = GXcopy;
3185 XChangeGC (s->display, s->gc, mask, &xgcv);
3187 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
3188 s->slice.x, s->slice.y,
3189 s->slice.width, s->slice.height, x, y);
3190 XSetClipMask (s->display, s->gc, None);
3192 else
3194 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
3195 s->slice.x, s->slice.y,
3196 s->slice.width, s->slice.height, x, y);
3198 /* When the image has a mask, we can expect that at
3199 least part of a mouse highlight or a block cursor will
3200 be visible. If the image doesn't have a mask, make
3201 a block cursor visible by drawing a rectangle around
3202 the image. I believe it's looking better if we do
3203 nothing here for mouse-face. */
3204 if (s->hl == DRAW_CURSOR)
3206 int r = eabs (s->img->relief);
3207 x_draw_rectangle (s->f, s->gc, x - r, y - r,
3208 s->slice.width + r*2 - 1,
3209 s->slice.height + r*2 - 1);
3213 else
3214 /* Draw a rectangle if image could not be loaded. */
3215 x_draw_rectangle (s->f, s->gc, x, y,
3216 s->slice.width - 1, s->slice.height - 1);
3220 /* Draw part of the background of glyph string S. X, Y, W, and H
3221 give the rectangle to draw. */
3223 static void
3224 x_draw_glyph_string_bg_rect (struct glyph_string *s, int x, int y, int w, int h)
3226 if (s->stippled_p)
3228 /* Fill background with a stipple pattern. */
3229 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
3230 x_fill_rectangle (s->f, s->gc, x, y, w, h);
3231 XSetFillStyle (s->display, s->gc, FillSolid);
3233 else
3234 x_clear_glyph_string_rect (s, x, y, w, h);
3238 /* Draw image glyph string S.
3240 s->y
3241 s->x +-------------------------
3242 | s->face->box
3244 | +-------------------------
3245 | | s->img->margin
3247 | | +-------------------
3248 | | | the image
3252 static void
3253 x_draw_image_glyph_string (struct glyph_string *s)
3255 int box_line_hwidth = eabs (s->face->box_line_width);
3256 int box_line_vwidth = max (s->face->box_line_width, 0);
3257 int height;
3258 Pixmap pixmap = None;
3260 height = s->height;
3261 if (s->slice.y == 0)
3262 height -= box_line_vwidth;
3263 if (s->slice.y + s->slice.height >= s->img->height)
3264 height -= box_line_vwidth;
3266 /* Fill background with face under the image. Do it only if row is
3267 taller than image or if image has a clip mask to reduce
3268 flickering. */
3269 s->stippled_p = s->face->stipple != 0;
3270 if (height > s->slice.height
3271 || s->img->hmargin
3272 || s->img->vmargin
3273 || s->img->mask
3274 || s->img->pixmap == 0
3275 || s->width != s->background_width)
3277 if (s->img->mask)
3279 /* Create a pixmap as large as the glyph string. Fill it
3280 with the background color. Copy the image to it, using
3281 its mask. Copy the temporary pixmap to the display. */
3282 Screen *screen = FRAME_X_SCREEN (s->f);
3283 int depth = DefaultDepthOfScreen (screen);
3285 /* Create a pixmap as large as the glyph string. */
3286 pixmap = XCreatePixmap (s->display, FRAME_X_DRAWABLE (s->f),
3287 s->background_width,
3288 s->height, depth);
3290 /* Don't clip in the following because we're working on the
3291 pixmap. */
3292 XSetClipMask (s->display, s->gc, None);
3294 /* Fill the pixmap with the background color/stipple. */
3295 if (s->stippled_p)
3297 /* Fill background with a stipple pattern. */
3298 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
3299 XSetTSOrigin (s->display, s->gc, - s->x, - s->y);
3300 XFillRectangle (s->display, pixmap, s->gc,
3301 0, 0, s->background_width, s->height);
3302 XSetFillStyle (s->display, s->gc, FillSolid);
3303 XSetTSOrigin (s->display, s->gc, 0, 0);
3305 else
3307 XGCValues xgcv;
3308 XGetGCValues (s->display, s->gc, GCForeground | GCBackground,
3309 &xgcv);
3310 XSetForeground (s->display, s->gc, xgcv.background);
3311 XFillRectangle (s->display, pixmap, s->gc,
3312 0, 0, s->background_width, s->height);
3313 XSetForeground (s->display, s->gc, xgcv.foreground);
3316 else
3318 int x = s->x;
3319 int y = s->y;
3320 int width = s->background_width;
3322 if (s->first_glyph->left_box_line_p
3323 && s->slice.x == 0)
3325 x += box_line_hwidth;
3326 width -= box_line_hwidth;
3329 if (s->slice.y == 0)
3330 y += box_line_vwidth;
3332 x_draw_glyph_string_bg_rect (s, x, y, width, height);
3335 s->background_filled_p = true;
3338 /* Draw the foreground. */
3339 #ifdef USE_CAIRO
3340 if (s->img->cr_data)
3342 cairo_t *cr = x_begin_cr_clip (s->f, s->gc);
3344 int x = s->x + s->img->hmargin;
3345 int y = s->y + s->img->vmargin;
3346 int width = s->background_width;
3348 cairo_set_source_surface (cr, s->img->cr_data,
3349 x - s->slice.x,
3350 y - s->slice.y);
3351 cairo_rectangle (cr, x, y, width, height);
3352 cairo_fill (cr);
3353 x_end_cr_clip (s->f);
3355 else
3356 #endif
3357 if (pixmap != None)
3359 x_draw_image_foreground_1 (s, pixmap);
3360 x_set_glyph_string_clipping (s);
3361 XCopyArea (s->display, pixmap, FRAME_X_DRAWABLE (s->f), s->gc,
3362 0, 0, s->background_width, s->height, s->x, s->y);
3363 XFreePixmap (s->display, pixmap);
3365 else
3366 x_draw_image_foreground (s);
3368 /* If we must draw a relief around the image, do it. */
3369 if (s->img->relief
3370 || s->hl == DRAW_IMAGE_RAISED
3371 || s->hl == DRAW_IMAGE_SUNKEN)
3372 x_draw_image_relief (s);
3376 /* Draw stretch glyph string S. */
3378 static void
3379 x_draw_stretch_glyph_string (struct glyph_string *s)
3381 eassert (s->first_glyph->type == STRETCH_GLYPH);
3383 if (s->hl == DRAW_CURSOR
3384 && !x_stretch_cursor_p)
3386 /* If `x-stretch-cursor' is nil, don't draw a block cursor as
3387 wide as the stretch glyph. */
3388 int width, background_width = s->background_width;
3389 int x = s->x;
3391 if (!s->row->reversed_p)
3393 int left_x = window_box_left_offset (s->w, TEXT_AREA);
3395 if (x < left_x)
3397 background_width -= left_x - x;
3398 x = left_x;
3401 else
3403 /* In R2L rows, draw the cursor on the right edge of the
3404 stretch glyph. */
3405 int right_x = window_box_right (s->w, TEXT_AREA);
3407 if (x + background_width > right_x)
3408 background_width -= x - right_x;
3409 x += background_width;
3411 width = min (FRAME_COLUMN_WIDTH (s->f), background_width);
3412 if (s->row->reversed_p)
3413 x -= width;
3415 /* Draw cursor. */
3416 x_draw_glyph_string_bg_rect (s, x, s->y, width, s->height);
3418 /* Clear rest using the GC of the original non-cursor face. */
3419 if (width < background_width)
3421 int y = s->y;
3422 int w = background_width - width, h = s->height;
3423 XRectangle r;
3424 GC gc;
3426 if (!s->row->reversed_p)
3427 x += width;
3428 else
3429 x = s->x;
3430 if (s->row->mouse_face_p
3431 && cursor_in_mouse_face_p (s->w))
3433 x_set_mouse_face_gc (s);
3434 gc = s->gc;
3436 else
3437 gc = s->face->gc;
3439 get_glyph_string_clip_rect (s, &r);
3440 x_set_clip_rectangles (s->f, gc, &r, 1);
3442 if (s->face->stipple)
3444 /* Fill background with a stipple pattern. */
3445 XSetFillStyle (s->display, gc, FillOpaqueStippled);
3446 x_fill_rectangle (s->f, gc, x, y, w, h);
3447 XSetFillStyle (s->display, gc, FillSolid);
3449 else
3451 XGCValues xgcv;
3452 XGetGCValues (s->display, gc, GCForeground | GCBackground, &xgcv);
3453 XSetForeground (s->display, gc, xgcv.background);
3454 x_fill_rectangle (s->f, gc, x, y, w, h);
3455 XSetForeground (s->display, gc, xgcv.foreground);
3458 x_reset_clip_rectangles (s->f, gc);
3461 else if (!s->background_filled_p)
3463 int background_width = s->background_width;
3464 int x = s->x, left_x = window_box_left_offset (s->w, TEXT_AREA);
3466 /* Don't draw into left margin, fringe or scrollbar area
3467 except for header line and mode line. */
3468 if (x < left_x && !s->row->mode_line_p)
3470 background_width -= left_x - x;
3471 x = left_x;
3473 if (background_width > 0)
3474 x_draw_glyph_string_bg_rect (s, x, s->y, background_width, s->height);
3477 s->background_filled_p = true;
3480 static void
3481 x_get_scale_factor(Display *disp, int *scale_x, int *scale_y)
3483 const int base_res = 96;
3484 struct x_display_info * dpyinfo = x_display_info_for_display (disp);
3486 *scale_x = *scale_y = 1;
3488 if (dpyinfo)
3490 if (dpyinfo->resx > base_res)
3491 *scale_x = floor (dpyinfo->resx / base_res);
3492 if (dpyinfo->resy > base_res)
3493 *scale_y = floor (dpyinfo->resy / base_res);
3498 Draw a wavy line under S. The wave fills wave_height pixels from y0.
3500 x0 wave_length = 2
3502 y0 * * * * *
3503 |* * * * * * * * *
3504 wave_height = 3 | * * * *
3507 static void
3508 x_draw_underwave (struct glyph_string *s)
3510 /* Adjust for scale/HiDPI. */
3511 int scale_x, scale_y;
3513 x_get_scale_factor (s->display, &scale_x, &scale_y);
3515 int wave_height = 3 * scale_y, wave_length = 2 * scale_x;
3517 #ifdef USE_CAIRO
3518 x_draw_horizontal_wave (s->f, s->gc, s->x, s->ybase - wave_height + 3,
3519 s->width, wave_height, wave_length);
3520 #else /* not USE_CAIRO */
3521 int dx, dy, x0, y0, width, x1, y1, x2, y2, xmax, thickness = scale_y;;
3522 bool odd;
3523 XRectangle wave_clip, string_clip, final_clip;
3525 dx = wave_length;
3526 dy = wave_height - 1;
3527 x0 = s->x;
3528 y0 = s->ybase + wave_height / 2 - scale_y;
3529 width = s->width;
3530 xmax = x0 + width;
3532 /* Find and set clipping rectangle */
3534 wave_clip.x = x0;
3535 wave_clip.y = y0;
3536 wave_clip.width = width;
3537 wave_clip.height = wave_height;
3538 get_glyph_string_clip_rect (s, &string_clip);
3540 if (!x_intersect_rectangles (&wave_clip, &string_clip, &final_clip))
3541 return;
3543 XSetClipRectangles (s->display, s->gc, 0, 0, &final_clip, 1, Unsorted);
3545 /* Draw the waves */
3547 x1 = x0 - (x0 % dx);
3548 x2 = x1 + dx;
3549 odd = (x1 / dx) & 1;
3550 y1 = y2 = y0;
3552 if (odd)
3553 y1 += dy;
3554 else
3555 y2 += dy;
3557 if (INT_MAX - dx < xmax)
3558 emacs_abort ();
3560 while (x1 <= xmax)
3562 XSetLineAttributes (s->display, s->gc, thickness, LineSolid, CapButt,
3563 JoinRound);
3564 XDrawLine (s->display, FRAME_X_DRAWABLE (s->f), s->gc, x1, y1, x2, y2);
3565 x1 = x2, y1 = y2;
3566 x2 += dx, y2 = y0 + odd*dy;
3567 odd = !odd;
3570 /* Restore previous clipping rectangle(s) */
3571 XSetClipRectangles (s->display, s->gc, 0, 0, s->clip, s->num_clips, Unsorted);
3572 #endif /* not USE_CAIRO */
3576 /* Draw glyph string S. */
3578 static void
3579 x_draw_glyph_string (struct glyph_string *s)
3581 bool relief_drawn_p = false;
3583 /* If S draws into the background of its successors, draw the
3584 background of the successors first so that S can draw into it.
3585 This makes S->next use XDrawString instead of XDrawImageString. */
3586 if (s->next && s->right_overhang && !s->for_overlaps)
3588 int width;
3589 struct glyph_string *next;
3591 for (width = 0, next = s->next;
3592 next && width < s->right_overhang;
3593 width += next->width, next = next->next)
3594 if (next->first_glyph->type != IMAGE_GLYPH)
3596 x_set_glyph_string_gc (next);
3597 x_set_glyph_string_clipping (next);
3598 if (next->first_glyph->type == STRETCH_GLYPH)
3599 x_draw_stretch_glyph_string (next);
3600 else
3601 x_draw_glyph_string_background (next, true);
3602 next->num_clips = 0;
3606 /* Set up S->gc, set clipping and draw S. */
3607 x_set_glyph_string_gc (s);
3609 /* Draw relief (if any) in advance for char/composition so that the
3610 glyph string can be drawn over it. */
3611 if (!s->for_overlaps
3612 && s->face->box != FACE_NO_BOX
3613 && (s->first_glyph->type == CHAR_GLYPH
3614 || s->first_glyph->type == COMPOSITE_GLYPH))
3617 x_set_glyph_string_clipping (s);
3618 x_draw_glyph_string_background (s, true);
3619 x_draw_glyph_string_box (s);
3620 x_set_glyph_string_clipping (s);
3621 relief_drawn_p = true;
3623 else if (!s->clip_head /* draw_glyphs didn't specify a clip mask. */
3624 && !s->clip_tail
3625 && ((s->prev && s->prev->hl != s->hl && s->left_overhang)
3626 || (s->next && s->next->hl != s->hl && s->right_overhang)))
3627 /* We must clip just this glyph. left_overhang part has already
3628 drawn when s->prev was drawn, and right_overhang part will be
3629 drawn later when s->next is drawn. */
3630 x_set_glyph_string_clipping_exactly (s, s);
3631 else
3632 x_set_glyph_string_clipping (s);
3634 switch (s->first_glyph->type)
3636 case IMAGE_GLYPH:
3637 x_draw_image_glyph_string (s);
3638 break;
3640 case XWIDGET_GLYPH:
3641 x_draw_xwidget_glyph_string (s);
3642 break;
3644 case STRETCH_GLYPH:
3645 x_draw_stretch_glyph_string (s);
3646 break;
3648 case CHAR_GLYPH:
3649 if (s->for_overlaps)
3650 s->background_filled_p = true;
3651 else
3652 x_draw_glyph_string_background (s, false);
3653 x_draw_glyph_string_foreground (s);
3654 break;
3656 case COMPOSITE_GLYPH:
3657 if (s->for_overlaps || (s->cmp_from > 0
3658 && ! s->first_glyph->u.cmp.automatic))
3659 s->background_filled_p = true;
3660 else
3661 x_draw_glyph_string_background (s, true);
3662 x_draw_composite_glyph_string_foreground (s);
3663 break;
3665 case GLYPHLESS_GLYPH:
3666 if (s->for_overlaps)
3667 s->background_filled_p = true;
3668 else
3669 x_draw_glyph_string_background (s, true);
3670 x_draw_glyphless_glyph_string_foreground (s);
3671 break;
3673 default:
3674 emacs_abort ();
3677 if (!s->for_overlaps)
3679 /* Draw underline. */
3680 if (s->face->underline_p)
3682 if (s->face->underline_type == FACE_UNDER_WAVE)
3684 if (s->face->underline_defaulted_p)
3685 x_draw_underwave (s);
3686 else
3688 XGCValues xgcv;
3689 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3690 XSetForeground (s->display, s->gc, s->face->underline_color);
3691 x_draw_underwave (s);
3692 XSetForeground (s->display, s->gc, xgcv.foreground);
3695 else if (s->face->underline_type == FACE_UNDER_LINE)
3697 unsigned long thickness, position;
3698 int y;
3700 if (s->prev && s->prev->face->underline_p
3701 && s->prev->face->underline_type == FACE_UNDER_LINE)
3703 /* We use the same underline style as the previous one. */
3704 thickness = s->prev->underline_thickness;
3705 position = s->prev->underline_position;
3707 else
3709 struct font *font = font_for_underline_metrics (s);
3711 /* Get the underline thickness. Default is 1 pixel. */
3712 if (font && font->underline_thickness > 0)
3713 thickness = font->underline_thickness;
3714 else
3715 thickness = 1;
3716 if (x_underline_at_descent_line)
3717 position = (s->height - thickness) - (s->ybase - s->y);
3718 else
3720 /* Get the underline position. This is the recommended
3721 vertical offset in pixels from the baseline to the top of
3722 the underline. This is a signed value according to the
3723 specs, and its default is
3725 ROUND ((maximum descent) / 2), with
3726 ROUND(x) = floor (x + 0.5) */
3728 if (x_use_underline_position_properties
3729 && font && font->underline_position >= 0)
3730 position = font->underline_position;
3731 else if (font)
3732 position = (font->descent + 1) / 2;
3733 else
3734 position = underline_minimum_offset;
3736 position = max (position, underline_minimum_offset);
3738 /* Check the sanity of thickness and position. We should
3739 avoid drawing underline out of the current line area. */
3740 if (s->y + s->height <= s->ybase + position)
3741 position = (s->height - 1) - (s->ybase - s->y);
3742 if (s->y + s->height < s->ybase + position + thickness)
3743 thickness = (s->y + s->height) - (s->ybase + position);
3744 s->underline_thickness = thickness;
3745 s->underline_position = position;
3746 y = s->ybase + position;
3747 if (s->face->underline_defaulted_p)
3748 x_fill_rectangle (s->f, s->gc,
3749 s->x, y, s->width, thickness);
3750 else
3752 XGCValues xgcv;
3753 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3754 XSetForeground (s->display, s->gc, s->face->underline_color);
3755 x_fill_rectangle (s->f, s->gc,
3756 s->x, y, s->width, thickness);
3757 XSetForeground (s->display, s->gc, xgcv.foreground);
3761 /* Draw overline. */
3762 if (s->face->overline_p)
3764 unsigned long dy = 0, h = 1;
3766 if (s->face->overline_color_defaulted_p)
3767 x_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3768 s->width, h);
3769 else
3771 XGCValues xgcv;
3772 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3773 XSetForeground (s->display, s->gc, s->face->overline_color);
3774 x_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3775 s->width, h);
3776 XSetForeground (s->display, s->gc, xgcv.foreground);
3780 /* Draw strike-through. */
3781 if (s->face->strike_through_p)
3783 /* Y-coordinate and height of the glyph string's first
3784 glyph. We cannot use s->y and s->height because those
3785 could be larger if there are taller display elements
3786 (e.g., characters displayed with a larger font) in the
3787 same glyph row. */
3788 int glyph_y = s->ybase - s->first_glyph->ascent;
3789 int glyph_height = s->first_glyph->ascent + s->first_glyph->descent;
3790 /* Strike-through width and offset from the glyph string's
3791 top edge. */
3792 unsigned long h = 1;
3793 unsigned long dy = (glyph_height - h) / 2;
3795 if (s->face->strike_through_color_defaulted_p)
3796 x_fill_rectangle (s->f, s->gc, s->x, glyph_y + dy,
3797 s->width, h);
3798 else
3800 XGCValues xgcv;
3801 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3802 XSetForeground (s->display, s->gc, s->face->strike_through_color);
3803 x_fill_rectangle (s->f, s->gc, s->x, glyph_y + dy,
3804 s->width, h);
3805 XSetForeground (s->display, s->gc, xgcv.foreground);
3809 /* Draw relief if not yet drawn. */
3810 if (!relief_drawn_p && s->face->box != FACE_NO_BOX)
3811 x_draw_glyph_string_box (s);
3813 if (s->prev)
3815 struct glyph_string *prev;
3817 for (prev = s->prev; prev; prev = prev->prev)
3818 if (prev->hl != s->hl
3819 && prev->x + prev->width + prev->right_overhang > s->x)
3821 /* As prev was drawn while clipped to its own area, we
3822 must draw the right_overhang part using s->hl now. */
3823 enum draw_glyphs_face save = prev->hl;
3825 prev->hl = s->hl;
3826 x_set_glyph_string_gc (prev);
3827 x_set_glyph_string_clipping_exactly (s, prev);
3828 if (prev->first_glyph->type == CHAR_GLYPH)
3829 x_draw_glyph_string_foreground (prev);
3830 else
3831 x_draw_composite_glyph_string_foreground (prev);
3832 x_reset_clip_rectangles (prev->f, prev->gc);
3833 prev->hl = save;
3834 prev->num_clips = 0;
3838 if (s->next)
3840 struct glyph_string *next;
3842 for (next = s->next; next; next = next->next)
3843 if (next->hl != s->hl
3844 && next->x - next->left_overhang < s->x + s->width)
3846 /* As next will be drawn while clipped to its own area,
3847 we must draw the left_overhang part using s->hl now. */
3848 enum draw_glyphs_face save = next->hl;
3850 next->hl = s->hl;
3851 x_set_glyph_string_gc (next);
3852 x_set_glyph_string_clipping_exactly (s, next);
3853 if (next->first_glyph->type == CHAR_GLYPH)
3854 x_draw_glyph_string_foreground (next);
3855 else
3856 x_draw_composite_glyph_string_foreground (next);
3857 x_reset_clip_rectangles (next->f, next->gc);
3858 next->hl = save;
3859 next->num_clips = 0;
3860 next->clip_head = s->next;
3865 /* Reset clipping. */
3866 x_reset_clip_rectangles (s->f, s->gc);
3867 s->num_clips = 0;
3870 /* Shift display to make room for inserted glyphs. */
3872 static void
3873 x_shift_glyphs_for_insert (struct frame *f, int x, int y, int width, int height, int shift_by)
3875 /* Never called on a GUI frame, see
3876 https://lists.gnu.org/r/emacs-devel/2015-05/msg00456.html
3878 XCopyArea (FRAME_X_DISPLAY (f), FRAME_X_DRAWABLE (f), FRAME_X_DRAWABLE (f),
3879 f->output_data.x->normal_gc,
3880 x, y, width, height,
3881 x + shift_by, y);
3884 /* Delete N glyphs at the nominal cursor position. Not implemented
3885 for X frames. */
3887 static void
3888 x_delete_glyphs (struct frame *f, register int n)
3890 emacs_abort ();
3894 /* Like XClearArea, but check that WIDTH and HEIGHT are reasonable.
3895 If they are <= 0, this is probably an error. */
3897 static ATTRIBUTE_UNUSED void
3898 x_clear_area1 (Display *dpy, Window window,
3899 int x, int y, int width, int height, int exposures)
3901 eassert (width > 0 && height > 0);
3902 XClearArea (dpy, window, x, y, width, height, exposures);
3905 void
3906 x_clear_area (struct frame *f, int x, int y, int width, int height)
3908 #ifdef USE_CAIRO
3909 cairo_t *cr;
3911 eassert (width > 0 && height > 0);
3913 cr = x_begin_cr_clip (f, NULL);
3914 x_set_cr_source_with_gc_background (f, f->output_data.x->normal_gc);
3915 cairo_rectangle (cr, x, y, width, height);
3916 cairo_fill (cr);
3917 x_end_cr_clip (f);
3918 #else
3919 if (FRAME_X_DOUBLE_BUFFERED_P (f))
3920 XFillRectangle (FRAME_X_DISPLAY (f),
3921 FRAME_X_DRAWABLE (f),
3922 f->output_data.x->reverse_gc,
3923 x, y, width, height);
3924 else
3925 x_clear_area1 (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3926 x, y, width, height, False);
3927 #endif
3931 /* Clear an entire frame. */
3933 static void
3934 x_clear_frame (struct frame *f)
3936 /* Clearing the frame will erase any cursor, so mark them all as no
3937 longer visible. */
3938 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
3940 block_input ();
3942 font_drop_xrender_surfaces (f);
3943 x_clear_window (f);
3945 /* We have to clear the scroll bars. If we have changed colors or
3946 something like that, then they should be notified. */
3947 x_scroll_bar_clear (f);
3949 XFlush (FRAME_X_DISPLAY (f));
3951 unblock_input ();
3954 /* RIF: Show hourglass cursor on frame F. */
3956 static void
3957 x_show_hourglass (struct frame *f)
3959 Display *dpy = FRAME_X_DISPLAY (f);
3961 if (dpy)
3963 struct x_output *x = FRAME_X_OUTPUT (f);
3964 #ifdef USE_X_TOOLKIT
3965 if (x->widget)
3966 #else
3967 if (FRAME_OUTER_WINDOW (f))
3968 #endif
3970 x->hourglass_p = true;
3972 if (!x->hourglass_window)
3974 unsigned long mask = CWCursor;
3975 XSetWindowAttributes attrs;
3976 #ifdef USE_GTK
3977 Window parent = FRAME_X_WINDOW (f);
3978 #else
3979 Window parent = FRAME_OUTER_WINDOW (f);
3980 #endif
3981 attrs.cursor = x->hourglass_cursor;
3983 x->hourglass_window = XCreateWindow
3984 (dpy, parent, 0, 0, 32000, 32000, 0, 0,
3985 InputOnly, CopyFromParent, mask, &attrs);
3988 XMapRaised (dpy, x->hourglass_window);
3989 XFlush (dpy);
3994 /* RIF: Cancel hourglass cursor on frame F. */
3996 static void
3997 x_hide_hourglass (struct frame *f)
3999 struct x_output *x = FRAME_X_OUTPUT (f);
4001 /* Watch out for newly created frames. */
4002 if (x->hourglass_window)
4004 XUnmapWindow (FRAME_X_DISPLAY (f), x->hourglass_window);
4005 /* Sync here because XTread_socket looks at the
4006 hourglass_p flag that is reset to zero below. */
4007 XSync (FRAME_X_DISPLAY (f), False);
4008 x->hourglass_p = false;
4012 /* Invert the middle quarter of the frame for .15 sec. */
4014 static void
4015 XTflash (struct frame *f)
4017 block_input ();
4020 #ifdef USE_GTK
4021 /* Use Gdk routines to draw. This way, we won't draw over scroll bars
4022 when the scroll bars and the edit widget share the same X window. */
4023 GdkWindow *window = gtk_widget_get_window (FRAME_GTK_WIDGET (f));
4024 #ifdef HAVE_GTK3
4025 #if GTK_CHECK_VERSION (3, 22, 0)
4026 cairo_region_t *region = gdk_window_get_visible_region (window);
4027 GdkDrawingContext *context = gdk_window_begin_draw_frame (window, region);
4028 cairo_t *cr = gdk_drawing_context_get_cairo_context (context);
4029 #else
4030 cairo_t *cr = gdk_cairo_create (window);
4031 #endif
4032 cairo_set_source_rgb (cr, 1, 1, 1);
4033 cairo_set_operator (cr, CAIRO_OPERATOR_DIFFERENCE);
4034 #define XFillRectangle(d, win, gc, x, y, w, h) \
4035 do { \
4036 cairo_rectangle (cr, x, y, w, h); \
4037 cairo_fill (cr); \
4039 while (false)
4040 #else /* ! HAVE_GTK3 */
4041 GdkGCValues vals;
4042 GdkGC *gc;
4043 vals.foreground.pixel = (FRAME_FOREGROUND_PIXEL (f)
4044 ^ FRAME_BACKGROUND_PIXEL (f));
4045 vals.function = GDK_XOR;
4046 gc = gdk_gc_new_with_values (window,
4047 &vals, GDK_GC_FUNCTION | GDK_GC_FOREGROUND);
4048 #define XFillRectangle(d, win, gc, x, y, w, h) \
4049 gdk_draw_rectangle (window, gc, true, x, y, w, h)
4050 #endif /* ! HAVE_GTK3 */
4051 #else /* ! USE_GTK */
4052 GC gc;
4054 /* Create a GC that will use the GXxor function to flip foreground
4055 pixels into background pixels. */
4057 XGCValues values;
4059 values.function = GXxor;
4060 values.foreground = (FRAME_FOREGROUND_PIXEL (f)
4061 ^ FRAME_BACKGROUND_PIXEL (f));
4063 gc = XCreateGC (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4064 GCFunction | GCForeground, &values);
4066 #endif
4068 /* Get the height not including a menu bar widget. */
4069 int height = FRAME_PIXEL_HEIGHT (f);
4070 /* Height of each line to flash. */
4071 int flash_height = FRAME_LINE_HEIGHT (f);
4072 /* These will be the left and right margins of the rectangles. */
4073 int flash_left = FRAME_INTERNAL_BORDER_WIDTH (f);
4074 int flash_right = FRAME_PIXEL_WIDTH (f) - FRAME_INTERNAL_BORDER_WIDTH (f);
4075 int width = flash_right - flash_left;
4077 /* If window is tall, flash top and bottom line. */
4078 if (height > 3 * FRAME_LINE_HEIGHT (f))
4080 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4081 flash_left,
4082 (FRAME_INTERNAL_BORDER_WIDTH (f)
4083 + FRAME_TOP_MARGIN_HEIGHT (f)),
4084 width, flash_height);
4085 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4086 flash_left,
4087 (height - flash_height
4088 - FRAME_INTERNAL_BORDER_WIDTH (f)),
4089 width, flash_height);
4092 else
4093 /* If it is short, flash it all. */
4094 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4095 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
4096 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
4098 x_flush (f);
4101 struct timespec delay = make_timespec (0, 150 * 1000 * 1000);
4102 struct timespec wakeup = timespec_add (current_timespec (), delay);
4104 /* Keep waiting until past the time wakeup or any input gets
4105 available. */
4106 while (! detect_input_pending ())
4108 struct timespec current = current_timespec ();
4109 struct timespec timeout;
4111 /* Break if result would not be positive. */
4112 if (timespec_cmp (wakeup, current) <= 0)
4113 break;
4115 /* How long `select' should wait. */
4116 timeout = make_timespec (0, 10 * 1000 * 1000);
4118 /* Try to wait that long--but we might wake up sooner. */
4119 pselect (0, NULL, NULL, NULL, &timeout, NULL);
4123 /* If window is tall, flash top and bottom line. */
4124 if (height > 3 * FRAME_LINE_HEIGHT (f))
4126 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4127 flash_left,
4128 (FRAME_INTERNAL_BORDER_WIDTH (f)
4129 + FRAME_TOP_MARGIN_HEIGHT (f)),
4130 width, flash_height);
4131 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4132 flash_left,
4133 (height - flash_height
4134 - FRAME_INTERNAL_BORDER_WIDTH (f)),
4135 width, flash_height);
4137 else
4138 /* If it is short, flash it all. */
4139 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4140 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
4141 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
4143 #ifdef USE_GTK
4144 #ifdef HAVE_GTK3
4145 #if GTK_CHECK_VERSION (3, 22, 0)
4146 gdk_window_end_draw_frame (window, context);
4147 cairo_region_destroy (region);
4148 #else
4149 cairo_destroy (cr);
4150 #endif
4151 #else
4152 g_object_unref (G_OBJECT (gc));
4153 #endif
4154 #undef XFillRectangle
4155 #else
4156 XFreeGC (FRAME_X_DISPLAY (f), gc);
4157 #endif
4158 x_flush (f);
4162 unblock_input ();
4166 static void
4167 XTtoggle_invisible_pointer (struct frame *f, bool invisible)
4169 block_input ();
4170 FRAME_DISPLAY_INFO (f)->toggle_visible_pointer (f, invisible);
4171 unblock_input ();
4175 /* Make audible bell. */
4177 static void
4178 XTring_bell (struct frame *f)
4180 if (FRAME_X_DISPLAY (f))
4182 if (visible_bell)
4183 XTflash (f);
4184 else
4186 block_input ();
4187 #ifdef HAVE_XKB
4188 XkbBell (FRAME_X_DISPLAY (f), None, 0, None);
4189 #else
4190 XBell (FRAME_X_DISPLAY (f), 0);
4191 #endif
4192 XFlush (FRAME_X_DISPLAY (f));
4193 unblock_input ();
4198 /***********************************************************************
4199 Line Dance
4200 ***********************************************************************/
4202 /* Perform an insert-lines or delete-lines operation, inserting N
4203 lines or deleting -N lines at vertical position VPOS. */
4205 static void
4206 x_ins_del_lines (struct frame *f, int vpos, int n)
4208 emacs_abort ();
4212 /* Scroll part of the display as described by RUN. */
4214 static void
4215 x_scroll_run (struct window *w, struct run *run)
4217 struct frame *f = XFRAME (w->frame);
4218 int x, y, width, height, from_y, to_y, bottom_y;
4220 /* Get frame-relative bounding box of the text display area of W,
4221 without mode lines. Include in this box the left and right
4222 fringe of W. */
4223 window_box (w, ANY_AREA, &x, &y, &width, &height);
4225 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
4226 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
4227 bottom_y = y + height;
4229 if (to_y < from_y)
4231 /* Scrolling up. Make sure we don't copy part of the mode
4232 line at the bottom. */
4233 if (from_y + run->height > bottom_y)
4234 height = bottom_y - from_y;
4235 else
4236 height = run->height;
4238 else
4240 /* Scrolling down. Make sure we don't copy over the mode line.
4241 at the bottom. */
4242 if (to_y + run->height > bottom_y)
4243 height = bottom_y - to_y;
4244 else
4245 height = run->height;
4248 block_input ();
4250 /* Cursor off. Will be switched on again in x_update_window_end. */
4251 x_clear_cursor (w);
4253 #ifdef USE_CAIRO
4254 SET_FRAME_GARBAGED (f);
4255 #else
4256 XCopyArea (FRAME_X_DISPLAY (f),
4257 FRAME_X_DRAWABLE (f), FRAME_X_DRAWABLE (f),
4258 f->output_data.x->normal_gc,
4259 x, from_y,
4260 width, height,
4261 x, to_y);
4262 #endif
4264 unblock_input ();
4269 /***********************************************************************
4270 Exposure Events
4271 ***********************************************************************/
4274 static void
4275 frame_highlight (struct frame *f)
4277 /* We used to only do this if Vx_no_window_manager was non-nil, but
4278 the ICCCM (section 4.1.6) says that the window's border pixmap
4279 and border pixel are window attributes which are "private to the
4280 client", so we can always change it to whatever we want. */
4281 block_input ();
4282 /* I recently started to get errors in this XSetWindowBorder, depending on
4283 the window-manager in use, tho something more is at play since I've been
4284 using that same window-manager binary for ever. Let's not crash just
4285 because of this (bug#9310). */
4286 x_catch_errors (FRAME_X_DISPLAY (f));
4287 XSetWindowBorder (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4288 f->output_data.x->border_pixel);
4289 x_uncatch_errors ();
4290 unblock_input ();
4291 x_update_cursor (f, true);
4292 x_set_frame_alpha (f);
4295 static void
4296 frame_unhighlight (struct frame *f)
4298 /* We used to only do this if Vx_no_window_manager was non-nil, but
4299 the ICCCM (section 4.1.6) says that the window's border pixmap
4300 and border pixel are window attributes which are "private to the
4301 client", so we can always change it to whatever we want. */
4302 block_input ();
4303 /* Same as above for XSetWindowBorder (bug#9310). */
4304 x_catch_errors (FRAME_X_DISPLAY (f));
4305 XSetWindowBorderPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4306 f->output_data.x->border_tile);
4307 x_uncatch_errors ();
4308 unblock_input ();
4309 x_update_cursor (f, true);
4310 x_set_frame_alpha (f);
4313 /* The focus has changed. Update the frames as necessary to reflect
4314 the new situation. Note that we can't change the selected frame
4315 here, because the Lisp code we are interrupting might become confused.
4316 Each event gets marked with the frame in which it occurred, so the
4317 Lisp code can tell when the switch took place by examining the events. */
4319 static void
4320 x_new_focus_frame (struct x_display_info *dpyinfo, struct frame *frame)
4322 struct frame *old_focus = dpyinfo->x_focus_frame;
4324 if (frame != dpyinfo->x_focus_frame)
4326 /* Set this before calling other routines, so that they see
4327 the correct value of x_focus_frame. */
4328 dpyinfo->x_focus_frame = frame;
4330 if (old_focus && old_focus->auto_lower)
4331 x_lower_frame (old_focus);
4333 if (dpyinfo->x_focus_frame && dpyinfo->x_focus_frame->auto_raise)
4334 dpyinfo->x_pending_autoraise_frame = dpyinfo->x_focus_frame;
4335 else
4336 dpyinfo->x_pending_autoraise_frame = NULL;
4339 x_frame_rehighlight (dpyinfo);
4342 /* Handle FocusIn and FocusOut state changes for FRAME.
4343 If FRAME has focus and there exists more than one frame, puts
4344 a FOCUS_IN_EVENT into *BUFP. */
4346 static void
4347 x_focus_changed (int type, int state, struct x_display_info *dpyinfo, struct frame *frame, struct input_event *bufp)
4349 if (type == FocusIn)
4351 if (dpyinfo->x_focus_event_frame != frame)
4353 x_new_focus_frame (dpyinfo, frame);
4354 dpyinfo->x_focus_event_frame = frame;
4356 /* Don't stop displaying the initial startup message
4357 for a switch-frame event we don't need. */
4358 /* When run as a daemon, Vterminal_frame is always NIL. */
4359 bufp->arg = (((NILP (Vterminal_frame)
4360 || ! FRAME_X_P (XFRAME (Vterminal_frame))
4361 || EQ (Fdaemonp (), Qt))
4362 && CONSP (Vframe_list)
4363 && !NILP (XCDR (Vframe_list)))
4364 ? Qt : Qnil);
4365 bufp->kind = FOCUS_IN_EVENT;
4366 XSETFRAME (bufp->frame_or_window, frame);
4369 frame->output_data.x->focus_state |= state;
4371 #ifdef HAVE_X_I18N
4372 if (FRAME_XIC (frame))
4373 XSetICFocus (FRAME_XIC (frame));
4374 #endif
4376 else if (type == FocusOut)
4378 frame->output_data.x->focus_state &= ~state;
4380 if (dpyinfo->x_focus_event_frame == frame)
4382 dpyinfo->x_focus_event_frame = 0;
4383 x_new_focus_frame (dpyinfo, 0);
4385 bufp->kind = FOCUS_OUT_EVENT;
4386 XSETFRAME (bufp->frame_or_window, frame);
4389 #ifdef HAVE_X_I18N
4390 if (FRAME_XIC (frame))
4391 XUnsetICFocus (FRAME_XIC (frame));
4392 #endif
4393 if (frame->pointer_invisible)
4394 XTtoggle_invisible_pointer (frame, false);
4398 /* Return the Emacs frame-object corresponding to an X window.
4399 It could be the frame's main window or an icon window. */
4401 static struct frame *
4402 x_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
4404 Lisp_Object tail, frame;
4405 struct frame *f;
4407 if (wdesc == None)
4408 return NULL;
4410 FOR_EACH_FRAME (tail, frame)
4412 f = XFRAME (frame);
4413 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
4414 continue;
4415 if (f->output_data.x->hourglass_window == wdesc)
4416 return f;
4417 #ifdef USE_X_TOOLKIT
4418 if ((f->output_data.x->edit_widget
4419 && XtWindow (f->output_data.x->edit_widget) == wdesc)
4420 /* A tooltip frame? */
4421 || (!f->output_data.x->edit_widget
4422 && FRAME_X_WINDOW (f) == wdesc)
4423 || f->output_data.x->icon_desc == wdesc)
4424 return f;
4425 #else /* not USE_X_TOOLKIT */
4426 #ifdef USE_GTK
4427 if (f->output_data.x->edit_widget)
4429 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
4430 struct x_output *x = f->output_data.x;
4431 if (gwdesc != 0 && gwdesc == x->edit_widget)
4432 return f;
4434 #endif /* USE_GTK */
4435 if (FRAME_X_WINDOW (f) == wdesc
4436 || f->output_data.x->icon_desc == wdesc)
4437 return f;
4438 #endif /* not USE_X_TOOLKIT */
4440 return 0;
4443 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
4445 /* Like x_window_to_frame but also compares the window with the widget's
4446 windows. */
4448 static struct frame *
4449 x_any_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
4451 Lisp_Object tail, frame;
4452 struct frame *f, *found = NULL;
4453 struct x_output *x;
4455 if (wdesc == None)
4456 return NULL;
4458 FOR_EACH_FRAME (tail, frame)
4460 if (found)
4461 break;
4462 f = XFRAME (frame);
4463 if (FRAME_X_P (f) && FRAME_DISPLAY_INFO (f) == dpyinfo)
4465 /* This frame matches if the window is any of its widgets. */
4466 x = f->output_data.x;
4467 if (x->hourglass_window == wdesc)
4468 found = f;
4469 else if (x->widget)
4471 #ifdef USE_GTK
4472 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
4473 if (gwdesc != 0
4474 && gtk_widget_get_toplevel (gwdesc) == x->widget)
4475 found = f;
4476 #else
4477 if (wdesc == XtWindow (x->widget)
4478 || wdesc == XtWindow (x->column_widget)
4479 || wdesc == XtWindow (x->edit_widget))
4480 found = f;
4481 /* Match if the window is this frame's menubar. */
4482 else if (lw_window_is_in_menubar (wdesc, x->menubar_widget))
4483 found = f;
4484 #endif
4486 else if (FRAME_X_WINDOW (f) == wdesc)
4487 /* A tooltip frame. */
4488 found = f;
4492 return found;
4495 /* Likewise, but consider only the menu bar widget. */
4497 static struct frame *
4498 x_menubar_window_to_frame (struct x_display_info *dpyinfo,
4499 const XEvent *event)
4501 Window wdesc = event->xany.window;
4502 Lisp_Object tail, frame;
4503 struct frame *f;
4504 struct x_output *x;
4506 if (wdesc == None)
4507 return NULL;
4509 FOR_EACH_FRAME (tail, frame)
4511 f = XFRAME (frame);
4512 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
4513 continue;
4514 x = f->output_data.x;
4515 #ifdef USE_GTK
4516 if (x->menubar_widget && xg_event_is_for_menubar (f, event))
4517 return f;
4518 #else
4519 /* Match if the window is this frame's menubar. */
4520 if (x->menubar_widget
4521 && lw_window_is_in_menubar (wdesc, x->menubar_widget))
4522 return f;
4523 #endif
4525 return 0;
4528 /* Return the frame whose principal (outermost) window is WDESC.
4529 If WDESC is some other (smaller) window, we return 0. */
4531 struct frame *
4532 x_top_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
4534 Lisp_Object tail, frame;
4535 struct frame *f;
4536 struct x_output *x;
4538 if (wdesc == None)
4539 return NULL;
4541 FOR_EACH_FRAME (tail, frame)
4543 f = XFRAME (frame);
4544 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
4545 continue;
4546 x = f->output_data.x;
4548 if (x->widget)
4550 /* This frame matches if the window is its topmost widget. */
4551 #ifdef USE_GTK
4552 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
4553 if (gwdesc == x->widget)
4554 return f;
4555 #else
4556 if (wdesc == XtWindow (x->widget))
4557 return f;
4558 #endif
4560 else if (FRAME_X_WINDOW (f) == wdesc)
4561 /* Tooltip frame. */
4562 return f;
4564 return 0;
4567 #else /* !USE_X_TOOLKIT && !USE_GTK */
4569 #define x_any_window_to_frame(d, i) x_window_to_frame (d, i)
4570 #define x_top_window_to_frame(d, i) x_window_to_frame (d, i)
4572 #endif /* USE_X_TOOLKIT || USE_GTK */
4574 /* The focus may have changed. Figure out if it is a real focus change,
4575 by checking both FocusIn/Out and Enter/LeaveNotify events.
4577 Returns FOCUS_IN_EVENT event in *BUFP. */
4579 static void
4580 x_detect_focus_change (struct x_display_info *dpyinfo, struct frame *frame,
4581 const XEvent *event, struct input_event *bufp)
4583 if (!frame)
4584 return;
4586 switch (event->type)
4588 case EnterNotify:
4589 case LeaveNotify:
4591 struct frame *focus_frame = dpyinfo->x_focus_event_frame;
4592 int focus_state
4593 = focus_frame ? focus_frame->output_data.x->focus_state : 0;
4595 if (event->xcrossing.detail != NotifyInferior
4596 && event->xcrossing.focus
4597 && ! (focus_state & FOCUS_EXPLICIT))
4598 x_focus_changed ((event->type == EnterNotify ? FocusIn : FocusOut),
4599 FOCUS_IMPLICIT,
4600 dpyinfo, frame, bufp);
4602 break;
4604 case FocusIn:
4605 case FocusOut:
4606 x_focus_changed (event->type,
4607 (event->xfocus.detail == NotifyPointer ?
4608 FOCUS_IMPLICIT : FOCUS_EXPLICIT),
4609 dpyinfo, frame, bufp);
4610 break;
4612 case ClientMessage:
4613 if (event->xclient.message_type == dpyinfo->Xatom_XEMBED)
4615 enum xembed_message msg = event->xclient.data.l[1];
4616 x_focus_changed ((msg == XEMBED_FOCUS_IN ? FocusIn : FocusOut),
4617 FOCUS_EXPLICIT, dpyinfo, frame, bufp);
4619 break;
4624 #if !defined USE_X_TOOLKIT && !defined USE_GTK
4625 /* Handle an event saying the mouse has moved out of an Emacs frame. */
4627 void
4628 x_mouse_leave (struct x_display_info *dpyinfo)
4630 x_new_focus_frame (dpyinfo, dpyinfo->x_focus_event_frame);
4632 #endif
4634 /* The focus has changed, or we have redirected a frame's focus to
4635 another frame (this happens when a frame uses a surrogate
4636 mini-buffer frame). Shift the highlight as appropriate.
4638 The FRAME argument doesn't necessarily have anything to do with which
4639 frame is being highlighted or un-highlighted; we only use it to find
4640 the appropriate X display info. */
4642 static void
4643 XTframe_rehighlight (struct frame *frame)
4645 x_frame_rehighlight (FRAME_DISPLAY_INFO (frame));
4648 static void
4649 x_frame_rehighlight (struct x_display_info *dpyinfo)
4651 struct frame *old_highlight = dpyinfo->x_highlight_frame;
4653 if (dpyinfo->x_focus_frame)
4655 dpyinfo->x_highlight_frame
4656 = ((FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame)))
4657 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
4658 : dpyinfo->x_focus_frame);
4659 if (! FRAME_LIVE_P (dpyinfo->x_highlight_frame))
4661 fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
4662 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
4665 else
4666 dpyinfo->x_highlight_frame = 0;
4668 if (dpyinfo->x_highlight_frame != old_highlight)
4670 if (old_highlight)
4671 frame_unhighlight (old_highlight);
4672 if (dpyinfo->x_highlight_frame)
4673 frame_highlight (dpyinfo->x_highlight_frame);
4679 /* Keyboard processing - modifier keys, vendor-specific keysyms, etc. */
4681 /* Initialize mode_switch_bit and modifier_meaning. */
4682 static void
4683 x_find_modifier_meanings (struct x_display_info *dpyinfo)
4685 int min_code, max_code;
4686 KeySym *syms;
4687 int syms_per_code;
4688 XModifierKeymap *mods;
4690 dpyinfo->meta_mod_mask = 0;
4691 dpyinfo->shift_lock_mask = 0;
4692 dpyinfo->alt_mod_mask = 0;
4693 dpyinfo->super_mod_mask = 0;
4694 dpyinfo->hyper_mod_mask = 0;
4696 XDisplayKeycodes (dpyinfo->display, &min_code, &max_code);
4698 syms = XGetKeyboardMapping (dpyinfo->display,
4699 min_code, max_code - min_code + 1,
4700 &syms_per_code);
4701 mods = XGetModifierMapping (dpyinfo->display);
4703 /* Scan the modifier table to see which modifier bits the Meta and
4704 Alt keysyms are on. */
4706 int row, col; /* The row and column in the modifier table. */
4707 bool found_alt_or_meta;
4709 for (row = 3; row < 8; row++)
4711 found_alt_or_meta = false;
4712 for (col = 0; col < mods->max_keypermod; col++)
4714 KeyCode code = mods->modifiermap[(row * mods->max_keypermod) + col];
4716 /* Zeroes are used for filler. Skip them. */
4717 if (code == 0)
4718 continue;
4720 /* Are any of this keycode's keysyms a meta key? */
4722 int code_col;
4724 for (code_col = 0; code_col < syms_per_code; code_col++)
4726 int sym = syms[((code - min_code) * syms_per_code) + code_col];
4728 switch (sym)
4730 case XK_Meta_L:
4731 case XK_Meta_R:
4732 found_alt_or_meta = true;
4733 dpyinfo->meta_mod_mask |= (1 << row);
4734 break;
4736 case XK_Alt_L:
4737 case XK_Alt_R:
4738 found_alt_or_meta = true;
4739 dpyinfo->alt_mod_mask |= (1 << row);
4740 break;
4742 case XK_Hyper_L:
4743 case XK_Hyper_R:
4744 if (!found_alt_or_meta)
4745 dpyinfo->hyper_mod_mask |= (1 << row);
4746 code_col = syms_per_code;
4747 col = mods->max_keypermod;
4748 break;
4750 case XK_Super_L:
4751 case XK_Super_R:
4752 if (!found_alt_or_meta)
4753 dpyinfo->super_mod_mask |= (1 << row);
4754 code_col = syms_per_code;
4755 col = mods->max_keypermod;
4756 break;
4758 case XK_Shift_Lock:
4759 /* Ignore this if it's not on the lock modifier. */
4760 if (!found_alt_or_meta && ((1 << row) == LockMask))
4761 dpyinfo->shift_lock_mask = LockMask;
4762 code_col = syms_per_code;
4763 col = mods->max_keypermod;
4764 break;
4772 /* If we couldn't find any meta keys, accept any alt keys as meta keys. */
4773 if (! dpyinfo->meta_mod_mask)
4775 dpyinfo->meta_mod_mask = dpyinfo->alt_mod_mask;
4776 dpyinfo->alt_mod_mask = 0;
4779 /* If some keys are both alt and meta,
4780 make them just meta, not alt. */
4781 if (dpyinfo->alt_mod_mask & dpyinfo->meta_mod_mask)
4783 dpyinfo->alt_mod_mask &= ~dpyinfo->meta_mod_mask;
4786 XFree (syms);
4787 XFreeModifiermap (mods);
4790 /* Convert between the modifier bits X uses and the modifier bits
4791 Emacs uses. */
4794 x_x_to_emacs_modifiers (struct x_display_info *dpyinfo, int state)
4796 int mod_ctrl = ctrl_modifier;
4797 int mod_meta = meta_modifier;
4798 int mod_alt = alt_modifier;
4799 int mod_hyper = hyper_modifier;
4800 int mod_super = super_modifier;
4801 Lisp_Object tem;
4803 tem = Fget (Vx_ctrl_keysym, Qmodifier_value);
4804 if (INTEGERP (tem)) mod_ctrl = XINT (tem) & INT_MAX;
4805 tem = Fget (Vx_alt_keysym, Qmodifier_value);
4806 if (INTEGERP (tem)) mod_alt = XINT (tem) & INT_MAX;
4807 tem = Fget (Vx_meta_keysym, Qmodifier_value);
4808 if (INTEGERP (tem)) mod_meta = XINT (tem) & INT_MAX;
4809 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
4810 if (INTEGERP (tem)) mod_hyper = XINT (tem) & INT_MAX;
4811 tem = Fget (Vx_super_keysym, Qmodifier_value);
4812 if (INTEGERP (tem)) mod_super = XINT (tem) & INT_MAX;
4814 return ( ((state & (ShiftMask | dpyinfo->shift_lock_mask)) ? shift_modifier : 0)
4815 | ((state & ControlMask) ? mod_ctrl : 0)
4816 | ((state & dpyinfo->meta_mod_mask) ? mod_meta : 0)
4817 | ((state & dpyinfo->alt_mod_mask) ? mod_alt : 0)
4818 | ((state & dpyinfo->super_mod_mask) ? mod_super : 0)
4819 | ((state & dpyinfo->hyper_mod_mask) ? mod_hyper : 0));
4822 static int
4823 x_emacs_to_x_modifiers (struct x_display_info *dpyinfo, EMACS_INT state)
4825 EMACS_INT mod_ctrl = ctrl_modifier;
4826 EMACS_INT mod_meta = meta_modifier;
4827 EMACS_INT mod_alt = alt_modifier;
4828 EMACS_INT mod_hyper = hyper_modifier;
4829 EMACS_INT mod_super = super_modifier;
4831 Lisp_Object tem;
4833 tem = Fget (Vx_ctrl_keysym, Qmodifier_value);
4834 if (INTEGERP (tem)) mod_ctrl = XINT (tem);
4835 tem = Fget (Vx_alt_keysym, Qmodifier_value);
4836 if (INTEGERP (tem)) mod_alt = XINT (tem);
4837 tem = Fget (Vx_meta_keysym, Qmodifier_value);
4838 if (INTEGERP (tem)) mod_meta = XINT (tem);
4839 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
4840 if (INTEGERP (tem)) mod_hyper = XINT (tem);
4841 tem = Fget (Vx_super_keysym, Qmodifier_value);
4842 if (INTEGERP (tem)) mod_super = XINT (tem);
4845 return ( ((state & mod_alt) ? dpyinfo->alt_mod_mask : 0)
4846 | ((state & mod_super) ? dpyinfo->super_mod_mask : 0)
4847 | ((state & mod_hyper) ? dpyinfo->hyper_mod_mask : 0)
4848 | ((state & shift_modifier) ? ShiftMask : 0)
4849 | ((state & mod_ctrl) ? ControlMask : 0)
4850 | ((state & mod_meta) ? dpyinfo->meta_mod_mask : 0));
4853 /* Convert a keysym to its name. */
4855 char *
4856 x_get_keysym_name (int keysym)
4858 char *value;
4860 block_input ();
4861 value = XKeysymToString (keysym);
4862 unblock_input ();
4864 return value;
4867 /* Mouse clicks and mouse movement. Rah.
4869 Formerly, we used PointerMotionHintMask (in standard_event_mask)
4870 so that we would have to call XQueryPointer after each MotionNotify
4871 event to ask for another such event. However, this made mouse tracking
4872 slow, and there was a bug that made it eventually stop.
4874 Simply asking for MotionNotify all the time seems to work better.
4876 In order to avoid asking for motion events and then throwing most
4877 of them away or busy-polling the server for mouse positions, we ask
4878 the server for pointer motion hints. This means that we get only
4879 one event per group of mouse movements. "Groups" are delimited by
4880 other kinds of events (focus changes and button clicks, for
4881 example), or by XQueryPointer calls; when one of these happens, we
4882 get another MotionNotify event the next time the mouse moves. This
4883 is at least as efficient as getting motion events when mouse
4884 tracking is on, and I suspect only negligibly worse when tracking
4885 is off. */
4887 /* Prepare a mouse-event in *RESULT for placement in the input queue.
4889 If the event is a button press, then note that we have grabbed
4890 the mouse. */
4892 static Lisp_Object
4893 construct_mouse_click (struct input_event *result,
4894 const XButtonEvent *event,
4895 struct frame *f)
4897 /* Make the event type NO_EVENT; we'll change that when we decide
4898 otherwise. */
4899 result->kind = MOUSE_CLICK_EVENT;
4900 result->code = event->button - Button1;
4901 result->timestamp = event->time;
4902 result->modifiers = (x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO (f),
4903 event->state)
4904 | (event->type == ButtonRelease
4905 ? up_modifier
4906 : down_modifier));
4908 XSETINT (result->x, event->x);
4909 XSETINT (result->y, event->y);
4910 XSETFRAME (result->frame_or_window, f);
4911 result->arg = Qnil;
4912 return Qnil;
4915 /* Function to report a mouse movement to the mainstream Emacs code.
4916 The input handler calls this.
4918 We have received a mouse movement event, which is given in *event.
4919 If the mouse is over a different glyph than it was last time, tell
4920 the mainstream emacs code by setting mouse_moved. If not, ask for
4921 another motion event, so we can check again the next time it moves. */
4923 static bool
4924 note_mouse_movement (struct frame *frame, const XMotionEvent *event)
4926 XRectangle *r;
4927 struct x_display_info *dpyinfo;
4929 if (!FRAME_X_OUTPUT (frame))
4930 return false;
4932 dpyinfo = FRAME_DISPLAY_INFO (frame);
4933 dpyinfo->last_mouse_movement_time = event->time;
4934 dpyinfo->last_mouse_motion_frame = frame;
4935 dpyinfo->last_mouse_motion_x = event->x;
4936 dpyinfo->last_mouse_motion_y = event->y;
4938 if (event->window != FRAME_X_WINDOW (frame))
4940 frame->mouse_moved = true;
4941 dpyinfo->last_mouse_scroll_bar = NULL;
4942 note_mouse_highlight (frame, -1, -1);
4943 dpyinfo->last_mouse_glyph_frame = NULL;
4944 return true;
4948 /* Has the mouse moved off the glyph it was on at the last sighting? */
4949 r = &dpyinfo->last_mouse_glyph;
4950 if (frame != dpyinfo->last_mouse_glyph_frame
4951 || event->x < r->x || event->x >= r->x + r->width
4952 || event->y < r->y || event->y >= r->y + r->height)
4954 frame->mouse_moved = true;
4955 dpyinfo->last_mouse_scroll_bar = NULL;
4956 note_mouse_highlight (frame, event->x, event->y);
4957 /* Remember which glyph we're now on. */
4958 remember_mouse_glyph (frame, event->x, event->y, r);
4959 dpyinfo->last_mouse_glyph_frame = frame;
4960 return true;
4963 return false;
4966 /* Return the current position of the mouse.
4967 *FP should be a frame which indicates which display to ask about.
4969 If the mouse movement started in a scroll bar, set *FP, *BAR_WINDOW,
4970 and *PART to the frame, window, and scroll bar part that the mouse
4971 is over. Set *X and *Y to the portion and whole of the mouse's
4972 position on the scroll bar.
4974 If the mouse movement started elsewhere, set *FP to the frame the
4975 mouse is on, *BAR_WINDOW to nil, and *X and *Y to the character cell
4976 the mouse is over.
4978 Set *TIMESTAMP to the server time-stamp for the time at which the mouse
4979 was at this position.
4981 Don't store anything if we don't have a valid set of values to report.
4983 This clears the mouse_moved flag, so we can wait for the next mouse
4984 movement. */
4986 static void
4987 XTmouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
4988 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
4989 Time *timestamp)
4991 struct frame *f1;
4992 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (*fp);
4994 block_input ();
4996 if (dpyinfo->last_mouse_scroll_bar && insist == 0)
4998 struct scroll_bar *bar = dpyinfo->last_mouse_scroll_bar;
5000 if (bar->horizontal)
5001 x_horizontal_scroll_bar_report_motion (fp, bar_window, part, x, y, timestamp);
5002 else
5003 x_scroll_bar_report_motion (fp, bar_window, part, x, y, timestamp);
5005 else
5007 Window root;
5008 int root_x, root_y;
5010 Window dummy_window;
5011 int dummy;
5013 Lisp_Object frame, tail;
5015 /* Clear the mouse-moved flag for every frame on this display. */
5016 FOR_EACH_FRAME (tail, frame)
5017 if (FRAME_X_P (XFRAME (frame))
5018 && FRAME_X_DISPLAY (XFRAME (frame)) == FRAME_X_DISPLAY (*fp))
5019 XFRAME (frame)->mouse_moved = false;
5021 dpyinfo->last_mouse_scroll_bar = NULL;
5023 /* Figure out which root window we're on. */
5024 XQueryPointer (FRAME_X_DISPLAY (*fp),
5025 DefaultRootWindow (FRAME_X_DISPLAY (*fp)),
5027 /* The root window which contains the pointer. */
5028 &root,
5030 /* Trash which we can't trust if the pointer is on
5031 a different screen. */
5032 &dummy_window,
5034 /* The position on that root window. */
5035 &root_x, &root_y,
5037 /* More trash we can't trust. */
5038 &dummy, &dummy,
5040 /* Modifier keys and pointer buttons, about which
5041 we don't care. */
5042 (unsigned int *) &dummy);
5044 /* Now we have a position on the root; find the innermost window
5045 containing the pointer. */
5047 Window win, child;
5048 #ifdef USE_GTK
5049 Window first_win = 0;
5050 #endif
5051 int win_x, win_y;
5052 int parent_x = 0, parent_y = 0;
5054 win = root;
5056 /* XTranslateCoordinates can get errors if the window
5057 structure is changing at the same time this function
5058 is running. So at least we must not crash from them. */
5060 x_catch_errors (FRAME_X_DISPLAY (*fp));
5062 if (x_mouse_grabbed (dpyinfo))
5064 /* If mouse was grabbed on a frame, give coords for that frame
5065 even if the mouse is now outside it. */
5066 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
5068 /* From-window. */
5069 root,
5071 /* To-window. */
5072 FRAME_X_WINDOW (dpyinfo->last_mouse_frame),
5074 /* From-position, to-position. */
5075 root_x, root_y, &win_x, &win_y,
5077 /* Child of win. */
5078 &child);
5079 f1 = dpyinfo->last_mouse_frame;
5081 else
5083 while (true)
5085 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
5087 /* From-window, to-window. */
5088 root, win,
5090 /* From-position, to-position. */
5091 root_x, root_y, &win_x, &win_y,
5093 /* Child of win. */
5094 &child);
5096 if (child == None || child == win)
5098 #ifdef USE_GTK
5099 /* On GTK we have not inspected WIN yet. If it has
5100 a frame and that frame has a parent, use it. */
5101 struct frame *f = x_window_to_frame (dpyinfo, win);
5103 if (f && FRAME_PARENT_FRAME (f))
5104 first_win = win;
5105 #endif
5106 break;
5108 #ifdef USE_GTK
5109 /* We don't wan't to know the innermost window. We
5110 want the edit window. For non-Gtk+ the innermost
5111 window is the edit window. For Gtk+ it might not
5112 be. It might be the tool bar for example. */
5113 if (x_window_to_frame (dpyinfo, win))
5114 /* But don't hurry. We might find a child frame
5115 beneath. */
5116 first_win = win;
5117 #endif
5118 win = child;
5119 parent_x = win_x;
5120 parent_y = win_y;
5123 #ifdef USE_GTK
5124 if (first_win)
5125 win = first_win;
5126 #endif
5128 /* Now we know that:
5129 win is the innermost window containing the pointer
5130 (XTC says it has no child containing the pointer),
5131 win_x and win_y are the pointer's position in it
5132 (XTC did this the last time through), and
5133 parent_x and parent_y are the pointer's position in win's parent.
5134 (They are what win_x and win_y were when win was child.
5135 If win is the root window, it has no parent, and
5136 parent_{x,y} are invalid, but that's okay, because we'll
5137 never use them in that case.) */
5139 #ifdef USE_GTK
5140 /* We don't wan't to know the innermost window. We
5141 want the edit window. */
5142 f1 = x_window_to_frame (dpyinfo, win);
5143 #else
5144 /* Is win one of our frames? */
5145 f1 = x_any_window_to_frame (dpyinfo, win);
5146 #endif
5148 #ifdef USE_X_TOOLKIT
5149 /* If we end up with the menu bar window, say it's not
5150 on the frame. */
5151 if (f1 != NULL
5152 && f1->output_data.x->menubar_widget
5153 && win == XtWindow (f1->output_data.x->menubar_widget))
5154 f1 = NULL;
5155 #endif /* USE_X_TOOLKIT */
5158 if (x_had_errors_p (FRAME_X_DISPLAY (*fp)))
5159 f1 = 0;
5161 x_uncatch_errors_after_check ();
5163 /* If not, is it one of our scroll bars? */
5164 if (! f1)
5166 struct scroll_bar *bar;
5168 bar = x_window_to_scroll_bar (FRAME_X_DISPLAY (*fp), win, 2);
5170 if (bar)
5172 f1 = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5173 win_x = parent_x;
5174 win_y = parent_y;
5178 if (f1 == 0 && insist > 0)
5179 f1 = SELECTED_FRAME ();
5181 if (f1)
5183 /* Ok, we found a frame. Store all the values.
5184 last_mouse_glyph is a rectangle used to reduce the
5185 generation of mouse events. To not miss any motion
5186 events, we must divide the frame into rectangles of the
5187 size of the smallest character that could be displayed
5188 on it, i.e. into the same rectangles that matrices on
5189 the frame are divided into. */
5191 /* FIXME: what if F1 is not an X frame? */
5192 dpyinfo = FRAME_DISPLAY_INFO (f1);
5193 remember_mouse_glyph (f1, win_x, win_y, &dpyinfo->last_mouse_glyph);
5194 dpyinfo->last_mouse_glyph_frame = f1;
5196 *bar_window = Qnil;
5197 *part = 0;
5198 *fp = f1;
5199 XSETINT (*x, win_x);
5200 XSETINT (*y, win_y);
5201 *timestamp = dpyinfo->last_mouse_movement_time;
5206 unblock_input ();
5211 /***********************************************************************
5212 Scroll bars
5213 ***********************************************************************/
5215 /* Scroll bar support. */
5217 /* Given an X window ID and a DISPLAY, find the struct scroll_bar which
5218 manages it.
5219 This can be called in GC, so we have to make sure to strip off mark
5220 bits. */
5222 static struct scroll_bar *
5223 x_window_to_scroll_bar (Display *display, Window window_id, int type)
5225 Lisp_Object tail, frame;
5227 #if defined (USE_GTK) && defined (USE_TOOLKIT_SCROLL_BARS)
5228 window_id = (Window) xg_get_scroll_id_for_window (display, window_id);
5229 #endif /* USE_GTK && USE_TOOLKIT_SCROLL_BARS */
5231 FOR_EACH_FRAME (tail, frame)
5233 Lisp_Object bar, condemned;
5235 if (! FRAME_X_P (XFRAME (frame)))
5236 continue;
5238 /* Scan this frame's scroll bar list for a scroll bar with the
5239 right window ID. */
5240 condemned = FRAME_CONDEMNED_SCROLL_BARS (XFRAME (frame));
5241 for (bar = FRAME_SCROLL_BARS (XFRAME (frame));
5242 /* This trick allows us to search both the ordinary and
5243 condemned scroll bar lists with one loop. */
5244 ! NILP (bar) || (bar = condemned,
5245 condemned = Qnil,
5246 ! NILP (bar));
5247 bar = XSCROLL_BAR (bar)->next)
5248 if (XSCROLL_BAR (bar)->x_window == window_id
5249 && FRAME_X_DISPLAY (XFRAME (frame)) == display
5250 && (type = 2
5251 || (type == 1 && XSCROLL_BAR (bar)->horizontal)
5252 || (type == 0 && !XSCROLL_BAR (bar)->horizontal)))
5253 return XSCROLL_BAR (bar);
5256 return NULL;
5260 #if defined USE_LUCID
5262 /* Return the Lucid menu bar WINDOW is part of. Return null
5263 if WINDOW is not part of a menu bar. */
5265 static Widget
5266 x_window_to_menu_bar (Window window)
5268 Lisp_Object tail, frame;
5270 FOR_EACH_FRAME (tail, frame)
5271 if (FRAME_X_P (XFRAME (frame)))
5273 Widget menu_bar = XFRAME (frame)->output_data.x->menubar_widget;
5275 if (menu_bar && xlwmenu_window_p (menu_bar, window))
5276 return menu_bar;
5278 return NULL;
5281 #endif /* USE_LUCID */
5284 /************************************************************************
5285 Toolkit scroll bars
5286 ************************************************************************/
5288 #ifdef USE_TOOLKIT_SCROLL_BARS
5290 static void x_send_scroll_bar_event (Lisp_Object, enum scroll_bar_part,
5291 int, int, bool);
5293 /* Lisp window being scrolled. Set when starting to interact with
5294 a toolkit scroll bar, reset to nil when ending the interaction. */
5296 static Lisp_Object window_being_scrolled;
5298 /* Whether this is an Xaw with arrow-scrollbars. This should imply
5299 that movements of 1/20 of the screen size are mapped to up/down. */
5301 #ifndef USE_GTK
5302 /* Id of action hook installed for scroll bars. */
5304 static XtActionHookId action_hook_id;
5305 static XtActionHookId horizontal_action_hook_id;
5307 static Boolean xaw3d_arrow_scroll;
5309 /* Whether the drag scrolling maintains the mouse at the top of the
5310 thumb. If not, resizing the thumb needs to be done more carefully
5311 to avoid jerkiness. */
5313 static Boolean xaw3d_pick_top;
5315 /* Action hook installed via XtAppAddActionHook when toolkit scroll
5316 bars are used.. The hook is responsible for detecting when
5317 the user ends an interaction with the scroll bar, and generates
5318 a `end-scroll' SCROLL_BAR_CLICK_EVENT' event if so. */
5320 static void
5321 xt_action_hook (Widget widget, XtPointer client_data, String action_name,
5322 XEvent *event, String *params, Cardinal *num_params)
5324 bool scroll_bar_p;
5325 const char *end_action;
5327 #ifdef USE_MOTIF
5328 scroll_bar_p = XmIsScrollBar (widget);
5329 end_action = "Release";
5330 #else /* !USE_MOTIF i.e. use Xaw */
5331 scroll_bar_p = XtIsSubclass (widget, scrollbarWidgetClass);
5332 end_action = "EndScroll";
5333 #endif /* USE_MOTIF */
5335 if (scroll_bar_p
5336 && strcmp (action_name, end_action) == 0
5337 && WINDOWP (window_being_scrolled))
5339 struct window *w;
5340 struct scroll_bar *bar;
5342 x_send_scroll_bar_event (window_being_scrolled,
5343 scroll_bar_end_scroll, 0, 0, false);
5344 w = XWINDOW (window_being_scrolled);
5345 bar = XSCROLL_BAR (w->vertical_scroll_bar);
5347 if (bar->dragging != -1)
5349 bar->dragging = -1;
5350 /* The thumb size is incorrect while dragging: fix it. */
5351 set_vertical_scroll_bar (w);
5353 window_being_scrolled = Qnil;
5354 #if defined (USE_LUCID)
5355 bar->last_seen_part = scroll_bar_nowhere;
5356 #endif
5357 /* Xt timeouts no longer needed. */
5358 toolkit_scroll_bar_interaction = false;
5363 static void
5364 xt_horizontal_action_hook (Widget widget, XtPointer client_data, String action_name,
5365 XEvent *event, String *params, Cardinal *num_params)
5367 bool scroll_bar_p;
5368 const char *end_action;
5370 #ifdef USE_MOTIF
5371 scroll_bar_p = XmIsScrollBar (widget);
5372 end_action = "Release";
5373 #else /* !USE_MOTIF i.e. use Xaw */
5374 scroll_bar_p = XtIsSubclass (widget, scrollbarWidgetClass);
5375 end_action = "EndScroll";
5376 #endif /* USE_MOTIF */
5378 if (scroll_bar_p
5379 && strcmp (action_name, end_action) == 0
5380 && WINDOWP (window_being_scrolled))
5382 struct window *w;
5383 struct scroll_bar *bar;
5385 x_send_scroll_bar_event (window_being_scrolled,
5386 scroll_bar_end_scroll, 0, 0, true);
5387 w = XWINDOW (window_being_scrolled);
5388 if (!NILP (w->horizontal_scroll_bar))
5390 bar = XSCROLL_BAR (w->horizontal_scroll_bar);
5391 if (bar->dragging != -1)
5393 bar->dragging = -1;
5394 /* The thumb size is incorrect while dragging: fix it. */
5395 set_horizontal_scroll_bar (w);
5397 window_being_scrolled = Qnil;
5398 #if defined (USE_LUCID)
5399 bar->last_seen_part = scroll_bar_nowhere;
5400 #endif
5401 /* Xt timeouts no longer needed. */
5402 toolkit_scroll_bar_interaction = false;
5406 #endif /* not USE_GTK */
5408 /* Send a client message with message type Xatom_Scrollbar for a
5409 scroll action to the frame of WINDOW. PART is a value identifying
5410 the part of the scroll bar that was clicked on. PORTION is the
5411 amount to scroll of a whole of WHOLE. */
5413 static void
5414 x_send_scroll_bar_event (Lisp_Object window, enum scroll_bar_part part,
5415 int portion, int whole, bool horizontal)
5417 XEvent event;
5418 XClientMessageEvent *ev = &event.xclient;
5419 struct window *w = XWINDOW (window);
5420 struct frame *f = XFRAME (w->frame);
5421 intptr_t iw = (intptr_t) w;
5422 verify (INTPTR_WIDTH <= 64);
5423 int sign_shift = INTPTR_WIDTH - 32;
5425 block_input ();
5427 /* Construct a ClientMessage event to send to the frame. */
5428 ev->type = ClientMessage;
5429 ev->message_type = (horizontal
5430 ? FRAME_DISPLAY_INFO (f)->Xatom_Horizontal_Scrollbar
5431 : FRAME_DISPLAY_INFO (f)->Xatom_Scrollbar);
5432 ev->display = FRAME_X_DISPLAY (f);
5433 ev->window = FRAME_X_WINDOW (f);
5434 ev->format = 32;
5436 /* A 32-bit X client on a 64-bit X server can pass a window pointer
5437 as-is. A 64-bit client on a 32-bit X server is in trouble
5438 because a pointer does not fit and would be truncated while
5439 passing through the server. So use two slots and hope that X12
5440 will resolve such issues someday. */
5441 ev->data.l[0] = iw >> 31 >> 1;
5442 ev->data.l[1] = sign_shift <= 0 ? iw : iw << sign_shift >> sign_shift;
5443 ev->data.l[2] = part;
5444 ev->data.l[3] = portion;
5445 ev->data.l[4] = whole;
5447 /* Make Xt timeouts work while the scroll bar is active. */
5448 #ifdef USE_X_TOOLKIT
5449 toolkit_scroll_bar_interaction = true;
5450 x_activate_timeout_atimer ();
5451 #endif
5453 /* Setting the event mask to zero means that the message will
5454 be sent to the client that created the window, and if that
5455 window no longer exists, no event will be sent. */
5456 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), False, 0, &event);
5457 unblock_input ();
5461 /* Transform a scroll bar ClientMessage EVENT to an Emacs input event
5462 in *IEVENT. */
5464 static void
5465 x_scroll_bar_to_input_event (const XEvent *event,
5466 struct input_event *ievent)
5468 const XClientMessageEvent *ev = &event->xclient;
5469 Lisp_Object window;
5470 struct window *w;
5472 /* See the comment in the function above. */
5473 intptr_t iw0 = ev->data.l[0];
5474 intptr_t iw1 = ev->data.l[1];
5475 intptr_t iw = (iw0 << 31 << 1) + (iw1 & 0xffffffffu);
5476 w = (struct window *) iw;
5478 XSETWINDOW (window, w);
5480 ievent->kind = SCROLL_BAR_CLICK_EVENT;
5481 ievent->frame_or_window = window;
5482 ievent->arg = Qnil;
5483 #ifdef USE_GTK
5484 ievent->timestamp = CurrentTime;
5485 #else
5486 ievent->timestamp =
5487 XtLastTimestampProcessed (FRAME_X_DISPLAY (XFRAME (w->frame)));
5488 #endif
5489 ievent->code = 0;
5490 ievent->part = ev->data.l[2];
5491 ievent->x = make_number (ev->data.l[3]);
5492 ievent->y = make_number (ev->data.l[4]);
5493 ievent->modifiers = 0;
5496 /* Transform a horizontal scroll bar ClientMessage EVENT to an Emacs
5497 input event in *IEVENT. */
5499 static void
5500 x_horizontal_scroll_bar_to_input_event (const XEvent *event,
5501 struct input_event *ievent)
5503 const XClientMessageEvent *ev = &event->xclient;
5504 Lisp_Object window;
5505 struct window *w;
5507 /* See the comment in the function above. */
5508 intptr_t iw0 = ev->data.l[0];
5509 intptr_t iw1 = ev->data.l[1];
5510 intptr_t iw = (iw0 << 31 << 1) + (iw1 & 0xffffffffu);
5511 w = (struct window *) iw;
5513 XSETWINDOW (window, w);
5515 ievent->kind = HORIZONTAL_SCROLL_BAR_CLICK_EVENT;
5516 ievent->frame_or_window = window;
5517 ievent->arg = Qnil;
5518 #ifdef USE_GTK
5519 ievent->timestamp = CurrentTime;
5520 #else
5521 ievent->timestamp =
5522 XtLastTimestampProcessed (FRAME_X_DISPLAY (XFRAME (w->frame)));
5523 #endif
5524 ievent->code = 0;
5525 ievent->part = ev->data.l[2];
5526 ievent->x = make_number (ev->data.l[3]);
5527 ievent->y = make_number (ev->data.l[4]);
5528 ievent->modifiers = 0;
5532 #ifdef USE_MOTIF
5534 /* Minimum and maximum values used for Motif scroll bars. */
5536 #define XM_SB_MAX 10000000
5538 /* Scroll bar callback for Motif scroll bars. WIDGET is the scroll
5539 bar widget. CLIENT_DATA is a pointer to the scroll_bar structure.
5540 CALL_DATA is a pointer to a XmScrollBarCallbackStruct. */
5542 static void
5543 xm_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
5545 struct scroll_bar *bar = client_data;
5546 XmScrollBarCallbackStruct *cs = call_data;
5547 enum scroll_bar_part part = scroll_bar_nowhere;
5548 bool horizontal = bar->horizontal;
5549 int whole = 0, portion = 0;
5551 switch (cs->reason)
5553 case XmCR_DECREMENT:
5554 bar->dragging = -1;
5555 part = horizontal ? scroll_bar_left_arrow : scroll_bar_up_arrow;
5556 break;
5558 case XmCR_INCREMENT:
5559 bar->dragging = -1;
5560 part = horizontal ? scroll_bar_right_arrow : scroll_bar_down_arrow;
5561 break;
5563 case XmCR_PAGE_DECREMENT:
5564 bar->dragging = -1;
5565 part = horizontal ? scroll_bar_before_handle : scroll_bar_above_handle;
5566 break;
5568 case XmCR_PAGE_INCREMENT:
5569 bar->dragging = -1;
5570 part = horizontal ? scroll_bar_after_handle : scroll_bar_below_handle;
5571 break;
5573 case XmCR_TO_TOP:
5574 bar->dragging = -1;
5575 part = horizontal ? scroll_bar_to_leftmost : scroll_bar_to_top;
5576 break;
5578 case XmCR_TO_BOTTOM:
5579 bar->dragging = -1;
5580 part = horizontal ? scroll_bar_to_rightmost : scroll_bar_to_bottom;
5581 break;
5583 case XmCR_DRAG:
5585 int slider_size;
5587 block_input ();
5588 XtVaGetValues (widget, XmNsliderSize, &slider_size, NULL);
5589 unblock_input ();
5591 if (horizontal)
5593 portion = bar->whole * ((float)cs->value / XM_SB_MAX);
5594 whole = bar->whole * ((float)(XM_SB_MAX - slider_size) / XM_SB_MAX);
5595 portion = min (portion, whole);
5596 part = scroll_bar_horizontal_handle;
5598 else
5600 whole = XM_SB_MAX - slider_size;
5601 portion = min (cs->value, whole);
5602 part = scroll_bar_handle;
5605 bar->dragging = cs->value;
5607 break;
5609 case XmCR_VALUE_CHANGED:
5610 break;
5613 if (part != scroll_bar_nowhere)
5615 window_being_scrolled = bar->window;
5616 x_send_scroll_bar_event (bar->window, part, portion, whole,
5617 bar->horizontal);
5621 #elif defined USE_GTK
5623 /* Scroll bar callback for GTK scroll bars. WIDGET is the scroll
5624 bar widget. DATA is a pointer to the scroll_bar structure. */
5626 static gboolean
5627 xg_scroll_callback (GtkRange *range,
5628 GtkScrollType scroll,
5629 gdouble value,
5630 gpointer user_data)
5632 int whole = 0, portion = 0;
5633 struct scroll_bar *bar = user_data;
5634 enum scroll_bar_part part = scroll_bar_nowhere;
5635 GtkAdjustment *adj = GTK_ADJUSTMENT (gtk_range_get_adjustment (range));
5636 struct frame *f = g_object_get_data (G_OBJECT (range), XG_FRAME_DATA);
5638 if (xg_ignore_gtk_scrollbar) return false;
5640 switch (scroll)
5642 case GTK_SCROLL_JUMP:
5643 /* Buttons 1 2 or 3 must be grabbed. */
5644 if (FRAME_DISPLAY_INFO (f)->grabbed != 0
5645 && FRAME_DISPLAY_INFO (f)->grabbed < (1 << 4))
5647 if (bar->horizontal)
5649 part = scroll_bar_horizontal_handle;
5650 whole = (int)(gtk_adjustment_get_upper (adj) -
5651 gtk_adjustment_get_page_size (adj));
5652 portion = min ((int)value, whole);
5653 bar->dragging = portion;
5655 else
5657 part = scroll_bar_handle;
5658 whole = gtk_adjustment_get_upper (adj) -
5659 gtk_adjustment_get_page_size (adj);
5660 portion = min ((int)value, whole);
5661 bar->dragging = portion;
5664 break;
5665 case GTK_SCROLL_STEP_BACKWARD:
5666 part = (bar->horizontal
5667 ? scroll_bar_left_arrow : scroll_bar_up_arrow);
5668 bar->dragging = -1;
5669 break;
5670 case GTK_SCROLL_STEP_FORWARD:
5671 part = (bar->horizontal
5672 ? scroll_bar_right_arrow : scroll_bar_down_arrow);
5673 bar->dragging = -1;
5674 break;
5675 case GTK_SCROLL_PAGE_BACKWARD:
5676 part = (bar->horizontal
5677 ? scroll_bar_before_handle : scroll_bar_above_handle);
5678 bar->dragging = -1;
5679 break;
5680 case GTK_SCROLL_PAGE_FORWARD:
5681 part = (bar->horizontal
5682 ? scroll_bar_after_handle : scroll_bar_below_handle);
5683 bar->dragging = -1;
5684 break;
5685 default:
5686 break;
5689 if (part != scroll_bar_nowhere)
5691 window_being_scrolled = bar->window;
5692 x_send_scroll_bar_event (bar->window, part, portion, whole,
5693 bar->horizontal);
5696 return false;
5699 /* Callback for button release. Sets dragging to -1 when dragging is done. */
5701 static gboolean
5702 xg_end_scroll_callback (GtkWidget *widget,
5703 GdkEventButton *event,
5704 gpointer user_data)
5706 struct scroll_bar *bar = user_data;
5707 bar->dragging = -1;
5708 if (WINDOWP (window_being_scrolled))
5710 x_send_scroll_bar_event (window_being_scrolled,
5711 scroll_bar_end_scroll, 0, 0, bar->horizontal);
5712 window_being_scrolled = Qnil;
5715 return false;
5719 #else /* not USE_GTK and not USE_MOTIF */
5721 /* Xaw scroll bar callback. Invoked when the thumb is dragged.
5722 WIDGET is the scroll bar widget. CLIENT_DATA is a pointer to the
5723 scroll bar struct. CALL_DATA is a pointer to a float saying where
5724 the thumb is. */
5726 static void
5727 xaw_jump_callback (Widget widget, XtPointer client_data, XtPointer call_data)
5729 struct scroll_bar *bar = client_data;
5730 float *top_addr = call_data;
5731 float top = *top_addr;
5732 float shown;
5733 int whole, portion, height, width;
5734 enum scroll_bar_part part;
5735 bool horizontal = bar->horizontal;
5737 if (horizontal)
5739 /* Get the size of the thumb, a value between 0 and 1. */
5740 block_input ();
5741 XtVaGetValues (widget, XtNshown, &shown, XtNwidth, &width, NULL);
5742 unblock_input ();
5744 if (shown < 1)
5746 whole = bar->whole - (shown * bar->whole);
5747 portion = min (top * bar->whole, whole);
5749 else
5751 whole = bar->whole;
5752 portion = 0;
5755 part = scroll_bar_horizontal_handle;
5757 else
5759 /* Get the size of the thumb, a value between 0 and 1. */
5760 block_input ();
5761 XtVaGetValues (widget, XtNshown, &shown, XtNheight, &height, NULL);
5762 unblock_input ();
5764 whole = 10000000;
5765 portion = shown < 1 ? top * whole : 0;
5767 if (shown < 1 && (eabs (top + shown - 1) < 1.0f / height))
5768 /* Some derivatives of Xaw refuse to shrink the thumb when you reach
5769 the bottom, so we force the scrolling whenever we see that we're
5770 too close to the bottom (in x_set_toolkit_scroll_bar_thumb
5771 we try to ensure that we always stay two pixels away from the
5772 bottom). */
5773 part = scroll_bar_down_arrow;
5774 else
5775 part = scroll_bar_handle;
5778 window_being_scrolled = bar->window;
5779 bar->dragging = portion;
5780 bar->last_seen_part = part;
5781 x_send_scroll_bar_event (bar->window, part, portion, whole, bar->horizontal);
5785 /* Xaw scroll bar callback. Invoked for incremental scrolling.,
5786 i.e. line or page up or down. WIDGET is the Xaw scroll bar
5787 widget. CLIENT_DATA is a pointer to the scroll_bar structure for
5788 the scroll bar. CALL_DATA is an integer specifying the action that
5789 has taken place. Its magnitude is in the range 0..height of the
5790 scroll bar. Negative values mean scroll towards buffer start.
5791 Values < height of scroll bar mean line-wise movement. */
5793 static void
5794 xaw_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
5796 struct scroll_bar *bar = client_data;
5797 /* The position really is stored cast to a pointer. */
5798 int position = (intptr_t) call_data;
5799 Dimension height, width;
5800 enum scroll_bar_part part;
5802 if (bar->horizontal)
5804 /* Get the width of the scroll bar. */
5805 block_input ();
5806 XtVaGetValues (widget, XtNwidth, &width, NULL);
5807 unblock_input ();
5809 if (eabs (position) >= width)
5810 part = (position < 0) ? scroll_bar_before_handle : scroll_bar_after_handle;
5812 /* If Xaw3d was compiled with ARROW_SCROLLBAR,
5813 it maps line-movement to call_data = max(5, height/20). */
5814 else if (xaw3d_arrow_scroll && eabs (position) <= max (5, width / 20))
5815 part = (position < 0) ? scroll_bar_left_arrow : scroll_bar_right_arrow;
5816 else
5817 part = scroll_bar_move_ratio;
5819 window_being_scrolled = bar->window;
5820 bar->dragging = -1;
5821 bar->last_seen_part = part;
5822 x_send_scroll_bar_event (bar->window, part, position, width,
5823 bar->horizontal);
5825 else
5828 /* Get the height of the scroll bar. */
5829 block_input ();
5830 XtVaGetValues (widget, XtNheight, &height, NULL);
5831 unblock_input ();
5833 if (eabs (position) >= height)
5834 part = (position < 0) ? scroll_bar_above_handle : scroll_bar_below_handle;
5836 /* If Xaw3d was compiled with ARROW_SCROLLBAR,
5837 it maps line-movement to call_data = max(5, height/20). */
5838 else if (xaw3d_arrow_scroll && eabs (position) <= max (5, height / 20))
5839 part = (position < 0) ? scroll_bar_up_arrow : scroll_bar_down_arrow;
5840 else
5841 part = scroll_bar_move_ratio;
5843 window_being_scrolled = bar->window;
5844 bar->dragging = -1;
5845 bar->last_seen_part = part;
5846 x_send_scroll_bar_event (bar->window, part, position, height,
5847 bar->horizontal);
5851 #endif /* not USE_GTK and not USE_MOTIF */
5853 #define SCROLL_BAR_NAME "verticalScrollBar"
5854 #define SCROLL_BAR_HORIZONTAL_NAME "horizontalScrollBar"
5856 /* Create the widget for scroll bar BAR on frame F. Record the widget
5857 and X window of the scroll bar in BAR. */
5859 #ifdef USE_GTK
5860 static void
5861 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
5863 const char *scroll_bar_name = SCROLL_BAR_NAME;
5865 block_input ();
5866 xg_create_scroll_bar (f, bar, G_CALLBACK (xg_scroll_callback),
5867 G_CALLBACK (xg_end_scroll_callback),
5868 scroll_bar_name);
5869 unblock_input ();
5872 static void
5873 x_create_horizontal_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
5875 const char *scroll_bar_name = SCROLL_BAR_HORIZONTAL_NAME;
5877 block_input ();
5878 xg_create_horizontal_scroll_bar (f, bar, G_CALLBACK (xg_scroll_callback),
5879 G_CALLBACK (xg_end_scroll_callback),
5880 scroll_bar_name);
5881 unblock_input ();
5884 #else /* not USE_GTK */
5886 static void
5887 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
5889 Window xwindow;
5890 Widget widget;
5891 Arg av[20];
5892 int ac = 0;
5893 const char *scroll_bar_name = SCROLL_BAR_NAME;
5894 unsigned long pixel;
5896 block_input ();
5898 #ifdef USE_MOTIF
5899 /* Set resources. Create the widget. */
5900 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
5901 XtSetArg (av[ac], XmNminimum, 0); ++ac;
5902 XtSetArg (av[ac], XmNmaximum, XM_SB_MAX); ++ac;
5903 XtSetArg (av[ac], XmNorientation, XmVERTICAL); ++ac;
5904 XtSetArg (av[ac], XmNprocessingDirection, XmMAX_ON_BOTTOM), ++ac;
5905 XtSetArg (av[ac], XmNincrement, 1); ++ac;
5906 XtSetArg (av[ac], XmNpageIncrement, 1); ++ac;
5908 pixel = f->output_data.x->scroll_bar_foreground_pixel;
5909 if (pixel != -1)
5911 XtSetArg (av[ac], XmNforeground, pixel);
5912 ++ac;
5915 pixel = f->output_data.x->scroll_bar_background_pixel;
5916 if (pixel != -1)
5918 XtSetArg (av[ac], XmNbackground, pixel);
5919 ++ac;
5922 widget = XmCreateScrollBar (f->output_data.x->edit_widget,
5923 (char *) scroll_bar_name, av, ac);
5925 /* Add one callback for everything that can happen. */
5926 XtAddCallback (widget, XmNdecrementCallback, xm_scroll_callback,
5927 (XtPointer) bar);
5928 XtAddCallback (widget, XmNdragCallback, xm_scroll_callback,
5929 (XtPointer) bar);
5930 XtAddCallback (widget, XmNincrementCallback, xm_scroll_callback,
5931 (XtPointer) bar);
5932 XtAddCallback (widget, XmNpageDecrementCallback, xm_scroll_callback,
5933 (XtPointer) bar);
5934 XtAddCallback (widget, XmNpageIncrementCallback, xm_scroll_callback,
5935 (XtPointer) bar);
5936 XtAddCallback (widget, XmNtoBottomCallback, xm_scroll_callback,
5937 (XtPointer) bar);
5938 XtAddCallback (widget, XmNtoTopCallback, xm_scroll_callback,
5939 (XtPointer) bar);
5941 /* Realize the widget. Only after that is the X window created. */
5942 XtRealizeWidget (widget);
5944 /* Set the cursor to an arrow. I didn't find a resource to do that.
5945 And I'm wondering why it hasn't an arrow cursor by default. */
5946 XDefineCursor (XtDisplay (widget), XtWindow (widget),
5947 f->output_data.x->nontext_cursor);
5949 #else /* !USE_MOTIF i.e. use Xaw */
5951 /* Set resources. Create the widget. The background of the
5952 Xaw3d scroll bar widget is a little bit light for my taste.
5953 We don't alter it here to let users change it according
5954 to their taste with `emacs*verticalScrollBar.background: xxx'. */
5955 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
5956 XtSetArg (av[ac], XtNorientation, XtorientVertical); ++ac;
5957 /* For smoother scrolling with Xaw3d -sm */
5958 /* XtSetArg (av[ac], XtNpickTop, True); ++ac; */
5960 pixel = f->output_data.x->scroll_bar_foreground_pixel;
5961 if (pixel != -1)
5963 XtSetArg (av[ac], XtNforeground, pixel);
5964 ++ac;
5967 pixel = f->output_data.x->scroll_bar_background_pixel;
5968 if (pixel != -1)
5970 XtSetArg (av[ac], XtNbackground, pixel);
5971 ++ac;
5974 /* Top/bottom shadow colors. */
5976 /* Allocate them, if necessary. */
5977 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1)
5979 pixel = f->output_data.x->scroll_bar_background_pixel;
5980 if (pixel != -1)
5982 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
5983 FRAME_X_COLORMAP (f),
5984 &pixel, 1.2, 0x8000))
5985 pixel = -1;
5986 f->output_data.x->scroll_bar_top_shadow_pixel = pixel;
5989 if (f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
5991 pixel = f->output_data.x->scroll_bar_background_pixel;
5992 if (pixel != -1)
5994 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
5995 FRAME_X_COLORMAP (f),
5996 &pixel, 0.6, 0x4000))
5997 pixel = -1;
5998 f->output_data.x->scroll_bar_bottom_shadow_pixel = pixel;
6002 #ifdef XtNbeNiceToColormap
6003 /* Tell the toolkit about them. */
6004 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1
6005 || f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
6006 /* We tried to allocate a color for the top/bottom shadow, and
6007 failed, so tell Xaw3d to use dithering instead. */
6008 /* But only if we have a small colormap. Xaw3d can allocate nice
6009 colors itself. */
6011 XtSetArg (av[ac], XtNbeNiceToColormap,
6012 DefaultDepthOfScreen (FRAME_X_SCREEN (f)) < 16);
6013 ++ac;
6015 else
6016 /* Tell what colors Xaw3d should use for the top/bottom shadow, to
6017 be more consistent with other emacs 3d colors, and since Xaw3d is
6018 not good at dealing with allocation failure. */
6020 /* This tells Xaw3d to use real colors instead of dithering for
6021 the shadows. */
6022 XtSetArg (av[ac], XtNbeNiceToColormap, False);
6023 ++ac;
6025 /* Specify the colors. */
6026 pixel = f->output_data.x->scroll_bar_top_shadow_pixel;
6027 if (pixel != -1)
6029 XtSetArg (av[ac], XtNtopShadowPixel, pixel);
6030 ++ac;
6032 pixel = f->output_data.x->scroll_bar_bottom_shadow_pixel;
6033 if (pixel != -1)
6035 XtSetArg (av[ac], XtNbottomShadowPixel, pixel);
6036 ++ac;
6039 #endif
6041 widget = XtCreateWidget (scroll_bar_name, scrollbarWidgetClass,
6042 f->output_data.x->edit_widget, av, ac);
6045 char const *initial = "";
6046 char const *val = initial;
6047 XtVaGetValues (widget, XtNscrollVCursor, (XtPointer) &val,
6048 #ifdef XtNarrowScrollbars
6049 XtNarrowScrollbars, (XtPointer) &xaw3d_arrow_scroll,
6050 #endif
6051 XtNpickTop, (XtPointer) &xaw3d_pick_top, NULL);
6052 if (xaw3d_arrow_scroll || val == initial)
6053 { /* ARROW_SCROLL */
6054 xaw3d_arrow_scroll = True;
6055 /* Isn't that just a personal preference ? --Stef */
6056 XtVaSetValues (widget, XtNcursorName, "top_left_arrow", NULL);
6060 /* Define callbacks. */
6061 XtAddCallback (widget, XtNjumpProc, xaw_jump_callback, (XtPointer) bar);
6062 XtAddCallback (widget, XtNscrollProc, xaw_scroll_callback,
6063 (XtPointer) bar);
6065 /* Realize the widget. Only after that is the X window created. */
6066 XtRealizeWidget (widget);
6068 #endif /* !USE_MOTIF */
6070 /* Install an action hook that lets us detect when the user
6071 finishes interacting with a scroll bar. */
6072 if (action_hook_id == 0)
6073 action_hook_id = XtAppAddActionHook (Xt_app_con, xt_action_hook, 0);
6075 /* Remember X window and widget in the scroll bar vector. */
6076 SET_SCROLL_BAR_X_WIDGET (bar, widget);
6077 xwindow = XtWindow (widget);
6078 bar->x_window = xwindow;
6079 bar->whole = 1;
6080 bar->horizontal = false;
6082 unblock_input ();
6085 static void
6086 x_create_horizontal_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
6088 Window xwindow;
6089 Widget widget;
6090 Arg av[20];
6091 int ac = 0;
6092 const char *scroll_bar_name = SCROLL_BAR_HORIZONTAL_NAME;
6093 unsigned long pixel;
6095 block_input ();
6097 #ifdef USE_MOTIF
6098 /* Set resources. Create the widget. */
6099 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
6100 XtSetArg (av[ac], XmNminimum, 0); ++ac;
6101 XtSetArg (av[ac], XmNmaximum, XM_SB_MAX); ++ac;
6102 XtSetArg (av[ac], XmNorientation, XmHORIZONTAL); ++ac;
6103 XtSetArg (av[ac], XmNprocessingDirection, XmMAX_ON_RIGHT), ++ac;
6104 XtSetArg (av[ac], XmNincrement, 1); ++ac;
6105 XtSetArg (av[ac], XmNpageIncrement, 1); ++ac;
6107 pixel = f->output_data.x->scroll_bar_foreground_pixel;
6108 if (pixel != -1)
6110 XtSetArg (av[ac], XmNforeground, pixel);
6111 ++ac;
6114 pixel = f->output_data.x->scroll_bar_background_pixel;
6115 if (pixel != -1)
6117 XtSetArg (av[ac], XmNbackground, pixel);
6118 ++ac;
6121 widget = XmCreateScrollBar (f->output_data.x->edit_widget,
6122 (char *) scroll_bar_name, av, ac);
6124 /* Add one callback for everything that can happen. */
6125 XtAddCallback (widget, XmNdecrementCallback, xm_scroll_callback,
6126 (XtPointer) bar);
6127 XtAddCallback (widget, XmNdragCallback, xm_scroll_callback,
6128 (XtPointer) bar);
6129 XtAddCallback (widget, XmNincrementCallback, xm_scroll_callback,
6130 (XtPointer) bar);
6131 XtAddCallback (widget, XmNpageDecrementCallback, xm_scroll_callback,
6132 (XtPointer) bar);
6133 XtAddCallback (widget, XmNpageIncrementCallback, xm_scroll_callback,
6134 (XtPointer) bar);
6135 XtAddCallback (widget, XmNtoBottomCallback, xm_scroll_callback,
6136 (XtPointer) bar);
6137 XtAddCallback (widget, XmNtoTopCallback, xm_scroll_callback,
6138 (XtPointer) bar);
6140 /* Realize the widget. Only after that is the X window created. */
6141 XtRealizeWidget (widget);
6143 /* Set the cursor to an arrow. I didn't find a resource to do that.
6144 And I'm wondering why it hasn't an arrow cursor by default. */
6145 XDefineCursor (XtDisplay (widget), XtWindow (widget),
6146 f->output_data.x->nontext_cursor);
6148 #else /* !USE_MOTIF i.e. use Xaw */
6150 /* Set resources. Create the widget. The background of the
6151 Xaw3d scroll bar widget is a little bit light for my taste.
6152 We don't alter it here to let users change it according
6153 to their taste with `emacs*verticalScrollBar.background: xxx'. */
6154 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
6155 XtSetArg (av[ac], XtNorientation, XtorientHorizontal); ++ac;
6156 /* For smoother scrolling with Xaw3d -sm */
6157 /* XtSetArg (av[ac], XtNpickTop, True); ++ac; */
6159 pixel = f->output_data.x->scroll_bar_foreground_pixel;
6160 if (pixel != -1)
6162 XtSetArg (av[ac], XtNforeground, pixel);
6163 ++ac;
6166 pixel = f->output_data.x->scroll_bar_background_pixel;
6167 if (pixel != -1)
6169 XtSetArg (av[ac], XtNbackground, pixel);
6170 ++ac;
6173 /* Top/bottom shadow colors. */
6175 /* Allocate them, if necessary. */
6176 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1)
6178 pixel = f->output_data.x->scroll_bar_background_pixel;
6179 if (pixel != -1)
6181 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
6182 FRAME_X_COLORMAP (f),
6183 &pixel, 1.2, 0x8000))
6184 pixel = -1;
6185 f->output_data.x->scroll_bar_top_shadow_pixel = pixel;
6188 if (f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
6190 pixel = f->output_data.x->scroll_bar_background_pixel;
6191 if (pixel != -1)
6193 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
6194 FRAME_X_COLORMAP (f),
6195 &pixel, 0.6, 0x4000))
6196 pixel = -1;
6197 f->output_data.x->scroll_bar_bottom_shadow_pixel = pixel;
6201 #ifdef XtNbeNiceToColormap
6202 /* Tell the toolkit about them. */
6203 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1
6204 || f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
6205 /* We tried to allocate a color for the top/bottom shadow, and
6206 failed, so tell Xaw3d to use dithering instead. */
6207 /* But only if we have a small colormap. Xaw3d can allocate nice
6208 colors itself. */
6210 XtSetArg (av[ac], XtNbeNiceToColormap,
6211 DefaultDepthOfScreen (FRAME_X_SCREEN (f)) < 16);
6212 ++ac;
6214 else
6215 /* Tell what colors Xaw3d should use for the top/bottom shadow, to
6216 be more consistent with other emacs 3d colors, and since Xaw3d is
6217 not good at dealing with allocation failure. */
6219 /* This tells Xaw3d to use real colors instead of dithering for
6220 the shadows. */
6221 XtSetArg (av[ac], XtNbeNiceToColormap, False);
6222 ++ac;
6224 /* Specify the colors. */
6225 pixel = f->output_data.x->scroll_bar_top_shadow_pixel;
6226 if (pixel != -1)
6228 XtSetArg (av[ac], XtNtopShadowPixel, pixel);
6229 ++ac;
6231 pixel = f->output_data.x->scroll_bar_bottom_shadow_pixel;
6232 if (pixel != -1)
6234 XtSetArg (av[ac], XtNbottomShadowPixel, pixel);
6235 ++ac;
6238 #endif
6240 widget = XtCreateWidget (scroll_bar_name, scrollbarWidgetClass,
6241 f->output_data.x->edit_widget, av, ac);
6244 char const *initial = "";
6245 char const *val = initial;
6246 XtVaGetValues (widget, XtNscrollVCursor, (XtPointer) &val,
6247 #ifdef XtNarrowScrollbars
6248 XtNarrowScrollbars, (XtPointer) &xaw3d_arrow_scroll,
6249 #endif
6250 XtNpickTop, (XtPointer) &xaw3d_pick_top, NULL);
6251 if (xaw3d_arrow_scroll || val == initial)
6252 { /* ARROW_SCROLL */
6253 xaw3d_arrow_scroll = True;
6254 /* Isn't that just a personal preference ? --Stef */
6255 XtVaSetValues (widget, XtNcursorName, "top_left_arrow", NULL);
6259 /* Define callbacks. */
6260 XtAddCallback (widget, XtNjumpProc, xaw_jump_callback, (XtPointer) bar);
6261 XtAddCallback (widget, XtNscrollProc, xaw_scroll_callback,
6262 (XtPointer) bar);
6264 /* Realize the widget. Only after that is the X window created. */
6265 XtRealizeWidget (widget);
6267 #endif /* !USE_MOTIF */
6269 /* Install an action hook that lets us detect when the user
6270 finishes interacting with a scroll bar. */
6271 if (horizontal_action_hook_id == 0)
6272 horizontal_action_hook_id
6273 = XtAppAddActionHook (Xt_app_con, xt_horizontal_action_hook, 0);
6275 /* Remember X window and widget in the scroll bar vector. */
6276 SET_SCROLL_BAR_X_WIDGET (bar, widget);
6277 xwindow = XtWindow (widget);
6278 bar->x_window = xwindow;
6279 bar->whole = 1;
6280 bar->horizontal = true;
6282 unblock_input ();
6284 #endif /* not USE_GTK */
6287 /* Set the thumb size and position of scroll bar BAR. We are currently
6288 displaying PORTION out of a whole WHOLE, and our position POSITION. */
6290 #ifdef USE_GTK
6291 static void
6292 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position, int whole)
6294 xg_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
6297 static void
6298 x_set_toolkit_horizontal_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position, int whole)
6300 xg_set_toolkit_horizontal_scroll_bar_thumb (bar, portion, position, whole);
6303 #else /* not USE_GTK */
6304 static void
6305 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position,
6306 int whole)
6308 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6309 Widget widget = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
6310 float top, shown;
6312 block_input ();
6314 #ifdef USE_MOTIF
6316 if (scroll_bar_adjust_thumb_portion_p)
6318 /* We use an estimate of 30 chars per line rather than the real
6319 `portion' value. This has the disadvantage that the thumb size
6320 is not very representative, but it makes our life a lot easier.
6321 Otherwise, we have to constantly adjust the thumb size, which
6322 we can't always do quickly enough: while dragging, the size of
6323 the thumb might prevent the user from dragging the thumb all the
6324 way to the end. but Motif and some versions of Xaw3d don't allow
6325 updating the thumb size while dragging. Also, even if we can update
6326 its size, the update will often happen too late.
6327 If you don't believe it, check out revision 1.650 of xterm.c to see
6328 what hoops we were going through and the still poor behavior we got. */
6329 portion = WINDOW_TOTAL_LINES (XWINDOW (bar->window)) * 30;
6330 /* When the thumb is at the bottom, position == whole.
6331 So we need to increase `whole' to make space for the thumb. */
6332 whole += portion;
6335 if (whole <= 0)
6336 top = 0, shown = 1;
6337 else
6339 top = (float) position / whole;
6340 shown = (float) portion / whole;
6343 if (bar->dragging == -1)
6345 int size, value;
6347 /* Slider size. Must be in the range [1 .. MAX - MIN] where MAX
6348 is the scroll bar's maximum and MIN is the scroll bar's minimum
6349 value. */
6350 size = clip_to_bounds (1, shown * XM_SB_MAX, XM_SB_MAX);
6352 /* Position. Must be in the range [MIN .. MAX - SLIDER_SIZE]. */
6353 value = top * XM_SB_MAX;
6354 value = min (value, XM_SB_MAX - size);
6356 XmScrollBarSetValues (widget, value, size, 0, 0, False);
6358 #else /* !USE_MOTIF i.e. use Xaw */
6360 if (whole == 0)
6361 top = 0, shown = 1;
6362 else
6364 top = (float) position / whole;
6365 shown = (float) portion / whole;
6369 float old_top, old_shown;
6370 Dimension height;
6371 XtVaGetValues (widget,
6372 XtNtopOfThumb, &old_top,
6373 XtNshown, &old_shown,
6374 XtNheight, &height,
6375 NULL);
6377 /* Massage the top+shown values. */
6378 if (bar->dragging == -1 || bar->last_seen_part == scroll_bar_down_arrow)
6379 top = max (0, min (1, top));
6380 else
6381 top = old_top;
6382 #if ! defined (HAVE_XAW3D)
6383 /* With Xaw, 'top' values too closer to 1.0 may
6384 cause the thumb to disappear. Fix that. */
6385 top = min (top, 0.99f);
6386 #endif
6387 /* Keep two pixels available for moving the thumb down. */
6388 shown = max (0, min (1 - top - (2.0f / height), shown));
6389 #if ! defined (HAVE_XAW3D)
6390 /* Likewise with too small 'shown'. */
6391 shown = max (shown, 0.01f);
6392 #endif
6394 /* If the call to XawScrollbarSetThumb below doesn't seem to
6395 work, check that 'NARROWPROTO' is defined in src/config.h.
6396 If this is not so, most likely you need to fix configure. */
6397 if (top != old_top || shown != old_shown)
6399 if (bar->dragging == -1)
6400 XawScrollbarSetThumb (widget, top, shown);
6401 else
6403 /* Try to make the scrolling a tad smoother. */
6404 if (!xaw3d_pick_top)
6405 shown = min (shown, old_shown);
6407 XawScrollbarSetThumb (widget, top, shown);
6411 #endif /* !USE_MOTIF */
6413 unblock_input ();
6416 static void
6417 x_set_toolkit_horizontal_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position,
6418 int whole)
6420 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6421 Widget widget = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
6422 float top, shown;
6424 block_input ();
6426 #ifdef USE_MOTIF
6427 bar->whole = whole;
6428 shown = (float) portion / whole;
6429 top = (float) position / (whole - portion);
6431 int size = clip_to_bounds (1, shown * XM_SB_MAX, XM_SB_MAX);
6432 int value = clip_to_bounds (0, top * (XM_SB_MAX - size), XM_SB_MAX - size);
6434 XmScrollBarSetValues (widget, value, size, 0, 0, False);
6436 #else /* !USE_MOTIF i.e. use Xaw */
6437 bar->whole = whole;
6438 if (whole == 0)
6439 top = 0, shown = 1;
6440 else
6442 top = (float) position / whole;
6443 shown = (float) portion / whole;
6447 float old_top, old_shown;
6448 Dimension height;
6449 XtVaGetValues (widget,
6450 XtNtopOfThumb, &old_top,
6451 XtNshown, &old_shown,
6452 XtNheight, &height,
6453 NULL);
6455 #if false
6456 /* Massage the top+shown values. */
6457 if (bar->dragging == -1 || bar->last_seen_part == scroll_bar_down_arrow)
6458 top = max (0, min (1, top));
6459 else
6460 top = old_top;
6461 #if ! defined (HAVE_XAW3D)
6462 /* With Xaw, 'top' values too closer to 1.0 may
6463 cause the thumb to disappear. Fix that. */
6464 top = min (top, 0.99f);
6465 #endif
6466 /* Keep two pixels available for moving the thumb down. */
6467 shown = max (0, min (1 - top - (2.0f / height), shown));
6468 #if ! defined (HAVE_XAW3D)
6469 /* Likewise with too small 'shown'. */
6470 shown = max (shown, 0.01f);
6471 #endif
6472 #endif
6474 /* If the call to XawScrollbarSetThumb below doesn't seem to
6475 work, check that 'NARROWPROTO' is defined in src/config.h.
6476 If this is not so, most likely you need to fix configure. */
6477 XawScrollbarSetThumb (widget, top, shown);
6478 #if false
6479 if (top != old_top || shown != old_shown)
6481 if (bar->dragging == -1)
6482 XawScrollbarSetThumb (widget, top, shown);
6483 else
6485 /* Try to make the scrolling a tad smoother. */
6486 if (!xaw3d_pick_top)
6487 shown = min (shown, old_shown);
6489 XawScrollbarSetThumb (widget, top, shown);
6492 #endif
6494 #endif /* !USE_MOTIF */
6496 unblock_input ();
6498 #endif /* not USE_GTK */
6500 #endif /* USE_TOOLKIT_SCROLL_BARS */
6504 /************************************************************************
6505 Scroll bars, general
6506 ************************************************************************/
6508 /* Create a scroll bar and return the scroll bar vector for it. W is
6509 the Emacs window on which to create the scroll bar. TOP, LEFT,
6510 WIDTH and HEIGHT are the pixel coordinates and dimensions of the
6511 scroll bar. */
6513 static struct scroll_bar *
6514 x_scroll_bar_create (struct window *w, int top, int left,
6515 int width, int height, bool horizontal)
6517 struct frame *f = XFRAME (w->frame);
6518 struct scroll_bar *bar
6519 = ALLOCATE_PSEUDOVECTOR (struct scroll_bar, x_window, PVEC_OTHER);
6520 Lisp_Object barobj;
6522 block_input ();
6524 #ifdef USE_TOOLKIT_SCROLL_BARS
6525 if (horizontal)
6526 x_create_horizontal_toolkit_scroll_bar (f, bar);
6527 else
6528 x_create_toolkit_scroll_bar (f, bar);
6529 #else /* not USE_TOOLKIT_SCROLL_BARS */
6531 XSetWindowAttributes a;
6532 unsigned long mask;
6533 Window window;
6535 a.background_pixel = f->output_data.x->scroll_bar_background_pixel;
6536 if (a.background_pixel == -1)
6537 a.background_pixel = FRAME_BACKGROUND_PIXEL (f);
6539 a.event_mask = (ButtonPressMask | ButtonReleaseMask
6540 | ButtonMotionMask | PointerMotionHintMask
6541 | ExposureMask);
6542 a.cursor = FRAME_DISPLAY_INFO (f)->vertical_scroll_bar_cursor;
6544 mask = (CWBackPixel | CWEventMask | CWCursor);
6546 /* Clear the area of W that will serve as a scroll bar. This is
6547 for the case that a window has been split horizontally. In
6548 this case, no clear_frame is generated to reduce flickering. */
6549 if (width > 0 && window_box_height (w) > 0)
6550 x_clear_area (f, left, top, width, window_box_height (w));
6552 window = XCreateWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
6553 /* Position and size of scroll bar. */
6554 left, top, width, height,
6555 /* Border width, depth, class, and visual. */
6557 CopyFromParent,
6558 CopyFromParent,
6559 CopyFromParent,
6560 /* Attributes. */
6561 mask, &a);
6562 bar->x_window = window;
6564 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6566 XSETWINDOW (bar->window, w);
6567 bar->top = top;
6568 bar->left = left;
6569 bar->width = width;
6570 bar->height = height;
6571 bar->start = 0;
6572 bar->end = 0;
6573 bar->dragging = -1;
6574 bar->horizontal = horizontal;
6575 #if defined (USE_TOOLKIT_SCROLL_BARS) && defined (USE_LUCID)
6576 bar->last_seen_part = scroll_bar_nowhere;
6577 #endif
6579 /* Add bar to its frame's list of scroll bars. */
6580 bar->next = FRAME_SCROLL_BARS (f);
6581 bar->prev = Qnil;
6582 XSETVECTOR (barobj, bar);
6583 fset_scroll_bars (f, barobj);
6584 if (!NILP (bar->next))
6585 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
6587 /* Map the window/widget. */
6588 #ifdef USE_TOOLKIT_SCROLL_BARS
6590 #ifdef USE_GTK
6591 if (horizontal)
6592 xg_update_horizontal_scrollbar_pos (f, bar->x_window, top,
6593 left, width, max (height, 1));
6594 else
6595 xg_update_scrollbar_pos (f, bar->x_window, top,
6596 left, width, max (height, 1));
6597 #else /* not USE_GTK */
6598 Widget scroll_bar = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
6599 XtConfigureWidget (scroll_bar, left, top, width, max (height, 1), 0);
6600 XtMapWidget (scroll_bar);
6601 /* Don't obscure any child frames. */
6602 XLowerWindow (FRAME_X_DISPLAY (f), bar->x_window);
6603 #endif /* not USE_GTK */
6605 #else /* not USE_TOOLKIT_SCROLL_BARS */
6606 XMapWindow (FRAME_X_DISPLAY (f), bar->x_window);
6607 /* Don't obscure any child frames. */
6608 XLowerWindow (FRAME_X_DISPLAY (f), bar->x_window);
6609 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6611 unblock_input ();
6612 return bar;
6616 #ifndef USE_TOOLKIT_SCROLL_BARS
6618 /* Draw BAR's handle in the proper position.
6620 If the handle is already drawn from START to END, don't bother
6621 redrawing it, unless REBUILD; in that case, always
6622 redraw it. (REBUILD is handy for drawing the handle after expose
6623 events.)
6625 Normally, we want to constrain the start and end of the handle to
6626 fit inside its rectangle, but if the user is dragging the scroll
6627 bar handle, we want to let them drag it down all the way, so that
6628 the bar's top is as far down as it goes; otherwise, there's no way
6629 to move to the very end of the buffer. */
6631 static void
6632 x_scroll_bar_set_handle (struct scroll_bar *bar, int start, int end,
6633 bool rebuild)
6635 bool dragging = bar->dragging != -1;
6636 Window w = bar->x_window;
6637 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6638 GC gc = f->output_data.x->normal_gc;
6640 /* If the display is already accurate, do nothing. */
6641 if (! rebuild
6642 && start == bar->start
6643 && end == bar->end)
6644 return;
6646 block_input ();
6649 int inside_width = VERTICAL_SCROLL_BAR_INSIDE_WIDTH (f, bar->width);
6650 int inside_height = VERTICAL_SCROLL_BAR_INSIDE_HEIGHT (f, bar->height);
6651 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
6653 /* Make sure the values are reasonable, and try to preserve
6654 the distance between start and end. */
6656 int length = end - start;
6658 if (start < 0)
6659 start = 0;
6660 else if (start > top_range)
6661 start = top_range;
6662 end = start + length;
6664 if (end < start)
6665 end = start;
6666 else if (end > top_range && ! dragging)
6667 end = top_range;
6670 /* Store the adjusted setting in the scroll bar. */
6671 bar->start = start;
6672 bar->end = end;
6674 /* Clip the end position, just for display. */
6675 if (end > top_range)
6676 end = top_range;
6678 /* Draw bottom positions VERTICAL_SCROLL_BAR_MIN_HANDLE pixels
6679 below top positions, to make sure the handle is always at least
6680 that many pixels tall. */
6681 end += VERTICAL_SCROLL_BAR_MIN_HANDLE;
6683 /* Draw the empty space above the handle. Note that we can't clear
6684 zero-height areas; that means "clear to end of window." */
6685 if ((inside_width > 0) && (start > 0))
6686 x_clear_area1 (FRAME_X_DISPLAY (f), w,
6687 VERTICAL_SCROLL_BAR_LEFT_BORDER,
6688 VERTICAL_SCROLL_BAR_TOP_BORDER,
6689 inside_width, start, False);
6691 /* Change to proper foreground color if one is specified. */
6692 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
6693 XSetForeground (FRAME_X_DISPLAY (f), gc,
6694 f->output_data.x->scroll_bar_foreground_pixel);
6696 /* Draw the handle itself. */
6697 XFillRectangle (FRAME_X_DISPLAY (f), w, gc,
6698 /* x, y, width, height */
6699 VERTICAL_SCROLL_BAR_LEFT_BORDER,
6700 VERTICAL_SCROLL_BAR_TOP_BORDER + start,
6701 inside_width, end - start);
6703 /* Restore the foreground color of the GC if we changed it above. */
6704 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
6705 XSetForeground (FRAME_X_DISPLAY (f), gc,
6706 FRAME_FOREGROUND_PIXEL (f));
6708 /* Draw the empty space below the handle. Note that we can't
6709 clear zero-height areas; that means "clear to end of window." */
6710 if ((inside_width > 0) && (end < inside_height))
6711 x_clear_area1 (FRAME_X_DISPLAY (f), w,
6712 VERTICAL_SCROLL_BAR_LEFT_BORDER,
6713 VERTICAL_SCROLL_BAR_TOP_BORDER + end,
6714 inside_width, inside_height - end, False);
6717 unblock_input ();
6720 #endif /* !USE_TOOLKIT_SCROLL_BARS */
6722 /* Destroy scroll bar BAR, and set its Emacs window's scroll bar to
6723 nil. */
6725 static void
6726 x_scroll_bar_remove (struct scroll_bar *bar)
6728 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6729 block_input ();
6731 #ifdef USE_TOOLKIT_SCROLL_BARS
6732 #ifdef USE_GTK
6733 xg_remove_scroll_bar (f, bar->x_window);
6734 #else /* not USE_GTK */
6735 XtDestroyWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar));
6736 #endif /* not USE_GTK */
6737 #else
6738 XDestroyWindow (FRAME_X_DISPLAY (f), bar->x_window);
6739 #endif
6741 /* Dissociate this scroll bar from its window. */
6742 if (bar->horizontal)
6743 wset_horizontal_scroll_bar (XWINDOW (bar->window), Qnil);
6744 else
6745 wset_vertical_scroll_bar (XWINDOW (bar->window), Qnil);
6747 unblock_input ();
6751 /* Set the handle of the vertical scroll bar for WINDOW to indicate
6752 that we are displaying PORTION characters out of a total of WHOLE
6753 characters, starting at POSITION. If WINDOW has no scroll bar,
6754 create one. */
6756 static void
6757 XTset_vertical_scroll_bar (struct window *w, int portion, int whole, int position)
6759 struct frame *f = XFRAME (w->frame);
6760 Lisp_Object barobj;
6761 struct scroll_bar *bar;
6762 int top, height, left, width;
6763 int window_y, window_height;
6765 /* Get window dimensions. */
6766 window_box (w, ANY_AREA, 0, &window_y, 0, &window_height);
6767 top = window_y;
6768 height = window_height;
6769 left = WINDOW_SCROLL_BAR_AREA_X (w);
6770 width = WINDOW_SCROLL_BAR_AREA_WIDTH (w);
6772 /* Does the scroll bar exist yet? */
6773 if (NILP (w->vertical_scroll_bar))
6775 if (width > 0 && height > 0)
6777 block_input ();
6778 x_clear_area (f, left, top, width, height);
6779 unblock_input ();
6782 bar = x_scroll_bar_create (w, top, left, width, max (height, 1), false);
6784 else
6786 /* It may just need to be moved and resized. */
6787 unsigned int mask = 0;
6789 bar = XSCROLL_BAR (w->vertical_scroll_bar);
6791 block_input ();
6793 if (left != bar->left)
6794 mask |= CWX;
6795 if (top != bar->top)
6796 mask |= CWY;
6797 if (width != bar->width)
6798 mask |= CWWidth;
6799 if (height != bar->height)
6800 mask |= CWHeight;
6802 #ifdef USE_TOOLKIT_SCROLL_BARS
6804 /* Move/size the scroll bar widget. */
6805 if (mask)
6807 /* Since toolkit scroll bars are smaller than the space reserved
6808 for them on the frame, we have to clear "under" them. */
6809 if (width > 0 && height > 0)
6810 x_clear_area (f, left, top, width, height);
6811 #ifdef USE_GTK
6812 xg_update_scrollbar_pos (f, bar->x_window, top,
6813 left, width, max (height, 1));
6814 #else /* not USE_GTK */
6815 XtConfigureWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar),
6816 left, top, width, max (height, 1), 0);
6817 #endif /* not USE_GTK */
6819 #else /* not USE_TOOLKIT_SCROLL_BARS */
6821 /* Move/size the scroll bar window. */
6822 if (mask)
6824 XWindowChanges wc;
6826 wc.x = left;
6827 wc.y = top;
6828 wc.width = width;
6829 wc.height = height;
6830 XConfigureWindow (FRAME_X_DISPLAY (f), bar->x_window,
6831 mask, &wc);
6834 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6836 /* Remember new settings. */
6837 bar->left = left;
6838 bar->top = top;
6839 bar->width = width;
6840 bar->height = height;
6842 unblock_input ();
6845 #ifdef USE_TOOLKIT_SCROLL_BARS
6846 x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
6847 #else /* not USE_TOOLKIT_SCROLL_BARS */
6848 /* Set the scroll bar's current state, unless we're currently being
6849 dragged. */
6850 if (bar->dragging == -1)
6852 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, height);
6854 if (whole == 0)
6855 x_scroll_bar_set_handle (bar, 0, top_range, false);
6856 else
6858 int start = ((double) position * top_range) / whole;
6859 int end = ((double) (position + portion) * top_range) / whole;
6860 x_scroll_bar_set_handle (bar, start, end, false);
6863 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6865 XSETVECTOR (barobj, bar);
6866 wset_vertical_scroll_bar (w, barobj);
6870 static void
6871 XTset_horizontal_scroll_bar (struct window *w, int portion, int whole, int position)
6873 struct frame *f = XFRAME (w->frame);
6874 Lisp_Object barobj;
6875 struct scroll_bar *bar;
6876 int top, height, left, width;
6877 int window_x, window_width;
6878 int pixel_width = WINDOW_PIXEL_WIDTH (w);
6880 /* Get window dimensions. */
6881 window_box (w, ANY_AREA, &window_x, 0, &window_width, 0);
6882 left = window_x;
6883 width = window_width;
6884 top = WINDOW_SCROLL_BAR_AREA_Y (w);
6885 height = WINDOW_SCROLL_BAR_AREA_HEIGHT (w);
6887 /* Does the scroll bar exist yet? */
6888 if (NILP (w->horizontal_scroll_bar))
6890 if (width > 0 && height > 0)
6892 block_input ();
6894 /* Clear also part between window_width and
6895 WINDOW_PIXEL_WIDTH. */
6896 x_clear_area (f, left, top, pixel_width, height);
6897 unblock_input ();
6900 bar = x_scroll_bar_create (w, top, left, width, height, true);
6902 else
6904 /* It may just need to be moved and resized. */
6905 unsigned int mask = 0;
6907 bar = XSCROLL_BAR (w->horizontal_scroll_bar);
6909 block_input ();
6911 if (left != bar->left)
6912 mask |= CWX;
6913 if (top != bar->top)
6914 mask |= CWY;
6915 if (width != bar->width)
6916 mask |= CWWidth;
6917 if (height != bar->height)
6918 mask |= CWHeight;
6920 #ifdef USE_TOOLKIT_SCROLL_BARS
6921 /* Move/size the scroll bar widget. */
6922 if (mask)
6924 /* Since toolkit scroll bars are smaller than the space reserved
6925 for them on the frame, we have to clear "under" them. */
6926 if (width > 0 && height > 0)
6927 x_clear_area (f,
6928 WINDOW_LEFT_EDGE_X (w), top,
6929 pixel_width - WINDOW_RIGHT_DIVIDER_WIDTH (w), height);
6930 #ifdef USE_GTK
6931 xg_update_horizontal_scrollbar_pos (f, bar->x_window, top, left,
6932 width, height);
6933 #else /* not USE_GTK */
6934 XtConfigureWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar),
6935 left, top, width, height, 0);
6936 #endif /* not USE_GTK */
6938 #else /* not USE_TOOLKIT_SCROLL_BARS */
6940 /* Clear areas not covered by the scroll bar because it's not as
6941 wide as the area reserved for it. This makes sure a
6942 previous mode line display is cleared after C-x 2 C-x 1, for
6943 example. */
6945 int area_height = WINDOW_CONFIG_SCROLL_BAR_HEIGHT (w);
6946 int rest = area_height - height;
6947 if (rest > 0 && width > 0)
6948 x_clear_area (f, left, top, width, rest);
6951 /* Move/size the scroll bar window. */
6952 if (mask)
6954 XWindowChanges wc;
6956 wc.x = left;
6957 wc.y = top;
6958 wc.width = width;
6959 wc.height = height;
6960 XConfigureWindow (FRAME_X_DISPLAY (f), bar->x_window,
6961 mask, &wc);
6964 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6966 /* Remember new settings. */
6967 bar->left = left;
6968 bar->top = top;
6969 bar->width = width;
6970 bar->height = height;
6972 unblock_input ();
6975 #ifdef USE_TOOLKIT_SCROLL_BARS
6976 x_set_toolkit_horizontal_scroll_bar_thumb (bar, portion, position, whole);
6977 #else /* not USE_TOOLKIT_SCROLL_BARS */
6978 /* Set the scroll bar's current state, unless we're currently being
6979 dragged. */
6980 if (bar->dragging == -1)
6982 int left_range = HORIZONTAL_SCROLL_BAR_LEFT_RANGE (f, width);
6984 if (whole == 0)
6985 x_scroll_bar_set_handle (bar, 0, left_range, false);
6986 else
6988 int start = ((double) position * left_range) / whole;
6989 int end = ((double) (position + portion) * left_range) / whole;
6990 x_scroll_bar_set_handle (bar, start, end, false);
6993 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6995 XSETVECTOR (barobj, bar);
6996 wset_horizontal_scroll_bar (w, barobj);
7000 /* The following three hooks are used when we're doing a thorough
7001 redisplay of the frame. We don't explicitly know which scroll bars
7002 are going to be deleted, because keeping track of when windows go
7003 away is a real pain - "Can you say set-window-configuration, boys
7004 and girls?" Instead, we just assert at the beginning of redisplay
7005 that *all* scroll bars are to be removed, and then save a scroll bar
7006 from the fiery pit when we actually redisplay its window. */
7008 /* Arrange for all scroll bars on FRAME to be removed at the next call
7009 to `*judge_scroll_bars_hook'. A scroll bar may be spared if
7010 `*redeem_scroll_bar_hook' is applied to its window before the judgment. */
7012 static void
7013 XTcondemn_scroll_bars (struct frame *frame)
7015 if (!NILP (FRAME_SCROLL_BARS (frame)))
7017 if (!NILP (FRAME_CONDEMNED_SCROLL_BARS (frame)))
7019 /* Prepend scrollbars to already condemned ones. */
7020 Lisp_Object last = FRAME_SCROLL_BARS (frame);
7022 while (!NILP (XSCROLL_BAR (last)->next))
7023 last = XSCROLL_BAR (last)->next;
7025 XSCROLL_BAR (last)->next = FRAME_CONDEMNED_SCROLL_BARS (frame);
7026 XSCROLL_BAR (FRAME_CONDEMNED_SCROLL_BARS (frame))->prev = last;
7029 fset_condemned_scroll_bars (frame, FRAME_SCROLL_BARS (frame));
7030 fset_scroll_bars (frame, Qnil);
7035 /* Un-mark WINDOW's scroll bar for deletion in this judgment cycle.
7036 Note that WINDOW isn't necessarily condemned at all. */
7038 static void
7039 XTredeem_scroll_bar (struct window *w)
7041 struct scroll_bar *bar;
7042 Lisp_Object barobj;
7043 struct frame *f;
7045 /* We can't redeem this window's scroll bar if it doesn't have one. */
7046 if (NILP (w->vertical_scroll_bar) && NILP (w->horizontal_scroll_bar))
7047 emacs_abort ();
7049 if (!NILP (w->vertical_scroll_bar) && WINDOW_HAS_VERTICAL_SCROLL_BAR (w))
7051 bar = XSCROLL_BAR (w->vertical_scroll_bar);
7052 /* Unlink it from the condemned list. */
7053 f = XFRAME (WINDOW_FRAME (w));
7054 if (NILP (bar->prev))
7056 /* If the prev pointer is nil, it must be the first in one of
7057 the lists. */
7058 if (EQ (FRAME_SCROLL_BARS (f), w->vertical_scroll_bar))
7059 /* It's not condemned. Everything's fine. */
7060 goto horizontal;
7061 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
7062 w->vertical_scroll_bar))
7063 fset_condemned_scroll_bars (f, bar->next);
7064 else
7065 /* If its prev pointer is nil, it must be at the front of
7066 one or the other! */
7067 emacs_abort ();
7069 else
7070 XSCROLL_BAR (bar->prev)->next = bar->next;
7072 if (! NILP (bar->next))
7073 XSCROLL_BAR (bar->next)->prev = bar->prev;
7075 bar->next = FRAME_SCROLL_BARS (f);
7076 bar->prev = Qnil;
7077 XSETVECTOR (barobj, bar);
7078 fset_scroll_bars (f, barobj);
7079 if (! NILP (bar->next))
7080 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
7083 horizontal:
7084 if (!NILP (w->horizontal_scroll_bar) && WINDOW_HAS_HORIZONTAL_SCROLL_BAR (w))
7086 bar = XSCROLL_BAR (w->horizontal_scroll_bar);
7087 /* Unlink it from the condemned list. */
7088 f = XFRAME (WINDOW_FRAME (w));
7089 if (NILP (bar->prev))
7091 /* If the prev pointer is nil, it must be the first in one of
7092 the lists. */
7093 if (EQ (FRAME_SCROLL_BARS (f), w->horizontal_scroll_bar))
7094 /* It's not condemned. Everything's fine. */
7095 return;
7096 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
7097 w->horizontal_scroll_bar))
7098 fset_condemned_scroll_bars (f, bar->next);
7099 else
7100 /* If its prev pointer is nil, it must be at the front of
7101 one or the other! */
7102 emacs_abort ();
7104 else
7105 XSCROLL_BAR (bar->prev)->next = bar->next;
7107 if (! NILP (bar->next))
7108 XSCROLL_BAR (bar->next)->prev = bar->prev;
7110 bar->next = FRAME_SCROLL_BARS (f);
7111 bar->prev = Qnil;
7112 XSETVECTOR (barobj, bar);
7113 fset_scroll_bars (f, barobj);
7114 if (! NILP (bar->next))
7115 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
7119 /* Remove all scroll bars on FRAME that haven't been saved since the
7120 last call to `*condemn_scroll_bars_hook'. */
7122 static void
7123 XTjudge_scroll_bars (struct frame *f)
7125 Lisp_Object bar, next;
7127 bar = FRAME_CONDEMNED_SCROLL_BARS (f);
7129 /* Clear out the condemned list now so we won't try to process any
7130 more events on the hapless scroll bars. */
7131 fset_condemned_scroll_bars (f, Qnil);
7133 for (; ! NILP (bar); bar = next)
7135 struct scroll_bar *b = XSCROLL_BAR (bar);
7137 x_scroll_bar_remove (b);
7139 next = b->next;
7140 b->next = b->prev = Qnil;
7143 /* Now there should be no references to the condemned scroll bars,
7144 and they should get garbage-collected. */
7148 #ifndef USE_TOOLKIT_SCROLL_BARS
7149 /* Handle an Expose or GraphicsExpose event on a scroll bar. This
7150 is a no-op when using toolkit scroll bars.
7152 This may be called from a signal handler, so we have to ignore GC
7153 mark bits. */
7155 static void
7156 x_scroll_bar_expose (struct scroll_bar *bar, const XEvent *event)
7158 Window w = bar->x_window;
7159 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
7160 GC gc = f->output_data.x->normal_gc;
7162 block_input ();
7164 x_scroll_bar_set_handle (bar, bar->start, bar->end, true);
7166 /* Switch to scroll bar foreground color. */
7167 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
7168 XSetForeground (FRAME_X_DISPLAY (f), gc,
7169 f->output_data.x->scroll_bar_foreground_pixel);
7171 /* Draw a one-pixel border just inside the edges of the scroll bar. */
7172 XDrawRectangle (FRAME_X_DISPLAY (f), w, gc,
7173 /* x, y, width, height */
7174 0, 0, bar->width - 1, bar->height - 1);
7176 /* Restore the foreground color of the GC if we changed it above. */
7177 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
7178 XSetForeground (FRAME_X_DISPLAY (f), gc,
7179 FRAME_FOREGROUND_PIXEL (f));
7181 unblock_input ();
7184 #endif /* not USE_TOOLKIT_SCROLL_BARS */
7186 /* Handle a mouse click on the scroll bar BAR. If *EMACS_EVENT's kind
7187 is set to something other than NO_EVENT, it is enqueued.
7189 This may be called from a signal handler, so we have to ignore GC
7190 mark bits. */
7193 static void
7194 x_scroll_bar_handle_click (struct scroll_bar *bar,
7195 const XEvent *event,
7196 struct input_event *emacs_event)
7198 if (! WINDOWP (bar->window))
7199 emacs_abort ();
7201 emacs_event->kind = (bar->horizontal
7202 ? HORIZONTAL_SCROLL_BAR_CLICK_EVENT
7203 : SCROLL_BAR_CLICK_EVENT);
7204 emacs_event->code = event->xbutton.button - Button1;
7205 emacs_event->modifiers
7206 = (x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO
7207 (XFRAME (WINDOW_FRAME (XWINDOW (bar->window)))),
7208 event->xbutton.state)
7209 | (event->type == ButtonRelease
7210 ? up_modifier
7211 : down_modifier));
7212 emacs_event->frame_or_window = bar->window;
7213 emacs_event->arg = Qnil;
7214 emacs_event->timestamp = event->xbutton.time;
7215 if (bar->horizontal)
7217 int left_range
7218 = HORIZONTAL_SCROLL_BAR_LEFT_RANGE (f, bar->width);
7219 int x = event->xbutton.x - HORIZONTAL_SCROLL_BAR_LEFT_BORDER;
7221 if (x < 0) x = 0;
7222 if (x > left_range) x = left_range;
7224 if (x < bar->start)
7225 emacs_event->part = scroll_bar_before_handle;
7226 else if (x < bar->end + HORIZONTAL_SCROLL_BAR_MIN_HANDLE)
7227 emacs_event->part = scroll_bar_horizontal_handle;
7228 else
7229 emacs_event->part = scroll_bar_after_handle;
7231 #ifndef USE_TOOLKIT_SCROLL_BARS
7232 /* If the user has released the handle, set it to its final position. */
7233 if (event->type == ButtonRelease && bar->dragging != -1)
7235 int new_start = - bar->dragging;
7236 int new_end = new_start + bar->end - bar->start;
7238 x_scroll_bar_set_handle (bar, new_start, new_end, false);
7239 bar->dragging = -1;
7241 #endif
7243 XSETINT (emacs_event->x, left_range);
7244 XSETINT (emacs_event->y, x);
7246 else
7248 int top_range
7249 = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
7250 int y = event->xbutton.y - VERTICAL_SCROLL_BAR_TOP_BORDER;
7252 if (y < 0) y = 0;
7253 if (y > top_range) y = top_range;
7255 if (y < bar->start)
7256 emacs_event->part = scroll_bar_above_handle;
7257 else if (y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
7258 emacs_event->part = scroll_bar_handle;
7259 else
7260 emacs_event->part = scroll_bar_below_handle;
7262 #ifndef USE_TOOLKIT_SCROLL_BARS
7263 /* If the user has released the handle, set it to its final position. */
7264 if (event->type == ButtonRelease && bar->dragging != -1)
7266 int new_start = y - bar->dragging;
7267 int new_end = new_start + bar->end - bar->start;
7269 x_scroll_bar_set_handle (bar, new_start, new_end, false);
7270 bar->dragging = -1;
7272 #endif
7274 XSETINT (emacs_event->x, y);
7275 XSETINT (emacs_event->y, top_range);
7279 #ifndef USE_TOOLKIT_SCROLL_BARS
7281 /* Handle some mouse motion while someone is dragging the scroll bar.
7283 This may be called from a signal handler, so we have to ignore GC
7284 mark bits. */
7286 static void
7287 x_scroll_bar_note_movement (struct scroll_bar *bar,
7288 const XMotionEvent *event)
7290 struct frame *f = XFRAME (XWINDOW (bar->window)->frame);
7291 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
7293 dpyinfo->last_mouse_movement_time = event->time;
7294 dpyinfo->last_mouse_scroll_bar = bar;
7295 f->mouse_moved = true;
7297 /* If we're dragging the bar, display it. */
7298 if (bar->dragging != -1)
7300 /* Where should the handle be now? */
7301 int new_start = event->y - bar->dragging;
7303 if (new_start != bar->start)
7305 int new_end = new_start + bar->end - bar->start;
7307 x_scroll_bar_set_handle (bar, new_start, new_end, false);
7312 #endif /* !USE_TOOLKIT_SCROLL_BARS */
7314 /* Return information to the user about the current position of the mouse
7315 on the scroll bar. */
7317 static void
7318 x_scroll_bar_report_motion (struct frame **fp, Lisp_Object *bar_window,
7319 enum scroll_bar_part *part, Lisp_Object *x,
7320 Lisp_Object *y, Time *timestamp)
7322 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (*fp);
7323 struct scroll_bar *bar = dpyinfo->last_mouse_scroll_bar;
7324 Window w = bar->x_window;
7325 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
7326 int win_x, win_y;
7327 Window dummy_window;
7328 int dummy_coord;
7329 unsigned int dummy_mask;
7331 block_input ();
7333 /* Get the mouse's position relative to the scroll bar window, and
7334 report that. */
7335 if (XQueryPointer (FRAME_X_DISPLAY (f), w,
7337 /* Root, child, root x and root y. */
7338 &dummy_window, &dummy_window,
7339 &dummy_coord, &dummy_coord,
7341 /* Position relative to scroll bar. */
7342 &win_x, &win_y,
7344 /* Mouse buttons and modifier keys. */
7345 &dummy_mask))
7347 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
7349 win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
7351 if (bar->dragging != -1)
7352 win_y -= bar->dragging;
7354 if (win_y < 0)
7355 win_y = 0;
7356 if (win_y > top_range)
7357 win_y = top_range;
7359 *fp = f;
7360 *bar_window = bar->window;
7362 if (bar->dragging != -1)
7363 *part = scroll_bar_handle;
7364 else if (win_y < bar->start)
7365 *part = scroll_bar_above_handle;
7366 else if (win_y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
7367 *part = scroll_bar_handle;
7368 else
7369 *part = scroll_bar_below_handle;
7371 XSETINT (*x, win_y);
7372 XSETINT (*y, top_range);
7374 f->mouse_moved = false;
7375 dpyinfo->last_mouse_scroll_bar = NULL;
7376 *timestamp = dpyinfo->last_mouse_movement_time;
7379 unblock_input ();
7383 /* Return information to the user about the current position of the mouse
7384 on the scroll bar. */
7386 static void
7387 x_horizontal_scroll_bar_report_motion (struct frame **fp, Lisp_Object *bar_window,
7388 enum scroll_bar_part *part, Lisp_Object *x,
7389 Lisp_Object *y, Time *timestamp)
7391 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (*fp);
7392 struct scroll_bar *bar = dpyinfo->last_mouse_scroll_bar;
7393 Window w = bar->x_window;
7394 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
7395 int win_x, win_y;
7396 Window dummy_window;
7397 int dummy_coord;
7398 unsigned int dummy_mask;
7400 block_input ();
7402 /* Get the mouse's position relative to the scroll bar window, and
7403 report that. */
7404 if (XQueryPointer (FRAME_X_DISPLAY (f), w,
7406 /* Root, child, root x and root y. */
7407 &dummy_window, &dummy_window,
7408 &dummy_coord, &dummy_coord,
7410 /* Position relative to scroll bar. */
7411 &win_x, &win_y,
7413 /* Mouse buttons and modifier keys. */
7414 &dummy_mask))
7416 int left_range = HORIZONTAL_SCROLL_BAR_LEFT_RANGE (f, bar->width);
7418 win_x -= HORIZONTAL_SCROLL_BAR_LEFT_BORDER;
7420 if (bar->dragging != -1)
7421 win_x -= bar->dragging;
7423 if (win_x < 0)
7424 win_x = 0;
7425 if (win_x > left_range)
7426 win_x = left_range;
7428 *fp = f;
7429 *bar_window = bar->window;
7431 if (bar->dragging != -1)
7432 *part = scroll_bar_horizontal_handle;
7433 else if (win_x < bar->start)
7434 *part = scroll_bar_before_handle;
7435 else if (win_x < bar->end + HORIZONTAL_SCROLL_BAR_MIN_HANDLE)
7436 *part = scroll_bar_handle;
7437 else
7438 *part = scroll_bar_after_handle;
7440 XSETINT (*y, win_x);
7441 XSETINT (*x, left_range);
7443 f->mouse_moved = false;
7444 dpyinfo->last_mouse_scroll_bar = NULL;
7445 *timestamp = dpyinfo->last_mouse_movement_time;
7448 unblock_input ();
7452 /* The screen has been cleared so we may have changed foreground or
7453 background colors, and the scroll bars may need to be redrawn.
7454 Clear out the scroll bars, and ask for expose events, so we can
7455 redraw them. */
7457 static void
7458 x_scroll_bar_clear (struct frame *f)
7460 #ifndef USE_TOOLKIT_SCROLL_BARS
7461 Lisp_Object bar;
7463 /* We can have scroll bars even if this is 0,
7464 if we just turned off scroll bar mode.
7465 But in that case we should not clear them. */
7466 if (FRAME_HAS_VERTICAL_SCROLL_BARS (f))
7467 for (bar = FRAME_SCROLL_BARS (f); VECTORP (bar);
7468 bar = XSCROLL_BAR (bar)->next)
7469 XClearArea (FRAME_X_DISPLAY (f),
7470 XSCROLL_BAR (bar)->x_window,
7471 0, 0, 0, 0, True);
7472 #endif /* not USE_TOOLKIT_SCROLL_BARS */
7475 #ifdef ENABLE_CHECKING
7477 /* Record the last 100 characters stored
7478 to help debug the loss-of-chars-during-GC problem. */
7480 static int temp_index;
7481 static short temp_buffer[100];
7483 #define STORE_KEYSYM_FOR_DEBUG(keysym) \
7484 if (temp_index == ARRAYELTS (temp_buffer)) \
7485 temp_index = 0; \
7486 temp_buffer[temp_index++] = (keysym)
7488 #else /* not ENABLE_CHECKING */
7490 #define STORE_KEYSYM_FOR_DEBUG(keysym) ((void)0)
7492 #endif /* ENABLE_CHECKING */
7494 /* Set this to nonzero to fake an "X I/O error"
7495 on a particular display. */
7497 static struct x_display_info *XTread_socket_fake_io_error;
7499 /* When we find no input here, we occasionally do a no-op command
7500 to verify that the X server is still running and we can still talk with it.
7501 We try all the open displays, one by one.
7502 This variable is used for cycling thru the displays. */
7504 static struct x_display_info *next_noop_dpyinfo;
7506 enum
7508 X_EVENT_NORMAL,
7509 X_EVENT_GOTO_OUT,
7510 X_EVENT_DROP
7513 /* Filter events for the current X input method.
7514 DPYINFO is the display this event is for.
7515 EVENT is the X event to filter.
7517 Returns non-zero if the event was filtered, caller shall not process
7518 this event further.
7519 Returns zero if event is wasn't filtered. */
7521 #ifdef HAVE_X_I18N
7522 static int
7523 x_filter_event (struct x_display_info *dpyinfo, XEvent *event)
7525 /* XFilterEvent returns non-zero if the input method has
7526 consumed the event. We pass the frame's X window to
7527 XFilterEvent because that's the one for which the IC
7528 was created. */
7530 struct frame *f1 = x_any_window_to_frame (dpyinfo,
7531 event->xclient.window);
7533 return XFilterEvent (event, f1 ? FRAME_X_WINDOW (f1) : None);
7535 #endif
7537 #ifdef USE_GTK
7538 static int current_count;
7539 static int current_finish;
7540 static struct input_event *current_hold_quit;
7542 /* This is the filter function invoked by the GTK event loop.
7543 It is invoked before the XEvent is translated to a GdkEvent,
7544 so we have a chance to act on the event before GTK. */
7545 static GdkFilterReturn
7546 event_handler_gdk (GdkXEvent *gxev, GdkEvent *ev, gpointer data)
7548 XEvent *xev = (XEvent *) gxev;
7550 block_input ();
7551 if (current_count >= 0)
7553 struct x_display_info *dpyinfo;
7555 dpyinfo = x_display_info_for_display (xev->xany.display);
7557 #ifdef HAVE_X_I18N
7558 /* Filter events for the current X input method.
7559 GTK calls XFilterEvent but not for key press and release,
7560 so we do it here. */
7561 if ((xev->type == KeyPress || xev->type == KeyRelease)
7562 && dpyinfo
7563 && x_filter_event (dpyinfo, xev))
7565 unblock_input ();
7566 return GDK_FILTER_REMOVE;
7568 #endif
7570 if (! dpyinfo)
7571 current_finish = X_EVENT_NORMAL;
7572 else
7573 current_count
7574 += handle_one_xevent (dpyinfo, xev, &current_finish,
7575 current_hold_quit);
7577 else
7578 current_finish = x_dispatch_event (xev, xev->xany.display);
7580 unblock_input ();
7582 if (current_finish == X_EVENT_GOTO_OUT || current_finish == X_EVENT_DROP)
7583 return GDK_FILTER_REMOVE;
7585 return GDK_FILTER_CONTINUE;
7587 #endif /* USE_GTK */
7590 static void xembed_send_message (struct frame *f, Time,
7591 enum xembed_message,
7592 long detail, long data1, long data2);
7594 static void
7595 x_net_wm_state (struct frame *f, Window window)
7597 int value = FULLSCREEN_NONE;
7598 Lisp_Object lval = Qnil;
7599 bool sticky = false;
7601 get_current_wm_state (f, window, &value, &sticky);
7603 switch (value)
7605 case FULLSCREEN_WIDTH:
7606 lval = Qfullwidth;
7607 break;
7608 case FULLSCREEN_HEIGHT:
7609 lval = Qfullheight;
7610 break;
7611 case FULLSCREEN_BOTH:
7612 lval = Qfullboth;
7613 break;
7614 case FULLSCREEN_MAXIMIZED:
7615 lval = Qmaximized;
7616 break;
7619 frame_size_history_add
7620 (f, Qx_net_wm_state, 0, 0,
7621 list2 (get_frame_param (f, Qfullscreen), lval));
7623 store_frame_param (f, Qfullscreen, lval);
7624 /** store_frame_param (f, Qsticky, sticky ? Qt : Qnil); **/
7627 /* Flip back buffers on any frames with undrawn content. */
7628 static void
7629 flush_dirty_back_buffers (void)
7631 block_input ();
7632 Lisp_Object tail, frame;
7633 FOR_EACH_FRAME (tail, frame)
7635 struct frame *f = XFRAME (frame);
7636 if (FRAME_LIVE_P (f) &&
7637 FRAME_X_P (f) &&
7638 FRAME_X_WINDOW (f) &&
7639 !FRAME_GARBAGED_P (f) &&
7640 !buffer_flipping_blocked_p () &&
7641 FRAME_X_NEED_BUFFER_FLIP (f))
7642 show_back_buffer (f);
7644 unblock_input ();
7647 /* Handles the XEvent EVENT on display DPYINFO.
7649 *FINISH is X_EVENT_GOTO_OUT if caller should stop reading events.
7650 *FINISH is zero if caller should continue reading events.
7651 *FINISH is X_EVENT_DROP if event should not be passed to the toolkit.
7652 *EVENT is unchanged unless we're processing KeyPress event.
7654 We return the number of characters stored into the buffer. */
7656 static int
7657 handle_one_xevent (struct x_display_info *dpyinfo,
7658 const XEvent *event,
7659 int *finish, struct input_event *hold_quit)
7661 union buffered_input_event inev;
7662 int count = 0;
7663 int do_help = 0;
7664 ptrdiff_t nbytes = 0;
7665 struct frame *any, *f = NULL;
7666 struct coding_system coding;
7667 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
7668 /* This holds the state XLookupString needs to implement dead keys
7669 and other tricks known as "compose processing". _X Window System_
7670 says that a portable program can't use this, but Stephen Gildea assures
7671 me that letting the compiler initialize it to zeros will work okay. */
7672 static XComposeStatus compose_status;
7673 XEvent configureEvent;
7674 XEvent next_event;
7676 USE_SAFE_ALLOCA;
7678 *finish = X_EVENT_NORMAL;
7680 EVENT_INIT (inev.ie);
7681 inev.ie.kind = NO_EVENT;
7682 inev.ie.arg = Qnil;
7684 any = x_any_window_to_frame (dpyinfo, event->xany.window);
7686 if (any && any->wait_event_type == event->type)
7687 any->wait_event_type = 0; /* Indicates we got it. */
7689 switch (event->type)
7691 case ClientMessage:
7693 if (event->xclient.message_type == dpyinfo->Xatom_wm_protocols
7694 && event->xclient.format == 32)
7696 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_take_focus)
7698 /* Use the value returned by x_any_window_to_frame
7699 because this could be the shell widget window
7700 if the frame has no title bar. */
7701 f = any;
7702 #ifdef HAVE_X_I18N
7703 /* Not quite sure this is needed -pd */
7704 if (f && FRAME_XIC (f))
7705 XSetICFocus (FRAME_XIC (f));
7706 #endif
7707 #if false
7708 /* Emacs sets WM hints whose `input' field is `true'. This
7709 instructs the WM to set the input focus automatically for
7710 Emacs with a call to XSetInputFocus. Setting WM_TAKE_FOCUS
7711 tells the WM to send us a ClientMessage WM_TAKE_FOCUS after
7712 it has set the focus. So, XSetInputFocus below is not
7713 needed.
7715 The call to XSetInputFocus below has also caused trouble. In
7716 cases where the XSetInputFocus done by the WM and the one
7717 below are temporally close (on a fast machine), the call
7718 below can generate additional FocusIn events which confuse
7719 Emacs. */
7721 /* Since we set WM_TAKE_FOCUS, we must call
7722 XSetInputFocus explicitly. But not if f is null,
7723 since that might be an event for a deleted frame. */
7724 if (f)
7726 Display *d = event->xclient.display;
7727 /* Catch and ignore errors, in case window has been
7728 iconified by a window manager such as GWM. */
7729 x_catch_errors (d);
7730 XSetInputFocus (d, event->xclient.window,
7731 /* The ICCCM says this is
7732 the only valid choice. */
7733 RevertToParent,
7734 event->xclient.data.l[1]);
7735 x_uncatch_errors ();
7737 /* Not certain about handling scroll bars here */
7738 #endif
7739 goto done;
7742 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_save_yourself)
7744 /* Save state modify the WM_COMMAND property to
7745 something which can reinstate us. This notifies
7746 the session manager, who's looking for such a
7747 PropertyNotify. Can restart processing when
7748 a keyboard or mouse event arrives. */
7749 /* If we have a session manager, don't set this.
7750 KDE will then start two Emacsen, one for the
7751 session manager and one for this. */
7752 #ifdef HAVE_X_SM
7753 if (! x_session_have_connection ())
7754 #endif
7756 f = x_top_window_to_frame (dpyinfo,
7757 event->xclient.window);
7758 /* This is just so we only give real data once
7759 for a single Emacs process. */
7760 if (f == SELECTED_FRAME ())
7761 XSetCommand (FRAME_X_DISPLAY (f),
7762 event->xclient.window,
7763 initial_argv, initial_argc);
7764 else if (f)
7765 XSetCommand (FRAME_X_DISPLAY (f),
7766 event->xclient.window,
7767 0, 0);
7769 goto done;
7772 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_delete_window)
7774 f = any;
7775 if (!f)
7776 goto OTHER; /* May be a dialog that is to be removed */
7778 inev.ie.kind = DELETE_WINDOW_EVENT;
7779 XSETFRAME (inev.ie.frame_or_window, f);
7780 goto done;
7783 goto done;
7786 if (event->xclient.message_type == dpyinfo->Xatom_wm_configure_denied)
7787 goto done;
7789 if (event->xclient.message_type == dpyinfo->Xatom_wm_window_moved)
7791 int new_x, new_y;
7792 f = x_window_to_frame (dpyinfo, event->xclient.window);
7794 new_x = event->xclient.data.s[0];
7795 new_y = event->xclient.data.s[1];
7797 if (f)
7799 f->left_pos = new_x;
7800 f->top_pos = new_y;
7802 goto done;
7805 #ifdef X_TOOLKIT_EDITRES
7806 if (event->xclient.message_type == dpyinfo->Xatom_editres)
7808 f = any;
7809 if (f)
7810 _XEditResCheckMessages (f->output_data.x->widget,
7811 NULL, (XEvent *) event, NULL);
7812 goto done;
7814 #endif /* X_TOOLKIT_EDITRES */
7816 if (event->xclient.message_type == dpyinfo->Xatom_DONE
7817 || event->xclient.message_type == dpyinfo->Xatom_PAGE)
7819 /* Ghostview job completed. Kill it. We could
7820 reply with "Next" if we received "Page", but we
7821 currently never do because we are interested in
7822 images, only, which should have 1 page. */
7823 Pixmap pixmap = (Pixmap) event->xclient.data.l[1];
7824 f = x_window_to_frame (dpyinfo, event->xclient.window);
7825 if (!f)
7826 goto OTHER;
7827 x_kill_gs_process (pixmap, f);
7828 expose_frame (f, 0, 0, 0, 0);
7829 goto done;
7832 #ifdef USE_TOOLKIT_SCROLL_BARS
7833 /* Scroll bar callbacks send a ClientMessage from which
7834 we construct an input_event. */
7835 if (event->xclient.message_type == dpyinfo->Xatom_Scrollbar)
7837 x_scroll_bar_to_input_event (event, &inev.ie);
7838 *finish = X_EVENT_GOTO_OUT;
7839 goto done;
7841 else if (event->xclient.message_type == dpyinfo->Xatom_Horizontal_Scrollbar)
7843 x_horizontal_scroll_bar_to_input_event (event, &inev.ie);
7844 *finish = X_EVENT_GOTO_OUT;
7845 goto done;
7847 #endif /* USE_TOOLKIT_SCROLL_BARS */
7849 /* XEmbed messages from the embedder (if any). */
7850 if (event->xclient.message_type == dpyinfo->Xatom_XEMBED)
7852 enum xembed_message msg = event->xclient.data.l[1];
7853 if (msg == XEMBED_FOCUS_IN || msg == XEMBED_FOCUS_OUT)
7854 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
7856 *finish = X_EVENT_GOTO_OUT;
7857 goto done;
7860 xft_settings_event (dpyinfo, event);
7862 f = any;
7863 if (!f)
7864 goto OTHER;
7865 if (x_handle_dnd_message (f, &event->xclient, dpyinfo, &inev.ie))
7866 *finish = X_EVENT_DROP;
7868 break;
7870 case SelectionNotify:
7871 x_display_set_last_user_time (dpyinfo, event->xselection.time);
7872 #ifdef USE_X_TOOLKIT
7873 if (! x_window_to_frame (dpyinfo, event->xselection.requestor))
7874 goto OTHER;
7875 #endif /* not USE_X_TOOLKIT */
7876 x_handle_selection_notify (&event->xselection);
7877 break;
7879 case SelectionClear: /* Someone has grabbed ownership. */
7880 x_display_set_last_user_time (dpyinfo, event->xselectionclear.time);
7881 #ifdef USE_X_TOOLKIT
7882 if (! x_window_to_frame (dpyinfo, event->xselectionclear.window))
7883 goto OTHER;
7884 #endif /* USE_X_TOOLKIT */
7886 const XSelectionClearEvent *eventp = &event->xselectionclear;
7888 inev.sie.kind = SELECTION_CLEAR_EVENT;
7889 SELECTION_EVENT_DPYINFO (&inev.sie) = dpyinfo;
7890 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
7891 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
7893 break;
7895 case SelectionRequest: /* Someone wants our selection. */
7896 x_display_set_last_user_time (dpyinfo, event->xselectionrequest.time);
7897 #ifdef USE_X_TOOLKIT
7898 if (!x_window_to_frame (dpyinfo, event->xselectionrequest.owner))
7899 goto OTHER;
7900 #endif /* USE_X_TOOLKIT */
7902 const XSelectionRequestEvent *eventp = &event->xselectionrequest;
7904 inev.sie.kind = SELECTION_REQUEST_EVENT;
7905 SELECTION_EVENT_DPYINFO (&inev.sie) = dpyinfo;
7906 SELECTION_EVENT_REQUESTOR (&inev.sie) = eventp->requestor;
7907 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
7908 SELECTION_EVENT_TARGET (&inev.sie) = eventp->target;
7909 SELECTION_EVENT_PROPERTY (&inev.sie) = eventp->property;
7910 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
7912 break;
7914 case PropertyNotify:
7915 x_display_set_last_user_time (dpyinfo, event->xproperty.time);
7916 f = x_top_window_to_frame (dpyinfo, event->xproperty.window);
7917 if (f && event->xproperty.atom == dpyinfo->Xatom_net_wm_state)
7919 bool not_hidden = x_handle_net_wm_state (f, &event->xproperty);
7920 if (not_hidden && FRAME_ICONIFIED_P (f))
7922 /* Gnome shell does not iconify us when C-z is pressed.
7923 It hides the frame. So if our state says we aren't
7924 hidden anymore, treat it as deiconified. */
7925 SET_FRAME_VISIBLE (f, 1);
7926 SET_FRAME_ICONIFIED (f, false);
7927 f->output_data.x->has_been_visible = true;
7928 inev.ie.kind = DEICONIFY_EVENT;
7929 XSETFRAME (inev.ie.frame_or_window, f);
7931 else if (! not_hidden && ! FRAME_ICONIFIED_P (f))
7933 SET_FRAME_VISIBLE (f, 0);
7934 SET_FRAME_ICONIFIED (f, true);
7935 inev.ie.kind = ICONIFY_EVENT;
7936 XSETFRAME (inev.ie.frame_or_window, f);
7940 x_handle_property_notify (&event->xproperty);
7941 xft_settings_event (dpyinfo, event);
7942 goto OTHER;
7944 case ReparentNotify:
7945 f = x_top_window_to_frame (dpyinfo, event->xreparent.window);
7946 if (f)
7948 /* Maybe we shouldn't set this for child frames ?? */
7949 f->output_data.x->parent_desc = event->xreparent.parent;
7950 if (!FRAME_PARENT_FRAME (f))
7951 x_real_positions (f, &f->left_pos, &f->top_pos);
7952 else
7954 Window root;
7955 unsigned int dummy_uint;
7957 block_input ();
7958 XGetGeometry (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
7959 &root, &f->left_pos, &f->top_pos,
7960 &dummy_uint, &dummy_uint, &dummy_uint, &dummy_uint);
7961 unblock_input ();
7964 /* Perhaps reparented due to a WM restart. Reset this. */
7965 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_UNKNOWN;
7966 FRAME_DISPLAY_INFO (f)->net_supported_window = 0;
7968 x_set_frame_alpha (f);
7970 goto OTHER;
7972 case Expose:
7973 f = x_window_to_frame (dpyinfo, event->xexpose.window);
7974 if (f)
7976 if (!FRAME_VISIBLE_P (f))
7978 block_input ();
7979 SET_FRAME_VISIBLE (f, 1);
7980 SET_FRAME_ICONIFIED (f, false);
7981 if (FRAME_X_DOUBLE_BUFFERED_P (f))
7982 font_drop_xrender_surfaces (f);
7983 f->output_data.x->has_been_visible = true;
7984 SET_FRAME_GARBAGED (f);
7985 unblock_input ();
7987 else if (FRAME_GARBAGED_P (f))
7989 #ifdef USE_GTK
7990 /* Go around the back buffer and manually clear the
7991 window the first time we show it. This way, we avoid
7992 showing users the sanity-defying horror of whatever
7993 GtkWindow is rendering beneath us. We've garbaged
7994 the frame, so we'll redraw the whole thing on next
7995 redisplay anyway. Yuck. */
7996 x_clear_area1 (
7997 FRAME_X_DISPLAY (f),
7998 FRAME_X_WINDOW (f),
7999 event->xexpose.x, event->xexpose.y,
8000 event->xexpose.width, event->xexpose.height,
8002 x_clear_under_internal_border (f);
8003 #endif
8007 if (!FRAME_GARBAGED_P (f))
8009 #ifdef USE_GTK
8010 /* This seems to be needed for GTK 2.6 and later, see
8011 https://debbugs.gnu.org/cgi/bugreport.cgi?bug=15398. */
8012 x_clear_area (f,
8013 event->xexpose.x, event->xexpose.y,
8014 event->xexpose.width, event->xexpose.height);
8015 #endif
8016 expose_frame (f, event->xexpose.x, event->xexpose.y,
8017 event->xexpose.width, event->xexpose.height);
8018 #ifdef USE_GTK
8019 x_clear_under_internal_border (f);
8020 #endif
8023 if (!FRAME_GARBAGED_P (f))
8024 show_back_buffer (f);
8026 else
8028 #ifndef USE_TOOLKIT_SCROLL_BARS
8029 struct scroll_bar *bar;
8030 #endif
8031 #if defined USE_LUCID
8032 /* Submenus of the Lucid menu bar aren't widgets
8033 themselves, so there's no way to dispatch events
8034 to them. Recognize this case separately. */
8036 Widget widget = x_window_to_menu_bar (event->xexpose.window);
8037 if (widget)
8038 xlwmenu_redisplay (widget);
8040 #endif /* USE_LUCID */
8042 #ifdef USE_TOOLKIT_SCROLL_BARS
8043 /* Dispatch event to the widget. */
8044 goto OTHER;
8045 #else /* not USE_TOOLKIT_SCROLL_BARS */
8046 bar = x_window_to_scroll_bar (event->xexpose.display,
8047 event->xexpose.window, 2);
8049 if (bar)
8050 x_scroll_bar_expose (bar, event);
8051 #ifdef USE_X_TOOLKIT
8052 else
8053 goto OTHER;
8054 #endif /* USE_X_TOOLKIT */
8055 #endif /* not USE_TOOLKIT_SCROLL_BARS */
8057 break;
8059 case GraphicsExpose: /* This occurs when an XCopyArea's
8060 source area was obscured or not
8061 available. */
8062 f = x_window_to_frame (dpyinfo, event->xgraphicsexpose.drawable);
8063 if (f)
8065 expose_frame (f, event->xgraphicsexpose.x,
8066 event->xgraphicsexpose.y,
8067 event->xgraphicsexpose.width,
8068 event->xgraphicsexpose.height);
8069 #ifdef USE_GTK
8070 x_clear_under_internal_border (f);
8071 #endif
8072 show_back_buffer (f);
8074 #ifdef USE_X_TOOLKIT
8075 else
8076 goto OTHER;
8077 #endif /* USE_X_TOOLKIT */
8078 break;
8080 case NoExpose: /* This occurs when an XCopyArea's
8081 source area was completely
8082 available. */
8083 break;
8085 case UnmapNotify:
8086 /* Redo the mouse-highlight after the tooltip has gone. */
8087 if (event->xunmap.window == tip_window)
8089 tip_window = None;
8090 x_redo_mouse_highlight (dpyinfo);
8093 f = x_top_window_to_frame (dpyinfo, event->xunmap.window);
8094 if (f) /* F may no longer exist if
8095 the frame was deleted. */
8097 bool visible = FRAME_VISIBLE_P (f);
8098 /* While a frame is unmapped, display generation is
8099 disabled; you don't want to spend time updating a
8100 display that won't ever be seen. */
8101 SET_FRAME_VISIBLE (f, 0);
8102 /* We can't distinguish, from the event, whether the window
8103 has become iconified or invisible. So assume, if it
8104 was previously visible, than now it is iconified.
8105 But x_make_frame_invisible clears both
8106 the visible flag and the iconified flag;
8107 and that way, we know the window is not iconified now. */
8108 if (visible || FRAME_ICONIFIED_P (f))
8110 SET_FRAME_ICONIFIED (f, true);
8111 inev.ie.kind = ICONIFY_EVENT;
8112 XSETFRAME (inev.ie.frame_or_window, f);
8115 goto OTHER;
8117 case MapNotify:
8118 /* We use x_top_window_to_frame because map events can
8119 come for sub-windows and they don't mean that the
8120 frame is visible. */
8121 f = x_top_window_to_frame (dpyinfo, event->xmap.window);
8122 if (f)
8124 bool iconified = FRAME_ICONIFIED_P (f);
8126 /* Check if fullscreen was specified before we where mapped the
8127 first time, i.e. from the command line. */
8128 if (!f->output_data.x->has_been_visible)
8131 x_check_fullscreen (f);
8132 #ifndef USE_GTK
8133 /* For systems that cannot synthesize `skip_taskbar' for
8134 unmapped windows do the following. */
8135 if (FRAME_SKIP_TASKBAR (f))
8136 x_set_skip_taskbar (f, Qt, Qnil);
8137 #endif /* Not USE_GTK */
8140 if (!iconified)
8142 /* The `z-group' is reset every time a frame becomes
8143 invisible. Handle this here. */
8144 if (FRAME_Z_GROUP (f) == z_group_above)
8145 x_set_z_group (f, Qabove, Qnil);
8146 else if (FRAME_Z_GROUP (f) == z_group_below)
8147 x_set_z_group (f, Qbelow, Qnil);
8150 SET_FRAME_VISIBLE (f, 1);
8151 SET_FRAME_ICONIFIED (f, false);
8152 f->output_data.x->has_been_visible = true;
8154 if (iconified)
8156 inev.ie.kind = DEICONIFY_EVENT;
8157 XSETFRAME (inev.ie.frame_or_window, f);
8159 else if (! NILP (Vframe_list) && ! NILP (XCDR (Vframe_list)))
8160 /* Force a redisplay sooner or later to update the
8161 frame titles in case this is the second frame. */
8162 record_asynch_buffer_change ();
8164 goto OTHER;
8166 case KeyPress:
8168 x_display_set_last_user_time (dpyinfo, event->xkey.time);
8169 ignore_next_mouse_click_timeout = 0;
8171 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
8172 /* Dispatch KeyPress events when in menu. */
8173 if (popup_activated ())
8174 goto OTHER;
8175 #endif
8177 f = any;
8179 /* If mouse-highlight is an integer, input clears out
8180 mouse highlighting. */
8181 if (!hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight)
8182 #if ! defined (USE_GTK)
8183 && (f == 0
8184 || !EQ (f->tool_bar_window, hlinfo->mouse_face_window))
8185 #endif
8188 clear_mouse_face (hlinfo);
8189 hlinfo->mouse_face_hidden = true;
8192 #if defined USE_MOTIF && defined USE_TOOLKIT_SCROLL_BARS
8193 if (f == 0)
8195 /* Scroll bars consume key events, but we want
8196 the keys to go to the scroll bar's frame. */
8197 Widget widget = XtWindowToWidget (dpyinfo->display,
8198 event->xkey.window);
8199 if (widget && XmIsScrollBar (widget))
8201 widget = XtParent (widget);
8202 f = x_any_window_to_frame (dpyinfo, XtWindow (widget));
8205 #endif /* USE_MOTIF and USE_TOOLKIT_SCROLL_BARS */
8207 if (f != 0)
8209 KeySym keysym, orig_keysym;
8210 /* al%imercury@uunet.uu.net says that making this 81
8211 instead of 80 fixed a bug whereby meta chars made
8212 his Emacs hang.
8214 It seems that some version of XmbLookupString has
8215 a bug of not returning XBufferOverflow in
8216 status_return even if the input is too long to
8217 fit in 81 bytes. So, we must prepare sufficient
8218 bytes for copy_buffer. 513 bytes (256 chars for
8219 two-byte character set) seems to be a fairly good
8220 approximation. -- 2000.8.10 handa@etl.go.jp */
8221 unsigned char copy_buffer[513];
8222 unsigned char *copy_bufptr = copy_buffer;
8223 int copy_bufsiz = sizeof (copy_buffer);
8224 int modifiers;
8225 Lisp_Object coding_system = Qlatin_1;
8226 Lisp_Object c;
8227 /* Event will be modified. */
8228 XKeyEvent xkey = event->xkey;
8230 #ifdef USE_GTK
8231 /* Don't pass keys to GTK. A Tab will shift focus to the
8232 tool bar in GTK 2.4. Keys will still go to menus and
8233 dialogs because in that case popup_activated is nonzero
8234 (see above). */
8235 *finish = X_EVENT_DROP;
8236 #endif
8238 xkey.state |= x_emacs_to_x_modifiers (FRAME_DISPLAY_INFO (f),
8239 extra_keyboard_modifiers);
8240 modifiers = xkey.state;
8242 /* This will have to go some day... */
8244 /* make_lispy_event turns chars into control chars.
8245 Don't do it here because XLookupString is too eager. */
8246 xkey.state &= ~ControlMask;
8247 xkey.state &= ~(dpyinfo->meta_mod_mask
8248 | dpyinfo->super_mod_mask
8249 | dpyinfo->hyper_mod_mask
8250 | dpyinfo->alt_mod_mask);
8252 /* In case Meta is ComposeCharacter,
8253 clear its status. According to Markus Ehrnsperger
8254 Markus.Ehrnsperger@lehrstuhl-bross.physik.uni-muenchen.de
8255 this enables ComposeCharacter to work whether or
8256 not it is combined with Meta. */
8257 if (modifiers & dpyinfo->meta_mod_mask)
8258 memset (&compose_status, 0, sizeof (compose_status));
8260 #ifdef HAVE_X_I18N
8261 if (FRAME_XIC (f))
8263 Status status_return;
8265 coding_system = Vlocale_coding_system;
8266 nbytes = XmbLookupString (FRAME_XIC (f),
8267 &xkey, (char *) copy_bufptr,
8268 copy_bufsiz, &keysym,
8269 &status_return);
8270 if (status_return == XBufferOverflow)
8272 copy_bufsiz = nbytes + 1;
8273 copy_bufptr = alloca (copy_bufsiz);
8274 nbytes = XmbLookupString (FRAME_XIC (f),
8275 &xkey, (char *) copy_bufptr,
8276 copy_bufsiz, &keysym,
8277 &status_return);
8279 /* Xutf8LookupString is a new but already deprecated interface. -stef */
8280 if (status_return == XLookupNone)
8281 break;
8282 else if (status_return == XLookupChars)
8284 keysym = NoSymbol;
8285 modifiers = 0;
8287 else if (status_return != XLookupKeySym
8288 && status_return != XLookupBoth)
8289 emacs_abort ();
8291 else
8292 nbytes = XLookupString (&xkey, (char *) copy_bufptr,
8293 copy_bufsiz, &keysym,
8294 &compose_status);
8295 #else
8296 nbytes = XLookupString (&xkey, (char *) copy_bufptr,
8297 copy_bufsiz, &keysym,
8298 &compose_status);
8299 #endif
8301 /* If not using XIM/XIC, and a compose sequence is in progress,
8302 we break here. Otherwise, chars_matched is always 0. */
8303 if (compose_status.chars_matched > 0 && nbytes == 0)
8304 break;
8306 memset (&compose_status, 0, sizeof (compose_status));
8307 orig_keysym = keysym;
8309 /* Common for all keysym input events. */
8310 XSETFRAME (inev.ie.frame_or_window, f);
8311 inev.ie.modifiers
8312 = x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO (f), modifiers);
8313 inev.ie.timestamp = xkey.time;
8315 /* First deal with keysyms which have defined
8316 translations to characters. */
8317 if (keysym >= 32 && keysym < 128)
8318 /* Avoid explicitly decoding each ASCII character. */
8320 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
8321 inev.ie.code = keysym;
8322 goto done_keysym;
8325 /* Keysyms directly mapped to Unicode characters. */
8326 if (keysym >= 0x01000000 && keysym <= 0x0110FFFF)
8328 if (keysym < 0x01000080)
8329 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
8330 else
8331 inev.ie.kind = MULTIBYTE_CHAR_KEYSTROKE_EVENT;
8332 inev.ie.code = keysym & 0xFFFFFF;
8333 goto done_keysym;
8336 /* Now non-ASCII. */
8337 if (HASH_TABLE_P (Vx_keysym_table)
8338 && (c = Fgethash (make_number (keysym),
8339 Vx_keysym_table,
8340 Qnil),
8341 NATNUMP (c)))
8343 inev.ie.kind = (SINGLE_BYTE_CHAR_P (XFASTINT (c))
8344 ? ASCII_KEYSTROKE_EVENT
8345 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
8346 inev.ie.code = XFASTINT (c);
8347 goto done_keysym;
8350 /* Random non-modifier sorts of keysyms. */
8351 if (((keysym >= XK_BackSpace && keysym <= XK_Escape)
8352 || keysym == XK_Delete
8353 #ifdef XK_ISO_Left_Tab
8354 || (keysym >= XK_ISO_Left_Tab
8355 && keysym <= XK_ISO_Enter)
8356 #endif
8357 || IsCursorKey (keysym) /* 0xff50 <= x < 0xff60 */
8358 || IsMiscFunctionKey (keysym) /* 0xff60 <= x < VARIES */
8359 #ifdef HPUX
8360 /* This recognizes the "extended function
8361 keys". It seems there's no cleaner way.
8362 Test IsModifierKey to avoid handling
8363 mode_switch incorrectly. */
8364 || (XK_Select <= keysym && keysym < XK_KP_Space)
8365 #endif
8366 #ifdef XK_dead_circumflex
8367 || orig_keysym == XK_dead_circumflex
8368 #endif
8369 #ifdef XK_dead_grave
8370 || orig_keysym == XK_dead_grave
8371 #endif
8372 #ifdef XK_dead_tilde
8373 || orig_keysym == XK_dead_tilde
8374 #endif
8375 #ifdef XK_dead_diaeresis
8376 || orig_keysym == XK_dead_diaeresis
8377 #endif
8378 #ifdef XK_dead_macron
8379 || orig_keysym == XK_dead_macron
8380 #endif
8381 #ifdef XK_dead_degree
8382 || orig_keysym == XK_dead_degree
8383 #endif
8384 #ifdef XK_dead_acute
8385 || orig_keysym == XK_dead_acute
8386 #endif
8387 #ifdef XK_dead_cedilla
8388 || orig_keysym == XK_dead_cedilla
8389 #endif
8390 #ifdef XK_dead_breve
8391 || orig_keysym == XK_dead_breve
8392 #endif
8393 #ifdef XK_dead_ogonek
8394 || orig_keysym == XK_dead_ogonek
8395 #endif
8396 #ifdef XK_dead_caron
8397 || orig_keysym == XK_dead_caron
8398 #endif
8399 #ifdef XK_dead_doubleacute
8400 || orig_keysym == XK_dead_doubleacute
8401 #endif
8402 #ifdef XK_dead_abovedot
8403 || orig_keysym == XK_dead_abovedot
8404 #endif
8405 || IsKeypadKey (keysym) /* 0xff80 <= x < 0xffbe */
8406 || IsFunctionKey (keysym) /* 0xffbe <= x < 0xffe1 */
8407 /* Any "vendor-specific" key is ok. */
8408 || (orig_keysym & (1 << 28))
8409 || (keysym != NoSymbol && nbytes == 0))
8410 && ! (IsModifierKey (orig_keysym)
8411 /* The symbols from XK_ISO_Lock
8412 to XK_ISO_Last_Group_Lock
8413 don't have real modifiers but
8414 should be treated similarly to
8415 Mode_switch by Emacs. */
8416 #if defined XK_ISO_Lock && defined XK_ISO_Last_Group_Lock
8417 || (XK_ISO_Lock <= orig_keysym
8418 && orig_keysym <= XK_ISO_Last_Group_Lock)
8419 #endif
8422 STORE_KEYSYM_FOR_DEBUG (keysym);
8423 /* make_lispy_event will convert this to a symbolic
8424 key. */
8425 inev.ie.kind = NON_ASCII_KEYSTROKE_EVENT;
8426 inev.ie.code = keysym;
8427 goto done_keysym;
8430 { /* Raw bytes, not keysym. */
8431 ptrdiff_t i;
8432 int nchars, len;
8434 for (i = 0, nchars = 0; i < nbytes; i++)
8436 if (ASCII_CHAR_P (copy_bufptr[i]))
8437 nchars++;
8438 STORE_KEYSYM_FOR_DEBUG (copy_bufptr[i]);
8441 if (nchars < nbytes)
8443 /* Decode the input data. */
8445 /* The input should be decoded with `coding_system'
8446 which depends on which X*LookupString function
8447 we used just above and the locale. */
8448 setup_coding_system (coding_system, &coding);
8449 coding.src_multibyte = false;
8450 coding.dst_multibyte = true;
8451 /* The input is converted to events, thus we can't
8452 handle composition. Anyway, there's no XIM that
8453 gives us composition information. */
8454 coding.common_flags &= ~CODING_ANNOTATION_MASK;
8456 SAFE_NALLOCA (coding.destination, MAX_MULTIBYTE_LENGTH,
8457 nbytes);
8458 coding.dst_bytes = MAX_MULTIBYTE_LENGTH * nbytes;
8459 coding.mode |= CODING_MODE_LAST_BLOCK;
8460 decode_coding_c_string (&coding, copy_bufptr, nbytes, Qnil);
8461 nbytes = coding.produced;
8462 nchars = coding.produced_char;
8463 copy_bufptr = coding.destination;
8466 /* Convert the input data to a sequence of
8467 character events. */
8468 for (i = 0; i < nbytes; i += len)
8470 int ch;
8471 if (nchars == nbytes)
8472 ch = copy_bufptr[i], len = 1;
8473 else
8474 ch = STRING_CHAR_AND_LENGTH (copy_bufptr + i, len);
8475 inev.ie.kind = (SINGLE_BYTE_CHAR_P (ch)
8476 ? ASCII_KEYSTROKE_EVENT
8477 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
8478 inev.ie.code = ch;
8479 kbd_buffer_store_buffered_event (&inev, hold_quit);
8482 count += nchars;
8484 inev.ie.kind = NO_EVENT; /* Already stored above. */
8486 if (keysym == NoSymbol)
8487 break;
8489 /* FIXME: check side effects and remove this. */
8490 ((XEvent *) event)->xkey = xkey;
8492 done_keysym:
8493 #ifdef HAVE_X_I18N
8494 /* Don't dispatch this event since XtDispatchEvent calls
8495 XFilterEvent, and two calls in a row may freeze the
8496 client. */
8497 break;
8498 #else
8499 goto OTHER;
8500 #endif
8502 case KeyRelease:
8503 x_display_set_last_user_time (dpyinfo, event->xkey.time);
8504 #ifdef HAVE_X_I18N
8505 /* Don't dispatch this event since XtDispatchEvent calls
8506 XFilterEvent, and two calls in a row may freeze the
8507 client. */
8508 break;
8509 #else
8510 goto OTHER;
8511 #endif
8513 case EnterNotify:
8514 x_display_set_last_user_time (dpyinfo, event->xcrossing.time);
8515 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
8517 f = any;
8519 if (f && x_mouse_click_focus_ignore_position)
8520 ignore_next_mouse_click_timeout = event->xmotion.time + 200;
8522 /* EnterNotify counts as mouse movement,
8523 so update things that depend on mouse position. */
8524 if (f && !f->output_data.x->hourglass_p)
8525 note_mouse_movement (f, &event->xmotion);
8526 #ifdef USE_GTK
8527 /* We may get an EnterNotify on the buttons in the toolbar. In that
8528 case we moved out of any highlighted area and need to note this. */
8529 if (!f && dpyinfo->last_mouse_glyph_frame)
8530 note_mouse_movement (dpyinfo->last_mouse_glyph_frame, &event->xmotion);
8531 #endif
8532 goto OTHER;
8534 case FocusIn:
8535 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
8536 goto OTHER;
8538 case LeaveNotify:
8539 x_display_set_last_user_time (dpyinfo, event->xcrossing.time);
8540 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
8542 f = x_top_window_to_frame (dpyinfo, event->xcrossing.window);
8543 if (f)
8545 if (f == hlinfo->mouse_face_mouse_frame)
8547 /* If we move outside the frame, then we're
8548 certainly no longer on any text in the frame. */
8549 clear_mouse_face (hlinfo);
8550 hlinfo->mouse_face_mouse_frame = 0;
8553 /* Generate a nil HELP_EVENT to cancel a help-echo.
8554 Do it only if there's something to cancel.
8555 Otherwise, the startup message is cleared when
8556 the mouse leaves the frame. */
8557 if (any_help_event_p)
8558 do_help = -1;
8560 #ifdef USE_GTK
8561 /* See comment in EnterNotify above */
8562 else if (dpyinfo->last_mouse_glyph_frame)
8563 note_mouse_movement (dpyinfo->last_mouse_glyph_frame, &event->xmotion);
8564 #endif
8565 goto OTHER;
8567 case FocusOut:
8568 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
8569 goto OTHER;
8571 case MotionNotify:
8573 x_display_set_last_user_time (dpyinfo, event->xmotion.time);
8574 previous_help_echo_string = help_echo_string;
8575 help_echo_string = Qnil;
8577 f = (x_mouse_grabbed (dpyinfo) ? dpyinfo->last_mouse_frame
8578 : x_window_to_frame (dpyinfo, event->xmotion.window));
8580 if (hlinfo->mouse_face_hidden)
8582 hlinfo->mouse_face_hidden = false;
8583 clear_mouse_face (hlinfo);
8586 #ifdef USE_GTK
8587 if (f && xg_event_is_for_scrollbar (f, event))
8588 f = 0;
8589 #endif
8590 if (f)
8592 /* Maybe generate a SELECT_WINDOW_EVENT for
8593 `mouse-autoselect-window' but don't let popup menus
8594 interfere with this (Bug#1261). */
8595 if (!NILP (Vmouse_autoselect_window)
8596 && !popup_activated ()
8597 /* Don't switch if we're currently in the minibuffer.
8598 This tries to work around problems where the
8599 minibuffer gets unselected unexpectedly, and where
8600 you then have to move your mouse all the way down to
8601 the minibuffer to select it. */
8602 && !MINI_WINDOW_P (XWINDOW (selected_window))
8603 /* With `focus-follows-mouse' non-nil create an event
8604 also when the target window is on another frame. */
8605 && (f == XFRAME (selected_frame)
8606 || !NILP (focus_follows_mouse)))
8608 static Lisp_Object last_mouse_window;
8609 Lisp_Object window = window_from_coordinates
8610 (f, event->xmotion.x, event->xmotion.y, 0, false);
8612 /* A window will be autoselected only when it is not
8613 selected now and the last mouse movement event was
8614 not in it. The remainder of the code is a bit vague
8615 wrt what a "window" is. For immediate autoselection,
8616 the window is usually the entire window but for GTK
8617 where the scroll bars don't count. For delayed
8618 autoselection the window is usually the window's text
8619 area including the margins. */
8620 if (WINDOWP (window)
8621 && !EQ (window, last_mouse_window)
8622 && !EQ (window, selected_window))
8624 inev.ie.kind = SELECT_WINDOW_EVENT;
8625 inev.ie.frame_or_window = window;
8628 /* Remember the last window where we saw the mouse. */
8629 last_mouse_window = window;
8632 if (!note_mouse_movement (f, &event->xmotion))
8633 help_echo_string = previous_help_echo_string;
8635 else
8637 #ifndef USE_TOOLKIT_SCROLL_BARS
8638 struct scroll_bar *bar
8639 = x_window_to_scroll_bar (event->xmotion.display,
8640 event->xmotion.window, 2);
8642 if (bar)
8643 x_scroll_bar_note_movement (bar, &event->xmotion);
8644 #endif /* USE_TOOLKIT_SCROLL_BARS */
8646 /* If we move outside the frame, then we're
8647 certainly no longer on any text in the frame. */
8648 clear_mouse_face (hlinfo);
8651 /* If the contents of the global variable help_echo_string
8652 has changed, generate a HELP_EVENT. */
8653 if (!NILP (help_echo_string)
8654 || !NILP (previous_help_echo_string))
8655 do_help = 1;
8656 goto OTHER;
8659 case ConfigureNotify:
8660 /* An opaque move can generate a stream of events as the window
8661 is dragged around. If the connection round trip time isn't
8662 really short, they may come faster than we can respond to
8663 them, given the multiple queries we can do to check window
8664 manager state, translate coordinates, etc.
8666 So if this ConfigureNotify is immediately followed by another
8667 for the same window, use the info from the latest update, and
8668 consider the events all handled. */
8669 /* Opaque resize may be trickier; ConfigureNotify events are
8670 mixed with Expose events for multiple windows. */
8671 configureEvent = *event;
8672 while (XPending (dpyinfo->display))
8674 XNextEvent (dpyinfo->display, &next_event);
8675 if (next_event.type != ConfigureNotify
8676 || next_event.xconfigure.window != event->xconfigure.window
8677 /* Skipping events with different sizes can lead to a
8678 mispositioned mode line at initial window creation.
8679 Only drop window motion events for now. */
8680 || next_event.xconfigure.width != event->xconfigure.width
8681 || next_event.xconfigure.height != event->xconfigure.height)
8683 XPutBackEvent (dpyinfo->display, &next_event);
8684 break;
8686 else
8687 configureEvent = next_event;
8690 f = x_top_window_to_frame (dpyinfo, configureEvent.xconfigure.window);
8691 /* Unfortunately, we need to call font_drop_xrender_surfaces for
8692 _all_ ConfigureNotify events, otherwise we miss some and
8693 flicker. Don't try to optimize these calls by looking only
8694 for size changes: that's not sufficient. We miss some
8695 surface invalidations and flicker. */
8696 block_input ();
8697 if (f && FRAME_X_DOUBLE_BUFFERED_P (f))
8698 font_drop_xrender_surfaces (f);
8699 unblock_input ();
8700 #ifdef USE_CAIRO
8701 if (f) x_cr_destroy_surface (f);
8702 #endif
8703 #ifdef USE_GTK
8704 if (!f
8705 && (f = any)
8706 && configureEvent.xconfigure.window == FRAME_X_WINDOW (f))
8708 block_input ();
8709 if (FRAME_X_DOUBLE_BUFFERED_P (f))
8710 font_drop_xrender_surfaces (f);
8711 unblock_input ();
8712 xg_frame_resized (f, configureEvent.xconfigure.width,
8713 configureEvent.xconfigure.height);
8714 #ifdef USE_CAIRO
8715 x_cr_destroy_surface (f);
8716 #endif
8717 f = 0;
8719 #endif
8720 if (f)
8722 #ifdef USE_GTK
8723 /* For GTK+ don't call x_net_wm_state for the scroll bar
8724 window. (Bug#24963, Bug#25887) */
8725 if (configureEvent.xconfigure.window == FRAME_X_WINDOW (f))
8726 #endif
8727 x_net_wm_state (f, configureEvent.xconfigure.window);
8729 #ifdef USE_X_TOOLKIT
8730 /* Tip frames are pure X window, set size for them. */
8731 if (FRAME_TOOLTIP_P (f))
8733 if (FRAME_PIXEL_HEIGHT (f) != configureEvent.xconfigure.height
8734 || FRAME_PIXEL_WIDTH (f) != configureEvent.xconfigure.width)
8736 SET_FRAME_GARBAGED (f);
8738 FRAME_PIXEL_HEIGHT (f) = configureEvent.xconfigure.height;
8739 FRAME_PIXEL_WIDTH (f) = configureEvent.xconfigure.width;
8741 #endif
8743 #ifndef USE_X_TOOLKIT
8744 #ifndef USE_GTK
8745 int width =
8746 FRAME_PIXEL_TO_TEXT_WIDTH (f, configureEvent.xconfigure.width);
8747 int height =
8748 FRAME_PIXEL_TO_TEXT_HEIGHT (f, configureEvent.xconfigure.height);
8750 /* In the toolkit version, change_frame_size
8751 is called by the code that handles resizing
8752 of the EmacsFrame widget. */
8754 /* Even if the number of character rows and columns has
8755 not changed, the font size may have changed, so we need
8756 to check the pixel dimensions as well. */
8757 if (width != FRAME_TEXT_WIDTH (f)
8758 || height != FRAME_TEXT_HEIGHT (f)
8759 || configureEvent.xconfigure.width != FRAME_PIXEL_WIDTH (f)
8760 || configureEvent.xconfigure.height != FRAME_PIXEL_HEIGHT (f))
8762 change_frame_size (f, width, height, false, true, false, true);
8763 x_clear_under_internal_border (f);
8764 SET_FRAME_GARBAGED (f);
8765 cancel_mouse_face (f);
8767 #endif /* not USE_GTK */
8768 #endif
8770 #ifdef USE_GTK
8771 /* GTK creates windows but doesn't map them.
8772 Only get real positions when mapped. */
8773 if (FRAME_GTK_OUTER_WIDGET (f)
8774 && gtk_widget_get_mapped (FRAME_GTK_OUTER_WIDGET (f)))
8775 #endif
8777 int old_left = f->left_pos;
8778 int old_top = f->top_pos;
8779 Lisp_Object frame = Qnil;
8781 XSETFRAME (frame, f);
8783 if (!FRAME_PARENT_FRAME (f))
8784 x_real_positions (f, &f->left_pos, &f->top_pos);
8785 else
8787 Window root;
8788 unsigned int dummy_uint;
8790 block_input ();
8791 XGetGeometry (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8792 &root, &f->left_pos, &f->top_pos,
8793 &dummy_uint, &dummy_uint, &dummy_uint, &dummy_uint);
8794 unblock_input ();
8797 if (old_left != f->left_pos || old_top != f->top_pos)
8799 inev.ie.kind = MOVE_FRAME_EVENT;
8800 XSETFRAME (inev.ie.frame_or_window, f);
8805 #ifdef HAVE_X_I18N
8806 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMStatusArea))
8807 xic_set_statusarea (f);
8808 #endif
8811 goto OTHER;
8813 case ButtonRelease:
8814 case ButtonPress:
8816 /* If we decide we want to generate an event to be seen
8817 by the rest of Emacs, we put it here. */
8818 bool tool_bar_p = false;
8820 memset (&compose_status, 0, sizeof (compose_status));
8821 dpyinfo->last_mouse_glyph_frame = NULL;
8822 x_display_set_last_user_time (dpyinfo, event->xbutton.time);
8824 if (x_mouse_grabbed (dpyinfo))
8825 f = dpyinfo->last_mouse_frame;
8826 else
8828 f = x_window_to_frame (dpyinfo, event->xbutton.window);
8830 if (f && event->xbutton.type == ButtonPress
8831 && !popup_activated ()
8832 && !x_window_to_scroll_bar (event->xbutton.display,
8833 event->xbutton.window, 2)
8834 && !FRAME_NO_ACCEPT_FOCUS (f))
8836 /* When clicking into a child frame or when clicking
8837 into a parent frame with the child frame selected and
8838 `no-accept-focus' is not set, select the clicked
8839 frame. */
8840 struct frame *hf = dpyinfo->x_highlight_frame;
8842 if (FRAME_PARENT_FRAME (f) || (hf && frame_ancestor_p (f, hf)))
8844 block_input ();
8845 XSetInputFocus (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8846 RevertToParent, CurrentTime);
8847 if (FRAME_PARENT_FRAME (f))
8848 XRaiseWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
8849 unblock_input ();
8854 #ifdef USE_GTK
8855 if (f && xg_event_is_for_scrollbar (f, event))
8856 f = 0;
8857 #endif
8858 if (f)
8860 #if ! defined (USE_GTK)
8861 /* Is this in the tool-bar? */
8862 if (WINDOWP (f->tool_bar_window)
8863 && WINDOW_TOTAL_LINES (XWINDOW (f->tool_bar_window)))
8865 Lisp_Object window;
8866 int x = event->xbutton.x;
8867 int y = event->xbutton.y;
8869 window = window_from_coordinates (f, x, y, 0, true);
8870 tool_bar_p = EQ (window, f->tool_bar_window);
8872 if (tool_bar_p && event->xbutton.button < 4)
8873 handle_tool_bar_click
8874 (f, x, y, event->xbutton.type == ButtonPress,
8875 x_x_to_emacs_modifiers (dpyinfo, event->xbutton.state));
8877 #endif /* !USE_GTK */
8879 if (!tool_bar_p)
8880 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
8881 if (! popup_activated ())
8882 #endif
8884 if (ignore_next_mouse_click_timeout)
8886 if (event->type == ButtonPress
8887 && event->xbutton.time > ignore_next_mouse_click_timeout)
8889 ignore_next_mouse_click_timeout = 0;
8890 construct_mouse_click (&inev.ie, &event->xbutton, f);
8892 if (event->type == ButtonRelease)
8893 ignore_next_mouse_click_timeout = 0;
8895 else
8896 construct_mouse_click (&inev.ie, &event->xbutton, f);
8898 if (FRAME_X_EMBEDDED_P (f))
8899 xembed_send_message (f, event->xbutton.time,
8900 XEMBED_REQUEST_FOCUS, 0, 0, 0);
8902 else
8904 struct scroll_bar *bar
8905 = x_window_to_scroll_bar (event->xbutton.display,
8906 event->xbutton.window, 2);
8908 #ifdef USE_TOOLKIT_SCROLL_BARS
8909 /* Make the "Ctrl-Mouse-2 splits window" work for toolkit
8910 scroll bars. */
8911 if (bar && event->xbutton.state & ControlMask)
8913 x_scroll_bar_handle_click (bar, event, &inev.ie);
8914 *finish = X_EVENT_DROP;
8916 #else /* not USE_TOOLKIT_SCROLL_BARS */
8917 if (bar)
8918 x_scroll_bar_handle_click (bar, event, &inev.ie);
8919 #endif /* not USE_TOOLKIT_SCROLL_BARS */
8922 if (event->type == ButtonPress)
8924 dpyinfo->grabbed |= (1 << event->xbutton.button);
8925 dpyinfo->last_mouse_frame = f;
8926 #if ! defined (USE_GTK)
8927 if (f && !tool_bar_p)
8928 f->last_tool_bar_item = -1;
8929 #endif /* not USE_GTK */
8931 else
8932 dpyinfo->grabbed &= ~(1 << event->xbutton.button);
8934 /* Ignore any mouse motion that happened before this event;
8935 any subsequent mouse-movement Emacs events should reflect
8936 only motion after the ButtonPress/Release. */
8937 if (f != 0)
8938 f->mouse_moved = false;
8940 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
8941 f = x_menubar_window_to_frame (dpyinfo, event);
8942 /* For a down-event in the menu bar,
8943 don't pass it to Xt right now.
8944 Instead, save it away
8945 and we will pass it to Xt from kbd_buffer_get_event.
8946 That way, we can run some Lisp code first. */
8947 if (! popup_activated ()
8948 #ifdef USE_GTK
8949 /* Gtk+ menus only react to the first three buttons. */
8950 && event->xbutton.button < 3
8951 #endif
8952 && f && event->type == ButtonPress
8953 /* Verify the event is really within the menu bar
8954 and not just sent to it due to grabbing. */
8955 && event->xbutton.x >= 0
8956 && event->xbutton.x < FRAME_PIXEL_WIDTH (f)
8957 && event->xbutton.y >= 0
8958 && event->xbutton.y < FRAME_MENUBAR_HEIGHT (f)
8959 && event->xbutton.same_screen)
8961 if (!f->output_data.x->saved_menu_event)
8962 f->output_data.x->saved_menu_event = xmalloc (sizeof *event);
8963 *f->output_data.x->saved_menu_event = *event;
8964 inev.ie.kind = MENU_BAR_ACTIVATE_EVENT;
8965 XSETFRAME (inev.ie.frame_or_window, f);
8966 *finish = X_EVENT_DROP;
8968 else
8969 goto OTHER;
8970 #endif /* USE_X_TOOLKIT || USE_GTK */
8972 break;
8974 case CirculateNotify:
8975 goto OTHER;
8977 case CirculateRequest:
8978 goto OTHER;
8980 case VisibilityNotify:
8981 goto OTHER;
8983 case MappingNotify:
8984 /* Someone has changed the keyboard mapping - update the
8985 local cache. */
8986 switch (event->xmapping.request)
8988 case MappingModifier:
8989 x_find_modifier_meanings (dpyinfo);
8990 FALLTHROUGH;
8991 case MappingKeyboard:
8992 XRefreshKeyboardMapping ((XMappingEvent *) &event->xmapping);
8994 goto OTHER;
8996 case DestroyNotify:
8997 xft_settings_event (dpyinfo, event);
8998 break;
9000 default:
9001 OTHER:
9002 #ifdef USE_X_TOOLKIT
9003 block_input ();
9004 if (*finish != X_EVENT_DROP)
9005 XtDispatchEvent ((XEvent *) event);
9006 unblock_input ();
9007 #endif /* USE_X_TOOLKIT */
9008 break;
9011 done:
9012 if (inev.ie.kind != NO_EVENT)
9014 kbd_buffer_store_buffered_event (&inev, hold_quit);
9015 count++;
9018 if (do_help
9019 && !(hold_quit && hold_quit->kind != NO_EVENT))
9021 Lisp_Object frame;
9023 if (f)
9024 XSETFRAME (frame, f);
9025 else
9026 frame = Qnil;
9028 if (do_help > 0)
9030 any_help_event_p = true;
9031 gen_help_event (help_echo_string, frame, help_echo_window,
9032 help_echo_object, help_echo_pos);
9034 else
9036 help_echo_string = Qnil;
9037 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
9039 count++;
9042 /* Sometimes event processing draws to the frame outside redisplay.
9043 To ensure that these changes become visible, draw them here. */
9044 flush_dirty_back_buffers ();
9045 SAFE_FREE ();
9046 return count;
9049 #if defined USE_X_TOOLKIT || defined USE_MOTIF || defined USE_GTK
9051 /* Handles the XEvent EVENT on display DISPLAY.
9052 This is used for event loops outside the normal event handling,
9053 i.e. looping while a popup menu or a dialog is posted.
9055 Returns the value handle_one_xevent sets in the finish argument. */
9057 x_dispatch_event (XEvent *event, Display *display)
9059 struct x_display_info *dpyinfo;
9060 int finish = X_EVENT_NORMAL;
9062 dpyinfo = x_display_info_for_display (display);
9064 if (dpyinfo)
9065 handle_one_xevent (dpyinfo, event, &finish, 0);
9067 return finish;
9069 #endif
9071 /* Read events coming from the X server.
9072 Return as soon as there are no more events to be read.
9074 Return the number of characters stored into the buffer,
9075 thus pretending to be `read' (except the characters we store
9076 in the keyboard buffer can be multibyte, so are not necessarily
9077 C chars). */
9079 static int
9080 XTread_socket (struct terminal *terminal, struct input_event *hold_quit)
9082 int count = 0;
9083 bool event_found = false;
9084 struct x_display_info *dpyinfo = terminal->display_info.x;
9086 block_input ();
9088 /* For debugging, this gives a way to fake an I/O error. */
9089 if (dpyinfo == XTread_socket_fake_io_error)
9091 XTread_socket_fake_io_error = 0;
9092 x_io_error_quitter (dpyinfo->display);
9095 #ifndef USE_GTK
9096 while (XPending (dpyinfo->display))
9098 int finish;
9099 XEvent event;
9101 XNextEvent (dpyinfo->display, &event);
9103 #ifdef HAVE_X_I18N
9104 /* Filter events for the current X input method. */
9105 if (x_filter_event (dpyinfo, &event))
9106 continue;
9107 #endif
9108 event_found = true;
9110 count += handle_one_xevent (dpyinfo, &event, &finish, hold_quit);
9112 if (finish == X_EVENT_GOTO_OUT)
9113 break;
9116 #else /* USE_GTK */
9118 /* For GTK we must use the GTK event loop. But XEvents gets passed
9119 to our filter function above, and then to the big event switch.
9120 We use a bunch of globals to communicate with our filter function,
9121 that is kind of ugly, but it works.
9123 There is no way to do one display at the time, GTK just does events
9124 from all displays. */
9126 while (gtk_events_pending ())
9128 current_count = count;
9129 current_hold_quit = hold_quit;
9131 gtk_main_iteration ();
9133 count = current_count;
9134 current_count = -1;
9135 current_hold_quit = 0;
9137 if (current_finish == X_EVENT_GOTO_OUT)
9138 break;
9140 #endif /* USE_GTK */
9142 /* On some systems, an X bug causes Emacs to get no more events
9143 when the window is destroyed. Detect that. (1994.) */
9144 if (! event_found)
9146 /* Emacs and the X Server eats up CPU time if XNoOp is done every time.
9147 One XNOOP in 100 loops will make Emacs terminate.
9148 B. Bretthauer, 1994 */
9149 x_noop_count++;
9150 if (x_noop_count >= 100)
9152 x_noop_count=0;
9154 if (next_noop_dpyinfo == 0)
9155 next_noop_dpyinfo = x_display_list;
9157 XNoOp (next_noop_dpyinfo->display);
9159 /* Each time we get here, cycle through the displays now open. */
9160 next_noop_dpyinfo = next_noop_dpyinfo->next;
9164 /* If the focus was just given to an auto-raising frame,
9165 raise it now. FIXME: handle more than one such frame. */
9166 if (dpyinfo->x_pending_autoraise_frame)
9168 x_raise_frame (dpyinfo->x_pending_autoraise_frame);
9169 dpyinfo->x_pending_autoraise_frame = NULL;
9172 unblock_input ();
9174 return count;
9180 /***********************************************************************
9181 Text Cursor
9182 ***********************************************************************/
9184 /* Set clipping for output in glyph row ROW. W is the window in which
9185 we operate. GC is the graphics context to set clipping in.
9187 ROW may be a text row or, e.g., a mode line. Text rows must be
9188 clipped to the interior of the window dedicated to text display,
9189 mode lines must be clipped to the whole window. */
9191 static void
9192 x_clip_to_row (struct window *w, struct glyph_row *row,
9193 enum glyph_row_area area, GC gc)
9195 struct frame *f = XFRAME (WINDOW_FRAME (w));
9196 XRectangle clip_rect;
9197 int window_x, window_y, window_width;
9199 window_box (w, area, &window_x, &window_y, &window_width, 0);
9201 clip_rect.x = window_x;
9202 clip_rect.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
9203 clip_rect.y = max (clip_rect.y, window_y);
9204 clip_rect.width = window_width;
9205 clip_rect.height = row->visible_height;
9207 x_set_clip_rectangles (f, gc, &clip_rect, 1);
9211 /* Draw a hollow box cursor on window W in glyph row ROW. */
9213 static void
9214 x_draw_hollow_cursor (struct window *w, struct glyph_row *row)
9216 struct frame *f = XFRAME (WINDOW_FRAME (w));
9217 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
9218 Display *dpy = FRAME_X_DISPLAY (f);
9219 int x, y, wd, h;
9220 XGCValues xgcv;
9221 struct glyph *cursor_glyph;
9222 GC gc;
9224 /* Get the glyph the cursor is on. If we can't tell because
9225 the current matrix is invalid or such, give up. */
9226 cursor_glyph = get_phys_cursor_glyph (w);
9227 if (cursor_glyph == NULL)
9228 return;
9230 /* Compute frame-relative coordinates for phys cursor. */
9231 get_phys_cursor_geometry (w, row, cursor_glyph, &x, &y, &h);
9232 wd = w->phys_cursor_width - 1;
9234 /* The foreground of cursor_gc is typically the same as the normal
9235 background color, which can cause the cursor box to be invisible. */
9236 xgcv.foreground = f->output_data.x->cursor_pixel;
9237 if (dpyinfo->scratch_cursor_gc)
9238 XChangeGC (dpy, dpyinfo->scratch_cursor_gc, GCForeground, &xgcv);
9239 else
9240 dpyinfo->scratch_cursor_gc = XCreateGC (dpy, FRAME_X_DRAWABLE (f),
9241 GCForeground, &xgcv);
9242 gc = dpyinfo->scratch_cursor_gc;
9244 /* When on R2L character, show cursor at the right edge of the
9245 glyph, unless the cursor box is as wide as the glyph or wider
9246 (the latter happens when x-stretch-cursor is non-nil). */
9247 if ((cursor_glyph->resolved_level & 1) != 0
9248 && cursor_glyph->pixel_width > wd)
9250 x += cursor_glyph->pixel_width - wd;
9251 if (wd > 0)
9252 wd -= 1;
9254 /* Set clipping, draw the rectangle, and reset clipping again. */
9255 x_clip_to_row (w, row, TEXT_AREA, gc);
9256 x_draw_rectangle (f, gc, x, y, wd, h - 1);
9257 x_reset_clip_rectangles (f, gc);
9261 /* Draw a bar cursor on window W in glyph row ROW.
9263 Implementation note: One would like to draw a bar cursor with an
9264 angle equal to the one given by the font property XA_ITALIC_ANGLE.
9265 Unfortunately, I didn't find a font yet that has this property set.
9266 --gerd. */
9268 static void
9269 x_draw_bar_cursor (struct window *w, struct glyph_row *row, int width, enum text_cursor_kinds kind)
9271 struct frame *f = XFRAME (w->frame);
9272 struct glyph *cursor_glyph;
9274 /* If cursor is out of bounds, don't draw garbage. This can happen
9275 in mini-buffer windows when switching between echo area glyphs
9276 and mini-buffer. */
9277 cursor_glyph = get_phys_cursor_glyph (w);
9278 if (cursor_glyph == NULL)
9279 return;
9281 /* Experimental avoidance of cursor on xwidget. */
9282 if (cursor_glyph->type == XWIDGET_GLYPH)
9283 return;
9285 /* If on an image, draw like a normal cursor. That's usually better
9286 visible than drawing a bar, esp. if the image is large so that
9287 the bar might not be in the window. */
9288 if (cursor_glyph->type == IMAGE_GLYPH)
9290 struct glyph_row *r;
9291 r = MATRIX_ROW (w->current_matrix, w->phys_cursor.vpos);
9292 draw_phys_cursor_glyph (w, r, DRAW_CURSOR);
9294 else
9296 Display *dpy = FRAME_X_DISPLAY (f);
9297 Drawable drawable = FRAME_X_DRAWABLE (f);
9298 GC gc = FRAME_DISPLAY_INFO (f)->scratch_cursor_gc;
9299 unsigned long mask = GCForeground | GCBackground | GCGraphicsExposures;
9300 struct face *face = FACE_FROM_ID (f, cursor_glyph->face_id);
9301 XGCValues xgcv;
9303 /* If the glyph's background equals the color we normally draw
9304 the bars cursor in, the bar cursor in its normal color is
9305 invisible. Use the glyph's foreground color instead in this
9306 case, on the assumption that the glyph's colors are chosen so
9307 that the glyph is legible. */
9308 if (face->background == f->output_data.x->cursor_pixel)
9309 xgcv.background = xgcv.foreground = face->foreground;
9310 else
9311 xgcv.background = xgcv.foreground = f->output_data.x->cursor_pixel;
9312 xgcv.graphics_exposures = False;
9314 if (gc)
9315 XChangeGC (dpy, gc, mask, &xgcv);
9316 else
9318 gc = XCreateGC (dpy, drawable, mask, &xgcv);
9319 FRAME_DISPLAY_INFO (f)->scratch_cursor_gc = gc;
9322 x_clip_to_row (w, row, TEXT_AREA, gc);
9324 if (kind == BAR_CURSOR)
9326 int x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
9328 if (width < 0)
9329 width = FRAME_CURSOR_WIDTH (f);
9330 width = min (cursor_glyph->pixel_width, width);
9332 w->phys_cursor_width = width;
9334 /* If the character under cursor is R2L, draw the bar cursor
9335 on the right of its glyph, rather than on the left. */
9336 if ((cursor_glyph->resolved_level & 1) != 0)
9337 x += cursor_glyph->pixel_width - width;
9339 x_fill_rectangle (f, gc, x,
9340 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y),
9341 width, row->height);
9343 else /* HBAR_CURSOR */
9345 int dummy_x, dummy_y, dummy_h;
9346 int x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
9348 if (width < 0)
9349 width = row->height;
9351 width = min (row->height, width);
9353 get_phys_cursor_geometry (w, row, cursor_glyph, &dummy_x,
9354 &dummy_y, &dummy_h);
9356 if ((cursor_glyph->resolved_level & 1) != 0
9357 && cursor_glyph->pixel_width > w->phys_cursor_width - 1)
9358 x += cursor_glyph->pixel_width - w->phys_cursor_width + 1;
9359 x_fill_rectangle (f, gc, x,
9360 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y +
9361 row->height - width),
9362 w->phys_cursor_width - 1, width);
9365 x_reset_clip_rectangles (f, gc);
9370 /* RIF: Define cursor CURSOR on frame F. */
9372 static void
9373 x_define_frame_cursor (struct frame *f, Cursor cursor)
9375 if (!f->pointer_invisible
9376 && f->output_data.x->current_cursor != cursor)
9377 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), cursor);
9378 f->output_data.x->current_cursor = cursor;
9382 /* RIF: Clear area on frame F. */
9384 static void
9385 x_clear_frame_area (struct frame *f, int x, int y, int width, int height)
9387 x_clear_area (f, x, y, width, height);
9391 /* RIF: Draw cursor on window W. */
9393 static void
9394 x_draw_window_cursor (struct window *w, struct glyph_row *glyph_row, int x,
9395 int y, enum text_cursor_kinds cursor_type,
9396 int cursor_width, bool on_p, bool active_p)
9398 struct frame *f = XFRAME (WINDOW_FRAME (w));
9400 if (on_p)
9402 w->phys_cursor_type = cursor_type;
9403 w->phys_cursor_on_p = true;
9405 if (glyph_row->exact_window_width_line_p
9406 && (glyph_row->reversed_p
9407 ? (w->phys_cursor.hpos < 0)
9408 : (w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])))
9410 glyph_row->cursor_in_fringe_p = true;
9411 draw_fringe_bitmap (w, glyph_row, glyph_row->reversed_p);
9413 else
9415 switch (cursor_type)
9417 case HOLLOW_BOX_CURSOR:
9418 x_draw_hollow_cursor (w, glyph_row);
9419 break;
9421 case FILLED_BOX_CURSOR:
9422 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
9423 break;
9425 case BAR_CURSOR:
9426 x_draw_bar_cursor (w, glyph_row, cursor_width, BAR_CURSOR);
9427 break;
9429 case HBAR_CURSOR:
9430 x_draw_bar_cursor (w, glyph_row, cursor_width, HBAR_CURSOR);
9431 break;
9433 case NO_CURSOR:
9434 w->phys_cursor_width = 0;
9435 break;
9437 default:
9438 emacs_abort ();
9442 #ifdef HAVE_X_I18N
9443 if (w == XWINDOW (f->selected_window))
9444 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMPreeditPosition))
9445 xic_set_preeditarea (w, x, y);
9446 #endif
9449 XFlush (FRAME_X_DISPLAY (f));
9453 /* Icons. */
9455 /* Make the x-window of frame F use the gnu icon bitmap. */
9457 bool
9458 x_bitmap_icon (struct frame *f, Lisp_Object file)
9460 ptrdiff_t bitmap_id;
9462 if (FRAME_X_WINDOW (f) == 0)
9463 return true;
9465 /* Free up our existing icon bitmap and mask if any. */
9466 if (f->output_data.x->icon_bitmap > 0)
9467 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
9468 f->output_data.x->icon_bitmap = 0;
9470 if (STRINGP (file))
9472 #ifdef USE_GTK
9473 /* Use gtk_window_set_icon_from_file () if available,
9474 It's not restricted to bitmaps */
9475 if (xg_set_icon (f, file))
9476 return false;
9477 #endif /* USE_GTK */
9478 bitmap_id = x_create_bitmap_from_file (f, file);
9479 x_create_bitmap_mask (f, bitmap_id);
9481 else
9483 /* Create the GNU bitmap and mask if necessary. */
9484 if (FRAME_DISPLAY_INFO (f)->icon_bitmap_id < 0)
9486 ptrdiff_t rc = -1;
9488 #ifdef USE_GTK
9490 if (xg_set_icon (f, xg_default_icon_file)
9491 || xg_set_icon_from_xpm_data (f, gnu_xpm_bits))
9493 FRAME_DISPLAY_INFO (f)->icon_bitmap_id = -2;
9494 return false;
9497 #elif defined (HAVE_XPM) && defined (HAVE_X_WINDOWS)
9499 rc = x_create_bitmap_from_xpm_data (f, gnu_xpm_bits);
9500 if (rc != -1)
9501 FRAME_DISPLAY_INFO (f)->icon_bitmap_id = rc;
9503 #endif
9505 /* If all else fails, use the (black and white) xbm image. */
9506 if (rc == -1)
9508 rc = x_create_bitmap_from_data (f, (char *) gnu_xbm_bits,
9509 gnu_xbm_width, gnu_xbm_height);
9510 if (rc == -1)
9511 return true;
9513 FRAME_DISPLAY_INFO (f)->icon_bitmap_id = rc;
9514 x_create_bitmap_mask (f, FRAME_DISPLAY_INFO (f)->icon_bitmap_id);
9518 /* The first time we create the GNU bitmap and mask,
9519 this increments the ref-count one extra time.
9520 As a result, the GNU bitmap and mask are never freed.
9521 That way, we don't have to worry about allocating it again. */
9522 x_reference_bitmap (f, FRAME_DISPLAY_INFO (f)->icon_bitmap_id);
9524 bitmap_id = FRAME_DISPLAY_INFO (f)->icon_bitmap_id;
9527 x_wm_set_icon_pixmap (f, bitmap_id);
9528 f->output_data.x->icon_bitmap = bitmap_id;
9530 return false;
9534 /* Make the x-window of frame F use a rectangle with text.
9535 Use ICON_NAME as the text. */
9537 bool
9538 x_text_icon (struct frame *f, const char *icon_name)
9540 if (FRAME_X_WINDOW (f) == 0)
9541 return true;
9544 XTextProperty text;
9545 text.value = (unsigned char *) icon_name;
9546 text.encoding = XA_STRING;
9547 text.format = 8;
9548 text.nitems = strlen (icon_name);
9549 XSetWMIconName (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f), &text);
9552 if (f->output_data.x->icon_bitmap > 0)
9553 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
9554 f->output_data.x->icon_bitmap = 0;
9555 x_wm_set_icon_pixmap (f, 0);
9557 return false;
9560 #define X_ERROR_MESSAGE_SIZE 200
9562 /* If non-nil, this should be a string.
9563 It means catch X errors and store the error message in this string.
9565 The reason we use a stack is that x_catch_error/x_uncatch_error can
9566 be called from a signal handler.
9569 struct x_error_message_stack {
9570 char string[X_ERROR_MESSAGE_SIZE];
9571 Display *dpy;
9572 x_special_error_handler handler;
9573 void *handler_data;
9574 struct x_error_message_stack *prev;
9576 static struct x_error_message_stack *x_error_message;
9578 /* An X error handler which stores the error message in
9579 *x_error_message. This is called from x_error_handler if
9580 x_catch_errors is in effect. */
9582 static void
9583 x_error_catcher (Display *display, XErrorEvent *event)
9585 XGetErrorText (display, event->error_code,
9586 x_error_message->string,
9587 X_ERROR_MESSAGE_SIZE);
9588 if (x_error_message->handler)
9589 x_error_message->handler (display, event, x_error_message->string,
9590 x_error_message->handler_data);
9593 /* Begin trapping X errors for display DPY. Actually we trap X errors
9594 for all displays, but DPY should be the display you are actually
9595 operating on.
9597 After calling this function, X protocol errors no longer cause
9598 Emacs to exit; instead, they are recorded in the string
9599 stored in *x_error_message.
9601 Calling x_check_errors signals an Emacs error if an X error has
9602 occurred since the last call to x_catch_errors or x_check_errors.
9604 Calling x_uncatch_errors resumes the normal error handling.
9605 Calling x_uncatch_errors_after_check is similar, but skips an XSync
9606 to the server, and should be used only immediately after
9607 x_had_errors_p or x_check_errors. */
9609 void
9610 x_catch_errors_with_handler (Display *dpy, x_special_error_handler handler,
9611 void *handler_data)
9613 struct x_error_message_stack *data = xmalloc (sizeof *data);
9615 /* Make sure any errors from previous requests have been dealt with. */
9616 XSync (dpy, False);
9618 data->dpy = dpy;
9619 data->string[0] = 0;
9620 data->handler = handler;
9621 data->handler_data = handler_data;
9622 data->prev = x_error_message;
9623 x_error_message = data;
9626 void
9627 x_catch_errors (Display *dpy)
9629 x_catch_errors_with_handler (dpy, NULL, NULL);
9632 /* Undo the last x_catch_errors call.
9633 DPY should be the display that was passed to x_catch_errors.
9635 This version should be used only if the immediately preceding
9636 X-protocol-related thing was x_check_errors or x_had_error_p, both
9637 of which issue XSync calls, so we don't need to re-sync here. */
9639 void
9640 x_uncatch_errors_after_check (void)
9642 struct x_error_message_stack *tmp;
9644 block_input ();
9645 tmp = x_error_message;
9646 x_error_message = x_error_message->prev;
9647 xfree (tmp);
9648 unblock_input ();
9651 /* Undo the last x_catch_errors call.
9652 DPY should be the display that was passed to x_catch_errors. */
9654 void
9655 x_uncatch_errors (void)
9657 struct x_error_message_stack *tmp;
9659 block_input ();
9661 /* The display may have been closed before this function is called.
9662 Check if it is still open before calling XSync. */
9663 if (x_display_info_for_display (x_error_message->dpy) != 0)
9664 XSync (x_error_message->dpy, False);
9666 tmp = x_error_message;
9667 x_error_message = x_error_message->prev;
9668 xfree (tmp);
9669 unblock_input ();
9672 /* If any X protocol errors have arrived since the last call to
9673 x_catch_errors or x_check_errors, signal an Emacs error using
9674 sprintf (a buffer, FORMAT, the x error message text) as the text. */
9676 void
9677 x_check_errors (Display *dpy, const char *format)
9679 /* Make sure to catch any errors incurred so far. */
9680 XSync (dpy, False);
9682 if (x_error_message->string[0])
9684 char string[X_ERROR_MESSAGE_SIZE];
9685 memcpy (string, x_error_message->string, X_ERROR_MESSAGE_SIZE);
9686 x_uncatch_errors ();
9687 error (format, string);
9691 /* Nonzero if we had any X protocol errors
9692 since we did x_catch_errors on DPY. */
9694 bool
9695 x_had_errors_p (Display *dpy)
9697 /* Make sure to catch any errors incurred so far. */
9698 XSync (dpy, False);
9700 return x_error_message->string[0] != 0;
9703 /* Forget about any errors we have had, since we did x_catch_errors on DPY. */
9705 void
9706 x_clear_errors (Display *dpy)
9708 x_error_message->string[0] = 0;
9711 #if false
9712 /* See comment in unwind_to_catch why calling this is a bad
9713 * idea. --lorentey */
9714 /* Close off all unclosed x_catch_errors calls. */
9716 void
9717 x_fully_uncatch_errors (void)
9719 while (x_error_message)
9720 x_uncatch_errors ();
9722 #endif
9724 #if false
9725 static unsigned int x_wire_count;
9726 x_trace_wire (void)
9728 fprintf (stderr, "Lib call: %d\n", ++x_wire_count);
9730 #endif
9733 /************************************************************************
9734 Handling X errors
9735 ************************************************************************/
9737 /* Error message passed to x_connection_closed. */
9739 static char *error_msg;
9741 /* Handle the loss of connection to display DPY. ERROR_MESSAGE is
9742 the text of an error message that lead to the connection loss. */
9744 static _Noreturn void
9745 x_connection_closed (Display *dpy, const char *error_message, bool ioerror)
9747 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
9748 Lisp_Object frame, tail;
9749 ptrdiff_t idx = SPECPDL_INDEX ();
9751 error_msg = alloca (strlen (error_message) + 1);
9752 strcpy (error_msg, error_message);
9754 /* Inhibit redisplay while frames are being deleted. */
9755 specbind (Qinhibit_redisplay, Qt);
9757 if (dpyinfo)
9759 /* Protect display from being closed when we delete the last
9760 frame on it. */
9761 dpyinfo->reference_count++;
9762 dpyinfo->terminal->reference_count++;
9764 if (ioerror) dpyinfo->display = 0;
9766 /* First delete frames whose mini-buffers are on frames
9767 that are on the dead display. */
9768 FOR_EACH_FRAME (tail, frame)
9770 Lisp_Object minibuf_frame;
9771 minibuf_frame
9772 = WINDOW_FRAME (XWINDOW (FRAME_MINIBUF_WINDOW (XFRAME (frame))));
9773 if (FRAME_X_P (XFRAME (frame))
9774 && FRAME_X_P (XFRAME (minibuf_frame))
9775 && ! EQ (frame, minibuf_frame)
9776 && FRAME_DISPLAY_INFO (XFRAME (minibuf_frame)) == dpyinfo)
9777 delete_frame (frame, Qnoelisp);
9780 /* Now delete all remaining frames on the dead display.
9781 We are now sure none of these is used as the mini-buffer
9782 for another frame that we need to delete. */
9783 FOR_EACH_FRAME (tail, frame)
9784 if (FRAME_X_P (XFRAME (frame))
9785 && FRAME_DISPLAY_INFO (XFRAME (frame)) == dpyinfo)
9787 /* Set this to t so that delete_frame won't get confused
9788 trying to find a replacement. */
9789 kset_default_minibuffer_frame (FRAME_KBOARD (XFRAME (frame)), Qt);
9790 delete_frame (frame, Qnoelisp);
9793 /* If DPYINFO is null, this means we didn't open the display in the
9794 first place, so don't try to close it. */
9795 if (dpyinfo)
9797 /* We can not call XtCloseDisplay here because it calls XSync.
9798 XSync inside the error handler apparently hangs Emacs. On
9799 current Xt versions, this isn't needed either. */
9800 #ifdef USE_GTK
9801 /* A long-standing GTK bug prevents proper disconnect handling
9802 (https://bugzilla.gnome.org/show_bug.cgi?id=85715). Once,
9803 the resulting Glib error message loop filled a user's disk.
9804 To avoid this, kill Emacs unconditionally on disconnect. */
9805 shut_down_emacs (0, Qnil);
9806 fprintf (stderr, "%s\n\
9807 When compiled with GTK, Emacs cannot recover from X disconnects.\n\
9808 This is a GTK bug: https://bugzilla.gnome.org/show_bug.cgi?id=85715\n\
9809 For details, see etc/PROBLEMS.\n",
9810 error_msg);
9811 emacs_abort ();
9812 #endif /* USE_GTK */
9814 /* Indicate that this display is dead. */
9815 dpyinfo->display = 0;
9817 dpyinfo->reference_count--;
9818 dpyinfo->terminal->reference_count--;
9819 if (dpyinfo->reference_count != 0)
9820 /* We have just closed all frames on this display. */
9821 emacs_abort ();
9824 Lisp_Object tmp;
9825 XSETTERMINAL (tmp, dpyinfo->terminal);
9826 Fdelete_terminal (tmp, Qnoelisp);
9830 if (terminal_list == 0)
9832 fprintf (stderr, "%s\n", error_msg);
9833 Fkill_emacs (make_number (70));
9834 /* NOTREACHED */
9837 totally_unblock_input ();
9839 unbind_to (idx, Qnil);
9840 clear_waiting_for_input ();
9842 /* Here, we absolutely have to use a non-local exit (e.g. signal, throw,
9843 longjmp), because returning from this function would get us back into
9844 Xlib's code which will directly call `exit'. */
9845 error ("%s", error_msg);
9848 /* We specifically use it before defining it, so that gcc doesn't inline it,
9849 otherwise gdb doesn't know how to properly put a breakpoint on it. */
9850 static void x_error_quitter (Display *, XErrorEvent *);
9852 /* This is the first-level handler for X protocol errors.
9853 It calls x_error_quitter or x_error_catcher. */
9855 static int
9856 x_error_handler (Display *display, XErrorEvent *event)
9858 #if defined USE_GTK && defined HAVE_GTK3
9859 if ((event->error_code == BadMatch || event->error_code == BadWindow)
9860 && event->request_code == X_SetInputFocus)
9862 return 0;
9864 #endif
9866 if (x_error_message)
9867 x_error_catcher (display, event);
9868 else
9869 x_error_quitter (display, event);
9870 return 0;
9873 /* This is the usual handler for X protocol errors.
9874 It kills all frames on the display that we got the error for.
9875 If that was the only one, it prints an error message and kills Emacs. */
9877 /* .gdbinit puts a breakpoint here, so make sure it is not inlined. */
9879 /* On older GCC versions, just putting x_error_quitter
9880 after x_error_handler prevents inlining into the former. */
9882 static void NO_INLINE
9883 x_error_quitter (Display *display, XErrorEvent *event)
9885 char buf[256], buf1[356];
9887 /* Ignore BadName errors. They can happen because of fonts
9888 or colors that are not defined. */
9890 if (event->error_code == BadName)
9891 return;
9893 /* Note that there is no real way portable across R3/R4 to get the
9894 original error handler. */
9896 XGetErrorText (display, event->error_code, buf, sizeof (buf));
9897 sprintf (buf1, "X protocol error: %s on protocol request %d",
9898 buf, event->request_code);
9899 x_connection_closed (display, buf1, false);
9903 /* This is the handler for X IO errors, always.
9904 It kills all frames on the display that we lost touch with.
9905 If that was the only one, it prints an error message and kills Emacs. */
9907 static _Noreturn int
9908 x_io_error_quitter (Display *display)
9910 char buf[256];
9912 snprintf (buf, sizeof buf, "Connection lost to X server '%s'",
9913 DisplayString (display));
9914 x_connection_closed (display, buf, true);
9915 assume (false);
9918 /* Changing the font of the frame. */
9920 /* Give frame F the font FONT-OBJECT as its default font. The return
9921 value is FONT-OBJECT. FONTSET is an ID of the fontset for the
9922 frame. If it is negative, generate a new fontset from
9923 FONT-OBJECT. */
9925 Lisp_Object
9926 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
9928 struct font *font = XFONT_OBJECT (font_object);
9929 int unit, font_ascent, font_descent;
9930 #ifndef USE_X_TOOLKIT
9931 int old_menu_bar_height = FRAME_MENU_BAR_HEIGHT (f);
9932 Lisp_Object fullscreen;
9933 #endif
9935 if (fontset < 0)
9936 fontset = fontset_from_font (font_object);
9937 FRAME_FONTSET (f) = fontset;
9938 if (FRAME_FONT (f) == font)
9939 /* This font is already set in frame F. There's nothing more to
9940 do. */
9941 return font_object;
9943 FRAME_FONT (f) = font;
9944 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
9945 FRAME_COLUMN_WIDTH (f) = font->average_width;
9946 get_font_ascent_descent (font, &font_ascent, &font_descent);
9947 FRAME_LINE_HEIGHT (f) = font_ascent + font_descent;
9949 #ifndef USE_X_TOOLKIT
9950 FRAME_MENU_BAR_HEIGHT (f) = FRAME_MENU_BAR_LINES (f) * FRAME_LINE_HEIGHT (f);
9951 #endif
9953 /* Compute character columns occupied by scrollbar.
9955 Don't do things differently for non-toolkit scrollbars
9956 (Bug#17163). */
9957 unit = FRAME_COLUMN_WIDTH (f);
9958 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
9959 FRAME_CONFIG_SCROLL_BAR_COLS (f)
9960 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + unit - 1) / unit;
9961 else
9962 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + unit - 1) / unit;
9964 if (FRAME_X_WINDOW (f) != 0)
9966 /* Don't change the size of a tip frame; there's no point in
9967 doing it because it's done in Fx_show_tip, and it leads to
9968 problems because the tip frame has no widget. */
9969 if (!FRAME_TOOLTIP_P (f))
9971 adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
9972 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 3,
9973 false, Qfont);
9974 #ifndef USE_X_TOOLKIT
9975 if (FRAME_MENU_BAR_HEIGHT (f) != old_menu_bar_height
9976 && !f->after_make_frame
9977 && (EQ (frame_inhibit_implied_resize, Qt)
9978 || (CONSP (frame_inhibit_implied_resize)
9979 && NILP (Fmemq (Qfont, frame_inhibit_implied_resize))))
9980 && (NILP (fullscreen = get_frame_param (f, Qfullscreen))
9981 || EQ (fullscreen, Qfullwidth)))
9982 /* If the menu bar height changes, try to keep text height
9983 constant. */
9984 adjust_frame_size
9985 (f, -1, FRAME_TEXT_HEIGHT (f) + FRAME_MENU_BAR_HEIGHT (f)
9986 - old_menu_bar_height, 1, false, Qfont);
9987 #endif /* USE_X_TOOLKIT */
9991 #ifdef HAVE_X_I18N
9992 if (FRAME_XIC (f)
9993 && (FRAME_XIC_STYLE (f) & (XIMPreeditPosition | XIMStatusArea)))
9995 block_input ();
9996 xic_set_xfontset (f, SSDATA (fontset_ascii (fontset)));
9997 unblock_input ();
9999 #endif
10001 return font_object;
10005 /***********************************************************************
10006 X Input Methods
10007 ***********************************************************************/
10009 #ifdef HAVE_X_I18N
10011 #ifdef HAVE_X11R6
10013 /* XIM destroy callback function, which is called whenever the
10014 connection to input method XIM dies. CLIENT_DATA contains a
10015 pointer to the x_display_info structure corresponding to XIM. */
10017 static void
10018 xim_destroy_callback (XIM xim, XPointer client_data, XPointer call_data)
10020 struct x_display_info *dpyinfo = (struct x_display_info *) client_data;
10021 Lisp_Object frame, tail;
10023 block_input ();
10025 /* No need to call XDestroyIC.. */
10026 FOR_EACH_FRAME (tail, frame)
10028 struct frame *f = XFRAME (frame);
10029 if (FRAME_X_P (f) && FRAME_DISPLAY_INFO (f) == dpyinfo)
10031 FRAME_XIC (f) = NULL;
10032 xic_free_xfontset (f);
10036 /* No need to call XCloseIM. */
10037 dpyinfo->xim = NULL;
10038 XFree (dpyinfo->xim_styles);
10039 unblock_input ();
10042 #endif /* HAVE_X11R6 */
10044 /* Open the connection to the XIM server on display DPYINFO.
10045 RESOURCE_NAME is the resource name Emacs uses. */
10047 static void
10048 xim_open_dpy (struct x_display_info *dpyinfo, char *resource_name)
10050 XIM xim;
10052 #ifdef HAVE_XIM
10053 if (use_xim)
10055 if (dpyinfo->xim)
10056 XCloseIM (dpyinfo->xim);
10057 xim = XOpenIM (dpyinfo->display, dpyinfo->xrdb, resource_name,
10058 emacs_class);
10059 dpyinfo->xim = xim;
10061 if (xim)
10063 #ifdef HAVE_X11R6
10064 XIMCallback destroy;
10065 #endif
10067 /* Get supported styles and XIM values. */
10068 XGetIMValues (xim, XNQueryInputStyle, &dpyinfo->xim_styles, NULL);
10070 #ifdef HAVE_X11R6
10071 destroy.callback = xim_destroy_callback;
10072 destroy.client_data = (XPointer)dpyinfo;
10073 XSetIMValues (xim, XNDestroyCallback, &destroy, NULL);
10074 #endif
10078 else
10079 #endif /* HAVE_XIM */
10080 dpyinfo->xim = NULL;
10084 #ifdef HAVE_X11R6_XIM
10086 /* XIM instantiate callback function, which is called whenever an XIM
10087 server is available. DISPLAY is the display of the XIM.
10088 CLIENT_DATA contains a pointer to an xim_inst_t structure created
10089 when the callback was registered. */
10091 static void
10092 xim_instantiate_callback (Display *display, XPointer client_data, XPointer call_data)
10094 struct xim_inst_t *xim_inst = (struct xim_inst_t *) client_data;
10095 struct x_display_info *dpyinfo = xim_inst->dpyinfo;
10097 /* We don't support multiple XIM connections. */
10098 if (dpyinfo->xim)
10099 return;
10101 xim_open_dpy (dpyinfo, xim_inst->resource_name);
10103 /* Create XIC for the existing frames on the same display, as long
10104 as they have no XIC. */
10105 if (dpyinfo->xim && dpyinfo->reference_count > 0)
10107 Lisp_Object tail, frame;
10109 block_input ();
10110 FOR_EACH_FRAME (tail, frame)
10112 struct frame *f = XFRAME (frame);
10114 if (FRAME_X_P (f)
10115 && FRAME_DISPLAY_INFO (f) == xim_inst->dpyinfo)
10116 if (FRAME_XIC (f) == NULL)
10118 create_frame_xic (f);
10119 if (FRAME_XIC_STYLE (f) & XIMStatusArea)
10120 xic_set_statusarea (f);
10121 if (FRAME_XIC_STYLE (f) & XIMPreeditPosition)
10123 struct window *w = XWINDOW (f->selected_window);
10124 xic_set_preeditarea (w, w->cursor.x, w->cursor.y);
10129 unblock_input ();
10133 #endif /* HAVE_X11R6_XIM */
10136 /* Open a connection to the XIM server on display DPYINFO.
10137 RESOURCE_NAME is the resource name for Emacs. On X11R5, open the
10138 connection only at the first time. On X11R6, open the connection
10139 in the XIM instantiate callback function. */
10141 static void
10142 xim_initialize (struct x_display_info *dpyinfo, char *resource_name)
10144 dpyinfo->xim = NULL;
10145 #ifdef HAVE_XIM
10146 if (use_xim)
10148 #ifdef HAVE_X11R6_XIM
10149 struct xim_inst_t *xim_inst = xmalloc (sizeof *xim_inst);
10150 Bool ret;
10152 dpyinfo->xim_callback_data = xim_inst;
10153 xim_inst->dpyinfo = dpyinfo;
10154 xim_inst->resource_name = xstrdup (resource_name);
10155 ret = XRegisterIMInstantiateCallback
10156 (dpyinfo->display, dpyinfo->xrdb, xim_inst->resource_name,
10157 emacs_class, xim_instantiate_callback,
10158 /* This is XPointer in XFree86 but (XPointer *)
10159 on Tru64, at least, hence the configure test. */
10160 (XRegisterIMInstantiateCallback_arg6) xim_inst);
10161 eassert (ret == True);
10162 #else /* not HAVE_X11R6_XIM */
10163 xim_open_dpy (dpyinfo, resource_name);
10164 #endif /* not HAVE_X11R6_XIM */
10166 #endif /* HAVE_XIM */
10170 /* Close the connection to the XIM server on display DPYINFO. */
10172 static void
10173 xim_close_dpy (struct x_display_info *dpyinfo)
10175 #ifdef HAVE_XIM
10176 if (use_xim)
10178 #ifdef HAVE_X11R6_XIM
10179 struct xim_inst_t *xim_inst = dpyinfo->xim_callback_data;
10181 if (dpyinfo->display)
10183 Bool ret = XUnregisterIMInstantiateCallback
10184 (dpyinfo->display, dpyinfo->xrdb, xim_inst->resource_name,
10185 emacs_class, xim_instantiate_callback,
10186 (XRegisterIMInstantiateCallback_arg6) xim_inst);
10187 eassert (ret == True);
10189 xfree (xim_inst->resource_name);
10190 xfree (xim_inst);
10191 #endif /* HAVE_X11R6_XIM */
10192 if (dpyinfo->display)
10193 XCloseIM (dpyinfo->xim);
10194 dpyinfo->xim = NULL;
10195 XFree (dpyinfo->xim_styles);
10197 #endif /* HAVE_XIM */
10200 #endif /* not HAVE_X11R6_XIM */
10204 /* Calculate the absolute position in frame F
10205 from its current recorded position values and gravity. */
10207 static void
10208 x_calc_absolute_position (struct frame *f)
10210 int flags = f->size_hint_flags;
10211 struct frame *p = FRAME_PARENT_FRAME (f);
10213 /* We have nothing to do if the current position
10214 is already for the top-left corner. */
10215 if (! ((flags & XNegative) || (flags & YNegative)))
10216 return;
10218 /* Treat negative positions as relative to the leftmost bottommost
10219 position that fits on the screen. */
10220 if ((flags & XNegative) && (f->left_pos <= 0))
10222 int width = FRAME_PIXEL_WIDTH (f);
10224 /* A frame that has been visible at least once should have outer
10225 edges. */
10226 if (f->output_data.x->has_been_visible && !p)
10228 Lisp_Object frame;
10229 Lisp_Object edges = Qnil;
10231 XSETFRAME (frame, f);
10232 edges = Fx_frame_edges (frame, Qouter_edges);
10233 if (!NILP (edges))
10234 width = (XINT (Fnth (make_number (2), edges))
10235 - XINT (Fnth (make_number (0), edges)));
10238 if (p)
10239 f->left_pos = (FRAME_PIXEL_WIDTH (p) - width - 2 * f->border_width
10240 + f->left_pos);
10241 else
10242 f->left_pos = (x_display_pixel_width (FRAME_DISPLAY_INFO (f))
10243 - width + f->left_pos);
10247 if ((flags & YNegative) && (f->top_pos <= 0))
10249 int height = FRAME_PIXEL_HEIGHT (f);
10251 #if defined USE_X_TOOLKIT && defined USE_MOTIF
10252 /* Something is fishy here. When using Motif, starting Emacs with
10253 `-g -0-0', the frame appears too low by a few pixels.
10255 This seems to be so because initially, while Emacs is starting,
10256 the column widget's height and the frame's pixel height are
10257 different. The column widget's height is the right one. In
10258 later invocations, when Emacs is up, the frame's pixel height
10259 is right, though.
10261 It's not obvious where the initial small difference comes from.
10262 2000-12-01, gerd. */
10264 XtVaGetValues (f->output_data.x->column_widget, XtNheight, &height, NULL);
10265 #endif
10267 if (f->output_data.x->has_been_visible && !p)
10269 Lisp_Object frame;
10270 Lisp_Object edges = Qnil;
10272 XSETFRAME (frame, f);
10273 if (NILP (edges))
10274 edges = Fx_frame_edges (frame, Qouter_edges);
10275 if (!NILP (edges))
10276 height = (XINT (Fnth (make_number (3), edges))
10277 - XINT (Fnth (make_number (1), edges)));
10280 if (p)
10281 f->top_pos = (FRAME_PIXEL_HEIGHT (p) - height - 2 * f->border_width
10282 + f->top_pos);
10283 else
10284 f->top_pos = (x_display_pixel_height (FRAME_DISPLAY_INFO (f))
10285 - height + f->top_pos);
10288 /* The left_pos and top_pos
10289 are now relative to the top and left screen edges,
10290 so the flags should correspond. */
10291 f->size_hint_flags &= ~ (XNegative | YNegative);
10294 /* CHANGE_GRAVITY is 1 when calling from Fset_frame_position,
10295 to really change the position, and 0 when calling from
10296 x_make_frame_visible (in that case, XOFF and YOFF are the current
10297 position values). It is -1 when calling from x_set_frame_parameters,
10298 which means, do adjust for borders but don't change the gravity. */
10300 void
10301 x_set_offset (struct frame *f, register int xoff, register int yoff, int change_gravity)
10303 int modified_top, modified_left;
10305 if (change_gravity > 0)
10307 f->top_pos = yoff;
10308 f->left_pos = xoff;
10309 f->size_hint_flags &= ~ (XNegative | YNegative);
10310 if (xoff < 0)
10311 f->size_hint_flags |= XNegative;
10312 if (yoff < 0)
10313 f->size_hint_flags |= YNegative;
10314 f->win_gravity = NorthWestGravity;
10317 x_calc_absolute_position (f);
10319 block_input ();
10320 x_wm_set_size_hint (f, 0, false);
10322 #ifdef USE_GTK
10323 if (x_gtk_use_window_move)
10325 /* When a position change was requested and the outer GTK widget
10326 has been realized already, leave it to gtk_window_move to DTRT
10327 and return. Used for Bug#25851 and Bug#25943. */
10328 if (change_gravity != 0 && FRAME_GTK_OUTER_WIDGET (f))
10329 gtk_window_move (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)),
10330 f->left_pos, f->top_pos);
10331 unblock_input ();
10332 return;
10334 #endif /* USE_GTK */
10336 modified_left = f->left_pos;
10337 modified_top = f->top_pos;
10339 if (change_gravity != 0 && FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A)
10341 /* Some WMs (twm, wmaker at least) has an offset that is smaller
10342 than the WM decorations. So we use the calculated offset instead
10343 of the WM decoration sizes here (x/y_pixels_outer_diff). */
10344 modified_left += FRAME_X_OUTPUT (f)->move_offset_left;
10345 modified_top += FRAME_X_OUTPUT (f)->move_offset_top;
10348 #ifdef USE_GTK
10349 gtk_window_move (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)),
10350 modified_left, modified_top);
10351 #else
10352 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
10353 modified_left, modified_top);
10354 #endif
10356 x_sync_with_move (f, f->left_pos, f->top_pos,
10357 FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN);
10359 /* change_gravity is non-zero when this function is called from Lisp to
10360 programmatically move a frame. In that case, we call
10361 x_check_expected_move to discover if we have a "Type A" or "Type B"
10362 window manager, and, for a "Type A" window manager, adjust the position
10363 of the frame.
10365 We call x_check_expected_move if a programmatic move occurred, and
10366 either the window manager type (A/B) is unknown or it is Type A but we
10367 need to compute the top/left offset adjustment for this frame. */
10369 if (change_gravity != 0
10370 && !FRAME_PARENT_FRAME (f)
10371 && (FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN
10372 || (FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A
10373 && (FRAME_X_OUTPUT (f)->move_offset_left == 0
10374 && FRAME_X_OUTPUT (f)->move_offset_top == 0))))
10375 x_check_expected_move (f, modified_left, modified_top);
10377 unblock_input ();
10380 /* Return true if _NET_SUPPORTING_WM_CHECK window exists and _NET_SUPPORTED
10381 on the root window for frame F contains ATOMNAME.
10382 This is how a WM check shall be done according to the Window Manager
10383 Specification/Extended Window Manager Hints at
10384 http://freedesktop.org/wiki/Specifications/wm-spec. */
10386 bool
10387 x_wm_supports (struct frame *f, Atom want_atom)
10389 Atom actual_type;
10390 unsigned long actual_size, bytes_remaining;
10391 int i, rc, actual_format;
10392 bool ret;
10393 Window wmcheck_window;
10394 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10395 Window target_window = dpyinfo->root_window;
10396 int max_len = 65536;
10397 Display *dpy = FRAME_X_DISPLAY (f);
10398 unsigned char *tmp_data = NULL;
10399 Atom target_type = XA_WINDOW;
10401 block_input ();
10403 x_catch_errors (dpy);
10404 rc = XGetWindowProperty (dpy, target_window,
10405 dpyinfo->Xatom_net_supporting_wm_check,
10406 0, max_len, False, target_type,
10407 &actual_type, &actual_format, &actual_size,
10408 &bytes_remaining, &tmp_data);
10410 if (rc != Success || actual_type != XA_WINDOW || x_had_errors_p (dpy))
10412 if (tmp_data) XFree (tmp_data);
10413 x_uncatch_errors ();
10414 unblock_input ();
10415 return false;
10418 wmcheck_window = *(Window *) tmp_data;
10419 XFree (tmp_data);
10421 /* Check if window exists. */
10422 XSelectInput (dpy, wmcheck_window, StructureNotifyMask);
10423 if (x_had_errors_p (dpy))
10425 x_uncatch_errors_after_check ();
10426 unblock_input ();
10427 return false;
10430 if (dpyinfo->net_supported_window != wmcheck_window)
10432 /* Window changed, reload atoms */
10433 if (dpyinfo->net_supported_atoms != NULL)
10434 XFree (dpyinfo->net_supported_atoms);
10435 dpyinfo->net_supported_atoms = NULL;
10436 dpyinfo->nr_net_supported_atoms = 0;
10437 dpyinfo->net_supported_window = 0;
10439 target_type = XA_ATOM;
10440 tmp_data = NULL;
10441 rc = XGetWindowProperty (dpy, target_window,
10442 dpyinfo->Xatom_net_supported,
10443 0, max_len, False, target_type,
10444 &actual_type, &actual_format, &actual_size,
10445 &bytes_remaining, &tmp_data);
10447 if (rc != Success || actual_type != XA_ATOM || x_had_errors_p (dpy))
10449 if (tmp_data) XFree (tmp_data);
10450 x_uncatch_errors ();
10451 unblock_input ();
10452 return false;
10455 dpyinfo->net_supported_atoms = (Atom *)tmp_data;
10456 dpyinfo->nr_net_supported_atoms = actual_size;
10457 dpyinfo->net_supported_window = wmcheck_window;
10460 ret = false;
10462 for (i = 0; !ret && i < dpyinfo->nr_net_supported_atoms; ++i)
10463 ret = dpyinfo->net_supported_atoms[i] == want_atom;
10465 x_uncatch_errors ();
10466 unblock_input ();
10468 return ret;
10471 static void
10472 set_wm_state (Lisp_Object frame, bool add, Atom atom, Atom value)
10474 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (XFRAME (frame));
10476 x_send_client_event (frame, make_number (0), frame,
10477 dpyinfo->Xatom_net_wm_state,
10478 make_number (32),
10479 /* 1 = add, 0 = remove */
10480 Fcons
10481 (make_number (add),
10482 Fcons
10483 (make_fixnum_or_float (atom),
10484 (value != 0
10485 ? list1 (make_fixnum_or_float (value))
10486 : Qnil))));
10489 void
10490 x_set_sticky (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
10492 Lisp_Object frame;
10493 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10495 XSETFRAME (frame, f);
10497 set_wm_state (frame, !NILP (new_value),
10498 dpyinfo->Xatom_net_wm_state_sticky, None);
10502 * x_set_skip_taskbar:
10504 * Set frame F's `skip-taskbar' parameter. If non-nil, this should
10505 * remove F's icon from the taskbar associated with the display of F's
10506 * window-system window and inhibit switching to F's window via
10507 * <Alt>-<TAB>. If nil, lift these restrictions.
10509 * Some window managers may not honor this parameter.
10511 void
10512 x_set_skip_taskbar (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
10514 if (!EQ (new_value, old_value))
10516 #ifdef USE_GTK
10517 xg_set_skip_taskbar (f, new_value);
10518 #else
10519 Lisp_Object frame;
10520 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10522 XSETFRAME (frame, f);
10523 set_wm_state (frame, !NILP (new_value),
10524 dpyinfo->Xatom_net_wm_state_skip_taskbar, None);
10525 #endif /* USE_GTK */
10526 FRAME_SKIP_TASKBAR (f) = !NILP (new_value);
10531 * x_set_z_group:
10533 * Set frame F's `z-group' parameter. If `above', F's window-system
10534 * window is displayed above all windows that do not have the `above'
10535 * property set. If nil, F's window is shown below all windows that
10536 * have the `above' property set and above all windows that have the
10537 * `below' property set. If `below', F's window is displayed below all
10538 * windows that do not have the `below' property set.
10540 * Some window managers may not honor this parameter.
10542 void
10543 x_set_z_group (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
10545 /* We don't care about old_value. The window manager might have
10546 reset the value without telling us. */
10547 Lisp_Object frame;
10548 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10550 XSETFRAME (frame, f);
10552 if (NILP (new_value))
10554 set_wm_state (frame, false,
10555 dpyinfo->Xatom_net_wm_state_above, None);
10556 set_wm_state (frame, false,
10557 dpyinfo->Xatom_net_wm_state_below, None);
10558 FRAME_Z_GROUP (f) = z_group_none;
10560 else if (EQ (new_value, Qabove))
10562 set_wm_state (frame, true,
10563 dpyinfo->Xatom_net_wm_state_above, None);
10564 set_wm_state (frame, false,
10565 dpyinfo->Xatom_net_wm_state_below, None);
10566 FRAME_Z_GROUP (f) = z_group_above;
10568 else if (EQ (new_value, Qbelow))
10570 set_wm_state (frame, false,
10571 dpyinfo->Xatom_net_wm_state_above, None);
10572 set_wm_state (frame, true,
10573 dpyinfo->Xatom_net_wm_state_below, None);
10574 FRAME_Z_GROUP (f) = z_group_below;
10576 else if (EQ (new_value, Qabove_suspended))
10578 set_wm_state (frame, false,
10579 dpyinfo->Xatom_net_wm_state_above, None);
10580 FRAME_Z_GROUP (f) = z_group_above_suspended;
10582 else
10583 error ("Invalid z-group specification");
10587 /* Return the current _NET_WM_STATE.
10588 SIZE_STATE is set to one of the FULLSCREEN_* values.
10589 Set *STICKY to the sticky state.
10591 Return true iff we are not hidden. */
10593 static bool
10594 get_current_wm_state (struct frame *f,
10595 Window window,
10596 int *size_state,
10597 bool *sticky)
10599 unsigned long actual_size;
10600 int i;
10601 bool is_hidden = false;
10602 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10603 long max_len = 65536;
10604 Atom target_type = XA_ATOM;
10605 /* If XCB is available, we can avoid three XSync calls. */
10606 #ifdef USE_XCB
10607 xcb_get_property_cookie_t prop_cookie;
10608 xcb_get_property_reply_t *prop;
10609 xcb_atom_t *reply_data;
10610 #else
10611 Display *dpy = FRAME_X_DISPLAY (f);
10612 unsigned long bytes_remaining;
10613 int rc, actual_format;
10614 Atom actual_type;
10615 unsigned char *tmp_data = NULL;
10616 Atom *reply_data;
10617 #endif
10619 *sticky = false;
10620 *size_state = FULLSCREEN_NONE;
10622 block_input ();
10624 #ifdef USE_XCB
10625 prop_cookie = xcb_get_property (dpyinfo->xcb_connection, 0, window,
10626 dpyinfo->Xatom_net_wm_state,
10627 target_type, 0, max_len);
10628 prop = xcb_get_property_reply (dpyinfo->xcb_connection, prop_cookie, NULL);
10629 if (prop && prop->type == target_type)
10631 int actual_bytes = xcb_get_property_value_length (prop);
10632 eassume (0 <= actual_bytes);
10633 actual_size = actual_bytes / sizeof *reply_data;
10634 reply_data = xcb_get_property_value (prop);
10636 else
10638 actual_size = 0;
10639 is_hidden = FRAME_ICONIFIED_P (f);
10641 #else
10642 x_catch_errors (dpy);
10643 rc = XGetWindowProperty (dpy, window, dpyinfo->Xatom_net_wm_state,
10644 0, max_len, False, target_type,
10645 &actual_type, &actual_format, &actual_size,
10646 &bytes_remaining, &tmp_data);
10648 if (rc == Success && actual_type == target_type && ! x_had_errors_p (dpy))
10649 reply_data = (Atom *) tmp_data;
10650 else
10652 actual_size = 0;
10653 is_hidden = FRAME_ICONIFIED_P (f);
10656 x_uncatch_errors ();
10657 #endif
10659 for (i = 0; i < actual_size; ++i)
10661 Atom a = reply_data[i];
10662 if (a == dpyinfo->Xatom_net_wm_state_hidden)
10663 is_hidden = true;
10664 else if (a == dpyinfo->Xatom_net_wm_state_maximized_horz)
10666 if (*size_state == FULLSCREEN_HEIGHT)
10667 *size_state = FULLSCREEN_MAXIMIZED;
10668 else
10669 *size_state = FULLSCREEN_WIDTH;
10671 else if (a == dpyinfo->Xatom_net_wm_state_maximized_vert)
10673 if (*size_state == FULLSCREEN_WIDTH)
10674 *size_state = FULLSCREEN_MAXIMIZED;
10675 else
10676 *size_state = FULLSCREEN_HEIGHT;
10678 else if (a == dpyinfo->Xatom_net_wm_state_fullscreen)
10679 *size_state = FULLSCREEN_BOTH;
10680 else if (a == dpyinfo->Xatom_net_wm_state_sticky)
10681 *sticky = true;
10684 #ifdef USE_XCB
10685 free (prop);
10686 #else
10687 if (tmp_data) XFree (tmp_data);
10688 #endif
10690 unblock_input ();
10691 return ! is_hidden;
10694 /* Do fullscreen as specified in extended window manager hints */
10696 static bool
10697 do_ewmh_fullscreen (struct frame *f)
10699 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10700 bool have_net_atom = x_wm_supports (f, dpyinfo->Xatom_net_wm_state);
10701 int cur;
10702 bool dummy;
10704 get_current_wm_state (f, FRAME_OUTER_WINDOW (f), &cur, &dummy);
10706 /* Some window managers don't say they support _NET_WM_STATE, but they do say
10707 they support _NET_WM_STATE_FULLSCREEN. Try that also. */
10708 if (!have_net_atom)
10709 have_net_atom = x_wm_supports (f, dpyinfo->Xatom_net_wm_state_fullscreen);
10711 if (have_net_atom && cur != f->want_fullscreen)
10713 Lisp_Object frame;
10715 XSETFRAME (frame, f);
10717 /* Keep number of calls to set_wm_state as low as possible.
10718 Some window managers, or possible Gtk+, hangs when too many
10719 are sent at once. */
10720 switch (f->want_fullscreen)
10722 case FULLSCREEN_BOTH:
10723 if (cur != FULLSCREEN_BOTH)
10724 set_wm_state (frame, true, dpyinfo->Xatom_net_wm_state_fullscreen,
10725 None);
10726 break;
10727 case FULLSCREEN_WIDTH:
10728 if (x_frame_normalize_before_maximize && cur == FULLSCREEN_MAXIMIZED)
10730 set_wm_state (frame, false,
10731 dpyinfo->Xatom_net_wm_state_maximized_horz,
10732 dpyinfo->Xatom_net_wm_state_maximized_vert);
10733 set_wm_state (frame, true,
10734 dpyinfo->Xatom_net_wm_state_maximized_horz, None);
10736 else
10738 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_HEIGHT
10739 || cur == FULLSCREEN_MAXIMIZED)
10740 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
10741 dpyinfo->Xatom_net_wm_state_maximized_vert);
10742 if (cur != FULLSCREEN_MAXIMIZED || x_frame_normalize_before_maximize)
10743 set_wm_state (frame, true,
10744 dpyinfo->Xatom_net_wm_state_maximized_horz, None);
10746 break;
10747 case FULLSCREEN_HEIGHT:
10748 if (x_frame_normalize_before_maximize && cur == FULLSCREEN_MAXIMIZED)
10750 set_wm_state (frame, false,
10751 dpyinfo->Xatom_net_wm_state_maximized_horz,
10752 dpyinfo->Xatom_net_wm_state_maximized_vert);
10753 set_wm_state (frame, true,
10754 dpyinfo->Xatom_net_wm_state_maximized_vert, None);
10756 else
10758 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_WIDTH
10759 || cur == FULLSCREEN_MAXIMIZED)
10760 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
10761 dpyinfo->Xatom_net_wm_state_maximized_horz);
10762 if (cur != FULLSCREEN_MAXIMIZED || x_frame_normalize_before_maximize)
10763 set_wm_state (frame, true,
10764 dpyinfo->Xatom_net_wm_state_maximized_vert, None);
10766 break;
10767 case FULLSCREEN_MAXIMIZED:
10768 if (x_frame_normalize_before_maximize && cur == FULLSCREEN_BOTH)
10770 set_wm_state (frame, false,
10771 dpyinfo->Xatom_net_wm_state_fullscreen, None);
10772 set_wm_state (frame, true,
10773 dpyinfo->Xatom_net_wm_state_maximized_horz,
10774 dpyinfo->Xatom_net_wm_state_maximized_vert);
10776 else if (x_frame_normalize_before_maximize && cur == FULLSCREEN_WIDTH)
10778 set_wm_state (frame, false,
10779 dpyinfo->Xatom_net_wm_state_maximized_horz, None);
10780 set_wm_state (frame, true,
10781 dpyinfo->Xatom_net_wm_state_maximized_horz,
10782 dpyinfo->Xatom_net_wm_state_maximized_vert);
10784 else if (x_frame_normalize_before_maximize && cur == FULLSCREEN_HEIGHT)
10786 set_wm_state (frame, false,
10787 dpyinfo->Xatom_net_wm_state_maximized_vert, None);
10788 set_wm_state (frame, true,
10789 dpyinfo->Xatom_net_wm_state_maximized_horz,
10790 dpyinfo->Xatom_net_wm_state_maximized_vert);
10792 else
10794 if (cur == FULLSCREEN_BOTH)
10795 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
10796 None);
10797 else if (cur == FULLSCREEN_HEIGHT)
10798 set_wm_state (frame, true,
10799 dpyinfo->Xatom_net_wm_state_maximized_horz, None);
10800 else if (cur == FULLSCREEN_WIDTH)
10801 set_wm_state (frame, true, None,
10802 dpyinfo->Xatom_net_wm_state_maximized_vert);
10803 else
10804 set_wm_state (frame, true,
10805 dpyinfo->Xatom_net_wm_state_maximized_horz,
10806 dpyinfo->Xatom_net_wm_state_maximized_vert);
10808 break;
10809 case FULLSCREEN_NONE:
10810 if (cur == FULLSCREEN_BOTH)
10811 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
10812 None);
10813 else
10814 set_wm_state (frame, false,
10815 dpyinfo->Xatom_net_wm_state_maximized_horz,
10816 dpyinfo->Xatom_net_wm_state_maximized_vert);
10819 f->want_fullscreen = FULLSCREEN_NONE;
10823 return have_net_atom;
10826 static void
10827 XTfullscreen_hook (struct frame *f)
10829 if (FRAME_VISIBLE_P (f))
10831 block_input ();
10832 x_check_fullscreen (f);
10833 x_sync (f);
10834 unblock_input ();
10839 static bool
10840 x_handle_net_wm_state (struct frame *f, const XPropertyEvent *event)
10842 int value = FULLSCREEN_NONE;
10843 Lisp_Object lval;
10844 bool sticky = false;
10845 bool not_hidden = get_current_wm_state (f, event->window, &value, &sticky);
10847 lval = Qnil;
10848 switch (value)
10850 case FULLSCREEN_WIDTH:
10851 lval = Qfullwidth;
10852 break;
10853 case FULLSCREEN_HEIGHT:
10854 lval = Qfullheight;
10855 break;
10856 case FULLSCREEN_BOTH:
10857 lval = Qfullboth;
10858 break;
10859 case FULLSCREEN_MAXIMIZED:
10860 lval = Qmaximized;
10861 break;
10864 frame_size_history_add
10865 (f, Qx_handle_net_wm_state, 0, 0,
10866 list2 (get_frame_param (f, Qfullscreen), lval));
10868 store_frame_param (f, Qfullscreen, lval);
10869 store_frame_param (f, Qsticky, sticky ? Qt : Qnil);
10871 return not_hidden;
10874 /* Check if we need to resize the frame due to a fullscreen request.
10875 If so needed, resize the frame. */
10876 static void
10877 x_check_fullscreen (struct frame *f)
10879 Lisp_Object lval = Qnil;
10881 if (do_ewmh_fullscreen (f))
10882 return;
10884 if (f->output_data.x->parent_desc != FRAME_DISPLAY_INFO (f)->root_window)
10885 return; /* Only fullscreen without WM or with EWM hints (above). */
10887 /* Setting fullscreen to nil doesn't do anything. We could save the
10888 last non-fullscreen size and restore it, but it seems like a
10889 lot of work for this unusual case (no window manager running). */
10891 if (f->want_fullscreen != FULLSCREEN_NONE)
10893 int width = FRAME_PIXEL_WIDTH (f), height = FRAME_PIXEL_HEIGHT (f);
10894 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10896 switch (f->want_fullscreen)
10898 /* No difference between these two when there is no WM */
10899 case FULLSCREEN_MAXIMIZED:
10900 lval = Qmaximized;
10901 width = x_display_pixel_width (dpyinfo);
10902 height = x_display_pixel_height (dpyinfo);
10903 break;
10904 case FULLSCREEN_BOTH:
10905 lval = Qfullboth;
10906 width = x_display_pixel_width (dpyinfo);
10907 height = x_display_pixel_height (dpyinfo);
10908 break;
10909 case FULLSCREEN_WIDTH:
10910 lval = Qfullwidth;
10911 width = x_display_pixel_width (dpyinfo);
10912 height = height + FRAME_MENUBAR_HEIGHT (f);
10913 break;
10914 case FULLSCREEN_HEIGHT:
10915 lval = Qfullheight;
10916 height = x_display_pixel_height (dpyinfo);
10917 break;
10918 default:
10919 emacs_abort ();
10922 frame_size_history_add
10923 (f, Qx_check_fullscreen, width, height, Qnil);
10925 x_wm_set_size_hint (f, 0, false);
10927 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
10928 width, height);
10930 if (FRAME_VISIBLE_P (f))
10931 x_wait_for_event (f, ConfigureNotify);
10932 else
10934 change_frame_size (f, width, height - FRAME_MENUBAR_HEIGHT (f),
10935 false, true, false, true);
10936 x_sync (f);
10940 /* `x_net_wm_state' might have reset the fullscreen frame parameter,
10941 restore it. */
10942 store_frame_param (f, Qfullscreen, lval);
10945 /* This function is called by x_set_offset to determine whether the window
10946 manager interfered with the positioning of the frame. Type A window
10947 managers position the surrounding window manager decorations a small
10948 amount above and left of the user-supplied position. Type B window
10949 managers position the surrounding window manager decorations at the
10950 user-specified position. If we detect a Type A window manager, we
10951 compensate by moving the window right and down by the proper amount. */
10953 static void
10954 x_check_expected_move (struct frame *f, int expected_left, int expected_top)
10956 int current_left = 0, current_top = 0;
10958 /* x_real_positions returns the left and top offsets of the outermost
10959 window manager window around the frame. */
10961 x_real_positions (f, &current_left, &current_top);
10963 if (current_left != expected_left || current_top != expected_top)
10965 /* It's a "Type A" window manager. */
10967 int adjusted_left;
10968 int adjusted_top;
10970 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_A;
10971 FRAME_X_OUTPUT (f)->move_offset_left = expected_left - current_left;
10972 FRAME_X_OUTPUT (f)->move_offset_top = expected_top - current_top;
10974 /* Now fix the mispositioned frame's location. */
10976 adjusted_left = expected_left + FRAME_X_OUTPUT (f)->move_offset_left;
10977 adjusted_top = expected_top + FRAME_X_OUTPUT (f)->move_offset_top;
10979 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
10980 adjusted_left, adjusted_top);
10982 x_sync_with_move (f, expected_left, expected_top, false);
10984 else
10985 /* It's a "Type B" window manager. We don't have to adjust the
10986 frame's position. */
10988 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_B;
10992 /* Wait for XGetGeometry to return up-to-date position information for a
10993 recently-moved frame. Call this immediately after calling XMoveWindow.
10994 If FUZZY is non-zero, then LEFT and TOP are just estimates of where the
10995 frame has been moved to, so we use a fuzzy position comparison instead
10996 of an exact comparison. */
10998 static void
10999 x_sync_with_move (struct frame *f, int left, int top, bool fuzzy)
11001 int count = 0;
11003 while (count++ < 50)
11005 int current_left = 0, current_top = 0;
11007 /* In theory, this call to XSync only needs to happen once, but in
11008 practice, it doesn't seem to work, hence the need for the surrounding
11009 loop. */
11011 XSync (FRAME_X_DISPLAY (f), False);
11012 x_real_positions (f, &current_left, &current_top);
11014 if (fuzzy)
11016 /* The left fuzz-factor is 10 pixels. The top fuzz-factor is 40
11017 pixels. */
11019 if (eabs (current_left - left) <= 10
11020 && eabs (current_top - top) <= 40)
11021 return;
11023 else if (current_left == left && current_top == top)
11024 return;
11027 /* As a last resort, just wait 0.5 seconds and hope that XGetGeometry
11028 will then return up-to-date position info. */
11030 wait_reading_process_output (0, 500000000, 0, false, Qnil, NULL, 0);
11034 /* Wait for an event on frame F matching EVENTTYPE. */
11035 void
11036 x_wait_for_event (struct frame *f, int eventtype)
11038 if (!FLOATP (Vx_wait_for_event_timeout))
11039 return;
11041 int level = interrupt_input_blocked;
11042 fd_set fds;
11043 struct timespec tmo, tmo_at, time_now;
11044 int fd = ConnectionNumber (FRAME_X_DISPLAY (f));
11046 f->wait_event_type = eventtype;
11048 /* Default timeout is 0.1 second. Hopefully not noticeable. */
11049 double timeout = XFLOAT_DATA (Vx_wait_for_event_timeout);
11050 time_t timeout_seconds = (time_t) timeout;
11051 tmo = make_timespec
11052 (timeout_seconds, (long int) ((timeout - timeout_seconds)
11053 * 1000 * 1000 * 1000));
11054 tmo_at = timespec_add (current_timespec (), tmo);
11056 while (f->wait_event_type)
11058 pending_signals = true;
11059 totally_unblock_input ();
11060 /* XTread_socket is called after unblock. */
11061 block_input ();
11062 interrupt_input_blocked = level;
11064 FD_ZERO (&fds);
11065 FD_SET (fd, &fds);
11067 time_now = current_timespec ();
11068 if (timespec_cmp (tmo_at, time_now) < 0)
11069 break;
11071 tmo = timespec_sub (tmo_at, time_now);
11072 if (pselect (fd + 1, &fds, NULL, NULL, &tmo, NULL) == 0)
11073 break; /* Timeout */
11076 f->wait_event_type = 0;
11080 /* Change the size of frame F's X window to WIDTH/HEIGHT in the case F
11081 doesn't have a widget. If CHANGE_GRAVITY, change to
11082 top-left-corner window gravity for this size change and subsequent
11083 size changes. Otherwise leave the window gravity unchanged. */
11085 static void
11086 x_set_window_size_1 (struct frame *f, bool change_gravity,
11087 int width, int height)
11089 int pixelwidth = FRAME_TEXT_TO_PIXEL_WIDTH (f, width);
11090 int pixelheight = FRAME_TEXT_TO_PIXEL_HEIGHT (f, height);
11091 int old_width = FRAME_PIXEL_WIDTH (f);
11092 int old_height = FRAME_PIXEL_HEIGHT (f);
11093 Lisp_Object fullscreen = get_frame_param (f, Qfullscreen);
11095 if (change_gravity)
11096 f->win_gravity = NorthWestGravity;
11097 x_wm_set_size_hint (f, 0, false);
11099 /* When the frame is fullheight and we only want to change the width
11100 or it is fullwidth and we only want to change the height we should
11101 be able to preserve the fullscreen property. However, due to the
11102 fact that we have to send a resize request anyway, the window
11103 manager will abolish it. At least the respective size should
11104 remain unchanged but giving the frame back its normal size will
11105 be broken ... */
11106 if (EQ (fullscreen, Qfullwidth) && width == FRAME_TEXT_WIDTH (f))
11108 frame_size_history_add
11109 (f, Qx_set_window_size_1, width, height,
11110 list2 (make_number (old_height),
11111 make_number (pixelheight + FRAME_MENUBAR_HEIGHT (f))));
11113 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11114 old_width, pixelheight + FRAME_MENUBAR_HEIGHT (f));
11116 else if (EQ (fullscreen, Qfullheight) && height == FRAME_TEXT_HEIGHT (f))
11118 frame_size_history_add
11119 (f, Qx_set_window_size_2, width, height,
11120 list2 (make_number (old_width), make_number (pixelwidth)));
11122 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11123 pixelwidth, old_height);
11126 else
11128 frame_size_history_add
11129 (f, Qx_set_window_size_3, width, height,
11130 list3 (make_number (pixelwidth + FRAME_TOOLBAR_WIDTH (f)),
11131 make_number (pixelheight + FRAME_TOOLBAR_HEIGHT (f)
11132 + FRAME_MENUBAR_HEIGHT (f)),
11133 make_number (FRAME_MENUBAR_HEIGHT (f))));
11135 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11136 pixelwidth, pixelheight + FRAME_MENUBAR_HEIGHT (f));
11137 fullscreen = Qnil;
11142 /* We've set {FRAME,PIXEL}_{WIDTH,HEIGHT} to the values we hope to
11143 receive in the ConfigureNotify event; if we get what we asked
11144 for, then the event won't cause the screen to become garbaged, so
11145 we have to make sure to do it here. */
11146 SET_FRAME_GARBAGED (f);
11148 /* Now, strictly speaking, we can't be sure that this is accurate,
11149 but the window manager will get around to dealing with the size
11150 change request eventually, and we'll hear how it went when the
11151 ConfigureNotify event gets here.
11153 We could just not bother storing any of this information here,
11154 and let the ConfigureNotify event set everything up, but that
11155 might be kind of confusing to the Lisp code, since size changes
11156 wouldn't be reported in the frame parameters until some random
11157 point in the future when the ConfigureNotify event arrives.
11159 Pass true for DELAY since we can't run Lisp code inside of
11160 a BLOCK_INPUT. */
11162 /* But the ConfigureNotify may in fact never arrive, and then this is
11163 not right if the frame is visible. Instead wait (with timeout)
11164 for the ConfigureNotify. */
11165 if (FRAME_VISIBLE_P (f))
11167 x_wait_for_event (f, ConfigureNotify);
11169 if (!NILP (fullscreen))
11170 /* Try to restore fullscreen state. */
11172 store_frame_param (f, Qfullscreen, fullscreen);
11173 x_set_fullscreen (f, fullscreen, fullscreen);
11176 else
11178 change_frame_size (f, width, height, false, true, false, true);
11179 x_sync (f);
11184 /* Call this to change the size of frame F's x-window.
11185 If CHANGE_GRAVITY, change to top-left-corner window gravity
11186 for this size change and subsequent size changes.
11187 Otherwise we leave the window gravity unchanged. */
11189 void
11190 x_set_window_size (struct frame *f, bool change_gravity,
11191 int width, int height, bool pixelwise)
11193 block_input ();
11195 /* The following breaks our calculations. If it's really needed,
11196 think of something else. */
11197 #if false
11198 if (!FRAME_TOOLTIP_P (f))
11200 int text_width, text_height;
11202 /* When the frame is maximized/fullscreen or running under for
11203 example Xmonad, x_set_window_size_1 will be a no-op.
11204 In that case, the right thing to do is extend rows/width to
11205 the current frame size. We do that first if x_set_window_size_1
11206 turns out to not be a no-op (there is no way to know).
11207 The size will be adjusted again if the frame gets a
11208 ConfigureNotify event as a result of x_set_window_size. */
11209 int pixelh = FRAME_PIXEL_HEIGHT (f);
11210 #ifdef USE_X_TOOLKIT
11211 /* The menu bar is not part of text lines. The tool bar
11212 is however. */
11213 pixelh -= FRAME_MENUBAR_HEIGHT (f);
11214 #endif
11215 text_width = FRAME_PIXEL_TO_TEXT_WIDTH (f, FRAME_PIXEL_WIDTH (f));
11216 text_height = FRAME_PIXEL_TO_TEXT_HEIGHT (f, pixelh);
11218 change_frame_size (f, text_width, text_height, false, true, false, true);
11220 #endif
11222 /* Pixelize width and height, if necessary. */
11223 if (! pixelwise)
11225 width = width * FRAME_COLUMN_WIDTH (f);
11226 height = height * FRAME_LINE_HEIGHT (f);
11229 #ifdef USE_GTK
11230 if (FRAME_GTK_WIDGET (f))
11231 xg_frame_set_char_size (f, width, height);
11232 else
11233 x_set_window_size_1 (f, change_gravity, width, height);
11234 #else /* not USE_GTK */
11235 x_set_window_size_1 (f, change_gravity, width, height);
11236 x_clear_under_internal_border (f);
11237 #endif /* not USE_GTK */
11239 /* If cursor was outside the new size, mark it as off. */
11240 mark_window_cursors_off (XWINDOW (f->root_window));
11242 /* Clear out any recollection of where the mouse highlighting was,
11243 since it might be in a place that's outside the new frame size.
11244 Actually checking whether it is outside is a pain in the neck,
11245 so don't try--just let the highlighting be done afresh with new size. */
11246 cancel_mouse_face (f);
11248 unblock_input ();
11250 do_pending_window_change (false);
11253 /* Move the mouse to position pixel PIX_X, PIX_Y relative to frame F. */
11255 void
11256 frame_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
11258 block_input ();
11260 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
11261 0, 0, 0, 0, pix_x, pix_y);
11262 unblock_input ();
11265 /* Raise frame F. */
11267 void
11268 x_raise_frame (struct frame *f)
11270 block_input ();
11271 if (FRAME_VISIBLE_P (f))
11272 XRaiseWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
11273 XFlush (FRAME_X_DISPLAY (f));
11274 unblock_input ();
11277 /* Lower frame F. */
11279 static void
11280 x_lower_frame (struct frame *f)
11282 if (FRAME_VISIBLE_P (f))
11284 block_input ();
11285 XLowerWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
11286 XFlush (FRAME_X_DISPLAY (f));
11287 unblock_input ();
11291 /* Request focus with XEmbed */
11293 void
11294 xembed_request_focus (struct frame *f)
11296 /* See XEmbed Protocol Specification at
11297 http://freedesktop.org/wiki/Specifications/xembed-spec */
11298 if (FRAME_VISIBLE_P (f))
11299 xembed_send_message (f, CurrentTime,
11300 XEMBED_REQUEST_FOCUS, 0, 0, 0);
11303 /* Activate frame with Extended Window Manager Hints */
11305 void
11306 x_ewmh_activate_frame (struct frame *f)
11308 /* See Window Manager Specification/Extended Window Manager Hints at
11309 http://freedesktop.org/wiki/Specifications/wm-spec */
11311 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
11313 if (FRAME_VISIBLE_P (f) && x_wm_supports (f, dpyinfo->Xatom_net_active_window))
11315 Lisp_Object frame;
11316 XSETFRAME (frame, f);
11317 x_send_client_event (frame, make_number (0), frame,
11318 dpyinfo->Xatom_net_active_window,
11319 make_number (32),
11320 list2i (1, dpyinfo->last_user_time));
11324 static void
11325 XTframe_raise_lower (struct frame *f, bool raise_flag)
11327 if (raise_flag)
11328 x_raise_frame (f);
11329 else
11330 x_lower_frame (f);
11333 /* XEmbed implementation. */
11335 #if defined USE_X_TOOLKIT || ! defined USE_GTK
11337 /* XEmbed implementation. */
11339 #define XEMBED_VERSION 0
11341 static void
11342 xembed_set_info (struct frame *f, enum xembed_info flags)
11344 unsigned long data[2];
11345 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
11347 data[0] = XEMBED_VERSION;
11348 data[1] = flags;
11350 XChangeProperty (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11351 dpyinfo->Xatom_XEMBED_INFO, dpyinfo->Xatom_XEMBED_INFO,
11352 32, PropModeReplace, (unsigned char *) data, 2);
11354 #endif /* defined USE_X_TOOLKIT || ! defined USE_GTK */
11356 static void
11357 xembed_send_message (struct frame *f, Time t, enum xembed_message msg,
11358 long int detail, long int data1, long int data2)
11360 XEvent event;
11362 event.xclient.type = ClientMessage;
11363 event.xclient.window = FRAME_X_OUTPUT (f)->parent_desc;
11364 event.xclient.message_type = FRAME_DISPLAY_INFO (f)->Xatom_XEMBED;
11365 event.xclient.format = 32;
11366 event.xclient.data.l[0] = t;
11367 event.xclient.data.l[1] = msg;
11368 event.xclient.data.l[2] = detail;
11369 event.xclient.data.l[3] = data1;
11370 event.xclient.data.l[4] = data2;
11372 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_OUTPUT (f)->parent_desc,
11373 False, NoEventMask, &event);
11374 XSync (FRAME_X_DISPLAY (f), False);
11377 /* Change of visibility. */
11379 /* This tries to wait until the frame is really visible, depending on
11380 the value of Vx_wait_for_event_timeout.
11381 However, if the window manager asks the user where to position
11382 the frame, this will return before the user finishes doing that.
11383 The frame will not actually be visible at that time,
11384 but it will become visible later when the window manager
11385 finishes with it. */
11387 void
11388 x_make_frame_visible (struct frame *f)
11390 if (FRAME_PARENT_FRAME (f))
11392 if (!FRAME_VISIBLE_P (f))
11394 block_input ();
11395 #ifdef USE_GTK
11396 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
11397 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11398 f->left_pos, f->top_pos);
11399 #else
11400 XMapRaised (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
11401 #endif
11402 unblock_input ();
11404 SET_FRAME_VISIBLE (f, true);
11405 SET_FRAME_ICONIFIED (f, false);
11407 return;
11410 block_input ();
11412 x_set_bitmap_icon (f);
11414 if (! FRAME_VISIBLE_P (f))
11416 /* We test asked_for_visible here to make sure we don't
11417 call x_set_offset a second time
11418 if we get to x_make_frame_visible a second time
11419 before the window gets really visible. */
11420 if (! FRAME_ICONIFIED_P (f)
11421 && ! FRAME_X_EMBEDDED_P (f)
11422 && ! f->output_data.x->asked_for_visible)
11423 x_set_offset (f, f->left_pos, f->top_pos, 0);
11425 f->output_data.x->asked_for_visible = true;
11427 if (! EQ (Vx_no_window_manager, Qt))
11428 x_wm_set_window_state (f, NormalState);
11429 #ifdef USE_X_TOOLKIT
11430 if (FRAME_X_EMBEDDED_P (f))
11431 xembed_set_info (f, XEMBED_MAPPED);
11432 else
11434 /* This was XtPopup, but that did nothing for an iconified frame. */
11435 XtMapWidget (f->output_data.x->widget);
11437 #else /* not USE_X_TOOLKIT */
11438 #ifdef USE_GTK
11439 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
11440 gtk_window_deiconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
11441 #else
11442 if (FRAME_X_EMBEDDED_P (f))
11443 xembed_set_info (f, XEMBED_MAPPED);
11444 else
11445 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11446 #endif /* not USE_GTK */
11447 #endif /* not USE_X_TOOLKIT */
11450 XFlush (FRAME_X_DISPLAY (f));
11452 /* Synchronize to ensure Emacs knows the frame is visible
11453 before we do anything else. We do this loop with input not blocked
11454 so that incoming events are handled. */
11456 Lisp_Object frame;
11457 /* This must be before UNBLOCK_INPUT
11458 since events that arrive in response to the actions above
11459 will set it when they are handled. */
11460 bool previously_visible = f->output_data.x->has_been_visible;
11462 XSETFRAME (frame, f);
11464 int original_left = f->left_pos;
11465 int original_top = f->top_pos;
11467 /* This must come after we set COUNT. */
11468 unblock_input ();
11470 /* We unblock here so that arriving X events are processed. */
11472 /* Now move the window back to where it was "supposed to be".
11473 But don't do it if the gravity is negative.
11474 When the gravity is negative, this uses a position
11475 that is 3 pixels too low. Perhaps that's really the border width.
11477 Don't do this if the window has never been visible before,
11478 because the window manager may choose the position
11479 and we don't want to override it. */
11481 if (!FRAME_VISIBLE_P (f)
11482 && !FRAME_ICONIFIED_P (f)
11483 && !FRAME_X_EMBEDDED_P (f)
11484 && !FRAME_PARENT_FRAME (f)
11485 && f->win_gravity == NorthWestGravity
11486 && previously_visible)
11488 Drawable rootw;
11489 int x, y;
11490 unsigned int width, height, border, depth;
11492 block_input ();
11494 /* On some window managers (such as FVWM) moving an existing
11495 window, even to the same place, causes the window manager
11496 to introduce an offset. This can cause the window to move
11497 to an unexpected location. Check the geometry (a little
11498 slow here) and then verify that the window is in the right
11499 place. If the window is not in the right place, move it
11500 there, and take the potential window manager hit. */
11501 XGetGeometry (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11502 &rootw, &x, &y, &width, &height, &border, &depth);
11504 if (original_left != x || original_top != y)
11505 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11506 original_left, original_top);
11508 unblock_input ();
11511 /* Try to wait for a MapNotify event (that is what tells us when a
11512 frame becomes visible). */
11514 #ifdef CYGWIN
11515 /* On Cygwin, which uses input polling, we need to force input to
11516 be read. See
11517 https://lists.gnu.org/r/emacs-devel/2013-12/msg00351.html
11518 and https://debbugs.gnu.org/cgi/bugreport.cgi?bug=24091#131.
11519 Fake an alarm signal to let the handler know that there's
11520 something to be read.
11522 It could be confusing if a real alarm arrives while processing
11523 the fake one. Turn it off and let the handler reset it. */
11524 int old_poll_suppress_count = poll_suppress_count;
11525 poll_suppress_count = 1;
11526 poll_for_input_1 ();
11527 poll_suppress_count = old_poll_suppress_count;
11528 #endif
11529 x_wait_for_event (f, MapNotify);
11533 /* Change from mapped state to withdrawn state. */
11535 /* Make the frame visible (mapped and not iconified). */
11537 void
11538 x_make_frame_invisible (struct frame *f)
11540 Window window;
11542 /* Use the frame's outermost window, not the one we normally draw on. */
11543 window = FRAME_OUTER_WINDOW (f);
11545 /* Don't keep the highlight on an invisible frame. */
11546 if (FRAME_DISPLAY_INFO (f)->x_highlight_frame == f)
11547 FRAME_DISPLAY_INFO (f)->x_highlight_frame = 0;
11549 block_input ();
11551 /* Before unmapping the window, update the WM_SIZE_HINTS property to claim
11552 that the current position of the window is user-specified, rather than
11553 program-specified, so that when the window is mapped again, it will be
11554 placed at the same location, without forcing the user to position it
11555 by hand again (they have already done that once for this window.) */
11556 x_wm_set_size_hint (f, 0, true);
11558 #ifdef USE_GTK
11559 if (FRAME_GTK_OUTER_WIDGET (f))
11560 gtk_widget_hide (FRAME_GTK_OUTER_WIDGET (f));
11561 else
11562 #else
11563 if (FRAME_X_EMBEDDED_P (f))
11564 xembed_set_info (f, 0);
11565 else
11566 #endif
11568 if (! XWithdrawWindow (FRAME_X_DISPLAY (f), window,
11569 DefaultScreen (FRAME_X_DISPLAY (f))))
11571 unblock_input ();
11572 error ("Can't notify window manager of window withdrawal");
11575 x_sync (f);
11577 /* We can't distinguish this from iconification
11578 just by the event that we get from the server.
11579 So we can't win using the usual strategy of letting
11580 FRAME_SAMPLE_VISIBILITY set this. So do it by hand,
11581 and synchronize with the server to make sure we agree. */
11582 SET_FRAME_VISIBLE (f, 0);
11583 SET_FRAME_ICONIFIED (f, false);
11585 unblock_input ();
11588 /* Change window state from mapped to iconified. */
11590 void
11591 x_iconify_frame (struct frame *f)
11593 #ifdef USE_X_TOOLKIT
11594 int result;
11595 #endif
11597 /* Don't keep the highlight on an invisible frame. */
11598 if (FRAME_DISPLAY_INFO (f)->x_highlight_frame == f)
11599 FRAME_DISPLAY_INFO (f)->x_highlight_frame = 0;
11601 if (FRAME_ICONIFIED_P (f))
11602 return;
11604 block_input ();
11606 x_set_bitmap_icon (f);
11608 #if defined (USE_GTK)
11609 if (FRAME_GTK_OUTER_WIDGET (f))
11611 if (! FRAME_VISIBLE_P (f))
11612 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
11614 gtk_window_iconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
11615 SET_FRAME_VISIBLE (f, 0);
11616 SET_FRAME_ICONIFIED (f, true);
11617 unblock_input ();
11618 return;
11620 #endif
11622 #ifdef USE_X_TOOLKIT
11624 if (! FRAME_VISIBLE_P (f))
11626 if (! EQ (Vx_no_window_manager, Qt))
11627 x_wm_set_window_state (f, IconicState);
11628 /* This was XtPopup, but that did nothing for an iconified frame. */
11629 XtMapWidget (f->output_data.x->widget);
11630 /* The server won't give us any event to indicate
11631 that an invisible frame was changed to an icon,
11632 so we have to record it here. */
11633 SET_FRAME_VISIBLE (f, 0);
11634 SET_FRAME_ICONIFIED (f, true);
11635 unblock_input ();
11636 return;
11639 result = XIconifyWindow (FRAME_X_DISPLAY (f),
11640 XtWindow (f->output_data.x->widget),
11641 DefaultScreen (FRAME_X_DISPLAY (f)));
11642 unblock_input ();
11644 if (!result)
11645 error ("Can't notify window manager of iconification");
11647 SET_FRAME_ICONIFIED (f, true);
11648 SET_FRAME_VISIBLE (f, 0);
11650 block_input ();
11651 XFlush (FRAME_X_DISPLAY (f));
11652 unblock_input ();
11653 #else /* not USE_X_TOOLKIT */
11655 /* Make sure the X server knows where the window should be positioned,
11656 in case the user deiconifies with the window manager. */
11657 if (! FRAME_VISIBLE_P (f)
11658 && ! FRAME_ICONIFIED_P (f)
11659 && ! FRAME_X_EMBEDDED_P (f))
11660 x_set_offset (f, f->left_pos, f->top_pos, 0);
11662 /* Since we don't know which revision of X we're running, we'll use both
11663 the X11R3 and X11R4 techniques. I don't know if this is a good idea. */
11665 /* X11R4: send a ClientMessage to the window manager using the
11666 WM_CHANGE_STATE type. */
11668 XEvent msg;
11670 msg.xclient.window = FRAME_X_WINDOW (f);
11671 msg.xclient.type = ClientMessage;
11672 msg.xclient.message_type = FRAME_DISPLAY_INFO (f)->Xatom_wm_change_state;
11673 msg.xclient.format = 32;
11674 msg.xclient.data.l[0] = IconicState;
11676 if (! XSendEvent (FRAME_X_DISPLAY (f),
11677 DefaultRootWindow (FRAME_X_DISPLAY (f)),
11678 False,
11679 SubstructureRedirectMask | SubstructureNotifyMask,
11680 &msg))
11682 unblock_input ();
11683 error ("Can't notify window manager of iconification");
11687 /* X11R3: set the initial_state field of the window manager hints to
11688 IconicState. */
11689 x_wm_set_window_state (f, IconicState);
11691 if (!FRAME_VISIBLE_P (f))
11693 /* If the frame was withdrawn, before, we must map it. */
11694 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11697 SET_FRAME_ICONIFIED (f, true);
11698 SET_FRAME_VISIBLE (f, 0);
11700 XFlush (FRAME_X_DISPLAY (f));
11701 unblock_input ();
11702 #endif /* not USE_X_TOOLKIT */
11706 /* Free X resources of frame F. */
11708 void
11709 x_free_frame_resources (struct frame *f)
11711 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
11712 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
11713 #ifdef USE_X_TOOLKIT
11714 Lisp_Object bar;
11715 struct scroll_bar *b;
11716 #endif
11718 block_input ();
11720 /* If a display connection is dead, don't try sending more
11721 commands to the X server. */
11722 if (dpyinfo->display)
11724 /* Always exit with visible pointer to avoid weird issue
11725 with Xfixes (Bug#17609). */
11726 if (f->pointer_invisible)
11727 FRAME_DISPLAY_INFO (f)->toggle_visible_pointer (f, 0);
11729 /* We must free faces before destroying windows because some
11730 font-driver (e.g. xft) access a window while finishing a
11731 face. */
11732 free_frame_faces (f);
11733 tear_down_x_back_buffer (f);
11735 if (f->output_data.x->icon_desc)
11736 XDestroyWindow (FRAME_X_DISPLAY (f), f->output_data.x->icon_desc);
11738 #ifdef USE_X_TOOLKIT
11739 /* Explicitly destroy the scroll bars of the frame. Without
11740 this, we get "BadDrawable" errors from the toolkit later on,
11741 presumably from expose events generated for the disappearing
11742 toolkit scroll bars. */
11743 for (bar = FRAME_SCROLL_BARS (f); !NILP (bar); bar = b->next)
11745 b = XSCROLL_BAR (bar);
11746 x_scroll_bar_remove (b);
11748 #endif
11750 #ifdef HAVE_X_I18N
11751 if (FRAME_XIC (f))
11752 free_frame_xic (f);
11753 #endif
11755 x_free_cr_resources (f);
11756 #ifdef USE_X_TOOLKIT
11757 if (f->output_data.x->widget)
11759 XtDestroyWidget (f->output_data.x->widget);
11760 f->output_data.x->widget = NULL;
11762 /* Tooltips don't have widgets, only a simple X window, even if
11763 we are using a toolkit. */
11764 else if (FRAME_X_WINDOW (f))
11765 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11767 free_frame_menubar (f);
11769 if (f->shell_position)
11770 xfree (f->shell_position);
11771 #else /* !USE_X_TOOLKIT */
11773 #ifdef USE_GTK
11774 xg_free_frame_widgets (f);
11775 #endif /* USE_GTK */
11777 tear_down_x_back_buffer (f);
11778 if (FRAME_X_WINDOW (f))
11779 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11780 #endif /* !USE_X_TOOLKIT */
11782 unload_color (f, FRAME_FOREGROUND_PIXEL (f));
11783 unload_color (f, FRAME_BACKGROUND_PIXEL (f));
11784 unload_color (f, f->output_data.x->cursor_pixel);
11785 unload_color (f, f->output_data.x->cursor_foreground_pixel);
11786 unload_color (f, f->output_data.x->border_pixel);
11787 unload_color (f, f->output_data.x->mouse_pixel);
11789 if (f->output_data.x->scroll_bar_background_pixel != -1)
11790 unload_color (f, f->output_data.x->scroll_bar_background_pixel);
11791 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
11792 unload_color (f, f->output_data.x->scroll_bar_foreground_pixel);
11793 #if defined (USE_LUCID) && defined (USE_TOOLKIT_SCROLL_BARS)
11794 /* Scrollbar shadow colors. */
11795 if (f->output_data.x->scroll_bar_top_shadow_pixel != -1)
11796 unload_color (f, f->output_data.x->scroll_bar_top_shadow_pixel);
11797 if (f->output_data.x->scroll_bar_bottom_shadow_pixel != -1)
11798 unload_color (f, f->output_data.x->scroll_bar_bottom_shadow_pixel);
11799 #endif /* USE_LUCID && USE_TOOLKIT_SCROLL_BARS */
11800 if (f->output_data.x->white_relief.pixel != -1)
11801 unload_color (f, f->output_data.x->white_relief.pixel);
11802 if (f->output_data.x->black_relief.pixel != -1)
11803 unload_color (f, f->output_data.x->black_relief.pixel);
11805 x_free_gcs (f);
11807 /* Free extra GCs allocated by x_setup_relief_colors. */
11808 if (f->output_data.x->white_relief.gc)
11810 XFreeGC (dpyinfo->display, f->output_data.x->white_relief.gc);
11811 f->output_data.x->white_relief.gc = 0;
11813 if (f->output_data.x->black_relief.gc)
11815 XFreeGC (dpyinfo->display, f->output_data.x->black_relief.gc);
11816 f->output_data.x->black_relief.gc = 0;
11819 /* Free cursors. */
11820 if (f->output_data.x->text_cursor != 0)
11821 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->text_cursor);
11822 if (f->output_data.x->nontext_cursor != 0)
11823 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->nontext_cursor);
11824 if (f->output_data.x->modeline_cursor != 0)
11825 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->modeline_cursor);
11826 if (f->output_data.x->hand_cursor != 0)
11827 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->hand_cursor);
11828 if (f->output_data.x->hourglass_cursor != 0)
11829 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->hourglass_cursor);
11830 if (f->output_data.x->horizontal_drag_cursor != 0)
11831 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->horizontal_drag_cursor);
11832 if (f->output_data.x->vertical_drag_cursor != 0)
11833 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->vertical_drag_cursor);
11834 if (f->output_data.x->left_edge_cursor != 0)
11835 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->left_edge_cursor);
11836 if (f->output_data.x->top_left_corner_cursor != 0)
11837 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->top_left_corner_cursor);
11838 if (f->output_data.x->top_edge_cursor != 0)
11839 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->top_edge_cursor);
11840 if (f->output_data.x->top_right_corner_cursor != 0)
11841 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->top_right_corner_cursor);
11842 if (f->output_data.x->right_edge_cursor != 0)
11843 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->right_edge_cursor);
11844 if (f->output_data.x->bottom_right_corner_cursor != 0)
11845 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->bottom_right_corner_cursor);
11846 if (f->output_data.x->bottom_edge_cursor != 0)
11847 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->bottom_edge_cursor);
11848 if (f->output_data.x->bottom_left_corner_cursor != 0)
11849 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->bottom_left_corner_cursor);
11851 XFlush (FRAME_X_DISPLAY (f));
11854 xfree (f->output_data.x->saved_menu_event);
11855 xfree (f->output_data.x);
11856 f->output_data.x = NULL;
11858 if (f == dpyinfo->x_focus_frame)
11859 dpyinfo->x_focus_frame = 0;
11860 if (f == dpyinfo->x_focus_event_frame)
11861 dpyinfo->x_focus_event_frame = 0;
11862 if (f == dpyinfo->x_highlight_frame)
11863 dpyinfo->x_highlight_frame = 0;
11864 if (f == hlinfo->mouse_face_mouse_frame)
11865 reset_mouse_highlight (hlinfo);
11867 unblock_input ();
11871 /* Destroy the X window of frame F. */
11873 static void
11874 x_destroy_window (struct frame *f)
11876 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
11878 /* If a display connection is dead, don't try sending more
11879 commands to the X server. */
11880 if (dpyinfo->display != 0)
11881 x_free_frame_resources (f);
11883 dpyinfo->reference_count--;
11887 /* Setting window manager hints. */
11889 /* Set the normal size hints for the window manager, for frame F.
11890 FLAGS is the flags word to use--or 0 meaning preserve the flags
11891 that the window now has.
11892 If USER_POSITION, set the USPosition
11893 flag (this is useful when FLAGS is 0).
11894 The GTK version is in gtkutils.c. */
11896 #ifndef USE_GTK
11897 void
11898 x_wm_set_size_hint (struct frame *f, long flags, bool user_position)
11900 XSizeHints size_hints;
11901 Window window = FRAME_OUTER_WINDOW (f);
11903 if (!window)
11904 return;
11906 #ifdef USE_X_TOOLKIT
11907 if (f->output_data.x->widget)
11909 widget_update_wm_size_hints (f->output_data.x->widget);
11910 return;
11912 #endif
11914 /* Setting PMaxSize caused various problems. */
11915 size_hints.flags = PResizeInc | PMinSize /* | PMaxSize */;
11917 size_hints.x = f->left_pos;
11918 size_hints.y = f->top_pos;
11920 size_hints.width = FRAME_PIXEL_WIDTH (f);
11921 size_hints.height = FRAME_PIXEL_HEIGHT (f);
11923 size_hints.width_inc = frame_resize_pixelwise ? 1 : FRAME_COLUMN_WIDTH (f);
11924 size_hints.height_inc = frame_resize_pixelwise ? 1 : FRAME_LINE_HEIGHT (f);
11926 size_hints.max_width = x_display_pixel_width (FRAME_DISPLAY_INFO (f))
11927 - FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
11928 size_hints.max_height = x_display_pixel_height (FRAME_DISPLAY_INFO (f))
11929 - FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
11931 /* Calculate the base and minimum sizes. */
11933 int base_width, base_height;
11935 base_width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
11936 base_height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
11938 /* The window manager uses the base width hints to calculate the
11939 current number of rows and columns in the frame while
11940 resizing; min_width and min_height aren't useful for this
11941 purpose, since they might not give the dimensions for a
11942 zero-row, zero-column frame. */
11944 size_hints.flags |= PBaseSize;
11945 size_hints.base_width = base_width;
11946 size_hints.base_height = base_height + FRAME_MENUBAR_HEIGHT (f);
11947 size_hints.min_width = base_width;
11948 size_hints.min_height = base_height;
11951 /* If we don't need the old flags, we don't need the old hint at all. */
11952 if (flags)
11954 size_hints.flags |= flags;
11955 goto no_read;
11959 XSizeHints hints; /* Sometimes I hate X Windows... */
11960 long supplied_return;
11961 int value;
11963 value = XGetWMNormalHints (FRAME_X_DISPLAY (f), window, &hints,
11964 &supplied_return);
11966 if (flags)
11967 size_hints.flags |= flags;
11968 else
11970 if (value == 0)
11971 hints.flags = 0;
11972 if (hints.flags & PSize)
11973 size_hints.flags |= PSize;
11974 if (hints.flags & PPosition)
11975 size_hints.flags |= PPosition;
11976 if (hints.flags & USPosition)
11977 size_hints.flags |= USPosition;
11978 if (hints.flags & USSize)
11979 size_hints.flags |= USSize;
11983 no_read:
11985 #ifdef PWinGravity
11986 size_hints.win_gravity = f->win_gravity;
11987 size_hints.flags |= PWinGravity;
11989 if (user_position)
11991 size_hints.flags &= ~ PPosition;
11992 size_hints.flags |= USPosition;
11994 #endif /* PWinGravity */
11996 XSetWMNormalHints (FRAME_X_DISPLAY (f), window, &size_hints);
11998 #endif /* not USE_GTK */
12000 /* Used for IconicState or NormalState */
12002 static void
12003 x_wm_set_window_state (struct frame *f, int state)
12005 #ifdef USE_X_TOOLKIT
12006 Arg al[1];
12008 XtSetArg (al[0], XtNinitialState, state);
12009 XtSetValues (f->output_data.x->widget, al, 1);
12010 #else /* not USE_X_TOOLKIT */
12011 Window window = FRAME_X_WINDOW (f);
12013 f->output_data.x->wm_hints.flags |= StateHint;
12014 f->output_data.x->wm_hints.initial_state = state;
12016 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
12017 #endif /* not USE_X_TOOLKIT */
12020 static void
12021 x_wm_set_icon_pixmap (struct frame *f, ptrdiff_t pixmap_id)
12023 Pixmap icon_pixmap, icon_mask;
12025 #if !defined USE_X_TOOLKIT && !defined USE_GTK
12026 Window window = FRAME_OUTER_WINDOW (f);
12027 #endif
12029 if (pixmap_id > 0)
12031 icon_pixmap = x_bitmap_pixmap (f, pixmap_id);
12032 f->output_data.x->wm_hints.icon_pixmap = icon_pixmap;
12033 icon_mask = x_bitmap_mask (f, pixmap_id);
12034 f->output_data.x->wm_hints.icon_mask = icon_mask;
12036 else
12038 /* It seems there is no way to turn off use of an icon
12039 pixmap. */
12040 return;
12044 #ifdef USE_GTK
12046 xg_set_frame_icon (f, icon_pixmap, icon_mask);
12047 return;
12050 #elif defined (USE_X_TOOLKIT) /* same as in x_wm_set_window_state. */
12053 Arg al[1];
12054 XtSetArg (al[0], XtNiconPixmap, icon_pixmap);
12055 XtSetValues (f->output_data.x->widget, al, 1);
12056 XtSetArg (al[0], XtNiconMask, icon_mask);
12057 XtSetValues (f->output_data.x->widget, al, 1);
12060 #else /* not USE_X_TOOLKIT && not USE_GTK */
12062 f->output_data.x->wm_hints.flags |= (IconPixmapHint | IconMaskHint);
12063 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
12065 #endif /* not USE_X_TOOLKIT && not USE_GTK */
12068 void
12069 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
12071 Window window = FRAME_OUTER_WINDOW (f);
12073 f->output_data.x->wm_hints.flags |= IconPositionHint;
12074 f->output_data.x->wm_hints.icon_x = icon_x;
12075 f->output_data.x->wm_hints.icon_y = icon_y;
12077 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
12081 /***********************************************************************
12082 Fonts
12083 ***********************************************************************/
12085 #ifdef GLYPH_DEBUG
12087 /* Check that FONT is valid on frame F. It is if it can be found in F's
12088 font table. */
12090 static void
12091 x_check_font (struct frame *f, struct font *font)
12093 eassert (font != NULL && ! NILP (font->props[FONT_TYPE_INDEX]));
12094 if (font->driver->check)
12095 eassert (font->driver->check (f, font) == 0);
12098 #endif /* GLYPH_DEBUG */
12101 /***********************************************************************
12102 Initialization
12103 ***********************************************************************/
12105 #ifdef USE_X_TOOLKIT
12106 static XrmOptionDescRec emacs_options[] = {
12107 {(char *) "-geometry", (char *) ".geometry", XrmoptionSepArg, NULL},
12108 {(char *) "-iconic", (char *) ".iconic", XrmoptionNoArg, (XtPointer) "yes"},
12110 {(char *) "-internal-border-width",
12111 (char *) "*EmacsScreen.internalBorderWidth", XrmoptionSepArg, NULL},
12112 {(char *) "-ib", (char *) "*EmacsScreen.internalBorderWidth",
12113 XrmoptionSepArg, NULL},
12114 {(char *) "-T", (char *) "*EmacsShell.title", XrmoptionSepArg, NULL},
12115 {(char *) "-wn", (char *) "*EmacsShell.title", XrmoptionSepArg, NULL},
12116 {(char *) "-title", (char *) "*EmacsShell.title", XrmoptionSepArg, NULL},
12117 {(char *) "-iconname", (char *) "*EmacsShell.iconName",
12118 XrmoptionSepArg, NULL},
12119 {(char *) "-in", (char *) "*EmacsShell.iconName", XrmoptionSepArg, NULL},
12120 {(char *) "-mc", (char *) "*pointerColor", XrmoptionSepArg, NULL},
12121 {(char *) "-cr", (char *) "*cursorColor", XrmoptionSepArg, NULL}
12124 /* Whether atimer for Xt timeouts is activated or not. */
12126 static bool x_timeout_atimer_activated_flag;
12128 #endif /* USE_X_TOOLKIT */
12130 static int x_initialized;
12132 /* Test whether two display-name strings agree up to the dot that separates
12133 the screen number from the server number. */
12134 static bool
12135 same_x_server (const char *name1, const char *name2)
12137 bool seen_colon = false;
12138 Lisp_Object sysname = Fsystem_name ();
12139 const char *system_name = SSDATA (sysname);
12140 ptrdiff_t system_name_length = SBYTES (sysname);
12141 ptrdiff_t length_until_period = 0;
12143 while (system_name[length_until_period] != 0
12144 && system_name[length_until_period] != '.')
12145 length_until_period++;
12147 /* Treat `unix' like an empty host name. */
12148 if (! strncmp (name1, "unix:", 5))
12149 name1 += 4;
12150 if (! strncmp (name2, "unix:", 5))
12151 name2 += 4;
12152 /* Treat this host's name like an empty host name. */
12153 if (! strncmp (name1, system_name, system_name_length)
12154 && name1[system_name_length] == ':')
12155 name1 += system_name_length;
12156 if (! strncmp (name2, system_name, system_name_length)
12157 && name2[system_name_length] == ':')
12158 name2 += system_name_length;
12159 /* Treat this host's domainless name like an empty host name. */
12160 if (! strncmp (name1, system_name, length_until_period)
12161 && name1[length_until_period] == ':')
12162 name1 += length_until_period;
12163 if (! strncmp (name2, system_name, length_until_period)
12164 && name2[length_until_period] == ':')
12165 name2 += length_until_period;
12167 for (; *name1 != '\0' && *name1 == *name2; name1++, name2++)
12169 if (*name1 == ':')
12170 seen_colon = true;
12171 if (seen_colon && *name1 == '.')
12172 return true;
12174 return (seen_colon
12175 && (*name1 == '.' || *name1 == '\0')
12176 && (*name2 == '.' || *name2 == '\0'));
12179 /* Count number of set bits in mask and number of bits to shift to
12180 get to the first bit. With MASK 0x7e0, *BITS is set to 6, and *OFFSET
12181 to 5. */
12182 static void
12183 get_bits_and_offset (unsigned long mask, int *bits, int *offset)
12185 int nr = 0;
12186 int off = 0;
12188 while (!(mask & 1))
12190 off++;
12191 mask >>= 1;
12194 while (mask & 1)
12196 nr++;
12197 mask >>= 1;
12200 *offset = off;
12201 *bits = nr;
12204 /* Return true iff display DISPLAY is available for use.
12205 But don't permanently open it, just test its availability. */
12207 bool
12208 x_display_ok (const char *display)
12210 /* XOpenDisplay fails if it gets a signal. Block SIGIO which may arrive. */
12211 unrequest_sigio ();
12212 Display *dpy = XOpenDisplay (display);
12213 request_sigio ();
12214 if (!dpy)
12215 return false;
12216 XCloseDisplay (dpy);
12217 return true;
12220 #ifdef USE_GTK
12221 static void
12222 my_log_handler (const gchar *log_domain, GLogLevelFlags log_level,
12223 const gchar *msg, gpointer user_data)
12225 if (!strstr (msg, "g_set_prgname"))
12226 fprintf (stderr, "%s-WARNING **: %s\n", log_domain, msg);
12228 #endif
12230 /* Create invisible cursor on X display referred by DPYINFO. */
12232 static Cursor
12233 make_invisible_cursor (struct x_display_info *dpyinfo)
12235 Display *dpy = dpyinfo->display;
12236 static char const no_data[] = { 0 };
12237 Pixmap pix;
12238 XColor col;
12239 Cursor c = 0;
12241 x_catch_errors (dpy);
12242 pix = XCreateBitmapFromData (dpy, dpyinfo->root_window, no_data, 1, 1);
12243 if (! x_had_errors_p (dpy) && pix != None)
12245 Cursor pixc;
12246 col.pixel = 0;
12247 col.red = col.green = col.blue = 0;
12248 col.flags = DoRed | DoGreen | DoBlue;
12249 pixc = XCreatePixmapCursor (dpy, pix, pix, &col, &col, 0, 0);
12250 if (! x_had_errors_p (dpy) && pixc != None)
12251 c = pixc;
12252 XFreePixmap (dpy, pix);
12255 x_uncatch_errors ();
12257 return c;
12260 /* True if DPY supports Xfixes extension >= 4. */
12262 static bool
12263 x_probe_xfixes_extension (Display *dpy)
12265 #ifdef HAVE_XFIXES
12266 int major, minor;
12267 return XFixesQueryVersion (dpy, &major, &minor) && major >= 4;
12268 #else
12269 return false;
12270 #endif /* HAVE_XFIXES */
12273 /* Toggle mouse pointer visibility on frame F by using Xfixes functions. */
12275 static void
12276 xfixes_toggle_visible_pointer (struct frame *f, bool invisible)
12278 #ifdef HAVE_XFIXES
12279 if (invisible)
12280 XFixesHideCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
12281 else
12282 XFixesShowCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
12283 f->pointer_invisible = invisible;
12284 #else
12285 emacs_abort ();
12286 #endif /* HAVE_XFIXES */
12289 /* Toggle mouse pointer visibility on frame F by using invisible cursor. */
12291 static void
12292 x_toggle_visible_pointer (struct frame *f, bool invisible)
12294 eassert (FRAME_DISPLAY_INFO (f)->invisible_cursor != 0);
12295 if (invisible)
12296 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
12297 FRAME_DISPLAY_INFO (f)->invisible_cursor);
12298 else
12299 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
12300 f->output_data.x->current_cursor);
12301 f->pointer_invisible = invisible;
12304 /* Setup pointer blanking, prefer Xfixes if available. */
12306 static void
12307 x_setup_pointer_blanking (struct x_display_info *dpyinfo)
12309 /* FIXME: the brave tester should set EMACS_XFIXES because we're suspecting
12310 X server bug, see https://debbugs.gnu.org/cgi/bugreport.cgi?bug=17609. */
12311 if (egetenv ("EMACS_XFIXES") && x_probe_xfixes_extension (dpyinfo->display))
12312 dpyinfo->toggle_visible_pointer = xfixes_toggle_visible_pointer;
12313 else
12315 dpyinfo->toggle_visible_pointer = x_toggle_visible_pointer;
12316 dpyinfo->invisible_cursor = make_invisible_cursor (dpyinfo);
12320 /* Current X display connection identifier. Incremented for each next
12321 connection established. */
12322 static unsigned x_display_id;
12324 /* Open a connection to X display DISPLAY_NAME, and return
12325 the structure that describes the open display.
12326 If we cannot contact the display, return null. */
12328 struct x_display_info *
12329 x_term_init (Lisp_Object display_name, char *xrm_option, char *resource_name)
12331 Display *dpy;
12332 struct terminal *terminal;
12333 struct x_display_info *dpyinfo;
12334 XrmDatabase xrdb;
12335 #ifdef USE_XCB
12336 xcb_connection_t *xcb_conn;
12337 #endif
12339 block_input ();
12341 if (!x_initialized)
12343 x_initialize ();
12344 ++x_initialized;
12347 if (! x_display_ok (SSDATA (display_name)))
12348 error ("Display %s can't be opened", SSDATA (display_name));
12350 #ifdef USE_GTK
12352 #define NUM_ARGV 10
12353 int argc;
12354 char *argv[NUM_ARGV];
12355 char **argv2 = argv;
12356 guint id;
12358 if (x_initialized++ > 1)
12360 xg_display_open (SSDATA (display_name), &dpy);
12362 else
12364 static char display_opt[] = "--display";
12365 static char name_opt[] = "--name";
12367 for (argc = 0; argc < NUM_ARGV; ++argc)
12368 argv[argc] = 0;
12370 argc = 0;
12371 argv[argc++] = initial_argv[0];
12373 if (! NILP (display_name))
12375 argv[argc++] = display_opt;
12376 argv[argc++] = SSDATA (display_name);
12379 argv[argc++] = name_opt;
12380 argv[argc++] = resource_name;
12382 XSetLocaleModifiers ("");
12384 /* Work around GLib bug that outputs a faulty warning. See
12385 https://bugzilla.gnome.org/show_bug.cgi?id=563627. */
12386 id = g_log_set_handler ("GLib", G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
12387 | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
12389 /* NULL window -> events for all windows go to our function.
12390 Call before gtk_init so Gtk+ event filters comes after our. */
12391 gdk_window_add_filter (NULL, event_handler_gdk, NULL);
12393 /* gtk_init does set_locale. Fix locale before and after. */
12394 fixup_locale ();
12395 unrequest_sigio (); /* See comment in x_display_ok. */
12396 gtk_init (&argc, &argv2);
12397 request_sigio ();
12398 fixup_locale ();
12400 g_log_remove_handler ("GLib", id);
12402 xg_initialize ();
12404 dpy = DEFAULT_GDK_DISPLAY ();
12406 #if ! GTK_CHECK_VERSION (2, 90, 0)
12407 /* Load our own gtkrc if it exists. */
12409 const char *file = "~/.emacs.d/gtkrc";
12410 Lisp_Object s, abs_file;
12412 s = build_string (file);
12413 abs_file = Fexpand_file_name (s, Qnil);
12415 if (! NILP (abs_file) && !NILP (Ffile_readable_p (abs_file)))
12416 gtk_rc_parse (SSDATA (abs_file));
12418 #endif
12420 XSetErrorHandler (x_error_handler);
12421 XSetIOErrorHandler (x_io_error_quitter);
12424 #else /* not USE_GTK */
12425 #ifdef USE_X_TOOLKIT
12426 /* weiner@footloose.sps.mot.com reports that this causes
12427 errors with X11R5:
12428 X protocol error: BadAtom (invalid Atom parameter)
12429 on protocol request 18skiloaf.
12430 So let's not use it until R6. */
12431 #ifdef HAVE_X11XTR6
12432 XtSetLanguageProc (NULL, NULL, NULL);
12433 #endif
12436 int argc = 0;
12437 char *argv[3];
12439 argv[0] = (char *) "";
12440 argc = 1;
12441 if (xrm_option)
12443 argv[argc++] = (char *) "-xrm";
12444 argv[argc++] = xrm_option;
12446 turn_on_atimers (false);
12447 unrequest_sigio (); /* See comment in x_display_ok. */
12448 dpy = XtOpenDisplay (Xt_app_con, SSDATA (display_name),
12449 resource_name, EMACS_CLASS,
12450 emacs_options, XtNumber (emacs_options),
12451 &argc, argv);
12452 request_sigio ();
12453 turn_on_atimers (true);
12455 #ifdef HAVE_X11XTR6
12456 /* I think this is to compensate for XtSetLanguageProc. */
12457 fixup_locale ();
12458 #endif
12461 #else /* not USE_X_TOOLKIT */
12462 XSetLocaleModifiers ("");
12463 unrequest_sigio (); /* See comment in x_display_ok. */
12464 dpy = XOpenDisplay (SSDATA (display_name));
12465 request_sigio ();
12466 #endif /* not USE_X_TOOLKIT */
12467 #endif /* not USE_GTK*/
12469 /* Detect failure. */
12470 if (dpy == 0)
12472 unblock_input ();
12473 return 0;
12476 #ifdef USE_XCB
12477 xcb_conn = XGetXCBConnection (dpy);
12478 if (xcb_conn == 0)
12480 #ifdef USE_GTK
12481 xg_display_close (dpy);
12482 #else
12483 #ifdef USE_X_TOOLKIT
12484 XtCloseDisplay (dpy);
12485 #else
12486 XCloseDisplay (dpy);
12487 #endif
12488 #endif /* ! USE_GTK */
12490 unblock_input ();
12491 return 0;
12493 #endif
12495 /* We have definitely succeeded. Record the new connection. */
12497 dpyinfo = xzalloc (sizeof *dpyinfo);
12498 terminal = x_create_terminal (dpyinfo);
12501 struct x_display_info *share;
12503 for (share = x_display_list; share; share = share->next)
12504 if (same_x_server (SSDATA (XCAR (share->name_list_element)),
12505 SSDATA (display_name)))
12506 break;
12507 if (share)
12508 terminal->kboard = share->terminal->kboard;
12509 else
12511 terminal->kboard = allocate_kboard (Qx);
12513 if (!EQ (XSYMBOL (Qvendor_specific_keysyms)->u.s.function, Qunbound))
12515 char *vendor = ServerVendor (dpy);
12517 /* Temporarily hide the partially initialized terminal. */
12518 terminal_list = terminal->next_terminal;
12519 unblock_input ();
12520 kset_system_key_alist
12521 (terminal->kboard,
12522 call1 (Qvendor_specific_keysyms,
12523 vendor ? build_string (vendor) : empty_unibyte_string));
12524 block_input ();
12525 terminal->next_terminal = terminal_list;
12526 terminal_list = terminal;
12529 /* Don't let the initial kboard remain current longer than necessary.
12530 That would cause problems if a file loaded on startup tries to
12531 prompt in the mini-buffer. */
12532 if (current_kboard == initial_kboard)
12533 current_kboard = terminal->kboard;
12535 terminal->kboard->reference_count++;
12538 /* Put this display on the chain. */
12539 dpyinfo->next = x_display_list;
12540 x_display_list = dpyinfo;
12542 dpyinfo->name_list_element = Fcons (display_name, Qnil);
12543 dpyinfo->display = dpy;
12544 dpyinfo->connection = ConnectionNumber (dpyinfo->display);
12545 #ifdef USE_XCB
12546 dpyinfo->xcb_connection = xcb_conn;
12547 #endif
12549 /* https://lists.gnu.org/r/emacs-devel/2015-11/msg00194.html */
12550 dpyinfo->smallest_font_height = 1;
12551 dpyinfo->smallest_char_width = 1;
12553 /* Set the name of the terminal. */
12554 terminal->name = xlispstrdup (display_name);
12556 #if false
12557 XSetAfterFunction (x_current_display, x_trace_wire);
12558 #endif
12560 Lisp_Object system_name = Fsystem_name ();
12561 ptrdiff_t nbytes;
12562 if (INT_ADD_WRAPV (SBYTES (Vinvocation_name), SBYTES (system_name) + 2,
12563 &nbytes))
12564 memory_full (SIZE_MAX);
12565 dpyinfo->x_id = ++x_display_id;
12566 dpyinfo->x_id_name = xmalloc (nbytes);
12567 char *nametail = lispstpcpy (dpyinfo->x_id_name, Vinvocation_name);
12568 *nametail++ = '@';
12569 lispstpcpy (nametail, system_name);
12571 /* Figure out which modifier bits mean what. */
12572 x_find_modifier_meanings (dpyinfo);
12574 /* Get the scroll bar cursor. */
12575 #ifdef USE_GTK
12576 /* We must create a GTK cursor, it is required for GTK widgets. */
12577 dpyinfo->xg_cursor = xg_create_default_cursor (dpyinfo->display);
12578 #endif /* USE_GTK */
12580 dpyinfo->vertical_scroll_bar_cursor
12581 = XCreateFontCursor (dpyinfo->display, XC_sb_v_double_arrow);
12583 dpyinfo->horizontal_scroll_bar_cursor
12584 = XCreateFontCursor (dpyinfo->display, XC_sb_h_double_arrow);
12586 xrdb = x_load_resources (dpyinfo->display, xrm_option,
12587 resource_name, EMACS_CLASS);
12588 #ifdef HAVE_XRMSETDATABASE
12589 XrmSetDatabase (dpyinfo->display, xrdb);
12590 #else
12591 dpyinfo->display->db = xrdb;
12592 #endif
12593 /* Put the rdb where we can find it in a way that works on
12594 all versions. */
12595 dpyinfo->xrdb = xrdb;
12597 dpyinfo->screen = ScreenOfDisplay (dpyinfo->display,
12598 DefaultScreen (dpyinfo->display));
12599 select_visual (dpyinfo);
12600 dpyinfo->cmap = DefaultColormapOfScreen (dpyinfo->screen);
12601 dpyinfo->root_window = RootWindowOfScreen (dpyinfo->screen);
12602 dpyinfo->icon_bitmap_id = -1;
12603 dpyinfo->wm_type = X_WMTYPE_UNKNOWN;
12605 reset_mouse_highlight (&dpyinfo->mouse_highlight);
12607 /* See if we can construct pixel values from RGB values. */
12608 if (dpyinfo->visual->class == TrueColor)
12610 get_bits_and_offset (dpyinfo->visual->red_mask,
12611 &dpyinfo->red_bits, &dpyinfo->red_offset);
12612 get_bits_and_offset (dpyinfo->visual->blue_mask,
12613 &dpyinfo->blue_bits, &dpyinfo->blue_offset);
12614 get_bits_and_offset (dpyinfo->visual->green_mask,
12615 &dpyinfo->green_bits, &dpyinfo->green_offset);
12618 /* See if a private colormap is requested. */
12619 if (dpyinfo->visual == DefaultVisualOfScreen (dpyinfo->screen))
12621 if (dpyinfo->visual->class == PseudoColor)
12623 AUTO_STRING (privateColormap, "privateColormap");
12624 AUTO_STRING (PrivateColormap, "PrivateColormap");
12625 Lisp_Object value
12626 = display_x_get_resource (dpyinfo, privateColormap,
12627 PrivateColormap, Qnil, Qnil);
12628 if (STRINGP (value)
12629 && (!strcmp (SSDATA (value), "true")
12630 || !strcmp (SSDATA (value), "on")))
12631 dpyinfo->cmap = XCopyColormapAndFree (dpyinfo->display, dpyinfo->cmap);
12634 else
12635 dpyinfo->cmap = XCreateColormap (dpyinfo->display, dpyinfo->root_window,
12636 dpyinfo->visual, AllocNone);
12638 #ifdef HAVE_XDBE
12639 dpyinfo->supports_xdbe = false;
12640 int xdbe_major;
12641 int xdbe_minor;
12642 if (XdbeQueryExtension (dpyinfo->display, &xdbe_major, &xdbe_minor))
12643 dpyinfo->supports_xdbe = true;
12644 #endif
12646 #ifdef HAVE_XFT
12648 /* If we are using Xft, the following precautions should be made:
12650 1. Make sure that the Xrender extension is added before the Xft one.
12651 Otherwise, the close-display hook set by Xft is called after the one
12652 for Xrender, and the former tries to re-add the latter. This results
12653 in inconsistency of internal states and leads to X protocol error when
12654 one reconnects to the same X server (Bug#1696).
12656 2. Check dpi value in X resources. It is better we use it as well,
12657 since Xft will use it, as will all Gnome applications. If our real DPI
12658 is smaller or larger than the one Xft uses, our font will look smaller
12659 or larger than other for other applications, even if it is the same
12660 font name (monospace-10 for example). */
12662 int event_base, error_base;
12663 char *v;
12664 double d;
12666 XRenderQueryExtension (dpyinfo->display, &event_base, &error_base);
12668 v = XGetDefault (dpyinfo->display, "Xft", "dpi");
12669 if (v != NULL && sscanf (v, "%lf", &d) == 1)
12670 dpyinfo->resy = dpyinfo->resx = d;
12672 #endif
12674 if (dpyinfo->resy < 1)
12676 int screen_number = XScreenNumberOfScreen (dpyinfo->screen);
12677 double pixels = DisplayHeight (dpyinfo->display, screen_number);
12678 double mm = DisplayHeightMM (dpyinfo->display, screen_number);
12679 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
12680 dpyinfo->resy = (mm < 1) ? 100 : pixels * 25.4 / mm;
12681 pixels = DisplayWidth (dpyinfo->display, screen_number);
12682 mm = DisplayWidthMM (dpyinfo->display, screen_number);
12683 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
12684 dpyinfo->resx = (mm < 1) ? 100 : pixels * 25.4 / mm;
12688 static const struct
12690 const char *name;
12691 int offset;
12692 } atom_refs[] = {
12693 #define ATOM_REFS_INIT(string, member) \
12694 { string, offsetof (struct x_display_info, member) },
12695 ATOM_REFS_INIT ("WM_PROTOCOLS", Xatom_wm_protocols)
12696 ATOM_REFS_INIT ("WM_TAKE_FOCUS", Xatom_wm_take_focus)
12697 ATOM_REFS_INIT ("WM_SAVE_YOURSELF", Xatom_wm_save_yourself)
12698 ATOM_REFS_INIT ("WM_DELETE_WINDOW", Xatom_wm_delete_window)
12699 ATOM_REFS_INIT ("WM_CHANGE_STATE", Xatom_wm_change_state)
12700 ATOM_REFS_INIT ("WM_CONFIGURE_DENIED", Xatom_wm_configure_denied)
12701 ATOM_REFS_INIT ("WM_MOVED", Xatom_wm_window_moved)
12702 ATOM_REFS_INIT ("WM_CLIENT_LEADER", Xatom_wm_client_leader)
12703 ATOM_REFS_INIT ("Editres", Xatom_editres)
12704 ATOM_REFS_INIT ("CLIPBOARD", Xatom_CLIPBOARD)
12705 ATOM_REFS_INIT ("TIMESTAMP", Xatom_TIMESTAMP)
12706 ATOM_REFS_INIT ("TEXT", Xatom_TEXT)
12707 ATOM_REFS_INIT ("COMPOUND_TEXT", Xatom_COMPOUND_TEXT)
12708 ATOM_REFS_INIT ("UTF8_STRING", Xatom_UTF8_STRING)
12709 ATOM_REFS_INIT ("DELETE", Xatom_DELETE)
12710 ATOM_REFS_INIT ("MULTIPLE", Xatom_MULTIPLE)
12711 ATOM_REFS_INIT ("INCR", Xatom_INCR)
12712 ATOM_REFS_INIT ("_EMACS_TMP_", Xatom_EMACS_TMP)
12713 ATOM_REFS_INIT ("TARGETS", Xatom_TARGETS)
12714 ATOM_REFS_INIT ("NULL", Xatom_NULL)
12715 ATOM_REFS_INIT ("ATOM", Xatom_ATOM)
12716 ATOM_REFS_INIT ("ATOM_PAIR", Xatom_ATOM_PAIR)
12717 ATOM_REFS_INIT ("CLIPBOARD_MANAGER", Xatom_CLIPBOARD_MANAGER)
12718 ATOM_REFS_INIT ("_XEMBED_INFO", Xatom_XEMBED_INFO)
12719 /* For properties of font. */
12720 ATOM_REFS_INIT ("PIXEL_SIZE", Xatom_PIXEL_SIZE)
12721 ATOM_REFS_INIT ("AVERAGE_WIDTH", Xatom_AVERAGE_WIDTH)
12722 ATOM_REFS_INIT ("_MULE_BASELINE_OFFSET", Xatom_MULE_BASELINE_OFFSET)
12723 ATOM_REFS_INIT ("_MULE_RELATIVE_COMPOSE", Xatom_MULE_RELATIVE_COMPOSE)
12724 ATOM_REFS_INIT ("_MULE_DEFAULT_ASCENT", Xatom_MULE_DEFAULT_ASCENT)
12725 /* Ghostscript support. */
12726 ATOM_REFS_INIT ("DONE", Xatom_DONE)
12727 ATOM_REFS_INIT ("PAGE", Xatom_PAGE)
12728 ATOM_REFS_INIT ("SCROLLBAR", Xatom_Scrollbar)
12729 ATOM_REFS_INIT ("HORIZONTAL_SCROLLBAR", Xatom_Horizontal_Scrollbar)
12730 ATOM_REFS_INIT ("_XEMBED", Xatom_XEMBED)
12731 /* EWMH */
12732 ATOM_REFS_INIT ("_NET_WM_STATE", Xatom_net_wm_state)
12733 ATOM_REFS_INIT ("_NET_WM_STATE_FULLSCREEN", Xatom_net_wm_state_fullscreen)
12734 ATOM_REFS_INIT ("_NET_WM_STATE_MAXIMIZED_HORZ",
12735 Xatom_net_wm_state_maximized_horz)
12736 ATOM_REFS_INIT ("_NET_WM_STATE_MAXIMIZED_VERT",
12737 Xatom_net_wm_state_maximized_vert)
12738 ATOM_REFS_INIT ("_NET_WM_STATE_STICKY", Xatom_net_wm_state_sticky)
12739 ATOM_REFS_INIT ("_NET_WM_STATE_HIDDEN", Xatom_net_wm_state_hidden)
12740 ATOM_REFS_INIT ("_NET_WM_WINDOW_TYPE", Xatom_net_window_type)
12741 ATOM_REFS_INIT ("_NET_WM_WINDOW_TYPE_TOOLTIP",
12742 Xatom_net_window_type_tooltip)
12743 ATOM_REFS_INIT ("_NET_WM_ICON_NAME", Xatom_net_wm_icon_name)
12744 ATOM_REFS_INIT ("_NET_WM_NAME", Xatom_net_wm_name)
12745 ATOM_REFS_INIT ("_NET_SUPPORTED", Xatom_net_supported)
12746 ATOM_REFS_INIT ("_NET_SUPPORTING_WM_CHECK", Xatom_net_supporting_wm_check)
12747 ATOM_REFS_INIT ("_NET_WM_WINDOW_OPACITY", Xatom_net_wm_window_opacity)
12748 ATOM_REFS_INIT ("_NET_ACTIVE_WINDOW", Xatom_net_active_window)
12749 ATOM_REFS_INIT ("_NET_FRAME_EXTENTS", Xatom_net_frame_extents)
12750 ATOM_REFS_INIT ("_NET_CURRENT_DESKTOP", Xatom_net_current_desktop)
12751 ATOM_REFS_INIT ("_NET_WORKAREA", Xatom_net_workarea)
12752 /* Session management */
12753 ATOM_REFS_INIT ("SM_CLIENT_ID", Xatom_SM_CLIENT_ID)
12754 ATOM_REFS_INIT ("_XSETTINGS_SETTINGS", Xatom_xsettings_prop)
12755 ATOM_REFS_INIT ("MANAGER", Xatom_xsettings_mgr)
12756 ATOM_REFS_INIT ("_NET_WM_STATE_SKIP_TASKBAR", Xatom_net_wm_state_skip_taskbar)
12757 ATOM_REFS_INIT ("_NET_WM_STATE_ABOVE", Xatom_net_wm_state_above)
12758 ATOM_REFS_INIT ("_NET_WM_STATE_BELOW", Xatom_net_wm_state_below)
12761 int i;
12762 enum { atom_count = ARRAYELTS (atom_refs) };
12763 /* 1 for _XSETTINGS_SN. */
12764 enum { total_atom_count = 1 + atom_count };
12765 Atom atoms_return[total_atom_count];
12766 char *atom_names[total_atom_count];
12767 static char const xsettings_fmt[] = "_XSETTINGS_S%d";
12768 char xsettings_atom_name[sizeof xsettings_fmt - 2
12769 + INT_STRLEN_BOUND (int)];
12771 for (i = 0; i < atom_count; i++)
12772 atom_names[i] = (char *) atom_refs[i].name;
12774 /* Build _XSETTINGS_SN atom name. */
12775 sprintf (xsettings_atom_name, xsettings_fmt,
12776 XScreenNumberOfScreen (dpyinfo->screen));
12777 atom_names[i] = xsettings_atom_name;
12779 XInternAtoms (dpyinfo->display, atom_names, total_atom_count,
12780 False, atoms_return);
12782 for (i = 0; i < atom_count; i++)
12783 *(Atom *) ((char *) dpyinfo + atom_refs[i].offset) = atoms_return[i];
12785 /* Manually copy last atom. */
12786 dpyinfo->Xatom_xsettings_sel = atoms_return[i];
12789 dpyinfo->x_dnd_atoms_size = 8;
12790 dpyinfo->x_dnd_atoms = xmalloc (sizeof *dpyinfo->x_dnd_atoms
12791 * dpyinfo->x_dnd_atoms_size);
12792 dpyinfo->gray
12793 = XCreatePixmapFromBitmapData (dpyinfo->display, dpyinfo->root_window,
12794 gray_bits, gray_width, gray_height,
12795 1, 0, 1);
12797 x_setup_pointer_blanking (dpyinfo);
12799 #ifdef HAVE_X_I18N
12800 xim_initialize (dpyinfo, resource_name);
12801 #endif
12803 xsettings_initialize (dpyinfo);
12805 /* This is only needed for distinguishing keyboard and process input. */
12806 if (dpyinfo->connection != 0)
12807 add_keyboard_wait_descriptor (dpyinfo->connection);
12809 #ifdef F_SETOWN
12810 fcntl (dpyinfo->connection, F_SETOWN, getpid ());
12811 #endif /* ! defined (F_SETOWN) */
12813 if (interrupt_input)
12814 init_sigio (dpyinfo->connection);
12816 #ifdef USE_LUCID
12818 XrmValue d, fr, to;
12819 Font font;
12821 dpy = dpyinfo->display;
12822 d.addr = (XPointer)&dpy;
12823 d.size = sizeof (Display *);
12824 fr.addr = (char *) XtDefaultFont;
12825 fr.size = sizeof (XtDefaultFont);
12826 to.size = sizeof (Font *);
12827 to.addr = (XPointer)&font;
12828 x_catch_errors (dpy);
12829 if (!XtCallConverter (dpy, XtCvtStringToFont, &d, 1, &fr, &to, NULL))
12830 emacs_abort ();
12831 if (x_had_errors_p (dpy) || !XQueryFont (dpy, font))
12832 XrmPutLineResource (&xrdb, "Emacs.dialog.*.font: 9x15");
12833 /* Do not free XFontStruct returned by the above call to XQueryFont.
12834 This leads to X protocol errors at XtCloseDisplay (Bug#18403). */
12835 x_uncatch_errors ();
12837 #endif
12839 /* See if we should run in synchronous mode. This is useful
12840 for debugging X code. */
12842 AUTO_STRING (synchronous, "synchronous");
12843 AUTO_STRING (Synchronous, "Synchronous");
12844 Lisp_Object value = display_x_get_resource (dpyinfo, synchronous,
12845 Synchronous, Qnil, Qnil);
12846 if (STRINGP (value)
12847 && (!strcmp (SSDATA (value), "true")
12848 || !strcmp (SSDATA (value), "on")))
12849 XSynchronize (dpyinfo->display, True);
12853 AUTO_STRING (useXIM, "useXIM");
12854 AUTO_STRING (UseXIM, "UseXIM");
12855 Lisp_Object value = display_x_get_resource (dpyinfo, useXIM, UseXIM,
12856 Qnil, Qnil);
12857 #ifdef USE_XIM
12858 if (STRINGP (value)
12859 && (!strcmp (SSDATA (value), "false")
12860 || !strcmp (SSDATA (value), "off")))
12861 use_xim = false;
12862 #else
12863 if (STRINGP (value)
12864 && (!strcmp (SSDATA (value), "true")
12865 || !strcmp (SSDATA (value), "on")))
12866 use_xim = true;
12867 #endif
12870 #ifdef HAVE_X_SM
12871 /* Only do this for the very first display in the Emacs session.
12872 Ignore X session management when Emacs was first started on a
12873 tty or started as a daemon. */
12874 if (terminal->id == 1 && ! IS_DAEMON)
12875 x_session_initialize (dpyinfo);
12876 #endif
12878 #ifdef USE_CAIRO
12879 x_extension_initialize (dpyinfo);
12880 #endif
12882 unblock_input ();
12884 return dpyinfo;
12887 /* Get rid of display DPYINFO, deleting all frames on it,
12888 and without sending any more commands to the X server. */
12890 static void
12891 x_delete_display (struct x_display_info *dpyinfo)
12893 struct terminal *t;
12894 struct color_name_cache_entry *color_entry, *next_color_entry;
12896 /* Close all frames and delete the generic struct terminal for this
12897 X display. */
12898 for (t = terminal_list; t; t = t->next_terminal)
12899 if (t->type == output_x_window && t->display_info.x == dpyinfo)
12901 #ifdef HAVE_X_SM
12902 /* Close X session management when we close its display. */
12903 if (t->id == 1 && x_session_have_connection ())
12904 x_session_close ();
12905 #endif
12906 delete_terminal (t);
12907 break;
12910 if (next_noop_dpyinfo == dpyinfo)
12911 next_noop_dpyinfo = dpyinfo->next;
12913 if (x_display_list == dpyinfo)
12914 x_display_list = dpyinfo->next;
12915 else
12917 struct x_display_info *tail;
12919 for (tail = x_display_list; tail; tail = tail->next)
12920 if (tail->next == dpyinfo)
12921 tail->next = tail->next->next;
12924 for (color_entry = dpyinfo->color_names;
12925 color_entry;
12926 color_entry = next_color_entry)
12928 next_color_entry = color_entry->next;
12929 xfree (color_entry->name);
12930 xfree (color_entry);
12933 xfree (dpyinfo->x_id_name);
12934 xfree (dpyinfo->x_dnd_atoms);
12935 xfree (dpyinfo->color_cells);
12936 xfree (dpyinfo);
12939 #ifdef USE_X_TOOLKIT
12941 /* Atimer callback function for TIMER. Called every 0.1s to process
12942 Xt timeouts, if needed. We must avoid calling XtAppPending as
12943 much as possible because that function does an implicit XFlush
12944 that slows us down. */
12946 static void
12947 x_process_timeouts (struct atimer *timer)
12949 block_input ();
12950 x_timeout_atimer_activated_flag = false;
12951 if (toolkit_scroll_bar_interaction || popup_activated ())
12953 while (XtAppPending (Xt_app_con) & XtIMTimer)
12954 XtAppProcessEvent (Xt_app_con, XtIMTimer);
12955 /* Reactivate the atimer for next time. */
12956 x_activate_timeout_atimer ();
12958 unblock_input ();
12961 /* Install an asynchronous timer that processes Xt timeout events
12962 every 0.1s as long as either `toolkit_scroll_bar_interaction' or
12963 `popup_activated_flag' (in xmenu.c) is set. Make sure to call this
12964 function whenever these variables are set. This is necessary
12965 because some widget sets use timeouts internally, for example the
12966 LessTif menu bar, or the Xaw3d scroll bar. When Xt timeouts aren't
12967 processed, these widgets don't behave normally. */
12969 void
12970 x_activate_timeout_atimer (void)
12972 block_input ();
12973 if (!x_timeout_atimer_activated_flag)
12975 struct timespec interval = make_timespec (0, 100 * 1000 * 1000);
12976 start_atimer (ATIMER_RELATIVE, interval, x_process_timeouts, 0);
12977 x_timeout_atimer_activated_flag = true;
12979 unblock_input ();
12982 #endif /* USE_X_TOOLKIT */
12985 /* Set up use of X before we make the first connection. */
12987 static struct redisplay_interface x_redisplay_interface =
12989 x_frame_parm_handlers,
12990 x_produce_glyphs,
12991 x_write_glyphs,
12992 x_insert_glyphs,
12993 x_clear_end_of_line,
12994 x_scroll_run,
12995 x_after_update_window_line,
12996 x_update_window_begin,
12997 x_update_window_end,
12998 x_flip_and_flush,
12999 x_clear_window_mouse_face,
13000 x_get_glyph_overhangs,
13001 x_fix_overlapping_area,
13002 x_draw_fringe_bitmap,
13003 #ifdef USE_CAIRO
13004 x_cr_define_fringe_bitmap,
13005 x_cr_destroy_fringe_bitmap,
13006 #else
13007 0, /* define_fringe_bitmap */
13008 0, /* destroy_fringe_bitmap */
13009 #endif
13010 x_compute_glyph_string_overhangs,
13011 x_draw_glyph_string,
13012 x_define_frame_cursor,
13013 x_clear_frame_area,
13014 x_draw_window_cursor,
13015 x_draw_vertical_window_border,
13016 x_draw_window_divider,
13017 x_shift_glyphs_for_insert, /* Never called; see comment in function. */
13018 x_show_hourglass,
13019 x_hide_hourglass
13023 /* This function is called when the last frame on a display is deleted. */
13024 void
13025 x_delete_terminal (struct terminal *terminal)
13027 struct x_display_info *dpyinfo = terminal->display_info.x;
13029 /* Protect against recursive calls. delete_frame in
13030 delete_terminal calls us back when it deletes our last frame. */
13031 if (!terminal->name)
13032 return;
13034 block_input ();
13035 #ifdef HAVE_X_I18N
13036 /* We must close our connection to the XIM server before closing the
13037 X display. */
13038 if (dpyinfo->xim)
13039 xim_close_dpy (dpyinfo);
13040 #endif
13042 /* Normally, the display is available... */
13043 if (dpyinfo->display)
13045 x_destroy_all_bitmaps (dpyinfo);
13046 XSetCloseDownMode (dpyinfo->display, DestroyAll);
13048 /* Whether or not XCloseDisplay destroys the associated resource
13049 database depends on the version of libX11. To avoid both
13050 crash and memory leak, we dissociate the database from the
13051 display and then destroy dpyinfo->xrdb ourselves.
13053 Unfortunately, the above strategy does not work in some
13054 situations due to a bug in newer versions of libX11: because
13055 XrmSetDatabase doesn't clear the flag XlibDisplayDfltRMDB if
13056 dpy->db is NULL, XCloseDisplay destroys the associated
13057 database whereas it has not been created by XGetDefault
13058 (Bug#21974 in freedesktop.org Bugzilla). As a workaround, we
13059 don't destroy the database here in order to avoid the crash
13060 in the above situations for now, though that may cause memory
13061 leaks in other situations. */
13062 #if false
13063 #ifdef HAVE_XRMSETDATABASE
13064 XrmSetDatabase (dpyinfo->display, NULL);
13065 #else
13066 dpyinfo->display->db = NULL;
13067 #endif
13068 /* We used to call XrmDestroyDatabase from x_delete_display, but
13069 some older versions of libX11 crash if we call it after
13070 closing all the displays. */
13071 XrmDestroyDatabase (dpyinfo->xrdb);
13072 #endif
13074 #ifdef USE_GTK
13075 xg_display_close (dpyinfo->display);
13076 #else
13077 #ifdef USE_X_TOOLKIT
13078 XtCloseDisplay (dpyinfo->display);
13079 #else
13080 XCloseDisplay (dpyinfo->display);
13081 #endif
13082 #endif /* ! USE_GTK */
13083 /* Do not close the connection here because it's already closed
13084 by X(t)CloseDisplay (Bug#18403). */
13085 dpyinfo->display = NULL;
13088 /* ...but if called from x_connection_closed, the display may already
13089 be closed and dpyinfo->display was set to 0 to indicate that. Since
13090 X server is most likely gone, explicit close is the only reliable
13091 way to continue and avoid Bug#19147. */
13092 else if (dpyinfo->connection >= 0)
13093 emacs_close (dpyinfo->connection);
13095 /* No more input on this descriptor. */
13096 delete_keyboard_wait_descriptor (dpyinfo->connection);
13097 /* Mark as dead. */
13098 dpyinfo->connection = -1;
13100 x_delete_display (dpyinfo);
13101 unblock_input ();
13104 /* Create a struct terminal, initialize it with the X11 specific
13105 functions and make DISPLAY->TERMINAL point to it. */
13107 static struct terminal *
13108 x_create_terminal (struct x_display_info *dpyinfo)
13110 struct terminal *terminal;
13112 terminal = create_terminal (output_x_window, &x_redisplay_interface);
13114 terminal->display_info.x = dpyinfo;
13115 dpyinfo->terminal = terminal;
13117 /* kboard is initialized in x_term_init. */
13119 terminal->clear_frame_hook = x_clear_frame;
13120 terminal->ins_del_lines_hook = x_ins_del_lines;
13121 terminal->delete_glyphs_hook = x_delete_glyphs;
13122 terminal->ring_bell_hook = XTring_bell;
13123 terminal->toggle_invisible_pointer_hook = XTtoggle_invisible_pointer;
13124 terminal->update_begin_hook = x_update_begin;
13125 terminal->update_end_hook = x_update_end;
13126 terminal->read_socket_hook = XTread_socket;
13127 terminal->frame_up_to_date_hook = XTframe_up_to_date;
13128 terminal->buffer_flipping_unblocked_hook = XTbuffer_flipping_unblocked_hook;
13129 terminal->mouse_position_hook = XTmouse_position;
13130 terminal->frame_rehighlight_hook = XTframe_rehighlight;
13131 terminal->frame_raise_lower_hook = XTframe_raise_lower;
13132 terminal->fullscreen_hook = XTfullscreen_hook;
13133 terminal->menu_show_hook = x_menu_show;
13134 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
13135 terminal->popup_dialog_hook = xw_popup_dialog;
13136 #endif
13137 terminal->set_vertical_scroll_bar_hook = XTset_vertical_scroll_bar;
13138 terminal->set_horizontal_scroll_bar_hook = XTset_horizontal_scroll_bar;
13139 terminal->condemn_scroll_bars_hook = XTcondemn_scroll_bars;
13140 terminal->redeem_scroll_bar_hook = XTredeem_scroll_bar;
13141 terminal->judge_scroll_bars_hook = XTjudge_scroll_bars;
13142 terminal->delete_frame_hook = x_destroy_window;
13143 terminal->delete_terminal_hook = x_delete_terminal;
13144 /* Other hooks are NULL by default. */
13146 return terminal;
13149 static void
13150 x_initialize (void)
13152 baud_rate = 19200;
13154 x_noop_count = 0;
13155 any_help_event_p = false;
13156 ignore_next_mouse_click_timeout = 0;
13158 #ifdef USE_GTK
13159 current_count = -1;
13160 #endif
13162 /* Try to use interrupt input; if we can't, then start polling. */
13163 Fset_input_interrupt_mode (Qt);
13165 #if THREADS_ENABLED
13166 /* This must be called before any other Xlib routines. */
13167 if (XInitThreads () == 0)
13168 fprintf (stderr,
13169 "Warning: An error occurred initializing X11 thread support!\n");
13170 #endif
13172 #ifdef USE_X_TOOLKIT
13173 XtToolkitInitialize ();
13175 Xt_app_con = XtCreateApplicationContext ();
13177 /* Register a converter from strings to pixels, which uses
13178 Emacs' color allocation infrastructure. */
13179 XtAppSetTypeConverter (Xt_app_con,
13180 XtRString, XtRPixel, cvt_string_to_pixel,
13181 cvt_string_to_pixel_args,
13182 XtNumber (cvt_string_to_pixel_args),
13183 XtCacheByDisplay, cvt_pixel_dtor);
13185 XtAppSetFallbackResources (Xt_app_con, Xt_default_resources);
13186 #endif
13188 #ifdef USE_TOOLKIT_SCROLL_BARS
13189 #ifndef USE_GTK
13190 xaw3d_arrow_scroll = False;
13191 xaw3d_pick_top = True;
13192 #endif
13193 #endif
13195 #ifdef USE_CAIRO
13196 x_cr_init_fringe (&x_redisplay_interface);
13197 #endif
13199 /* Note that there is no real way portable across R3/R4 to get the
13200 original error handler. */
13201 XSetErrorHandler (x_error_handler);
13202 XSetIOErrorHandler (x_io_error_quitter);
13205 #ifdef USE_GTK
13206 void
13207 init_xterm (void)
13209 /* Emacs can handle only core input events, so make sure
13210 Gtk doesn't use Xinput or Xinput2 extensions. */
13211 xputenv ("GDK_CORE_DEVICE_EVENTS=1");
13213 #endif
13215 void
13216 syms_of_xterm (void)
13218 x_error_message = NULL;
13220 DEFSYM (Qvendor_specific_keysyms, "vendor-specific-keysyms");
13221 DEFSYM (Qlatin_1, "latin-1");
13223 #ifdef USE_GTK
13224 xg_default_icon_file = build_pure_c_string ("icons/hicolor/scalable/apps/emacs.svg");
13225 staticpro (&xg_default_icon_file);
13227 DEFSYM (Qx_gtk_map_stock, "x-gtk-map-stock");
13228 #endif
13230 DEFVAR_BOOL ("x-use-underline-position-properties",
13231 x_use_underline_position_properties,
13232 doc: /* Non-nil means make use of UNDERLINE_POSITION font properties.
13233 A value of nil means ignore them. If you encounter fonts with bogus
13234 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
13235 to 4.1, set this to nil. You can also use `underline-minimum-offset'
13236 to override the font's UNDERLINE_POSITION for small font display
13237 sizes. */);
13238 x_use_underline_position_properties = true;
13240 DEFVAR_BOOL ("x-underline-at-descent-line",
13241 x_underline_at_descent_line,
13242 doc: /* Non-nil means to draw the underline at the same place as the descent line.
13243 A value of nil means to draw the underline according to the value of the
13244 variable `x-use-underline-position-properties', which is usually at the
13245 baseline level. The default value is nil. */);
13246 x_underline_at_descent_line = false;
13248 DEFVAR_BOOL ("x-mouse-click-focus-ignore-position",
13249 x_mouse_click_focus_ignore_position,
13250 doc: /* Non-nil means that a mouse click to focus a frame does not move point.
13251 This variable is only used when the window manager requires that you
13252 click on a frame to select it (give it focus). In that case, a value
13253 of nil, means that the selected window and cursor position changes to
13254 reflect the mouse click position, while a non-nil value means that the
13255 selected window or cursor position is preserved. */);
13256 x_mouse_click_focus_ignore_position = false;
13258 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
13259 doc: /* Which toolkit scroll bars Emacs uses, if any.
13260 A value of nil means Emacs doesn't use toolkit scroll bars.
13261 With the X Window system, the value is a symbol describing the
13262 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
13263 With MS Windows or Nextstep, the value is t. */);
13264 #ifdef USE_TOOLKIT_SCROLL_BARS
13265 #ifdef USE_MOTIF
13266 Vx_toolkit_scroll_bars = intern_c_string ("motif");
13267 #elif defined HAVE_XAW3D
13268 Vx_toolkit_scroll_bars = intern_c_string ("xaw3d");
13269 #elif USE_GTK
13270 Vx_toolkit_scroll_bars = intern_c_string ("gtk");
13271 #else
13272 Vx_toolkit_scroll_bars = intern_c_string ("xaw");
13273 #endif
13274 #else
13275 Vx_toolkit_scroll_bars = Qnil;
13276 #endif
13278 DEFSYM (Qmodifier_value, "modifier-value");
13279 DEFSYM (Qctrl, "ctrl");
13280 Fput (Qctrl, Qmodifier_value, make_number (ctrl_modifier));
13281 DEFSYM (Qalt, "alt");
13282 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
13283 DEFSYM (Qhyper, "hyper");
13284 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
13285 DEFSYM (Qmeta, "meta");
13286 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
13287 DEFSYM (Qsuper, "super");
13288 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
13290 DEFVAR_LISP ("x-ctrl-keysym", Vx_ctrl_keysym,
13291 doc: /* Which keys Emacs uses for the ctrl modifier.
13292 This should be one of the symbols `ctrl', `alt', `hyper', `meta',
13293 `super'. For example, `ctrl' means use the Ctrl_L and Ctrl_R keysyms.
13294 The default is nil, which is the same as `ctrl'. */);
13295 Vx_ctrl_keysym = Qnil;
13297 DEFVAR_LISP ("x-alt-keysym", Vx_alt_keysym,
13298 doc: /* Which keys Emacs uses for the alt modifier.
13299 This should be one of the symbols `ctrl', `alt', `hyper', `meta',
13300 `super'. For example, `alt' means use the Alt_L and Alt_R keysyms.
13301 The default is nil, which is the same as `alt'. */);
13302 Vx_alt_keysym = Qnil;
13304 DEFVAR_LISP ("x-hyper-keysym", Vx_hyper_keysym,
13305 doc: /* Which keys Emacs uses for the hyper modifier.
13306 This should be one of the symbols `ctrl', `alt', `hyper', `meta',
13307 `super'. For example, `hyper' means use the Hyper_L and Hyper_R
13308 keysyms. The default is nil, which is the same as `hyper'. */);
13309 Vx_hyper_keysym = Qnil;
13311 DEFVAR_LISP ("x-meta-keysym", Vx_meta_keysym,
13312 doc: /* Which keys Emacs uses for the meta modifier.
13313 This should be one of the symbols `ctrl', `alt', `hyper', `meta',
13314 `super'. For example, `meta' means use the Meta_L and Meta_R keysyms.
13315 The default is nil, which is the same as `meta'. */);
13316 Vx_meta_keysym = Qnil;
13318 DEFVAR_LISP ("x-super-keysym", Vx_super_keysym,
13319 doc: /* Which keys Emacs uses for the super modifier.
13320 This should be one of the symbols `ctrl', `alt', `hyper', `meta',
13321 `super'. For example, `super' means use the Super_L and Super_R
13322 keysyms. The default is nil, which is the same as `super'. */);
13323 Vx_super_keysym = Qnil;
13325 DEFVAR_LISP ("x-wait-for-event-timeout", Vx_wait_for_event_timeout,
13326 doc: /* How long to wait for X events.
13328 Emacs will wait up to this many seconds to receive X events after
13329 making changes which affect the state of the graphical interface.
13330 Under some window managers this can take an indefinite amount of time,
13331 so it is important to limit the wait.
13333 If set to a non-float value, there will be no wait at all. */);
13334 Vx_wait_for_event_timeout = make_float (0.1);
13336 DEFVAR_LISP ("x-keysym-table", Vx_keysym_table,
13337 doc: /* Hash table of character codes indexed by X keysym codes. */);
13338 Vx_keysym_table = make_hash_table (hashtest_eql, 900,
13339 DEFAULT_REHASH_SIZE,
13340 DEFAULT_REHASH_THRESHOLD,
13341 Qnil, false);
13343 DEFVAR_BOOL ("x-frame-normalize-before-maximize",
13344 x_frame_normalize_before_maximize,
13345 doc: /* Non-nil means normalize frame before maximizing.
13346 If this variable is t, Emacs first asks the window manager to give the
13347 frame its normal size, and only then the final state, whenever changing
13348 from a full-height, full-width or full-both state to the maximized one
13349 or when changing from the maximized to the full-height or full-width
13350 state.
13352 Set this variable only if your window manager cannot handle the
13353 transition between the various maximization states. */);
13354 x_frame_normalize_before_maximize = false;
13356 DEFVAR_BOOL ("x-gtk-use-window-move", x_gtk_use_window_move,
13357 doc: /* Non-nil means rely on gtk_window_move to set frame positions.
13358 If this variable is t (the default), the GTK build uses the function
13359 gtk_window_move to set or store frame positions and disables some time
13360 consuming frame position adjustments. In newer versions of GTK, Emacs
13361 always uses gtk_window_move and ignores the value of this variable. */);
13362 x_gtk_use_window_move = true;