Allow 'browse-url-emacs' to fetch URL in the selected window
[emacs.git] / src / xterm.c
blobdb5ea4ac55ecef90fa7a5ecd3fae6ef490cd092d
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);
3710 unsigned long minimum_offset;
3711 bool underline_at_descent_line;
3712 bool use_underline_position_properties;
3713 Lisp_Object val
3714 = buffer_local_value (Qunderline_minimum_offset,
3715 s->w->contents);
3716 if (INTEGERP (val))
3717 minimum_offset = XFASTINT (val);
3718 else
3719 minimum_offset = 1;
3720 val = buffer_local_value (Qx_underline_at_descent_line,
3721 s->w->contents);
3722 underline_at_descent_line
3723 = !(NILP (val) || EQ (val, Qunbound));
3725 = buffer_local_value (Qx_use_underline_position_properties,
3726 s->w->contents);
3727 use_underline_position_properties
3728 = !(NILP (val) || EQ (val, Qunbound));
3730 /* Get the underline thickness. Default is 1 pixel. */
3731 if (font && font->underline_thickness > 0)
3732 thickness = font->underline_thickness;
3733 else
3734 thickness = 1;
3735 if (underline_at_descent_line)
3736 position = (s->height - thickness) - (s->ybase - s->y);
3737 else
3739 /* Get the underline position. This is the
3740 recommended vertical offset in pixels from
3741 the baseline to the top of the underline.
3742 This is a signed value according to the
3743 specs, and its default is
3745 ROUND ((maximum descent) / 2), with
3746 ROUND(x) = floor (x + 0.5) */
3748 if (use_underline_position_properties
3749 && font && font->underline_position >= 0)
3750 position = font->underline_position;
3751 else if (font)
3752 position = (font->descent + 1) / 2;
3753 else
3754 position = minimum_offset;
3756 position = max (position, minimum_offset);
3758 /* Check the sanity of thickness and position. We should
3759 avoid drawing underline out of the current line area. */
3760 if (s->y + s->height <= s->ybase + position)
3761 position = (s->height - 1) - (s->ybase - s->y);
3762 if (s->y + s->height < s->ybase + position + thickness)
3763 thickness = (s->y + s->height) - (s->ybase + position);
3764 s->underline_thickness = thickness;
3765 s->underline_position = position;
3766 y = s->ybase + position;
3767 if (s->face->underline_defaulted_p)
3768 x_fill_rectangle (s->f, s->gc,
3769 s->x, y, s->width, thickness);
3770 else
3772 XGCValues xgcv;
3773 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3774 XSetForeground (s->display, s->gc, s->face->underline_color);
3775 x_fill_rectangle (s->f, s->gc,
3776 s->x, y, s->width, thickness);
3777 XSetForeground (s->display, s->gc, xgcv.foreground);
3781 /* Draw overline. */
3782 if (s->face->overline_p)
3784 unsigned long dy = 0, h = 1;
3786 if (s->face->overline_color_defaulted_p)
3787 x_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3788 s->width, h);
3789 else
3791 XGCValues xgcv;
3792 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3793 XSetForeground (s->display, s->gc, s->face->overline_color);
3794 x_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3795 s->width, h);
3796 XSetForeground (s->display, s->gc, xgcv.foreground);
3800 /* Draw strike-through. */
3801 if (s->face->strike_through_p)
3803 /* Y-coordinate and height of the glyph string's first
3804 glyph. We cannot use s->y and s->height because those
3805 could be larger if there are taller display elements
3806 (e.g., characters displayed with a larger font) in the
3807 same glyph row. */
3808 int glyph_y = s->ybase - s->first_glyph->ascent;
3809 int glyph_height = s->first_glyph->ascent + s->first_glyph->descent;
3810 /* Strike-through width and offset from the glyph string's
3811 top edge. */
3812 unsigned long h = 1;
3813 unsigned long dy = (glyph_height - h) / 2;
3815 if (s->face->strike_through_color_defaulted_p)
3816 x_fill_rectangle (s->f, s->gc, s->x, glyph_y + dy,
3817 s->width, h);
3818 else
3820 XGCValues xgcv;
3821 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3822 XSetForeground (s->display, s->gc, s->face->strike_through_color);
3823 x_fill_rectangle (s->f, s->gc, s->x, glyph_y + dy,
3824 s->width, h);
3825 XSetForeground (s->display, s->gc, xgcv.foreground);
3829 /* Draw relief if not yet drawn. */
3830 if (!relief_drawn_p && s->face->box != FACE_NO_BOX)
3831 x_draw_glyph_string_box (s);
3833 if (s->prev)
3835 struct glyph_string *prev;
3837 for (prev = s->prev; prev; prev = prev->prev)
3838 if (prev->hl != s->hl
3839 && prev->x + prev->width + prev->right_overhang > s->x)
3841 /* As prev was drawn while clipped to its own area, we
3842 must draw the right_overhang part using s->hl now. */
3843 enum draw_glyphs_face save = prev->hl;
3845 prev->hl = s->hl;
3846 x_set_glyph_string_gc (prev);
3847 x_set_glyph_string_clipping_exactly (s, prev);
3848 if (prev->first_glyph->type == CHAR_GLYPH)
3849 x_draw_glyph_string_foreground (prev);
3850 else
3851 x_draw_composite_glyph_string_foreground (prev);
3852 x_reset_clip_rectangles (prev->f, prev->gc);
3853 prev->hl = save;
3854 prev->num_clips = 0;
3858 if (s->next)
3860 struct glyph_string *next;
3862 for (next = s->next; next; next = next->next)
3863 if (next->hl != s->hl
3864 && next->x - next->left_overhang < s->x + s->width)
3866 /* As next will be drawn while clipped to its own area,
3867 we must draw the left_overhang part using s->hl now. */
3868 enum draw_glyphs_face save = next->hl;
3870 next->hl = s->hl;
3871 x_set_glyph_string_gc (next);
3872 x_set_glyph_string_clipping_exactly (s, next);
3873 if (next->first_glyph->type == CHAR_GLYPH)
3874 x_draw_glyph_string_foreground (next);
3875 else
3876 x_draw_composite_glyph_string_foreground (next);
3877 x_reset_clip_rectangles (next->f, next->gc);
3878 next->hl = save;
3879 next->num_clips = 0;
3880 next->clip_head = s->next;
3885 /* Reset clipping. */
3886 x_reset_clip_rectangles (s->f, s->gc);
3887 s->num_clips = 0;
3890 /* Shift display to make room for inserted glyphs. */
3892 static void
3893 x_shift_glyphs_for_insert (struct frame *f, int x, int y, int width, int height, int shift_by)
3895 /* Never called on a GUI frame, see
3896 https://lists.gnu.org/r/emacs-devel/2015-05/msg00456.html
3898 XCopyArea (FRAME_X_DISPLAY (f), FRAME_X_DRAWABLE (f), FRAME_X_DRAWABLE (f),
3899 f->output_data.x->normal_gc,
3900 x, y, width, height,
3901 x + shift_by, y);
3904 /* Delete N glyphs at the nominal cursor position. Not implemented
3905 for X frames. */
3907 static void
3908 x_delete_glyphs (struct frame *f, register int n)
3910 emacs_abort ();
3914 /* Like XClearArea, but check that WIDTH and HEIGHT are reasonable.
3915 If they are <= 0, this is probably an error. */
3917 static ATTRIBUTE_UNUSED void
3918 x_clear_area1 (Display *dpy, Window window,
3919 int x, int y, int width, int height, int exposures)
3921 eassert (width > 0 && height > 0);
3922 XClearArea (dpy, window, x, y, width, height, exposures);
3925 void
3926 x_clear_area (struct frame *f, int x, int y, int width, int height)
3928 #ifdef USE_CAIRO
3929 cairo_t *cr;
3931 eassert (width > 0 && height > 0);
3933 cr = x_begin_cr_clip (f, NULL);
3934 x_set_cr_source_with_gc_background (f, f->output_data.x->normal_gc);
3935 cairo_rectangle (cr, x, y, width, height);
3936 cairo_fill (cr);
3937 x_end_cr_clip (f);
3938 #else
3939 if (FRAME_X_DOUBLE_BUFFERED_P (f))
3940 XFillRectangle (FRAME_X_DISPLAY (f),
3941 FRAME_X_DRAWABLE (f),
3942 f->output_data.x->reverse_gc,
3943 x, y, width, height);
3944 else
3945 x_clear_area1 (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3946 x, y, width, height, False);
3947 #endif
3951 /* Clear an entire frame. */
3953 static void
3954 x_clear_frame (struct frame *f)
3956 /* Clearing the frame will erase any cursor, so mark them all as no
3957 longer visible. */
3958 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
3960 block_input ();
3962 font_drop_xrender_surfaces (f);
3963 x_clear_window (f);
3965 /* We have to clear the scroll bars. If we have changed colors or
3966 something like that, then they should be notified. */
3967 x_scroll_bar_clear (f);
3969 XFlush (FRAME_X_DISPLAY (f));
3971 unblock_input ();
3974 /* RIF: Show hourglass cursor on frame F. */
3976 static void
3977 x_show_hourglass (struct frame *f)
3979 Display *dpy = FRAME_X_DISPLAY (f);
3981 if (dpy)
3983 struct x_output *x = FRAME_X_OUTPUT (f);
3984 #ifdef USE_X_TOOLKIT
3985 if (x->widget)
3986 #else
3987 if (FRAME_OUTER_WINDOW (f))
3988 #endif
3990 x->hourglass_p = true;
3992 if (!x->hourglass_window)
3994 unsigned long mask = CWCursor;
3995 XSetWindowAttributes attrs;
3996 #ifdef USE_GTK
3997 Window parent = FRAME_X_WINDOW (f);
3998 #else
3999 Window parent = FRAME_OUTER_WINDOW (f);
4000 #endif
4001 attrs.cursor = x->hourglass_cursor;
4003 x->hourglass_window = XCreateWindow
4004 (dpy, parent, 0, 0, 32000, 32000, 0, 0,
4005 InputOnly, CopyFromParent, mask, &attrs);
4008 XMapRaised (dpy, x->hourglass_window);
4009 XFlush (dpy);
4014 /* RIF: Cancel hourglass cursor on frame F. */
4016 static void
4017 x_hide_hourglass (struct frame *f)
4019 struct x_output *x = FRAME_X_OUTPUT (f);
4021 /* Watch out for newly created frames. */
4022 if (x->hourglass_window)
4024 XUnmapWindow (FRAME_X_DISPLAY (f), x->hourglass_window);
4025 /* Sync here because XTread_socket looks at the
4026 hourglass_p flag that is reset to zero below. */
4027 XSync (FRAME_X_DISPLAY (f), False);
4028 x->hourglass_p = false;
4032 /* Invert the middle quarter of the frame for .15 sec. */
4034 static void
4035 XTflash (struct frame *f)
4037 block_input ();
4040 #ifdef USE_GTK
4041 /* Use Gdk routines to draw. This way, we won't draw over scroll bars
4042 when the scroll bars and the edit widget share the same X window. */
4043 GdkWindow *window = gtk_widget_get_window (FRAME_GTK_WIDGET (f));
4044 #ifdef HAVE_GTK3
4045 #if GTK_CHECK_VERSION (3, 22, 0)
4046 cairo_region_t *region = gdk_window_get_visible_region (window);
4047 GdkDrawingContext *context = gdk_window_begin_draw_frame (window, region);
4048 cairo_t *cr = gdk_drawing_context_get_cairo_context (context);
4049 #else
4050 cairo_t *cr = gdk_cairo_create (window);
4051 #endif
4052 cairo_set_source_rgb (cr, 1, 1, 1);
4053 cairo_set_operator (cr, CAIRO_OPERATOR_DIFFERENCE);
4054 #define XFillRectangle(d, win, gc, x, y, w, h) \
4055 do { \
4056 cairo_rectangle (cr, x, y, w, h); \
4057 cairo_fill (cr); \
4059 while (false)
4060 #else /* ! HAVE_GTK3 */
4061 GdkGCValues vals;
4062 GdkGC *gc;
4063 vals.foreground.pixel = (FRAME_FOREGROUND_PIXEL (f)
4064 ^ FRAME_BACKGROUND_PIXEL (f));
4065 vals.function = GDK_XOR;
4066 gc = gdk_gc_new_with_values (window,
4067 &vals, GDK_GC_FUNCTION | GDK_GC_FOREGROUND);
4068 #define XFillRectangle(d, win, gc, x, y, w, h) \
4069 gdk_draw_rectangle (window, gc, true, x, y, w, h)
4070 #endif /* ! HAVE_GTK3 */
4071 #else /* ! USE_GTK */
4072 GC gc;
4074 /* Create a GC that will use the GXxor function to flip foreground
4075 pixels into background pixels. */
4077 XGCValues values;
4079 values.function = GXxor;
4080 values.foreground = (FRAME_FOREGROUND_PIXEL (f)
4081 ^ FRAME_BACKGROUND_PIXEL (f));
4083 gc = XCreateGC (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4084 GCFunction | GCForeground, &values);
4086 #endif
4088 /* Get the height not including a menu bar widget. */
4089 int height = FRAME_PIXEL_HEIGHT (f);
4090 /* Height of each line to flash. */
4091 int flash_height = FRAME_LINE_HEIGHT (f);
4092 /* These will be the left and right margins of the rectangles. */
4093 int flash_left = FRAME_INTERNAL_BORDER_WIDTH (f);
4094 int flash_right = FRAME_PIXEL_WIDTH (f) - FRAME_INTERNAL_BORDER_WIDTH (f);
4095 int width = flash_right - flash_left;
4097 /* If window is tall, flash top and bottom line. */
4098 if (height > 3 * FRAME_LINE_HEIGHT (f))
4100 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4101 flash_left,
4102 (FRAME_INTERNAL_BORDER_WIDTH (f)
4103 + FRAME_TOP_MARGIN_HEIGHT (f)),
4104 width, flash_height);
4105 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4106 flash_left,
4107 (height - flash_height
4108 - FRAME_INTERNAL_BORDER_WIDTH (f)),
4109 width, flash_height);
4112 else
4113 /* If it is short, flash it all. */
4114 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4115 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
4116 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
4118 x_flush (f);
4121 struct timespec delay = make_timespec (0, 150 * 1000 * 1000);
4122 struct timespec wakeup = timespec_add (current_timespec (), delay);
4124 /* Keep waiting until past the time wakeup or any input gets
4125 available. */
4126 while (! detect_input_pending ())
4128 struct timespec current = current_timespec ();
4129 struct timespec timeout;
4131 /* Break if result would not be positive. */
4132 if (timespec_cmp (wakeup, current) <= 0)
4133 break;
4135 /* How long `select' should wait. */
4136 timeout = make_timespec (0, 10 * 1000 * 1000);
4138 /* Try to wait that long--but we might wake up sooner. */
4139 pselect (0, NULL, NULL, NULL, &timeout, NULL);
4143 /* If window is tall, flash top and bottom line. */
4144 if (height > 3 * FRAME_LINE_HEIGHT (f))
4146 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4147 flash_left,
4148 (FRAME_INTERNAL_BORDER_WIDTH (f)
4149 + FRAME_TOP_MARGIN_HEIGHT (f)),
4150 width, flash_height);
4151 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4152 flash_left,
4153 (height - flash_height
4154 - FRAME_INTERNAL_BORDER_WIDTH (f)),
4155 width, flash_height);
4157 else
4158 /* If it is short, flash it all. */
4159 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4160 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
4161 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
4163 #ifdef USE_GTK
4164 #ifdef HAVE_GTK3
4165 #if GTK_CHECK_VERSION (3, 22, 0)
4166 gdk_window_end_draw_frame (window, context);
4167 cairo_region_destroy (region);
4168 #else
4169 cairo_destroy (cr);
4170 #endif
4171 #else
4172 g_object_unref (G_OBJECT (gc));
4173 #endif
4174 #undef XFillRectangle
4175 #else
4176 XFreeGC (FRAME_X_DISPLAY (f), gc);
4177 #endif
4178 x_flush (f);
4182 unblock_input ();
4186 static void
4187 XTtoggle_invisible_pointer (struct frame *f, bool invisible)
4189 block_input ();
4190 FRAME_DISPLAY_INFO (f)->toggle_visible_pointer (f, invisible);
4191 unblock_input ();
4195 /* Make audible bell. */
4197 static void
4198 XTring_bell (struct frame *f)
4200 if (FRAME_X_DISPLAY (f))
4202 if (visible_bell)
4203 XTflash (f);
4204 else
4206 block_input ();
4207 #ifdef HAVE_XKB
4208 XkbBell (FRAME_X_DISPLAY (f), None, 0, None);
4209 #else
4210 XBell (FRAME_X_DISPLAY (f), 0);
4211 #endif
4212 XFlush (FRAME_X_DISPLAY (f));
4213 unblock_input ();
4218 /***********************************************************************
4219 Line Dance
4220 ***********************************************************************/
4222 /* Perform an insert-lines or delete-lines operation, inserting N
4223 lines or deleting -N lines at vertical position VPOS. */
4225 static void
4226 x_ins_del_lines (struct frame *f, int vpos, int n)
4228 emacs_abort ();
4232 /* Scroll part of the display as described by RUN. */
4234 static void
4235 x_scroll_run (struct window *w, struct run *run)
4237 struct frame *f = XFRAME (w->frame);
4238 int x, y, width, height, from_y, to_y, bottom_y;
4240 /* Get frame-relative bounding box of the text display area of W,
4241 without mode lines. Include in this box the left and right
4242 fringe of W. */
4243 window_box (w, ANY_AREA, &x, &y, &width, &height);
4245 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
4246 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
4247 bottom_y = y + height;
4249 if (to_y < from_y)
4251 /* Scrolling up. Make sure we don't copy part of the mode
4252 line at the bottom. */
4253 if (from_y + run->height > bottom_y)
4254 height = bottom_y - from_y;
4255 else
4256 height = run->height;
4258 else
4260 /* Scrolling down. Make sure we don't copy over the mode line.
4261 at the bottom. */
4262 if (to_y + run->height > bottom_y)
4263 height = bottom_y - to_y;
4264 else
4265 height = run->height;
4268 block_input ();
4270 /* Cursor off. Will be switched on again in x_update_window_end. */
4271 x_clear_cursor (w);
4273 #ifdef USE_CAIRO
4274 SET_FRAME_GARBAGED (f);
4275 #else
4276 XCopyArea (FRAME_X_DISPLAY (f),
4277 FRAME_X_DRAWABLE (f), FRAME_X_DRAWABLE (f),
4278 f->output_data.x->normal_gc,
4279 x, from_y,
4280 width, height,
4281 x, to_y);
4282 #endif
4284 unblock_input ();
4289 /***********************************************************************
4290 Exposure Events
4291 ***********************************************************************/
4294 static void
4295 frame_highlight (struct frame *f)
4297 /* We used to only do this if Vx_no_window_manager was non-nil, but
4298 the ICCCM (section 4.1.6) says that the window's border pixmap
4299 and border pixel are window attributes which are "private to the
4300 client", so we can always change it to whatever we want. */
4301 block_input ();
4302 /* I recently started to get errors in this XSetWindowBorder, depending on
4303 the window-manager in use, tho something more is at play since I've been
4304 using that same window-manager binary for ever. Let's not crash just
4305 because of this (bug#9310). */
4306 x_catch_errors (FRAME_X_DISPLAY (f));
4307 XSetWindowBorder (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4308 f->output_data.x->border_pixel);
4309 x_uncatch_errors ();
4310 unblock_input ();
4311 x_update_cursor (f, true);
4312 x_set_frame_alpha (f);
4315 static void
4316 frame_unhighlight (struct frame *f)
4318 /* We used to only do this if Vx_no_window_manager was non-nil, but
4319 the ICCCM (section 4.1.6) says that the window's border pixmap
4320 and border pixel are window attributes which are "private to the
4321 client", so we can always change it to whatever we want. */
4322 block_input ();
4323 /* Same as above for XSetWindowBorder (bug#9310). */
4324 x_catch_errors (FRAME_X_DISPLAY (f));
4325 XSetWindowBorderPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4326 f->output_data.x->border_tile);
4327 x_uncatch_errors ();
4328 unblock_input ();
4329 x_update_cursor (f, true);
4330 x_set_frame_alpha (f);
4333 /* The focus has changed. Update the frames as necessary to reflect
4334 the new situation. Note that we can't change the selected frame
4335 here, because the Lisp code we are interrupting might become confused.
4336 Each event gets marked with the frame in which it occurred, so the
4337 Lisp code can tell when the switch took place by examining the events. */
4339 static void
4340 x_new_focus_frame (struct x_display_info *dpyinfo, struct frame *frame)
4342 struct frame *old_focus = dpyinfo->x_focus_frame;
4344 if (frame != dpyinfo->x_focus_frame)
4346 /* Set this before calling other routines, so that they see
4347 the correct value of x_focus_frame. */
4348 dpyinfo->x_focus_frame = frame;
4350 if (old_focus && old_focus->auto_lower)
4351 x_lower_frame (old_focus);
4353 if (dpyinfo->x_focus_frame && dpyinfo->x_focus_frame->auto_raise)
4354 dpyinfo->x_pending_autoraise_frame = dpyinfo->x_focus_frame;
4355 else
4356 dpyinfo->x_pending_autoraise_frame = NULL;
4359 x_frame_rehighlight (dpyinfo);
4362 /* Handle FocusIn and FocusOut state changes for FRAME.
4363 If FRAME has focus and there exists more than one frame, puts
4364 a FOCUS_IN_EVENT into *BUFP. */
4366 static void
4367 x_focus_changed (int type, int state, struct x_display_info *dpyinfo, struct frame *frame, struct input_event *bufp)
4369 if (type == FocusIn)
4371 if (dpyinfo->x_focus_event_frame != frame)
4373 x_new_focus_frame (dpyinfo, frame);
4374 dpyinfo->x_focus_event_frame = frame;
4376 /* Don't stop displaying the initial startup message
4377 for a switch-frame event we don't need. */
4378 /* When run as a daemon, Vterminal_frame is always NIL. */
4379 bufp->arg = (((NILP (Vterminal_frame)
4380 || ! FRAME_X_P (XFRAME (Vterminal_frame))
4381 || EQ (Fdaemonp (), Qt))
4382 && CONSP (Vframe_list)
4383 && !NILP (XCDR (Vframe_list)))
4384 ? Qt : Qnil);
4385 bufp->kind = FOCUS_IN_EVENT;
4386 XSETFRAME (bufp->frame_or_window, frame);
4389 frame->output_data.x->focus_state |= state;
4391 #ifdef HAVE_X_I18N
4392 if (FRAME_XIC (frame))
4393 XSetICFocus (FRAME_XIC (frame));
4394 #endif
4396 else if (type == FocusOut)
4398 frame->output_data.x->focus_state &= ~state;
4400 if (dpyinfo->x_focus_event_frame == frame)
4402 dpyinfo->x_focus_event_frame = 0;
4403 x_new_focus_frame (dpyinfo, 0);
4405 bufp->kind = FOCUS_OUT_EVENT;
4406 XSETFRAME (bufp->frame_or_window, frame);
4409 #ifdef HAVE_X_I18N
4410 if (FRAME_XIC (frame))
4411 XUnsetICFocus (FRAME_XIC (frame));
4412 #endif
4413 if (frame->pointer_invisible)
4414 XTtoggle_invisible_pointer (frame, false);
4418 /* Return the Emacs frame-object corresponding to an X window.
4419 It could be the frame's main window or an icon window. */
4421 static struct frame *
4422 x_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
4424 Lisp_Object tail, frame;
4425 struct frame *f;
4427 if (wdesc == None)
4428 return NULL;
4430 FOR_EACH_FRAME (tail, frame)
4432 f = XFRAME (frame);
4433 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
4434 continue;
4435 if (f->output_data.x->hourglass_window == wdesc)
4436 return f;
4437 #ifdef USE_X_TOOLKIT
4438 if ((f->output_data.x->edit_widget
4439 && XtWindow (f->output_data.x->edit_widget) == wdesc)
4440 /* A tooltip frame? */
4441 || (!f->output_data.x->edit_widget
4442 && FRAME_X_WINDOW (f) == wdesc)
4443 || f->output_data.x->icon_desc == wdesc)
4444 return f;
4445 #else /* not USE_X_TOOLKIT */
4446 #ifdef USE_GTK
4447 if (f->output_data.x->edit_widget)
4449 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
4450 struct x_output *x = f->output_data.x;
4451 if (gwdesc != 0 && gwdesc == x->edit_widget)
4452 return f;
4454 #endif /* USE_GTK */
4455 if (FRAME_X_WINDOW (f) == wdesc
4456 || f->output_data.x->icon_desc == wdesc)
4457 return f;
4458 #endif /* not USE_X_TOOLKIT */
4460 return 0;
4463 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
4465 /* Like x_window_to_frame but also compares the window with the widget's
4466 windows. */
4468 static struct frame *
4469 x_any_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
4471 Lisp_Object tail, frame;
4472 struct frame *f, *found = NULL;
4473 struct x_output *x;
4475 if (wdesc == None)
4476 return NULL;
4478 FOR_EACH_FRAME (tail, frame)
4480 if (found)
4481 break;
4482 f = XFRAME (frame);
4483 if (FRAME_X_P (f) && FRAME_DISPLAY_INFO (f) == dpyinfo)
4485 /* This frame matches if the window is any of its widgets. */
4486 x = f->output_data.x;
4487 if (x->hourglass_window == wdesc)
4488 found = f;
4489 else if (x->widget)
4491 #ifdef USE_GTK
4492 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
4493 if (gwdesc != 0
4494 && gtk_widget_get_toplevel (gwdesc) == x->widget)
4495 found = f;
4496 #else
4497 if (wdesc == XtWindow (x->widget)
4498 || wdesc == XtWindow (x->column_widget)
4499 || wdesc == XtWindow (x->edit_widget))
4500 found = f;
4501 /* Match if the window is this frame's menubar. */
4502 else if (lw_window_is_in_menubar (wdesc, x->menubar_widget))
4503 found = f;
4504 #endif
4506 else if (FRAME_X_WINDOW (f) == wdesc)
4507 /* A tooltip frame. */
4508 found = f;
4512 return found;
4515 /* Likewise, but consider only the menu bar widget. */
4517 static struct frame *
4518 x_menubar_window_to_frame (struct x_display_info *dpyinfo,
4519 const XEvent *event)
4521 Window wdesc = event->xany.window;
4522 Lisp_Object tail, frame;
4523 struct frame *f;
4524 struct x_output *x;
4526 if (wdesc == None)
4527 return NULL;
4529 FOR_EACH_FRAME (tail, frame)
4531 f = XFRAME (frame);
4532 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
4533 continue;
4534 x = f->output_data.x;
4535 #ifdef USE_GTK
4536 if (x->menubar_widget && xg_event_is_for_menubar (f, event))
4537 return f;
4538 #else
4539 /* Match if the window is this frame's menubar. */
4540 if (x->menubar_widget
4541 && lw_window_is_in_menubar (wdesc, x->menubar_widget))
4542 return f;
4543 #endif
4545 return 0;
4548 /* Return the frame whose principal (outermost) window is WDESC.
4549 If WDESC is some other (smaller) window, we return 0. */
4551 struct frame *
4552 x_top_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
4554 Lisp_Object tail, frame;
4555 struct frame *f;
4556 struct x_output *x;
4558 if (wdesc == None)
4559 return NULL;
4561 FOR_EACH_FRAME (tail, frame)
4563 f = XFRAME (frame);
4564 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
4565 continue;
4566 x = f->output_data.x;
4568 if (x->widget)
4570 /* This frame matches if the window is its topmost widget. */
4571 #ifdef USE_GTK
4572 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
4573 if (gwdesc == x->widget)
4574 return f;
4575 #else
4576 if (wdesc == XtWindow (x->widget))
4577 return f;
4578 #endif
4580 else if (FRAME_X_WINDOW (f) == wdesc)
4581 /* Tooltip frame. */
4582 return f;
4584 return 0;
4587 #else /* !USE_X_TOOLKIT && !USE_GTK */
4589 #define x_any_window_to_frame(d, i) x_window_to_frame (d, i)
4590 #define x_top_window_to_frame(d, i) x_window_to_frame (d, i)
4592 #endif /* USE_X_TOOLKIT || USE_GTK */
4594 /* The focus may have changed. Figure out if it is a real focus change,
4595 by checking both FocusIn/Out and Enter/LeaveNotify events.
4597 Returns FOCUS_IN_EVENT event in *BUFP. */
4599 static void
4600 x_detect_focus_change (struct x_display_info *dpyinfo, struct frame *frame,
4601 const XEvent *event, struct input_event *bufp)
4603 if (!frame)
4604 return;
4606 switch (event->type)
4608 case EnterNotify:
4609 case LeaveNotify:
4611 struct frame *focus_frame = dpyinfo->x_focus_event_frame;
4612 int focus_state
4613 = focus_frame ? focus_frame->output_data.x->focus_state : 0;
4615 if (event->xcrossing.detail != NotifyInferior
4616 && event->xcrossing.focus
4617 && ! (focus_state & FOCUS_EXPLICIT))
4618 x_focus_changed ((event->type == EnterNotify ? FocusIn : FocusOut),
4619 FOCUS_IMPLICIT,
4620 dpyinfo, frame, bufp);
4622 break;
4624 case FocusIn:
4625 case FocusOut:
4626 x_focus_changed (event->type,
4627 (event->xfocus.detail == NotifyPointer ?
4628 FOCUS_IMPLICIT : FOCUS_EXPLICIT),
4629 dpyinfo, frame, bufp);
4630 break;
4632 case ClientMessage:
4633 if (event->xclient.message_type == dpyinfo->Xatom_XEMBED)
4635 enum xembed_message msg = event->xclient.data.l[1];
4636 x_focus_changed ((msg == XEMBED_FOCUS_IN ? FocusIn : FocusOut),
4637 FOCUS_EXPLICIT, dpyinfo, frame, bufp);
4639 break;
4644 #if !defined USE_X_TOOLKIT && !defined USE_GTK
4645 /* Handle an event saying the mouse has moved out of an Emacs frame. */
4647 void
4648 x_mouse_leave (struct x_display_info *dpyinfo)
4650 x_new_focus_frame (dpyinfo, dpyinfo->x_focus_event_frame);
4652 #endif
4654 /* The focus has changed, or we have redirected a frame's focus to
4655 another frame (this happens when a frame uses a surrogate
4656 mini-buffer frame). Shift the highlight as appropriate.
4658 The FRAME argument doesn't necessarily have anything to do with which
4659 frame is being highlighted or un-highlighted; we only use it to find
4660 the appropriate X display info. */
4662 static void
4663 XTframe_rehighlight (struct frame *frame)
4665 x_frame_rehighlight (FRAME_DISPLAY_INFO (frame));
4668 static void
4669 x_frame_rehighlight (struct x_display_info *dpyinfo)
4671 struct frame *old_highlight = dpyinfo->x_highlight_frame;
4673 if (dpyinfo->x_focus_frame)
4675 dpyinfo->x_highlight_frame
4676 = ((FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame)))
4677 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
4678 : dpyinfo->x_focus_frame);
4679 if (! FRAME_LIVE_P (dpyinfo->x_highlight_frame))
4681 fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
4682 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
4685 else
4686 dpyinfo->x_highlight_frame = 0;
4688 if (dpyinfo->x_highlight_frame != old_highlight)
4690 if (old_highlight)
4691 frame_unhighlight (old_highlight);
4692 if (dpyinfo->x_highlight_frame)
4693 frame_highlight (dpyinfo->x_highlight_frame);
4699 /* Keyboard processing - modifier keys, vendor-specific keysyms, etc. */
4701 /* Initialize mode_switch_bit and modifier_meaning. */
4702 static void
4703 x_find_modifier_meanings (struct x_display_info *dpyinfo)
4705 int min_code, max_code;
4706 KeySym *syms;
4707 int syms_per_code;
4708 XModifierKeymap *mods;
4710 dpyinfo->meta_mod_mask = 0;
4711 dpyinfo->shift_lock_mask = 0;
4712 dpyinfo->alt_mod_mask = 0;
4713 dpyinfo->super_mod_mask = 0;
4714 dpyinfo->hyper_mod_mask = 0;
4716 XDisplayKeycodes (dpyinfo->display, &min_code, &max_code);
4718 syms = XGetKeyboardMapping (dpyinfo->display,
4719 min_code, max_code - min_code + 1,
4720 &syms_per_code);
4721 mods = XGetModifierMapping (dpyinfo->display);
4723 /* Scan the modifier table to see which modifier bits the Meta and
4724 Alt keysyms are on. */
4726 int row, col; /* The row and column in the modifier table. */
4727 bool found_alt_or_meta;
4729 for (row = 3; row < 8; row++)
4731 found_alt_or_meta = false;
4732 for (col = 0; col < mods->max_keypermod; col++)
4734 KeyCode code = mods->modifiermap[(row * mods->max_keypermod) + col];
4736 /* Zeroes are used for filler. Skip them. */
4737 if (code == 0)
4738 continue;
4740 /* Are any of this keycode's keysyms a meta key? */
4742 int code_col;
4744 for (code_col = 0; code_col < syms_per_code; code_col++)
4746 int sym = syms[((code - min_code) * syms_per_code) + code_col];
4748 switch (sym)
4750 case XK_Meta_L:
4751 case XK_Meta_R:
4752 found_alt_or_meta = true;
4753 dpyinfo->meta_mod_mask |= (1 << row);
4754 break;
4756 case XK_Alt_L:
4757 case XK_Alt_R:
4758 found_alt_or_meta = true;
4759 dpyinfo->alt_mod_mask |= (1 << row);
4760 break;
4762 case XK_Hyper_L:
4763 case XK_Hyper_R:
4764 if (!found_alt_or_meta)
4765 dpyinfo->hyper_mod_mask |= (1 << row);
4766 code_col = syms_per_code;
4767 col = mods->max_keypermod;
4768 break;
4770 case XK_Super_L:
4771 case XK_Super_R:
4772 if (!found_alt_or_meta)
4773 dpyinfo->super_mod_mask |= (1 << row);
4774 code_col = syms_per_code;
4775 col = mods->max_keypermod;
4776 break;
4778 case XK_Shift_Lock:
4779 /* Ignore this if it's not on the lock modifier. */
4780 if (!found_alt_or_meta && ((1 << row) == LockMask))
4781 dpyinfo->shift_lock_mask = LockMask;
4782 code_col = syms_per_code;
4783 col = mods->max_keypermod;
4784 break;
4792 /* If we couldn't find any meta keys, accept any alt keys as meta keys. */
4793 if (! dpyinfo->meta_mod_mask)
4795 dpyinfo->meta_mod_mask = dpyinfo->alt_mod_mask;
4796 dpyinfo->alt_mod_mask = 0;
4799 /* If some keys are both alt and meta,
4800 make them just meta, not alt. */
4801 if (dpyinfo->alt_mod_mask & dpyinfo->meta_mod_mask)
4803 dpyinfo->alt_mod_mask &= ~dpyinfo->meta_mod_mask;
4806 XFree (syms);
4807 XFreeModifiermap (mods);
4810 /* Convert between the modifier bits X uses and the modifier bits
4811 Emacs uses. */
4814 x_x_to_emacs_modifiers (struct x_display_info *dpyinfo, int state)
4816 int mod_ctrl = ctrl_modifier;
4817 int mod_meta = meta_modifier;
4818 int mod_alt = alt_modifier;
4819 int mod_hyper = hyper_modifier;
4820 int mod_super = super_modifier;
4821 Lisp_Object tem;
4823 tem = Fget (Vx_ctrl_keysym, Qmodifier_value);
4824 if (INTEGERP (tem)) mod_ctrl = XINT (tem) & INT_MAX;
4825 tem = Fget (Vx_alt_keysym, Qmodifier_value);
4826 if (INTEGERP (tem)) mod_alt = XINT (tem) & INT_MAX;
4827 tem = Fget (Vx_meta_keysym, Qmodifier_value);
4828 if (INTEGERP (tem)) mod_meta = XINT (tem) & INT_MAX;
4829 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
4830 if (INTEGERP (tem)) mod_hyper = XINT (tem) & INT_MAX;
4831 tem = Fget (Vx_super_keysym, Qmodifier_value);
4832 if (INTEGERP (tem)) mod_super = XINT (tem) & INT_MAX;
4834 return ( ((state & (ShiftMask | dpyinfo->shift_lock_mask)) ? shift_modifier : 0)
4835 | ((state & ControlMask) ? mod_ctrl : 0)
4836 | ((state & dpyinfo->meta_mod_mask) ? mod_meta : 0)
4837 | ((state & dpyinfo->alt_mod_mask) ? mod_alt : 0)
4838 | ((state & dpyinfo->super_mod_mask) ? mod_super : 0)
4839 | ((state & dpyinfo->hyper_mod_mask) ? mod_hyper : 0));
4842 static int
4843 x_emacs_to_x_modifiers (struct x_display_info *dpyinfo, EMACS_INT state)
4845 EMACS_INT mod_ctrl = ctrl_modifier;
4846 EMACS_INT mod_meta = meta_modifier;
4847 EMACS_INT mod_alt = alt_modifier;
4848 EMACS_INT mod_hyper = hyper_modifier;
4849 EMACS_INT mod_super = super_modifier;
4851 Lisp_Object tem;
4853 tem = Fget (Vx_ctrl_keysym, Qmodifier_value);
4854 if (INTEGERP (tem)) mod_ctrl = XINT (tem);
4855 tem = Fget (Vx_alt_keysym, Qmodifier_value);
4856 if (INTEGERP (tem)) mod_alt = XINT (tem);
4857 tem = Fget (Vx_meta_keysym, Qmodifier_value);
4858 if (INTEGERP (tem)) mod_meta = XINT (tem);
4859 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
4860 if (INTEGERP (tem)) mod_hyper = XINT (tem);
4861 tem = Fget (Vx_super_keysym, Qmodifier_value);
4862 if (INTEGERP (tem)) mod_super = XINT (tem);
4865 return ( ((state & mod_alt) ? dpyinfo->alt_mod_mask : 0)
4866 | ((state & mod_super) ? dpyinfo->super_mod_mask : 0)
4867 | ((state & mod_hyper) ? dpyinfo->hyper_mod_mask : 0)
4868 | ((state & shift_modifier) ? ShiftMask : 0)
4869 | ((state & mod_ctrl) ? ControlMask : 0)
4870 | ((state & mod_meta) ? dpyinfo->meta_mod_mask : 0));
4873 /* Convert a keysym to its name. */
4875 char *
4876 x_get_keysym_name (int keysym)
4878 char *value;
4880 block_input ();
4881 value = XKeysymToString (keysym);
4882 unblock_input ();
4884 return value;
4887 /* Mouse clicks and mouse movement. Rah.
4889 Formerly, we used PointerMotionHintMask (in standard_event_mask)
4890 so that we would have to call XQueryPointer after each MotionNotify
4891 event to ask for another such event. However, this made mouse tracking
4892 slow, and there was a bug that made it eventually stop.
4894 Simply asking for MotionNotify all the time seems to work better.
4896 In order to avoid asking for motion events and then throwing most
4897 of them away or busy-polling the server for mouse positions, we ask
4898 the server for pointer motion hints. This means that we get only
4899 one event per group of mouse movements. "Groups" are delimited by
4900 other kinds of events (focus changes and button clicks, for
4901 example), or by XQueryPointer calls; when one of these happens, we
4902 get another MotionNotify event the next time the mouse moves. This
4903 is at least as efficient as getting motion events when mouse
4904 tracking is on, and I suspect only negligibly worse when tracking
4905 is off. */
4907 /* Prepare a mouse-event in *RESULT for placement in the input queue.
4909 If the event is a button press, then note that we have grabbed
4910 the mouse. */
4912 static Lisp_Object
4913 construct_mouse_click (struct input_event *result,
4914 const XButtonEvent *event,
4915 struct frame *f)
4917 /* Make the event type NO_EVENT; we'll change that when we decide
4918 otherwise. */
4919 result->kind = MOUSE_CLICK_EVENT;
4920 result->code = event->button - Button1;
4921 result->timestamp = event->time;
4922 result->modifiers = (x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO (f),
4923 event->state)
4924 | (event->type == ButtonRelease
4925 ? up_modifier
4926 : down_modifier));
4928 XSETINT (result->x, event->x);
4929 XSETINT (result->y, event->y);
4930 XSETFRAME (result->frame_or_window, f);
4931 result->arg = Qnil;
4932 return Qnil;
4935 /* Function to report a mouse movement to the mainstream Emacs code.
4936 The input handler calls this.
4938 We have received a mouse movement event, which is given in *event.
4939 If the mouse is over a different glyph than it was last time, tell
4940 the mainstream emacs code by setting mouse_moved. If not, ask for
4941 another motion event, so we can check again the next time it moves. */
4943 static bool
4944 note_mouse_movement (struct frame *frame, const XMotionEvent *event)
4946 XRectangle *r;
4947 struct x_display_info *dpyinfo;
4949 if (!FRAME_X_OUTPUT (frame))
4950 return false;
4952 dpyinfo = FRAME_DISPLAY_INFO (frame);
4953 dpyinfo->last_mouse_movement_time = event->time;
4954 dpyinfo->last_mouse_motion_frame = frame;
4955 dpyinfo->last_mouse_motion_x = event->x;
4956 dpyinfo->last_mouse_motion_y = event->y;
4958 if (event->window != FRAME_X_WINDOW (frame))
4960 frame->mouse_moved = true;
4961 dpyinfo->last_mouse_scroll_bar = NULL;
4962 note_mouse_highlight (frame, -1, -1);
4963 dpyinfo->last_mouse_glyph_frame = NULL;
4964 return true;
4968 /* Has the mouse moved off the glyph it was on at the last sighting? */
4969 r = &dpyinfo->last_mouse_glyph;
4970 if (frame != dpyinfo->last_mouse_glyph_frame
4971 || event->x < r->x || event->x >= r->x + r->width
4972 || event->y < r->y || event->y >= r->y + r->height)
4974 frame->mouse_moved = true;
4975 dpyinfo->last_mouse_scroll_bar = NULL;
4976 note_mouse_highlight (frame, event->x, event->y);
4977 /* Remember which glyph we're now on. */
4978 remember_mouse_glyph (frame, event->x, event->y, r);
4979 dpyinfo->last_mouse_glyph_frame = frame;
4980 return true;
4983 return false;
4986 /* Return the current position of the mouse.
4987 *FP should be a frame which indicates which display to ask about.
4989 If the mouse movement started in a scroll bar, set *FP, *BAR_WINDOW,
4990 and *PART to the frame, window, and scroll bar part that the mouse
4991 is over. Set *X and *Y to the portion and whole of the mouse's
4992 position on the scroll bar.
4994 If the mouse movement started elsewhere, set *FP to the frame the
4995 mouse is on, *BAR_WINDOW to nil, and *X and *Y to the character cell
4996 the mouse is over.
4998 Set *TIMESTAMP to the server time-stamp for the time at which the mouse
4999 was at this position.
5001 Don't store anything if we don't have a valid set of values to report.
5003 This clears the mouse_moved flag, so we can wait for the next mouse
5004 movement. */
5006 static void
5007 XTmouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
5008 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
5009 Time *timestamp)
5011 struct frame *f1;
5012 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (*fp);
5014 block_input ();
5016 if (dpyinfo->last_mouse_scroll_bar && insist == 0)
5018 struct scroll_bar *bar = dpyinfo->last_mouse_scroll_bar;
5020 if (bar->horizontal)
5021 x_horizontal_scroll_bar_report_motion (fp, bar_window, part, x, y, timestamp);
5022 else
5023 x_scroll_bar_report_motion (fp, bar_window, part, x, y, timestamp);
5025 else
5027 Window root;
5028 int root_x, root_y;
5030 Window dummy_window;
5031 int dummy;
5033 Lisp_Object frame, tail;
5035 /* Clear the mouse-moved flag for every frame on this display. */
5036 FOR_EACH_FRAME (tail, frame)
5037 if (FRAME_X_P (XFRAME (frame))
5038 && FRAME_X_DISPLAY (XFRAME (frame)) == FRAME_X_DISPLAY (*fp))
5039 XFRAME (frame)->mouse_moved = false;
5041 dpyinfo->last_mouse_scroll_bar = NULL;
5043 /* Figure out which root window we're on. */
5044 XQueryPointer (FRAME_X_DISPLAY (*fp),
5045 DefaultRootWindow (FRAME_X_DISPLAY (*fp)),
5047 /* The root window which contains the pointer. */
5048 &root,
5050 /* Trash which we can't trust if the pointer is on
5051 a different screen. */
5052 &dummy_window,
5054 /* The position on that root window. */
5055 &root_x, &root_y,
5057 /* More trash we can't trust. */
5058 &dummy, &dummy,
5060 /* Modifier keys and pointer buttons, about which
5061 we don't care. */
5062 (unsigned int *) &dummy);
5064 /* Now we have a position on the root; find the innermost window
5065 containing the pointer. */
5067 Window win, child;
5068 #ifdef USE_GTK
5069 Window first_win = 0;
5070 #endif
5071 int win_x, win_y;
5072 int parent_x = 0, parent_y = 0;
5074 win = root;
5076 /* XTranslateCoordinates can get errors if the window
5077 structure is changing at the same time this function
5078 is running. So at least we must not crash from them. */
5080 x_catch_errors (FRAME_X_DISPLAY (*fp));
5082 if (x_mouse_grabbed (dpyinfo))
5084 /* If mouse was grabbed on a frame, give coords for that frame
5085 even if the mouse is now outside it. */
5086 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
5088 /* From-window. */
5089 root,
5091 /* To-window. */
5092 FRAME_X_WINDOW (dpyinfo->last_mouse_frame),
5094 /* From-position, to-position. */
5095 root_x, root_y, &win_x, &win_y,
5097 /* Child of win. */
5098 &child);
5099 f1 = dpyinfo->last_mouse_frame;
5101 else
5103 while (true)
5105 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
5107 /* From-window, to-window. */
5108 root, win,
5110 /* From-position, to-position. */
5111 root_x, root_y, &win_x, &win_y,
5113 /* Child of win. */
5114 &child);
5116 if (child == None || child == win)
5118 #ifdef USE_GTK
5119 /* On GTK we have not inspected WIN yet. If it has
5120 a frame and that frame has a parent, use it. */
5121 struct frame *f = x_window_to_frame (dpyinfo, win);
5123 if (f && FRAME_PARENT_FRAME (f))
5124 first_win = win;
5125 #endif
5126 break;
5128 #ifdef USE_GTK
5129 /* We don't wan't to know the innermost window. We
5130 want the edit window. For non-Gtk+ the innermost
5131 window is the edit window. For Gtk+ it might not
5132 be. It might be the tool bar for example. */
5133 if (x_window_to_frame (dpyinfo, win))
5134 /* But don't hurry. We might find a child frame
5135 beneath. */
5136 first_win = win;
5137 #endif
5138 win = child;
5139 parent_x = win_x;
5140 parent_y = win_y;
5143 #ifdef USE_GTK
5144 if (first_win)
5145 win = first_win;
5146 #endif
5148 /* Now we know that:
5149 win is the innermost window containing the pointer
5150 (XTC says it has no child containing the pointer),
5151 win_x and win_y are the pointer's position in it
5152 (XTC did this the last time through), and
5153 parent_x and parent_y are the pointer's position in win's parent.
5154 (They are what win_x and win_y were when win was child.
5155 If win is the root window, it has no parent, and
5156 parent_{x,y} are invalid, but that's okay, because we'll
5157 never use them in that case.) */
5159 #ifdef USE_GTK
5160 /* We don't wan't to know the innermost window. We
5161 want the edit window. */
5162 f1 = x_window_to_frame (dpyinfo, win);
5163 #else
5164 /* Is win one of our frames? */
5165 f1 = x_any_window_to_frame (dpyinfo, win);
5166 #endif
5168 #ifdef USE_X_TOOLKIT
5169 /* If we end up with the menu bar window, say it's not
5170 on the frame. */
5171 if (f1 != NULL
5172 && f1->output_data.x->menubar_widget
5173 && win == XtWindow (f1->output_data.x->menubar_widget))
5174 f1 = NULL;
5175 #endif /* USE_X_TOOLKIT */
5178 if (x_had_errors_p (FRAME_X_DISPLAY (*fp)))
5179 f1 = 0;
5181 x_uncatch_errors_after_check ();
5183 /* If not, is it one of our scroll bars? */
5184 if (! f1)
5186 struct scroll_bar *bar;
5188 bar = x_window_to_scroll_bar (FRAME_X_DISPLAY (*fp), win, 2);
5190 if (bar)
5192 f1 = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5193 win_x = parent_x;
5194 win_y = parent_y;
5198 if (f1 == 0 && insist > 0)
5199 f1 = SELECTED_FRAME ();
5201 if (f1)
5203 /* Ok, we found a frame. Store all the values.
5204 last_mouse_glyph is a rectangle used to reduce the
5205 generation of mouse events. To not miss any motion
5206 events, we must divide the frame into rectangles of the
5207 size of the smallest character that could be displayed
5208 on it, i.e. into the same rectangles that matrices on
5209 the frame are divided into. */
5211 /* FIXME: what if F1 is not an X frame? */
5212 dpyinfo = FRAME_DISPLAY_INFO (f1);
5213 remember_mouse_glyph (f1, win_x, win_y, &dpyinfo->last_mouse_glyph);
5214 dpyinfo->last_mouse_glyph_frame = f1;
5216 *bar_window = Qnil;
5217 *part = 0;
5218 *fp = f1;
5219 XSETINT (*x, win_x);
5220 XSETINT (*y, win_y);
5221 *timestamp = dpyinfo->last_mouse_movement_time;
5226 unblock_input ();
5231 /***********************************************************************
5232 Scroll bars
5233 ***********************************************************************/
5235 /* Scroll bar support. */
5237 /* Given an X window ID and a DISPLAY, find the struct scroll_bar which
5238 manages it.
5239 This can be called in GC, so we have to make sure to strip off mark
5240 bits. */
5242 static struct scroll_bar *
5243 x_window_to_scroll_bar (Display *display, Window window_id, int type)
5245 Lisp_Object tail, frame;
5247 #if defined (USE_GTK) && defined (USE_TOOLKIT_SCROLL_BARS)
5248 window_id = (Window) xg_get_scroll_id_for_window (display, window_id);
5249 #endif /* USE_GTK && USE_TOOLKIT_SCROLL_BARS */
5251 FOR_EACH_FRAME (tail, frame)
5253 Lisp_Object bar, condemned;
5255 if (! FRAME_X_P (XFRAME (frame)))
5256 continue;
5258 /* Scan this frame's scroll bar list for a scroll bar with the
5259 right window ID. */
5260 condemned = FRAME_CONDEMNED_SCROLL_BARS (XFRAME (frame));
5261 for (bar = FRAME_SCROLL_BARS (XFRAME (frame));
5262 /* This trick allows us to search both the ordinary and
5263 condemned scroll bar lists with one loop. */
5264 ! NILP (bar) || (bar = condemned,
5265 condemned = Qnil,
5266 ! NILP (bar));
5267 bar = XSCROLL_BAR (bar)->next)
5268 if (XSCROLL_BAR (bar)->x_window == window_id
5269 && FRAME_X_DISPLAY (XFRAME (frame)) == display
5270 && (type = 2
5271 || (type == 1 && XSCROLL_BAR (bar)->horizontal)
5272 || (type == 0 && !XSCROLL_BAR (bar)->horizontal)))
5273 return XSCROLL_BAR (bar);
5276 return NULL;
5280 #if defined USE_LUCID
5282 /* Return the Lucid menu bar WINDOW is part of. Return null
5283 if WINDOW is not part of a menu bar. */
5285 static Widget
5286 x_window_to_menu_bar (Window window)
5288 Lisp_Object tail, frame;
5290 FOR_EACH_FRAME (tail, frame)
5291 if (FRAME_X_P (XFRAME (frame)))
5293 Widget menu_bar = XFRAME (frame)->output_data.x->menubar_widget;
5295 if (menu_bar && xlwmenu_window_p (menu_bar, window))
5296 return menu_bar;
5298 return NULL;
5301 #endif /* USE_LUCID */
5304 /************************************************************************
5305 Toolkit scroll bars
5306 ************************************************************************/
5308 #ifdef USE_TOOLKIT_SCROLL_BARS
5310 static void x_send_scroll_bar_event (Lisp_Object, enum scroll_bar_part,
5311 int, int, bool);
5313 /* Lisp window being scrolled. Set when starting to interact with
5314 a toolkit scroll bar, reset to nil when ending the interaction. */
5316 static Lisp_Object window_being_scrolled;
5318 /* Whether this is an Xaw with arrow-scrollbars. This should imply
5319 that movements of 1/20 of the screen size are mapped to up/down. */
5321 #ifndef USE_GTK
5322 /* Id of action hook installed for scroll bars. */
5324 static XtActionHookId action_hook_id;
5325 static XtActionHookId horizontal_action_hook_id;
5327 static Boolean xaw3d_arrow_scroll;
5329 /* Whether the drag scrolling maintains the mouse at the top of the
5330 thumb. If not, resizing the thumb needs to be done more carefully
5331 to avoid jerkiness. */
5333 static Boolean xaw3d_pick_top;
5335 /* Action hook installed via XtAppAddActionHook when toolkit scroll
5336 bars are used.. The hook is responsible for detecting when
5337 the user ends an interaction with the scroll bar, and generates
5338 a `end-scroll' SCROLL_BAR_CLICK_EVENT' event if so. */
5340 static void
5341 xt_action_hook (Widget widget, XtPointer client_data, String action_name,
5342 XEvent *event, String *params, Cardinal *num_params)
5344 bool scroll_bar_p;
5345 const char *end_action;
5347 #ifdef USE_MOTIF
5348 scroll_bar_p = XmIsScrollBar (widget);
5349 end_action = "Release";
5350 #else /* !USE_MOTIF i.e. use Xaw */
5351 scroll_bar_p = XtIsSubclass (widget, scrollbarWidgetClass);
5352 end_action = "EndScroll";
5353 #endif /* USE_MOTIF */
5355 if (scroll_bar_p
5356 && strcmp (action_name, end_action) == 0
5357 && WINDOWP (window_being_scrolled))
5359 struct window *w;
5360 struct scroll_bar *bar;
5362 x_send_scroll_bar_event (window_being_scrolled,
5363 scroll_bar_end_scroll, 0, 0, false);
5364 w = XWINDOW (window_being_scrolled);
5365 bar = XSCROLL_BAR (w->vertical_scroll_bar);
5367 if (bar->dragging != -1)
5369 bar->dragging = -1;
5370 /* The thumb size is incorrect while dragging: fix it. */
5371 set_vertical_scroll_bar (w);
5373 window_being_scrolled = Qnil;
5374 #if defined (USE_LUCID)
5375 bar->last_seen_part = scroll_bar_nowhere;
5376 #endif
5377 /* Xt timeouts no longer needed. */
5378 toolkit_scroll_bar_interaction = false;
5383 static void
5384 xt_horizontal_action_hook (Widget widget, XtPointer client_data, String action_name,
5385 XEvent *event, String *params, Cardinal *num_params)
5387 bool scroll_bar_p;
5388 const char *end_action;
5390 #ifdef USE_MOTIF
5391 scroll_bar_p = XmIsScrollBar (widget);
5392 end_action = "Release";
5393 #else /* !USE_MOTIF i.e. use Xaw */
5394 scroll_bar_p = XtIsSubclass (widget, scrollbarWidgetClass);
5395 end_action = "EndScroll";
5396 #endif /* USE_MOTIF */
5398 if (scroll_bar_p
5399 && strcmp (action_name, end_action) == 0
5400 && WINDOWP (window_being_scrolled))
5402 struct window *w;
5403 struct scroll_bar *bar;
5405 x_send_scroll_bar_event (window_being_scrolled,
5406 scroll_bar_end_scroll, 0, 0, true);
5407 w = XWINDOW (window_being_scrolled);
5408 if (!NILP (w->horizontal_scroll_bar))
5410 bar = XSCROLL_BAR (w->horizontal_scroll_bar);
5411 if (bar->dragging != -1)
5413 bar->dragging = -1;
5414 /* The thumb size is incorrect while dragging: fix it. */
5415 set_horizontal_scroll_bar (w);
5417 window_being_scrolled = Qnil;
5418 #if defined (USE_LUCID)
5419 bar->last_seen_part = scroll_bar_nowhere;
5420 #endif
5421 /* Xt timeouts no longer needed. */
5422 toolkit_scroll_bar_interaction = false;
5426 #endif /* not USE_GTK */
5428 /* Send a client message with message type Xatom_Scrollbar for a
5429 scroll action to the frame of WINDOW. PART is a value identifying
5430 the part of the scroll bar that was clicked on. PORTION is the
5431 amount to scroll of a whole of WHOLE. */
5433 static void
5434 x_send_scroll_bar_event (Lisp_Object window, enum scroll_bar_part part,
5435 int portion, int whole, bool horizontal)
5437 XEvent event;
5438 XClientMessageEvent *ev = &event.xclient;
5439 struct window *w = XWINDOW (window);
5440 struct frame *f = XFRAME (w->frame);
5441 intptr_t iw = (intptr_t) w;
5442 verify (INTPTR_WIDTH <= 64);
5443 int sign_shift = INTPTR_WIDTH - 32;
5445 block_input ();
5447 /* Construct a ClientMessage event to send to the frame. */
5448 ev->type = ClientMessage;
5449 ev->message_type = (horizontal
5450 ? FRAME_DISPLAY_INFO (f)->Xatom_Horizontal_Scrollbar
5451 : FRAME_DISPLAY_INFO (f)->Xatom_Scrollbar);
5452 ev->display = FRAME_X_DISPLAY (f);
5453 ev->window = FRAME_X_WINDOW (f);
5454 ev->format = 32;
5456 /* A 32-bit X client on a 64-bit X server can pass a window pointer
5457 as-is. A 64-bit client on a 32-bit X server is in trouble
5458 because a pointer does not fit and would be truncated while
5459 passing through the server. So use two slots and hope that X12
5460 will resolve such issues someday. */
5461 ev->data.l[0] = iw >> 31 >> 1;
5462 ev->data.l[1] = sign_shift <= 0 ? iw : iw << sign_shift >> sign_shift;
5463 ev->data.l[2] = part;
5464 ev->data.l[3] = portion;
5465 ev->data.l[4] = whole;
5467 /* Make Xt timeouts work while the scroll bar is active. */
5468 #ifdef USE_X_TOOLKIT
5469 toolkit_scroll_bar_interaction = true;
5470 x_activate_timeout_atimer ();
5471 #endif
5473 /* Setting the event mask to zero means that the message will
5474 be sent to the client that created the window, and if that
5475 window no longer exists, no event will be sent. */
5476 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), False, 0, &event);
5477 unblock_input ();
5481 /* Transform a scroll bar ClientMessage EVENT to an Emacs input event
5482 in *IEVENT. */
5484 static void
5485 x_scroll_bar_to_input_event (const XEvent *event,
5486 struct input_event *ievent)
5488 const XClientMessageEvent *ev = &event->xclient;
5489 Lisp_Object window;
5490 struct window *w;
5492 /* See the comment in the function above. */
5493 intptr_t iw0 = ev->data.l[0];
5494 intptr_t iw1 = ev->data.l[1];
5495 intptr_t iw = (iw0 << 31 << 1) + (iw1 & 0xffffffffu);
5496 w = (struct window *) iw;
5498 XSETWINDOW (window, w);
5500 ievent->kind = SCROLL_BAR_CLICK_EVENT;
5501 ievent->frame_or_window = window;
5502 ievent->arg = Qnil;
5503 #ifdef USE_GTK
5504 ievent->timestamp = CurrentTime;
5505 #else
5506 ievent->timestamp =
5507 XtLastTimestampProcessed (FRAME_X_DISPLAY (XFRAME (w->frame)));
5508 #endif
5509 ievent->code = 0;
5510 ievent->part = ev->data.l[2];
5511 ievent->x = make_number (ev->data.l[3]);
5512 ievent->y = make_number (ev->data.l[4]);
5513 ievent->modifiers = 0;
5516 /* Transform a horizontal scroll bar ClientMessage EVENT to an Emacs
5517 input event in *IEVENT. */
5519 static void
5520 x_horizontal_scroll_bar_to_input_event (const XEvent *event,
5521 struct input_event *ievent)
5523 const XClientMessageEvent *ev = &event->xclient;
5524 Lisp_Object window;
5525 struct window *w;
5527 /* See the comment in the function above. */
5528 intptr_t iw0 = ev->data.l[0];
5529 intptr_t iw1 = ev->data.l[1];
5530 intptr_t iw = (iw0 << 31 << 1) + (iw1 & 0xffffffffu);
5531 w = (struct window *) iw;
5533 XSETWINDOW (window, w);
5535 ievent->kind = HORIZONTAL_SCROLL_BAR_CLICK_EVENT;
5536 ievent->frame_or_window = window;
5537 ievent->arg = Qnil;
5538 #ifdef USE_GTK
5539 ievent->timestamp = CurrentTime;
5540 #else
5541 ievent->timestamp =
5542 XtLastTimestampProcessed (FRAME_X_DISPLAY (XFRAME (w->frame)));
5543 #endif
5544 ievent->code = 0;
5545 ievent->part = ev->data.l[2];
5546 ievent->x = make_number (ev->data.l[3]);
5547 ievent->y = make_number (ev->data.l[4]);
5548 ievent->modifiers = 0;
5552 #ifdef USE_MOTIF
5554 /* Minimum and maximum values used for Motif scroll bars. */
5556 #define XM_SB_MAX 10000000
5558 /* Scroll bar callback for Motif scroll bars. WIDGET is the scroll
5559 bar widget. CLIENT_DATA is a pointer to the scroll_bar structure.
5560 CALL_DATA is a pointer to a XmScrollBarCallbackStruct. */
5562 static void
5563 xm_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
5565 struct scroll_bar *bar = client_data;
5566 XmScrollBarCallbackStruct *cs = call_data;
5567 enum scroll_bar_part part = scroll_bar_nowhere;
5568 bool horizontal = bar->horizontal;
5569 int whole = 0, portion = 0;
5571 switch (cs->reason)
5573 case XmCR_DECREMENT:
5574 bar->dragging = -1;
5575 part = horizontal ? scroll_bar_left_arrow : scroll_bar_up_arrow;
5576 break;
5578 case XmCR_INCREMENT:
5579 bar->dragging = -1;
5580 part = horizontal ? scroll_bar_right_arrow : scroll_bar_down_arrow;
5581 break;
5583 case XmCR_PAGE_DECREMENT:
5584 bar->dragging = -1;
5585 part = horizontal ? scroll_bar_before_handle : scroll_bar_above_handle;
5586 break;
5588 case XmCR_PAGE_INCREMENT:
5589 bar->dragging = -1;
5590 part = horizontal ? scroll_bar_after_handle : scroll_bar_below_handle;
5591 break;
5593 case XmCR_TO_TOP:
5594 bar->dragging = -1;
5595 part = horizontal ? scroll_bar_to_leftmost : scroll_bar_to_top;
5596 break;
5598 case XmCR_TO_BOTTOM:
5599 bar->dragging = -1;
5600 part = horizontal ? scroll_bar_to_rightmost : scroll_bar_to_bottom;
5601 break;
5603 case XmCR_DRAG:
5605 int slider_size;
5607 block_input ();
5608 XtVaGetValues (widget, XmNsliderSize, &slider_size, NULL);
5609 unblock_input ();
5611 if (horizontal)
5613 portion = bar->whole * ((float)cs->value / XM_SB_MAX);
5614 whole = bar->whole * ((float)(XM_SB_MAX - slider_size) / XM_SB_MAX);
5615 portion = min (portion, whole);
5616 part = scroll_bar_horizontal_handle;
5618 else
5620 whole = XM_SB_MAX - slider_size;
5621 portion = min (cs->value, whole);
5622 part = scroll_bar_handle;
5625 bar->dragging = cs->value;
5627 break;
5629 case XmCR_VALUE_CHANGED:
5630 break;
5633 if (part != scroll_bar_nowhere)
5635 window_being_scrolled = bar->window;
5636 x_send_scroll_bar_event (bar->window, part, portion, whole,
5637 bar->horizontal);
5641 #elif defined USE_GTK
5643 /* Scroll bar callback for GTK scroll bars. WIDGET is the scroll
5644 bar widget. DATA is a pointer to the scroll_bar structure. */
5646 static gboolean
5647 xg_scroll_callback (GtkRange *range,
5648 GtkScrollType scroll,
5649 gdouble value,
5650 gpointer user_data)
5652 int whole = 0, portion = 0;
5653 struct scroll_bar *bar = user_data;
5654 enum scroll_bar_part part = scroll_bar_nowhere;
5655 GtkAdjustment *adj = GTK_ADJUSTMENT (gtk_range_get_adjustment (range));
5656 struct frame *f = g_object_get_data (G_OBJECT (range), XG_FRAME_DATA);
5658 if (xg_ignore_gtk_scrollbar) return false;
5660 switch (scroll)
5662 case GTK_SCROLL_JUMP:
5663 /* Buttons 1 2 or 3 must be grabbed. */
5664 if (FRAME_DISPLAY_INFO (f)->grabbed != 0
5665 && FRAME_DISPLAY_INFO (f)->grabbed < (1 << 4))
5667 if (bar->horizontal)
5669 part = scroll_bar_horizontal_handle;
5670 whole = (int)(gtk_adjustment_get_upper (adj) -
5671 gtk_adjustment_get_page_size (adj));
5672 portion = min ((int)value, whole);
5673 bar->dragging = portion;
5675 else
5677 part = scroll_bar_handle;
5678 whole = gtk_adjustment_get_upper (adj) -
5679 gtk_adjustment_get_page_size (adj);
5680 portion = min ((int)value, whole);
5681 bar->dragging = portion;
5684 break;
5685 case GTK_SCROLL_STEP_BACKWARD:
5686 part = (bar->horizontal
5687 ? scroll_bar_left_arrow : scroll_bar_up_arrow);
5688 bar->dragging = -1;
5689 break;
5690 case GTK_SCROLL_STEP_FORWARD:
5691 part = (bar->horizontal
5692 ? scroll_bar_right_arrow : scroll_bar_down_arrow);
5693 bar->dragging = -1;
5694 break;
5695 case GTK_SCROLL_PAGE_BACKWARD:
5696 part = (bar->horizontal
5697 ? scroll_bar_before_handle : scroll_bar_above_handle);
5698 bar->dragging = -1;
5699 break;
5700 case GTK_SCROLL_PAGE_FORWARD:
5701 part = (bar->horizontal
5702 ? scroll_bar_after_handle : scroll_bar_below_handle);
5703 bar->dragging = -1;
5704 break;
5705 default:
5706 break;
5709 if (part != scroll_bar_nowhere)
5711 window_being_scrolled = bar->window;
5712 x_send_scroll_bar_event (bar->window, part, portion, whole,
5713 bar->horizontal);
5716 return false;
5719 /* Callback for button release. Sets dragging to -1 when dragging is done. */
5721 static gboolean
5722 xg_end_scroll_callback (GtkWidget *widget,
5723 GdkEventButton *event,
5724 gpointer user_data)
5726 struct scroll_bar *bar = user_data;
5727 bar->dragging = -1;
5728 if (WINDOWP (window_being_scrolled))
5730 x_send_scroll_bar_event (window_being_scrolled,
5731 scroll_bar_end_scroll, 0, 0, bar->horizontal);
5732 window_being_scrolled = Qnil;
5735 return false;
5739 #else /* not USE_GTK and not USE_MOTIF */
5741 /* Xaw scroll bar callback. Invoked when the thumb is dragged.
5742 WIDGET is the scroll bar widget. CLIENT_DATA is a pointer to the
5743 scroll bar struct. CALL_DATA is a pointer to a float saying where
5744 the thumb is. */
5746 static void
5747 xaw_jump_callback (Widget widget, XtPointer client_data, XtPointer call_data)
5749 struct scroll_bar *bar = client_data;
5750 float *top_addr = call_data;
5751 float top = *top_addr;
5752 float shown;
5753 int whole, portion, height, width;
5754 enum scroll_bar_part part;
5755 bool horizontal = bar->horizontal;
5757 if (horizontal)
5759 /* Get the size of the thumb, a value between 0 and 1. */
5760 block_input ();
5761 XtVaGetValues (widget, XtNshown, &shown, XtNwidth, &width, NULL);
5762 unblock_input ();
5764 if (shown < 1)
5766 whole = bar->whole - (shown * bar->whole);
5767 portion = min (top * bar->whole, whole);
5769 else
5771 whole = bar->whole;
5772 portion = 0;
5775 part = scroll_bar_horizontal_handle;
5777 else
5779 /* Get the size of the thumb, a value between 0 and 1. */
5780 block_input ();
5781 XtVaGetValues (widget, XtNshown, &shown, XtNheight, &height, NULL);
5782 unblock_input ();
5784 whole = 10000000;
5785 portion = shown < 1 ? top * whole : 0;
5787 if (shown < 1 && (eabs (top + shown - 1) < 1.0f / height))
5788 /* Some derivatives of Xaw refuse to shrink the thumb when you reach
5789 the bottom, so we force the scrolling whenever we see that we're
5790 too close to the bottom (in x_set_toolkit_scroll_bar_thumb
5791 we try to ensure that we always stay two pixels away from the
5792 bottom). */
5793 part = scroll_bar_down_arrow;
5794 else
5795 part = scroll_bar_handle;
5798 window_being_scrolled = bar->window;
5799 bar->dragging = portion;
5800 bar->last_seen_part = part;
5801 x_send_scroll_bar_event (bar->window, part, portion, whole, bar->horizontal);
5805 /* Xaw scroll bar callback. Invoked for incremental scrolling.,
5806 i.e. line or page up or down. WIDGET is the Xaw scroll bar
5807 widget. CLIENT_DATA is a pointer to the scroll_bar structure for
5808 the scroll bar. CALL_DATA is an integer specifying the action that
5809 has taken place. Its magnitude is in the range 0..height of the
5810 scroll bar. Negative values mean scroll towards buffer start.
5811 Values < height of scroll bar mean line-wise movement. */
5813 static void
5814 xaw_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
5816 struct scroll_bar *bar = client_data;
5817 /* The position really is stored cast to a pointer. */
5818 int position = (intptr_t) call_data;
5819 Dimension height, width;
5820 enum scroll_bar_part part;
5822 if (bar->horizontal)
5824 /* Get the width of the scroll bar. */
5825 block_input ();
5826 XtVaGetValues (widget, XtNwidth, &width, NULL);
5827 unblock_input ();
5829 if (eabs (position) >= width)
5830 part = (position < 0) ? scroll_bar_before_handle : scroll_bar_after_handle;
5832 /* If Xaw3d was compiled with ARROW_SCROLLBAR,
5833 it maps line-movement to call_data = max(5, height/20). */
5834 else if (xaw3d_arrow_scroll && eabs (position) <= max (5, width / 20))
5835 part = (position < 0) ? scroll_bar_left_arrow : scroll_bar_right_arrow;
5836 else
5837 part = scroll_bar_move_ratio;
5839 window_being_scrolled = bar->window;
5840 bar->dragging = -1;
5841 bar->last_seen_part = part;
5842 x_send_scroll_bar_event (bar->window, part, position, width,
5843 bar->horizontal);
5845 else
5848 /* Get the height of the scroll bar. */
5849 block_input ();
5850 XtVaGetValues (widget, XtNheight, &height, NULL);
5851 unblock_input ();
5853 if (eabs (position) >= height)
5854 part = (position < 0) ? scroll_bar_above_handle : scroll_bar_below_handle;
5856 /* If Xaw3d was compiled with ARROW_SCROLLBAR,
5857 it maps line-movement to call_data = max(5, height/20). */
5858 else if (xaw3d_arrow_scroll && eabs (position) <= max (5, height / 20))
5859 part = (position < 0) ? scroll_bar_up_arrow : scroll_bar_down_arrow;
5860 else
5861 part = scroll_bar_move_ratio;
5863 window_being_scrolled = bar->window;
5864 bar->dragging = -1;
5865 bar->last_seen_part = part;
5866 x_send_scroll_bar_event (bar->window, part, position, height,
5867 bar->horizontal);
5871 #endif /* not USE_GTK and not USE_MOTIF */
5873 #define SCROLL_BAR_NAME "verticalScrollBar"
5874 #define SCROLL_BAR_HORIZONTAL_NAME "horizontalScrollBar"
5876 /* Create the widget for scroll bar BAR on frame F. Record the widget
5877 and X window of the scroll bar in BAR. */
5879 #ifdef USE_GTK
5880 static void
5881 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
5883 const char *scroll_bar_name = SCROLL_BAR_NAME;
5885 block_input ();
5886 xg_create_scroll_bar (f, bar, G_CALLBACK (xg_scroll_callback),
5887 G_CALLBACK (xg_end_scroll_callback),
5888 scroll_bar_name);
5889 unblock_input ();
5892 static void
5893 x_create_horizontal_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
5895 const char *scroll_bar_name = SCROLL_BAR_HORIZONTAL_NAME;
5897 block_input ();
5898 xg_create_horizontal_scroll_bar (f, bar, G_CALLBACK (xg_scroll_callback),
5899 G_CALLBACK (xg_end_scroll_callback),
5900 scroll_bar_name);
5901 unblock_input ();
5904 #else /* not USE_GTK */
5906 static void
5907 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
5909 Window xwindow;
5910 Widget widget;
5911 Arg av[20];
5912 int ac = 0;
5913 const char *scroll_bar_name = SCROLL_BAR_NAME;
5914 unsigned long pixel;
5916 block_input ();
5918 #ifdef USE_MOTIF
5919 /* Set resources. Create the widget. */
5920 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
5921 XtSetArg (av[ac], XmNminimum, 0); ++ac;
5922 XtSetArg (av[ac], XmNmaximum, XM_SB_MAX); ++ac;
5923 XtSetArg (av[ac], XmNorientation, XmVERTICAL); ++ac;
5924 XtSetArg (av[ac], XmNprocessingDirection, XmMAX_ON_BOTTOM), ++ac;
5925 XtSetArg (av[ac], XmNincrement, 1); ++ac;
5926 XtSetArg (av[ac], XmNpageIncrement, 1); ++ac;
5928 pixel = f->output_data.x->scroll_bar_foreground_pixel;
5929 if (pixel != -1)
5931 XtSetArg (av[ac], XmNforeground, pixel);
5932 ++ac;
5935 pixel = f->output_data.x->scroll_bar_background_pixel;
5936 if (pixel != -1)
5938 XtSetArg (av[ac], XmNbackground, pixel);
5939 ++ac;
5942 widget = XmCreateScrollBar (f->output_data.x->edit_widget,
5943 (char *) scroll_bar_name, av, ac);
5945 /* Add one callback for everything that can happen. */
5946 XtAddCallback (widget, XmNdecrementCallback, xm_scroll_callback,
5947 (XtPointer) bar);
5948 XtAddCallback (widget, XmNdragCallback, xm_scroll_callback,
5949 (XtPointer) bar);
5950 XtAddCallback (widget, XmNincrementCallback, xm_scroll_callback,
5951 (XtPointer) bar);
5952 XtAddCallback (widget, XmNpageDecrementCallback, xm_scroll_callback,
5953 (XtPointer) bar);
5954 XtAddCallback (widget, XmNpageIncrementCallback, xm_scroll_callback,
5955 (XtPointer) bar);
5956 XtAddCallback (widget, XmNtoBottomCallback, xm_scroll_callback,
5957 (XtPointer) bar);
5958 XtAddCallback (widget, XmNtoTopCallback, xm_scroll_callback,
5959 (XtPointer) bar);
5961 /* Realize the widget. Only after that is the X window created. */
5962 XtRealizeWidget (widget);
5964 /* Set the cursor to an arrow. I didn't find a resource to do that.
5965 And I'm wondering why it hasn't an arrow cursor by default. */
5966 XDefineCursor (XtDisplay (widget), XtWindow (widget),
5967 f->output_data.x->nontext_cursor);
5969 #else /* !USE_MOTIF i.e. use Xaw */
5971 /* Set resources. Create the widget. The background of the
5972 Xaw3d scroll bar widget is a little bit light for my taste.
5973 We don't alter it here to let users change it according
5974 to their taste with `emacs*verticalScrollBar.background: xxx'. */
5975 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
5976 XtSetArg (av[ac], XtNorientation, XtorientVertical); ++ac;
5977 /* For smoother scrolling with Xaw3d -sm */
5978 /* XtSetArg (av[ac], XtNpickTop, True); ++ac; */
5980 pixel = f->output_data.x->scroll_bar_foreground_pixel;
5981 if (pixel != -1)
5983 XtSetArg (av[ac], XtNforeground, pixel);
5984 ++ac;
5987 pixel = f->output_data.x->scroll_bar_background_pixel;
5988 if (pixel != -1)
5990 XtSetArg (av[ac], XtNbackground, pixel);
5991 ++ac;
5994 /* Top/bottom shadow colors. */
5996 /* Allocate them, if necessary. */
5997 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1)
5999 pixel = f->output_data.x->scroll_bar_background_pixel;
6000 if (pixel != -1)
6002 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
6003 FRAME_X_COLORMAP (f),
6004 &pixel, 1.2, 0x8000))
6005 pixel = -1;
6006 f->output_data.x->scroll_bar_top_shadow_pixel = pixel;
6009 if (f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
6011 pixel = f->output_data.x->scroll_bar_background_pixel;
6012 if (pixel != -1)
6014 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
6015 FRAME_X_COLORMAP (f),
6016 &pixel, 0.6, 0x4000))
6017 pixel = -1;
6018 f->output_data.x->scroll_bar_bottom_shadow_pixel = pixel;
6022 #ifdef XtNbeNiceToColormap
6023 /* Tell the toolkit about them. */
6024 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1
6025 || f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
6026 /* We tried to allocate a color for the top/bottom shadow, and
6027 failed, so tell Xaw3d to use dithering instead. */
6028 /* But only if we have a small colormap. Xaw3d can allocate nice
6029 colors itself. */
6031 XtSetArg (av[ac], XtNbeNiceToColormap,
6032 DefaultDepthOfScreen (FRAME_X_SCREEN (f)) < 16);
6033 ++ac;
6035 else
6036 /* Tell what colors Xaw3d should use for the top/bottom shadow, to
6037 be more consistent with other emacs 3d colors, and since Xaw3d is
6038 not good at dealing with allocation failure. */
6040 /* This tells Xaw3d to use real colors instead of dithering for
6041 the shadows. */
6042 XtSetArg (av[ac], XtNbeNiceToColormap, False);
6043 ++ac;
6045 /* Specify the colors. */
6046 pixel = f->output_data.x->scroll_bar_top_shadow_pixel;
6047 if (pixel != -1)
6049 XtSetArg (av[ac], XtNtopShadowPixel, pixel);
6050 ++ac;
6052 pixel = f->output_data.x->scroll_bar_bottom_shadow_pixel;
6053 if (pixel != -1)
6055 XtSetArg (av[ac], XtNbottomShadowPixel, pixel);
6056 ++ac;
6059 #endif
6061 widget = XtCreateWidget (scroll_bar_name, scrollbarWidgetClass,
6062 f->output_data.x->edit_widget, av, ac);
6065 char const *initial = "";
6066 char const *val = initial;
6067 XtVaGetValues (widget, XtNscrollVCursor, (XtPointer) &val,
6068 #ifdef XtNarrowScrollbars
6069 XtNarrowScrollbars, (XtPointer) &xaw3d_arrow_scroll,
6070 #endif
6071 XtNpickTop, (XtPointer) &xaw3d_pick_top, NULL);
6072 if (xaw3d_arrow_scroll || val == initial)
6073 { /* ARROW_SCROLL */
6074 xaw3d_arrow_scroll = True;
6075 /* Isn't that just a personal preference ? --Stef */
6076 XtVaSetValues (widget, XtNcursorName, "top_left_arrow", NULL);
6080 /* Define callbacks. */
6081 XtAddCallback (widget, XtNjumpProc, xaw_jump_callback, (XtPointer) bar);
6082 XtAddCallback (widget, XtNscrollProc, xaw_scroll_callback,
6083 (XtPointer) bar);
6085 /* Realize the widget. Only after that is the X window created. */
6086 XtRealizeWidget (widget);
6088 #endif /* !USE_MOTIF */
6090 /* Install an action hook that lets us detect when the user
6091 finishes interacting with a scroll bar. */
6092 if (action_hook_id == 0)
6093 action_hook_id = XtAppAddActionHook (Xt_app_con, xt_action_hook, 0);
6095 /* Remember X window and widget in the scroll bar vector. */
6096 SET_SCROLL_BAR_X_WIDGET (bar, widget);
6097 xwindow = XtWindow (widget);
6098 bar->x_window = xwindow;
6099 bar->whole = 1;
6100 bar->horizontal = false;
6102 unblock_input ();
6105 static void
6106 x_create_horizontal_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
6108 Window xwindow;
6109 Widget widget;
6110 Arg av[20];
6111 int ac = 0;
6112 const char *scroll_bar_name = SCROLL_BAR_HORIZONTAL_NAME;
6113 unsigned long pixel;
6115 block_input ();
6117 #ifdef USE_MOTIF
6118 /* Set resources. Create the widget. */
6119 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
6120 XtSetArg (av[ac], XmNminimum, 0); ++ac;
6121 XtSetArg (av[ac], XmNmaximum, XM_SB_MAX); ++ac;
6122 XtSetArg (av[ac], XmNorientation, XmHORIZONTAL); ++ac;
6123 XtSetArg (av[ac], XmNprocessingDirection, XmMAX_ON_RIGHT), ++ac;
6124 XtSetArg (av[ac], XmNincrement, 1); ++ac;
6125 XtSetArg (av[ac], XmNpageIncrement, 1); ++ac;
6127 pixel = f->output_data.x->scroll_bar_foreground_pixel;
6128 if (pixel != -1)
6130 XtSetArg (av[ac], XmNforeground, pixel);
6131 ++ac;
6134 pixel = f->output_data.x->scroll_bar_background_pixel;
6135 if (pixel != -1)
6137 XtSetArg (av[ac], XmNbackground, pixel);
6138 ++ac;
6141 widget = XmCreateScrollBar (f->output_data.x->edit_widget,
6142 (char *) scroll_bar_name, av, ac);
6144 /* Add one callback for everything that can happen. */
6145 XtAddCallback (widget, XmNdecrementCallback, xm_scroll_callback,
6146 (XtPointer) bar);
6147 XtAddCallback (widget, XmNdragCallback, xm_scroll_callback,
6148 (XtPointer) bar);
6149 XtAddCallback (widget, XmNincrementCallback, xm_scroll_callback,
6150 (XtPointer) bar);
6151 XtAddCallback (widget, XmNpageDecrementCallback, xm_scroll_callback,
6152 (XtPointer) bar);
6153 XtAddCallback (widget, XmNpageIncrementCallback, xm_scroll_callback,
6154 (XtPointer) bar);
6155 XtAddCallback (widget, XmNtoBottomCallback, xm_scroll_callback,
6156 (XtPointer) bar);
6157 XtAddCallback (widget, XmNtoTopCallback, xm_scroll_callback,
6158 (XtPointer) bar);
6160 /* Realize the widget. Only after that is the X window created. */
6161 XtRealizeWidget (widget);
6163 /* Set the cursor to an arrow. I didn't find a resource to do that.
6164 And I'm wondering why it hasn't an arrow cursor by default. */
6165 XDefineCursor (XtDisplay (widget), XtWindow (widget),
6166 f->output_data.x->nontext_cursor);
6168 #else /* !USE_MOTIF i.e. use Xaw */
6170 /* Set resources. Create the widget. The background of the
6171 Xaw3d scroll bar widget is a little bit light for my taste.
6172 We don't alter it here to let users change it according
6173 to their taste with `emacs*verticalScrollBar.background: xxx'. */
6174 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
6175 XtSetArg (av[ac], XtNorientation, XtorientHorizontal); ++ac;
6176 /* For smoother scrolling with Xaw3d -sm */
6177 /* XtSetArg (av[ac], XtNpickTop, True); ++ac; */
6179 pixel = f->output_data.x->scroll_bar_foreground_pixel;
6180 if (pixel != -1)
6182 XtSetArg (av[ac], XtNforeground, pixel);
6183 ++ac;
6186 pixel = f->output_data.x->scroll_bar_background_pixel;
6187 if (pixel != -1)
6189 XtSetArg (av[ac], XtNbackground, pixel);
6190 ++ac;
6193 /* Top/bottom shadow colors. */
6195 /* Allocate them, if necessary. */
6196 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1)
6198 pixel = f->output_data.x->scroll_bar_background_pixel;
6199 if (pixel != -1)
6201 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
6202 FRAME_X_COLORMAP (f),
6203 &pixel, 1.2, 0x8000))
6204 pixel = -1;
6205 f->output_data.x->scroll_bar_top_shadow_pixel = pixel;
6208 if (f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
6210 pixel = f->output_data.x->scroll_bar_background_pixel;
6211 if (pixel != -1)
6213 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
6214 FRAME_X_COLORMAP (f),
6215 &pixel, 0.6, 0x4000))
6216 pixel = -1;
6217 f->output_data.x->scroll_bar_bottom_shadow_pixel = pixel;
6221 #ifdef XtNbeNiceToColormap
6222 /* Tell the toolkit about them. */
6223 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1
6224 || f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
6225 /* We tried to allocate a color for the top/bottom shadow, and
6226 failed, so tell Xaw3d to use dithering instead. */
6227 /* But only if we have a small colormap. Xaw3d can allocate nice
6228 colors itself. */
6230 XtSetArg (av[ac], XtNbeNiceToColormap,
6231 DefaultDepthOfScreen (FRAME_X_SCREEN (f)) < 16);
6232 ++ac;
6234 else
6235 /* Tell what colors Xaw3d should use for the top/bottom shadow, to
6236 be more consistent with other emacs 3d colors, and since Xaw3d is
6237 not good at dealing with allocation failure. */
6239 /* This tells Xaw3d to use real colors instead of dithering for
6240 the shadows. */
6241 XtSetArg (av[ac], XtNbeNiceToColormap, False);
6242 ++ac;
6244 /* Specify the colors. */
6245 pixel = f->output_data.x->scroll_bar_top_shadow_pixel;
6246 if (pixel != -1)
6248 XtSetArg (av[ac], XtNtopShadowPixel, pixel);
6249 ++ac;
6251 pixel = f->output_data.x->scroll_bar_bottom_shadow_pixel;
6252 if (pixel != -1)
6254 XtSetArg (av[ac], XtNbottomShadowPixel, pixel);
6255 ++ac;
6258 #endif
6260 widget = XtCreateWidget (scroll_bar_name, scrollbarWidgetClass,
6261 f->output_data.x->edit_widget, av, ac);
6264 char const *initial = "";
6265 char const *val = initial;
6266 XtVaGetValues (widget, XtNscrollVCursor, (XtPointer) &val,
6267 #ifdef XtNarrowScrollbars
6268 XtNarrowScrollbars, (XtPointer) &xaw3d_arrow_scroll,
6269 #endif
6270 XtNpickTop, (XtPointer) &xaw3d_pick_top, NULL);
6271 if (xaw3d_arrow_scroll || val == initial)
6272 { /* ARROW_SCROLL */
6273 xaw3d_arrow_scroll = True;
6274 /* Isn't that just a personal preference ? --Stef */
6275 XtVaSetValues (widget, XtNcursorName, "top_left_arrow", NULL);
6279 /* Define callbacks. */
6280 XtAddCallback (widget, XtNjumpProc, xaw_jump_callback, (XtPointer) bar);
6281 XtAddCallback (widget, XtNscrollProc, xaw_scroll_callback,
6282 (XtPointer) bar);
6284 /* Realize the widget. Only after that is the X window created. */
6285 XtRealizeWidget (widget);
6287 #endif /* !USE_MOTIF */
6289 /* Install an action hook that lets us detect when the user
6290 finishes interacting with a scroll bar. */
6291 if (horizontal_action_hook_id == 0)
6292 horizontal_action_hook_id
6293 = XtAppAddActionHook (Xt_app_con, xt_horizontal_action_hook, 0);
6295 /* Remember X window and widget in the scroll bar vector. */
6296 SET_SCROLL_BAR_X_WIDGET (bar, widget);
6297 xwindow = XtWindow (widget);
6298 bar->x_window = xwindow;
6299 bar->whole = 1;
6300 bar->horizontal = true;
6302 unblock_input ();
6304 #endif /* not USE_GTK */
6307 /* Set the thumb size and position of scroll bar BAR. We are currently
6308 displaying PORTION out of a whole WHOLE, and our position POSITION. */
6310 #ifdef USE_GTK
6311 static void
6312 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position, int whole)
6314 xg_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
6317 static void
6318 x_set_toolkit_horizontal_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position, int whole)
6320 xg_set_toolkit_horizontal_scroll_bar_thumb (bar, portion, position, whole);
6323 #else /* not USE_GTK */
6324 static void
6325 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position,
6326 int whole)
6328 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6329 Widget widget = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
6330 float top, shown;
6332 block_input ();
6334 #ifdef USE_MOTIF
6336 if (scroll_bar_adjust_thumb_portion_p)
6338 /* We use an estimate of 30 chars per line rather than the real
6339 `portion' value. This has the disadvantage that the thumb size
6340 is not very representative, but it makes our life a lot easier.
6341 Otherwise, we have to constantly adjust the thumb size, which
6342 we can't always do quickly enough: while dragging, the size of
6343 the thumb might prevent the user from dragging the thumb all the
6344 way to the end. but Motif and some versions of Xaw3d don't allow
6345 updating the thumb size while dragging. Also, even if we can update
6346 its size, the update will often happen too late.
6347 If you don't believe it, check out revision 1.650 of xterm.c to see
6348 what hoops we were going through and the still poor behavior we got. */
6349 portion = WINDOW_TOTAL_LINES (XWINDOW (bar->window)) * 30;
6350 /* When the thumb is at the bottom, position == whole.
6351 So we need to increase `whole' to make space for the thumb. */
6352 whole += portion;
6355 if (whole <= 0)
6356 top = 0, shown = 1;
6357 else
6359 top = (float) position / whole;
6360 shown = (float) portion / whole;
6363 if (bar->dragging == -1)
6365 int size, value;
6367 /* Slider size. Must be in the range [1 .. MAX - MIN] where MAX
6368 is the scroll bar's maximum and MIN is the scroll bar's minimum
6369 value. */
6370 size = clip_to_bounds (1, shown * XM_SB_MAX, XM_SB_MAX);
6372 /* Position. Must be in the range [MIN .. MAX - SLIDER_SIZE]. */
6373 value = top * XM_SB_MAX;
6374 value = min (value, XM_SB_MAX - size);
6376 XmScrollBarSetValues (widget, value, size, 0, 0, False);
6378 #else /* !USE_MOTIF i.e. use Xaw */
6380 if (whole == 0)
6381 top = 0, shown = 1;
6382 else
6384 top = (float) position / whole;
6385 shown = (float) portion / whole;
6389 float old_top, old_shown;
6390 Dimension height;
6391 XtVaGetValues (widget,
6392 XtNtopOfThumb, &old_top,
6393 XtNshown, &old_shown,
6394 XtNheight, &height,
6395 NULL);
6397 /* Massage the top+shown values. */
6398 if (bar->dragging == -1 || bar->last_seen_part == scroll_bar_down_arrow)
6399 top = max (0, min (1, top));
6400 else
6401 top = old_top;
6402 #if ! defined (HAVE_XAW3D)
6403 /* With Xaw, 'top' values too closer to 1.0 may
6404 cause the thumb to disappear. Fix that. */
6405 top = min (top, 0.99f);
6406 #endif
6407 /* Keep two pixels available for moving the thumb down. */
6408 shown = max (0, min (1 - top - (2.0f / height), shown));
6409 #if ! defined (HAVE_XAW3D)
6410 /* Likewise with too small 'shown'. */
6411 shown = max (shown, 0.01f);
6412 #endif
6414 /* If the call to XawScrollbarSetThumb below doesn't seem to
6415 work, check that 'NARROWPROTO' is defined in src/config.h.
6416 If this is not so, most likely you need to fix configure. */
6417 if (top != old_top || shown != old_shown)
6419 if (bar->dragging == -1)
6420 XawScrollbarSetThumb (widget, top, shown);
6421 else
6423 /* Try to make the scrolling a tad smoother. */
6424 if (!xaw3d_pick_top)
6425 shown = min (shown, old_shown);
6427 XawScrollbarSetThumb (widget, top, shown);
6431 #endif /* !USE_MOTIF */
6433 unblock_input ();
6436 static void
6437 x_set_toolkit_horizontal_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position,
6438 int whole)
6440 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6441 Widget widget = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
6442 float top, shown;
6444 block_input ();
6446 #ifdef USE_MOTIF
6447 bar->whole = whole;
6448 shown = (float) portion / whole;
6449 top = (float) position / (whole - portion);
6451 int size = clip_to_bounds (1, shown * XM_SB_MAX, XM_SB_MAX);
6452 int value = clip_to_bounds (0, top * (XM_SB_MAX - size), XM_SB_MAX - size);
6454 XmScrollBarSetValues (widget, value, size, 0, 0, False);
6456 #else /* !USE_MOTIF i.e. use Xaw */
6457 bar->whole = whole;
6458 if (whole == 0)
6459 top = 0, shown = 1;
6460 else
6462 top = (float) position / whole;
6463 shown = (float) portion / whole;
6467 float old_top, old_shown;
6468 Dimension height;
6469 XtVaGetValues (widget,
6470 XtNtopOfThumb, &old_top,
6471 XtNshown, &old_shown,
6472 XtNheight, &height,
6473 NULL);
6475 #if false
6476 /* Massage the top+shown values. */
6477 if (bar->dragging == -1 || bar->last_seen_part == scroll_bar_down_arrow)
6478 top = max (0, min (1, top));
6479 else
6480 top = old_top;
6481 #if ! defined (HAVE_XAW3D)
6482 /* With Xaw, 'top' values too closer to 1.0 may
6483 cause the thumb to disappear. Fix that. */
6484 top = min (top, 0.99f);
6485 #endif
6486 /* Keep two pixels available for moving the thumb down. */
6487 shown = max (0, min (1 - top - (2.0f / height), shown));
6488 #if ! defined (HAVE_XAW3D)
6489 /* Likewise with too small 'shown'. */
6490 shown = max (shown, 0.01f);
6491 #endif
6492 #endif
6494 /* If the call to XawScrollbarSetThumb below doesn't seem to
6495 work, check that 'NARROWPROTO' is defined in src/config.h.
6496 If this is not so, most likely you need to fix configure. */
6497 XawScrollbarSetThumb (widget, top, shown);
6498 #if false
6499 if (top != old_top || shown != old_shown)
6501 if (bar->dragging == -1)
6502 XawScrollbarSetThumb (widget, top, shown);
6503 else
6505 /* Try to make the scrolling a tad smoother. */
6506 if (!xaw3d_pick_top)
6507 shown = min (shown, old_shown);
6509 XawScrollbarSetThumb (widget, top, shown);
6512 #endif
6514 #endif /* !USE_MOTIF */
6516 unblock_input ();
6518 #endif /* not USE_GTK */
6520 #endif /* USE_TOOLKIT_SCROLL_BARS */
6524 /************************************************************************
6525 Scroll bars, general
6526 ************************************************************************/
6528 /* Create a scroll bar and return the scroll bar vector for it. W is
6529 the Emacs window on which to create the scroll bar. TOP, LEFT,
6530 WIDTH and HEIGHT are the pixel coordinates and dimensions of the
6531 scroll bar. */
6533 static struct scroll_bar *
6534 x_scroll_bar_create (struct window *w, int top, int left,
6535 int width, int height, bool horizontal)
6537 struct frame *f = XFRAME (w->frame);
6538 struct scroll_bar *bar
6539 = ALLOCATE_PSEUDOVECTOR (struct scroll_bar, x_window, PVEC_OTHER);
6540 Lisp_Object barobj;
6542 block_input ();
6544 #ifdef USE_TOOLKIT_SCROLL_BARS
6545 if (horizontal)
6546 x_create_horizontal_toolkit_scroll_bar (f, bar);
6547 else
6548 x_create_toolkit_scroll_bar (f, bar);
6549 #else /* not USE_TOOLKIT_SCROLL_BARS */
6551 XSetWindowAttributes a;
6552 unsigned long mask;
6553 Window window;
6555 a.background_pixel = f->output_data.x->scroll_bar_background_pixel;
6556 if (a.background_pixel == -1)
6557 a.background_pixel = FRAME_BACKGROUND_PIXEL (f);
6559 a.event_mask = (ButtonPressMask | ButtonReleaseMask
6560 | ButtonMotionMask | PointerMotionHintMask
6561 | ExposureMask);
6562 a.cursor = FRAME_DISPLAY_INFO (f)->vertical_scroll_bar_cursor;
6564 mask = (CWBackPixel | CWEventMask | CWCursor);
6566 /* Clear the area of W that will serve as a scroll bar. This is
6567 for the case that a window has been split horizontally. In
6568 this case, no clear_frame is generated to reduce flickering. */
6569 if (width > 0 && window_box_height (w) > 0)
6570 x_clear_area (f, left, top, width, window_box_height (w));
6572 window = XCreateWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
6573 /* Position and size of scroll bar. */
6574 left, top, width, height,
6575 /* Border width, depth, class, and visual. */
6577 CopyFromParent,
6578 CopyFromParent,
6579 CopyFromParent,
6580 /* Attributes. */
6581 mask, &a);
6582 bar->x_window = window;
6584 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6586 XSETWINDOW (bar->window, w);
6587 bar->top = top;
6588 bar->left = left;
6589 bar->width = width;
6590 bar->height = height;
6591 bar->start = 0;
6592 bar->end = 0;
6593 bar->dragging = -1;
6594 bar->horizontal = horizontal;
6595 #if defined (USE_TOOLKIT_SCROLL_BARS) && defined (USE_LUCID)
6596 bar->last_seen_part = scroll_bar_nowhere;
6597 #endif
6599 /* Add bar to its frame's list of scroll bars. */
6600 bar->next = FRAME_SCROLL_BARS (f);
6601 bar->prev = Qnil;
6602 XSETVECTOR (barobj, bar);
6603 fset_scroll_bars (f, barobj);
6604 if (!NILP (bar->next))
6605 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
6607 /* Map the window/widget. */
6608 #ifdef USE_TOOLKIT_SCROLL_BARS
6610 #ifdef USE_GTK
6611 if (horizontal)
6612 xg_update_horizontal_scrollbar_pos (f, bar->x_window, top,
6613 left, width, max (height, 1));
6614 else
6615 xg_update_scrollbar_pos (f, bar->x_window, top,
6616 left, width, max (height, 1));
6617 #else /* not USE_GTK */
6618 Widget scroll_bar = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
6619 XtConfigureWidget (scroll_bar, left, top, width, max (height, 1), 0);
6620 XtMapWidget (scroll_bar);
6621 /* Don't obscure any child frames. */
6622 XLowerWindow (FRAME_X_DISPLAY (f), bar->x_window);
6623 #endif /* not USE_GTK */
6625 #else /* not USE_TOOLKIT_SCROLL_BARS */
6626 XMapWindow (FRAME_X_DISPLAY (f), bar->x_window);
6627 /* Don't obscure any child frames. */
6628 XLowerWindow (FRAME_X_DISPLAY (f), bar->x_window);
6629 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6631 unblock_input ();
6632 return bar;
6636 #ifndef USE_TOOLKIT_SCROLL_BARS
6638 /* Draw BAR's handle in the proper position.
6640 If the handle is already drawn from START to END, don't bother
6641 redrawing it, unless REBUILD; in that case, always
6642 redraw it. (REBUILD is handy for drawing the handle after expose
6643 events.)
6645 Normally, we want to constrain the start and end of the handle to
6646 fit inside its rectangle, but if the user is dragging the scroll
6647 bar handle, we want to let them drag it down all the way, so that
6648 the bar's top is as far down as it goes; otherwise, there's no way
6649 to move to the very end of the buffer. */
6651 static void
6652 x_scroll_bar_set_handle (struct scroll_bar *bar, int start, int end,
6653 bool rebuild)
6655 bool dragging = bar->dragging != -1;
6656 Window w = bar->x_window;
6657 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6658 GC gc = f->output_data.x->normal_gc;
6660 /* If the display is already accurate, do nothing. */
6661 if (! rebuild
6662 && start == bar->start
6663 && end == bar->end)
6664 return;
6666 block_input ();
6669 int inside_width = VERTICAL_SCROLL_BAR_INSIDE_WIDTH (f, bar->width);
6670 int inside_height = VERTICAL_SCROLL_BAR_INSIDE_HEIGHT (f, bar->height);
6671 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
6673 /* Make sure the values are reasonable, and try to preserve
6674 the distance between start and end. */
6676 int length = end - start;
6678 if (start < 0)
6679 start = 0;
6680 else if (start > top_range)
6681 start = top_range;
6682 end = start + length;
6684 if (end < start)
6685 end = start;
6686 else if (end > top_range && ! dragging)
6687 end = top_range;
6690 /* Store the adjusted setting in the scroll bar. */
6691 bar->start = start;
6692 bar->end = end;
6694 /* Clip the end position, just for display. */
6695 if (end > top_range)
6696 end = top_range;
6698 /* Draw bottom positions VERTICAL_SCROLL_BAR_MIN_HANDLE pixels
6699 below top positions, to make sure the handle is always at least
6700 that many pixels tall. */
6701 end += VERTICAL_SCROLL_BAR_MIN_HANDLE;
6703 /* Draw the empty space above the handle. Note that we can't clear
6704 zero-height areas; that means "clear to end of window." */
6705 if ((inside_width > 0) && (start > 0))
6706 x_clear_area1 (FRAME_X_DISPLAY (f), w,
6707 VERTICAL_SCROLL_BAR_LEFT_BORDER,
6708 VERTICAL_SCROLL_BAR_TOP_BORDER,
6709 inside_width, start, False);
6711 /* Change to proper foreground color if one is specified. */
6712 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
6713 XSetForeground (FRAME_X_DISPLAY (f), gc,
6714 f->output_data.x->scroll_bar_foreground_pixel);
6716 /* Draw the handle itself. */
6717 XFillRectangle (FRAME_X_DISPLAY (f), w, gc,
6718 /* x, y, width, height */
6719 VERTICAL_SCROLL_BAR_LEFT_BORDER,
6720 VERTICAL_SCROLL_BAR_TOP_BORDER + start,
6721 inside_width, end - start);
6723 /* Restore the foreground color of the GC if we changed it above. */
6724 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
6725 XSetForeground (FRAME_X_DISPLAY (f), gc,
6726 FRAME_FOREGROUND_PIXEL (f));
6728 /* Draw the empty space below the handle. Note that we can't
6729 clear zero-height areas; that means "clear to end of window." */
6730 if ((inside_width > 0) && (end < inside_height))
6731 x_clear_area1 (FRAME_X_DISPLAY (f), w,
6732 VERTICAL_SCROLL_BAR_LEFT_BORDER,
6733 VERTICAL_SCROLL_BAR_TOP_BORDER + end,
6734 inside_width, inside_height - end, False);
6737 unblock_input ();
6740 #endif /* !USE_TOOLKIT_SCROLL_BARS */
6742 /* Destroy scroll bar BAR, and set its Emacs window's scroll bar to
6743 nil. */
6745 static void
6746 x_scroll_bar_remove (struct scroll_bar *bar)
6748 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6749 block_input ();
6751 #ifdef USE_TOOLKIT_SCROLL_BARS
6752 #ifdef USE_GTK
6753 xg_remove_scroll_bar (f, bar->x_window);
6754 #else /* not USE_GTK */
6755 XtDestroyWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar));
6756 #endif /* not USE_GTK */
6757 #else
6758 XDestroyWindow (FRAME_X_DISPLAY (f), bar->x_window);
6759 #endif
6761 /* Dissociate this scroll bar from its window. */
6762 if (bar->horizontal)
6763 wset_horizontal_scroll_bar (XWINDOW (bar->window), Qnil);
6764 else
6765 wset_vertical_scroll_bar (XWINDOW (bar->window), Qnil);
6767 unblock_input ();
6771 /* Set the handle of the vertical scroll bar for WINDOW to indicate
6772 that we are displaying PORTION characters out of a total of WHOLE
6773 characters, starting at POSITION. If WINDOW has no scroll bar,
6774 create one. */
6776 static void
6777 XTset_vertical_scroll_bar (struct window *w, int portion, int whole, int position)
6779 struct frame *f = XFRAME (w->frame);
6780 Lisp_Object barobj;
6781 struct scroll_bar *bar;
6782 int top, height, left, width;
6783 int window_y, window_height;
6785 /* Get window dimensions. */
6786 window_box (w, ANY_AREA, 0, &window_y, 0, &window_height);
6787 top = window_y;
6788 height = window_height;
6789 left = WINDOW_SCROLL_BAR_AREA_X (w);
6790 width = WINDOW_SCROLL_BAR_AREA_WIDTH (w);
6792 /* Does the scroll bar exist yet? */
6793 if (NILP (w->vertical_scroll_bar))
6795 if (width > 0 && height > 0)
6797 block_input ();
6798 x_clear_area (f, left, top, width, height);
6799 unblock_input ();
6802 bar = x_scroll_bar_create (w, top, left, width, max (height, 1), false);
6804 else
6806 /* It may just need to be moved and resized. */
6807 unsigned int mask = 0;
6809 bar = XSCROLL_BAR (w->vertical_scroll_bar);
6811 block_input ();
6813 if (left != bar->left)
6814 mask |= CWX;
6815 if (top != bar->top)
6816 mask |= CWY;
6817 if (width != bar->width)
6818 mask |= CWWidth;
6819 if (height != bar->height)
6820 mask |= CWHeight;
6822 #ifdef USE_TOOLKIT_SCROLL_BARS
6824 /* Move/size the scroll bar widget. */
6825 if (mask)
6827 /* Since toolkit scroll bars are smaller than the space reserved
6828 for them on the frame, we have to clear "under" them. */
6829 if (width > 0 && height > 0)
6830 x_clear_area (f, left, top, width, height);
6831 #ifdef USE_GTK
6832 xg_update_scrollbar_pos (f, bar->x_window, top,
6833 left, width, max (height, 1));
6834 #else /* not USE_GTK */
6835 XtConfigureWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar),
6836 left, top, width, max (height, 1), 0);
6837 #endif /* not USE_GTK */
6839 #else /* not USE_TOOLKIT_SCROLL_BARS */
6841 /* Move/size the scroll bar window. */
6842 if (mask)
6844 XWindowChanges wc;
6846 wc.x = left;
6847 wc.y = top;
6848 wc.width = width;
6849 wc.height = height;
6850 XConfigureWindow (FRAME_X_DISPLAY (f), bar->x_window,
6851 mask, &wc);
6854 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6856 /* Remember new settings. */
6857 bar->left = left;
6858 bar->top = top;
6859 bar->width = width;
6860 bar->height = height;
6862 unblock_input ();
6865 #ifdef USE_TOOLKIT_SCROLL_BARS
6866 x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
6867 #else /* not USE_TOOLKIT_SCROLL_BARS */
6868 /* Set the scroll bar's current state, unless we're currently being
6869 dragged. */
6870 if (bar->dragging == -1)
6872 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, height);
6874 if (whole == 0)
6875 x_scroll_bar_set_handle (bar, 0, top_range, false);
6876 else
6878 int start = ((double) position * top_range) / whole;
6879 int end = ((double) (position + portion) * top_range) / whole;
6880 x_scroll_bar_set_handle (bar, start, end, false);
6883 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6885 XSETVECTOR (barobj, bar);
6886 wset_vertical_scroll_bar (w, barobj);
6890 static void
6891 XTset_horizontal_scroll_bar (struct window *w, int portion, int whole, int position)
6893 struct frame *f = XFRAME (w->frame);
6894 Lisp_Object barobj;
6895 struct scroll_bar *bar;
6896 int top, height, left, width;
6897 int window_x, window_width;
6898 int pixel_width = WINDOW_PIXEL_WIDTH (w);
6900 /* Get window dimensions. */
6901 window_box (w, ANY_AREA, &window_x, 0, &window_width, 0);
6902 left = window_x;
6903 width = window_width;
6904 top = WINDOW_SCROLL_BAR_AREA_Y (w);
6905 height = WINDOW_SCROLL_BAR_AREA_HEIGHT (w);
6907 /* Does the scroll bar exist yet? */
6908 if (NILP (w->horizontal_scroll_bar))
6910 if (width > 0 && height > 0)
6912 block_input ();
6914 /* Clear also part between window_width and
6915 WINDOW_PIXEL_WIDTH. */
6916 x_clear_area (f, left, top, pixel_width, height);
6917 unblock_input ();
6920 bar = x_scroll_bar_create (w, top, left, width, height, true);
6922 else
6924 /* It may just need to be moved and resized. */
6925 unsigned int mask = 0;
6927 bar = XSCROLL_BAR (w->horizontal_scroll_bar);
6929 block_input ();
6931 if (left != bar->left)
6932 mask |= CWX;
6933 if (top != bar->top)
6934 mask |= CWY;
6935 if (width != bar->width)
6936 mask |= CWWidth;
6937 if (height != bar->height)
6938 mask |= CWHeight;
6940 #ifdef USE_TOOLKIT_SCROLL_BARS
6941 /* Move/size the scroll bar widget. */
6942 if (mask)
6944 /* Since toolkit scroll bars are smaller than the space reserved
6945 for them on the frame, we have to clear "under" them. */
6946 if (width > 0 && height > 0)
6947 x_clear_area (f,
6948 WINDOW_LEFT_EDGE_X (w), top,
6949 pixel_width - WINDOW_RIGHT_DIVIDER_WIDTH (w), height);
6950 #ifdef USE_GTK
6951 xg_update_horizontal_scrollbar_pos (f, bar->x_window, top, left,
6952 width, height);
6953 #else /* not USE_GTK */
6954 XtConfigureWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar),
6955 left, top, width, height, 0);
6956 #endif /* not USE_GTK */
6958 #else /* not USE_TOOLKIT_SCROLL_BARS */
6960 /* Clear areas not covered by the scroll bar because it's not as
6961 wide as the area reserved for it. This makes sure a
6962 previous mode line display is cleared after C-x 2 C-x 1, for
6963 example. */
6965 int area_height = WINDOW_CONFIG_SCROLL_BAR_HEIGHT (w);
6966 int rest = area_height - height;
6967 if (rest > 0 && width > 0)
6968 x_clear_area (f, left, top, width, rest);
6971 /* Move/size the scroll bar window. */
6972 if (mask)
6974 XWindowChanges wc;
6976 wc.x = left;
6977 wc.y = top;
6978 wc.width = width;
6979 wc.height = height;
6980 XConfigureWindow (FRAME_X_DISPLAY (f), bar->x_window,
6981 mask, &wc);
6984 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6986 /* Remember new settings. */
6987 bar->left = left;
6988 bar->top = top;
6989 bar->width = width;
6990 bar->height = height;
6992 unblock_input ();
6995 #ifdef USE_TOOLKIT_SCROLL_BARS
6996 x_set_toolkit_horizontal_scroll_bar_thumb (bar, portion, position, whole);
6997 #else /* not USE_TOOLKIT_SCROLL_BARS */
6998 /* Set the scroll bar's current state, unless we're currently being
6999 dragged. */
7000 if (bar->dragging == -1)
7002 int left_range = HORIZONTAL_SCROLL_BAR_LEFT_RANGE (f, width);
7004 if (whole == 0)
7005 x_scroll_bar_set_handle (bar, 0, left_range, false);
7006 else
7008 int start = ((double) position * left_range) / whole;
7009 int end = ((double) (position + portion) * left_range) / whole;
7010 x_scroll_bar_set_handle (bar, start, end, false);
7013 #endif /* not USE_TOOLKIT_SCROLL_BARS */
7015 XSETVECTOR (barobj, bar);
7016 wset_horizontal_scroll_bar (w, barobj);
7020 /* The following three hooks are used when we're doing a thorough
7021 redisplay of the frame. We don't explicitly know which scroll bars
7022 are going to be deleted, because keeping track of when windows go
7023 away is a real pain - "Can you say set-window-configuration, boys
7024 and girls?" Instead, we just assert at the beginning of redisplay
7025 that *all* scroll bars are to be removed, and then save a scroll bar
7026 from the fiery pit when we actually redisplay its window. */
7028 /* Arrange for all scroll bars on FRAME to be removed at the next call
7029 to `*judge_scroll_bars_hook'. A scroll bar may be spared if
7030 `*redeem_scroll_bar_hook' is applied to its window before the judgment. */
7032 static void
7033 XTcondemn_scroll_bars (struct frame *frame)
7035 if (!NILP (FRAME_SCROLL_BARS (frame)))
7037 if (!NILP (FRAME_CONDEMNED_SCROLL_BARS (frame)))
7039 /* Prepend scrollbars to already condemned ones. */
7040 Lisp_Object last = FRAME_SCROLL_BARS (frame);
7042 while (!NILP (XSCROLL_BAR (last)->next))
7043 last = XSCROLL_BAR (last)->next;
7045 XSCROLL_BAR (last)->next = FRAME_CONDEMNED_SCROLL_BARS (frame);
7046 XSCROLL_BAR (FRAME_CONDEMNED_SCROLL_BARS (frame))->prev = last;
7049 fset_condemned_scroll_bars (frame, FRAME_SCROLL_BARS (frame));
7050 fset_scroll_bars (frame, Qnil);
7055 /* Un-mark WINDOW's scroll bar for deletion in this judgment cycle.
7056 Note that WINDOW isn't necessarily condemned at all. */
7058 static void
7059 XTredeem_scroll_bar (struct window *w)
7061 struct scroll_bar *bar;
7062 Lisp_Object barobj;
7063 struct frame *f;
7065 /* We can't redeem this window's scroll bar if it doesn't have one. */
7066 if (NILP (w->vertical_scroll_bar) && NILP (w->horizontal_scroll_bar))
7067 emacs_abort ();
7069 if (!NILP (w->vertical_scroll_bar) && WINDOW_HAS_VERTICAL_SCROLL_BAR (w))
7071 bar = XSCROLL_BAR (w->vertical_scroll_bar);
7072 /* Unlink it from the condemned list. */
7073 f = XFRAME (WINDOW_FRAME (w));
7074 if (NILP (bar->prev))
7076 /* If the prev pointer is nil, it must be the first in one of
7077 the lists. */
7078 if (EQ (FRAME_SCROLL_BARS (f), w->vertical_scroll_bar))
7079 /* It's not condemned. Everything's fine. */
7080 goto horizontal;
7081 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
7082 w->vertical_scroll_bar))
7083 fset_condemned_scroll_bars (f, bar->next);
7084 else
7085 /* If its prev pointer is nil, it must be at the front of
7086 one or the other! */
7087 emacs_abort ();
7089 else
7090 XSCROLL_BAR (bar->prev)->next = bar->next;
7092 if (! NILP (bar->next))
7093 XSCROLL_BAR (bar->next)->prev = bar->prev;
7095 bar->next = FRAME_SCROLL_BARS (f);
7096 bar->prev = Qnil;
7097 XSETVECTOR (barobj, bar);
7098 fset_scroll_bars (f, barobj);
7099 if (! NILP (bar->next))
7100 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
7103 horizontal:
7104 if (!NILP (w->horizontal_scroll_bar) && WINDOW_HAS_HORIZONTAL_SCROLL_BAR (w))
7106 bar = XSCROLL_BAR (w->horizontal_scroll_bar);
7107 /* Unlink it from the condemned list. */
7108 f = XFRAME (WINDOW_FRAME (w));
7109 if (NILP (bar->prev))
7111 /* If the prev pointer is nil, it must be the first in one of
7112 the lists. */
7113 if (EQ (FRAME_SCROLL_BARS (f), w->horizontal_scroll_bar))
7114 /* It's not condemned. Everything's fine. */
7115 return;
7116 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
7117 w->horizontal_scroll_bar))
7118 fset_condemned_scroll_bars (f, bar->next);
7119 else
7120 /* If its prev pointer is nil, it must be at the front of
7121 one or the other! */
7122 emacs_abort ();
7124 else
7125 XSCROLL_BAR (bar->prev)->next = bar->next;
7127 if (! NILP (bar->next))
7128 XSCROLL_BAR (bar->next)->prev = bar->prev;
7130 bar->next = FRAME_SCROLL_BARS (f);
7131 bar->prev = Qnil;
7132 XSETVECTOR (barobj, bar);
7133 fset_scroll_bars (f, barobj);
7134 if (! NILP (bar->next))
7135 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
7139 /* Remove all scroll bars on FRAME that haven't been saved since the
7140 last call to `*condemn_scroll_bars_hook'. */
7142 static void
7143 XTjudge_scroll_bars (struct frame *f)
7145 Lisp_Object bar, next;
7147 bar = FRAME_CONDEMNED_SCROLL_BARS (f);
7149 /* Clear out the condemned list now so we won't try to process any
7150 more events on the hapless scroll bars. */
7151 fset_condemned_scroll_bars (f, Qnil);
7153 for (; ! NILP (bar); bar = next)
7155 struct scroll_bar *b = XSCROLL_BAR (bar);
7157 x_scroll_bar_remove (b);
7159 next = b->next;
7160 b->next = b->prev = Qnil;
7163 /* Now there should be no references to the condemned scroll bars,
7164 and they should get garbage-collected. */
7168 #ifndef USE_TOOLKIT_SCROLL_BARS
7169 /* Handle an Expose or GraphicsExpose event on a scroll bar. This
7170 is a no-op when using toolkit scroll bars.
7172 This may be called from a signal handler, so we have to ignore GC
7173 mark bits. */
7175 static void
7176 x_scroll_bar_expose (struct scroll_bar *bar, const XEvent *event)
7178 Window w = bar->x_window;
7179 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
7180 GC gc = f->output_data.x->normal_gc;
7182 block_input ();
7184 x_scroll_bar_set_handle (bar, bar->start, bar->end, true);
7186 /* Switch to scroll bar foreground color. */
7187 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
7188 XSetForeground (FRAME_X_DISPLAY (f), gc,
7189 f->output_data.x->scroll_bar_foreground_pixel);
7191 /* Draw a one-pixel border just inside the edges of the scroll bar. */
7192 XDrawRectangle (FRAME_X_DISPLAY (f), w, gc,
7193 /* x, y, width, height */
7194 0, 0, bar->width - 1, bar->height - 1);
7196 /* Restore the foreground color of the GC if we changed it above. */
7197 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
7198 XSetForeground (FRAME_X_DISPLAY (f), gc,
7199 FRAME_FOREGROUND_PIXEL (f));
7201 unblock_input ();
7204 #endif /* not USE_TOOLKIT_SCROLL_BARS */
7206 /* Handle a mouse click on the scroll bar BAR. If *EMACS_EVENT's kind
7207 is set to something other than NO_EVENT, it is enqueued.
7209 This may be called from a signal handler, so we have to ignore GC
7210 mark bits. */
7213 static void
7214 x_scroll_bar_handle_click (struct scroll_bar *bar,
7215 const XEvent *event,
7216 struct input_event *emacs_event)
7218 if (! WINDOWP (bar->window))
7219 emacs_abort ();
7221 emacs_event->kind = (bar->horizontal
7222 ? HORIZONTAL_SCROLL_BAR_CLICK_EVENT
7223 : SCROLL_BAR_CLICK_EVENT);
7224 emacs_event->code = event->xbutton.button - Button1;
7225 emacs_event->modifiers
7226 = (x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO
7227 (XFRAME (WINDOW_FRAME (XWINDOW (bar->window)))),
7228 event->xbutton.state)
7229 | (event->type == ButtonRelease
7230 ? up_modifier
7231 : down_modifier));
7232 emacs_event->frame_or_window = bar->window;
7233 emacs_event->arg = Qnil;
7234 emacs_event->timestamp = event->xbutton.time;
7235 if (bar->horizontal)
7237 int left_range
7238 = HORIZONTAL_SCROLL_BAR_LEFT_RANGE (f, bar->width);
7239 int x = event->xbutton.x - HORIZONTAL_SCROLL_BAR_LEFT_BORDER;
7241 if (x < 0) x = 0;
7242 if (x > left_range) x = left_range;
7244 if (x < bar->start)
7245 emacs_event->part = scroll_bar_before_handle;
7246 else if (x < bar->end + HORIZONTAL_SCROLL_BAR_MIN_HANDLE)
7247 emacs_event->part = scroll_bar_horizontal_handle;
7248 else
7249 emacs_event->part = scroll_bar_after_handle;
7251 #ifndef USE_TOOLKIT_SCROLL_BARS
7252 /* If the user has released the handle, set it to its final position. */
7253 if (event->type == ButtonRelease && bar->dragging != -1)
7255 int new_start = - bar->dragging;
7256 int new_end = new_start + bar->end - bar->start;
7258 x_scroll_bar_set_handle (bar, new_start, new_end, false);
7259 bar->dragging = -1;
7261 #endif
7263 XSETINT (emacs_event->x, left_range);
7264 XSETINT (emacs_event->y, x);
7266 else
7268 int top_range
7269 = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
7270 int y = event->xbutton.y - VERTICAL_SCROLL_BAR_TOP_BORDER;
7272 if (y < 0) y = 0;
7273 if (y > top_range) y = top_range;
7275 if (y < bar->start)
7276 emacs_event->part = scroll_bar_above_handle;
7277 else if (y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
7278 emacs_event->part = scroll_bar_handle;
7279 else
7280 emacs_event->part = scroll_bar_below_handle;
7282 #ifndef USE_TOOLKIT_SCROLL_BARS
7283 /* If the user has released the handle, set it to its final position. */
7284 if (event->type == ButtonRelease && bar->dragging != -1)
7286 int new_start = y - bar->dragging;
7287 int new_end = new_start + bar->end - bar->start;
7289 x_scroll_bar_set_handle (bar, new_start, new_end, false);
7290 bar->dragging = -1;
7292 #endif
7294 XSETINT (emacs_event->x, y);
7295 XSETINT (emacs_event->y, top_range);
7299 #ifndef USE_TOOLKIT_SCROLL_BARS
7301 /* Handle some mouse motion while someone is dragging the scroll bar.
7303 This may be called from a signal handler, so we have to ignore GC
7304 mark bits. */
7306 static void
7307 x_scroll_bar_note_movement (struct scroll_bar *bar,
7308 const XMotionEvent *event)
7310 struct frame *f = XFRAME (XWINDOW (bar->window)->frame);
7311 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
7313 dpyinfo->last_mouse_movement_time = event->time;
7314 dpyinfo->last_mouse_scroll_bar = bar;
7315 f->mouse_moved = true;
7317 /* If we're dragging the bar, display it. */
7318 if (bar->dragging != -1)
7320 /* Where should the handle be now? */
7321 int new_start = event->y - bar->dragging;
7323 if (new_start != bar->start)
7325 int new_end = new_start + bar->end - bar->start;
7327 x_scroll_bar_set_handle (bar, new_start, new_end, false);
7332 #endif /* !USE_TOOLKIT_SCROLL_BARS */
7334 /* Return information to the user about the current position of the mouse
7335 on the scroll bar. */
7337 static void
7338 x_scroll_bar_report_motion (struct frame **fp, Lisp_Object *bar_window,
7339 enum scroll_bar_part *part, Lisp_Object *x,
7340 Lisp_Object *y, Time *timestamp)
7342 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (*fp);
7343 struct scroll_bar *bar = dpyinfo->last_mouse_scroll_bar;
7344 Window w = bar->x_window;
7345 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
7346 int win_x, win_y;
7347 Window dummy_window;
7348 int dummy_coord;
7349 unsigned int dummy_mask;
7351 block_input ();
7353 /* Get the mouse's position relative to the scroll bar window, and
7354 report that. */
7355 if (XQueryPointer (FRAME_X_DISPLAY (f), w,
7357 /* Root, child, root x and root y. */
7358 &dummy_window, &dummy_window,
7359 &dummy_coord, &dummy_coord,
7361 /* Position relative to scroll bar. */
7362 &win_x, &win_y,
7364 /* Mouse buttons and modifier keys. */
7365 &dummy_mask))
7367 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
7369 win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
7371 if (bar->dragging != -1)
7372 win_y -= bar->dragging;
7374 if (win_y < 0)
7375 win_y = 0;
7376 if (win_y > top_range)
7377 win_y = top_range;
7379 *fp = f;
7380 *bar_window = bar->window;
7382 if (bar->dragging != -1)
7383 *part = scroll_bar_handle;
7384 else if (win_y < bar->start)
7385 *part = scroll_bar_above_handle;
7386 else if (win_y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
7387 *part = scroll_bar_handle;
7388 else
7389 *part = scroll_bar_below_handle;
7391 XSETINT (*x, win_y);
7392 XSETINT (*y, top_range);
7394 f->mouse_moved = false;
7395 dpyinfo->last_mouse_scroll_bar = NULL;
7396 *timestamp = dpyinfo->last_mouse_movement_time;
7399 unblock_input ();
7403 /* Return information to the user about the current position of the mouse
7404 on the scroll bar. */
7406 static void
7407 x_horizontal_scroll_bar_report_motion (struct frame **fp, Lisp_Object *bar_window,
7408 enum scroll_bar_part *part, Lisp_Object *x,
7409 Lisp_Object *y, Time *timestamp)
7411 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (*fp);
7412 struct scroll_bar *bar = dpyinfo->last_mouse_scroll_bar;
7413 Window w = bar->x_window;
7414 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
7415 int win_x, win_y;
7416 Window dummy_window;
7417 int dummy_coord;
7418 unsigned int dummy_mask;
7420 block_input ();
7422 /* Get the mouse's position relative to the scroll bar window, and
7423 report that. */
7424 if (XQueryPointer (FRAME_X_DISPLAY (f), w,
7426 /* Root, child, root x and root y. */
7427 &dummy_window, &dummy_window,
7428 &dummy_coord, &dummy_coord,
7430 /* Position relative to scroll bar. */
7431 &win_x, &win_y,
7433 /* Mouse buttons and modifier keys. */
7434 &dummy_mask))
7436 int left_range = HORIZONTAL_SCROLL_BAR_LEFT_RANGE (f, bar->width);
7438 win_x -= HORIZONTAL_SCROLL_BAR_LEFT_BORDER;
7440 if (bar->dragging != -1)
7441 win_x -= bar->dragging;
7443 if (win_x < 0)
7444 win_x = 0;
7445 if (win_x > left_range)
7446 win_x = left_range;
7448 *fp = f;
7449 *bar_window = bar->window;
7451 if (bar->dragging != -1)
7452 *part = scroll_bar_horizontal_handle;
7453 else if (win_x < bar->start)
7454 *part = scroll_bar_before_handle;
7455 else if (win_x < bar->end + HORIZONTAL_SCROLL_BAR_MIN_HANDLE)
7456 *part = scroll_bar_handle;
7457 else
7458 *part = scroll_bar_after_handle;
7460 XSETINT (*y, win_x);
7461 XSETINT (*x, left_range);
7463 f->mouse_moved = false;
7464 dpyinfo->last_mouse_scroll_bar = NULL;
7465 *timestamp = dpyinfo->last_mouse_movement_time;
7468 unblock_input ();
7472 /* The screen has been cleared so we may have changed foreground or
7473 background colors, and the scroll bars may need to be redrawn.
7474 Clear out the scroll bars, and ask for expose events, so we can
7475 redraw them. */
7477 static void
7478 x_scroll_bar_clear (struct frame *f)
7480 #ifndef USE_TOOLKIT_SCROLL_BARS
7481 Lisp_Object bar;
7483 /* We can have scroll bars even if this is 0,
7484 if we just turned off scroll bar mode.
7485 But in that case we should not clear them. */
7486 if (FRAME_HAS_VERTICAL_SCROLL_BARS (f))
7487 for (bar = FRAME_SCROLL_BARS (f); VECTORP (bar);
7488 bar = XSCROLL_BAR (bar)->next)
7489 XClearArea (FRAME_X_DISPLAY (f),
7490 XSCROLL_BAR (bar)->x_window,
7491 0, 0, 0, 0, True);
7492 #endif /* not USE_TOOLKIT_SCROLL_BARS */
7495 #ifdef ENABLE_CHECKING
7497 /* Record the last 100 characters stored
7498 to help debug the loss-of-chars-during-GC problem. */
7500 static int temp_index;
7501 static short temp_buffer[100];
7503 #define STORE_KEYSYM_FOR_DEBUG(keysym) \
7504 if (temp_index == ARRAYELTS (temp_buffer)) \
7505 temp_index = 0; \
7506 temp_buffer[temp_index++] = (keysym)
7508 #else /* not ENABLE_CHECKING */
7510 #define STORE_KEYSYM_FOR_DEBUG(keysym) ((void)0)
7512 #endif /* ENABLE_CHECKING */
7514 /* Set this to nonzero to fake an "X I/O error"
7515 on a particular display. */
7517 static struct x_display_info *XTread_socket_fake_io_error;
7519 /* When we find no input here, we occasionally do a no-op command
7520 to verify that the X server is still running and we can still talk with it.
7521 We try all the open displays, one by one.
7522 This variable is used for cycling thru the displays. */
7524 static struct x_display_info *next_noop_dpyinfo;
7526 enum
7528 X_EVENT_NORMAL,
7529 X_EVENT_GOTO_OUT,
7530 X_EVENT_DROP
7533 /* Filter events for the current X input method.
7534 DPYINFO is the display this event is for.
7535 EVENT is the X event to filter.
7537 Returns non-zero if the event was filtered, caller shall not process
7538 this event further.
7539 Returns zero if event is wasn't filtered. */
7541 #ifdef HAVE_X_I18N
7542 static int
7543 x_filter_event (struct x_display_info *dpyinfo, XEvent *event)
7545 /* XFilterEvent returns non-zero if the input method has
7546 consumed the event. We pass the frame's X window to
7547 XFilterEvent because that's the one for which the IC
7548 was created. */
7550 struct frame *f1 = x_any_window_to_frame (dpyinfo,
7551 event->xclient.window);
7553 return XFilterEvent (event, f1 ? FRAME_X_WINDOW (f1) : None);
7555 #endif
7557 #ifdef USE_GTK
7558 static int current_count;
7559 static int current_finish;
7560 static struct input_event *current_hold_quit;
7562 /* This is the filter function invoked by the GTK event loop.
7563 It is invoked before the XEvent is translated to a GdkEvent,
7564 so we have a chance to act on the event before GTK. */
7565 static GdkFilterReturn
7566 event_handler_gdk (GdkXEvent *gxev, GdkEvent *ev, gpointer data)
7568 XEvent *xev = (XEvent *) gxev;
7570 block_input ();
7571 if (current_count >= 0)
7573 struct x_display_info *dpyinfo;
7575 dpyinfo = x_display_info_for_display (xev->xany.display);
7577 #ifdef HAVE_X_I18N
7578 /* Filter events for the current X input method.
7579 GTK calls XFilterEvent but not for key press and release,
7580 so we do it here. */
7581 if ((xev->type == KeyPress || xev->type == KeyRelease)
7582 && dpyinfo
7583 && x_filter_event (dpyinfo, xev))
7585 unblock_input ();
7586 return GDK_FILTER_REMOVE;
7588 #endif
7590 if (! dpyinfo)
7591 current_finish = X_EVENT_NORMAL;
7592 else
7593 current_count
7594 += handle_one_xevent (dpyinfo, xev, &current_finish,
7595 current_hold_quit);
7597 else
7598 current_finish = x_dispatch_event (xev, xev->xany.display);
7600 unblock_input ();
7602 if (current_finish == X_EVENT_GOTO_OUT || current_finish == X_EVENT_DROP)
7603 return GDK_FILTER_REMOVE;
7605 return GDK_FILTER_CONTINUE;
7607 #endif /* USE_GTK */
7610 static void xembed_send_message (struct frame *f, Time,
7611 enum xembed_message,
7612 long detail, long data1, long data2);
7614 static void
7615 x_net_wm_state (struct frame *f, Window window)
7617 int value = FULLSCREEN_NONE;
7618 Lisp_Object lval = Qnil;
7619 bool sticky = false;
7621 get_current_wm_state (f, window, &value, &sticky);
7623 switch (value)
7625 case FULLSCREEN_WIDTH:
7626 lval = Qfullwidth;
7627 break;
7628 case FULLSCREEN_HEIGHT:
7629 lval = Qfullheight;
7630 break;
7631 case FULLSCREEN_BOTH:
7632 lval = Qfullboth;
7633 break;
7634 case FULLSCREEN_MAXIMIZED:
7635 lval = Qmaximized;
7636 break;
7639 frame_size_history_add
7640 (f, Qx_net_wm_state, 0, 0,
7641 list2 (get_frame_param (f, Qfullscreen), lval));
7643 store_frame_param (f, Qfullscreen, lval);
7644 /** store_frame_param (f, Qsticky, sticky ? Qt : Qnil); **/
7647 /* Flip back buffers on any frames with undrawn content. */
7648 static void
7649 flush_dirty_back_buffers (void)
7651 block_input ();
7652 Lisp_Object tail, frame;
7653 FOR_EACH_FRAME (tail, frame)
7655 struct frame *f = XFRAME (frame);
7656 if (FRAME_LIVE_P (f) &&
7657 FRAME_X_P (f) &&
7658 FRAME_X_WINDOW (f) &&
7659 !FRAME_GARBAGED_P (f) &&
7660 !buffer_flipping_blocked_p () &&
7661 FRAME_X_NEED_BUFFER_FLIP (f))
7662 show_back_buffer (f);
7664 unblock_input ();
7667 /* Handles the XEvent EVENT on display DPYINFO.
7669 *FINISH is X_EVENT_GOTO_OUT if caller should stop reading events.
7670 *FINISH is zero if caller should continue reading events.
7671 *FINISH is X_EVENT_DROP if event should not be passed to the toolkit.
7672 *EVENT is unchanged unless we're processing KeyPress event.
7674 We return the number of characters stored into the buffer. */
7676 static int
7677 handle_one_xevent (struct x_display_info *dpyinfo,
7678 const XEvent *event,
7679 int *finish, struct input_event *hold_quit)
7681 union buffered_input_event inev;
7682 int count = 0;
7683 int do_help = 0;
7684 ptrdiff_t nbytes = 0;
7685 struct frame *any, *f = NULL;
7686 struct coding_system coding;
7687 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
7688 /* This holds the state XLookupString needs to implement dead keys
7689 and other tricks known as "compose processing". _X Window System_
7690 says that a portable program can't use this, but Stephen Gildea assures
7691 me that letting the compiler initialize it to zeros will work okay. */
7692 static XComposeStatus compose_status;
7693 XEvent configureEvent;
7694 XEvent next_event;
7696 USE_SAFE_ALLOCA;
7698 *finish = X_EVENT_NORMAL;
7700 EVENT_INIT (inev.ie);
7701 inev.ie.kind = NO_EVENT;
7702 inev.ie.arg = Qnil;
7704 any = x_any_window_to_frame (dpyinfo, event->xany.window);
7706 if (any && any->wait_event_type == event->type)
7707 any->wait_event_type = 0; /* Indicates we got it. */
7709 switch (event->type)
7711 case ClientMessage:
7713 if (event->xclient.message_type == dpyinfo->Xatom_wm_protocols
7714 && event->xclient.format == 32)
7716 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_take_focus)
7718 /* Use the value returned by x_any_window_to_frame
7719 because this could be the shell widget window
7720 if the frame has no title bar. */
7721 f = any;
7722 #ifdef HAVE_X_I18N
7723 /* Not quite sure this is needed -pd */
7724 if (f && FRAME_XIC (f))
7725 XSetICFocus (FRAME_XIC (f));
7726 #endif
7727 #if false
7728 /* Emacs sets WM hints whose `input' field is `true'. This
7729 instructs the WM to set the input focus automatically for
7730 Emacs with a call to XSetInputFocus. Setting WM_TAKE_FOCUS
7731 tells the WM to send us a ClientMessage WM_TAKE_FOCUS after
7732 it has set the focus. So, XSetInputFocus below is not
7733 needed.
7735 The call to XSetInputFocus below has also caused trouble. In
7736 cases where the XSetInputFocus done by the WM and the one
7737 below are temporally close (on a fast machine), the call
7738 below can generate additional FocusIn events which confuse
7739 Emacs. */
7741 /* Since we set WM_TAKE_FOCUS, we must call
7742 XSetInputFocus explicitly. But not if f is null,
7743 since that might be an event for a deleted frame. */
7744 if (f)
7746 Display *d = event->xclient.display;
7747 /* Catch and ignore errors, in case window has been
7748 iconified by a window manager such as GWM. */
7749 x_catch_errors (d);
7750 XSetInputFocus (d, event->xclient.window,
7751 /* The ICCCM says this is
7752 the only valid choice. */
7753 RevertToParent,
7754 event->xclient.data.l[1]);
7755 x_uncatch_errors ();
7757 /* Not certain about handling scroll bars here */
7758 #endif
7759 goto done;
7762 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_save_yourself)
7764 /* Save state modify the WM_COMMAND property to
7765 something which can reinstate us. This notifies
7766 the session manager, who's looking for such a
7767 PropertyNotify. Can restart processing when
7768 a keyboard or mouse event arrives. */
7769 /* If we have a session manager, don't set this.
7770 KDE will then start two Emacsen, one for the
7771 session manager and one for this. */
7772 #ifdef HAVE_X_SM
7773 if (! x_session_have_connection ())
7774 #endif
7776 f = x_top_window_to_frame (dpyinfo,
7777 event->xclient.window);
7778 /* This is just so we only give real data once
7779 for a single Emacs process. */
7780 if (f == SELECTED_FRAME ())
7781 XSetCommand (FRAME_X_DISPLAY (f),
7782 event->xclient.window,
7783 initial_argv, initial_argc);
7784 else if (f)
7785 XSetCommand (FRAME_X_DISPLAY (f),
7786 event->xclient.window,
7787 0, 0);
7789 goto done;
7792 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_delete_window)
7794 f = any;
7795 if (!f)
7796 goto OTHER; /* May be a dialog that is to be removed */
7798 inev.ie.kind = DELETE_WINDOW_EVENT;
7799 XSETFRAME (inev.ie.frame_or_window, f);
7800 goto done;
7803 goto done;
7806 if (event->xclient.message_type == dpyinfo->Xatom_wm_configure_denied)
7807 goto done;
7809 if (event->xclient.message_type == dpyinfo->Xatom_wm_window_moved)
7811 int new_x, new_y;
7812 f = x_window_to_frame (dpyinfo, event->xclient.window);
7814 new_x = event->xclient.data.s[0];
7815 new_y = event->xclient.data.s[1];
7817 if (f)
7819 f->left_pos = new_x;
7820 f->top_pos = new_y;
7822 goto done;
7825 #ifdef X_TOOLKIT_EDITRES
7826 if (event->xclient.message_type == dpyinfo->Xatom_editres)
7828 f = any;
7829 if (f)
7830 _XEditResCheckMessages (f->output_data.x->widget,
7831 NULL, (XEvent *) event, NULL);
7832 goto done;
7834 #endif /* X_TOOLKIT_EDITRES */
7836 if (event->xclient.message_type == dpyinfo->Xatom_DONE
7837 || event->xclient.message_type == dpyinfo->Xatom_PAGE)
7839 /* Ghostview job completed. Kill it. We could
7840 reply with "Next" if we received "Page", but we
7841 currently never do because we are interested in
7842 images, only, which should have 1 page. */
7843 Pixmap pixmap = (Pixmap) event->xclient.data.l[1];
7844 f = x_window_to_frame (dpyinfo, event->xclient.window);
7845 if (!f)
7846 goto OTHER;
7847 x_kill_gs_process (pixmap, f);
7848 expose_frame (f, 0, 0, 0, 0);
7849 goto done;
7852 #ifdef USE_TOOLKIT_SCROLL_BARS
7853 /* Scroll bar callbacks send a ClientMessage from which
7854 we construct an input_event. */
7855 if (event->xclient.message_type == dpyinfo->Xatom_Scrollbar)
7857 x_scroll_bar_to_input_event (event, &inev.ie);
7858 *finish = X_EVENT_GOTO_OUT;
7859 goto done;
7861 else if (event->xclient.message_type == dpyinfo->Xatom_Horizontal_Scrollbar)
7863 x_horizontal_scroll_bar_to_input_event (event, &inev.ie);
7864 *finish = X_EVENT_GOTO_OUT;
7865 goto done;
7867 #endif /* USE_TOOLKIT_SCROLL_BARS */
7869 /* XEmbed messages from the embedder (if any). */
7870 if (event->xclient.message_type == dpyinfo->Xatom_XEMBED)
7872 enum xembed_message msg = event->xclient.data.l[1];
7873 if (msg == XEMBED_FOCUS_IN || msg == XEMBED_FOCUS_OUT)
7874 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
7876 *finish = X_EVENT_GOTO_OUT;
7877 goto done;
7880 xft_settings_event (dpyinfo, event);
7882 f = any;
7883 if (!f)
7884 goto OTHER;
7885 if (x_handle_dnd_message (f, &event->xclient, dpyinfo, &inev.ie))
7886 *finish = X_EVENT_DROP;
7888 break;
7890 case SelectionNotify:
7891 x_display_set_last_user_time (dpyinfo, event->xselection.time);
7892 #ifdef USE_X_TOOLKIT
7893 if (! x_window_to_frame (dpyinfo, event->xselection.requestor))
7894 goto OTHER;
7895 #endif /* not USE_X_TOOLKIT */
7896 x_handle_selection_notify (&event->xselection);
7897 break;
7899 case SelectionClear: /* Someone has grabbed ownership. */
7900 x_display_set_last_user_time (dpyinfo, event->xselectionclear.time);
7901 #ifdef USE_X_TOOLKIT
7902 if (! x_window_to_frame (dpyinfo, event->xselectionclear.window))
7903 goto OTHER;
7904 #endif /* USE_X_TOOLKIT */
7906 const XSelectionClearEvent *eventp = &event->xselectionclear;
7908 inev.sie.kind = SELECTION_CLEAR_EVENT;
7909 SELECTION_EVENT_DPYINFO (&inev.sie) = dpyinfo;
7910 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
7911 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
7913 break;
7915 case SelectionRequest: /* Someone wants our selection. */
7916 x_display_set_last_user_time (dpyinfo, event->xselectionrequest.time);
7917 #ifdef USE_X_TOOLKIT
7918 if (!x_window_to_frame (dpyinfo, event->xselectionrequest.owner))
7919 goto OTHER;
7920 #endif /* USE_X_TOOLKIT */
7922 const XSelectionRequestEvent *eventp = &event->xselectionrequest;
7924 inev.sie.kind = SELECTION_REQUEST_EVENT;
7925 SELECTION_EVENT_DPYINFO (&inev.sie) = dpyinfo;
7926 SELECTION_EVENT_REQUESTOR (&inev.sie) = eventp->requestor;
7927 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
7928 SELECTION_EVENT_TARGET (&inev.sie) = eventp->target;
7929 SELECTION_EVENT_PROPERTY (&inev.sie) = eventp->property;
7930 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
7932 break;
7934 case PropertyNotify:
7935 x_display_set_last_user_time (dpyinfo, event->xproperty.time);
7936 f = x_top_window_to_frame (dpyinfo, event->xproperty.window);
7937 if (f && event->xproperty.atom == dpyinfo->Xatom_net_wm_state)
7939 bool not_hidden = x_handle_net_wm_state (f, &event->xproperty);
7940 if (not_hidden && FRAME_ICONIFIED_P (f))
7942 /* Gnome shell does not iconify us when C-z is pressed.
7943 It hides the frame. So if our state says we aren't
7944 hidden anymore, treat it as deiconified. */
7945 SET_FRAME_VISIBLE (f, 1);
7946 SET_FRAME_ICONIFIED (f, false);
7947 f->output_data.x->has_been_visible = true;
7948 inev.ie.kind = DEICONIFY_EVENT;
7949 XSETFRAME (inev.ie.frame_or_window, f);
7951 else if (! not_hidden && ! FRAME_ICONIFIED_P (f))
7953 SET_FRAME_VISIBLE (f, 0);
7954 SET_FRAME_ICONIFIED (f, true);
7955 inev.ie.kind = ICONIFY_EVENT;
7956 XSETFRAME (inev.ie.frame_or_window, f);
7960 x_handle_property_notify (&event->xproperty);
7961 xft_settings_event (dpyinfo, event);
7962 goto OTHER;
7964 case ReparentNotify:
7965 f = x_top_window_to_frame (dpyinfo, event->xreparent.window);
7966 if (f)
7968 /* Maybe we shouldn't set this for child frames ?? */
7969 f->output_data.x->parent_desc = event->xreparent.parent;
7970 if (!FRAME_PARENT_FRAME (f))
7971 x_real_positions (f, &f->left_pos, &f->top_pos);
7972 else
7974 Window root;
7975 unsigned int dummy_uint;
7977 block_input ();
7978 XGetGeometry (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
7979 &root, &f->left_pos, &f->top_pos,
7980 &dummy_uint, &dummy_uint, &dummy_uint, &dummy_uint);
7981 unblock_input ();
7984 /* Perhaps reparented due to a WM restart. Reset this. */
7985 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_UNKNOWN;
7986 FRAME_DISPLAY_INFO (f)->net_supported_window = 0;
7988 x_set_frame_alpha (f);
7990 goto OTHER;
7992 case Expose:
7993 f = x_window_to_frame (dpyinfo, event->xexpose.window);
7994 if (f)
7996 if (!FRAME_VISIBLE_P (f))
7998 block_input ();
7999 SET_FRAME_VISIBLE (f, 1);
8000 SET_FRAME_ICONIFIED (f, false);
8001 if (FRAME_X_DOUBLE_BUFFERED_P (f))
8002 font_drop_xrender_surfaces (f);
8003 f->output_data.x->has_been_visible = true;
8004 SET_FRAME_GARBAGED (f);
8005 unblock_input ();
8007 else if (FRAME_GARBAGED_P (f))
8009 #ifdef USE_GTK
8010 /* Go around the back buffer and manually clear the
8011 window the first time we show it. This way, we avoid
8012 showing users the sanity-defying horror of whatever
8013 GtkWindow is rendering beneath us. We've garbaged
8014 the frame, so we'll redraw the whole thing on next
8015 redisplay anyway. Yuck. */
8016 x_clear_area1 (
8017 FRAME_X_DISPLAY (f),
8018 FRAME_X_WINDOW (f),
8019 event->xexpose.x, event->xexpose.y,
8020 event->xexpose.width, event->xexpose.height,
8022 x_clear_under_internal_border (f);
8023 #endif
8027 if (!FRAME_GARBAGED_P (f))
8029 #ifdef USE_GTK
8030 /* This seems to be needed for GTK 2.6 and later, see
8031 https://debbugs.gnu.org/cgi/bugreport.cgi?bug=15398. */
8032 x_clear_area (f,
8033 event->xexpose.x, event->xexpose.y,
8034 event->xexpose.width, event->xexpose.height);
8035 #endif
8036 expose_frame (f, event->xexpose.x, event->xexpose.y,
8037 event->xexpose.width, event->xexpose.height);
8038 #ifdef USE_GTK
8039 x_clear_under_internal_border (f);
8040 #endif
8043 if (!FRAME_GARBAGED_P (f))
8044 show_back_buffer (f);
8046 else
8048 #ifndef USE_TOOLKIT_SCROLL_BARS
8049 struct scroll_bar *bar;
8050 #endif
8051 #if defined USE_LUCID
8052 /* Submenus of the Lucid menu bar aren't widgets
8053 themselves, so there's no way to dispatch events
8054 to them. Recognize this case separately. */
8056 Widget widget = x_window_to_menu_bar (event->xexpose.window);
8057 if (widget)
8058 xlwmenu_redisplay (widget);
8060 #endif /* USE_LUCID */
8062 #ifdef USE_TOOLKIT_SCROLL_BARS
8063 /* Dispatch event to the widget. */
8064 goto OTHER;
8065 #else /* not USE_TOOLKIT_SCROLL_BARS */
8066 bar = x_window_to_scroll_bar (event->xexpose.display,
8067 event->xexpose.window, 2);
8069 if (bar)
8070 x_scroll_bar_expose (bar, event);
8071 #ifdef USE_X_TOOLKIT
8072 else
8073 goto OTHER;
8074 #endif /* USE_X_TOOLKIT */
8075 #endif /* not USE_TOOLKIT_SCROLL_BARS */
8077 break;
8079 case GraphicsExpose: /* This occurs when an XCopyArea's
8080 source area was obscured or not
8081 available. */
8082 f = x_window_to_frame (dpyinfo, event->xgraphicsexpose.drawable);
8083 if (f)
8085 expose_frame (f, event->xgraphicsexpose.x,
8086 event->xgraphicsexpose.y,
8087 event->xgraphicsexpose.width,
8088 event->xgraphicsexpose.height);
8089 #ifdef USE_GTK
8090 x_clear_under_internal_border (f);
8091 #endif
8092 show_back_buffer (f);
8094 #ifdef USE_X_TOOLKIT
8095 else
8096 goto OTHER;
8097 #endif /* USE_X_TOOLKIT */
8098 break;
8100 case NoExpose: /* This occurs when an XCopyArea's
8101 source area was completely
8102 available. */
8103 break;
8105 case UnmapNotify:
8106 /* Redo the mouse-highlight after the tooltip has gone. */
8107 if (event->xunmap.window == tip_window)
8109 tip_window = None;
8110 x_redo_mouse_highlight (dpyinfo);
8113 f = x_top_window_to_frame (dpyinfo, event->xunmap.window);
8114 if (f) /* F may no longer exist if
8115 the frame was deleted. */
8117 bool visible = FRAME_VISIBLE_P (f);
8118 /* While a frame is unmapped, display generation is
8119 disabled; you don't want to spend time updating a
8120 display that won't ever be seen. */
8121 SET_FRAME_VISIBLE (f, 0);
8122 /* We can't distinguish, from the event, whether the window
8123 has become iconified or invisible. So assume, if it
8124 was previously visible, than now it is iconified.
8125 But x_make_frame_invisible clears both
8126 the visible flag and the iconified flag;
8127 and that way, we know the window is not iconified now. */
8128 if (visible || FRAME_ICONIFIED_P (f))
8130 SET_FRAME_ICONIFIED (f, true);
8131 inev.ie.kind = ICONIFY_EVENT;
8132 XSETFRAME (inev.ie.frame_or_window, f);
8135 goto OTHER;
8137 case MapNotify:
8138 /* We use x_top_window_to_frame because map events can
8139 come for sub-windows and they don't mean that the
8140 frame is visible. */
8141 f = x_top_window_to_frame (dpyinfo, event->xmap.window);
8142 if (f)
8144 bool iconified = FRAME_ICONIFIED_P (f);
8146 /* Check if fullscreen was specified before we where mapped the
8147 first time, i.e. from the command line. */
8148 if (!f->output_data.x->has_been_visible)
8151 x_check_fullscreen (f);
8152 #ifndef USE_GTK
8153 /* For systems that cannot synthesize `skip_taskbar' for
8154 unmapped windows do the following. */
8155 if (FRAME_SKIP_TASKBAR (f))
8156 x_set_skip_taskbar (f, Qt, Qnil);
8157 #endif /* Not USE_GTK */
8160 if (!iconified)
8162 /* The `z-group' is reset every time a frame becomes
8163 invisible. Handle this here. */
8164 if (FRAME_Z_GROUP (f) == z_group_above)
8165 x_set_z_group (f, Qabove, Qnil);
8166 else if (FRAME_Z_GROUP (f) == z_group_below)
8167 x_set_z_group (f, Qbelow, Qnil);
8170 SET_FRAME_VISIBLE (f, 1);
8171 SET_FRAME_ICONIFIED (f, false);
8172 f->output_data.x->has_been_visible = true;
8174 if (iconified)
8176 inev.ie.kind = DEICONIFY_EVENT;
8177 XSETFRAME (inev.ie.frame_or_window, f);
8179 else if (! NILP (Vframe_list) && ! NILP (XCDR (Vframe_list)))
8180 /* Force a redisplay sooner or later to update the
8181 frame titles in case this is the second frame. */
8182 record_asynch_buffer_change ();
8184 goto OTHER;
8186 case KeyPress:
8188 x_display_set_last_user_time (dpyinfo, event->xkey.time);
8189 ignore_next_mouse_click_timeout = 0;
8191 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
8192 /* Dispatch KeyPress events when in menu. */
8193 if (popup_activated ())
8194 goto OTHER;
8195 #endif
8197 f = any;
8199 /* If mouse-highlight is an integer, input clears out
8200 mouse highlighting. */
8201 if (!hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight)
8202 #if ! defined (USE_GTK)
8203 && (f == 0
8204 || !EQ (f->tool_bar_window, hlinfo->mouse_face_window))
8205 #endif
8208 clear_mouse_face (hlinfo);
8209 hlinfo->mouse_face_hidden = true;
8212 #if defined USE_MOTIF && defined USE_TOOLKIT_SCROLL_BARS
8213 if (f == 0)
8215 /* Scroll bars consume key events, but we want
8216 the keys to go to the scroll bar's frame. */
8217 Widget widget = XtWindowToWidget (dpyinfo->display,
8218 event->xkey.window);
8219 if (widget && XmIsScrollBar (widget))
8221 widget = XtParent (widget);
8222 f = x_any_window_to_frame (dpyinfo, XtWindow (widget));
8225 #endif /* USE_MOTIF and USE_TOOLKIT_SCROLL_BARS */
8227 if (f != 0)
8229 KeySym keysym, orig_keysym;
8230 /* al%imercury@uunet.uu.net says that making this 81
8231 instead of 80 fixed a bug whereby meta chars made
8232 his Emacs hang.
8234 It seems that some version of XmbLookupString has
8235 a bug of not returning XBufferOverflow in
8236 status_return even if the input is too long to
8237 fit in 81 bytes. So, we must prepare sufficient
8238 bytes for copy_buffer. 513 bytes (256 chars for
8239 two-byte character set) seems to be a fairly good
8240 approximation. -- 2000.8.10 handa@etl.go.jp */
8241 unsigned char copy_buffer[513];
8242 unsigned char *copy_bufptr = copy_buffer;
8243 int copy_bufsiz = sizeof (copy_buffer);
8244 int modifiers;
8245 Lisp_Object coding_system = Qlatin_1;
8246 Lisp_Object c;
8247 /* Event will be modified. */
8248 XKeyEvent xkey = event->xkey;
8250 #ifdef USE_GTK
8251 /* Don't pass keys to GTK. A Tab will shift focus to the
8252 tool bar in GTK 2.4. Keys will still go to menus and
8253 dialogs because in that case popup_activated is nonzero
8254 (see above). */
8255 *finish = X_EVENT_DROP;
8256 #endif
8258 xkey.state |= x_emacs_to_x_modifiers (FRAME_DISPLAY_INFO (f),
8259 extra_keyboard_modifiers);
8260 modifiers = xkey.state;
8262 /* This will have to go some day... */
8264 /* make_lispy_event turns chars into control chars.
8265 Don't do it here because XLookupString is too eager. */
8266 xkey.state &= ~ControlMask;
8267 xkey.state &= ~(dpyinfo->meta_mod_mask
8268 | dpyinfo->super_mod_mask
8269 | dpyinfo->hyper_mod_mask
8270 | dpyinfo->alt_mod_mask);
8272 /* In case Meta is ComposeCharacter,
8273 clear its status. According to Markus Ehrnsperger
8274 Markus.Ehrnsperger@lehrstuhl-bross.physik.uni-muenchen.de
8275 this enables ComposeCharacter to work whether or
8276 not it is combined with Meta. */
8277 if (modifiers & dpyinfo->meta_mod_mask)
8278 memset (&compose_status, 0, sizeof (compose_status));
8280 #ifdef HAVE_X_I18N
8281 if (FRAME_XIC (f))
8283 Status status_return;
8285 coding_system = Vlocale_coding_system;
8286 nbytes = XmbLookupString (FRAME_XIC (f),
8287 &xkey, (char *) copy_bufptr,
8288 copy_bufsiz, &keysym,
8289 &status_return);
8290 if (status_return == XBufferOverflow)
8292 copy_bufsiz = nbytes + 1;
8293 copy_bufptr = alloca (copy_bufsiz);
8294 nbytes = XmbLookupString (FRAME_XIC (f),
8295 &xkey, (char *) copy_bufptr,
8296 copy_bufsiz, &keysym,
8297 &status_return);
8299 /* Xutf8LookupString is a new but already deprecated interface. -stef */
8300 if (status_return == XLookupNone)
8301 break;
8302 else if (status_return == XLookupChars)
8304 keysym = NoSymbol;
8305 modifiers = 0;
8307 else if (status_return != XLookupKeySym
8308 && status_return != XLookupBoth)
8309 emacs_abort ();
8311 else
8312 nbytes = XLookupString (&xkey, (char *) copy_bufptr,
8313 copy_bufsiz, &keysym,
8314 &compose_status);
8315 #else
8316 nbytes = XLookupString (&xkey, (char *) copy_bufptr,
8317 copy_bufsiz, &keysym,
8318 &compose_status);
8319 #endif
8321 /* If not using XIM/XIC, and a compose sequence is in progress,
8322 we break here. Otherwise, chars_matched is always 0. */
8323 if (compose_status.chars_matched > 0 && nbytes == 0)
8324 break;
8326 memset (&compose_status, 0, sizeof (compose_status));
8327 orig_keysym = keysym;
8329 /* Common for all keysym input events. */
8330 XSETFRAME (inev.ie.frame_or_window, f);
8331 inev.ie.modifiers
8332 = x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO (f), modifiers);
8333 inev.ie.timestamp = xkey.time;
8335 /* First deal with keysyms which have defined
8336 translations to characters. */
8337 if (keysym >= 32 && keysym < 128)
8338 /* Avoid explicitly decoding each ASCII character. */
8340 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
8341 inev.ie.code = keysym;
8342 goto done_keysym;
8345 /* Keysyms directly mapped to Unicode characters. */
8346 if (keysym >= 0x01000000 && keysym <= 0x0110FFFF)
8348 if (keysym < 0x01000080)
8349 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
8350 else
8351 inev.ie.kind = MULTIBYTE_CHAR_KEYSTROKE_EVENT;
8352 inev.ie.code = keysym & 0xFFFFFF;
8353 goto done_keysym;
8356 /* Now non-ASCII. */
8357 if (HASH_TABLE_P (Vx_keysym_table)
8358 && (c = Fgethash (make_number (keysym),
8359 Vx_keysym_table,
8360 Qnil),
8361 NATNUMP (c)))
8363 inev.ie.kind = (SINGLE_BYTE_CHAR_P (XFASTINT (c))
8364 ? ASCII_KEYSTROKE_EVENT
8365 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
8366 inev.ie.code = XFASTINT (c);
8367 goto done_keysym;
8370 /* Random non-modifier sorts of keysyms. */
8371 if (((keysym >= XK_BackSpace && keysym <= XK_Escape)
8372 || keysym == XK_Delete
8373 #ifdef XK_ISO_Left_Tab
8374 || (keysym >= XK_ISO_Left_Tab
8375 && keysym <= XK_ISO_Enter)
8376 #endif
8377 || IsCursorKey (keysym) /* 0xff50 <= x < 0xff60 */
8378 || IsMiscFunctionKey (keysym) /* 0xff60 <= x < VARIES */
8379 #ifdef HPUX
8380 /* This recognizes the "extended function
8381 keys". It seems there's no cleaner way.
8382 Test IsModifierKey to avoid handling
8383 mode_switch incorrectly. */
8384 || (XK_Select <= keysym && keysym < XK_KP_Space)
8385 #endif
8386 #ifdef XK_dead_circumflex
8387 || orig_keysym == XK_dead_circumflex
8388 #endif
8389 #ifdef XK_dead_grave
8390 || orig_keysym == XK_dead_grave
8391 #endif
8392 #ifdef XK_dead_tilde
8393 || orig_keysym == XK_dead_tilde
8394 #endif
8395 #ifdef XK_dead_diaeresis
8396 || orig_keysym == XK_dead_diaeresis
8397 #endif
8398 #ifdef XK_dead_macron
8399 || orig_keysym == XK_dead_macron
8400 #endif
8401 #ifdef XK_dead_degree
8402 || orig_keysym == XK_dead_degree
8403 #endif
8404 #ifdef XK_dead_acute
8405 || orig_keysym == XK_dead_acute
8406 #endif
8407 #ifdef XK_dead_cedilla
8408 || orig_keysym == XK_dead_cedilla
8409 #endif
8410 #ifdef XK_dead_breve
8411 || orig_keysym == XK_dead_breve
8412 #endif
8413 #ifdef XK_dead_ogonek
8414 || orig_keysym == XK_dead_ogonek
8415 #endif
8416 #ifdef XK_dead_caron
8417 || orig_keysym == XK_dead_caron
8418 #endif
8419 #ifdef XK_dead_doubleacute
8420 || orig_keysym == XK_dead_doubleacute
8421 #endif
8422 #ifdef XK_dead_abovedot
8423 || orig_keysym == XK_dead_abovedot
8424 #endif
8425 || IsKeypadKey (keysym) /* 0xff80 <= x < 0xffbe */
8426 || IsFunctionKey (keysym) /* 0xffbe <= x < 0xffe1 */
8427 /* Any "vendor-specific" key is ok. */
8428 || (orig_keysym & (1 << 28))
8429 || (keysym != NoSymbol && nbytes == 0))
8430 && ! (IsModifierKey (orig_keysym)
8431 /* The symbols from XK_ISO_Lock
8432 to XK_ISO_Last_Group_Lock
8433 don't have real modifiers but
8434 should be treated similarly to
8435 Mode_switch by Emacs. */
8436 #if defined XK_ISO_Lock && defined XK_ISO_Last_Group_Lock
8437 || (XK_ISO_Lock <= orig_keysym
8438 && orig_keysym <= XK_ISO_Last_Group_Lock)
8439 #endif
8442 STORE_KEYSYM_FOR_DEBUG (keysym);
8443 /* make_lispy_event will convert this to a symbolic
8444 key. */
8445 inev.ie.kind = NON_ASCII_KEYSTROKE_EVENT;
8446 inev.ie.code = keysym;
8447 goto done_keysym;
8450 { /* Raw bytes, not keysym. */
8451 ptrdiff_t i;
8452 int nchars, len;
8454 for (i = 0, nchars = 0; i < nbytes; i++)
8456 if (ASCII_CHAR_P (copy_bufptr[i]))
8457 nchars++;
8458 STORE_KEYSYM_FOR_DEBUG (copy_bufptr[i]);
8461 if (nchars < nbytes)
8463 /* Decode the input data. */
8465 /* The input should be decoded with `coding_system'
8466 which depends on which X*LookupString function
8467 we used just above and the locale. */
8468 setup_coding_system (coding_system, &coding);
8469 coding.src_multibyte = false;
8470 coding.dst_multibyte = true;
8471 /* The input is converted to events, thus we can't
8472 handle composition. Anyway, there's no XIM that
8473 gives us composition information. */
8474 coding.common_flags &= ~CODING_ANNOTATION_MASK;
8476 SAFE_NALLOCA (coding.destination, MAX_MULTIBYTE_LENGTH,
8477 nbytes);
8478 coding.dst_bytes = MAX_MULTIBYTE_LENGTH * nbytes;
8479 coding.mode |= CODING_MODE_LAST_BLOCK;
8480 decode_coding_c_string (&coding, copy_bufptr, nbytes, Qnil);
8481 nbytes = coding.produced;
8482 nchars = coding.produced_char;
8483 copy_bufptr = coding.destination;
8486 /* Convert the input data to a sequence of
8487 character events. */
8488 for (i = 0; i < nbytes; i += len)
8490 int ch;
8491 if (nchars == nbytes)
8492 ch = copy_bufptr[i], len = 1;
8493 else
8494 ch = STRING_CHAR_AND_LENGTH (copy_bufptr + i, len);
8495 inev.ie.kind = (SINGLE_BYTE_CHAR_P (ch)
8496 ? ASCII_KEYSTROKE_EVENT
8497 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
8498 inev.ie.code = ch;
8499 kbd_buffer_store_buffered_event (&inev, hold_quit);
8502 count += nchars;
8504 inev.ie.kind = NO_EVENT; /* Already stored above. */
8506 if (keysym == NoSymbol)
8507 break;
8509 /* FIXME: check side effects and remove this. */
8510 ((XEvent *) event)->xkey = xkey;
8512 done_keysym:
8513 #ifdef HAVE_X_I18N
8514 /* Don't dispatch this event since XtDispatchEvent calls
8515 XFilterEvent, and two calls in a row may freeze the
8516 client. */
8517 break;
8518 #else
8519 goto OTHER;
8520 #endif
8522 case KeyRelease:
8523 x_display_set_last_user_time (dpyinfo, event->xkey.time);
8524 #ifdef HAVE_X_I18N
8525 /* Don't dispatch this event since XtDispatchEvent calls
8526 XFilterEvent, and two calls in a row may freeze the
8527 client. */
8528 break;
8529 #else
8530 goto OTHER;
8531 #endif
8533 case EnterNotify:
8534 x_display_set_last_user_time (dpyinfo, event->xcrossing.time);
8535 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
8537 f = any;
8539 if (f && x_mouse_click_focus_ignore_position)
8540 ignore_next_mouse_click_timeout = event->xmotion.time + 200;
8542 /* EnterNotify counts as mouse movement,
8543 so update things that depend on mouse position. */
8544 if (f && !f->output_data.x->hourglass_p)
8545 note_mouse_movement (f, &event->xmotion);
8546 #ifdef USE_GTK
8547 /* We may get an EnterNotify on the buttons in the toolbar. In that
8548 case we moved out of any highlighted area and need to note this. */
8549 if (!f && dpyinfo->last_mouse_glyph_frame)
8550 note_mouse_movement (dpyinfo->last_mouse_glyph_frame, &event->xmotion);
8551 #endif
8552 goto OTHER;
8554 case FocusIn:
8555 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
8556 goto OTHER;
8558 case LeaveNotify:
8559 x_display_set_last_user_time (dpyinfo, event->xcrossing.time);
8560 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
8562 f = x_top_window_to_frame (dpyinfo, event->xcrossing.window);
8563 if (f)
8565 if (f == hlinfo->mouse_face_mouse_frame)
8567 /* If we move outside the frame, then we're
8568 certainly no longer on any text in the frame. */
8569 clear_mouse_face (hlinfo);
8570 hlinfo->mouse_face_mouse_frame = 0;
8573 /* Generate a nil HELP_EVENT to cancel a help-echo.
8574 Do it only if there's something to cancel.
8575 Otherwise, the startup message is cleared when
8576 the mouse leaves the frame. */
8577 if (any_help_event_p)
8578 do_help = -1;
8580 #ifdef USE_GTK
8581 /* See comment in EnterNotify above */
8582 else if (dpyinfo->last_mouse_glyph_frame)
8583 note_mouse_movement (dpyinfo->last_mouse_glyph_frame, &event->xmotion);
8584 #endif
8585 goto OTHER;
8587 case FocusOut:
8588 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
8589 goto OTHER;
8591 case MotionNotify:
8593 x_display_set_last_user_time (dpyinfo, event->xmotion.time);
8594 previous_help_echo_string = help_echo_string;
8595 help_echo_string = Qnil;
8597 f = (x_mouse_grabbed (dpyinfo) ? dpyinfo->last_mouse_frame
8598 : x_window_to_frame (dpyinfo, event->xmotion.window));
8600 if (hlinfo->mouse_face_hidden)
8602 hlinfo->mouse_face_hidden = false;
8603 clear_mouse_face (hlinfo);
8606 #ifdef USE_GTK
8607 if (f && xg_event_is_for_scrollbar (f, event))
8608 f = 0;
8609 #endif
8610 if (f)
8612 /* Maybe generate a SELECT_WINDOW_EVENT for
8613 `mouse-autoselect-window' but don't let popup menus
8614 interfere with this (Bug#1261). */
8615 if (!NILP (Vmouse_autoselect_window)
8616 && !popup_activated ()
8617 /* Don't switch if we're currently in the minibuffer.
8618 This tries to work around problems where the
8619 minibuffer gets unselected unexpectedly, and where
8620 you then have to move your mouse all the way down to
8621 the minibuffer to select it. */
8622 && !MINI_WINDOW_P (XWINDOW (selected_window))
8623 /* With `focus-follows-mouse' non-nil create an event
8624 also when the target window is on another frame. */
8625 && (f == XFRAME (selected_frame)
8626 || !NILP (focus_follows_mouse)))
8628 static Lisp_Object last_mouse_window;
8629 Lisp_Object window = window_from_coordinates
8630 (f, event->xmotion.x, event->xmotion.y, 0, false);
8632 /* A window will be autoselected only when it is not
8633 selected now and the last mouse movement event was
8634 not in it. The remainder of the code is a bit vague
8635 wrt what a "window" is. For immediate autoselection,
8636 the window is usually the entire window but for GTK
8637 where the scroll bars don't count. For delayed
8638 autoselection the window is usually the window's text
8639 area including the margins. */
8640 if (WINDOWP (window)
8641 && !EQ (window, last_mouse_window)
8642 && !EQ (window, selected_window))
8644 inev.ie.kind = SELECT_WINDOW_EVENT;
8645 inev.ie.frame_or_window = window;
8648 /* Remember the last window where we saw the mouse. */
8649 last_mouse_window = window;
8652 if (!note_mouse_movement (f, &event->xmotion))
8653 help_echo_string = previous_help_echo_string;
8655 else
8657 #ifndef USE_TOOLKIT_SCROLL_BARS
8658 struct scroll_bar *bar
8659 = x_window_to_scroll_bar (event->xmotion.display,
8660 event->xmotion.window, 2);
8662 if (bar)
8663 x_scroll_bar_note_movement (bar, &event->xmotion);
8664 #endif /* USE_TOOLKIT_SCROLL_BARS */
8666 /* If we move outside the frame, then we're
8667 certainly no longer on any text in the frame. */
8668 clear_mouse_face (hlinfo);
8671 /* If the contents of the global variable help_echo_string
8672 has changed, generate a HELP_EVENT. */
8673 if (!NILP (help_echo_string)
8674 || !NILP (previous_help_echo_string))
8675 do_help = 1;
8676 goto OTHER;
8679 case ConfigureNotify:
8680 /* An opaque move can generate a stream of events as the window
8681 is dragged around. If the connection round trip time isn't
8682 really short, they may come faster than we can respond to
8683 them, given the multiple queries we can do to check window
8684 manager state, translate coordinates, etc.
8686 So if this ConfigureNotify is immediately followed by another
8687 for the same window, use the info from the latest update, and
8688 consider the events all handled. */
8689 /* Opaque resize may be trickier; ConfigureNotify events are
8690 mixed with Expose events for multiple windows. */
8691 configureEvent = *event;
8692 while (XPending (dpyinfo->display))
8694 XNextEvent (dpyinfo->display, &next_event);
8695 if (next_event.type != ConfigureNotify
8696 || next_event.xconfigure.window != event->xconfigure.window
8697 /* Skipping events with different sizes can lead to a
8698 mispositioned mode line at initial window creation.
8699 Only drop window motion events for now. */
8700 || next_event.xconfigure.width != event->xconfigure.width
8701 || next_event.xconfigure.height != event->xconfigure.height)
8703 XPutBackEvent (dpyinfo->display, &next_event);
8704 break;
8706 else
8707 configureEvent = next_event;
8710 f = x_top_window_to_frame (dpyinfo, configureEvent.xconfigure.window);
8711 /* Unfortunately, we need to call font_drop_xrender_surfaces for
8712 _all_ ConfigureNotify events, otherwise we miss some and
8713 flicker. Don't try to optimize these calls by looking only
8714 for size changes: that's not sufficient. We miss some
8715 surface invalidations and flicker. */
8716 block_input ();
8717 if (f && FRAME_X_DOUBLE_BUFFERED_P (f))
8718 font_drop_xrender_surfaces (f);
8719 unblock_input ();
8720 #ifdef USE_CAIRO
8721 if (f) x_cr_destroy_surface (f);
8722 #endif
8723 #ifdef USE_GTK
8724 if (!f
8725 && (f = any)
8726 && configureEvent.xconfigure.window == FRAME_X_WINDOW (f))
8728 block_input ();
8729 if (FRAME_X_DOUBLE_BUFFERED_P (f))
8730 font_drop_xrender_surfaces (f);
8731 unblock_input ();
8732 xg_frame_resized (f, configureEvent.xconfigure.width,
8733 configureEvent.xconfigure.height);
8734 #ifdef USE_CAIRO
8735 x_cr_destroy_surface (f);
8736 #endif
8737 f = 0;
8739 #endif
8740 if (f)
8742 #ifdef USE_GTK
8743 /* For GTK+ don't call x_net_wm_state for the scroll bar
8744 window. (Bug#24963, Bug#25887) */
8745 if (configureEvent.xconfigure.window == FRAME_X_WINDOW (f))
8746 #endif
8747 x_net_wm_state (f, configureEvent.xconfigure.window);
8749 #ifdef USE_X_TOOLKIT
8750 /* Tip frames are pure X window, set size for them. */
8751 if (FRAME_TOOLTIP_P (f))
8753 if (FRAME_PIXEL_HEIGHT (f) != configureEvent.xconfigure.height
8754 || FRAME_PIXEL_WIDTH (f) != configureEvent.xconfigure.width)
8756 SET_FRAME_GARBAGED (f);
8758 FRAME_PIXEL_HEIGHT (f) = configureEvent.xconfigure.height;
8759 FRAME_PIXEL_WIDTH (f) = configureEvent.xconfigure.width;
8761 #endif
8763 #ifndef USE_X_TOOLKIT
8764 #ifndef USE_GTK
8765 int width =
8766 FRAME_PIXEL_TO_TEXT_WIDTH (f, configureEvent.xconfigure.width);
8767 int height =
8768 FRAME_PIXEL_TO_TEXT_HEIGHT (f, configureEvent.xconfigure.height);
8770 /* In the toolkit version, change_frame_size
8771 is called by the code that handles resizing
8772 of the EmacsFrame widget. */
8774 /* Even if the number of character rows and columns has
8775 not changed, the font size may have changed, so we need
8776 to check the pixel dimensions as well. */
8777 if (width != FRAME_TEXT_WIDTH (f)
8778 || height != FRAME_TEXT_HEIGHT (f)
8779 || configureEvent.xconfigure.width != FRAME_PIXEL_WIDTH (f)
8780 || configureEvent.xconfigure.height != FRAME_PIXEL_HEIGHT (f))
8782 change_frame_size (f, width, height, false, true, false, true);
8783 x_clear_under_internal_border (f);
8784 SET_FRAME_GARBAGED (f);
8785 cancel_mouse_face (f);
8787 #endif /* not USE_GTK */
8788 #endif
8790 #ifdef USE_GTK
8791 /* GTK creates windows but doesn't map them.
8792 Only get real positions when mapped. */
8793 if (FRAME_GTK_OUTER_WIDGET (f)
8794 && gtk_widget_get_mapped (FRAME_GTK_OUTER_WIDGET (f)))
8795 #endif
8797 int old_left = f->left_pos;
8798 int old_top = f->top_pos;
8799 Lisp_Object frame = Qnil;
8801 XSETFRAME (frame, f);
8803 if (!FRAME_PARENT_FRAME (f))
8804 x_real_positions (f, &f->left_pos, &f->top_pos);
8805 else
8807 Window root;
8808 unsigned int dummy_uint;
8810 block_input ();
8811 XGetGeometry (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8812 &root, &f->left_pos, &f->top_pos,
8813 &dummy_uint, &dummy_uint, &dummy_uint, &dummy_uint);
8814 unblock_input ();
8817 if (old_left != f->left_pos || old_top != f->top_pos)
8819 inev.ie.kind = MOVE_FRAME_EVENT;
8820 XSETFRAME (inev.ie.frame_or_window, f);
8825 #ifdef HAVE_X_I18N
8826 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMStatusArea))
8827 xic_set_statusarea (f);
8828 #endif
8831 goto OTHER;
8833 case ButtonRelease:
8834 case ButtonPress:
8836 /* If we decide we want to generate an event to be seen
8837 by the rest of Emacs, we put it here. */
8838 bool tool_bar_p = false;
8840 memset (&compose_status, 0, sizeof (compose_status));
8841 dpyinfo->last_mouse_glyph_frame = NULL;
8842 x_display_set_last_user_time (dpyinfo, event->xbutton.time);
8844 if (x_mouse_grabbed (dpyinfo))
8845 f = dpyinfo->last_mouse_frame;
8846 else
8848 f = x_window_to_frame (dpyinfo, event->xbutton.window);
8850 if (f && event->xbutton.type == ButtonPress
8851 && !popup_activated ()
8852 && !x_window_to_scroll_bar (event->xbutton.display,
8853 event->xbutton.window, 2)
8854 && !FRAME_NO_ACCEPT_FOCUS (f))
8856 /* When clicking into a child frame or when clicking
8857 into a parent frame with the child frame selected and
8858 `no-accept-focus' is not set, select the clicked
8859 frame. */
8860 struct frame *hf = dpyinfo->x_highlight_frame;
8862 if (FRAME_PARENT_FRAME (f) || (hf && frame_ancestor_p (f, hf)))
8864 block_input ();
8865 XSetInputFocus (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8866 RevertToParent, CurrentTime);
8867 if (FRAME_PARENT_FRAME (f))
8868 XRaiseWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
8869 unblock_input ();
8874 #ifdef USE_GTK
8875 if (f && xg_event_is_for_scrollbar (f, event))
8876 f = 0;
8877 #endif
8878 if (f)
8880 #if ! defined (USE_GTK)
8881 /* Is this in the tool-bar? */
8882 if (WINDOWP (f->tool_bar_window)
8883 && WINDOW_TOTAL_LINES (XWINDOW (f->tool_bar_window)))
8885 Lisp_Object window;
8886 int x = event->xbutton.x;
8887 int y = event->xbutton.y;
8889 window = window_from_coordinates (f, x, y, 0, true);
8890 tool_bar_p = EQ (window, f->tool_bar_window);
8892 if (tool_bar_p && event->xbutton.button < 4)
8893 handle_tool_bar_click
8894 (f, x, y, event->xbutton.type == ButtonPress,
8895 x_x_to_emacs_modifiers (dpyinfo, event->xbutton.state));
8897 #endif /* !USE_GTK */
8899 if (!tool_bar_p)
8900 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
8901 if (! popup_activated ())
8902 #endif
8904 if (ignore_next_mouse_click_timeout)
8906 if (event->type == ButtonPress
8907 && event->xbutton.time > ignore_next_mouse_click_timeout)
8909 ignore_next_mouse_click_timeout = 0;
8910 construct_mouse_click (&inev.ie, &event->xbutton, f);
8912 if (event->type == ButtonRelease)
8913 ignore_next_mouse_click_timeout = 0;
8915 else
8916 construct_mouse_click (&inev.ie, &event->xbutton, f);
8918 if (FRAME_X_EMBEDDED_P (f))
8919 xembed_send_message (f, event->xbutton.time,
8920 XEMBED_REQUEST_FOCUS, 0, 0, 0);
8922 else
8924 struct scroll_bar *bar
8925 = x_window_to_scroll_bar (event->xbutton.display,
8926 event->xbutton.window, 2);
8928 #ifdef USE_TOOLKIT_SCROLL_BARS
8929 /* Make the "Ctrl-Mouse-2 splits window" work for toolkit
8930 scroll bars. */
8931 if (bar && event->xbutton.state & ControlMask)
8933 x_scroll_bar_handle_click (bar, event, &inev.ie);
8934 *finish = X_EVENT_DROP;
8936 #else /* not USE_TOOLKIT_SCROLL_BARS */
8937 if (bar)
8938 x_scroll_bar_handle_click (bar, event, &inev.ie);
8939 #endif /* not USE_TOOLKIT_SCROLL_BARS */
8942 if (event->type == ButtonPress)
8944 dpyinfo->grabbed |= (1 << event->xbutton.button);
8945 dpyinfo->last_mouse_frame = f;
8946 #if ! defined (USE_GTK)
8947 if (f && !tool_bar_p)
8948 f->last_tool_bar_item = -1;
8949 #endif /* not USE_GTK */
8951 else
8952 dpyinfo->grabbed &= ~(1 << event->xbutton.button);
8954 /* Ignore any mouse motion that happened before this event;
8955 any subsequent mouse-movement Emacs events should reflect
8956 only motion after the ButtonPress/Release. */
8957 if (f != 0)
8958 f->mouse_moved = false;
8960 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
8961 f = x_menubar_window_to_frame (dpyinfo, event);
8962 /* For a down-event in the menu bar,
8963 don't pass it to Xt right now.
8964 Instead, save it away
8965 and we will pass it to Xt from kbd_buffer_get_event.
8966 That way, we can run some Lisp code first. */
8967 if (! popup_activated ()
8968 #ifdef USE_GTK
8969 /* Gtk+ menus only react to the first three buttons. */
8970 && event->xbutton.button < 3
8971 #endif
8972 && f && event->type == ButtonPress
8973 /* Verify the event is really within the menu bar
8974 and not just sent to it due to grabbing. */
8975 && event->xbutton.x >= 0
8976 && event->xbutton.x < FRAME_PIXEL_WIDTH (f)
8977 && event->xbutton.y >= 0
8978 && event->xbutton.y < FRAME_MENUBAR_HEIGHT (f)
8979 && event->xbutton.same_screen)
8981 if (!f->output_data.x->saved_menu_event)
8982 f->output_data.x->saved_menu_event = xmalloc (sizeof *event);
8983 *f->output_data.x->saved_menu_event = *event;
8984 inev.ie.kind = MENU_BAR_ACTIVATE_EVENT;
8985 XSETFRAME (inev.ie.frame_or_window, f);
8986 *finish = X_EVENT_DROP;
8988 else
8989 goto OTHER;
8990 #endif /* USE_X_TOOLKIT || USE_GTK */
8992 break;
8994 case CirculateNotify:
8995 goto OTHER;
8997 case CirculateRequest:
8998 goto OTHER;
9000 case VisibilityNotify:
9001 goto OTHER;
9003 case MappingNotify:
9004 /* Someone has changed the keyboard mapping - update the
9005 local cache. */
9006 switch (event->xmapping.request)
9008 case MappingModifier:
9009 x_find_modifier_meanings (dpyinfo);
9010 FALLTHROUGH;
9011 case MappingKeyboard:
9012 XRefreshKeyboardMapping ((XMappingEvent *) &event->xmapping);
9014 goto OTHER;
9016 case DestroyNotify:
9017 xft_settings_event (dpyinfo, event);
9018 break;
9020 default:
9021 OTHER:
9022 #ifdef USE_X_TOOLKIT
9023 block_input ();
9024 if (*finish != X_EVENT_DROP)
9025 XtDispatchEvent ((XEvent *) event);
9026 unblock_input ();
9027 #endif /* USE_X_TOOLKIT */
9028 break;
9031 done:
9032 if (inev.ie.kind != NO_EVENT)
9034 kbd_buffer_store_buffered_event (&inev, hold_quit);
9035 count++;
9038 if (do_help
9039 && !(hold_quit && hold_quit->kind != NO_EVENT))
9041 Lisp_Object frame;
9043 if (f)
9044 XSETFRAME (frame, f);
9045 else
9046 frame = Qnil;
9048 if (do_help > 0)
9050 any_help_event_p = true;
9051 gen_help_event (help_echo_string, frame, help_echo_window,
9052 help_echo_object, help_echo_pos);
9054 else
9056 help_echo_string = Qnil;
9057 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
9059 count++;
9062 /* Sometimes event processing draws to the frame outside redisplay.
9063 To ensure that these changes become visible, draw them here. */
9064 flush_dirty_back_buffers ();
9065 SAFE_FREE ();
9066 return count;
9069 #if defined USE_X_TOOLKIT || defined USE_MOTIF || defined USE_GTK
9071 /* Handles the XEvent EVENT on display DISPLAY.
9072 This is used for event loops outside the normal event handling,
9073 i.e. looping while a popup menu or a dialog is posted.
9075 Returns the value handle_one_xevent sets in the finish argument. */
9077 x_dispatch_event (XEvent *event, Display *display)
9079 struct x_display_info *dpyinfo;
9080 int finish = X_EVENT_NORMAL;
9082 dpyinfo = x_display_info_for_display (display);
9084 if (dpyinfo)
9085 handle_one_xevent (dpyinfo, event, &finish, 0);
9087 return finish;
9089 #endif
9091 /* Read events coming from the X server.
9092 Return as soon as there are no more events to be read.
9094 Return the number of characters stored into the buffer,
9095 thus pretending to be `read' (except the characters we store
9096 in the keyboard buffer can be multibyte, so are not necessarily
9097 C chars). */
9099 static int
9100 XTread_socket (struct terminal *terminal, struct input_event *hold_quit)
9102 int count = 0;
9103 bool event_found = false;
9104 struct x_display_info *dpyinfo = terminal->display_info.x;
9106 block_input ();
9108 /* For debugging, this gives a way to fake an I/O error. */
9109 if (dpyinfo == XTread_socket_fake_io_error)
9111 XTread_socket_fake_io_error = 0;
9112 x_io_error_quitter (dpyinfo->display);
9115 #ifndef USE_GTK
9116 while (XPending (dpyinfo->display))
9118 int finish;
9119 XEvent event;
9121 XNextEvent (dpyinfo->display, &event);
9123 #ifdef HAVE_X_I18N
9124 /* Filter events for the current X input method. */
9125 if (x_filter_event (dpyinfo, &event))
9126 continue;
9127 #endif
9128 event_found = true;
9130 count += handle_one_xevent (dpyinfo, &event, &finish, hold_quit);
9132 if (finish == X_EVENT_GOTO_OUT)
9133 break;
9136 #else /* USE_GTK */
9138 /* For GTK we must use the GTK event loop. But XEvents gets passed
9139 to our filter function above, and then to the big event switch.
9140 We use a bunch of globals to communicate with our filter function,
9141 that is kind of ugly, but it works.
9143 There is no way to do one display at the time, GTK just does events
9144 from all displays. */
9146 while (gtk_events_pending ())
9148 current_count = count;
9149 current_hold_quit = hold_quit;
9151 gtk_main_iteration ();
9153 count = current_count;
9154 current_count = -1;
9155 current_hold_quit = 0;
9157 if (current_finish == X_EVENT_GOTO_OUT)
9158 break;
9160 #endif /* USE_GTK */
9162 /* On some systems, an X bug causes Emacs to get no more events
9163 when the window is destroyed. Detect that. (1994.) */
9164 if (! event_found)
9166 /* Emacs and the X Server eats up CPU time if XNoOp is done every time.
9167 One XNOOP in 100 loops will make Emacs terminate.
9168 B. Bretthauer, 1994 */
9169 x_noop_count++;
9170 if (x_noop_count >= 100)
9172 x_noop_count=0;
9174 if (next_noop_dpyinfo == 0)
9175 next_noop_dpyinfo = x_display_list;
9177 XNoOp (next_noop_dpyinfo->display);
9179 /* Each time we get here, cycle through the displays now open. */
9180 next_noop_dpyinfo = next_noop_dpyinfo->next;
9184 /* If the focus was just given to an auto-raising frame,
9185 raise it now. FIXME: handle more than one such frame. */
9186 if (dpyinfo->x_pending_autoraise_frame)
9188 x_raise_frame (dpyinfo->x_pending_autoraise_frame);
9189 dpyinfo->x_pending_autoraise_frame = NULL;
9192 unblock_input ();
9194 return count;
9200 /***********************************************************************
9201 Text Cursor
9202 ***********************************************************************/
9204 /* Set clipping for output in glyph row ROW. W is the window in which
9205 we operate. GC is the graphics context to set clipping in.
9207 ROW may be a text row or, e.g., a mode line. Text rows must be
9208 clipped to the interior of the window dedicated to text display,
9209 mode lines must be clipped to the whole window. */
9211 static void
9212 x_clip_to_row (struct window *w, struct glyph_row *row,
9213 enum glyph_row_area area, GC gc)
9215 struct frame *f = XFRAME (WINDOW_FRAME (w));
9216 XRectangle clip_rect;
9217 int window_x, window_y, window_width;
9219 window_box (w, area, &window_x, &window_y, &window_width, 0);
9221 clip_rect.x = window_x;
9222 clip_rect.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
9223 clip_rect.y = max (clip_rect.y, window_y);
9224 clip_rect.width = window_width;
9225 clip_rect.height = row->visible_height;
9227 x_set_clip_rectangles (f, gc, &clip_rect, 1);
9231 /* Draw a hollow box cursor on window W in glyph row ROW. */
9233 static void
9234 x_draw_hollow_cursor (struct window *w, struct glyph_row *row)
9236 struct frame *f = XFRAME (WINDOW_FRAME (w));
9237 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
9238 Display *dpy = FRAME_X_DISPLAY (f);
9239 int x, y, wd, h;
9240 XGCValues xgcv;
9241 struct glyph *cursor_glyph;
9242 GC gc;
9244 /* Get the glyph the cursor is on. If we can't tell because
9245 the current matrix is invalid or such, give up. */
9246 cursor_glyph = get_phys_cursor_glyph (w);
9247 if (cursor_glyph == NULL)
9248 return;
9250 /* Compute frame-relative coordinates for phys cursor. */
9251 get_phys_cursor_geometry (w, row, cursor_glyph, &x, &y, &h);
9252 wd = w->phys_cursor_width - 1;
9254 /* The foreground of cursor_gc is typically the same as the normal
9255 background color, which can cause the cursor box to be invisible. */
9256 xgcv.foreground = f->output_data.x->cursor_pixel;
9257 if (dpyinfo->scratch_cursor_gc)
9258 XChangeGC (dpy, dpyinfo->scratch_cursor_gc, GCForeground, &xgcv);
9259 else
9260 dpyinfo->scratch_cursor_gc = XCreateGC (dpy, FRAME_X_DRAWABLE (f),
9261 GCForeground, &xgcv);
9262 gc = dpyinfo->scratch_cursor_gc;
9264 /* When on R2L character, show cursor at the right edge of the
9265 glyph, unless the cursor box is as wide as the glyph or wider
9266 (the latter happens when x-stretch-cursor is non-nil). */
9267 if ((cursor_glyph->resolved_level & 1) != 0
9268 && cursor_glyph->pixel_width > wd)
9270 x += cursor_glyph->pixel_width - wd;
9271 if (wd > 0)
9272 wd -= 1;
9274 /* Set clipping, draw the rectangle, and reset clipping again. */
9275 x_clip_to_row (w, row, TEXT_AREA, gc);
9276 x_draw_rectangle (f, gc, x, y, wd, h - 1);
9277 x_reset_clip_rectangles (f, gc);
9281 /* Draw a bar cursor on window W in glyph row ROW.
9283 Implementation note: One would like to draw a bar cursor with an
9284 angle equal to the one given by the font property XA_ITALIC_ANGLE.
9285 Unfortunately, I didn't find a font yet that has this property set.
9286 --gerd. */
9288 static void
9289 x_draw_bar_cursor (struct window *w, struct glyph_row *row, int width, enum text_cursor_kinds kind)
9291 struct frame *f = XFRAME (w->frame);
9292 struct glyph *cursor_glyph;
9294 /* If cursor is out of bounds, don't draw garbage. This can happen
9295 in mini-buffer windows when switching between echo area glyphs
9296 and mini-buffer. */
9297 cursor_glyph = get_phys_cursor_glyph (w);
9298 if (cursor_glyph == NULL)
9299 return;
9301 /* Experimental avoidance of cursor on xwidget. */
9302 if (cursor_glyph->type == XWIDGET_GLYPH)
9303 return;
9305 /* If on an image, draw like a normal cursor. That's usually better
9306 visible than drawing a bar, esp. if the image is large so that
9307 the bar might not be in the window. */
9308 if (cursor_glyph->type == IMAGE_GLYPH)
9310 struct glyph_row *r;
9311 r = MATRIX_ROW (w->current_matrix, w->phys_cursor.vpos);
9312 draw_phys_cursor_glyph (w, r, DRAW_CURSOR);
9314 else
9316 Display *dpy = FRAME_X_DISPLAY (f);
9317 Drawable drawable = FRAME_X_DRAWABLE (f);
9318 GC gc = FRAME_DISPLAY_INFO (f)->scratch_cursor_gc;
9319 unsigned long mask = GCForeground | GCBackground | GCGraphicsExposures;
9320 struct face *face = FACE_FROM_ID (f, cursor_glyph->face_id);
9321 XGCValues xgcv;
9323 /* If the glyph's background equals the color we normally draw
9324 the bars cursor in, the bar cursor in its normal color is
9325 invisible. Use the glyph's foreground color instead in this
9326 case, on the assumption that the glyph's colors are chosen so
9327 that the glyph is legible. */
9328 if (face->background == f->output_data.x->cursor_pixel)
9329 xgcv.background = xgcv.foreground = face->foreground;
9330 else
9331 xgcv.background = xgcv.foreground = f->output_data.x->cursor_pixel;
9332 xgcv.graphics_exposures = False;
9334 if (gc)
9335 XChangeGC (dpy, gc, mask, &xgcv);
9336 else
9338 gc = XCreateGC (dpy, drawable, mask, &xgcv);
9339 FRAME_DISPLAY_INFO (f)->scratch_cursor_gc = gc;
9342 x_clip_to_row (w, row, TEXT_AREA, gc);
9344 if (kind == BAR_CURSOR)
9346 int x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
9348 if (width < 0)
9349 width = FRAME_CURSOR_WIDTH (f);
9350 width = min (cursor_glyph->pixel_width, width);
9352 w->phys_cursor_width = width;
9354 /* If the character under cursor is R2L, draw the bar cursor
9355 on the right of its glyph, rather than on the left. */
9356 if ((cursor_glyph->resolved_level & 1) != 0)
9357 x += cursor_glyph->pixel_width - width;
9359 x_fill_rectangle (f, gc, x,
9360 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y),
9361 width, row->height);
9363 else /* HBAR_CURSOR */
9365 int dummy_x, dummy_y, dummy_h;
9366 int x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
9368 if (width < 0)
9369 width = row->height;
9371 width = min (row->height, width);
9373 get_phys_cursor_geometry (w, row, cursor_glyph, &dummy_x,
9374 &dummy_y, &dummy_h);
9376 if ((cursor_glyph->resolved_level & 1) != 0
9377 && cursor_glyph->pixel_width > w->phys_cursor_width - 1)
9378 x += cursor_glyph->pixel_width - w->phys_cursor_width + 1;
9379 x_fill_rectangle (f, gc, x,
9380 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y +
9381 row->height - width),
9382 w->phys_cursor_width - 1, width);
9385 x_reset_clip_rectangles (f, gc);
9390 /* RIF: Define cursor CURSOR on frame F. */
9392 static void
9393 x_define_frame_cursor (struct frame *f, Cursor cursor)
9395 if (!f->pointer_invisible
9396 && f->output_data.x->current_cursor != cursor)
9397 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), cursor);
9398 f->output_data.x->current_cursor = cursor;
9402 /* RIF: Clear area on frame F. */
9404 static void
9405 x_clear_frame_area (struct frame *f, int x, int y, int width, int height)
9407 x_clear_area (f, x, y, width, height);
9411 /* RIF: Draw cursor on window W. */
9413 static void
9414 x_draw_window_cursor (struct window *w, struct glyph_row *glyph_row, int x,
9415 int y, enum text_cursor_kinds cursor_type,
9416 int cursor_width, bool on_p, bool active_p)
9418 struct frame *f = XFRAME (WINDOW_FRAME (w));
9420 if (on_p)
9422 w->phys_cursor_type = cursor_type;
9423 w->phys_cursor_on_p = true;
9425 if (glyph_row->exact_window_width_line_p
9426 && (glyph_row->reversed_p
9427 ? (w->phys_cursor.hpos < 0)
9428 : (w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])))
9430 glyph_row->cursor_in_fringe_p = true;
9431 draw_fringe_bitmap (w, glyph_row, glyph_row->reversed_p);
9433 else
9435 switch (cursor_type)
9437 case HOLLOW_BOX_CURSOR:
9438 x_draw_hollow_cursor (w, glyph_row);
9439 break;
9441 case FILLED_BOX_CURSOR:
9442 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
9443 break;
9445 case BAR_CURSOR:
9446 x_draw_bar_cursor (w, glyph_row, cursor_width, BAR_CURSOR);
9447 break;
9449 case HBAR_CURSOR:
9450 x_draw_bar_cursor (w, glyph_row, cursor_width, HBAR_CURSOR);
9451 break;
9453 case NO_CURSOR:
9454 w->phys_cursor_width = 0;
9455 break;
9457 default:
9458 emacs_abort ();
9462 #ifdef HAVE_X_I18N
9463 if (w == XWINDOW (f->selected_window))
9464 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMPreeditPosition))
9465 xic_set_preeditarea (w, x, y);
9466 #endif
9469 XFlush (FRAME_X_DISPLAY (f));
9473 /* Icons. */
9475 /* Make the x-window of frame F use the gnu icon bitmap. */
9477 bool
9478 x_bitmap_icon (struct frame *f, Lisp_Object file)
9480 ptrdiff_t bitmap_id;
9482 if (FRAME_X_WINDOW (f) == 0)
9483 return true;
9485 /* Free up our existing icon bitmap and mask if any. */
9486 if (f->output_data.x->icon_bitmap > 0)
9487 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
9488 f->output_data.x->icon_bitmap = 0;
9490 if (STRINGP (file))
9492 #ifdef USE_GTK
9493 /* Use gtk_window_set_icon_from_file () if available,
9494 It's not restricted to bitmaps */
9495 if (xg_set_icon (f, file))
9496 return false;
9497 #endif /* USE_GTK */
9498 bitmap_id = x_create_bitmap_from_file (f, file);
9499 x_create_bitmap_mask (f, bitmap_id);
9501 else
9503 /* Create the GNU bitmap and mask if necessary. */
9504 if (FRAME_DISPLAY_INFO (f)->icon_bitmap_id < 0)
9506 ptrdiff_t rc = -1;
9508 #ifdef USE_GTK
9510 if (xg_set_icon (f, xg_default_icon_file)
9511 || xg_set_icon_from_xpm_data (f, gnu_xpm_bits))
9513 FRAME_DISPLAY_INFO (f)->icon_bitmap_id = -2;
9514 return false;
9517 #elif defined (HAVE_XPM) && defined (HAVE_X_WINDOWS)
9519 rc = x_create_bitmap_from_xpm_data (f, gnu_xpm_bits);
9520 if (rc != -1)
9521 FRAME_DISPLAY_INFO (f)->icon_bitmap_id = rc;
9523 #endif
9525 /* If all else fails, use the (black and white) xbm image. */
9526 if (rc == -1)
9528 rc = x_create_bitmap_from_data (f, (char *) gnu_xbm_bits,
9529 gnu_xbm_width, gnu_xbm_height);
9530 if (rc == -1)
9531 return true;
9533 FRAME_DISPLAY_INFO (f)->icon_bitmap_id = rc;
9534 x_create_bitmap_mask (f, FRAME_DISPLAY_INFO (f)->icon_bitmap_id);
9538 /* The first time we create the GNU bitmap and mask,
9539 this increments the ref-count one extra time.
9540 As a result, the GNU bitmap and mask are never freed.
9541 That way, we don't have to worry about allocating it again. */
9542 x_reference_bitmap (f, FRAME_DISPLAY_INFO (f)->icon_bitmap_id);
9544 bitmap_id = FRAME_DISPLAY_INFO (f)->icon_bitmap_id;
9547 x_wm_set_icon_pixmap (f, bitmap_id);
9548 f->output_data.x->icon_bitmap = bitmap_id;
9550 return false;
9554 /* Make the x-window of frame F use a rectangle with text.
9555 Use ICON_NAME as the text. */
9557 bool
9558 x_text_icon (struct frame *f, const char *icon_name)
9560 if (FRAME_X_WINDOW (f) == 0)
9561 return true;
9564 XTextProperty text;
9565 text.value = (unsigned char *) icon_name;
9566 text.encoding = XA_STRING;
9567 text.format = 8;
9568 text.nitems = strlen (icon_name);
9569 XSetWMIconName (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f), &text);
9572 if (f->output_data.x->icon_bitmap > 0)
9573 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
9574 f->output_data.x->icon_bitmap = 0;
9575 x_wm_set_icon_pixmap (f, 0);
9577 return false;
9580 #define X_ERROR_MESSAGE_SIZE 200
9582 /* If non-nil, this should be a string.
9583 It means catch X errors and store the error message in this string.
9585 The reason we use a stack is that x_catch_error/x_uncatch_error can
9586 be called from a signal handler.
9589 struct x_error_message_stack {
9590 char string[X_ERROR_MESSAGE_SIZE];
9591 Display *dpy;
9592 x_special_error_handler handler;
9593 void *handler_data;
9594 struct x_error_message_stack *prev;
9596 static struct x_error_message_stack *x_error_message;
9598 /* An X error handler which stores the error message in
9599 *x_error_message. This is called from x_error_handler if
9600 x_catch_errors is in effect. */
9602 static void
9603 x_error_catcher (Display *display, XErrorEvent *event)
9605 XGetErrorText (display, event->error_code,
9606 x_error_message->string,
9607 X_ERROR_MESSAGE_SIZE);
9608 if (x_error_message->handler)
9609 x_error_message->handler (display, event, x_error_message->string,
9610 x_error_message->handler_data);
9613 /* Begin trapping X errors for display DPY. Actually we trap X errors
9614 for all displays, but DPY should be the display you are actually
9615 operating on.
9617 After calling this function, X protocol errors no longer cause
9618 Emacs to exit; instead, they are recorded in the string
9619 stored in *x_error_message.
9621 Calling x_check_errors signals an Emacs error if an X error has
9622 occurred since the last call to x_catch_errors or x_check_errors.
9624 Calling x_uncatch_errors resumes the normal error handling.
9625 Calling x_uncatch_errors_after_check is similar, but skips an XSync
9626 to the server, and should be used only immediately after
9627 x_had_errors_p or x_check_errors. */
9629 void
9630 x_catch_errors_with_handler (Display *dpy, x_special_error_handler handler,
9631 void *handler_data)
9633 struct x_error_message_stack *data = xmalloc (sizeof *data);
9635 /* Make sure any errors from previous requests have been dealt with. */
9636 XSync (dpy, False);
9638 data->dpy = dpy;
9639 data->string[0] = 0;
9640 data->handler = handler;
9641 data->handler_data = handler_data;
9642 data->prev = x_error_message;
9643 x_error_message = data;
9646 void
9647 x_catch_errors (Display *dpy)
9649 x_catch_errors_with_handler (dpy, NULL, NULL);
9652 /* Undo the last x_catch_errors call.
9653 DPY should be the display that was passed to x_catch_errors.
9655 This version should be used only if the immediately preceding
9656 X-protocol-related thing was x_check_errors or x_had_error_p, both
9657 of which issue XSync calls, so we don't need to re-sync here. */
9659 void
9660 x_uncatch_errors_after_check (void)
9662 struct x_error_message_stack *tmp;
9664 block_input ();
9665 tmp = x_error_message;
9666 x_error_message = x_error_message->prev;
9667 xfree (tmp);
9668 unblock_input ();
9671 /* Undo the last x_catch_errors call.
9672 DPY should be the display that was passed to x_catch_errors. */
9674 void
9675 x_uncatch_errors (void)
9677 struct x_error_message_stack *tmp;
9679 block_input ();
9681 /* The display may have been closed before this function is called.
9682 Check if it is still open before calling XSync. */
9683 if (x_display_info_for_display (x_error_message->dpy) != 0)
9684 XSync (x_error_message->dpy, False);
9686 tmp = x_error_message;
9687 x_error_message = x_error_message->prev;
9688 xfree (tmp);
9689 unblock_input ();
9692 /* If any X protocol errors have arrived since the last call to
9693 x_catch_errors or x_check_errors, signal an Emacs error using
9694 sprintf (a buffer, FORMAT, the x error message text) as the text. */
9696 void
9697 x_check_errors (Display *dpy, const char *format)
9699 /* Make sure to catch any errors incurred so far. */
9700 XSync (dpy, False);
9702 if (x_error_message->string[0])
9704 char string[X_ERROR_MESSAGE_SIZE];
9705 memcpy (string, x_error_message->string, X_ERROR_MESSAGE_SIZE);
9706 x_uncatch_errors ();
9707 error (format, string);
9711 /* Nonzero if we had any X protocol errors
9712 since we did x_catch_errors on DPY. */
9714 bool
9715 x_had_errors_p (Display *dpy)
9717 /* Make sure to catch any errors incurred so far. */
9718 XSync (dpy, False);
9720 return x_error_message->string[0] != 0;
9723 /* Forget about any errors we have had, since we did x_catch_errors on DPY. */
9725 void
9726 x_clear_errors (Display *dpy)
9728 x_error_message->string[0] = 0;
9731 #if false
9732 /* See comment in unwind_to_catch why calling this is a bad
9733 * idea. --lorentey */
9734 /* Close off all unclosed x_catch_errors calls. */
9736 void
9737 x_fully_uncatch_errors (void)
9739 while (x_error_message)
9740 x_uncatch_errors ();
9742 #endif
9744 #if false
9745 static unsigned int x_wire_count;
9746 x_trace_wire (void)
9748 fprintf (stderr, "Lib call: %d\n", ++x_wire_count);
9750 #endif
9753 /************************************************************************
9754 Handling X errors
9755 ************************************************************************/
9757 /* Error message passed to x_connection_closed. */
9759 static char *error_msg;
9761 /* Handle the loss of connection to display DPY. ERROR_MESSAGE is
9762 the text of an error message that lead to the connection loss. */
9764 static _Noreturn void
9765 x_connection_closed (Display *dpy, const char *error_message, bool ioerror)
9767 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
9768 Lisp_Object frame, tail;
9769 ptrdiff_t idx = SPECPDL_INDEX ();
9771 error_msg = alloca (strlen (error_message) + 1);
9772 strcpy (error_msg, error_message);
9774 /* Inhibit redisplay while frames are being deleted. */
9775 specbind (Qinhibit_redisplay, Qt);
9777 if (dpyinfo)
9779 /* Protect display from being closed when we delete the last
9780 frame on it. */
9781 dpyinfo->reference_count++;
9782 dpyinfo->terminal->reference_count++;
9784 if (ioerror) dpyinfo->display = 0;
9786 /* First delete frames whose mini-buffers are on frames
9787 that are on the dead display. */
9788 FOR_EACH_FRAME (tail, frame)
9790 Lisp_Object minibuf_frame;
9791 minibuf_frame
9792 = WINDOW_FRAME (XWINDOW (FRAME_MINIBUF_WINDOW (XFRAME (frame))));
9793 if (FRAME_X_P (XFRAME (frame))
9794 && FRAME_X_P (XFRAME (minibuf_frame))
9795 && ! EQ (frame, minibuf_frame)
9796 && FRAME_DISPLAY_INFO (XFRAME (minibuf_frame)) == dpyinfo)
9797 delete_frame (frame, Qnoelisp);
9800 /* Now delete all remaining frames on the dead display.
9801 We are now sure none of these is used as the mini-buffer
9802 for another frame that we need to delete. */
9803 FOR_EACH_FRAME (tail, frame)
9804 if (FRAME_X_P (XFRAME (frame))
9805 && FRAME_DISPLAY_INFO (XFRAME (frame)) == dpyinfo)
9807 /* Set this to t so that delete_frame won't get confused
9808 trying to find a replacement. */
9809 kset_default_minibuffer_frame (FRAME_KBOARD (XFRAME (frame)), Qt);
9810 delete_frame (frame, Qnoelisp);
9813 /* If DPYINFO is null, this means we didn't open the display in the
9814 first place, so don't try to close it. */
9815 if (dpyinfo)
9817 /* We can not call XtCloseDisplay here because it calls XSync.
9818 XSync inside the error handler apparently hangs Emacs. On
9819 current Xt versions, this isn't needed either. */
9820 #ifdef USE_GTK
9821 /* A long-standing GTK bug prevents proper disconnect handling
9822 (https://bugzilla.gnome.org/show_bug.cgi?id=85715). Once,
9823 the resulting Glib error message loop filled a user's disk.
9824 To avoid this, kill Emacs unconditionally on disconnect. */
9825 shut_down_emacs (0, Qnil);
9826 fprintf (stderr, "%s\n\
9827 When compiled with GTK, Emacs cannot recover from X disconnects.\n\
9828 This is a GTK bug: https://bugzilla.gnome.org/show_bug.cgi?id=85715\n\
9829 For details, see etc/PROBLEMS.\n",
9830 error_msg);
9831 emacs_abort ();
9832 #endif /* USE_GTK */
9834 /* Indicate that this display is dead. */
9835 dpyinfo->display = 0;
9837 dpyinfo->reference_count--;
9838 dpyinfo->terminal->reference_count--;
9839 if (dpyinfo->reference_count != 0)
9840 /* We have just closed all frames on this display. */
9841 emacs_abort ();
9844 Lisp_Object tmp;
9845 XSETTERMINAL (tmp, dpyinfo->terminal);
9846 Fdelete_terminal (tmp, Qnoelisp);
9850 if (terminal_list == 0)
9852 fprintf (stderr, "%s\n", error_msg);
9853 Fkill_emacs (make_number (70));
9854 /* NOTREACHED */
9857 totally_unblock_input ();
9859 unbind_to (idx, Qnil);
9860 clear_waiting_for_input ();
9862 /* Here, we absolutely have to use a non-local exit (e.g. signal, throw,
9863 longjmp), because returning from this function would get us back into
9864 Xlib's code which will directly call `exit'. */
9865 error ("%s", error_msg);
9868 /* We specifically use it before defining it, so that gcc doesn't inline it,
9869 otherwise gdb doesn't know how to properly put a breakpoint on it. */
9870 static void x_error_quitter (Display *, XErrorEvent *);
9872 /* This is the first-level handler for X protocol errors.
9873 It calls x_error_quitter or x_error_catcher. */
9875 static int
9876 x_error_handler (Display *display, XErrorEvent *event)
9878 #if defined USE_GTK && defined HAVE_GTK3
9879 if ((event->error_code == BadMatch || event->error_code == BadWindow)
9880 && event->request_code == X_SetInputFocus)
9882 return 0;
9884 #endif
9886 if (x_error_message)
9887 x_error_catcher (display, event);
9888 else
9889 x_error_quitter (display, event);
9890 return 0;
9893 /* This is the usual handler for X protocol errors.
9894 It kills all frames on the display that we got the error for.
9895 If that was the only one, it prints an error message and kills Emacs. */
9897 /* .gdbinit puts a breakpoint here, so make sure it is not inlined. */
9899 /* On older GCC versions, just putting x_error_quitter
9900 after x_error_handler prevents inlining into the former. */
9902 static void NO_INLINE
9903 x_error_quitter (Display *display, XErrorEvent *event)
9905 char buf[256], buf1[356];
9907 /* Ignore BadName errors. They can happen because of fonts
9908 or colors that are not defined. */
9910 if (event->error_code == BadName)
9911 return;
9913 /* Note that there is no real way portable across R3/R4 to get the
9914 original error handler. */
9916 XGetErrorText (display, event->error_code, buf, sizeof (buf));
9917 sprintf (buf1, "X protocol error: %s on protocol request %d",
9918 buf, event->request_code);
9919 x_connection_closed (display, buf1, false);
9923 /* This is the handler for X IO errors, always.
9924 It kills all frames on the display that we lost touch with.
9925 If that was the only one, it prints an error message and kills Emacs. */
9927 static _Noreturn int
9928 x_io_error_quitter (Display *display)
9930 char buf[256];
9932 snprintf (buf, sizeof buf, "Connection lost to X server '%s'",
9933 DisplayString (display));
9934 x_connection_closed (display, buf, true);
9935 assume (false);
9938 /* Changing the font of the frame. */
9940 /* Give frame F the font FONT-OBJECT as its default font. The return
9941 value is FONT-OBJECT. FONTSET is an ID of the fontset for the
9942 frame. If it is negative, generate a new fontset from
9943 FONT-OBJECT. */
9945 Lisp_Object
9946 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
9948 struct font *font = XFONT_OBJECT (font_object);
9949 int unit, font_ascent, font_descent;
9950 #ifndef USE_X_TOOLKIT
9951 int old_menu_bar_height = FRAME_MENU_BAR_HEIGHT (f);
9952 Lisp_Object fullscreen;
9953 #endif
9955 if (fontset < 0)
9956 fontset = fontset_from_font (font_object);
9957 FRAME_FONTSET (f) = fontset;
9958 if (FRAME_FONT (f) == font)
9959 /* This font is already set in frame F. There's nothing more to
9960 do. */
9961 return font_object;
9963 FRAME_FONT (f) = font;
9964 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
9965 FRAME_COLUMN_WIDTH (f) = font->average_width;
9966 get_font_ascent_descent (font, &font_ascent, &font_descent);
9967 FRAME_LINE_HEIGHT (f) = font_ascent + font_descent;
9969 #ifndef USE_X_TOOLKIT
9970 FRAME_MENU_BAR_HEIGHT (f) = FRAME_MENU_BAR_LINES (f) * FRAME_LINE_HEIGHT (f);
9971 #endif
9973 /* Compute character columns occupied by scrollbar.
9975 Don't do things differently for non-toolkit scrollbars
9976 (Bug#17163). */
9977 unit = FRAME_COLUMN_WIDTH (f);
9978 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
9979 FRAME_CONFIG_SCROLL_BAR_COLS (f)
9980 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + unit - 1) / unit;
9981 else
9982 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + unit - 1) / unit;
9984 if (FRAME_X_WINDOW (f) != 0)
9986 /* Don't change the size of a tip frame; there's no point in
9987 doing it because it's done in Fx_show_tip, and it leads to
9988 problems because the tip frame has no widget. */
9989 if (!FRAME_TOOLTIP_P (f))
9991 adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
9992 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 3,
9993 false, Qfont);
9994 #ifndef USE_X_TOOLKIT
9995 if (FRAME_MENU_BAR_HEIGHT (f) != old_menu_bar_height
9996 && !f->after_make_frame
9997 && (EQ (frame_inhibit_implied_resize, Qt)
9998 || (CONSP (frame_inhibit_implied_resize)
9999 && NILP (Fmemq (Qfont, frame_inhibit_implied_resize))))
10000 && (NILP (fullscreen = get_frame_param (f, Qfullscreen))
10001 || EQ (fullscreen, Qfullwidth)))
10002 /* If the menu bar height changes, try to keep text height
10003 constant. */
10004 adjust_frame_size
10005 (f, -1, FRAME_TEXT_HEIGHT (f) + FRAME_MENU_BAR_HEIGHT (f)
10006 - old_menu_bar_height, 1, false, Qfont);
10007 #endif /* USE_X_TOOLKIT */
10011 #ifdef HAVE_X_I18N
10012 if (FRAME_XIC (f)
10013 && (FRAME_XIC_STYLE (f) & (XIMPreeditPosition | XIMStatusArea)))
10015 block_input ();
10016 xic_set_xfontset (f, SSDATA (fontset_ascii (fontset)));
10017 unblock_input ();
10019 #endif
10021 return font_object;
10025 /***********************************************************************
10026 X Input Methods
10027 ***********************************************************************/
10029 #ifdef HAVE_X_I18N
10031 #ifdef HAVE_X11R6
10033 /* XIM destroy callback function, which is called whenever the
10034 connection to input method XIM dies. CLIENT_DATA contains a
10035 pointer to the x_display_info structure corresponding to XIM. */
10037 static void
10038 xim_destroy_callback (XIM xim, XPointer client_data, XPointer call_data)
10040 struct x_display_info *dpyinfo = (struct x_display_info *) client_data;
10041 Lisp_Object frame, tail;
10043 block_input ();
10045 /* No need to call XDestroyIC.. */
10046 FOR_EACH_FRAME (tail, frame)
10048 struct frame *f = XFRAME (frame);
10049 if (FRAME_X_P (f) && FRAME_DISPLAY_INFO (f) == dpyinfo)
10051 FRAME_XIC (f) = NULL;
10052 xic_free_xfontset (f);
10056 /* No need to call XCloseIM. */
10057 dpyinfo->xim = NULL;
10058 XFree (dpyinfo->xim_styles);
10059 unblock_input ();
10062 #endif /* HAVE_X11R6 */
10064 /* Open the connection to the XIM server on display DPYINFO.
10065 RESOURCE_NAME is the resource name Emacs uses. */
10067 static void
10068 xim_open_dpy (struct x_display_info *dpyinfo, char *resource_name)
10070 XIM xim;
10072 #ifdef HAVE_XIM
10073 if (use_xim)
10075 if (dpyinfo->xim)
10076 XCloseIM (dpyinfo->xim);
10077 xim = XOpenIM (dpyinfo->display, dpyinfo->xrdb, resource_name,
10078 emacs_class);
10079 dpyinfo->xim = xim;
10081 if (xim)
10083 #ifdef HAVE_X11R6
10084 XIMCallback destroy;
10085 #endif
10087 /* Get supported styles and XIM values. */
10088 XGetIMValues (xim, XNQueryInputStyle, &dpyinfo->xim_styles, NULL);
10090 #ifdef HAVE_X11R6
10091 destroy.callback = xim_destroy_callback;
10092 destroy.client_data = (XPointer)dpyinfo;
10093 XSetIMValues (xim, XNDestroyCallback, &destroy, NULL);
10094 #endif
10098 else
10099 #endif /* HAVE_XIM */
10100 dpyinfo->xim = NULL;
10104 #ifdef HAVE_X11R6_XIM
10106 /* XIM instantiate callback function, which is called whenever an XIM
10107 server is available. DISPLAY is the display of the XIM.
10108 CLIENT_DATA contains a pointer to an xim_inst_t structure created
10109 when the callback was registered. */
10111 static void
10112 xim_instantiate_callback (Display *display, XPointer client_data, XPointer call_data)
10114 struct xim_inst_t *xim_inst = (struct xim_inst_t *) client_data;
10115 struct x_display_info *dpyinfo = xim_inst->dpyinfo;
10117 /* We don't support multiple XIM connections. */
10118 if (dpyinfo->xim)
10119 return;
10121 xim_open_dpy (dpyinfo, xim_inst->resource_name);
10123 /* Create XIC for the existing frames on the same display, as long
10124 as they have no XIC. */
10125 if (dpyinfo->xim && dpyinfo->reference_count > 0)
10127 Lisp_Object tail, frame;
10129 block_input ();
10130 FOR_EACH_FRAME (tail, frame)
10132 struct frame *f = XFRAME (frame);
10134 if (FRAME_X_P (f)
10135 && FRAME_DISPLAY_INFO (f) == xim_inst->dpyinfo)
10136 if (FRAME_XIC (f) == NULL)
10138 create_frame_xic (f);
10139 if (FRAME_XIC_STYLE (f) & XIMStatusArea)
10140 xic_set_statusarea (f);
10141 if (FRAME_XIC_STYLE (f) & XIMPreeditPosition)
10143 struct window *w = XWINDOW (f->selected_window);
10144 xic_set_preeditarea (w, w->cursor.x, w->cursor.y);
10149 unblock_input ();
10153 #endif /* HAVE_X11R6_XIM */
10156 /* Open a connection to the XIM server on display DPYINFO.
10157 RESOURCE_NAME is the resource name for Emacs. On X11R5, open the
10158 connection only at the first time. On X11R6, open the connection
10159 in the XIM instantiate callback function. */
10161 static void
10162 xim_initialize (struct x_display_info *dpyinfo, char *resource_name)
10164 dpyinfo->xim = NULL;
10165 #ifdef HAVE_XIM
10166 if (use_xim)
10168 #ifdef HAVE_X11R6_XIM
10169 struct xim_inst_t *xim_inst = xmalloc (sizeof *xim_inst);
10170 Bool ret;
10172 dpyinfo->xim_callback_data = xim_inst;
10173 xim_inst->dpyinfo = dpyinfo;
10174 xim_inst->resource_name = xstrdup (resource_name);
10175 ret = XRegisterIMInstantiateCallback
10176 (dpyinfo->display, dpyinfo->xrdb, xim_inst->resource_name,
10177 emacs_class, xim_instantiate_callback,
10178 /* This is XPointer in XFree86 but (XPointer *)
10179 on Tru64, at least, hence the configure test. */
10180 (XRegisterIMInstantiateCallback_arg6) xim_inst);
10181 eassert (ret == True);
10182 #else /* not HAVE_X11R6_XIM */
10183 xim_open_dpy (dpyinfo, resource_name);
10184 #endif /* not HAVE_X11R6_XIM */
10186 #endif /* HAVE_XIM */
10190 /* Close the connection to the XIM server on display DPYINFO. */
10192 static void
10193 xim_close_dpy (struct x_display_info *dpyinfo)
10195 #ifdef HAVE_XIM
10196 if (use_xim)
10198 #ifdef HAVE_X11R6_XIM
10199 struct xim_inst_t *xim_inst = dpyinfo->xim_callback_data;
10201 if (dpyinfo->display)
10203 Bool ret = XUnregisterIMInstantiateCallback
10204 (dpyinfo->display, dpyinfo->xrdb, xim_inst->resource_name,
10205 emacs_class, xim_instantiate_callback,
10206 (XRegisterIMInstantiateCallback_arg6) xim_inst);
10207 eassert (ret == True);
10209 xfree (xim_inst->resource_name);
10210 xfree (xim_inst);
10211 #endif /* HAVE_X11R6_XIM */
10212 if (dpyinfo->display)
10213 XCloseIM (dpyinfo->xim);
10214 dpyinfo->xim = NULL;
10215 XFree (dpyinfo->xim_styles);
10217 #endif /* HAVE_XIM */
10220 #endif /* not HAVE_X11R6_XIM */
10224 /* Calculate the absolute position in frame F
10225 from its current recorded position values and gravity. */
10227 static void
10228 x_calc_absolute_position (struct frame *f)
10230 int flags = f->size_hint_flags;
10231 struct frame *p = FRAME_PARENT_FRAME (f);
10233 /* We have nothing to do if the current position
10234 is already for the top-left corner. */
10235 if (! ((flags & XNegative) || (flags & YNegative)))
10236 return;
10238 /* Treat negative positions as relative to the leftmost bottommost
10239 position that fits on the screen. */
10240 if ((flags & XNegative) && (f->left_pos <= 0))
10242 int width = FRAME_PIXEL_WIDTH (f);
10244 /* A frame that has been visible at least once should have outer
10245 edges. */
10246 if (f->output_data.x->has_been_visible && !p)
10248 Lisp_Object frame;
10249 Lisp_Object edges = Qnil;
10251 XSETFRAME (frame, f);
10252 edges = Fx_frame_edges (frame, Qouter_edges);
10253 if (!NILP (edges))
10254 width = (XINT (Fnth (make_number (2), edges))
10255 - XINT (Fnth (make_number (0), edges)));
10258 if (p)
10259 f->left_pos = (FRAME_PIXEL_WIDTH (p) - width - 2 * f->border_width
10260 + f->left_pos);
10261 else
10262 f->left_pos = (x_display_pixel_width (FRAME_DISPLAY_INFO (f))
10263 - width + f->left_pos);
10267 if ((flags & YNegative) && (f->top_pos <= 0))
10269 int height = FRAME_PIXEL_HEIGHT (f);
10271 #if defined USE_X_TOOLKIT && defined USE_MOTIF
10272 /* Something is fishy here. When using Motif, starting Emacs with
10273 `-g -0-0', the frame appears too low by a few pixels.
10275 This seems to be so because initially, while Emacs is starting,
10276 the column widget's height and the frame's pixel height are
10277 different. The column widget's height is the right one. In
10278 later invocations, when Emacs is up, the frame's pixel height
10279 is right, though.
10281 It's not obvious where the initial small difference comes from.
10282 2000-12-01, gerd. */
10284 XtVaGetValues (f->output_data.x->column_widget, XtNheight, &height, NULL);
10285 #endif
10287 if (f->output_data.x->has_been_visible && !p)
10289 Lisp_Object frame;
10290 Lisp_Object edges = Qnil;
10292 XSETFRAME (frame, f);
10293 if (NILP (edges))
10294 edges = Fx_frame_edges (frame, Qouter_edges);
10295 if (!NILP (edges))
10296 height = (XINT (Fnth (make_number (3), edges))
10297 - XINT (Fnth (make_number (1), edges)));
10300 if (p)
10301 f->top_pos = (FRAME_PIXEL_HEIGHT (p) - height - 2 * f->border_width
10302 + f->top_pos);
10303 else
10304 f->top_pos = (x_display_pixel_height (FRAME_DISPLAY_INFO (f))
10305 - height + f->top_pos);
10308 /* The left_pos and top_pos
10309 are now relative to the top and left screen edges,
10310 so the flags should correspond. */
10311 f->size_hint_flags &= ~ (XNegative | YNegative);
10314 /* CHANGE_GRAVITY is 1 when calling from Fset_frame_position,
10315 to really change the position, and 0 when calling from
10316 x_make_frame_visible (in that case, XOFF and YOFF are the current
10317 position values). It is -1 when calling from x_set_frame_parameters,
10318 which means, do adjust for borders but don't change the gravity. */
10320 void
10321 x_set_offset (struct frame *f, register int xoff, register int yoff, int change_gravity)
10323 int modified_top, modified_left;
10324 #ifdef USE_GTK
10325 int scale = xg_get_scale (f);
10326 #endif
10328 if (change_gravity > 0)
10330 f->top_pos = yoff;
10331 f->left_pos = xoff;
10332 f->size_hint_flags &= ~ (XNegative | YNegative);
10333 if (xoff < 0)
10334 f->size_hint_flags |= XNegative;
10335 if (yoff < 0)
10336 f->size_hint_flags |= YNegative;
10337 f->win_gravity = NorthWestGravity;
10340 x_calc_absolute_position (f);
10342 block_input ();
10343 x_wm_set_size_hint (f, 0, false);
10345 #ifdef USE_GTK
10346 if (x_gtk_use_window_move)
10348 /* When a position change was requested and the outer GTK widget
10349 has been realized already, leave it to gtk_window_move to
10350 DTRT and return. Used for Bug#25851 and Bug#25943. Convert
10351 from X pixels to GTK scaled pixels. */
10352 if (change_gravity != 0 && FRAME_GTK_OUTER_WIDGET (f))
10353 gtk_window_move (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)),
10354 f->left_pos / scale, f->top_pos / scale);
10355 unblock_input ();
10356 return;
10358 #endif /* USE_GTK */
10360 modified_left = f->left_pos;
10361 modified_top = f->top_pos;
10363 if (change_gravity != 0 && FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A)
10365 /* Some WMs (twm, wmaker at least) has an offset that is smaller
10366 than the WM decorations. So we use the calculated offset instead
10367 of the WM decoration sizes here (x/y_pixels_outer_diff). */
10368 modified_left += FRAME_X_OUTPUT (f)->move_offset_left;
10369 modified_top += FRAME_X_OUTPUT (f)->move_offset_top;
10372 #ifdef USE_GTK
10373 /* Make sure we adjust for possible scaling. */
10374 gtk_window_move (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)),
10375 modified_left / scale, modified_top / scale);
10376 #else
10377 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
10378 modified_left, modified_top);
10379 #endif
10381 x_sync_with_move (f, f->left_pos, f->top_pos,
10382 FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN);
10384 /* change_gravity is non-zero when this function is called from Lisp to
10385 programmatically move a frame. In that case, we call
10386 x_check_expected_move to discover if we have a "Type A" or "Type B"
10387 window manager, and, for a "Type A" window manager, adjust the position
10388 of the frame.
10390 We call x_check_expected_move if a programmatic move occurred, and
10391 either the window manager type (A/B) is unknown or it is Type A but we
10392 need to compute the top/left offset adjustment for this frame. */
10394 if (change_gravity != 0
10395 && !FRAME_PARENT_FRAME (f)
10396 && (FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN
10397 || (FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A
10398 && (FRAME_X_OUTPUT (f)->move_offset_left == 0
10399 && FRAME_X_OUTPUT (f)->move_offset_top == 0))))
10400 x_check_expected_move (f, modified_left, modified_top);
10402 unblock_input ();
10405 /* Return true if _NET_SUPPORTING_WM_CHECK window exists and _NET_SUPPORTED
10406 on the root window for frame F contains ATOMNAME.
10407 This is how a WM check shall be done according to the Window Manager
10408 Specification/Extended Window Manager Hints at
10409 http://freedesktop.org/wiki/Specifications/wm-spec. */
10411 bool
10412 x_wm_supports (struct frame *f, Atom want_atom)
10414 Atom actual_type;
10415 unsigned long actual_size, bytes_remaining;
10416 int i, rc, actual_format;
10417 bool ret;
10418 Window wmcheck_window;
10419 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10420 Window target_window = dpyinfo->root_window;
10421 int max_len = 65536;
10422 Display *dpy = FRAME_X_DISPLAY (f);
10423 unsigned char *tmp_data = NULL;
10424 Atom target_type = XA_WINDOW;
10426 block_input ();
10428 x_catch_errors (dpy);
10429 rc = XGetWindowProperty (dpy, target_window,
10430 dpyinfo->Xatom_net_supporting_wm_check,
10431 0, max_len, False, target_type,
10432 &actual_type, &actual_format, &actual_size,
10433 &bytes_remaining, &tmp_data);
10435 if (rc != Success || actual_type != XA_WINDOW || x_had_errors_p (dpy))
10437 if (tmp_data) XFree (tmp_data);
10438 x_uncatch_errors ();
10439 unblock_input ();
10440 return false;
10443 wmcheck_window = *(Window *) tmp_data;
10444 XFree (tmp_data);
10446 /* Check if window exists. */
10447 XSelectInput (dpy, wmcheck_window, StructureNotifyMask);
10448 if (x_had_errors_p (dpy))
10450 x_uncatch_errors_after_check ();
10451 unblock_input ();
10452 return false;
10455 if (dpyinfo->net_supported_window != wmcheck_window)
10457 /* Window changed, reload atoms */
10458 if (dpyinfo->net_supported_atoms != NULL)
10459 XFree (dpyinfo->net_supported_atoms);
10460 dpyinfo->net_supported_atoms = NULL;
10461 dpyinfo->nr_net_supported_atoms = 0;
10462 dpyinfo->net_supported_window = 0;
10464 target_type = XA_ATOM;
10465 tmp_data = NULL;
10466 rc = XGetWindowProperty (dpy, target_window,
10467 dpyinfo->Xatom_net_supported,
10468 0, max_len, False, target_type,
10469 &actual_type, &actual_format, &actual_size,
10470 &bytes_remaining, &tmp_data);
10472 if (rc != Success || actual_type != XA_ATOM || x_had_errors_p (dpy))
10474 if (tmp_data) XFree (tmp_data);
10475 x_uncatch_errors ();
10476 unblock_input ();
10477 return false;
10480 dpyinfo->net_supported_atoms = (Atom *)tmp_data;
10481 dpyinfo->nr_net_supported_atoms = actual_size;
10482 dpyinfo->net_supported_window = wmcheck_window;
10485 ret = false;
10487 for (i = 0; !ret && i < dpyinfo->nr_net_supported_atoms; ++i)
10488 ret = dpyinfo->net_supported_atoms[i] == want_atom;
10490 x_uncatch_errors ();
10491 unblock_input ();
10493 return ret;
10496 static void
10497 set_wm_state (Lisp_Object frame, bool add, Atom atom, Atom value)
10499 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (XFRAME (frame));
10501 x_send_client_event (frame, make_number (0), frame,
10502 dpyinfo->Xatom_net_wm_state,
10503 make_number (32),
10504 /* 1 = add, 0 = remove */
10505 Fcons
10506 (make_number (add),
10507 Fcons
10508 (make_fixnum_or_float (atom),
10509 (value != 0
10510 ? list1 (make_fixnum_or_float (value))
10511 : Qnil))));
10514 void
10515 x_set_sticky (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
10517 Lisp_Object frame;
10518 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10520 XSETFRAME (frame, f);
10522 set_wm_state (frame, !NILP (new_value),
10523 dpyinfo->Xatom_net_wm_state_sticky, None);
10527 * x_set_skip_taskbar:
10529 * Set frame F's `skip-taskbar' parameter. If non-nil, this should
10530 * remove F's icon from the taskbar associated with the display of F's
10531 * window-system window and inhibit switching to F's window via
10532 * <Alt>-<TAB>. If nil, lift these restrictions.
10534 * Some window managers may not honor this parameter.
10536 void
10537 x_set_skip_taskbar (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
10539 if (!EQ (new_value, old_value))
10541 #ifdef USE_GTK
10542 xg_set_skip_taskbar (f, new_value);
10543 #else
10544 Lisp_Object frame;
10545 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10547 XSETFRAME (frame, f);
10548 set_wm_state (frame, !NILP (new_value),
10549 dpyinfo->Xatom_net_wm_state_skip_taskbar, None);
10550 #endif /* USE_GTK */
10551 FRAME_SKIP_TASKBAR (f) = !NILP (new_value);
10556 * x_set_z_group:
10558 * Set frame F's `z-group' parameter. If `above', F's window-system
10559 * window is displayed above all windows that do not have the `above'
10560 * property set. If nil, F's window is shown below all windows that
10561 * have the `above' property set and above all windows that have the
10562 * `below' property set. If `below', F's window is displayed below all
10563 * windows that do not have the `below' property set.
10565 * Some window managers may not honor this parameter.
10567 void
10568 x_set_z_group (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
10570 /* We don't care about old_value. The window manager might have
10571 reset the value without telling us. */
10572 Lisp_Object frame;
10573 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10575 XSETFRAME (frame, f);
10577 if (NILP (new_value))
10579 set_wm_state (frame, false,
10580 dpyinfo->Xatom_net_wm_state_above, None);
10581 set_wm_state (frame, false,
10582 dpyinfo->Xatom_net_wm_state_below, None);
10583 FRAME_Z_GROUP (f) = z_group_none;
10585 else if (EQ (new_value, Qabove))
10587 set_wm_state (frame, true,
10588 dpyinfo->Xatom_net_wm_state_above, None);
10589 set_wm_state (frame, false,
10590 dpyinfo->Xatom_net_wm_state_below, None);
10591 FRAME_Z_GROUP (f) = z_group_above;
10593 else if (EQ (new_value, Qbelow))
10595 set_wm_state (frame, false,
10596 dpyinfo->Xatom_net_wm_state_above, None);
10597 set_wm_state (frame, true,
10598 dpyinfo->Xatom_net_wm_state_below, None);
10599 FRAME_Z_GROUP (f) = z_group_below;
10601 else if (EQ (new_value, Qabove_suspended))
10603 set_wm_state (frame, false,
10604 dpyinfo->Xatom_net_wm_state_above, None);
10605 FRAME_Z_GROUP (f) = z_group_above_suspended;
10607 else
10608 error ("Invalid z-group specification");
10612 /* Return the current _NET_WM_STATE.
10613 SIZE_STATE is set to one of the FULLSCREEN_* values.
10614 Set *STICKY to the sticky state.
10616 Return true iff we are not hidden. */
10618 static bool
10619 get_current_wm_state (struct frame *f,
10620 Window window,
10621 int *size_state,
10622 bool *sticky)
10624 unsigned long actual_size;
10625 int i;
10626 bool is_hidden = false;
10627 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10628 long max_len = 65536;
10629 Atom target_type = XA_ATOM;
10630 /* If XCB is available, we can avoid three XSync calls. */
10631 #ifdef USE_XCB
10632 xcb_get_property_cookie_t prop_cookie;
10633 xcb_get_property_reply_t *prop;
10634 xcb_atom_t *reply_data;
10635 #else
10636 Display *dpy = FRAME_X_DISPLAY (f);
10637 unsigned long bytes_remaining;
10638 int rc, actual_format;
10639 Atom actual_type;
10640 unsigned char *tmp_data = NULL;
10641 Atom *reply_data;
10642 #endif
10644 *sticky = false;
10645 *size_state = FULLSCREEN_NONE;
10647 block_input ();
10649 #ifdef USE_XCB
10650 prop_cookie = xcb_get_property (dpyinfo->xcb_connection, 0, window,
10651 dpyinfo->Xatom_net_wm_state,
10652 target_type, 0, max_len);
10653 prop = xcb_get_property_reply (dpyinfo->xcb_connection, prop_cookie, NULL);
10654 if (prop && prop->type == target_type)
10656 int actual_bytes = xcb_get_property_value_length (prop);
10657 eassume (0 <= actual_bytes);
10658 actual_size = actual_bytes / sizeof *reply_data;
10659 reply_data = xcb_get_property_value (prop);
10661 else
10663 actual_size = 0;
10664 is_hidden = FRAME_ICONIFIED_P (f);
10666 #else
10667 x_catch_errors (dpy);
10668 rc = XGetWindowProperty (dpy, window, dpyinfo->Xatom_net_wm_state,
10669 0, max_len, False, target_type,
10670 &actual_type, &actual_format, &actual_size,
10671 &bytes_remaining, &tmp_data);
10673 if (rc == Success && actual_type == target_type && ! x_had_errors_p (dpy))
10674 reply_data = (Atom *) tmp_data;
10675 else
10677 actual_size = 0;
10678 is_hidden = FRAME_ICONIFIED_P (f);
10681 x_uncatch_errors ();
10682 #endif
10684 for (i = 0; i < actual_size; ++i)
10686 Atom a = reply_data[i];
10687 if (a == dpyinfo->Xatom_net_wm_state_hidden)
10688 is_hidden = true;
10689 else if (a == dpyinfo->Xatom_net_wm_state_maximized_horz)
10691 if (*size_state == FULLSCREEN_HEIGHT)
10692 *size_state = FULLSCREEN_MAXIMIZED;
10693 else
10694 *size_state = FULLSCREEN_WIDTH;
10696 else if (a == dpyinfo->Xatom_net_wm_state_maximized_vert)
10698 if (*size_state == FULLSCREEN_WIDTH)
10699 *size_state = FULLSCREEN_MAXIMIZED;
10700 else
10701 *size_state = FULLSCREEN_HEIGHT;
10703 else if (a == dpyinfo->Xatom_net_wm_state_fullscreen)
10704 *size_state = FULLSCREEN_BOTH;
10705 else if (a == dpyinfo->Xatom_net_wm_state_sticky)
10706 *sticky = true;
10709 #ifdef USE_XCB
10710 free (prop);
10711 #else
10712 if (tmp_data) XFree (tmp_data);
10713 #endif
10715 unblock_input ();
10716 return ! is_hidden;
10719 /* Do fullscreen as specified in extended window manager hints */
10721 static bool
10722 do_ewmh_fullscreen (struct frame *f)
10724 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10725 bool have_net_atom = x_wm_supports (f, dpyinfo->Xatom_net_wm_state);
10726 int cur;
10727 bool dummy;
10729 get_current_wm_state (f, FRAME_OUTER_WINDOW (f), &cur, &dummy);
10731 /* Some window managers don't say they support _NET_WM_STATE, but they do say
10732 they support _NET_WM_STATE_FULLSCREEN. Try that also. */
10733 if (!have_net_atom)
10734 have_net_atom = x_wm_supports (f, dpyinfo->Xatom_net_wm_state_fullscreen);
10736 if (have_net_atom && cur != f->want_fullscreen)
10738 Lisp_Object frame;
10740 XSETFRAME (frame, f);
10742 /* Keep number of calls to set_wm_state as low as possible.
10743 Some window managers, or possible Gtk+, hangs when too many
10744 are sent at once. */
10745 switch (f->want_fullscreen)
10747 case FULLSCREEN_BOTH:
10748 if (cur != FULLSCREEN_BOTH)
10749 set_wm_state (frame, true, dpyinfo->Xatom_net_wm_state_fullscreen,
10750 None);
10751 break;
10752 case FULLSCREEN_WIDTH:
10753 if (x_frame_normalize_before_maximize && cur == FULLSCREEN_MAXIMIZED)
10755 set_wm_state (frame, false,
10756 dpyinfo->Xatom_net_wm_state_maximized_horz,
10757 dpyinfo->Xatom_net_wm_state_maximized_vert);
10758 set_wm_state (frame, true,
10759 dpyinfo->Xatom_net_wm_state_maximized_horz, None);
10761 else
10763 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_HEIGHT
10764 || cur == FULLSCREEN_MAXIMIZED)
10765 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
10766 dpyinfo->Xatom_net_wm_state_maximized_vert);
10767 if (cur != FULLSCREEN_MAXIMIZED || x_frame_normalize_before_maximize)
10768 set_wm_state (frame, true,
10769 dpyinfo->Xatom_net_wm_state_maximized_horz, None);
10771 break;
10772 case FULLSCREEN_HEIGHT:
10773 if (x_frame_normalize_before_maximize && cur == FULLSCREEN_MAXIMIZED)
10775 set_wm_state (frame, false,
10776 dpyinfo->Xatom_net_wm_state_maximized_horz,
10777 dpyinfo->Xatom_net_wm_state_maximized_vert);
10778 set_wm_state (frame, true,
10779 dpyinfo->Xatom_net_wm_state_maximized_vert, None);
10781 else
10783 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_WIDTH
10784 || cur == FULLSCREEN_MAXIMIZED)
10785 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
10786 dpyinfo->Xatom_net_wm_state_maximized_horz);
10787 if (cur != FULLSCREEN_MAXIMIZED || x_frame_normalize_before_maximize)
10788 set_wm_state (frame, true,
10789 dpyinfo->Xatom_net_wm_state_maximized_vert, None);
10791 break;
10792 case FULLSCREEN_MAXIMIZED:
10793 if (x_frame_normalize_before_maximize && cur == FULLSCREEN_BOTH)
10795 set_wm_state (frame, false,
10796 dpyinfo->Xatom_net_wm_state_fullscreen, None);
10797 set_wm_state (frame, true,
10798 dpyinfo->Xatom_net_wm_state_maximized_horz,
10799 dpyinfo->Xatom_net_wm_state_maximized_vert);
10801 else if (x_frame_normalize_before_maximize && cur == FULLSCREEN_WIDTH)
10803 set_wm_state (frame, false,
10804 dpyinfo->Xatom_net_wm_state_maximized_horz, None);
10805 set_wm_state (frame, true,
10806 dpyinfo->Xatom_net_wm_state_maximized_horz,
10807 dpyinfo->Xatom_net_wm_state_maximized_vert);
10809 else if (x_frame_normalize_before_maximize && cur == FULLSCREEN_HEIGHT)
10811 set_wm_state (frame, false,
10812 dpyinfo->Xatom_net_wm_state_maximized_vert, None);
10813 set_wm_state (frame, true,
10814 dpyinfo->Xatom_net_wm_state_maximized_horz,
10815 dpyinfo->Xatom_net_wm_state_maximized_vert);
10817 else
10819 if (cur == FULLSCREEN_BOTH)
10820 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
10821 None);
10822 else if (cur == FULLSCREEN_HEIGHT)
10823 set_wm_state (frame, true,
10824 dpyinfo->Xatom_net_wm_state_maximized_horz, None);
10825 else if (cur == FULLSCREEN_WIDTH)
10826 set_wm_state (frame, true, None,
10827 dpyinfo->Xatom_net_wm_state_maximized_vert);
10828 else
10829 set_wm_state (frame, true,
10830 dpyinfo->Xatom_net_wm_state_maximized_horz,
10831 dpyinfo->Xatom_net_wm_state_maximized_vert);
10833 break;
10834 case FULLSCREEN_NONE:
10835 if (cur == FULLSCREEN_BOTH)
10836 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
10837 None);
10838 else
10839 set_wm_state (frame, false,
10840 dpyinfo->Xatom_net_wm_state_maximized_horz,
10841 dpyinfo->Xatom_net_wm_state_maximized_vert);
10844 f->want_fullscreen = FULLSCREEN_NONE;
10848 return have_net_atom;
10851 static void
10852 XTfullscreen_hook (struct frame *f)
10854 if (FRAME_VISIBLE_P (f))
10856 block_input ();
10857 x_check_fullscreen (f);
10858 x_sync (f);
10859 unblock_input ();
10864 static bool
10865 x_handle_net_wm_state (struct frame *f, const XPropertyEvent *event)
10867 int value = FULLSCREEN_NONE;
10868 Lisp_Object lval;
10869 bool sticky = false;
10870 bool not_hidden = get_current_wm_state (f, event->window, &value, &sticky);
10872 lval = Qnil;
10873 switch (value)
10875 case FULLSCREEN_WIDTH:
10876 lval = Qfullwidth;
10877 break;
10878 case FULLSCREEN_HEIGHT:
10879 lval = Qfullheight;
10880 break;
10881 case FULLSCREEN_BOTH:
10882 lval = Qfullboth;
10883 break;
10884 case FULLSCREEN_MAXIMIZED:
10885 lval = Qmaximized;
10886 break;
10889 frame_size_history_add
10890 (f, Qx_handle_net_wm_state, 0, 0,
10891 list2 (get_frame_param (f, Qfullscreen), lval));
10893 store_frame_param (f, Qfullscreen, lval);
10894 store_frame_param (f, Qsticky, sticky ? Qt : Qnil);
10896 return not_hidden;
10899 /* Check if we need to resize the frame due to a fullscreen request.
10900 If so needed, resize the frame. */
10901 static void
10902 x_check_fullscreen (struct frame *f)
10904 Lisp_Object lval = Qnil;
10906 if (do_ewmh_fullscreen (f))
10907 return;
10909 if (f->output_data.x->parent_desc != FRAME_DISPLAY_INFO (f)->root_window)
10910 return; /* Only fullscreen without WM or with EWM hints (above). */
10912 /* Setting fullscreen to nil doesn't do anything. We could save the
10913 last non-fullscreen size and restore it, but it seems like a
10914 lot of work for this unusual case (no window manager running). */
10916 if (f->want_fullscreen != FULLSCREEN_NONE)
10918 int width = FRAME_PIXEL_WIDTH (f), height = FRAME_PIXEL_HEIGHT (f);
10919 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10921 switch (f->want_fullscreen)
10923 /* No difference between these two when there is no WM */
10924 case FULLSCREEN_MAXIMIZED:
10925 lval = Qmaximized;
10926 width = x_display_pixel_width (dpyinfo);
10927 height = x_display_pixel_height (dpyinfo);
10928 break;
10929 case FULLSCREEN_BOTH:
10930 lval = Qfullboth;
10931 width = x_display_pixel_width (dpyinfo);
10932 height = x_display_pixel_height (dpyinfo);
10933 break;
10934 case FULLSCREEN_WIDTH:
10935 lval = Qfullwidth;
10936 width = x_display_pixel_width (dpyinfo);
10937 height = height + FRAME_MENUBAR_HEIGHT (f);
10938 break;
10939 case FULLSCREEN_HEIGHT:
10940 lval = Qfullheight;
10941 height = x_display_pixel_height (dpyinfo);
10942 break;
10943 default:
10944 emacs_abort ();
10947 frame_size_history_add
10948 (f, Qx_check_fullscreen, width, height, Qnil);
10950 x_wm_set_size_hint (f, 0, false);
10952 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
10953 width, height);
10955 if (FRAME_VISIBLE_P (f))
10956 x_wait_for_event (f, ConfigureNotify);
10957 else
10959 change_frame_size (f, width, height - FRAME_MENUBAR_HEIGHT (f),
10960 false, true, false, true);
10961 x_sync (f);
10965 /* `x_net_wm_state' might have reset the fullscreen frame parameter,
10966 restore it. */
10967 store_frame_param (f, Qfullscreen, lval);
10970 /* This function is called by x_set_offset to determine whether the window
10971 manager interfered with the positioning of the frame. Type A window
10972 managers position the surrounding window manager decorations a small
10973 amount above and left of the user-supplied position. Type B window
10974 managers position the surrounding window manager decorations at the
10975 user-specified position. If we detect a Type A window manager, we
10976 compensate by moving the window right and down by the proper amount. */
10978 static void
10979 x_check_expected_move (struct frame *f, int expected_left, int expected_top)
10981 int current_left = 0, current_top = 0;
10983 /* x_real_positions returns the left and top offsets of the outermost
10984 window manager window around the frame. */
10986 x_real_positions (f, &current_left, &current_top);
10988 if (current_left != expected_left || current_top != expected_top)
10990 /* It's a "Type A" window manager. */
10992 int adjusted_left;
10993 int adjusted_top;
10995 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_A;
10996 FRAME_X_OUTPUT (f)->move_offset_left = expected_left - current_left;
10997 FRAME_X_OUTPUT (f)->move_offset_top = expected_top - current_top;
10999 /* Now fix the mispositioned frame's location. */
11001 adjusted_left = expected_left + FRAME_X_OUTPUT (f)->move_offset_left;
11002 adjusted_top = expected_top + FRAME_X_OUTPUT (f)->move_offset_top;
11004 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11005 adjusted_left, adjusted_top);
11007 x_sync_with_move (f, expected_left, expected_top, false);
11009 else
11010 /* It's a "Type B" window manager. We don't have to adjust the
11011 frame's position. */
11013 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_B;
11017 /* Wait for XGetGeometry to return up-to-date position information for a
11018 recently-moved frame. Call this immediately after calling XMoveWindow.
11019 If FUZZY is non-zero, then LEFT and TOP are just estimates of where the
11020 frame has been moved to, so we use a fuzzy position comparison instead
11021 of an exact comparison. */
11023 static void
11024 x_sync_with_move (struct frame *f, int left, int top, bool fuzzy)
11026 int count = 0;
11028 while (count++ < 50)
11030 int current_left = 0, current_top = 0;
11032 /* In theory, this call to XSync only needs to happen once, but in
11033 practice, it doesn't seem to work, hence the need for the surrounding
11034 loop. */
11036 XSync (FRAME_X_DISPLAY (f), False);
11037 x_real_positions (f, &current_left, &current_top);
11039 if (fuzzy)
11041 /* The left fuzz-factor is 10 pixels. The top fuzz-factor is 40
11042 pixels. */
11044 if (eabs (current_left - left) <= 10
11045 && eabs (current_top - top) <= 40)
11046 return;
11048 else if (current_left == left && current_top == top)
11049 return;
11052 /* As a last resort, just wait 0.5 seconds and hope that XGetGeometry
11053 will then return up-to-date position info. */
11055 wait_reading_process_output (0, 500000000, 0, false, Qnil, NULL, 0);
11059 /* Wait for an event on frame F matching EVENTTYPE. */
11060 void
11061 x_wait_for_event (struct frame *f, int eventtype)
11063 if (!FLOATP (Vx_wait_for_event_timeout))
11064 return;
11066 int level = interrupt_input_blocked;
11067 fd_set fds;
11068 struct timespec tmo, tmo_at, time_now;
11069 int fd = ConnectionNumber (FRAME_X_DISPLAY (f));
11071 f->wait_event_type = eventtype;
11073 /* Default timeout is 0.1 second. Hopefully not noticeable. */
11074 double timeout = XFLOAT_DATA (Vx_wait_for_event_timeout);
11075 time_t timeout_seconds = (time_t) timeout;
11076 tmo = make_timespec
11077 (timeout_seconds, (long int) ((timeout - timeout_seconds)
11078 * 1000 * 1000 * 1000));
11079 tmo_at = timespec_add (current_timespec (), tmo);
11081 while (f->wait_event_type)
11083 pending_signals = true;
11084 totally_unblock_input ();
11085 /* XTread_socket is called after unblock. */
11086 block_input ();
11087 interrupt_input_blocked = level;
11089 FD_ZERO (&fds);
11090 FD_SET (fd, &fds);
11092 time_now = current_timespec ();
11093 if (timespec_cmp (tmo_at, time_now) < 0)
11094 break;
11096 tmo = timespec_sub (tmo_at, time_now);
11097 if (pselect (fd + 1, &fds, NULL, NULL, &tmo, NULL) == 0)
11098 break; /* Timeout */
11101 f->wait_event_type = 0;
11105 /* Change the size of frame F's X window to WIDTH/HEIGHT in the case F
11106 doesn't have a widget. If CHANGE_GRAVITY, change to
11107 top-left-corner window gravity for this size change and subsequent
11108 size changes. Otherwise leave the window gravity unchanged. */
11110 static void
11111 x_set_window_size_1 (struct frame *f, bool change_gravity,
11112 int width, int height)
11114 int pixelwidth = FRAME_TEXT_TO_PIXEL_WIDTH (f, width);
11115 int pixelheight = FRAME_TEXT_TO_PIXEL_HEIGHT (f, height);
11116 int old_width = FRAME_PIXEL_WIDTH (f);
11117 int old_height = FRAME_PIXEL_HEIGHT (f);
11118 Lisp_Object fullscreen = get_frame_param (f, Qfullscreen);
11120 if (change_gravity)
11121 f->win_gravity = NorthWestGravity;
11122 x_wm_set_size_hint (f, 0, false);
11124 /* When the frame is fullheight and we only want to change the width
11125 or it is fullwidth and we only want to change the height we should
11126 be able to preserve the fullscreen property. However, due to the
11127 fact that we have to send a resize request anyway, the window
11128 manager will abolish it. At least the respective size should
11129 remain unchanged but giving the frame back its normal size will
11130 be broken ... */
11131 if (EQ (fullscreen, Qfullwidth) && width == FRAME_TEXT_WIDTH (f))
11133 frame_size_history_add
11134 (f, Qx_set_window_size_1, width, height,
11135 list2 (make_number (old_height),
11136 make_number (pixelheight + FRAME_MENUBAR_HEIGHT (f))));
11138 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11139 old_width, pixelheight + FRAME_MENUBAR_HEIGHT (f));
11141 else if (EQ (fullscreen, Qfullheight) && height == FRAME_TEXT_HEIGHT (f))
11143 frame_size_history_add
11144 (f, Qx_set_window_size_2, width, height,
11145 list2 (make_number (old_width), make_number (pixelwidth)));
11147 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11148 pixelwidth, old_height);
11151 else
11153 frame_size_history_add
11154 (f, Qx_set_window_size_3, width, height,
11155 list3 (make_number (pixelwidth + FRAME_TOOLBAR_WIDTH (f)),
11156 make_number (pixelheight + FRAME_TOOLBAR_HEIGHT (f)
11157 + FRAME_MENUBAR_HEIGHT (f)),
11158 make_number (FRAME_MENUBAR_HEIGHT (f))));
11160 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11161 pixelwidth, pixelheight + FRAME_MENUBAR_HEIGHT (f));
11162 fullscreen = Qnil;
11167 /* We've set {FRAME,PIXEL}_{WIDTH,HEIGHT} to the values we hope to
11168 receive in the ConfigureNotify event; if we get what we asked
11169 for, then the event won't cause the screen to become garbaged, so
11170 we have to make sure to do it here. */
11171 SET_FRAME_GARBAGED (f);
11173 /* Now, strictly speaking, we can't be sure that this is accurate,
11174 but the window manager will get around to dealing with the size
11175 change request eventually, and we'll hear how it went when the
11176 ConfigureNotify event gets here.
11178 We could just not bother storing any of this information here,
11179 and let the ConfigureNotify event set everything up, but that
11180 might be kind of confusing to the Lisp code, since size changes
11181 wouldn't be reported in the frame parameters until some random
11182 point in the future when the ConfigureNotify event arrives.
11184 Pass true for DELAY since we can't run Lisp code inside of
11185 a BLOCK_INPUT. */
11187 /* But the ConfigureNotify may in fact never arrive, and then this is
11188 not right if the frame is visible. Instead wait (with timeout)
11189 for the ConfigureNotify. */
11190 if (FRAME_VISIBLE_P (f))
11192 x_wait_for_event (f, ConfigureNotify);
11194 if (!NILP (fullscreen))
11195 /* Try to restore fullscreen state. */
11197 store_frame_param (f, Qfullscreen, fullscreen);
11198 x_set_fullscreen (f, fullscreen, fullscreen);
11201 else
11203 change_frame_size (f, width, height, false, true, false, true);
11204 x_sync (f);
11209 /* Call this to change the size of frame F's x-window.
11210 If CHANGE_GRAVITY, change to top-left-corner window gravity
11211 for this size change and subsequent size changes.
11212 Otherwise we leave the window gravity unchanged. */
11214 void
11215 x_set_window_size (struct frame *f, bool change_gravity,
11216 int width, int height, bool pixelwise)
11218 block_input ();
11220 /* The following breaks our calculations. If it's really needed,
11221 think of something else. */
11222 #if false
11223 if (!FRAME_TOOLTIP_P (f))
11225 int text_width, text_height;
11227 /* When the frame is maximized/fullscreen or running under for
11228 example Xmonad, x_set_window_size_1 will be a no-op.
11229 In that case, the right thing to do is extend rows/width to
11230 the current frame size. We do that first if x_set_window_size_1
11231 turns out to not be a no-op (there is no way to know).
11232 The size will be adjusted again if the frame gets a
11233 ConfigureNotify event as a result of x_set_window_size. */
11234 int pixelh = FRAME_PIXEL_HEIGHT (f);
11235 #ifdef USE_X_TOOLKIT
11236 /* The menu bar is not part of text lines. The tool bar
11237 is however. */
11238 pixelh -= FRAME_MENUBAR_HEIGHT (f);
11239 #endif
11240 text_width = FRAME_PIXEL_TO_TEXT_WIDTH (f, FRAME_PIXEL_WIDTH (f));
11241 text_height = FRAME_PIXEL_TO_TEXT_HEIGHT (f, pixelh);
11243 change_frame_size (f, text_width, text_height, false, true, false, true);
11245 #endif
11247 /* Pixelize width and height, if necessary. */
11248 if (! pixelwise)
11250 width = width * FRAME_COLUMN_WIDTH (f);
11251 height = height * FRAME_LINE_HEIGHT (f);
11254 #ifdef USE_GTK
11255 if (FRAME_GTK_WIDGET (f))
11256 xg_frame_set_char_size (f, width, height);
11257 else
11258 x_set_window_size_1 (f, change_gravity, width, height);
11259 #else /* not USE_GTK */
11260 x_set_window_size_1 (f, change_gravity, width, height);
11261 x_clear_under_internal_border (f);
11262 #endif /* not USE_GTK */
11264 /* If cursor was outside the new size, mark it as off. */
11265 mark_window_cursors_off (XWINDOW (f->root_window));
11267 /* Clear out any recollection of where the mouse highlighting was,
11268 since it might be in a place that's outside the new frame size.
11269 Actually checking whether it is outside is a pain in the neck,
11270 so don't try--just let the highlighting be done afresh with new size. */
11271 cancel_mouse_face (f);
11273 unblock_input ();
11275 do_pending_window_change (false);
11278 /* Move the mouse to position pixel PIX_X, PIX_Y relative to frame F. */
11280 void
11281 frame_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
11283 block_input ();
11285 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
11286 0, 0, 0, 0, pix_x, pix_y);
11287 unblock_input ();
11290 /* Raise frame F. */
11292 void
11293 x_raise_frame (struct frame *f)
11295 block_input ();
11296 if (FRAME_VISIBLE_P (f))
11297 XRaiseWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
11298 XFlush (FRAME_X_DISPLAY (f));
11299 unblock_input ();
11302 /* Lower frame F. */
11304 static void
11305 x_lower_frame (struct frame *f)
11307 if (FRAME_VISIBLE_P (f))
11309 block_input ();
11310 XLowerWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
11311 XFlush (FRAME_X_DISPLAY (f));
11312 unblock_input ();
11316 /* Request focus with XEmbed */
11318 void
11319 xembed_request_focus (struct frame *f)
11321 /* See XEmbed Protocol Specification at
11322 http://freedesktop.org/wiki/Specifications/xembed-spec */
11323 if (FRAME_VISIBLE_P (f))
11324 xembed_send_message (f, CurrentTime,
11325 XEMBED_REQUEST_FOCUS, 0, 0, 0);
11328 /* Activate frame with Extended Window Manager Hints */
11330 void
11331 x_ewmh_activate_frame (struct frame *f)
11333 /* See Window Manager Specification/Extended Window Manager Hints at
11334 http://freedesktop.org/wiki/Specifications/wm-spec */
11336 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
11338 if (FRAME_VISIBLE_P (f) && x_wm_supports (f, dpyinfo->Xatom_net_active_window))
11340 Lisp_Object frame;
11341 XSETFRAME (frame, f);
11342 x_send_client_event (frame, make_number (0), frame,
11343 dpyinfo->Xatom_net_active_window,
11344 make_number (32),
11345 list2i (1, dpyinfo->last_user_time));
11349 static void
11350 XTframe_raise_lower (struct frame *f, bool raise_flag)
11352 if (raise_flag)
11353 x_raise_frame (f);
11354 else
11355 x_lower_frame (f);
11358 /* XEmbed implementation. */
11360 #if defined USE_X_TOOLKIT || ! defined USE_GTK
11362 /* XEmbed implementation. */
11364 #define XEMBED_VERSION 0
11366 static void
11367 xembed_set_info (struct frame *f, enum xembed_info flags)
11369 unsigned long data[2];
11370 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
11372 data[0] = XEMBED_VERSION;
11373 data[1] = flags;
11375 XChangeProperty (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11376 dpyinfo->Xatom_XEMBED_INFO, dpyinfo->Xatom_XEMBED_INFO,
11377 32, PropModeReplace, (unsigned char *) data, 2);
11379 #endif /* defined USE_X_TOOLKIT || ! defined USE_GTK */
11381 static void
11382 xembed_send_message (struct frame *f, Time t, enum xembed_message msg,
11383 long int detail, long int data1, long int data2)
11385 XEvent event;
11387 event.xclient.type = ClientMessage;
11388 event.xclient.window = FRAME_X_OUTPUT (f)->parent_desc;
11389 event.xclient.message_type = FRAME_DISPLAY_INFO (f)->Xatom_XEMBED;
11390 event.xclient.format = 32;
11391 event.xclient.data.l[0] = t;
11392 event.xclient.data.l[1] = msg;
11393 event.xclient.data.l[2] = detail;
11394 event.xclient.data.l[3] = data1;
11395 event.xclient.data.l[4] = data2;
11397 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_OUTPUT (f)->parent_desc,
11398 False, NoEventMask, &event);
11399 XSync (FRAME_X_DISPLAY (f), False);
11402 /* Change of visibility. */
11404 /* This tries to wait until the frame is really visible, depending on
11405 the value of Vx_wait_for_event_timeout.
11406 However, if the window manager asks the user where to position
11407 the frame, this will return before the user finishes doing that.
11408 The frame will not actually be visible at that time,
11409 but it will become visible later when the window manager
11410 finishes with it. */
11412 void
11413 x_make_frame_visible (struct frame *f)
11415 if (FRAME_PARENT_FRAME (f))
11417 if (!FRAME_VISIBLE_P (f))
11419 block_input ();
11420 #ifdef USE_GTK
11421 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
11422 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11423 f->left_pos, f->top_pos);
11424 #else
11425 XMapRaised (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
11426 #endif
11427 unblock_input ();
11429 SET_FRAME_VISIBLE (f, true);
11430 SET_FRAME_ICONIFIED (f, false);
11432 return;
11435 block_input ();
11437 x_set_bitmap_icon (f);
11439 if (! FRAME_VISIBLE_P (f))
11441 /* We test asked_for_visible here to make sure we don't
11442 call x_set_offset a second time
11443 if we get to x_make_frame_visible a second time
11444 before the window gets really visible. */
11445 if (! FRAME_ICONIFIED_P (f)
11446 && ! FRAME_X_EMBEDDED_P (f)
11447 && ! f->output_data.x->asked_for_visible)
11448 x_set_offset (f, f->left_pos, f->top_pos, 0);
11450 f->output_data.x->asked_for_visible = true;
11452 if (! EQ (Vx_no_window_manager, Qt))
11453 x_wm_set_window_state (f, NormalState);
11454 #ifdef USE_X_TOOLKIT
11455 if (FRAME_X_EMBEDDED_P (f))
11456 xembed_set_info (f, XEMBED_MAPPED);
11457 else
11459 /* This was XtPopup, but that did nothing for an iconified frame. */
11460 XtMapWidget (f->output_data.x->widget);
11462 #else /* not USE_X_TOOLKIT */
11463 #ifdef USE_GTK
11464 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
11465 gtk_window_deiconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
11466 #else
11467 if (FRAME_X_EMBEDDED_P (f))
11468 xembed_set_info (f, XEMBED_MAPPED);
11469 else
11470 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11471 #endif /* not USE_GTK */
11472 #endif /* not USE_X_TOOLKIT */
11475 XFlush (FRAME_X_DISPLAY (f));
11477 /* Synchronize to ensure Emacs knows the frame is visible
11478 before we do anything else. We do this loop with input not blocked
11479 so that incoming events are handled. */
11481 Lisp_Object frame;
11482 /* This must be before UNBLOCK_INPUT
11483 since events that arrive in response to the actions above
11484 will set it when they are handled. */
11485 bool previously_visible = f->output_data.x->has_been_visible;
11487 XSETFRAME (frame, f);
11489 int original_left = f->left_pos;
11490 int original_top = f->top_pos;
11492 /* This must come after we set COUNT. */
11493 unblock_input ();
11495 /* We unblock here so that arriving X events are processed. */
11497 /* Now move the window back to where it was "supposed to be".
11498 But don't do it if the gravity is negative.
11499 When the gravity is negative, this uses a position
11500 that is 3 pixels too low. Perhaps that's really the border width.
11502 Don't do this if the window has never been visible before,
11503 because the window manager may choose the position
11504 and we don't want to override it. */
11506 if (!FRAME_VISIBLE_P (f)
11507 && !FRAME_ICONIFIED_P (f)
11508 && !FRAME_X_EMBEDDED_P (f)
11509 && !FRAME_PARENT_FRAME (f)
11510 && f->win_gravity == NorthWestGravity
11511 && previously_visible)
11513 Drawable rootw;
11514 int x, y;
11515 unsigned int width, height, border, depth;
11517 block_input ();
11519 /* On some window managers (such as FVWM) moving an existing
11520 window, even to the same place, causes the window manager
11521 to introduce an offset. This can cause the window to move
11522 to an unexpected location. Check the geometry (a little
11523 slow here) and then verify that the window is in the right
11524 place. If the window is not in the right place, move it
11525 there, and take the potential window manager hit. */
11526 XGetGeometry (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11527 &rootw, &x, &y, &width, &height, &border, &depth);
11529 if (original_left != x || original_top != y)
11530 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11531 original_left, original_top);
11533 unblock_input ();
11536 /* Try to wait for a MapNotify event (that is what tells us when a
11537 frame becomes visible). */
11539 #ifdef CYGWIN
11540 /* On Cygwin, which uses input polling, we need to force input to
11541 be read. See
11542 https://lists.gnu.org/r/emacs-devel/2013-12/msg00351.html
11543 and https://debbugs.gnu.org/cgi/bugreport.cgi?bug=24091#131.
11544 Fake an alarm signal to let the handler know that there's
11545 something to be read.
11547 It could be confusing if a real alarm arrives while processing
11548 the fake one. Turn it off and let the handler reset it. */
11549 int old_poll_suppress_count = poll_suppress_count;
11550 poll_suppress_count = 1;
11551 poll_for_input_1 ();
11552 poll_suppress_count = old_poll_suppress_count;
11553 #endif
11554 x_wait_for_event (f, MapNotify);
11558 /* Change from mapped state to withdrawn state. */
11560 /* Make the frame visible (mapped and not iconified). */
11562 void
11563 x_make_frame_invisible (struct frame *f)
11565 Window window;
11567 /* Use the frame's outermost window, not the one we normally draw on. */
11568 window = FRAME_OUTER_WINDOW (f);
11570 /* Don't keep the highlight on an invisible frame. */
11571 if (FRAME_DISPLAY_INFO (f)->x_highlight_frame == f)
11572 FRAME_DISPLAY_INFO (f)->x_highlight_frame = 0;
11574 block_input ();
11576 /* Before unmapping the window, update the WM_SIZE_HINTS property to claim
11577 that the current position of the window is user-specified, rather than
11578 program-specified, so that when the window is mapped again, it will be
11579 placed at the same location, without forcing the user to position it
11580 by hand again (they have already done that once for this window.) */
11581 x_wm_set_size_hint (f, 0, true);
11583 #ifdef USE_GTK
11584 if (FRAME_GTK_OUTER_WIDGET (f))
11585 gtk_widget_hide (FRAME_GTK_OUTER_WIDGET (f));
11586 else
11587 #else
11588 if (FRAME_X_EMBEDDED_P (f))
11589 xembed_set_info (f, 0);
11590 else
11591 #endif
11593 if (! XWithdrawWindow (FRAME_X_DISPLAY (f), window,
11594 DefaultScreen (FRAME_X_DISPLAY (f))))
11596 unblock_input ();
11597 error ("Can't notify window manager of window withdrawal");
11600 x_sync (f);
11602 /* We can't distinguish this from iconification
11603 just by the event that we get from the server.
11604 So we can't win using the usual strategy of letting
11605 FRAME_SAMPLE_VISIBILITY set this. So do it by hand,
11606 and synchronize with the server to make sure we agree. */
11607 SET_FRAME_VISIBLE (f, 0);
11608 SET_FRAME_ICONIFIED (f, false);
11610 unblock_input ();
11613 /* Change window state from mapped to iconified. */
11615 void
11616 x_iconify_frame (struct frame *f)
11618 #ifdef USE_X_TOOLKIT
11619 int result;
11620 #endif
11622 /* Don't keep the highlight on an invisible frame. */
11623 if (FRAME_DISPLAY_INFO (f)->x_highlight_frame == f)
11624 FRAME_DISPLAY_INFO (f)->x_highlight_frame = 0;
11626 if (FRAME_ICONIFIED_P (f))
11627 return;
11629 block_input ();
11631 x_set_bitmap_icon (f);
11633 #if defined (USE_GTK)
11634 if (FRAME_GTK_OUTER_WIDGET (f))
11636 if (! FRAME_VISIBLE_P (f))
11637 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
11639 gtk_window_iconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
11640 SET_FRAME_VISIBLE (f, 0);
11641 SET_FRAME_ICONIFIED (f, true);
11642 unblock_input ();
11643 return;
11645 #endif
11647 #ifdef USE_X_TOOLKIT
11649 if (! FRAME_VISIBLE_P (f))
11651 if (! EQ (Vx_no_window_manager, Qt))
11652 x_wm_set_window_state (f, IconicState);
11653 /* This was XtPopup, but that did nothing for an iconified frame. */
11654 XtMapWidget (f->output_data.x->widget);
11655 /* The server won't give us any event to indicate
11656 that an invisible frame was changed to an icon,
11657 so we have to record it here. */
11658 SET_FRAME_VISIBLE (f, 0);
11659 SET_FRAME_ICONIFIED (f, true);
11660 unblock_input ();
11661 return;
11664 result = XIconifyWindow (FRAME_X_DISPLAY (f),
11665 XtWindow (f->output_data.x->widget),
11666 DefaultScreen (FRAME_X_DISPLAY (f)));
11667 unblock_input ();
11669 if (!result)
11670 error ("Can't notify window manager of iconification");
11672 SET_FRAME_ICONIFIED (f, true);
11673 SET_FRAME_VISIBLE (f, 0);
11675 block_input ();
11676 XFlush (FRAME_X_DISPLAY (f));
11677 unblock_input ();
11678 #else /* not USE_X_TOOLKIT */
11680 /* Make sure the X server knows where the window should be positioned,
11681 in case the user deiconifies with the window manager. */
11682 if (! FRAME_VISIBLE_P (f)
11683 && ! FRAME_ICONIFIED_P (f)
11684 && ! FRAME_X_EMBEDDED_P (f))
11685 x_set_offset (f, f->left_pos, f->top_pos, 0);
11687 /* Since we don't know which revision of X we're running, we'll use both
11688 the X11R3 and X11R4 techniques. I don't know if this is a good idea. */
11690 /* X11R4: send a ClientMessage to the window manager using the
11691 WM_CHANGE_STATE type. */
11693 XEvent msg;
11695 msg.xclient.window = FRAME_X_WINDOW (f);
11696 msg.xclient.type = ClientMessage;
11697 msg.xclient.message_type = FRAME_DISPLAY_INFO (f)->Xatom_wm_change_state;
11698 msg.xclient.format = 32;
11699 msg.xclient.data.l[0] = IconicState;
11701 if (! XSendEvent (FRAME_X_DISPLAY (f),
11702 DefaultRootWindow (FRAME_X_DISPLAY (f)),
11703 False,
11704 SubstructureRedirectMask | SubstructureNotifyMask,
11705 &msg))
11707 unblock_input ();
11708 error ("Can't notify window manager of iconification");
11712 /* X11R3: set the initial_state field of the window manager hints to
11713 IconicState. */
11714 x_wm_set_window_state (f, IconicState);
11716 if (!FRAME_VISIBLE_P (f))
11718 /* If the frame was withdrawn, before, we must map it. */
11719 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11722 SET_FRAME_ICONIFIED (f, true);
11723 SET_FRAME_VISIBLE (f, 0);
11725 XFlush (FRAME_X_DISPLAY (f));
11726 unblock_input ();
11727 #endif /* not USE_X_TOOLKIT */
11731 /* Free X resources of frame F. */
11733 void
11734 x_free_frame_resources (struct frame *f)
11736 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
11737 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
11738 #ifdef USE_X_TOOLKIT
11739 Lisp_Object bar;
11740 struct scroll_bar *b;
11741 #endif
11743 block_input ();
11745 /* If a display connection is dead, don't try sending more
11746 commands to the X server. */
11747 if (dpyinfo->display)
11749 /* Always exit with visible pointer to avoid weird issue
11750 with Xfixes (Bug#17609). */
11751 if (f->pointer_invisible)
11752 FRAME_DISPLAY_INFO (f)->toggle_visible_pointer (f, 0);
11754 /* We must free faces before destroying windows because some
11755 font-driver (e.g. xft) access a window while finishing a
11756 face. */
11757 free_frame_faces (f);
11758 tear_down_x_back_buffer (f);
11760 if (f->output_data.x->icon_desc)
11761 XDestroyWindow (FRAME_X_DISPLAY (f), f->output_data.x->icon_desc);
11763 #ifdef USE_X_TOOLKIT
11764 /* Explicitly destroy the scroll bars of the frame. Without
11765 this, we get "BadDrawable" errors from the toolkit later on,
11766 presumably from expose events generated for the disappearing
11767 toolkit scroll bars. */
11768 for (bar = FRAME_SCROLL_BARS (f); !NILP (bar); bar = b->next)
11770 b = XSCROLL_BAR (bar);
11771 x_scroll_bar_remove (b);
11773 #endif
11775 #ifdef HAVE_X_I18N
11776 if (FRAME_XIC (f))
11777 free_frame_xic (f);
11778 #endif
11780 x_free_cr_resources (f);
11781 #ifdef USE_X_TOOLKIT
11782 if (f->output_data.x->widget)
11784 XtDestroyWidget (f->output_data.x->widget);
11785 f->output_data.x->widget = NULL;
11787 /* Tooltips don't have widgets, only a simple X window, even if
11788 we are using a toolkit. */
11789 else if (FRAME_X_WINDOW (f))
11790 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11792 free_frame_menubar (f);
11794 if (f->shell_position)
11795 xfree (f->shell_position);
11796 #else /* !USE_X_TOOLKIT */
11798 #ifdef USE_GTK
11799 xg_free_frame_widgets (f);
11800 #endif /* USE_GTK */
11802 tear_down_x_back_buffer (f);
11803 if (FRAME_X_WINDOW (f))
11804 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11805 #endif /* !USE_X_TOOLKIT */
11807 unload_color (f, FRAME_FOREGROUND_PIXEL (f));
11808 unload_color (f, FRAME_BACKGROUND_PIXEL (f));
11809 unload_color (f, f->output_data.x->cursor_pixel);
11810 unload_color (f, f->output_data.x->cursor_foreground_pixel);
11811 unload_color (f, f->output_data.x->border_pixel);
11812 unload_color (f, f->output_data.x->mouse_pixel);
11814 if (f->output_data.x->scroll_bar_background_pixel != -1)
11815 unload_color (f, f->output_data.x->scroll_bar_background_pixel);
11816 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
11817 unload_color (f, f->output_data.x->scroll_bar_foreground_pixel);
11818 #if defined (USE_LUCID) && defined (USE_TOOLKIT_SCROLL_BARS)
11819 /* Scrollbar shadow colors. */
11820 if (f->output_data.x->scroll_bar_top_shadow_pixel != -1)
11821 unload_color (f, f->output_data.x->scroll_bar_top_shadow_pixel);
11822 if (f->output_data.x->scroll_bar_bottom_shadow_pixel != -1)
11823 unload_color (f, f->output_data.x->scroll_bar_bottom_shadow_pixel);
11824 #endif /* USE_LUCID && USE_TOOLKIT_SCROLL_BARS */
11825 if (f->output_data.x->white_relief.pixel != -1)
11826 unload_color (f, f->output_data.x->white_relief.pixel);
11827 if (f->output_data.x->black_relief.pixel != -1)
11828 unload_color (f, f->output_data.x->black_relief.pixel);
11830 x_free_gcs (f);
11832 /* Free extra GCs allocated by x_setup_relief_colors. */
11833 if (f->output_data.x->white_relief.gc)
11835 XFreeGC (dpyinfo->display, f->output_data.x->white_relief.gc);
11836 f->output_data.x->white_relief.gc = 0;
11838 if (f->output_data.x->black_relief.gc)
11840 XFreeGC (dpyinfo->display, f->output_data.x->black_relief.gc);
11841 f->output_data.x->black_relief.gc = 0;
11844 /* Free cursors. */
11845 if (f->output_data.x->text_cursor != 0)
11846 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->text_cursor);
11847 if (f->output_data.x->nontext_cursor != 0)
11848 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->nontext_cursor);
11849 if (f->output_data.x->modeline_cursor != 0)
11850 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->modeline_cursor);
11851 if (f->output_data.x->hand_cursor != 0)
11852 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->hand_cursor);
11853 if (f->output_data.x->hourglass_cursor != 0)
11854 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->hourglass_cursor);
11855 if (f->output_data.x->horizontal_drag_cursor != 0)
11856 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->horizontal_drag_cursor);
11857 if (f->output_data.x->vertical_drag_cursor != 0)
11858 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->vertical_drag_cursor);
11859 if (f->output_data.x->left_edge_cursor != 0)
11860 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->left_edge_cursor);
11861 if (f->output_data.x->top_left_corner_cursor != 0)
11862 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->top_left_corner_cursor);
11863 if (f->output_data.x->top_edge_cursor != 0)
11864 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->top_edge_cursor);
11865 if (f->output_data.x->top_right_corner_cursor != 0)
11866 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->top_right_corner_cursor);
11867 if (f->output_data.x->right_edge_cursor != 0)
11868 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->right_edge_cursor);
11869 if (f->output_data.x->bottom_right_corner_cursor != 0)
11870 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->bottom_right_corner_cursor);
11871 if (f->output_data.x->bottom_edge_cursor != 0)
11872 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->bottom_edge_cursor);
11873 if (f->output_data.x->bottom_left_corner_cursor != 0)
11874 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->bottom_left_corner_cursor);
11876 XFlush (FRAME_X_DISPLAY (f));
11879 xfree (f->output_data.x->saved_menu_event);
11880 xfree (f->output_data.x);
11881 f->output_data.x = NULL;
11883 if (f == dpyinfo->x_focus_frame)
11884 dpyinfo->x_focus_frame = 0;
11885 if (f == dpyinfo->x_focus_event_frame)
11886 dpyinfo->x_focus_event_frame = 0;
11887 if (f == dpyinfo->x_highlight_frame)
11888 dpyinfo->x_highlight_frame = 0;
11889 if (f == hlinfo->mouse_face_mouse_frame)
11890 reset_mouse_highlight (hlinfo);
11892 unblock_input ();
11896 /* Destroy the X window of frame F. */
11898 static void
11899 x_destroy_window (struct frame *f)
11901 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
11903 /* If a display connection is dead, don't try sending more
11904 commands to the X server. */
11905 if (dpyinfo->display != 0)
11906 x_free_frame_resources (f);
11908 dpyinfo->reference_count--;
11912 /* Setting window manager hints. */
11914 /* Set the normal size hints for the window manager, for frame F.
11915 FLAGS is the flags word to use--or 0 meaning preserve the flags
11916 that the window now has.
11917 If USER_POSITION, set the USPosition
11918 flag (this is useful when FLAGS is 0).
11919 The GTK version is in gtkutils.c. */
11921 #ifndef USE_GTK
11922 void
11923 x_wm_set_size_hint (struct frame *f, long flags, bool user_position)
11925 XSizeHints size_hints;
11926 Window window = FRAME_OUTER_WINDOW (f);
11928 if (!window)
11929 return;
11931 #ifdef USE_X_TOOLKIT
11932 if (f->output_data.x->widget)
11934 widget_update_wm_size_hints (f->output_data.x->widget);
11935 return;
11937 #endif
11939 /* Setting PMaxSize caused various problems. */
11940 size_hints.flags = PResizeInc | PMinSize /* | PMaxSize */;
11942 size_hints.x = f->left_pos;
11943 size_hints.y = f->top_pos;
11945 size_hints.width = FRAME_PIXEL_WIDTH (f);
11946 size_hints.height = FRAME_PIXEL_HEIGHT (f);
11948 size_hints.width_inc = frame_resize_pixelwise ? 1 : FRAME_COLUMN_WIDTH (f);
11949 size_hints.height_inc = frame_resize_pixelwise ? 1 : FRAME_LINE_HEIGHT (f);
11951 size_hints.max_width = x_display_pixel_width (FRAME_DISPLAY_INFO (f))
11952 - FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
11953 size_hints.max_height = x_display_pixel_height (FRAME_DISPLAY_INFO (f))
11954 - FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
11956 /* Calculate the base and minimum sizes. */
11958 int base_width, base_height;
11960 base_width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
11961 base_height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
11963 /* The window manager uses the base width hints to calculate the
11964 current number of rows and columns in the frame while
11965 resizing; min_width and min_height aren't useful for this
11966 purpose, since they might not give the dimensions for a
11967 zero-row, zero-column frame. */
11969 size_hints.flags |= PBaseSize;
11970 size_hints.base_width = base_width;
11971 size_hints.base_height = base_height + FRAME_MENUBAR_HEIGHT (f);
11972 size_hints.min_width = base_width;
11973 size_hints.min_height = base_height;
11976 /* If we don't need the old flags, we don't need the old hint at all. */
11977 if (flags)
11979 size_hints.flags |= flags;
11980 goto no_read;
11984 XSizeHints hints; /* Sometimes I hate X Windows... */
11985 long supplied_return;
11986 int value;
11988 value = XGetWMNormalHints (FRAME_X_DISPLAY (f), window, &hints,
11989 &supplied_return);
11991 if (flags)
11992 size_hints.flags |= flags;
11993 else
11995 if (value == 0)
11996 hints.flags = 0;
11997 if (hints.flags & PSize)
11998 size_hints.flags |= PSize;
11999 if (hints.flags & PPosition)
12000 size_hints.flags |= PPosition;
12001 if (hints.flags & USPosition)
12002 size_hints.flags |= USPosition;
12003 if (hints.flags & USSize)
12004 size_hints.flags |= USSize;
12008 no_read:
12010 #ifdef PWinGravity
12011 size_hints.win_gravity = f->win_gravity;
12012 size_hints.flags |= PWinGravity;
12014 if (user_position)
12016 size_hints.flags &= ~ PPosition;
12017 size_hints.flags |= USPosition;
12019 #endif /* PWinGravity */
12021 XSetWMNormalHints (FRAME_X_DISPLAY (f), window, &size_hints);
12023 #endif /* not USE_GTK */
12025 /* Used for IconicState or NormalState */
12027 static void
12028 x_wm_set_window_state (struct frame *f, int state)
12030 #ifdef USE_X_TOOLKIT
12031 Arg al[1];
12033 XtSetArg (al[0], XtNinitialState, state);
12034 XtSetValues (f->output_data.x->widget, al, 1);
12035 #else /* not USE_X_TOOLKIT */
12036 Window window = FRAME_X_WINDOW (f);
12038 f->output_data.x->wm_hints.flags |= StateHint;
12039 f->output_data.x->wm_hints.initial_state = state;
12041 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
12042 #endif /* not USE_X_TOOLKIT */
12045 static void
12046 x_wm_set_icon_pixmap (struct frame *f, ptrdiff_t pixmap_id)
12048 Pixmap icon_pixmap, icon_mask;
12050 #if !defined USE_X_TOOLKIT && !defined USE_GTK
12051 Window window = FRAME_OUTER_WINDOW (f);
12052 #endif
12054 if (pixmap_id > 0)
12056 icon_pixmap = x_bitmap_pixmap (f, pixmap_id);
12057 f->output_data.x->wm_hints.icon_pixmap = icon_pixmap;
12058 icon_mask = x_bitmap_mask (f, pixmap_id);
12059 f->output_data.x->wm_hints.icon_mask = icon_mask;
12061 else
12063 /* It seems there is no way to turn off use of an icon
12064 pixmap. */
12065 return;
12069 #ifdef USE_GTK
12071 xg_set_frame_icon (f, icon_pixmap, icon_mask);
12072 return;
12075 #elif defined (USE_X_TOOLKIT) /* same as in x_wm_set_window_state. */
12078 Arg al[1];
12079 XtSetArg (al[0], XtNiconPixmap, icon_pixmap);
12080 XtSetValues (f->output_data.x->widget, al, 1);
12081 XtSetArg (al[0], XtNiconMask, icon_mask);
12082 XtSetValues (f->output_data.x->widget, al, 1);
12085 #else /* not USE_X_TOOLKIT && not USE_GTK */
12087 f->output_data.x->wm_hints.flags |= (IconPixmapHint | IconMaskHint);
12088 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
12090 #endif /* not USE_X_TOOLKIT && not USE_GTK */
12093 void
12094 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
12096 Window window = FRAME_OUTER_WINDOW (f);
12098 f->output_data.x->wm_hints.flags |= IconPositionHint;
12099 f->output_data.x->wm_hints.icon_x = icon_x;
12100 f->output_data.x->wm_hints.icon_y = icon_y;
12102 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
12106 /***********************************************************************
12107 Fonts
12108 ***********************************************************************/
12110 #ifdef GLYPH_DEBUG
12112 /* Check that FONT is valid on frame F. It is if it can be found in F's
12113 font table. */
12115 static void
12116 x_check_font (struct frame *f, struct font *font)
12118 eassert (font != NULL && ! NILP (font->props[FONT_TYPE_INDEX]));
12119 if (font->driver->check)
12120 eassert (font->driver->check (f, font) == 0);
12123 #endif /* GLYPH_DEBUG */
12126 /***********************************************************************
12127 Initialization
12128 ***********************************************************************/
12130 #ifdef USE_X_TOOLKIT
12131 static XrmOptionDescRec emacs_options[] = {
12132 {(char *) "-geometry", (char *) ".geometry", XrmoptionSepArg, NULL},
12133 {(char *) "-iconic", (char *) ".iconic", XrmoptionNoArg, (XtPointer) "yes"},
12135 {(char *) "-internal-border-width",
12136 (char *) "*EmacsScreen.internalBorderWidth", XrmoptionSepArg, NULL},
12137 {(char *) "-ib", (char *) "*EmacsScreen.internalBorderWidth",
12138 XrmoptionSepArg, NULL},
12139 {(char *) "-T", (char *) "*EmacsShell.title", XrmoptionSepArg, NULL},
12140 {(char *) "-wn", (char *) "*EmacsShell.title", XrmoptionSepArg, NULL},
12141 {(char *) "-title", (char *) "*EmacsShell.title", XrmoptionSepArg, NULL},
12142 {(char *) "-iconname", (char *) "*EmacsShell.iconName",
12143 XrmoptionSepArg, NULL},
12144 {(char *) "-in", (char *) "*EmacsShell.iconName", XrmoptionSepArg, NULL},
12145 {(char *) "-mc", (char *) "*pointerColor", XrmoptionSepArg, NULL},
12146 {(char *) "-cr", (char *) "*cursorColor", XrmoptionSepArg, NULL}
12149 /* Whether atimer for Xt timeouts is activated or not. */
12151 static bool x_timeout_atimer_activated_flag;
12153 #endif /* USE_X_TOOLKIT */
12155 static int x_initialized;
12157 /* Test whether two display-name strings agree up to the dot that separates
12158 the screen number from the server number. */
12159 static bool
12160 same_x_server (const char *name1, const char *name2)
12162 bool seen_colon = false;
12163 Lisp_Object sysname = Fsystem_name ();
12164 if (! STRINGP (sysname))
12165 sysname = empty_unibyte_string;
12166 const char *system_name = SSDATA (sysname);
12167 ptrdiff_t system_name_length = SBYTES (sysname);
12168 ptrdiff_t length_until_period = 0;
12170 while (system_name[length_until_period] != 0
12171 && system_name[length_until_period] != '.')
12172 length_until_period++;
12174 /* Treat `unix' like an empty host name. */
12175 if (! strncmp (name1, "unix:", 5))
12176 name1 += 4;
12177 if (! strncmp (name2, "unix:", 5))
12178 name2 += 4;
12179 /* Treat this host's name like an empty host name. */
12180 if (! strncmp (name1, system_name, system_name_length)
12181 && name1[system_name_length] == ':')
12182 name1 += system_name_length;
12183 if (! strncmp (name2, system_name, system_name_length)
12184 && name2[system_name_length] == ':')
12185 name2 += system_name_length;
12186 /* Treat this host's domainless name like an empty host name. */
12187 if (! strncmp (name1, system_name, length_until_period)
12188 && name1[length_until_period] == ':')
12189 name1 += length_until_period;
12190 if (! strncmp (name2, system_name, length_until_period)
12191 && name2[length_until_period] == ':')
12192 name2 += length_until_period;
12194 for (; *name1 != '\0' && *name1 == *name2; name1++, name2++)
12196 if (*name1 == ':')
12197 seen_colon = true;
12198 if (seen_colon && *name1 == '.')
12199 return true;
12201 return (seen_colon
12202 && (*name1 == '.' || *name1 == '\0')
12203 && (*name2 == '.' || *name2 == '\0'));
12206 /* Count number of set bits in mask and number of bits to shift to
12207 get to the first bit. With MASK 0x7e0, *BITS is set to 6, and *OFFSET
12208 to 5. */
12209 static void
12210 get_bits_and_offset (unsigned long mask, int *bits, int *offset)
12212 int nr = 0;
12213 int off = 0;
12215 while (!(mask & 1))
12217 off++;
12218 mask >>= 1;
12221 while (mask & 1)
12223 nr++;
12224 mask >>= 1;
12227 *offset = off;
12228 *bits = nr;
12231 /* Return true iff display DISPLAY is available for use.
12232 But don't permanently open it, just test its availability. */
12234 bool
12235 x_display_ok (const char *display)
12237 /* XOpenDisplay fails if it gets a signal. Block SIGIO which may arrive. */
12238 unrequest_sigio ();
12239 Display *dpy = XOpenDisplay (display);
12240 request_sigio ();
12241 if (!dpy)
12242 return false;
12243 XCloseDisplay (dpy);
12244 return true;
12247 #ifdef USE_GTK
12248 static void
12249 my_log_handler (const gchar *log_domain, GLogLevelFlags log_level,
12250 const gchar *msg, gpointer user_data)
12252 if (!strstr (msg, "g_set_prgname"))
12253 fprintf (stderr, "%s-WARNING **: %s\n", log_domain, msg);
12255 #endif
12257 /* Create invisible cursor on X display referred by DPYINFO. */
12259 static Cursor
12260 make_invisible_cursor (struct x_display_info *dpyinfo)
12262 Display *dpy = dpyinfo->display;
12263 static char const no_data[] = { 0 };
12264 Pixmap pix;
12265 XColor col;
12266 Cursor c = 0;
12268 x_catch_errors (dpy);
12269 pix = XCreateBitmapFromData (dpy, dpyinfo->root_window, no_data, 1, 1);
12270 if (! x_had_errors_p (dpy) && pix != None)
12272 Cursor pixc;
12273 col.pixel = 0;
12274 col.red = col.green = col.blue = 0;
12275 col.flags = DoRed | DoGreen | DoBlue;
12276 pixc = XCreatePixmapCursor (dpy, pix, pix, &col, &col, 0, 0);
12277 if (! x_had_errors_p (dpy) && pixc != None)
12278 c = pixc;
12279 XFreePixmap (dpy, pix);
12282 x_uncatch_errors ();
12284 return c;
12287 /* True if DPY supports Xfixes extension >= 4. */
12289 static bool
12290 x_probe_xfixes_extension (Display *dpy)
12292 #ifdef HAVE_XFIXES
12293 int major, minor;
12294 return XFixesQueryVersion (dpy, &major, &minor) && major >= 4;
12295 #else
12296 return false;
12297 #endif /* HAVE_XFIXES */
12300 /* Toggle mouse pointer visibility on frame F by using Xfixes functions. */
12302 static void
12303 xfixes_toggle_visible_pointer (struct frame *f, bool invisible)
12305 #ifdef HAVE_XFIXES
12306 if (invisible)
12307 XFixesHideCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
12308 else
12309 XFixesShowCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
12310 f->pointer_invisible = invisible;
12311 #else
12312 emacs_abort ();
12313 #endif /* HAVE_XFIXES */
12316 /* Toggle mouse pointer visibility on frame F by using invisible cursor. */
12318 static void
12319 x_toggle_visible_pointer (struct frame *f, bool invisible)
12321 eassert (FRAME_DISPLAY_INFO (f)->invisible_cursor != 0);
12322 if (invisible)
12323 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
12324 FRAME_DISPLAY_INFO (f)->invisible_cursor);
12325 else
12326 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
12327 f->output_data.x->current_cursor);
12328 f->pointer_invisible = invisible;
12331 /* Setup pointer blanking, prefer Xfixes if available. */
12333 static void
12334 x_setup_pointer_blanking (struct x_display_info *dpyinfo)
12336 /* FIXME: the brave tester should set EMACS_XFIXES because we're suspecting
12337 X server bug, see https://debbugs.gnu.org/cgi/bugreport.cgi?bug=17609. */
12338 if (egetenv ("EMACS_XFIXES") && x_probe_xfixes_extension (dpyinfo->display))
12339 dpyinfo->toggle_visible_pointer = xfixes_toggle_visible_pointer;
12340 else
12342 dpyinfo->toggle_visible_pointer = x_toggle_visible_pointer;
12343 dpyinfo->invisible_cursor = make_invisible_cursor (dpyinfo);
12347 /* Current X display connection identifier. Incremented for each next
12348 connection established. */
12349 static unsigned x_display_id;
12351 /* Open a connection to X display DISPLAY_NAME, and return
12352 the structure that describes the open display.
12353 If we cannot contact the display, return null. */
12355 struct x_display_info *
12356 x_term_init (Lisp_Object display_name, char *xrm_option, char *resource_name)
12358 Display *dpy;
12359 struct terminal *terminal;
12360 struct x_display_info *dpyinfo;
12361 XrmDatabase xrdb;
12362 #ifdef USE_XCB
12363 xcb_connection_t *xcb_conn;
12364 #endif
12366 block_input ();
12368 if (!x_initialized)
12370 x_initialize ();
12371 ++x_initialized;
12374 if (! x_display_ok (SSDATA (display_name)))
12375 error ("Display %s can't be opened", SSDATA (display_name));
12377 #ifdef USE_GTK
12379 #define NUM_ARGV 10
12380 int argc;
12381 char *argv[NUM_ARGV];
12382 char **argv2 = argv;
12383 guint id;
12385 if (x_initialized++ > 1)
12387 xg_display_open (SSDATA (display_name), &dpy);
12389 else
12391 static char display_opt[] = "--display";
12392 static char name_opt[] = "--name";
12394 for (argc = 0; argc < NUM_ARGV; ++argc)
12395 argv[argc] = 0;
12397 argc = 0;
12398 argv[argc++] = initial_argv[0];
12400 if (! NILP (display_name))
12402 argv[argc++] = display_opt;
12403 argv[argc++] = SSDATA (display_name);
12406 argv[argc++] = name_opt;
12407 argv[argc++] = resource_name;
12409 XSetLocaleModifiers ("");
12411 /* Work around GLib bug that outputs a faulty warning. See
12412 https://bugzilla.gnome.org/show_bug.cgi?id=563627. */
12413 id = g_log_set_handler ("GLib", G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
12414 | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
12416 /* NULL window -> events for all windows go to our function.
12417 Call before gtk_init so Gtk+ event filters comes after our. */
12418 gdk_window_add_filter (NULL, event_handler_gdk, NULL);
12420 /* gtk_init does set_locale. Fix locale before and after. */
12421 fixup_locale ();
12422 unrequest_sigio (); /* See comment in x_display_ok. */
12423 gtk_init (&argc, &argv2);
12424 request_sigio ();
12425 fixup_locale ();
12427 g_log_remove_handler ("GLib", id);
12429 xg_initialize ();
12431 dpy = DEFAULT_GDK_DISPLAY ();
12433 #if ! GTK_CHECK_VERSION (2, 90, 0)
12434 /* Load our own gtkrc if it exists. */
12436 const char *file = "~/.emacs.d/gtkrc";
12437 Lisp_Object s, abs_file;
12439 s = build_string (file);
12440 abs_file = Fexpand_file_name (s, Qnil);
12442 if (! NILP (abs_file) && !NILP (Ffile_readable_p (abs_file)))
12443 gtk_rc_parse (SSDATA (abs_file));
12445 #endif
12447 XSetErrorHandler (x_error_handler);
12448 XSetIOErrorHandler (x_io_error_quitter);
12451 #else /* not USE_GTK */
12452 #ifdef USE_X_TOOLKIT
12453 /* weiner@footloose.sps.mot.com reports that this causes
12454 errors with X11R5:
12455 X protocol error: BadAtom (invalid Atom parameter)
12456 on protocol request 18skiloaf.
12457 So let's not use it until R6. */
12458 #ifdef HAVE_X11XTR6
12459 XtSetLanguageProc (NULL, NULL, NULL);
12460 #endif
12463 int argc = 0;
12464 char *argv[3];
12466 argv[0] = (char *) "";
12467 argc = 1;
12468 if (xrm_option)
12470 argv[argc++] = (char *) "-xrm";
12471 argv[argc++] = xrm_option;
12473 turn_on_atimers (false);
12474 unrequest_sigio (); /* See comment in x_display_ok. */
12475 dpy = XtOpenDisplay (Xt_app_con, SSDATA (display_name),
12476 resource_name, EMACS_CLASS,
12477 emacs_options, XtNumber (emacs_options),
12478 &argc, argv);
12479 request_sigio ();
12480 turn_on_atimers (true);
12482 #ifdef HAVE_X11XTR6
12483 /* I think this is to compensate for XtSetLanguageProc. */
12484 fixup_locale ();
12485 #endif
12488 #else /* not USE_X_TOOLKIT */
12489 XSetLocaleModifiers ("");
12490 unrequest_sigio (); /* See comment in x_display_ok. */
12491 dpy = XOpenDisplay (SSDATA (display_name));
12492 request_sigio ();
12493 #endif /* not USE_X_TOOLKIT */
12494 #endif /* not USE_GTK*/
12496 /* Detect failure. */
12497 if (dpy == 0)
12499 unblock_input ();
12500 return 0;
12503 #ifdef USE_XCB
12504 xcb_conn = XGetXCBConnection (dpy);
12505 if (xcb_conn == 0)
12507 #ifdef USE_GTK
12508 xg_display_close (dpy);
12509 #else
12510 #ifdef USE_X_TOOLKIT
12511 XtCloseDisplay (dpy);
12512 #else
12513 XCloseDisplay (dpy);
12514 #endif
12515 #endif /* ! USE_GTK */
12517 unblock_input ();
12518 return 0;
12520 #endif
12522 /* We have definitely succeeded. Record the new connection. */
12524 dpyinfo = xzalloc (sizeof *dpyinfo);
12525 terminal = x_create_terminal (dpyinfo);
12528 struct x_display_info *share;
12530 for (share = x_display_list; share; share = share->next)
12531 if (same_x_server (SSDATA (XCAR (share->name_list_element)),
12532 SSDATA (display_name)))
12533 break;
12534 if (share)
12535 terminal->kboard = share->terminal->kboard;
12536 else
12538 terminal->kboard = allocate_kboard (Qx);
12540 if (!EQ (XSYMBOL (Qvendor_specific_keysyms)->u.s.function, Qunbound))
12542 char *vendor = ServerVendor (dpy);
12544 /* Temporarily hide the partially initialized terminal. */
12545 terminal_list = terminal->next_terminal;
12546 unblock_input ();
12547 kset_system_key_alist
12548 (terminal->kboard,
12549 call1 (Qvendor_specific_keysyms,
12550 vendor ? build_string (vendor) : empty_unibyte_string));
12551 block_input ();
12552 terminal->next_terminal = terminal_list;
12553 terminal_list = terminal;
12556 /* Don't let the initial kboard remain current longer than necessary.
12557 That would cause problems if a file loaded on startup tries to
12558 prompt in the mini-buffer. */
12559 if (current_kboard == initial_kboard)
12560 current_kboard = terminal->kboard;
12562 terminal->kboard->reference_count++;
12565 /* Put this display on the chain. */
12566 dpyinfo->next = x_display_list;
12567 x_display_list = dpyinfo;
12569 dpyinfo->name_list_element = Fcons (display_name, Qnil);
12570 dpyinfo->display = dpy;
12571 dpyinfo->connection = ConnectionNumber (dpyinfo->display);
12572 #ifdef USE_XCB
12573 dpyinfo->xcb_connection = xcb_conn;
12574 #endif
12576 /* https://lists.gnu.org/r/emacs-devel/2015-11/msg00194.html */
12577 dpyinfo->smallest_font_height = 1;
12578 dpyinfo->smallest_char_width = 1;
12580 /* Set the name of the terminal. */
12581 terminal->name = xlispstrdup (display_name);
12583 #if false
12584 XSetAfterFunction (x_current_display, x_trace_wire);
12585 #endif
12587 Lisp_Object system_name = Fsystem_name ();
12589 ptrdiff_t nbytes = SBYTES (Vinvocation_name) + 1;
12590 if (STRINGP (system_name)
12591 && INT_ADD_WRAPV (nbytes, SBYTES (system_name) + 1, &nbytes))
12592 memory_full (SIZE_MAX);
12593 dpyinfo->x_id = ++x_display_id;
12594 dpyinfo->x_id_name = xmalloc (nbytes);
12595 char *nametail = lispstpcpy (dpyinfo->x_id_name, Vinvocation_name);
12596 if (STRINGP (system_name))
12598 *nametail++ = '@';
12599 lispstpcpy (nametail, system_name);
12602 /* Figure out which modifier bits mean what. */
12603 x_find_modifier_meanings (dpyinfo);
12605 /* Get the scroll bar cursor. */
12606 #ifdef USE_GTK
12607 /* We must create a GTK cursor, it is required for GTK widgets. */
12608 dpyinfo->xg_cursor = xg_create_default_cursor (dpyinfo->display);
12609 #endif /* USE_GTK */
12611 dpyinfo->vertical_scroll_bar_cursor
12612 = XCreateFontCursor (dpyinfo->display, XC_sb_v_double_arrow);
12614 dpyinfo->horizontal_scroll_bar_cursor
12615 = XCreateFontCursor (dpyinfo->display, XC_sb_h_double_arrow);
12617 xrdb = x_load_resources (dpyinfo->display, xrm_option,
12618 resource_name, EMACS_CLASS);
12619 #ifdef HAVE_XRMSETDATABASE
12620 XrmSetDatabase (dpyinfo->display, xrdb);
12621 #else
12622 dpyinfo->display->db = xrdb;
12623 #endif
12624 /* Put the rdb where we can find it in a way that works on
12625 all versions. */
12626 dpyinfo->xrdb = xrdb;
12628 dpyinfo->screen = ScreenOfDisplay (dpyinfo->display,
12629 DefaultScreen (dpyinfo->display));
12630 select_visual (dpyinfo);
12631 dpyinfo->cmap = DefaultColormapOfScreen (dpyinfo->screen);
12632 dpyinfo->root_window = RootWindowOfScreen (dpyinfo->screen);
12633 dpyinfo->icon_bitmap_id = -1;
12634 dpyinfo->wm_type = X_WMTYPE_UNKNOWN;
12636 reset_mouse_highlight (&dpyinfo->mouse_highlight);
12638 /* See if we can construct pixel values from RGB values. */
12639 if (dpyinfo->visual->class == TrueColor)
12641 get_bits_and_offset (dpyinfo->visual->red_mask,
12642 &dpyinfo->red_bits, &dpyinfo->red_offset);
12643 get_bits_and_offset (dpyinfo->visual->blue_mask,
12644 &dpyinfo->blue_bits, &dpyinfo->blue_offset);
12645 get_bits_and_offset (dpyinfo->visual->green_mask,
12646 &dpyinfo->green_bits, &dpyinfo->green_offset);
12649 /* See if a private colormap is requested. */
12650 if (dpyinfo->visual == DefaultVisualOfScreen (dpyinfo->screen))
12652 if (dpyinfo->visual->class == PseudoColor)
12654 AUTO_STRING (privateColormap, "privateColormap");
12655 AUTO_STRING (PrivateColormap, "PrivateColormap");
12656 Lisp_Object value
12657 = display_x_get_resource (dpyinfo, privateColormap,
12658 PrivateColormap, Qnil, Qnil);
12659 if (STRINGP (value)
12660 && (!strcmp (SSDATA (value), "true")
12661 || !strcmp (SSDATA (value), "on")))
12662 dpyinfo->cmap = XCopyColormapAndFree (dpyinfo->display, dpyinfo->cmap);
12665 else
12666 dpyinfo->cmap = XCreateColormap (dpyinfo->display, dpyinfo->root_window,
12667 dpyinfo->visual, AllocNone);
12669 #ifdef HAVE_XDBE
12670 dpyinfo->supports_xdbe = false;
12671 int xdbe_major;
12672 int xdbe_minor;
12673 if (XdbeQueryExtension (dpyinfo->display, &xdbe_major, &xdbe_minor))
12674 dpyinfo->supports_xdbe = true;
12675 #endif
12677 #ifdef HAVE_XFT
12679 /* If we are using Xft, the following precautions should be made:
12681 1. Make sure that the Xrender extension is added before the Xft one.
12682 Otherwise, the close-display hook set by Xft is called after the one
12683 for Xrender, and the former tries to re-add the latter. This results
12684 in inconsistency of internal states and leads to X protocol error when
12685 one reconnects to the same X server (Bug#1696).
12687 2. Check dpi value in X resources. It is better we use it as well,
12688 since Xft will use it, as will all Gnome applications. If our real DPI
12689 is smaller or larger than the one Xft uses, our font will look smaller
12690 or larger than other for other applications, even if it is the same
12691 font name (monospace-10 for example). */
12693 int event_base, error_base;
12694 char *v;
12695 double d;
12697 XRenderQueryExtension (dpyinfo->display, &event_base, &error_base);
12699 v = XGetDefault (dpyinfo->display, "Xft", "dpi");
12700 if (v != NULL && sscanf (v, "%lf", &d) == 1)
12701 dpyinfo->resy = dpyinfo->resx = d;
12703 #endif
12705 if (dpyinfo->resy < 1)
12707 int screen_number = XScreenNumberOfScreen (dpyinfo->screen);
12708 double pixels = DisplayHeight (dpyinfo->display, screen_number);
12709 double mm = DisplayHeightMM (dpyinfo->display, screen_number);
12710 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
12711 dpyinfo->resy = (mm < 1) ? 100 : pixels * 25.4 / mm;
12712 pixels = DisplayWidth (dpyinfo->display, screen_number);
12713 mm = DisplayWidthMM (dpyinfo->display, screen_number);
12714 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
12715 dpyinfo->resx = (mm < 1) ? 100 : pixels * 25.4 / mm;
12719 static const struct
12721 const char *name;
12722 int offset;
12723 } atom_refs[] = {
12724 #define ATOM_REFS_INIT(string, member) \
12725 { string, offsetof (struct x_display_info, member) },
12726 ATOM_REFS_INIT ("WM_PROTOCOLS", Xatom_wm_protocols)
12727 ATOM_REFS_INIT ("WM_TAKE_FOCUS", Xatom_wm_take_focus)
12728 ATOM_REFS_INIT ("WM_SAVE_YOURSELF", Xatom_wm_save_yourself)
12729 ATOM_REFS_INIT ("WM_DELETE_WINDOW", Xatom_wm_delete_window)
12730 ATOM_REFS_INIT ("WM_CHANGE_STATE", Xatom_wm_change_state)
12731 ATOM_REFS_INIT ("WM_CONFIGURE_DENIED", Xatom_wm_configure_denied)
12732 ATOM_REFS_INIT ("WM_MOVED", Xatom_wm_window_moved)
12733 ATOM_REFS_INIT ("WM_CLIENT_LEADER", Xatom_wm_client_leader)
12734 ATOM_REFS_INIT ("Editres", Xatom_editres)
12735 ATOM_REFS_INIT ("CLIPBOARD", Xatom_CLIPBOARD)
12736 ATOM_REFS_INIT ("TIMESTAMP", Xatom_TIMESTAMP)
12737 ATOM_REFS_INIT ("TEXT", Xatom_TEXT)
12738 ATOM_REFS_INIT ("COMPOUND_TEXT", Xatom_COMPOUND_TEXT)
12739 ATOM_REFS_INIT ("UTF8_STRING", Xatom_UTF8_STRING)
12740 ATOM_REFS_INIT ("DELETE", Xatom_DELETE)
12741 ATOM_REFS_INIT ("MULTIPLE", Xatom_MULTIPLE)
12742 ATOM_REFS_INIT ("INCR", Xatom_INCR)
12743 ATOM_REFS_INIT ("_EMACS_TMP_", Xatom_EMACS_TMP)
12744 ATOM_REFS_INIT ("TARGETS", Xatom_TARGETS)
12745 ATOM_REFS_INIT ("NULL", Xatom_NULL)
12746 ATOM_REFS_INIT ("ATOM", Xatom_ATOM)
12747 ATOM_REFS_INIT ("ATOM_PAIR", Xatom_ATOM_PAIR)
12748 ATOM_REFS_INIT ("CLIPBOARD_MANAGER", Xatom_CLIPBOARD_MANAGER)
12749 ATOM_REFS_INIT ("_XEMBED_INFO", Xatom_XEMBED_INFO)
12750 /* For properties of font. */
12751 ATOM_REFS_INIT ("PIXEL_SIZE", Xatom_PIXEL_SIZE)
12752 ATOM_REFS_INIT ("AVERAGE_WIDTH", Xatom_AVERAGE_WIDTH)
12753 ATOM_REFS_INIT ("_MULE_BASELINE_OFFSET", Xatom_MULE_BASELINE_OFFSET)
12754 ATOM_REFS_INIT ("_MULE_RELATIVE_COMPOSE", Xatom_MULE_RELATIVE_COMPOSE)
12755 ATOM_REFS_INIT ("_MULE_DEFAULT_ASCENT", Xatom_MULE_DEFAULT_ASCENT)
12756 /* Ghostscript support. */
12757 ATOM_REFS_INIT ("DONE", Xatom_DONE)
12758 ATOM_REFS_INIT ("PAGE", Xatom_PAGE)
12759 ATOM_REFS_INIT ("SCROLLBAR", Xatom_Scrollbar)
12760 ATOM_REFS_INIT ("HORIZONTAL_SCROLLBAR", Xatom_Horizontal_Scrollbar)
12761 ATOM_REFS_INIT ("_XEMBED", Xatom_XEMBED)
12762 /* EWMH */
12763 ATOM_REFS_INIT ("_NET_WM_STATE", Xatom_net_wm_state)
12764 ATOM_REFS_INIT ("_NET_WM_STATE_FULLSCREEN", Xatom_net_wm_state_fullscreen)
12765 ATOM_REFS_INIT ("_NET_WM_STATE_MAXIMIZED_HORZ",
12766 Xatom_net_wm_state_maximized_horz)
12767 ATOM_REFS_INIT ("_NET_WM_STATE_MAXIMIZED_VERT",
12768 Xatom_net_wm_state_maximized_vert)
12769 ATOM_REFS_INIT ("_NET_WM_STATE_STICKY", Xatom_net_wm_state_sticky)
12770 ATOM_REFS_INIT ("_NET_WM_STATE_HIDDEN", Xatom_net_wm_state_hidden)
12771 ATOM_REFS_INIT ("_NET_WM_WINDOW_TYPE", Xatom_net_window_type)
12772 ATOM_REFS_INIT ("_NET_WM_WINDOW_TYPE_TOOLTIP",
12773 Xatom_net_window_type_tooltip)
12774 ATOM_REFS_INIT ("_NET_WM_ICON_NAME", Xatom_net_wm_icon_name)
12775 ATOM_REFS_INIT ("_NET_WM_NAME", Xatom_net_wm_name)
12776 ATOM_REFS_INIT ("_NET_SUPPORTED", Xatom_net_supported)
12777 ATOM_REFS_INIT ("_NET_SUPPORTING_WM_CHECK", Xatom_net_supporting_wm_check)
12778 ATOM_REFS_INIT ("_NET_WM_WINDOW_OPACITY", Xatom_net_wm_window_opacity)
12779 ATOM_REFS_INIT ("_NET_ACTIVE_WINDOW", Xatom_net_active_window)
12780 ATOM_REFS_INIT ("_NET_FRAME_EXTENTS", Xatom_net_frame_extents)
12781 ATOM_REFS_INIT ("_NET_CURRENT_DESKTOP", Xatom_net_current_desktop)
12782 ATOM_REFS_INIT ("_NET_WORKAREA", Xatom_net_workarea)
12783 /* Session management */
12784 ATOM_REFS_INIT ("SM_CLIENT_ID", Xatom_SM_CLIENT_ID)
12785 ATOM_REFS_INIT ("_XSETTINGS_SETTINGS", Xatom_xsettings_prop)
12786 ATOM_REFS_INIT ("MANAGER", Xatom_xsettings_mgr)
12787 ATOM_REFS_INIT ("_NET_WM_STATE_SKIP_TASKBAR", Xatom_net_wm_state_skip_taskbar)
12788 ATOM_REFS_INIT ("_NET_WM_STATE_ABOVE", Xatom_net_wm_state_above)
12789 ATOM_REFS_INIT ("_NET_WM_STATE_BELOW", Xatom_net_wm_state_below)
12792 int i;
12793 enum { atom_count = ARRAYELTS (atom_refs) };
12794 /* 1 for _XSETTINGS_SN. */
12795 enum { total_atom_count = 1 + atom_count };
12796 Atom atoms_return[total_atom_count];
12797 char *atom_names[total_atom_count];
12798 static char const xsettings_fmt[] = "_XSETTINGS_S%d";
12799 char xsettings_atom_name[sizeof xsettings_fmt - 2
12800 + INT_STRLEN_BOUND (int)];
12802 for (i = 0; i < atom_count; i++)
12803 atom_names[i] = (char *) atom_refs[i].name;
12805 /* Build _XSETTINGS_SN atom name. */
12806 sprintf (xsettings_atom_name, xsettings_fmt,
12807 XScreenNumberOfScreen (dpyinfo->screen));
12808 atom_names[i] = xsettings_atom_name;
12810 XInternAtoms (dpyinfo->display, atom_names, total_atom_count,
12811 False, atoms_return);
12813 for (i = 0; i < atom_count; i++)
12814 *(Atom *) ((char *) dpyinfo + atom_refs[i].offset) = atoms_return[i];
12816 /* Manually copy last atom. */
12817 dpyinfo->Xatom_xsettings_sel = atoms_return[i];
12820 dpyinfo->x_dnd_atoms_size = 8;
12821 dpyinfo->x_dnd_atoms = xmalloc (sizeof *dpyinfo->x_dnd_atoms
12822 * dpyinfo->x_dnd_atoms_size);
12823 dpyinfo->gray
12824 = XCreatePixmapFromBitmapData (dpyinfo->display, dpyinfo->root_window,
12825 gray_bits, gray_width, gray_height,
12826 1, 0, 1);
12828 x_setup_pointer_blanking (dpyinfo);
12830 #ifdef HAVE_X_I18N
12831 xim_initialize (dpyinfo, resource_name);
12832 #endif
12834 xsettings_initialize (dpyinfo);
12836 /* This is only needed for distinguishing keyboard and process input. */
12837 if (dpyinfo->connection != 0)
12838 add_keyboard_wait_descriptor (dpyinfo->connection);
12840 #ifdef F_SETOWN
12841 fcntl (dpyinfo->connection, F_SETOWN, getpid ());
12842 #endif /* ! defined (F_SETOWN) */
12844 if (interrupt_input)
12845 init_sigio (dpyinfo->connection);
12847 #ifdef USE_LUCID
12849 XrmValue d, fr, to;
12850 Font font;
12852 dpy = dpyinfo->display;
12853 d.addr = (XPointer)&dpy;
12854 d.size = sizeof (Display *);
12855 fr.addr = (char *) XtDefaultFont;
12856 fr.size = sizeof (XtDefaultFont);
12857 to.size = sizeof (Font *);
12858 to.addr = (XPointer)&font;
12859 x_catch_errors (dpy);
12860 if (!XtCallConverter (dpy, XtCvtStringToFont, &d, 1, &fr, &to, NULL))
12861 emacs_abort ();
12862 if (x_had_errors_p (dpy) || !XQueryFont (dpy, font))
12863 XrmPutLineResource (&xrdb, "Emacs.dialog.*.font: 9x15");
12864 /* Do not free XFontStruct returned by the above call to XQueryFont.
12865 This leads to X protocol errors at XtCloseDisplay (Bug#18403). */
12866 x_uncatch_errors ();
12868 #endif
12870 /* See if we should run in synchronous mode. This is useful
12871 for debugging X code. */
12873 AUTO_STRING (synchronous, "synchronous");
12874 AUTO_STRING (Synchronous, "Synchronous");
12875 Lisp_Object value = display_x_get_resource (dpyinfo, synchronous,
12876 Synchronous, Qnil, Qnil);
12877 if (STRINGP (value)
12878 && (!strcmp (SSDATA (value), "true")
12879 || !strcmp (SSDATA (value), "on")))
12880 XSynchronize (dpyinfo->display, True);
12884 AUTO_STRING (useXIM, "useXIM");
12885 AUTO_STRING (UseXIM, "UseXIM");
12886 Lisp_Object value = display_x_get_resource (dpyinfo, useXIM, UseXIM,
12887 Qnil, Qnil);
12888 #ifdef USE_XIM
12889 if (STRINGP (value)
12890 && (!strcmp (SSDATA (value), "false")
12891 || !strcmp (SSDATA (value), "off")))
12892 use_xim = false;
12893 #else
12894 if (STRINGP (value)
12895 && (!strcmp (SSDATA (value), "true")
12896 || !strcmp (SSDATA (value), "on")))
12897 use_xim = true;
12898 #endif
12901 #ifdef HAVE_X_SM
12902 /* Only do this for the very first display in the Emacs session.
12903 Ignore X session management when Emacs was first started on a
12904 tty or started as a daemon. */
12905 if (terminal->id == 1 && ! IS_DAEMON)
12906 x_session_initialize (dpyinfo);
12907 #endif
12909 #ifdef USE_CAIRO
12910 x_extension_initialize (dpyinfo);
12911 #endif
12913 unblock_input ();
12915 return dpyinfo;
12918 /* Get rid of display DPYINFO, deleting all frames on it,
12919 and without sending any more commands to the X server. */
12921 static void
12922 x_delete_display (struct x_display_info *dpyinfo)
12924 struct terminal *t;
12925 struct color_name_cache_entry *color_entry, *next_color_entry;
12927 /* Close all frames and delete the generic struct terminal for this
12928 X display. */
12929 for (t = terminal_list; t; t = t->next_terminal)
12930 if (t->type == output_x_window && t->display_info.x == dpyinfo)
12932 #ifdef HAVE_X_SM
12933 /* Close X session management when we close its display. */
12934 if (t->id == 1 && x_session_have_connection ())
12935 x_session_close ();
12936 #endif
12937 delete_terminal (t);
12938 break;
12941 if (next_noop_dpyinfo == dpyinfo)
12942 next_noop_dpyinfo = dpyinfo->next;
12944 if (x_display_list == dpyinfo)
12945 x_display_list = dpyinfo->next;
12946 else
12948 struct x_display_info *tail;
12950 for (tail = x_display_list; tail; tail = tail->next)
12951 if (tail->next == dpyinfo)
12952 tail->next = tail->next->next;
12955 for (color_entry = dpyinfo->color_names;
12956 color_entry;
12957 color_entry = next_color_entry)
12959 next_color_entry = color_entry->next;
12960 xfree (color_entry->name);
12961 xfree (color_entry);
12964 xfree (dpyinfo->x_id_name);
12965 xfree (dpyinfo->x_dnd_atoms);
12966 xfree (dpyinfo->color_cells);
12967 xfree (dpyinfo);
12970 #ifdef USE_X_TOOLKIT
12972 /* Atimer callback function for TIMER. Called every 0.1s to process
12973 Xt timeouts, if needed. We must avoid calling XtAppPending as
12974 much as possible because that function does an implicit XFlush
12975 that slows us down. */
12977 static void
12978 x_process_timeouts (struct atimer *timer)
12980 block_input ();
12981 x_timeout_atimer_activated_flag = false;
12982 if (toolkit_scroll_bar_interaction || popup_activated ())
12984 while (XtAppPending (Xt_app_con) & XtIMTimer)
12985 XtAppProcessEvent (Xt_app_con, XtIMTimer);
12986 /* Reactivate the atimer for next time. */
12987 x_activate_timeout_atimer ();
12989 unblock_input ();
12992 /* Install an asynchronous timer that processes Xt timeout events
12993 every 0.1s as long as either `toolkit_scroll_bar_interaction' or
12994 `popup_activated_flag' (in xmenu.c) is set. Make sure to call this
12995 function whenever these variables are set. This is necessary
12996 because some widget sets use timeouts internally, for example the
12997 LessTif menu bar, or the Xaw3d scroll bar. When Xt timeouts aren't
12998 processed, these widgets don't behave normally. */
13000 void
13001 x_activate_timeout_atimer (void)
13003 block_input ();
13004 if (!x_timeout_atimer_activated_flag)
13006 struct timespec interval = make_timespec (0, 100 * 1000 * 1000);
13007 start_atimer (ATIMER_RELATIVE, interval, x_process_timeouts, 0);
13008 x_timeout_atimer_activated_flag = true;
13010 unblock_input ();
13013 #endif /* USE_X_TOOLKIT */
13016 /* Set up use of X before we make the first connection. */
13018 static struct redisplay_interface x_redisplay_interface =
13020 x_frame_parm_handlers,
13021 x_produce_glyphs,
13022 x_write_glyphs,
13023 x_insert_glyphs,
13024 x_clear_end_of_line,
13025 x_scroll_run,
13026 x_after_update_window_line,
13027 x_update_window_begin,
13028 x_update_window_end,
13029 x_flip_and_flush,
13030 x_clear_window_mouse_face,
13031 x_get_glyph_overhangs,
13032 x_fix_overlapping_area,
13033 x_draw_fringe_bitmap,
13034 #ifdef USE_CAIRO
13035 x_cr_define_fringe_bitmap,
13036 x_cr_destroy_fringe_bitmap,
13037 #else
13038 0, /* define_fringe_bitmap */
13039 0, /* destroy_fringe_bitmap */
13040 #endif
13041 x_compute_glyph_string_overhangs,
13042 x_draw_glyph_string,
13043 x_define_frame_cursor,
13044 x_clear_frame_area,
13045 x_draw_window_cursor,
13046 x_draw_vertical_window_border,
13047 x_draw_window_divider,
13048 x_shift_glyphs_for_insert, /* Never called; see comment in function. */
13049 x_show_hourglass,
13050 x_hide_hourglass
13054 /* This function is called when the last frame on a display is deleted. */
13055 void
13056 x_delete_terminal (struct terminal *terminal)
13058 struct x_display_info *dpyinfo = terminal->display_info.x;
13060 /* Protect against recursive calls. delete_frame in
13061 delete_terminal calls us back when it deletes our last frame. */
13062 if (!terminal->name)
13063 return;
13065 block_input ();
13066 #ifdef HAVE_X_I18N
13067 /* We must close our connection to the XIM server before closing the
13068 X display. */
13069 if (dpyinfo->xim)
13070 xim_close_dpy (dpyinfo);
13071 #endif
13073 /* Normally, the display is available... */
13074 if (dpyinfo->display)
13076 x_destroy_all_bitmaps (dpyinfo);
13077 XSetCloseDownMode (dpyinfo->display, DestroyAll);
13079 /* Whether or not XCloseDisplay destroys the associated resource
13080 database depends on the version of libX11. To avoid both
13081 crash and memory leak, we dissociate the database from the
13082 display and then destroy dpyinfo->xrdb ourselves.
13084 Unfortunately, the above strategy does not work in some
13085 situations due to a bug in newer versions of libX11: because
13086 XrmSetDatabase doesn't clear the flag XlibDisplayDfltRMDB if
13087 dpy->db is NULL, XCloseDisplay destroys the associated
13088 database whereas it has not been created by XGetDefault
13089 (Bug#21974 in freedesktop.org Bugzilla). As a workaround, we
13090 don't destroy the database here in order to avoid the crash
13091 in the above situations for now, though that may cause memory
13092 leaks in other situations. */
13093 #if false
13094 #ifdef HAVE_XRMSETDATABASE
13095 XrmSetDatabase (dpyinfo->display, NULL);
13096 #else
13097 dpyinfo->display->db = NULL;
13098 #endif
13099 /* We used to call XrmDestroyDatabase from x_delete_display, but
13100 some older versions of libX11 crash if we call it after
13101 closing all the displays. */
13102 XrmDestroyDatabase (dpyinfo->xrdb);
13103 #endif
13105 #ifdef USE_GTK
13106 xg_display_close (dpyinfo->display);
13107 #else
13108 #ifdef USE_X_TOOLKIT
13109 XtCloseDisplay (dpyinfo->display);
13110 #else
13111 XCloseDisplay (dpyinfo->display);
13112 #endif
13113 #endif /* ! USE_GTK */
13114 /* Do not close the connection here because it's already closed
13115 by X(t)CloseDisplay (Bug#18403). */
13116 dpyinfo->display = NULL;
13119 /* ...but if called from x_connection_closed, the display may already
13120 be closed and dpyinfo->display was set to 0 to indicate that. Since
13121 X server is most likely gone, explicit close is the only reliable
13122 way to continue and avoid Bug#19147. */
13123 else if (dpyinfo->connection >= 0)
13124 emacs_close (dpyinfo->connection);
13126 /* No more input on this descriptor. */
13127 delete_keyboard_wait_descriptor (dpyinfo->connection);
13128 /* Mark as dead. */
13129 dpyinfo->connection = -1;
13131 x_delete_display (dpyinfo);
13132 unblock_input ();
13135 /* Create a struct terminal, initialize it with the X11 specific
13136 functions and make DISPLAY->TERMINAL point to it. */
13138 static struct terminal *
13139 x_create_terminal (struct x_display_info *dpyinfo)
13141 struct terminal *terminal;
13143 terminal = create_terminal (output_x_window, &x_redisplay_interface);
13145 terminal->display_info.x = dpyinfo;
13146 dpyinfo->terminal = terminal;
13148 /* kboard is initialized in x_term_init. */
13150 terminal->clear_frame_hook = x_clear_frame;
13151 terminal->ins_del_lines_hook = x_ins_del_lines;
13152 terminal->delete_glyphs_hook = x_delete_glyphs;
13153 terminal->ring_bell_hook = XTring_bell;
13154 terminal->toggle_invisible_pointer_hook = XTtoggle_invisible_pointer;
13155 terminal->update_begin_hook = x_update_begin;
13156 terminal->update_end_hook = x_update_end;
13157 terminal->read_socket_hook = XTread_socket;
13158 terminal->frame_up_to_date_hook = XTframe_up_to_date;
13159 terminal->buffer_flipping_unblocked_hook = XTbuffer_flipping_unblocked_hook;
13160 terminal->mouse_position_hook = XTmouse_position;
13161 terminal->frame_rehighlight_hook = XTframe_rehighlight;
13162 terminal->frame_raise_lower_hook = XTframe_raise_lower;
13163 terminal->fullscreen_hook = XTfullscreen_hook;
13164 terminal->menu_show_hook = x_menu_show;
13165 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
13166 terminal->popup_dialog_hook = xw_popup_dialog;
13167 #endif
13168 terminal->set_vertical_scroll_bar_hook = XTset_vertical_scroll_bar;
13169 terminal->set_horizontal_scroll_bar_hook = XTset_horizontal_scroll_bar;
13170 terminal->condemn_scroll_bars_hook = XTcondemn_scroll_bars;
13171 terminal->redeem_scroll_bar_hook = XTredeem_scroll_bar;
13172 terminal->judge_scroll_bars_hook = XTjudge_scroll_bars;
13173 terminal->delete_frame_hook = x_destroy_window;
13174 terminal->delete_terminal_hook = x_delete_terminal;
13175 /* Other hooks are NULL by default. */
13177 return terminal;
13180 static void
13181 x_initialize (void)
13183 baud_rate = 19200;
13185 x_noop_count = 0;
13186 any_help_event_p = false;
13187 ignore_next_mouse_click_timeout = 0;
13189 #ifdef USE_GTK
13190 current_count = -1;
13191 #endif
13193 /* Try to use interrupt input; if we can't, then start polling. */
13194 Fset_input_interrupt_mode (Qt);
13196 #if THREADS_ENABLED
13197 /* This must be called before any other Xlib routines. */
13198 if (XInitThreads () == 0)
13199 fprintf (stderr,
13200 "Warning: An error occurred initializing X11 thread support!\n");
13201 #endif
13203 #ifdef USE_X_TOOLKIT
13204 XtToolkitInitialize ();
13206 Xt_app_con = XtCreateApplicationContext ();
13208 /* Register a converter from strings to pixels, which uses
13209 Emacs' color allocation infrastructure. */
13210 XtAppSetTypeConverter (Xt_app_con,
13211 XtRString, XtRPixel, cvt_string_to_pixel,
13212 cvt_string_to_pixel_args,
13213 XtNumber (cvt_string_to_pixel_args),
13214 XtCacheByDisplay, cvt_pixel_dtor);
13216 XtAppSetFallbackResources (Xt_app_con, Xt_default_resources);
13217 #endif
13219 #ifdef USE_TOOLKIT_SCROLL_BARS
13220 #ifndef USE_GTK
13221 xaw3d_arrow_scroll = False;
13222 xaw3d_pick_top = True;
13223 #endif
13224 #endif
13226 #ifdef USE_CAIRO
13227 x_cr_init_fringe (&x_redisplay_interface);
13228 #endif
13230 /* Note that there is no real way portable across R3/R4 to get the
13231 original error handler. */
13232 XSetErrorHandler (x_error_handler);
13233 XSetIOErrorHandler (x_io_error_quitter);
13236 #ifdef USE_GTK
13237 void
13238 init_xterm (void)
13240 /* Emacs can handle only core input events, so make sure
13241 Gtk doesn't use Xinput or Xinput2 extensions. */
13242 xputenv ("GDK_CORE_DEVICE_EVENTS=1");
13244 #endif
13246 void
13247 syms_of_xterm (void)
13249 x_error_message = NULL;
13251 DEFSYM (Qvendor_specific_keysyms, "vendor-specific-keysyms");
13252 DEFSYM (Qlatin_1, "latin-1");
13254 #ifdef USE_GTK
13255 xg_default_icon_file = build_pure_c_string ("icons/hicolor/scalable/apps/emacs.svg");
13256 staticpro (&xg_default_icon_file);
13258 DEFSYM (Qx_gtk_map_stock, "x-gtk-map-stock");
13259 #endif
13261 DEFVAR_BOOL ("x-use-underline-position-properties",
13262 x_use_underline_position_properties,
13263 doc: /* Non-nil means make use of UNDERLINE_POSITION font properties.
13264 A value of nil means ignore them. If you encounter fonts with bogus
13265 UNDERLINE_POSITION font properties, set this to nil. You can also use
13266 `underline-minimum-offset' to override the font's UNDERLINE_POSITION for
13267 small font display sizes. */);
13268 x_use_underline_position_properties = true;
13269 DEFSYM (Qx_use_underline_position_properties,
13270 "x-use-underline-position-properties");
13272 DEFVAR_BOOL ("x-underline-at-descent-line",
13273 x_underline_at_descent_line,
13274 doc: /* Non-nil means to draw the underline at the same place as the descent line.
13275 (If `line-spacing' is in effect, that moves the underline lower by
13276 that many pixels.)
13277 A value of nil means to draw the underline according to the value of the
13278 variable `x-use-underline-position-properties', which is usually at the
13279 baseline level. The default value is nil. */);
13280 x_underline_at_descent_line = false;
13281 DEFSYM (Qx_underline_at_descent_line, "x-underline-at-descent-line");
13283 DEFVAR_BOOL ("x-mouse-click-focus-ignore-position",
13284 x_mouse_click_focus_ignore_position,
13285 doc: /* Non-nil means that a mouse click to focus a frame does not move point.
13286 This variable is only used when the window manager requires that you
13287 click on a frame to select it (give it focus). In that case, a value
13288 of nil, means that the selected window and cursor position changes to
13289 reflect the mouse click position, while a non-nil value means that the
13290 selected window or cursor position is preserved. */);
13291 x_mouse_click_focus_ignore_position = false;
13293 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
13294 doc: /* Which toolkit scroll bars Emacs uses, if any.
13295 A value of nil means Emacs doesn't use toolkit scroll bars.
13296 With the X Window system, the value is a symbol describing the
13297 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
13298 With MS Windows or Nextstep, the value is t. */);
13299 #ifdef USE_TOOLKIT_SCROLL_BARS
13300 #ifdef USE_MOTIF
13301 Vx_toolkit_scroll_bars = intern_c_string ("motif");
13302 #elif defined HAVE_XAW3D
13303 Vx_toolkit_scroll_bars = intern_c_string ("xaw3d");
13304 #elif USE_GTK
13305 Vx_toolkit_scroll_bars = intern_c_string ("gtk");
13306 #else
13307 Vx_toolkit_scroll_bars = intern_c_string ("xaw");
13308 #endif
13309 #else
13310 Vx_toolkit_scroll_bars = Qnil;
13311 #endif
13313 DEFSYM (Qmodifier_value, "modifier-value");
13314 DEFSYM (Qctrl, "ctrl");
13315 Fput (Qctrl, Qmodifier_value, make_number (ctrl_modifier));
13316 DEFSYM (Qalt, "alt");
13317 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
13318 DEFSYM (Qhyper, "hyper");
13319 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
13320 DEFSYM (Qmeta, "meta");
13321 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
13322 DEFSYM (Qsuper, "super");
13323 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
13325 DEFVAR_LISP ("x-ctrl-keysym", Vx_ctrl_keysym,
13326 doc: /* Which keys Emacs uses for the ctrl modifier.
13327 This should be one of the symbols `ctrl', `alt', `hyper', `meta',
13328 `super'. For example, `ctrl' means use the Ctrl_L and Ctrl_R keysyms.
13329 The default is nil, which is the same as `ctrl'. */);
13330 Vx_ctrl_keysym = Qnil;
13332 DEFVAR_LISP ("x-alt-keysym", Vx_alt_keysym,
13333 doc: /* Which keys Emacs uses for the alt modifier.
13334 This should be one of the symbols `ctrl', `alt', `hyper', `meta',
13335 `super'. For example, `alt' means use the Alt_L and Alt_R keysyms.
13336 The default is nil, which is the same as `alt'. */);
13337 Vx_alt_keysym = Qnil;
13339 DEFVAR_LISP ("x-hyper-keysym", Vx_hyper_keysym,
13340 doc: /* Which keys Emacs uses for the hyper modifier.
13341 This should be one of the symbols `ctrl', `alt', `hyper', `meta',
13342 `super'. For example, `hyper' means use the Hyper_L and Hyper_R
13343 keysyms. The default is nil, which is the same as `hyper'. */);
13344 Vx_hyper_keysym = Qnil;
13346 DEFVAR_LISP ("x-meta-keysym", Vx_meta_keysym,
13347 doc: /* Which keys Emacs uses for the meta modifier.
13348 This should be one of the symbols `ctrl', `alt', `hyper', `meta',
13349 `super'. For example, `meta' means use the Meta_L and Meta_R keysyms.
13350 The default is nil, which is the same as `meta'. */);
13351 Vx_meta_keysym = Qnil;
13353 DEFVAR_LISP ("x-super-keysym", Vx_super_keysym,
13354 doc: /* Which keys Emacs uses for the super modifier.
13355 This should be one of the symbols `ctrl', `alt', `hyper', `meta',
13356 `super'. For example, `super' means use the Super_L and Super_R
13357 keysyms. The default is nil, which is the same as `super'. */);
13358 Vx_super_keysym = Qnil;
13360 DEFVAR_LISP ("x-wait-for-event-timeout", Vx_wait_for_event_timeout,
13361 doc: /* How long to wait for X events.
13363 Emacs will wait up to this many seconds to receive X events after
13364 making changes which affect the state of the graphical interface.
13365 Under some window managers this can take an indefinite amount of time,
13366 so it is important to limit the wait.
13368 If set to a non-float value, there will be no wait at all. */);
13369 Vx_wait_for_event_timeout = make_float (0.1);
13371 DEFVAR_LISP ("x-keysym-table", Vx_keysym_table,
13372 doc: /* Hash table of character codes indexed by X keysym codes. */);
13373 Vx_keysym_table = make_hash_table (hashtest_eql, 900,
13374 DEFAULT_REHASH_SIZE,
13375 DEFAULT_REHASH_THRESHOLD,
13376 Qnil, false);
13378 DEFVAR_BOOL ("x-frame-normalize-before-maximize",
13379 x_frame_normalize_before_maximize,
13380 doc: /* Non-nil means normalize frame before maximizing.
13381 If this variable is t, Emacs first asks the window manager to give the
13382 frame its normal size, and only then the final state, whenever changing
13383 from a full-height, full-width or full-both state to the maximized one
13384 or when changing from the maximized to the full-height or full-width
13385 state.
13387 Set this variable only if your window manager cannot handle the
13388 transition between the various maximization states. */);
13389 x_frame_normalize_before_maximize = false;
13391 DEFVAR_BOOL ("x-gtk-use-window-move", x_gtk_use_window_move,
13392 doc: /* Non-nil means rely on gtk_window_move to set frame positions.
13393 If this variable is t (the default), the GTK build uses the function
13394 gtk_window_move to set or store frame positions and disables some time
13395 consuming frame position adjustments. In newer versions of GTK, Emacs
13396 always uses gtk_window_move and ignores the value of this variable. */);
13397 x_gtk_use_window_move = true;