; doc/emacs/misc.texi (Network Security): Fix typo.
[emacs.git] / src / xterm.c
blob9504bfb183403ecadd2f722dfd09d3a50f4b9838
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 FRAME_CR_SURFACE (f) =
364 cairo_image_surface_create (CAIRO_FORMAT_ARGB32,
365 FRAME_PIXEL_WIDTH (f),
366 FRAME_PIXEL_HEIGHT (f));
368 cr = cairo_create (FRAME_CR_SURFACE (f));
369 FRAME_CR_CONTEXT (f) = cr;
371 cairo_save (cr);
373 if (gc)
375 struct x_gc_ext_data *gc_ext = x_gc_get_ext_data (f, gc, 0);
377 if (gc_ext && gc_ext->n_clip_rects)
379 int i;
381 for (i = 0; i < gc_ext->n_clip_rects; i++)
382 cairo_rectangle (cr, gc_ext->clip_rects[i].x,
383 gc_ext->clip_rects[i].y,
384 gc_ext->clip_rects[i].width,
385 gc_ext->clip_rects[i].height);
386 cairo_clip (cr);
390 return cr;
393 void
394 x_end_cr_clip (struct frame *f)
396 cairo_restore (FRAME_CR_CONTEXT (f));
399 void
400 x_set_cr_source_with_gc_foreground (struct frame *f, GC gc)
402 XGCValues xgcv;
403 XColor color;
405 XGetGCValues (FRAME_X_DISPLAY (f), gc, GCForeground, &xgcv);
406 color.pixel = xgcv.foreground;
407 x_query_color (f, &color);
408 cairo_set_source_rgb (FRAME_CR_CONTEXT (f), color.red / 65535.0,
409 color.green / 65535.0, color.blue / 65535.0);
412 void
413 x_set_cr_source_with_gc_background (struct frame *f, GC gc)
415 XGCValues xgcv;
416 XColor color;
418 XGetGCValues (FRAME_X_DISPLAY (f), gc, GCBackground, &xgcv);
419 color.pixel = xgcv.background;
420 x_query_color (f, &color);
421 cairo_set_source_rgb (FRAME_CR_CONTEXT (f), color.red / 65535.0,
422 color.green / 65535.0, color.blue / 65535.0);
425 /* Fringe bitmaps. */
427 static int max_fringe_bmp = 0;
428 static cairo_pattern_t **fringe_bmp = 0;
430 static void
431 x_cr_define_fringe_bitmap (int which, unsigned short *bits, int h, int wd)
433 int i, stride;
434 cairo_surface_t *surface;
435 unsigned char *data;
436 cairo_pattern_t *pattern;
438 if (which >= max_fringe_bmp)
440 i = max_fringe_bmp;
441 max_fringe_bmp = which + 20;
442 fringe_bmp = (cairo_pattern_t **) xrealloc (fringe_bmp, max_fringe_bmp * sizeof (cairo_pattern_t *));
443 while (i < max_fringe_bmp)
444 fringe_bmp[i++] = 0;
447 block_input ();
449 surface = cairo_image_surface_create (CAIRO_FORMAT_A1, wd, h);
450 stride = cairo_image_surface_get_stride (surface);
451 data = cairo_image_surface_get_data (surface);
453 for (i = 0; i < h; i++)
455 *((unsigned short *) data) = bits[i];
456 data += stride;
459 cairo_surface_mark_dirty (surface);
460 pattern = cairo_pattern_create_for_surface (surface);
461 cairo_surface_destroy (surface);
463 unblock_input ();
465 fringe_bmp[which] = pattern;
468 static void
469 x_cr_destroy_fringe_bitmap (int which)
471 if (which >= max_fringe_bmp)
472 return;
474 if (fringe_bmp[which])
476 block_input ();
477 cairo_pattern_destroy (fringe_bmp[which]);
478 unblock_input ();
480 fringe_bmp[which] = 0;
483 static void
484 x_cr_draw_image (struct frame *f, GC gc, cairo_pattern_t *image,
485 int src_x, int src_y, int width, int height,
486 int dest_x, int dest_y, bool overlay_p)
488 cairo_t *cr;
489 cairo_matrix_t matrix;
490 cairo_surface_t *surface;
491 cairo_format_t format;
493 cr = x_begin_cr_clip (f, gc);
494 if (overlay_p)
495 cairo_rectangle (cr, dest_x, dest_y, width, height);
496 else
498 x_set_cr_source_with_gc_background (f, gc);
499 cairo_rectangle (cr, dest_x, dest_y, width, height);
500 cairo_fill_preserve (cr);
502 cairo_clip (cr);
503 cairo_matrix_init_translate (&matrix, src_x - dest_x, src_y - dest_y);
504 cairo_pattern_set_matrix (image, &matrix);
505 cairo_pattern_get_surface (image, &surface);
506 format = cairo_image_surface_get_format (surface);
507 if (format != CAIRO_FORMAT_A8 && format != CAIRO_FORMAT_A1)
509 cairo_set_source (cr, image);
510 cairo_fill (cr);
512 else
514 x_set_cr_source_with_gc_foreground (f, gc);
515 cairo_mask (cr, image);
517 x_end_cr_clip (f);
520 void
521 x_cr_draw_frame (cairo_t *cr, struct frame *f)
523 int width, height;
525 width = FRAME_PIXEL_WIDTH (f);
526 height = FRAME_PIXEL_HEIGHT (f);
528 x_free_cr_resources (f);
529 FRAME_CR_CONTEXT (f) = cr;
530 x_clear_area (f, 0, 0, width, height);
531 expose_frame (f, 0, 0, width, height);
532 FRAME_CR_CONTEXT (f) = NULL;
535 static cairo_status_t
536 x_cr_accumulate_data (void *closure, const unsigned char *data,
537 unsigned int length)
539 Lisp_Object *acc = (Lisp_Object *) closure;
541 *acc = Fcons (make_unibyte_string ((char const *) data, length), *acc);
543 return CAIRO_STATUS_SUCCESS;
546 static void
547 x_cr_destroy (void *cr)
549 block_input ();
550 cairo_destroy (cr);
551 unblock_input ();
554 Lisp_Object
555 x_cr_export_frames (Lisp_Object frames, cairo_surface_type_t surface_type)
557 struct frame *f;
558 cairo_surface_t *surface;
559 cairo_t *cr;
560 int width, height;
561 void (*surface_set_size_func) (cairo_surface_t *, double, double) = NULL;
562 Lisp_Object acc = Qnil;
563 ptrdiff_t count = SPECPDL_INDEX ();
565 specbind (Qredisplay_dont_pause, Qt);
566 redisplay_preserve_echo_area (31);
568 f = XFRAME (XCAR (frames));
569 frames = XCDR (frames);
570 width = FRAME_PIXEL_WIDTH (f);
571 height = FRAME_PIXEL_HEIGHT (f);
573 block_input ();
574 #ifdef CAIRO_HAS_PDF_SURFACE
575 if (surface_type == CAIRO_SURFACE_TYPE_PDF)
577 surface = cairo_pdf_surface_create_for_stream (x_cr_accumulate_data, &acc,
578 width, height);
579 surface_set_size_func = cairo_pdf_surface_set_size;
581 else
582 #endif
583 #ifdef CAIRO_HAS_PNG_FUNCTIONS
584 if (surface_type == CAIRO_SURFACE_TYPE_IMAGE)
585 surface = cairo_image_surface_create (CAIRO_FORMAT_RGB24, width, height);
586 else
587 #endif
588 #ifdef CAIRO_HAS_PS_SURFACE
589 if (surface_type == CAIRO_SURFACE_TYPE_PS)
591 surface = cairo_ps_surface_create_for_stream (x_cr_accumulate_data, &acc,
592 width, height);
593 surface_set_size_func = cairo_ps_surface_set_size;
595 else
596 #endif
597 #ifdef CAIRO_HAS_SVG_SURFACE
598 if (surface_type == CAIRO_SURFACE_TYPE_SVG)
599 surface = cairo_svg_surface_create_for_stream (x_cr_accumulate_data, &acc,
600 width, height);
601 else
602 #endif
603 abort ();
605 cr = cairo_create (surface);
606 cairo_surface_destroy (surface);
607 record_unwind_protect_ptr (x_cr_destroy, cr);
609 while (1)
611 x_free_cr_resources (f);
612 FRAME_CR_CONTEXT (f) = cr;
613 x_clear_area (f, 0, 0, width, height);
614 expose_frame (f, 0, 0, width, height);
615 FRAME_CR_CONTEXT (f) = NULL;
617 if (NILP (frames))
618 break;
620 cairo_surface_show_page (surface);
621 f = XFRAME (XCAR (frames));
622 frames = XCDR (frames);
623 width = FRAME_PIXEL_WIDTH (f);
624 height = FRAME_PIXEL_HEIGHT (f);
625 if (surface_set_size_func)
626 (*surface_set_size_func) (surface, width, height);
628 unblock_input ();
629 maybe_quit ();
630 block_input ();
633 #ifdef CAIRO_HAS_PNG_FUNCTIONS
634 if (surface_type == CAIRO_SURFACE_TYPE_IMAGE)
636 cairo_surface_flush (surface);
637 cairo_surface_write_to_png_stream (surface, x_cr_accumulate_data, &acc);
639 #endif
640 unblock_input ();
642 unbind_to (count, Qnil);
644 return CALLN (Fapply, intern ("concat"), Fnreverse (acc));
647 #endif /* USE_CAIRO */
649 static void
650 x_free_cr_resources (struct frame *f)
652 #ifdef USE_CAIRO
653 if (f == NULL)
655 Lisp_Object rest, frame;
656 FOR_EACH_FRAME (rest, frame)
657 if (FRAME_X_P (XFRAME (frame)))
658 x_free_cr_resources (XFRAME (frame));
660 else
662 cairo_t *cr = FRAME_CR_CONTEXT (f);
664 if (cr)
666 cairo_surface_t *surface = cairo_get_target (cr);
668 if (cairo_surface_get_type (surface) == CAIRO_SURFACE_TYPE_XLIB)
670 cairo_destroy (cr);
671 FRAME_CR_CONTEXT (f) = NULL;
675 #endif
678 static void
679 x_set_clip_rectangles (struct frame *f, GC gc, XRectangle *rectangles, int n)
681 XSetClipRectangles (FRAME_X_DISPLAY (f), gc, 0, 0, rectangles, n, Unsorted);
682 #ifdef USE_CAIRO
683 eassert (n >= 0 && n <= MAX_CLIP_RECTS);
686 struct x_gc_ext_data *gc_ext = x_gc_get_ext_data (f, gc, 1);
688 gc_ext->n_clip_rects = n;
689 memcpy (gc_ext->clip_rects, rectangles, sizeof (XRectangle) * n);
691 #endif
694 static void
695 x_reset_clip_rectangles (struct frame *f, GC gc)
697 XSetClipMask (FRAME_X_DISPLAY (f), gc, None);
698 #ifdef USE_CAIRO
700 struct x_gc_ext_data *gc_ext = x_gc_get_ext_data (f, gc, 0);
702 if (gc_ext)
703 gc_ext->n_clip_rects = 0;
705 #endif
708 static void
709 x_fill_rectangle (struct frame *f, GC gc, int x, int y, int width, int height)
711 #ifdef USE_CAIRO
712 cairo_t *cr;
714 cr = x_begin_cr_clip (f, gc);
715 x_set_cr_source_with_gc_foreground (f, gc);
716 cairo_rectangle (cr, x, y, width, height);
717 cairo_fill (cr);
718 x_end_cr_clip (f);
719 #else
720 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_DRAWABLE (f),
721 gc, x, y, width, height);
722 #endif
725 static void
726 x_draw_rectangle (struct frame *f, GC gc, int x, int y, int width, int height)
728 #ifdef USE_CAIRO
729 cairo_t *cr;
731 cr = x_begin_cr_clip (f, gc);
732 x_set_cr_source_with_gc_foreground (f, gc);
733 cairo_rectangle (cr, x + 0.5, y + 0.5, width, height);
734 cairo_set_line_width (cr, 1);
735 cairo_stroke (cr);
736 x_end_cr_clip (f);
737 #else
738 XDrawRectangle (FRAME_X_DISPLAY (f), FRAME_X_DRAWABLE (f),
739 gc, x, y, width, height);
740 #endif
743 static void
744 x_clear_window (struct frame *f)
746 #ifdef USE_CAIRO
747 cairo_t *cr;
749 cr = x_begin_cr_clip (f, NULL);
750 x_set_cr_source_with_gc_background (f, f->output_data.x->normal_gc);
751 cairo_paint (cr);
752 x_end_cr_clip (f);
753 #else
754 if (FRAME_X_DOUBLE_BUFFERED_P (f))
755 x_clear_area (f, 0, 0, FRAME_PIXEL_WIDTH (f), FRAME_PIXEL_HEIGHT (f));
756 else
757 XClearWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
758 #endif
761 #ifdef USE_CAIRO
762 static void
763 x_fill_trapezoid_for_relief (struct frame *f, GC gc, int x, int y,
764 int width, int height, int top_p)
766 cairo_t *cr;
768 cr = x_begin_cr_clip (f, gc);
769 x_set_cr_source_with_gc_foreground (f, gc);
770 cairo_move_to (cr, top_p ? x : x + height, y);
771 cairo_line_to (cr, x, y + height);
772 cairo_line_to (cr, top_p ? x + width - height : x + width, y + height);
773 cairo_line_to (cr, x + width, y);
774 cairo_fill (cr);
775 x_end_cr_clip (f);
778 enum corners
780 CORNER_BOTTOM_RIGHT, /* 0 -> pi/2 */
781 CORNER_BOTTOM_LEFT, /* pi/2 -> pi */
782 CORNER_TOP_LEFT, /* pi -> 3pi/2 */
783 CORNER_TOP_RIGHT, /* 3pi/2 -> 2pi */
784 CORNER_LAST
787 static void
788 x_erase_corners_for_relief (struct frame *f, GC gc, int x, int y,
789 int width, int height,
790 double radius, double margin, int corners)
792 cairo_t *cr;
793 int i;
795 cr = x_begin_cr_clip (f, gc);
796 x_set_cr_source_with_gc_background (f, gc);
797 for (i = 0; i < CORNER_LAST; i++)
798 if (corners & (1 << i))
800 double xm, ym, xc, yc;
802 if (i == CORNER_TOP_LEFT || i == CORNER_BOTTOM_LEFT)
803 xm = x - margin, xc = xm + radius;
804 else
805 xm = x + width + margin, xc = xm - radius;
806 if (i == CORNER_TOP_LEFT || i == CORNER_TOP_RIGHT)
807 ym = y - margin, yc = ym + radius;
808 else
809 ym = y + height + margin, yc = ym - radius;
811 cairo_move_to (cr, xm, ym);
812 cairo_arc (cr, xc, yc, radius, i * M_PI_2, (i + 1) * M_PI_2);
814 cairo_clip (cr);
815 cairo_rectangle (cr, x, y, width, height);
816 cairo_fill (cr);
817 x_end_cr_clip (f);
820 static void
821 x_draw_horizontal_wave (struct frame *f, GC gc, int x, int y,
822 int width, int height, int wave_length)
824 cairo_t *cr;
825 double dx = wave_length, dy = height - 1;
826 int xoffset, n;
828 cr = x_begin_cr_clip (f, gc);
829 x_set_cr_source_with_gc_foreground (f, gc);
830 cairo_rectangle (cr, x, y, width, height);
831 cairo_clip (cr);
833 if (x >= 0)
835 xoffset = x % (wave_length * 2);
836 if (xoffset == 0)
837 xoffset = wave_length * 2;
839 else
840 xoffset = x % (wave_length * 2) + wave_length * 2;
841 n = (width + xoffset) / wave_length + 1;
842 if (xoffset > wave_length)
844 xoffset -= wave_length;
845 --n;
846 y += height - 1;
847 dy = -dy;
850 cairo_move_to (cr, x - xoffset + 0.5, y + 0.5);
851 while (--n >= 0)
853 cairo_rel_line_to (cr, dx, dy);
854 dy = -dy;
856 cairo_set_line_width (cr, 1);
857 cairo_stroke (cr);
858 x_end_cr_clip (f);
860 #endif
863 /* Return the struct x_display_info corresponding to DPY. */
865 struct x_display_info *
866 x_display_info_for_display (Display *dpy)
868 struct x_display_info *dpyinfo;
870 for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
871 if (dpyinfo->display == dpy)
872 return dpyinfo;
874 return 0;
877 static Window
878 x_find_topmost_parent (struct frame *f)
880 struct x_output *x = f->output_data.x;
881 Window win = None, wi = x->parent_desc;
882 Display *dpy = FRAME_X_DISPLAY (f);
884 while (wi != FRAME_DISPLAY_INFO (f)->root_window)
886 Window root;
887 Window *children;
888 unsigned int nchildren;
890 win = wi;
891 if (XQueryTree (dpy, win, &root, &wi, &children, &nchildren))
892 XFree (children);
893 else
894 break;
897 return win;
900 #define OPAQUE 0xffffffff
902 void
903 x_set_frame_alpha (struct frame *f)
905 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
906 Display *dpy = FRAME_X_DISPLAY (f);
907 Window win = FRAME_OUTER_WINDOW (f);
908 double alpha = 1.0;
909 double alpha_min = 1.0;
910 unsigned long opac;
911 Window parent;
913 if (dpyinfo->x_highlight_frame == f)
914 alpha = f->alpha[0];
915 else
916 alpha = f->alpha[1];
918 if (FLOATP (Vframe_alpha_lower_limit))
919 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
920 else if (INTEGERP (Vframe_alpha_lower_limit))
921 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
923 if (alpha < 0.0)
924 return;
925 else if (alpha > 1.0)
926 alpha = 1.0;
927 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
928 alpha = alpha_min;
930 opac = alpha * OPAQUE;
932 x_catch_errors (dpy);
934 /* If there is a parent from the window manager, put the property there
935 also, to work around broken window managers that fail to do that.
936 Do this unconditionally as this function is called on reparent when
937 alpha has not changed on the frame. */
939 if (!FRAME_PARENT_FRAME (f))
941 parent = x_find_topmost_parent (f);
942 if (parent != None)
943 XChangeProperty (dpy, parent, dpyinfo->Xatom_net_wm_window_opacity,
944 XA_CARDINAL, 32, PropModeReplace,
945 (unsigned char *) &opac, 1);
948 /* return unless necessary */
950 unsigned char *data;
951 Atom actual;
952 int rc, format;
953 unsigned long n, left;
955 rc = XGetWindowProperty (dpy, win, dpyinfo->Xatom_net_wm_window_opacity,
956 0, 1, False, XA_CARDINAL,
957 &actual, &format, &n, &left,
958 &data);
960 if (rc == Success && actual != None)
962 unsigned long value = *(unsigned long *)data;
963 XFree (data);
964 if (value == opac)
966 x_uncatch_errors ();
967 return;
972 XChangeProperty (dpy, win, dpyinfo->Xatom_net_wm_window_opacity,
973 XA_CARDINAL, 32, PropModeReplace,
974 (unsigned char *) &opac, 1);
975 x_uncatch_errors ();
978 /***********************************************************************
979 Starting and ending an update
980 ***********************************************************************/
982 /* Start an update of frame F. This function is installed as a hook
983 for update_begin, i.e. it is called when update_begin is called.
984 This function is called prior to calls to x_update_window_begin for
985 each window being updated. Currently, there is nothing to do here
986 because all interesting stuff is done on a window basis. */
988 static void
989 x_update_begin (struct frame *f)
991 #ifdef USE_CAIRO
992 if (FRAME_TOOLTIP_P (f) && !FRAME_VISIBLE_P (f))
993 return;
995 if (! FRAME_CR_SURFACE (f))
997 int width, height;
998 #ifdef USE_GTK
999 if (FRAME_GTK_WIDGET (f))
1001 GdkWindow *w = gtk_widget_get_window (FRAME_GTK_WIDGET (f));
1002 width = gdk_window_get_width (w);
1003 height = gdk_window_get_height (w);
1005 else
1006 #endif
1008 width = FRAME_PIXEL_WIDTH (f);
1009 height = FRAME_PIXEL_HEIGHT (f);
1010 if (! FRAME_EXTERNAL_TOOL_BAR (f))
1011 height += FRAME_TOOL_BAR_HEIGHT (f);
1012 if (! FRAME_EXTERNAL_MENU_BAR (f))
1013 height += FRAME_MENU_BAR_HEIGHT (f);
1016 if (width > 0 && height > 0)
1018 block_input();
1019 FRAME_CR_SURFACE (f) = cairo_image_surface_create
1020 (CAIRO_FORMAT_ARGB32, width, height);
1021 unblock_input();
1024 #endif /* USE_CAIRO */
1027 /* Start update of window W. */
1029 static void
1030 x_update_window_begin (struct window *w)
1032 struct frame *f = XFRAME (WINDOW_FRAME (w));
1033 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1035 w->output_cursor = w->cursor;
1037 block_input ();
1039 if (f == hlinfo->mouse_face_mouse_frame)
1041 /* Don't do highlighting for mouse motion during the update. */
1042 hlinfo->mouse_face_defer = true;
1044 /* If F needs to be redrawn, simply forget about any prior mouse
1045 highlighting. */
1046 if (FRAME_GARBAGED_P (f))
1047 hlinfo->mouse_face_window = Qnil;
1050 unblock_input ();
1054 /* Draw a vertical window border from (x,y0) to (x,y1) */
1056 static void
1057 x_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
1059 struct frame *f = XFRAME (WINDOW_FRAME (w));
1060 struct face *face;
1062 face = FACE_FROM_ID_OR_NULL (f, VERTICAL_BORDER_FACE_ID);
1063 if (face)
1064 XSetForeground (FRAME_X_DISPLAY (f), f->output_data.x->normal_gc,
1065 face->foreground);
1067 #ifdef USE_CAIRO
1068 x_fill_rectangle (f, f->output_data.x->normal_gc, x, y0, 1, y1 - y0);
1069 #else
1070 XDrawLine (FRAME_X_DISPLAY (f), FRAME_X_DRAWABLE (f),
1071 f->output_data.x->normal_gc, x, y0, x, y1);
1072 #endif
1075 /* Draw a window divider from (x0,y0) to (x1,y1) */
1077 static void
1078 x_draw_window_divider (struct window *w, int x0, int x1, int y0, int y1)
1080 struct frame *f = XFRAME (WINDOW_FRAME (w));
1081 struct face *face = FACE_FROM_ID_OR_NULL (f, WINDOW_DIVIDER_FACE_ID);
1082 struct face *face_first
1083 = FACE_FROM_ID_OR_NULL (f, WINDOW_DIVIDER_FIRST_PIXEL_FACE_ID);
1084 struct face *face_last
1085 = FACE_FROM_ID_OR_NULL (f, WINDOW_DIVIDER_LAST_PIXEL_FACE_ID);
1086 unsigned long color = face ? face->foreground : FRAME_FOREGROUND_PIXEL (f);
1087 unsigned long color_first = (face_first
1088 ? face_first->foreground
1089 : FRAME_FOREGROUND_PIXEL (f));
1090 unsigned long color_last = (face_last
1091 ? face_last->foreground
1092 : FRAME_FOREGROUND_PIXEL (f));
1093 Display *display = FRAME_X_DISPLAY (f);
1095 if ((y1 - y0 > x1 - x0) && (x1 - x0 >= 3))
1096 /* A vertical divider, at least three pixels wide: Draw first and
1097 last pixels differently. */
1099 XSetForeground (display, f->output_data.x->normal_gc, color_first);
1100 x_fill_rectangle (f, f->output_data.x->normal_gc,
1101 x0, y0, 1, y1 - y0);
1102 XSetForeground (display, f->output_data.x->normal_gc, color);
1103 x_fill_rectangle (f, f->output_data.x->normal_gc,
1104 x0 + 1, y0, x1 - x0 - 2, y1 - y0);
1105 XSetForeground (display, f->output_data.x->normal_gc, color_last);
1106 x_fill_rectangle (f, f->output_data.x->normal_gc,
1107 x1 - 1, y0, 1, y1 - y0);
1109 else if ((x1 - x0 > y1 - y0) && (y1 - y0 >= 3))
1110 /* A horizontal divider, at least three pixels high: Draw first and
1111 last pixels differently. */
1113 XSetForeground (display, f->output_data.x->normal_gc, color_first);
1114 x_fill_rectangle (f, f->output_data.x->normal_gc,
1115 x0, y0, x1 - x0, 1);
1116 XSetForeground (display, f->output_data.x->normal_gc, color);
1117 x_fill_rectangle (f, f->output_data.x->normal_gc,
1118 x0, y0 + 1, x1 - x0, y1 - y0 - 2);
1119 XSetForeground (display, f->output_data.x->normal_gc, color_last);
1120 x_fill_rectangle (f, f->output_data.x->normal_gc,
1121 x0, y1 - 1, x1 - x0, 1);
1123 else
1125 /* In any other case do not draw the first and last pixels
1126 differently. */
1127 XSetForeground (display, f->output_data.x->normal_gc, color);
1128 x_fill_rectangle (f, f->output_data.x->normal_gc,
1129 x0, y0, x1 - x0, y1 - y0);
1133 /* End update of window W.
1135 Draw vertical borders between horizontally adjacent windows, and
1136 display W's cursor if CURSOR_ON_P is non-zero.
1138 MOUSE_FACE_OVERWRITTEN_P non-zero means that some row containing
1139 glyphs in mouse-face were overwritten. In that case we have to
1140 make sure that the mouse-highlight is properly redrawn.
1142 W may be a menu bar pseudo-window in case we don't have X toolkit
1143 support. Such windows don't have a cursor, so don't display it
1144 here. */
1146 static void
1147 x_update_window_end (struct window *w, bool cursor_on_p,
1148 bool mouse_face_overwritten_p)
1150 if (!w->pseudo_window_p)
1152 block_input ();
1154 if (cursor_on_p)
1155 display_and_set_cursor (w, true,
1156 w->output_cursor.hpos, w->output_cursor.vpos,
1157 w->output_cursor.x, w->output_cursor.y);
1159 if (draw_window_fringes (w, true))
1161 if (WINDOW_RIGHT_DIVIDER_WIDTH (w))
1162 x_draw_right_divider (w);
1163 else
1164 x_draw_vertical_border (w);
1167 unblock_input ();
1170 /* If a row with mouse-face was overwritten, arrange for
1171 XTframe_up_to_date to redisplay the mouse highlight. */
1172 if (mouse_face_overwritten_p)
1174 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (XFRAME (w->frame));
1176 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
1177 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
1178 hlinfo->mouse_face_window = Qnil;
1182 /* Show the frame back buffer. If frame is double-buffered,
1183 atomically publish to the user's screen graphics updates made since
1184 the last call to show_back_buffer. */
1185 static void
1186 show_back_buffer (struct frame *f)
1188 block_input ();
1189 if (FRAME_X_DOUBLE_BUFFERED_P (f))
1191 #ifdef HAVE_XDBE
1192 XdbeSwapInfo swap_info;
1193 memset (&swap_info, 0, sizeof (swap_info));
1194 swap_info.swap_window = FRAME_X_WINDOW (f);
1195 swap_info.swap_action = XdbeCopied;
1196 XdbeSwapBuffers (FRAME_X_DISPLAY (f), &swap_info, 1);
1197 #else
1198 eassert (!"should have back-buffer only with XDBE");
1199 #endif
1201 FRAME_X_NEED_BUFFER_FLIP (f) = false;
1202 unblock_input ();
1205 /* Updates back buffer and flushes changes to display. Called from
1206 minibuf read code. Note that we display the back buffer even if
1207 buffer flipping is blocked. */
1208 static void
1209 x_flip_and_flush (struct frame *f)
1211 block_input ();
1212 if (FRAME_X_NEED_BUFFER_FLIP (f))
1213 show_back_buffer (f);
1214 x_flush (f);
1215 unblock_input ();
1218 /* End update of frame F. This function is installed as a hook in
1219 update_end. */
1221 static void
1222 x_update_end (struct frame *f)
1224 /* Mouse highlight may be displayed again. */
1225 MOUSE_HL_INFO (f)->mouse_face_defer = false;
1227 #ifdef USE_CAIRO
1228 if (FRAME_CR_SURFACE (f))
1230 cairo_t *cr;
1231 cairo_surface_t *surface;
1232 int width, height;
1234 block_input ();
1235 width = FRAME_PIXEL_WIDTH (f);
1236 height = FRAME_PIXEL_HEIGHT (f);
1237 if (! FRAME_EXTERNAL_TOOL_BAR (f))
1238 height += FRAME_TOOL_BAR_HEIGHT (f);
1239 if (! FRAME_EXTERNAL_MENU_BAR (f))
1240 height += FRAME_MENU_BAR_HEIGHT (f);
1241 surface = cairo_xlib_surface_create (FRAME_X_DISPLAY (f),
1242 FRAME_X_DRAWABLE (f),
1243 FRAME_DISPLAY_INFO (f)->visual,
1244 width,
1245 height);
1246 cr = cairo_create (surface);
1247 cairo_surface_destroy (surface);
1249 cairo_set_source_surface (cr, FRAME_CR_SURFACE (f), 0, 0);
1250 cairo_paint (cr);
1251 cairo_destroy (cr);
1252 unblock_input ();
1254 #endif
1256 #ifndef XFlush
1257 block_input ();
1258 XFlush (FRAME_X_DISPLAY (f));
1259 unblock_input ();
1260 #endif
1263 /* This function is called from various places in xdisp.c
1264 whenever a complete update has been performed. */
1266 static void
1267 XTframe_up_to_date (struct frame *f)
1269 eassert (FRAME_X_P (f));
1270 block_input ();
1271 FRAME_MOUSE_UPDATE (f);
1272 if (!buffer_flipping_blocked_p () && FRAME_X_NEED_BUFFER_FLIP (f))
1273 show_back_buffer (f);
1274 unblock_input ();
1277 static void
1278 XTbuffer_flipping_unblocked_hook (struct frame *f)
1280 if (FRAME_X_NEED_BUFFER_FLIP (f))
1281 show_back_buffer (f);
1285 * x_clear_under_internal_border:
1287 * Clear area of frame F's internal border. If the internal border face
1288 * of F has been specified (is not null), fill the area with that face.
1290 void
1291 x_clear_under_internal_border (struct frame *f)
1293 if (FRAME_INTERNAL_BORDER_WIDTH (f) > 0)
1295 int border = FRAME_INTERNAL_BORDER_WIDTH (f);
1296 int width = FRAME_PIXEL_WIDTH (f);
1297 int height = FRAME_PIXEL_HEIGHT (f);
1298 #ifdef USE_GTK
1299 int margin = 0;
1300 #else
1301 int margin = FRAME_TOP_MARGIN_HEIGHT (f);
1302 #endif
1303 struct face *face = FACE_FROM_ID_OR_NULL (f, INTERNAL_BORDER_FACE_ID);
1305 block_input ();
1307 if (face)
1309 unsigned long color = face->background;
1310 Display *display = FRAME_X_DISPLAY (f);
1311 GC gc = f->output_data.x->normal_gc;
1313 XSetForeground (display, gc, color);
1314 x_fill_rectangle (f, gc, 0, margin, width, border);
1315 x_fill_rectangle (f, gc, 0, 0, border, height);
1316 x_fill_rectangle (f, gc, width - border, 0, border, height);
1317 x_fill_rectangle (f, gc, 0, height - border, width, border);
1318 XSetForeground (display, gc, FRAME_FOREGROUND_PIXEL (f));
1320 else
1322 x_clear_area (f, 0, 0, border, height);
1323 x_clear_area (f, 0, margin, width, border);
1324 x_clear_area (f, width - border, 0, border, height);
1325 x_clear_area (f, 0, height - border, width, border);
1328 unblock_input ();
1332 /* Draw truncation mark bitmaps, continuation mark bitmaps, overlay
1333 arrow bitmaps, or clear the fringes if no bitmaps are required
1334 before DESIRED_ROW is made current. This function is called from
1335 update_window_line only if it is known that there are differences
1336 between bitmaps to be drawn between current row and DESIRED_ROW. */
1338 static void
1339 x_after_update_window_line (struct window *w, struct glyph_row *desired_row)
1341 eassert (w);
1343 if (!desired_row->mode_line_p && !w->pseudo_window_p)
1344 desired_row->redraw_fringe_bitmaps_p = true;
1346 #ifdef USE_X_TOOLKIT
1347 /* When a window has disappeared, make sure that no rest of
1348 full-width rows stays visible in the internal border. Could
1349 check here if updated window is the leftmost/rightmost window,
1350 but I guess it's not worth doing since vertically split windows
1351 are almost never used, internal border is rarely set, and the
1352 overhead is very small. */
1354 struct frame *f;
1355 int width, height;
1357 if (windows_or_buffers_changed
1358 && desired_row->full_width_p
1359 && (f = XFRAME (w->frame),
1360 width = FRAME_INTERNAL_BORDER_WIDTH (f),
1361 width != 0)
1362 && (height = desired_row->visible_height,
1363 height > 0))
1365 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
1366 struct face *face = FACE_FROM_ID_OR_NULL (f, INTERNAL_BORDER_FACE_ID);
1368 block_input ();
1369 if (face)
1371 unsigned long color = face->background;
1372 Display *display = FRAME_X_DISPLAY (f);
1373 GC gc = f->output_data.x->normal_gc;
1375 XSetForeground (display, gc, color);
1376 x_fill_rectangle (f, gc, 0, y, width, height);
1377 x_fill_rectangle (f, gc, FRAME_PIXEL_WIDTH (f) - width, y,
1378 width, height);
1379 XSetForeground (display, gc, FRAME_FOREGROUND_PIXEL (f));
1381 else
1383 x_clear_area (f, 0, y, width, height);
1384 x_clear_area (f, FRAME_PIXEL_WIDTH (f) - width, y, width, height);
1386 unblock_input ();
1389 #endif
1392 static void
1393 x_draw_fringe_bitmap (struct window *w, struct glyph_row *row, struct draw_fringe_bitmap_params *p)
1395 struct frame *f = XFRAME (WINDOW_FRAME (w));
1396 Display *display = FRAME_X_DISPLAY (f);
1397 GC gc = f->output_data.x->normal_gc;
1398 struct face *face = p->face;
1400 /* Must clip because of partially visible lines. */
1401 x_clip_to_row (w, row, ANY_AREA, gc);
1403 if (p->bx >= 0 && !p->overlay_p)
1405 /* In case the same realized face is used for fringes and
1406 for something displayed in the text (e.g. face `region' on
1407 mono-displays, the fill style may have been changed to
1408 FillSolid in x_draw_glyph_string_background. */
1409 if (face->stipple)
1410 XSetFillStyle (display, face->gc, FillOpaqueStippled);
1411 else
1412 XSetForeground (display, face->gc, face->background);
1414 x_fill_rectangle (f, face->gc, p->bx, p->by, p->nx, p->ny);
1416 if (!face->stipple)
1417 XSetForeground (display, face->gc, face->foreground);
1420 #ifdef USE_CAIRO
1421 if (p->which && p->which < max_fringe_bmp)
1423 XGCValues gcv;
1425 XGetGCValues (display, gc, GCForeground | GCBackground, &gcv);
1426 XSetForeground (display, gc, (p->cursor_p
1427 ? (p->overlay_p ? face->background
1428 : f->output_data.x->cursor_pixel)
1429 : face->foreground));
1430 XSetBackground (display, gc, face->background);
1431 x_cr_draw_image (f, gc, fringe_bmp[p->which], 0, p->dh,
1432 p->wd, p->h, p->x, p->y, p->overlay_p);
1433 XSetForeground (display, gc, gcv.foreground);
1434 XSetBackground (display, gc, gcv.background);
1436 #else /* not USE_CAIRO */
1437 if (p->which)
1439 Drawable drawable = FRAME_X_DRAWABLE (f);
1440 char *bits;
1441 Pixmap pixmap, clipmask = (Pixmap) 0;
1442 int depth = DefaultDepthOfScreen (FRAME_X_SCREEN (f));
1443 XGCValues gcv;
1445 if (p->wd > 8)
1446 bits = (char *) (p->bits + p->dh);
1447 else
1448 bits = (char *) p->bits + p->dh;
1450 /* Draw the bitmap. I believe these small pixmaps can be cached
1451 by the server. */
1452 pixmap = XCreatePixmapFromBitmapData (display, drawable, bits, p->wd, p->h,
1453 (p->cursor_p
1454 ? (p->overlay_p ? face->background
1455 : f->output_data.x->cursor_pixel)
1456 : face->foreground),
1457 face->background, depth);
1459 if (p->overlay_p)
1461 clipmask = XCreatePixmapFromBitmapData (display,
1462 FRAME_DISPLAY_INFO (f)->root_window,
1463 bits, p->wd, p->h,
1464 1, 0, 1);
1465 gcv.clip_mask = clipmask;
1466 gcv.clip_x_origin = p->x;
1467 gcv.clip_y_origin = p->y;
1468 XChangeGC (display, gc, GCClipMask | GCClipXOrigin | GCClipYOrigin, &gcv);
1471 XCopyArea (display, pixmap, drawable, gc, 0, 0,
1472 p->wd, p->h, p->x, p->y);
1473 XFreePixmap (display, pixmap);
1475 if (p->overlay_p)
1477 gcv.clip_mask = (Pixmap) 0;
1478 XChangeGC (display, gc, GCClipMask, &gcv);
1479 XFreePixmap (display, clipmask);
1482 #endif /* not USE_CAIRO */
1484 x_reset_clip_rectangles (f, gc);
1487 /***********************************************************************
1488 Glyph display
1489 ***********************************************************************/
1493 static void x_set_glyph_string_clipping (struct glyph_string *);
1494 static void x_set_glyph_string_gc (struct glyph_string *);
1495 static void x_draw_glyph_string_foreground (struct glyph_string *);
1496 static void x_draw_composite_glyph_string_foreground (struct glyph_string *);
1497 static void x_draw_glyph_string_box (struct glyph_string *);
1498 static void x_draw_glyph_string (struct glyph_string *);
1499 static _Noreturn void x_delete_glyphs (struct frame *, int);
1500 static void x_compute_glyph_string_overhangs (struct glyph_string *);
1501 static void x_set_cursor_gc (struct glyph_string *);
1502 static void x_set_mode_line_face_gc (struct glyph_string *);
1503 static void x_set_mouse_face_gc (struct glyph_string *);
1504 static bool x_alloc_lighter_color (struct frame *, Display *, Colormap,
1505 unsigned long *, double, int);
1506 static void x_setup_relief_color (struct frame *, struct relief *,
1507 double, int, unsigned long);
1508 static void x_setup_relief_colors (struct glyph_string *);
1509 static void x_draw_image_glyph_string (struct glyph_string *);
1510 static void x_draw_image_relief (struct glyph_string *);
1511 static void x_draw_image_foreground (struct glyph_string *);
1512 static void x_draw_image_foreground_1 (struct glyph_string *, Pixmap);
1513 static void x_clear_glyph_string_rect (struct glyph_string *, int,
1514 int, int, int);
1515 static void x_draw_relief_rect (struct frame *, int, int, int, int,
1516 int, bool, bool, bool, bool, bool,
1517 XRectangle *);
1518 static void x_draw_box_rect (struct glyph_string *, int, int, int, int,
1519 int, bool, bool, XRectangle *);
1520 static void x_scroll_bar_clear (struct frame *);
1522 #ifdef GLYPH_DEBUG
1523 static void x_check_font (struct frame *, struct font *);
1524 #endif
1527 /* Set S->gc to a suitable GC for drawing glyph string S in cursor
1528 face. */
1530 static void
1531 x_set_cursor_gc (struct glyph_string *s)
1533 if (s->font == FRAME_FONT (s->f)
1534 && s->face->background == FRAME_BACKGROUND_PIXEL (s->f)
1535 && s->face->foreground == FRAME_FOREGROUND_PIXEL (s->f)
1536 && !s->cmp)
1537 s->gc = s->f->output_data.x->cursor_gc;
1538 else
1540 /* Cursor on non-default face: must merge. */
1541 XGCValues xgcv;
1542 unsigned long mask;
1544 xgcv.background = s->f->output_data.x->cursor_pixel;
1545 xgcv.foreground = s->face->background;
1547 /* If the glyph would be invisible, try a different foreground. */
1548 if (xgcv.foreground == xgcv.background)
1549 xgcv.foreground = s->face->foreground;
1550 if (xgcv.foreground == xgcv.background)
1551 xgcv.foreground = s->f->output_data.x->cursor_foreground_pixel;
1552 if (xgcv.foreground == xgcv.background)
1553 xgcv.foreground = s->face->foreground;
1555 /* Make sure the cursor is distinct from text in this face. */
1556 if (xgcv.background == s->face->background
1557 && xgcv.foreground == s->face->foreground)
1559 xgcv.background = s->face->foreground;
1560 xgcv.foreground = s->face->background;
1563 IF_DEBUG (x_check_font (s->f, s->font));
1564 xgcv.graphics_exposures = False;
1565 mask = GCForeground | GCBackground | GCGraphicsExposures;
1567 if (FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc)
1568 XChangeGC (s->display, FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc,
1569 mask, &xgcv);
1570 else
1571 FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc
1572 = XCreateGC (s->display, FRAME_X_DRAWABLE (s->f), mask, &xgcv);
1574 s->gc = FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc;
1579 /* Set up S->gc of glyph string S for drawing text in mouse face. */
1581 static void
1582 x_set_mouse_face_gc (struct glyph_string *s)
1584 int face_id;
1585 struct face *face;
1587 /* What face has to be used last for the mouse face? */
1588 face_id = MOUSE_HL_INFO (s->f)->mouse_face_face_id;
1589 face = FACE_FROM_ID_OR_NULL (s->f, face_id);
1590 if (face == NULL)
1591 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
1593 if (s->first_glyph->type == CHAR_GLYPH)
1594 face_id = FACE_FOR_CHAR (s->f, face, s->first_glyph->u.ch, -1, Qnil);
1595 else
1596 face_id = FACE_FOR_CHAR (s->f, face, 0, -1, Qnil);
1597 s->face = FACE_FROM_ID (s->f, face_id);
1598 prepare_face_for_display (s->f, s->face);
1600 if (s->font == s->face->font)
1601 s->gc = s->face->gc;
1602 else
1604 /* Otherwise construct scratch_cursor_gc with values from FACE
1605 except for FONT. */
1606 XGCValues xgcv;
1607 unsigned long mask;
1609 xgcv.background = s->face->background;
1610 xgcv.foreground = s->face->foreground;
1611 xgcv.graphics_exposures = False;
1612 mask = GCForeground | GCBackground | GCGraphicsExposures;
1614 if (FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc)
1615 XChangeGC (s->display, FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc,
1616 mask, &xgcv);
1617 else
1618 FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc
1619 = XCreateGC (s->display, FRAME_X_DRAWABLE (s->f), mask, &xgcv);
1621 s->gc = FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc;
1624 eassert (s->gc != 0);
1628 /* Set S->gc of glyph string S to a GC suitable for drawing a mode line.
1629 Faces to use in the mode line have already been computed when the
1630 matrix was built, so there isn't much to do, here. */
1632 static void
1633 x_set_mode_line_face_gc (struct glyph_string *s)
1635 s->gc = s->face->gc;
1639 /* Set S->gc of glyph string S for drawing that glyph string. Set
1640 S->stippled_p to a non-zero value if the face of S has a stipple
1641 pattern. */
1643 static void
1644 x_set_glyph_string_gc (struct glyph_string *s)
1646 prepare_face_for_display (s->f, s->face);
1648 if (s->hl == DRAW_NORMAL_TEXT)
1650 s->gc = s->face->gc;
1651 s->stippled_p = s->face->stipple != 0;
1653 else if (s->hl == DRAW_INVERSE_VIDEO)
1655 x_set_mode_line_face_gc (s);
1656 s->stippled_p = s->face->stipple != 0;
1658 else if (s->hl == DRAW_CURSOR)
1660 x_set_cursor_gc (s);
1661 s->stippled_p = false;
1663 else if (s->hl == DRAW_MOUSE_FACE)
1665 x_set_mouse_face_gc (s);
1666 s->stippled_p = s->face->stipple != 0;
1668 else if (s->hl == DRAW_IMAGE_RAISED
1669 || s->hl == DRAW_IMAGE_SUNKEN)
1671 s->gc = s->face->gc;
1672 s->stippled_p = s->face->stipple != 0;
1674 else
1675 emacs_abort ();
1677 /* GC must have been set. */
1678 eassert (s->gc != 0);
1682 /* Set clipping for output of glyph string S. S may be part of a mode
1683 line or menu if we don't have X toolkit support. */
1685 static void
1686 x_set_glyph_string_clipping (struct glyph_string *s)
1688 XRectangle *r = s->clip;
1689 int n = get_glyph_string_clip_rects (s, r, 2);
1691 if (n > 0)
1692 x_set_clip_rectangles (s->f, s->gc, r, n);
1693 s->num_clips = n;
1697 /* Set SRC's clipping for output of glyph string DST. This is called
1698 when we are drawing DST's left_overhang or right_overhang only in
1699 the area of SRC. */
1701 static void
1702 x_set_glyph_string_clipping_exactly (struct glyph_string *src, struct glyph_string *dst)
1704 XRectangle r;
1706 r.x = src->x;
1707 r.width = src->width;
1708 r.y = src->y;
1709 r.height = src->height;
1710 dst->clip[0] = r;
1711 dst->num_clips = 1;
1712 x_set_clip_rectangles (dst->f, dst->gc, &r, 1);
1716 /* RIF:
1717 Compute left and right overhang of glyph string S. */
1719 static void
1720 x_compute_glyph_string_overhangs (struct glyph_string *s)
1722 if (s->cmp == NULL
1723 && (s->first_glyph->type == CHAR_GLYPH
1724 || s->first_glyph->type == COMPOSITE_GLYPH))
1726 struct font_metrics metrics;
1728 if (s->first_glyph->type == CHAR_GLYPH)
1730 unsigned *code = alloca (sizeof (unsigned) * s->nchars);
1731 struct font *font = s->font;
1732 int i;
1734 for (i = 0; i < s->nchars; i++)
1735 code[i] = (s->char2b[i].byte1 << 8) | s->char2b[i].byte2;
1736 font->driver->text_extents (font, code, s->nchars, &metrics);
1738 else
1740 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1742 composition_gstring_width (gstring, s->cmp_from, s->cmp_to, &metrics);
1744 s->right_overhang = (metrics.rbearing > metrics.width
1745 ? metrics.rbearing - metrics.width : 0);
1746 s->left_overhang = metrics.lbearing < 0 ? - metrics.lbearing : 0;
1748 else if (s->cmp)
1750 s->right_overhang = s->cmp->rbearing - s->cmp->pixel_width;
1751 s->left_overhang = - s->cmp->lbearing;
1756 /* Fill rectangle X, Y, W, H with background color of glyph string S. */
1758 static void
1759 x_clear_glyph_string_rect (struct glyph_string *s, int x, int y, int w, int h)
1761 XGCValues xgcv;
1762 XGetGCValues (s->display, s->gc, GCForeground | GCBackground, &xgcv);
1763 XSetForeground (s->display, s->gc, xgcv.background);
1764 x_fill_rectangle (s->f, s->gc, x, y, w, h);
1765 XSetForeground (s->display, s->gc, xgcv.foreground);
1769 /* Draw the background of glyph_string S. If S->background_filled_p
1770 is non-zero don't draw it. FORCE_P non-zero means draw the
1771 background even if it wouldn't be drawn normally. This is used
1772 when a string preceding S draws into the background of S, or S
1773 contains the first component of a composition. */
1775 static void
1776 x_draw_glyph_string_background (struct glyph_string *s, bool force_p)
1778 /* Nothing to do if background has already been drawn or if it
1779 shouldn't be drawn in the first place. */
1780 if (!s->background_filled_p)
1782 int box_line_width = max (s->face->box_line_width, 0);
1784 if (s->stippled_p)
1786 /* Fill background with a stipple pattern. */
1787 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
1788 x_fill_rectangle (s->f, s->gc, s->x,
1789 s->y + box_line_width,
1790 s->background_width,
1791 s->height - 2 * box_line_width);
1792 XSetFillStyle (s->display, s->gc, FillSolid);
1793 s->background_filled_p = true;
1795 else if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
1796 /* When xdisp.c ignores FONT_HEIGHT, we cannot trust
1797 font dimensions, since the actual glyphs might be
1798 much smaller. So in that case we always clear the
1799 rectangle with background color. */
1800 || FONT_TOO_HIGH (s->font)
1801 || s->font_not_found_p
1802 || s->extends_to_end_of_line_p
1803 || force_p)
1805 x_clear_glyph_string_rect (s, s->x, s->y + box_line_width,
1806 s->background_width,
1807 s->height - 2 * box_line_width);
1808 s->background_filled_p = true;
1814 /* Draw the foreground of glyph string S. */
1816 static void
1817 x_draw_glyph_string_foreground (struct glyph_string *s)
1819 int i, x;
1821 /* If first glyph of S has a left box line, start drawing the text
1822 of S to the right of that box line. */
1823 if (s->face->box != FACE_NO_BOX
1824 && s->first_glyph->left_box_line_p)
1825 x = s->x + eabs (s->face->box_line_width);
1826 else
1827 x = s->x;
1829 /* Draw characters of S as rectangles if S's font could not be
1830 loaded. */
1831 if (s->font_not_found_p)
1833 for (i = 0; i < s->nchars; ++i)
1835 struct glyph *g = s->first_glyph + i;
1836 x_draw_rectangle (s->f,
1837 s->gc, x, s->y, g->pixel_width - 1,
1838 s->height - 1);
1839 x += g->pixel_width;
1842 else
1844 struct font *font = s->font;
1845 int boff = font->baseline_offset;
1846 int y;
1848 if (font->vertical_centering)
1849 boff = VCENTER_BASELINE_OFFSET (font, s->f) - boff;
1851 y = s->ybase - boff;
1852 if (s->for_overlaps
1853 || (s->background_filled_p && s->hl != DRAW_CURSOR))
1854 font->driver->draw (s, 0, s->nchars, x, y, false);
1855 else
1856 font->driver->draw (s, 0, s->nchars, x, y, true);
1857 if (s->face->overstrike)
1858 font->driver->draw (s, 0, s->nchars, x + 1, y, false);
1862 /* Draw the foreground of composite glyph string S. */
1864 static void
1865 x_draw_composite_glyph_string_foreground (struct glyph_string *s)
1867 int i, j, x;
1868 struct font *font = s->font;
1870 /* If first glyph of S has a left box line, start drawing the text
1871 of S to the right of that box line. */
1872 if (s->face && s->face->box != FACE_NO_BOX
1873 && s->first_glyph->left_box_line_p)
1874 x = s->x + eabs (s->face->box_line_width);
1875 else
1876 x = s->x;
1878 /* S is a glyph string for a composition. S->cmp_from is the index
1879 of the first character drawn for glyphs of this composition.
1880 S->cmp_from == 0 means we are drawing the very first character of
1881 this composition. */
1883 /* Draw a rectangle for the composition if the font for the very
1884 first character of the composition could not be loaded. */
1885 if (s->font_not_found_p)
1887 if (s->cmp_from == 0)
1888 x_draw_rectangle (s->f, s->gc, x, s->y,
1889 s->width - 1, s->height - 1);
1891 else if (! s->first_glyph->u.cmp.automatic)
1893 int y = s->ybase;
1895 for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
1896 /* TAB in a composition means display glyphs with padding
1897 space on the left or right. */
1898 if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
1900 int xx = x + s->cmp->offsets[j * 2];
1901 int yy = y - s->cmp->offsets[j * 2 + 1];
1903 font->driver->draw (s, j, j + 1, xx, yy, false);
1904 if (s->face->overstrike)
1905 font->driver->draw (s, j, j + 1, xx + 1, yy, false);
1908 else
1910 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1911 Lisp_Object glyph;
1912 int y = s->ybase;
1913 int width = 0;
1915 for (i = j = s->cmp_from; i < s->cmp_to; i++)
1917 glyph = LGSTRING_GLYPH (gstring, i);
1918 if (NILP (LGLYPH_ADJUSTMENT (glyph)))
1919 width += LGLYPH_WIDTH (glyph);
1920 else
1922 int xoff, yoff, wadjust;
1924 if (j < i)
1926 font->driver->draw (s, j, i, x, y, false);
1927 if (s->face->overstrike)
1928 font->driver->draw (s, j, i, x + 1, y, false);
1929 x += width;
1931 xoff = LGLYPH_XOFF (glyph);
1932 yoff = LGLYPH_YOFF (glyph);
1933 wadjust = LGLYPH_WADJUST (glyph);
1934 font->driver->draw (s, i, i + 1, x + xoff, y + yoff, false);
1935 if (s->face->overstrike)
1936 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff,
1937 false);
1938 x += wadjust;
1939 j = i + 1;
1940 width = 0;
1943 if (j < i)
1945 font->driver->draw (s, j, i, x, y, false);
1946 if (s->face->overstrike)
1947 font->driver->draw (s, j, i, x + 1, y, false);
1953 /* Draw the foreground of glyph string S for glyphless characters. */
1955 static void
1956 x_draw_glyphless_glyph_string_foreground (struct glyph_string *s)
1958 struct glyph *glyph = s->first_glyph;
1959 XChar2b char2b[8];
1960 int x, i, j;
1962 /* If first glyph of S has a left box line, start drawing the text
1963 of S to the right of that box line. */
1964 if (s->face && s->face->box != FACE_NO_BOX
1965 && s->first_glyph->left_box_line_p)
1966 x = s->x + eabs (s->face->box_line_width);
1967 else
1968 x = s->x;
1970 s->char2b = char2b;
1972 for (i = 0; i < s->nchars; i++, glyph++)
1974 #ifdef GCC_LINT
1975 enum { PACIFY_GCC_BUG_81401 = 1 };
1976 #else
1977 enum { PACIFY_GCC_BUG_81401 = 0 };
1978 #endif
1979 char buf[7 + PACIFY_GCC_BUG_81401];
1980 char *str = NULL;
1981 int len = glyph->u.glyphless.len;
1983 if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_ACRONYM)
1985 if (len > 0
1986 && CHAR_TABLE_P (Vglyphless_char_display)
1987 && (CHAR_TABLE_EXTRA_SLOTS (XCHAR_TABLE (Vglyphless_char_display))
1988 >= 1))
1990 Lisp_Object acronym
1991 = (! glyph->u.glyphless.for_no_font
1992 ? CHAR_TABLE_REF (Vglyphless_char_display,
1993 glyph->u.glyphless.ch)
1994 : XCHAR_TABLE (Vglyphless_char_display)->extras[0]);
1995 if (STRINGP (acronym))
1996 str = SSDATA (acronym);
1999 else if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_HEX_CODE)
2001 unsigned int ch = glyph->u.glyphless.ch;
2002 eassume (ch <= MAX_CHAR);
2003 sprintf (buf, "%0*X", ch < 0x10000 ? 4 : 6, ch);
2004 str = buf;
2007 if (str)
2009 int upper_len = (len + 1) / 2;
2010 unsigned code;
2012 /* It is assured that all LEN characters in STR is ASCII. */
2013 for (j = 0; j < len; j++)
2015 code = s->font->driver->encode_char (s->font, str[j]);
2016 STORE_XCHAR2B (char2b + j, code >> 8, code & 0xFF);
2018 s->font->driver->draw (s, 0, upper_len,
2019 x + glyph->slice.glyphless.upper_xoff,
2020 s->ybase + glyph->slice.glyphless.upper_yoff,
2021 false);
2022 s->font->driver->draw (s, upper_len, len,
2023 x + glyph->slice.glyphless.lower_xoff,
2024 s->ybase + glyph->slice.glyphless.lower_yoff,
2025 false);
2027 if (glyph->u.glyphless.method != GLYPHLESS_DISPLAY_THIN_SPACE)
2028 x_draw_rectangle (s->f, s->gc,
2029 x, s->ybase - glyph->ascent,
2030 glyph->pixel_width - 1,
2031 glyph->ascent + glyph->descent - 1);
2032 x += glyph->pixel_width;
2036 #ifdef USE_X_TOOLKIT
2038 #ifdef USE_LUCID
2040 /* Return the frame on which widget WIDGET is used.. Abort if frame
2041 cannot be determined. */
2043 static struct frame *
2044 x_frame_of_widget (Widget widget)
2046 struct x_display_info *dpyinfo;
2047 Lisp_Object tail, frame;
2048 struct frame *f;
2050 dpyinfo = x_display_info_for_display (XtDisplay (widget));
2052 /* Find the top-level shell of the widget. Note that this function
2053 can be called when the widget is not yet realized, so XtWindow
2054 (widget) == 0. That's the reason we can't simply use
2055 x_any_window_to_frame. */
2056 while (!XtIsTopLevelShell (widget))
2057 widget = XtParent (widget);
2059 /* Look for a frame with that top-level widget. Allocate the color
2060 on that frame to get the right gamma correction value. */
2061 FOR_EACH_FRAME (tail, frame)
2063 f = XFRAME (frame);
2064 if (FRAME_X_P (f)
2065 && f->output_data.nothing != 1
2066 && FRAME_DISPLAY_INFO (f) == dpyinfo
2067 && f->output_data.x->widget == widget)
2068 return f;
2070 emacs_abort ();
2073 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
2074 or DELTA. Try a color with RGB values multiplied by FACTOR first.
2075 If this produces the same color as PIXEL, try a color where all RGB
2076 values have DELTA added. Return the allocated color in *PIXEL.
2077 DISPLAY is the X display, CMAP is the colormap to operate on.
2078 Value is true if successful. */
2080 bool
2081 x_alloc_lighter_color_for_widget (Widget widget, Display *display, Colormap cmap,
2082 unsigned long *pixel, double factor, int delta)
2084 struct frame *f = x_frame_of_widget (widget);
2085 return x_alloc_lighter_color (f, display, cmap, pixel, factor, delta);
2088 #endif /* USE_LUCID */
2091 /* Structure specifying which arguments should be passed by Xt to
2092 cvt_string_to_pixel. We want the widget's screen and colormap. */
2094 static XtConvertArgRec cvt_string_to_pixel_args[] =
2096 {XtWidgetBaseOffset, (XtPointer) offsetof (WidgetRec, core.screen),
2097 sizeof (Screen *)},
2098 {XtWidgetBaseOffset, (XtPointer) offsetof (WidgetRec, core.colormap),
2099 sizeof (Colormap)}
2103 /* The address of this variable is returned by
2104 cvt_string_to_pixel. */
2106 static Pixel cvt_string_to_pixel_value;
2109 /* Convert a color name to a pixel color.
2111 DPY is the display we are working on.
2113 ARGS is an array of *NARGS XrmValue structures holding additional
2114 information about the widget for which the conversion takes place.
2115 The contents of this array are determined by the specification
2116 in cvt_string_to_pixel_args.
2118 FROM is a pointer to an XrmValue which points to the color name to
2119 convert. TO is an XrmValue in which to return the pixel color.
2121 CLOSURE_RET is a pointer to user-data, in which we record if
2122 we allocated the color or not.
2124 Value is True if successful, False otherwise. */
2126 static Boolean
2127 cvt_string_to_pixel (Display *dpy, XrmValue *args, Cardinal *nargs,
2128 XrmValue *from, XrmValue *to,
2129 XtPointer *closure_ret)
2131 Screen *screen;
2132 Colormap cmap;
2133 Pixel pixel;
2134 String color_name;
2135 XColor color;
2137 if (*nargs != 2)
2139 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
2140 "wrongParameters", "cvt_string_to_pixel",
2141 "XtToolkitError",
2142 "Screen and colormap args required", NULL, NULL);
2143 return False;
2146 screen = *(Screen **) args[0].addr;
2147 cmap = *(Colormap *) args[1].addr;
2148 color_name = (String) from->addr;
2150 if (strcmp (color_name, XtDefaultBackground) == 0)
2152 *closure_ret = (XtPointer) False;
2153 pixel = WhitePixelOfScreen (screen);
2155 else if (strcmp (color_name, XtDefaultForeground) == 0)
2157 *closure_ret = (XtPointer) False;
2158 pixel = BlackPixelOfScreen (screen);
2160 else if (XParseColor (dpy, cmap, color_name, &color)
2161 && x_alloc_nearest_color_1 (dpy, cmap, &color))
2163 pixel = color.pixel;
2164 *closure_ret = (XtPointer) True;
2166 else
2168 String params[1];
2169 Cardinal nparams = 1;
2171 params[0] = color_name;
2172 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
2173 "badValue", "cvt_string_to_pixel",
2174 "XtToolkitError", "Invalid color '%s'",
2175 params, &nparams);
2176 return False;
2179 if (to->addr != NULL)
2181 if (to->size < sizeof (Pixel))
2183 to->size = sizeof (Pixel);
2184 return False;
2187 *(Pixel *) to->addr = pixel;
2189 else
2191 cvt_string_to_pixel_value = pixel;
2192 to->addr = (XtPointer) &cvt_string_to_pixel_value;
2195 to->size = sizeof (Pixel);
2196 return True;
2200 /* Free a pixel color which was previously allocated via
2201 cvt_string_to_pixel. This is registered as the destructor
2202 for this type of resource via XtSetTypeConverter.
2204 APP is the application context in which we work.
2206 TO is a pointer to an XrmValue holding the color to free.
2207 CLOSURE is the value we stored in CLOSURE_RET for this color
2208 in cvt_string_to_pixel.
2210 ARGS and NARGS are like for cvt_string_to_pixel. */
2212 static void
2213 cvt_pixel_dtor (XtAppContext app, XrmValuePtr to, XtPointer closure, XrmValuePtr args,
2214 Cardinal *nargs)
2216 if (*nargs != 2)
2218 XtAppWarningMsg (app, "wrongParameters", "cvt_pixel_dtor",
2219 "XtToolkitError",
2220 "Screen and colormap arguments required",
2221 NULL, NULL);
2223 else if (closure != NULL)
2225 /* We did allocate the pixel, so free it. */
2226 Screen *screen = *(Screen **) args[0].addr;
2227 Colormap cmap = *(Colormap *) args[1].addr;
2228 x_free_dpy_colors (DisplayOfScreen (screen), screen, cmap,
2229 (Pixel *) to->addr, 1);
2234 #endif /* USE_X_TOOLKIT */
2237 /* Value is an array of XColor structures for the contents of the
2238 color map of display DPY. Set *NCELLS to the size of the array.
2239 Note that this probably shouldn't be called for large color maps,
2240 say a 24-bit TrueColor map. */
2242 static const XColor *
2243 x_color_cells (Display *dpy, int *ncells)
2245 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
2246 eassume (dpyinfo);
2248 if (dpyinfo->color_cells == NULL)
2250 Screen *screen = dpyinfo->screen;
2251 int ncolor_cells = XDisplayCells (dpy, XScreenNumberOfScreen (screen));
2252 int i;
2254 dpyinfo->color_cells = xnmalloc (ncolor_cells,
2255 sizeof *dpyinfo->color_cells);
2256 dpyinfo->ncolor_cells = ncolor_cells;
2258 for (i = 0; i < ncolor_cells; ++i)
2259 dpyinfo->color_cells[i].pixel = i;
2261 XQueryColors (dpy, dpyinfo->cmap,
2262 dpyinfo->color_cells, ncolor_cells);
2265 *ncells = dpyinfo->ncolor_cells;
2266 return dpyinfo->color_cells;
2270 /* On frame F, translate pixel colors to RGB values for the NCOLORS
2271 colors in COLORS. Use cached information, if available. */
2273 void
2274 x_query_colors (struct frame *f, XColor *colors, int ncolors)
2276 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2278 if (dpyinfo->red_bits > 0)
2280 /* For TrueColor displays, we can decompose the RGB value
2281 directly. */
2282 int i;
2283 unsigned int rmult, gmult, bmult;
2284 unsigned int rmask, gmask, bmask;
2286 rmask = (1 << dpyinfo->red_bits) - 1;
2287 gmask = (1 << dpyinfo->green_bits) - 1;
2288 bmask = (1 << dpyinfo->blue_bits) - 1;
2289 /* If we're widening, for example, 8 bits in the pixel value to
2290 16 bits for the separate-color representation, we want to
2291 extrapolate the lower bits based on those bits available --
2292 in other words, we'd like 0xff to become 0xffff instead of
2293 the 0xff00 we'd get by just zero-filling the lower bits.
2295 We generate a 32-bit scaled-up value and shift it, in case
2296 the bit count doesn't divide 16 evenly (e.g., when dealing
2297 with a 3-3-2 bit RGB display), to get more of the lower bits
2298 correct.
2300 Should we cache the multipliers in dpyinfo? Maybe
2301 special-case the 8-8-8 common case? */
2302 rmult = 0xffffffff / rmask;
2303 gmult = 0xffffffff / gmask;
2304 bmult = 0xffffffff / bmask;
2306 for (i = 0; i < ncolors; ++i)
2308 unsigned int r, g, b;
2309 unsigned long pixel = colors[i].pixel;
2311 r = (pixel >> dpyinfo->red_offset) & rmask;
2312 g = (pixel >> dpyinfo->green_offset) & gmask;
2313 b = (pixel >> dpyinfo->blue_offset) & bmask;
2315 colors[i].red = (r * rmult) >> 16;
2316 colors[i].green = (g * gmult) >> 16;
2317 colors[i].blue = (b * bmult) >> 16;
2319 return;
2322 if (dpyinfo->color_cells)
2324 int i;
2325 for (i = 0; i < ncolors; ++i)
2327 unsigned long pixel = colors[i].pixel;
2328 eassert (pixel < dpyinfo->ncolor_cells);
2329 eassert (dpyinfo->color_cells[pixel].pixel == pixel);
2330 colors[i] = dpyinfo->color_cells[pixel];
2332 return;
2335 XQueryColors (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), colors, ncolors);
2339 /* On frame F, translate pixel color to RGB values for the color in
2340 COLOR. Use cached information, if available. */
2342 void
2343 x_query_color (struct frame *f, XColor *color)
2345 x_query_colors (f, color, 1);
2349 /* On frame F, translate the color name to RGB values. Use cached
2350 information, if possible.
2352 Note that there is currently no way to clean old entries out of the
2353 cache. However, it is limited to names in the server's database,
2354 and names we've actually looked up; list-colors-display is probably
2355 the most color-intensive case we're likely to hit. */
2357 Status x_parse_color (struct frame *f, const char *color_name,
2358 XColor *color)
2360 Display *dpy = FRAME_X_DISPLAY (f);
2361 Colormap cmap = FRAME_X_COLORMAP (f);
2362 struct color_name_cache_entry *cache_entry;
2364 if (color_name[0] == '#')
2366 /* The hex form is parsed directly by XParseColor without
2367 talking to the X server. No need for caching. */
2368 return XParseColor (dpy, cmap, color_name, color);
2371 for (cache_entry = FRAME_DISPLAY_INFO (f)->color_names; cache_entry;
2372 cache_entry = cache_entry->next)
2374 if (!xstrcasecmp(cache_entry->name, color_name))
2376 *color = cache_entry->rgb;
2377 return 1;
2381 if (XParseColor (dpy, cmap, color_name, color) == 0)
2382 /* No caching of negative results, currently. */
2383 return 0;
2385 cache_entry = xzalloc (sizeof *cache_entry);
2386 cache_entry->rgb = *color;
2387 cache_entry->name = xstrdup (color_name);
2388 cache_entry->next = FRAME_DISPLAY_INFO (f)->color_names;
2389 FRAME_DISPLAY_INFO (f)->color_names = cache_entry;
2390 return 1;
2394 /* Allocate the color COLOR->pixel on DISPLAY, colormap CMAP. If an
2395 exact match can't be allocated, try the nearest color available.
2396 Value is true if successful. Set *COLOR to the color
2397 allocated. */
2399 static bool
2400 x_alloc_nearest_color_1 (Display *dpy, Colormap cmap, XColor *color)
2402 bool rc;
2404 rc = XAllocColor (dpy, cmap, color) != 0;
2405 if (rc == 0)
2407 /* If we got to this point, the colormap is full, so we're going
2408 to try to get the next closest color. The algorithm used is
2409 a least-squares matching, which is what X uses for closest
2410 color matching with StaticColor visuals. */
2411 int nearest, i;
2412 int max_color_delta = 255;
2413 int max_delta = 3 * max_color_delta;
2414 int nearest_delta = max_delta + 1;
2415 int ncells;
2416 const XColor *cells = x_color_cells (dpy, &ncells);
2418 for (nearest = i = 0; i < ncells; ++i)
2420 int dred = (color->red >> 8) - (cells[i].red >> 8);
2421 int dgreen = (color->green >> 8) - (cells[i].green >> 8);
2422 int dblue = (color->blue >> 8) - (cells[i].blue >> 8);
2423 int delta = dred * dred + dgreen * dgreen + dblue * dblue;
2425 if (delta < nearest_delta)
2427 nearest = i;
2428 nearest_delta = delta;
2432 color->red = cells[nearest].red;
2433 color->green = cells[nearest].green;
2434 color->blue = cells[nearest].blue;
2435 rc = XAllocColor (dpy, cmap, color) != 0;
2437 else
2439 /* If allocation succeeded, and the allocated pixel color is not
2440 equal to a cached pixel color recorded earlier, there was a
2441 change in the colormap, so clear the color cache. */
2442 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
2443 eassume (dpyinfo);
2445 if (dpyinfo->color_cells)
2447 XColor *cached_color = &dpyinfo->color_cells[color->pixel];
2448 if (cached_color->red != color->red
2449 || cached_color->blue != color->blue
2450 || cached_color->green != color->green)
2452 xfree (dpyinfo->color_cells);
2453 dpyinfo->color_cells = NULL;
2454 dpyinfo->ncolor_cells = 0;
2459 #ifdef DEBUG_X_COLORS
2460 if (rc)
2461 register_color (color->pixel);
2462 #endif /* DEBUG_X_COLORS */
2464 return rc;
2468 /* Allocate the color COLOR->pixel on frame F, colormap CMAP, after
2469 gamma correction. If an exact match can't be allocated, try the
2470 nearest color available. Value is true if successful. Set *COLOR
2471 to the color allocated. */
2473 bool
2474 x_alloc_nearest_color (struct frame *f, Colormap cmap, XColor *color)
2476 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2478 gamma_correct (f, color);
2480 if (dpyinfo->red_bits > 0)
2482 color->pixel = x_make_truecolor_pixel (dpyinfo,
2483 color->red,
2484 color->green,
2485 color->blue);
2486 return true;
2489 return x_alloc_nearest_color_1 (FRAME_X_DISPLAY (f), cmap, color);
2493 /* Allocate color PIXEL on frame F. PIXEL must already be allocated.
2494 It's necessary to do this instead of just using PIXEL directly to
2495 get color reference counts right. */
2497 unsigned long
2498 x_copy_color (struct frame *f, unsigned long pixel)
2500 XColor color;
2502 /* If display has an immutable color map, freeing colors is not
2503 necessary and some servers don't allow it. Since we won't free a
2504 color once we've allocated it, we don't need to re-allocate it to
2505 maintain the server's reference count. */
2506 if (!x_mutable_colormap (FRAME_X_VISUAL (f)))
2507 return pixel;
2509 color.pixel = pixel;
2510 block_input ();
2511 /* The color could still be found in the color_cells array. */
2512 x_query_color (f, &color);
2513 XAllocColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &color);
2514 unblock_input ();
2515 #ifdef DEBUG_X_COLORS
2516 register_color (pixel);
2517 #endif
2518 return color.pixel;
2522 /* Brightness beyond which a color won't have its highlight brightness
2523 boosted.
2525 Nominally, highlight colors for `3d' faces are calculated by
2526 brightening an object's color by a constant scale factor, but this
2527 doesn't yield good results for dark colors, so for colors who's
2528 brightness is less than this value (on a scale of 0-65535) have an
2529 use an additional additive factor.
2531 The value here is set so that the default menu-bar/mode-line color
2532 (grey75) will not have its highlights changed at all. */
2533 #define HIGHLIGHT_COLOR_DARK_BOOST_LIMIT 48000
2536 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
2537 or DELTA. Try a color with RGB values multiplied by FACTOR first.
2538 If this produces the same color as PIXEL, try a color where all RGB
2539 values have DELTA added. Return the allocated color in *PIXEL.
2540 DISPLAY is the X display, CMAP is the colormap to operate on.
2541 Value is non-zero if successful. */
2543 static bool
2544 x_alloc_lighter_color (struct frame *f, Display *display, Colormap cmap,
2545 unsigned long *pixel, double factor, int delta)
2547 XColor color, new;
2548 long bright;
2549 bool success_p;
2551 /* Get RGB color values. */
2552 color.pixel = *pixel;
2553 x_query_color (f, &color);
2555 /* Change RGB values by specified FACTOR. Avoid overflow! */
2556 eassert (factor >= 0);
2557 new.red = min (0xffff, factor * color.red);
2558 new.green = min (0xffff, factor * color.green);
2559 new.blue = min (0xffff, factor * color.blue);
2561 /* Calculate brightness of COLOR. */
2562 bright = (2 * color.red + 3 * color.green + color.blue) / 6;
2564 /* We only boost colors that are darker than
2565 HIGHLIGHT_COLOR_DARK_BOOST_LIMIT. */
2566 if (bright < HIGHLIGHT_COLOR_DARK_BOOST_LIMIT)
2567 /* Make an additive adjustment to NEW, because it's dark enough so
2568 that scaling by FACTOR alone isn't enough. */
2570 /* How far below the limit this color is (0 - 1, 1 being darker). */
2571 double dimness = 1 - (double)bright / HIGHLIGHT_COLOR_DARK_BOOST_LIMIT;
2572 /* The additive adjustment. */
2573 int min_delta = delta * dimness * factor / 2;
2575 if (factor < 1)
2577 new.red = max (0, new.red - min_delta);
2578 new.green = max (0, new.green - min_delta);
2579 new.blue = max (0, new.blue - min_delta);
2581 else
2583 new.red = min (0xffff, min_delta + new.red);
2584 new.green = min (0xffff, min_delta + new.green);
2585 new.blue = min (0xffff, min_delta + new.blue);
2589 /* Try to allocate the color. */
2590 success_p = x_alloc_nearest_color (f, cmap, &new);
2591 if (success_p)
2593 if (new.pixel == *pixel)
2595 /* If we end up with the same color as before, try adding
2596 delta to the RGB values. */
2597 x_free_colors (f, &new.pixel, 1);
2599 new.red = min (0xffff, delta + color.red);
2600 new.green = min (0xffff, delta + color.green);
2601 new.blue = min (0xffff, delta + color.blue);
2602 success_p = x_alloc_nearest_color (f, cmap, &new);
2604 else
2605 success_p = true;
2606 *pixel = new.pixel;
2609 return success_p;
2613 /* Set up the foreground color for drawing relief lines of glyph
2614 string S. RELIEF is a pointer to a struct relief containing the GC
2615 with which lines will be drawn. Use a color that is FACTOR or
2616 DELTA lighter or darker than the relief's background which is found
2617 in S->f->output_data.x->relief_background. If such a color cannot
2618 be allocated, use DEFAULT_PIXEL, instead. */
2620 static void
2621 x_setup_relief_color (struct frame *f, struct relief *relief, double factor,
2622 int delta, unsigned long default_pixel)
2624 XGCValues xgcv;
2625 struct x_output *di = f->output_data.x;
2626 unsigned long mask = GCForeground | GCLineWidth | GCGraphicsExposures;
2627 unsigned long pixel;
2628 unsigned long background = di->relief_background;
2629 Colormap cmap = FRAME_X_COLORMAP (f);
2630 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2631 Display *dpy = FRAME_X_DISPLAY (f);
2633 xgcv.graphics_exposures = False;
2634 xgcv.line_width = 1;
2636 /* Free previously allocated color. The color cell will be reused
2637 when it has been freed as many times as it was allocated, so this
2638 doesn't affect faces using the same colors. */
2639 if (relief->gc && relief->pixel != -1)
2641 x_free_colors (f, &relief->pixel, 1);
2642 relief->pixel = -1;
2645 /* Allocate new color. */
2646 xgcv.foreground = default_pixel;
2647 pixel = background;
2648 if (dpyinfo->n_planes != 1
2649 && x_alloc_lighter_color (f, dpy, cmap, &pixel, factor, delta))
2650 xgcv.foreground = relief->pixel = pixel;
2652 if (relief->gc == 0)
2654 xgcv.stipple = dpyinfo->gray;
2655 mask |= GCStipple;
2656 relief->gc = XCreateGC (dpy, FRAME_X_DRAWABLE (f), mask, &xgcv);
2658 else
2659 XChangeGC (dpy, relief->gc, mask, &xgcv);
2663 /* Set up colors for the relief lines around glyph string S. */
2665 static void
2666 x_setup_relief_colors (struct glyph_string *s)
2668 struct x_output *di = s->f->output_data.x;
2669 unsigned long color;
2671 if (s->face->use_box_color_for_shadows_p)
2672 color = s->face->box_color;
2673 else if (s->first_glyph->type == IMAGE_GLYPH
2674 && s->img->pixmap
2675 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2676 color = IMAGE_BACKGROUND (s->img, s->f, 0);
2677 else
2679 XGCValues xgcv;
2681 /* Get the background color of the face. */
2682 XGetGCValues (s->display, s->gc, GCBackground, &xgcv);
2683 color = xgcv.background;
2686 if (di->white_relief.gc == 0
2687 || color != di->relief_background)
2689 di->relief_background = color;
2690 x_setup_relief_color (s->f, &di->white_relief, 1.2, 0x8000,
2691 WHITE_PIX_DEFAULT (s->f));
2692 x_setup_relief_color (s->f, &di->black_relief, 0.6, 0x4000,
2693 BLACK_PIX_DEFAULT (s->f));
2698 /* Draw a relief on frame F inside the rectangle given by LEFT_X,
2699 TOP_Y, RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the relief
2700 to draw, it must be >= 0. RAISED_P means draw a raised
2701 relief. LEFT_P means draw a relief on the left side of
2702 the rectangle. RIGHT_P means draw a relief on the right
2703 side of the rectangle. CLIP_RECT is the clipping rectangle to use
2704 when drawing. */
2706 static void
2707 x_draw_relief_rect (struct frame *f,
2708 int left_x, int top_y, int right_x, int bottom_y,
2709 int width, bool raised_p, bool top_p, bool bot_p,
2710 bool left_p, bool right_p,
2711 XRectangle *clip_rect)
2713 #ifdef USE_CAIRO
2714 GC top_left_gc, bottom_right_gc;
2715 int corners = 0;
2717 if (raised_p)
2719 top_left_gc = f->output_data.x->white_relief.gc;
2720 bottom_right_gc = f->output_data.x->black_relief.gc;
2722 else
2724 top_left_gc = f->output_data.x->black_relief.gc;
2725 bottom_right_gc = f->output_data.x->white_relief.gc;
2728 x_set_clip_rectangles (f, top_left_gc, clip_rect, 1);
2729 x_set_clip_rectangles (f, bottom_right_gc, clip_rect, 1);
2731 if (left_p)
2733 x_fill_rectangle (f, top_left_gc, left_x, top_y,
2734 width, bottom_y + 1 - top_y);
2735 if (top_p)
2736 corners |= 1 << CORNER_TOP_LEFT;
2737 if (bot_p)
2738 corners |= 1 << CORNER_BOTTOM_LEFT;
2740 if (right_p)
2742 x_fill_rectangle (f, bottom_right_gc, right_x + 1 - width, top_y,
2743 width, bottom_y + 1 - top_y);
2744 if (top_p)
2745 corners |= 1 << CORNER_TOP_RIGHT;
2746 if (bot_p)
2747 corners |= 1 << CORNER_BOTTOM_RIGHT;
2749 if (top_p)
2751 if (!right_p)
2752 x_fill_rectangle (f, top_left_gc, left_x, top_y,
2753 right_x + 1 - left_x, width);
2754 else
2755 x_fill_trapezoid_for_relief (f, top_left_gc, left_x, top_y,
2756 right_x + 1 - left_x, width, 1);
2758 if (bot_p)
2760 if (!left_p)
2761 x_fill_rectangle (f, bottom_right_gc, left_x, bottom_y + 1 - width,
2762 right_x + 1 - left_x, width);
2763 else
2764 x_fill_trapezoid_for_relief (f, bottom_right_gc,
2765 left_x, bottom_y + 1 - width,
2766 right_x + 1 - left_x, width, 0);
2768 if (left_p && width != 1)
2769 x_fill_rectangle (f, bottom_right_gc, left_x, top_y,
2770 1, bottom_y + 1 - top_y);
2771 if (top_p && width != 1)
2772 x_fill_rectangle (f, bottom_right_gc, left_x, top_y,
2773 right_x + 1 - left_x, 1);
2774 if (corners)
2776 XSetBackground (FRAME_X_DISPLAY (f), top_left_gc,
2777 FRAME_BACKGROUND_PIXEL (f));
2778 x_erase_corners_for_relief (f, top_left_gc, left_x, top_y,
2779 right_x - left_x + 1, bottom_y - top_y + 1,
2780 6, 1, corners);
2783 x_reset_clip_rectangles (f, top_left_gc);
2784 x_reset_clip_rectangles (f, bottom_right_gc);
2785 #else
2786 Display *dpy = FRAME_X_DISPLAY (f);
2787 Drawable drawable = FRAME_X_DRAWABLE (f);
2788 int i;
2789 GC gc;
2791 if (raised_p)
2792 gc = f->output_data.x->white_relief.gc;
2793 else
2794 gc = f->output_data.x->black_relief.gc;
2795 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
2797 /* This code is more complicated than it has to be, because of two
2798 minor hacks to make the boxes look nicer: (i) if width > 1, draw
2799 the outermost line using the black relief. (ii) Omit the four
2800 corner pixels. */
2802 /* Top. */
2803 if (top_p)
2805 if (width == 1)
2806 XDrawLine (dpy, drawable, gc,
2807 left_x + left_p, top_y,
2808 right_x + !right_p, top_y);
2810 for (i = 1; i < width; ++i)
2811 XDrawLine (dpy, drawable, gc,
2812 left_x + i * left_p, top_y + i,
2813 right_x + 1 - i * right_p, top_y + i);
2816 /* Left. */
2817 if (left_p)
2819 if (width == 1)
2820 XDrawLine (dpy, drawable, gc, left_x, top_y + 1, left_x, bottom_y);
2822 x_clear_area(f, left_x, top_y, 1, 1);
2823 x_clear_area(f, left_x, bottom_y, 1, 1);
2825 for (i = (width > 1 ? 1 : 0); i < width; ++i)
2826 XDrawLine (dpy, drawable, gc,
2827 left_x + i, top_y + (i + 1) * top_p,
2828 left_x + i, bottom_y + 1 - (i + 1) * bot_p);
2831 XSetClipMask (dpy, gc, None);
2832 if (raised_p)
2833 gc = f->output_data.x->black_relief.gc;
2834 else
2835 gc = f->output_data.x->white_relief.gc;
2836 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
2838 if (width > 1)
2840 /* Outermost top line. */
2841 if (top_p)
2842 XDrawLine (dpy, drawable, gc,
2843 left_x + left_p, top_y,
2844 right_x + !right_p, top_y);
2846 /* Outermost left line. */
2847 if (left_p)
2848 XDrawLine (dpy, drawable, gc, left_x, top_y + 1, left_x, bottom_y);
2851 /* Bottom. */
2852 if (bot_p)
2854 XDrawLine (dpy, drawable, gc,
2855 left_x + left_p, bottom_y,
2856 right_x + !right_p, bottom_y);
2857 for (i = 1; i < width; ++i)
2858 XDrawLine (dpy, drawable, gc,
2859 left_x + i * left_p, bottom_y - i,
2860 right_x + 1 - i * right_p, bottom_y - i);
2863 /* Right. */
2864 if (right_p)
2866 x_clear_area(f, right_x, top_y, 1, 1);
2867 x_clear_area(f, right_x, bottom_y, 1, 1);
2868 for (i = 0; i < width; ++i)
2869 XDrawLine (dpy, drawable, gc,
2870 right_x - i, top_y + (i + 1) * top_p,
2871 right_x - i, bottom_y + 1 - (i + 1) * bot_p);
2874 x_reset_clip_rectangles (f, gc);
2876 #endif
2880 /* Draw a box on frame F inside the rectangle given by LEFT_X, TOP_Y,
2881 RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the lines to
2882 draw, it must be >= 0. LEFT_P means draw a line on the
2883 left side of the rectangle. RIGHT_P means draw a line
2884 on the right side of the rectangle. CLIP_RECT is the clipping
2885 rectangle to use when drawing. */
2887 static void
2888 x_draw_box_rect (struct glyph_string *s,
2889 int left_x, int top_y, int right_x, int bottom_y, int width,
2890 bool left_p, bool right_p, XRectangle *clip_rect)
2892 XGCValues xgcv;
2894 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2895 XSetForeground (s->display, s->gc, s->face->box_color);
2896 x_set_clip_rectangles (s->f, s->gc, clip_rect, 1);
2898 /* Top. */
2899 x_fill_rectangle (s->f, s->gc,
2900 left_x, top_y, right_x - left_x + 1, width);
2902 /* Left. */
2903 if (left_p)
2904 x_fill_rectangle (s->f, s->gc,
2905 left_x, top_y, width, bottom_y - top_y + 1);
2907 /* Bottom. */
2908 x_fill_rectangle (s->f, s->gc,
2909 left_x, bottom_y - width + 1, right_x - left_x + 1, width);
2911 /* Right. */
2912 if (right_p)
2913 x_fill_rectangle (s->f, s->gc,
2914 right_x - width + 1, top_y, width, bottom_y - top_y + 1);
2916 XSetForeground (s->display, s->gc, xgcv.foreground);
2917 x_reset_clip_rectangles (s->f, s->gc);
2921 /* Draw a box around glyph string S. */
2923 static void
2924 x_draw_glyph_string_box (struct glyph_string *s)
2926 int width, left_x, right_x, top_y, bottom_y, last_x;
2927 bool raised_p, left_p, right_p;
2928 struct glyph *last_glyph;
2929 XRectangle clip_rect;
2931 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2932 ? WINDOW_RIGHT_EDGE_X (s->w)
2933 : window_box_right (s->w, s->area));
2935 /* The glyph that may have a right box line. */
2936 last_glyph = (s->cmp || s->img
2937 ? s->first_glyph
2938 : s->first_glyph + s->nchars - 1);
2940 width = eabs (s->face->box_line_width);
2941 raised_p = s->face->box == FACE_RAISED_BOX;
2942 left_x = s->x;
2943 right_x = (s->row->full_width_p && s->extends_to_end_of_line_p
2944 ? last_x - 1
2945 : min (last_x, s->x + s->background_width) - 1);
2946 top_y = s->y;
2947 bottom_y = top_y + s->height - 1;
2949 left_p = (s->first_glyph->left_box_line_p
2950 || (s->hl == DRAW_MOUSE_FACE
2951 && (s->prev == NULL
2952 || s->prev->hl != s->hl)));
2953 right_p = (last_glyph->right_box_line_p
2954 || (s->hl == DRAW_MOUSE_FACE
2955 && (s->next == NULL
2956 || s->next->hl != s->hl)));
2958 get_glyph_string_clip_rect (s, &clip_rect);
2960 if (s->face->box == FACE_SIMPLE_BOX)
2961 x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
2962 left_p, right_p, &clip_rect);
2963 else
2965 x_setup_relief_colors (s);
2966 x_draw_relief_rect (s->f, left_x, top_y, right_x, bottom_y,
2967 width, raised_p, true, true, left_p, right_p,
2968 &clip_rect);
2973 /* Draw foreground of image glyph string S. */
2975 static void
2976 x_draw_image_foreground (struct glyph_string *s)
2978 int x = s->x;
2979 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2981 /* If first glyph of S has a left box line, start drawing it to the
2982 right of that line. */
2983 if (s->face->box != FACE_NO_BOX
2984 && s->first_glyph->left_box_line_p
2985 && s->slice.x == 0)
2986 x += eabs (s->face->box_line_width);
2988 /* If there is a margin around the image, adjust x- and y-position
2989 by that margin. */
2990 if (s->slice.x == 0)
2991 x += s->img->hmargin;
2992 if (s->slice.y == 0)
2993 y += s->img->vmargin;
2995 if (s->img->pixmap)
2997 if (s->img->mask)
2999 /* We can't set both a clip mask and use XSetClipRectangles
3000 because the latter also sets a clip mask. We also can't
3001 trust on the shape extension to be available
3002 (XShapeCombineRegion). So, compute the rectangle to draw
3003 manually. */
3004 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
3005 | GCFunction);
3006 XGCValues xgcv;
3007 XRectangle clip_rect, image_rect, r;
3009 xgcv.clip_mask = s->img->mask;
3010 xgcv.clip_x_origin = x;
3011 xgcv.clip_y_origin = y;
3012 xgcv.function = GXcopy;
3013 XChangeGC (s->display, s->gc, mask, &xgcv);
3015 get_glyph_string_clip_rect (s, &clip_rect);
3016 image_rect.x = x;
3017 image_rect.y = y;
3018 image_rect.width = s->slice.width;
3019 image_rect.height = s->slice.height;
3020 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
3021 XCopyArea (s->display, s->img->pixmap,
3022 FRAME_X_DRAWABLE (s->f), s->gc,
3023 s->slice.x + r.x - x, s->slice.y + r.y - y,
3024 r.width, r.height, r.x, r.y);
3026 else
3028 XRectangle clip_rect, image_rect, r;
3030 get_glyph_string_clip_rect (s, &clip_rect);
3031 image_rect.x = x;
3032 image_rect.y = y;
3033 image_rect.width = s->slice.width;
3034 image_rect.height = s->slice.height;
3035 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
3036 XCopyArea (s->display, s->img->pixmap,
3037 FRAME_X_DRAWABLE (s->f), s->gc,
3038 s->slice.x + r.x - x, s->slice.y + r.y - y,
3039 r.width, r.height, r.x, r.y);
3041 /* When the image has a mask, we can expect that at
3042 least part of a mouse highlight or a block cursor will
3043 be visible. If the image doesn't have a mask, make
3044 a block cursor visible by drawing a rectangle around
3045 the image. I believe it's looking better if we do
3046 nothing here for mouse-face. */
3047 if (s->hl == DRAW_CURSOR)
3049 int relief = eabs (s->img->relief);
3050 x_draw_rectangle (s->f, s->gc,
3051 x - relief, y - relief,
3052 s->slice.width + relief*2 - 1,
3053 s->slice.height + relief*2 - 1);
3057 else
3058 /* Draw a rectangle if image could not be loaded. */
3059 x_draw_rectangle (s->f, s->gc, x, y,
3060 s->slice.width - 1, s->slice.height - 1);
3064 /* Draw a relief around the image glyph string S. */
3066 static void
3067 x_draw_image_relief (struct glyph_string *s)
3069 int x1, y1, thick;
3070 bool raised_p, top_p, bot_p, left_p, right_p;
3071 int extra_x, extra_y;
3072 XRectangle r;
3073 int x = s->x;
3074 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
3076 /* If first glyph of S has a left box line, start drawing it to the
3077 right of that line. */
3078 if (s->face->box != FACE_NO_BOX
3079 && s->first_glyph->left_box_line_p
3080 && s->slice.x == 0)
3081 x += eabs (s->face->box_line_width);
3083 /* If there is a margin around the image, adjust x- and y-position
3084 by that margin. */
3085 if (s->slice.x == 0)
3086 x += s->img->hmargin;
3087 if (s->slice.y == 0)
3088 y += s->img->vmargin;
3090 if (s->hl == DRAW_IMAGE_SUNKEN
3091 || s->hl == DRAW_IMAGE_RAISED)
3093 thick = tool_bar_button_relief >= 0 ? tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3094 raised_p = s->hl == DRAW_IMAGE_RAISED;
3096 else
3098 thick = eabs (s->img->relief);
3099 raised_p = s->img->relief > 0;
3102 x1 = x + s->slice.width - 1;
3103 y1 = y + s->slice.height - 1;
3105 extra_x = extra_y = 0;
3106 if (s->face->id == TOOL_BAR_FACE_ID)
3108 if (CONSP (Vtool_bar_button_margin)
3109 && INTEGERP (XCAR (Vtool_bar_button_margin))
3110 && INTEGERP (XCDR (Vtool_bar_button_margin)))
3112 extra_x = XINT (XCAR (Vtool_bar_button_margin));
3113 extra_y = XINT (XCDR (Vtool_bar_button_margin));
3115 else if (INTEGERP (Vtool_bar_button_margin))
3116 extra_x = extra_y = XINT (Vtool_bar_button_margin);
3119 top_p = bot_p = left_p = right_p = false;
3121 if (s->slice.x == 0)
3122 x -= thick + extra_x, left_p = true;
3123 if (s->slice.y == 0)
3124 y -= thick + extra_y, top_p = true;
3125 if (s->slice.x + s->slice.width == s->img->width)
3126 x1 += thick + extra_x, right_p = true;
3127 if (s->slice.y + s->slice.height == s->img->height)
3128 y1 += thick + extra_y, bot_p = true;
3130 x_setup_relief_colors (s);
3131 get_glyph_string_clip_rect (s, &r);
3132 x_draw_relief_rect (s->f, x, y, x1, y1, thick, raised_p,
3133 top_p, bot_p, left_p, right_p, &r);
3137 /* Draw the foreground of image glyph string S to PIXMAP. */
3139 static void
3140 x_draw_image_foreground_1 (struct glyph_string *s, Pixmap pixmap)
3142 int x = 0;
3143 int y = s->ybase - s->y - image_ascent (s->img, s->face, &s->slice);
3145 /* If first glyph of S has a left box line, start drawing it to the
3146 right of that line. */
3147 if (s->face->box != FACE_NO_BOX
3148 && s->first_glyph->left_box_line_p
3149 && s->slice.x == 0)
3150 x += eabs (s->face->box_line_width);
3152 /* If there is a margin around the image, adjust x- and y-position
3153 by that margin. */
3154 if (s->slice.x == 0)
3155 x += s->img->hmargin;
3156 if (s->slice.y == 0)
3157 y += s->img->vmargin;
3159 if (s->img->pixmap)
3161 if (s->img->mask)
3163 /* We can't set both a clip mask and use XSetClipRectangles
3164 because the latter also sets a clip mask. We also can't
3165 trust on the shape extension to be available
3166 (XShapeCombineRegion). So, compute the rectangle to draw
3167 manually. */
3168 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
3169 | GCFunction);
3170 XGCValues xgcv;
3172 xgcv.clip_mask = s->img->mask;
3173 xgcv.clip_x_origin = x - s->slice.x;
3174 xgcv.clip_y_origin = y - s->slice.y;
3175 xgcv.function = GXcopy;
3176 XChangeGC (s->display, s->gc, mask, &xgcv);
3178 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
3179 s->slice.x, s->slice.y,
3180 s->slice.width, s->slice.height, x, y);
3181 XSetClipMask (s->display, s->gc, None);
3183 else
3185 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
3186 s->slice.x, s->slice.y,
3187 s->slice.width, s->slice.height, x, y);
3189 /* When the image has a mask, we can expect that at
3190 least part of a mouse highlight or a block cursor will
3191 be visible. If the image doesn't have a mask, make
3192 a block cursor visible by drawing a rectangle around
3193 the image. I believe it's looking better if we do
3194 nothing here for mouse-face. */
3195 if (s->hl == DRAW_CURSOR)
3197 int r = eabs (s->img->relief);
3198 x_draw_rectangle (s->f, s->gc, x - r, y - r,
3199 s->slice.width + r*2 - 1,
3200 s->slice.height + r*2 - 1);
3204 else
3205 /* Draw a rectangle if image could not be loaded. */
3206 x_draw_rectangle (s->f, s->gc, x, y,
3207 s->slice.width - 1, s->slice.height - 1);
3211 /* Draw part of the background of glyph string S. X, Y, W, and H
3212 give the rectangle to draw. */
3214 static void
3215 x_draw_glyph_string_bg_rect (struct glyph_string *s, int x, int y, int w, int h)
3217 if (s->stippled_p)
3219 /* Fill background with a stipple pattern. */
3220 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
3221 x_fill_rectangle (s->f, s->gc, x, y, w, h);
3222 XSetFillStyle (s->display, s->gc, FillSolid);
3224 else
3225 x_clear_glyph_string_rect (s, x, y, w, h);
3229 /* Draw image glyph string S.
3231 s->y
3232 s->x +-------------------------
3233 | s->face->box
3235 | +-------------------------
3236 | | s->img->margin
3238 | | +-------------------
3239 | | | the image
3243 static void
3244 x_draw_image_glyph_string (struct glyph_string *s)
3246 int box_line_hwidth = eabs (s->face->box_line_width);
3247 int box_line_vwidth = max (s->face->box_line_width, 0);
3248 int height;
3249 Pixmap pixmap = None;
3251 height = s->height;
3252 if (s->slice.y == 0)
3253 height -= box_line_vwidth;
3254 if (s->slice.y + s->slice.height >= s->img->height)
3255 height -= box_line_vwidth;
3257 /* Fill background with face under the image. Do it only if row is
3258 taller than image or if image has a clip mask to reduce
3259 flickering. */
3260 s->stippled_p = s->face->stipple != 0;
3261 if (height > s->slice.height
3262 || s->img->hmargin
3263 || s->img->vmargin
3264 || s->img->mask
3265 || s->img->pixmap == 0
3266 || s->width != s->background_width)
3268 if (s->img->mask)
3270 /* Create a pixmap as large as the glyph string. Fill it
3271 with the background color. Copy the image to it, using
3272 its mask. Copy the temporary pixmap to the display. */
3273 Screen *screen = FRAME_X_SCREEN (s->f);
3274 int depth = DefaultDepthOfScreen (screen);
3276 /* Create a pixmap as large as the glyph string. */
3277 pixmap = XCreatePixmap (s->display, FRAME_X_DRAWABLE (s->f),
3278 s->background_width,
3279 s->height, depth);
3281 /* Don't clip in the following because we're working on the
3282 pixmap. */
3283 XSetClipMask (s->display, s->gc, None);
3285 /* Fill the pixmap with the background color/stipple. */
3286 if (s->stippled_p)
3288 /* Fill background with a stipple pattern. */
3289 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
3290 XSetTSOrigin (s->display, s->gc, - s->x, - s->y);
3291 XFillRectangle (s->display, pixmap, s->gc,
3292 0, 0, s->background_width, s->height);
3293 XSetFillStyle (s->display, s->gc, FillSolid);
3294 XSetTSOrigin (s->display, s->gc, 0, 0);
3296 else
3298 XGCValues xgcv;
3299 XGetGCValues (s->display, s->gc, GCForeground | GCBackground,
3300 &xgcv);
3301 XSetForeground (s->display, s->gc, xgcv.background);
3302 XFillRectangle (s->display, pixmap, s->gc,
3303 0, 0, s->background_width, s->height);
3304 XSetForeground (s->display, s->gc, xgcv.foreground);
3307 else
3309 int x = s->x;
3310 int y = s->y;
3311 int width = s->background_width;
3313 if (s->first_glyph->left_box_line_p
3314 && s->slice.x == 0)
3316 x += box_line_hwidth;
3317 width -= box_line_hwidth;
3320 if (s->slice.y == 0)
3321 y += box_line_vwidth;
3323 x_draw_glyph_string_bg_rect (s, x, y, width, height);
3326 s->background_filled_p = true;
3329 /* Draw the foreground. */
3330 #ifdef USE_CAIRO
3331 if (s->img->cr_data)
3333 cairo_t *cr = x_begin_cr_clip (s->f, s->gc);
3335 int x = s->x + s->img->hmargin;
3336 int y = s->y + s->img->vmargin;
3337 int width = s->background_width;
3339 cairo_set_source_surface (cr, s->img->cr_data,
3340 x - s->slice.x,
3341 y - s->slice.y);
3342 cairo_rectangle (cr, x, y, width, height);
3343 cairo_fill (cr);
3344 x_end_cr_clip (s->f);
3346 else
3347 #endif
3348 if (pixmap != None)
3350 x_draw_image_foreground_1 (s, pixmap);
3351 x_set_glyph_string_clipping (s);
3352 XCopyArea (s->display, pixmap, FRAME_X_DRAWABLE (s->f), s->gc,
3353 0, 0, s->background_width, s->height, s->x, s->y);
3354 XFreePixmap (s->display, pixmap);
3356 else
3357 x_draw_image_foreground (s);
3359 /* If we must draw a relief around the image, do it. */
3360 if (s->img->relief
3361 || s->hl == DRAW_IMAGE_RAISED
3362 || s->hl == DRAW_IMAGE_SUNKEN)
3363 x_draw_image_relief (s);
3367 /* Draw stretch glyph string S. */
3369 static void
3370 x_draw_stretch_glyph_string (struct glyph_string *s)
3372 eassert (s->first_glyph->type == STRETCH_GLYPH);
3374 if (s->hl == DRAW_CURSOR
3375 && !x_stretch_cursor_p)
3377 /* If `x-stretch-cursor' is nil, don't draw a block cursor as
3378 wide as the stretch glyph. */
3379 int width, background_width = s->background_width;
3380 int x = s->x;
3382 if (!s->row->reversed_p)
3384 int left_x = window_box_left_offset (s->w, TEXT_AREA);
3386 if (x < left_x)
3388 background_width -= left_x - x;
3389 x = left_x;
3392 else
3394 /* In R2L rows, draw the cursor on the right edge of the
3395 stretch glyph. */
3396 int right_x = window_box_right (s->w, TEXT_AREA);
3398 if (x + background_width > right_x)
3399 background_width -= x - right_x;
3400 x += background_width;
3402 width = min (FRAME_COLUMN_WIDTH (s->f), background_width);
3403 if (s->row->reversed_p)
3404 x -= width;
3406 /* Draw cursor. */
3407 x_draw_glyph_string_bg_rect (s, x, s->y, width, s->height);
3409 /* Clear rest using the GC of the original non-cursor face. */
3410 if (width < background_width)
3412 int y = s->y;
3413 int w = background_width - width, h = s->height;
3414 XRectangle r;
3415 GC gc;
3417 if (!s->row->reversed_p)
3418 x += width;
3419 else
3420 x = s->x;
3421 if (s->row->mouse_face_p
3422 && cursor_in_mouse_face_p (s->w))
3424 x_set_mouse_face_gc (s);
3425 gc = s->gc;
3427 else
3428 gc = s->face->gc;
3430 get_glyph_string_clip_rect (s, &r);
3431 x_set_clip_rectangles (s->f, gc, &r, 1);
3433 if (s->face->stipple)
3435 /* Fill background with a stipple pattern. */
3436 XSetFillStyle (s->display, gc, FillOpaqueStippled);
3437 x_fill_rectangle (s->f, gc, x, y, w, h);
3438 XSetFillStyle (s->display, gc, FillSolid);
3440 else
3442 XGCValues xgcv;
3443 XGetGCValues (s->display, gc, GCForeground | GCBackground, &xgcv);
3444 XSetForeground (s->display, gc, xgcv.background);
3445 x_fill_rectangle (s->f, gc, x, y, w, h);
3446 XSetForeground (s->display, gc, xgcv.foreground);
3449 x_reset_clip_rectangles (s->f, gc);
3452 else if (!s->background_filled_p)
3454 int background_width = s->background_width;
3455 int x = s->x, left_x = window_box_left_offset (s->w, TEXT_AREA);
3457 /* Don't draw into left margin, fringe or scrollbar area
3458 except for header line and mode line. */
3459 if (x < left_x && !s->row->mode_line_p)
3461 background_width -= left_x - x;
3462 x = left_x;
3464 if (background_width > 0)
3465 x_draw_glyph_string_bg_rect (s, x, s->y, background_width, s->height);
3468 s->background_filled_p = true;
3471 static void
3472 x_get_scale_factor(Display *disp, int *scale_x, int *scale_y)
3474 const int base_res = 96;
3475 struct x_display_info * dpyinfo = x_display_info_for_display (disp);
3477 *scale_x = *scale_y = 1;
3479 if (dpyinfo)
3481 if (dpyinfo->resx > base_res)
3482 *scale_x = floor (dpyinfo->resx / base_res);
3483 if (dpyinfo->resy > base_res)
3484 *scale_y = floor (dpyinfo->resy / base_res);
3489 Draw a wavy line under S. The wave fills wave_height pixels from y0.
3491 x0 wave_length = 2
3493 y0 * * * * *
3494 |* * * * * * * * *
3495 wave_height = 3 | * * * *
3498 static void
3499 x_draw_underwave (struct glyph_string *s)
3501 /* Adjust for scale/HiDPI. */
3502 int scale_x, scale_y;
3504 x_get_scale_factor (s->display, &scale_x, &scale_y);
3506 int wave_height = 3 * scale_y, wave_length = 2 * scale_x;
3508 #ifdef USE_CAIRO
3509 x_draw_horizontal_wave (s->f, s->gc, s->x, s->ybase - wave_height + 3,
3510 s->width, wave_height, wave_length);
3511 #else /* not USE_CAIRO */
3512 int dx, dy, x0, y0, width, x1, y1, x2, y2, xmax, thickness = scale_y;;
3513 bool odd;
3514 XRectangle wave_clip, string_clip, final_clip;
3516 dx = wave_length;
3517 dy = wave_height - 1;
3518 x0 = s->x;
3519 y0 = s->ybase + wave_height / 2 - scale_y;
3520 width = s->width;
3521 xmax = x0 + width;
3523 /* Find and set clipping rectangle */
3525 wave_clip.x = x0;
3526 wave_clip.y = y0;
3527 wave_clip.width = width;
3528 wave_clip.height = wave_height;
3529 get_glyph_string_clip_rect (s, &string_clip);
3531 if (!x_intersect_rectangles (&wave_clip, &string_clip, &final_clip))
3532 return;
3534 XSetClipRectangles (s->display, s->gc, 0, 0, &final_clip, 1, Unsorted);
3536 /* Draw the waves */
3538 x1 = x0 - (x0 % dx);
3539 x2 = x1 + dx;
3540 odd = (x1 / dx) & 1;
3541 y1 = y2 = y0;
3543 if (odd)
3544 y1 += dy;
3545 else
3546 y2 += dy;
3548 if (INT_MAX - dx < xmax)
3549 emacs_abort ();
3551 while (x1 <= xmax)
3553 XSetLineAttributes (s->display, s->gc, thickness, LineSolid, CapButt,
3554 JoinRound);
3555 XDrawLine (s->display, FRAME_X_DRAWABLE (s->f), s->gc, x1, y1, x2, y2);
3556 x1 = x2, y1 = y2;
3557 x2 += dx, y2 = y0 + odd*dy;
3558 odd = !odd;
3561 /* Restore previous clipping rectangle(s) */
3562 XSetClipRectangles (s->display, s->gc, 0, 0, s->clip, s->num_clips, Unsorted);
3563 #endif /* not USE_CAIRO */
3567 /* Draw glyph string S. */
3569 static void
3570 x_draw_glyph_string (struct glyph_string *s)
3572 bool relief_drawn_p = false;
3574 /* If S draws into the background of its successors, draw the
3575 background of the successors first so that S can draw into it.
3576 This makes S->next use XDrawString instead of XDrawImageString. */
3577 if (s->next && s->right_overhang && !s->for_overlaps)
3579 int width;
3580 struct glyph_string *next;
3582 for (width = 0, next = s->next;
3583 next && width < s->right_overhang;
3584 width += next->width, next = next->next)
3585 if (next->first_glyph->type != IMAGE_GLYPH)
3587 x_set_glyph_string_gc (next);
3588 x_set_glyph_string_clipping (next);
3589 if (next->first_glyph->type == STRETCH_GLYPH)
3590 x_draw_stretch_glyph_string (next);
3591 else
3592 x_draw_glyph_string_background (next, true);
3593 next->num_clips = 0;
3597 /* Set up S->gc, set clipping and draw S. */
3598 x_set_glyph_string_gc (s);
3600 /* Draw relief (if any) in advance for char/composition so that the
3601 glyph string can be drawn over it. */
3602 if (!s->for_overlaps
3603 && s->face->box != FACE_NO_BOX
3604 && (s->first_glyph->type == CHAR_GLYPH
3605 || s->first_glyph->type == COMPOSITE_GLYPH))
3608 x_set_glyph_string_clipping (s);
3609 x_draw_glyph_string_background (s, true);
3610 x_draw_glyph_string_box (s);
3611 x_set_glyph_string_clipping (s);
3612 relief_drawn_p = true;
3614 else if (!s->clip_head /* draw_glyphs didn't specify a clip mask. */
3615 && !s->clip_tail
3616 && ((s->prev && s->prev->hl != s->hl && s->left_overhang)
3617 || (s->next && s->next->hl != s->hl && s->right_overhang)))
3618 /* We must clip just this glyph. left_overhang part has already
3619 drawn when s->prev was drawn, and right_overhang part will be
3620 drawn later when s->next is drawn. */
3621 x_set_glyph_string_clipping_exactly (s, s);
3622 else
3623 x_set_glyph_string_clipping (s);
3625 switch (s->first_glyph->type)
3627 case IMAGE_GLYPH:
3628 x_draw_image_glyph_string (s);
3629 break;
3631 case XWIDGET_GLYPH:
3632 x_draw_xwidget_glyph_string (s);
3633 break;
3635 case STRETCH_GLYPH:
3636 x_draw_stretch_glyph_string (s);
3637 break;
3639 case CHAR_GLYPH:
3640 if (s->for_overlaps)
3641 s->background_filled_p = true;
3642 else
3643 x_draw_glyph_string_background (s, false);
3644 x_draw_glyph_string_foreground (s);
3645 break;
3647 case COMPOSITE_GLYPH:
3648 if (s->for_overlaps || (s->cmp_from > 0
3649 && ! s->first_glyph->u.cmp.automatic))
3650 s->background_filled_p = true;
3651 else
3652 x_draw_glyph_string_background (s, true);
3653 x_draw_composite_glyph_string_foreground (s);
3654 break;
3656 case GLYPHLESS_GLYPH:
3657 if (s->for_overlaps)
3658 s->background_filled_p = true;
3659 else
3660 x_draw_glyph_string_background (s, true);
3661 x_draw_glyphless_glyph_string_foreground (s);
3662 break;
3664 default:
3665 emacs_abort ();
3668 if (!s->for_overlaps)
3670 /* Draw underline. */
3671 if (s->face->underline_p)
3673 if (s->face->underline_type == FACE_UNDER_WAVE)
3675 if (s->face->underline_defaulted_p)
3676 x_draw_underwave (s);
3677 else
3679 XGCValues xgcv;
3680 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3681 XSetForeground (s->display, s->gc, s->face->underline_color);
3682 x_draw_underwave (s);
3683 XSetForeground (s->display, s->gc, xgcv.foreground);
3686 else if (s->face->underline_type == FACE_UNDER_LINE)
3688 unsigned long thickness, position;
3689 int y;
3691 if (s->prev && s->prev->face->underline_p
3692 && s->prev->face->underline_type == FACE_UNDER_LINE)
3694 /* We use the same underline style as the previous one. */
3695 thickness = s->prev->underline_thickness;
3696 position = s->prev->underline_position;
3698 else
3700 struct font *font = font_for_underline_metrics (s);
3701 unsigned long minimum_offset;
3702 bool underline_at_descent_line;
3703 bool use_underline_position_properties;
3704 Lisp_Object val
3705 = buffer_local_value (Qunderline_minimum_offset,
3706 s->w->contents);
3707 if (INTEGERP (val))
3708 minimum_offset = XFASTINT (val);
3709 else
3710 minimum_offset = 1;
3711 val = buffer_local_value (Qx_underline_at_descent_line,
3712 s->w->contents);
3713 underline_at_descent_line
3714 = !(NILP (val) || EQ (val, Qunbound));
3716 = buffer_local_value (Qx_use_underline_position_properties,
3717 s->w->contents);
3718 use_underline_position_properties
3719 = !(NILP (val) || EQ (val, Qunbound));
3721 /* Get the underline thickness. Default is 1 pixel. */
3722 if (font && font->underline_thickness > 0)
3723 thickness = font->underline_thickness;
3724 else
3725 thickness = 1;
3726 if (underline_at_descent_line)
3727 position = (s->height - thickness) - (s->ybase - s->y);
3728 else
3730 /* Get the underline position. This is the
3731 recommended vertical offset in pixels from
3732 the baseline to the top of the underline.
3733 This is a signed value according to the
3734 specs, and its default is
3736 ROUND ((maximum descent) / 2), with
3737 ROUND(x) = floor (x + 0.5) */
3739 if (use_underline_position_properties
3740 && font && font->underline_position >= 0)
3741 position = font->underline_position;
3742 else if (font)
3743 position = (font->descent + 1) / 2;
3744 else
3745 position = minimum_offset;
3747 position = max (position, minimum_offset);
3749 /* Check the sanity of thickness and position. We should
3750 avoid drawing underline out of the current line area. */
3751 if (s->y + s->height <= s->ybase + position)
3752 position = (s->height - 1) - (s->ybase - s->y);
3753 if (s->y + s->height < s->ybase + position + thickness)
3754 thickness = (s->y + s->height) - (s->ybase + position);
3755 s->underline_thickness = thickness;
3756 s->underline_position = position;
3757 y = s->ybase + position;
3758 if (s->face->underline_defaulted_p)
3759 x_fill_rectangle (s->f, s->gc,
3760 s->x, y, s->width, thickness);
3761 else
3763 XGCValues xgcv;
3764 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3765 XSetForeground (s->display, s->gc, s->face->underline_color);
3766 x_fill_rectangle (s->f, s->gc,
3767 s->x, y, s->width, thickness);
3768 XSetForeground (s->display, s->gc, xgcv.foreground);
3772 /* Draw overline. */
3773 if (s->face->overline_p)
3775 unsigned long dy = 0, h = 1;
3777 if (s->face->overline_color_defaulted_p)
3778 x_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3779 s->width, h);
3780 else
3782 XGCValues xgcv;
3783 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3784 XSetForeground (s->display, s->gc, s->face->overline_color);
3785 x_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3786 s->width, h);
3787 XSetForeground (s->display, s->gc, xgcv.foreground);
3791 /* Draw strike-through. */
3792 if (s->face->strike_through_p)
3794 /* Y-coordinate and height of the glyph string's first
3795 glyph. We cannot use s->y and s->height because those
3796 could be larger if there are taller display elements
3797 (e.g., characters displayed with a larger font) in the
3798 same glyph row. */
3799 int glyph_y = s->ybase - s->first_glyph->ascent;
3800 int glyph_height = s->first_glyph->ascent + s->first_glyph->descent;
3801 /* Strike-through width and offset from the glyph string's
3802 top edge. */
3803 unsigned long h = 1;
3804 unsigned long dy = (glyph_height - h) / 2;
3806 if (s->face->strike_through_color_defaulted_p)
3807 x_fill_rectangle (s->f, s->gc, s->x, glyph_y + dy,
3808 s->width, h);
3809 else
3811 XGCValues xgcv;
3812 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3813 XSetForeground (s->display, s->gc, s->face->strike_through_color);
3814 x_fill_rectangle (s->f, s->gc, s->x, glyph_y + dy,
3815 s->width, h);
3816 XSetForeground (s->display, s->gc, xgcv.foreground);
3820 /* Draw relief if not yet drawn. */
3821 if (!relief_drawn_p && s->face->box != FACE_NO_BOX)
3822 x_draw_glyph_string_box (s);
3824 if (s->prev)
3826 struct glyph_string *prev;
3828 for (prev = s->prev; prev; prev = prev->prev)
3829 if (prev->hl != s->hl
3830 && prev->x + prev->width + prev->right_overhang > s->x)
3832 /* As prev was drawn while clipped to its own area, we
3833 must draw the right_overhang part using s->hl now. */
3834 enum draw_glyphs_face save = prev->hl;
3836 prev->hl = s->hl;
3837 x_set_glyph_string_gc (prev);
3838 x_set_glyph_string_clipping_exactly (s, prev);
3839 if (prev->first_glyph->type == CHAR_GLYPH)
3840 x_draw_glyph_string_foreground (prev);
3841 else
3842 x_draw_composite_glyph_string_foreground (prev);
3843 x_reset_clip_rectangles (prev->f, prev->gc);
3844 prev->hl = save;
3845 prev->num_clips = 0;
3849 if (s->next)
3851 struct glyph_string *next;
3853 for (next = s->next; next; next = next->next)
3854 if (next->hl != s->hl
3855 && next->x - next->left_overhang < s->x + s->width)
3857 /* As next will be drawn while clipped to its own area,
3858 we must draw the left_overhang part using s->hl now. */
3859 enum draw_glyphs_face save = next->hl;
3861 next->hl = s->hl;
3862 x_set_glyph_string_gc (next);
3863 x_set_glyph_string_clipping_exactly (s, next);
3864 if (next->first_glyph->type == CHAR_GLYPH)
3865 x_draw_glyph_string_foreground (next);
3866 else
3867 x_draw_composite_glyph_string_foreground (next);
3868 x_reset_clip_rectangles (next->f, next->gc);
3869 next->hl = save;
3870 next->num_clips = 0;
3871 next->clip_head = s->next;
3876 /* Reset clipping. */
3877 x_reset_clip_rectangles (s->f, s->gc);
3878 s->num_clips = 0;
3881 /* Shift display to make room for inserted glyphs. */
3883 static void
3884 x_shift_glyphs_for_insert (struct frame *f, int x, int y, int width, int height, int shift_by)
3886 /* Never called on a GUI frame, see
3887 https://lists.gnu.org/r/emacs-devel/2015-05/msg00456.html
3889 XCopyArea (FRAME_X_DISPLAY (f), FRAME_X_DRAWABLE (f), FRAME_X_DRAWABLE (f),
3890 f->output_data.x->normal_gc,
3891 x, y, width, height,
3892 x + shift_by, y);
3895 /* Delete N glyphs at the nominal cursor position. Not implemented
3896 for X frames. */
3898 static void
3899 x_delete_glyphs (struct frame *f, register int n)
3901 emacs_abort ();
3905 /* Like XClearArea, but check that WIDTH and HEIGHT are reasonable.
3906 If they are <= 0, this is probably an error. */
3908 static ATTRIBUTE_UNUSED void
3909 x_clear_area1 (Display *dpy, Window window,
3910 int x, int y, int width, int height, int exposures)
3912 eassert (width > 0 && height > 0);
3913 XClearArea (dpy, window, x, y, width, height, exposures);
3916 void
3917 x_clear_area (struct frame *f, int x, int y, int width, int height)
3919 #ifdef USE_CAIRO
3920 cairo_t *cr;
3922 eassert (width > 0 && height > 0);
3924 cr = x_begin_cr_clip (f, NULL);
3925 x_set_cr_source_with_gc_background (f, f->output_data.x->normal_gc);
3926 cairo_rectangle (cr, x, y, width, height);
3927 cairo_fill (cr);
3928 x_end_cr_clip (f);
3929 #else
3930 if (FRAME_X_DOUBLE_BUFFERED_P (f))
3931 XFillRectangle (FRAME_X_DISPLAY (f),
3932 FRAME_X_DRAWABLE (f),
3933 f->output_data.x->reverse_gc,
3934 x, y, width, height);
3935 else
3936 x_clear_area1 (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3937 x, y, width, height, False);
3938 #endif
3942 /* Clear an entire frame. */
3944 static void
3945 x_clear_frame (struct frame *f)
3947 /* Clearing the frame will erase any cursor, so mark them all as no
3948 longer visible. */
3949 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
3951 block_input ();
3953 font_drop_xrender_surfaces (f);
3954 x_clear_window (f);
3956 /* We have to clear the scroll bars. If we have changed colors or
3957 something like that, then they should be notified. */
3958 x_scroll_bar_clear (f);
3960 XFlush (FRAME_X_DISPLAY (f));
3962 unblock_input ();
3965 /* RIF: Show hourglass cursor on frame F. */
3967 static void
3968 x_show_hourglass (struct frame *f)
3970 Display *dpy = FRAME_X_DISPLAY (f);
3972 if (dpy)
3974 struct x_output *x = FRAME_X_OUTPUT (f);
3975 #ifdef USE_X_TOOLKIT
3976 if (x->widget)
3977 #else
3978 if (FRAME_OUTER_WINDOW (f))
3979 #endif
3981 x->hourglass_p = true;
3983 if (!x->hourglass_window)
3985 unsigned long mask = CWCursor;
3986 XSetWindowAttributes attrs;
3987 #ifdef USE_GTK
3988 Window parent = FRAME_X_WINDOW (f);
3989 #else
3990 Window parent = FRAME_OUTER_WINDOW (f);
3991 #endif
3992 attrs.cursor = x->hourglass_cursor;
3994 x->hourglass_window = XCreateWindow
3995 (dpy, parent, 0, 0, 32000, 32000, 0, 0,
3996 InputOnly, CopyFromParent, mask, &attrs);
3999 XMapRaised (dpy, x->hourglass_window);
4000 XFlush (dpy);
4005 /* RIF: Cancel hourglass cursor on frame F. */
4007 static void
4008 x_hide_hourglass (struct frame *f)
4010 struct x_output *x = FRAME_X_OUTPUT (f);
4012 /* Watch out for newly created frames. */
4013 if (x->hourglass_window)
4015 XUnmapWindow (FRAME_X_DISPLAY (f), x->hourglass_window);
4016 /* Sync here because XTread_socket looks at the
4017 hourglass_p flag that is reset to zero below. */
4018 XSync (FRAME_X_DISPLAY (f), False);
4019 x->hourglass_p = false;
4023 /* Invert the middle quarter of the frame for .15 sec. */
4025 static void
4026 XTflash (struct frame *f)
4028 block_input ();
4031 #ifdef USE_GTK
4032 /* Use Gdk routines to draw. This way, we won't draw over scroll bars
4033 when the scroll bars and the edit widget share the same X window. */
4034 GdkWindow *window = gtk_widget_get_window (FRAME_GTK_WIDGET (f));
4035 #ifdef HAVE_GTK3
4036 #if GTK_CHECK_VERSION (3, 22, 0)
4037 cairo_region_t *region = gdk_window_get_visible_region (window);
4038 GdkDrawingContext *context = gdk_window_begin_draw_frame (window, region);
4039 cairo_t *cr = gdk_drawing_context_get_cairo_context (context);
4040 #else
4041 cairo_t *cr = gdk_cairo_create (window);
4042 #endif
4043 cairo_set_source_rgb (cr, 1, 1, 1);
4044 cairo_set_operator (cr, CAIRO_OPERATOR_DIFFERENCE);
4045 #define XFillRectangle(d, win, gc, x, y, w, h) \
4046 do { \
4047 cairo_rectangle (cr, x, y, w, h); \
4048 cairo_fill (cr); \
4050 while (false)
4051 #else /* ! HAVE_GTK3 */
4052 GdkGCValues vals;
4053 GdkGC *gc;
4054 vals.foreground.pixel = (FRAME_FOREGROUND_PIXEL (f)
4055 ^ FRAME_BACKGROUND_PIXEL (f));
4056 vals.function = GDK_XOR;
4057 gc = gdk_gc_new_with_values (window,
4058 &vals, GDK_GC_FUNCTION | GDK_GC_FOREGROUND);
4059 #define XFillRectangle(d, win, gc, x, y, w, h) \
4060 gdk_draw_rectangle (window, gc, true, x, y, w, h)
4061 #endif /* ! HAVE_GTK3 */
4062 #else /* ! USE_GTK */
4063 GC gc;
4065 /* Create a GC that will use the GXxor function to flip foreground
4066 pixels into background pixels. */
4068 XGCValues values;
4070 values.function = GXxor;
4071 values.foreground = (FRAME_FOREGROUND_PIXEL (f)
4072 ^ FRAME_BACKGROUND_PIXEL (f));
4074 gc = XCreateGC (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4075 GCFunction | GCForeground, &values);
4077 #endif
4079 /* Get the height not including a menu bar widget. */
4080 int height = FRAME_PIXEL_HEIGHT (f);
4081 /* Height of each line to flash. */
4082 int flash_height = FRAME_LINE_HEIGHT (f);
4083 /* These will be the left and right margins of the rectangles. */
4084 int flash_left = FRAME_INTERNAL_BORDER_WIDTH (f);
4085 int flash_right = FRAME_PIXEL_WIDTH (f) - FRAME_INTERNAL_BORDER_WIDTH (f);
4086 int width = flash_right - flash_left;
4088 /* If window is tall, flash top and bottom line. */
4089 if (height > 3 * FRAME_LINE_HEIGHT (f))
4091 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4092 flash_left,
4093 (FRAME_INTERNAL_BORDER_WIDTH (f)
4094 + FRAME_TOP_MARGIN_HEIGHT (f)),
4095 width, flash_height);
4096 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4097 flash_left,
4098 (height - flash_height
4099 - FRAME_INTERNAL_BORDER_WIDTH (f)),
4100 width, flash_height);
4103 else
4104 /* If it is short, flash it all. */
4105 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4106 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
4107 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
4109 x_flush (f);
4112 struct timespec delay = make_timespec (0, 150 * 1000 * 1000);
4113 struct timespec wakeup = timespec_add (current_timespec (), delay);
4115 /* Keep waiting until past the time wakeup or any input gets
4116 available. */
4117 while (! detect_input_pending ())
4119 struct timespec current = current_timespec ();
4120 struct timespec timeout;
4122 /* Break if result would not be positive. */
4123 if (timespec_cmp (wakeup, current) <= 0)
4124 break;
4126 /* How long `select' should wait. */
4127 timeout = make_timespec (0, 10 * 1000 * 1000);
4129 /* Try to wait that long--but we might wake up sooner. */
4130 pselect (0, NULL, NULL, NULL, &timeout, NULL);
4134 /* If window is tall, flash top and bottom line. */
4135 if (height > 3 * FRAME_LINE_HEIGHT (f))
4137 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4138 flash_left,
4139 (FRAME_INTERNAL_BORDER_WIDTH (f)
4140 + FRAME_TOP_MARGIN_HEIGHT (f)),
4141 width, flash_height);
4142 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4143 flash_left,
4144 (height - flash_height
4145 - FRAME_INTERNAL_BORDER_WIDTH (f)),
4146 width, flash_height);
4148 else
4149 /* If it is short, flash it all. */
4150 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4151 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
4152 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
4154 #ifdef USE_GTK
4155 #ifdef HAVE_GTK3
4156 #if GTK_CHECK_VERSION (3, 22, 0)
4157 gdk_window_end_draw_frame (window, context);
4158 cairo_region_destroy (region);
4159 #else
4160 cairo_destroy (cr);
4161 #endif
4162 #else
4163 g_object_unref (G_OBJECT (gc));
4164 #endif
4165 #undef XFillRectangle
4166 #else
4167 XFreeGC (FRAME_X_DISPLAY (f), gc);
4168 #endif
4169 x_flush (f);
4173 unblock_input ();
4177 static void
4178 XTtoggle_invisible_pointer (struct frame *f, bool invisible)
4180 block_input ();
4181 FRAME_DISPLAY_INFO (f)->toggle_visible_pointer (f, invisible);
4182 unblock_input ();
4186 /* Make audible bell. */
4188 static void
4189 XTring_bell (struct frame *f)
4191 if (FRAME_X_DISPLAY (f))
4193 if (visible_bell)
4194 XTflash (f);
4195 else
4197 block_input ();
4198 #ifdef HAVE_XKB
4199 XkbBell (FRAME_X_DISPLAY (f), None, 0, None);
4200 #else
4201 XBell (FRAME_X_DISPLAY (f), 0);
4202 #endif
4203 XFlush (FRAME_X_DISPLAY (f));
4204 unblock_input ();
4209 /***********************************************************************
4210 Line Dance
4211 ***********************************************************************/
4213 /* Perform an insert-lines or delete-lines operation, inserting N
4214 lines or deleting -N lines at vertical position VPOS. */
4216 static void
4217 x_ins_del_lines (struct frame *f, int vpos, int n)
4219 emacs_abort ();
4223 /* Scroll part of the display as described by RUN. */
4225 static void
4226 x_scroll_run (struct window *w, struct run *run)
4228 struct frame *f = XFRAME (w->frame);
4229 int x, y, width, height, from_y, to_y, bottom_y;
4231 /* Get frame-relative bounding box of the text display area of W,
4232 without mode lines. Include in this box the left and right
4233 fringe of W. */
4234 window_box (w, ANY_AREA, &x, &y, &width, &height);
4236 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
4237 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
4238 bottom_y = y + height;
4240 if (to_y < from_y)
4242 /* Scrolling up. Make sure we don't copy part of the mode
4243 line at the bottom. */
4244 if (from_y + run->height > bottom_y)
4245 height = bottom_y - from_y;
4246 else
4247 height = run->height;
4249 else
4251 /* Scrolling down. Make sure we don't copy over the mode line.
4252 at the bottom. */
4253 if (to_y + run->height > bottom_y)
4254 height = bottom_y - to_y;
4255 else
4256 height = run->height;
4259 block_input ();
4261 /* Cursor off. Will be switched on again in x_update_window_end. */
4262 x_clear_cursor (w);
4264 #ifdef USE_CAIRO
4265 if (FRAME_CR_CONTEXT (f))
4267 int wx = WINDOW_LEFT_EDGE_X (w);
4268 cairo_surface_t *s = cairo_image_surface_create (CAIRO_FORMAT_ARGB32,
4269 width, height);
4270 cairo_t *cr = cairo_create (s);
4271 cairo_set_source_surface (cr, cairo_get_target (FRAME_CR_CONTEXT (f)),
4272 -x, -from_y);
4273 cairo_paint (cr);
4274 cairo_destroy (cr);
4276 cr = FRAME_CR_CONTEXT (f);
4277 cairo_save (cr);
4278 cairo_set_source_surface (cr, s, wx, to_y);
4279 cairo_rectangle (cr, wx, to_y, width, height);
4280 cairo_fill (cr);
4281 cairo_restore (cr);
4282 cairo_surface_destroy (s);
4284 else
4286 SET_FRAME_GARBAGED (f);
4288 #else
4289 XCopyArea (FRAME_X_DISPLAY (f),
4290 FRAME_X_DRAWABLE (f), FRAME_X_DRAWABLE (f),
4291 f->output_data.x->normal_gc,
4292 x, from_y,
4293 width, height,
4294 x, to_y);
4295 #endif
4297 unblock_input ();
4302 /***********************************************************************
4303 Exposure Events
4304 ***********************************************************************/
4307 static void
4308 frame_highlight (struct frame *f)
4310 /* We used to only do this if Vx_no_window_manager was non-nil, but
4311 the ICCCM (section 4.1.6) says that the window's border pixmap
4312 and border pixel are window attributes which are "private to the
4313 client", so we can always change it to whatever we want. */
4314 block_input ();
4315 /* I recently started to get errors in this XSetWindowBorder, depending on
4316 the window-manager in use, tho something more is at play since I've been
4317 using that same window-manager binary for ever. Let's not crash just
4318 because of this (bug#9310). */
4319 x_catch_errors (FRAME_X_DISPLAY (f));
4320 XSetWindowBorder (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4321 f->output_data.x->border_pixel);
4322 x_uncatch_errors ();
4323 unblock_input ();
4324 x_update_cursor (f, true);
4325 x_set_frame_alpha (f);
4328 static void
4329 frame_unhighlight (struct frame *f)
4331 /* We used to only do this if Vx_no_window_manager was non-nil, but
4332 the ICCCM (section 4.1.6) says that the window's border pixmap
4333 and border pixel are window attributes which are "private to the
4334 client", so we can always change it to whatever we want. */
4335 block_input ();
4336 /* Same as above for XSetWindowBorder (bug#9310). */
4337 x_catch_errors (FRAME_X_DISPLAY (f));
4338 XSetWindowBorderPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4339 f->output_data.x->border_tile);
4340 x_uncatch_errors ();
4341 unblock_input ();
4342 x_update_cursor (f, true);
4343 x_set_frame_alpha (f);
4346 /* The focus has changed. Update the frames as necessary to reflect
4347 the new situation. Note that we can't change the selected frame
4348 here, because the Lisp code we are interrupting might become confused.
4349 Each event gets marked with the frame in which it occurred, so the
4350 Lisp code can tell when the switch took place by examining the events. */
4352 static void
4353 x_new_focus_frame (struct x_display_info *dpyinfo, struct frame *frame)
4355 struct frame *old_focus = dpyinfo->x_focus_frame;
4357 if (frame != dpyinfo->x_focus_frame)
4359 /* Set this before calling other routines, so that they see
4360 the correct value of x_focus_frame. */
4361 dpyinfo->x_focus_frame = frame;
4363 if (old_focus && old_focus->auto_lower)
4364 x_lower_frame (old_focus);
4366 if (dpyinfo->x_focus_frame && dpyinfo->x_focus_frame->auto_raise)
4367 dpyinfo->x_pending_autoraise_frame = dpyinfo->x_focus_frame;
4368 else
4369 dpyinfo->x_pending_autoraise_frame = NULL;
4372 x_frame_rehighlight (dpyinfo);
4375 /* Handle FocusIn and FocusOut state changes for FRAME.
4376 If FRAME has focus and there exists more than one frame, puts
4377 a FOCUS_IN_EVENT into *BUFP. */
4379 static void
4380 x_focus_changed (int type, int state, struct x_display_info *dpyinfo, struct frame *frame, struct input_event *bufp)
4382 if (type == FocusIn)
4384 if (dpyinfo->x_focus_event_frame != frame)
4386 x_new_focus_frame (dpyinfo, frame);
4387 dpyinfo->x_focus_event_frame = frame;
4388 bufp->kind = FOCUS_IN_EVENT;
4389 XSETFRAME (bufp->frame_or_window, frame);
4392 frame->output_data.x->focus_state |= state;
4394 #ifdef HAVE_X_I18N
4395 if (FRAME_XIC (frame))
4396 XSetICFocus (FRAME_XIC (frame));
4397 #endif
4399 else if (type == FocusOut)
4401 frame->output_data.x->focus_state &= ~state;
4403 if (dpyinfo->x_focus_event_frame == frame)
4405 dpyinfo->x_focus_event_frame = 0;
4406 x_new_focus_frame (dpyinfo, 0);
4408 bufp->kind = FOCUS_OUT_EVENT;
4409 XSETFRAME (bufp->frame_or_window, frame);
4412 #ifdef HAVE_X_I18N
4413 if (FRAME_XIC (frame))
4414 XUnsetICFocus (FRAME_XIC (frame));
4415 #endif
4416 if (frame->pointer_invisible)
4417 XTtoggle_invisible_pointer (frame, false);
4421 /* Return the Emacs frame-object corresponding to an X window.
4422 It could be the frame's main window or an icon window. */
4424 static struct frame *
4425 x_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
4427 Lisp_Object tail, frame;
4428 struct frame *f;
4430 if (wdesc == None)
4431 return NULL;
4433 FOR_EACH_FRAME (tail, frame)
4435 f = XFRAME (frame);
4436 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
4437 continue;
4438 if (f->output_data.x->hourglass_window == wdesc)
4439 return f;
4440 #ifdef USE_X_TOOLKIT
4441 if ((f->output_data.x->edit_widget
4442 && XtWindow (f->output_data.x->edit_widget) == wdesc)
4443 /* A tooltip frame? */
4444 || (!f->output_data.x->edit_widget
4445 && FRAME_X_WINDOW (f) == wdesc)
4446 || f->output_data.x->icon_desc == wdesc)
4447 return f;
4448 #else /* not USE_X_TOOLKIT */
4449 #ifdef USE_GTK
4450 if (f->output_data.x->edit_widget)
4452 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
4453 struct x_output *x = f->output_data.x;
4454 if (gwdesc != 0 && gwdesc == x->edit_widget)
4455 return f;
4457 #endif /* USE_GTK */
4458 if (FRAME_X_WINDOW (f) == wdesc
4459 || f->output_data.x->icon_desc == wdesc)
4460 return f;
4461 #endif /* not USE_X_TOOLKIT */
4463 return 0;
4466 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
4468 /* Like x_window_to_frame but also compares the window with the widget's
4469 windows. */
4471 static struct frame *
4472 x_any_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
4474 Lisp_Object tail, frame;
4475 struct frame *f, *found = NULL;
4476 struct x_output *x;
4478 if (wdesc == None)
4479 return NULL;
4481 FOR_EACH_FRAME (tail, frame)
4483 if (found)
4484 break;
4485 f = XFRAME (frame);
4486 if (FRAME_X_P (f) && FRAME_DISPLAY_INFO (f) == dpyinfo)
4488 /* This frame matches if the window is any of its widgets. */
4489 x = f->output_data.x;
4490 if (x->hourglass_window == wdesc)
4491 found = f;
4492 else if (x->widget)
4494 #ifdef USE_GTK
4495 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
4496 if (gwdesc != 0
4497 && gtk_widget_get_toplevel (gwdesc) == x->widget)
4498 found = f;
4499 #else
4500 if (wdesc == XtWindow (x->widget)
4501 || wdesc == XtWindow (x->column_widget)
4502 || wdesc == XtWindow (x->edit_widget))
4503 found = f;
4504 /* Match if the window is this frame's menubar. */
4505 else if (lw_window_is_in_menubar (wdesc, x->menubar_widget))
4506 found = f;
4507 #endif
4509 else if (FRAME_X_WINDOW (f) == wdesc)
4510 /* A tooltip frame. */
4511 found = f;
4515 return found;
4518 /* Likewise, but consider only the menu bar widget. */
4520 static struct frame *
4521 x_menubar_window_to_frame (struct x_display_info *dpyinfo,
4522 const XEvent *event)
4524 Window wdesc = event->xany.window;
4525 Lisp_Object tail, frame;
4526 struct frame *f;
4527 struct x_output *x;
4529 if (wdesc == None)
4530 return NULL;
4532 FOR_EACH_FRAME (tail, frame)
4534 f = XFRAME (frame);
4535 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
4536 continue;
4537 x = f->output_data.x;
4538 #ifdef USE_GTK
4539 if (x->menubar_widget && xg_event_is_for_menubar (f, event))
4540 return f;
4541 #else
4542 /* Match if the window is this frame's menubar. */
4543 if (x->menubar_widget
4544 && lw_window_is_in_menubar (wdesc, x->menubar_widget))
4545 return f;
4546 #endif
4548 return 0;
4551 /* Return the frame whose principal (outermost) window is WDESC.
4552 If WDESC is some other (smaller) window, we return 0. */
4554 struct frame *
4555 x_top_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
4557 Lisp_Object tail, frame;
4558 struct frame *f;
4559 struct x_output *x;
4561 if (wdesc == None)
4562 return NULL;
4564 FOR_EACH_FRAME (tail, frame)
4566 f = XFRAME (frame);
4567 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
4568 continue;
4569 x = f->output_data.x;
4571 if (x->widget)
4573 /* This frame matches if the window is its topmost widget. */
4574 #ifdef USE_GTK
4575 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
4576 if (gwdesc == x->widget)
4577 return f;
4578 #else
4579 if (wdesc == XtWindow (x->widget))
4580 return f;
4581 #endif
4583 else if (FRAME_X_WINDOW (f) == wdesc)
4584 /* Tooltip frame. */
4585 return f;
4587 return 0;
4590 #else /* !USE_X_TOOLKIT && !USE_GTK */
4592 #define x_any_window_to_frame(d, i) x_window_to_frame (d, i)
4593 #define x_top_window_to_frame(d, i) x_window_to_frame (d, i)
4595 #endif /* USE_X_TOOLKIT || USE_GTK */
4597 /* The focus may have changed. Figure out if it is a real focus change,
4598 by checking both FocusIn/Out and Enter/LeaveNotify events.
4600 Returns FOCUS_IN_EVENT event in *BUFP. */
4602 static void
4603 x_detect_focus_change (struct x_display_info *dpyinfo, struct frame *frame,
4604 const XEvent *event, struct input_event *bufp)
4606 if (!frame)
4607 return;
4609 switch (event->type)
4611 case EnterNotify:
4612 case LeaveNotify:
4614 struct frame *focus_frame = dpyinfo->x_focus_event_frame;
4615 int focus_state
4616 = focus_frame ? focus_frame->output_data.x->focus_state : 0;
4618 if (event->xcrossing.detail != NotifyInferior
4619 && event->xcrossing.focus
4620 && ! (focus_state & FOCUS_EXPLICIT))
4621 x_focus_changed ((event->type == EnterNotify ? FocusIn : FocusOut),
4622 FOCUS_IMPLICIT,
4623 dpyinfo, frame, bufp);
4625 break;
4627 case FocusIn:
4628 case FocusOut:
4629 x_focus_changed (event->type,
4630 (event->xfocus.detail == NotifyPointer ?
4631 FOCUS_IMPLICIT : FOCUS_EXPLICIT),
4632 dpyinfo, frame, bufp);
4633 break;
4635 case ClientMessage:
4636 if (event->xclient.message_type == dpyinfo->Xatom_XEMBED)
4638 enum xembed_message msg = event->xclient.data.l[1];
4639 x_focus_changed ((msg == XEMBED_FOCUS_IN ? FocusIn : FocusOut),
4640 FOCUS_EXPLICIT, dpyinfo, frame, bufp);
4642 break;
4647 #if !defined USE_X_TOOLKIT && !defined USE_GTK
4648 /* Handle an event saying the mouse has moved out of an Emacs frame. */
4650 void
4651 x_mouse_leave (struct x_display_info *dpyinfo)
4653 x_new_focus_frame (dpyinfo, dpyinfo->x_focus_event_frame);
4655 #endif
4657 /* The focus has changed, or we have redirected a frame's focus to
4658 another frame (this happens when a frame uses a surrogate
4659 mini-buffer frame). Shift the highlight as appropriate.
4661 The FRAME argument doesn't necessarily have anything to do with which
4662 frame is being highlighted or un-highlighted; we only use it to find
4663 the appropriate X display info. */
4665 static void
4666 XTframe_rehighlight (struct frame *frame)
4668 x_frame_rehighlight (FRAME_DISPLAY_INFO (frame));
4671 static void
4672 x_frame_rehighlight (struct x_display_info *dpyinfo)
4674 struct frame *old_highlight = dpyinfo->x_highlight_frame;
4676 if (dpyinfo->x_focus_frame)
4678 dpyinfo->x_highlight_frame
4679 = ((FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame)))
4680 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
4681 : dpyinfo->x_focus_frame);
4682 if (! FRAME_LIVE_P (dpyinfo->x_highlight_frame))
4684 fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
4685 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
4688 else
4689 dpyinfo->x_highlight_frame = 0;
4691 if (dpyinfo->x_highlight_frame != old_highlight)
4693 if (old_highlight)
4694 frame_unhighlight (old_highlight);
4695 if (dpyinfo->x_highlight_frame)
4696 frame_highlight (dpyinfo->x_highlight_frame);
4702 /* Keyboard processing - modifier keys, vendor-specific keysyms, etc. */
4704 /* Initialize mode_switch_bit and modifier_meaning. */
4705 static void
4706 x_find_modifier_meanings (struct x_display_info *dpyinfo)
4708 int min_code, max_code;
4709 KeySym *syms;
4710 int syms_per_code;
4711 XModifierKeymap *mods;
4713 dpyinfo->meta_mod_mask = 0;
4714 dpyinfo->shift_lock_mask = 0;
4715 dpyinfo->alt_mod_mask = 0;
4716 dpyinfo->super_mod_mask = 0;
4717 dpyinfo->hyper_mod_mask = 0;
4719 XDisplayKeycodes (dpyinfo->display, &min_code, &max_code);
4721 syms = XGetKeyboardMapping (dpyinfo->display,
4722 min_code, max_code - min_code + 1,
4723 &syms_per_code);
4724 mods = XGetModifierMapping (dpyinfo->display);
4726 /* Scan the modifier table to see which modifier bits the Meta and
4727 Alt keysyms are on. */
4729 int row, col; /* The row and column in the modifier table. */
4730 bool found_alt_or_meta;
4732 for (row = 3; row < 8; row++)
4734 found_alt_or_meta = false;
4735 for (col = 0; col < mods->max_keypermod; col++)
4737 KeyCode code = mods->modifiermap[(row * mods->max_keypermod) + col];
4739 /* Zeroes are used for filler. Skip them. */
4740 if (code == 0)
4741 continue;
4743 /* Are any of this keycode's keysyms a meta key? */
4745 int code_col;
4747 for (code_col = 0; code_col < syms_per_code; code_col++)
4749 int sym = syms[((code - min_code) * syms_per_code) + code_col];
4751 switch (sym)
4753 case XK_Meta_L:
4754 case XK_Meta_R:
4755 found_alt_or_meta = true;
4756 dpyinfo->meta_mod_mask |= (1 << row);
4757 break;
4759 case XK_Alt_L:
4760 case XK_Alt_R:
4761 found_alt_or_meta = true;
4762 dpyinfo->alt_mod_mask |= (1 << row);
4763 break;
4765 case XK_Hyper_L:
4766 case XK_Hyper_R:
4767 if (!found_alt_or_meta)
4768 dpyinfo->hyper_mod_mask |= (1 << row);
4769 code_col = syms_per_code;
4770 col = mods->max_keypermod;
4771 break;
4773 case XK_Super_L:
4774 case XK_Super_R:
4775 if (!found_alt_or_meta)
4776 dpyinfo->super_mod_mask |= (1 << row);
4777 code_col = syms_per_code;
4778 col = mods->max_keypermod;
4779 break;
4781 case XK_Shift_Lock:
4782 /* Ignore this if it's not on the lock modifier. */
4783 if (!found_alt_or_meta && ((1 << row) == LockMask))
4784 dpyinfo->shift_lock_mask = LockMask;
4785 code_col = syms_per_code;
4786 col = mods->max_keypermod;
4787 break;
4795 /* If we couldn't find any meta keys, accept any alt keys as meta keys. */
4796 if (! dpyinfo->meta_mod_mask)
4798 dpyinfo->meta_mod_mask = dpyinfo->alt_mod_mask;
4799 dpyinfo->alt_mod_mask = 0;
4802 /* If some keys are both alt and meta,
4803 make them just meta, not alt. */
4804 if (dpyinfo->alt_mod_mask & dpyinfo->meta_mod_mask)
4806 dpyinfo->alt_mod_mask &= ~dpyinfo->meta_mod_mask;
4809 XFree (syms);
4810 XFreeModifiermap (mods);
4813 /* Convert between the modifier bits X uses and the modifier bits
4814 Emacs uses. */
4817 x_x_to_emacs_modifiers (struct x_display_info *dpyinfo, int state)
4819 int mod_ctrl = ctrl_modifier;
4820 int mod_meta = meta_modifier;
4821 int mod_alt = alt_modifier;
4822 int mod_hyper = hyper_modifier;
4823 int mod_super = super_modifier;
4824 Lisp_Object tem;
4826 tem = Fget (Vx_ctrl_keysym, Qmodifier_value);
4827 if (INTEGERP (tem)) mod_ctrl = XINT (tem) & INT_MAX;
4828 tem = Fget (Vx_alt_keysym, Qmodifier_value);
4829 if (INTEGERP (tem)) mod_alt = XINT (tem) & INT_MAX;
4830 tem = Fget (Vx_meta_keysym, Qmodifier_value);
4831 if (INTEGERP (tem)) mod_meta = XINT (tem) & INT_MAX;
4832 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
4833 if (INTEGERP (tem)) mod_hyper = XINT (tem) & INT_MAX;
4834 tem = Fget (Vx_super_keysym, Qmodifier_value);
4835 if (INTEGERP (tem)) mod_super = XINT (tem) & INT_MAX;
4837 return ( ((state & (ShiftMask | dpyinfo->shift_lock_mask)) ? shift_modifier : 0)
4838 | ((state & ControlMask) ? mod_ctrl : 0)
4839 | ((state & dpyinfo->meta_mod_mask) ? mod_meta : 0)
4840 | ((state & dpyinfo->alt_mod_mask) ? mod_alt : 0)
4841 | ((state & dpyinfo->super_mod_mask) ? mod_super : 0)
4842 | ((state & dpyinfo->hyper_mod_mask) ? mod_hyper : 0));
4845 static int
4846 x_emacs_to_x_modifiers (struct x_display_info *dpyinfo, EMACS_INT state)
4848 EMACS_INT mod_ctrl = ctrl_modifier;
4849 EMACS_INT mod_meta = meta_modifier;
4850 EMACS_INT mod_alt = alt_modifier;
4851 EMACS_INT mod_hyper = hyper_modifier;
4852 EMACS_INT mod_super = super_modifier;
4854 Lisp_Object tem;
4856 tem = Fget (Vx_ctrl_keysym, Qmodifier_value);
4857 if (INTEGERP (tem)) mod_ctrl = XINT (tem);
4858 tem = Fget (Vx_alt_keysym, Qmodifier_value);
4859 if (INTEGERP (tem)) mod_alt = XINT (tem);
4860 tem = Fget (Vx_meta_keysym, Qmodifier_value);
4861 if (INTEGERP (tem)) mod_meta = XINT (tem);
4862 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
4863 if (INTEGERP (tem)) mod_hyper = XINT (tem);
4864 tem = Fget (Vx_super_keysym, Qmodifier_value);
4865 if (INTEGERP (tem)) mod_super = XINT (tem);
4868 return ( ((state & mod_alt) ? dpyinfo->alt_mod_mask : 0)
4869 | ((state & mod_super) ? dpyinfo->super_mod_mask : 0)
4870 | ((state & mod_hyper) ? dpyinfo->hyper_mod_mask : 0)
4871 | ((state & shift_modifier) ? ShiftMask : 0)
4872 | ((state & mod_ctrl) ? ControlMask : 0)
4873 | ((state & mod_meta) ? dpyinfo->meta_mod_mask : 0));
4876 /* Convert a keysym to its name. */
4878 char *
4879 x_get_keysym_name (int keysym)
4881 char *value;
4883 block_input ();
4884 value = XKeysymToString (keysym);
4885 unblock_input ();
4887 return value;
4890 /* Mouse clicks and mouse movement. Rah.
4892 Formerly, we used PointerMotionHintMask (in standard_event_mask)
4893 so that we would have to call XQueryPointer after each MotionNotify
4894 event to ask for another such event. However, this made mouse tracking
4895 slow, and there was a bug that made it eventually stop.
4897 Simply asking for MotionNotify all the time seems to work better.
4899 In order to avoid asking for motion events and then throwing most
4900 of them away or busy-polling the server for mouse positions, we ask
4901 the server for pointer motion hints. This means that we get only
4902 one event per group of mouse movements. "Groups" are delimited by
4903 other kinds of events (focus changes and button clicks, for
4904 example), or by XQueryPointer calls; when one of these happens, we
4905 get another MotionNotify event the next time the mouse moves. This
4906 is at least as efficient as getting motion events when mouse
4907 tracking is on, and I suspect only negligibly worse when tracking
4908 is off. */
4910 /* Prepare a mouse-event in *RESULT for placement in the input queue.
4912 If the event is a button press, then note that we have grabbed
4913 the mouse. */
4915 static Lisp_Object
4916 construct_mouse_click (struct input_event *result,
4917 const XButtonEvent *event,
4918 struct frame *f)
4920 /* Make the event type NO_EVENT; we'll change that when we decide
4921 otherwise. */
4922 result->kind = MOUSE_CLICK_EVENT;
4923 result->code = event->button - Button1;
4924 result->timestamp = event->time;
4925 result->modifiers = (x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO (f),
4926 event->state)
4927 | (event->type == ButtonRelease
4928 ? up_modifier
4929 : down_modifier));
4931 XSETINT (result->x, event->x);
4932 XSETINT (result->y, event->y);
4933 XSETFRAME (result->frame_or_window, f);
4934 result->arg = Qnil;
4935 return Qnil;
4938 /* Function to report a mouse movement to the mainstream Emacs code.
4939 The input handler calls this.
4941 We have received a mouse movement event, which is given in *event.
4942 If the mouse is over a different glyph than it was last time, tell
4943 the mainstream emacs code by setting mouse_moved. If not, ask for
4944 another motion event, so we can check again the next time it moves. */
4946 static bool
4947 note_mouse_movement (struct frame *frame, const XMotionEvent *event)
4949 XRectangle *r;
4950 struct x_display_info *dpyinfo;
4952 if (!FRAME_X_OUTPUT (frame))
4953 return false;
4955 dpyinfo = FRAME_DISPLAY_INFO (frame);
4956 dpyinfo->last_mouse_movement_time = event->time;
4957 dpyinfo->last_mouse_motion_frame = frame;
4958 dpyinfo->last_mouse_motion_x = event->x;
4959 dpyinfo->last_mouse_motion_y = event->y;
4961 if (event->window != FRAME_X_WINDOW (frame))
4963 frame->mouse_moved = true;
4964 dpyinfo->last_mouse_scroll_bar = NULL;
4965 note_mouse_highlight (frame, -1, -1);
4966 dpyinfo->last_mouse_glyph_frame = NULL;
4967 return true;
4971 /* Has the mouse moved off the glyph it was on at the last sighting? */
4972 r = &dpyinfo->last_mouse_glyph;
4973 if (frame != dpyinfo->last_mouse_glyph_frame
4974 || event->x < r->x || event->x >= r->x + r->width
4975 || event->y < r->y || event->y >= r->y + r->height)
4977 frame->mouse_moved = true;
4978 dpyinfo->last_mouse_scroll_bar = NULL;
4979 note_mouse_highlight (frame, event->x, event->y);
4980 /* Remember which glyph we're now on. */
4981 remember_mouse_glyph (frame, event->x, event->y, r);
4982 dpyinfo->last_mouse_glyph_frame = frame;
4983 return true;
4986 return false;
4989 /* Return the current position of the mouse.
4990 *FP should be a frame which indicates which display to ask about.
4992 If the mouse movement started in a scroll bar, set *FP, *BAR_WINDOW,
4993 and *PART to the frame, window, and scroll bar part that the mouse
4994 is over. Set *X and *Y to the portion and whole of the mouse's
4995 position on the scroll bar.
4997 If the mouse movement started elsewhere, set *FP to the frame the
4998 mouse is on, *BAR_WINDOW to nil, and *X and *Y to the character cell
4999 the mouse is over.
5001 Set *TIMESTAMP to the server time-stamp for the time at which the mouse
5002 was at this position.
5004 Don't store anything if we don't have a valid set of values to report.
5006 This clears the mouse_moved flag, so we can wait for the next mouse
5007 movement. */
5009 static void
5010 XTmouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
5011 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
5012 Time *timestamp)
5014 struct frame *f1;
5015 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (*fp);
5017 block_input ();
5019 if (dpyinfo->last_mouse_scroll_bar && insist == 0)
5021 struct scroll_bar *bar = dpyinfo->last_mouse_scroll_bar;
5023 if (bar->horizontal)
5024 x_horizontal_scroll_bar_report_motion (fp, bar_window, part, x, y, timestamp);
5025 else
5026 x_scroll_bar_report_motion (fp, bar_window, part, x, y, timestamp);
5028 else
5030 Window root;
5031 int root_x, root_y;
5033 Window dummy_window;
5034 int dummy;
5036 Lisp_Object frame, tail;
5038 /* Clear the mouse-moved flag for every frame on this display. */
5039 FOR_EACH_FRAME (tail, frame)
5040 if (FRAME_X_P (XFRAME (frame))
5041 && FRAME_X_DISPLAY (XFRAME (frame)) == FRAME_X_DISPLAY (*fp))
5042 XFRAME (frame)->mouse_moved = false;
5044 dpyinfo->last_mouse_scroll_bar = NULL;
5046 /* Figure out which root window we're on. */
5047 XQueryPointer (FRAME_X_DISPLAY (*fp),
5048 DefaultRootWindow (FRAME_X_DISPLAY (*fp)),
5050 /* The root window which contains the pointer. */
5051 &root,
5053 /* Trash which we can't trust if the pointer is on
5054 a different screen. */
5055 &dummy_window,
5057 /* The position on that root window. */
5058 &root_x, &root_y,
5060 /* More trash we can't trust. */
5061 &dummy, &dummy,
5063 /* Modifier keys and pointer buttons, about which
5064 we don't care. */
5065 (unsigned int *) &dummy);
5067 /* Now we have a position on the root; find the innermost window
5068 containing the pointer. */
5070 Window win, child;
5071 #ifdef USE_GTK
5072 Window first_win = 0;
5073 #endif
5074 int win_x, win_y;
5075 int parent_x = 0, parent_y = 0;
5077 win = root;
5079 /* XTranslateCoordinates can get errors if the window
5080 structure is changing at the same time this function
5081 is running. So at least we must not crash from them. */
5083 x_catch_errors (FRAME_X_DISPLAY (*fp));
5085 if (x_mouse_grabbed (dpyinfo))
5087 /* If mouse was grabbed on a frame, give coords for that frame
5088 even if the mouse is now outside it. */
5089 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
5091 /* From-window. */
5092 root,
5094 /* To-window. */
5095 FRAME_X_WINDOW (dpyinfo->last_mouse_frame),
5097 /* From-position, to-position. */
5098 root_x, root_y, &win_x, &win_y,
5100 /* Child of win. */
5101 &child);
5102 f1 = dpyinfo->last_mouse_frame;
5104 else
5106 while (true)
5108 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
5110 /* From-window, to-window. */
5111 root, win,
5113 /* From-position, to-position. */
5114 root_x, root_y, &win_x, &win_y,
5116 /* Child of win. */
5117 &child);
5119 if (child == None || child == win)
5121 #ifdef USE_GTK
5122 /* On GTK we have not inspected WIN yet. If it has
5123 a frame and that frame has a parent, use it. */
5124 struct frame *f = x_window_to_frame (dpyinfo, win);
5126 if (f && FRAME_PARENT_FRAME (f))
5127 first_win = win;
5128 #endif
5129 break;
5131 #ifdef USE_GTK
5132 /* We don't wan't to know the innermost window. We
5133 want the edit window. For non-Gtk+ the innermost
5134 window is the edit window. For Gtk+ it might not
5135 be. It might be the tool bar for example. */
5136 if (x_window_to_frame (dpyinfo, win))
5137 /* But don't hurry. We might find a child frame
5138 beneath. */
5139 first_win = win;
5140 #endif
5141 win = child;
5142 parent_x = win_x;
5143 parent_y = win_y;
5146 #ifdef USE_GTK
5147 if (first_win)
5148 win = first_win;
5149 #endif
5151 /* Now we know that:
5152 win is the innermost window containing the pointer
5153 (XTC says it has no child containing the pointer),
5154 win_x and win_y are the pointer's position in it
5155 (XTC did this the last time through), and
5156 parent_x and parent_y are the pointer's position in win's parent.
5157 (They are what win_x and win_y were when win was child.
5158 If win is the root window, it has no parent, and
5159 parent_{x,y} are invalid, but that's okay, because we'll
5160 never use them in that case.) */
5162 #ifdef USE_GTK
5163 /* We don't wan't to know the innermost window. We
5164 want the edit window. */
5165 f1 = x_window_to_frame (dpyinfo, win);
5166 #else
5167 /* Is win one of our frames? */
5168 f1 = x_any_window_to_frame (dpyinfo, win);
5169 #endif
5171 #ifdef USE_X_TOOLKIT
5172 /* If we end up with the menu bar window, say it's not
5173 on the frame. */
5174 if (f1 != NULL
5175 && f1->output_data.x->menubar_widget
5176 && win == XtWindow (f1->output_data.x->menubar_widget))
5177 f1 = NULL;
5178 #endif /* USE_X_TOOLKIT */
5181 if (x_had_errors_p (FRAME_X_DISPLAY (*fp)))
5182 f1 = 0;
5184 x_uncatch_errors_after_check ();
5186 /* If not, is it one of our scroll bars? */
5187 if (! f1)
5189 struct scroll_bar *bar;
5191 bar = x_window_to_scroll_bar (FRAME_X_DISPLAY (*fp), win, 2);
5193 if (bar)
5195 f1 = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5196 win_x = parent_x;
5197 win_y = parent_y;
5201 if (f1 == 0 && insist > 0)
5202 f1 = SELECTED_FRAME ();
5204 if (f1)
5206 /* Ok, we found a frame. Store all the values.
5207 last_mouse_glyph is a rectangle used to reduce the
5208 generation of mouse events. To not miss any motion
5209 events, we must divide the frame into rectangles of the
5210 size of the smallest character that could be displayed
5211 on it, i.e. into the same rectangles that matrices on
5212 the frame are divided into. */
5214 /* FIXME: what if F1 is not an X frame? */
5215 dpyinfo = FRAME_DISPLAY_INFO (f1);
5216 remember_mouse_glyph (f1, win_x, win_y, &dpyinfo->last_mouse_glyph);
5217 dpyinfo->last_mouse_glyph_frame = f1;
5219 *bar_window = Qnil;
5220 *part = 0;
5221 *fp = f1;
5222 XSETINT (*x, win_x);
5223 XSETINT (*y, win_y);
5224 *timestamp = dpyinfo->last_mouse_movement_time;
5229 unblock_input ();
5234 /***********************************************************************
5235 Scroll bars
5236 ***********************************************************************/
5238 /* Scroll bar support. */
5240 /* Given an X window ID and a DISPLAY, find the struct scroll_bar which
5241 manages it.
5242 This can be called in GC, so we have to make sure to strip off mark
5243 bits. */
5245 static struct scroll_bar *
5246 x_window_to_scroll_bar (Display *display, Window window_id, int type)
5248 Lisp_Object tail, frame;
5250 #if defined (USE_GTK) && defined (USE_TOOLKIT_SCROLL_BARS)
5251 window_id = (Window) xg_get_scroll_id_for_window (display, window_id);
5252 #endif /* USE_GTK && USE_TOOLKIT_SCROLL_BARS */
5254 FOR_EACH_FRAME (tail, frame)
5256 Lisp_Object bar, condemned;
5258 if (! FRAME_X_P (XFRAME (frame)))
5259 continue;
5261 /* Scan this frame's scroll bar list for a scroll bar with the
5262 right window ID. */
5263 condemned = FRAME_CONDEMNED_SCROLL_BARS (XFRAME (frame));
5264 for (bar = FRAME_SCROLL_BARS (XFRAME (frame));
5265 /* This trick allows us to search both the ordinary and
5266 condemned scroll bar lists with one loop. */
5267 ! NILP (bar) || (bar = condemned,
5268 condemned = Qnil,
5269 ! NILP (bar));
5270 bar = XSCROLL_BAR (bar)->next)
5271 if (XSCROLL_BAR (bar)->x_window == window_id
5272 && FRAME_X_DISPLAY (XFRAME (frame)) == display
5273 && (type = 2
5274 || (type == 1 && XSCROLL_BAR (bar)->horizontal)
5275 || (type == 0 && !XSCROLL_BAR (bar)->horizontal)))
5276 return XSCROLL_BAR (bar);
5279 return NULL;
5283 #if defined USE_LUCID
5285 /* Return the Lucid menu bar WINDOW is part of. Return null
5286 if WINDOW is not part of a menu bar. */
5288 static Widget
5289 x_window_to_menu_bar (Window window)
5291 Lisp_Object tail, frame;
5293 FOR_EACH_FRAME (tail, frame)
5294 if (FRAME_X_P (XFRAME (frame)))
5296 Widget menu_bar = XFRAME (frame)->output_data.x->menubar_widget;
5298 if (menu_bar && xlwmenu_window_p (menu_bar, window))
5299 return menu_bar;
5301 return NULL;
5304 #endif /* USE_LUCID */
5307 /************************************************************************
5308 Toolkit scroll bars
5309 ************************************************************************/
5311 #ifdef USE_TOOLKIT_SCROLL_BARS
5313 static void x_send_scroll_bar_event (Lisp_Object, enum scroll_bar_part,
5314 int, int, bool);
5316 /* Lisp window being scrolled. Set when starting to interact with
5317 a toolkit scroll bar, reset to nil when ending the interaction. */
5319 static Lisp_Object window_being_scrolled;
5321 /* Whether this is an Xaw with arrow-scrollbars. This should imply
5322 that movements of 1/20 of the screen size are mapped to up/down. */
5324 #ifndef USE_GTK
5325 /* Id of action hook installed for scroll bars. */
5327 static XtActionHookId action_hook_id;
5328 static XtActionHookId horizontal_action_hook_id;
5330 static Boolean xaw3d_arrow_scroll;
5332 /* Whether the drag scrolling maintains the mouse at the top of the
5333 thumb. If not, resizing the thumb needs to be done more carefully
5334 to avoid jerkiness. */
5336 static Boolean xaw3d_pick_top;
5338 /* Action hook installed via XtAppAddActionHook when toolkit scroll
5339 bars are used.. The hook is responsible for detecting when
5340 the user ends an interaction with the scroll bar, and generates
5341 a `end-scroll' SCROLL_BAR_CLICK_EVENT' event if so. */
5343 static void
5344 xt_action_hook (Widget widget, XtPointer client_data, String action_name,
5345 XEvent *event, String *params, Cardinal *num_params)
5347 bool scroll_bar_p;
5348 const char *end_action;
5350 #ifdef USE_MOTIF
5351 scroll_bar_p = XmIsScrollBar (widget);
5352 end_action = "Release";
5353 #else /* !USE_MOTIF i.e. use Xaw */
5354 scroll_bar_p = XtIsSubclass (widget, scrollbarWidgetClass);
5355 end_action = "EndScroll";
5356 #endif /* USE_MOTIF */
5358 if (scroll_bar_p
5359 && strcmp (action_name, end_action) == 0
5360 && WINDOWP (window_being_scrolled))
5362 struct window *w;
5363 struct scroll_bar *bar;
5365 x_send_scroll_bar_event (window_being_scrolled,
5366 scroll_bar_end_scroll, 0, 0, false);
5367 w = XWINDOW (window_being_scrolled);
5368 bar = XSCROLL_BAR (w->vertical_scroll_bar);
5370 if (bar->dragging != -1)
5372 bar->dragging = -1;
5373 /* The thumb size is incorrect while dragging: fix it. */
5374 set_vertical_scroll_bar (w);
5376 window_being_scrolled = Qnil;
5377 #if defined (USE_LUCID)
5378 bar->last_seen_part = scroll_bar_nowhere;
5379 #endif
5380 /* Xt timeouts no longer needed. */
5381 toolkit_scroll_bar_interaction = false;
5386 static void
5387 xt_horizontal_action_hook (Widget widget, XtPointer client_data, String action_name,
5388 XEvent *event, String *params, Cardinal *num_params)
5390 bool scroll_bar_p;
5391 const char *end_action;
5393 #ifdef USE_MOTIF
5394 scroll_bar_p = XmIsScrollBar (widget);
5395 end_action = "Release";
5396 #else /* !USE_MOTIF i.e. use Xaw */
5397 scroll_bar_p = XtIsSubclass (widget, scrollbarWidgetClass);
5398 end_action = "EndScroll";
5399 #endif /* USE_MOTIF */
5401 if (scroll_bar_p
5402 && strcmp (action_name, end_action) == 0
5403 && WINDOWP (window_being_scrolled))
5405 struct window *w;
5406 struct scroll_bar *bar;
5408 x_send_scroll_bar_event (window_being_scrolled,
5409 scroll_bar_end_scroll, 0, 0, true);
5410 w = XWINDOW (window_being_scrolled);
5411 if (!NILP (w->horizontal_scroll_bar))
5413 bar = XSCROLL_BAR (w->horizontal_scroll_bar);
5414 if (bar->dragging != -1)
5416 bar->dragging = -1;
5417 /* The thumb size is incorrect while dragging: fix it. */
5418 set_horizontal_scroll_bar (w);
5420 window_being_scrolled = Qnil;
5421 #if defined (USE_LUCID)
5422 bar->last_seen_part = scroll_bar_nowhere;
5423 #endif
5424 /* Xt timeouts no longer needed. */
5425 toolkit_scroll_bar_interaction = false;
5429 #endif /* not USE_GTK */
5431 /* Send a client message with message type Xatom_Scrollbar for a
5432 scroll action to the frame of WINDOW. PART is a value identifying
5433 the part of the scroll bar that was clicked on. PORTION is the
5434 amount to scroll of a whole of WHOLE. */
5436 static void
5437 x_send_scroll_bar_event (Lisp_Object window, enum scroll_bar_part part,
5438 int portion, int whole, bool horizontal)
5440 XEvent event;
5441 XClientMessageEvent *ev = &event.xclient;
5442 struct window *w = XWINDOW (window);
5443 struct frame *f = XFRAME (w->frame);
5444 intptr_t iw = (intptr_t) w;
5445 verify (INTPTR_WIDTH <= 64);
5446 int sign_shift = INTPTR_WIDTH - 32;
5448 block_input ();
5450 /* Construct a ClientMessage event to send to the frame. */
5451 ev->type = ClientMessage;
5452 ev->message_type = (horizontal
5453 ? FRAME_DISPLAY_INFO (f)->Xatom_Horizontal_Scrollbar
5454 : FRAME_DISPLAY_INFO (f)->Xatom_Scrollbar);
5455 ev->display = FRAME_X_DISPLAY (f);
5456 ev->window = FRAME_X_WINDOW (f);
5457 ev->format = 32;
5459 /* A 32-bit X client on a 64-bit X server can pass a window pointer
5460 as-is. A 64-bit client on a 32-bit X server is in trouble
5461 because a pointer does not fit and would be truncated while
5462 passing through the server. So use two slots and hope that X12
5463 will resolve such issues someday. */
5464 ev->data.l[0] = iw >> 31 >> 1;
5465 ev->data.l[1] = sign_shift <= 0 ? iw : iw << sign_shift >> sign_shift;
5466 ev->data.l[2] = part;
5467 ev->data.l[3] = portion;
5468 ev->data.l[4] = whole;
5470 /* Make Xt timeouts work while the scroll bar is active. */
5471 #ifdef USE_X_TOOLKIT
5472 toolkit_scroll_bar_interaction = true;
5473 x_activate_timeout_atimer ();
5474 #endif
5476 /* Setting the event mask to zero means that the message will
5477 be sent to the client that created the window, and if that
5478 window no longer exists, no event will be sent. */
5479 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), False, 0, &event);
5480 unblock_input ();
5484 /* Transform a scroll bar ClientMessage EVENT to an Emacs input event
5485 in *IEVENT. */
5487 static void
5488 x_scroll_bar_to_input_event (const XEvent *event,
5489 struct input_event *ievent)
5491 const XClientMessageEvent *ev = &event->xclient;
5492 Lisp_Object window;
5493 struct window *w;
5495 /* See the comment in the function above. */
5496 intptr_t iw0 = ev->data.l[0];
5497 intptr_t iw1 = ev->data.l[1];
5498 intptr_t iw = (iw0 << 31 << 1) + (iw1 & 0xffffffffu);
5499 w = (struct window *) iw;
5501 XSETWINDOW (window, w);
5503 ievent->kind = SCROLL_BAR_CLICK_EVENT;
5504 ievent->frame_or_window = window;
5505 ievent->arg = Qnil;
5506 #ifdef USE_GTK
5507 ievent->timestamp = CurrentTime;
5508 #else
5509 ievent->timestamp =
5510 XtLastTimestampProcessed (FRAME_X_DISPLAY (XFRAME (w->frame)));
5511 #endif
5512 ievent->code = 0;
5513 ievent->part = ev->data.l[2];
5514 ievent->x = make_number (ev->data.l[3]);
5515 ievent->y = make_number (ev->data.l[4]);
5516 ievent->modifiers = 0;
5519 /* Transform a horizontal scroll bar ClientMessage EVENT to an Emacs
5520 input event in *IEVENT. */
5522 static void
5523 x_horizontal_scroll_bar_to_input_event (const XEvent *event,
5524 struct input_event *ievent)
5526 const XClientMessageEvent *ev = &event->xclient;
5527 Lisp_Object window;
5528 struct window *w;
5530 /* See the comment in the function above. */
5531 intptr_t iw0 = ev->data.l[0];
5532 intptr_t iw1 = ev->data.l[1];
5533 intptr_t iw = (iw0 << 31 << 1) + (iw1 & 0xffffffffu);
5534 w = (struct window *) iw;
5536 XSETWINDOW (window, w);
5538 ievent->kind = HORIZONTAL_SCROLL_BAR_CLICK_EVENT;
5539 ievent->frame_or_window = window;
5540 ievent->arg = Qnil;
5541 #ifdef USE_GTK
5542 ievent->timestamp = CurrentTime;
5543 #else
5544 ievent->timestamp =
5545 XtLastTimestampProcessed (FRAME_X_DISPLAY (XFRAME (w->frame)));
5546 #endif
5547 ievent->code = 0;
5548 ievent->part = ev->data.l[2];
5549 ievent->x = make_number (ev->data.l[3]);
5550 ievent->y = make_number (ev->data.l[4]);
5551 ievent->modifiers = 0;
5555 #ifdef USE_MOTIF
5557 /* Minimum and maximum values used for Motif scroll bars. */
5559 #define XM_SB_MAX 10000000
5561 /* Scroll bar callback for Motif scroll bars. WIDGET is the scroll
5562 bar widget. CLIENT_DATA is a pointer to the scroll_bar structure.
5563 CALL_DATA is a pointer to a XmScrollBarCallbackStruct. */
5565 static void
5566 xm_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
5568 struct scroll_bar *bar = client_data;
5569 XmScrollBarCallbackStruct *cs = call_data;
5570 enum scroll_bar_part part = scroll_bar_nowhere;
5571 bool horizontal = bar->horizontal;
5572 int whole = 0, portion = 0;
5574 switch (cs->reason)
5576 case XmCR_DECREMENT:
5577 bar->dragging = -1;
5578 part = horizontal ? scroll_bar_left_arrow : scroll_bar_up_arrow;
5579 break;
5581 case XmCR_INCREMENT:
5582 bar->dragging = -1;
5583 part = horizontal ? scroll_bar_right_arrow : scroll_bar_down_arrow;
5584 break;
5586 case XmCR_PAGE_DECREMENT:
5587 bar->dragging = -1;
5588 part = horizontal ? scroll_bar_before_handle : scroll_bar_above_handle;
5589 break;
5591 case XmCR_PAGE_INCREMENT:
5592 bar->dragging = -1;
5593 part = horizontal ? scroll_bar_after_handle : scroll_bar_below_handle;
5594 break;
5596 case XmCR_TO_TOP:
5597 bar->dragging = -1;
5598 part = horizontal ? scroll_bar_to_leftmost : scroll_bar_to_top;
5599 break;
5601 case XmCR_TO_BOTTOM:
5602 bar->dragging = -1;
5603 part = horizontal ? scroll_bar_to_rightmost : scroll_bar_to_bottom;
5604 break;
5606 case XmCR_DRAG:
5608 int slider_size;
5610 block_input ();
5611 XtVaGetValues (widget, XmNsliderSize, &slider_size, NULL);
5612 unblock_input ();
5614 if (horizontal)
5616 portion = bar->whole * ((float)cs->value / XM_SB_MAX);
5617 whole = bar->whole * ((float)(XM_SB_MAX - slider_size) / XM_SB_MAX);
5618 portion = min (portion, whole);
5619 part = scroll_bar_horizontal_handle;
5621 else
5623 whole = XM_SB_MAX - slider_size;
5624 portion = min (cs->value, whole);
5625 part = scroll_bar_handle;
5628 bar->dragging = cs->value;
5630 break;
5632 case XmCR_VALUE_CHANGED:
5633 break;
5636 if (part != scroll_bar_nowhere)
5638 window_being_scrolled = bar->window;
5639 x_send_scroll_bar_event (bar->window, part, portion, whole,
5640 bar->horizontal);
5644 #elif defined USE_GTK
5646 /* Scroll bar callback for GTK scroll bars. WIDGET is the scroll
5647 bar widget. DATA is a pointer to the scroll_bar structure. */
5649 static gboolean
5650 xg_scroll_callback (GtkRange *range,
5651 GtkScrollType scroll,
5652 gdouble value,
5653 gpointer user_data)
5655 int whole = 0, portion = 0;
5656 struct scroll_bar *bar = user_data;
5657 enum scroll_bar_part part = scroll_bar_nowhere;
5658 GtkAdjustment *adj = GTK_ADJUSTMENT (gtk_range_get_adjustment (range));
5659 struct frame *f = g_object_get_data (G_OBJECT (range), XG_FRAME_DATA);
5661 if (xg_ignore_gtk_scrollbar) return false;
5663 switch (scroll)
5665 case GTK_SCROLL_JUMP:
5666 /* Buttons 1 2 or 3 must be grabbed. */
5667 if (FRAME_DISPLAY_INFO (f)->grabbed != 0
5668 && FRAME_DISPLAY_INFO (f)->grabbed < (1 << 4))
5670 if (bar->horizontal)
5672 part = scroll_bar_horizontal_handle;
5673 whole = (int)(gtk_adjustment_get_upper (adj) -
5674 gtk_adjustment_get_page_size (adj));
5675 portion = min ((int)value, whole);
5676 bar->dragging = portion;
5678 else
5680 part = scroll_bar_handle;
5681 whole = gtk_adjustment_get_upper (adj) -
5682 gtk_adjustment_get_page_size (adj);
5683 portion = min ((int)value, whole);
5684 bar->dragging = portion;
5687 break;
5688 case GTK_SCROLL_STEP_BACKWARD:
5689 part = (bar->horizontal
5690 ? scroll_bar_left_arrow : scroll_bar_up_arrow);
5691 bar->dragging = -1;
5692 break;
5693 case GTK_SCROLL_STEP_FORWARD:
5694 part = (bar->horizontal
5695 ? scroll_bar_right_arrow : scroll_bar_down_arrow);
5696 bar->dragging = -1;
5697 break;
5698 case GTK_SCROLL_PAGE_BACKWARD:
5699 part = (bar->horizontal
5700 ? scroll_bar_before_handle : scroll_bar_above_handle);
5701 bar->dragging = -1;
5702 break;
5703 case GTK_SCROLL_PAGE_FORWARD:
5704 part = (bar->horizontal
5705 ? scroll_bar_after_handle : scroll_bar_below_handle);
5706 bar->dragging = -1;
5707 break;
5708 default:
5709 break;
5712 if (part != scroll_bar_nowhere)
5714 window_being_scrolled = bar->window;
5715 x_send_scroll_bar_event (bar->window, part, portion, whole,
5716 bar->horizontal);
5719 return false;
5722 /* Callback for button release. Sets dragging to -1 when dragging is done. */
5724 static gboolean
5725 xg_end_scroll_callback (GtkWidget *widget,
5726 GdkEventButton *event,
5727 gpointer user_data)
5729 struct scroll_bar *bar = user_data;
5730 bar->dragging = -1;
5731 if (WINDOWP (window_being_scrolled))
5733 x_send_scroll_bar_event (window_being_scrolled,
5734 scroll_bar_end_scroll, 0, 0, bar->horizontal);
5735 window_being_scrolled = Qnil;
5738 return false;
5742 #else /* not USE_GTK and not USE_MOTIF */
5744 /* Xaw scroll bar callback. Invoked when the thumb is dragged.
5745 WIDGET is the scroll bar widget. CLIENT_DATA is a pointer to the
5746 scroll bar struct. CALL_DATA is a pointer to a float saying where
5747 the thumb is. */
5749 static void
5750 xaw_jump_callback (Widget widget, XtPointer client_data, XtPointer call_data)
5752 struct scroll_bar *bar = client_data;
5753 float *top_addr = call_data;
5754 float top = *top_addr;
5755 float shown;
5756 int whole, portion, height, width;
5757 enum scroll_bar_part part;
5758 bool horizontal = bar->horizontal;
5760 if (horizontal)
5762 /* Get the size of the thumb, a value between 0 and 1. */
5763 block_input ();
5764 XtVaGetValues (widget, XtNshown, &shown, XtNwidth, &width, NULL);
5765 unblock_input ();
5767 if (shown < 1)
5769 whole = bar->whole - (shown * bar->whole);
5770 portion = min (top * bar->whole, whole);
5772 else
5774 whole = bar->whole;
5775 portion = 0;
5778 part = scroll_bar_horizontal_handle;
5780 else
5782 /* Get the size of the thumb, a value between 0 and 1. */
5783 block_input ();
5784 XtVaGetValues (widget, XtNshown, &shown, XtNheight, &height, NULL);
5785 unblock_input ();
5787 whole = 10000000;
5788 portion = shown < 1 ? top * whole : 0;
5790 if (shown < 1 && (eabs (top + shown - 1) < 1.0f / height))
5791 /* Some derivatives of Xaw refuse to shrink the thumb when you reach
5792 the bottom, so we force the scrolling whenever we see that we're
5793 too close to the bottom (in x_set_toolkit_scroll_bar_thumb
5794 we try to ensure that we always stay two pixels away from the
5795 bottom). */
5796 part = scroll_bar_down_arrow;
5797 else
5798 part = scroll_bar_handle;
5801 window_being_scrolled = bar->window;
5802 bar->dragging = portion;
5803 bar->last_seen_part = part;
5804 x_send_scroll_bar_event (bar->window, part, portion, whole, bar->horizontal);
5808 /* Xaw scroll bar callback. Invoked for incremental scrolling.,
5809 i.e. line or page up or down. WIDGET is the Xaw scroll bar
5810 widget. CLIENT_DATA is a pointer to the scroll_bar structure for
5811 the scroll bar. CALL_DATA is an integer specifying the action that
5812 has taken place. Its magnitude is in the range 0..height of the
5813 scroll bar. Negative values mean scroll towards buffer start.
5814 Values < height of scroll bar mean line-wise movement. */
5816 static void
5817 xaw_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
5819 struct scroll_bar *bar = client_data;
5820 /* The position really is stored cast to a pointer. */
5821 int position = (intptr_t) call_data;
5822 Dimension height, width;
5823 enum scroll_bar_part part;
5825 if (bar->horizontal)
5827 /* Get the width of the scroll bar. */
5828 block_input ();
5829 XtVaGetValues (widget, XtNwidth, &width, NULL);
5830 unblock_input ();
5832 if (eabs (position) >= width)
5833 part = (position < 0) ? scroll_bar_before_handle : scroll_bar_after_handle;
5835 /* If Xaw3d was compiled with ARROW_SCROLLBAR,
5836 it maps line-movement to call_data = max(5, height/20). */
5837 else if (xaw3d_arrow_scroll && eabs (position) <= max (5, width / 20))
5838 part = (position < 0) ? scroll_bar_left_arrow : scroll_bar_right_arrow;
5839 else
5840 part = scroll_bar_move_ratio;
5842 window_being_scrolled = bar->window;
5843 bar->dragging = -1;
5844 bar->last_seen_part = part;
5845 x_send_scroll_bar_event (bar->window, part, position, width,
5846 bar->horizontal);
5848 else
5851 /* Get the height of the scroll bar. */
5852 block_input ();
5853 XtVaGetValues (widget, XtNheight, &height, NULL);
5854 unblock_input ();
5856 if (eabs (position) >= height)
5857 part = (position < 0) ? scroll_bar_above_handle : scroll_bar_below_handle;
5859 /* If Xaw3d was compiled with ARROW_SCROLLBAR,
5860 it maps line-movement to call_data = max(5, height/20). */
5861 else if (xaw3d_arrow_scroll && eabs (position) <= max (5, height / 20))
5862 part = (position < 0) ? scroll_bar_up_arrow : scroll_bar_down_arrow;
5863 else
5864 part = scroll_bar_move_ratio;
5866 window_being_scrolled = bar->window;
5867 bar->dragging = -1;
5868 bar->last_seen_part = part;
5869 x_send_scroll_bar_event (bar->window, part, position, height,
5870 bar->horizontal);
5874 #endif /* not USE_GTK and not USE_MOTIF */
5876 #define SCROLL_BAR_NAME "verticalScrollBar"
5877 #define SCROLL_BAR_HORIZONTAL_NAME "horizontalScrollBar"
5879 /* Create the widget for scroll bar BAR on frame F. Record the widget
5880 and X window of the scroll bar in BAR. */
5882 #ifdef USE_GTK
5883 static void
5884 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
5886 const char *scroll_bar_name = SCROLL_BAR_NAME;
5888 block_input ();
5889 xg_create_scroll_bar (f, bar, G_CALLBACK (xg_scroll_callback),
5890 G_CALLBACK (xg_end_scroll_callback),
5891 scroll_bar_name);
5892 unblock_input ();
5895 static void
5896 x_create_horizontal_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
5898 const char *scroll_bar_name = SCROLL_BAR_HORIZONTAL_NAME;
5900 block_input ();
5901 xg_create_horizontal_scroll_bar (f, bar, G_CALLBACK (xg_scroll_callback),
5902 G_CALLBACK (xg_end_scroll_callback),
5903 scroll_bar_name);
5904 unblock_input ();
5907 #else /* not USE_GTK */
5909 static void
5910 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
5912 Window xwindow;
5913 Widget widget;
5914 Arg av[20];
5915 int ac = 0;
5916 const char *scroll_bar_name = SCROLL_BAR_NAME;
5917 unsigned long pixel;
5919 block_input ();
5921 #ifdef USE_MOTIF
5922 /* Set resources. Create the widget. */
5923 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
5924 XtSetArg (av[ac], XmNminimum, 0); ++ac;
5925 XtSetArg (av[ac], XmNmaximum, XM_SB_MAX); ++ac;
5926 XtSetArg (av[ac], XmNorientation, XmVERTICAL); ++ac;
5927 XtSetArg (av[ac], XmNprocessingDirection, XmMAX_ON_BOTTOM), ++ac;
5928 XtSetArg (av[ac], XmNincrement, 1); ++ac;
5929 XtSetArg (av[ac], XmNpageIncrement, 1); ++ac;
5931 pixel = f->output_data.x->scroll_bar_foreground_pixel;
5932 if (pixel != -1)
5934 XtSetArg (av[ac], XmNforeground, pixel);
5935 ++ac;
5938 pixel = f->output_data.x->scroll_bar_background_pixel;
5939 if (pixel != -1)
5941 XtSetArg (av[ac], XmNbackground, pixel);
5942 ++ac;
5945 widget = XmCreateScrollBar (f->output_data.x->edit_widget,
5946 (char *) scroll_bar_name, av, ac);
5948 /* Add one callback for everything that can happen. */
5949 XtAddCallback (widget, XmNdecrementCallback, xm_scroll_callback,
5950 (XtPointer) bar);
5951 XtAddCallback (widget, XmNdragCallback, xm_scroll_callback,
5952 (XtPointer) bar);
5953 XtAddCallback (widget, XmNincrementCallback, xm_scroll_callback,
5954 (XtPointer) bar);
5955 XtAddCallback (widget, XmNpageDecrementCallback, xm_scroll_callback,
5956 (XtPointer) bar);
5957 XtAddCallback (widget, XmNpageIncrementCallback, xm_scroll_callback,
5958 (XtPointer) bar);
5959 XtAddCallback (widget, XmNtoBottomCallback, xm_scroll_callback,
5960 (XtPointer) bar);
5961 XtAddCallback (widget, XmNtoTopCallback, xm_scroll_callback,
5962 (XtPointer) bar);
5964 /* Realize the widget. Only after that is the X window created. */
5965 XtRealizeWidget (widget);
5967 /* Set the cursor to an arrow. I didn't find a resource to do that.
5968 And I'm wondering why it hasn't an arrow cursor by default. */
5969 XDefineCursor (XtDisplay (widget), XtWindow (widget),
5970 f->output_data.x->nontext_cursor);
5972 #else /* !USE_MOTIF i.e. use Xaw */
5974 /* Set resources. Create the widget. The background of the
5975 Xaw3d scroll bar widget is a little bit light for my taste.
5976 We don't alter it here to let users change it according
5977 to their taste with `emacs*verticalScrollBar.background: xxx'. */
5978 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
5979 XtSetArg (av[ac], XtNorientation, XtorientVertical); ++ac;
5980 /* For smoother scrolling with Xaw3d -sm */
5981 /* XtSetArg (av[ac], XtNpickTop, True); ++ac; */
5983 pixel = f->output_data.x->scroll_bar_foreground_pixel;
5984 if (pixel != -1)
5986 XtSetArg (av[ac], XtNforeground, pixel);
5987 ++ac;
5990 pixel = f->output_data.x->scroll_bar_background_pixel;
5991 if (pixel != -1)
5993 XtSetArg (av[ac], XtNbackground, pixel);
5994 ++ac;
5997 /* Top/bottom shadow colors. */
5999 /* Allocate them, if necessary. */
6000 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1)
6002 pixel = f->output_data.x->scroll_bar_background_pixel;
6003 if (pixel != -1)
6005 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
6006 FRAME_X_COLORMAP (f),
6007 &pixel, 1.2, 0x8000))
6008 pixel = -1;
6009 f->output_data.x->scroll_bar_top_shadow_pixel = pixel;
6012 if (f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
6014 pixel = f->output_data.x->scroll_bar_background_pixel;
6015 if (pixel != -1)
6017 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
6018 FRAME_X_COLORMAP (f),
6019 &pixel, 0.6, 0x4000))
6020 pixel = -1;
6021 f->output_data.x->scroll_bar_bottom_shadow_pixel = pixel;
6025 #ifdef XtNbeNiceToColormap
6026 /* Tell the toolkit about them. */
6027 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1
6028 || f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
6029 /* We tried to allocate a color for the top/bottom shadow, and
6030 failed, so tell Xaw3d to use dithering instead. */
6031 /* But only if we have a small colormap. Xaw3d can allocate nice
6032 colors itself. */
6034 XtSetArg (av[ac], XtNbeNiceToColormap,
6035 DefaultDepthOfScreen (FRAME_X_SCREEN (f)) < 16);
6036 ++ac;
6038 else
6039 /* Tell what colors Xaw3d should use for the top/bottom shadow, to
6040 be more consistent with other emacs 3d colors, and since Xaw3d is
6041 not good at dealing with allocation failure. */
6043 /* This tells Xaw3d to use real colors instead of dithering for
6044 the shadows. */
6045 XtSetArg (av[ac], XtNbeNiceToColormap, False);
6046 ++ac;
6048 /* Specify the colors. */
6049 pixel = f->output_data.x->scroll_bar_top_shadow_pixel;
6050 if (pixel != -1)
6052 XtSetArg (av[ac], XtNtopShadowPixel, pixel);
6053 ++ac;
6055 pixel = f->output_data.x->scroll_bar_bottom_shadow_pixel;
6056 if (pixel != -1)
6058 XtSetArg (av[ac], XtNbottomShadowPixel, pixel);
6059 ++ac;
6062 #endif
6064 widget = XtCreateWidget (scroll_bar_name, scrollbarWidgetClass,
6065 f->output_data.x->edit_widget, av, ac);
6068 char const *initial = "";
6069 char const *val = initial;
6070 XtVaGetValues (widget, XtNscrollVCursor, (XtPointer) &val,
6071 #ifdef XtNarrowScrollbars
6072 XtNarrowScrollbars, (XtPointer) &xaw3d_arrow_scroll,
6073 #endif
6074 XtNpickTop, (XtPointer) &xaw3d_pick_top, NULL);
6075 if (xaw3d_arrow_scroll || val == initial)
6076 { /* ARROW_SCROLL */
6077 xaw3d_arrow_scroll = True;
6078 /* Isn't that just a personal preference ? --Stef */
6079 XtVaSetValues (widget, XtNcursorName, "top_left_arrow", NULL);
6083 /* Define callbacks. */
6084 XtAddCallback (widget, XtNjumpProc, xaw_jump_callback, (XtPointer) bar);
6085 XtAddCallback (widget, XtNscrollProc, xaw_scroll_callback,
6086 (XtPointer) bar);
6088 /* Realize the widget. Only after that is the X window created. */
6089 XtRealizeWidget (widget);
6091 #endif /* !USE_MOTIF */
6093 /* Install an action hook that lets us detect when the user
6094 finishes interacting with a scroll bar. */
6095 if (action_hook_id == 0)
6096 action_hook_id = XtAppAddActionHook (Xt_app_con, xt_action_hook, 0);
6098 /* Remember X window and widget in the scroll bar vector. */
6099 SET_SCROLL_BAR_X_WIDGET (bar, widget);
6100 xwindow = XtWindow (widget);
6101 bar->x_window = xwindow;
6102 bar->whole = 1;
6103 bar->horizontal = false;
6105 unblock_input ();
6108 static void
6109 x_create_horizontal_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
6111 Window xwindow;
6112 Widget widget;
6113 Arg av[20];
6114 int ac = 0;
6115 const char *scroll_bar_name = SCROLL_BAR_HORIZONTAL_NAME;
6116 unsigned long pixel;
6118 block_input ();
6120 #ifdef USE_MOTIF
6121 /* Set resources. Create the widget. */
6122 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
6123 XtSetArg (av[ac], XmNminimum, 0); ++ac;
6124 XtSetArg (av[ac], XmNmaximum, XM_SB_MAX); ++ac;
6125 XtSetArg (av[ac], XmNorientation, XmHORIZONTAL); ++ac;
6126 XtSetArg (av[ac], XmNprocessingDirection, XmMAX_ON_RIGHT), ++ac;
6127 XtSetArg (av[ac], XmNincrement, 1); ++ac;
6128 XtSetArg (av[ac], XmNpageIncrement, 1); ++ac;
6130 pixel = f->output_data.x->scroll_bar_foreground_pixel;
6131 if (pixel != -1)
6133 XtSetArg (av[ac], XmNforeground, pixel);
6134 ++ac;
6137 pixel = f->output_data.x->scroll_bar_background_pixel;
6138 if (pixel != -1)
6140 XtSetArg (av[ac], XmNbackground, pixel);
6141 ++ac;
6144 widget = XmCreateScrollBar (f->output_data.x->edit_widget,
6145 (char *) scroll_bar_name, av, ac);
6147 /* Add one callback for everything that can happen. */
6148 XtAddCallback (widget, XmNdecrementCallback, xm_scroll_callback,
6149 (XtPointer) bar);
6150 XtAddCallback (widget, XmNdragCallback, xm_scroll_callback,
6151 (XtPointer) bar);
6152 XtAddCallback (widget, XmNincrementCallback, xm_scroll_callback,
6153 (XtPointer) bar);
6154 XtAddCallback (widget, XmNpageDecrementCallback, xm_scroll_callback,
6155 (XtPointer) bar);
6156 XtAddCallback (widget, XmNpageIncrementCallback, xm_scroll_callback,
6157 (XtPointer) bar);
6158 XtAddCallback (widget, XmNtoBottomCallback, xm_scroll_callback,
6159 (XtPointer) bar);
6160 XtAddCallback (widget, XmNtoTopCallback, xm_scroll_callback,
6161 (XtPointer) bar);
6163 /* Realize the widget. Only after that is the X window created. */
6164 XtRealizeWidget (widget);
6166 /* Set the cursor to an arrow. I didn't find a resource to do that.
6167 And I'm wondering why it hasn't an arrow cursor by default. */
6168 XDefineCursor (XtDisplay (widget), XtWindow (widget),
6169 f->output_data.x->nontext_cursor);
6171 #else /* !USE_MOTIF i.e. use Xaw */
6173 /* Set resources. Create the widget. The background of the
6174 Xaw3d scroll bar widget is a little bit light for my taste.
6175 We don't alter it here to let users change it according
6176 to their taste with `emacs*verticalScrollBar.background: xxx'. */
6177 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
6178 XtSetArg (av[ac], XtNorientation, XtorientHorizontal); ++ac;
6179 /* For smoother scrolling with Xaw3d -sm */
6180 /* XtSetArg (av[ac], XtNpickTop, True); ++ac; */
6182 pixel = f->output_data.x->scroll_bar_foreground_pixel;
6183 if (pixel != -1)
6185 XtSetArg (av[ac], XtNforeground, pixel);
6186 ++ac;
6189 pixel = f->output_data.x->scroll_bar_background_pixel;
6190 if (pixel != -1)
6192 XtSetArg (av[ac], XtNbackground, pixel);
6193 ++ac;
6196 /* Top/bottom shadow colors. */
6198 /* Allocate them, if necessary. */
6199 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1)
6201 pixel = f->output_data.x->scroll_bar_background_pixel;
6202 if (pixel != -1)
6204 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
6205 FRAME_X_COLORMAP (f),
6206 &pixel, 1.2, 0x8000))
6207 pixel = -1;
6208 f->output_data.x->scroll_bar_top_shadow_pixel = pixel;
6211 if (f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
6213 pixel = f->output_data.x->scroll_bar_background_pixel;
6214 if (pixel != -1)
6216 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
6217 FRAME_X_COLORMAP (f),
6218 &pixel, 0.6, 0x4000))
6219 pixel = -1;
6220 f->output_data.x->scroll_bar_bottom_shadow_pixel = pixel;
6224 #ifdef XtNbeNiceToColormap
6225 /* Tell the toolkit about them. */
6226 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1
6227 || f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
6228 /* We tried to allocate a color for the top/bottom shadow, and
6229 failed, so tell Xaw3d to use dithering instead. */
6230 /* But only if we have a small colormap. Xaw3d can allocate nice
6231 colors itself. */
6233 XtSetArg (av[ac], XtNbeNiceToColormap,
6234 DefaultDepthOfScreen (FRAME_X_SCREEN (f)) < 16);
6235 ++ac;
6237 else
6238 /* Tell what colors Xaw3d should use for the top/bottom shadow, to
6239 be more consistent with other emacs 3d colors, and since Xaw3d is
6240 not good at dealing with allocation failure. */
6242 /* This tells Xaw3d to use real colors instead of dithering for
6243 the shadows. */
6244 XtSetArg (av[ac], XtNbeNiceToColormap, False);
6245 ++ac;
6247 /* Specify the colors. */
6248 pixel = f->output_data.x->scroll_bar_top_shadow_pixel;
6249 if (pixel != -1)
6251 XtSetArg (av[ac], XtNtopShadowPixel, pixel);
6252 ++ac;
6254 pixel = f->output_data.x->scroll_bar_bottom_shadow_pixel;
6255 if (pixel != -1)
6257 XtSetArg (av[ac], XtNbottomShadowPixel, pixel);
6258 ++ac;
6261 #endif
6263 widget = XtCreateWidget (scroll_bar_name, scrollbarWidgetClass,
6264 f->output_data.x->edit_widget, av, ac);
6267 char const *initial = "";
6268 char const *val = initial;
6269 XtVaGetValues (widget, XtNscrollVCursor, (XtPointer) &val,
6270 #ifdef XtNarrowScrollbars
6271 XtNarrowScrollbars, (XtPointer) &xaw3d_arrow_scroll,
6272 #endif
6273 XtNpickTop, (XtPointer) &xaw3d_pick_top, NULL);
6274 if (xaw3d_arrow_scroll || val == initial)
6275 { /* ARROW_SCROLL */
6276 xaw3d_arrow_scroll = True;
6277 /* Isn't that just a personal preference ? --Stef */
6278 XtVaSetValues (widget, XtNcursorName, "top_left_arrow", NULL);
6282 /* Define callbacks. */
6283 XtAddCallback (widget, XtNjumpProc, xaw_jump_callback, (XtPointer) bar);
6284 XtAddCallback (widget, XtNscrollProc, xaw_scroll_callback,
6285 (XtPointer) bar);
6287 /* Realize the widget. Only after that is the X window created. */
6288 XtRealizeWidget (widget);
6290 #endif /* !USE_MOTIF */
6292 /* Install an action hook that lets us detect when the user
6293 finishes interacting with a scroll bar. */
6294 if (horizontal_action_hook_id == 0)
6295 horizontal_action_hook_id
6296 = XtAppAddActionHook (Xt_app_con, xt_horizontal_action_hook, 0);
6298 /* Remember X window and widget in the scroll bar vector. */
6299 SET_SCROLL_BAR_X_WIDGET (bar, widget);
6300 xwindow = XtWindow (widget);
6301 bar->x_window = xwindow;
6302 bar->whole = 1;
6303 bar->horizontal = true;
6305 unblock_input ();
6307 #endif /* not USE_GTK */
6310 /* Set the thumb size and position of scroll bar BAR. We are currently
6311 displaying PORTION out of a whole WHOLE, and our position POSITION. */
6313 #ifdef USE_GTK
6314 static void
6315 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position, int whole)
6317 xg_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
6320 static void
6321 x_set_toolkit_horizontal_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position, int whole)
6323 xg_set_toolkit_horizontal_scroll_bar_thumb (bar, portion, position, whole);
6326 #else /* not USE_GTK */
6327 static void
6328 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position,
6329 int whole)
6331 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6332 Widget widget = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
6333 float top, shown;
6335 block_input ();
6337 #ifdef USE_MOTIF
6339 if (scroll_bar_adjust_thumb_portion_p)
6341 /* We use an estimate of 30 chars per line rather than the real
6342 `portion' value. This has the disadvantage that the thumb size
6343 is not very representative, but it makes our life a lot easier.
6344 Otherwise, we have to constantly adjust the thumb size, which
6345 we can't always do quickly enough: while dragging, the size of
6346 the thumb might prevent the user from dragging the thumb all the
6347 way to the end. but Motif and some versions of Xaw3d don't allow
6348 updating the thumb size while dragging. Also, even if we can update
6349 its size, the update will often happen too late.
6350 If you don't believe it, check out revision 1.650 of xterm.c to see
6351 what hoops we were going through and the still poor behavior we got. */
6352 portion = WINDOW_TOTAL_LINES (XWINDOW (bar->window)) * 30;
6353 /* When the thumb is at the bottom, position == whole.
6354 So we need to increase `whole' to make space for the thumb. */
6355 whole += portion;
6358 if (whole <= 0)
6359 top = 0, shown = 1;
6360 else
6362 top = (float) position / whole;
6363 shown = (float) portion / whole;
6366 if (bar->dragging == -1)
6368 int size, value;
6370 /* Slider size. Must be in the range [1 .. MAX - MIN] where MAX
6371 is the scroll bar's maximum and MIN is the scroll bar's minimum
6372 value. */
6373 size = clip_to_bounds (1, shown * XM_SB_MAX, XM_SB_MAX);
6375 /* Position. Must be in the range [MIN .. MAX - SLIDER_SIZE]. */
6376 value = top * XM_SB_MAX;
6377 value = min (value, XM_SB_MAX - size);
6379 XmScrollBarSetValues (widget, value, size, 0, 0, False);
6381 #else /* !USE_MOTIF i.e. use Xaw */
6383 if (whole == 0)
6384 top = 0, shown = 1;
6385 else
6387 top = (float) position / whole;
6388 shown = (float) portion / whole;
6392 float old_top, old_shown;
6393 Dimension height;
6394 XtVaGetValues (widget,
6395 XtNtopOfThumb, &old_top,
6396 XtNshown, &old_shown,
6397 XtNheight, &height,
6398 NULL);
6400 /* Massage the top+shown values. */
6401 if (bar->dragging == -1 || bar->last_seen_part == scroll_bar_down_arrow)
6402 top = max (0, min (1, top));
6403 else
6404 top = old_top;
6405 #if ! defined (HAVE_XAW3D)
6406 /* With Xaw, 'top' values too closer to 1.0 may
6407 cause the thumb to disappear. Fix that. */
6408 top = min (top, 0.99f);
6409 #endif
6410 /* Keep two pixels available for moving the thumb down. */
6411 shown = max (0, min (1 - top - (2.0f / height), shown));
6412 #if ! defined (HAVE_XAW3D)
6413 /* Likewise with too small 'shown'. */
6414 shown = max (shown, 0.01f);
6415 #endif
6417 /* If the call to XawScrollbarSetThumb below doesn't seem to
6418 work, check that 'NARROWPROTO' is defined in src/config.h.
6419 If this is not so, most likely you need to fix configure. */
6420 if (top != old_top || shown != old_shown)
6422 if (bar->dragging == -1)
6423 XawScrollbarSetThumb (widget, top, shown);
6424 else
6426 /* Try to make the scrolling a tad smoother. */
6427 if (!xaw3d_pick_top)
6428 shown = min (shown, old_shown);
6430 XawScrollbarSetThumb (widget, top, shown);
6434 #endif /* !USE_MOTIF */
6436 unblock_input ();
6439 static void
6440 x_set_toolkit_horizontal_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position,
6441 int whole)
6443 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6444 Widget widget = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
6445 float top, shown;
6447 block_input ();
6449 #ifdef USE_MOTIF
6450 bar->whole = whole;
6451 shown = (float) portion / whole;
6452 top = (float) position / (whole - portion);
6454 int size = clip_to_bounds (1, shown * XM_SB_MAX, XM_SB_MAX);
6455 int value = clip_to_bounds (0, top * (XM_SB_MAX - size), XM_SB_MAX - size);
6457 XmScrollBarSetValues (widget, value, size, 0, 0, False);
6459 #else /* !USE_MOTIF i.e. use Xaw */
6460 bar->whole = whole;
6461 if (whole == 0)
6462 top = 0, shown = 1;
6463 else
6465 top = (float) position / whole;
6466 shown = (float) portion / whole;
6470 float old_top, old_shown;
6471 Dimension height;
6472 XtVaGetValues (widget,
6473 XtNtopOfThumb, &old_top,
6474 XtNshown, &old_shown,
6475 XtNheight, &height,
6476 NULL);
6478 #if false
6479 /* Massage the top+shown values. */
6480 if (bar->dragging == -1 || bar->last_seen_part == scroll_bar_down_arrow)
6481 top = max (0, min (1, top));
6482 else
6483 top = old_top;
6484 #if ! defined (HAVE_XAW3D)
6485 /* With Xaw, 'top' values too closer to 1.0 may
6486 cause the thumb to disappear. Fix that. */
6487 top = min (top, 0.99f);
6488 #endif
6489 /* Keep two pixels available for moving the thumb down. */
6490 shown = max (0, min (1 - top - (2.0f / height), shown));
6491 #if ! defined (HAVE_XAW3D)
6492 /* Likewise with too small 'shown'. */
6493 shown = max (shown, 0.01f);
6494 #endif
6495 #endif
6497 /* If the call to XawScrollbarSetThumb below doesn't seem to
6498 work, check that 'NARROWPROTO' is defined in src/config.h.
6499 If this is not so, most likely you need to fix configure. */
6500 XawScrollbarSetThumb (widget, top, shown);
6501 #if false
6502 if (top != old_top || shown != old_shown)
6504 if (bar->dragging == -1)
6505 XawScrollbarSetThumb (widget, top, shown);
6506 else
6508 /* Try to make the scrolling a tad smoother. */
6509 if (!xaw3d_pick_top)
6510 shown = min (shown, old_shown);
6512 XawScrollbarSetThumb (widget, top, shown);
6515 #endif
6517 #endif /* !USE_MOTIF */
6519 unblock_input ();
6521 #endif /* not USE_GTK */
6523 #endif /* USE_TOOLKIT_SCROLL_BARS */
6527 /************************************************************************
6528 Scroll bars, general
6529 ************************************************************************/
6531 /* Create a scroll bar and return the scroll bar vector for it. W is
6532 the Emacs window on which to create the scroll bar. TOP, LEFT,
6533 WIDTH and HEIGHT are the pixel coordinates and dimensions of the
6534 scroll bar. */
6536 static struct scroll_bar *
6537 x_scroll_bar_create (struct window *w, int top, int left,
6538 int width, int height, bool horizontal)
6540 struct frame *f = XFRAME (w->frame);
6541 struct scroll_bar *bar
6542 = ALLOCATE_PSEUDOVECTOR (struct scroll_bar, x_window, PVEC_OTHER);
6543 Lisp_Object barobj;
6545 block_input ();
6547 #ifdef USE_TOOLKIT_SCROLL_BARS
6548 if (horizontal)
6549 x_create_horizontal_toolkit_scroll_bar (f, bar);
6550 else
6551 x_create_toolkit_scroll_bar (f, bar);
6552 #else /* not USE_TOOLKIT_SCROLL_BARS */
6554 XSetWindowAttributes a;
6555 unsigned long mask;
6556 Window window;
6558 a.background_pixel = f->output_data.x->scroll_bar_background_pixel;
6559 if (a.background_pixel == -1)
6560 a.background_pixel = FRAME_BACKGROUND_PIXEL (f);
6562 a.event_mask = (ButtonPressMask | ButtonReleaseMask
6563 | ButtonMotionMask | PointerMotionHintMask
6564 | ExposureMask);
6565 a.cursor = FRAME_DISPLAY_INFO (f)->vertical_scroll_bar_cursor;
6567 mask = (CWBackPixel | CWEventMask | CWCursor);
6569 /* Clear the area of W that will serve as a scroll bar. This is
6570 for the case that a window has been split horizontally. In
6571 this case, no clear_frame is generated to reduce flickering. */
6572 if (width > 0 && window_box_height (w) > 0)
6573 x_clear_area (f, left, top, width, window_box_height (w));
6575 window = XCreateWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
6576 /* Position and size of scroll bar. */
6577 left, top, width, height,
6578 /* Border width, depth, class, and visual. */
6580 CopyFromParent,
6581 CopyFromParent,
6582 CopyFromParent,
6583 /* Attributes. */
6584 mask, &a);
6585 bar->x_window = window;
6587 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6589 XSETWINDOW (bar->window, w);
6590 bar->top = top;
6591 bar->left = left;
6592 bar->width = width;
6593 bar->height = height;
6594 bar->start = 0;
6595 bar->end = 0;
6596 bar->dragging = -1;
6597 bar->horizontal = horizontal;
6598 #if defined (USE_TOOLKIT_SCROLL_BARS) && defined (USE_LUCID)
6599 bar->last_seen_part = scroll_bar_nowhere;
6600 #endif
6602 /* Add bar to its frame's list of scroll bars. */
6603 bar->next = FRAME_SCROLL_BARS (f);
6604 bar->prev = Qnil;
6605 XSETVECTOR (barobj, bar);
6606 fset_scroll_bars (f, barobj);
6607 if (!NILP (bar->next))
6608 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
6610 /* Map the window/widget. */
6611 #ifdef USE_TOOLKIT_SCROLL_BARS
6613 #ifdef USE_GTK
6614 if (horizontal)
6615 xg_update_horizontal_scrollbar_pos (f, bar->x_window, top,
6616 left, width, max (height, 1));
6617 else
6618 xg_update_scrollbar_pos (f, bar->x_window, top,
6619 left, width, max (height, 1));
6620 #else /* not USE_GTK */
6621 Widget scroll_bar = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
6622 XtConfigureWidget (scroll_bar, left, top, width, max (height, 1), 0);
6623 XtMapWidget (scroll_bar);
6624 /* Don't obscure any child frames. */
6625 XLowerWindow (FRAME_X_DISPLAY (f), bar->x_window);
6626 #endif /* not USE_GTK */
6628 #else /* not USE_TOOLKIT_SCROLL_BARS */
6629 XMapWindow (FRAME_X_DISPLAY (f), bar->x_window);
6630 /* Don't obscure any child frames. */
6631 XLowerWindow (FRAME_X_DISPLAY (f), bar->x_window);
6632 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6634 unblock_input ();
6635 return bar;
6639 #ifndef USE_TOOLKIT_SCROLL_BARS
6641 /* Draw BAR's handle in the proper position.
6643 If the handle is already drawn from START to END, don't bother
6644 redrawing it, unless REBUILD; in that case, always
6645 redraw it. (REBUILD is handy for drawing the handle after expose
6646 events.)
6648 Normally, we want to constrain the start and end of the handle to
6649 fit inside its rectangle, but if the user is dragging the scroll
6650 bar handle, we want to let them drag it down all the way, so that
6651 the bar's top is as far down as it goes; otherwise, there's no way
6652 to move to the very end of the buffer. */
6654 static void
6655 x_scroll_bar_set_handle (struct scroll_bar *bar, int start, int end,
6656 bool rebuild)
6658 bool dragging = bar->dragging != -1;
6659 Window w = bar->x_window;
6660 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6661 GC gc = f->output_data.x->normal_gc;
6663 /* If the display is already accurate, do nothing. */
6664 if (! rebuild
6665 && start == bar->start
6666 && end == bar->end)
6667 return;
6669 block_input ();
6672 int inside_width = VERTICAL_SCROLL_BAR_INSIDE_WIDTH (f, bar->width);
6673 int inside_height = VERTICAL_SCROLL_BAR_INSIDE_HEIGHT (f, bar->height);
6674 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
6676 /* Make sure the values are reasonable, and try to preserve
6677 the distance between start and end. */
6679 int length = end - start;
6681 if (start < 0)
6682 start = 0;
6683 else if (start > top_range)
6684 start = top_range;
6685 end = start + length;
6687 if (end < start)
6688 end = start;
6689 else if (end > top_range && ! dragging)
6690 end = top_range;
6693 /* Store the adjusted setting in the scroll bar. */
6694 bar->start = start;
6695 bar->end = end;
6697 /* Clip the end position, just for display. */
6698 if (end > top_range)
6699 end = top_range;
6701 /* Draw bottom positions VERTICAL_SCROLL_BAR_MIN_HANDLE pixels
6702 below top positions, to make sure the handle is always at least
6703 that many pixels tall. */
6704 end += VERTICAL_SCROLL_BAR_MIN_HANDLE;
6706 /* Draw the empty space above the handle. Note that we can't clear
6707 zero-height areas; that means "clear to end of window." */
6708 if ((inside_width > 0) && (start > 0))
6709 x_clear_area1 (FRAME_X_DISPLAY (f), w,
6710 VERTICAL_SCROLL_BAR_LEFT_BORDER,
6711 VERTICAL_SCROLL_BAR_TOP_BORDER,
6712 inside_width, start, False);
6714 /* Change to proper foreground color if one is specified. */
6715 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
6716 XSetForeground (FRAME_X_DISPLAY (f), gc,
6717 f->output_data.x->scroll_bar_foreground_pixel);
6719 /* Draw the handle itself. */
6720 XFillRectangle (FRAME_X_DISPLAY (f), w, gc,
6721 /* x, y, width, height */
6722 VERTICAL_SCROLL_BAR_LEFT_BORDER,
6723 VERTICAL_SCROLL_BAR_TOP_BORDER + start,
6724 inside_width, end - start);
6726 /* Restore the foreground color of the GC if we changed it above. */
6727 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
6728 XSetForeground (FRAME_X_DISPLAY (f), gc,
6729 FRAME_FOREGROUND_PIXEL (f));
6731 /* Draw the empty space below the handle. Note that we can't
6732 clear zero-height areas; that means "clear to end of window." */
6733 if ((inside_width > 0) && (end < inside_height))
6734 x_clear_area1 (FRAME_X_DISPLAY (f), w,
6735 VERTICAL_SCROLL_BAR_LEFT_BORDER,
6736 VERTICAL_SCROLL_BAR_TOP_BORDER + end,
6737 inside_width, inside_height - end, False);
6740 unblock_input ();
6743 #endif /* !USE_TOOLKIT_SCROLL_BARS */
6745 /* Destroy scroll bar BAR, and set its Emacs window's scroll bar to
6746 nil. */
6748 static void
6749 x_scroll_bar_remove (struct scroll_bar *bar)
6751 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6752 block_input ();
6754 #ifdef USE_TOOLKIT_SCROLL_BARS
6755 #ifdef USE_GTK
6756 xg_remove_scroll_bar (f, bar->x_window);
6757 #else /* not USE_GTK */
6758 XtDestroyWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar));
6759 #endif /* not USE_GTK */
6760 #else
6761 XDestroyWindow (FRAME_X_DISPLAY (f), bar->x_window);
6762 #endif
6764 /* Dissociate this scroll bar from its window. */
6765 if (bar->horizontal)
6766 wset_horizontal_scroll_bar (XWINDOW (bar->window), Qnil);
6767 else
6768 wset_vertical_scroll_bar (XWINDOW (bar->window), Qnil);
6770 unblock_input ();
6774 /* Set the handle of the vertical scroll bar for WINDOW to indicate
6775 that we are displaying PORTION characters out of a total of WHOLE
6776 characters, starting at POSITION. If WINDOW has no scroll bar,
6777 create one. */
6779 static void
6780 XTset_vertical_scroll_bar (struct window *w, int portion, int whole, int position)
6782 struct frame *f = XFRAME (w->frame);
6783 Lisp_Object barobj;
6784 struct scroll_bar *bar;
6785 int top, height, left, width;
6786 int window_y, window_height;
6788 /* Get window dimensions. */
6789 window_box (w, ANY_AREA, 0, &window_y, 0, &window_height);
6790 top = window_y;
6791 height = window_height;
6792 left = WINDOW_SCROLL_BAR_AREA_X (w);
6793 width = WINDOW_SCROLL_BAR_AREA_WIDTH (w);
6795 /* Does the scroll bar exist yet? */
6796 if (NILP (w->vertical_scroll_bar))
6798 if (width > 0 && height > 0)
6800 block_input ();
6801 x_clear_area (f, left, top, width, height);
6802 unblock_input ();
6805 bar = x_scroll_bar_create (w, top, left, width, max (height, 1), false);
6807 else
6809 /* It may just need to be moved and resized. */
6810 unsigned int mask = 0;
6812 bar = XSCROLL_BAR (w->vertical_scroll_bar);
6814 block_input ();
6816 if (left != bar->left)
6817 mask |= CWX;
6818 if (top != bar->top)
6819 mask |= CWY;
6820 if (width != bar->width)
6821 mask |= CWWidth;
6822 if (height != bar->height)
6823 mask |= CWHeight;
6825 #ifdef USE_TOOLKIT_SCROLL_BARS
6827 /* Move/size the scroll bar widget. */
6828 if (mask)
6830 /* Since toolkit scroll bars are smaller than the space reserved
6831 for them on the frame, we have to clear "under" them. */
6832 if (width > 0 && height > 0)
6833 x_clear_area (f, left, top, width, height);
6834 #ifdef USE_GTK
6835 xg_update_scrollbar_pos (f, bar->x_window, top,
6836 left, width, max (height, 1));
6837 #else /* not USE_GTK */
6838 XtConfigureWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar),
6839 left, top, width, max (height, 1), 0);
6840 #endif /* not USE_GTK */
6842 #else /* not USE_TOOLKIT_SCROLL_BARS */
6844 /* Move/size the scroll bar window. */
6845 if (mask)
6847 XWindowChanges wc;
6849 wc.x = left;
6850 wc.y = top;
6851 wc.width = width;
6852 wc.height = height;
6853 XConfigureWindow (FRAME_X_DISPLAY (f), bar->x_window,
6854 mask, &wc);
6857 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6859 /* Remember new settings. */
6860 bar->left = left;
6861 bar->top = top;
6862 bar->width = width;
6863 bar->height = height;
6865 unblock_input ();
6868 #ifdef USE_TOOLKIT_SCROLL_BARS
6869 x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
6870 #else /* not USE_TOOLKIT_SCROLL_BARS */
6871 /* Set the scroll bar's current state, unless we're currently being
6872 dragged. */
6873 if (bar->dragging == -1)
6875 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, height);
6877 if (whole == 0)
6878 x_scroll_bar_set_handle (bar, 0, top_range, false);
6879 else
6881 int start = ((double) position * top_range) / whole;
6882 int end = ((double) (position + portion) * top_range) / whole;
6883 x_scroll_bar_set_handle (bar, start, end, false);
6886 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6888 XSETVECTOR (barobj, bar);
6889 wset_vertical_scroll_bar (w, barobj);
6893 static void
6894 XTset_horizontal_scroll_bar (struct window *w, int portion, int whole, int position)
6896 struct frame *f = XFRAME (w->frame);
6897 Lisp_Object barobj;
6898 struct scroll_bar *bar;
6899 int top, height, left, width;
6900 int window_x, window_width;
6901 int pixel_width = WINDOW_PIXEL_WIDTH (w);
6903 /* Get window dimensions. */
6904 window_box (w, ANY_AREA, &window_x, 0, &window_width, 0);
6905 left = window_x;
6906 width = window_width;
6907 top = WINDOW_SCROLL_BAR_AREA_Y (w);
6908 height = WINDOW_SCROLL_BAR_AREA_HEIGHT (w);
6910 /* Does the scroll bar exist yet? */
6911 if (NILP (w->horizontal_scroll_bar))
6913 if (width > 0 && height > 0)
6915 block_input ();
6917 /* Clear also part between window_width and
6918 WINDOW_PIXEL_WIDTH. */
6919 x_clear_area (f, left, top, pixel_width, height);
6920 unblock_input ();
6923 bar = x_scroll_bar_create (w, top, left, width, height, true);
6925 else
6927 /* It may just need to be moved and resized. */
6928 unsigned int mask = 0;
6930 bar = XSCROLL_BAR (w->horizontal_scroll_bar);
6932 block_input ();
6934 if (left != bar->left)
6935 mask |= CWX;
6936 if (top != bar->top)
6937 mask |= CWY;
6938 if (width != bar->width)
6939 mask |= CWWidth;
6940 if (height != bar->height)
6941 mask |= CWHeight;
6943 #ifdef USE_TOOLKIT_SCROLL_BARS
6944 /* Move/size the scroll bar widget. */
6945 if (mask)
6947 /* Since toolkit scroll bars are smaller than the space reserved
6948 for them on the frame, we have to clear "under" them. */
6949 if (width > 0 && height > 0)
6950 x_clear_area (f,
6951 WINDOW_LEFT_EDGE_X (w), top,
6952 pixel_width - WINDOW_RIGHT_DIVIDER_WIDTH (w), height);
6953 #ifdef USE_GTK
6954 xg_update_horizontal_scrollbar_pos (f, bar->x_window, top, left,
6955 width, height);
6956 #else /* not USE_GTK */
6957 XtConfigureWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar),
6958 left, top, width, height, 0);
6959 #endif /* not USE_GTK */
6961 #else /* not USE_TOOLKIT_SCROLL_BARS */
6963 /* Clear areas not covered by the scroll bar because it's not as
6964 wide as the area reserved for it. This makes sure a
6965 previous mode line display is cleared after C-x 2 C-x 1, for
6966 example. */
6968 int area_height = WINDOW_CONFIG_SCROLL_BAR_HEIGHT (w);
6969 int rest = area_height - height;
6970 if (rest > 0 && width > 0)
6971 x_clear_area (f, left, top, width, rest);
6974 /* Move/size the scroll bar window. */
6975 if (mask)
6977 XWindowChanges wc;
6979 wc.x = left;
6980 wc.y = top;
6981 wc.width = width;
6982 wc.height = height;
6983 XConfigureWindow (FRAME_X_DISPLAY (f), bar->x_window,
6984 mask, &wc);
6987 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6989 /* Remember new settings. */
6990 bar->left = left;
6991 bar->top = top;
6992 bar->width = width;
6993 bar->height = height;
6995 unblock_input ();
6998 #ifdef USE_TOOLKIT_SCROLL_BARS
6999 x_set_toolkit_horizontal_scroll_bar_thumb (bar, portion, position, whole);
7000 #else /* not USE_TOOLKIT_SCROLL_BARS */
7001 /* Set the scroll bar's current state, unless we're currently being
7002 dragged. */
7003 if (bar->dragging == -1)
7005 int left_range = HORIZONTAL_SCROLL_BAR_LEFT_RANGE (f, width);
7007 if (whole == 0)
7008 x_scroll_bar_set_handle (bar, 0, left_range, false);
7009 else
7011 int start = ((double) position * left_range) / whole;
7012 int end = ((double) (position + portion) * left_range) / whole;
7013 x_scroll_bar_set_handle (bar, start, end, false);
7016 #endif /* not USE_TOOLKIT_SCROLL_BARS */
7018 XSETVECTOR (barobj, bar);
7019 wset_horizontal_scroll_bar (w, barobj);
7023 /* The following three hooks are used when we're doing a thorough
7024 redisplay of the frame. We don't explicitly know which scroll bars
7025 are going to be deleted, because keeping track of when windows go
7026 away is a real pain - "Can you say set-window-configuration, boys
7027 and girls?" Instead, we just assert at the beginning of redisplay
7028 that *all* scroll bars are to be removed, and then save a scroll bar
7029 from the fiery pit when we actually redisplay its window. */
7031 /* Arrange for all scroll bars on FRAME to be removed at the next call
7032 to `*judge_scroll_bars_hook'. A scroll bar may be spared if
7033 `*redeem_scroll_bar_hook' is applied to its window before the judgment. */
7035 static void
7036 XTcondemn_scroll_bars (struct frame *frame)
7038 if (!NILP (FRAME_SCROLL_BARS (frame)))
7040 if (!NILP (FRAME_CONDEMNED_SCROLL_BARS (frame)))
7042 /* Prepend scrollbars to already condemned ones. */
7043 Lisp_Object last = FRAME_SCROLL_BARS (frame);
7045 while (!NILP (XSCROLL_BAR (last)->next))
7046 last = XSCROLL_BAR (last)->next;
7048 XSCROLL_BAR (last)->next = FRAME_CONDEMNED_SCROLL_BARS (frame);
7049 XSCROLL_BAR (FRAME_CONDEMNED_SCROLL_BARS (frame))->prev = last;
7052 fset_condemned_scroll_bars (frame, FRAME_SCROLL_BARS (frame));
7053 fset_scroll_bars (frame, Qnil);
7058 /* Un-mark WINDOW's scroll bar for deletion in this judgment cycle.
7059 Note that WINDOW isn't necessarily condemned at all. */
7061 static void
7062 XTredeem_scroll_bar (struct window *w)
7064 struct scroll_bar *bar;
7065 Lisp_Object barobj;
7066 struct frame *f;
7068 /* We can't redeem this window's scroll bar if it doesn't have one. */
7069 if (NILP (w->vertical_scroll_bar) && NILP (w->horizontal_scroll_bar))
7070 emacs_abort ();
7072 if (!NILP (w->vertical_scroll_bar) && WINDOW_HAS_VERTICAL_SCROLL_BAR (w))
7074 bar = XSCROLL_BAR (w->vertical_scroll_bar);
7075 /* Unlink it from the condemned list. */
7076 f = XFRAME (WINDOW_FRAME (w));
7077 if (NILP (bar->prev))
7079 /* If the prev pointer is nil, it must be the first in one of
7080 the lists. */
7081 if (EQ (FRAME_SCROLL_BARS (f), w->vertical_scroll_bar))
7082 /* It's not condemned. Everything's fine. */
7083 goto horizontal;
7084 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
7085 w->vertical_scroll_bar))
7086 fset_condemned_scroll_bars (f, bar->next);
7087 else
7088 /* If its prev pointer is nil, it must be at the front of
7089 one or the other! */
7090 emacs_abort ();
7092 else
7093 XSCROLL_BAR (bar->prev)->next = bar->next;
7095 if (! NILP (bar->next))
7096 XSCROLL_BAR (bar->next)->prev = bar->prev;
7098 bar->next = FRAME_SCROLL_BARS (f);
7099 bar->prev = Qnil;
7100 XSETVECTOR (barobj, bar);
7101 fset_scroll_bars (f, barobj);
7102 if (! NILP (bar->next))
7103 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
7106 horizontal:
7107 if (!NILP (w->horizontal_scroll_bar) && WINDOW_HAS_HORIZONTAL_SCROLL_BAR (w))
7109 bar = XSCROLL_BAR (w->horizontal_scroll_bar);
7110 /* Unlink it from the condemned list. */
7111 f = XFRAME (WINDOW_FRAME (w));
7112 if (NILP (bar->prev))
7114 /* If the prev pointer is nil, it must be the first in one of
7115 the lists. */
7116 if (EQ (FRAME_SCROLL_BARS (f), w->horizontal_scroll_bar))
7117 /* It's not condemned. Everything's fine. */
7118 return;
7119 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
7120 w->horizontal_scroll_bar))
7121 fset_condemned_scroll_bars (f, bar->next);
7122 else
7123 /* If its prev pointer is nil, it must be at the front of
7124 one or the other! */
7125 emacs_abort ();
7127 else
7128 XSCROLL_BAR (bar->prev)->next = bar->next;
7130 if (! NILP (bar->next))
7131 XSCROLL_BAR (bar->next)->prev = bar->prev;
7133 bar->next = FRAME_SCROLL_BARS (f);
7134 bar->prev = Qnil;
7135 XSETVECTOR (barobj, bar);
7136 fset_scroll_bars (f, barobj);
7137 if (! NILP (bar->next))
7138 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
7142 /* Remove all scroll bars on FRAME that haven't been saved since the
7143 last call to `*condemn_scroll_bars_hook'. */
7145 static void
7146 XTjudge_scroll_bars (struct frame *f)
7148 Lisp_Object bar, next;
7150 bar = FRAME_CONDEMNED_SCROLL_BARS (f);
7152 /* Clear out the condemned list now so we won't try to process any
7153 more events on the hapless scroll bars. */
7154 fset_condemned_scroll_bars (f, Qnil);
7156 for (; ! NILP (bar); bar = next)
7158 struct scroll_bar *b = XSCROLL_BAR (bar);
7160 x_scroll_bar_remove (b);
7162 next = b->next;
7163 b->next = b->prev = Qnil;
7166 /* Now there should be no references to the condemned scroll bars,
7167 and they should get garbage-collected. */
7171 #ifndef USE_TOOLKIT_SCROLL_BARS
7172 /* Handle an Expose or GraphicsExpose event on a scroll bar. This
7173 is a no-op when using toolkit scroll bars.
7175 This may be called from a signal handler, so we have to ignore GC
7176 mark bits. */
7178 static void
7179 x_scroll_bar_expose (struct scroll_bar *bar, const XEvent *event)
7181 Window w = bar->x_window;
7182 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
7183 GC gc = f->output_data.x->normal_gc;
7185 block_input ();
7187 x_scroll_bar_set_handle (bar, bar->start, bar->end, true);
7189 /* Switch to scroll bar foreground color. */
7190 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
7191 XSetForeground (FRAME_X_DISPLAY (f), gc,
7192 f->output_data.x->scroll_bar_foreground_pixel);
7194 /* Draw a one-pixel border just inside the edges of the scroll bar. */
7195 XDrawRectangle (FRAME_X_DISPLAY (f), w, gc,
7196 /* x, y, width, height */
7197 0, 0, bar->width - 1, bar->height - 1);
7199 /* Restore the foreground color of the GC if we changed it above. */
7200 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
7201 XSetForeground (FRAME_X_DISPLAY (f), gc,
7202 FRAME_FOREGROUND_PIXEL (f));
7204 unblock_input ();
7207 #endif /* not USE_TOOLKIT_SCROLL_BARS */
7209 /* Handle a mouse click on the scroll bar BAR. If *EMACS_EVENT's kind
7210 is set to something other than NO_EVENT, it is enqueued.
7212 This may be called from a signal handler, so we have to ignore GC
7213 mark bits. */
7216 static void
7217 x_scroll_bar_handle_click (struct scroll_bar *bar,
7218 const XEvent *event,
7219 struct input_event *emacs_event)
7221 if (! WINDOWP (bar->window))
7222 emacs_abort ();
7224 emacs_event->kind = (bar->horizontal
7225 ? HORIZONTAL_SCROLL_BAR_CLICK_EVENT
7226 : SCROLL_BAR_CLICK_EVENT);
7227 emacs_event->code = event->xbutton.button - Button1;
7228 emacs_event->modifiers
7229 = (x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO
7230 (XFRAME (WINDOW_FRAME (XWINDOW (bar->window)))),
7231 event->xbutton.state)
7232 | (event->type == ButtonRelease
7233 ? up_modifier
7234 : down_modifier));
7235 emacs_event->frame_or_window = bar->window;
7236 emacs_event->arg = Qnil;
7237 emacs_event->timestamp = event->xbutton.time;
7238 if (bar->horizontal)
7240 int left_range
7241 = HORIZONTAL_SCROLL_BAR_LEFT_RANGE (f, bar->width);
7242 int x = event->xbutton.x - HORIZONTAL_SCROLL_BAR_LEFT_BORDER;
7244 if (x < 0) x = 0;
7245 if (x > left_range) x = left_range;
7247 if (x < bar->start)
7248 emacs_event->part = scroll_bar_before_handle;
7249 else if (x < bar->end + HORIZONTAL_SCROLL_BAR_MIN_HANDLE)
7250 emacs_event->part = scroll_bar_horizontal_handle;
7251 else
7252 emacs_event->part = scroll_bar_after_handle;
7254 #ifndef USE_TOOLKIT_SCROLL_BARS
7255 /* If the user has released the handle, set it to its final position. */
7256 if (event->type == ButtonRelease && bar->dragging != -1)
7258 int new_start = - bar->dragging;
7259 int new_end = new_start + bar->end - bar->start;
7261 x_scroll_bar_set_handle (bar, new_start, new_end, false);
7262 bar->dragging = -1;
7264 #endif
7266 XSETINT (emacs_event->x, left_range);
7267 XSETINT (emacs_event->y, x);
7269 else
7271 int top_range
7272 = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
7273 int y = event->xbutton.y - VERTICAL_SCROLL_BAR_TOP_BORDER;
7275 if (y < 0) y = 0;
7276 if (y > top_range) y = top_range;
7278 if (y < bar->start)
7279 emacs_event->part = scroll_bar_above_handle;
7280 else if (y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
7281 emacs_event->part = scroll_bar_handle;
7282 else
7283 emacs_event->part = scroll_bar_below_handle;
7285 #ifndef USE_TOOLKIT_SCROLL_BARS
7286 /* If the user has released the handle, set it to its final position. */
7287 if (event->type == ButtonRelease && bar->dragging != -1)
7289 int new_start = y - bar->dragging;
7290 int new_end = new_start + bar->end - bar->start;
7292 x_scroll_bar_set_handle (bar, new_start, new_end, false);
7293 bar->dragging = -1;
7295 #endif
7297 XSETINT (emacs_event->x, y);
7298 XSETINT (emacs_event->y, top_range);
7302 #ifndef USE_TOOLKIT_SCROLL_BARS
7304 /* Handle some mouse motion while someone is dragging the scroll bar.
7306 This may be called from a signal handler, so we have to ignore GC
7307 mark bits. */
7309 static void
7310 x_scroll_bar_note_movement (struct scroll_bar *bar,
7311 const XMotionEvent *event)
7313 struct frame *f = XFRAME (XWINDOW (bar->window)->frame);
7314 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
7316 dpyinfo->last_mouse_movement_time = event->time;
7317 dpyinfo->last_mouse_scroll_bar = bar;
7318 f->mouse_moved = true;
7320 /* If we're dragging the bar, display it. */
7321 if (bar->dragging != -1)
7323 /* Where should the handle be now? */
7324 int new_start = event->y - bar->dragging;
7326 if (new_start != bar->start)
7328 int new_end = new_start + bar->end - bar->start;
7330 x_scroll_bar_set_handle (bar, new_start, new_end, false);
7335 #endif /* !USE_TOOLKIT_SCROLL_BARS */
7337 /* Return information to the user about the current position of the mouse
7338 on the scroll bar. */
7340 static void
7341 x_scroll_bar_report_motion (struct frame **fp, Lisp_Object *bar_window,
7342 enum scroll_bar_part *part, Lisp_Object *x,
7343 Lisp_Object *y, Time *timestamp)
7345 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (*fp);
7346 struct scroll_bar *bar = dpyinfo->last_mouse_scroll_bar;
7347 Window w = bar->x_window;
7348 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
7349 int win_x, win_y;
7350 Window dummy_window;
7351 int dummy_coord;
7352 unsigned int dummy_mask;
7354 block_input ();
7356 /* Get the mouse's position relative to the scroll bar window, and
7357 report that. */
7358 if (XQueryPointer (FRAME_X_DISPLAY (f), w,
7360 /* Root, child, root x and root y. */
7361 &dummy_window, &dummy_window,
7362 &dummy_coord, &dummy_coord,
7364 /* Position relative to scroll bar. */
7365 &win_x, &win_y,
7367 /* Mouse buttons and modifier keys. */
7368 &dummy_mask))
7370 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
7372 win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
7374 if (bar->dragging != -1)
7375 win_y -= bar->dragging;
7377 if (win_y < 0)
7378 win_y = 0;
7379 if (win_y > top_range)
7380 win_y = top_range;
7382 *fp = f;
7383 *bar_window = bar->window;
7385 if (bar->dragging != -1)
7386 *part = scroll_bar_handle;
7387 else if (win_y < bar->start)
7388 *part = scroll_bar_above_handle;
7389 else if (win_y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
7390 *part = scroll_bar_handle;
7391 else
7392 *part = scroll_bar_below_handle;
7394 XSETINT (*x, win_y);
7395 XSETINT (*y, top_range);
7397 f->mouse_moved = false;
7398 dpyinfo->last_mouse_scroll_bar = NULL;
7399 *timestamp = dpyinfo->last_mouse_movement_time;
7402 unblock_input ();
7406 /* Return information to the user about the current position of the mouse
7407 on the scroll bar. */
7409 static void
7410 x_horizontal_scroll_bar_report_motion (struct frame **fp, Lisp_Object *bar_window,
7411 enum scroll_bar_part *part, Lisp_Object *x,
7412 Lisp_Object *y, Time *timestamp)
7414 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (*fp);
7415 struct scroll_bar *bar = dpyinfo->last_mouse_scroll_bar;
7416 Window w = bar->x_window;
7417 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
7418 int win_x, win_y;
7419 Window dummy_window;
7420 int dummy_coord;
7421 unsigned int dummy_mask;
7423 block_input ();
7425 /* Get the mouse's position relative to the scroll bar window, and
7426 report that. */
7427 if (XQueryPointer (FRAME_X_DISPLAY (f), w,
7429 /* Root, child, root x and root y. */
7430 &dummy_window, &dummy_window,
7431 &dummy_coord, &dummy_coord,
7433 /* Position relative to scroll bar. */
7434 &win_x, &win_y,
7436 /* Mouse buttons and modifier keys. */
7437 &dummy_mask))
7439 int left_range = HORIZONTAL_SCROLL_BAR_LEFT_RANGE (f, bar->width);
7441 win_x -= HORIZONTAL_SCROLL_BAR_LEFT_BORDER;
7443 if (bar->dragging != -1)
7444 win_x -= bar->dragging;
7446 if (win_x < 0)
7447 win_x = 0;
7448 if (win_x > left_range)
7449 win_x = left_range;
7451 *fp = f;
7452 *bar_window = bar->window;
7454 if (bar->dragging != -1)
7455 *part = scroll_bar_horizontal_handle;
7456 else if (win_x < bar->start)
7457 *part = scroll_bar_before_handle;
7458 else if (win_x < bar->end + HORIZONTAL_SCROLL_BAR_MIN_HANDLE)
7459 *part = scroll_bar_handle;
7460 else
7461 *part = scroll_bar_after_handle;
7463 XSETINT (*y, win_x);
7464 XSETINT (*x, left_range);
7466 f->mouse_moved = false;
7467 dpyinfo->last_mouse_scroll_bar = NULL;
7468 *timestamp = dpyinfo->last_mouse_movement_time;
7471 unblock_input ();
7475 /* The screen has been cleared so we may have changed foreground or
7476 background colors, and the scroll bars may need to be redrawn.
7477 Clear out the scroll bars, and ask for expose events, so we can
7478 redraw them. */
7480 static void
7481 x_scroll_bar_clear (struct frame *f)
7483 #ifndef USE_TOOLKIT_SCROLL_BARS
7484 Lisp_Object bar;
7486 /* We can have scroll bars even if this is 0,
7487 if we just turned off scroll bar mode.
7488 But in that case we should not clear them. */
7489 if (FRAME_HAS_VERTICAL_SCROLL_BARS (f))
7490 for (bar = FRAME_SCROLL_BARS (f); VECTORP (bar);
7491 bar = XSCROLL_BAR (bar)->next)
7492 XClearArea (FRAME_X_DISPLAY (f),
7493 XSCROLL_BAR (bar)->x_window,
7494 0, 0, 0, 0, True);
7495 #endif /* not USE_TOOLKIT_SCROLL_BARS */
7498 #ifdef ENABLE_CHECKING
7500 /* Record the last 100 characters stored
7501 to help debug the loss-of-chars-during-GC problem. */
7503 static int temp_index;
7504 static short temp_buffer[100];
7506 #define STORE_KEYSYM_FOR_DEBUG(keysym) \
7507 if (temp_index == ARRAYELTS (temp_buffer)) \
7508 temp_index = 0; \
7509 temp_buffer[temp_index++] = (keysym)
7511 #else /* not ENABLE_CHECKING */
7513 #define STORE_KEYSYM_FOR_DEBUG(keysym) ((void)0)
7515 #endif /* ENABLE_CHECKING */
7517 /* Set this to nonzero to fake an "X I/O error"
7518 on a particular display. */
7520 static struct x_display_info *XTread_socket_fake_io_error;
7522 /* When we find no input here, we occasionally do a no-op command
7523 to verify that the X server is still running and we can still talk with it.
7524 We try all the open displays, one by one.
7525 This variable is used for cycling thru the displays. */
7527 static struct x_display_info *next_noop_dpyinfo;
7529 enum
7531 X_EVENT_NORMAL,
7532 X_EVENT_GOTO_OUT,
7533 X_EVENT_DROP
7536 /* Filter events for the current X input method.
7537 DPYINFO is the display this event is for.
7538 EVENT is the X event to filter.
7540 Returns non-zero if the event was filtered, caller shall not process
7541 this event further.
7542 Returns zero if event is wasn't filtered. */
7544 #ifdef HAVE_X_I18N
7545 static int
7546 x_filter_event (struct x_display_info *dpyinfo, XEvent *event)
7548 /* XFilterEvent returns non-zero if the input method has
7549 consumed the event. We pass the frame's X window to
7550 XFilterEvent because that's the one for which the IC
7551 was created. */
7553 struct frame *f1 = x_any_window_to_frame (dpyinfo,
7554 event->xclient.window);
7556 return XFilterEvent (event, f1 ? FRAME_X_WINDOW (f1) : None);
7558 #endif
7560 #ifdef USE_GTK
7561 static int current_count;
7562 static int current_finish;
7563 static struct input_event *current_hold_quit;
7565 /* This is the filter function invoked by the GTK event loop.
7566 It is invoked before the XEvent is translated to a GdkEvent,
7567 so we have a chance to act on the event before GTK. */
7568 static GdkFilterReturn
7569 event_handler_gdk (GdkXEvent *gxev, GdkEvent *ev, gpointer data)
7571 XEvent *xev = (XEvent *) gxev;
7573 block_input ();
7574 if (current_count >= 0)
7576 struct x_display_info *dpyinfo;
7578 dpyinfo = x_display_info_for_display (xev->xany.display);
7580 #ifdef HAVE_X_I18N
7581 /* Filter events for the current X input method.
7582 GTK calls XFilterEvent but not for key press and release,
7583 so we do it here. */
7584 if ((xev->type == KeyPress || xev->type == KeyRelease)
7585 && dpyinfo
7586 && x_filter_event (dpyinfo, xev))
7588 unblock_input ();
7589 return GDK_FILTER_REMOVE;
7591 #endif
7593 if (! dpyinfo)
7594 current_finish = X_EVENT_NORMAL;
7595 else
7596 current_count
7597 += handle_one_xevent (dpyinfo, xev, &current_finish,
7598 current_hold_quit);
7600 else
7601 current_finish = x_dispatch_event (xev, xev->xany.display);
7603 unblock_input ();
7605 if (current_finish == X_EVENT_GOTO_OUT || current_finish == X_EVENT_DROP)
7606 return GDK_FILTER_REMOVE;
7608 return GDK_FILTER_CONTINUE;
7610 #endif /* USE_GTK */
7613 static void xembed_send_message (struct frame *f, Time,
7614 enum xembed_message,
7615 long detail, long data1, long data2);
7617 static void
7618 x_net_wm_state (struct frame *f, Window window)
7620 int value = FULLSCREEN_NONE;
7621 Lisp_Object lval = Qnil;
7622 bool sticky = false;
7624 get_current_wm_state (f, window, &value, &sticky);
7626 switch (value)
7628 case FULLSCREEN_WIDTH:
7629 lval = Qfullwidth;
7630 break;
7631 case FULLSCREEN_HEIGHT:
7632 lval = Qfullheight;
7633 break;
7634 case FULLSCREEN_BOTH:
7635 lval = Qfullboth;
7636 break;
7637 case FULLSCREEN_MAXIMIZED:
7638 lval = Qmaximized;
7639 break;
7642 frame_size_history_add
7643 (f, Qx_net_wm_state, 0, 0,
7644 list2 (get_frame_param (f, Qfullscreen), lval));
7646 store_frame_param (f, Qfullscreen, lval);
7647 /** store_frame_param (f, Qsticky, sticky ? Qt : Qnil); **/
7650 /* Flip back buffers on any frames with undrawn content. */
7651 static void
7652 flush_dirty_back_buffers (void)
7654 block_input ();
7655 Lisp_Object tail, frame;
7656 FOR_EACH_FRAME (tail, frame)
7658 struct frame *f = XFRAME (frame);
7659 if (FRAME_LIVE_P (f) &&
7660 FRAME_X_P (f) &&
7661 FRAME_X_WINDOW (f) &&
7662 !FRAME_GARBAGED_P (f) &&
7663 !buffer_flipping_blocked_p () &&
7664 FRAME_X_NEED_BUFFER_FLIP (f))
7665 show_back_buffer (f);
7667 unblock_input ();
7670 /* Handles the XEvent EVENT on display DPYINFO.
7672 *FINISH is X_EVENT_GOTO_OUT if caller should stop reading events.
7673 *FINISH is zero if caller should continue reading events.
7674 *FINISH is X_EVENT_DROP if event should not be passed to the toolkit.
7675 *EVENT is unchanged unless we're processing KeyPress event.
7677 We return the number of characters stored into the buffer. */
7679 static int
7680 handle_one_xevent (struct x_display_info *dpyinfo,
7681 const XEvent *event,
7682 int *finish, struct input_event *hold_quit)
7684 union buffered_input_event inev;
7685 int count = 0;
7686 int do_help = 0;
7687 ptrdiff_t nbytes = 0;
7688 struct frame *any, *f = NULL;
7689 struct coding_system coding;
7690 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
7691 /* This holds the state XLookupString needs to implement dead keys
7692 and other tricks known as "compose processing". _X Window System_
7693 says that a portable program can't use this, but Stephen Gildea assures
7694 me that letting the compiler initialize it to zeros will work okay. */
7695 static XComposeStatus compose_status;
7696 XEvent configureEvent;
7697 XEvent next_event;
7699 USE_SAFE_ALLOCA;
7701 *finish = X_EVENT_NORMAL;
7703 EVENT_INIT (inev.ie);
7704 inev.ie.kind = NO_EVENT;
7705 inev.ie.arg = Qnil;
7707 any = x_any_window_to_frame (dpyinfo, event->xany.window);
7709 if (any && any->wait_event_type == event->type)
7710 any->wait_event_type = 0; /* Indicates we got it. */
7712 switch (event->type)
7714 case ClientMessage:
7716 if (event->xclient.message_type == dpyinfo->Xatom_wm_protocols
7717 && event->xclient.format == 32)
7719 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_take_focus)
7721 /* Use the value returned by x_any_window_to_frame
7722 because this could be the shell widget window
7723 if the frame has no title bar. */
7724 f = any;
7725 #ifdef HAVE_X_I18N
7726 /* Not quite sure this is needed -pd */
7727 if (f && FRAME_XIC (f))
7728 XSetICFocus (FRAME_XIC (f));
7729 #endif
7730 #if false
7731 /* Emacs sets WM hints whose `input' field is `true'. This
7732 instructs the WM to set the input focus automatically for
7733 Emacs with a call to XSetInputFocus. Setting WM_TAKE_FOCUS
7734 tells the WM to send us a ClientMessage WM_TAKE_FOCUS after
7735 it has set the focus. So, XSetInputFocus below is not
7736 needed.
7738 The call to XSetInputFocus below has also caused trouble. In
7739 cases where the XSetInputFocus done by the WM and the one
7740 below are temporally close (on a fast machine), the call
7741 below can generate additional FocusIn events which confuse
7742 Emacs. */
7744 /* Since we set WM_TAKE_FOCUS, we must call
7745 XSetInputFocus explicitly. But not if f is null,
7746 since that might be an event for a deleted frame. */
7747 if (f)
7749 Display *d = event->xclient.display;
7750 /* Catch and ignore errors, in case window has been
7751 iconified by a window manager such as GWM. */
7752 x_catch_errors (d);
7753 XSetInputFocus (d, event->xclient.window,
7754 /* The ICCCM says this is
7755 the only valid choice. */
7756 RevertToParent,
7757 event->xclient.data.l[1]);
7758 x_uncatch_errors ();
7760 /* Not certain about handling scroll bars here */
7761 #endif
7762 goto done;
7765 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_save_yourself)
7767 /* Save state modify the WM_COMMAND property to
7768 something which can reinstate us. This notifies
7769 the session manager, who's looking for such a
7770 PropertyNotify. Can restart processing when
7771 a keyboard or mouse event arrives. */
7772 /* If we have a session manager, don't set this.
7773 KDE will then start two Emacsen, one for the
7774 session manager and one for this. */
7775 #ifdef HAVE_X_SM
7776 if (! x_session_have_connection ())
7777 #endif
7779 f = x_top_window_to_frame (dpyinfo,
7780 event->xclient.window);
7781 /* This is just so we only give real data once
7782 for a single Emacs process. */
7783 if (f == SELECTED_FRAME ())
7784 XSetCommand (FRAME_X_DISPLAY (f),
7785 event->xclient.window,
7786 initial_argv, initial_argc);
7787 else if (f)
7788 XSetCommand (FRAME_X_DISPLAY (f),
7789 event->xclient.window,
7790 0, 0);
7792 goto done;
7795 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_delete_window)
7797 f = any;
7798 if (!f)
7799 goto OTHER; /* May be a dialog that is to be removed */
7801 inev.ie.kind = DELETE_WINDOW_EVENT;
7802 XSETFRAME (inev.ie.frame_or_window, f);
7803 goto done;
7806 goto done;
7809 if (event->xclient.message_type == dpyinfo->Xatom_wm_configure_denied)
7810 goto done;
7812 if (event->xclient.message_type == dpyinfo->Xatom_wm_window_moved)
7814 int new_x, new_y;
7815 f = x_window_to_frame (dpyinfo, event->xclient.window);
7817 new_x = event->xclient.data.s[0];
7818 new_y = event->xclient.data.s[1];
7820 if (f)
7822 f->left_pos = new_x;
7823 f->top_pos = new_y;
7825 goto done;
7828 #ifdef X_TOOLKIT_EDITRES
7829 if (event->xclient.message_type == dpyinfo->Xatom_editres)
7831 f = any;
7832 if (f)
7833 _XEditResCheckMessages (f->output_data.x->widget,
7834 NULL, (XEvent *) event, NULL);
7835 goto done;
7837 #endif /* X_TOOLKIT_EDITRES */
7839 if (event->xclient.message_type == dpyinfo->Xatom_DONE
7840 || event->xclient.message_type == dpyinfo->Xatom_PAGE)
7842 /* Ghostview job completed. Kill it. We could
7843 reply with "Next" if we received "Page", but we
7844 currently never do because we are interested in
7845 images, only, which should have 1 page. */
7846 Pixmap pixmap = (Pixmap) event->xclient.data.l[1];
7847 f = x_window_to_frame (dpyinfo, event->xclient.window);
7848 if (!f)
7849 goto OTHER;
7850 x_kill_gs_process (pixmap, f);
7851 expose_frame (f, 0, 0, 0, 0);
7852 goto done;
7855 #ifdef USE_TOOLKIT_SCROLL_BARS
7856 /* Scroll bar callbacks send a ClientMessage from which
7857 we construct an input_event. */
7858 if (event->xclient.message_type == dpyinfo->Xatom_Scrollbar)
7860 x_scroll_bar_to_input_event (event, &inev.ie);
7861 *finish = X_EVENT_GOTO_OUT;
7862 goto done;
7864 else if (event->xclient.message_type == dpyinfo->Xatom_Horizontal_Scrollbar)
7866 x_horizontal_scroll_bar_to_input_event (event, &inev.ie);
7867 *finish = X_EVENT_GOTO_OUT;
7868 goto done;
7870 #endif /* USE_TOOLKIT_SCROLL_BARS */
7872 /* XEmbed messages from the embedder (if any). */
7873 if (event->xclient.message_type == dpyinfo->Xatom_XEMBED)
7875 enum xembed_message msg = event->xclient.data.l[1];
7876 if (msg == XEMBED_FOCUS_IN || msg == XEMBED_FOCUS_OUT)
7877 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
7879 *finish = X_EVENT_GOTO_OUT;
7880 goto done;
7883 xft_settings_event (dpyinfo, event);
7885 f = any;
7886 if (!f)
7887 goto OTHER;
7888 if (x_handle_dnd_message (f, &event->xclient, dpyinfo, &inev.ie))
7889 *finish = X_EVENT_DROP;
7891 break;
7893 case SelectionNotify:
7894 x_display_set_last_user_time (dpyinfo, event->xselection.time);
7895 #ifdef USE_X_TOOLKIT
7896 if (! x_window_to_frame (dpyinfo, event->xselection.requestor))
7897 goto OTHER;
7898 #endif /* not USE_X_TOOLKIT */
7899 x_handle_selection_notify (&event->xselection);
7900 break;
7902 case SelectionClear: /* Someone has grabbed ownership. */
7903 x_display_set_last_user_time (dpyinfo, event->xselectionclear.time);
7904 #ifdef USE_X_TOOLKIT
7905 if (! x_window_to_frame (dpyinfo, event->xselectionclear.window))
7906 goto OTHER;
7907 #endif /* USE_X_TOOLKIT */
7909 const XSelectionClearEvent *eventp = &event->xselectionclear;
7911 inev.sie.kind = SELECTION_CLEAR_EVENT;
7912 SELECTION_EVENT_DPYINFO (&inev.sie) = dpyinfo;
7913 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
7914 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
7916 break;
7918 case SelectionRequest: /* Someone wants our selection. */
7919 x_display_set_last_user_time (dpyinfo, event->xselectionrequest.time);
7920 #ifdef USE_X_TOOLKIT
7921 if (!x_window_to_frame (dpyinfo, event->xselectionrequest.owner))
7922 goto OTHER;
7923 #endif /* USE_X_TOOLKIT */
7925 const XSelectionRequestEvent *eventp = &event->xselectionrequest;
7927 inev.sie.kind = SELECTION_REQUEST_EVENT;
7928 SELECTION_EVENT_DPYINFO (&inev.sie) = dpyinfo;
7929 SELECTION_EVENT_REQUESTOR (&inev.sie) = eventp->requestor;
7930 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
7931 SELECTION_EVENT_TARGET (&inev.sie) = eventp->target;
7932 SELECTION_EVENT_PROPERTY (&inev.sie) = eventp->property;
7933 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
7935 break;
7937 case PropertyNotify:
7938 x_display_set_last_user_time (dpyinfo, event->xproperty.time);
7939 f = x_top_window_to_frame (dpyinfo, event->xproperty.window);
7940 if (f && event->xproperty.atom == dpyinfo->Xatom_net_wm_state)
7942 bool not_hidden = x_handle_net_wm_state (f, &event->xproperty);
7943 if (not_hidden && FRAME_ICONIFIED_P (f))
7945 /* Gnome shell does not iconify us when C-z is pressed.
7946 It hides the frame. So if our state says we aren't
7947 hidden anymore, treat it as deiconified. */
7948 SET_FRAME_VISIBLE (f, 1);
7949 SET_FRAME_ICONIFIED (f, false);
7950 f->output_data.x->has_been_visible = true;
7951 inev.ie.kind = DEICONIFY_EVENT;
7952 XSETFRAME (inev.ie.frame_or_window, f);
7954 else if (! not_hidden && ! FRAME_ICONIFIED_P (f))
7956 SET_FRAME_VISIBLE (f, 0);
7957 SET_FRAME_ICONIFIED (f, true);
7958 inev.ie.kind = ICONIFY_EVENT;
7959 XSETFRAME (inev.ie.frame_or_window, f);
7963 x_handle_property_notify (&event->xproperty);
7964 xft_settings_event (dpyinfo, event);
7965 goto OTHER;
7967 case ReparentNotify:
7968 f = x_top_window_to_frame (dpyinfo, event->xreparent.window);
7969 if (f)
7971 /* Maybe we shouldn't set this for child frames ?? */
7972 f->output_data.x->parent_desc = event->xreparent.parent;
7973 if (!FRAME_PARENT_FRAME (f))
7974 x_real_positions (f, &f->left_pos, &f->top_pos);
7975 else
7977 Window root;
7978 unsigned int dummy_uint;
7980 block_input ();
7981 XGetGeometry (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
7982 &root, &f->left_pos, &f->top_pos,
7983 &dummy_uint, &dummy_uint, &dummy_uint, &dummy_uint);
7984 unblock_input ();
7987 /* Perhaps reparented due to a WM restart. Reset this. */
7988 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_UNKNOWN;
7989 FRAME_DISPLAY_INFO (f)->net_supported_window = 0;
7991 x_set_frame_alpha (f);
7993 goto OTHER;
7995 case Expose:
7996 f = x_window_to_frame (dpyinfo, event->xexpose.window);
7997 if (f)
7999 if (!FRAME_VISIBLE_P (f))
8001 block_input ();
8002 SET_FRAME_VISIBLE (f, 1);
8003 SET_FRAME_ICONIFIED (f, false);
8004 if (FRAME_X_DOUBLE_BUFFERED_P (f))
8005 font_drop_xrender_surfaces (f);
8006 f->output_data.x->has_been_visible = true;
8007 SET_FRAME_GARBAGED (f);
8008 unblock_input ();
8010 else if (FRAME_GARBAGED_P (f))
8012 #ifdef USE_GTK
8013 /* Go around the back buffer and manually clear the
8014 window the first time we show it. This way, we avoid
8015 showing users the sanity-defying horror of whatever
8016 GtkWindow is rendering beneath us. We've garbaged
8017 the frame, so we'll redraw the whole thing on next
8018 redisplay anyway. Yuck. */
8019 x_clear_area1 (
8020 FRAME_X_DISPLAY (f),
8021 FRAME_X_WINDOW (f),
8022 event->xexpose.x, event->xexpose.y,
8023 event->xexpose.width, event->xexpose.height,
8025 x_clear_under_internal_border (f);
8026 #endif
8030 if (!FRAME_GARBAGED_P (f))
8032 #ifdef USE_GTK
8033 /* This seems to be needed for GTK 2.6 and later, see
8034 https://debbugs.gnu.org/cgi/bugreport.cgi?bug=15398. */
8035 x_clear_area (f,
8036 event->xexpose.x, event->xexpose.y,
8037 event->xexpose.width, event->xexpose.height);
8038 #endif
8039 expose_frame (f, event->xexpose.x, event->xexpose.y,
8040 event->xexpose.width, event->xexpose.height);
8041 #ifdef USE_GTK
8042 x_clear_under_internal_border (f);
8043 #endif
8046 if (!FRAME_GARBAGED_P (f))
8047 show_back_buffer (f);
8049 else
8051 #ifndef USE_TOOLKIT_SCROLL_BARS
8052 struct scroll_bar *bar;
8053 #endif
8054 #if defined USE_LUCID
8055 /* Submenus of the Lucid menu bar aren't widgets
8056 themselves, so there's no way to dispatch events
8057 to them. Recognize this case separately. */
8059 Widget widget = x_window_to_menu_bar (event->xexpose.window);
8060 if (widget)
8061 xlwmenu_redisplay (widget);
8063 #endif /* USE_LUCID */
8065 #ifdef USE_TOOLKIT_SCROLL_BARS
8066 /* Dispatch event to the widget. */
8067 goto OTHER;
8068 #else /* not USE_TOOLKIT_SCROLL_BARS */
8069 bar = x_window_to_scroll_bar (event->xexpose.display,
8070 event->xexpose.window, 2);
8072 if (bar)
8073 x_scroll_bar_expose (bar, event);
8074 #ifdef USE_X_TOOLKIT
8075 else
8076 goto OTHER;
8077 #endif /* USE_X_TOOLKIT */
8078 #endif /* not USE_TOOLKIT_SCROLL_BARS */
8080 break;
8082 case GraphicsExpose: /* This occurs when an XCopyArea's
8083 source area was obscured or not
8084 available. */
8085 f = x_window_to_frame (dpyinfo, event->xgraphicsexpose.drawable);
8086 if (f)
8088 expose_frame (f, event->xgraphicsexpose.x,
8089 event->xgraphicsexpose.y,
8090 event->xgraphicsexpose.width,
8091 event->xgraphicsexpose.height);
8092 #ifdef USE_GTK
8093 x_clear_under_internal_border (f);
8094 #endif
8095 show_back_buffer (f);
8097 #ifdef USE_X_TOOLKIT
8098 else
8099 goto OTHER;
8100 #endif /* USE_X_TOOLKIT */
8101 break;
8103 case NoExpose: /* This occurs when an XCopyArea's
8104 source area was completely
8105 available. */
8106 break;
8108 case UnmapNotify:
8109 /* Redo the mouse-highlight after the tooltip has gone. */
8110 if (event->xunmap.window == tip_window)
8112 tip_window = None;
8113 x_redo_mouse_highlight (dpyinfo);
8116 f = x_top_window_to_frame (dpyinfo, event->xunmap.window);
8117 if (f) /* F may no longer exist if
8118 the frame was deleted. */
8120 bool visible = FRAME_VISIBLE_P (f);
8121 /* While a frame is unmapped, display generation is
8122 disabled; you don't want to spend time updating a
8123 display that won't ever be seen. */
8124 SET_FRAME_VISIBLE (f, 0);
8125 /* We can't distinguish, from the event, whether the window
8126 has become iconified or invisible. So assume, if it
8127 was previously visible, than now it is iconified.
8128 But x_make_frame_invisible clears both
8129 the visible flag and the iconified flag;
8130 and that way, we know the window is not iconified now. */
8131 if (visible || FRAME_ICONIFIED_P (f))
8133 SET_FRAME_ICONIFIED (f, true);
8134 inev.ie.kind = ICONIFY_EVENT;
8135 XSETFRAME (inev.ie.frame_or_window, f);
8138 goto OTHER;
8140 case MapNotify:
8141 /* We use x_top_window_to_frame because map events can
8142 come for sub-windows and they don't mean that the
8143 frame is visible. */
8144 f = x_top_window_to_frame (dpyinfo, event->xmap.window);
8145 if (f)
8147 bool iconified = FRAME_ICONIFIED_P (f);
8149 /* Check if fullscreen was specified before we where mapped the
8150 first time, i.e. from the command line. */
8151 if (!f->output_data.x->has_been_visible)
8154 x_check_fullscreen (f);
8155 #ifndef USE_GTK
8156 /* For systems that cannot synthesize `skip_taskbar' for
8157 unmapped windows do the following. */
8158 if (FRAME_SKIP_TASKBAR (f))
8159 x_set_skip_taskbar (f, Qt, Qnil);
8160 #endif /* Not USE_GTK */
8163 if (!iconified)
8165 /* The `z-group' is reset every time a frame becomes
8166 invisible. Handle this here. */
8167 if (FRAME_Z_GROUP (f) == z_group_above)
8168 x_set_z_group (f, Qabove, Qnil);
8169 else if (FRAME_Z_GROUP (f) == z_group_below)
8170 x_set_z_group (f, Qbelow, Qnil);
8173 SET_FRAME_VISIBLE (f, 1);
8174 SET_FRAME_ICONIFIED (f, false);
8175 f->output_data.x->has_been_visible = true;
8177 if (iconified)
8179 inev.ie.kind = DEICONIFY_EVENT;
8180 XSETFRAME (inev.ie.frame_or_window, f);
8182 else if (! NILP (Vframe_list) && ! NILP (XCDR (Vframe_list)))
8183 /* Force a redisplay sooner or later to update the
8184 frame titles in case this is the second frame. */
8185 record_asynch_buffer_change ();
8187 goto OTHER;
8189 case KeyPress:
8191 x_display_set_last_user_time (dpyinfo, event->xkey.time);
8192 ignore_next_mouse_click_timeout = 0;
8194 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
8195 /* Dispatch KeyPress events when in menu. */
8196 if (popup_activated ())
8197 goto OTHER;
8198 #endif
8200 f = any;
8202 /* If mouse-highlight is an integer, input clears out
8203 mouse highlighting. */
8204 if (!hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight)
8205 #if ! defined (USE_GTK)
8206 && (f == 0
8207 || !EQ (f->tool_bar_window, hlinfo->mouse_face_window))
8208 #endif
8211 clear_mouse_face (hlinfo);
8212 hlinfo->mouse_face_hidden = true;
8215 #if defined USE_MOTIF && defined USE_TOOLKIT_SCROLL_BARS
8216 if (f == 0)
8218 /* Scroll bars consume key events, but we want
8219 the keys to go to the scroll bar's frame. */
8220 Widget widget = XtWindowToWidget (dpyinfo->display,
8221 event->xkey.window);
8222 if (widget && XmIsScrollBar (widget))
8224 widget = XtParent (widget);
8225 f = x_any_window_to_frame (dpyinfo, XtWindow (widget));
8228 #endif /* USE_MOTIF and USE_TOOLKIT_SCROLL_BARS */
8230 if (f != 0)
8232 KeySym keysym, orig_keysym;
8233 /* al%imercury@uunet.uu.net says that making this 81
8234 instead of 80 fixed a bug whereby meta chars made
8235 his Emacs hang.
8237 It seems that some version of XmbLookupString has
8238 a bug of not returning XBufferOverflow in
8239 status_return even if the input is too long to
8240 fit in 81 bytes. So, we must prepare sufficient
8241 bytes for copy_buffer. 513 bytes (256 chars for
8242 two-byte character set) seems to be a fairly good
8243 approximation. -- 2000.8.10 handa@etl.go.jp */
8244 unsigned char copy_buffer[513];
8245 unsigned char *copy_bufptr = copy_buffer;
8246 int copy_bufsiz = sizeof (copy_buffer);
8247 int modifiers;
8248 Lisp_Object coding_system = Qlatin_1;
8249 Lisp_Object c;
8250 /* Event will be modified. */
8251 XKeyEvent xkey = event->xkey;
8253 #ifdef USE_GTK
8254 /* Don't pass keys to GTK. A Tab will shift focus to the
8255 tool bar in GTK 2.4. Keys will still go to menus and
8256 dialogs because in that case popup_activated is nonzero
8257 (see above). */
8258 *finish = X_EVENT_DROP;
8259 #endif
8261 xkey.state |= x_emacs_to_x_modifiers (FRAME_DISPLAY_INFO (f),
8262 extra_keyboard_modifiers);
8263 modifiers = xkey.state;
8265 /* This will have to go some day... */
8267 /* make_lispy_event turns chars into control chars.
8268 Don't do it here because XLookupString is too eager. */
8269 xkey.state &= ~ControlMask;
8270 xkey.state &= ~(dpyinfo->meta_mod_mask
8271 | dpyinfo->super_mod_mask
8272 | dpyinfo->hyper_mod_mask
8273 | dpyinfo->alt_mod_mask);
8275 /* In case Meta is ComposeCharacter,
8276 clear its status. According to Markus Ehrnsperger
8277 Markus.Ehrnsperger@lehrstuhl-bross.physik.uni-muenchen.de
8278 this enables ComposeCharacter to work whether or
8279 not it is combined with Meta. */
8280 if (modifiers & dpyinfo->meta_mod_mask)
8281 memset (&compose_status, 0, sizeof (compose_status));
8283 #ifdef HAVE_X_I18N
8284 if (FRAME_XIC (f))
8286 Status status_return;
8288 coding_system = Vlocale_coding_system;
8289 nbytes = XmbLookupString (FRAME_XIC (f),
8290 &xkey, (char *) copy_bufptr,
8291 copy_bufsiz, &keysym,
8292 &status_return);
8293 if (status_return == XBufferOverflow)
8295 copy_bufsiz = nbytes + 1;
8296 copy_bufptr = alloca (copy_bufsiz);
8297 nbytes = XmbLookupString (FRAME_XIC (f),
8298 &xkey, (char *) copy_bufptr,
8299 copy_bufsiz, &keysym,
8300 &status_return);
8302 /* Xutf8LookupString is a new but already deprecated interface. -stef */
8303 if (status_return == XLookupNone)
8304 break;
8305 else if (status_return == XLookupChars)
8307 keysym = NoSymbol;
8308 modifiers = 0;
8310 else if (status_return != XLookupKeySym
8311 && status_return != XLookupBoth)
8312 emacs_abort ();
8314 else
8315 nbytes = XLookupString (&xkey, (char *) copy_bufptr,
8316 copy_bufsiz, &keysym,
8317 &compose_status);
8318 #else
8319 nbytes = XLookupString (&xkey, (char *) copy_bufptr,
8320 copy_bufsiz, &keysym,
8321 &compose_status);
8322 #endif
8324 /* If not using XIM/XIC, and a compose sequence is in progress,
8325 we break here. Otherwise, chars_matched is always 0. */
8326 if (compose_status.chars_matched > 0 && nbytes == 0)
8327 break;
8329 memset (&compose_status, 0, sizeof (compose_status));
8330 orig_keysym = keysym;
8332 /* Common for all keysym input events. */
8333 XSETFRAME (inev.ie.frame_or_window, f);
8334 inev.ie.modifiers
8335 = x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO (f), modifiers);
8336 inev.ie.timestamp = xkey.time;
8338 /* First deal with keysyms which have defined
8339 translations to characters. */
8340 if (keysym >= 32 && keysym < 128)
8341 /* Avoid explicitly decoding each ASCII character. */
8343 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
8344 inev.ie.code = keysym;
8345 goto done_keysym;
8348 /* Keysyms directly mapped to Unicode characters. */
8349 if (keysym >= 0x01000000 && keysym <= 0x0110FFFF)
8351 if (keysym < 0x01000080)
8352 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
8353 else
8354 inev.ie.kind = MULTIBYTE_CHAR_KEYSTROKE_EVENT;
8355 inev.ie.code = keysym & 0xFFFFFF;
8356 goto done_keysym;
8359 /* Now non-ASCII. */
8360 if (HASH_TABLE_P (Vx_keysym_table)
8361 && (c = Fgethash (make_number (keysym),
8362 Vx_keysym_table,
8363 Qnil),
8364 NATNUMP (c)))
8366 inev.ie.kind = (SINGLE_BYTE_CHAR_P (XFASTINT (c))
8367 ? ASCII_KEYSTROKE_EVENT
8368 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
8369 inev.ie.code = XFASTINT (c);
8370 goto done_keysym;
8373 /* Random non-modifier sorts of keysyms. */
8374 if (((keysym >= XK_BackSpace && keysym <= XK_Escape)
8375 || keysym == XK_Delete
8376 #ifdef XK_ISO_Left_Tab
8377 || (keysym >= XK_ISO_Left_Tab
8378 && keysym <= XK_ISO_Enter)
8379 #endif
8380 || IsCursorKey (keysym) /* 0xff50 <= x < 0xff60 */
8381 || IsMiscFunctionKey (keysym) /* 0xff60 <= x < VARIES */
8382 #ifdef HPUX
8383 /* This recognizes the "extended function
8384 keys". It seems there's no cleaner way.
8385 Test IsModifierKey to avoid handling
8386 mode_switch incorrectly. */
8387 || (XK_Select <= keysym && keysym < XK_KP_Space)
8388 #endif
8389 #ifdef XK_dead_circumflex
8390 || orig_keysym == XK_dead_circumflex
8391 #endif
8392 #ifdef XK_dead_grave
8393 || orig_keysym == XK_dead_grave
8394 #endif
8395 #ifdef XK_dead_tilde
8396 || orig_keysym == XK_dead_tilde
8397 #endif
8398 #ifdef XK_dead_diaeresis
8399 || orig_keysym == XK_dead_diaeresis
8400 #endif
8401 #ifdef XK_dead_macron
8402 || orig_keysym == XK_dead_macron
8403 #endif
8404 #ifdef XK_dead_degree
8405 || orig_keysym == XK_dead_degree
8406 #endif
8407 #ifdef XK_dead_acute
8408 || orig_keysym == XK_dead_acute
8409 #endif
8410 #ifdef XK_dead_cedilla
8411 || orig_keysym == XK_dead_cedilla
8412 #endif
8413 #ifdef XK_dead_breve
8414 || orig_keysym == XK_dead_breve
8415 #endif
8416 #ifdef XK_dead_ogonek
8417 || orig_keysym == XK_dead_ogonek
8418 #endif
8419 #ifdef XK_dead_caron
8420 || orig_keysym == XK_dead_caron
8421 #endif
8422 #ifdef XK_dead_doubleacute
8423 || orig_keysym == XK_dead_doubleacute
8424 #endif
8425 #ifdef XK_dead_abovedot
8426 || orig_keysym == XK_dead_abovedot
8427 #endif
8428 || IsKeypadKey (keysym) /* 0xff80 <= x < 0xffbe */
8429 || IsFunctionKey (keysym) /* 0xffbe <= x < 0xffe1 */
8430 /* Any "vendor-specific" key is ok. */
8431 || (orig_keysym & (1 << 28))
8432 || (keysym != NoSymbol && nbytes == 0))
8433 && ! (IsModifierKey (orig_keysym)
8434 /* The symbols from XK_ISO_Lock
8435 to XK_ISO_Last_Group_Lock
8436 don't have real modifiers but
8437 should be treated similarly to
8438 Mode_switch by Emacs. */
8439 #if defined XK_ISO_Lock && defined XK_ISO_Last_Group_Lock
8440 || (XK_ISO_Lock <= orig_keysym
8441 && orig_keysym <= XK_ISO_Last_Group_Lock)
8442 #endif
8445 STORE_KEYSYM_FOR_DEBUG (keysym);
8446 /* make_lispy_event will convert this to a symbolic
8447 key. */
8448 inev.ie.kind = NON_ASCII_KEYSTROKE_EVENT;
8449 inev.ie.code = keysym;
8450 goto done_keysym;
8453 { /* Raw bytes, not keysym. */
8454 ptrdiff_t i;
8455 int nchars, len;
8457 for (i = 0, nchars = 0; i < nbytes; i++)
8459 if (ASCII_CHAR_P (copy_bufptr[i]))
8460 nchars++;
8461 STORE_KEYSYM_FOR_DEBUG (copy_bufptr[i]);
8464 if (nchars < nbytes)
8466 /* Decode the input data. */
8468 /* The input should be decoded with `coding_system'
8469 which depends on which X*LookupString function
8470 we used just above and the locale. */
8471 setup_coding_system (coding_system, &coding);
8472 coding.src_multibyte = false;
8473 coding.dst_multibyte = true;
8474 /* The input is converted to events, thus we can't
8475 handle composition. Anyway, there's no XIM that
8476 gives us composition information. */
8477 coding.common_flags &= ~CODING_ANNOTATION_MASK;
8479 SAFE_NALLOCA (coding.destination, MAX_MULTIBYTE_LENGTH,
8480 nbytes);
8481 coding.dst_bytes = MAX_MULTIBYTE_LENGTH * nbytes;
8482 coding.mode |= CODING_MODE_LAST_BLOCK;
8483 decode_coding_c_string (&coding, copy_bufptr, nbytes, Qnil);
8484 nbytes = coding.produced;
8485 nchars = coding.produced_char;
8486 copy_bufptr = coding.destination;
8489 /* Convert the input data to a sequence of
8490 character events. */
8491 for (i = 0; i < nbytes; i += len)
8493 int ch;
8494 if (nchars == nbytes)
8495 ch = copy_bufptr[i], len = 1;
8496 else
8497 ch = STRING_CHAR_AND_LENGTH (copy_bufptr + i, len);
8498 inev.ie.kind = (SINGLE_BYTE_CHAR_P (ch)
8499 ? ASCII_KEYSTROKE_EVENT
8500 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
8501 inev.ie.code = ch;
8502 kbd_buffer_store_buffered_event (&inev, hold_quit);
8505 count += nchars;
8507 inev.ie.kind = NO_EVENT; /* Already stored above. */
8509 if (keysym == NoSymbol)
8510 break;
8512 /* FIXME: check side effects and remove this. */
8513 ((XEvent *) event)->xkey = xkey;
8515 done_keysym:
8516 #ifdef HAVE_X_I18N
8517 /* Don't dispatch this event since XtDispatchEvent calls
8518 XFilterEvent, and two calls in a row may freeze the
8519 client. */
8520 break;
8521 #else
8522 goto OTHER;
8523 #endif
8525 case KeyRelease:
8526 x_display_set_last_user_time (dpyinfo, event->xkey.time);
8527 #ifdef HAVE_X_I18N
8528 /* Don't dispatch this event since XtDispatchEvent calls
8529 XFilterEvent, and two calls in a row may freeze the
8530 client. */
8531 break;
8532 #else
8533 goto OTHER;
8534 #endif
8536 case EnterNotify:
8537 x_display_set_last_user_time (dpyinfo, event->xcrossing.time);
8538 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
8540 f = any;
8542 if (f && x_mouse_click_focus_ignore_position)
8543 ignore_next_mouse_click_timeout = event->xmotion.time + 200;
8545 /* EnterNotify counts as mouse movement,
8546 so update things that depend on mouse position. */
8547 if (f && !f->output_data.x->hourglass_p)
8548 note_mouse_movement (f, &event->xmotion);
8549 #ifdef USE_GTK
8550 /* We may get an EnterNotify on the buttons in the toolbar. In that
8551 case we moved out of any highlighted area and need to note this. */
8552 if (!f && dpyinfo->last_mouse_glyph_frame)
8553 note_mouse_movement (dpyinfo->last_mouse_glyph_frame, &event->xmotion);
8554 #endif
8555 goto OTHER;
8557 case FocusIn:
8558 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
8559 goto OTHER;
8561 case LeaveNotify:
8562 x_display_set_last_user_time (dpyinfo, event->xcrossing.time);
8563 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
8565 f = x_top_window_to_frame (dpyinfo, event->xcrossing.window);
8566 if (f)
8568 if (f == hlinfo->mouse_face_mouse_frame)
8570 /* If we move outside the frame, then we're
8571 certainly no longer on any text in the frame. */
8572 clear_mouse_face (hlinfo);
8573 hlinfo->mouse_face_mouse_frame = 0;
8576 /* Generate a nil HELP_EVENT to cancel a help-echo.
8577 Do it only if there's something to cancel.
8578 Otherwise, the startup message is cleared when
8579 the mouse leaves the frame. */
8580 if (any_help_event_p)
8581 do_help = -1;
8583 #ifdef USE_GTK
8584 /* See comment in EnterNotify above */
8585 else if (dpyinfo->last_mouse_glyph_frame)
8586 note_mouse_movement (dpyinfo->last_mouse_glyph_frame, &event->xmotion);
8587 #endif
8588 goto OTHER;
8590 case FocusOut:
8591 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
8592 goto OTHER;
8594 case MotionNotify:
8596 x_display_set_last_user_time (dpyinfo, event->xmotion.time);
8597 previous_help_echo_string = help_echo_string;
8598 help_echo_string = Qnil;
8600 f = (x_mouse_grabbed (dpyinfo) ? dpyinfo->last_mouse_frame
8601 : x_window_to_frame (dpyinfo, event->xmotion.window));
8603 if (hlinfo->mouse_face_hidden)
8605 hlinfo->mouse_face_hidden = false;
8606 clear_mouse_face (hlinfo);
8609 #ifdef USE_GTK
8610 if (f && xg_event_is_for_scrollbar (f, event))
8611 f = 0;
8612 #endif
8613 if (f)
8615 /* Maybe generate a SELECT_WINDOW_EVENT for
8616 `mouse-autoselect-window' but don't let popup menus
8617 interfere with this (Bug#1261). */
8618 if (!NILP (Vmouse_autoselect_window)
8619 && !popup_activated ()
8620 /* Don't switch if we're currently in the minibuffer.
8621 This tries to work around problems where the
8622 minibuffer gets unselected unexpectedly, and where
8623 you then have to move your mouse all the way down to
8624 the minibuffer to select it. */
8625 && !MINI_WINDOW_P (XWINDOW (selected_window))
8626 /* With `focus-follows-mouse' non-nil create an event
8627 also when the target window is on another frame. */
8628 && (f == XFRAME (selected_frame)
8629 || !NILP (focus_follows_mouse)))
8631 static Lisp_Object last_mouse_window;
8632 Lisp_Object window = window_from_coordinates
8633 (f, event->xmotion.x, event->xmotion.y, 0, false);
8635 /* A window will be autoselected only when it is not
8636 selected now and the last mouse movement event was
8637 not in it. The remainder of the code is a bit vague
8638 wrt what a "window" is. For immediate autoselection,
8639 the window is usually the entire window but for GTK
8640 where the scroll bars don't count. For delayed
8641 autoselection the window is usually the window's text
8642 area including the margins. */
8643 if (WINDOWP (window)
8644 && !EQ (window, last_mouse_window)
8645 && !EQ (window, selected_window))
8647 inev.ie.kind = SELECT_WINDOW_EVENT;
8648 inev.ie.frame_or_window = window;
8651 /* Remember the last window where we saw the mouse. */
8652 last_mouse_window = window;
8655 if (!note_mouse_movement (f, &event->xmotion))
8656 help_echo_string = previous_help_echo_string;
8658 else
8660 #ifndef USE_TOOLKIT_SCROLL_BARS
8661 struct scroll_bar *bar
8662 = x_window_to_scroll_bar (event->xmotion.display,
8663 event->xmotion.window, 2);
8665 if (bar)
8666 x_scroll_bar_note_movement (bar, &event->xmotion);
8667 #endif /* USE_TOOLKIT_SCROLL_BARS */
8669 /* If we move outside the frame, then we're
8670 certainly no longer on any text in the frame. */
8671 clear_mouse_face (hlinfo);
8674 /* If the contents of the global variable help_echo_string
8675 has changed, generate a HELP_EVENT. */
8676 if (!NILP (help_echo_string)
8677 || !NILP (previous_help_echo_string))
8678 do_help = 1;
8679 goto OTHER;
8682 case ConfigureNotify:
8683 /* An opaque move can generate a stream of events as the window
8684 is dragged around. If the connection round trip time isn't
8685 really short, they may come faster than we can respond to
8686 them, given the multiple queries we can do to check window
8687 manager state, translate coordinates, etc.
8689 So if this ConfigureNotify is immediately followed by another
8690 for the same window, use the info from the latest update, and
8691 consider the events all handled. */
8692 /* Opaque resize may be trickier; ConfigureNotify events are
8693 mixed with Expose events for multiple windows. */
8694 configureEvent = *event;
8695 while (XPending (dpyinfo->display))
8697 XNextEvent (dpyinfo->display, &next_event);
8698 if (next_event.type != ConfigureNotify
8699 || next_event.xconfigure.window != event->xconfigure.window
8700 /* Skipping events with different sizes can lead to a
8701 mispositioned mode line at initial window creation.
8702 Only drop window motion events for now. */
8703 || next_event.xconfigure.width != event->xconfigure.width
8704 || next_event.xconfigure.height != event->xconfigure.height)
8706 XPutBackEvent (dpyinfo->display, &next_event);
8707 break;
8709 else
8710 configureEvent = next_event;
8713 f = x_top_window_to_frame (dpyinfo, configureEvent.xconfigure.window);
8714 /* Unfortunately, we need to call font_drop_xrender_surfaces for
8715 _all_ ConfigureNotify events, otherwise we miss some and
8716 flicker. Don't try to optimize these calls by looking only
8717 for size changes: that's not sufficient. We miss some
8718 surface invalidations and flicker. */
8719 block_input ();
8720 if (f && FRAME_X_DOUBLE_BUFFERED_P (f))
8721 font_drop_xrender_surfaces (f);
8722 unblock_input ();
8723 #ifdef USE_CAIRO
8724 if (f) x_cr_destroy_surface (f);
8725 #endif
8726 #ifdef USE_GTK
8727 if (!f
8728 && (f = any)
8729 && configureEvent.xconfigure.window == FRAME_X_WINDOW (f))
8731 block_input ();
8732 if (FRAME_X_DOUBLE_BUFFERED_P (f))
8733 font_drop_xrender_surfaces (f);
8734 unblock_input ();
8735 xg_frame_resized (f, configureEvent.xconfigure.width,
8736 configureEvent.xconfigure.height);
8737 #ifdef USE_CAIRO
8738 x_cr_destroy_surface (f);
8739 #endif
8740 f = 0;
8742 #endif
8743 if (f)
8745 #ifdef USE_GTK
8746 /* For GTK+ don't call x_net_wm_state for the scroll bar
8747 window. (Bug#24963, Bug#25887) */
8748 if (configureEvent.xconfigure.window == FRAME_X_WINDOW (f))
8749 #endif
8750 x_net_wm_state (f, configureEvent.xconfigure.window);
8752 #ifdef USE_X_TOOLKIT
8753 /* Tip frames are pure X window, set size for them. */
8754 if (FRAME_TOOLTIP_P (f))
8756 if (FRAME_PIXEL_HEIGHT (f) != configureEvent.xconfigure.height
8757 || FRAME_PIXEL_WIDTH (f) != configureEvent.xconfigure.width)
8759 SET_FRAME_GARBAGED (f);
8761 FRAME_PIXEL_HEIGHT (f) = configureEvent.xconfigure.height;
8762 FRAME_PIXEL_WIDTH (f) = configureEvent.xconfigure.width;
8764 #endif
8766 #ifndef USE_X_TOOLKIT
8767 #ifndef USE_GTK
8768 int width =
8769 FRAME_PIXEL_TO_TEXT_WIDTH (f, configureEvent.xconfigure.width);
8770 int height =
8771 FRAME_PIXEL_TO_TEXT_HEIGHT (f, configureEvent.xconfigure.height);
8773 /* In the toolkit version, change_frame_size
8774 is called by the code that handles resizing
8775 of the EmacsFrame widget. */
8777 /* Even if the number of character rows and columns has
8778 not changed, the font size may have changed, so we need
8779 to check the pixel dimensions as well. */
8780 if (width != FRAME_TEXT_WIDTH (f)
8781 || height != FRAME_TEXT_HEIGHT (f)
8782 || configureEvent.xconfigure.width != FRAME_PIXEL_WIDTH (f)
8783 || configureEvent.xconfigure.height != FRAME_PIXEL_HEIGHT (f))
8785 change_frame_size (f, width, height, false, true, false, true);
8786 x_clear_under_internal_border (f);
8787 SET_FRAME_GARBAGED (f);
8788 cancel_mouse_face (f);
8790 #endif /* not USE_GTK */
8791 #endif
8793 #ifdef USE_GTK
8794 /* GTK creates windows but doesn't map them.
8795 Only get real positions when mapped. */
8796 if (FRAME_GTK_OUTER_WIDGET (f)
8797 && gtk_widget_get_mapped (FRAME_GTK_OUTER_WIDGET (f)))
8798 #endif
8800 int old_left = f->left_pos;
8801 int old_top = f->top_pos;
8802 Lisp_Object frame = Qnil;
8804 XSETFRAME (frame, f);
8806 if (!FRAME_PARENT_FRAME (f))
8807 x_real_positions (f, &f->left_pos, &f->top_pos);
8808 else
8810 Window root;
8811 unsigned int dummy_uint;
8813 block_input ();
8814 XGetGeometry (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8815 &root, &f->left_pos, &f->top_pos,
8816 &dummy_uint, &dummy_uint, &dummy_uint, &dummy_uint);
8817 unblock_input ();
8820 if (old_left != f->left_pos || old_top != f->top_pos)
8822 inev.ie.kind = MOVE_FRAME_EVENT;
8823 XSETFRAME (inev.ie.frame_or_window, f);
8828 #ifdef HAVE_X_I18N
8829 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMStatusArea))
8830 xic_set_statusarea (f);
8831 #endif
8834 goto OTHER;
8836 case ButtonRelease:
8837 case ButtonPress:
8839 /* If we decide we want to generate an event to be seen
8840 by the rest of Emacs, we put it here. */
8841 bool tool_bar_p = false;
8843 memset (&compose_status, 0, sizeof (compose_status));
8844 dpyinfo->last_mouse_glyph_frame = NULL;
8845 x_display_set_last_user_time (dpyinfo, event->xbutton.time);
8847 if (x_mouse_grabbed (dpyinfo))
8848 f = dpyinfo->last_mouse_frame;
8849 else
8851 f = x_window_to_frame (dpyinfo, event->xbutton.window);
8853 if (f && event->xbutton.type == ButtonPress
8854 && !popup_activated ()
8855 && !x_window_to_scroll_bar (event->xbutton.display,
8856 event->xbutton.window, 2)
8857 && !FRAME_NO_ACCEPT_FOCUS (f))
8859 /* When clicking into a child frame or when clicking
8860 into a parent frame with the child frame selected and
8861 `no-accept-focus' is not set, select the clicked
8862 frame. */
8863 struct frame *hf = dpyinfo->x_highlight_frame;
8865 if (FRAME_PARENT_FRAME (f) || (hf && frame_ancestor_p (f, hf)))
8867 block_input ();
8868 XSetInputFocus (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8869 RevertToParent, CurrentTime);
8870 if (FRAME_PARENT_FRAME (f))
8871 XRaiseWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
8872 unblock_input ();
8877 #ifdef USE_GTK
8878 if (f && xg_event_is_for_scrollbar (f, event))
8879 f = 0;
8880 #endif
8881 if (f)
8883 #if ! defined (USE_GTK)
8884 /* Is this in the tool-bar? */
8885 if (WINDOWP (f->tool_bar_window)
8886 && WINDOW_TOTAL_LINES (XWINDOW (f->tool_bar_window)))
8888 Lisp_Object window;
8889 int x = event->xbutton.x;
8890 int y = event->xbutton.y;
8892 window = window_from_coordinates (f, x, y, 0, true);
8893 tool_bar_p = EQ (window, f->tool_bar_window);
8895 if (tool_bar_p && event->xbutton.button < 4)
8896 handle_tool_bar_click
8897 (f, x, y, event->xbutton.type == ButtonPress,
8898 x_x_to_emacs_modifiers (dpyinfo, event->xbutton.state));
8900 #endif /* !USE_GTK */
8902 if (!tool_bar_p)
8903 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
8904 if (! popup_activated ())
8905 #endif
8907 if (ignore_next_mouse_click_timeout)
8909 if (event->type == ButtonPress
8910 && event->xbutton.time > ignore_next_mouse_click_timeout)
8912 ignore_next_mouse_click_timeout = 0;
8913 construct_mouse_click (&inev.ie, &event->xbutton, f);
8915 if (event->type == ButtonRelease)
8916 ignore_next_mouse_click_timeout = 0;
8918 else
8919 construct_mouse_click (&inev.ie, &event->xbutton, f);
8921 if (FRAME_X_EMBEDDED_P (f))
8922 xembed_send_message (f, event->xbutton.time,
8923 XEMBED_REQUEST_FOCUS, 0, 0, 0);
8925 else
8927 struct scroll_bar *bar
8928 = x_window_to_scroll_bar (event->xbutton.display,
8929 event->xbutton.window, 2);
8931 #ifdef USE_TOOLKIT_SCROLL_BARS
8932 /* Make the "Ctrl-Mouse-2 splits window" work for toolkit
8933 scroll bars. */
8934 if (bar && event->xbutton.state & ControlMask)
8936 x_scroll_bar_handle_click (bar, event, &inev.ie);
8937 *finish = X_EVENT_DROP;
8939 #else /* not USE_TOOLKIT_SCROLL_BARS */
8940 if (bar)
8941 x_scroll_bar_handle_click (bar, event, &inev.ie);
8942 #endif /* not USE_TOOLKIT_SCROLL_BARS */
8945 if (event->type == ButtonPress)
8947 dpyinfo->grabbed |= (1 << event->xbutton.button);
8948 dpyinfo->last_mouse_frame = f;
8949 #if ! defined (USE_GTK)
8950 if (f && !tool_bar_p)
8951 f->last_tool_bar_item = -1;
8952 #endif /* not USE_GTK */
8954 else
8955 dpyinfo->grabbed &= ~(1 << event->xbutton.button);
8957 /* Ignore any mouse motion that happened before this event;
8958 any subsequent mouse-movement Emacs events should reflect
8959 only motion after the ButtonPress/Release. */
8960 if (f != 0)
8961 f->mouse_moved = false;
8963 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
8964 f = x_menubar_window_to_frame (dpyinfo, event);
8965 /* For a down-event in the menu bar,
8966 don't pass it to Xt right now.
8967 Instead, save it away
8968 and we will pass it to Xt from kbd_buffer_get_event.
8969 That way, we can run some Lisp code first. */
8970 if (! popup_activated ()
8971 #ifdef USE_GTK
8972 /* Gtk+ menus only react to the first three buttons. */
8973 && event->xbutton.button < 3
8974 #endif
8975 && f && event->type == ButtonPress
8976 /* Verify the event is really within the menu bar
8977 and not just sent to it due to grabbing. */
8978 && event->xbutton.x >= 0
8979 && event->xbutton.x < FRAME_PIXEL_WIDTH (f)
8980 && event->xbutton.y >= 0
8981 && event->xbutton.y < FRAME_MENUBAR_HEIGHT (f)
8982 && event->xbutton.same_screen)
8984 if (!f->output_data.x->saved_menu_event)
8985 f->output_data.x->saved_menu_event = xmalloc (sizeof *event);
8986 *f->output_data.x->saved_menu_event = *event;
8987 inev.ie.kind = MENU_BAR_ACTIVATE_EVENT;
8988 XSETFRAME (inev.ie.frame_or_window, f);
8989 *finish = X_EVENT_DROP;
8991 else
8992 goto OTHER;
8993 #endif /* USE_X_TOOLKIT || USE_GTK */
8995 break;
8997 case CirculateNotify:
8998 goto OTHER;
9000 case CirculateRequest:
9001 goto OTHER;
9003 case VisibilityNotify:
9004 goto OTHER;
9006 case MappingNotify:
9007 /* Someone has changed the keyboard mapping - update the
9008 local cache. */
9009 switch (event->xmapping.request)
9011 case MappingModifier:
9012 x_find_modifier_meanings (dpyinfo);
9013 FALLTHROUGH;
9014 case MappingKeyboard:
9015 XRefreshKeyboardMapping ((XMappingEvent *) &event->xmapping);
9017 goto OTHER;
9019 case DestroyNotify:
9020 xft_settings_event (dpyinfo, event);
9021 break;
9023 default:
9024 OTHER:
9025 #ifdef USE_X_TOOLKIT
9026 block_input ();
9027 if (*finish != X_EVENT_DROP)
9028 XtDispatchEvent ((XEvent *) event);
9029 unblock_input ();
9030 #endif /* USE_X_TOOLKIT */
9031 break;
9034 done:
9035 if (inev.ie.kind != NO_EVENT)
9037 kbd_buffer_store_buffered_event (&inev, hold_quit);
9038 count++;
9041 if (do_help
9042 && !(hold_quit && hold_quit->kind != NO_EVENT))
9044 Lisp_Object frame;
9046 if (f)
9047 XSETFRAME (frame, f);
9048 else
9049 frame = Qnil;
9051 if (do_help > 0)
9053 any_help_event_p = true;
9054 gen_help_event (help_echo_string, frame, help_echo_window,
9055 help_echo_object, help_echo_pos);
9057 else
9059 help_echo_string = Qnil;
9060 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
9062 count++;
9065 /* Sometimes event processing draws to the frame outside redisplay.
9066 To ensure that these changes become visible, draw them here. */
9067 flush_dirty_back_buffers ();
9068 SAFE_FREE ();
9069 return count;
9072 #if defined USE_X_TOOLKIT || defined USE_MOTIF || defined USE_GTK
9074 /* Handles the XEvent EVENT on display DISPLAY.
9075 This is used for event loops outside the normal event handling,
9076 i.e. looping while a popup menu or a dialog is posted.
9078 Returns the value handle_one_xevent sets in the finish argument. */
9080 x_dispatch_event (XEvent *event, Display *display)
9082 struct x_display_info *dpyinfo;
9083 int finish = X_EVENT_NORMAL;
9085 dpyinfo = x_display_info_for_display (display);
9087 if (dpyinfo)
9088 handle_one_xevent (dpyinfo, event, &finish, 0);
9090 return finish;
9092 #endif
9094 /* Read events coming from the X server.
9095 Return as soon as there are no more events to be read.
9097 Return the number of characters stored into the buffer,
9098 thus pretending to be `read' (except the characters we store
9099 in the keyboard buffer can be multibyte, so are not necessarily
9100 C chars). */
9102 static int
9103 XTread_socket (struct terminal *terminal, struct input_event *hold_quit)
9105 int count = 0;
9106 bool event_found = false;
9107 struct x_display_info *dpyinfo = terminal->display_info.x;
9109 block_input ();
9111 /* For debugging, this gives a way to fake an I/O error. */
9112 if (dpyinfo == XTread_socket_fake_io_error)
9114 XTread_socket_fake_io_error = 0;
9115 x_io_error_quitter (dpyinfo->display);
9118 #ifndef USE_GTK
9119 while (XPending (dpyinfo->display))
9121 int finish;
9122 XEvent event;
9124 XNextEvent (dpyinfo->display, &event);
9126 #ifdef HAVE_X_I18N
9127 /* Filter events for the current X input method. */
9128 if (x_filter_event (dpyinfo, &event))
9129 continue;
9130 #endif
9131 event_found = true;
9133 count += handle_one_xevent (dpyinfo, &event, &finish, hold_quit);
9135 if (finish == X_EVENT_GOTO_OUT)
9136 break;
9139 #else /* USE_GTK */
9141 /* For GTK we must use the GTK event loop. But XEvents gets passed
9142 to our filter function above, and then to the big event switch.
9143 We use a bunch of globals to communicate with our filter function,
9144 that is kind of ugly, but it works.
9146 There is no way to do one display at the time, GTK just does events
9147 from all displays. */
9149 while (gtk_events_pending ())
9151 current_count = count;
9152 current_hold_quit = hold_quit;
9154 gtk_main_iteration ();
9156 count = current_count;
9157 current_count = -1;
9158 current_hold_quit = 0;
9160 if (current_finish == X_EVENT_GOTO_OUT)
9161 break;
9163 #endif /* USE_GTK */
9165 /* On some systems, an X bug causes Emacs to get no more events
9166 when the window is destroyed. Detect that. (1994.) */
9167 if (! event_found)
9169 /* Emacs and the X Server eats up CPU time if XNoOp is done every time.
9170 One XNOOP in 100 loops will make Emacs terminate.
9171 B. Bretthauer, 1994 */
9172 x_noop_count++;
9173 if (x_noop_count >= 100)
9175 x_noop_count=0;
9177 if (next_noop_dpyinfo == 0)
9178 next_noop_dpyinfo = x_display_list;
9180 XNoOp (next_noop_dpyinfo->display);
9182 /* Each time we get here, cycle through the displays now open. */
9183 next_noop_dpyinfo = next_noop_dpyinfo->next;
9187 /* If the focus was just given to an auto-raising frame,
9188 raise it now. FIXME: handle more than one such frame. */
9189 if (dpyinfo->x_pending_autoraise_frame)
9191 x_raise_frame (dpyinfo->x_pending_autoraise_frame);
9192 dpyinfo->x_pending_autoraise_frame = NULL;
9195 unblock_input ();
9197 return count;
9203 /***********************************************************************
9204 Text Cursor
9205 ***********************************************************************/
9207 /* Set clipping for output in glyph row ROW. W is the window in which
9208 we operate. GC is the graphics context to set clipping in.
9210 ROW may be a text row or, e.g., a mode line. Text rows must be
9211 clipped to the interior of the window dedicated to text display,
9212 mode lines must be clipped to the whole window. */
9214 static void
9215 x_clip_to_row (struct window *w, struct glyph_row *row,
9216 enum glyph_row_area area, GC gc)
9218 struct frame *f = XFRAME (WINDOW_FRAME (w));
9219 XRectangle clip_rect;
9220 int window_x, window_y, window_width;
9222 window_box (w, area, &window_x, &window_y, &window_width, 0);
9224 clip_rect.x = window_x;
9225 clip_rect.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
9226 clip_rect.y = max (clip_rect.y, window_y);
9227 clip_rect.width = window_width;
9228 clip_rect.height = row->visible_height;
9230 x_set_clip_rectangles (f, gc, &clip_rect, 1);
9234 /* Draw a hollow box cursor on window W in glyph row ROW. */
9236 static void
9237 x_draw_hollow_cursor (struct window *w, struct glyph_row *row)
9239 struct frame *f = XFRAME (WINDOW_FRAME (w));
9240 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
9241 Display *dpy = FRAME_X_DISPLAY (f);
9242 int x, y, wd, h;
9243 XGCValues xgcv;
9244 struct glyph *cursor_glyph;
9245 GC gc;
9247 /* Get the glyph the cursor is on. If we can't tell because
9248 the current matrix is invalid or such, give up. */
9249 cursor_glyph = get_phys_cursor_glyph (w);
9250 if (cursor_glyph == NULL)
9251 return;
9253 /* Compute frame-relative coordinates for phys cursor. */
9254 get_phys_cursor_geometry (w, row, cursor_glyph, &x, &y, &h);
9255 wd = w->phys_cursor_width - 1;
9257 /* The foreground of cursor_gc is typically the same as the normal
9258 background color, which can cause the cursor box to be invisible. */
9259 xgcv.foreground = f->output_data.x->cursor_pixel;
9260 if (dpyinfo->scratch_cursor_gc)
9261 XChangeGC (dpy, dpyinfo->scratch_cursor_gc, GCForeground, &xgcv);
9262 else
9263 dpyinfo->scratch_cursor_gc = XCreateGC (dpy, FRAME_X_DRAWABLE (f),
9264 GCForeground, &xgcv);
9265 gc = dpyinfo->scratch_cursor_gc;
9267 /* When on R2L character, show cursor at the right edge of the
9268 glyph, unless the cursor box is as wide as the glyph or wider
9269 (the latter happens when x-stretch-cursor is non-nil). */
9270 if ((cursor_glyph->resolved_level & 1) != 0
9271 && cursor_glyph->pixel_width > wd)
9273 x += cursor_glyph->pixel_width - wd;
9274 if (wd > 0)
9275 wd -= 1;
9277 /* Set clipping, draw the rectangle, and reset clipping again. */
9278 x_clip_to_row (w, row, TEXT_AREA, gc);
9279 x_draw_rectangle (f, gc, x, y, wd, h - 1);
9280 x_reset_clip_rectangles (f, gc);
9284 /* Draw a bar cursor on window W in glyph row ROW.
9286 Implementation note: One would like to draw a bar cursor with an
9287 angle equal to the one given by the font property XA_ITALIC_ANGLE.
9288 Unfortunately, I didn't find a font yet that has this property set.
9289 --gerd. */
9291 static void
9292 x_draw_bar_cursor (struct window *w, struct glyph_row *row, int width, enum text_cursor_kinds kind)
9294 struct frame *f = XFRAME (w->frame);
9295 struct glyph *cursor_glyph;
9297 /* If cursor is out of bounds, don't draw garbage. This can happen
9298 in mini-buffer windows when switching between echo area glyphs
9299 and mini-buffer. */
9300 cursor_glyph = get_phys_cursor_glyph (w);
9301 if (cursor_glyph == NULL)
9302 return;
9304 /* Experimental avoidance of cursor on xwidget. */
9305 if (cursor_glyph->type == XWIDGET_GLYPH)
9306 return;
9308 /* If on an image, draw like a normal cursor. That's usually better
9309 visible than drawing a bar, esp. if the image is large so that
9310 the bar might not be in the window. */
9311 if (cursor_glyph->type == IMAGE_GLYPH)
9313 struct glyph_row *r;
9314 r = MATRIX_ROW (w->current_matrix, w->phys_cursor.vpos);
9315 draw_phys_cursor_glyph (w, r, DRAW_CURSOR);
9317 else
9319 Display *dpy = FRAME_X_DISPLAY (f);
9320 Drawable drawable = FRAME_X_DRAWABLE (f);
9321 GC gc = FRAME_DISPLAY_INFO (f)->scratch_cursor_gc;
9322 unsigned long mask = GCForeground | GCBackground | GCGraphicsExposures;
9323 struct face *face = FACE_FROM_ID (f, cursor_glyph->face_id);
9324 XGCValues xgcv;
9326 /* If the glyph's background equals the color we normally draw
9327 the bars cursor in, the bar cursor in its normal color is
9328 invisible. Use the glyph's foreground color instead in this
9329 case, on the assumption that the glyph's colors are chosen so
9330 that the glyph is legible. */
9331 if (face->background == f->output_data.x->cursor_pixel)
9332 xgcv.background = xgcv.foreground = face->foreground;
9333 else
9334 xgcv.background = xgcv.foreground = f->output_data.x->cursor_pixel;
9335 xgcv.graphics_exposures = False;
9337 if (gc)
9338 XChangeGC (dpy, gc, mask, &xgcv);
9339 else
9341 gc = XCreateGC (dpy, drawable, mask, &xgcv);
9342 FRAME_DISPLAY_INFO (f)->scratch_cursor_gc = gc;
9345 x_clip_to_row (w, row, TEXT_AREA, gc);
9347 if (kind == BAR_CURSOR)
9349 int x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
9351 if (width < 0)
9352 width = FRAME_CURSOR_WIDTH (f);
9353 width = min (cursor_glyph->pixel_width, width);
9355 w->phys_cursor_width = width;
9357 /* If the character under cursor is R2L, draw the bar cursor
9358 on the right of its glyph, rather than on the left. */
9359 if ((cursor_glyph->resolved_level & 1) != 0)
9360 x += cursor_glyph->pixel_width - width;
9362 x_fill_rectangle (f, gc, x,
9363 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y),
9364 width, row->height);
9366 else /* HBAR_CURSOR */
9368 int dummy_x, dummy_y, dummy_h;
9369 int x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
9371 if (width < 0)
9372 width = row->height;
9374 width = min (row->height, width);
9376 get_phys_cursor_geometry (w, row, cursor_glyph, &dummy_x,
9377 &dummy_y, &dummy_h);
9379 if ((cursor_glyph->resolved_level & 1) != 0
9380 && cursor_glyph->pixel_width > w->phys_cursor_width - 1)
9381 x += cursor_glyph->pixel_width - w->phys_cursor_width + 1;
9382 x_fill_rectangle (f, gc, x,
9383 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y +
9384 row->height - width),
9385 w->phys_cursor_width - 1, width);
9388 x_reset_clip_rectangles (f, gc);
9393 /* RIF: Define cursor CURSOR on frame F. */
9395 static void
9396 x_define_frame_cursor (struct frame *f, Cursor cursor)
9398 if (!f->pointer_invisible
9399 && f->output_data.x->current_cursor != cursor)
9400 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), cursor);
9401 f->output_data.x->current_cursor = cursor;
9405 /* RIF: Clear area on frame F. */
9407 static void
9408 x_clear_frame_area (struct frame *f, int x, int y, int width, int height)
9410 x_clear_area (f, x, y, width, height);
9414 /* RIF: Draw cursor on window W. */
9416 static void
9417 x_draw_window_cursor (struct window *w, struct glyph_row *glyph_row, int x,
9418 int y, enum text_cursor_kinds cursor_type,
9419 int cursor_width, bool on_p, bool active_p)
9421 struct frame *f = XFRAME (WINDOW_FRAME (w));
9423 if (on_p)
9425 w->phys_cursor_type = cursor_type;
9426 w->phys_cursor_on_p = true;
9428 if (glyph_row->exact_window_width_line_p
9429 && (glyph_row->reversed_p
9430 ? (w->phys_cursor.hpos < 0)
9431 : (w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])))
9433 glyph_row->cursor_in_fringe_p = true;
9434 draw_fringe_bitmap (w, glyph_row, glyph_row->reversed_p);
9436 else
9438 switch (cursor_type)
9440 case HOLLOW_BOX_CURSOR:
9441 x_draw_hollow_cursor (w, glyph_row);
9442 break;
9444 case FILLED_BOX_CURSOR:
9445 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
9446 break;
9448 case BAR_CURSOR:
9449 x_draw_bar_cursor (w, glyph_row, cursor_width, BAR_CURSOR);
9450 break;
9452 case HBAR_CURSOR:
9453 x_draw_bar_cursor (w, glyph_row, cursor_width, HBAR_CURSOR);
9454 break;
9456 case NO_CURSOR:
9457 w->phys_cursor_width = 0;
9458 break;
9460 default:
9461 emacs_abort ();
9465 #ifdef HAVE_X_I18N
9466 if (w == XWINDOW (f->selected_window))
9467 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMPreeditPosition))
9468 xic_set_preeditarea (w, x, y);
9469 #endif
9472 XFlush (FRAME_X_DISPLAY (f));
9476 /* Icons. */
9478 /* Make the x-window of frame F use the gnu icon bitmap. */
9480 bool
9481 x_bitmap_icon (struct frame *f, Lisp_Object file)
9483 ptrdiff_t bitmap_id;
9485 if (FRAME_X_WINDOW (f) == 0)
9486 return true;
9488 /* Free up our existing icon bitmap and mask if any. */
9489 if (f->output_data.x->icon_bitmap > 0)
9490 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
9491 f->output_data.x->icon_bitmap = 0;
9493 if (STRINGP (file))
9495 #ifdef USE_GTK
9496 /* Use gtk_window_set_icon_from_file () if available,
9497 It's not restricted to bitmaps */
9498 if (xg_set_icon (f, file))
9499 return false;
9500 #endif /* USE_GTK */
9501 bitmap_id = x_create_bitmap_from_file (f, file);
9502 x_create_bitmap_mask (f, bitmap_id);
9504 else
9506 /* Create the GNU bitmap and mask if necessary. */
9507 if (FRAME_DISPLAY_INFO (f)->icon_bitmap_id < 0)
9509 ptrdiff_t rc = -1;
9511 #ifdef USE_GTK
9513 if (xg_set_icon (f, xg_default_icon_file)
9514 || xg_set_icon_from_xpm_data (f, gnu_xpm_bits))
9516 FRAME_DISPLAY_INFO (f)->icon_bitmap_id = -2;
9517 return false;
9520 #elif defined (HAVE_XPM) && defined (HAVE_X_WINDOWS)
9522 rc = x_create_bitmap_from_xpm_data (f, gnu_xpm_bits);
9523 if (rc != -1)
9524 FRAME_DISPLAY_INFO (f)->icon_bitmap_id = rc;
9526 #endif
9528 /* If all else fails, use the (black and white) xbm image. */
9529 if (rc == -1)
9531 rc = x_create_bitmap_from_data (f, (char *) gnu_xbm_bits,
9532 gnu_xbm_width, gnu_xbm_height);
9533 if (rc == -1)
9534 return true;
9536 FRAME_DISPLAY_INFO (f)->icon_bitmap_id = rc;
9537 x_create_bitmap_mask (f, FRAME_DISPLAY_INFO (f)->icon_bitmap_id);
9541 /* The first time we create the GNU bitmap and mask,
9542 this increments the ref-count one extra time.
9543 As a result, the GNU bitmap and mask are never freed.
9544 That way, we don't have to worry about allocating it again. */
9545 x_reference_bitmap (f, FRAME_DISPLAY_INFO (f)->icon_bitmap_id);
9547 bitmap_id = FRAME_DISPLAY_INFO (f)->icon_bitmap_id;
9550 x_wm_set_icon_pixmap (f, bitmap_id);
9551 f->output_data.x->icon_bitmap = bitmap_id;
9553 return false;
9557 /* Make the x-window of frame F use a rectangle with text.
9558 Use ICON_NAME as the text. */
9560 bool
9561 x_text_icon (struct frame *f, const char *icon_name)
9563 if (FRAME_X_WINDOW (f) == 0)
9564 return true;
9567 XTextProperty text;
9568 text.value = (unsigned char *) icon_name;
9569 text.encoding = XA_STRING;
9570 text.format = 8;
9571 text.nitems = strlen (icon_name);
9572 XSetWMIconName (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f), &text);
9575 if (f->output_data.x->icon_bitmap > 0)
9576 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
9577 f->output_data.x->icon_bitmap = 0;
9578 x_wm_set_icon_pixmap (f, 0);
9580 return false;
9583 #define X_ERROR_MESSAGE_SIZE 200
9585 /* If non-nil, this should be a string.
9586 It means catch X errors and store the error message in this string.
9588 The reason we use a stack is that x_catch_error/x_uncatch_error can
9589 be called from a signal handler.
9592 struct x_error_message_stack {
9593 char string[X_ERROR_MESSAGE_SIZE];
9594 Display *dpy;
9595 x_special_error_handler handler;
9596 void *handler_data;
9597 struct x_error_message_stack *prev;
9599 static struct x_error_message_stack *x_error_message;
9601 /* An X error handler which stores the error message in
9602 *x_error_message. This is called from x_error_handler if
9603 x_catch_errors is in effect. */
9605 static void
9606 x_error_catcher (Display *display, XErrorEvent *event)
9608 XGetErrorText (display, event->error_code,
9609 x_error_message->string,
9610 X_ERROR_MESSAGE_SIZE);
9611 if (x_error_message->handler)
9612 x_error_message->handler (display, event, x_error_message->string,
9613 x_error_message->handler_data);
9616 /* Begin trapping X errors for display DPY. Actually we trap X errors
9617 for all displays, but DPY should be the display you are actually
9618 operating on.
9620 After calling this function, X protocol errors no longer cause
9621 Emacs to exit; instead, they are recorded in the string
9622 stored in *x_error_message.
9624 Calling x_check_errors signals an Emacs error if an X error has
9625 occurred since the last call to x_catch_errors or x_check_errors.
9627 Calling x_uncatch_errors resumes the normal error handling.
9628 Calling x_uncatch_errors_after_check is similar, but skips an XSync
9629 to the server, and should be used only immediately after
9630 x_had_errors_p or x_check_errors. */
9632 void
9633 x_catch_errors_with_handler (Display *dpy, x_special_error_handler handler,
9634 void *handler_data)
9636 struct x_error_message_stack *data = xmalloc (sizeof *data);
9638 /* Make sure any errors from previous requests have been dealt with. */
9639 XSync (dpy, False);
9641 data->dpy = dpy;
9642 data->string[0] = 0;
9643 data->handler = handler;
9644 data->handler_data = handler_data;
9645 data->prev = x_error_message;
9646 x_error_message = data;
9649 void
9650 x_catch_errors (Display *dpy)
9652 x_catch_errors_with_handler (dpy, NULL, NULL);
9655 /* Undo the last x_catch_errors call.
9656 DPY should be the display that was passed to x_catch_errors.
9658 This version should be used only if the immediately preceding
9659 X-protocol-related thing was x_check_errors or x_had_error_p, both
9660 of which issue XSync calls, so we don't need to re-sync here. */
9662 void
9663 x_uncatch_errors_after_check (void)
9665 struct x_error_message_stack *tmp;
9667 block_input ();
9668 tmp = x_error_message;
9669 x_error_message = x_error_message->prev;
9670 xfree (tmp);
9671 unblock_input ();
9674 /* Undo the last x_catch_errors call.
9675 DPY should be the display that was passed to x_catch_errors. */
9677 void
9678 x_uncatch_errors (void)
9680 struct x_error_message_stack *tmp;
9682 block_input ();
9684 /* The display may have been closed before this function is called.
9685 Check if it is still open before calling XSync. */
9686 if (x_display_info_for_display (x_error_message->dpy) != 0)
9687 XSync (x_error_message->dpy, False);
9689 tmp = x_error_message;
9690 x_error_message = x_error_message->prev;
9691 xfree (tmp);
9692 unblock_input ();
9695 /* If any X protocol errors have arrived since the last call to
9696 x_catch_errors or x_check_errors, signal an Emacs error using
9697 sprintf (a buffer, FORMAT, the x error message text) as the text. */
9699 void
9700 x_check_errors (Display *dpy, const char *format)
9702 /* Make sure to catch any errors incurred so far. */
9703 XSync (dpy, False);
9705 if (x_error_message->string[0])
9707 char string[X_ERROR_MESSAGE_SIZE];
9708 memcpy (string, x_error_message->string, X_ERROR_MESSAGE_SIZE);
9709 x_uncatch_errors ();
9710 error (format, string);
9714 /* Nonzero if we had any X protocol errors
9715 since we did x_catch_errors on DPY. */
9717 bool
9718 x_had_errors_p (Display *dpy)
9720 /* Make sure to catch any errors incurred so far. */
9721 XSync (dpy, False);
9723 return x_error_message->string[0] != 0;
9726 /* Forget about any errors we have had, since we did x_catch_errors on DPY. */
9728 void
9729 x_clear_errors (Display *dpy)
9731 x_error_message->string[0] = 0;
9734 #if false
9735 /* See comment in unwind_to_catch why calling this is a bad
9736 * idea. --lorentey */
9737 /* Close off all unclosed x_catch_errors calls. */
9739 void
9740 x_fully_uncatch_errors (void)
9742 while (x_error_message)
9743 x_uncatch_errors ();
9745 #endif
9747 #if false
9748 static unsigned int x_wire_count;
9749 x_trace_wire (void)
9751 fprintf (stderr, "Lib call: %d\n", ++x_wire_count);
9753 #endif
9756 /************************************************************************
9757 Handling X errors
9758 ************************************************************************/
9760 /* Error message passed to x_connection_closed. */
9762 static char *error_msg;
9764 /* Handle the loss of connection to display DPY. ERROR_MESSAGE is
9765 the text of an error message that lead to the connection loss. */
9767 static _Noreturn void
9768 x_connection_closed (Display *dpy, const char *error_message, bool ioerror)
9770 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
9771 Lisp_Object frame, tail;
9772 ptrdiff_t idx = SPECPDL_INDEX ();
9774 error_msg = alloca (strlen (error_message) + 1);
9775 strcpy (error_msg, error_message);
9777 /* Inhibit redisplay while frames are being deleted. */
9778 specbind (Qinhibit_redisplay, Qt);
9780 if (dpyinfo)
9782 /* Protect display from being closed when we delete the last
9783 frame on it. */
9784 dpyinfo->reference_count++;
9785 dpyinfo->terminal->reference_count++;
9787 if (ioerror) dpyinfo->display = 0;
9789 /* First delete frames whose mini-buffers are on frames
9790 that are on the dead display. */
9791 FOR_EACH_FRAME (tail, frame)
9793 Lisp_Object minibuf_frame;
9794 minibuf_frame
9795 = WINDOW_FRAME (XWINDOW (FRAME_MINIBUF_WINDOW (XFRAME (frame))));
9796 if (FRAME_X_P (XFRAME (frame))
9797 && FRAME_X_P (XFRAME (minibuf_frame))
9798 && ! EQ (frame, minibuf_frame)
9799 && FRAME_DISPLAY_INFO (XFRAME (minibuf_frame)) == dpyinfo)
9800 delete_frame (frame, Qnoelisp);
9803 /* Now delete all remaining frames on the dead display.
9804 We are now sure none of these is used as the mini-buffer
9805 for another frame that we need to delete. */
9806 FOR_EACH_FRAME (tail, frame)
9807 if (FRAME_X_P (XFRAME (frame))
9808 && FRAME_DISPLAY_INFO (XFRAME (frame)) == dpyinfo)
9810 /* Set this to t so that delete_frame won't get confused
9811 trying to find a replacement. */
9812 kset_default_minibuffer_frame (FRAME_KBOARD (XFRAME (frame)), Qt);
9813 delete_frame (frame, Qnoelisp);
9816 /* If DPYINFO is null, this means we didn't open the display in the
9817 first place, so don't try to close it. */
9818 if (dpyinfo)
9820 /* We can not call XtCloseDisplay here because it calls XSync.
9821 XSync inside the error handler apparently hangs Emacs. On
9822 current Xt versions, this isn't needed either. */
9823 #ifdef USE_GTK
9824 /* A long-standing GTK bug prevents proper disconnect handling
9825 <https://gitlab.gnome.org/GNOME/gtk/issues/221>. Once,
9826 the resulting Glib error message loop filled a user's disk.
9827 To avoid this, kill Emacs unconditionally on disconnect. */
9828 shut_down_emacs (0, Qnil);
9829 fprintf (stderr, "%s\n\
9830 When compiled with GTK, Emacs cannot recover from X disconnects.\n\
9831 This is a GTK bug: https://gitlab.gnome.org/GNOME/gtk/issues/221\n\
9832 For details, see etc/PROBLEMS.\n",
9833 error_msg);
9834 emacs_abort ();
9835 #endif /* USE_GTK */
9837 /* Indicate that this display is dead. */
9838 dpyinfo->display = 0;
9840 dpyinfo->reference_count--;
9841 dpyinfo->terminal->reference_count--;
9842 if (dpyinfo->reference_count != 0)
9843 /* We have just closed all frames on this display. */
9844 emacs_abort ();
9847 Lisp_Object tmp;
9848 XSETTERMINAL (tmp, dpyinfo->terminal);
9849 Fdelete_terminal (tmp, Qnoelisp);
9853 if (terminal_list == 0)
9855 fprintf (stderr, "%s\n", error_msg);
9856 Fkill_emacs (make_number (70));
9857 /* NOTREACHED */
9860 totally_unblock_input ();
9862 unbind_to (idx, Qnil);
9863 clear_waiting_for_input ();
9865 /* Here, we absolutely have to use a non-local exit (e.g. signal, throw,
9866 longjmp), because returning from this function would get us back into
9867 Xlib's code which will directly call `exit'. */
9868 error ("%s", error_msg);
9871 /* We specifically use it before defining it, so that gcc doesn't inline it,
9872 otherwise gdb doesn't know how to properly put a breakpoint on it. */
9873 static void x_error_quitter (Display *, XErrorEvent *);
9875 /* This is the first-level handler for X protocol errors.
9876 It calls x_error_quitter or x_error_catcher. */
9878 static int
9879 x_error_handler (Display *display, XErrorEvent *event)
9881 #if defined USE_GTK && defined HAVE_GTK3
9882 if ((event->error_code == BadMatch || event->error_code == BadWindow)
9883 && event->request_code == X_SetInputFocus)
9885 return 0;
9887 #endif
9889 if (x_error_message)
9890 x_error_catcher (display, event);
9891 else
9892 x_error_quitter (display, event);
9893 return 0;
9896 /* This is the usual handler for X protocol errors.
9897 It kills all frames on the display that we got the error for.
9898 If that was the only one, it prints an error message and kills Emacs. */
9900 /* .gdbinit puts a breakpoint here, so make sure it is not inlined. */
9902 /* On older GCC versions, just putting x_error_quitter
9903 after x_error_handler prevents inlining into the former. */
9905 static void NO_INLINE
9906 x_error_quitter (Display *display, XErrorEvent *event)
9908 char buf[256], buf1[356];
9910 /* Ignore BadName errors. They can happen because of fonts
9911 or colors that are not defined. */
9913 if (event->error_code == BadName)
9914 return;
9916 /* Note that there is no real way portable across R3/R4 to get the
9917 original error handler. */
9919 XGetErrorText (display, event->error_code, buf, sizeof (buf));
9920 sprintf (buf1, "X protocol error: %s on protocol request %d",
9921 buf, event->request_code);
9922 x_connection_closed (display, buf1, false);
9926 /* This is the handler for X IO errors, always.
9927 It kills all frames on the display that we lost touch with.
9928 If that was the only one, it prints an error message and kills Emacs. */
9930 static _Noreturn int
9931 x_io_error_quitter (Display *display)
9933 char buf[256];
9935 snprintf (buf, sizeof buf, "Connection lost to X server '%s'",
9936 DisplayString (display));
9937 x_connection_closed (display, buf, true);
9938 assume (false);
9941 /* Changing the font of the frame. */
9943 /* Give frame F the font FONT-OBJECT as its default font. The return
9944 value is FONT-OBJECT. FONTSET is an ID of the fontset for the
9945 frame. If it is negative, generate a new fontset from
9946 FONT-OBJECT. */
9948 Lisp_Object
9949 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
9951 struct font *font = XFONT_OBJECT (font_object);
9952 int unit, font_ascent, font_descent;
9953 #ifndef USE_X_TOOLKIT
9954 int old_menu_bar_height = FRAME_MENU_BAR_HEIGHT (f);
9955 Lisp_Object fullscreen;
9956 #endif
9958 if (fontset < 0)
9959 fontset = fontset_from_font (font_object);
9960 FRAME_FONTSET (f) = fontset;
9961 if (FRAME_FONT (f) == font)
9962 /* This font is already set in frame F. There's nothing more to
9963 do. */
9964 return font_object;
9966 FRAME_FONT (f) = font;
9967 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
9968 FRAME_COLUMN_WIDTH (f) = font->average_width;
9969 get_font_ascent_descent (font, &font_ascent, &font_descent);
9970 FRAME_LINE_HEIGHT (f) = font_ascent + font_descent;
9972 #ifndef USE_X_TOOLKIT
9973 FRAME_MENU_BAR_HEIGHT (f) = FRAME_MENU_BAR_LINES (f) * FRAME_LINE_HEIGHT (f);
9974 #endif
9976 /* Compute character columns occupied by scrollbar.
9978 Don't do things differently for non-toolkit scrollbars
9979 (Bug#17163). */
9980 unit = FRAME_COLUMN_WIDTH (f);
9981 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
9982 FRAME_CONFIG_SCROLL_BAR_COLS (f)
9983 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + unit - 1) / unit;
9984 else
9985 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + unit - 1) / unit;
9987 if (FRAME_X_WINDOW (f) != 0)
9989 /* Don't change the size of a tip frame; there's no point in
9990 doing it because it's done in Fx_show_tip, and it leads to
9991 problems because the tip frame has no widget. */
9992 if (!FRAME_TOOLTIP_P (f))
9994 adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
9995 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 3,
9996 false, Qfont);
9997 #ifndef USE_X_TOOLKIT
9998 if (FRAME_MENU_BAR_HEIGHT (f) != old_menu_bar_height
9999 && !f->after_make_frame
10000 && (EQ (frame_inhibit_implied_resize, Qt)
10001 || (CONSP (frame_inhibit_implied_resize)
10002 && NILP (Fmemq (Qfont, frame_inhibit_implied_resize))))
10003 && (NILP (fullscreen = get_frame_param (f, Qfullscreen))
10004 || EQ (fullscreen, Qfullwidth)))
10005 /* If the menu bar height changes, try to keep text height
10006 constant. */
10007 adjust_frame_size
10008 (f, -1, FRAME_TEXT_HEIGHT (f) + FRAME_MENU_BAR_HEIGHT (f)
10009 - old_menu_bar_height, 1, false, Qfont);
10010 #endif /* USE_X_TOOLKIT */
10014 #ifdef HAVE_X_I18N
10015 if (FRAME_XIC (f)
10016 && (FRAME_XIC_STYLE (f) & (XIMPreeditPosition | XIMStatusArea)))
10018 block_input ();
10019 xic_set_xfontset (f, SSDATA (fontset_ascii (fontset)));
10020 unblock_input ();
10022 #endif
10024 return font_object;
10028 /***********************************************************************
10029 X Input Methods
10030 ***********************************************************************/
10032 #ifdef HAVE_X_I18N
10034 #ifdef HAVE_X11R6
10036 /* XIM destroy callback function, which is called whenever the
10037 connection to input method XIM dies. CLIENT_DATA contains a
10038 pointer to the x_display_info structure corresponding to XIM. */
10040 static void
10041 xim_destroy_callback (XIM xim, XPointer client_data, XPointer call_data)
10043 struct x_display_info *dpyinfo = (struct x_display_info *) client_data;
10044 Lisp_Object frame, tail;
10046 block_input ();
10048 /* No need to call XDestroyIC.. */
10049 FOR_EACH_FRAME (tail, frame)
10051 struct frame *f = XFRAME (frame);
10052 if (FRAME_X_P (f) && FRAME_DISPLAY_INFO (f) == dpyinfo)
10054 FRAME_XIC (f) = NULL;
10055 xic_free_xfontset (f);
10059 /* No need to call XCloseIM. */
10060 dpyinfo->xim = NULL;
10061 XFree (dpyinfo->xim_styles);
10062 unblock_input ();
10065 #endif /* HAVE_X11R6 */
10067 /* Open the connection to the XIM server on display DPYINFO.
10068 RESOURCE_NAME is the resource name Emacs uses. */
10070 static void
10071 xim_open_dpy (struct x_display_info *dpyinfo, char *resource_name)
10073 XIM xim;
10075 #ifdef HAVE_XIM
10076 if (use_xim)
10078 if (dpyinfo->xim)
10079 XCloseIM (dpyinfo->xim);
10080 xim = XOpenIM (dpyinfo->display, dpyinfo->xrdb, resource_name,
10081 emacs_class);
10082 dpyinfo->xim = xim;
10084 if (xim)
10086 #ifdef HAVE_X11R6
10087 XIMCallback destroy;
10088 #endif
10090 /* Get supported styles and XIM values. */
10091 XGetIMValues (xim, XNQueryInputStyle, &dpyinfo->xim_styles, NULL);
10093 #ifdef HAVE_X11R6
10094 destroy.callback = xim_destroy_callback;
10095 destroy.client_data = (XPointer)dpyinfo;
10096 XSetIMValues (xim, XNDestroyCallback, &destroy, NULL);
10097 #endif
10101 else
10102 #endif /* HAVE_XIM */
10103 dpyinfo->xim = NULL;
10107 #ifdef HAVE_X11R6_XIM
10109 /* XIM instantiate callback function, which is called whenever an XIM
10110 server is available. DISPLAY is the display of the XIM.
10111 CLIENT_DATA contains a pointer to an xim_inst_t structure created
10112 when the callback was registered. */
10114 static void
10115 xim_instantiate_callback (Display *display, XPointer client_data, XPointer call_data)
10117 struct xim_inst_t *xim_inst = (struct xim_inst_t *) client_data;
10118 struct x_display_info *dpyinfo = xim_inst->dpyinfo;
10120 /* We don't support multiple XIM connections. */
10121 if (dpyinfo->xim)
10122 return;
10124 xim_open_dpy (dpyinfo, xim_inst->resource_name);
10126 /* Create XIC for the existing frames on the same display, as long
10127 as they have no XIC. */
10128 if (dpyinfo->xim && dpyinfo->reference_count > 0)
10130 Lisp_Object tail, frame;
10132 block_input ();
10133 FOR_EACH_FRAME (tail, frame)
10135 struct frame *f = XFRAME (frame);
10137 if (FRAME_X_P (f)
10138 && FRAME_DISPLAY_INFO (f) == xim_inst->dpyinfo)
10139 if (FRAME_XIC (f) == NULL)
10141 create_frame_xic (f);
10142 if (FRAME_XIC_STYLE (f) & XIMStatusArea)
10143 xic_set_statusarea (f);
10144 if (FRAME_XIC_STYLE (f) & XIMPreeditPosition)
10146 struct window *w = XWINDOW (f->selected_window);
10147 xic_set_preeditarea (w, w->cursor.x, w->cursor.y);
10152 unblock_input ();
10156 #endif /* HAVE_X11R6_XIM */
10159 /* Open a connection to the XIM server on display DPYINFO.
10160 RESOURCE_NAME is the resource name for Emacs. On X11R5, open the
10161 connection only at the first time. On X11R6, open the connection
10162 in the XIM instantiate callback function. */
10164 static void
10165 xim_initialize (struct x_display_info *dpyinfo, char *resource_name)
10167 dpyinfo->xim = NULL;
10168 #ifdef HAVE_XIM
10169 if (use_xim)
10171 #ifdef HAVE_X11R6_XIM
10172 struct xim_inst_t *xim_inst = xmalloc (sizeof *xim_inst);
10173 Bool ret;
10175 dpyinfo->xim_callback_data = xim_inst;
10176 xim_inst->dpyinfo = dpyinfo;
10177 xim_inst->resource_name = xstrdup (resource_name);
10178 ret = XRegisterIMInstantiateCallback
10179 (dpyinfo->display, dpyinfo->xrdb, xim_inst->resource_name,
10180 emacs_class, xim_instantiate_callback,
10181 /* This is XPointer in XFree86 but (XPointer *)
10182 on Tru64, at least, hence the configure test. */
10183 (XRegisterIMInstantiateCallback_arg6) xim_inst);
10184 eassert (ret == True);
10185 #else /* not HAVE_X11R6_XIM */
10186 xim_open_dpy (dpyinfo, resource_name);
10187 #endif /* not HAVE_X11R6_XIM */
10189 #endif /* HAVE_XIM */
10193 /* Close the connection to the XIM server on display DPYINFO. */
10195 static void
10196 xim_close_dpy (struct x_display_info *dpyinfo)
10198 #ifdef HAVE_XIM
10199 if (use_xim)
10201 #ifdef HAVE_X11R6_XIM
10202 struct xim_inst_t *xim_inst = dpyinfo->xim_callback_data;
10204 if (dpyinfo->display)
10206 Bool ret = XUnregisterIMInstantiateCallback
10207 (dpyinfo->display, dpyinfo->xrdb, xim_inst->resource_name,
10208 emacs_class, xim_instantiate_callback,
10209 (XRegisterIMInstantiateCallback_arg6) xim_inst);
10210 eassert (ret == True);
10212 xfree (xim_inst->resource_name);
10213 xfree (xim_inst);
10214 #endif /* HAVE_X11R6_XIM */
10215 if (dpyinfo->display)
10216 XCloseIM (dpyinfo->xim);
10217 dpyinfo->xim = NULL;
10218 XFree (dpyinfo->xim_styles);
10220 #endif /* HAVE_XIM */
10223 #endif /* not HAVE_X11R6_XIM */
10227 /* Calculate the absolute position in frame F
10228 from its current recorded position values and gravity. */
10230 static void
10231 x_calc_absolute_position (struct frame *f)
10233 int flags = f->size_hint_flags;
10234 struct frame *p = FRAME_PARENT_FRAME (f);
10236 /* We have nothing to do if the current position
10237 is already for the top-left corner. */
10238 if (! ((flags & XNegative) || (flags & YNegative)))
10239 return;
10241 /* Treat negative positions as relative to the leftmost bottommost
10242 position that fits on the screen. */
10243 if ((flags & XNegative) && (f->left_pos <= 0))
10245 int width = FRAME_PIXEL_WIDTH (f);
10247 /* A frame that has been visible at least once should have outer
10248 edges. */
10249 if (f->output_data.x->has_been_visible && !p)
10251 Lisp_Object frame;
10252 Lisp_Object edges = Qnil;
10254 XSETFRAME (frame, f);
10255 edges = Fx_frame_edges (frame, Qouter_edges);
10256 if (!NILP (edges))
10257 width = (XINT (Fnth (make_number (2), edges))
10258 - XINT (Fnth (make_number (0), edges)));
10261 if (p)
10262 f->left_pos = (FRAME_PIXEL_WIDTH (p) - width - 2 * f->border_width
10263 + f->left_pos);
10264 else
10265 f->left_pos = (x_display_pixel_width (FRAME_DISPLAY_INFO (f))
10266 - width + f->left_pos);
10270 if ((flags & YNegative) && (f->top_pos <= 0))
10272 int height = FRAME_PIXEL_HEIGHT (f);
10274 #if defined USE_X_TOOLKIT && defined USE_MOTIF
10275 /* Something is fishy here. When using Motif, starting Emacs with
10276 `-g -0-0', the frame appears too low by a few pixels.
10278 This seems to be so because initially, while Emacs is starting,
10279 the column widget's height and the frame's pixel height are
10280 different. The column widget's height is the right one. In
10281 later invocations, when Emacs is up, the frame's pixel height
10282 is right, though.
10284 It's not obvious where the initial small difference comes from.
10285 2000-12-01, gerd. */
10287 XtVaGetValues (f->output_data.x->column_widget, XtNheight, &height, NULL);
10288 #endif
10290 if (f->output_data.x->has_been_visible && !p)
10292 Lisp_Object frame;
10293 Lisp_Object edges = Qnil;
10295 XSETFRAME (frame, f);
10296 if (NILP (edges))
10297 edges = Fx_frame_edges (frame, Qouter_edges);
10298 if (!NILP (edges))
10299 height = (XINT (Fnth (make_number (3), edges))
10300 - XINT (Fnth (make_number (1), edges)));
10303 if (p)
10304 f->top_pos = (FRAME_PIXEL_HEIGHT (p) - height - 2 * f->border_width
10305 + f->top_pos);
10306 else
10307 f->top_pos = (x_display_pixel_height (FRAME_DISPLAY_INFO (f))
10308 - height + f->top_pos);
10311 /* The left_pos and top_pos
10312 are now relative to the top and left screen edges,
10313 so the flags should correspond. */
10314 f->size_hint_flags &= ~ (XNegative | YNegative);
10317 /* CHANGE_GRAVITY is 1 when calling from Fset_frame_position,
10318 to really change the position, and 0 when calling from
10319 x_make_frame_visible (in that case, XOFF and YOFF are the current
10320 position values). It is -1 when calling from x_set_frame_parameters,
10321 which means, do adjust for borders but don't change the gravity. */
10323 void
10324 x_set_offset (struct frame *f, register int xoff, register int yoff, int change_gravity)
10326 int modified_top, modified_left;
10327 #ifdef USE_GTK
10328 int scale = xg_get_scale (f);
10329 #endif
10331 if (change_gravity > 0)
10333 f->top_pos = yoff;
10334 f->left_pos = xoff;
10335 f->size_hint_flags &= ~ (XNegative | YNegative);
10336 if (xoff < 0)
10337 f->size_hint_flags |= XNegative;
10338 if (yoff < 0)
10339 f->size_hint_flags |= YNegative;
10340 f->win_gravity = NorthWestGravity;
10343 x_calc_absolute_position (f);
10345 block_input ();
10346 x_wm_set_size_hint (f, 0, false);
10348 #ifdef USE_GTK
10349 if (x_gtk_use_window_move)
10351 /* When a position change was requested and the outer GTK widget
10352 has been realized already, leave it to gtk_window_move to
10353 DTRT and return. Used for Bug#25851 and Bug#25943. Convert
10354 from X pixels to GTK scaled pixels. */
10355 if (change_gravity != 0 && FRAME_GTK_OUTER_WIDGET (f))
10356 gtk_window_move (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)),
10357 f->left_pos / scale, f->top_pos / scale);
10358 unblock_input ();
10359 return;
10361 #endif /* USE_GTK */
10363 modified_left = f->left_pos;
10364 modified_top = f->top_pos;
10366 if (change_gravity != 0 && FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A)
10368 /* Some WMs (twm, wmaker at least) has an offset that is smaller
10369 than the WM decorations. So we use the calculated offset instead
10370 of the WM decoration sizes here (x/y_pixels_outer_diff). */
10371 modified_left += FRAME_X_OUTPUT (f)->move_offset_left;
10372 modified_top += FRAME_X_OUTPUT (f)->move_offset_top;
10375 #ifdef USE_GTK
10376 /* Make sure we adjust for possible scaling. */
10377 gtk_window_move (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)),
10378 modified_left / scale, modified_top / scale);
10379 #else
10380 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
10381 modified_left, modified_top);
10382 #endif
10384 x_sync_with_move (f, f->left_pos, f->top_pos,
10385 FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN);
10387 /* change_gravity is non-zero when this function is called from Lisp to
10388 programmatically move a frame. In that case, we call
10389 x_check_expected_move to discover if we have a "Type A" or "Type B"
10390 window manager, and, for a "Type A" window manager, adjust the position
10391 of the frame.
10393 We call x_check_expected_move if a programmatic move occurred, and
10394 either the window manager type (A/B) is unknown or it is Type A but we
10395 need to compute the top/left offset adjustment for this frame. */
10397 if (change_gravity != 0
10398 && !FRAME_PARENT_FRAME (f)
10399 && (FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN
10400 || (FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A
10401 && (FRAME_X_OUTPUT (f)->move_offset_left == 0
10402 && FRAME_X_OUTPUT (f)->move_offset_top == 0))))
10403 x_check_expected_move (f, modified_left, modified_top);
10405 unblock_input ();
10408 /* Return true if _NET_SUPPORTING_WM_CHECK window exists and _NET_SUPPORTED
10409 on the root window for frame F contains ATOMNAME.
10410 This is how a WM check shall be done according to the Window Manager
10411 Specification/Extended Window Manager Hints at
10412 http://freedesktop.org/wiki/Specifications/wm-spec. */
10414 bool
10415 x_wm_supports (struct frame *f, Atom want_atom)
10417 Atom actual_type;
10418 unsigned long actual_size, bytes_remaining;
10419 int i, rc, actual_format;
10420 bool ret;
10421 Window wmcheck_window;
10422 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10423 Window target_window = dpyinfo->root_window;
10424 int max_len = 65536;
10425 Display *dpy = FRAME_X_DISPLAY (f);
10426 unsigned char *tmp_data = NULL;
10427 Atom target_type = XA_WINDOW;
10429 block_input ();
10431 x_catch_errors (dpy);
10432 rc = XGetWindowProperty (dpy, target_window,
10433 dpyinfo->Xatom_net_supporting_wm_check,
10434 0, max_len, False, target_type,
10435 &actual_type, &actual_format, &actual_size,
10436 &bytes_remaining, &tmp_data);
10438 if (rc != Success || actual_type != XA_WINDOW || x_had_errors_p (dpy))
10440 if (tmp_data) XFree (tmp_data);
10441 x_uncatch_errors ();
10442 unblock_input ();
10443 return false;
10446 wmcheck_window = *(Window *) tmp_data;
10447 XFree (tmp_data);
10449 /* Check if window exists. */
10450 XSelectInput (dpy, wmcheck_window, StructureNotifyMask);
10451 if (x_had_errors_p (dpy))
10453 x_uncatch_errors_after_check ();
10454 unblock_input ();
10455 return false;
10458 if (dpyinfo->net_supported_window != wmcheck_window)
10460 /* Window changed, reload atoms */
10461 if (dpyinfo->net_supported_atoms != NULL)
10462 XFree (dpyinfo->net_supported_atoms);
10463 dpyinfo->net_supported_atoms = NULL;
10464 dpyinfo->nr_net_supported_atoms = 0;
10465 dpyinfo->net_supported_window = 0;
10467 target_type = XA_ATOM;
10468 tmp_data = NULL;
10469 rc = XGetWindowProperty (dpy, target_window,
10470 dpyinfo->Xatom_net_supported,
10471 0, max_len, False, target_type,
10472 &actual_type, &actual_format, &actual_size,
10473 &bytes_remaining, &tmp_data);
10475 if (rc != Success || actual_type != XA_ATOM || x_had_errors_p (dpy))
10477 if (tmp_data) XFree (tmp_data);
10478 x_uncatch_errors ();
10479 unblock_input ();
10480 return false;
10483 dpyinfo->net_supported_atoms = (Atom *)tmp_data;
10484 dpyinfo->nr_net_supported_atoms = actual_size;
10485 dpyinfo->net_supported_window = wmcheck_window;
10488 ret = false;
10490 for (i = 0; !ret && i < dpyinfo->nr_net_supported_atoms; ++i)
10491 ret = dpyinfo->net_supported_atoms[i] == want_atom;
10493 x_uncatch_errors ();
10494 unblock_input ();
10496 return ret;
10499 static void
10500 set_wm_state (Lisp_Object frame, bool add, Atom atom, Atom value)
10502 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (XFRAME (frame));
10504 x_send_client_event (frame, make_number (0), frame,
10505 dpyinfo->Xatom_net_wm_state,
10506 make_number (32),
10507 /* 1 = add, 0 = remove */
10508 Fcons
10509 (make_number (add),
10510 Fcons
10511 (make_fixnum_or_float (atom),
10512 (value != 0
10513 ? list1 (make_fixnum_or_float (value))
10514 : Qnil))));
10517 void
10518 x_set_sticky (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
10520 Lisp_Object frame;
10521 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10523 XSETFRAME (frame, f);
10525 set_wm_state (frame, !NILP (new_value),
10526 dpyinfo->Xatom_net_wm_state_sticky, None);
10530 * x_set_skip_taskbar:
10532 * Set frame F's `skip-taskbar' parameter. If non-nil, this should
10533 * remove F's icon from the taskbar associated with the display of F's
10534 * window-system window and inhibit switching to F's window via
10535 * <Alt>-<TAB>. If nil, lift these restrictions.
10537 * Some window managers may not honor this parameter.
10539 void
10540 x_set_skip_taskbar (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
10542 if (!EQ (new_value, old_value))
10544 #ifdef USE_GTK
10545 xg_set_skip_taskbar (f, new_value);
10546 #else
10547 Lisp_Object frame;
10548 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10550 XSETFRAME (frame, f);
10551 set_wm_state (frame, !NILP (new_value),
10552 dpyinfo->Xatom_net_wm_state_skip_taskbar, None);
10553 #endif /* USE_GTK */
10554 FRAME_SKIP_TASKBAR (f) = !NILP (new_value);
10559 * x_set_z_group:
10561 * Set frame F's `z-group' parameter. If `above', F's window-system
10562 * window is displayed above all windows that do not have the `above'
10563 * property set. If nil, F's window is shown below all windows that
10564 * have the `above' property set and above all windows that have the
10565 * `below' property set. If `below', F's window is displayed below all
10566 * windows that do not have the `below' property set.
10568 * Some window managers may not honor this parameter.
10570 void
10571 x_set_z_group (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
10573 /* We don't care about old_value. The window manager might have
10574 reset the value without telling us. */
10575 Lisp_Object frame;
10576 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10578 XSETFRAME (frame, f);
10580 if (NILP (new_value))
10582 set_wm_state (frame, false,
10583 dpyinfo->Xatom_net_wm_state_above, None);
10584 set_wm_state (frame, false,
10585 dpyinfo->Xatom_net_wm_state_below, None);
10586 FRAME_Z_GROUP (f) = z_group_none;
10588 else if (EQ (new_value, Qabove))
10590 set_wm_state (frame, true,
10591 dpyinfo->Xatom_net_wm_state_above, None);
10592 set_wm_state (frame, false,
10593 dpyinfo->Xatom_net_wm_state_below, None);
10594 FRAME_Z_GROUP (f) = z_group_above;
10596 else if (EQ (new_value, Qbelow))
10598 set_wm_state (frame, false,
10599 dpyinfo->Xatom_net_wm_state_above, None);
10600 set_wm_state (frame, true,
10601 dpyinfo->Xatom_net_wm_state_below, None);
10602 FRAME_Z_GROUP (f) = z_group_below;
10604 else if (EQ (new_value, Qabove_suspended))
10606 set_wm_state (frame, false,
10607 dpyinfo->Xatom_net_wm_state_above, None);
10608 FRAME_Z_GROUP (f) = z_group_above_suspended;
10610 else
10611 error ("Invalid z-group specification");
10615 /* Return the current _NET_WM_STATE.
10616 SIZE_STATE is set to one of the FULLSCREEN_* values.
10617 Set *STICKY to the sticky state.
10619 Return true iff we are not hidden. */
10621 static bool
10622 get_current_wm_state (struct frame *f,
10623 Window window,
10624 int *size_state,
10625 bool *sticky)
10627 unsigned long actual_size;
10628 int i;
10629 bool is_hidden = false;
10630 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10631 long max_len = 65536;
10632 Atom target_type = XA_ATOM;
10633 /* If XCB is available, we can avoid three XSync calls. */
10634 #ifdef USE_XCB
10635 xcb_get_property_cookie_t prop_cookie;
10636 xcb_get_property_reply_t *prop;
10637 xcb_atom_t *reply_data;
10638 #else
10639 Display *dpy = FRAME_X_DISPLAY (f);
10640 unsigned long bytes_remaining;
10641 int rc, actual_format;
10642 Atom actual_type;
10643 unsigned char *tmp_data = NULL;
10644 Atom *reply_data;
10645 #endif
10647 *sticky = false;
10648 *size_state = FULLSCREEN_NONE;
10650 block_input ();
10652 #ifdef USE_XCB
10653 prop_cookie = xcb_get_property (dpyinfo->xcb_connection, 0, window,
10654 dpyinfo->Xatom_net_wm_state,
10655 target_type, 0, max_len);
10656 prop = xcb_get_property_reply (dpyinfo->xcb_connection, prop_cookie, NULL);
10657 if (prop && prop->type == target_type)
10659 int actual_bytes = xcb_get_property_value_length (prop);
10660 eassume (0 <= actual_bytes);
10661 actual_size = actual_bytes / sizeof *reply_data;
10662 reply_data = xcb_get_property_value (prop);
10664 else
10666 actual_size = 0;
10667 is_hidden = FRAME_ICONIFIED_P (f);
10669 #else
10670 x_catch_errors (dpy);
10671 rc = XGetWindowProperty (dpy, window, dpyinfo->Xatom_net_wm_state,
10672 0, max_len, False, target_type,
10673 &actual_type, &actual_format, &actual_size,
10674 &bytes_remaining, &tmp_data);
10676 if (rc == Success && actual_type == target_type && ! x_had_errors_p (dpy))
10677 reply_data = (Atom *) tmp_data;
10678 else
10680 actual_size = 0;
10681 is_hidden = FRAME_ICONIFIED_P (f);
10684 x_uncatch_errors ();
10685 #endif
10687 for (i = 0; i < actual_size; ++i)
10689 Atom a = reply_data[i];
10690 if (a == dpyinfo->Xatom_net_wm_state_hidden)
10691 is_hidden = true;
10692 else if (a == dpyinfo->Xatom_net_wm_state_maximized_horz)
10694 if (*size_state == FULLSCREEN_HEIGHT)
10695 *size_state = FULLSCREEN_MAXIMIZED;
10696 else
10697 *size_state = FULLSCREEN_WIDTH;
10699 else if (a == dpyinfo->Xatom_net_wm_state_maximized_vert)
10701 if (*size_state == FULLSCREEN_WIDTH)
10702 *size_state = FULLSCREEN_MAXIMIZED;
10703 else
10704 *size_state = FULLSCREEN_HEIGHT;
10706 else if (a == dpyinfo->Xatom_net_wm_state_fullscreen)
10707 *size_state = FULLSCREEN_BOTH;
10708 else if (a == dpyinfo->Xatom_net_wm_state_sticky)
10709 *sticky = true;
10712 #ifdef USE_XCB
10713 free (prop);
10714 #else
10715 if (tmp_data) XFree (tmp_data);
10716 #endif
10718 unblock_input ();
10719 return ! is_hidden;
10722 /* Do fullscreen as specified in extended window manager hints */
10724 static bool
10725 do_ewmh_fullscreen (struct frame *f)
10727 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10728 bool have_net_atom = x_wm_supports (f, dpyinfo->Xatom_net_wm_state);
10729 int cur;
10730 bool dummy;
10732 get_current_wm_state (f, FRAME_OUTER_WINDOW (f), &cur, &dummy);
10734 /* Some window managers don't say they support _NET_WM_STATE, but they do say
10735 they support _NET_WM_STATE_FULLSCREEN. Try that also. */
10736 if (!have_net_atom)
10737 have_net_atom = x_wm_supports (f, dpyinfo->Xatom_net_wm_state_fullscreen);
10739 if (have_net_atom && cur != f->want_fullscreen)
10741 Lisp_Object frame;
10743 XSETFRAME (frame, f);
10745 /* Keep number of calls to set_wm_state as low as possible.
10746 Some window managers, or possible Gtk+, hangs when too many
10747 are sent at once. */
10748 switch (f->want_fullscreen)
10750 case FULLSCREEN_BOTH:
10751 if (cur != FULLSCREEN_BOTH)
10752 set_wm_state (frame, true, dpyinfo->Xatom_net_wm_state_fullscreen,
10753 None);
10754 break;
10755 case FULLSCREEN_WIDTH:
10756 if (x_frame_normalize_before_maximize && cur == FULLSCREEN_MAXIMIZED)
10758 set_wm_state (frame, false,
10759 dpyinfo->Xatom_net_wm_state_maximized_horz,
10760 dpyinfo->Xatom_net_wm_state_maximized_vert);
10761 set_wm_state (frame, true,
10762 dpyinfo->Xatom_net_wm_state_maximized_horz, None);
10764 else
10766 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_HEIGHT
10767 || cur == FULLSCREEN_MAXIMIZED)
10768 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
10769 dpyinfo->Xatom_net_wm_state_maximized_vert);
10770 if (cur != FULLSCREEN_MAXIMIZED || x_frame_normalize_before_maximize)
10771 set_wm_state (frame, true,
10772 dpyinfo->Xatom_net_wm_state_maximized_horz, None);
10774 break;
10775 case FULLSCREEN_HEIGHT:
10776 if (x_frame_normalize_before_maximize && cur == FULLSCREEN_MAXIMIZED)
10778 set_wm_state (frame, false,
10779 dpyinfo->Xatom_net_wm_state_maximized_horz,
10780 dpyinfo->Xatom_net_wm_state_maximized_vert);
10781 set_wm_state (frame, true,
10782 dpyinfo->Xatom_net_wm_state_maximized_vert, None);
10784 else
10786 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_WIDTH
10787 || cur == FULLSCREEN_MAXIMIZED)
10788 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
10789 dpyinfo->Xatom_net_wm_state_maximized_horz);
10790 if (cur != FULLSCREEN_MAXIMIZED || x_frame_normalize_before_maximize)
10791 set_wm_state (frame, true,
10792 dpyinfo->Xatom_net_wm_state_maximized_vert, None);
10794 break;
10795 case FULLSCREEN_MAXIMIZED:
10796 if (x_frame_normalize_before_maximize && cur == FULLSCREEN_BOTH)
10798 set_wm_state (frame, false,
10799 dpyinfo->Xatom_net_wm_state_fullscreen, None);
10800 set_wm_state (frame, true,
10801 dpyinfo->Xatom_net_wm_state_maximized_horz,
10802 dpyinfo->Xatom_net_wm_state_maximized_vert);
10804 else if (x_frame_normalize_before_maximize && cur == FULLSCREEN_WIDTH)
10806 set_wm_state (frame, false,
10807 dpyinfo->Xatom_net_wm_state_maximized_horz, None);
10808 set_wm_state (frame, true,
10809 dpyinfo->Xatom_net_wm_state_maximized_horz,
10810 dpyinfo->Xatom_net_wm_state_maximized_vert);
10812 else if (x_frame_normalize_before_maximize && cur == FULLSCREEN_HEIGHT)
10814 set_wm_state (frame, false,
10815 dpyinfo->Xatom_net_wm_state_maximized_vert, None);
10816 set_wm_state (frame, true,
10817 dpyinfo->Xatom_net_wm_state_maximized_horz,
10818 dpyinfo->Xatom_net_wm_state_maximized_vert);
10820 else
10822 if (cur == FULLSCREEN_BOTH)
10823 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
10824 None);
10825 else if (cur == FULLSCREEN_HEIGHT)
10826 set_wm_state (frame, true,
10827 dpyinfo->Xatom_net_wm_state_maximized_horz, None);
10828 else if (cur == FULLSCREEN_WIDTH)
10829 set_wm_state (frame, true, None,
10830 dpyinfo->Xatom_net_wm_state_maximized_vert);
10831 else
10832 set_wm_state (frame, true,
10833 dpyinfo->Xatom_net_wm_state_maximized_horz,
10834 dpyinfo->Xatom_net_wm_state_maximized_vert);
10836 break;
10837 case FULLSCREEN_NONE:
10838 if (cur == FULLSCREEN_BOTH)
10839 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
10840 None);
10841 else
10842 set_wm_state (frame, false,
10843 dpyinfo->Xatom_net_wm_state_maximized_horz,
10844 dpyinfo->Xatom_net_wm_state_maximized_vert);
10847 f->want_fullscreen = FULLSCREEN_NONE;
10851 return have_net_atom;
10854 static void
10855 XTfullscreen_hook (struct frame *f)
10857 if (FRAME_VISIBLE_P (f))
10859 block_input ();
10860 x_check_fullscreen (f);
10861 x_sync (f);
10862 unblock_input ();
10867 static bool
10868 x_handle_net_wm_state (struct frame *f, const XPropertyEvent *event)
10870 int value = FULLSCREEN_NONE;
10871 Lisp_Object lval;
10872 bool sticky = false;
10873 bool not_hidden = get_current_wm_state (f, event->window, &value, &sticky);
10875 lval = Qnil;
10876 switch (value)
10878 case FULLSCREEN_WIDTH:
10879 lval = Qfullwidth;
10880 break;
10881 case FULLSCREEN_HEIGHT:
10882 lval = Qfullheight;
10883 break;
10884 case FULLSCREEN_BOTH:
10885 lval = Qfullboth;
10886 break;
10887 case FULLSCREEN_MAXIMIZED:
10888 lval = Qmaximized;
10889 break;
10892 frame_size_history_add
10893 (f, Qx_handle_net_wm_state, 0, 0,
10894 list2 (get_frame_param (f, Qfullscreen), lval));
10896 store_frame_param (f, Qfullscreen, lval);
10897 store_frame_param (f, Qsticky, sticky ? Qt : Qnil);
10899 return not_hidden;
10902 /* Check if we need to resize the frame due to a fullscreen request.
10903 If so needed, resize the frame. */
10904 static void
10905 x_check_fullscreen (struct frame *f)
10907 Lisp_Object lval = Qnil;
10909 if (do_ewmh_fullscreen (f))
10910 return;
10912 if (f->output_data.x->parent_desc != FRAME_DISPLAY_INFO (f)->root_window)
10913 return; /* Only fullscreen without WM or with EWM hints (above). */
10915 /* Setting fullscreen to nil doesn't do anything. We could save the
10916 last non-fullscreen size and restore it, but it seems like a
10917 lot of work for this unusual case (no window manager running). */
10919 if (f->want_fullscreen != FULLSCREEN_NONE)
10921 int width = FRAME_PIXEL_WIDTH (f), height = FRAME_PIXEL_HEIGHT (f);
10922 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10924 switch (f->want_fullscreen)
10926 /* No difference between these two when there is no WM */
10927 case FULLSCREEN_MAXIMIZED:
10928 lval = Qmaximized;
10929 width = x_display_pixel_width (dpyinfo);
10930 height = x_display_pixel_height (dpyinfo);
10931 break;
10932 case FULLSCREEN_BOTH:
10933 lval = Qfullboth;
10934 width = x_display_pixel_width (dpyinfo);
10935 height = x_display_pixel_height (dpyinfo);
10936 break;
10937 case FULLSCREEN_WIDTH:
10938 lval = Qfullwidth;
10939 width = x_display_pixel_width (dpyinfo);
10940 height = height + FRAME_MENUBAR_HEIGHT (f);
10941 break;
10942 case FULLSCREEN_HEIGHT:
10943 lval = Qfullheight;
10944 height = x_display_pixel_height (dpyinfo);
10945 break;
10946 default:
10947 emacs_abort ();
10950 frame_size_history_add
10951 (f, Qx_check_fullscreen, width, height, Qnil);
10953 x_wm_set_size_hint (f, 0, false);
10955 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
10956 width, height);
10958 if (FRAME_VISIBLE_P (f))
10959 x_wait_for_event (f, ConfigureNotify);
10960 else
10962 change_frame_size (f, width, height - FRAME_MENUBAR_HEIGHT (f),
10963 false, true, false, true);
10964 x_sync (f);
10968 /* `x_net_wm_state' might have reset the fullscreen frame parameter,
10969 restore it. */
10970 store_frame_param (f, Qfullscreen, lval);
10973 /* This function is called by x_set_offset to determine whether the window
10974 manager interfered with the positioning of the frame. Type A window
10975 managers position the surrounding window manager decorations a small
10976 amount above and left of the user-supplied position. Type B window
10977 managers position the surrounding window manager decorations at the
10978 user-specified position. If we detect a Type A window manager, we
10979 compensate by moving the window right and down by the proper amount. */
10981 static void
10982 x_check_expected_move (struct frame *f, int expected_left, int expected_top)
10984 int current_left = 0, current_top = 0;
10986 /* x_real_positions returns the left and top offsets of the outermost
10987 window manager window around the frame. */
10989 x_real_positions (f, &current_left, &current_top);
10991 if (current_left != expected_left || current_top != expected_top)
10993 /* It's a "Type A" window manager. */
10995 int adjusted_left;
10996 int adjusted_top;
10998 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_A;
10999 FRAME_X_OUTPUT (f)->move_offset_left = expected_left - current_left;
11000 FRAME_X_OUTPUT (f)->move_offset_top = expected_top - current_top;
11002 /* Now fix the mispositioned frame's location. */
11004 adjusted_left = expected_left + FRAME_X_OUTPUT (f)->move_offset_left;
11005 adjusted_top = expected_top + FRAME_X_OUTPUT (f)->move_offset_top;
11007 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11008 adjusted_left, adjusted_top);
11010 x_sync_with_move (f, expected_left, expected_top, false);
11012 else
11013 /* It's a "Type B" window manager. We don't have to adjust the
11014 frame's position. */
11016 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_B;
11020 /* Wait for XGetGeometry to return up-to-date position information for a
11021 recently-moved frame. Call this immediately after calling XMoveWindow.
11022 If FUZZY is non-zero, then LEFT and TOP are just estimates of where the
11023 frame has been moved to, so we use a fuzzy position comparison instead
11024 of an exact comparison. */
11026 static void
11027 x_sync_with_move (struct frame *f, int left, int top, bool fuzzy)
11029 int count = 0;
11031 while (count++ < 50)
11033 int current_left = 0, current_top = 0;
11035 /* In theory, this call to XSync only needs to happen once, but in
11036 practice, it doesn't seem to work, hence the need for the surrounding
11037 loop. */
11039 XSync (FRAME_X_DISPLAY (f), False);
11040 x_real_positions (f, &current_left, &current_top);
11042 if (fuzzy)
11044 /* The left fuzz-factor is 10 pixels. The top fuzz-factor is 40
11045 pixels. */
11047 if (eabs (current_left - left) <= 10
11048 && eabs (current_top - top) <= 40)
11049 return;
11051 else if (current_left == left && current_top == top)
11052 return;
11055 /* As a last resort, just wait 0.5 seconds and hope that XGetGeometry
11056 will then return up-to-date position info. */
11058 wait_reading_process_output (0, 500000000, 0, false, Qnil, NULL, 0);
11062 /* Wait for an event on frame F matching EVENTTYPE. */
11063 void
11064 x_wait_for_event (struct frame *f, int eventtype)
11066 if (!FLOATP (Vx_wait_for_event_timeout))
11067 return;
11069 int level = interrupt_input_blocked;
11070 fd_set fds;
11071 struct timespec tmo, tmo_at, time_now;
11072 int fd = ConnectionNumber (FRAME_X_DISPLAY (f));
11074 f->wait_event_type = eventtype;
11076 /* Default timeout is 0.1 second. Hopefully not noticeable. */
11077 double timeout = XFLOAT_DATA (Vx_wait_for_event_timeout);
11078 time_t timeout_seconds = (time_t) timeout;
11079 tmo = make_timespec
11080 (timeout_seconds, (long int) ((timeout - timeout_seconds)
11081 * 1000 * 1000 * 1000));
11082 tmo_at = timespec_add (current_timespec (), tmo);
11084 while (f->wait_event_type)
11086 pending_signals = true;
11087 totally_unblock_input ();
11088 /* XTread_socket is called after unblock. */
11089 block_input ();
11090 interrupt_input_blocked = level;
11092 FD_ZERO (&fds);
11093 FD_SET (fd, &fds);
11095 time_now = current_timespec ();
11096 if (timespec_cmp (tmo_at, time_now) < 0)
11097 break;
11099 tmo = timespec_sub (tmo_at, time_now);
11100 if (pselect (fd + 1, &fds, NULL, NULL, &tmo, NULL) == 0)
11101 break; /* Timeout */
11104 f->wait_event_type = 0;
11108 /* Change the size of frame F's X window to WIDTH/HEIGHT in the case F
11109 doesn't have a widget. If CHANGE_GRAVITY, change to
11110 top-left-corner window gravity for this size change and subsequent
11111 size changes. Otherwise leave the window gravity unchanged. */
11113 static void
11114 x_set_window_size_1 (struct frame *f, bool change_gravity,
11115 int width, int height)
11117 int pixelwidth = FRAME_TEXT_TO_PIXEL_WIDTH (f, width);
11118 int pixelheight = FRAME_TEXT_TO_PIXEL_HEIGHT (f, height);
11119 int old_width = FRAME_PIXEL_WIDTH (f);
11120 int old_height = FRAME_PIXEL_HEIGHT (f);
11121 Lisp_Object fullscreen = get_frame_param (f, Qfullscreen);
11123 if (change_gravity)
11124 f->win_gravity = NorthWestGravity;
11125 x_wm_set_size_hint (f, 0, false);
11127 /* When the frame is fullheight and we only want to change the width
11128 or it is fullwidth and we only want to change the height we should
11129 be able to preserve the fullscreen property. However, due to the
11130 fact that we have to send a resize request anyway, the window
11131 manager will abolish it. At least the respective size should
11132 remain unchanged but giving the frame back its normal size will
11133 be broken ... */
11134 if (EQ (fullscreen, Qfullwidth) && width == FRAME_TEXT_WIDTH (f))
11136 frame_size_history_add
11137 (f, Qx_set_window_size_1, width, height,
11138 list2 (make_number (old_height),
11139 make_number (pixelheight + FRAME_MENUBAR_HEIGHT (f))));
11141 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11142 old_width, pixelheight + FRAME_MENUBAR_HEIGHT (f));
11144 else if (EQ (fullscreen, Qfullheight) && height == FRAME_TEXT_HEIGHT (f))
11146 frame_size_history_add
11147 (f, Qx_set_window_size_2, width, height,
11148 list2 (make_number (old_width), make_number (pixelwidth)));
11150 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11151 pixelwidth, old_height);
11154 else
11156 frame_size_history_add
11157 (f, Qx_set_window_size_3, width, height,
11158 list3 (make_number (pixelwidth + FRAME_TOOLBAR_WIDTH (f)),
11159 make_number (pixelheight + FRAME_TOOLBAR_HEIGHT (f)
11160 + FRAME_MENUBAR_HEIGHT (f)),
11161 make_number (FRAME_MENUBAR_HEIGHT (f))));
11163 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11164 pixelwidth, pixelheight + FRAME_MENUBAR_HEIGHT (f));
11165 fullscreen = Qnil;
11170 /* We've set {FRAME,PIXEL}_{WIDTH,HEIGHT} to the values we hope to
11171 receive in the ConfigureNotify event; if we get what we asked
11172 for, then the event won't cause the screen to become garbaged, so
11173 we have to make sure to do it here. */
11174 SET_FRAME_GARBAGED (f);
11176 /* Now, strictly speaking, we can't be sure that this is accurate,
11177 but the window manager will get around to dealing with the size
11178 change request eventually, and we'll hear how it went when the
11179 ConfigureNotify event gets here.
11181 We could just not bother storing any of this information here,
11182 and let the ConfigureNotify event set everything up, but that
11183 might be kind of confusing to the Lisp code, since size changes
11184 wouldn't be reported in the frame parameters until some random
11185 point in the future when the ConfigureNotify event arrives.
11187 Pass true for DELAY since we can't run Lisp code inside of
11188 a BLOCK_INPUT. */
11190 /* But the ConfigureNotify may in fact never arrive, and then this is
11191 not right if the frame is visible. Instead wait (with timeout)
11192 for the ConfigureNotify. */
11193 if (FRAME_VISIBLE_P (f))
11195 x_wait_for_event (f, ConfigureNotify);
11197 if (!NILP (fullscreen))
11198 /* Try to restore fullscreen state. */
11200 store_frame_param (f, Qfullscreen, fullscreen);
11201 x_set_fullscreen (f, fullscreen, fullscreen);
11204 else
11206 change_frame_size (f, width, height, false, true, false, true);
11207 x_sync (f);
11212 /* Call this to change the size of frame F's x-window.
11213 If CHANGE_GRAVITY, change to top-left-corner window gravity
11214 for this size change and subsequent size changes.
11215 Otherwise we leave the window gravity unchanged. */
11217 void
11218 x_set_window_size (struct frame *f, bool change_gravity,
11219 int width, int height, bool pixelwise)
11221 block_input ();
11223 /* The following breaks our calculations. If it's really needed,
11224 think of something else. */
11225 #if false
11226 if (!FRAME_TOOLTIP_P (f))
11228 int text_width, text_height;
11230 /* When the frame is maximized/fullscreen or running under for
11231 example Xmonad, x_set_window_size_1 will be a no-op.
11232 In that case, the right thing to do is extend rows/width to
11233 the current frame size. We do that first if x_set_window_size_1
11234 turns out to not be a no-op (there is no way to know).
11235 The size will be adjusted again if the frame gets a
11236 ConfigureNotify event as a result of x_set_window_size. */
11237 int pixelh = FRAME_PIXEL_HEIGHT (f);
11238 #ifdef USE_X_TOOLKIT
11239 /* The menu bar is not part of text lines. The tool bar
11240 is however. */
11241 pixelh -= FRAME_MENUBAR_HEIGHT (f);
11242 #endif
11243 text_width = FRAME_PIXEL_TO_TEXT_WIDTH (f, FRAME_PIXEL_WIDTH (f));
11244 text_height = FRAME_PIXEL_TO_TEXT_HEIGHT (f, pixelh);
11246 change_frame_size (f, text_width, text_height, false, true, false, true);
11248 #endif
11250 /* Pixelize width and height, if necessary. */
11251 if (! pixelwise)
11253 width = width * FRAME_COLUMN_WIDTH (f);
11254 height = height * FRAME_LINE_HEIGHT (f);
11257 #ifdef USE_GTK
11258 if (FRAME_GTK_WIDGET (f))
11259 xg_frame_set_char_size (f, width, height);
11260 else
11261 x_set_window_size_1 (f, change_gravity, width, height);
11262 #else /* not USE_GTK */
11263 x_set_window_size_1 (f, change_gravity, width, height);
11264 x_clear_under_internal_border (f);
11265 #endif /* not USE_GTK */
11267 /* If cursor was outside the new size, mark it as off. */
11268 mark_window_cursors_off (XWINDOW (f->root_window));
11270 /* Clear out any recollection of where the mouse highlighting was,
11271 since it might be in a place that's outside the new frame size.
11272 Actually checking whether it is outside is a pain in the neck,
11273 so don't try--just let the highlighting be done afresh with new size. */
11274 cancel_mouse_face (f);
11276 unblock_input ();
11278 do_pending_window_change (false);
11281 /* Move the mouse to position pixel PIX_X, PIX_Y relative to frame F. */
11283 void
11284 frame_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
11286 block_input ();
11288 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
11289 0, 0, 0, 0, pix_x, pix_y);
11290 unblock_input ();
11293 /* Raise frame F. */
11295 void
11296 x_raise_frame (struct frame *f)
11298 block_input ();
11299 if (FRAME_VISIBLE_P (f))
11300 XRaiseWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
11301 XFlush (FRAME_X_DISPLAY (f));
11302 unblock_input ();
11305 /* Lower frame F. */
11307 static void
11308 x_lower_frame (struct frame *f)
11310 if (FRAME_VISIBLE_P (f))
11312 block_input ();
11313 XLowerWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
11314 XFlush (FRAME_X_DISPLAY (f));
11315 unblock_input ();
11319 /* Request focus with XEmbed */
11321 void
11322 xembed_request_focus (struct frame *f)
11324 /* See XEmbed Protocol Specification at
11325 http://freedesktop.org/wiki/Specifications/xembed-spec */
11326 if (FRAME_VISIBLE_P (f))
11327 xembed_send_message (f, CurrentTime,
11328 XEMBED_REQUEST_FOCUS, 0, 0, 0);
11331 /* Activate frame with Extended Window Manager Hints */
11333 void
11334 x_ewmh_activate_frame (struct frame *f)
11336 /* See Window Manager Specification/Extended Window Manager Hints at
11337 http://freedesktop.org/wiki/Specifications/wm-spec */
11339 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
11341 if (FRAME_VISIBLE_P (f) && x_wm_supports (f, dpyinfo->Xatom_net_active_window))
11343 Lisp_Object frame;
11344 XSETFRAME (frame, f);
11345 x_send_client_event (frame, make_number (0), frame,
11346 dpyinfo->Xatom_net_active_window,
11347 make_number (32),
11348 list2i (1, dpyinfo->last_user_time));
11352 static void
11353 XTframe_raise_lower (struct frame *f, bool raise_flag)
11355 if (raise_flag)
11356 x_raise_frame (f);
11357 else
11358 x_lower_frame (f);
11361 /* XEmbed implementation. */
11363 #if defined USE_X_TOOLKIT || ! defined USE_GTK
11365 /* XEmbed implementation. */
11367 #define XEMBED_VERSION 0
11369 static void
11370 xembed_set_info (struct frame *f, enum xembed_info flags)
11372 unsigned long data[2];
11373 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
11375 data[0] = XEMBED_VERSION;
11376 data[1] = flags;
11378 XChangeProperty (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11379 dpyinfo->Xatom_XEMBED_INFO, dpyinfo->Xatom_XEMBED_INFO,
11380 32, PropModeReplace, (unsigned char *) data, 2);
11382 #endif /* defined USE_X_TOOLKIT || ! defined USE_GTK */
11384 static void
11385 xembed_send_message (struct frame *f, Time t, enum xembed_message msg,
11386 long int detail, long int data1, long int data2)
11388 XEvent event;
11390 event.xclient.type = ClientMessage;
11391 event.xclient.window = FRAME_X_OUTPUT (f)->parent_desc;
11392 event.xclient.message_type = FRAME_DISPLAY_INFO (f)->Xatom_XEMBED;
11393 event.xclient.format = 32;
11394 event.xclient.data.l[0] = t;
11395 event.xclient.data.l[1] = msg;
11396 event.xclient.data.l[2] = detail;
11397 event.xclient.data.l[3] = data1;
11398 event.xclient.data.l[4] = data2;
11400 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_OUTPUT (f)->parent_desc,
11401 False, NoEventMask, &event);
11402 XSync (FRAME_X_DISPLAY (f), False);
11405 /* Change of visibility. */
11407 /* This tries to wait until the frame is really visible, depending on
11408 the value of Vx_wait_for_event_timeout.
11409 However, if the window manager asks the user where to position
11410 the frame, this will return before the user finishes doing that.
11411 The frame will not actually be visible at that time,
11412 but it will become visible later when the window manager
11413 finishes with it. */
11415 void
11416 x_make_frame_visible (struct frame *f)
11418 if (FRAME_PARENT_FRAME (f))
11420 if (!FRAME_VISIBLE_P (f))
11422 block_input ();
11423 #ifdef USE_GTK
11424 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
11425 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11426 f->left_pos, f->top_pos);
11427 #else
11428 XMapRaised (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
11429 #endif
11430 unblock_input ();
11432 SET_FRAME_VISIBLE (f, true);
11433 SET_FRAME_ICONIFIED (f, false);
11435 return;
11438 block_input ();
11440 x_set_bitmap_icon (f);
11442 if (! FRAME_VISIBLE_P (f))
11444 /* We test asked_for_visible here to make sure we don't
11445 call x_set_offset a second time
11446 if we get to x_make_frame_visible a second time
11447 before the window gets really visible. */
11448 if (! FRAME_ICONIFIED_P (f)
11449 && ! FRAME_X_EMBEDDED_P (f)
11450 && ! f->output_data.x->asked_for_visible)
11451 x_set_offset (f, f->left_pos, f->top_pos, 0);
11453 f->output_data.x->asked_for_visible = true;
11455 if (! EQ (Vx_no_window_manager, Qt))
11456 x_wm_set_window_state (f, NormalState);
11457 #ifdef USE_X_TOOLKIT
11458 if (FRAME_X_EMBEDDED_P (f))
11459 xembed_set_info (f, XEMBED_MAPPED);
11460 else
11462 /* This was XtPopup, but that did nothing for an iconified frame. */
11463 XtMapWidget (f->output_data.x->widget);
11465 #else /* not USE_X_TOOLKIT */
11466 #ifdef USE_GTK
11467 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
11468 gtk_window_deiconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
11469 #else
11470 if (FRAME_X_EMBEDDED_P (f))
11471 xembed_set_info (f, XEMBED_MAPPED);
11472 else
11473 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11474 #endif /* not USE_GTK */
11475 #endif /* not USE_X_TOOLKIT */
11478 XFlush (FRAME_X_DISPLAY (f));
11480 /* Synchronize to ensure Emacs knows the frame is visible
11481 before we do anything else. We do this loop with input not blocked
11482 so that incoming events are handled. */
11484 Lisp_Object frame;
11485 /* This must be before UNBLOCK_INPUT
11486 since events that arrive in response to the actions above
11487 will set it when they are handled. */
11488 bool previously_visible = f->output_data.x->has_been_visible;
11490 XSETFRAME (frame, f);
11492 int original_left = f->left_pos;
11493 int original_top = f->top_pos;
11495 /* This must come after we set COUNT. */
11496 unblock_input ();
11498 /* We unblock here so that arriving X events are processed. */
11500 /* Now move the window back to where it was "supposed to be".
11501 But don't do it if the gravity is negative.
11502 When the gravity is negative, this uses a position
11503 that is 3 pixels too low. Perhaps that's really the border width.
11505 Don't do this if the window has never been visible before,
11506 because the window manager may choose the position
11507 and we don't want to override it. */
11509 if (!FRAME_VISIBLE_P (f)
11510 && !FRAME_ICONIFIED_P (f)
11511 && !FRAME_X_EMBEDDED_P (f)
11512 && !FRAME_PARENT_FRAME (f)
11513 && f->win_gravity == NorthWestGravity
11514 && previously_visible)
11516 Drawable rootw;
11517 int x, y;
11518 unsigned int width, height, border, depth;
11520 block_input ();
11522 /* On some window managers (such as FVWM) moving an existing
11523 window, even to the same place, causes the window manager
11524 to introduce an offset. This can cause the window to move
11525 to an unexpected location. Check the geometry (a little
11526 slow here) and then verify that the window is in the right
11527 place. If the window is not in the right place, move it
11528 there, and take the potential window manager hit. */
11529 XGetGeometry (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11530 &rootw, &x, &y, &width, &height, &border, &depth);
11532 if (original_left != x || original_top != y)
11533 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11534 original_left, original_top);
11536 unblock_input ();
11539 /* Try to wait for a MapNotify event (that is what tells us when a
11540 frame becomes visible). */
11542 #ifdef CYGWIN
11543 /* On Cygwin, which uses input polling, we need to force input to
11544 be read. See
11545 https://lists.gnu.org/r/emacs-devel/2013-12/msg00351.html
11546 and https://debbugs.gnu.org/cgi/bugreport.cgi?bug=24091#131.
11547 Fake an alarm signal to let the handler know that there's
11548 something to be read.
11550 It could be confusing if a real alarm arrives while processing
11551 the fake one. Turn it off and let the handler reset it. */
11552 int old_poll_suppress_count = poll_suppress_count;
11553 poll_suppress_count = 1;
11554 poll_for_input_1 ();
11555 poll_suppress_count = old_poll_suppress_count;
11556 #endif
11557 if (! FRAME_VISIBLE_P (f))
11558 x_wait_for_event (f, MapNotify);
11562 /* Change from mapped state to withdrawn state. */
11564 /* Make the frame visible (mapped and not iconified). */
11566 void
11567 x_make_frame_invisible (struct frame *f)
11569 Window window;
11571 /* Use the frame's outermost window, not the one we normally draw on. */
11572 window = FRAME_OUTER_WINDOW (f);
11574 /* Don't keep the highlight on an invisible frame. */
11575 if (FRAME_DISPLAY_INFO (f)->x_highlight_frame == f)
11576 FRAME_DISPLAY_INFO (f)->x_highlight_frame = 0;
11578 block_input ();
11580 /* Before unmapping the window, update the WM_SIZE_HINTS property to claim
11581 that the current position of the window is user-specified, rather than
11582 program-specified, so that when the window is mapped again, it will be
11583 placed at the same location, without forcing the user to position it
11584 by hand again (they have already done that once for this window.) */
11585 x_wm_set_size_hint (f, 0, true);
11587 #ifdef USE_GTK
11588 if (FRAME_GTK_OUTER_WIDGET (f))
11589 gtk_widget_hide (FRAME_GTK_OUTER_WIDGET (f));
11590 else
11591 #else
11592 if (FRAME_X_EMBEDDED_P (f))
11593 xembed_set_info (f, 0);
11594 else
11595 #endif
11597 if (! XWithdrawWindow (FRAME_X_DISPLAY (f), window,
11598 DefaultScreen (FRAME_X_DISPLAY (f))))
11600 unblock_input ();
11601 error ("Can't notify window manager of window withdrawal");
11604 x_sync (f);
11606 /* We can't distinguish this from iconification
11607 just by the event that we get from the server.
11608 So we can't win using the usual strategy of letting
11609 FRAME_SAMPLE_VISIBILITY set this. So do it by hand,
11610 and synchronize with the server to make sure we agree. */
11611 SET_FRAME_VISIBLE (f, 0);
11612 SET_FRAME_ICONIFIED (f, false);
11614 unblock_input ();
11617 /* Change window state from mapped to iconified. */
11619 void
11620 x_iconify_frame (struct frame *f)
11622 #ifdef USE_X_TOOLKIT
11623 int result;
11624 #endif
11626 /* Don't keep the highlight on an invisible frame. */
11627 if (FRAME_DISPLAY_INFO (f)->x_highlight_frame == f)
11628 FRAME_DISPLAY_INFO (f)->x_highlight_frame = 0;
11630 if (FRAME_ICONIFIED_P (f))
11631 return;
11633 block_input ();
11635 x_set_bitmap_icon (f);
11637 #if defined (USE_GTK)
11638 if (FRAME_GTK_OUTER_WIDGET (f))
11640 if (! FRAME_VISIBLE_P (f))
11641 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
11643 gtk_window_iconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
11644 SET_FRAME_VISIBLE (f, 0);
11645 SET_FRAME_ICONIFIED (f, true);
11646 unblock_input ();
11647 return;
11649 #endif
11651 #ifdef USE_X_TOOLKIT
11653 if (! FRAME_VISIBLE_P (f))
11655 if (! EQ (Vx_no_window_manager, Qt))
11656 x_wm_set_window_state (f, IconicState);
11657 /* This was XtPopup, but that did nothing for an iconified frame. */
11658 XtMapWidget (f->output_data.x->widget);
11659 /* The server won't give us any event to indicate
11660 that an invisible frame was changed to an icon,
11661 so we have to record it here. */
11662 SET_FRAME_VISIBLE (f, 0);
11663 SET_FRAME_ICONIFIED (f, true);
11664 unblock_input ();
11665 return;
11668 result = XIconifyWindow (FRAME_X_DISPLAY (f),
11669 XtWindow (f->output_data.x->widget),
11670 DefaultScreen (FRAME_X_DISPLAY (f)));
11671 unblock_input ();
11673 if (!result)
11674 error ("Can't notify window manager of iconification");
11676 SET_FRAME_ICONIFIED (f, true);
11677 SET_FRAME_VISIBLE (f, 0);
11679 block_input ();
11680 XFlush (FRAME_X_DISPLAY (f));
11681 unblock_input ();
11682 #else /* not USE_X_TOOLKIT */
11684 /* Make sure the X server knows where the window should be positioned,
11685 in case the user deiconifies with the window manager. */
11686 if (! FRAME_VISIBLE_P (f)
11687 && ! FRAME_ICONIFIED_P (f)
11688 && ! FRAME_X_EMBEDDED_P (f))
11689 x_set_offset (f, f->left_pos, f->top_pos, 0);
11691 /* Since we don't know which revision of X we're running, we'll use both
11692 the X11R3 and X11R4 techniques. I don't know if this is a good idea. */
11694 /* X11R4: send a ClientMessage to the window manager using the
11695 WM_CHANGE_STATE type. */
11697 XEvent msg;
11699 msg.xclient.window = FRAME_X_WINDOW (f);
11700 msg.xclient.type = ClientMessage;
11701 msg.xclient.message_type = FRAME_DISPLAY_INFO (f)->Xatom_wm_change_state;
11702 msg.xclient.format = 32;
11703 msg.xclient.data.l[0] = IconicState;
11705 if (! XSendEvent (FRAME_X_DISPLAY (f),
11706 DefaultRootWindow (FRAME_X_DISPLAY (f)),
11707 False,
11708 SubstructureRedirectMask | SubstructureNotifyMask,
11709 &msg))
11711 unblock_input ();
11712 error ("Can't notify window manager of iconification");
11716 /* X11R3: set the initial_state field of the window manager hints to
11717 IconicState. */
11718 x_wm_set_window_state (f, IconicState);
11720 if (!FRAME_VISIBLE_P (f))
11722 /* If the frame was withdrawn, before, we must map it. */
11723 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11726 SET_FRAME_ICONIFIED (f, true);
11727 SET_FRAME_VISIBLE (f, 0);
11729 XFlush (FRAME_X_DISPLAY (f));
11730 unblock_input ();
11731 #endif /* not USE_X_TOOLKIT */
11735 /* Free X resources of frame F. */
11737 void
11738 x_free_frame_resources (struct frame *f)
11740 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
11741 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
11742 #ifdef USE_X_TOOLKIT
11743 Lisp_Object bar;
11744 struct scroll_bar *b;
11745 #endif
11747 block_input ();
11749 /* If a display connection is dead, don't try sending more
11750 commands to the X server. */
11751 if (dpyinfo->display)
11753 /* Always exit with visible pointer to avoid weird issue
11754 with Xfixes (Bug#17609). */
11755 if (f->pointer_invisible)
11756 FRAME_DISPLAY_INFO (f)->toggle_visible_pointer (f, 0);
11758 /* We must free faces before destroying windows because some
11759 font-driver (e.g. xft) access a window while finishing a
11760 face. */
11761 free_frame_faces (f);
11762 tear_down_x_back_buffer (f);
11764 if (f->output_data.x->icon_desc)
11765 XDestroyWindow (FRAME_X_DISPLAY (f), f->output_data.x->icon_desc);
11767 #ifdef USE_X_TOOLKIT
11768 /* Explicitly destroy the scroll bars of the frame. Without
11769 this, we get "BadDrawable" errors from the toolkit later on,
11770 presumably from expose events generated for the disappearing
11771 toolkit scroll bars. */
11772 for (bar = FRAME_SCROLL_BARS (f); !NILP (bar); bar = b->next)
11774 b = XSCROLL_BAR (bar);
11775 x_scroll_bar_remove (b);
11777 #endif
11779 #ifdef HAVE_X_I18N
11780 if (FRAME_XIC (f))
11781 free_frame_xic (f);
11782 #endif
11784 x_free_cr_resources (f);
11785 #ifdef USE_X_TOOLKIT
11786 if (f->output_data.x->widget)
11788 XtDestroyWidget (f->output_data.x->widget);
11789 f->output_data.x->widget = NULL;
11791 /* Tooltips don't have widgets, only a simple X window, even if
11792 we are using a toolkit. */
11793 else if (FRAME_X_WINDOW (f))
11794 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11796 free_frame_menubar (f);
11798 if (f->shell_position)
11799 xfree (f->shell_position);
11800 #else /* !USE_X_TOOLKIT */
11802 #ifdef USE_GTK
11803 xg_free_frame_widgets (f);
11804 #endif /* USE_GTK */
11806 tear_down_x_back_buffer (f);
11807 if (FRAME_X_WINDOW (f))
11808 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11809 #endif /* !USE_X_TOOLKIT */
11811 unload_color (f, FRAME_FOREGROUND_PIXEL (f));
11812 unload_color (f, FRAME_BACKGROUND_PIXEL (f));
11813 unload_color (f, f->output_data.x->cursor_pixel);
11814 unload_color (f, f->output_data.x->cursor_foreground_pixel);
11815 unload_color (f, f->output_data.x->border_pixel);
11816 unload_color (f, f->output_data.x->mouse_pixel);
11818 if (f->output_data.x->scroll_bar_background_pixel != -1)
11819 unload_color (f, f->output_data.x->scroll_bar_background_pixel);
11820 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
11821 unload_color (f, f->output_data.x->scroll_bar_foreground_pixel);
11822 #if defined (USE_LUCID) && defined (USE_TOOLKIT_SCROLL_BARS)
11823 /* Scrollbar shadow colors. */
11824 if (f->output_data.x->scroll_bar_top_shadow_pixel != -1)
11825 unload_color (f, f->output_data.x->scroll_bar_top_shadow_pixel);
11826 if (f->output_data.x->scroll_bar_bottom_shadow_pixel != -1)
11827 unload_color (f, f->output_data.x->scroll_bar_bottom_shadow_pixel);
11828 #endif /* USE_LUCID && USE_TOOLKIT_SCROLL_BARS */
11829 if (f->output_data.x->white_relief.pixel != -1)
11830 unload_color (f, f->output_data.x->white_relief.pixel);
11831 if (f->output_data.x->black_relief.pixel != -1)
11832 unload_color (f, f->output_data.x->black_relief.pixel);
11834 x_free_gcs (f);
11836 /* Free extra GCs allocated by x_setup_relief_colors. */
11837 if (f->output_data.x->white_relief.gc)
11839 XFreeGC (dpyinfo->display, f->output_data.x->white_relief.gc);
11840 f->output_data.x->white_relief.gc = 0;
11842 if (f->output_data.x->black_relief.gc)
11844 XFreeGC (dpyinfo->display, f->output_data.x->black_relief.gc);
11845 f->output_data.x->black_relief.gc = 0;
11848 /* Free cursors. */
11849 if (f->output_data.x->text_cursor != 0)
11850 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->text_cursor);
11851 if (f->output_data.x->nontext_cursor != 0)
11852 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->nontext_cursor);
11853 if (f->output_data.x->modeline_cursor != 0)
11854 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->modeline_cursor);
11855 if (f->output_data.x->hand_cursor != 0)
11856 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->hand_cursor);
11857 if (f->output_data.x->hourglass_cursor != 0)
11858 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->hourglass_cursor);
11859 if (f->output_data.x->horizontal_drag_cursor != 0)
11860 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->horizontal_drag_cursor);
11861 if (f->output_data.x->vertical_drag_cursor != 0)
11862 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->vertical_drag_cursor);
11863 if (f->output_data.x->left_edge_cursor != 0)
11864 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->left_edge_cursor);
11865 if (f->output_data.x->top_left_corner_cursor != 0)
11866 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->top_left_corner_cursor);
11867 if (f->output_data.x->top_edge_cursor != 0)
11868 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->top_edge_cursor);
11869 if (f->output_data.x->top_right_corner_cursor != 0)
11870 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->top_right_corner_cursor);
11871 if (f->output_data.x->right_edge_cursor != 0)
11872 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->right_edge_cursor);
11873 if (f->output_data.x->bottom_right_corner_cursor != 0)
11874 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->bottom_right_corner_cursor);
11875 if (f->output_data.x->bottom_edge_cursor != 0)
11876 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->bottom_edge_cursor);
11877 if (f->output_data.x->bottom_left_corner_cursor != 0)
11878 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->bottom_left_corner_cursor);
11880 XFlush (FRAME_X_DISPLAY (f));
11883 xfree (f->output_data.x->saved_menu_event);
11884 xfree (f->output_data.x);
11885 f->output_data.x = NULL;
11887 if (f == dpyinfo->x_focus_frame)
11888 dpyinfo->x_focus_frame = 0;
11889 if (f == dpyinfo->x_focus_event_frame)
11890 dpyinfo->x_focus_event_frame = 0;
11891 if (f == dpyinfo->x_highlight_frame)
11892 dpyinfo->x_highlight_frame = 0;
11893 if (f == hlinfo->mouse_face_mouse_frame)
11894 reset_mouse_highlight (hlinfo);
11896 unblock_input ();
11900 /* Destroy the X window of frame F. */
11902 static void
11903 x_destroy_window (struct frame *f)
11905 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
11907 /* If a display connection is dead, don't try sending more
11908 commands to the X server. */
11909 if (dpyinfo->display != 0)
11910 x_free_frame_resources (f);
11912 dpyinfo->reference_count--;
11916 /* Setting window manager hints. */
11918 /* Set the normal size hints for the window manager, for frame F.
11919 FLAGS is the flags word to use--or 0 meaning preserve the flags
11920 that the window now has.
11921 If USER_POSITION, set the USPosition
11922 flag (this is useful when FLAGS is 0).
11923 The GTK version is in gtkutils.c. */
11925 #ifndef USE_GTK
11926 void
11927 x_wm_set_size_hint (struct frame *f, long flags, bool user_position)
11929 XSizeHints size_hints;
11930 Window window = FRAME_OUTER_WINDOW (f);
11932 if (!window)
11933 return;
11935 #ifdef USE_X_TOOLKIT
11936 if (f->output_data.x->widget)
11938 widget_update_wm_size_hints (f->output_data.x->widget);
11939 return;
11941 #endif
11943 /* Setting PMaxSize caused various problems. */
11944 size_hints.flags = PResizeInc | PMinSize /* | PMaxSize */;
11946 size_hints.x = f->left_pos;
11947 size_hints.y = f->top_pos;
11949 size_hints.width = FRAME_PIXEL_WIDTH (f);
11950 size_hints.height = FRAME_PIXEL_HEIGHT (f);
11952 size_hints.width_inc = frame_resize_pixelwise ? 1 : FRAME_COLUMN_WIDTH (f);
11953 size_hints.height_inc = frame_resize_pixelwise ? 1 : FRAME_LINE_HEIGHT (f);
11955 size_hints.max_width = x_display_pixel_width (FRAME_DISPLAY_INFO (f))
11956 - FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
11957 size_hints.max_height = x_display_pixel_height (FRAME_DISPLAY_INFO (f))
11958 - FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
11960 /* Calculate the base and minimum sizes. */
11962 int base_width, base_height;
11964 base_width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
11965 base_height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
11967 /* The window manager uses the base width hints to calculate the
11968 current number of rows and columns in the frame while
11969 resizing; min_width and min_height aren't useful for this
11970 purpose, since they might not give the dimensions for a
11971 zero-row, zero-column frame. */
11973 size_hints.flags |= PBaseSize;
11974 size_hints.base_width = base_width;
11975 size_hints.base_height = base_height + FRAME_MENUBAR_HEIGHT (f);
11976 size_hints.min_width = base_width;
11977 size_hints.min_height = base_height;
11980 /* If we don't need the old flags, we don't need the old hint at all. */
11981 if (flags)
11983 size_hints.flags |= flags;
11984 goto no_read;
11988 XSizeHints hints; /* Sometimes I hate X Windows... */
11989 long supplied_return;
11990 int value;
11992 value = XGetWMNormalHints (FRAME_X_DISPLAY (f), window, &hints,
11993 &supplied_return);
11995 if (flags)
11996 size_hints.flags |= flags;
11997 else
11999 if (value == 0)
12000 hints.flags = 0;
12001 if (hints.flags & PSize)
12002 size_hints.flags |= PSize;
12003 if (hints.flags & PPosition)
12004 size_hints.flags |= PPosition;
12005 if (hints.flags & USPosition)
12006 size_hints.flags |= USPosition;
12007 if (hints.flags & USSize)
12008 size_hints.flags |= USSize;
12012 no_read:
12014 #ifdef PWinGravity
12015 size_hints.win_gravity = f->win_gravity;
12016 size_hints.flags |= PWinGravity;
12018 if (user_position)
12020 size_hints.flags &= ~ PPosition;
12021 size_hints.flags |= USPosition;
12023 #endif /* PWinGravity */
12025 XSetWMNormalHints (FRAME_X_DISPLAY (f), window, &size_hints);
12027 #endif /* not USE_GTK */
12029 /* Used for IconicState or NormalState */
12031 static void
12032 x_wm_set_window_state (struct frame *f, int state)
12034 #ifdef USE_X_TOOLKIT
12035 Arg al[1];
12037 XtSetArg (al[0], XtNinitialState, state);
12038 XtSetValues (f->output_data.x->widget, al, 1);
12039 #else /* not USE_X_TOOLKIT */
12040 Window window = FRAME_X_WINDOW (f);
12042 f->output_data.x->wm_hints.flags |= StateHint;
12043 f->output_data.x->wm_hints.initial_state = state;
12045 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
12046 #endif /* not USE_X_TOOLKIT */
12049 static void
12050 x_wm_set_icon_pixmap (struct frame *f, ptrdiff_t pixmap_id)
12052 Pixmap icon_pixmap, icon_mask;
12054 #if !defined USE_X_TOOLKIT && !defined USE_GTK
12055 Window window = FRAME_OUTER_WINDOW (f);
12056 #endif
12058 if (pixmap_id > 0)
12060 icon_pixmap = x_bitmap_pixmap (f, pixmap_id);
12061 f->output_data.x->wm_hints.icon_pixmap = icon_pixmap;
12062 icon_mask = x_bitmap_mask (f, pixmap_id);
12063 f->output_data.x->wm_hints.icon_mask = icon_mask;
12065 else
12067 /* It seems there is no way to turn off use of an icon
12068 pixmap. */
12069 return;
12073 #ifdef USE_GTK
12075 xg_set_frame_icon (f, icon_pixmap, icon_mask);
12076 return;
12079 #elif defined (USE_X_TOOLKIT) /* same as in x_wm_set_window_state. */
12082 Arg al[1];
12083 XtSetArg (al[0], XtNiconPixmap, icon_pixmap);
12084 XtSetValues (f->output_data.x->widget, al, 1);
12085 XtSetArg (al[0], XtNiconMask, icon_mask);
12086 XtSetValues (f->output_data.x->widget, al, 1);
12089 #else /* not USE_X_TOOLKIT && not USE_GTK */
12091 f->output_data.x->wm_hints.flags |= (IconPixmapHint | IconMaskHint);
12092 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
12094 #endif /* not USE_X_TOOLKIT && not USE_GTK */
12097 void
12098 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
12100 Window window = FRAME_OUTER_WINDOW (f);
12102 f->output_data.x->wm_hints.flags |= IconPositionHint;
12103 f->output_data.x->wm_hints.icon_x = icon_x;
12104 f->output_data.x->wm_hints.icon_y = icon_y;
12106 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
12110 /***********************************************************************
12111 Fonts
12112 ***********************************************************************/
12114 #ifdef GLYPH_DEBUG
12116 /* Check that FONT is valid on frame F. It is if it can be found in F's
12117 font table. */
12119 static void
12120 x_check_font (struct frame *f, struct font *font)
12122 eassert (font != NULL && ! NILP (font->props[FONT_TYPE_INDEX]));
12123 if (font->driver->check)
12124 eassert (font->driver->check (f, font) == 0);
12127 #endif /* GLYPH_DEBUG */
12130 /***********************************************************************
12131 Initialization
12132 ***********************************************************************/
12134 #ifdef USE_X_TOOLKIT
12135 static XrmOptionDescRec emacs_options[] = {
12136 {(char *) "-geometry", (char *) ".geometry", XrmoptionSepArg, NULL},
12137 {(char *) "-iconic", (char *) ".iconic", XrmoptionNoArg, (XtPointer) "yes"},
12139 {(char *) "-internal-border-width",
12140 (char *) "*EmacsScreen.internalBorderWidth", XrmoptionSepArg, NULL},
12141 {(char *) "-ib", (char *) "*EmacsScreen.internalBorderWidth",
12142 XrmoptionSepArg, NULL},
12143 {(char *) "-T", (char *) "*EmacsShell.title", XrmoptionSepArg, NULL},
12144 {(char *) "-wn", (char *) "*EmacsShell.title", XrmoptionSepArg, NULL},
12145 {(char *) "-title", (char *) "*EmacsShell.title", XrmoptionSepArg, NULL},
12146 {(char *) "-iconname", (char *) "*EmacsShell.iconName",
12147 XrmoptionSepArg, NULL},
12148 {(char *) "-in", (char *) "*EmacsShell.iconName", XrmoptionSepArg, NULL},
12149 {(char *) "-mc", (char *) "*pointerColor", XrmoptionSepArg, NULL},
12150 {(char *) "-cr", (char *) "*cursorColor", XrmoptionSepArg, NULL}
12153 /* Whether atimer for Xt timeouts is activated or not. */
12155 static bool x_timeout_atimer_activated_flag;
12157 #endif /* USE_X_TOOLKIT */
12159 static int x_initialized;
12161 /* Test whether two display-name strings agree up to the dot that separates
12162 the screen number from the server number. */
12163 static bool
12164 same_x_server (const char *name1, const char *name2)
12166 bool seen_colon = false;
12167 Lisp_Object sysname = Fsystem_name ();
12168 if (! STRINGP (sysname))
12169 sysname = empty_unibyte_string;
12170 const char *system_name = SSDATA (sysname);
12171 ptrdiff_t system_name_length = SBYTES (sysname);
12172 ptrdiff_t length_until_period = 0;
12174 while (system_name[length_until_period] != 0
12175 && system_name[length_until_period] != '.')
12176 length_until_period++;
12178 /* Treat `unix' like an empty host name. */
12179 if (! strncmp (name1, "unix:", 5))
12180 name1 += 4;
12181 if (! strncmp (name2, "unix:", 5))
12182 name2 += 4;
12183 /* Treat this host's name like an empty host name. */
12184 if (! strncmp (name1, system_name, system_name_length)
12185 && name1[system_name_length] == ':')
12186 name1 += system_name_length;
12187 if (! strncmp (name2, system_name, system_name_length)
12188 && name2[system_name_length] == ':')
12189 name2 += system_name_length;
12190 /* Treat this host's domainless name like an empty host name. */
12191 if (! strncmp (name1, system_name, length_until_period)
12192 && name1[length_until_period] == ':')
12193 name1 += length_until_period;
12194 if (! strncmp (name2, system_name, length_until_period)
12195 && name2[length_until_period] == ':')
12196 name2 += length_until_period;
12198 for (; *name1 != '\0' && *name1 == *name2; name1++, name2++)
12200 if (*name1 == ':')
12201 seen_colon = true;
12202 if (seen_colon && *name1 == '.')
12203 return true;
12205 return (seen_colon
12206 && (*name1 == '.' || *name1 == '\0')
12207 && (*name2 == '.' || *name2 == '\0'));
12210 /* Count number of set bits in mask and number of bits to shift to
12211 get to the first bit. With MASK 0x7e0, *BITS is set to 6, and *OFFSET
12212 to 5. */
12213 static void
12214 get_bits_and_offset (unsigned long mask, int *bits, int *offset)
12216 int nr = 0;
12217 int off = 0;
12219 while (!(mask & 1))
12221 off++;
12222 mask >>= 1;
12225 while (mask & 1)
12227 nr++;
12228 mask >>= 1;
12231 *offset = off;
12232 *bits = nr;
12235 /* Return true iff display DISPLAY is available for use.
12236 But don't permanently open it, just test its availability. */
12238 bool
12239 x_display_ok (const char *display)
12241 /* XOpenDisplay fails if it gets a signal. Block SIGIO which may arrive. */
12242 unrequest_sigio ();
12243 Display *dpy = XOpenDisplay (display);
12244 request_sigio ();
12245 if (!dpy)
12246 return false;
12247 XCloseDisplay (dpy);
12248 return true;
12251 #ifdef USE_GTK
12252 static void
12253 my_log_handler (const gchar *log_domain, GLogLevelFlags log_level,
12254 const gchar *msg, gpointer user_data)
12256 if (!strstr (msg, "g_set_prgname"))
12257 fprintf (stderr, "%s-WARNING **: %s\n", log_domain, msg);
12259 #endif
12261 /* Create invisible cursor on X display referred by DPYINFO. */
12263 static Cursor
12264 make_invisible_cursor (struct x_display_info *dpyinfo)
12266 Display *dpy = dpyinfo->display;
12267 static char const no_data[] = { 0 };
12268 Pixmap pix;
12269 XColor col;
12270 Cursor c = 0;
12272 x_catch_errors (dpy);
12273 pix = XCreateBitmapFromData (dpy, dpyinfo->root_window, no_data, 1, 1);
12274 if (! x_had_errors_p (dpy) && pix != None)
12276 Cursor pixc;
12277 col.pixel = 0;
12278 col.red = col.green = col.blue = 0;
12279 col.flags = DoRed | DoGreen | DoBlue;
12280 pixc = XCreatePixmapCursor (dpy, pix, pix, &col, &col, 0, 0);
12281 if (! x_had_errors_p (dpy) && pixc != None)
12282 c = pixc;
12283 XFreePixmap (dpy, pix);
12286 x_uncatch_errors ();
12288 return c;
12291 /* True if DPY supports Xfixes extension >= 4. */
12293 static bool
12294 x_probe_xfixes_extension (Display *dpy)
12296 #ifdef HAVE_XFIXES
12297 int major, minor;
12298 return XFixesQueryVersion (dpy, &major, &minor) && major >= 4;
12299 #else
12300 return false;
12301 #endif /* HAVE_XFIXES */
12304 /* Toggle mouse pointer visibility on frame F by using Xfixes functions. */
12306 static void
12307 xfixes_toggle_visible_pointer (struct frame *f, bool invisible)
12309 #ifdef HAVE_XFIXES
12310 if (invisible)
12311 XFixesHideCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
12312 else
12313 XFixesShowCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
12314 f->pointer_invisible = invisible;
12315 #else
12316 emacs_abort ();
12317 #endif /* HAVE_XFIXES */
12320 /* Toggle mouse pointer visibility on frame F by using invisible cursor. */
12322 static void
12323 x_toggle_visible_pointer (struct frame *f, bool invisible)
12325 eassert (FRAME_DISPLAY_INFO (f)->invisible_cursor != 0);
12326 if (invisible)
12327 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
12328 FRAME_DISPLAY_INFO (f)->invisible_cursor);
12329 else
12330 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
12331 f->output_data.x->current_cursor);
12332 f->pointer_invisible = invisible;
12335 /* Setup pointer blanking, prefer Xfixes if available. */
12337 static void
12338 x_setup_pointer_blanking (struct x_display_info *dpyinfo)
12340 /* FIXME: the brave tester should set EMACS_XFIXES because we're suspecting
12341 X server bug, see https://debbugs.gnu.org/cgi/bugreport.cgi?bug=17609. */
12342 if (egetenv ("EMACS_XFIXES") && x_probe_xfixes_extension (dpyinfo->display))
12343 dpyinfo->toggle_visible_pointer = xfixes_toggle_visible_pointer;
12344 else
12346 dpyinfo->toggle_visible_pointer = x_toggle_visible_pointer;
12347 dpyinfo->invisible_cursor = make_invisible_cursor (dpyinfo);
12351 /* Current X display connection identifier. Incremented for each next
12352 connection established. */
12353 static unsigned x_display_id;
12355 /* Open a connection to X display DISPLAY_NAME, and return
12356 the structure that describes the open display.
12357 If we cannot contact the display, return null. */
12359 struct x_display_info *
12360 x_term_init (Lisp_Object display_name, char *xrm_option, char *resource_name)
12362 Display *dpy;
12363 struct terminal *terminal;
12364 struct x_display_info *dpyinfo;
12365 XrmDatabase xrdb;
12366 #ifdef USE_XCB
12367 xcb_connection_t *xcb_conn;
12368 #endif
12370 block_input ();
12372 if (!x_initialized)
12374 x_initialize ();
12375 ++x_initialized;
12378 if (! x_display_ok (SSDATA (display_name)))
12379 error ("Display %s can't be opened", SSDATA (display_name));
12381 #ifdef USE_GTK
12383 #define NUM_ARGV 10
12384 int argc;
12385 char *argv[NUM_ARGV];
12386 char **argv2 = argv;
12387 guint id;
12389 if (x_initialized++ > 1)
12391 xg_display_open (SSDATA (display_name), &dpy);
12393 else
12395 static char display_opt[] = "--display";
12396 static char name_opt[] = "--name";
12398 for (argc = 0; argc < NUM_ARGV; ++argc)
12399 argv[argc] = 0;
12401 argc = 0;
12402 argv[argc++] = initial_argv[0];
12404 if (! NILP (display_name))
12406 argv[argc++] = display_opt;
12407 argv[argc++] = SSDATA (display_name);
12410 argv[argc++] = name_opt;
12411 argv[argc++] = resource_name;
12413 XSetLocaleModifiers ("");
12415 /* Work around GLib bug that outputs a faulty warning. See
12416 https://bugzilla.gnome.org/show_bug.cgi?id=563627. */
12417 id = g_log_set_handler ("GLib", G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
12418 | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
12420 /* NULL window -> events for all windows go to our function.
12421 Call before gtk_init so Gtk+ event filters comes after our. */
12422 gdk_window_add_filter (NULL, event_handler_gdk, NULL);
12424 /* gtk_init does set_locale. Fix locale before and after. */
12425 fixup_locale ();
12426 unrequest_sigio (); /* See comment in x_display_ok. */
12427 gtk_init (&argc, &argv2);
12428 request_sigio ();
12430 g_log_remove_handler ("GLib", id);
12432 xg_initialize ();
12434 /* Do this after the call to xg_initialize, because when
12435 Fontconfig is used, xg_initialize calls its initialization
12436 function which in some versions of Fontconfig calls setlocale. */
12437 fixup_locale ();
12439 dpy = DEFAULT_GDK_DISPLAY ();
12441 #if ! GTK_CHECK_VERSION (2, 90, 0)
12442 /* Load our own gtkrc if it exists. */
12444 const char *file = "~/.emacs.d/gtkrc";
12445 Lisp_Object s, abs_file;
12447 s = build_string (file);
12448 abs_file = Fexpand_file_name (s, Qnil);
12450 if (! NILP (abs_file) && !NILP (Ffile_readable_p (abs_file)))
12451 gtk_rc_parse (SSDATA (abs_file));
12453 #endif
12455 XSetErrorHandler (x_error_handler);
12456 XSetIOErrorHandler (x_io_error_quitter);
12459 #else /* not USE_GTK */
12460 #ifdef USE_X_TOOLKIT
12461 /* weiner@footloose.sps.mot.com reports that this causes
12462 errors with X11R5:
12463 X protocol error: BadAtom (invalid Atom parameter)
12464 on protocol request 18skiloaf.
12465 So let's not use it until R6. */
12466 #ifdef HAVE_X11XTR6
12467 XtSetLanguageProc (NULL, NULL, NULL);
12468 #endif
12471 int argc = 0;
12472 char *argv[3];
12474 argv[0] = (char *) "";
12475 argc = 1;
12476 if (xrm_option)
12478 argv[argc++] = (char *) "-xrm";
12479 argv[argc++] = xrm_option;
12481 turn_on_atimers (false);
12482 unrequest_sigio (); /* See comment in x_display_ok. */
12483 dpy = XtOpenDisplay (Xt_app_con, SSDATA (display_name),
12484 resource_name, EMACS_CLASS,
12485 emacs_options, XtNumber (emacs_options),
12486 &argc, argv);
12487 request_sigio ();
12488 turn_on_atimers (true);
12490 #ifdef HAVE_X11XTR6
12491 /* I think this is to compensate for XtSetLanguageProc. */
12492 fixup_locale ();
12493 #endif
12496 #else /* not USE_X_TOOLKIT */
12497 XSetLocaleModifiers ("");
12498 unrequest_sigio (); /* See comment in x_display_ok. */
12499 dpy = XOpenDisplay (SSDATA (display_name));
12500 request_sigio ();
12501 #endif /* not USE_X_TOOLKIT */
12502 #endif /* not USE_GTK*/
12504 /* Detect failure. */
12505 if (dpy == 0)
12507 unblock_input ();
12508 return 0;
12511 #ifdef USE_XCB
12512 xcb_conn = XGetXCBConnection (dpy);
12513 if (xcb_conn == 0)
12515 #ifdef USE_GTK
12516 xg_display_close (dpy);
12517 #else
12518 #ifdef USE_X_TOOLKIT
12519 XtCloseDisplay (dpy);
12520 #else
12521 XCloseDisplay (dpy);
12522 #endif
12523 #endif /* ! USE_GTK */
12525 unblock_input ();
12526 return 0;
12528 #endif
12530 /* We have definitely succeeded. Record the new connection. */
12532 dpyinfo = xzalloc (sizeof *dpyinfo);
12533 terminal = x_create_terminal (dpyinfo);
12536 struct x_display_info *share;
12538 for (share = x_display_list; share; share = share->next)
12539 if (same_x_server (SSDATA (XCAR (share->name_list_element)),
12540 SSDATA (display_name)))
12541 break;
12542 if (share)
12543 terminal->kboard = share->terminal->kboard;
12544 else
12546 terminal->kboard = allocate_kboard (Qx);
12548 if (!EQ (XSYMBOL (Qvendor_specific_keysyms)->u.s.function, Qunbound))
12550 char *vendor = ServerVendor (dpy);
12552 /* Temporarily hide the partially initialized terminal. */
12553 terminal_list = terminal->next_terminal;
12554 unblock_input ();
12555 kset_system_key_alist
12556 (terminal->kboard,
12557 call1 (Qvendor_specific_keysyms,
12558 vendor ? build_string (vendor) : empty_unibyte_string));
12559 block_input ();
12560 terminal->next_terminal = terminal_list;
12561 terminal_list = terminal;
12564 /* Don't let the initial kboard remain current longer than necessary.
12565 That would cause problems if a file loaded on startup tries to
12566 prompt in the mini-buffer. */
12567 if (current_kboard == initial_kboard)
12568 current_kboard = terminal->kboard;
12570 terminal->kboard->reference_count++;
12573 /* Put this display on the chain. */
12574 dpyinfo->next = x_display_list;
12575 x_display_list = dpyinfo;
12577 dpyinfo->name_list_element = Fcons (display_name, Qnil);
12578 dpyinfo->display = dpy;
12579 dpyinfo->connection = ConnectionNumber (dpyinfo->display);
12580 #ifdef USE_XCB
12581 dpyinfo->xcb_connection = xcb_conn;
12582 #endif
12584 /* https://lists.gnu.org/r/emacs-devel/2015-11/msg00194.html */
12585 dpyinfo->smallest_font_height = 1;
12586 dpyinfo->smallest_char_width = 1;
12588 /* Set the name of the terminal. */
12589 terminal->name = xlispstrdup (display_name);
12591 #if false
12592 XSetAfterFunction (x_current_display, x_trace_wire);
12593 #endif
12595 Lisp_Object system_name = Fsystem_name ();
12597 ptrdiff_t nbytes = SBYTES (Vinvocation_name) + 1;
12598 if (STRINGP (system_name)
12599 && INT_ADD_WRAPV (nbytes, SBYTES (system_name) + 1, &nbytes))
12600 memory_full (SIZE_MAX);
12601 dpyinfo->x_id = ++x_display_id;
12602 dpyinfo->x_id_name = xmalloc (nbytes);
12603 char *nametail = lispstpcpy (dpyinfo->x_id_name, Vinvocation_name);
12604 if (STRINGP (system_name))
12606 *nametail++ = '@';
12607 lispstpcpy (nametail, system_name);
12610 /* Figure out which modifier bits mean what. */
12611 x_find_modifier_meanings (dpyinfo);
12613 /* Get the scroll bar cursor. */
12614 #ifdef USE_GTK
12615 /* We must create a GTK cursor, it is required for GTK widgets. */
12616 dpyinfo->xg_cursor = xg_create_default_cursor (dpyinfo->display);
12617 #endif /* USE_GTK */
12619 dpyinfo->vertical_scroll_bar_cursor
12620 = XCreateFontCursor (dpyinfo->display, XC_sb_v_double_arrow);
12622 dpyinfo->horizontal_scroll_bar_cursor
12623 = XCreateFontCursor (dpyinfo->display, XC_sb_h_double_arrow);
12625 xrdb = x_load_resources (dpyinfo->display, xrm_option,
12626 resource_name, EMACS_CLASS);
12627 #ifdef HAVE_XRMSETDATABASE
12628 XrmSetDatabase (dpyinfo->display, xrdb);
12629 #else
12630 dpyinfo->display->db = xrdb;
12631 #endif
12632 /* Put the rdb where we can find it in a way that works on
12633 all versions. */
12634 dpyinfo->xrdb = xrdb;
12636 dpyinfo->screen = ScreenOfDisplay (dpyinfo->display,
12637 DefaultScreen (dpyinfo->display));
12638 select_visual (dpyinfo);
12639 dpyinfo->cmap = DefaultColormapOfScreen (dpyinfo->screen);
12640 dpyinfo->root_window = RootWindowOfScreen (dpyinfo->screen);
12641 dpyinfo->icon_bitmap_id = -1;
12642 dpyinfo->wm_type = X_WMTYPE_UNKNOWN;
12644 reset_mouse_highlight (&dpyinfo->mouse_highlight);
12646 /* See if we can construct pixel values from RGB values. */
12647 if (dpyinfo->visual->class == TrueColor)
12649 get_bits_and_offset (dpyinfo->visual->red_mask,
12650 &dpyinfo->red_bits, &dpyinfo->red_offset);
12651 get_bits_and_offset (dpyinfo->visual->blue_mask,
12652 &dpyinfo->blue_bits, &dpyinfo->blue_offset);
12653 get_bits_and_offset (dpyinfo->visual->green_mask,
12654 &dpyinfo->green_bits, &dpyinfo->green_offset);
12657 /* See if a private colormap is requested. */
12658 if (dpyinfo->visual == DefaultVisualOfScreen (dpyinfo->screen))
12660 if (dpyinfo->visual->class == PseudoColor)
12662 AUTO_STRING (privateColormap, "privateColormap");
12663 AUTO_STRING (PrivateColormap, "PrivateColormap");
12664 Lisp_Object value
12665 = display_x_get_resource (dpyinfo, privateColormap,
12666 PrivateColormap, Qnil, Qnil);
12667 if (STRINGP (value)
12668 && (!strcmp (SSDATA (value), "true")
12669 || !strcmp (SSDATA (value), "on")))
12670 dpyinfo->cmap = XCopyColormapAndFree (dpyinfo->display, dpyinfo->cmap);
12673 else
12674 dpyinfo->cmap = XCreateColormap (dpyinfo->display, dpyinfo->root_window,
12675 dpyinfo->visual, AllocNone);
12677 #ifdef HAVE_XDBE
12678 dpyinfo->supports_xdbe = false;
12679 int xdbe_major;
12680 int xdbe_minor;
12681 if (XdbeQueryExtension (dpyinfo->display, &xdbe_major, &xdbe_minor))
12682 dpyinfo->supports_xdbe = true;
12683 #endif
12685 #ifdef HAVE_XFT
12687 /* If we are using Xft, the following precautions should be made:
12689 1. Make sure that the Xrender extension is added before the Xft one.
12690 Otherwise, the close-display hook set by Xft is called after the one
12691 for Xrender, and the former tries to re-add the latter. This results
12692 in inconsistency of internal states and leads to X protocol error when
12693 one reconnects to the same X server (Bug#1696).
12695 2. Check dpi value in X resources. It is better we use it as well,
12696 since Xft will use it, as will all Gnome applications. If our real DPI
12697 is smaller or larger than the one Xft uses, our font will look smaller
12698 or larger than other for other applications, even if it is the same
12699 font name (monospace-10 for example). */
12701 int event_base, error_base;
12702 char *v;
12703 double d;
12705 XRenderQueryExtension (dpyinfo->display, &event_base, &error_base);
12707 v = XGetDefault (dpyinfo->display, "Xft", "dpi");
12708 if (v != NULL && sscanf (v, "%lf", &d) == 1)
12709 dpyinfo->resy = dpyinfo->resx = d;
12711 #endif
12713 if (dpyinfo->resy < 1)
12715 int screen_number = XScreenNumberOfScreen (dpyinfo->screen);
12716 double pixels = DisplayHeight (dpyinfo->display, screen_number);
12717 double mm = DisplayHeightMM (dpyinfo->display, screen_number);
12718 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
12719 dpyinfo->resy = (mm < 1) ? 100 : pixels * 25.4 / mm;
12720 pixels = DisplayWidth (dpyinfo->display, screen_number);
12721 mm = DisplayWidthMM (dpyinfo->display, screen_number);
12722 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
12723 dpyinfo->resx = (mm < 1) ? 100 : pixels * 25.4 / mm;
12727 static const struct
12729 const char *name;
12730 int offset;
12731 } atom_refs[] = {
12732 #define ATOM_REFS_INIT(string, member) \
12733 { string, offsetof (struct x_display_info, member) },
12734 ATOM_REFS_INIT ("WM_PROTOCOLS", Xatom_wm_protocols)
12735 ATOM_REFS_INIT ("WM_TAKE_FOCUS", Xatom_wm_take_focus)
12736 ATOM_REFS_INIT ("WM_SAVE_YOURSELF", Xatom_wm_save_yourself)
12737 ATOM_REFS_INIT ("WM_DELETE_WINDOW", Xatom_wm_delete_window)
12738 ATOM_REFS_INIT ("WM_CHANGE_STATE", Xatom_wm_change_state)
12739 ATOM_REFS_INIT ("WM_CONFIGURE_DENIED", Xatom_wm_configure_denied)
12740 ATOM_REFS_INIT ("WM_MOVED", Xatom_wm_window_moved)
12741 ATOM_REFS_INIT ("WM_CLIENT_LEADER", Xatom_wm_client_leader)
12742 ATOM_REFS_INIT ("Editres", Xatom_editres)
12743 ATOM_REFS_INIT ("CLIPBOARD", Xatom_CLIPBOARD)
12744 ATOM_REFS_INIT ("TIMESTAMP", Xatom_TIMESTAMP)
12745 ATOM_REFS_INIT ("TEXT", Xatom_TEXT)
12746 ATOM_REFS_INIT ("COMPOUND_TEXT", Xatom_COMPOUND_TEXT)
12747 ATOM_REFS_INIT ("UTF8_STRING", Xatom_UTF8_STRING)
12748 ATOM_REFS_INIT ("DELETE", Xatom_DELETE)
12749 ATOM_REFS_INIT ("MULTIPLE", Xatom_MULTIPLE)
12750 ATOM_REFS_INIT ("INCR", Xatom_INCR)
12751 ATOM_REFS_INIT ("_EMACS_TMP_", Xatom_EMACS_TMP)
12752 ATOM_REFS_INIT ("TARGETS", Xatom_TARGETS)
12753 ATOM_REFS_INIT ("NULL", Xatom_NULL)
12754 ATOM_REFS_INIT ("ATOM", Xatom_ATOM)
12755 ATOM_REFS_INIT ("ATOM_PAIR", Xatom_ATOM_PAIR)
12756 ATOM_REFS_INIT ("CLIPBOARD_MANAGER", Xatom_CLIPBOARD_MANAGER)
12757 ATOM_REFS_INIT ("_XEMBED_INFO", Xatom_XEMBED_INFO)
12758 /* For properties of font. */
12759 ATOM_REFS_INIT ("PIXEL_SIZE", Xatom_PIXEL_SIZE)
12760 ATOM_REFS_INIT ("AVERAGE_WIDTH", Xatom_AVERAGE_WIDTH)
12761 ATOM_REFS_INIT ("_MULE_BASELINE_OFFSET", Xatom_MULE_BASELINE_OFFSET)
12762 ATOM_REFS_INIT ("_MULE_RELATIVE_COMPOSE", Xatom_MULE_RELATIVE_COMPOSE)
12763 ATOM_REFS_INIT ("_MULE_DEFAULT_ASCENT", Xatom_MULE_DEFAULT_ASCENT)
12764 /* Ghostscript support. */
12765 ATOM_REFS_INIT ("DONE", Xatom_DONE)
12766 ATOM_REFS_INIT ("PAGE", Xatom_PAGE)
12767 ATOM_REFS_INIT ("SCROLLBAR", Xatom_Scrollbar)
12768 ATOM_REFS_INIT ("HORIZONTAL_SCROLLBAR", Xatom_Horizontal_Scrollbar)
12769 ATOM_REFS_INIT ("_XEMBED", Xatom_XEMBED)
12770 /* EWMH */
12771 ATOM_REFS_INIT ("_NET_WM_STATE", Xatom_net_wm_state)
12772 ATOM_REFS_INIT ("_NET_WM_STATE_FULLSCREEN", Xatom_net_wm_state_fullscreen)
12773 ATOM_REFS_INIT ("_NET_WM_STATE_MAXIMIZED_HORZ",
12774 Xatom_net_wm_state_maximized_horz)
12775 ATOM_REFS_INIT ("_NET_WM_STATE_MAXIMIZED_VERT",
12776 Xatom_net_wm_state_maximized_vert)
12777 ATOM_REFS_INIT ("_NET_WM_STATE_STICKY", Xatom_net_wm_state_sticky)
12778 ATOM_REFS_INIT ("_NET_WM_STATE_HIDDEN", Xatom_net_wm_state_hidden)
12779 ATOM_REFS_INIT ("_NET_WM_WINDOW_TYPE", Xatom_net_window_type)
12780 ATOM_REFS_INIT ("_NET_WM_WINDOW_TYPE_TOOLTIP",
12781 Xatom_net_window_type_tooltip)
12782 ATOM_REFS_INIT ("_NET_WM_ICON_NAME", Xatom_net_wm_icon_name)
12783 ATOM_REFS_INIT ("_NET_WM_NAME", Xatom_net_wm_name)
12784 ATOM_REFS_INIT ("_NET_SUPPORTED", Xatom_net_supported)
12785 ATOM_REFS_INIT ("_NET_SUPPORTING_WM_CHECK", Xatom_net_supporting_wm_check)
12786 ATOM_REFS_INIT ("_NET_WM_WINDOW_OPACITY", Xatom_net_wm_window_opacity)
12787 ATOM_REFS_INIT ("_NET_ACTIVE_WINDOW", Xatom_net_active_window)
12788 ATOM_REFS_INIT ("_NET_FRAME_EXTENTS", Xatom_net_frame_extents)
12789 ATOM_REFS_INIT ("_NET_CURRENT_DESKTOP", Xatom_net_current_desktop)
12790 ATOM_REFS_INIT ("_NET_WORKAREA", Xatom_net_workarea)
12791 /* Session management */
12792 ATOM_REFS_INIT ("SM_CLIENT_ID", Xatom_SM_CLIENT_ID)
12793 ATOM_REFS_INIT ("_XSETTINGS_SETTINGS", Xatom_xsettings_prop)
12794 ATOM_REFS_INIT ("MANAGER", Xatom_xsettings_mgr)
12795 ATOM_REFS_INIT ("_NET_WM_STATE_SKIP_TASKBAR", Xatom_net_wm_state_skip_taskbar)
12796 ATOM_REFS_INIT ("_NET_WM_STATE_ABOVE", Xatom_net_wm_state_above)
12797 ATOM_REFS_INIT ("_NET_WM_STATE_BELOW", Xatom_net_wm_state_below)
12800 int i;
12801 enum { atom_count = ARRAYELTS (atom_refs) };
12802 /* 1 for _XSETTINGS_SN. */
12803 enum { total_atom_count = 1 + atom_count };
12804 Atom atoms_return[total_atom_count];
12805 char *atom_names[total_atom_count];
12806 static char const xsettings_fmt[] = "_XSETTINGS_S%d";
12807 char xsettings_atom_name[sizeof xsettings_fmt - 2
12808 + INT_STRLEN_BOUND (int)];
12810 for (i = 0; i < atom_count; i++)
12811 atom_names[i] = (char *) atom_refs[i].name;
12813 /* Build _XSETTINGS_SN atom name. */
12814 sprintf (xsettings_atom_name, xsettings_fmt,
12815 XScreenNumberOfScreen (dpyinfo->screen));
12816 atom_names[i] = xsettings_atom_name;
12818 XInternAtoms (dpyinfo->display, atom_names, total_atom_count,
12819 False, atoms_return);
12821 for (i = 0; i < atom_count; i++)
12822 *(Atom *) ((char *) dpyinfo + atom_refs[i].offset) = atoms_return[i];
12824 /* Manually copy last atom. */
12825 dpyinfo->Xatom_xsettings_sel = atoms_return[i];
12828 dpyinfo->x_dnd_atoms_size = 8;
12829 dpyinfo->x_dnd_atoms = xmalloc (sizeof *dpyinfo->x_dnd_atoms
12830 * dpyinfo->x_dnd_atoms_size);
12831 dpyinfo->gray
12832 = XCreatePixmapFromBitmapData (dpyinfo->display, dpyinfo->root_window,
12833 gray_bits, gray_width, gray_height,
12834 1, 0, 1);
12836 x_setup_pointer_blanking (dpyinfo);
12838 #ifdef HAVE_X_I18N
12839 xim_initialize (dpyinfo, resource_name);
12840 #endif
12842 xsettings_initialize (dpyinfo);
12844 /* This is only needed for distinguishing keyboard and process input. */
12845 if (dpyinfo->connection != 0)
12846 add_keyboard_wait_descriptor (dpyinfo->connection);
12848 #ifdef F_SETOWN
12849 fcntl (dpyinfo->connection, F_SETOWN, getpid ());
12850 #endif /* ! defined (F_SETOWN) */
12852 if (interrupt_input)
12853 init_sigio (dpyinfo->connection);
12855 #ifdef USE_LUCID
12857 XrmValue d, fr, to;
12858 Font font;
12860 dpy = dpyinfo->display;
12861 d.addr = (XPointer)&dpy;
12862 d.size = sizeof (Display *);
12863 fr.addr = (char *) XtDefaultFont;
12864 fr.size = sizeof (XtDefaultFont);
12865 to.size = sizeof (Font *);
12866 to.addr = (XPointer)&font;
12867 x_catch_errors (dpy);
12868 if (!XtCallConverter (dpy, XtCvtStringToFont, &d, 1, &fr, &to, NULL))
12869 emacs_abort ();
12870 if (x_had_errors_p (dpy) || !XQueryFont (dpy, font))
12871 XrmPutLineResource (&xrdb, "Emacs.dialog.*.font: 9x15");
12872 /* Do not free XFontStruct returned by the above call to XQueryFont.
12873 This leads to X protocol errors at XtCloseDisplay (Bug#18403). */
12874 x_uncatch_errors ();
12876 #endif
12878 /* See if we should run in synchronous mode. This is useful
12879 for debugging X code. */
12881 AUTO_STRING (synchronous, "synchronous");
12882 AUTO_STRING (Synchronous, "Synchronous");
12883 Lisp_Object value = display_x_get_resource (dpyinfo, synchronous,
12884 Synchronous, Qnil, Qnil);
12885 if (STRINGP (value)
12886 && (!strcmp (SSDATA (value), "true")
12887 || !strcmp (SSDATA (value), "on")))
12888 XSynchronize (dpyinfo->display, True);
12892 AUTO_STRING (useXIM, "useXIM");
12893 AUTO_STRING (UseXIM, "UseXIM");
12894 Lisp_Object value = display_x_get_resource (dpyinfo, useXIM, UseXIM,
12895 Qnil, Qnil);
12896 #ifdef USE_XIM
12897 if (STRINGP (value)
12898 && (!strcmp (SSDATA (value), "false")
12899 || !strcmp (SSDATA (value), "off")))
12900 use_xim = false;
12901 #else
12902 if (STRINGP (value)
12903 && (!strcmp (SSDATA (value), "true")
12904 || !strcmp (SSDATA (value), "on")))
12905 use_xim = true;
12906 #endif
12909 #ifdef HAVE_X_SM
12910 /* Only do this for the very first display in the Emacs session.
12911 Ignore X session management when Emacs was first started on a
12912 tty or started as a daemon. */
12913 if (terminal->id == 1 && ! IS_DAEMON)
12914 x_session_initialize (dpyinfo);
12915 #endif
12917 #ifdef USE_CAIRO
12918 x_extension_initialize (dpyinfo);
12919 #endif
12921 unblock_input ();
12923 return dpyinfo;
12926 /* Get rid of display DPYINFO, deleting all frames on it,
12927 and without sending any more commands to the X server. */
12929 static void
12930 x_delete_display (struct x_display_info *dpyinfo)
12932 struct terminal *t;
12933 struct color_name_cache_entry *color_entry, *next_color_entry;
12935 /* Close all frames and delete the generic struct terminal for this
12936 X display. */
12937 for (t = terminal_list; t; t = t->next_terminal)
12938 if (t->type == output_x_window && t->display_info.x == dpyinfo)
12940 #ifdef HAVE_X_SM
12941 /* Close X session management when we close its display. */
12942 if (t->id == 1 && x_session_have_connection ())
12943 x_session_close ();
12944 #endif
12945 delete_terminal (t);
12946 break;
12949 if (next_noop_dpyinfo == dpyinfo)
12950 next_noop_dpyinfo = dpyinfo->next;
12952 if (x_display_list == dpyinfo)
12953 x_display_list = dpyinfo->next;
12954 else
12956 struct x_display_info *tail;
12958 for (tail = x_display_list; tail; tail = tail->next)
12959 if (tail->next == dpyinfo)
12960 tail->next = tail->next->next;
12963 for (color_entry = dpyinfo->color_names;
12964 color_entry;
12965 color_entry = next_color_entry)
12967 next_color_entry = color_entry->next;
12968 xfree (color_entry->name);
12969 xfree (color_entry);
12972 xfree (dpyinfo->x_id_name);
12973 xfree (dpyinfo->x_dnd_atoms);
12974 xfree (dpyinfo->color_cells);
12975 xfree (dpyinfo);
12978 #ifdef USE_X_TOOLKIT
12980 /* Atimer callback function for TIMER. Called every 0.1s to process
12981 Xt timeouts, if needed. We must avoid calling XtAppPending as
12982 much as possible because that function does an implicit XFlush
12983 that slows us down. */
12985 static void
12986 x_process_timeouts (struct atimer *timer)
12988 block_input ();
12989 x_timeout_atimer_activated_flag = false;
12990 if (toolkit_scroll_bar_interaction || popup_activated ())
12992 while (XtAppPending (Xt_app_con) & XtIMTimer)
12993 XtAppProcessEvent (Xt_app_con, XtIMTimer);
12994 /* Reactivate the atimer for next time. */
12995 x_activate_timeout_atimer ();
12997 unblock_input ();
13000 /* Install an asynchronous timer that processes Xt timeout events
13001 every 0.1s as long as either `toolkit_scroll_bar_interaction' or
13002 `popup_activated_flag' (in xmenu.c) is set. Make sure to call this
13003 function whenever these variables are set. This is necessary
13004 because some widget sets use timeouts internally, for example the
13005 LessTif menu bar, or the Xaw3d scroll bar. When Xt timeouts aren't
13006 processed, these widgets don't behave normally. */
13008 void
13009 x_activate_timeout_atimer (void)
13011 block_input ();
13012 if (!x_timeout_atimer_activated_flag)
13014 struct timespec interval = make_timespec (0, 100 * 1000 * 1000);
13015 start_atimer (ATIMER_RELATIVE, interval, x_process_timeouts, 0);
13016 x_timeout_atimer_activated_flag = true;
13018 unblock_input ();
13021 #endif /* USE_X_TOOLKIT */
13024 /* Set up use of X before we make the first connection. */
13026 static struct redisplay_interface x_redisplay_interface =
13028 x_frame_parm_handlers,
13029 x_produce_glyphs,
13030 x_write_glyphs,
13031 x_insert_glyphs,
13032 x_clear_end_of_line,
13033 x_scroll_run,
13034 x_after_update_window_line,
13035 x_update_window_begin,
13036 x_update_window_end,
13037 x_flip_and_flush,
13038 x_clear_window_mouse_face,
13039 x_get_glyph_overhangs,
13040 x_fix_overlapping_area,
13041 x_draw_fringe_bitmap,
13042 #ifdef USE_CAIRO
13043 x_cr_define_fringe_bitmap,
13044 x_cr_destroy_fringe_bitmap,
13045 #else
13046 0, /* define_fringe_bitmap */
13047 0, /* destroy_fringe_bitmap */
13048 #endif
13049 x_compute_glyph_string_overhangs,
13050 x_draw_glyph_string,
13051 x_define_frame_cursor,
13052 x_clear_frame_area,
13053 x_draw_window_cursor,
13054 x_draw_vertical_window_border,
13055 x_draw_window_divider,
13056 x_shift_glyphs_for_insert, /* Never called; see comment in function. */
13057 x_show_hourglass,
13058 x_hide_hourglass
13062 /* This function is called when the last frame on a display is deleted. */
13063 void
13064 x_delete_terminal (struct terminal *terminal)
13066 struct x_display_info *dpyinfo = terminal->display_info.x;
13068 /* Protect against recursive calls. delete_frame in
13069 delete_terminal calls us back when it deletes our last frame. */
13070 if (!terminal->name)
13071 return;
13073 block_input ();
13074 #ifdef HAVE_X_I18N
13075 /* We must close our connection to the XIM server before closing the
13076 X display. */
13077 if (dpyinfo->xim)
13078 xim_close_dpy (dpyinfo);
13079 #endif
13081 /* Normally, the display is available... */
13082 if (dpyinfo->display)
13084 x_destroy_all_bitmaps (dpyinfo);
13085 XSetCloseDownMode (dpyinfo->display, DestroyAll);
13087 /* Whether or not XCloseDisplay destroys the associated resource
13088 database depends on the version of libX11. To avoid both
13089 crash and memory leak, we dissociate the database from the
13090 display and then destroy dpyinfo->xrdb ourselves.
13092 Unfortunately, the above strategy does not work in some
13093 situations due to a bug in newer versions of libX11: because
13094 XrmSetDatabase doesn't clear the flag XlibDisplayDfltRMDB if
13095 dpy->db is NULL, XCloseDisplay destroys the associated
13096 database whereas it has not been created by XGetDefault
13097 (Bug#21974 in freedesktop.org Bugzilla). As a workaround, we
13098 don't destroy the database here in order to avoid the crash
13099 in the above situations for now, though that may cause memory
13100 leaks in other situations. */
13101 #if false
13102 #ifdef HAVE_XRMSETDATABASE
13103 XrmSetDatabase (dpyinfo->display, NULL);
13104 #else
13105 dpyinfo->display->db = NULL;
13106 #endif
13107 /* We used to call XrmDestroyDatabase from x_delete_display, but
13108 some older versions of libX11 crash if we call it after
13109 closing all the displays. */
13110 XrmDestroyDatabase (dpyinfo->xrdb);
13111 #endif
13113 #ifdef USE_GTK
13114 xg_display_close (dpyinfo->display);
13115 #else
13116 #ifdef USE_X_TOOLKIT
13117 XtCloseDisplay (dpyinfo->display);
13118 #else
13119 XCloseDisplay (dpyinfo->display);
13120 #endif
13121 #endif /* ! USE_GTK */
13122 /* Do not close the connection here because it's already closed
13123 by X(t)CloseDisplay (Bug#18403). */
13124 dpyinfo->display = NULL;
13127 /* ...but if called from x_connection_closed, the display may already
13128 be closed and dpyinfo->display was set to 0 to indicate that. Since
13129 X server is most likely gone, explicit close is the only reliable
13130 way to continue and avoid Bug#19147. */
13131 else if (dpyinfo->connection >= 0)
13132 emacs_close (dpyinfo->connection);
13134 /* No more input on this descriptor. */
13135 delete_keyboard_wait_descriptor (dpyinfo->connection);
13136 /* Mark as dead. */
13137 dpyinfo->connection = -1;
13139 x_delete_display (dpyinfo);
13140 unblock_input ();
13143 /* Create a struct terminal, initialize it with the X11 specific
13144 functions and make DISPLAY->TERMINAL point to it. */
13146 static struct terminal *
13147 x_create_terminal (struct x_display_info *dpyinfo)
13149 struct terminal *terminal;
13151 terminal = create_terminal (output_x_window, &x_redisplay_interface);
13153 terminal->display_info.x = dpyinfo;
13154 dpyinfo->terminal = terminal;
13156 /* kboard is initialized in x_term_init. */
13158 terminal->clear_frame_hook = x_clear_frame;
13159 terminal->ins_del_lines_hook = x_ins_del_lines;
13160 terminal->delete_glyphs_hook = x_delete_glyphs;
13161 terminal->ring_bell_hook = XTring_bell;
13162 terminal->toggle_invisible_pointer_hook = XTtoggle_invisible_pointer;
13163 terminal->update_begin_hook = x_update_begin;
13164 terminal->update_end_hook = x_update_end;
13165 terminal->read_socket_hook = XTread_socket;
13166 terminal->frame_up_to_date_hook = XTframe_up_to_date;
13167 terminal->buffer_flipping_unblocked_hook = XTbuffer_flipping_unblocked_hook;
13168 terminal->mouse_position_hook = XTmouse_position;
13169 terminal->frame_rehighlight_hook = XTframe_rehighlight;
13170 terminal->frame_raise_lower_hook = XTframe_raise_lower;
13171 terminal->fullscreen_hook = XTfullscreen_hook;
13172 terminal->menu_show_hook = x_menu_show;
13173 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
13174 terminal->popup_dialog_hook = xw_popup_dialog;
13175 #endif
13176 terminal->set_vertical_scroll_bar_hook = XTset_vertical_scroll_bar;
13177 terminal->set_horizontal_scroll_bar_hook = XTset_horizontal_scroll_bar;
13178 terminal->condemn_scroll_bars_hook = XTcondemn_scroll_bars;
13179 terminal->redeem_scroll_bar_hook = XTredeem_scroll_bar;
13180 terminal->judge_scroll_bars_hook = XTjudge_scroll_bars;
13181 terminal->delete_frame_hook = x_destroy_window;
13182 terminal->delete_terminal_hook = x_delete_terminal;
13183 /* Other hooks are NULL by default. */
13185 return terminal;
13188 static void
13189 x_initialize (void)
13191 baud_rate = 19200;
13193 x_noop_count = 0;
13194 any_help_event_p = false;
13195 ignore_next_mouse_click_timeout = 0;
13197 #ifdef USE_GTK
13198 current_count = -1;
13199 #endif
13201 /* Try to use interrupt input; if we can't, then start polling. */
13202 Fset_input_interrupt_mode (Qt);
13204 #if THREADS_ENABLED
13205 /* This must be called before any other Xlib routines. */
13206 if (XInitThreads () == 0)
13207 fprintf (stderr,
13208 "Warning: An error occurred initializing X11 thread support!\n");
13209 #endif
13211 #ifdef USE_X_TOOLKIT
13212 XtToolkitInitialize ();
13214 Xt_app_con = XtCreateApplicationContext ();
13216 /* Register a converter from strings to pixels, which uses
13217 Emacs' color allocation infrastructure. */
13218 XtAppSetTypeConverter (Xt_app_con,
13219 XtRString, XtRPixel, cvt_string_to_pixel,
13220 cvt_string_to_pixel_args,
13221 XtNumber (cvt_string_to_pixel_args),
13222 XtCacheByDisplay, cvt_pixel_dtor);
13224 XtAppSetFallbackResources (Xt_app_con, Xt_default_resources);
13225 #endif
13227 #ifdef USE_TOOLKIT_SCROLL_BARS
13228 #ifndef USE_GTK
13229 xaw3d_arrow_scroll = False;
13230 xaw3d_pick_top = True;
13231 #endif
13232 #endif
13234 #ifdef USE_CAIRO
13235 x_cr_init_fringe (&x_redisplay_interface);
13236 #endif
13238 /* Note that there is no real way portable across R3/R4 to get the
13239 original error handler. */
13240 XSetErrorHandler (x_error_handler);
13241 XSetIOErrorHandler (x_io_error_quitter);
13244 #ifdef USE_GTK
13245 void
13246 init_xterm (void)
13248 /* Emacs can handle only core input events, so make sure
13249 Gtk doesn't use Xinput or Xinput2 extensions. */
13250 xputenv ("GDK_CORE_DEVICE_EVENTS=1");
13252 #endif
13254 void
13255 syms_of_xterm (void)
13257 x_error_message = NULL;
13259 DEFSYM (Qvendor_specific_keysyms, "vendor-specific-keysyms");
13260 DEFSYM (Qlatin_1, "latin-1");
13262 #ifdef USE_GTK
13263 xg_default_icon_file = build_pure_c_string ("icons/hicolor/scalable/apps/emacs.svg");
13264 staticpro (&xg_default_icon_file);
13266 DEFSYM (Qx_gtk_map_stock, "x-gtk-map-stock");
13267 #endif
13269 DEFVAR_BOOL ("x-use-underline-position-properties",
13270 x_use_underline_position_properties,
13271 doc: /* Non-nil means make use of UNDERLINE_POSITION font properties.
13272 A value of nil means ignore them. If you encounter fonts with bogus
13273 UNDERLINE_POSITION font properties, set this to nil. You can also use
13274 `underline-minimum-offset' to override the font's UNDERLINE_POSITION for
13275 small font display sizes. */);
13276 x_use_underline_position_properties = true;
13277 DEFSYM (Qx_use_underline_position_properties,
13278 "x-use-underline-position-properties");
13280 DEFVAR_BOOL ("x-underline-at-descent-line",
13281 x_underline_at_descent_line,
13282 doc: /* Non-nil means to draw the underline at the same place as the descent line.
13283 (If `line-spacing' is in effect, that moves the underline lower by
13284 that many pixels.)
13285 A value of nil means to draw the underline according to the value of the
13286 variable `x-use-underline-position-properties', which is usually at the
13287 baseline level. The default value is nil. */);
13288 x_underline_at_descent_line = false;
13289 DEFSYM (Qx_underline_at_descent_line, "x-underline-at-descent-line");
13291 DEFVAR_BOOL ("x-mouse-click-focus-ignore-position",
13292 x_mouse_click_focus_ignore_position,
13293 doc: /* Non-nil means that a mouse click to focus a frame does not move point.
13294 This variable is only used when the window manager requires that you
13295 click on a frame to select it (give it focus). In that case, a value
13296 of nil, means that the selected window and cursor position changes to
13297 reflect the mouse click position, while a non-nil value means that the
13298 selected window or cursor position is preserved. */);
13299 x_mouse_click_focus_ignore_position = false;
13301 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
13302 doc: /* Which toolkit scroll bars Emacs uses, if any.
13303 A value of nil means Emacs doesn't use toolkit scroll bars.
13304 With the X Window system, the value is a symbol describing the
13305 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
13306 With MS Windows or Nextstep, the value is t. */);
13307 #ifdef USE_TOOLKIT_SCROLL_BARS
13308 #ifdef USE_MOTIF
13309 Vx_toolkit_scroll_bars = intern_c_string ("motif");
13310 #elif defined HAVE_XAW3D
13311 Vx_toolkit_scroll_bars = intern_c_string ("xaw3d");
13312 #elif USE_GTK
13313 Vx_toolkit_scroll_bars = intern_c_string ("gtk");
13314 #else
13315 Vx_toolkit_scroll_bars = intern_c_string ("xaw");
13316 #endif
13317 #else
13318 Vx_toolkit_scroll_bars = Qnil;
13319 #endif
13321 DEFSYM (Qmodifier_value, "modifier-value");
13322 DEFSYM (Qctrl, "ctrl");
13323 Fput (Qctrl, Qmodifier_value, make_number (ctrl_modifier));
13324 DEFSYM (Qalt, "alt");
13325 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
13326 DEFSYM (Qhyper, "hyper");
13327 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
13328 DEFSYM (Qmeta, "meta");
13329 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
13330 DEFSYM (Qsuper, "super");
13331 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
13333 DEFVAR_LISP ("x-ctrl-keysym", Vx_ctrl_keysym,
13334 doc: /* Which keys Emacs uses for the ctrl modifier.
13335 This should be one of the symbols `ctrl', `alt', `hyper', `meta',
13336 `super'. For example, `ctrl' means use the Ctrl_L and Ctrl_R keysyms.
13337 The default is nil, which is the same as `ctrl'. */);
13338 Vx_ctrl_keysym = Qnil;
13340 DEFVAR_LISP ("x-alt-keysym", Vx_alt_keysym,
13341 doc: /* Which keys Emacs uses for the alt modifier.
13342 This should be one of the symbols `ctrl', `alt', `hyper', `meta',
13343 `super'. For example, `alt' means use the Alt_L and Alt_R keysyms.
13344 The default is nil, which is the same as `alt'. */);
13345 Vx_alt_keysym = Qnil;
13347 DEFVAR_LISP ("x-hyper-keysym", Vx_hyper_keysym,
13348 doc: /* Which keys Emacs uses for the hyper modifier.
13349 This should be one of the symbols `ctrl', `alt', `hyper', `meta',
13350 `super'. For example, `hyper' means use the Hyper_L and Hyper_R
13351 keysyms. The default is nil, which is the same as `hyper'. */);
13352 Vx_hyper_keysym = Qnil;
13354 DEFVAR_LISP ("x-meta-keysym", Vx_meta_keysym,
13355 doc: /* Which keys Emacs uses for the meta modifier.
13356 This should be one of the symbols `ctrl', `alt', `hyper', `meta',
13357 `super'. For example, `meta' means use the Meta_L and Meta_R keysyms.
13358 The default is nil, which is the same as `meta'. */);
13359 Vx_meta_keysym = Qnil;
13361 DEFVAR_LISP ("x-super-keysym", Vx_super_keysym,
13362 doc: /* Which keys Emacs uses for the super modifier.
13363 This should be one of the symbols `ctrl', `alt', `hyper', `meta',
13364 `super'. For example, `super' means use the Super_L and Super_R
13365 keysyms. The default is nil, which is the same as `super'. */);
13366 Vx_super_keysym = Qnil;
13368 DEFVAR_LISP ("x-wait-for-event-timeout", Vx_wait_for_event_timeout,
13369 doc: /* How long to wait for X events.
13371 Emacs will wait up to this many seconds to receive X events after
13372 making changes which affect the state of the graphical interface.
13373 Under some window managers this can take an indefinite amount of time,
13374 so it is important to limit the wait.
13376 If set to a non-float value, there will be no wait at all. */);
13377 Vx_wait_for_event_timeout = make_float (0.1);
13379 DEFVAR_LISP ("x-keysym-table", Vx_keysym_table,
13380 doc: /* Hash table of character codes indexed by X keysym codes. */);
13381 Vx_keysym_table = make_hash_table (hashtest_eql, 900,
13382 DEFAULT_REHASH_SIZE,
13383 DEFAULT_REHASH_THRESHOLD,
13384 Qnil, false);
13386 DEFVAR_BOOL ("x-frame-normalize-before-maximize",
13387 x_frame_normalize_before_maximize,
13388 doc: /* Non-nil means normalize frame before maximizing.
13389 If this variable is t, Emacs first asks the window manager to give the
13390 frame its normal size, and only then the final state, whenever changing
13391 from a full-height, full-width or full-both state to the maximized one
13392 or when changing from the maximized to the full-height or full-width
13393 state.
13395 Set this variable only if your window manager cannot handle the
13396 transition between the various maximization states. */);
13397 x_frame_normalize_before_maximize = false;
13399 DEFVAR_BOOL ("x-gtk-use-window-move", x_gtk_use_window_move,
13400 doc: /* Non-nil means rely on gtk_window_move to set frame positions.
13401 If this variable is t (the default), the GTK build uses the function
13402 gtk_window_move to set or store frame positions and disables some time
13403 consuming frame position adjustments. In newer versions of GTK, Emacs
13404 always uses gtk_window_move and ignores the value of this variable. */);
13405 x_gtk_use_window_move = true;