Fix some problems in the Cairo build
[emacs.git] / src / xterm.c
blob35e10568fa7e1aaa13edc9e1c37b3b5864f014b5
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 (Lisp_Object arg)
549 cairo_t *cr = (cairo_t *) XSAVE_POINTER (arg, 0);
551 block_input ();
552 cairo_destroy (cr);
553 unblock_input ();
556 Lisp_Object
557 x_cr_export_frames (Lisp_Object frames, cairo_surface_type_t surface_type)
559 struct frame *f;
560 cairo_surface_t *surface;
561 cairo_t *cr;
562 int width, height;
563 void (*surface_set_size_func) (cairo_surface_t *, double, double) = NULL;
564 Lisp_Object acc = Qnil;
565 ptrdiff_t count = SPECPDL_INDEX ();
567 specbind (Qredisplay_dont_pause, Qt);
568 redisplay_preserve_echo_area (31);
570 f = XFRAME (XCAR (frames));
571 frames = XCDR (frames);
572 width = FRAME_PIXEL_WIDTH (f);
573 height = FRAME_PIXEL_HEIGHT (f);
575 block_input ();
576 #ifdef CAIRO_HAS_PDF_SURFACE
577 if (surface_type == CAIRO_SURFACE_TYPE_PDF)
579 surface = cairo_pdf_surface_create_for_stream (x_cr_accumulate_data, &acc,
580 width, height);
581 surface_set_size_func = cairo_pdf_surface_set_size;
583 else
584 #endif
585 #ifdef CAIRO_HAS_PNG_FUNCTIONS
586 if (surface_type == CAIRO_SURFACE_TYPE_IMAGE)
587 surface = cairo_image_surface_create (CAIRO_FORMAT_RGB24, width, height);
588 else
589 #endif
590 #ifdef CAIRO_HAS_PS_SURFACE
591 if (surface_type == CAIRO_SURFACE_TYPE_PS)
593 surface = cairo_ps_surface_create_for_stream (x_cr_accumulate_data, &acc,
594 width, height);
595 surface_set_size_func = cairo_ps_surface_set_size;
597 else
598 #endif
599 #ifdef CAIRO_HAS_SVG_SURFACE
600 if (surface_type == CAIRO_SURFACE_TYPE_SVG)
601 surface = cairo_svg_surface_create_for_stream (x_cr_accumulate_data, &acc,
602 width, height);
603 else
604 #endif
605 abort ();
607 cr = cairo_create (surface);
608 cairo_surface_destroy (surface);
609 record_unwind_protect (x_cr_destroy, make_save_ptr (cr));
611 while (1)
613 x_free_cr_resources (f);
614 FRAME_CR_CONTEXT (f) = cr;
615 x_clear_area (f, 0, 0, width, height);
616 expose_frame (f, 0, 0, width, height);
617 FRAME_CR_CONTEXT (f) = NULL;
619 if (NILP (frames))
620 break;
622 cairo_surface_show_page (surface);
623 f = XFRAME (XCAR (frames));
624 frames = XCDR (frames);
625 width = FRAME_PIXEL_WIDTH (f);
626 height = FRAME_PIXEL_HEIGHT (f);
627 if (surface_set_size_func)
628 (*surface_set_size_func) (surface, width, height);
630 unblock_input ();
631 maybe_quit ();
632 block_input ();
635 #ifdef CAIRO_HAS_PNG_FUNCTIONS
636 if (surface_type == CAIRO_SURFACE_TYPE_IMAGE)
638 cairo_surface_flush (surface);
639 cairo_surface_write_to_png_stream (surface, x_cr_accumulate_data, &acc);
641 #endif
642 unblock_input ();
644 unbind_to (count, Qnil);
646 return CALLN (Fapply, intern ("concat"), Fnreverse (acc));
649 #endif /* USE_CAIRO */
651 static void
652 x_free_cr_resources (struct frame *f)
654 #ifdef USE_CAIRO
655 if (f == NULL)
657 Lisp_Object rest, frame;
658 FOR_EACH_FRAME (rest, frame)
659 if (FRAME_X_P (XFRAME (frame)))
660 x_free_cr_resources (XFRAME (frame));
662 else
664 cairo_t *cr = FRAME_CR_CONTEXT (f);
666 if (cr)
668 cairo_surface_t *surface = cairo_get_target (cr);
670 if (cairo_surface_get_type (surface) == CAIRO_SURFACE_TYPE_XLIB)
672 cairo_destroy (cr);
673 FRAME_CR_CONTEXT (f) = NULL;
677 #endif
680 static void
681 x_set_clip_rectangles (struct frame *f, GC gc, XRectangle *rectangles, int n)
683 XSetClipRectangles (FRAME_X_DISPLAY (f), gc, 0, 0, rectangles, n, Unsorted);
684 #ifdef USE_CAIRO
685 eassert (n >= 0 && n <= MAX_CLIP_RECTS);
688 struct x_gc_ext_data *gc_ext = x_gc_get_ext_data (f, gc, 1);
690 gc_ext->n_clip_rects = n;
691 memcpy (gc_ext->clip_rects, rectangles, sizeof (XRectangle) * n);
693 #endif
696 static void
697 x_reset_clip_rectangles (struct frame *f, GC gc)
699 XSetClipMask (FRAME_X_DISPLAY (f), gc, None);
700 #ifdef USE_CAIRO
702 struct x_gc_ext_data *gc_ext = x_gc_get_ext_data (f, gc, 0);
704 if (gc_ext)
705 gc_ext->n_clip_rects = 0;
707 #endif
710 static void
711 x_fill_rectangle (struct frame *f, GC gc, int x, int y, int width, int height)
713 #ifdef USE_CAIRO
714 cairo_t *cr;
716 cr = x_begin_cr_clip (f, gc);
717 x_set_cr_source_with_gc_foreground (f, gc);
718 cairo_rectangle (cr, x, y, width, height);
719 cairo_fill (cr);
720 x_end_cr_clip (f);
721 #else
722 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_DRAWABLE (f),
723 gc, x, y, width, height);
724 #endif
727 static void
728 x_draw_rectangle (struct frame *f, GC gc, int x, int y, int width, int height)
730 #ifdef USE_CAIRO
731 cairo_t *cr;
733 cr = x_begin_cr_clip (f, gc);
734 x_set_cr_source_with_gc_foreground (f, gc);
735 cairo_rectangle (cr, x + 0.5, y + 0.5, width, height);
736 cairo_set_line_width (cr, 1);
737 cairo_stroke (cr);
738 x_end_cr_clip (f);
739 #else
740 XDrawRectangle (FRAME_X_DISPLAY (f), FRAME_X_DRAWABLE (f),
741 gc, x, y, width, height);
742 #endif
745 static void
746 x_clear_window (struct frame *f)
748 #ifdef USE_CAIRO
749 cairo_t *cr;
751 cr = x_begin_cr_clip (f, NULL);
752 x_set_cr_source_with_gc_background (f, f->output_data.x->normal_gc);
753 cairo_paint (cr);
754 x_end_cr_clip (f);
755 #else
756 if (FRAME_X_DOUBLE_BUFFERED_P (f))
757 x_clear_area (f, 0, 0, FRAME_PIXEL_WIDTH (f), FRAME_PIXEL_HEIGHT (f));
758 else
759 XClearWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
760 #endif
763 #ifdef USE_CAIRO
764 static void
765 x_fill_trapezoid_for_relief (struct frame *f, GC gc, int x, int y,
766 int width, int height, int top_p)
768 cairo_t *cr;
770 cr = x_begin_cr_clip (f, gc);
771 x_set_cr_source_with_gc_foreground (f, gc);
772 cairo_move_to (cr, top_p ? x : x + height, y);
773 cairo_line_to (cr, x, y + height);
774 cairo_line_to (cr, top_p ? x + width - height : x + width, y + height);
775 cairo_line_to (cr, x + width, y);
776 cairo_fill (cr);
777 x_end_cr_clip (f);
780 enum corners
782 CORNER_BOTTOM_RIGHT, /* 0 -> pi/2 */
783 CORNER_BOTTOM_LEFT, /* pi/2 -> pi */
784 CORNER_TOP_LEFT, /* pi -> 3pi/2 */
785 CORNER_TOP_RIGHT, /* 3pi/2 -> 2pi */
786 CORNER_LAST
789 static void
790 x_erase_corners_for_relief (struct frame *f, GC gc, int x, int y,
791 int width, int height,
792 double radius, double margin, int corners)
794 cairo_t *cr;
795 int i;
797 cr = x_begin_cr_clip (f, gc);
798 x_set_cr_source_with_gc_background (f, gc);
799 for (i = 0; i < CORNER_LAST; i++)
800 if (corners & (1 << i))
802 double xm, ym, xc, yc;
804 if (i == CORNER_TOP_LEFT || i == CORNER_BOTTOM_LEFT)
805 xm = x - margin, xc = xm + radius;
806 else
807 xm = x + width + margin, xc = xm - radius;
808 if (i == CORNER_TOP_LEFT || i == CORNER_TOP_RIGHT)
809 ym = y - margin, yc = ym + radius;
810 else
811 ym = y + height + margin, yc = ym - radius;
813 cairo_move_to (cr, xm, ym);
814 cairo_arc (cr, xc, yc, radius, i * M_PI_2, (i + 1) * M_PI_2);
816 cairo_clip (cr);
817 cairo_rectangle (cr, x, y, width, height);
818 cairo_fill (cr);
819 x_end_cr_clip (f);
822 static void
823 x_draw_horizontal_wave (struct frame *f, GC gc, int x, int y,
824 int width, int height, int wave_length)
826 cairo_t *cr;
827 double dx = wave_length, dy = height - 1;
828 int xoffset, n;
830 cr = x_begin_cr_clip (f, gc);
831 x_set_cr_source_with_gc_foreground (f, gc);
832 cairo_rectangle (cr, x, y, width, height);
833 cairo_clip (cr);
835 if (x >= 0)
837 xoffset = x % (wave_length * 2);
838 if (xoffset == 0)
839 xoffset = wave_length * 2;
841 else
842 xoffset = x % (wave_length * 2) + wave_length * 2;
843 n = (width + xoffset) / wave_length + 1;
844 if (xoffset > wave_length)
846 xoffset -= wave_length;
847 --n;
848 y += height - 1;
849 dy = -dy;
852 cairo_move_to (cr, x - xoffset + 0.5, y + 0.5);
853 while (--n >= 0)
855 cairo_rel_line_to (cr, dx, dy);
856 dy = -dy;
858 cairo_set_line_width (cr, 1);
859 cairo_stroke (cr);
860 x_end_cr_clip (f);
862 #endif
865 /* Return the struct x_display_info corresponding to DPY. */
867 struct x_display_info *
868 x_display_info_for_display (Display *dpy)
870 struct x_display_info *dpyinfo;
872 for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
873 if (dpyinfo->display == dpy)
874 return dpyinfo;
876 return 0;
879 static Window
880 x_find_topmost_parent (struct frame *f)
882 struct x_output *x = f->output_data.x;
883 Window win = None, wi = x->parent_desc;
884 Display *dpy = FRAME_X_DISPLAY (f);
886 while (wi != FRAME_DISPLAY_INFO (f)->root_window)
888 Window root;
889 Window *children;
890 unsigned int nchildren;
892 win = wi;
893 if (XQueryTree (dpy, win, &root, &wi, &children, &nchildren))
894 XFree (children);
895 else
896 break;
899 return win;
902 #define OPAQUE 0xffffffff
904 void
905 x_set_frame_alpha (struct frame *f)
907 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
908 Display *dpy = FRAME_X_DISPLAY (f);
909 Window win = FRAME_OUTER_WINDOW (f);
910 double alpha = 1.0;
911 double alpha_min = 1.0;
912 unsigned long opac;
913 Window parent;
915 if (dpyinfo->x_highlight_frame == f)
916 alpha = f->alpha[0];
917 else
918 alpha = f->alpha[1];
920 if (FLOATP (Vframe_alpha_lower_limit))
921 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
922 else if (INTEGERP (Vframe_alpha_lower_limit))
923 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
925 if (alpha < 0.0)
926 return;
927 else if (alpha > 1.0)
928 alpha = 1.0;
929 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
930 alpha = alpha_min;
932 opac = alpha * OPAQUE;
934 x_catch_errors (dpy);
936 /* If there is a parent from the window manager, put the property there
937 also, to work around broken window managers that fail to do that.
938 Do this unconditionally as this function is called on reparent when
939 alpha has not changed on the frame. */
941 if (!FRAME_PARENT_FRAME (f))
943 parent = x_find_topmost_parent (f);
944 if (parent != None)
945 XChangeProperty (dpy, parent, dpyinfo->Xatom_net_wm_window_opacity,
946 XA_CARDINAL, 32, PropModeReplace,
947 (unsigned char *) &opac, 1);
950 /* return unless necessary */
952 unsigned char *data;
953 Atom actual;
954 int rc, format;
955 unsigned long n, left;
957 rc = XGetWindowProperty (dpy, win, dpyinfo->Xatom_net_wm_window_opacity,
958 0, 1, False, XA_CARDINAL,
959 &actual, &format, &n, &left,
960 &data);
962 if (rc == Success && actual != None)
964 unsigned long value = *(unsigned long *)data;
965 XFree (data);
966 if (value == opac)
968 x_uncatch_errors ();
969 return;
974 XChangeProperty (dpy, win, dpyinfo->Xatom_net_wm_window_opacity,
975 XA_CARDINAL, 32, PropModeReplace,
976 (unsigned char *) &opac, 1);
977 x_uncatch_errors ();
980 /***********************************************************************
981 Starting and ending an update
982 ***********************************************************************/
984 /* Start an update of frame F. This function is installed as a hook
985 for update_begin, i.e. it is called when update_begin is called.
986 This function is called prior to calls to x_update_window_begin for
987 each window being updated. Currently, there is nothing to do here
988 because all interesting stuff is done on a window basis. */
990 static void
991 x_update_begin (struct frame *f)
993 #ifdef USE_CAIRO
994 if (FRAME_TOOLTIP_P (f) && !FRAME_VISIBLE_P (f))
995 return;
997 if (! FRAME_CR_SURFACE (f))
999 int width, height;
1000 #ifdef USE_GTK
1001 if (FRAME_GTK_WIDGET (f))
1003 GdkWindow *w = gtk_widget_get_window (FRAME_GTK_WIDGET (f));
1004 width = gdk_window_get_width (w);
1005 height = gdk_window_get_height (w);
1007 else
1008 #endif
1010 width = FRAME_PIXEL_WIDTH (f);
1011 height = FRAME_PIXEL_HEIGHT (f);
1012 if (! FRAME_EXTERNAL_TOOL_BAR (f))
1013 height += FRAME_TOOL_BAR_HEIGHT (f);
1014 if (! FRAME_EXTERNAL_MENU_BAR (f))
1015 height += FRAME_MENU_BAR_HEIGHT (f);
1018 if (width > 0 && height > 0)
1020 block_input();
1021 FRAME_CR_SURFACE (f) = cairo_image_surface_create
1022 (CAIRO_FORMAT_ARGB32, width, height);
1023 unblock_input();
1026 #endif /* USE_CAIRO */
1029 /* Start update of window W. */
1031 static void
1032 x_update_window_begin (struct window *w)
1034 struct frame *f = XFRAME (WINDOW_FRAME (w));
1035 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1037 w->output_cursor = w->cursor;
1039 block_input ();
1041 if (f == hlinfo->mouse_face_mouse_frame)
1043 /* Don't do highlighting for mouse motion during the update. */
1044 hlinfo->mouse_face_defer = true;
1046 /* If F needs to be redrawn, simply forget about any prior mouse
1047 highlighting. */
1048 if (FRAME_GARBAGED_P (f))
1049 hlinfo->mouse_face_window = Qnil;
1052 unblock_input ();
1056 /* Draw a vertical window border from (x,y0) to (x,y1) */
1058 static void
1059 x_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
1061 struct frame *f = XFRAME (WINDOW_FRAME (w));
1062 struct face *face;
1064 face = FACE_FROM_ID_OR_NULL (f, VERTICAL_BORDER_FACE_ID);
1065 if (face)
1066 XSetForeground (FRAME_X_DISPLAY (f), f->output_data.x->normal_gc,
1067 face->foreground);
1069 #ifdef USE_CAIRO
1070 x_fill_rectangle (f, f->output_data.x->normal_gc, x, y0, 1, y1 - y0);
1071 #else
1072 XDrawLine (FRAME_X_DISPLAY (f), FRAME_X_DRAWABLE (f),
1073 f->output_data.x->normal_gc, x, y0, x, y1);
1074 #endif
1077 /* Draw a window divider from (x0,y0) to (x1,y1) */
1079 static void
1080 x_draw_window_divider (struct window *w, int x0, int x1, int y0, int y1)
1082 struct frame *f = XFRAME (WINDOW_FRAME (w));
1083 struct face *face = FACE_FROM_ID_OR_NULL (f, WINDOW_DIVIDER_FACE_ID);
1084 struct face *face_first
1085 = FACE_FROM_ID_OR_NULL (f, WINDOW_DIVIDER_FIRST_PIXEL_FACE_ID);
1086 struct face *face_last
1087 = FACE_FROM_ID_OR_NULL (f, WINDOW_DIVIDER_LAST_PIXEL_FACE_ID);
1088 unsigned long color = face ? face->foreground : FRAME_FOREGROUND_PIXEL (f);
1089 unsigned long color_first = (face_first
1090 ? face_first->foreground
1091 : FRAME_FOREGROUND_PIXEL (f));
1092 unsigned long color_last = (face_last
1093 ? face_last->foreground
1094 : FRAME_FOREGROUND_PIXEL (f));
1095 Display *display = FRAME_X_DISPLAY (f);
1097 if ((y1 - y0 > x1 - x0) && (x1 - x0 >= 3))
1098 /* A vertical divider, at least three pixels wide: Draw first and
1099 last pixels differently. */
1101 XSetForeground (display, f->output_data.x->normal_gc, color_first);
1102 x_fill_rectangle (f, f->output_data.x->normal_gc,
1103 x0, y0, 1, y1 - y0);
1104 XSetForeground (display, f->output_data.x->normal_gc, color);
1105 x_fill_rectangle (f, f->output_data.x->normal_gc,
1106 x0 + 1, y0, x1 - x0 - 2, y1 - y0);
1107 XSetForeground (display, f->output_data.x->normal_gc, color_last);
1108 x_fill_rectangle (f, f->output_data.x->normal_gc,
1109 x1 - 1, y0, 1, y1 - y0);
1111 else if ((x1 - x0 > y1 - y0) && (y1 - y0 >= 3))
1112 /* A horizontal divider, at least three pixels high: Draw first and
1113 last pixels differently. */
1115 XSetForeground (display, f->output_data.x->normal_gc, color_first);
1116 x_fill_rectangle (f, f->output_data.x->normal_gc,
1117 x0, y0, x1 - x0, 1);
1118 XSetForeground (display, f->output_data.x->normal_gc, color);
1119 x_fill_rectangle (f, f->output_data.x->normal_gc,
1120 x0, y0 + 1, x1 - x0, y1 - y0 - 2);
1121 XSetForeground (display, f->output_data.x->normal_gc, color_last);
1122 x_fill_rectangle (f, f->output_data.x->normal_gc,
1123 x0, y1 - 1, x1 - x0, 1);
1125 else
1127 /* In any other case do not draw the first and last pixels
1128 differently. */
1129 XSetForeground (display, f->output_data.x->normal_gc, color);
1130 x_fill_rectangle (f, f->output_data.x->normal_gc,
1131 x0, y0, x1 - x0, y1 - y0);
1135 /* End update of window W.
1137 Draw vertical borders between horizontally adjacent windows, and
1138 display W's cursor if CURSOR_ON_P is non-zero.
1140 MOUSE_FACE_OVERWRITTEN_P non-zero means that some row containing
1141 glyphs in mouse-face were overwritten. In that case we have to
1142 make sure that the mouse-highlight is properly redrawn.
1144 W may be a menu bar pseudo-window in case we don't have X toolkit
1145 support. Such windows don't have a cursor, so don't display it
1146 here. */
1148 static void
1149 x_update_window_end (struct window *w, bool cursor_on_p,
1150 bool mouse_face_overwritten_p)
1152 if (!w->pseudo_window_p)
1154 block_input ();
1156 if (cursor_on_p)
1157 display_and_set_cursor (w, true,
1158 w->output_cursor.hpos, w->output_cursor.vpos,
1159 w->output_cursor.x, w->output_cursor.y);
1161 if (draw_window_fringes (w, true))
1163 if (WINDOW_RIGHT_DIVIDER_WIDTH (w))
1164 x_draw_right_divider (w);
1165 else
1166 x_draw_vertical_border (w);
1169 unblock_input ();
1172 /* If a row with mouse-face was overwritten, arrange for
1173 XTframe_up_to_date to redisplay the mouse highlight. */
1174 if (mouse_face_overwritten_p)
1176 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (XFRAME (w->frame));
1178 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
1179 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
1180 hlinfo->mouse_face_window = Qnil;
1184 /* Show the frame back buffer. If frame is double-buffered,
1185 atomically publish to the user's screen graphics updates made since
1186 the last call to show_back_buffer. */
1187 static void
1188 show_back_buffer (struct frame *f)
1190 block_input ();
1191 if (FRAME_X_DOUBLE_BUFFERED_P (f))
1193 #ifdef HAVE_XDBE
1194 XdbeSwapInfo swap_info;
1195 memset (&swap_info, 0, sizeof (swap_info));
1196 swap_info.swap_window = FRAME_X_WINDOW (f);
1197 swap_info.swap_action = XdbeCopied;
1198 XdbeSwapBuffers (FRAME_X_DISPLAY (f), &swap_info, 1);
1199 #else
1200 eassert (!"should have back-buffer only with XDBE");
1201 #endif
1203 FRAME_X_NEED_BUFFER_FLIP (f) = false;
1204 unblock_input ();
1207 /* Updates back buffer and flushes changes to display. Called from
1208 minibuf read code. Note that we display the back buffer even if
1209 buffer flipping is blocked. */
1210 static void
1211 x_flip_and_flush (struct frame *f)
1213 block_input ();
1214 if (FRAME_X_NEED_BUFFER_FLIP (f))
1215 show_back_buffer (f);
1216 x_flush (f);
1217 unblock_input ();
1220 /* End update of frame F. This function is installed as a hook in
1221 update_end. */
1223 static void
1224 x_update_end (struct frame *f)
1226 /* Mouse highlight may be displayed again. */
1227 MOUSE_HL_INFO (f)->mouse_face_defer = false;
1229 #ifdef USE_CAIRO
1230 if (FRAME_CR_SURFACE (f))
1232 cairo_t *cr;
1233 cairo_surface_t *surface;
1234 int width, height;
1236 block_input ();
1237 width = FRAME_PIXEL_WIDTH (f);
1238 height = FRAME_PIXEL_HEIGHT (f);
1239 if (! FRAME_EXTERNAL_TOOL_BAR (f))
1240 height += FRAME_TOOL_BAR_HEIGHT (f);
1241 if (! FRAME_EXTERNAL_MENU_BAR (f))
1242 height += FRAME_MENU_BAR_HEIGHT (f);
1243 surface = cairo_xlib_surface_create (FRAME_X_DISPLAY (f),
1244 FRAME_X_DRAWABLE (f),
1245 FRAME_DISPLAY_INFO (f)->visual,
1246 width,
1247 height);
1248 cr = cairo_create (surface);
1249 cairo_surface_destroy (surface);
1251 cairo_set_source_surface (cr, FRAME_CR_SURFACE (f), 0, 0);
1252 cairo_paint (cr);
1253 cairo_destroy (cr);
1254 unblock_input ();
1256 #endif
1258 #ifndef XFlush
1259 block_input ();
1260 XFlush (FRAME_X_DISPLAY (f));
1261 unblock_input ();
1262 #endif
1265 /* This function is called from various places in xdisp.c
1266 whenever a complete update has been performed. */
1268 static void
1269 XTframe_up_to_date (struct frame *f)
1271 eassert (FRAME_X_P (f));
1272 block_input ();
1273 FRAME_MOUSE_UPDATE (f);
1274 if (!buffer_flipping_blocked_p () && FRAME_X_NEED_BUFFER_FLIP (f))
1275 show_back_buffer (f);
1276 unblock_input ();
1279 static void
1280 XTbuffer_flipping_unblocked_hook (struct frame *f)
1282 if (FRAME_X_NEED_BUFFER_FLIP (f))
1283 show_back_buffer (f);
1287 * x_clear_under_internal_border:
1289 * Clear area of frame F's internal border. If the internal border face
1290 * of F has been specified (is not null), fill the area with that face.
1292 void
1293 x_clear_under_internal_border (struct frame *f)
1295 if (FRAME_INTERNAL_BORDER_WIDTH (f) > 0)
1297 int border = FRAME_INTERNAL_BORDER_WIDTH (f);
1298 int width = FRAME_PIXEL_WIDTH (f);
1299 int height = FRAME_PIXEL_HEIGHT (f);
1300 #ifdef USE_GTK
1301 int margin = 0;
1302 #else
1303 int margin = FRAME_TOP_MARGIN_HEIGHT (f);
1304 #endif
1305 struct face *face = FACE_FROM_ID_OR_NULL (f, INTERNAL_BORDER_FACE_ID);
1307 block_input ();
1309 if (face)
1311 unsigned long color = face->background;
1312 Display *display = FRAME_X_DISPLAY (f);
1313 GC gc = f->output_data.x->normal_gc;
1315 XSetForeground (display, gc, color);
1316 x_fill_rectangle (f, gc, 0, margin, width, border);
1317 x_fill_rectangle (f, gc, 0, 0, border, height);
1318 x_fill_rectangle (f, gc, width - border, 0, border, height);
1319 x_fill_rectangle (f, gc, 0, height - border, width, border);
1320 XSetForeground (display, gc, FRAME_FOREGROUND_PIXEL (f));
1322 else
1324 x_clear_area (f, 0, 0, border, height);
1325 x_clear_area (f, 0, margin, width, border);
1326 x_clear_area (f, width - border, 0, border, height);
1327 x_clear_area (f, 0, height - border, width, border);
1330 unblock_input ();
1334 /* Draw truncation mark bitmaps, continuation mark bitmaps, overlay
1335 arrow bitmaps, or clear the fringes if no bitmaps are required
1336 before DESIRED_ROW is made current. This function is called from
1337 update_window_line only if it is known that there are differences
1338 between bitmaps to be drawn between current row and DESIRED_ROW. */
1340 static void
1341 x_after_update_window_line (struct window *w, struct glyph_row *desired_row)
1343 eassert (w);
1345 if (!desired_row->mode_line_p && !w->pseudo_window_p)
1346 desired_row->redraw_fringe_bitmaps_p = true;
1348 #ifdef USE_X_TOOLKIT
1349 /* When a window has disappeared, make sure that no rest of
1350 full-width rows stays visible in the internal border. Could
1351 check here if updated window is the leftmost/rightmost window,
1352 but I guess it's not worth doing since vertically split windows
1353 are almost never used, internal border is rarely set, and the
1354 overhead is very small. */
1356 struct frame *f;
1357 int width, height;
1359 if (windows_or_buffers_changed
1360 && desired_row->full_width_p
1361 && (f = XFRAME (w->frame),
1362 width = FRAME_INTERNAL_BORDER_WIDTH (f),
1363 width != 0)
1364 && (height = desired_row->visible_height,
1365 height > 0))
1367 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
1368 struct face *face = FACE_FROM_ID_OR_NULL (f, INTERNAL_BORDER_FACE_ID);
1370 block_input ();
1371 if (face)
1373 unsigned long color = face->background;
1374 Display *display = FRAME_X_DISPLAY (f);
1375 GC gc = f->output_data.x->normal_gc;
1377 XSetForeground (display, gc, color);
1378 x_fill_rectangle (f, gc, 0, y, width, height);
1379 x_fill_rectangle (f, gc, FRAME_PIXEL_WIDTH (f) - width, y,
1380 width, height);
1381 XSetForeground (display, gc, FRAME_FOREGROUND_PIXEL (f));
1383 else
1385 x_clear_area (f, 0, y, width, height);
1386 x_clear_area (f, FRAME_PIXEL_WIDTH (f) - width, y, width, height);
1388 unblock_input ();
1391 #endif
1394 static void
1395 x_draw_fringe_bitmap (struct window *w, struct glyph_row *row, struct draw_fringe_bitmap_params *p)
1397 struct frame *f = XFRAME (WINDOW_FRAME (w));
1398 Display *display = FRAME_X_DISPLAY (f);
1399 GC gc = f->output_data.x->normal_gc;
1400 struct face *face = p->face;
1402 /* Must clip because of partially visible lines. */
1403 x_clip_to_row (w, row, ANY_AREA, gc);
1405 if (p->bx >= 0 && !p->overlay_p)
1407 /* In case the same realized face is used for fringes and
1408 for something displayed in the text (e.g. face `region' on
1409 mono-displays, the fill style may have been changed to
1410 FillSolid in x_draw_glyph_string_background. */
1411 if (face->stipple)
1412 XSetFillStyle (display, face->gc, FillOpaqueStippled);
1413 else
1414 XSetForeground (display, face->gc, face->background);
1416 x_fill_rectangle (f, face->gc, p->bx, p->by, p->nx, p->ny);
1418 if (!face->stipple)
1419 XSetForeground (display, face->gc, face->foreground);
1422 #ifdef USE_CAIRO
1423 if (p->which && p->which < max_fringe_bmp)
1425 XGCValues gcv;
1427 XGetGCValues (display, gc, GCForeground | GCBackground, &gcv);
1428 XSetForeground (display, gc, (p->cursor_p
1429 ? (p->overlay_p ? face->background
1430 : f->output_data.x->cursor_pixel)
1431 : face->foreground));
1432 XSetBackground (display, gc, face->background);
1433 x_cr_draw_image (f, gc, fringe_bmp[p->which], 0, p->dh,
1434 p->wd, p->h, p->x, p->y, p->overlay_p);
1435 XSetForeground (display, gc, gcv.foreground);
1436 XSetBackground (display, gc, gcv.background);
1438 #else /* not USE_CAIRO */
1439 if (p->which)
1441 Drawable drawable = FRAME_X_DRAWABLE (f);
1442 char *bits;
1443 Pixmap pixmap, clipmask = (Pixmap) 0;
1444 int depth = DefaultDepthOfScreen (FRAME_X_SCREEN (f));
1445 XGCValues gcv;
1447 if (p->wd > 8)
1448 bits = (char *) (p->bits + p->dh);
1449 else
1450 bits = (char *) p->bits + p->dh;
1452 /* Draw the bitmap. I believe these small pixmaps can be cached
1453 by the server. */
1454 pixmap = XCreatePixmapFromBitmapData (display, drawable, bits, p->wd, p->h,
1455 (p->cursor_p
1456 ? (p->overlay_p ? face->background
1457 : f->output_data.x->cursor_pixel)
1458 : face->foreground),
1459 face->background, depth);
1461 if (p->overlay_p)
1463 clipmask = XCreatePixmapFromBitmapData (display,
1464 FRAME_DISPLAY_INFO (f)->root_window,
1465 bits, p->wd, p->h,
1466 1, 0, 1);
1467 gcv.clip_mask = clipmask;
1468 gcv.clip_x_origin = p->x;
1469 gcv.clip_y_origin = p->y;
1470 XChangeGC (display, gc, GCClipMask | GCClipXOrigin | GCClipYOrigin, &gcv);
1473 XCopyArea (display, pixmap, drawable, gc, 0, 0,
1474 p->wd, p->h, p->x, p->y);
1475 XFreePixmap (display, pixmap);
1477 if (p->overlay_p)
1479 gcv.clip_mask = (Pixmap) 0;
1480 XChangeGC (display, gc, GCClipMask, &gcv);
1481 XFreePixmap (display, clipmask);
1484 #endif /* not USE_CAIRO */
1486 x_reset_clip_rectangles (f, gc);
1489 /***********************************************************************
1490 Glyph display
1491 ***********************************************************************/
1495 static void x_set_glyph_string_clipping (struct glyph_string *);
1496 static void x_set_glyph_string_gc (struct glyph_string *);
1497 static void x_draw_glyph_string_foreground (struct glyph_string *);
1498 static void x_draw_composite_glyph_string_foreground (struct glyph_string *);
1499 static void x_draw_glyph_string_box (struct glyph_string *);
1500 static void x_draw_glyph_string (struct glyph_string *);
1501 static _Noreturn void x_delete_glyphs (struct frame *, int);
1502 static void x_compute_glyph_string_overhangs (struct glyph_string *);
1503 static void x_set_cursor_gc (struct glyph_string *);
1504 static void x_set_mode_line_face_gc (struct glyph_string *);
1505 static void x_set_mouse_face_gc (struct glyph_string *);
1506 static bool x_alloc_lighter_color (struct frame *, Display *, Colormap,
1507 unsigned long *, double, int);
1508 static void x_setup_relief_color (struct frame *, struct relief *,
1509 double, int, unsigned long);
1510 static void x_setup_relief_colors (struct glyph_string *);
1511 static void x_draw_image_glyph_string (struct glyph_string *);
1512 static void x_draw_image_relief (struct glyph_string *);
1513 static void x_draw_image_foreground (struct glyph_string *);
1514 static void x_draw_image_foreground_1 (struct glyph_string *, Pixmap);
1515 static void x_clear_glyph_string_rect (struct glyph_string *, int,
1516 int, int, int);
1517 static void x_draw_relief_rect (struct frame *, int, int, int, int,
1518 int, bool, bool, bool, bool, bool,
1519 XRectangle *);
1520 static void x_draw_box_rect (struct glyph_string *, int, int, int, int,
1521 int, bool, bool, XRectangle *);
1522 static void x_scroll_bar_clear (struct frame *);
1524 #ifdef GLYPH_DEBUG
1525 static void x_check_font (struct frame *, struct font *);
1526 #endif
1529 /* Set S->gc to a suitable GC for drawing glyph string S in cursor
1530 face. */
1532 static void
1533 x_set_cursor_gc (struct glyph_string *s)
1535 if (s->font == FRAME_FONT (s->f)
1536 && s->face->background == FRAME_BACKGROUND_PIXEL (s->f)
1537 && s->face->foreground == FRAME_FOREGROUND_PIXEL (s->f)
1538 && !s->cmp)
1539 s->gc = s->f->output_data.x->cursor_gc;
1540 else
1542 /* Cursor on non-default face: must merge. */
1543 XGCValues xgcv;
1544 unsigned long mask;
1546 xgcv.background = s->f->output_data.x->cursor_pixel;
1547 xgcv.foreground = s->face->background;
1549 /* If the glyph would be invisible, try a different foreground. */
1550 if (xgcv.foreground == xgcv.background)
1551 xgcv.foreground = s->face->foreground;
1552 if (xgcv.foreground == xgcv.background)
1553 xgcv.foreground = s->f->output_data.x->cursor_foreground_pixel;
1554 if (xgcv.foreground == xgcv.background)
1555 xgcv.foreground = s->face->foreground;
1557 /* Make sure the cursor is distinct from text in this face. */
1558 if (xgcv.background == s->face->background
1559 && xgcv.foreground == s->face->foreground)
1561 xgcv.background = s->face->foreground;
1562 xgcv.foreground = s->face->background;
1565 IF_DEBUG (x_check_font (s->f, s->font));
1566 xgcv.graphics_exposures = False;
1567 mask = GCForeground | GCBackground | GCGraphicsExposures;
1569 if (FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc)
1570 XChangeGC (s->display, FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc,
1571 mask, &xgcv);
1572 else
1573 FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc
1574 = XCreateGC (s->display, FRAME_X_DRAWABLE (s->f), mask, &xgcv);
1576 s->gc = FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc;
1581 /* Set up S->gc of glyph string S for drawing text in mouse face. */
1583 static void
1584 x_set_mouse_face_gc (struct glyph_string *s)
1586 int face_id;
1587 struct face *face;
1589 /* What face has to be used last for the mouse face? */
1590 face_id = MOUSE_HL_INFO (s->f)->mouse_face_face_id;
1591 face = FACE_FROM_ID_OR_NULL (s->f, face_id);
1592 if (face == NULL)
1593 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
1595 if (s->first_glyph->type == CHAR_GLYPH)
1596 face_id = FACE_FOR_CHAR (s->f, face, s->first_glyph->u.ch, -1, Qnil);
1597 else
1598 face_id = FACE_FOR_CHAR (s->f, face, 0, -1, Qnil);
1599 s->face = FACE_FROM_ID (s->f, face_id);
1600 prepare_face_for_display (s->f, s->face);
1602 if (s->font == s->face->font)
1603 s->gc = s->face->gc;
1604 else
1606 /* Otherwise construct scratch_cursor_gc with values from FACE
1607 except for FONT. */
1608 XGCValues xgcv;
1609 unsigned long mask;
1611 xgcv.background = s->face->background;
1612 xgcv.foreground = s->face->foreground;
1613 xgcv.graphics_exposures = False;
1614 mask = GCForeground | GCBackground | GCGraphicsExposures;
1616 if (FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc)
1617 XChangeGC (s->display, FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc,
1618 mask, &xgcv);
1619 else
1620 FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc
1621 = XCreateGC (s->display, FRAME_X_DRAWABLE (s->f), mask, &xgcv);
1623 s->gc = FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc;
1626 eassert (s->gc != 0);
1630 /* Set S->gc of glyph string S to a GC suitable for drawing a mode line.
1631 Faces to use in the mode line have already been computed when the
1632 matrix was built, so there isn't much to do, here. */
1634 static void
1635 x_set_mode_line_face_gc (struct glyph_string *s)
1637 s->gc = s->face->gc;
1641 /* Set S->gc of glyph string S for drawing that glyph string. Set
1642 S->stippled_p to a non-zero value if the face of S has a stipple
1643 pattern. */
1645 static void
1646 x_set_glyph_string_gc (struct glyph_string *s)
1648 prepare_face_for_display (s->f, s->face);
1650 if (s->hl == DRAW_NORMAL_TEXT)
1652 s->gc = s->face->gc;
1653 s->stippled_p = s->face->stipple != 0;
1655 else if (s->hl == DRAW_INVERSE_VIDEO)
1657 x_set_mode_line_face_gc (s);
1658 s->stippled_p = s->face->stipple != 0;
1660 else if (s->hl == DRAW_CURSOR)
1662 x_set_cursor_gc (s);
1663 s->stippled_p = false;
1665 else if (s->hl == DRAW_MOUSE_FACE)
1667 x_set_mouse_face_gc (s);
1668 s->stippled_p = s->face->stipple != 0;
1670 else if (s->hl == DRAW_IMAGE_RAISED
1671 || s->hl == DRAW_IMAGE_SUNKEN)
1673 s->gc = s->face->gc;
1674 s->stippled_p = s->face->stipple != 0;
1676 else
1677 emacs_abort ();
1679 /* GC must have been set. */
1680 eassert (s->gc != 0);
1684 /* Set clipping for output of glyph string S. S may be part of a mode
1685 line or menu if we don't have X toolkit support. */
1687 static void
1688 x_set_glyph_string_clipping (struct glyph_string *s)
1690 XRectangle *r = s->clip;
1691 int n = get_glyph_string_clip_rects (s, r, 2);
1693 if (n > 0)
1694 x_set_clip_rectangles (s->f, s->gc, r, n);
1695 s->num_clips = n;
1699 /* Set SRC's clipping for output of glyph string DST. This is called
1700 when we are drawing DST's left_overhang or right_overhang only in
1701 the area of SRC. */
1703 static void
1704 x_set_glyph_string_clipping_exactly (struct glyph_string *src, struct glyph_string *dst)
1706 XRectangle r;
1708 r.x = src->x;
1709 r.width = src->width;
1710 r.y = src->y;
1711 r.height = src->height;
1712 dst->clip[0] = r;
1713 dst->num_clips = 1;
1714 x_set_clip_rectangles (dst->f, dst->gc, &r, 1);
1718 /* RIF:
1719 Compute left and right overhang of glyph string S. */
1721 static void
1722 x_compute_glyph_string_overhangs (struct glyph_string *s)
1724 if (s->cmp == NULL
1725 && (s->first_glyph->type == CHAR_GLYPH
1726 || s->first_glyph->type == COMPOSITE_GLYPH))
1728 struct font_metrics metrics;
1730 if (s->first_glyph->type == CHAR_GLYPH)
1732 unsigned *code = alloca (sizeof (unsigned) * s->nchars);
1733 struct font *font = s->font;
1734 int i;
1736 for (i = 0; i < s->nchars; i++)
1737 code[i] = (s->char2b[i].byte1 << 8) | s->char2b[i].byte2;
1738 font->driver->text_extents (font, code, s->nchars, &metrics);
1740 else
1742 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1744 composition_gstring_width (gstring, s->cmp_from, s->cmp_to, &metrics);
1746 s->right_overhang = (metrics.rbearing > metrics.width
1747 ? metrics.rbearing - metrics.width : 0);
1748 s->left_overhang = metrics.lbearing < 0 ? - metrics.lbearing : 0;
1750 else if (s->cmp)
1752 s->right_overhang = s->cmp->rbearing - s->cmp->pixel_width;
1753 s->left_overhang = - s->cmp->lbearing;
1758 /* Fill rectangle X, Y, W, H with background color of glyph string S. */
1760 static void
1761 x_clear_glyph_string_rect (struct glyph_string *s, int x, int y, int w, int h)
1763 XGCValues xgcv;
1764 XGetGCValues (s->display, s->gc, GCForeground | GCBackground, &xgcv);
1765 XSetForeground (s->display, s->gc, xgcv.background);
1766 x_fill_rectangle (s->f, s->gc, x, y, w, h);
1767 XSetForeground (s->display, s->gc, xgcv.foreground);
1771 /* Draw the background of glyph_string S. If S->background_filled_p
1772 is non-zero don't draw it. FORCE_P non-zero means draw the
1773 background even if it wouldn't be drawn normally. This is used
1774 when a string preceding S draws into the background of S, or S
1775 contains the first component of a composition. */
1777 static void
1778 x_draw_glyph_string_background (struct glyph_string *s, bool force_p)
1780 /* Nothing to do if background has already been drawn or if it
1781 shouldn't be drawn in the first place. */
1782 if (!s->background_filled_p)
1784 int box_line_width = max (s->face->box_line_width, 0);
1786 if (s->stippled_p)
1788 /* Fill background with a stipple pattern. */
1789 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
1790 x_fill_rectangle (s->f, s->gc, s->x,
1791 s->y + box_line_width,
1792 s->background_width,
1793 s->height - 2 * box_line_width);
1794 XSetFillStyle (s->display, s->gc, FillSolid);
1795 s->background_filled_p = true;
1797 else if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
1798 /* When xdisp.c ignores FONT_HEIGHT, we cannot trust
1799 font dimensions, since the actual glyphs might be
1800 much smaller. So in that case we always clear the
1801 rectangle with background color. */
1802 || FONT_TOO_HIGH (s->font)
1803 || s->font_not_found_p
1804 || s->extends_to_end_of_line_p
1805 || force_p)
1807 x_clear_glyph_string_rect (s, s->x, s->y + box_line_width,
1808 s->background_width,
1809 s->height - 2 * box_line_width);
1810 s->background_filled_p = true;
1816 /* Draw the foreground of glyph string S. */
1818 static void
1819 x_draw_glyph_string_foreground (struct glyph_string *s)
1821 int i, x;
1823 /* If first glyph of S has a left box line, start drawing the text
1824 of S to the right of that box line. */
1825 if (s->face->box != FACE_NO_BOX
1826 && s->first_glyph->left_box_line_p)
1827 x = s->x + eabs (s->face->box_line_width);
1828 else
1829 x = s->x;
1831 /* Draw characters of S as rectangles if S's font could not be
1832 loaded. */
1833 if (s->font_not_found_p)
1835 for (i = 0; i < s->nchars; ++i)
1837 struct glyph *g = s->first_glyph + i;
1838 x_draw_rectangle (s->f,
1839 s->gc, x, s->y, g->pixel_width - 1,
1840 s->height - 1);
1841 x += g->pixel_width;
1844 else
1846 struct font *font = s->font;
1847 int boff = font->baseline_offset;
1848 int y;
1850 if (font->vertical_centering)
1851 boff = VCENTER_BASELINE_OFFSET (font, s->f) - boff;
1853 y = s->ybase - boff;
1854 if (s->for_overlaps
1855 || (s->background_filled_p && s->hl != DRAW_CURSOR))
1856 font->driver->draw (s, 0, s->nchars, x, y, false);
1857 else
1858 font->driver->draw (s, 0, s->nchars, x, y, true);
1859 if (s->face->overstrike)
1860 font->driver->draw (s, 0, s->nchars, x + 1, y, false);
1864 /* Draw the foreground of composite glyph string S. */
1866 static void
1867 x_draw_composite_glyph_string_foreground (struct glyph_string *s)
1869 int i, j, x;
1870 struct font *font = s->font;
1872 /* If first glyph of S has a left box line, start drawing the text
1873 of S to the right of that box line. */
1874 if (s->face && s->face->box != FACE_NO_BOX
1875 && s->first_glyph->left_box_line_p)
1876 x = s->x + eabs (s->face->box_line_width);
1877 else
1878 x = s->x;
1880 /* S is a glyph string for a composition. S->cmp_from is the index
1881 of the first character drawn for glyphs of this composition.
1882 S->cmp_from == 0 means we are drawing the very first character of
1883 this composition. */
1885 /* Draw a rectangle for the composition if the font for the very
1886 first character of the composition could not be loaded. */
1887 if (s->font_not_found_p)
1889 if (s->cmp_from == 0)
1890 x_draw_rectangle (s->f, s->gc, x, s->y,
1891 s->width - 1, s->height - 1);
1893 else if (! s->first_glyph->u.cmp.automatic)
1895 int y = s->ybase;
1897 for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
1898 /* TAB in a composition means display glyphs with padding
1899 space on the left or right. */
1900 if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
1902 int xx = x + s->cmp->offsets[j * 2];
1903 int yy = y - s->cmp->offsets[j * 2 + 1];
1905 font->driver->draw (s, j, j + 1, xx, yy, false);
1906 if (s->face->overstrike)
1907 font->driver->draw (s, j, j + 1, xx + 1, yy, false);
1910 else
1912 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1913 Lisp_Object glyph;
1914 int y = s->ybase;
1915 int width = 0;
1917 for (i = j = s->cmp_from; i < s->cmp_to; i++)
1919 glyph = LGSTRING_GLYPH (gstring, i);
1920 if (NILP (LGLYPH_ADJUSTMENT (glyph)))
1921 width += LGLYPH_WIDTH (glyph);
1922 else
1924 int xoff, yoff, wadjust;
1926 if (j < i)
1928 font->driver->draw (s, j, i, x, y, false);
1929 if (s->face->overstrike)
1930 font->driver->draw (s, j, i, x + 1, y, false);
1931 x += width;
1933 xoff = LGLYPH_XOFF (glyph);
1934 yoff = LGLYPH_YOFF (glyph);
1935 wadjust = LGLYPH_WADJUST (glyph);
1936 font->driver->draw (s, i, i + 1, x + xoff, y + yoff, false);
1937 if (s->face->overstrike)
1938 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff,
1939 false);
1940 x += wadjust;
1941 j = i + 1;
1942 width = 0;
1945 if (j < i)
1947 font->driver->draw (s, j, i, x, y, false);
1948 if (s->face->overstrike)
1949 font->driver->draw (s, j, i, x + 1, y, false);
1955 /* Draw the foreground of glyph string S for glyphless characters. */
1957 static void
1958 x_draw_glyphless_glyph_string_foreground (struct glyph_string *s)
1960 struct glyph *glyph = s->first_glyph;
1961 XChar2b char2b[8];
1962 int x, i, j;
1964 /* If first glyph of S has a left box line, start drawing the text
1965 of S to the right of that box line. */
1966 if (s->face && s->face->box != FACE_NO_BOX
1967 && s->first_glyph->left_box_line_p)
1968 x = s->x + eabs (s->face->box_line_width);
1969 else
1970 x = s->x;
1972 s->char2b = char2b;
1974 for (i = 0; i < s->nchars; i++, glyph++)
1976 char buf[7], *str = NULL;
1977 int len = glyph->u.glyphless.len;
1979 if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_ACRONYM)
1981 if (len > 0
1982 && CHAR_TABLE_P (Vglyphless_char_display)
1983 && (CHAR_TABLE_EXTRA_SLOTS (XCHAR_TABLE (Vglyphless_char_display))
1984 >= 1))
1986 Lisp_Object acronym
1987 = (! glyph->u.glyphless.for_no_font
1988 ? CHAR_TABLE_REF (Vglyphless_char_display,
1989 glyph->u.glyphless.ch)
1990 : XCHAR_TABLE (Vglyphless_char_display)->extras[0]);
1991 if (STRINGP (acronym))
1992 str = SSDATA (acronym);
1995 else if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_HEX_CODE)
1997 unsigned int ch = glyph->u.glyphless.ch;
1998 eassume (ch <= MAX_CHAR);
1999 sprintf (buf, "%0*X", ch < 0x10000 ? 4 : 6, ch);
2000 str = buf;
2003 if (str)
2005 int upper_len = (len + 1) / 2;
2006 unsigned code;
2008 /* It is assured that all LEN characters in STR is ASCII. */
2009 for (j = 0; j < len; j++)
2011 code = s->font->driver->encode_char (s->font, str[j]);
2012 STORE_XCHAR2B (char2b + j, code >> 8, code & 0xFF);
2014 s->font->driver->draw (s, 0, upper_len,
2015 x + glyph->slice.glyphless.upper_xoff,
2016 s->ybase + glyph->slice.glyphless.upper_yoff,
2017 false);
2018 s->font->driver->draw (s, upper_len, len,
2019 x + glyph->slice.glyphless.lower_xoff,
2020 s->ybase + glyph->slice.glyphless.lower_yoff,
2021 false);
2023 if (glyph->u.glyphless.method != GLYPHLESS_DISPLAY_THIN_SPACE)
2024 x_draw_rectangle (s->f, s->gc,
2025 x, s->ybase - glyph->ascent,
2026 glyph->pixel_width - 1,
2027 glyph->ascent + glyph->descent - 1);
2028 x += glyph->pixel_width;
2032 #ifdef USE_X_TOOLKIT
2034 #ifdef USE_LUCID
2036 /* Return the frame on which widget WIDGET is used.. Abort if frame
2037 cannot be determined. */
2039 static struct frame *
2040 x_frame_of_widget (Widget widget)
2042 struct x_display_info *dpyinfo;
2043 Lisp_Object tail, frame;
2044 struct frame *f;
2046 dpyinfo = x_display_info_for_display (XtDisplay (widget));
2048 /* Find the top-level shell of the widget. Note that this function
2049 can be called when the widget is not yet realized, so XtWindow
2050 (widget) == 0. That's the reason we can't simply use
2051 x_any_window_to_frame. */
2052 while (!XtIsTopLevelShell (widget))
2053 widget = XtParent (widget);
2055 /* Look for a frame with that top-level widget. Allocate the color
2056 on that frame to get the right gamma correction value. */
2057 FOR_EACH_FRAME (tail, frame)
2059 f = XFRAME (frame);
2060 if (FRAME_X_P (f)
2061 && f->output_data.nothing != 1
2062 && FRAME_DISPLAY_INFO (f) == dpyinfo
2063 && f->output_data.x->widget == widget)
2064 return f;
2066 emacs_abort ();
2069 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
2070 or DELTA. Try a color with RGB values multiplied by FACTOR first.
2071 If this produces the same color as PIXEL, try a color where all RGB
2072 values have DELTA added. Return the allocated color in *PIXEL.
2073 DISPLAY is the X display, CMAP is the colormap to operate on.
2074 Value is true if successful. */
2076 bool
2077 x_alloc_lighter_color_for_widget (Widget widget, Display *display, Colormap cmap,
2078 unsigned long *pixel, double factor, int delta)
2080 struct frame *f = x_frame_of_widget (widget);
2081 return x_alloc_lighter_color (f, display, cmap, pixel, factor, delta);
2084 #endif /* USE_LUCID */
2087 /* Structure specifying which arguments should be passed by Xt to
2088 cvt_string_to_pixel. We want the widget's screen and colormap. */
2090 static XtConvertArgRec cvt_string_to_pixel_args[] =
2092 {XtWidgetBaseOffset, (XtPointer) offsetof (WidgetRec, core.screen),
2093 sizeof (Screen *)},
2094 {XtWidgetBaseOffset, (XtPointer) offsetof (WidgetRec, core.colormap),
2095 sizeof (Colormap)}
2099 /* The address of this variable is returned by
2100 cvt_string_to_pixel. */
2102 static Pixel cvt_string_to_pixel_value;
2105 /* Convert a color name to a pixel color.
2107 DPY is the display we are working on.
2109 ARGS is an array of *NARGS XrmValue structures holding additional
2110 information about the widget for which the conversion takes place.
2111 The contents of this array are determined by the specification
2112 in cvt_string_to_pixel_args.
2114 FROM is a pointer to an XrmValue which points to the color name to
2115 convert. TO is an XrmValue in which to return the pixel color.
2117 CLOSURE_RET is a pointer to user-data, in which we record if
2118 we allocated the color or not.
2120 Value is True if successful, False otherwise. */
2122 static Boolean
2123 cvt_string_to_pixel (Display *dpy, XrmValue *args, Cardinal *nargs,
2124 XrmValue *from, XrmValue *to,
2125 XtPointer *closure_ret)
2127 Screen *screen;
2128 Colormap cmap;
2129 Pixel pixel;
2130 String color_name;
2131 XColor color;
2133 if (*nargs != 2)
2135 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
2136 "wrongParameters", "cvt_string_to_pixel",
2137 "XtToolkitError",
2138 "Screen and colormap args required", NULL, NULL);
2139 return False;
2142 screen = *(Screen **) args[0].addr;
2143 cmap = *(Colormap *) args[1].addr;
2144 color_name = (String) from->addr;
2146 if (strcmp (color_name, XtDefaultBackground) == 0)
2148 *closure_ret = (XtPointer) False;
2149 pixel = WhitePixelOfScreen (screen);
2151 else if (strcmp (color_name, XtDefaultForeground) == 0)
2153 *closure_ret = (XtPointer) False;
2154 pixel = BlackPixelOfScreen (screen);
2156 else if (XParseColor (dpy, cmap, color_name, &color)
2157 && x_alloc_nearest_color_1 (dpy, cmap, &color))
2159 pixel = color.pixel;
2160 *closure_ret = (XtPointer) True;
2162 else
2164 String params[1];
2165 Cardinal nparams = 1;
2167 params[0] = color_name;
2168 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
2169 "badValue", "cvt_string_to_pixel",
2170 "XtToolkitError", "Invalid color '%s'",
2171 params, &nparams);
2172 return False;
2175 if (to->addr != NULL)
2177 if (to->size < sizeof (Pixel))
2179 to->size = sizeof (Pixel);
2180 return False;
2183 *(Pixel *) to->addr = pixel;
2185 else
2187 cvt_string_to_pixel_value = pixel;
2188 to->addr = (XtPointer) &cvt_string_to_pixel_value;
2191 to->size = sizeof (Pixel);
2192 return True;
2196 /* Free a pixel color which was previously allocated via
2197 cvt_string_to_pixel. This is registered as the destructor
2198 for this type of resource via XtSetTypeConverter.
2200 APP is the application context in which we work.
2202 TO is a pointer to an XrmValue holding the color to free.
2203 CLOSURE is the value we stored in CLOSURE_RET for this color
2204 in cvt_string_to_pixel.
2206 ARGS and NARGS are like for cvt_string_to_pixel. */
2208 static void
2209 cvt_pixel_dtor (XtAppContext app, XrmValuePtr to, XtPointer closure, XrmValuePtr args,
2210 Cardinal *nargs)
2212 if (*nargs != 2)
2214 XtAppWarningMsg (app, "wrongParameters", "cvt_pixel_dtor",
2215 "XtToolkitError",
2216 "Screen and colormap arguments required",
2217 NULL, NULL);
2219 else if (closure != NULL)
2221 /* We did allocate the pixel, so free it. */
2222 Screen *screen = *(Screen **) args[0].addr;
2223 Colormap cmap = *(Colormap *) args[1].addr;
2224 x_free_dpy_colors (DisplayOfScreen (screen), screen, cmap,
2225 (Pixel *) to->addr, 1);
2230 #endif /* USE_X_TOOLKIT */
2233 /* Value is an array of XColor structures for the contents of the
2234 color map of display DPY. Set *NCELLS to the size of the array.
2235 Note that this probably shouldn't be called for large color maps,
2236 say a 24-bit TrueColor map. */
2238 static const XColor *
2239 x_color_cells (Display *dpy, int *ncells)
2241 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
2242 eassume (dpyinfo);
2244 if (dpyinfo->color_cells == NULL)
2246 Screen *screen = dpyinfo->screen;
2247 int ncolor_cells = XDisplayCells (dpy, XScreenNumberOfScreen (screen));
2248 int i;
2250 dpyinfo->color_cells = xnmalloc (ncolor_cells,
2251 sizeof *dpyinfo->color_cells);
2252 dpyinfo->ncolor_cells = ncolor_cells;
2254 for (i = 0; i < ncolor_cells; ++i)
2255 dpyinfo->color_cells[i].pixel = i;
2257 XQueryColors (dpy, dpyinfo->cmap,
2258 dpyinfo->color_cells, ncolor_cells);
2261 *ncells = dpyinfo->ncolor_cells;
2262 return dpyinfo->color_cells;
2266 /* On frame F, translate pixel colors to RGB values for the NCOLORS
2267 colors in COLORS. Use cached information, if available. */
2269 void
2270 x_query_colors (struct frame *f, XColor *colors, int ncolors)
2272 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2274 if (dpyinfo->red_bits > 0)
2276 /* For TrueColor displays, we can decompose the RGB value
2277 directly. */
2278 int i;
2279 unsigned int rmult, gmult, bmult;
2280 unsigned int rmask, gmask, bmask;
2282 rmask = (1 << dpyinfo->red_bits) - 1;
2283 gmask = (1 << dpyinfo->green_bits) - 1;
2284 bmask = (1 << dpyinfo->blue_bits) - 1;
2285 /* If we're widening, for example, 8 bits in the pixel value to
2286 16 bits for the separate-color representation, we want to
2287 extrapolate the lower bits based on those bits available --
2288 in other words, we'd like 0xff to become 0xffff instead of
2289 the 0xff00 we'd get by just zero-filling the lower bits.
2291 We generate a 32-bit scaled-up value and shift it, in case
2292 the bit count doesn't divide 16 evenly (e.g., when dealing
2293 with a 3-3-2 bit RGB display), to get more of the lower bits
2294 correct.
2296 Should we cache the multipliers in dpyinfo? Maybe
2297 special-case the 8-8-8 common case? */
2298 rmult = 0xffffffff / rmask;
2299 gmult = 0xffffffff / gmask;
2300 bmult = 0xffffffff / bmask;
2302 for (i = 0; i < ncolors; ++i)
2304 unsigned int r, g, b;
2305 unsigned long pixel = colors[i].pixel;
2307 r = (pixel >> dpyinfo->red_offset) & rmask;
2308 g = (pixel >> dpyinfo->green_offset) & gmask;
2309 b = (pixel >> dpyinfo->blue_offset) & bmask;
2311 colors[i].red = (r * rmult) >> 16;
2312 colors[i].green = (g * gmult) >> 16;
2313 colors[i].blue = (b * bmult) >> 16;
2315 return;
2318 if (dpyinfo->color_cells)
2320 int i;
2321 for (i = 0; i < ncolors; ++i)
2323 unsigned long pixel = colors[i].pixel;
2324 eassert (pixel < dpyinfo->ncolor_cells);
2325 eassert (dpyinfo->color_cells[pixel].pixel == pixel);
2326 colors[i] = dpyinfo->color_cells[pixel];
2328 return;
2331 XQueryColors (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), colors, ncolors);
2335 /* On frame F, translate pixel color to RGB values for the color in
2336 COLOR. Use cached information, if available. */
2338 void
2339 x_query_color (struct frame *f, XColor *color)
2341 x_query_colors (f, color, 1);
2345 /* On frame F, translate the color name to RGB values. Use cached
2346 information, if possible.
2348 Note that there is currently no way to clean old entries out of the
2349 cache. However, it is limited to names in the server's database,
2350 and names we've actually looked up; list-colors-display is probably
2351 the most color-intensive case we're likely to hit. */
2353 Status x_parse_color (struct frame *f, const char *color_name,
2354 XColor *color)
2356 Display *dpy = FRAME_X_DISPLAY (f);
2357 Colormap cmap = FRAME_X_COLORMAP (f);
2358 struct color_name_cache_entry *cache_entry;
2360 if (color_name[0] == '#')
2362 /* The hex form is parsed directly by XParseColor without
2363 talking to the X server. No need for caching. */
2364 return XParseColor (dpy, cmap, color_name, color);
2367 for (cache_entry = FRAME_DISPLAY_INFO (f)->color_names; cache_entry;
2368 cache_entry = cache_entry->next)
2370 if (!xstrcasecmp(cache_entry->name, color_name))
2372 *color = cache_entry->rgb;
2373 return 1;
2377 if (XParseColor (dpy, cmap, color_name, color) == 0)
2378 /* No caching of negative results, currently. */
2379 return 0;
2381 cache_entry = xzalloc (sizeof *cache_entry);
2382 cache_entry->rgb = *color;
2383 cache_entry->name = xstrdup (color_name);
2384 cache_entry->next = FRAME_DISPLAY_INFO (f)->color_names;
2385 FRAME_DISPLAY_INFO (f)->color_names = cache_entry;
2386 return 1;
2390 /* Allocate the color COLOR->pixel on DISPLAY, colormap CMAP. If an
2391 exact match can't be allocated, try the nearest color available.
2392 Value is true if successful. Set *COLOR to the color
2393 allocated. */
2395 static bool
2396 x_alloc_nearest_color_1 (Display *dpy, Colormap cmap, XColor *color)
2398 bool rc;
2400 rc = XAllocColor (dpy, cmap, color) != 0;
2401 if (rc == 0)
2403 /* If we got to this point, the colormap is full, so we're going
2404 to try to get the next closest color. The algorithm used is
2405 a least-squares matching, which is what X uses for closest
2406 color matching with StaticColor visuals. */
2407 int nearest, i;
2408 int max_color_delta = 255;
2409 int max_delta = 3 * max_color_delta;
2410 int nearest_delta = max_delta + 1;
2411 int ncells;
2412 const XColor *cells = x_color_cells (dpy, &ncells);
2414 for (nearest = i = 0; i < ncells; ++i)
2416 int dred = (color->red >> 8) - (cells[i].red >> 8);
2417 int dgreen = (color->green >> 8) - (cells[i].green >> 8);
2418 int dblue = (color->blue >> 8) - (cells[i].blue >> 8);
2419 int delta = dred * dred + dgreen * dgreen + dblue * dblue;
2421 if (delta < nearest_delta)
2423 nearest = i;
2424 nearest_delta = delta;
2428 color->red = cells[nearest].red;
2429 color->green = cells[nearest].green;
2430 color->blue = cells[nearest].blue;
2431 rc = XAllocColor (dpy, cmap, color) != 0;
2433 else
2435 /* If allocation succeeded, and the allocated pixel color is not
2436 equal to a cached pixel color recorded earlier, there was a
2437 change in the colormap, so clear the color cache. */
2438 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
2439 eassume (dpyinfo);
2441 if (dpyinfo->color_cells)
2443 XColor *cached_color = &dpyinfo->color_cells[color->pixel];
2444 if (cached_color->red != color->red
2445 || cached_color->blue != color->blue
2446 || cached_color->green != color->green)
2448 xfree (dpyinfo->color_cells);
2449 dpyinfo->color_cells = NULL;
2450 dpyinfo->ncolor_cells = 0;
2455 #ifdef DEBUG_X_COLORS
2456 if (rc)
2457 register_color (color->pixel);
2458 #endif /* DEBUG_X_COLORS */
2460 return rc;
2464 /* Allocate the color COLOR->pixel on frame F, colormap CMAP, after
2465 gamma correction. If an exact match can't be allocated, try the
2466 nearest color available. Value is true if successful. Set *COLOR
2467 to the color allocated. */
2469 bool
2470 x_alloc_nearest_color (struct frame *f, Colormap cmap, XColor *color)
2472 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2474 gamma_correct (f, color);
2476 if (dpyinfo->red_bits > 0)
2478 color->pixel = x_make_truecolor_pixel (dpyinfo,
2479 color->red,
2480 color->green,
2481 color->blue);
2482 return true;
2485 return x_alloc_nearest_color_1 (FRAME_X_DISPLAY (f), cmap, color);
2489 /* Allocate color PIXEL on frame F. PIXEL must already be allocated.
2490 It's necessary to do this instead of just using PIXEL directly to
2491 get color reference counts right. */
2493 unsigned long
2494 x_copy_color (struct frame *f, unsigned long pixel)
2496 XColor color;
2498 /* If display has an immutable color map, freeing colors is not
2499 necessary and some servers don't allow it. Since we won't free a
2500 color once we've allocated it, we don't need to re-allocate it to
2501 maintain the server's reference count. */
2502 if (!x_mutable_colormap (FRAME_X_VISUAL (f)))
2503 return pixel;
2505 color.pixel = pixel;
2506 block_input ();
2507 /* The color could still be found in the color_cells array. */
2508 x_query_color (f, &color);
2509 XAllocColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &color);
2510 unblock_input ();
2511 #ifdef DEBUG_X_COLORS
2512 register_color (pixel);
2513 #endif
2514 return color.pixel;
2518 /* Brightness beyond which a color won't have its highlight brightness
2519 boosted.
2521 Nominally, highlight colors for `3d' faces are calculated by
2522 brightening an object's color by a constant scale factor, but this
2523 doesn't yield good results for dark colors, so for colors who's
2524 brightness is less than this value (on a scale of 0-65535) have an
2525 use an additional additive factor.
2527 The value here is set so that the default menu-bar/mode-line color
2528 (grey75) will not have its highlights changed at all. */
2529 #define HIGHLIGHT_COLOR_DARK_BOOST_LIMIT 48000
2532 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
2533 or DELTA. Try a color with RGB values multiplied by FACTOR first.
2534 If this produces the same color as PIXEL, try a color where all RGB
2535 values have DELTA added. Return the allocated color in *PIXEL.
2536 DISPLAY is the X display, CMAP is the colormap to operate on.
2537 Value is non-zero if successful. */
2539 static bool
2540 x_alloc_lighter_color (struct frame *f, Display *display, Colormap cmap,
2541 unsigned long *pixel, double factor, int delta)
2543 XColor color, new;
2544 long bright;
2545 bool success_p;
2547 /* Get RGB color values. */
2548 color.pixel = *pixel;
2549 x_query_color (f, &color);
2551 /* Change RGB values by specified FACTOR. Avoid overflow! */
2552 eassert (factor >= 0);
2553 new.red = min (0xffff, factor * color.red);
2554 new.green = min (0xffff, factor * color.green);
2555 new.blue = min (0xffff, factor * color.blue);
2557 /* Calculate brightness of COLOR. */
2558 bright = (2 * color.red + 3 * color.green + color.blue) / 6;
2560 /* We only boost colors that are darker than
2561 HIGHLIGHT_COLOR_DARK_BOOST_LIMIT. */
2562 if (bright < HIGHLIGHT_COLOR_DARK_BOOST_LIMIT)
2563 /* Make an additive adjustment to NEW, because it's dark enough so
2564 that scaling by FACTOR alone isn't enough. */
2566 /* How far below the limit this color is (0 - 1, 1 being darker). */
2567 double dimness = 1 - (double)bright / HIGHLIGHT_COLOR_DARK_BOOST_LIMIT;
2568 /* The additive adjustment. */
2569 int min_delta = delta * dimness * factor / 2;
2571 if (factor < 1)
2573 new.red = max (0, new.red - min_delta);
2574 new.green = max (0, new.green - min_delta);
2575 new.blue = max (0, new.blue - min_delta);
2577 else
2579 new.red = min (0xffff, min_delta + new.red);
2580 new.green = min (0xffff, min_delta + new.green);
2581 new.blue = min (0xffff, min_delta + new.blue);
2585 /* Try to allocate the color. */
2586 success_p = x_alloc_nearest_color (f, cmap, &new);
2587 if (success_p)
2589 if (new.pixel == *pixel)
2591 /* If we end up with the same color as before, try adding
2592 delta to the RGB values. */
2593 x_free_colors (f, &new.pixel, 1);
2595 new.red = min (0xffff, delta + color.red);
2596 new.green = min (0xffff, delta + color.green);
2597 new.blue = min (0xffff, delta + color.blue);
2598 success_p = x_alloc_nearest_color (f, cmap, &new);
2600 else
2601 success_p = true;
2602 *pixel = new.pixel;
2605 return success_p;
2609 /* Set up the foreground color for drawing relief lines of glyph
2610 string S. RELIEF is a pointer to a struct relief containing the GC
2611 with which lines will be drawn. Use a color that is FACTOR or
2612 DELTA lighter or darker than the relief's background which is found
2613 in S->f->output_data.x->relief_background. If such a color cannot
2614 be allocated, use DEFAULT_PIXEL, instead. */
2616 static void
2617 x_setup_relief_color (struct frame *f, struct relief *relief, double factor,
2618 int delta, unsigned long default_pixel)
2620 XGCValues xgcv;
2621 struct x_output *di = f->output_data.x;
2622 unsigned long mask = GCForeground | GCLineWidth | GCGraphicsExposures;
2623 unsigned long pixel;
2624 unsigned long background = di->relief_background;
2625 Colormap cmap = FRAME_X_COLORMAP (f);
2626 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2627 Display *dpy = FRAME_X_DISPLAY (f);
2629 xgcv.graphics_exposures = False;
2630 xgcv.line_width = 1;
2632 /* Free previously allocated color. The color cell will be reused
2633 when it has been freed as many times as it was allocated, so this
2634 doesn't affect faces using the same colors. */
2635 if (relief->gc && relief->pixel != -1)
2637 x_free_colors (f, &relief->pixel, 1);
2638 relief->pixel = -1;
2641 /* Allocate new color. */
2642 xgcv.foreground = default_pixel;
2643 pixel = background;
2644 if (dpyinfo->n_planes != 1
2645 && x_alloc_lighter_color (f, dpy, cmap, &pixel, factor, delta))
2646 xgcv.foreground = relief->pixel = pixel;
2648 if (relief->gc == 0)
2650 xgcv.stipple = dpyinfo->gray;
2651 mask |= GCStipple;
2652 relief->gc = XCreateGC (dpy, FRAME_X_DRAWABLE (f), mask, &xgcv);
2654 else
2655 XChangeGC (dpy, relief->gc, mask, &xgcv);
2659 /* Set up colors for the relief lines around glyph string S. */
2661 static void
2662 x_setup_relief_colors (struct glyph_string *s)
2664 struct x_output *di = s->f->output_data.x;
2665 unsigned long color;
2667 if (s->face->use_box_color_for_shadows_p)
2668 color = s->face->box_color;
2669 else if (s->first_glyph->type == IMAGE_GLYPH
2670 && s->img->pixmap
2671 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2672 color = IMAGE_BACKGROUND (s->img, s->f, 0);
2673 else
2675 XGCValues xgcv;
2677 /* Get the background color of the face. */
2678 XGetGCValues (s->display, s->gc, GCBackground, &xgcv);
2679 color = xgcv.background;
2682 if (di->white_relief.gc == 0
2683 || color != di->relief_background)
2685 di->relief_background = color;
2686 x_setup_relief_color (s->f, &di->white_relief, 1.2, 0x8000,
2687 WHITE_PIX_DEFAULT (s->f));
2688 x_setup_relief_color (s->f, &di->black_relief, 0.6, 0x4000,
2689 BLACK_PIX_DEFAULT (s->f));
2694 /* Draw a relief on frame F inside the rectangle given by LEFT_X,
2695 TOP_Y, RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the relief
2696 to draw, it must be >= 0. RAISED_P means draw a raised
2697 relief. LEFT_P means draw a relief on the left side of
2698 the rectangle. RIGHT_P means draw a relief on the right
2699 side of the rectangle. CLIP_RECT is the clipping rectangle to use
2700 when drawing. */
2702 static void
2703 x_draw_relief_rect (struct frame *f,
2704 int left_x, int top_y, int right_x, int bottom_y,
2705 int width, bool raised_p, bool top_p, bool bot_p,
2706 bool left_p, bool right_p,
2707 XRectangle *clip_rect)
2709 #ifdef USE_CAIRO
2710 GC top_left_gc, bottom_right_gc;
2711 int corners = 0;
2713 if (raised_p)
2715 top_left_gc = f->output_data.x->white_relief.gc;
2716 bottom_right_gc = f->output_data.x->black_relief.gc;
2718 else
2720 top_left_gc = f->output_data.x->black_relief.gc;
2721 bottom_right_gc = f->output_data.x->white_relief.gc;
2724 x_set_clip_rectangles (f, top_left_gc, clip_rect, 1);
2725 x_set_clip_rectangles (f, bottom_right_gc, clip_rect, 1);
2727 if (left_p)
2729 x_fill_rectangle (f, top_left_gc, left_x, top_y,
2730 width, bottom_y + 1 - top_y);
2731 if (top_p)
2732 corners |= 1 << CORNER_TOP_LEFT;
2733 if (bot_p)
2734 corners |= 1 << CORNER_BOTTOM_LEFT;
2736 if (right_p)
2738 x_fill_rectangle (f, bottom_right_gc, right_x + 1 - width, top_y,
2739 width, bottom_y + 1 - top_y);
2740 if (top_p)
2741 corners |= 1 << CORNER_TOP_RIGHT;
2742 if (bot_p)
2743 corners |= 1 << CORNER_BOTTOM_RIGHT;
2745 if (top_p)
2747 if (!right_p)
2748 x_fill_rectangle (f, top_left_gc, left_x, top_y,
2749 right_x + 1 - left_x, width);
2750 else
2751 x_fill_trapezoid_for_relief (f, top_left_gc, left_x, top_y,
2752 right_x + 1 - left_x, width, 1);
2754 if (bot_p)
2756 if (!left_p)
2757 x_fill_rectangle (f, bottom_right_gc, left_x, bottom_y + 1 - width,
2758 right_x + 1 - left_x, width);
2759 else
2760 x_fill_trapezoid_for_relief (f, bottom_right_gc,
2761 left_x, bottom_y + 1 - width,
2762 right_x + 1 - left_x, width, 0);
2764 if (left_p && width != 1)
2765 x_fill_rectangle (f, bottom_right_gc, left_x, top_y,
2766 1, bottom_y + 1 - top_y);
2767 if (top_p && width != 1)
2768 x_fill_rectangle (f, bottom_right_gc, left_x, top_y,
2769 right_x + 1 - left_x, 1);
2770 if (corners)
2772 XSetBackground (FRAME_X_DISPLAY (f), top_left_gc,
2773 FRAME_BACKGROUND_PIXEL (f));
2774 x_erase_corners_for_relief (f, top_left_gc, left_x, top_y,
2775 right_x - left_x + 1, bottom_y - top_y + 1,
2776 6, 1, corners);
2779 x_reset_clip_rectangles (f, top_left_gc);
2780 x_reset_clip_rectangles (f, bottom_right_gc);
2781 #else
2782 Display *dpy = FRAME_X_DISPLAY (f);
2783 Drawable drawable = FRAME_X_DRAWABLE (f);
2784 int i;
2785 GC gc;
2787 if (raised_p)
2788 gc = f->output_data.x->white_relief.gc;
2789 else
2790 gc = f->output_data.x->black_relief.gc;
2791 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
2793 /* This code is more complicated than it has to be, because of two
2794 minor hacks to make the boxes look nicer: (i) if width > 1, draw
2795 the outermost line using the black relief. (ii) Omit the four
2796 corner pixels. */
2798 /* Top. */
2799 if (top_p)
2801 if (width == 1)
2802 XDrawLine (dpy, drawable, gc,
2803 left_x + left_p, top_y,
2804 right_x + !right_p, top_y);
2806 for (i = 1; i < width; ++i)
2807 XDrawLine (dpy, drawable, gc,
2808 left_x + i * left_p, top_y + i,
2809 right_x + 1 - i * right_p, top_y + i);
2812 /* Left. */
2813 if (left_p)
2815 if (width == 1)
2816 XDrawLine (dpy, drawable, gc, left_x, top_y + 1, left_x, bottom_y);
2818 x_clear_area(f, left_x, top_y, 1, 1);
2819 x_clear_area(f, left_x, bottom_y, 1, 1);
2821 for (i = (width > 1 ? 1 : 0); i < width; ++i)
2822 XDrawLine (dpy, drawable, gc,
2823 left_x + i, top_y + (i + 1) * top_p,
2824 left_x + i, bottom_y + 1 - (i + 1) * bot_p);
2827 XSetClipMask (dpy, gc, None);
2828 if (raised_p)
2829 gc = f->output_data.x->black_relief.gc;
2830 else
2831 gc = f->output_data.x->white_relief.gc;
2832 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
2834 if (width > 1)
2836 /* Outermost top line. */
2837 if (top_p)
2838 XDrawLine (dpy, drawable, gc,
2839 left_x + left_p, top_y,
2840 right_x + !right_p, top_y);
2842 /* Outermost left line. */
2843 if (left_p)
2844 XDrawLine (dpy, drawable, gc, left_x, top_y + 1, left_x, bottom_y);
2847 /* Bottom. */
2848 if (bot_p)
2850 XDrawLine (dpy, drawable, gc,
2851 left_x + left_p, bottom_y,
2852 right_x + !right_p, bottom_y);
2853 for (i = 1; i < width; ++i)
2854 XDrawLine (dpy, drawable, gc,
2855 left_x + i * left_p, bottom_y - i,
2856 right_x + 1 - i * right_p, bottom_y - i);
2859 /* Right. */
2860 if (right_p)
2862 x_clear_area(f, right_x, top_y, 1, 1);
2863 x_clear_area(f, right_x, bottom_y, 1, 1);
2864 for (i = 0; i < width; ++i)
2865 XDrawLine (dpy, drawable, gc,
2866 right_x - i, top_y + (i + 1) * top_p,
2867 right_x - i, bottom_y + 1 - (i + 1) * bot_p);
2870 x_reset_clip_rectangles (f, gc);
2872 #endif
2876 /* Draw a box on frame F inside the rectangle given by LEFT_X, TOP_Y,
2877 RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the lines to
2878 draw, it must be >= 0. LEFT_P means draw a line on the
2879 left side of the rectangle. RIGHT_P means draw a line
2880 on the right side of the rectangle. CLIP_RECT is the clipping
2881 rectangle to use when drawing. */
2883 static void
2884 x_draw_box_rect (struct glyph_string *s,
2885 int left_x, int top_y, int right_x, int bottom_y, int width,
2886 bool left_p, bool right_p, XRectangle *clip_rect)
2888 XGCValues xgcv;
2890 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2891 XSetForeground (s->display, s->gc, s->face->box_color);
2892 x_set_clip_rectangles (s->f, s->gc, clip_rect, 1);
2894 /* Top. */
2895 x_fill_rectangle (s->f, s->gc,
2896 left_x, top_y, right_x - left_x + 1, width);
2898 /* Left. */
2899 if (left_p)
2900 x_fill_rectangle (s->f, s->gc,
2901 left_x, top_y, width, bottom_y - top_y + 1);
2903 /* Bottom. */
2904 x_fill_rectangle (s->f, s->gc,
2905 left_x, bottom_y - width + 1, right_x - left_x + 1, width);
2907 /* Right. */
2908 if (right_p)
2909 x_fill_rectangle (s->f, s->gc,
2910 right_x - width + 1, top_y, width, bottom_y - top_y + 1);
2912 XSetForeground (s->display, s->gc, xgcv.foreground);
2913 x_reset_clip_rectangles (s->f, s->gc);
2917 /* Draw a box around glyph string S. */
2919 static void
2920 x_draw_glyph_string_box (struct glyph_string *s)
2922 int width, left_x, right_x, top_y, bottom_y, last_x;
2923 bool raised_p, left_p, right_p;
2924 struct glyph *last_glyph;
2925 XRectangle clip_rect;
2927 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2928 ? WINDOW_RIGHT_EDGE_X (s->w)
2929 : window_box_right (s->w, s->area));
2931 /* The glyph that may have a right box line. */
2932 last_glyph = (s->cmp || s->img
2933 ? s->first_glyph
2934 : s->first_glyph + s->nchars - 1);
2936 width = eabs (s->face->box_line_width);
2937 raised_p = s->face->box == FACE_RAISED_BOX;
2938 left_x = s->x;
2939 right_x = (s->row->full_width_p && s->extends_to_end_of_line_p
2940 ? last_x - 1
2941 : min (last_x, s->x + s->background_width) - 1);
2942 top_y = s->y;
2943 bottom_y = top_y + s->height - 1;
2945 left_p = (s->first_glyph->left_box_line_p
2946 || (s->hl == DRAW_MOUSE_FACE
2947 && (s->prev == NULL
2948 || s->prev->hl != s->hl)));
2949 right_p = (last_glyph->right_box_line_p
2950 || (s->hl == DRAW_MOUSE_FACE
2951 && (s->next == NULL
2952 || s->next->hl != s->hl)));
2954 get_glyph_string_clip_rect (s, &clip_rect);
2956 if (s->face->box == FACE_SIMPLE_BOX)
2957 x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
2958 left_p, right_p, &clip_rect);
2959 else
2961 x_setup_relief_colors (s);
2962 x_draw_relief_rect (s->f, left_x, top_y, right_x, bottom_y,
2963 width, raised_p, true, true, left_p, right_p,
2964 &clip_rect);
2969 /* Draw foreground of image glyph string S. */
2971 static void
2972 x_draw_image_foreground (struct glyph_string *s)
2974 int x = s->x;
2975 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2977 /* If first glyph of S has a left box line, start drawing it to the
2978 right of that line. */
2979 if (s->face->box != FACE_NO_BOX
2980 && s->first_glyph->left_box_line_p
2981 && s->slice.x == 0)
2982 x += eabs (s->face->box_line_width);
2984 /* If there is a margin around the image, adjust x- and y-position
2985 by that margin. */
2986 if (s->slice.x == 0)
2987 x += s->img->hmargin;
2988 if (s->slice.y == 0)
2989 y += s->img->vmargin;
2991 if (s->img->pixmap)
2993 if (s->img->mask)
2995 /* We can't set both a clip mask and use XSetClipRectangles
2996 because the latter also sets a clip mask. We also can't
2997 trust on the shape extension to be available
2998 (XShapeCombineRegion). So, compute the rectangle to draw
2999 manually. */
3000 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
3001 | GCFunction);
3002 XGCValues xgcv;
3003 XRectangle clip_rect, image_rect, r;
3005 xgcv.clip_mask = s->img->mask;
3006 xgcv.clip_x_origin = x;
3007 xgcv.clip_y_origin = y;
3008 xgcv.function = GXcopy;
3009 XChangeGC (s->display, s->gc, mask, &xgcv);
3011 get_glyph_string_clip_rect (s, &clip_rect);
3012 image_rect.x = x;
3013 image_rect.y = y;
3014 image_rect.width = s->slice.width;
3015 image_rect.height = s->slice.height;
3016 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
3017 XCopyArea (s->display, s->img->pixmap,
3018 FRAME_X_DRAWABLE (s->f), s->gc,
3019 s->slice.x + r.x - x, s->slice.y + r.y - y,
3020 r.width, r.height, r.x, r.y);
3022 else
3024 XRectangle clip_rect, image_rect, r;
3026 get_glyph_string_clip_rect (s, &clip_rect);
3027 image_rect.x = x;
3028 image_rect.y = y;
3029 image_rect.width = s->slice.width;
3030 image_rect.height = s->slice.height;
3031 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
3032 XCopyArea (s->display, s->img->pixmap,
3033 FRAME_X_DRAWABLE (s->f), s->gc,
3034 s->slice.x + r.x - x, s->slice.y + r.y - y,
3035 r.width, r.height, r.x, r.y);
3037 /* When the image has a mask, we can expect that at
3038 least part of a mouse highlight or a block cursor will
3039 be visible. If the image doesn't have a mask, make
3040 a block cursor visible by drawing a rectangle around
3041 the image. I believe it's looking better if we do
3042 nothing here for mouse-face. */
3043 if (s->hl == DRAW_CURSOR)
3045 int relief = eabs (s->img->relief);
3046 x_draw_rectangle (s->f, s->gc,
3047 x - relief, y - relief,
3048 s->slice.width + relief*2 - 1,
3049 s->slice.height + relief*2 - 1);
3053 else
3054 /* Draw a rectangle if image could not be loaded. */
3055 x_draw_rectangle (s->f, s->gc, x, y,
3056 s->slice.width - 1, s->slice.height - 1);
3060 /* Draw a relief around the image glyph string S. */
3062 static void
3063 x_draw_image_relief (struct glyph_string *s)
3065 int x1, y1, thick;
3066 bool raised_p, top_p, bot_p, left_p, right_p;
3067 int extra_x, extra_y;
3068 XRectangle r;
3069 int x = s->x;
3070 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
3072 /* If first glyph of S has a left box line, start drawing it to the
3073 right of that line. */
3074 if (s->face->box != FACE_NO_BOX
3075 && s->first_glyph->left_box_line_p
3076 && s->slice.x == 0)
3077 x += eabs (s->face->box_line_width);
3079 /* If there is a margin around the image, adjust x- and y-position
3080 by that margin. */
3081 if (s->slice.x == 0)
3082 x += s->img->hmargin;
3083 if (s->slice.y == 0)
3084 y += s->img->vmargin;
3086 if (s->hl == DRAW_IMAGE_SUNKEN
3087 || s->hl == DRAW_IMAGE_RAISED)
3089 thick = tool_bar_button_relief >= 0 ? tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3090 raised_p = s->hl == DRAW_IMAGE_RAISED;
3092 else
3094 thick = eabs (s->img->relief);
3095 raised_p = s->img->relief > 0;
3098 x1 = x + s->slice.width - 1;
3099 y1 = y + s->slice.height - 1;
3101 extra_x = extra_y = 0;
3102 if (s->face->id == TOOL_BAR_FACE_ID)
3104 if (CONSP (Vtool_bar_button_margin)
3105 && INTEGERP (XCAR (Vtool_bar_button_margin))
3106 && INTEGERP (XCDR (Vtool_bar_button_margin)))
3108 extra_x = XINT (XCAR (Vtool_bar_button_margin));
3109 extra_y = XINT (XCDR (Vtool_bar_button_margin));
3111 else if (INTEGERP (Vtool_bar_button_margin))
3112 extra_x = extra_y = XINT (Vtool_bar_button_margin);
3115 top_p = bot_p = left_p = right_p = false;
3117 if (s->slice.x == 0)
3118 x -= thick + extra_x, left_p = true;
3119 if (s->slice.y == 0)
3120 y -= thick + extra_y, top_p = true;
3121 if (s->slice.x + s->slice.width == s->img->width)
3122 x1 += thick + extra_x, right_p = true;
3123 if (s->slice.y + s->slice.height == s->img->height)
3124 y1 += thick + extra_y, bot_p = true;
3126 x_setup_relief_colors (s);
3127 get_glyph_string_clip_rect (s, &r);
3128 x_draw_relief_rect (s->f, x, y, x1, y1, thick, raised_p,
3129 top_p, bot_p, left_p, right_p, &r);
3133 /* Draw the foreground of image glyph string S to PIXMAP. */
3135 static void
3136 x_draw_image_foreground_1 (struct glyph_string *s, Pixmap pixmap)
3138 int x = 0;
3139 int y = s->ybase - s->y - image_ascent (s->img, s->face, &s->slice);
3141 /* If first glyph of S has a left box line, start drawing it to the
3142 right of that line. */
3143 if (s->face->box != FACE_NO_BOX
3144 && s->first_glyph->left_box_line_p
3145 && s->slice.x == 0)
3146 x += eabs (s->face->box_line_width);
3148 /* If there is a margin around the image, adjust x- and y-position
3149 by that margin. */
3150 if (s->slice.x == 0)
3151 x += s->img->hmargin;
3152 if (s->slice.y == 0)
3153 y += s->img->vmargin;
3155 if (s->img->pixmap)
3157 if (s->img->mask)
3159 /* We can't set both a clip mask and use XSetClipRectangles
3160 because the latter also sets a clip mask. We also can't
3161 trust on the shape extension to be available
3162 (XShapeCombineRegion). So, compute the rectangle to draw
3163 manually. */
3164 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
3165 | GCFunction);
3166 XGCValues xgcv;
3168 xgcv.clip_mask = s->img->mask;
3169 xgcv.clip_x_origin = x - s->slice.x;
3170 xgcv.clip_y_origin = y - s->slice.y;
3171 xgcv.function = GXcopy;
3172 XChangeGC (s->display, s->gc, mask, &xgcv);
3174 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
3175 s->slice.x, s->slice.y,
3176 s->slice.width, s->slice.height, x, y);
3177 XSetClipMask (s->display, s->gc, None);
3179 else
3181 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
3182 s->slice.x, s->slice.y,
3183 s->slice.width, s->slice.height, x, y);
3185 /* When the image has a mask, we can expect that at
3186 least part of a mouse highlight or a block cursor will
3187 be visible. If the image doesn't have a mask, make
3188 a block cursor visible by drawing a rectangle around
3189 the image. I believe it's looking better if we do
3190 nothing here for mouse-face. */
3191 if (s->hl == DRAW_CURSOR)
3193 int r = eabs (s->img->relief);
3194 x_draw_rectangle (s->f, s->gc, x - r, y - r,
3195 s->slice.width + r*2 - 1,
3196 s->slice.height + r*2 - 1);
3200 else
3201 /* Draw a rectangle if image could not be loaded. */
3202 x_draw_rectangle (s->f, s->gc, x, y,
3203 s->slice.width - 1, s->slice.height - 1);
3207 /* Draw part of the background of glyph string S. X, Y, W, and H
3208 give the rectangle to draw. */
3210 static void
3211 x_draw_glyph_string_bg_rect (struct glyph_string *s, int x, int y, int w, int h)
3213 if (s->stippled_p)
3215 /* Fill background with a stipple pattern. */
3216 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
3217 x_fill_rectangle (s->f, s->gc, x, y, w, h);
3218 XSetFillStyle (s->display, s->gc, FillSolid);
3220 else
3221 x_clear_glyph_string_rect (s, x, y, w, h);
3225 /* Draw image glyph string S.
3227 s->y
3228 s->x +-------------------------
3229 | s->face->box
3231 | +-------------------------
3232 | | s->img->margin
3234 | | +-------------------
3235 | | | the image
3239 static void
3240 x_draw_image_glyph_string (struct glyph_string *s)
3242 int box_line_hwidth = eabs (s->face->box_line_width);
3243 int box_line_vwidth = max (s->face->box_line_width, 0);
3244 int height;
3245 Pixmap pixmap = None;
3247 height = s->height;
3248 if (s->slice.y == 0)
3249 height -= box_line_vwidth;
3250 if (s->slice.y + s->slice.height >= s->img->height)
3251 height -= box_line_vwidth;
3253 /* Fill background with face under the image. Do it only if row is
3254 taller than image or if image has a clip mask to reduce
3255 flickering. */
3256 s->stippled_p = s->face->stipple != 0;
3257 if (height > s->slice.height
3258 || s->img->hmargin
3259 || s->img->vmargin
3260 || s->img->mask
3261 || s->img->pixmap == 0
3262 || s->width != s->background_width)
3264 if (s->img->mask)
3266 /* Create a pixmap as large as the glyph string. Fill it
3267 with the background color. Copy the image to it, using
3268 its mask. Copy the temporary pixmap to the display. */
3269 Screen *screen = FRAME_X_SCREEN (s->f);
3270 int depth = DefaultDepthOfScreen (screen);
3272 /* Create a pixmap as large as the glyph string. */
3273 pixmap = XCreatePixmap (s->display, FRAME_X_DRAWABLE (s->f),
3274 s->background_width,
3275 s->height, depth);
3277 /* Don't clip in the following because we're working on the
3278 pixmap. */
3279 XSetClipMask (s->display, s->gc, None);
3281 /* Fill the pixmap with the background color/stipple. */
3282 if (s->stippled_p)
3284 /* Fill background with a stipple pattern. */
3285 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
3286 XSetTSOrigin (s->display, s->gc, - s->x, - s->y);
3287 XFillRectangle (s->display, pixmap, s->gc,
3288 0, 0, s->background_width, s->height);
3289 XSetFillStyle (s->display, s->gc, FillSolid);
3290 XSetTSOrigin (s->display, s->gc, 0, 0);
3292 else
3294 XGCValues xgcv;
3295 XGetGCValues (s->display, s->gc, GCForeground | GCBackground,
3296 &xgcv);
3297 XSetForeground (s->display, s->gc, xgcv.background);
3298 XFillRectangle (s->display, pixmap, s->gc,
3299 0, 0, s->background_width, s->height);
3300 XSetForeground (s->display, s->gc, xgcv.foreground);
3303 else
3305 int x = s->x;
3306 int y = s->y;
3307 int width = s->background_width;
3309 if (s->first_glyph->left_box_line_p
3310 && s->slice.x == 0)
3312 x += box_line_hwidth;
3313 width -= box_line_hwidth;
3316 if (s->slice.y == 0)
3317 y += box_line_vwidth;
3319 x_draw_glyph_string_bg_rect (s, x, y, width, height);
3322 s->background_filled_p = true;
3325 /* Draw the foreground. */
3326 #ifdef USE_CAIRO
3327 if (s->img->cr_data)
3329 cairo_t *cr = x_begin_cr_clip (s->f, s->gc);
3331 int x = s->x + s->img->hmargin;
3332 int y = s->y + s->img->vmargin;
3333 int width = s->background_width;
3335 cairo_set_source_surface (cr, s->img->cr_data,
3336 x - s->slice.x,
3337 y - s->slice.y);
3338 cairo_rectangle (cr, x, y, width, height);
3339 cairo_fill (cr);
3340 x_end_cr_clip (s->f);
3342 else
3343 #endif
3344 if (pixmap != None)
3346 x_draw_image_foreground_1 (s, pixmap);
3347 x_set_glyph_string_clipping (s);
3348 XCopyArea (s->display, pixmap, FRAME_X_DRAWABLE (s->f), s->gc,
3349 0, 0, s->background_width, s->height, s->x, s->y);
3350 XFreePixmap (s->display, pixmap);
3352 else
3353 x_draw_image_foreground (s);
3355 /* If we must draw a relief around the image, do it. */
3356 if (s->img->relief
3357 || s->hl == DRAW_IMAGE_RAISED
3358 || s->hl == DRAW_IMAGE_SUNKEN)
3359 x_draw_image_relief (s);
3363 /* Draw stretch glyph string S. */
3365 static void
3366 x_draw_stretch_glyph_string (struct glyph_string *s)
3368 eassert (s->first_glyph->type == STRETCH_GLYPH);
3370 if (s->hl == DRAW_CURSOR
3371 && !x_stretch_cursor_p)
3373 /* If `x-stretch-cursor' is nil, don't draw a block cursor as
3374 wide as the stretch glyph. */
3375 int width, background_width = s->background_width;
3376 int x = s->x;
3378 if (!s->row->reversed_p)
3380 int left_x = window_box_left_offset (s->w, TEXT_AREA);
3382 if (x < left_x)
3384 background_width -= left_x - x;
3385 x = left_x;
3388 else
3390 /* In R2L rows, draw the cursor on the right edge of the
3391 stretch glyph. */
3392 int right_x = window_box_right (s->w, TEXT_AREA);
3394 if (x + background_width > right_x)
3395 background_width -= x - right_x;
3396 x += background_width;
3398 width = min (FRAME_COLUMN_WIDTH (s->f), background_width);
3399 if (s->row->reversed_p)
3400 x -= width;
3402 /* Draw cursor. */
3403 x_draw_glyph_string_bg_rect (s, x, s->y, width, s->height);
3405 /* Clear rest using the GC of the original non-cursor face. */
3406 if (width < background_width)
3408 int y = s->y;
3409 int w = background_width - width, h = s->height;
3410 XRectangle r;
3411 GC gc;
3413 if (!s->row->reversed_p)
3414 x += width;
3415 else
3416 x = s->x;
3417 if (s->row->mouse_face_p
3418 && cursor_in_mouse_face_p (s->w))
3420 x_set_mouse_face_gc (s);
3421 gc = s->gc;
3423 else
3424 gc = s->face->gc;
3426 get_glyph_string_clip_rect (s, &r);
3427 x_set_clip_rectangles (s->f, gc, &r, 1);
3429 if (s->face->stipple)
3431 /* Fill background with a stipple pattern. */
3432 XSetFillStyle (s->display, gc, FillOpaqueStippled);
3433 x_fill_rectangle (s->f, gc, x, y, w, h);
3434 XSetFillStyle (s->display, gc, FillSolid);
3436 else
3438 XGCValues xgcv;
3439 XGetGCValues (s->display, gc, GCForeground | GCBackground, &xgcv);
3440 XSetForeground (s->display, gc, xgcv.background);
3441 x_fill_rectangle (s->f, gc, x, y, w, h);
3442 XSetForeground (s->display, gc, xgcv.foreground);
3445 x_reset_clip_rectangles (s->f, gc);
3448 else if (!s->background_filled_p)
3450 int background_width = s->background_width;
3451 int x = s->x, left_x = window_box_left_offset (s->w, TEXT_AREA);
3453 /* Don't draw into left margin, fringe or scrollbar area
3454 except for header line and mode line. */
3455 if (x < left_x && !s->row->mode_line_p)
3457 background_width -= left_x - x;
3458 x = left_x;
3460 if (background_width > 0)
3461 x_draw_glyph_string_bg_rect (s, x, s->y, background_width, s->height);
3464 s->background_filled_p = true;
3467 static void
3468 x_get_scale_factor(Display *disp, int *scale_x, int *scale_y)
3470 const int base_res = 96;
3471 struct x_display_info * dpyinfo = x_display_info_for_display (disp);
3473 *scale_x = *scale_y = 1;
3475 if (dpyinfo)
3477 if (dpyinfo->resx > base_res)
3478 *scale_x = floor (dpyinfo->resx / base_res);
3479 if (dpyinfo->resy > base_res)
3480 *scale_y = floor (dpyinfo->resy / base_res);
3485 Draw a wavy line under S. The wave fills wave_height pixels from y0.
3487 x0 wave_length = 2
3489 y0 * * * * *
3490 |* * * * * * * * *
3491 wave_height = 3 | * * * *
3494 static void
3495 x_draw_underwave (struct glyph_string *s)
3497 /* Adjust for scale/HiDPI. */
3498 int scale_x, scale_y;
3500 x_get_scale_factor (s->display, &scale_x, &scale_y);
3502 int wave_height = 3 * scale_y, wave_length = 2 * scale_x;
3504 #ifdef USE_CAIRO
3505 x_draw_horizontal_wave (s->f, s->gc, s->x, s->ybase - wave_height + 3,
3506 s->width, wave_height, wave_length);
3507 #else /* not USE_CAIRO */
3508 int dx, dy, x0, y0, width, x1, y1, x2, y2, xmax, thickness = scale_y;;
3509 bool odd;
3510 XRectangle wave_clip, string_clip, final_clip;
3512 dx = wave_length;
3513 dy = wave_height - 1;
3514 x0 = s->x;
3515 y0 = s->ybase + wave_height / 2 - scale_y;
3516 width = s->width;
3517 xmax = x0 + width;
3519 /* Find and set clipping rectangle */
3521 wave_clip.x = x0;
3522 wave_clip.y = y0;
3523 wave_clip.width = width;
3524 wave_clip.height = wave_height;
3525 get_glyph_string_clip_rect (s, &string_clip);
3527 if (!x_intersect_rectangles (&wave_clip, &string_clip, &final_clip))
3528 return;
3530 XSetClipRectangles (s->display, s->gc, 0, 0, &final_clip, 1, Unsorted);
3532 /* Draw the waves */
3534 x1 = x0 - (x0 % dx);
3535 x2 = x1 + dx;
3536 odd = (x1 / dx) & 1;
3537 y1 = y2 = y0;
3539 if (odd)
3540 y1 += dy;
3541 else
3542 y2 += dy;
3544 if (INT_MAX - dx < xmax)
3545 emacs_abort ();
3547 while (x1 <= xmax)
3549 XSetLineAttributes (s->display, s->gc, thickness, LineSolid, CapButt,
3550 JoinRound);
3551 XDrawLine (s->display, FRAME_X_DRAWABLE (s->f), s->gc, x1, y1, x2, y2);
3552 x1 = x2, y1 = y2;
3553 x2 += dx, y2 = y0 + odd*dy;
3554 odd = !odd;
3557 /* Restore previous clipping rectangle(s) */
3558 XSetClipRectangles (s->display, s->gc, 0, 0, s->clip, s->num_clips, Unsorted);
3559 #endif /* not USE_CAIRO */
3563 /* Draw glyph string S. */
3565 static void
3566 x_draw_glyph_string (struct glyph_string *s)
3568 bool relief_drawn_p = false;
3570 /* If S draws into the background of its successors, draw the
3571 background of the successors first so that S can draw into it.
3572 This makes S->next use XDrawString instead of XDrawImageString. */
3573 if (s->next && s->right_overhang && !s->for_overlaps)
3575 int width;
3576 struct glyph_string *next;
3578 for (width = 0, next = s->next;
3579 next && width < s->right_overhang;
3580 width += next->width, next = next->next)
3581 if (next->first_glyph->type != IMAGE_GLYPH)
3583 x_set_glyph_string_gc (next);
3584 x_set_glyph_string_clipping (next);
3585 if (next->first_glyph->type == STRETCH_GLYPH)
3586 x_draw_stretch_glyph_string (next);
3587 else
3588 x_draw_glyph_string_background (next, true);
3589 next->num_clips = 0;
3593 /* Set up S->gc, set clipping and draw S. */
3594 x_set_glyph_string_gc (s);
3596 /* Draw relief (if any) in advance for char/composition so that the
3597 glyph string can be drawn over it. */
3598 if (!s->for_overlaps
3599 && s->face->box != FACE_NO_BOX
3600 && (s->first_glyph->type == CHAR_GLYPH
3601 || s->first_glyph->type == COMPOSITE_GLYPH))
3604 x_set_glyph_string_clipping (s);
3605 x_draw_glyph_string_background (s, true);
3606 x_draw_glyph_string_box (s);
3607 x_set_glyph_string_clipping (s);
3608 relief_drawn_p = true;
3610 else if (!s->clip_head /* draw_glyphs didn't specify a clip mask. */
3611 && !s->clip_tail
3612 && ((s->prev && s->prev->hl != s->hl && s->left_overhang)
3613 || (s->next && s->next->hl != s->hl && s->right_overhang)))
3614 /* We must clip just this glyph. left_overhang part has already
3615 drawn when s->prev was drawn, and right_overhang part will be
3616 drawn later when s->next is drawn. */
3617 x_set_glyph_string_clipping_exactly (s, s);
3618 else
3619 x_set_glyph_string_clipping (s);
3621 switch (s->first_glyph->type)
3623 case IMAGE_GLYPH:
3624 x_draw_image_glyph_string (s);
3625 break;
3627 case XWIDGET_GLYPH:
3628 x_draw_xwidget_glyph_string (s);
3629 break;
3631 case STRETCH_GLYPH:
3632 x_draw_stretch_glyph_string (s);
3633 break;
3635 case CHAR_GLYPH:
3636 if (s->for_overlaps)
3637 s->background_filled_p = true;
3638 else
3639 x_draw_glyph_string_background (s, false);
3640 x_draw_glyph_string_foreground (s);
3641 break;
3643 case COMPOSITE_GLYPH:
3644 if (s->for_overlaps || (s->cmp_from > 0
3645 && ! s->first_glyph->u.cmp.automatic))
3646 s->background_filled_p = true;
3647 else
3648 x_draw_glyph_string_background (s, true);
3649 x_draw_composite_glyph_string_foreground (s);
3650 break;
3652 case GLYPHLESS_GLYPH:
3653 if (s->for_overlaps)
3654 s->background_filled_p = true;
3655 else
3656 x_draw_glyph_string_background (s, true);
3657 x_draw_glyphless_glyph_string_foreground (s);
3658 break;
3660 default:
3661 emacs_abort ();
3664 if (!s->for_overlaps)
3666 /* Draw underline. */
3667 if (s->face->underline_p)
3669 if (s->face->underline_type == FACE_UNDER_WAVE)
3671 if (s->face->underline_defaulted_p)
3672 x_draw_underwave (s);
3673 else
3675 XGCValues xgcv;
3676 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3677 XSetForeground (s->display, s->gc, s->face->underline_color);
3678 x_draw_underwave (s);
3679 XSetForeground (s->display, s->gc, xgcv.foreground);
3682 else if (s->face->underline_type == FACE_UNDER_LINE)
3684 unsigned long thickness, position;
3685 int y;
3687 if (s->prev && s->prev->face->underline_p
3688 && s->prev->face->underline_type == FACE_UNDER_LINE)
3690 /* We use the same underline style as the previous one. */
3691 thickness = s->prev->underline_thickness;
3692 position = s->prev->underline_position;
3694 else
3696 struct font *font = font_for_underline_metrics (s);
3697 unsigned long minimum_offset;
3698 bool underline_at_descent_line;
3699 bool use_underline_position_properties;
3700 Lisp_Object val
3701 = buffer_local_value (Qunderline_minimum_offset,
3702 s->w->contents);
3703 if (INTEGERP (val))
3704 minimum_offset = XFASTINT (val);
3705 else
3706 minimum_offset = 1;
3707 val = buffer_local_value (Qx_underline_at_descent_line,
3708 s->w->contents);
3709 underline_at_descent_line
3710 = !(NILP (val) || EQ (val, Qunbound));
3712 = buffer_local_value (Qx_use_underline_position_properties,
3713 s->w->contents);
3714 use_underline_position_properties
3715 = !(NILP (val) || EQ (val, Qunbound));
3717 /* Get the underline thickness. Default is 1 pixel. */
3718 if (font && font->underline_thickness > 0)
3719 thickness = font->underline_thickness;
3720 else
3721 thickness = 1;
3722 if (underline_at_descent_line)
3723 position = (s->height - thickness) - (s->ybase - s->y);
3724 else
3726 /* Get the underline position. This is the
3727 recommended vertical offset in pixels from
3728 the baseline to the top of the underline.
3729 This is a signed value according to the
3730 specs, and its default is
3732 ROUND ((maximum descent) / 2), with
3733 ROUND(x) = floor (x + 0.5) */
3735 if (use_underline_position_properties
3736 && font && font->underline_position >= 0)
3737 position = font->underline_position;
3738 else if (font)
3739 position = (font->descent + 1) / 2;
3740 else
3741 position = minimum_offset;
3743 position = max (position, minimum_offset);
3745 /* Check the sanity of thickness and position. We should
3746 avoid drawing underline out of the current line area. */
3747 if (s->y + s->height <= s->ybase + position)
3748 position = (s->height - 1) - (s->ybase - s->y);
3749 if (s->y + s->height < s->ybase + position + thickness)
3750 thickness = (s->y + s->height) - (s->ybase + position);
3751 s->underline_thickness = thickness;
3752 s->underline_position = position;
3753 y = s->ybase + position;
3754 if (s->face->underline_defaulted_p)
3755 x_fill_rectangle (s->f, s->gc,
3756 s->x, y, s->width, thickness);
3757 else
3759 XGCValues xgcv;
3760 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3761 XSetForeground (s->display, s->gc, s->face->underline_color);
3762 x_fill_rectangle (s->f, s->gc,
3763 s->x, y, s->width, thickness);
3764 XSetForeground (s->display, s->gc, xgcv.foreground);
3768 /* Draw overline. */
3769 if (s->face->overline_p)
3771 unsigned long dy = 0, h = 1;
3773 if (s->face->overline_color_defaulted_p)
3774 x_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3775 s->width, h);
3776 else
3778 XGCValues xgcv;
3779 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3780 XSetForeground (s->display, s->gc, s->face->overline_color);
3781 x_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3782 s->width, h);
3783 XSetForeground (s->display, s->gc, xgcv.foreground);
3787 /* Draw strike-through. */
3788 if (s->face->strike_through_p)
3790 /* Y-coordinate and height of the glyph string's first
3791 glyph. We cannot use s->y and s->height because those
3792 could be larger if there are taller display elements
3793 (e.g., characters displayed with a larger font) in the
3794 same glyph row. */
3795 int glyph_y = s->ybase - s->first_glyph->ascent;
3796 int glyph_height = s->first_glyph->ascent + s->first_glyph->descent;
3797 /* Strike-through width and offset from the glyph string's
3798 top edge. */
3799 unsigned long h = 1;
3800 unsigned long dy = (glyph_height - h) / 2;
3802 if (s->face->strike_through_color_defaulted_p)
3803 x_fill_rectangle (s->f, s->gc, s->x, glyph_y + dy,
3804 s->width, h);
3805 else
3807 XGCValues xgcv;
3808 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3809 XSetForeground (s->display, s->gc, s->face->strike_through_color);
3810 x_fill_rectangle (s->f, s->gc, s->x, glyph_y + dy,
3811 s->width, h);
3812 XSetForeground (s->display, s->gc, xgcv.foreground);
3816 /* Draw relief if not yet drawn. */
3817 if (!relief_drawn_p && s->face->box != FACE_NO_BOX)
3818 x_draw_glyph_string_box (s);
3820 if (s->prev)
3822 struct glyph_string *prev;
3824 for (prev = s->prev; prev; prev = prev->prev)
3825 if (prev->hl != s->hl
3826 && prev->x + prev->width + prev->right_overhang > s->x)
3828 /* As prev was drawn while clipped to its own area, we
3829 must draw the right_overhang part using s->hl now. */
3830 enum draw_glyphs_face save = prev->hl;
3832 prev->hl = s->hl;
3833 x_set_glyph_string_gc (prev);
3834 x_set_glyph_string_clipping_exactly (s, prev);
3835 if (prev->first_glyph->type == CHAR_GLYPH)
3836 x_draw_glyph_string_foreground (prev);
3837 else
3838 x_draw_composite_glyph_string_foreground (prev);
3839 x_reset_clip_rectangles (prev->f, prev->gc);
3840 prev->hl = save;
3841 prev->num_clips = 0;
3845 if (s->next)
3847 struct glyph_string *next;
3849 for (next = s->next; next; next = next->next)
3850 if (next->hl != s->hl
3851 && next->x - next->left_overhang < s->x + s->width)
3853 /* As next will be drawn while clipped to its own area,
3854 we must draw the left_overhang part using s->hl now. */
3855 enum draw_glyphs_face save = next->hl;
3857 next->hl = s->hl;
3858 x_set_glyph_string_gc (next);
3859 x_set_glyph_string_clipping_exactly (s, next);
3860 if (next->first_glyph->type == CHAR_GLYPH)
3861 x_draw_glyph_string_foreground (next);
3862 else
3863 x_draw_composite_glyph_string_foreground (next);
3864 x_reset_clip_rectangles (next->f, next->gc);
3865 next->hl = save;
3866 next->num_clips = 0;
3867 next->clip_head = s->next;
3872 /* Reset clipping. */
3873 x_reset_clip_rectangles (s->f, s->gc);
3874 s->num_clips = 0;
3877 /* Shift display to make room for inserted glyphs. */
3879 static void
3880 x_shift_glyphs_for_insert (struct frame *f, int x, int y, int width, int height, int shift_by)
3882 /* Never called on a GUI frame, see
3883 https://lists.gnu.org/r/emacs-devel/2015-05/msg00456.html
3885 XCopyArea (FRAME_X_DISPLAY (f), FRAME_X_DRAWABLE (f), FRAME_X_DRAWABLE (f),
3886 f->output_data.x->normal_gc,
3887 x, y, width, height,
3888 x + shift_by, y);
3891 /* Delete N glyphs at the nominal cursor position. Not implemented
3892 for X frames. */
3894 static void
3895 x_delete_glyphs (struct frame *f, register int n)
3897 emacs_abort ();
3901 /* Like XClearArea, but check that WIDTH and HEIGHT are reasonable.
3902 If they are <= 0, this is probably an error. */
3904 static ATTRIBUTE_UNUSED void
3905 x_clear_area1 (Display *dpy, Window window,
3906 int x, int y, int width, int height, int exposures)
3908 eassert (width > 0 && height > 0);
3909 XClearArea (dpy, window, x, y, width, height, exposures);
3912 void
3913 x_clear_area (struct frame *f, int x, int y, int width, int height)
3915 #ifdef USE_CAIRO
3916 cairo_t *cr;
3918 eassert (width > 0 && height > 0);
3920 cr = x_begin_cr_clip (f, NULL);
3921 x_set_cr_source_with_gc_background (f, f->output_data.x->normal_gc);
3922 cairo_rectangle (cr, x, y, width, height);
3923 cairo_fill (cr);
3924 x_end_cr_clip (f);
3925 #else
3926 if (FRAME_X_DOUBLE_BUFFERED_P (f))
3927 XFillRectangle (FRAME_X_DISPLAY (f),
3928 FRAME_X_DRAWABLE (f),
3929 f->output_data.x->reverse_gc,
3930 x, y, width, height);
3931 else
3932 x_clear_area1 (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3933 x, y, width, height, False);
3934 #endif
3938 /* Clear an entire frame. */
3940 static void
3941 x_clear_frame (struct frame *f)
3943 /* Clearing the frame will erase any cursor, so mark them all as no
3944 longer visible. */
3945 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
3947 block_input ();
3949 font_drop_xrender_surfaces (f);
3950 x_clear_window (f);
3952 /* We have to clear the scroll bars. If we have changed colors or
3953 something like that, then they should be notified. */
3954 x_scroll_bar_clear (f);
3956 XFlush (FRAME_X_DISPLAY (f));
3958 unblock_input ();
3961 /* RIF: Show hourglass cursor on frame F. */
3963 static void
3964 x_show_hourglass (struct frame *f)
3966 Display *dpy = FRAME_X_DISPLAY (f);
3968 if (dpy)
3970 struct x_output *x = FRAME_X_OUTPUT (f);
3971 #ifdef USE_X_TOOLKIT
3972 if (x->widget)
3973 #else
3974 if (FRAME_OUTER_WINDOW (f))
3975 #endif
3977 x->hourglass_p = true;
3979 if (!x->hourglass_window)
3981 unsigned long mask = CWCursor;
3982 XSetWindowAttributes attrs;
3983 #ifdef USE_GTK
3984 Window parent = FRAME_X_WINDOW (f);
3985 #else
3986 Window parent = FRAME_OUTER_WINDOW (f);
3987 #endif
3988 attrs.cursor = x->hourglass_cursor;
3990 x->hourglass_window = XCreateWindow
3991 (dpy, parent, 0, 0, 32000, 32000, 0, 0,
3992 InputOnly, CopyFromParent, mask, &attrs);
3995 XMapRaised (dpy, x->hourglass_window);
3996 XFlush (dpy);
4001 /* RIF: Cancel hourglass cursor on frame F. */
4003 static void
4004 x_hide_hourglass (struct frame *f)
4006 struct x_output *x = FRAME_X_OUTPUT (f);
4008 /* Watch out for newly created frames. */
4009 if (x->hourglass_window)
4011 XUnmapWindow (FRAME_X_DISPLAY (f), x->hourglass_window);
4012 /* Sync here because XTread_socket looks at the
4013 hourglass_p flag that is reset to zero below. */
4014 XSync (FRAME_X_DISPLAY (f), False);
4015 x->hourglass_p = false;
4019 /* Invert the middle quarter of the frame for .15 sec. */
4021 static void
4022 XTflash (struct frame *f)
4024 block_input ();
4027 #ifdef USE_GTK
4028 /* Use Gdk routines to draw. This way, we won't draw over scroll bars
4029 when the scroll bars and the edit widget share the same X window. */
4030 GdkWindow *window = gtk_widget_get_window (FRAME_GTK_WIDGET (f));
4031 #ifdef HAVE_GTK3
4032 #if GTK_CHECK_VERSION (3, 22, 0)
4033 cairo_region_t *region = gdk_window_get_visible_region (window);
4034 GdkDrawingContext *context = gdk_window_begin_draw_frame (window, region);
4035 cairo_t *cr = gdk_drawing_context_get_cairo_context (context);
4036 #else
4037 cairo_t *cr = gdk_cairo_create (window);
4038 #endif
4039 cairo_set_source_rgb (cr, 1, 1, 1);
4040 cairo_set_operator (cr, CAIRO_OPERATOR_DIFFERENCE);
4041 #define XFillRectangle(d, win, gc, x, y, w, h) \
4042 do { \
4043 cairo_rectangle (cr, x, y, w, h); \
4044 cairo_fill (cr); \
4046 while (false)
4047 #else /* ! HAVE_GTK3 */
4048 GdkGCValues vals;
4049 GdkGC *gc;
4050 vals.foreground.pixel = (FRAME_FOREGROUND_PIXEL (f)
4051 ^ FRAME_BACKGROUND_PIXEL (f));
4052 vals.function = GDK_XOR;
4053 gc = gdk_gc_new_with_values (window,
4054 &vals, GDK_GC_FUNCTION | GDK_GC_FOREGROUND);
4055 #define XFillRectangle(d, win, gc, x, y, w, h) \
4056 gdk_draw_rectangle (window, gc, true, x, y, w, h)
4057 #endif /* ! HAVE_GTK3 */
4058 #else /* ! USE_GTK */
4059 GC gc;
4061 /* Create a GC that will use the GXxor function to flip foreground
4062 pixels into background pixels. */
4064 XGCValues values;
4066 values.function = GXxor;
4067 values.foreground = (FRAME_FOREGROUND_PIXEL (f)
4068 ^ FRAME_BACKGROUND_PIXEL (f));
4070 gc = XCreateGC (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4071 GCFunction | GCForeground, &values);
4073 #endif
4075 /* Get the height not including a menu bar widget. */
4076 int height = FRAME_PIXEL_HEIGHT (f);
4077 /* Height of each line to flash. */
4078 int flash_height = FRAME_LINE_HEIGHT (f);
4079 /* These will be the left and right margins of the rectangles. */
4080 int flash_left = FRAME_INTERNAL_BORDER_WIDTH (f);
4081 int flash_right = FRAME_PIXEL_WIDTH (f) - FRAME_INTERNAL_BORDER_WIDTH (f);
4082 int width = flash_right - flash_left;
4084 /* If window is tall, flash top and bottom line. */
4085 if (height > 3 * FRAME_LINE_HEIGHT (f))
4087 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4088 flash_left,
4089 (FRAME_INTERNAL_BORDER_WIDTH (f)
4090 + FRAME_TOP_MARGIN_HEIGHT (f)),
4091 width, flash_height);
4092 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4093 flash_left,
4094 (height - flash_height
4095 - FRAME_INTERNAL_BORDER_WIDTH (f)),
4096 width, flash_height);
4099 else
4100 /* If it is short, flash it all. */
4101 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4102 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
4103 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
4105 x_flush (f);
4108 struct timespec delay = make_timespec (0, 150 * 1000 * 1000);
4109 struct timespec wakeup = timespec_add (current_timespec (), delay);
4111 /* Keep waiting until past the time wakeup or any input gets
4112 available. */
4113 while (! detect_input_pending ())
4115 struct timespec current = current_timespec ();
4116 struct timespec timeout;
4118 /* Break if result would not be positive. */
4119 if (timespec_cmp (wakeup, current) <= 0)
4120 break;
4122 /* How long `select' should wait. */
4123 timeout = make_timespec (0, 10 * 1000 * 1000);
4125 /* Try to wait that long--but we might wake up sooner. */
4126 pselect (0, NULL, NULL, NULL, &timeout, NULL);
4130 /* If window is tall, flash top and bottom line. */
4131 if (height > 3 * FRAME_LINE_HEIGHT (f))
4133 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4134 flash_left,
4135 (FRAME_INTERNAL_BORDER_WIDTH (f)
4136 + FRAME_TOP_MARGIN_HEIGHT (f)),
4137 width, flash_height);
4138 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4139 flash_left,
4140 (height - flash_height
4141 - FRAME_INTERNAL_BORDER_WIDTH (f)),
4142 width, flash_height);
4144 else
4145 /* If it is short, flash it all. */
4146 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4147 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
4148 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
4150 #ifdef USE_GTK
4151 #ifdef HAVE_GTK3
4152 #if GTK_CHECK_VERSION (3, 22, 0)
4153 gdk_window_end_draw_frame (window, context);
4154 cairo_region_destroy (region);
4155 #else
4156 cairo_destroy (cr);
4157 #endif
4158 #else
4159 g_object_unref (G_OBJECT (gc));
4160 #endif
4161 #undef XFillRectangle
4162 #else
4163 XFreeGC (FRAME_X_DISPLAY (f), gc);
4164 #endif
4165 x_flush (f);
4169 unblock_input ();
4173 static void
4174 XTtoggle_invisible_pointer (struct frame *f, bool invisible)
4176 block_input ();
4177 FRAME_DISPLAY_INFO (f)->toggle_visible_pointer (f, invisible);
4178 unblock_input ();
4182 /* Make audible bell. */
4184 static void
4185 XTring_bell (struct frame *f)
4187 if (FRAME_X_DISPLAY (f))
4189 if (visible_bell)
4190 XTflash (f);
4191 else
4193 block_input ();
4194 #ifdef HAVE_XKB
4195 XkbBell (FRAME_X_DISPLAY (f), None, 0, None);
4196 #else
4197 XBell (FRAME_X_DISPLAY (f), 0);
4198 #endif
4199 XFlush (FRAME_X_DISPLAY (f));
4200 unblock_input ();
4205 /***********************************************************************
4206 Line Dance
4207 ***********************************************************************/
4209 /* Perform an insert-lines or delete-lines operation, inserting N
4210 lines or deleting -N lines at vertical position VPOS. */
4212 static void
4213 x_ins_del_lines (struct frame *f, int vpos, int n)
4215 emacs_abort ();
4219 /* Scroll part of the display as described by RUN. */
4221 static void
4222 x_scroll_run (struct window *w, struct run *run)
4224 struct frame *f = XFRAME (w->frame);
4225 int x, y, width, height, from_y, to_y, bottom_y;
4227 /* Get frame-relative bounding box of the text display area of W,
4228 without mode lines. Include in this box the left and right
4229 fringe of W. */
4230 window_box (w, ANY_AREA, &x, &y, &width, &height);
4232 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
4233 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
4234 bottom_y = y + height;
4236 if (to_y < from_y)
4238 /* Scrolling up. Make sure we don't copy part of the mode
4239 line at the bottom. */
4240 if (from_y + run->height > bottom_y)
4241 height = bottom_y - from_y;
4242 else
4243 height = run->height;
4245 else
4247 /* Scrolling down. Make sure we don't copy over the mode line.
4248 at the bottom. */
4249 if (to_y + run->height > bottom_y)
4250 height = bottom_y - to_y;
4251 else
4252 height = run->height;
4255 block_input ();
4257 /* Cursor off. Will be switched on again in x_update_window_end. */
4258 x_clear_cursor (w);
4260 #ifdef USE_CAIRO
4261 if (FRAME_CR_CONTEXT (f))
4263 cairo_surface_t *s = cairo_image_surface_create (CAIRO_FORMAT_ARGB32,
4264 width, height);
4265 cairo_t *cr = cairo_create (s);
4266 cairo_set_source_surface (cr, cairo_get_target (FRAME_CR_CONTEXT (f)),
4267 -x, -from_y);
4268 cairo_paint (cr);
4269 cairo_destroy (cr);
4271 cr = FRAME_CR_CONTEXT (f);
4272 cairo_save (cr);
4273 cairo_set_source_surface (cr, s, 0, to_y);
4274 cairo_rectangle (cr, x, to_y, width, height);
4275 cairo_fill (cr);
4276 cairo_restore (cr);
4277 cairo_surface_destroy (s);
4279 else
4281 SET_FRAME_GARBAGED (f);
4283 #else
4284 XCopyArea (FRAME_X_DISPLAY (f),
4285 FRAME_X_DRAWABLE (f), FRAME_X_DRAWABLE (f),
4286 f->output_data.x->normal_gc,
4287 x, from_y,
4288 width, height,
4289 x, to_y);
4290 #endif
4292 unblock_input ();
4297 /***********************************************************************
4298 Exposure Events
4299 ***********************************************************************/
4302 static void
4303 frame_highlight (struct frame *f)
4305 /* We used to only do this if Vx_no_window_manager was non-nil, but
4306 the ICCCM (section 4.1.6) says that the window's border pixmap
4307 and border pixel are window attributes which are "private to the
4308 client", so we can always change it to whatever we want. */
4309 block_input ();
4310 /* I recently started to get errors in this XSetWindowBorder, depending on
4311 the window-manager in use, tho something more is at play since I've been
4312 using that same window-manager binary for ever. Let's not crash just
4313 because of this (bug#9310). */
4314 x_catch_errors (FRAME_X_DISPLAY (f));
4315 XSetWindowBorder (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4316 f->output_data.x->border_pixel);
4317 x_uncatch_errors ();
4318 unblock_input ();
4319 x_update_cursor (f, true);
4320 x_set_frame_alpha (f);
4323 static void
4324 frame_unhighlight (struct frame *f)
4326 /* We used to only do this if Vx_no_window_manager was non-nil, but
4327 the ICCCM (section 4.1.6) says that the window's border pixmap
4328 and border pixel are window attributes which are "private to the
4329 client", so we can always change it to whatever we want. */
4330 block_input ();
4331 /* Same as above for XSetWindowBorder (bug#9310). */
4332 x_catch_errors (FRAME_X_DISPLAY (f));
4333 XSetWindowBorderPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4334 f->output_data.x->border_tile);
4335 x_uncatch_errors ();
4336 unblock_input ();
4337 x_update_cursor (f, true);
4338 x_set_frame_alpha (f);
4341 /* The focus has changed. Update the frames as necessary to reflect
4342 the new situation. Note that we can't change the selected frame
4343 here, because the Lisp code we are interrupting might become confused.
4344 Each event gets marked with the frame in which it occurred, so the
4345 Lisp code can tell when the switch took place by examining the events. */
4347 static void
4348 x_new_focus_frame (struct x_display_info *dpyinfo, struct frame *frame)
4350 struct frame *old_focus = dpyinfo->x_focus_frame;
4352 if (frame != dpyinfo->x_focus_frame)
4354 /* Set this before calling other routines, so that they see
4355 the correct value of x_focus_frame. */
4356 dpyinfo->x_focus_frame = frame;
4358 if (old_focus && old_focus->auto_lower)
4359 x_lower_frame (old_focus);
4361 if (dpyinfo->x_focus_frame && dpyinfo->x_focus_frame->auto_raise)
4362 dpyinfo->x_pending_autoraise_frame = dpyinfo->x_focus_frame;
4363 else
4364 dpyinfo->x_pending_autoraise_frame = NULL;
4367 x_frame_rehighlight (dpyinfo);
4370 /* Handle FocusIn and FocusOut state changes for FRAME.
4371 If FRAME has focus and there exists more than one frame, puts
4372 a FOCUS_IN_EVENT into *BUFP. */
4374 static void
4375 x_focus_changed (int type, int state, struct x_display_info *dpyinfo, struct frame *frame, struct input_event *bufp)
4377 if (type == FocusIn)
4379 if (dpyinfo->x_focus_event_frame != frame)
4381 x_new_focus_frame (dpyinfo, frame);
4382 dpyinfo->x_focus_event_frame = frame;
4384 /* Don't stop displaying the initial startup message
4385 for a switch-frame event we don't need. */
4386 /* When run as a daemon, Vterminal_frame is always NIL. */
4387 bufp->arg = (((NILP (Vterminal_frame)
4388 || ! FRAME_X_P (XFRAME (Vterminal_frame))
4389 || EQ (Fdaemonp (), Qt))
4390 && CONSP (Vframe_list)
4391 && !NILP (XCDR (Vframe_list)))
4392 ? Qt : Qnil);
4393 bufp->kind = FOCUS_IN_EVENT;
4394 XSETFRAME (bufp->frame_or_window, frame);
4397 frame->output_data.x->focus_state |= state;
4399 #ifdef HAVE_X_I18N
4400 if (FRAME_XIC (frame))
4401 XSetICFocus (FRAME_XIC (frame));
4402 #endif
4404 else if (type == FocusOut)
4406 frame->output_data.x->focus_state &= ~state;
4408 if (dpyinfo->x_focus_event_frame == frame)
4410 dpyinfo->x_focus_event_frame = 0;
4411 x_new_focus_frame (dpyinfo, 0);
4413 bufp->kind = FOCUS_OUT_EVENT;
4414 XSETFRAME (bufp->frame_or_window, frame);
4417 #ifdef HAVE_X_I18N
4418 if (FRAME_XIC (frame))
4419 XUnsetICFocus (FRAME_XIC (frame));
4420 #endif
4421 if (frame->pointer_invisible)
4422 XTtoggle_invisible_pointer (frame, false);
4426 /* Return the Emacs frame-object corresponding to an X window.
4427 It could be the frame's main window or an icon window. */
4429 static struct frame *
4430 x_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
4432 Lisp_Object tail, frame;
4433 struct frame *f;
4435 if (wdesc == None)
4436 return NULL;
4438 FOR_EACH_FRAME (tail, frame)
4440 f = XFRAME (frame);
4441 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
4442 continue;
4443 if (f->output_data.x->hourglass_window == wdesc)
4444 return f;
4445 #ifdef USE_X_TOOLKIT
4446 if ((f->output_data.x->edit_widget
4447 && XtWindow (f->output_data.x->edit_widget) == wdesc)
4448 /* A tooltip frame? */
4449 || (!f->output_data.x->edit_widget
4450 && FRAME_X_WINDOW (f) == wdesc)
4451 || f->output_data.x->icon_desc == wdesc)
4452 return f;
4453 #else /* not USE_X_TOOLKIT */
4454 #ifdef USE_GTK
4455 if (f->output_data.x->edit_widget)
4457 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
4458 struct x_output *x = f->output_data.x;
4459 if (gwdesc != 0 && gwdesc == x->edit_widget)
4460 return f;
4462 #endif /* USE_GTK */
4463 if (FRAME_X_WINDOW (f) == wdesc
4464 || f->output_data.x->icon_desc == wdesc)
4465 return f;
4466 #endif /* not USE_X_TOOLKIT */
4468 return 0;
4471 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
4473 /* Like x_window_to_frame but also compares the window with the widget's
4474 windows. */
4476 static struct frame *
4477 x_any_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
4479 Lisp_Object tail, frame;
4480 struct frame *f, *found = NULL;
4481 struct x_output *x;
4483 if (wdesc == None)
4484 return NULL;
4486 FOR_EACH_FRAME (tail, frame)
4488 if (found)
4489 break;
4490 f = XFRAME (frame);
4491 if (FRAME_X_P (f) && FRAME_DISPLAY_INFO (f) == dpyinfo)
4493 /* This frame matches if the window is any of its widgets. */
4494 x = f->output_data.x;
4495 if (x->hourglass_window == wdesc)
4496 found = f;
4497 else if (x->widget)
4499 #ifdef USE_GTK
4500 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
4501 if (gwdesc != 0
4502 && gtk_widget_get_toplevel (gwdesc) == x->widget)
4503 found = f;
4504 #else
4505 if (wdesc == XtWindow (x->widget)
4506 || wdesc == XtWindow (x->column_widget)
4507 || wdesc == XtWindow (x->edit_widget))
4508 found = f;
4509 /* Match if the window is this frame's menubar. */
4510 else if (lw_window_is_in_menubar (wdesc, x->menubar_widget))
4511 found = f;
4512 #endif
4514 else if (FRAME_X_WINDOW (f) == wdesc)
4515 /* A tooltip frame. */
4516 found = f;
4520 return found;
4523 /* Likewise, but consider only the menu bar widget. */
4525 static struct frame *
4526 x_menubar_window_to_frame (struct x_display_info *dpyinfo,
4527 const XEvent *event)
4529 Window wdesc = event->xany.window;
4530 Lisp_Object tail, frame;
4531 struct frame *f;
4532 struct x_output *x;
4534 if (wdesc == None)
4535 return NULL;
4537 FOR_EACH_FRAME (tail, frame)
4539 f = XFRAME (frame);
4540 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
4541 continue;
4542 x = f->output_data.x;
4543 #ifdef USE_GTK
4544 if (x->menubar_widget && xg_event_is_for_menubar (f, event))
4545 return f;
4546 #else
4547 /* Match if the window is this frame's menubar. */
4548 if (x->menubar_widget
4549 && lw_window_is_in_menubar (wdesc, x->menubar_widget))
4550 return f;
4551 #endif
4553 return 0;
4556 /* Return the frame whose principal (outermost) window is WDESC.
4557 If WDESC is some other (smaller) window, we return 0. */
4559 struct frame *
4560 x_top_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
4562 Lisp_Object tail, frame;
4563 struct frame *f;
4564 struct x_output *x;
4566 if (wdesc == None)
4567 return NULL;
4569 FOR_EACH_FRAME (tail, frame)
4571 f = XFRAME (frame);
4572 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
4573 continue;
4574 x = f->output_data.x;
4576 if (x->widget)
4578 /* This frame matches if the window is its topmost widget. */
4579 #ifdef USE_GTK
4580 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
4581 if (gwdesc == x->widget)
4582 return f;
4583 #else
4584 if (wdesc == XtWindow (x->widget))
4585 return f;
4586 #endif
4588 else if (FRAME_X_WINDOW (f) == wdesc)
4589 /* Tooltip frame. */
4590 return f;
4592 return 0;
4595 #else /* !USE_X_TOOLKIT && !USE_GTK */
4597 #define x_any_window_to_frame(d, i) x_window_to_frame (d, i)
4598 #define x_top_window_to_frame(d, i) x_window_to_frame (d, i)
4600 #endif /* USE_X_TOOLKIT || USE_GTK */
4602 /* The focus may have changed. Figure out if it is a real focus change,
4603 by checking both FocusIn/Out and Enter/LeaveNotify events.
4605 Returns FOCUS_IN_EVENT event in *BUFP. */
4607 static void
4608 x_detect_focus_change (struct x_display_info *dpyinfo, struct frame *frame,
4609 const XEvent *event, struct input_event *bufp)
4611 if (!frame)
4612 return;
4614 switch (event->type)
4616 case EnterNotify:
4617 case LeaveNotify:
4619 struct frame *focus_frame = dpyinfo->x_focus_event_frame;
4620 int focus_state
4621 = focus_frame ? focus_frame->output_data.x->focus_state : 0;
4623 if (event->xcrossing.detail != NotifyInferior
4624 && event->xcrossing.focus
4625 && ! (focus_state & FOCUS_EXPLICIT))
4626 x_focus_changed ((event->type == EnterNotify ? FocusIn : FocusOut),
4627 FOCUS_IMPLICIT,
4628 dpyinfo, frame, bufp);
4630 break;
4632 case FocusIn:
4633 case FocusOut:
4634 x_focus_changed (event->type,
4635 (event->xfocus.detail == NotifyPointer ?
4636 FOCUS_IMPLICIT : FOCUS_EXPLICIT),
4637 dpyinfo, frame, bufp);
4638 break;
4640 case ClientMessage:
4641 if (event->xclient.message_type == dpyinfo->Xatom_XEMBED)
4643 enum xembed_message msg = event->xclient.data.l[1];
4644 x_focus_changed ((msg == XEMBED_FOCUS_IN ? FocusIn : FocusOut),
4645 FOCUS_EXPLICIT, dpyinfo, frame, bufp);
4647 break;
4652 #if !defined USE_X_TOOLKIT && !defined USE_GTK
4653 /* Handle an event saying the mouse has moved out of an Emacs frame. */
4655 void
4656 x_mouse_leave (struct x_display_info *dpyinfo)
4658 x_new_focus_frame (dpyinfo, dpyinfo->x_focus_event_frame);
4660 #endif
4662 /* The focus has changed, or we have redirected a frame's focus to
4663 another frame (this happens when a frame uses a surrogate
4664 mini-buffer frame). Shift the highlight as appropriate.
4666 The FRAME argument doesn't necessarily have anything to do with which
4667 frame is being highlighted or un-highlighted; we only use it to find
4668 the appropriate X display info. */
4670 static void
4671 XTframe_rehighlight (struct frame *frame)
4673 x_frame_rehighlight (FRAME_DISPLAY_INFO (frame));
4676 static void
4677 x_frame_rehighlight (struct x_display_info *dpyinfo)
4679 struct frame *old_highlight = dpyinfo->x_highlight_frame;
4681 if (dpyinfo->x_focus_frame)
4683 dpyinfo->x_highlight_frame
4684 = ((FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame)))
4685 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
4686 : dpyinfo->x_focus_frame);
4687 if (! FRAME_LIVE_P (dpyinfo->x_highlight_frame))
4689 fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
4690 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
4693 else
4694 dpyinfo->x_highlight_frame = 0;
4696 if (dpyinfo->x_highlight_frame != old_highlight)
4698 if (old_highlight)
4699 frame_unhighlight (old_highlight);
4700 if (dpyinfo->x_highlight_frame)
4701 frame_highlight (dpyinfo->x_highlight_frame);
4707 /* Keyboard processing - modifier keys, vendor-specific keysyms, etc. */
4709 /* Initialize mode_switch_bit and modifier_meaning. */
4710 static void
4711 x_find_modifier_meanings (struct x_display_info *dpyinfo)
4713 int min_code, max_code;
4714 KeySym *syms;
4715 int syms_per_code;
4716 XModifierKeymap *mods;
4718 dpyinfo->meta_mod_mask = 0;
4719 dpyinfo->shift_lock_mask = 0;
4720 dpyinfo->alt_mod_mask = 0;
4721 dpyinfo->super_mod_mask = 0;
4722 dpyinfo->hyper_mod_mask = 0;
4724 XDisplayKeycodes (dpyinfo->display, &min_code, &max_code);
4726 syms = XGetKeyboardMapping (dpyinfo->display,
4727 min_code, max_code - min_code + 1,
4728 &syms_per_code);
4729 mods = XGetModifierMapping (dpyinfo->display);
4731 /* Scan the modifier table to see which modifier bits the Meta and
4732 Alt keysyms are on. */
4734 int row, col; /* The row and column in the modifier table. */
4735 bool found_alt_or_meta;
4737 for (row = 3; row < 8; row++)
4739 found_alt_or_meta = false;
4740 for (col = 0; col < mods->max_keypermod; col++)
4742 KeyCode code = mods->modifiermap[(row * mods->max_keypermod) + col];
4744 /* Zeroes are used for filler. Skip them. */
4745 if (code == 0)
4746 continue;
4748 /* Are any of this keycode's keysyms a meta key? */
4750 int code_col;
4752 for (code_col = 0; code_col < syms_per_code; code_col++)
4754 int sym = syms[((code - min_code) * syms_per_code) + code_col];
4756 switch (sym)
4758 case XK_Meta_L:
4759 case XK_Meta_R:
4760 found_alt_or_meta = true;
4761 dpyinfo->meta_mod_mask |= (1 << row);
4762 break;
4764 case XK_Alt_L:
4765 case XK_Alt_R:
4766 found_alt_or_meta = true;
4767 dpyinfo->alt_mod_mask |= (1 << row);
4768 break;
4770 case XK_Hyper_L:
4771 case XK_Hyper_R:
4772 if (!found_alt_or_meta)
4773 dpyinfo->hyper_mod_mask |= (1 << row);
4774 code_col = syms_per_code;
4775 col = mods->max_keypermod;
4776 break;
4778 case XK_Super_L:
4779 case XK_Super_R:
4780 if (!found_alt_or_meta)
4781 dpyinfo->super_mod_mask |= (1 << row);
4782 code_col = syms_per_code;
4783 col = mods->max_keypermod;
4784 break;
4786 case XK_Shift_Lock:
4787 /* Ignore this if it's not on the lock modifier. */
4788 if (!found_alt_or_meta && ((1 << row) == LockMask))
4789 dpyinfo->shift_lock_mask = LockMask;
4790 code_col = syms_per_code;
4791 col = mods->max_keypermod;
4792 break;
4800 /* If we couldn't find any meta keys, accept any alt keys as meta keys. */
4801 if (! dpyinfo->meta_mod_mask)
4803 dpyinfo->meta_mod_mask = dpyinfo->alt_mod_mask;
4804 dpyinfo->alt_mod_mask = 0;
4807 /* If some keys are both alt and meta,
4808 make them just meta, not alt. */
4809 if (dpyinfo->alt_mod_mask & dpyinfo->meta_mod_mask)
4811 dpyinfo->alt_mod_mask &= ~dpyinfo->meta_mod_mask;
4814 XFree (syms);
4815 XFreeModifiermap (mods);
4818 /* Convert between the modifier bits X uses and the modifier bits
4819 Emacs uses. */
4822 x_x_to_emacs_modifiers (struct x_display_info *dpyinfo, int state)
4824 int mod_ctrl = ctrl_modifier;
4825 int mod_meta = meta_modifier;
4826 int mod_alt = alt_modifier;
4827 int mod_hyper = hyper_modifier;
4828 int mod_super = super_modifier;
4829 Lisp_Object tem;
4831 tem = Fget (Vx_ctrl_keysym, Qmodifier_value);
4832 if (INTEGERP (tem)) mod_ctrl = XINT (tem) & INT_MAX;
4833 tem = Fget (Vx_alt_keysym, Qmodifier_value);
4834 if (INTEGERP (tem)) mod_alt = XINT (tem) & INT_MAX;
4835 tem = Fget (Vx_meta_keysym, Qmodifier_value);
4836 if (INTEGERP (tem)) mod_meta = XINT (tem) & INT_MAX;
4837 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
4838 if (INTEGERP (tem)) mod_hyper = XINT (tem) & INT_MAX;
4839 tem = Fget (Vx_super_keysym, Qmodifier_value);
4840 if (INTEGERP (tem)) mod_super = XINT (tem) & INT_MAX;
4842 return ( ((state & (ShiftMask | dpyinfo->shift_lock_mask)) ? shift_modifier : 0)
4843 | ((state & ControlMask) ? mod_ctrl : 0)
4844 | ((state & dpyinfo->meta_mod_mask) ? mod_meta : 0)
4845 | ((state & dpyinfo->alt_mod_mask) ? mod_alt : 0)
4846 | ((state & dpyinfo->super_mod_mask) ? mod_super : 0)
4847 | ((state & dpyinfo->hyper_mod_mask) ? mod_hyper : 0));
4850 static int
4851 x_emacs_to_x_modifiers (struct x_display_info *dpyinfo, EMACS_INT state)
4853 EMACS_INT mod_ctrl = ctrl_modifier;
4854 EMACS_INT mod_meta = meta_modifier;
4855 EMACS_INT mod_alt = alt_modifier;
4856 EMACS_INT mod_hyper = hyper_modifier;
4857 EMACS_INT mod_super = super_modifier;
4859 Lisp_Object tem;
4861 tem = Fget (Vx_ctrl_keysym, Qmodifier_value);
4862 if (INTEGERP (tem)) mod_ctrl = XINT (tem);
4863 tem = Fget (Vx_alt_keysym, Qmodifier_value);
4864 if (INTEGERP (tem)) mod_alt = XINT (tem);
4865 tem = Fget (Vx_meta_keysym, Qmodifier_value);
4866 if (INTEGERP (tem)) mod_meta = XINT (tem);
4867 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
4868 if (INTEGERP (tem)) mod_hyper = XINT (tem);
4869 tem = Fget (Vx_super_keysym, Qmodifier_value);
4870 if (INTEGERP (tem)) mod_super = XINT (tem);
4873 return ( ((state & mod_alt) ? dpyinfo->alt_mod_mask : 0)
4874 | ((state & mod_super) ? dpyinfo->super_mod_mask : 0)
4875 | ((state & mod_hyper) ? dpyinfo->hyper_mod_mask : 0)
4876 | ((state & shift_modifier) ? ShiftMask : 0)
4877 | ((state & mod_ctrl) ? ControlMask : 0)
4878 | ((state & mod_meta) ? dpyinfo->meta_mod_mask : 0));
4881 /* Convert a keysym to its name. */
4883 char *
4884 x_get_keysym_name (int keysym)
4886 char *value;
4888 block_input ();
4889 value = XKeysymToString (keysym);
4890 unblock_input ();
4892 return value;
4895 /* Mouse clicks and mouse movement. Rah.
4897 Formerly, we used PointerMotionHintMask (in standard_event_mask)
4898 so that we would have to call XQueryPointer after each MotionNotify
4899 event to ask for another such event. However, this made mouse tracking
4900 slow, and there was a bug that made it eventually stop.
4902 Simply asking for MotionNotify all the time seems to work better.
4904 In order to avoid asking for motion events and then throwing most
4905 of them away or busy-polling the server for mouse positions, we ask
4906 the server for pointer motion hints. This means that we get only
4907 one event per group of mouse movements. "Groups" are delimited by
4908 other kinds of events (focus changes and button clicks, for
4909 example), or by XQueryPointer calls; when one of these happens, we
4910 get another MotionNotify event the next time the mouse moves. This
4911 is at least as efficient as getting motion events when mouse
4912 tracking is on, and I suspect only negligibly worse when tracking
4913 is off. */
4915 /* Prepare a mouse-event in *RESULT for placement in the input queue.
4917 If the event is a button press, then note that we have grabbed
4918 the mouse. */
4920 static Lisp_Object
4921 construct_mouse_click (struct input_event *result,
4922 const XButtonEvent *event,
4923 struct frame *f)
4925 /* Make the event type NO_EVENT; we'll change that when we decide
4926 otherwise. */
4927 result->kind = MOUSE_CLICK_EVENT;
4928 result->code = event->button - Button1;
4929 result->timestamp = event->time;
4930 result->modifiers = (x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO (f),
4931 event->state)
4932 | (event->type == ButtonRelease
4933 ? up_modifier
4934 : down_modifier));
4936 XSETINT (result->x, event->x);
4937 XSETINT (result->y, event->y);
4938 XSETFRAME (result->frame_or_window, f);
4939 result->arg = Qnil;
4940 return Qnil;
4943 /* Function to report a mouse movement to the mainstream Emacs code.
4944 The input handler calls this.
4946 We have received a mouse movement event, which is given in *event.
4947 If the mouse is over a different glyph than it was last time, tell
4948 the mainstream emacs code by setting mouse_moved. If not, ask for
4949 another motion event, so we can check again the next time it moves. */
4951 static bool
4952 note_mouse_movement (struct frame *frame, const XMotionEvent *event)
4954 XRectangle *r;
4955 struct x_display_info *dpyinfo;
4957 if (!FRAME_X_OUTPUT (frame))
4958 return false;
4960 dpyinfo = FRAME_DISPLAY_INFO (frame);
4961 dpyinfo->last_mouse_movement_time = event->time;
4962 dpyinfo->last_mouse_motion_frame = frame;
4963 dpyinfo->last_mouse_motion_x = event->x;
4964 dpyinfo->last_mouse_motion_y = event->y;
4966 if (event->window != FRAME_X_WINDOW (frame))
4968 frame->mouse_moved = true;
4969 dpyinfo->last_mouse_scroll_bar = NULL;
4970 note_mouse_highlight (frame, -1, -1);
4971 dpyinfo->last_mouse_glyph_frame = NULL;
4972 return true;
4976 /* Has the mouse moved off the glyph it was on at the last sighting? */
4977 r = &dpyinfo->last_mouse_glyph;
4978 if (frame != dpyinfo->last_mouse_glyph_frame
4979 || event->x < r->x || event->x >= r->x + r->width
4980 || event->y < r->y || event->y >= r->y + r->height)
4982 frame->mouse_moved = true;
4983 dpyinfo->last_mouse_scroll_bar = NULL;
4984 note_mouse_highlight (frame, event->x, event->y);
4985 /* Remember which glyph we're now on. */
4986 remember_mouse_glyph (frame, event->x, event->y, r);
4987 dpyinfo->last_mouse_glyph_frame = frame;
4988 return true;
4991 return false;
4994 /* Return the current position of the mouse.
4995 *FP should be a frame which indicates which display to ask about.
4997 If the mouse movement started in a scroll bar, set *FP, *BAR_WINDOW,
4998 and *PART to the frame, window, and scroll bar part that the mouse
4999 is over. Set *X and *Y to the portion and whole of the mouse's
5000 position on the scroll bar.
5002 If the mouse movement started elsewhere, set *FP to the frame the
5003 mouse is on, *BAR_WINDOW to nil, and *X and *Y to the character cell
5004 the mouse is over.
5006 Set *TIMESTAMP to the server time-stamp for the time at which the mouse
5007 was at this position.
5009 Don't store anything if we don't have a valid set of values to report.
5011 This clears the mouse_moved flag, so we can wait for the next mouse
5012 movement. */
5014 static void
5015 XTmouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
5016 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
5017 Time *timestamp)
5019 struct frame *f1;
5020 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (*fp);
5022 block_input ();
5024 if (dpyinfo->last_mouse_scroll_bar && insist == 0)
5026 struct scroll_bar *bar = dpyinfo->last_mouse_scroll_bar;
5028 if (bar->horizontal)
5029 x_horizontal_scroll_bar_report_motion (fp, bar_window, part, x, y, timestamp);
5030 else
5031 x_scroll_bar_report_motion (fp, bar_window, part, x, y, timestamp);
5033 else
5035 Window root;
5036 int root_x, root_y;
5038 Window dummy_window;
5039 int dummy;
5041 Lisp_Object frame, tail;
5043 /* Clear the mouse-moved flag for every frame on this display. */
5044 FOR_EACH_FRAME (tail, frame)
5045 if (FRAME_X_P (XFRAME (frame))
5046 && FRAME_X_DISPLAY (XFRAME (frame)) == FRAME_X_DISPLAY (*fp))
5047 XFRAME (frame)->mouse_moved = false;
5049 dpyinfo->last_mouse_scroll_bar = NULL;
5051 /* Figure out which root window we're on. */
5052 XQueryPointer (FRAME_X_DISPLAY (*fp),
5053 DefaultRootWindow (FRAME_X_DISPLAY (*fp)),
5055 /* The root window which contains the pointer. */
5056 &root,
5058 /* Trash which we can't trust if the pointer is on
5059 a different screen. */
5060 &dummy_window,
5062 /* The position on that root window. */
5063 &root_x, &root_y,
5065 /* More trash we can't trust. */
5066 &dummy, &dummy,
5068 /* Modifier keys and pointer buttons, about which
5069 we don't care. */
5070 (unsigned int *) &dummy);
5072 /* Now we have a position on the root; find the innermost window
5073 containing the pointer. */
5075 Window win, child;
5076 #ifdef USE_GTK
5077 Window first_win = 0;
5078 #endif
5079 int win_x, win_y;
5080 int parent_x = 0, parent_y = 0;
5082 win = root;
5084 /* XTranslateCoordinates can get errors if the window
5085 structure is changing at the same time this function
5086 is running. So at least we must not crash from them. */
5088 x_catch_errors (FRAME_X_DISPLAY (*fp));
5090 if (x_mouse_grabbed (dpyinfo))
5092 /* If mouse was grabbed on a frame, give coords for that frame
5093 even if the mouse is now outside it. */
5094 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
5096 /* From-window. */
5097 root,
5099 /* To-window. */
5100 FRAME_X_WINDOW (dpyinfo->last_mouse_frame),
5102 /* From-position, to-position. */
5103 root_x, root_y, &win_x, &win_y,
5105 /* Child of win. */
5106 &child);
5107 f1 = dpyinfo->last_mouse_frame;
5109 else
5111 while (true)
5113 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
5115 /* From-window, to-window. */
5116 root, win,
5118 /* From-position, to-position. */
5119 root_x, root_y, &win_x, &win_y,
5121 /* Child of win. */
5122 &child);
5124 if (child == None || child == win)
5126 #ifdef USE_GTK
5127 /* On GTK we have not inspected WIN yet. If it has
5128 a frame and that frame has a parent, use it. */
5129 struct frame *f = x_window_to_frame (dpyinfo, win);
5131 if (f && FRAME_PARENT_FRAME (f))
5132 first_win = win;
5133 #endif
5134 break;
5136 #ifdef USE_GTK
5137 /* We don't wan't to know the innermost window. We
5138 want the edit window. For non-Gtk+ the innermost
5139 window is the edit window. For Gtk+ it might not
5140 be. It might be the tool bar for example. */
5141 if (x_window_to_frame (dpyinfo, win))
5142 /* But don't hurry. We might find a child frame
5143 beneath. */
5144 first_win = win;
5145 #endif
5146 win = child;
5147 parent_x = win_x;
5148 parent_y = win_y;
5151 #ifdef USE_GTK
5152 if (first_win)
5153 win = first_win;
5154 #endif
5156 /* Now we know that:
5157 win is the innermost window containing the pointer
5158 (XTC says it has no child containing the pointer),
5159 win_x and win_y are the pointer's position in it
5160 (XTC did this the last time through), and
5161 parent_x and parent_y are the pointer's position in win's parent.
5162 (They are what win_x and win_y were when win was child.
5163 If win is the root window, it has no parent, and
5164 parent_{x,y} are invalid, but that's okay, because we'll
5165 never use them in that case.) */
5167 #ifdef USE_GTK
5168 /* We don't wan't to know the innermost window. We
5169 want the edit window. */
5170 f1 = x_window_to_frame (dpyinfo, win);
5171 #else
5172 /* Is win one of our frames? */
5173 f1 = x_any_window_to_frame (dpyinfo, win);
5174 #endif
5176 #ifdef USE_X_TOOLKIT
5177 /* If we end up with the menu bar window, say it's not
5178 on the frame. */
5179 if (f1 != NULL
5180 && f1->output_data.x->menubar_widget
5181 && win == XtWindow (f1->output_data.x->menubar_widget))
5182 f1 = NULL;
5183 #endif /* USE_X_TOOLKIT */
5186 if (x_had_errors_p (FRAME_X_DISPLAY (*fp)))
5187 f1 = 0;
5189 x_uncatch_errors_after_check ();
5191 /* If not, is it one of our scroll bars? */
5192 if (! f1)
5194 struct scroll_bar *bar;
5196 bar = x_window_to_scroll_bar (FRAME_X_DISPLAY (*fp), win, 2);
5198 if (bar)
5200 f1 = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5201 win_x = parent_x;
5202 win_y = parent_y;
5206 if (f1 == 0 && insist > 0)
5207 f1 = SELECTED_FRAME ();
5209 if (f1)
5211 /* Ok, we found a frame. Store all the values.
5212 last_mouse_glyph is a rectangle used to reduce the
5213 generation of mouse events. To not miss any motion
5214 events, we must divide the frame into rectangles of the
5215 size of the smallest character that could be displayed
5216 on it, i.e. into the same rectangles that matrices on
5217 the frame are divided into. */
5219 /* FIXME: what if F1 is not an X frame? */
5220 dpyinfo = FRAME_DISPLAY_INFO (f1);
5221 remember_mouse_glyph (f1, win_x, win_y, &dpyinfo->last_mouse_glyph);
5222 dpyinfo->last_mouse_glyph_frame = f1;
5224 *bar_window = Qnil;
5225 *part = 0;
5226 *fp = f1;
5227 XSETINT (*x, win_x);
5228 XSETINT (*y, win_y);
5229 *timestamp = dpyinfo->last_mouse_movement_time;
5234 unblock_input ();
5239 /***********************************************************************
5240 Scroll bars
5241 ***********************************************************************/
5243 /* Scroll bar support. */
5245 /* Given an X window ID and a DISPLAY, find the struct scroll_bar which
5246 manages it.
5247 This can be called in GC, so we have to make sure to strip off mark
5248 bits. */
5250 static struct scroll_bar *
5251 x_window_to_scroll_bar (Display *display, Window window_id, int type)
5253 Lisp_Object tail, frame;
5255 #if defined (USE_GTK) && defined (USE_TOOLKIT_SCROLL_BARS)
5256 window_id = (Window) xg_get_scroll_id_for_window (display, window_id);
5257 #endif /* USE_GTK && USE_TOOLKIT_SCROLL_BARS */
5259 FOR_EACH_FRAME (tail, frame)
5261 Lisp_Object bar, condemned;
5263 if (! FRAME_X_P (XFRAME (frame)))
5264 continue;
5266 /* Scan this frame's scroll bar list for a scroll bar with the
5267 right window ID. */
5268 condemned = FRAME_CONDEMNED_SCROLL_BARS (XFRAME (frame));
5269 for (bar = FRAME_SCROLL_BARS (XFRAME (frame));
5270 /* This trick allows us to search both the ordinary and
5271 condemned scroll bar lists with one loop. */
5272 ! NILP (bar) || (bar = condemned,
5273 condemned = Qnil,
5274 ! NILP (bar));
5275 bar = XSCROLL_BAR (bar)->next)
5276 if (XSCROLL_BAR (bar)->x_window == window_id
5277 && FRAME_X_DISPLAY (XFRAME (frame)) == display
5278 && (type = 2
5279 || (type == 1 && XSCROLL_BAR (bar)->horizontal)
5280 || (type == 0 && !XSCROLL_BAR (bar)->horizontal)))
5281 return XSCROLL_BAR (bar);
5284 return NULL;
5288 #if defined USE_LUCID
5290 /* Return the Lucid menu bar WINDOW is part of. Return null
5291 if WINDOW is not part of a menu bar. */
5293 static Widget
5294 x_window_to_menu_bar (Window window)
5296 Lisp_Object tail, frame;
5298 FOR_EACH_FRAME (tail, frame)
5299 if (FRAME_X_P (XFRAME (frame)))
5301 Widget menu_bar = XFRAME (frame)->output_data.x->menubar_widget;
5303 if (menu_bar && xlwmenu_window_p (menu_bar, window))
5304 return menu_bar;
5306 return NULL;
5309 #endif /* USE_LUCID */
5312 /************************************************************************
5313 Toolkit scroll bars
5314 ************************************************************************/
5316 #ifdef USE_TOOLKIT_SCROLL_BARS
5318 static void x_send_scroll_bar_event (Lisp_Object, enum scroll_bar_part,
5319 int, int, bool);
5321 /* Lisp window being scrolled. Set when starting to interact with
5322 a toolkit scroll bar, reset to nil when ending the interaction. */
5324 static Lisp_Object window_being_scrolled;
5326 /* Whether this is an Xaw with arrow-scrollbars. This should imply
5327 that movements of 1/20 of the screen size are mapped to up/down. */
5329 #ifndef USE_GTK
5330 /* Id of action hook installed for scroll bars. */
5332 static XtActionHookId action_hook_id;
5333 static XtActionHookId horizontal_action_hook_id;
5335 static Boolean xaw3d_arrow_scroll;
5337 /* Whether the drag scrolling maintains the mouse at the top of the
5338 thumb. If not, resizing the thumb needs to be done more carefully
5339 to avoid jerkiness. */
5341 static Boolean xaw3d_pick_top;
5343 /* Action hook installed via XtAppAddActionHook when toolkit scroll
5344 bars are used.. The hook is responsible for detecting when
5345 the user ends an interaction with the scroll bar, and generates
5346 a `end-scroll' SCROLL_BAR_CLICK_EVENT' event if so. */
5348 static void
5349 xt_action_hook (Widget widget, XtPointer client_data, String action_name,
5350 XEvent *event, String *params, Cardinal *num_params)
5352 bool scroll_bar_p;
5353 const char *end_action;
5355 #ifdef USE_MOTIF
5356 scroll_bar_p = XmIsScrollBar (widget);
5357 end_action = "Release";
5358 #else /* !USE_MOTIF i.e. use Xaw */
5359 scroll_bar_p = XtIsSubclass (widget, scrollbarWidgetClass);
5360 end_action = "EndScroll";
5361 #endif /* USE_MOTIF */
5363 if (scroll_bar_p
5364 && strcmp (action_name, end_action) == 0
5365 && WINDOWP (window_being_scrolled))
5367 struct window *w;
5368 struct scroll_bar *bar;
5370 x_send_scroll_bar_event (window_being_scrolled,
5371 scroll_bar_end_scroll, 0, 0, false);
5372 w = XWINDOW (window_being_scrolled);
5373 bar = XSCROLL_BAR (w->vertical_scroll_bar);
5375 if (bar->dragging != -1)
5377 bar->dragging = -1;
5378 /* The thumb size is incorrect while dragging: fix it. */
5379 set_vertical_scroll_bar (w);
5381 window_being_scrolled = Qnil;
5382 #if defined (USE_LUCID)
5383 bar->last_seen_part = scroll_bar_nowhere;
5384 #endif
5385 /* Xt timeouts no longer needed. */
5386 toolkit_scroll_bar_interaction = false;
5391 static void
5392 xt_horizontal_action_hook (Widget widget, XtPointer client_data, String action_name,
5393 XEvent *event, String *params, Cardinal *num_params)
5395 bool scroll_bar_p;
5396 const char *end_action;
5398 #ifdef USE_MOTIF
5399 scroll_bar_p = XmIsScrollBar (widget);
5400 end_action = "Release";
5401 #else /* !USE_MOTIF i.e. use Xaw */
5402 scroll_bar_p = XtIsSubclass (widget, scrollbarWidgetClass);
5403 end_action = "EndScroll";
5404 #endif /* USE_MOTIF */
5406 if (scroll_bar_p
5407 && strcmp (action_name, end_action) == 0
5408 && WINDOWP (window_being_scrolled))
5410 struct window *w;
5411 struct scroll_bar *bar;
5413 x_send_scroll_bar_event (window_being_scrolled,
5414 scroll_bar_end_scroll, 0, 0, true);
5415 w = XWINDOW (window_being_scrolled);
5416 if (!NILP (w->horizontal_scroll_bar))
5418 bar = XSCROLL_BAR (w->horizontal_scroll_bar);
5419 if (bar->dragging != -1)
5421 bar->dragging = -1;
5422 /* The thumb size is incorrect while dragging: fix it. */
5423 set_horizontal_scroll_bar (w);
5425 window_being_scrolled = Qnil;
5426 #if defined (USE_LUCID)
5427 bar->last_seen_part = scroll_bar_nowhere;
5428 #endif
5429 /* Xt timeouts no longer needed. */
5430 toolkit_scroll_bar_interaction = false;
5434 #endif /* not USE_GTK */
5436 /* Send a client message with message type Xatom_Scrollbar for a
5437 scroll action to the frame of WINDOW. PART is a value identifying
5438 the part of the scroll bar that was clicked on. PORTION is the
5439 amount to scroll of a whole of WHOLE. */
5441 static void
5442 x_send_scroll_bar_event (Lisp_Object window, enum scroll_bar_part part,
5443 int portion, int whole, bool horizontal)
5445 XEvent event;
5446 XClientMessageEvent *ev = &event.xclient;
5447 struct window *w = XWINDOW (window);
5448 struct frame *f = XFRAME (w->frame);
5449 intptr_t iw = (intptr_t) w;
5450 verify (INTPTR_WIDTH <= 64);
5451 int sign_shift = INTPTR_WIDTH - 32;
5453 block_input ();
5455 /* Construct a ClientMessage event to send to the frame. */
5456 ev->type = ClientMessage;
5457 ev->message_type = (horizontal
5458 ? FRAME_DISPLAY_INFO (f)->Xatom_Horizontal_Scrollbar
5459 : FRAME_DISPLAY_INFO (f)->Xatom_Scrollbar);
5460 ev->display = FRAME_X_DISPLAY (f);
5461 ev->window = FRAME_X_WINDOW (f);
5462 ev->format = 32;
5464 /* A 32-bit X client on a 64-bit X server can pass a window pointer
5465 as-is. A 64-bit client on a 32-bit X server is in trouble
5466 because a pointer does not fit and would be truncated while
5467 passing through the server. So use two slots and hope that X12
5468 will resolve such issues someday. */
5469 ev->data.l[0] = iw >> 31 >> 1;
5470 ev->data.l[1] = sign_shift <= 0 ? iw : iw << sign_shift >> sign_shift;
5471 ev->data.l[2] = part;
5472 ev->data.l[3] = portion;
5473 ev->data.l[4] = whole;
5475 /* Make Xt timeouts work while the scroll bar is active. */
5476 #ifdef USE_X_TOOLKIT
5477 toolkit_scroll_bar_interaction = true;
5478 x_activate_timeout_atimer ();
5479 #endif
5481 /* Setting the event mask to zero means that the message will
5482 be sent to the client that created the window, and if that
5483 window no longer exists, no event will be sent. */
5484 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), False, 0, &event);
5485 unblock_input ();
5489 /* Transform a scroll bar ClientMessage EVENT to an Emacs input event
5490 in *IEVENT. */
5492 static void
5493 x_scroll_bar_to_input_event (const XEvent *event,
5494 struct input_event *ievent)
5496 const XClientMessageEvent *ev = &event->xclient;
5497 Lisp_Object window;
5498 struct window *w;
5500 /* See the comment in the function above. */
5501 intptr_t iw0 = ev->data.l[0];
5502 intptr_t iw1 = ev->data.l[1];
5503 intptr_t iw = (iw0 << 31 << 1) + (iw1 & 0xffffffffu);
5504 w = (struct window *) iw;
5506 XSETWINDOW (window, w);
5508 ievent->kind = SCROLL_BAR_CLICK_EVENT;
5509 ievent->frame_or_window = window;
5510 ievent->arg = Qnil;
5511 #ifdef USE_GTK
5512 ievent->timestamp = CurrentTime;
5513 #else
5514 ievent->timestamp =
5515 XtLastTimestampProcessed (FRAME_X_DISPLAY (XFRAME (w->frame)));
5516 #endif
5517 ievent->code = 0;
5518 ievent->part = ev->data.l[2];
5519 ievent->x = make_number (ev->data.l[3]);
5520 ievent->y = make_number (ev->data.l[4]);
5521 ievent->modifiers = 0;
5524 /* Transform a horizontal scroll bar ClientMessage EVENT to an Emacs
5525 input event in *IEVENT. */
5527 static void
5528 x_horizontal_scroll_bar_to_input_event (const XEvent *event,
5529 struct input_event *ievent)
5531 const XClientMessageEvent *ev = &event->xclient;
5532 Lisp_Object window;
5533 struct window *w;
5535 /* See the comment in the function above. */
5536 intptr_t iw0 = ev->data.l[0];
5537 intptr_t iw1 = ev->data.l[1];
5538 intptr_t iw = (iw0 << 31 << 1) + (iw1 & 0xffffffffu);
5539 w = (struct window *) iw;
5541 XSETWINDOW (window, w);
5543 ievent->kind = HORIZONTAL_SCROLL_BAR_CLICK_EVENT;
5544 ievent->frame_or_window = window;
5545 ievent->arg = Qnil;
5546 #ifdef USE_GTK
5547 ievent->timestamp = CurrentTime;
5548 #else
5549 ievent->timestamp =
5550 XtLastTimestampProcessed (FRAME_X_DISPLAY (XFRAME (w->frame)));
5551 #endif
5552 ievent->code = 0;
5553 ievent->part = ev->data.l[2];
5554 ievent->x = make_number (ev->data.l[3]);
5555 ievent->y = make_number (ev->data.l[4]);
5556 ievent->modifiers = 0;
5560 #ifdef USE_MOTIF
5562 /* Minimum and maximum values used for Motif scroll bars. */
5564 #define XM_SB_MAX 10000000
5566 /* Scroll bar callback for Motif scroll bars. WIDGET is the scroll
5567 bar widget. CLIENT_DATA is a pointer to the scroll_bar structure.
5568 CALL_DATA is a pointer to a XmScrollBarCallbackStruct. */
5570 static void
5571 xm_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
5573 struct scroll_bar *bar = client_data;
5574 XmScrollBarCallbackStruct *cs = call_data;
5575 enum scroll_bar_part part = scroll_bar_nowhere;
5576 bool horizontal = bar->horizontal;
5577 int whole = 0, portion = 0;
5579 switch (cs->reason)
5581 case XmCR_DECREMENT:
5582 bar->dragging = -1;
5583 part = horizontal ? scroll_bar_left_arrow : scroll_bar_up_arrow;
5584 break;
5586 case XmCR_INCREMENT:
5587 bar->dragging = -1;
5588 part = horizontal ? scroll_bar_right_arrow : scroll_bar_down_arrow;
5589 break;
5591 case XmCR_PAGE_DECREMENT:
5592 bar->dragging = -1;
5593 part = horizontal ? scroll_bar_before_handle : scroll_bar_above_handle;
5594 break;
5596 case XmCR_PAGE_INCREMENT:
5597 bar->dragging = -1;
5598 part = horizontal ? scroll_bar_after_handle : scroll_bar_below_handle;
5599 break;
5601 case XmCR_TO_TOP:
5602 bar->dragging = -1;
5603 part = horizontal ? scroll_bar_to_leftmost : scroll_bar_to_top;
5604 break;
5606 case XmCR_TO_BOTTOM:
5607 bar->dragging = -1;
5608 part = horizontal ? scroll_bar_to_rightmost : scroll_bar_to_bottom;
5609 break;
5611 case XmCR_DRAG:
5613 int slider_size;
5615 block_input ();
5616 XtVaGetValues (widget, XmNsliderSize, &slider_size, NULL);
5617 unblock_input ();
5619 if (horizontal)
5621 portion = bar->whole * ((float)cs->value / XM_SB_MAX);
5622 whole = bar->whole * ((float)(XM_SB_MAX - slider_size) / XM_SB_MAX);
5623 portion = min (portion, whole);
5624 part = scroll_bar_horizontal_handle;
5626 else
5628 whole = XM_SB_MAX - slider_size;
5629 portion = min (cs->value, whole);
5630 part = scroll_bar_handle;
5633 bar->dragging = cs->value;
5635 break;
5637 case XmCR_VALUE_CHANGED:
5638 break;
5641 if (part != scroll_bar_nowhere)
5643 window_being_scrolled = bar->window;
5644 x_send_scroll_bar_event (bar->window, part, portion, whole,
5645 bar->horizontal);
5649 #elif defined USE_GTK
5651 /* Scroll bar callback for GTK scroll bars. WIDGET is the scroll
5652 bar widget. DATA is a pointer to the scroll_bar structure. */
5654 static gboolean
5655 xg_scroll_callback (GtkRange *range,
5656 GtkScrollType scroll,
5657 gdouble value,
5658 gpointer user_data)
5660 int whole = 0, portion = 0;
5661 struct scroll_bar *bar = user_data;
5662 enum scroll_bar_part part = scroll_bar_nowhere;
5663 GtkAdjustment *adj = GTK_ADJUSTMENT (gtk_range_get_adjustment (range));
5664 struct frame *f = g_object_get_data (G_OBJECT (range), XG_FRAME_DATA);
5666 if (xg_ignore_gtk_scrollbar) return false;
5668 switch (scroll)
5670 case GTK_SCROLL_JUMP:
5671 /* Buttons 1 2 or 3 must be grabbed. */
5672 if (FRAME_DISPLAY_INFO (f)->grabbed != 0
5673 && FRAME_DISPLAY_INFO (f)->grabbed < (1 << 4))
5675 if (bar->horizontal)
5677 part = scroll_bar_horizontal_handle;
5678 whole = (int)(gtk_adjustment_get_upper (adj) -
5679 gtk_adjustment_get_page_size (adj));
5680 portion = min ((int)value, whole);
5681 bar->dragging = portion;
5683 else
5685 part = scroll_bar_handle;
5686 whole = gtk_adjustment_get_upper (adj) -
5687 gtk_adjustment_get_page_size (adj);
5688 portion = min ((int)value, whole);
5689 bar->dragging = portion;
5692 break;
5693 case GTK_SCROLL_STEP_BACKWARD:
5694 part = (bar->horizontal
5695 ? scroll_bar_left_arrow : scroll_bar_up_arrow);
5696 bar->dragging = -1;
5697 break;
5698 case GTK_SCROLL_STEP_FORWARD:
5699 part = (bar->horizontal
5700 ? scroll_bar_right_arrow : scroll_bar_down_arrow);
5701 bar->dragging = -1;
5702 break;
5703 case GTK_SCROLL_PAGE_BACKWARD:
5704 part = (bar->horizontal
5705 ? scroll_bar_before_handle : scroll_bar_above_handle);
5706 bar->dragging = -1;
5707 break;
5708 case GTK_SCROLL_PAGE_FORWARD:
5709 part = (bar->horizontal
5710 ? scroll_bar_after_handle : scroll_bar_below_handle);
5711 bar->dragging = -1;
5712 break;
5713 default:
5714 break;
5717 if (part != scroll_bar_nowhere)
5719 window_being_scrolled = bar->window;
5720 x_send_scroll_bar_event (bar->window, part, portion, whole,
5721 bar->horizontal);
5724 return false;
5727 /* Callback for button release. Sets dragging to -1 when dragging is done. */
5729 static gboolean
5730 xg_end_scroll_callback (GtkWidget *widget,
5731 GdkEventButton *event,
5732 gpointer user_data)
5734 struct scroll_bar *bar = user_data;
5735 bar->dragging = -1;
5736 if (WINDOWP (window_being_scrolled))
5738 x_send_scroll_bar_event (window_being_scrolled,
5739 scroll_bar_end_scroll, 0, 0, bar->horizontal);
5740 window_being_scrolled = Qnil;
5743 return false;
5747 #else /* not USE_GTK and not USE_MOTIF */
5749 /* Xaw scroll bar callback. Invoked when the thumb is dragged.
5750 WIDGET is the scroll bar widget. CLIENT_DATA is a pointer to the
5751 scroll bar struct. CALL_DATA is a pointer to a float saying where
5752 the thumb is. */
5754 static void
5755 xaw_jump_callback (Widget widget, XtPointer client_data, XtPointer call_data)
5757 struct scroll_bar *bar = client_data;
5758 float *top_addr = call_data;
5759 float top = *top_addr;
5760 float shown;
5761 int whole, portion, height, width;
5762 enum scroll_bar_part part;
5763 bool horizontal = bar->horizontal;
5765 if (horizontal)
5767 /* Get the size of the thumb, a value between 0 and 1. */
5768 block_input ();
5769 XtVaGetValues (widget, XtNshown, &shown, XtNwidth, &width, NULL);
5770 unblock_input ();
5772 if (shown < 1)
5774 whole = bar->whole - (shown * bar->whole);
5775 portion = min (top * bar->whole, whole);
5777 else
5779 whole = bar->whole;
5780 portion = 0;
5783 part = scroll_bar_horizontal_handle;
5785 else
5787 /* Get the size of the thumb, a value between 0 and 1. */
5788 block_input ();
5789 XtVaGetValues (widget, XtNshown, &shown, XtNheight, &height, NULL);
5790 unblock_input ();
5792 whole = 10000000;
5793 portion = shown < 1 ? top * whole : 0;
5795 if (shown < 1 && (eabs (top + shown - 1) < 1.0f / height))
5796 /* Some derivatives of Xaw refuse to shrink the thumb when you reach
5797 the bottom, so we force the scrolling whenever we see that we're
5798 too close to the bottom (in x_set_toolkit_scroll_bar_thumb
5799 we try to ensure that we always stay two pixels away from the
5800 bottom). */
5801 part = scroll_bar_down_arrow;
5802 else
5803 part = scroll_bar_handle;
5806 window_being_scrolled = bar->window;
5807 bar->dragging = portion;
5808 bar->last_seen_part = part;
5809 x_send_scroll_bar_event (bar->window, part, portion, whole, bar->horizontal);
5813 /* Xaw scroll bar callback. Invoked for incremental scrolling.,
5814 i.e. line or page up or down. WIDGET is the Xaw scroll bar
5815 widget. CLIENT_DATA is a pointer to the scroll_bar structure for
5816 the scroll bar. CALL_DATA is an integer specifying the action that
5817 has taken place. Its magnitude is in the range 0..height of the
5818 scroll bar. Negative values mean scroll towards buffer start.
5819 Values < height of scroll bar mean line-wise movement. */
5821 static void
5822 xaw_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
5824 struct scroll_bar *bar = client_data;
5825 /* The position really is stored cast to a pointer. */
5826 int position = (intptr_t) call_data;
5827 Dimension height, width;
5828 enum scroll_bar_part part;
5830 if (bar->horizontal)
5832 /* Get the width of the scroll bar. */
5833 block_input ();
5834 XtVaGetValues (widget, XtNwidth, &width, NULL);
5835 unblock_input ();
5837 if (eabs (position) >= width)
5838 part = (position < 0) ? scroll_bar_before_handle : scroll_bar_after_handle;
5840 /* If Xaw3d was compiled with ARROW_SCROLLBAR,
5841 it maps line-movement to call_data = max(5, height/20). */
5842 else if (xaw3d_arrow_scroll && eabs (position) <= max (5, width / 20))
5843 part = (position < 0) ? scroll_bar_left_arrow : scroll_bar_right_arrow;
5844 else
5845 part = scroll_bar_move_ratio;
5847 window_being_scrolled = bar->window;
5848 bar->dragging = -1;
5849 bar->last_seen_part = part;
5850 x_send_scroll_bar_event (bar->window, part, position, width,
5851 bar->horizontal);
5853 else
5856 /* Get the height of the scroll bar. */
5857 block_input ();
5858 XtVaGetValues (widget, XtNheight, &height, NULL);
5859 unblock_input ();
5861 if (eabs (position) >= height)
5862 part = (position < 0) ? scroll_bar_above_handle : scroll_bar_below_handle;
5864 /* If Xaw3d was compiled with ARROW_SCROLLBAR,
5865 it maps line-movement to call_data = max(5, height/20). */
5866 else if (xaw3d_arrow_scroll && eabs (position) <= max (5, height / 20))
5867 part = (position < 0) ? scroll_bar_up_arrow : scroll_bar_down_arrow;
5868 else
5869 part = scroll_bar_move_ratio;
5871 window_being_scrolled = bar->window;
5872 bar->dragging = -1;
5873 bar->last_seen_part = part;
5874 x_send_scroll_bar_event (bar->window, part, position, height,
5875 bar->horizontal);
5879 #endif /* not USE_GTK and not USE_MOTIF */
5881 #define SCROLL_BAR_NAME "verticalScrollBar"
5882 #define SCROLL_BAR_HORIZONTAL_NAME "horizontalScrollBar"
5884 /* Create the widget for scroll bar BAR on frame F. Record the widget
5885 and X window of the scroll bar in BAR. */
5887 #ifdef USE_GTK
5888 static void
5889 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
5891 const char *scroll_bar_name = SCROLL_BAR_NAME;
5893 block_input ();
5894 xg_create_scroll_bar (f, bar, G_CALLBACK (xg_scroll_callback),
5895 G_CALLBACK (xg_end_scroll_callback),
5896 scroll_bar_name);
5897 unblock_input ();
5900 static void
5901 x_create_horizontal_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
5903 const char *scroll_bar_name = SCROLL_BAR_HORIZONTAL_NAME;
5905 block_input ();
5906 xg_create_horizontal_scroll_bar (f, bar, G_CALLBACK (xg_scroll_callback),
5907 G_CALLBACK (xg_end_scroll_callback),
5908 scroll_bar_name);
5909 unblock_input ();
5912 #else /* not USE_GTK */
5914 static void
5915 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
5917 Window xwindow;
5918 Widget widget;
5919 Arg av[20];
5920 int ac = 0;
5921 const char *scroll_bar_name = SCROLL_BAR_NAME;
5922 unsigned long pixel;
5924 block_input ();
5926 #ifdef USE_MOTIF
5927 /* Set resources. Create the widget. */
5928 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
5929 XtSetArg (av[ac], XmNminimum, 0); ++ac;
5930 XtSetArg (av[ac], XmNmaximum, XM_SB_MAX); ++ac;
5931 XtSetArg (av[ac], XmNorientation, XmVERTICAL); ++ac;
5932 XtSetArg (av[ac], XmNprocessingDirection, XmMAX_ON_BOTTOM), ++ac;
5933 XtSetArg (av[ac], XmNincrement, 1); ++ac;
5934 XtSetArg (av[ac], XmNpageIncrement, 1); ++ac;
5936 pixel = f->output_data.x->scroll_bar_foreground_pixel;
5937 if (pixel != -1)
5939 XtSetArg (av[ac], XmNforeground, pixel);
5940 ++ac;
5943 pixel = f->output_data.x->scroll_bar_background_pixel;
5944 if (pixel != -1)
5946 XtSetArg (av[ac], XmNbackground, pixel);
5947 ++ac;
5950 widget = XmCreateScrollBar (f->output_data.x->edit_widget,
5951 (char *) scroll_bar_name, av, ac);
5953 /* Add one callback for everything that can happen. */
5954 XtAddCallback (widget, XmNdecrementCallback, xm_scroll_callback,
5955 (XtPointer) bar);
5956 XtAddCallback (widget, XmNdragCallback, xm_scroll_callback,
5957 (XtPointer) bar);
5958 XtAddCallback (widget, XmNincrementCallback, xm_scroll_callback,
5959 (XtPointer) bar);
5960 XtAddCallback (widget, XmNpageDecrementCallback, xm_scroll_callback,
5961 (XtPointer) bar);
5962 XtAddCallback (widget, XmNpageIncrementCallback, xm_scroll_callback,
5963 (XtPointer) bar);
5964 XtAddCallback (widget, XmNtoBottomCallback, xm_scroll_callback,
5965 (XtPointer) bar);
5966 XtAddCallback (widget, XmNtoTopCallback, xm_scroll_callback,
5967 (XtPointer) bar);
5969 /* Realize the widget. Only after that is the X window created. */
5970 XtRealizeWidget (widget);
5972 /* Set the cursor to an arrow. I didn't find a resource to do that.
5973 And I'm wondering why it hasn't an arrow cursor by default. */
5974 XDefineCursor (XtDisplay (widget), XtWindow (widget),
5975 f->output_data.x->nontext_cursor);
5977 #else /* !USE_MOTIF i.e. use Xaw */
5979 /* Set resources. Create the widget. The background of the
5980 Xaw3d scroll bar widget is a little bit light for my taste.
5981 We don't alter it here to let users change it according
5982 to their taste with `emacs*verticalScrollBar.background: xxx'. */
5983 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
5984 XtSetArg (av[ac], XtNorientation, XtorientVertical); ++ac;
5985 /* For smoother scrolling with Xaw3d -sm */
5986 /* XtSetArg (av[ac], XtNpickTop, True); ++ac; */
5988 pixel = f->output_data.x->scroll_bar_foreground_pixel;
5989 if (pixel != -1)
5991 XtSetArg (av[ac], XtNforeground, pixel);
5992 ++ac;
5995 pixel = f->output_data.x->scroll_bar_background_pixel;
5996 if (pixel != -1)
5998 XtSetArg (av[ac], XtNbackground, pixel);
5999 ++ac;
6002 /* Top/bottom shadow colors. */
6004 /* Allocate them, if necessary. */
6005 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1)
6007 pixel = f->output_data.x->scroll_bar_background_pixel;
6008 if (pixel != -1)
6010 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
6011 FRAME_X_COLORMAP (f),
6012 &pixel, 1.2, 0x8000))
6013 pixel = -1;
6014 f->output_data.x->scroll_bar_top_shadow_pixel = pixel;
6017 if (f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
6019 pixel = f->output_data.x->scroll_bar_background_pixel;
6020 if (pixel != -1)
6022 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
6023 FRAME_X_COLORMAP (f),
6024 &pixel, 0.6, 0x4000))
6025 pixel = -1;
6026 f->output_data.x->scroll_bar_bottom_shadow_pixel = pixel;
6030 #ifdef XtNbeNiceToColormap
6031 /* Tell the toolkit about them. */
6032 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1
6033 || f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
6034 /* We tried to allocate a color for the top/bottom shadow, and
6035 failed, so tell Xaw3d to use dithering instead. */
6036 /* But only if we have a small colormap. Xaw3d can allocate nice
6037 colors itself. */
6039 XtSetArg (av[ac], XtNbeNiceToColormap,
6040 DefaultDepthOfScreen (FRAME_X_SCREEN (f)) < 16);
6041 ++ac;
6043 else
6044 /* Tell what colors Xaw3d should use for the top/bottom shadow, to
6045 be more consistent with other emacs 3d colors, and since Xaw3d is
6046 not good at dealing with allocation failure. */
6048 /* This tells Xaw3d to use real colors instead of dithering for
6049 the shadows. */
6050 XtSetArg (av[ac], XtNbeNiceToColormap, False);
6051 ++ac;
6053 /* Specify the colors. */
6054 pixel = f->output_data.x->scroll_bar_top_shadow_pixel;
6055 if (pixel != -1)
6057 XtSetArg (av[ac], XtNtopShadowPixel, pixel);
6058 ++ac;
6060 pixel = f->output_data.x->scroll_bar_bottom_shadow_pixel;
6061 if (pixel != -1)
6063 XtSetArg (av[ac], XtNbottomShadowPixel, pixel);
6064 ++ac;
6067 #endif
6069 widget = XtCreateWidget (scroll_bar_name, scrollbarWidgetClass,
6070 f->output_data.x->edit_widget, av, ac);
6073 char const *initial = "";
6074 char const *val = initial;
6075 XtVaGetValues (widget, XtNscrollVCursor, (XtPointer) &val,
6076 #ifdef XtNarrowScrollbars
6077 XtNarrowScrollbars, (XtPointer) &xaw3d_arrow_scroll,
6078 #endif
6079 XtNpickTop, (XtPointer) &xaw3d_pick_top, NULL);
6080 if (xaw3d_arrow_scroll || val == initial)
6081 { /* ARROW_SCROLL */
6082 xaw3d_arrow_scroll = True;
6083 /* Isn't that just a personal preference ? --Stef */
6084 XtVaSetValues (widget, XtNcursorName, "top_left_arrow", NULL);
6088 /* Define callbacks. */
6089 XtAddCallback (widget, XtNjumpProc, xaw_jump_callback, (XtPointer) bar);
6090 XtAddCallback (widget, XtNscrollProc, xaw_scroll_callback,
6091 (XtPointer) bar);
6093 /* Realize the widget. Only after that is the X window created. */
6094 XtRealizeWidget (widget);
6096 #endif /* !USE_MOTIF */
6098 /* Install an action hook that lets us detect when the user
6099 finishes interacting with a scroll bar. */
6100 if (action_hook_id == 0)
6101 action_hook_id = XtAppAddActionHook (Xt_app_con, xt_action_hook, 0);
6103 /* Remember X window and widget in the scroll bar vector. */
6104 SET_SCROLL_BAR_X_WIDGET (bar, widget);
6105 xwindow = XtWindow (widget);
6106 bar->x_window = xwindow;
6107 bar->whole = 1;
6108 bar->horizontal = false;
6110 unblock_input ();
6113 static void
6114 x_create_horizontal_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
6116 Window xwindow;
6117 Widget widget;
6118 Arg av[20];
6119 int ac = 0;
6120 const char *scroll_bar_name = SCROLL_BAR_HORIZONTAL_NAME;
6121 unsigned long pixel;
6123 block_input ();
6125 #ifdef USE_MOTIF
6126 /* Set resources. Create the widget. */
6127 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
6128 XtSetArg (av[ac], XmNminimum, 0); ++ac;
6129 XtSetArg (av[ac], XmNmaximum, XM_SB_MAX); ++ac;
6130 XtSetArg (av[ac], XmNorientation, XmHORIZONTAL); ++ac;
6131 XtSetArg (av[ac], XmNprocessingDirection, XmMAX_ON_RIGHT), ++ac;
6132 XtSetArg (av[ac], XmNincrement, 1); ++ac;
6133 XtSetArg (av[ac], XmNpageIncrement, 1); ++ac;
6135 pixel = f->output_data.x->scroll_bar_foreground_pixel;
6136 if (pixel != -1)
6138 XtSetArg (av[ac], XmNforeground, pixel);
6139 ++ac;
6142 pixel = f->output_data.x->scroll_bar_background_pixel;
6143 if (pixel != -1)
6145 XtSetArg (av[ac], XmNbackground, pixel);
6146 ++ac;
6149 widget = XmCreateScrollBar (f->output_data.x->edit_widget,
6150 (char *) scroll_bar_name, av, ac);
6152 /* Add one callback for everything that can happen. */
6153 XtAddCallback (widget, XmNdecrementCallback, xm_scroll_callback,
6154 (XtPointer) bar);
6155 XtAddCallback (widget, XmNdragCallback, xm_scroll_callback,
6156 (XtPointer) bar);
6157 XtAddCallback (widget, XmNincrementCallback, xm_scroll_callback,
6158 (XtPointer) bar);
6159 XtAddCallback (widget, XmNpageDecrementCallback, xm_scroll_callback,
6160 (XtPointer) bar);
6161 XtAddCallback (widget, XmNpageIncrementCallback, xm_scroll_callback,
6162 (XtPointer) bar);
6163 XtAddCallback (widget, XmNtoBottomCallback, xm_scroll_callback,
6164 (XtPointer) bar);
6165 XtAddCallback (widget, XmNtoTopCallback, xm_scroll_callback,
6166 (XtPointer) bar);
6168 /* Realize the widget. Only after that is the X window created. */
6169 XtRealizeWidget (widget);
6171 /* Set the cursor to an arrow. I didn't find a resource to do that.
6172 And I'm wondering why it hasn't an arrow cursor by default. */
6173 XDefineCursor (XtDisplay (widget), XtWindow (widget),
6174 f->output_data.x->nontext_cursor);
6176 #else /* !USE_MOTIF i.e. use Xaw */
6178 /* Set resources. Create the widget. The background of the
6179 Xaw3d scroll bar widget is a little bit light for my taste.
6180 We don't alter it here to let users change it according
6181 to their taste with `emacs*verticalScrollBar.background: xxx'. */
6182 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
6183 XtSetArg (av[ac], XtNorientation, XtorientHorizontal); ++ac;
6184 /* For smoother scrolling with Xaw3d -sm */
6185 /* XtSetArg (av[ac], XtNpickTop, True); ++ac; */
6187 pixel = f->output_data.x->scroll_bar_foreground_pixel;
6188 if (pixel != -1)
6190 XtSetArg (av[ac], XtNforeground, pixel);
6191 ++ac;
6194 pixel = f->output_data.x->scroll_bar_background_pixel;
6195 if (pixel != -1)
6197 XtSetArg (av[ac], XtNbackground, pixel);
6198 ++ac;
6201 /* Top/bottom shadow colors. */
6203 /* Allocate them, if necessary. */
6204 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1)
6206 pixel = f->output_data.x->scroll_bar_background_pixel;
6207 if (pixel != -1)
6209 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
6210 FRAME_X_COLORMAP (f),
6211 &pixel, 1.2, 0x8000))
6212 pixel = -1;
6213 f->output_data.x->scroll_bar_top_shadow_pixel = pixel;
6216 if (f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
6218 pixel = f->output_data.x->scroll_bar_background_pixel;
6219 if (pixel != -1)
6221 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
6222 FRAME_X_COLORMAP (f),
6223 &pixel, 0.6, 0x4000))
6224 pixel = -1;
6225 f->output_data.x->scroll_bar_bottom_shadow_pixel = pixel;
6229 #ifdef XtNbeNiceToColormap
6230 /* Tell the toolkit about them. */
6231 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1
6232 || f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
6233 /* We tried to allocate a color for the top/bottom shadow, and
6234 failed, so tell Xaw3d to use dithering instead. */
6235 /* But only if we have a small colormap. Xaw3d can allocate nice
6236 colors itself. */
6238 XtSetArg (av[ac], XtNbeNiceToColormap,
6239 DefaultDepthOfScreen (FRAME_X_SCREEN (f)) < 16);
6240 ++ac;
6242 else
6243 /* Tell what colors Xaw3d should use for the top/bottom shadow, to
6244 be more consistent with other emacs 3d colors, and since Xaw3d is
6245 not good at dealing with allocation failure. */
6247 /* This tells Xaw3d to use real colors instead of dithering for
6248 the shadows. */
6249 XtSetArg (av[ac], XtNbeNiceToColormap, False);
6250 ++ac;
6252 /* Specify the colors. */
6253 pixel = f->output_data.x->scroll_bar_top_shadow_pixel;
6254 if (pixel != -1)
6256 XtSetArg (av[ac], XtNtopShadowPixel, pixel);
6257 ++ac;
6259 pixel = f->output_data.x->scroll_bar_bottom_shadow_pixel;
6260 if (pixel != -1)
6262 XtSetArg (av[ac], XtNbottomShadowPixel, pixel);
6263 ++ac;
6266 #endif
6268 widget = XtCreateWidget (scroll_bar_name, scrollbarWidgetClass,
6269 f->output_data.x->edit_widget, av, ac);
6272 char const *initial = "";
6273 char const *val = initial;
6274 XtVaGetValues (widget, XtNscrollVCursor, (XtPointer) &val,
6275 #ifdef XtNarrowScrollbars
6276 XtNarrowScrollbars, (XtPointer) &xaw3d_arrow_scroll,
6277 #endif
6278 XtNpickTop, (XtPointer) &xaw3d_pick_top, NULL);
6279 if (xaw3d_arrow_scroll || val == initial)
6280 { /* ARROW_SCROLL */
6281 xaw3d_arrow_scroll = True;
6282 /* Isn't that just a personal preference ? --Stef */
6283 XtVaSetValues (widget, XtNcursorName, "top_left_arrow", NULL);
6287 /* Define callbacks. */
6288 XtAddCallback (widget, XtNjumpProc, xaw_jump_callback, (XtPointer) bar);
6289 XtAddCallback (widget, XtNscrollProc, xaw_scroll_callback,
6290 (XtPointer) bar);
6292 /* Realize the widget. Only after that is the X window created. */
6293 XtRealizeWidget (widget);
6295 #endif /* !USE_MOTIF */
6297 /* Install an action hook that lets us detect when the user
6298 finishes interacting with a scroll bar. */
6299 if (horizontal_action_hook_id == 0)
6300 horizontal_action_hook_id
6301 = XtAppAddActionHook (Xt_app_con, xt_horizontal_action_hook, 0);
6303 /* Remember X window and widget in the scroll bar vector. */
6304 SET_SCROLL_BAR_X_WIDGET (bar, widget);
6305 xwindow = XtWindow (widget);
6306 bar->x_window = xwindow;
6307 bar->whole = 1;
6308 bar->horizontal = true;
6310 unblock_input ();
6312 #endif /* not USE_GTK */
6315 /* Set the thumb size and position of scroll bar BAR. We are currently
6316 displaying PORTION out of a whole WHOLE, and our position POSITION. */
6318 #ifdef USE_GTK
6319 static void
6320 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position, int whole)
6322 xg_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
6325 static void
6326 x_set_toolkit_horizontal_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position, int whole)
6328 xg_set_toolkit_horizontal_scroll_bar_thumb (bar, portion, position, whole);
6331 #else /* not USE_GTK */
6332 static void
6333 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position,
6334 int whole)
6336 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6337 Widget widget = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
6338 float top, shown;
6340 block_input ();
6342 #ifdef USE_MOTIF
6344 if (scroll_bar_adjust_thumb_portion_p)
6346 /* We use an estimate of 30 chars per line rather than the real
6347 `portion' value. This has the disadvantage that the thumb size
6348 is not very representative, but it makes our life a lot easier.
6349 Otherwise, we have to constantly adjust the thumb size, which
6350 we can't always do quickly enough: while dragging, the size of
6351 the thumb might prevent the user from dragging the thumb all the
6352 way to the end. but Motif and some versions of Xaw3d don't allow
6353 updating the thumb size while dragging. Also, even if we can update
6354 its size, the update will often happen too late.
6355 If you don't believe it, check out revision 1.650 of xterm.c to see
6356 what hoops we were going through and the still poor behavior we got. */
6357 portion = WINDOW_TOTAL_LINES (XWINDOW (bar->window)) * 30;
6358 /* When the thumb is at the bottom, position == whole.
6359 So we need to increase `whole' to make space for the thumb. */
6360 whole += portion;
6363 if (whole <= 0)
6364 top = 0, shown = 1;
6365 else
6367 top = (float) position / whole;
6368 shown = (float) portion / whole;
6371 if (bar->dragging == -1)
6373 int size, value;
6375 /* Slider size. Must be in the range [1 .. MAX - MIN] where MAX
6376 is the scroll bar's maximum and MIN is the scroll bar's minimum
6377 value. */
6378 size = clip_to_bounds (1, shown * XM_SB_MAX, XM_SB_MAX);
6380 /* Position. Must be in the range [MIN .. MAX - SLIDER_SIZE]. */
6381 value = top * XM_SB_MAX;
6382 value = min (value, XM_SB_MAX - size);
6384 XmScrollBarSetValues (widget, value, size, 0, 0, False);
6386 #else /* !USE_MOTIF i.e. use Xaw */
6388 if (whole == 0)
6389 top = 0, shown = 1;
6390 else
6392 top = (float) position / whole;
6393 shown = (float) portion / whole;
6397 float old_top, old_shown;
6398 Dimension height;
6399 XtVaGetValues (widget,
6400 XtNtopOfThumb, &old_top,
6401 XtNshown, &old_shown,
6402 XtNheight, &height,
6403 NULL);
6405 /* Massage the top+shown values. */
6406 if (bar->dragging == -1 || bar->last_seen_part == scroll_bar_down_arrow)
6407 top = max (0, min (1, top));
6408 else
6409 top = old_top;
6410 #if ! defined (HAVE_XAW3D)
6411 /* With Xaw, 'top' values too closer to 1.0 may
6412 cause the thumb to disappear. Fix that. */
6413 top = min (top, 0.99f);
6414 #endif
6415 /* Keep two pixels available for moving the thumb down. */
6416 shown = max (0, min (1 - top - (2.0f / height), shown));
6417 #if ! defined (HAVE_XAW3D)
6418 /* Likewise with too small 'shown'. */
6419 shown = max (shown, 0.01f);
6420 #endif
6422 /* If the call to XawScrollbarSetThumb below doesn't seem to
6423 work, check that 'NARROWPROTO' is defined in src/config.h.
6424 If this is not so, most likely you need to fix configure. */
6425 if (top != old_top || shown != old_shown)
6427 if (bar->dragging == -1)
6428 XawScrollbarSetThumb (widget, top, shown);
6429 else
6431 /* Try to make the scrolling a tad smoother. */
6432 if (!xaw3d_pick_top)
6433 shown = min (shown, old_shown);
6435 XawScrollbarSetThumb (widget, top, shown);
6439 #endif /* !USE_MOTIF */
6441 unblock_input ();
6444 static void
6445 x_set_toolkit_horizontal_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position,
6446 int whole)
6448 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6449 Widget widget = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
6450 float top, shown;
6452 block_input ();
6454 #ifdef USE_MOTIF
6455 bar->whole = whole;
6456 shown = (float) portion / whole;
6457 top = (float) position / (whole - portion);
6459 int size = clip_to_bounds (1, shown * XM_SB_MAX, XM_SB_MAX);
6460 int value = clip_to_bounds (0, top * (XM_SB_MAX - size), XM_SB_MAX - size);
6462 XmScrollBarSetValues (widget, value, size, 0, 0, False);
6464 #else /* !USE_MOTIF i.e. use Xaw */
6465 bar->whole = whole;
6466 if (whole == 0)
6467 top = 0, shown = 1;
6468 else
6470 top = (float) position / whole;
6471 shown = (float) portion / whole;
6475 float old_top, old_shown;
6476 Dimension height;
6477 XtVaGetValues (widget,
6478 XtNtopOfThumb, &old_top,
6479 XtNshown, &old_shown,
6480 XtNheight, &height,
6481 NULL);
6483 #if false
6484 /* Massage the top+shown values. */
6485 if (bar->dragging == -1 || bar->last_seen_part == scroll_bar_down_arrow)
6486 top = max (0, min (1, top));
6487 else
6488 top = old_top;
6489 #if ! defined (HAVE_XAW3D)
6490 /* With Xaw, 'top' values too closer to 1.0 may
6491 cause the thumb to disappear. Fix that. */
6492 top = min (top, 0.99f);
6493 #endif
6494 /* Keep two pixels available for moving the thumb down. */
6495 shown = max (0, min (1 - top - (2.0f / height), shown));
6496 #if ! defined (HAVE_XAW3D)
6497 /* Likewise with too small 'shown'. */
6498 shown = max (shown, 0.01f);
6499 #endif
6500 #endif
6502 /* If the call to XawScrollbarSetThumb below doesn't seem to
6503 work, check that 'NARROWPROTO' is defined in src/config.h.
6504 If this is not so, most likely you need to fix configure. */
6505 XawScrollbarSetThumb (widget, top, shown);
6506 #if false
6507 if (top != old_top || shown != old_shown)
6509 if (bar->dragging == -1)
6510 XawScrollbarSetThumb (widget, top, shown);
6511 else
6513 /* Try to make the scrolling a tad smoother. */
6514 if (!xaw3d_pick_top)
6515 shown = min (shown, old_shown);
6517 XawScrollbarSetThumb (widget, top, shown);
6520 #endif
6522 #endif /* !USE_MOTIF */
6524 unblock_input ();
6526 #endif /* not USE_GTK */
6528 #endif /* USE_TOOLKIT_SCROLL_BARS */
6532 /************************************************************************
6533 Scroll bars, general
6534 ************************************************************************/
6536 /* Create a scroll bar and return the scroll bar vector for it. W is
6537 the Emacs window on which to create the scroll bar. TOP, LEFT,
6538 WIDTH and HEIGHT are the pixel coordinates and dimensions of the
6539 scroll bar. */
6541 static struct scroll_bar *
6542 x_scroll_bar_create (struct window *w, int top, int left,
6543 int width, int height, bool horizontal)
6545 struct frame *f = XFRAME (w->frame);
6546 struct scroll_bar *bar
6547 = ALLOCATE_PSEUDOVECTOR (struct scroll_bar, x_window, PVEC_OTHER);
6548 Lisp_Object barobj;
6550 block_input ();
6552 #ifdef USE_TOOLKIT_SCROLL_BARS
6553 if (horizontal)
6554 x_create_horizontal_toolkit_scroll_bar (f, bar);
6555 else
6556 x_create_toolkit_scroll_bar (f, bar);
6557 #else /* not USE_TOOLKIT_SCROLL_BARS */
6559 XSetWindowAttributes a;
6560 unsigned long mask;
6561 Window window;
6563 a.background_pixel = f->output_data.x->scroll_bar_background_pixel;
6564 if (a.background_pixel == -1)
6565 a.background_pixel = FRAME_BACKGROUND_PIXEL (f);
6567 a.event_mask = (ButtonPressMask | ButtonReleaseMask
6568 | ButtonMotionMask | PointerMotionHintMask
6569 | ExposureMask);
6570 a.cursor = FRAME_DISPLAY_INFO (f)->vertical_scroll_bar_cursor;
6572 mask = (CWBackPixel | CWEventMask | CWCursor);
6574 /* Clear the area of W that will serve as a scroll bar. This is
6575 for the case that a window has been split horizontally. In
6576 this case, no clear_frame is generated to reduce flickering. */
6577 if (width > 0 && window_box_height (w) > 0)
6578 x_clear_area (f, left, top, width, window_box_height (w));
6580 window = XCreateWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
6581 /* Position and size of scroll bar. */
6582 left, top, width, height,
6583 /* Border width, depth, class, and visual. */
6585 CopyFromParent,
6586 CopyFromParent,
6587 CopyFromParent,
6588 /* Attributes. */
6589 mask, &a);
6590 bar->x_window = window;
6592 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6594 XSETWINDOW (bar->window, w);
6595 bar->top = top;
6596 bar->left = left;
6597 bar->width = width;
6598 bar->height = height;
6599 bar->start = 0;
6600 bar->end = 0;
6601 bar->dragging = -1;
6602 bar->horizontal = horizontal;
6603 #if defined (USE_TOOLKIT_SCROLL_BARS) && defined (USE_LUCID)
6604 bar->last_seen_part = scroll_bar_nowhere;
6605 #endif
6607 /* Add bar to its frame's list of scroll bars. */
6608 bar->next = FRAME_SCROLL_BARS (f);
6609 bar->prev = Qnil;
6610 XSETVECTOR (barobj, bar);
6611 fset_scroll_bars (f, barobj);
6612 if (!NILP (bar->next))
6613 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
6615 /* Map the window/widget. */
6616 #ifdef USE_TOOLKIT_SCROLL_BARS
6618 #ifdef USE_GTK
6619 if (horizontal)
6620 xg_update_horizontal_scrollbar_pos (f, bar->x_window, top,
6621 left, width, max (height, 1));
6622 else
6623 xg_update_scrollbar_pos (f, bar->x_window, top,
6624 left, width, max (height, 1));
6625 #else /* not USE_GTK */
6626 Widget scroll_bar = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
6627 XtConfigureWidget (scroll_bar, left, top, width, max (height, 1), 0);
6628 XtMapWidget (scroll_bar);
6629 /* Don't obscure any child frames. */
6630 XLowerWindow (FRAME_X_DISPLAY (f), bar->x_window);
6631 #endif /* not USE_GTK */
6633 #else /* not USE_TOOLKIT_SCROLL_BARS */
6634 XMapWindow (FRAME_X_DISPLAY (f), bar->x_window);
6635 /* Don't obscure any child frames. */
6636 XLowerWindow (FRAME_X_DISPLAY (f), bar->x_window);
6637 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6639 unblock_input ();
6640 return bar;
6644 #ifndef USE_TOOLKIT_SCROLL_BARS
6646 /* Draw BAR's handle in the proper position.
6648 If the handle is already drawn from START to END, don't bother
6649 redrawing it, unless REBUILD; in that case, always
6650 redraw it. (REBUILD is handy for drawing the handle after expose
6651 events.)
6653 Normally, we want to constrain the start and end of the handle to
6654 fit inside its rectangle, but if the user is dragging the scroll
6655 bar handle, we want to let them drag it down all the way, so that
6656 the bar's top is as far down as it goes; otherwise, there's no way
6657 to move to the very end of the buffer. */
6659 static void
6660 x_scroll_bar_set_handle (struct scroll_bar *bar, int start, int end,
6661 bool rebuild)
6663 bool dragging = bar->dragging != -1;
6664 Window w = bar->x_window;
6665 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6666 GC gc = f->output_data.x->normal_gc;
6668 /* If the display is already accurate, do nothing. */
6669 if (! rebuild
6670 && start == bar->start
6671 && end == bar->end)
6672 return;
6674 block_input ();
6677 int inside_width = VERTICAL_SCROLL_BAR_INSIDE_WIDTH (f, bar->width);
6678 int inside_height = VERTICAL_SCROLL_BAR_INSIDE_HEIGHT (f, bar->height);
6679 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
6681 /* Make sure the values are reasonable, and try to preserve
6682 the distance between start and end. */
6684 int length = end - start;
6686 if (start < 0)
6687 start = 0;
6688 else if (start > top_range)
6689 start = top_range;
6690 end = start + length;
6692 if (end < start)
6693 end = start;
6694 else if (end > top_range && ! dragging)
6695 end = top_range;
6698 /* Store the adjusted setting in the scroll bar. */
6699 bar->start = start;
6700 bar->end = end;
6702 /* Clip the end position, just for display. */
6703 if (end > top_range)
6704 end = top_range;
6706 /* Draw bottom positions VERTICAL_SCROLL_BAR_MIN_HANDLE pixels
6707 below top positions, to make sure the handle is always at least
6708 that many pixels tall. */
6709 end += VERTICAL_SCROLL_BAR_MIN_HANDLE;
6711 /* Draw the empty space above the handle. Note that we can't clear
6712 zero-height areas; that means "clear to end of window." */
6713 if ((inside_width > 0) && (start > 0))
6714 x_clear_area1 (FRAME_X_DISPLAY (f), w,
6715 VERTICAL_SCROLL_BAR_LEFT_BORDER,
6716 VERTICAL_SCROLL_BAR_TOP_BORDER,
6717 inside_width, start, False);
6719 /* Change to proper foreground color if one is specified. */
6720 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
6721 XSetForeground (FRAME_X_DISPLAY (f), gc,
6722 f->output_data.x->scroll_bar_foreground_pixel);
6724 /* Draw the handle itself. */
6725 XFillRectangle (FRAME_X_DISPLAY (f), w, gc,
6726 /* x, y, width, height */
6727 VERTICAL_SCROLL_BAR_LEFT_BORDER,
6728 VERTICAL_SCROLL_BAR_TOP_BORDER + start,
6729 inside_width, end - start);
6731 /* Restore the foreground color of the GC if we changed it above. */
6732 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
6733 XSetForeground (FRAME_X_DISPLAY (f), gc,
6734 FRAME_FOREGROUND_PIXEL (f));
6736 /* Draw the empty space below the handle. Note that we can't
6737 clear zero-height areas; that means "clear to end of window." */
6738 if ((inside_width > 0) && (end < inside_height))
6739 x_clear_area1 (FRAME_X_DISPLAY (f), w,
6740 VERTICAL_SCROLL_BAR_LEFT_BORDER,
6741 VERTICAL_SCROLL_BAR_TOP_BORDER + end,
6742 inside_width, inside_height - end, False);
6745 unblock_input ();
6748 #endif /* !USE_TOOLKIT_SCROLL_BARS */
6750 /* Destroy scroll bar BAR, and set its Emacs window's scroll bar to
6751 nil. */
6753 static void
6754 x_scroll_bar_remove (struct scroll_bar *bar)
6756 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6757 block_input ();
6759 #ifdef USE_TOOLKIT_SCROLL_BARS
6760 #ifdef USE_GTK
6761 xg_remove_scroll_bar (f, bar->x_window);
6762 #else /* not USE_GTK */
6763 XtDestroyWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar));
6764 #endif /* not USE_GTK */
6765 #else
6766 XDestroyWindow (FRAME_X_DISPLAY (f), bar->x_window);
6767 #endif
6769 /* Dissociate this scroll bar from its window. */
6770 if (bar->horizontal)
6771 wset_horizontal_scroll_bar (XWINDOW (bar->window), Qnil);
6772 else
6773 wset_vertical_scroll_bar (XWINDOW (bar->window), Qnil);
6775 unblock_input ();
6779 /* Set the handle of the vertical scroll bar for WINDOW to indicate
6780 that we are displaying PORTION characters out of a total of WHOLE
6781 characters, starting at POSITION. If WINDOW has no scroll bar,
6782 create one. */
6784 static void
6785 XTset_vertical_scroll_bar (struct window *w, int portion, int whole, int position)
6787 struct frame *f = XFRAME (w->frame);
6788 Lisp_Object barobj;
6789 struct scroll_bar *bar;
6790 int top, height, left, width;
6791 int window_y, window_height;
6793 /* Get window dimensions. */
6794 window_box (w, ANY_AREA, 0, &window_y, 0, &window_height);
6795 top = window_y;
6796 height = window_height;
6797 left = WINDOW_SCROLL_BAR_AREA_X (w);
6798 width = WINDOW_SCROLL_BAR_AREA_WIDTH (w);
6800 /* Does the scroll bar exist yet? */
6801 if (NILP (w->vertical_scroll_bar))
6803 if (width > 0 && height > 0)
6805 block_input ();
6806 x_clear_area (f, left, top, width, height);
6807 unblock_input ();
6810 bar = x_scroll_bar_create (w, top, left, width, max (height, 1), false);
6812 else
6814 /* It may just need to be moved and resized. */
6815 unsigned int mask = 0;
6817 bar = XSCROLL_BAR (w->vertical_scroll_bar);
6819 block_input ();
6821 if (left != bar->left)
6822 mask |= CWX;
6823 if (top != bar->top)
6824 mask |= CWY;
6825 if (width != bar->width)
6826 mask |= CWWidth;
6827 if (height != bar->height)
6828 mask |= CWHeight;
6830 #ifdef USE_TOOLKIT_SCROLL_BARS
6832 /* Move/size the scroll bar widget. */
6833 if (mask)
6835 /* Since toolkit scroll bars are smaller than the space reserved
6836 for them on the frame, we have to clear "under" them. */
6837 if (width > 0 && height > 0)
6838 x_clear_area (f, left, top, width, height);
6839 #ifdef USE_GTK
6840 xg_update_scrollbar_pos (f, bar->x_window, top,
6841 left, width, max (height, 1));
6842 #else /* not USE_GTK */
6843 XtConfigureWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar),
6844 left, top, width, max (height, 1), 0);
6845 #endif /* not USE_GTK */
6847 #else /* not USE_TOOLKIT_SCROLL_BARS */
6849 /* Move/size the scroll bar window. */
6850 if (mask)
6852 XWindowChanges wc;
6854 wc.x = left;
6855 wc.y = top;
6856 wc.width = width;
6857 wc.height = height;
6858 XConfigureWindow (FRAME_X_DISPLAY (f), bar->x_window,
6859 mask, &wc);
6862 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6864 /* Remember new settings. */
6865 bar->left = left;
6866 bar->top = top;
6867 bar->width = width;
6868 bar->height = height;
6870 unblock_input ();
6873 #ifdef USE_TOOLKIT_SCROLL_BARS
6874 x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
6875 #else /* not USE_TOOLKIT_SCROLL_BARS */
6876 /* Set the scroll bar's current state, unless we're currently being
6877 dragged. */
6878 if (bar->dragging == -1)
6880 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, height);
6882 if (whole == 0)
6883 x_scroll_bar_set_handle (bar, 0, top_range, false);
6884 else
6886 int start = ((double) position * top_range) / whole;
6887 int end = ((double) (position + portion) * top_range) / whole;
6888 x_scroll_bar_set_handle (bar, start, end, false);
6891 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6893 XSETVECTOR (barobj, bar);
6894 wset_vertical_scroll_bar (w, barobj);
6898 static void
6899 XTset_horizontal_scroll_bar (struct window *w, int portion, int whole, int position)
6901 struct frame *f = XFRAME (w->frame);
6902 Lisp_Object barobj;
6903 struct scroll_bar *bar;
6904 int top, height, left, width;
6905 int window_x, window_width;
6906 int pixel_width = WINDOW_PIXEL_WIDTH (w);
6908 /* Get window dimensions. */
6909 window_box (w, ANY_AREA, &window_x, 0, &window_width, 0);
6910 left = window_x;
6911 width = window_width;
6912 top = WINDOW_SCROLL_BAR_AREA_Y (w);
6913 height = WINDOW_SCROLL_BAR_AREA_HEIGHT (w);
6915 /* Does the scroll bar exist yet? */
6916 if (NILP (w->horizontal_scroll_bar))
6918 if (width > 0 && height > 0)
6920 block_input ();
6922 /* Clear also part between window_width and
6923 WINDOW_PIXEL_WIDTH. */
6924 x_clear_area (f, left, top, pixel_width, height);
6925 unblock_input ();
6928 bar = x_scroll_bar_create (w, top, left, width, height, true);
6930 else
6932 /* It may just need to be moved and resized. */
6933 unsigned int mask = 0;
6935 bar = XSCROLL_BAR (w->horizontal_scroll_bar);
6937 block_input ();
6939 if (left != bar->left)
6940 mask |= CWX;
6941 if (top != bar->top)
6942 mask |= CWY;
6943 if (width != bar->width)
6944 mask |= CWWidth;
6945 if (height != bar->height)
6946 mask |= CWHeight;
6948 #ifdef USE_TOOLKIT_SCROLL_BARS
6949 /* Move/size the scroll bar widget. */
6950 if (mask)
6952 /* Since toolkit scroll bars are smaller than the space reserved
6953 for them on the frame, we have to clear "under" them. */
6954 if (width > 0 && height > 0)
6955 x_clear_area (f,
6956 WINDOW_LEFT_EDGE_X (w), top,
6957 pixel_width - WINDOW_RIGHT_DIVIDER_WIDTH (w), height);
6958 #ifdef USE_GTK
6959 xg_update_horizontal_scrollbar_pos (f, bar->x_window, top, left,
6960 width, height);
6961 #else /* not USE_GTK */
6962 XtConfigureWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar),
6963 left, top, width, height, 0);
6964 #endif /* not USE_GTK */
6966 #else /* not USE_TOOLKIT_SCROLL_BARS */
6968 /* Clear areas not covered by the scroll bar because it's not as
6969 wide as the area reserved for it. This makes sure a
6970 previous mode line display is cleared after C-x 2 C-x 1, for
6971 example. */
6973 int area_height = WINDOW_CONFIG_SCROLL_BAR_HEIGHT (w);
6974 int rest = area_height - height;
6975 if (rest > 0 && width > 0)
6976 x_clear_area (f, left, top, width, rest);
6979 /* Move/size the scroll bar window. */
6980 if (mask)
6982 XWindowChanges wc;
6984 wc.x = left;
6985 wc.y = top;
6986 wc.width = width;
6987 wc.height = height;
6988 XConfigureWindow (FRAME_X_DISPLAY (f), bar->x_window,
6989 mask, &wc);
6992 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6994 /* Remember new settings. */
6995 bar->left = left;
6996 bar->top = top;
6997 bar->width = width;
6998 bar->height = height;
7000 unblock_input ();
7003 #ifdef USE_TOOLKIT_SCROLL_BARS
7004 x_set_toolkit_horizontal_scroll_bar_thumb (bar, portion, position, whole);
7005 #else /* not USE_TOOLKIT_SCROLL_BARS */
7006 /* Set the scroll bar's current state, unless we're currently being
7007 dragged. */
7008 if (bar->dragging == -1)
7010 int left_range = HORIZONTAL_SCROLL_BAR_LEFT_RANGE (f, width);
7012 if (whole == 0)
7013 x_scroll_bar_set_handle (bar, 0, left_range, false);
7014 else
7016 int start = ((double) position * left_range) / whole;
7017 int end = ((double) (position + portion) * left_range) / whole;
7018 x_scroll_bar_set_handle (bar, start, end, false);
7021 #endif /* not USE_TOOLKIT_SCROLL_BARS */
7023 XSETVECTOR (barobj, bar);
7024 wset_horizontal_scroll_bar (w, barobj);
7028 /* The following three hooks are used when we're doing a thorough
7029 redisplay of the frame. We don't explicitly know which scroll bars
7030 are going to be deleted, because keeping track of when windows go
7031 away is a real pain - "Can you say set-window-configuration, boys
7032 and girls?" Instead, we just assert at the beginning of redisplay
7033 that *all* scroll bars are to be removed, and then save a scroll bar
7034 from the fiery pit when we actually redisplay its window. */
7036 /* Arrange for all scroll bars on FRAME to be removed at the next call
7037 to `*judge_scroll_bars_hook'. A scroll bar may be spared if
7038 `*redeem_scroll_bar_hook' is applied to its window before the judgment. */
7040 static void
7041 XTcondemn_scroll_bars (struct frame *frame)
7043 if (!NILP (FRAME_SCROLL_BARS (frame)))
7045 if (!NILP (FRAME_CONDEMNED_SCROLL_BARS (frame)))
7047 /* Prepend scrollbars to already condemned ones. */
7048 Lisp_Object last = FRAME_SCROLL_BARS (frame);
7050 while (!NILP (XSCROLL_BAR (last)->next))
7051 last = XSCROLL_BAR (last)->next;
7053 XSCROLL_BAR (last)->next = FRAME_CONDEMNED_SCROLL_BARS (frame);
7054 XSCROLL_BAR (FRAME_CONDEMNED_SCROLL_BARS (frame))->prev = last;
7057 fset_condemned_scroll_bars (frame, FRAME_SCROLL_BARS (frame));
7058 fset_scroll_bars (frame, Qnil);
7063 /* Un-mark WINDOW's scroll bar for deletion in this judgment cycle.
7064 Note that WINDOW isn't necessarily condemned at all. */
7066 static void
7067 XTredeem_scroll_bar (struct window *w)
7069 struct scroll_bar *bar;
7070 Lisp_Object barobj;
7071 struct frame *f;
7073 /* We can't redeem this window's scroll bar if it doesn't have one. */
7074 if (NILP (w->vertical_scroll_bar) && NILP (w->horizontal_scroll_bar))
7075 emacs_abort ();
7077 if (!NILP (w->vertical_scroll_bar) && WINDOW_HAS_VERTICAL_SCROLL_BAR (w))
7079 bar = XSCROLL_BAR (w->vertical_scroll_bar);
7080 /* Unlink it from the condemned list. */
7081 f = XFRAME (WINDOW_FRAME (w));
7082 if (NILP (bar->prev))
7084 /* If the prev pointer is nil, it must be the first in one of
7085 the lists. */
7086 if (EQ (FRAME_SCROLL_BARS (f), w->vertical_scroll_bar))
7087 /* It's not condemned. Everything's fine. */
7088 goto horizontal;
7089 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
7090 w->vertical_scroll_bar))
7091 fset_condemned_scroll_bars (f, bar->next);
7092 else
7093 /* If its prev pointer is nil, it must be at the front of
7094 one or the other! */
7095 emacs_abort ();
7097 else
7098 XSCROLL_BAR (bar->prev)->next = bar->next;
7100 if (! NILP (bar->next))
7101 XSCROLL_BAR (bar->next)->prev = bar->prev;
7103 bar->next = FRAME_SCROLL_BARS (f);
7104 bar->prev = Qnil;
7105 XSETVECTOR (barobj, bar);
7106 fset_scroll_bars (f, barobj);
7107 if (! NILP (bar->next))
7108 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
7111 horizontal:
7112 if (!NILP (w->horizontal_scroll_bar) && WINDOW_HAS_HORIZONTAL_SCROLL_BAR (w))
7114 bar = XSCROLL_BAR (w->horizontal_scroll_bar);
7115 /* Unlink it from the condemned list. */
7116 f = XFRAME (WINDOW_FRAME (w));
7117 if (NILP (bar->prev))
7119 /* If the prev pointer is nil, it must be the first in one of
7120 the lists. */
7121 if (EQ (FRAME_SCROLL_BARS (f), w->horizontal_scroll_bar))
7122 /* It's not condemned. Everything's fine. */
7123 return;
7124 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
7125 w->horizontal_scroll_bar))
7126 fset_condemned_scroll_bars (f, bar->next);
7127 else
7128 /* If its prev pointer is nil, it must be at the front of
7129 one or the other! */
7130 emacs_abort ();
7132 else
7133 XSCROLL_BAR (bar->prev)->next = bar->next;
7135 if (! NILP (bar->next))
7136 XSCROLL_BAR (bar->next)->prev = bar->prev;
7138 bar->next = FRAME_SCROLL_BARS (f);
7139 bar->prev = Qnil;
7140 XSETVECTOR (barobj, bar);
7141 fset_scroll_bars (f, barobj);
7142 if (! NILP (bar->next))
7143 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
7147 /* Remove all scroll bars on FRAME that haven't been saved since the
7148 last call to `*condemn_scroll_bars_hook'. */
7150 static void
7151 XTjudge_scroll_bars (struct frame *f)
7153 Lisp_Object bar, next;
7155 bar = FRAME_CONDEMNED_SCROLL_BARS (f);
7157 /* Clear out the condemned list now so we won't try to process any
7158 more events on the hapless scroll bars. */
7159 fset_condemned_scroll_bars (f, Qnil);
7161 for (; ! NILP (bar); bar = next)
7163 struct scroll_bar *b = XSCROLL_BAR (bar);
7165 x_scroll_bar_remove (b);
7167 next = b->next;
7168 b->next = b->prev = Qnil;
7171 /* Now there should be no references to the condemned scroll bars,
7172 and they should get garbage-collected. */
7176 #ifndef USE_TOOLKIT_SCROLL_BARS
7177 /* Handle an Expose or GraphicsExpose event on a scroll bar. This
7178 is a no-op when using toolkit scroll bars.
7180 This may be called from a signal handler, so we have to ignore GC
7181 mark bits. */
7183 static void
7184 x_scroll_bar_expose (struct scroll_bar *bar, const XEvent *event)
7186 Window w = bar->x_window;
7187 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
7188 GC gc = f->output_data.x->normal_gc;
7190 block_input ();
7192 x_scroll_bar_set_handle (bar, bar->start, bar->end, true);
7194 /* Switch to scroll bar foreground color. */
7195 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
7196 XSetForeground (FRAME_X_DISPLAY (f), gc,
7197 f->output_data.x->scroll_bar_foreground_pixel);
7199 /* Draw a one-pixel border just inside the edges of the scroll bar. */
7200 XDrawRectangle (FRAME_X_DISPLAY (f), w, gc,
7201 /* x, y, width, height */
7202 0, 0, bar->width - 1, bar->height - 1);
7204 /* Restore the foreground color of the GC if we changed it above. */
7205 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
7206 XSetForeground (FRAME_X_DISPLAY (f), gc,
7207 FRAME_FOREGROUND_PIXEL (f));
7209 unblock_input ();
7212 #endif /* not USE_TOOLKIT_SCROLL_BARS */
7214 /* Handle a mouse click on the scroll bar BAR. If *EMACS_EVENT's kind
7215 is set to something other than NO_EVENT, it is enqueued.
7217 This may be called from a signal handler, so we have to ignore GC
7218 mark bits. */
7221 static void
7222 x_scroll_bar_handle_click (struct scroll_bar *bar,
7223 const XEvent *event,
7224 struct input_event *emacs_event)
7226 if (! WINDOWP (bar->window))
7227 emacs_abort ();
7229 emacs_event->kind = (bar->horizontal
7230 ? HORIZONTAL_SCROLL_BAR_CLICK_EVENT
7231 : SCROLL_BAR_CLICK_EVENT);
7232 emacs_event->code = event->xbutton.button - Button1;
7233 emacs_event->modifiers
7234 = (x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO
7235 (XFRAME (WINDOW_FRAME (XWINDOW (bar->window)))),
7236 event->xbutton.state)
7237 | (event->type == ButtonRelease
7238 ? up_modifier
7239 : down_modifier));
7240 emacs_event->frame_or_window = bar->window;
7241 emacs_event->arg = Qnil;
7242 emacs_event->timestamp = event->xbutton.time;
7243 if (bar->horizontal)
7245 int left_range
7246 = HORIZONTAL_SCROLL_BAR_LEFT_RANGE (f, bar->width);
7247 int x = event->xbutton.x - HORIZONTAL_SCROLL_BAR_LEFT_BORDER;
7249 if (x < 0) x = 0;
7250 if (x > left_range) x = left_range;
7252 if (x < bar->start)
7253 emacs_event->part = scroll_bar_before_handle;
7254 else if (x < bar->end + HORIZONTAL_SCROLL_BAR_MIN_HANDLE)
7255 emacs_event->part = scroll_bar_horizontal_handle;
7256 else
7257 emacs_event->part = scroll_bar_after_handle;
7259 #ifndef USE_TOOLKIT_SCROLL_BARS
7260 /* If the user has released the handle, set it to its final position. */
7261 if (event->type == ButtonRelease && bar->dragging != -1)
7263 int new_start = - bar->dragging;
7264 int new_end = new_start + bar->end - bar->start;
7266 x_scroll_bar_set_handle (bar, new_start, new_end, false);
7267 bar->dragging = -1;
7269 #endif
7271 XSETINT (emacs_event->x, left_range);
7272 XSETINT (emacs_event->y, x);
7274 else
7276 int top_range
7277 = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
7278 int y = event->xbutton.y - VERTICAL_SCROLL_BAR_TOP_BORDER;
7280 if (y < 0) y = 0;
7281 if (y > top_range) y = top_range;
7283 if (y < bar->start)
7284 emacs_event->part = scroll_bar_above_handle;
7285 else if (y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
7286 emacs_event->part = scroll_bar_handle;
7287 else
7288 emacs_event->part = scroll_bar_below_handle;
7290 #ifndef USE_TOOLKIT_SCROLL_BARS
7291 /* If the user has released the handle, set it to its final position. */
7292 if (event->type == ButtonRelease && bar->dragging != -1)
7294 int new_start = y - bar->dragging;
7295 int new_end = new_start + bar->end - bar->start;
7297 x_scroll_bar_set_handle (bar, new_start, new_end, false);
7298 bar->dragging = -1;
7300 #endif
7302 XSETINT (emacs_event->x, y);
7303 XSETINT (emacs_event->y, top_range);
7307 #ifndef USE_TOOLKIT_SCROLL_BARS
7309 /* Handle some mouse motion while someone is dragging the scroll bar.
7311 This may be called from a signal handler, so we have to ignore GC
7312 mark bits. */
7314 static void
7315 x_scroll_bar_note_movement (struct scroll_bar *bar,
7316 const XMotionEvent *event)
7318 struct frame *f = XFRAME (XWINDOW (bar->window)->frame);
7319 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
7321 dpyinfo->last_mouse_movement_time = event->time;
7322 dpyinfo->last_mouse_scroll_bar = bar;
7323 f->mouse_moved = true;
7325 /* If we're dragging the bar, display it. */
7326 if (bar->dragging != -1)
7328 /* Where should the handle be now? */
7329 int new_start = event->y - bar->dragging;
7331 if (new_start != bar->start)
7333 int new_end = new_start + bar->end - bar->start;
7335 x_scroll_bar_set_handle (bar, new_start, new_end, false);
7340 #endif /* !USE_TOOLKIT_SCROLL_BARS */
7342 /* Return information to the user about the current position of the mouse
7343 on the scroll bar. */
7345 static void
7346 x_scroll_bar_report_motion (struct frame **fp, Lisp_Object *bar_window,
7347 enum scroll_bar_part *part, Lisp_Object *x,
7348 Lisp_Object *y, Time *timestamp)
7350 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (*fp);
7351 struct scroll_bar *bar = dpyinfo->last_mouse_scroll_bar;
7352 Window w = bar->x_window;
7353 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
7354 int win_x, win_y;
7355 Window dummy_window;
7356 int dummy_coord;
7357 unsigned int dummy_mask;
7359 block_input ();
7361 /* Get the mouse's position relative to the scroll bar window, and
7362 report that. */
7363 if (XQueryPointer (FRAME_X_DISPLAY (f), w,
7365 /* Root, child, root x and root y. */
7366 &dummy_window, &dummy_window,
7367 &dummy_coord, &dummy_coord,
7369 /* Position relative to scroll bar. */
7370 &win_x, &win_y,
7372 /* Mouse buttons and modifier keys. */
7373 &dummy_mask))
7375 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
7377 win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
7379 if (bar->dragging != -1)
7380 win_y -= bar->dragging;
7382 if (win_y < 0)
7383 win_y = 0;
7384 if (win_y > top_range)
7385 win_y = top_range;
7387 *fp = f;
7388 *bar_window = bar->window;
7390 if (bar->dragging != -1)
7391 *part = scroll_bar_handle;
7392 else if (win_y < bar->start)
7393 *part = scroll_bar_above_handle;
7394 else if (win_y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
7395 *part = scroll_bar_handle;
7396 else
7397 *part = scroll_bar_below_handle;
7399 XSETINT (*x, win_y);
7400 XSETINT (*y, top_range);
7402 f->mouse_moved = false;
7403 dpyinfo->last_mouse_scroll_bar = NULL;
7404 *timestamp = dpyinfo->last_mouse_movement_time;
7407 unblock_input ();
7411 /* Return information to the user about the current position of the mouse
7412 on the scroll bar. */
7414 static void
7415 x_horizontal_scroll_bar_report_motion (struct frame **fp, Lisp_Object *bar_window,
7416 enum scroll_bar_part *part, Lisp_Object *x,
7417 Lisp_Object *y, Time *timestamp)
7419 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (*fp);
7420 struct scroll_bar *bar = dpyinfo->last_mouse_scroll_bar;
7421 Window w = bar->x_window;
7422 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
7423 int win_x, win_y;
7424 Window dummy_window;
7425 int dummy_coord;
7426 unsigned int dummy_mask;
7428 block_input ();
7430 /* Get the mouse's position relative to the scroll bar window, and
7431 report that. */
7432 if (XQueryPointer (FRAME_X_DISPLAY (f), w,
7434 /* Root, child, root x and root y. */
7435 &dummy_window, &dummy_window,
7436 &dummy_coord, &dummy_coord,
7438 /* Position relative to scroll bar. */
7439 &win_x, &win_y,
7441 /* Mouse buttons and modifier keys. */
7442 &dummy_mask))
7444 int left_range = HORIZONTAL_SCROLL_BAR_LEFT_RANGE (f, bar->width);
7446 win_x -= HORIZONTAL_SCROLL_BAR_LEFT_BORDER;
7448 if (bar->dragging != -1)
7449 win_x -= bar->dragging;
7451 if (win_x < 0)
7452 win_x = 0;
7453 if (win_x > left_range)
7454 win_x = left_range;
7456 *fp = f;
7457 *bar_window = bar->window;
7459 if (bar->dragging != -1)
7460 *part = scroll_bar_horizontal_handle;
7461 else if (win_x < bar->start)
7462 *part = scroll_bar_before_handle;
7463 else if (win_x < bar->end + HORIZONTAL_SCROLL_BAR_MIN_HANDLE)
7464 *part = scroll_bar_handle;
7465 else
7466 *part = scroll_bar_after_handle;
7468 XSETINT (*y, win_x);
7469 XSETINT (*x, left_range);
7471 f->mouse_moved = false;
7472 dpyinfo->last_mouse_scroll_bar = NULL;
7473 *timestamp = dpyinfo->last_mouse_movement_time;
7476 unblock_input ();
7480 /* The screen has been cleared so we may have changed foreground or
7481 background colors, and the scroll bars may need to be redrawn.
7482 Clear out the scroll bars, and ask for expose events, so we can
7483 redraw them. */
7485 static void
7486 x_scroll_bar_clear (struct frame *f)
7488 #ifndef USE_TOOLKIT_SCROLL_BARS
7489 Lisp_Object bar;
7491 /* We can have scroll bars even if this is 0,
7492 if we just turned off scroll bar mode.
7493 But in that case we should not clear them. */
7494 if (FRAME_HAS_VERTICAL_SCROLL_BARS (f))
7495 for (bar = FRAME_SCROLL_BARS (f); VECTORP (bar);
7496 bar = XSCROLL_BAR (bar)->next)
7497 XClearArea (FRAME_X_DISPLAY (f),
7498 XSCROLL_BAR (bar)->x_window,
7499 0, 0, 0, 0, True);
7500 #endif /* not USE_TOOLKIT_SCROLL_BARS */
7503 #ifdef ENABLE_CHECKING
7505 /* Record the last 100 characters stored
7506 to help debug the loss-of-chars-during-GC problem. */
7508 static int temp_index;
7509 static short temp_buffer[100];
7511 #define STORE_KEYSYM_FOR_DEBUG(keysym) \
7512 if (temp_index == ARRAYELTS (temp_buffer)) \
7513 temp_index = 0; \
7514 temp_buffer[temp_index++] = (keysym)
7516 #else /* not ENABLE_CHECKING */
7518 #define STORE_KEYSYM_FOR_DEBUG(keysym) ((void)0)
7520 #endif /* ENABLE_CHECKING */
7522 /* Set this to nonzero to fake an "X I/O error"
7523 on a particular display. */
7525 static struct x_display_info *XTread_socket_fake_io_error;
7527 /* When we find no input here, we occasionally do a no-op command
7528 to verify that the X server is still running and we can still talk with it.
7529 We try all the open displays, one by one.
7530 This variable is used for cycling thru the displays. */
7532 static struct x_display_info *next_noop_dpyinfo;
7534 enum
7536 X_EVENT_NORMAL,
7537 X_EVENT_GOTO_OUT,
7538 X_EVENT_DROP
7541 /* Filter events for the current X input method.
7542 DPYINFO is the display this event is for.
7543 EVENT is the X event to filter.
7545 Returns non-zero if the event was filtered, caller shall not process
7546 this event further.
7547 Returns zero if event is wasn't filtered. */
7549 #ifdef HAVE_X_I18N
7550 static int
7551 x_filter_event (struct x_display_info *dpyinfo, XEvent *event)
7553 /* XFilterEvent returns non-zero if the input method has
7554 consumed the event. We pass the frame's X window to
7555 XFilterEvent because that's the one for which the IC
7556 was created. */
7558 struct frame *f1 = x_any_window_to_frame (dpyinfo,
7559 event->xclient.window);
7561 return XFilterEvent (event, f1 ? FRAME_X_WINDOW (f1) : None);
7563 #endif
7565 #ifdef USE_GTK
7566 static int current_count;
7567 static int current_finish;
7568 static struct input_event *current_hold_quit;
7570 /* This is the filter function invoked by the GTK event loop.
7571 It is invoked before the XEvent is translated to a GdkEvent,
7572 so we have a chance to act on the event before GTK. */
7573 static GdkFilterReturn
7574 event_handler_gdk (GdkXEvent *gxev, GdkEvent *ev, gpointer data)
7576 XEvent *xev = (XEvent *) gxev;
7578 block_input ();
7579 if (current_count >= 0)
7581 struct x_display_info *dpyinfo;
7583 dpyinfo = x_display_info_for_display (xev->xany.display);
7585 #ifdef HAVE_X_I18N
7586 /* Filter events for the current X input method.
7587 GTK calls XFilterEvent but not for key press and release,
7588 so we do it here. */
7589 if ((xev->type == KeyPress || xev->type == KeyRelease)
7590 && dpyinfo
7591 && x_filter_event (dpyinfo, xev))
7593 unblock_input ();
7594 return GDK_FILTER_REMOVE;
7596 #endif
7598 if (! dpyinfo)
7599 current_finish = X_EVENT_NORMAL;
7600 else
7601 current_count
7602 += handle_one_xevent (dpyinfo, xev, &current_finish,
7603 current_hold_quit);
7605 else
7606 current_finish = x_dispatch_event (xev, xev->xany.display);
7608 unblock_input ();
7610 if (current_finish == X_EVENT_GOTO_OUT || current_finish == X_EVENT_DROP)
7611 return GDK_FILTER_REMOVE;
7613 return GDK_FILTER_CONTINUE;
7615 #endif /* USE_GTK */
7618 static void xembed_send_message (struct frame *f, Time,
7619 enum xembed_message,
7620 long detail, long data1, long data2);
7622 static void
7623 x_net_wm_state (struct frame *f, Window window)
7625 int value = FULLSCREEN_NONE;
7626 Lisp_Object lval = Qnil;
7627 bool sticky = false;
7629 get_current_wm_state (f, window, &value, &sticky);
7631 switch (value)
7633 case FULLSCREEN_WIDTH:
7634 lval = Qfullwidth;
7635 break;
7636 case FULLSCREEN_HEIGHT:
7637 lval = Qfullheight;
7638 break;
7639 case FULLSCREEN_BOTH:
7640 lval = Qfullboth;
7641 break;
7642 case FULLSCREEN_MAXIMIZED:
7643 lval = Qmaximized;
7644 break;
7647 frame_size_history_add
7648 (f, Qx_net_wm_state, 0, 0,
7649 list2 (get_frame_param (f, Qfullscreen), lval));
7651 store_frame_param (f, Qfullscreen, lval);
7652 /** store_frame_param (f, Qsticky, sticky ? Qt : Qnil); **/
7655 /* Flip back buffers on any frames with undrawn content. */
7656 static void
7657 flush_dirty_back_buffers (void)
7659 block_input ();
7660 Lisp_Object tail, frame;
7661 FOR_EACH_FRAME (tail, frame)
7663 struct frame *f = XFRAME (frame);
7664 if (FRAME_LIVE_P (f) &&
7665 FRAME_X_P (f) &&
7666 FRAME_X_WINDOW (f) &&
7667 !FRAME_GARBAGED_P (f) &&
7668 !buffer_flipping_blocked_p () &&
7669 FRAME_X_NEED_BUFFER_FLIP (f))
7670 show_back_buffer (f);
7672 unblock_input ();
7675 /* Handles the XEvent EVENT on display DPYINFO.
7677 *FINISH is X_EVENT_GOTO_OUT if caller should stop reading events.
7678 *FINISH is zero if caller should continue reading events.
7679 *FINISH is X_EVENT_DROP if event should not be passed to the toolkit.
7680 *EVENT is unchanged unless we're processing KeyPress event.
7682 We return the number of characters stored into the buffer. */
7684 static int
7685 handle_one_xevent (struct x_display_info *dpyinfo,
7686 const XEvent *event,
7687 int *finish, struct input_event *hold_quit)
7689 union buffered_input_event inev;
7690 int count = 0;
7691 int do_help = 0;
7692 ptrdiff_t nbytes = 0;
7693 struct frame *any, *f = NULL;
7694 struct coding_system coding;
7695 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
7696 /* This holds the state XLookupString needs to implement dead keys
7697 and other tricks known as "compose processing". _X Window System_
7698 says that a portable program can't use this, but Stephen Gildea assures
7699 me that letting the compiler initialize it to zeros will work okay. */
7700 static XComposeStatus compose_status;
7701 XEvent configureEvent;
7702 XEvent next_event;
7704 USE_SAFE_ALLOCA;
7706 *finish = X_EVENT_NORMAL;
7708 EVENT_INIT (inev.ie);
7709 inev.ie.kind = NO_EVENT;
7710 inev.ie.arg = Qnil;
7712 any = x_any_window_to_frame (dpyinfo, event->xany.window);
7714 if (any && any->wait_event_type == event->type)
7715 any->wait_event_type = 0; /* Indicates we got it. */
7717 switch (event->type)
7719 case ClientMessage:
7721 if (event->xclient.message_type == dpyinfo->Xatom_wm_protocols
7722 && event->xclient.format == 32)
7724 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_take_focus)
7726 /* Use the value returned by x_any_window_to_frame
7727 because this could be the shell widget window
7728 if the frame has no title bar. */
7729 f = any;
7730 #ifdef HAVE_X_I18N
7731 /* Not quite sure this is needed -pd */
7732 if (f && FRAME_XIC (f))
7733 XSetICFocus (FRAME_XIC (f));
7734 #endif
7735 #if false
7736 /* Emacs sets WM hints whose `input' field is `true'. This
7737 instructs the WM to set the input focus automatically for
7738 Emacs with a call to XSetInputFocus. Setting WM_TAKE_FOCUS
7739 tells the WM to send us a ClientMessage WM_TAKE_FOCUS after
7740 it has set the focus. So, XSetInputFocus below is not
7741 needed.
7743 The call to XSetInputFocus below has also caused trouble. In
7744 cases where the XSetInputFocus done by the WM and the one
7745 below are temporally close (on a fast machine), the call
7746 below can generate additional FocusIn events which confuse
7747 Emacs. */
7749 /* Since we set WM_TAKE_FOCUS, we must call
7750 XSetInputFocus explicitly. But not if f is null,
7751 since that might be an event for a deleted frame. */
7752 if (f)
7754 Display *d = event->xclient.display;
7755 /* Catch and ignore errors, in case window has been
7756 iconified by a window manager such as GWM. */
7757 x_catch_errors (d);
7758 XSetInputFocus (d, event->xclient.window,
7759 /* The ICCCM says this is
7760 the only valid choice. */
7761 RevertToParent,
7762 event->xclient.data.l[1]);
7763 x_uncatch_errors ();
7765 /* Not certain about handling scroll bars here */
7766 #endif
7767 goto done;
7770 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_save_yourself)
7772 /* Save state modify the WM_COMMAND property to
7773 something which can reinstate us. This notifies
7774 the session manager, who's looking for such a
7775 PropertyNotify. Can restart processing when
7776 a keyboard or mouse event arrives. */
7777 /* If we have a session manager, don't set this.
7778 KDE will then start two Emacsen, one for the
7779 session manager and one for this. */
7780 #ifdef HAVE_X_SM
7781 if (! x_session_have_connection ())
7782 #endif
7784 f = x_top_window_to_frame (dpyinfo,
7785 event->xclient.window);
7786 /* This is just so we only give real data once
7787 for a single Emacs process. */
7788 if (f == SELECTED_FRAME ())
7789 XSetCommand (FRAME_X_DISPLAY (f),
7790 event->xclient.window,
7791 initial_argv, initial_argc);
7792 else if (f)
7793 XSetCommand (FRAME_X_DISPLAY (f),
7794 event->xclient.window,
7795 0, 0);
7797 goto done;
7800 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_delete_window)
7802 f = any;
7803 if (!f)
7804 goto OTHER; /* May be a dialog that is to be removed */
7806 inev.ie.kind = DELETE_WINDOW_EVENT;
7807 XSETFRAME (inev.ie.frame_or_window, f);
7808 goto done;
7811 goto done;
7814 if (event->xclient.message_type == dpyinfo->Xatom_wm_configure_denied)
7815 goto done;
7817 if (event->xclient.message_type == dpyinfo->Xatom_wm_window_moved)
7819 int new_x, new_y;
7820 f = x_window_to_frame (dpyinfo, event->xclient.window);
7822 new_x = event->xclient.data.s[0];
7823 new_y = event->xclient.data.s[1];
7825 if (f)
7827 f->left_pos = new_x;
7828 f->top_pos = new_y;
7830 goto done;
7833 #ifdef X_TOOLKIT_EDITRES
7834 if (event->xclient.message_type == dpyinfo->Xatom_editres)
7836 f = any;
7837 if (f)
7838 _XEditResCheckMessages (f->output_data.x->widget,
7839 NULL, (XEvent *) event, NULL);
7840 goto done;
7842 #endif /* X_TOOLKIT_EDITRES */
7844 if (event->xclient.message_type == dpyinfo->Xatom_DONE
7845 || event->xclient.message_type == dpyinfo->Xatom_PAGE)
7847 /* Ghostview job completed. Kill it. We could
7848 reply with "Next" if we received "Page", but we
7849 currently never do because we are interested in
7850 images, only, which should have 1 page. */
7851 Pixmap pixmap = (Pixmap) event->xclient.data.l[1];
7852 f = x_window_to_frame (dpyinfo, event->xclient.window);
7853 if (!f)
7854 goto OTHER;
7855 x_kill_gs_process (pixmap, f);
7856 expose_frame (f, 0, 0, 0, 0);
7857 goto done;
7860 #ifdef USE_TOOLKIT_SCROLL_BARS
7861 /* Scroll bar callbacks send a ClientMessage from which
7862 we construct an input_event. */
7863 if (event->xclient.message_type == dpyinfo->Xatom_Scrollbar)
7865 x_scroll_bar_to_input_event (event, &inev.ie);
7866 *finish = X_EVENT_GOTO_OUT;
7867 goto done;
7869 else if (event->xclient.message_type == dpyinfo->Xatom_Horizontal_Scrollbar)
7871 x_horizontal_scroll_bar_to_input_event (event, &inev.ie);
7872 *finish = X_EVENT_GOTO_OUT;
7873 goto done;
7875 #endif /* USE_TOOLKIT_SCROLL_BARS */
7877 /* XEmbed messages from the embedder (if any). */
7878 if (event->xclient.message_type == dpyinfo->Xatom_XEMBED)
7880 enum xembed_message msg = event->xclient.data.l[1];
7881 if (msg == XEMBED_FOCUS_IN || msg == XEMBED_FOCUS_OUT)
7882 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
7884 *finish = X_EVENT_GOTO_OUT;
7885 goto done;
7888 xft_settings_event (dpyinfo, event);
7890 f = any;
7891 if (!f)
7892 goto OTHER;
7893 if (x_handle_dnd_message (f, &event->xclient, dpyinfo, &inev.ie))
7894 *finish = X_EVENT_DROP;
7896 break;
7898 case SelectionNotify:
7899 x_display_set_last_user_time (dpyinfo, event->xselection.time);
7900 #ifdef USE_X_TOOLKIT
7901 if (! x_window_to_frame (dpyinfo, event->xselection.requestor))
7902 goto OTHER;
7903 #endif /* not USE_X_TOOLKIT */
7904 x_handle_selection_notify (&event->xselection);
7905 break;
7907 case SelectionClear: /* Someone has grabbed ownership. */
7908 x_display_set_last_user_time (dpyinfo, event->xselectionclear.time);
7909 #ifdef USE_X_TOOLKIT
7910 if (! x_window_to_frame (dpyinfo, event->xselectionclear.window))
7911 goto OTHER;
7912 #endif /* USE_X_TOOLKIT */
7914 const XSelectionClearEvent *eventp = &event->xselectionclear;
7916 inev.sie.kind = SELECTION_CLEAR_EVENT;
7917 SELECTION_EVENT_DPYINFO (&inev.sie) = dpyinfo;
7918 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
7919 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
7921 break;
7923 case SelectionRequest: /* Someone wants our selection. */
7924 x_display_set_last_user_time (dpyinfo, event->xselectionrequest.time);
7925 #ifdef USE_X_TOOLKIT
7926 if (!x_window_to_frame (dpyinfo, event->xselectionrequest.owner))
7927 goto OTHER;
7928 #endif /* USE_X_TOOLKIT */
7930 const XSelectionRequestEvent *eventp = &event->xselectionrequest;
7932 inev.sie.kind = SELECTION_REQUEST_EVENT;
7933 SELECTION_EVENT_DPYINFO (&inev.sie) = dpyinfo;
7934 SELECTION_EVENT_REQUESTOR (&inev.sie) = eventp->requestor;
7935 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
7936 SELECTION_EVENT_TARGET (&inev.sie) = eventp->target;
7937 SELECTION_EVENT_PROPERTY (&inev.sie) = eventp->property;
7938 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
7940 break;
7942 case PropertyNotify:
7943 x_display_set_last_user_time (dpyinfo, event->xproperty.time);
7944 f = x_top_window_to_frame (dpyinfo, event->xproperty.window);
7945 if (f && event->xproperty.atom == dpyinfo->Xatom_net_wm_state)
7947 bool not_hidden = x_handle_net_wm_state (f, &event->xproperty);
7948 if (not_hidden && FRAME_ICONIFIED_P (f))
7950 /* Gnome shell does not iconify us when C-z is pressed.
7951 It hides the frame. So if our state says we aren't
7952 hidden anymore, treat it as deiconified. */
7953 SET_FRAME_VISIBLE (f, 1);
7954 SET_FRAME_ICONIFIED (f, false);
7955 f->output_data.x->has_been_visible = true;
7956 inev.ie.kind = DEICONIFY_EVENT;
7957 XSETFRAME (inev.ie.frame_or_window, f);
7959 else if (! not_hidden && ! FRAME_ICONIFIED_P (f))
7961 SET_FRAME_VISIBLE (f, 0);
7962 SET_FRAME_ICONIFIED (f, true);
7963 inev.ie.kind = ICONIFY_EVENT;
7964 XSETFRAME (inev.ie.frame_or_window, f);
7968 x_handle_property_notify (&event->xproperty);
7969 xft_settings_event (dpyinfo, event);
7970 goto OTHER;
7972 case ReparentNotify:
7973 f = x_top_window_to_frame (dpyinfo, event->xreparent.window);
7974 if (f)
7976 /* Maybe we shouldn't set this for child frames ?? */
7977 f->output_data.x->parent_desc = event->xreparent.parent;
7978 if (!FRAME_PARENT_FRAME (f))
7979 x_real_positions (f, &f->left_pos, &f->top_pos);
7980 else
7982 Window root;
7983 unsigned int dummy_uint;
7985 block_input ();
7986 XGetGeometry (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
7987 &root, &f->left_pos, &f->top_pos,
7988 &dummy_uint, &dummy_uint, &dummy_uint, &dummy_uint);
7989 unblock_input ();
7992 /* Perhaps reparented due to a WM restart. Reset this. */
7993 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_UNKNOWN;
7994 FRAME_DISPLAY_INFO (f)->net_supported_window = 0;
7996 x_set_frame_alpha (f);
7998 goto OTHER;
8000 case Expose:
8001 f = x_window_to_frame (dpyinfo, event->xexpose.window);
8002 if (f)
8004 if (!FRAME_VISIBLE_P (f))
8006 block_input ();
8007 SET_FRAME_VISIBLE (f, 1);
8008 SET_FRAME_ICONIFIED (f, false);
8009 if (FRAME_X_DOUBLE_BUFFERED_P (f))
8010 font_drop_xrender_surfaces (f);
8011 f->output_data.x->has_been_visible = true;
8012 SET_FRAME_GARBAGED (f);
8013 unblock_input ();
8015 else if (FRAME_GARBAGED_P (f))
8017 #ifdef USE_GTK
8018 /* Go around the back buffer and manually clear the
8019 window the first time we show it. This way, we avoid
8020 showing users the sanity-defying horror of whatever
8021 GtkWindow is rendering beneath us. We've garbaged
8022 the frame, so we'll redraw the whole thing on next
8023 redisplay anyway. Yuck. */
8024 x_clear_area1 (
8025 FRAME_X_DISPLAY (f),
8026 FRAME_X_WINDOW (f),
8027 event->xexpose.x, event->xexpose.y,
8028 event->xexpose.width, event->xexpose.height,
8030 x_clear_under_internal_border (f);
8031 #endif
8035 if (!FRAME_GARBAGED_P (f))
8037 #ifdef USE_GTK
8038 /* This seems to be needed for GTK 2.6 and later, see
8039 https://debbugs.gnu.org/cgi/bugreport.cgi?bug=15398. */
8040 x_clear_area (f,
8041 event->xexpose.x, event->xexpose.y,
8042 event->xexpose.width, event->xexpose.height);
8043 #endif
8044 expose_frame (f, event->xexpose.x, event->xexpose.y,
8045 event->xexpose.width, event->xexpose.height);
8046 #ifdef USE_GTK
8047 x_clear_under_internal_border (f);
8048 #endif
8051 if (!FRAME_GARBAGED_P (f))
8052 show_back_buffer (f);
8054 else
8056 #ifndef USE_TOOLKIT_SCROLL_BARS
8057 struct scroll_bar *bar;
8058 #endif
8059 #if defined USE_LUCID
8060 /* Submenus of the Lucid menu bar aren't widgets
8061 themselves, so there's no way to dispatch events
8062 to them. Recognize this case separately. */
8064 Widget widget = x_window_to_menu_bar (event->xexpose.window);
8065 if (widget)
8066 xlwmenu_redisplay (widget);
8068 #endif /* USE_LUCID */
8070 #ifdef USE_TOOLKIT_SCROLL_BARS
8071 /* Dispatch event to the widget. */
8072 goto OTHER;
8073 #else /* not USE_TOOLKIT_SCROLL_BARS */
8074 bar = x_window_to_scroll_bar (event->xexpose.display,
8075 event->xexpose.window, 2);
8077 if (bar)
8078 x_scroll_bar_expose (bar, event);
8079 #ifdef USE_X_TOOLKIT
8080 else
8081 goto OTHER;
8082 #endif /* USE_X_TOOLKIT */
8083 #endif /* not USE_TOOLKIT_SCROLL_BARS */
8085 break;
8087 case GraphicsExpose: /* This occurs when an XCopyArea's
8088 source area was obscured or not
8089 available. */
8090 f = x_window_to_frame (dpyinfo, event->xgraphicsexpose.drawable);
8091 if (f)
8093 expose_frame (f, event->xgraphicsexpose.x,
8094 event->xgraphicsexpose.y,
8095 event->xgraphicsexpose.width,
8096 event->xgraphicsexpose.height);
8097 #ifdef USE_GTK
8098 x_clear_under_internal_border (f);
8099 #endif
8100 show_back_buffer (f);
8102 #ifdef USE_X_TOOLKIT
8103 else
8104 goto OTHER;
8105 #endif /* USE_X_TOOLKIT */
8106 break;
8108 case NoExpose: /* This occurs when an XCopyArea's
8109 source area was completely
8110 available. */
8111 break;
8113 case UnmapNotify:
8114 /* Redo the mouse-highlight after the tooltip has gone. */
8115 if (event->xunmap.window == tip_window)
8117 tip_window = None;
8118 x_redo_mouse_highlight (dpyinfo);
8121 f = x_top_window_to_frame (dpyinfo, event->xunmap.window);
8122 if (f) /* F may no longer exist if
8123 the frame was deleted. */
8125 bool visible = FRAME_VISIBLE_P (f);
8126 /* While a frame is unmapped, display generation is
8127 disabled; you don't want to spend time updating a
8128 display that won't ever be seen. */
8129 SET_FRAME_VISIBLE (f, 0);
8130 /* We can't distinguish, from the event, whether the window
8131 has become iconified or invisible. So assume, if it
8132 was previously visible, than now it is iconified.
8133 But x_make_frame_invisible clears both
8134 the visible flag and the iconified flag;
8135 and that way, we know the window is not iconified now. */
8136 if (visible || FRAME_ICONIFIED_P (f))
8138 SET_FRAME_ICONIFIED (f, true);
8139 inev.ie.kind = ICONIFY_EVENT;
8140 XSETFRAME (inev.ie.frame_or_window, f);
8143 goto OTHER;
8145 case MapNotify:
8146 /* We use x_top_window_to_frame because map events can
8147 come for sub-windows and they don't mean that the
8148 frame is visible. */
8149 f = x_top_window_to_frame (dpyinfo, event->xmap.window);
8150 if (f)
8152 bool iconified = FRAME_ICONIFIED_P (f);
8154 /* Check if fullscreen was specified before we where mapped the
8155 first time, i.e. from the command line. */
8156 if (!f->output_data.x->has_been_visible)
8159 x_check_fullscreen (f);
8160 #ifndef USE_GTK
8161 /* For systems that cannot synthesize `skip_taskbar' for
8162 unmapped windows do the following. */
8163 if (FRAME_SKIP_TASKBAR (f))
8164 x_set_skip_taskbar (f, Qt, Qnil);
8165 #endif /* Not USE_GTK */
8168 if (!iconified)
8170 /* The `z-group' is reset every time a frame becomes
8171 invisible. Handle this here. */
8172 if (FRAME_Z_GROUP (f) == z_group_above)
8173 x_set_z_group (f, Qabove, Qnil);
8174 else if (FRAME_Z_GROUP (f) == z_group_below)
8175 x_set_z_group (f, Qbelow, Qnil);
8178 SET_FRAME_VISIBLE (f, 1);
8179 SET_FRAME_ICONIFIED (f, false);
8180 f->output_data.x->has_been_visible = true;
8182 if (iconified)
8184 inev.ie.kind = DEICONIFY_EVENT;
8185 XSETFRAME (inev.ie.frame_or_window, f);
8187 else if (! NILP (Vframe_list) && ! NILP (XCDR (Vframe_list)))
8188 /* Force a redisplay sooner or later to update the
8189 frame titles in case this is the second frame. */
8190 record_asynch_buffer_change ();
8192 goto OTHER;
8194 case KeyPress:
8196 x_display_set_last_user_time (dpyinfo, event->xkey.time);
8197 ignore_next_mouse_click_timeout = 0;
8199 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
8200 /* Dispatch KeyPress events when in menu. */
8201 if (popup_activated ())
8202 goto OTHER;
8203 #endif
8205 f = any;
8207 /* If mouse-highlight is an integer, input clears out
8208 mouse highlighting. */
8209 if (!hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight)
8210 #if ! defined (USE_GTK)
8211 && (f == 0
8212 || !EQ (f->tool_bar_window, hlinfo->mouse_face_window))
8213 #endif
8216 clear_mouse_face (hlinfo);
8217 hlinfo->mouse_face_hidden = true;
8220 #if defined USE_MOTIF && defined USE_TOOLKIT_SCROLL_BARS
8221 if (f == 0)
8223 /* Scroll bars consume key events, but we want
8224 the keys to go to the scroll bar's frame. */
8225 Widget widget = XtWindowToWidget (dpyinfo->display,
8226 event->xkey.window);
8227 if (widget && XmIsScrollBar (widget))
8229 widget = XtParent (widget);
8230 f = x_any_window_to_frame (dpyinfo, XtWindow (widget));
8233 #endif /* USE_MOTIF and USE_TOOLKIT_SCROLL_BARS */
8235 if (f != 0)
8237 KeySym keysym, orig_keysym;
8238 /* al%imercury@uunet.uu.net says that making this 81
8239 instead of 80 fixed a bug whereby meta chars made
8240 his Emacs hang.
8242 It seems that some version of XmbLookupString has
8243 a bug of not returning XBufferOverflow in
8244 status_return even if the input is too long to
8245 fit in 81 bytes. So, we must prepare sufficient
8246 bytes for copy_buffer. 513 bytes (256 chars for
8247 two-byte character set) seems to be a fairly good
8248 approximation. -- 2000.8.10 handa@etl.go.jp */
8249 unsigned char copy_buffer[513];
8250 unsigned char *copy_bufptr = copy_buffer;
8251 int copy_bufsiz = sizeof (copy_buffer);
8252 int modifiers;
8253 Lisp_Object coding_system = Qlatin_1;
8254 Lisp_Object c;
8255 /* Event will be modified. */
8256 XKeyEvent xkey = event->xkey;
8258 #ifdef USE_GTK
8259 /* Don't pass keys to GTK. A Tab will shift focus to the
8260 tool bar in GTK 2.4. Keys will still go to menus and
8261 dialogs because in that case popup_activated is nonzero
8262 (see above). */
8263 *finish = X_EVENT_DROP;
8264 #endif
8266 xkey.state |= x_emacs_to_x_modifiers (FRAME_DISPLAY_INFO (f),
8267 extra_keyboard_modifiers);
8268 modifiers = xkey.state;
8270 /* This will have to go some day... */
8272 /* make_lispy_event turns chars into control chars.
8273 Don't do it here because XLookupString is too eager. */
8274 xkey.state &= ~ControlMask;
8275 xkey.state &= ~(dpyinfo->meta_mod_mask
8276 | dpyinfo->super_mod_mask
8277 | dpyinfo->hyper_mod_mask
8278 | dpyinfo->alt_mod_mask);
8280 /* In case Meta is ComposeCharacter,
8281 clear its status. According to Markus Ehrnsperger
8282 Markus.Ehrnsperger@lehrstuhl-bross.physik.uni-muenchen.de
8283 this enables ComposeCharacter to work whether or
8284 not it is combined with Meta. */
8285 if (modifiers & dpyinfo->meta_mod_mask)
8286 memset (&compose_status, 0, sizeof (compose_status));
8288 #ifdef HAVE_X_I18N
8289 if (FRAME_XIC (f))
8291 Status status_return;
8293 coding_system = Vlocale_coding_system;
8294 nbytes = XmbLookupString (FRAME_XIC (f),
8295 &xkey, (char *) copy_bufptr,
8296 copy_bufsiz, &keysym,
8297 &status_return);
8298 if (status_return == XBufferOverflow)
8300 copy_bufsiz = nbytes + 1;
8301 copy_bufptr = alloca (copy_bufsiz);
8302 nbytes = XmbLookupString (FRAME_XIC (f),
8303 &xkey, (char *) copy_bufptr,
8304 copy_bufsiz, &keysym,
8305 &status_return);
8307 /* Xutf8LookupString is a new but already deprecated interface. -stef */
8308 if (status_return == XLookupNone)
8309 break;
8310 else if (status_return == XLookupChars)
8312 keysym = NoSymbol;
8313 modifiers = 0;
8315 else if (status_return != XLookupKeySym
8316 && status_return != XLookupBoth)
8317 emacs_abort ();
8319 else
8320 nbytes = XLookupString (&xkey, (char *) copy_bufptr,
8321 copy_bufsiz, &keysym,
8322 &compose_status);
8323 #else
8324 nbytes = XLookupString (&xkey, (char *) copy_bufptr,
8325 copy_bufsiz, &keysym,
8326 &compose_status);
8327 #endif
8329 /* If not using XIM/XIC, and a compose sequence is in progress,
8330 we break here. Otherwise, chars_matched is always 0. */
8331 if (compose_status.chars_matched > 0 && nbytes == 0)
8332 break;
8334 memset (&compose_status, 0, sizeof (compose_status));
8335 orig_keysym = keysym;
8337 /* Common for all keysym input events. */
8338 XSETFRAME (inev.ie.frame_or_window, f);
8339 inev.ie.modifiers
8340 = x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO (f), modifiers);
8341 inev.ie.timestamp = xkey.time;
8343 /* First deal with keysyms which have defined
8344 translations to characters. */
8345 if (keysym >= 32 && keysym < 128)
8346 /* Avoid explicitly decoding each ASCII character. */
8348 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
8349 inev.ie.code = keysym;
8350 goto done_keysym;
8353 /* Keysyms directly mapped to Unicode characters. */
8354 if (keysym >= 0x01000000 && keysym <= 0x0110FFFF)
8356 if (keysym < 0x01000080)
8357 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
8358 else
8359 inev.ie.kind = MULTIBYTE_CHAR_KEYSTROKE_EVENT;
8360 inev.ie.code = keysym & 0xFFFFFF;
8361 goto done_keysym;
8364 /* Now non-ASCII. */
8365 if (HASH_TABLE_P (Vx_keysym_table)
8366 && (c = Fgethash (make_number (keysym),
8367 Vx_keysym_table,
8368 Qnil),
8369 NATNUMP (c)))
8371 inev.ie.kind = (SINGLE_BYTE_CHAR_P (XFASTINT (c))
8372 ? ASCII_KEYSTROKE_EVENT
8373 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
8374 inev.ie.code = XFASTINT (c);
8375 goto done_keysym;
8378 /* Random non-modifier sorts of keysyms. */
8379 if (((keysym >= XK_BackSpace && keysym <= XK_Escape)
8380 || keysym == XK_Delete
8381 #ifdef XK_ISO_Left_Tab
8382 || (keysym >= XK_ISO_Left_Tab
8383 && keysym <= XK_ISO_Enter)
8384 #endif
8385 || IsCursorKey (keysym) /* 0xff50 <= x < 0xff60 */
8386 || IsMiscFunctionKey (keysym) /* 0xff60 <= x < VARIES */
8387 #ifdef HPUX
8388 /* This recognizes the "extended function
8389 keys". It seems there's no cleaner way.
8390 Test IsModifierKey to avoid handling
8391 mode_switch incorrectly. */
8392 || (XK_Select <= keysym && keysym < XK_KP_Space)
8393 #endif
8394 #ifdef XK_dead_circumflex
8395 || orig_keysym == XK_dead_circumflex
8396 #endif
8397 #ifdef XK_dead_grave
8398 || orig_keysym == XK_dead_grave
8399 #endif
8400 #ifdef XK_dead_tilde
8401 || orig_keysym == XK_dead_tilde
8402 #endif
8403 #ifdef XK_dead_diaeresis
8404 || orig_keysym == XK_dead_diaeresis
8405 #endif
8406 #ifdef XK_dead_macron
8407 || orig_keysym == XK_dead_macron
8408 #endif
8409 #ifdef XK_dead_degree
8410 || orig_keysym == XK_dead_degree
8411 #endif
8412 #ifdef XK_dead_acute
8413 || orig_keysym == XK_dead_acute
8414 #endif
8415 #ifdef XK_dead_cedilla
8416 || orig_keysym == XK_dead_cedilla
8417 #endif
8418 #ifdef XK_dead_breve
8419 || orig_keysym == XK_dead_breve
8420 #endif
8421 #ifdef XK_dead_ogonek
8422 || orig_keysym == XK_dead_ogonek
8423 #endif
8424 #ifdef XK_dead_caron
8425 || orig_keysym == XK_dead_caron
8426 #endif
8427 #ifdef XK_dead_doubleacute
8428 || orig_keysym == XK_dead_doubleacute
8429 #endif
8430 #ifdef XK_dead_abovedot
8431 || orig_keysym == XK_dead_abovedot
8432 #endif
8433 || IsKeypadKey (keysym) /* 0xff80 <= x < 0xffbe */
8434 || IsFunctionKey (keysym) /* 0xffbe <= x < 0xffe1 */
8435 /* Any "vendor-specific" key is ok. */
8436 || (orig_keysym & (1 << 28))
8437 || (keysym != NoSymbol && nbytes == 0))
8438 && ! (IsModifierKey (orig_keysym)
8439 /* The symbols from XK_ISO_Lock
8440 to XK_ISO_Last_Group_Lock
8441 don't have real modifiers but
8442 should be treated similarly to
8443 Mode_switch by Emacs. */
8444 #if defined XK_ISO_Lock && defined XK_ISO_Last_Group_Lock
8445 || (XK_ISO_Lock <= orig_keysym
8446 && orig_keysym <= XK_ISO_Last_Group_Lock)
8447 #endif
8450 STORE_KEYSYM_FOR_DEBUG (keysym);
8451 /* make_lispy_event will convert this to a symbolic
8452 key. */
8453 inev.ie.kind = NON_ASCII_KEYSTROKE_EVENT;
8454 inev.ie.code = keysym;
8455 goto done_keysym;
8458 { /* Raw bytes, not keysym. */
8459 ptrdiff_t i;
8460 int nchars, len;
8462 for (i = 0, nchars = 0; i < nbytes; i++)
8464 if (ASCII_CHAR_P (copy_bufptr[i]))
8465 nchars++;
8466 STORE_KEYSYM_FOR_DEBUG (copy_bufptr[i]);
8469 if (nchars < nbytes)
8471 /* Decode the input data. */
8473 /* The input should be decoded with `coding_system'
8474 which depends on which X*LookupString function
8475 we used just above and the locale. */
8476 setup_coding_system (coding_system, &coding);
8477 coding.src_multibyte = false;
8478 coding.dst_multibyte = true;
8479 /* The input is converted to events, thus we can't
8480 handle composition. Anyway, there's no XIM that
8481 gives us composition information. */
8482 coding.common_flags &= ~CODING_ANNOTATION_MASK;
8484 SAFE_NALLOCA (coding.destination, MAX_MULTIBYTE_LENGTH,
8485 nbytes);
8486 coding.dst_bytes = MAX_MULTIBYTE_LENGTH * nbytes;
8487 coding.mode |= CODING_MODE_LAST_BLOCK;
8488 decode_coding_c_string (&coding, copy_bufptr, nbytes, Qnil);
8489 nbytes = coding.produced;
8490 nchars = coding.produced_char;
8491 copy_bufptr = coding.destination;
8494 /* Convert the input data to a sequence of
8495 character events. */
8496 for (i = 0; i < nbytes; i += len)
8498 int ch;
8499 if (nchars == nbytes)
8500 ch = copy_bufptr[i], len = 1;
8501 else
8502 ch = STRING_CHAR_AND_LENGTH (copy_bufptr + i, len);
8503 inev.ie.kind = (SINGLE_BYTE_CHAR_P (ch)
8504 ? ASCII_KEYSTROKE_EVENT
8505 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
8506 inev.ie.code = ch;
8507 kbd_buffer_store_buffered_event (&inev, hold_quit);
8510 count += nchars;
8512 inev.ie.kind = NO_EVENT; /* Already stored above. */
8514 if (keysym == NoSymbol)
8515 break;
8517 /* FIXME: check side effects and remove this. */
8518 ((XEvent *) event)->xkey = xkey;
8520 done_keysym:
8521 #ifdef HAVE_X_I18N
8522 /* Don't dispatch this event since XtDispatchEvent calls
8523 XFilterEvent, and two calls in a row may freeze the
8524 client. */
8525 break;
8526 #else
8527 goto OTHER;
8528 #endif
8530 case KeyRelease:
8531 x_display_set_last_user_time (dpyinfo, event->xkey.time);
8532 #ifdef HAVE_X_I18N
8533 /* Don't dispatch this event since XtDispatchEvent calls
8534 XFilterEvent, and two calls in a row may freeze the
8535 client. */
8536 break;
8537 #else
8538 goto OTHER;
8539 #endif
8541 case EnterNotify:
8542 x_display_set_last_user_time (dpyinfo, event->xcrossing.time);
8543 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
8545 f = any;
8547 if (f && x_mouse_click_focus_ignore_position)
8548 ignore_next_mouse_click_timeout = event->xmotion.time + 200;
8550 /* EnterNotify counts as mouse movement,
8551 so update things that depend on mouse position. */
8552 if (f && !f->output_data.x->hourglass_p)
8553 note_mouse_movement (f, &event->xmotion);
8554 #ifdef USE_GTK
8555 /* We may get an EnterNotify on the buttons in the toolbar. In that
8556 case we moved out of any highlighted area and need to note this. */
8557 if (!f && dpyinfo->last_mouse_glyph_frame)
8558 note_mouse_movement (dpyinfo->last_mouse_glyph_frame, &event->xmotion);
8559 #endif
8560 goto OTHER;
8562 case FocusIn:
8563 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
8564 goto OTHER;
8566 case LeaveNotify:
8567 x_display_set_last_user_time (dpyinfo, event->xcrossing.time);
8568 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
8570 f = x_top_window_to_frame (dpyinfo, event->xcrossing.window);
8571 if (f)
8573 if (f == hlinfo->mouse_face_mouse_frame)
8575 /* If we move outside the frame, then we're
8576 certainly no longer on any text in the frame. */
8577 clear_mouse_face (hlinfo);
8578 hlinfo->mouse_face_mouse_frame = 0;
8581 /* Generate a nil HELP_EVENT to cancel a help-echo.
8582 Do it only if there's something to cancel.
8583 Otherwise, the startup message is cleared when
8584 the mouse leaves the frame. */
8585 if (any_help_event_p)
8586 do_help = -1;
8588 #ifdef USE_GTK
8589 /* See comment in EnterNotify above */
8590 else if (dpyinfo->last_mouse_glyph_frame)
8591 note_mouse_movement (dpyinfo->last_mouse_glyph_frame, &event->xmotion);
8592 #endif
8593 goto OTHER;
8595 case FocusOut:
8596 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
8597 goto OTHER;
8599 case MotionNotify:
8601 x_display_set_last_user_time (dpyinfo, event->xmotion.time);
8602 previous_help_echo_string = help_echo_string;
8603 help_echo_string = Qnil;
8605 f = (x_mouse_grabbed (dpyinfo) ? dpyinfo->last_mouse_frame
8606 : x_window_to_frame (dpyinfo, event->xmotion.window));
8608 if (hlinfo->mouse_face_hidden)
8610 hlinfo->mouse_face_hidden = false;
8611 clear_mouse_face (hlinfo);
8614 #ifdef USE_GTK
8615 if (f && xg_event_is_for_scrollbar (f, event))
8616 f = 0;
8617 #endif
8618 if (f)
8620 /* Maybe generate a SELECT_WINDOW_EVENT for
8621 `mouse-autoselect-window' but don't let popup menus
8622 interfere with this (Bug#1261). */
8623 if (!NILP (Vmouse_autoselect_window)
8624 && !popup_activated ()
8625 /* Don't switch if we're currently in the minibuffer.
8626 This tries to work around problems where the
8627 minibuffer gets unselected unexpectedly, and where
8628 you then have to move your mouse all the way down to
8629 the minibuffer to select it. */
8630 && !MINI_WINDOW_P (XWINDOW (selected_window))
8631 /* With `focus-follows-mouse' non-nil create an event
8632 also when the target window is on another frame. */
8633 && (f == XFRAME (selected_frame)
8634 || !NILP (focus_follows_mouse)))
8636 static Lisp_Object last_mouse_window;
8637 Lisp_Object window = window_from_coordinates
8638 (f, event->xmotion.x, event->xmotion.y, 0, false);
8640 /* A window will be autoselected only when it is not
8641 selected now and the last mouse movement event was
8642 not in it. The remainder of the code is a bit vague
8643 wrt what a "window" is. For immediate autoselection,
8644 the window is usually the entire window but for GTK
8645 where the scroll bars don't count. For delayed
8646 autoselection the window is usually the window's text
8647 area including the margins. */
8648 if (WINDOWP (window)
8649 && !EQ (window, last_mouse_window)
8650 && !EQ (window, selected_window))
8652 inev.ie.kind = SELECT_WINDOW_EVENT;
8653 inev.ie.frame_or_window = window;
8656 /* Remember the last window where we saw the mouse. */
8657 last_mouse_window = window;
8660 if (!note_mouse_movement (f, &event->xmotion))
8661 help_echo_string = previous_help_echo_string;
8663 else
8665 #ifndef USE_TOOLKIT_SCROLL_BARS
8666 struct scroll_bar *bar
8667 = x_window_to_scroll_bar (event->xmotion.display,
8668 event->xmotion.window, 2);
8670 if (bar)
8671 x_scroll_bar_note_movement (bar, &event->xmotion);
8672 #endif /* USE_TOOLKIT_SCROLL_BARS */
8674 /* If we move outside the frame, then we're
8675 certainly no longer on any text in the frame. */
8676 clear_mouse_face (hlinfo);
8679 /* If the contents of the global variable help_echo_string
8680 has changed, generate a HELP_EVENT. */
8681 if (!NILP (help_echo_string)
8682 || !NILP (previous_help_echo_string))
8683 do_help = 1;
8684 goto OTHER;
8687 case ConfigureNotify:
8688 /* An opaque move can generate a stream of events as the window
8689 is dragged around. If the connection round trip time isn't
8690 really short, they may come faster than we can respond to
8691 them, given the multiple queries we can do to check window
8692 manager state, translate coordinates, etc.
8694 So if this ConfigureNotify is immediately followed by another
8695 for the same window, use the info from the latest update, and
8696 consider the events all handled. */
8697 /* Opaque resize may be trickier; ConfigureNotify events are
8698 mixed with Expose events for multiple windows. */
8699 configureEvent = *event;
8700 while (XPending (dpyinfo->display))
8702 XNextEvent (dpyinfo->display, &next_event);
8703 if (next_event.type != ConfigureNotify
8704 || next_event.xconfigure.window != event->xconfigure.window
8705 /* Skipping events with different sizes can lead to a
8706 mispositioned mode line at initial window creation.
8707 Only drop window motion events for now. */
8708 || next_event.xconfigure.width != event->xconfigure.width
8709 || next_event.xconfigure.height != event->xconfigure.height)
8711 XPutBackEvent (dpyinfo->display, &next_event);
8712 break;
8714 else
8715 configureEvent = next_event;
8718 f = x_top_window_to_frame (dpyinfo, configureEvent.xconfigure.window);
8719 /* Unfortunately, we need to call font_drop_xrender_surfaces for
8720 _all_ ConfigureNotify events, otherwise we miss some and
8721 flicker. Don't try to optimize these calls by looking only
8722 for size changes: that's not sufficient. We miss some
8723 surface invalidations and flicker. */
8724 block_input ();
8725 if (f && FRAME_X_DOUBLE_BUFFERED_P (f))
8726 font_drop_xrender_surfaces (f);
8727 unblock_input ();
8728 #ifdef USE_CAIRO
8729 if (f) x_cr_destroy_surface (f);
8730 #endif
8731 #ifdef USE_GTK
8732 if (!f
8733 && (f = any)
8734 && configureEvent.xconfigure.window == FRAME_X_WINDOW (f))
8736 block_input ();
8737 if (FRAME_X_DOUBLE_BUFFERED_P (f))
8738 font_drop_xrender_surfaces (f);
8739 unblock_input ();
8740 xg_frame_resized (f, configureEvent.xconfigure.width,
8741 configureEvent.xconfigure.height);
8742 #ifdef USE_CAIRO
8743 x_cr_destroy_surface (f);
8744 #endif
8745 f = 0;
8747 #endif
8748 if (f)
8750 #ifdef USE_GTK
8751 /* For GTK+ don't call x_net_wm_state for the scroll bar
8752 window. (Bug#24963, Bug#25887) */
8753 if (configureEvent.xconfigure.window == FRAME_X_WINDOW (f))
8754 #endif
8755 x_net_wm_state (f, configureEvent.xconfigure.window);
8757 #ifdef USE_X_TOOLKIT
8758 /* Tip frames are pure X window, set size for them. */
8759 if (FRAME_TOOLTIP_P (f))
8761 if (FRAME_PIXEL_HEIGHT (f) != configureEvent.xconfigure.height
8762 || FRAME_PIXEL_WIDTH (f) != configureEvent.xconfigure.width)
8764 SET_FRAME_GARBAGED (f);
8766 FRAME_PIXEL_HEIGHT (f) = configureEvent.xconfigure.height;
8767 FRAME_PIXEL_WIDTH (f) = configureEvent.xconfigure.width;
8769 #endif
8771 #ifndef USE_X_TOOLKIT
8772 #ifndef USE_GTK
8773 int width =
8774 FRAME_PIXEL_TO_TEXT_WIDTH (f, configureEvent.xconfigure.width);
8775 int height =
8776 FRAME_PIXEL_TO_TEXT_HEIGHT (f, configureEvent.xconfigure.height);
8778 /* In the toolkit version, change_frame_size
8779 is called by the code that handles resizing
8780 of the EmacsFrame widget. */
8782 /* Even if the number of character rows and columns has
8783 not changed, the font size may have changed, so we need
8784 to check the pixel dimensions as well. */
8785 if (width != FRAME_TEXT_WIDTH (f)
8786 || height != FRAME_TEXT_HEIGHT (f)
8787 || configureEvent.xconfigure.width != FRAME_PIXEL_WIDTH (f)
8788 || configureEvent.xconfigure.height != FRAME_PIXEL_HEIGHT (f))
8790 change_frame_size (f, width, height, false, true, false, true);
8791 x_clear_under_internal_border (f);
8792 SET_FRAME_GARBAGED (f);
8793 cancel_mouse_face (f);
8795 #endif /* not USE_GTK */
8796 #endif
8798 #ifdef USE_GTK
8799 /* GTK creates windows but doesn't map them.
8800 Only get real positions when mapped. */
8801 if (FRAME_GTK_OUTER_WIDGET (f)
8802 && gtk_widget_get_mapped (FRAME_GTK_OUTER_WIDGET (f)))
8803 #endif
8805 int old_left = f->left_pos;
8806 int old_top = f->top_pos;
8807 Lisp_Object frame = Qnil;
8809 XSETFRAME (frame, f);
8811 if (!FRAME_PARENT_FRAME (f))
8812 x_real_positions (f, &f->left_pos, &f->top_pos);
8813 else
8815 Window root;
8816 unsigned int dummy_uint;
8818 block_input ();
8819 XGetGeometry (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8820 &root, &f->left_pos, &f->top_pos,
8821 &dummy_uint, &dummy_uint, &dummy_uint, &dummy_uint);
8822 unblock_input ();
8825 if (old_left != f->left_pos || old_top != f->top_pos)
8827 inev.ie.kind = MOVE_FRAME_EVENT;
8828 XSETFRAME (inev.ie.frame_or_window, f);
8833 #ifdef HAVE_X_I18N
8834 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMStatusArea))
8835 xic_set_statusarea (f);
8836 #endif
8839 goto OTHER;
8841 case ButtonRelease:
8842 case ButtonPress:
8844 /* If we decide we want to generate an event to be seen
8845 by the rest of Emacs, we put it here. */
8846 bool tool_bar_p = false;
8848 memset (&compose_status, 0, sizeof (compose_status));
8849 dpyinfo->last_mouse_glyph_frame = NULL;
8850 x_display_set_last_user_time (dpyinfo, event->xbutton.time);
8852 if (x_mouse_grabbed (dpyinfo))
8853 f = dpyinfo->last_mouse_frame;
8854 else
8856 f = x_window_to_frame (dpyinfo, event->xbutton.window);
8858 if (f && event->xbutton.type == ButtonPress
8859 && !popup_activated ()
8860 && !x_window_to_scroll_bar (event->xbutton.display,
8861 event->xbutton.window, 2)
8862 && !FRAME_NO_ACCEPT_FOCUS (f))
8864 /* When clicking into a child frame or when clicking
8865 into a parent frame with the child frame selected and
8866 `no-accept-focus' is not set, select the clicked
8867 frame. */
8868 struct frame *hf = dpyinfo->x_highlight_frame;
8870 if (FRAME_PARENT_FRAME (f) || (hf && frame_ancestor_p (f, hf)))
8872 block_input ();
8873 XSetInputFocus (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8874 RevertToParent, CurrentTime);
8875 if (FRAME_PARENT_FRAME (f))
8876 XRaiseWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
8877 unblock_input ();
8882 #ifdef USE_GTK
8883 if (f && xg_event_is_for_scrollbar (f, event))
8884 f = 0;
8885 #endif
8886 if (f)
8888 #if ! defined (USE_GTK)
8889 /* Is this in the tool-bar? */
8890 if (WINDOWP (f->tool_bar_window)
8891 && WINDOW_TOTAL_LINES (XWINDOW (f->tool_bar_window)))
8893 Lisp_Object window;
8894 int x = event->xbutton.x;
8895 int y = event->xbutton.y;
8897 window = window_from_coordinates (f, x, y, 0, true);
8898 tool_bar_p = EQ (window, f->tool_bar_window);
8900 if (tool_bar_p && event->xbutton.button < 4)
8901 handle_tool_bar_click
8902 (f, x, y, event->xbutton.type == ButtonPress,
8903 x_x_to_emacs_modifiers (dpyinfo, event->xbutton.state));
8905 #endif /* !USE_GTK */
8907 if (!tool_bar_p)
8908 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
8909 if (! popup_activated ())
8910 #endif
8912 if (ignore_next_mouse_click_timeout)
8914 if (event->type == ButtonPress
8915 && event->xbutton.time > ignore_next_mouse_click_timeout)
8917 ignore_next_mouse_click_timeout = 0;
8918 construct_mouse_click (&inev.ie, &event->xbutton, f);
8920 if (event->type == ButtonRelease)
8921 ignore_next_mouse_click_timeout = 0;
8923 else
8924 construct_mouse_click (&inev.ie, &event->xbutton, f);
8926 if (FRAME_X_EMBEDDED_P (f))
8927 xembed_send_message (f, event->xbutton.time,
8928 XEMBED_REQUEST_FOCUS, 0, 0, 0);
8930 else
8932 struct scroll_bar *bar
8933 = x_window_to_scroll_bar (event->xbutton.display,
8934 event->xbutton.window, 2);
8936 #ifdef USE_TOOLKIT_SCROLL_BARS
8937 /* Make the "Ctrl-Mouse-2 splits window" work for toolkit
8938 scroll bars. */
8939 if (bar && event->xbutton.state & ControlMask)
8941 x_scroll_bar_handle_click (bar, event, &inev.ie);
8942 *finish = X_EVENT_DROP;
8944 #else /* not USE_TOOLKIT_SCROLL_BARS */
8945 if (bar)
8946 x_scroll_bar_handle_click (bar, event, &inev.ie);
8947 #endif /* not USE_TOOLKIT_SCROLL_BARS */
8950 if (event->type == ButtonPress)
8952 dpyinfo->grabbed |= (1 << event->xbutton.button);
8953 dpyinfo->last_mouse_frame = f;
8954 #if ! defined (USE_GTK)
8955 if (f && !tool_bar_p)
8956 f->last_tool_bar_item = -1;
8957 #endif /* not USE_GTK */
8959 else
8960 dpyinfo->grabbed &= ~(1 << event->xbutton.button);
8962 /* Ignore any mouse motion that happened before this event;
8963 any subsequent mouse-movement Emacs events should reflect
8964 only motion after the ButtonPress/Release. */
8965 if (f != 0)
8966 f->mouse_moved = false;
8968 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
8969 f = x_menubar_window_to_frame (dpyinfo, event);
8970 /* For a down-event in the menu bar,
8971 don't pass it to Xt right now.
8972 Instead, save it away
8973 and we will pass it to Xt from kbd_buffer_get_event.
8974 That way, we can run some Lisp code first. */
8975 if (! popup_activated ()
8976 #ifdef USE_GTK
8977 /* Gtk+ menus only react to the first three buttons. */
8978 && event->xbutton.button < 3
8979 #endif
8980 && f && event->type == ButtonPress
8981 /* Verify the event is really within the menu bar
8982 and not just sent to it due to grabbing. */
8983 && event->xbutton.x >= 0
8984 && event->xbutton.x < FRAME_PIXEL_WIDTH (f)
8985 && event->xbutton.y >= 0
8986 && event->xbutton.y < FRAME_MENUBAR_HEIGHT (f)
8987 && event->xbutton.same_screen)
8989 if (!f->output_data.x->saved_menu_event)
8990 f->output_data.x->saved_menu_event = xmalloc (sizeof *event);
8991 *f->output_data.x->saved_menu_event = *event;
8992 inev.ie.kind = MENU_BAR_ACTIVATE_EVENT;
8993 XSETFRAME (inev.ie.frame_or_window, f);
8994 *finish = X_EVENT_DROP;
8996 else
8997 goto OTHER;
8998 #endif /* USE_X_TOOLKIT || USE_GTK */
9000 break;
9002 case CirculateNotify:
9003 goto OTHER;
9005 case CirculateRequest:
9006 goto OTHER;
9008 case VisibilityNotify:
9009 goto OTHER;
9011 case MappingNotify:
9012 /* Someone has changed the keyboard mapping - update the
9013 local cache. */
9014 switch (event->xmapping.request)
9016 case MappingModifier:
9017 x_find_modifier_meanings (dpyinfo);
9018 FALLTHROUGH;
9019 case MappingKeyboard:
9020 XRefreshKeyboardMapping ((XMappingEvent *) &event->xmapping);
9022 goto OTHER;
9024 case DestroyNotify:
9025 xft_settings_event (dpyinfo, event);
9026 break;
9028 default:
9029 OTHER:
9030 #ifdef USE_X_TOOLKIT
9031 block_input ();
9032 if (*finish != X_EVENT_DROP)
9033 XtDispatchEvent ((XEvent *) event);
9034 unblock_input ();
9035 #endif /* USE_X_TOOLKIT */
9036 break;
9039 done:
9040 if (inev.ie.kind != NO_EVENT)
9042 kbd_buffer_store_buffered_event (&inev, hold_quit);
9043 count++;
9046 if (do_help
9047 && !(hold_quit && hold_quit->kind != NO_EVENT))
9049 Lisp_Object frame;
9051 if (f)
9052 XSETFRAME (frame, f);
9053 else
9054 frame = Qnil;
9056 if (do_help > 0)
9058 any_help_event_p = true;
9059 gen_help_event (help_echo_string, frame, help_echo_window,
9060 help_echo_object, help_echo_pos);
9062 else
9064 help_echo_string = Qnil;
9065 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
9067 count++;
9070 /* Sometimes event processing draws to the frame outside redisplay.
9071 To ensure that these changes become visible, draw them here. */
9072 flush_dirty_back_buffers ();
9073 SAFE_FREE ();
9074 return count;
9077 #if defined USE_X_TOOLKIT || defined USE_MOTIF || defined USE_GTK
9079 /* Handles the XEvent EVENT on display DISPLAY.
9080 This is used for event loops outside the normal event handling,
9081 i.e. looping while a popup menu or a dialog is posted.
9083 Returns the value handle_one_xevent sets in the finish argument. */
9085 x_dispatch_event (XEvent *event, Display *display)
9087 struct x_display_info *dpyinfo;
9088 int finish = X_EVENT_NORMAL;
9090 dpyinfo = x_display_info_for_display (display);
9092 if (dpyinfo)
9093 handle_one_xevent (dpyinfo, event, &finish, 0);
9095 return finish;
9097 #endif
9099 /* Read events coming from the X server.
9100 Return as soon as there are no more events to be read.
9102 Return the number of characters stored into the buffer,
9103 thus pretending to be `read' (except the characters we store
9104 in the keyboard buffer can be multibyte, so are not necessarily
9105 C chars). */
9107 static int
9108 XTread_socket (struct terminal *terminal, struct input_event *hold_quit)
9110 int count = 0;
9111 bool event_found = false;
9112 struct x_display_info *dpyinfo = terminal->display_info.x;
9114 block_input ();
9116 /* For debugging, this gives a way to fake an I/O error. */
9117 if (dpyinfo == XTread_socket_fake_io_error)
9119 XTread_socket_fake_io_error = 0;
9120 x_io_error_quitter (dpyinfo->display);
9123 #ifndef USE_GTK
9124 while (XPending (dpyinfo->display))
9126 int finish;
9127 XEvent event;
9129 XNextEvent (dpyinfo->display, &event);
9131 #ifdef HAVE_X_I18N
9132 /* Filter events for the current X input method. */
9133 if (x_filter_event (dpyinfo, &event))
9134 continue;
9135 #endif
9136 event_found = true;
9138 count += handle_one_xevent (dpyinfo, &event, &finish, hold_quit);
9140 if (finish == X_EVENT_GOTO_OUT)
9141 break;
9144 #else /* USE_GTK */
9146 /* For GTK we must use the GTK event loop. But XEvents gets passed
9147 to our filter function above, and then to the big event switch.
9148 We use a bunch of globals to communicate with our filter function,
9149 that is kind of ugly, but it works.
9151 There is no way to do one display at the time, GTK just does events
9152 from all displays. */
9154 while (gtk_events_pending ())
9156 current_count = count;
9157 current_hold_quit = hold_quit;
9159 gtk_main_iteration ();
9161 count = current_count;
9162 current_count = -1;
9163 current_hold_quit = 0;
9165 if (current_finish == X_EVENT_GOTO_OUT)
9166 break;
9168 #endif /* USE_GTK */
9170 /* On some systems, an X bug causes Emacs to get no more events
9171 when the window is destroyed. Detect that. (1994.) */
9172 if (! event_found)
9174 /* Emacs and the X Server eats up CPU time if XNoOp is done every time.
9175 One XNOOP in 100 loops will make Emacs terminate.
9176 B. Bretthauer, 1994 */
9177 x_noop_count++;
9178 if (x_noop_count >= 100)
9180 x_noop_count=0;
9182 if (next_noop_dpyinfo == 0)
9183 next_noop_dpyinfo = x_display_list;
9185 XNoOp (next_noop_dpyinfo->display);
9187 /* Each time we get here, cycle through the displays now open. */
9188 next_noop_dpyinfo = next_noop_dpyinfo->next;
9192 /* If the focus was just given to an auto-raising frame,
9193 raise it now. FIXME: handle more than one such frame. */
9194 if (dpyinfo->x_pending_autoraise_frame)
9196 x_raise_frame (dpyinfo->x_pending_autoraise_frame);
9197 dpyinfo->x_pending_autoraise_frame = NULL;
9200 unblock_input ();
9202 return count;
9208 /***********************************************************************
9209 Text Cursor
9210 ***********************************************************************/
9212 /* Set clipping for output in glyph row ROW. W is the window in which
9213 we operate. GC is the graphics context to set clipping in.
9215 ROW may be a text row or, e.g., a mode line. Text rows must be
9216 clipped to the interior of the window dedicated to text display,
9217 mode lines must be clipped to the whole window. */
9219 static void
9220 x_clip_to_row (struct window *w, struct glyph_row *row,
9221 enum glyph_row_area area, GC gc)
9223 struct frame *f = XFRAME (WINDOW_FRAME (w));
9224 XRectangle clip_rect;
9225 int window_x, window_y, window_width;
9227 window_box (w, area, &window_x, &window_y, &window_width, 0);
9229 clip_rect.x = window_x;
9230 clip_rect.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
9231 clip_rect.y = max (clip_rect.y, window_y);
9232 clip_rect.width = window_width;
9233 clip_rect.height = row->visible_height;
9235 x_set_clip_rectangles (f, gc, &clip_rect, 1);
9239 /* Draw a hollow box cursor on window W in glyph row ROW. */
9241 static void
9242 x_draw_hollow_cursor (struct window *w, struct glyph_row *row)
9244 struct frame *f = XFRAME (WINDOW_FRAME (w));
9245 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
9246 Display *dpy = FRAME_X_DISPLAY (f);
9247 int x, y, wd, h;
9248 XGCValues xgcv;
9249 struct glyph *cursor_glyph;
9250 GC gc;
9252 /* Get the glyph the cursor is on. If we can't tell because
9253 the current matrix is invalid or such, give up. */
9254 cursor_glyph = get_phys_cursor_glyph (w);
9255 if (cursor_glyph == NULL)
9256 return;
9258 /* Compute frame-relative coordinates for phys cursor. */
9259 get_phys_cursor_geometry (w, row, cursor_glyph, &x, &y, &h);
9260 wd = w->phys_cursor_width - 1;
9262 /* The foreground of cursor_gc is typically the same as the normal
9263 background color, which can cause the cursor box to be invisible. */
9264 xgcv.foreground = f->output_data.x->cursor_pixel;
9265 if (dpyinfo->scratch_cursor_gc)
9266 XChangeGC (dpy, dpyinfo->scratch_cursor_gc, GCForeground, &xgcv);
9267 else
9268 dpyinfo->scratch_cursor_gc = XCreateGC (dpy, FRAME_X_DRAWABLE (f),
9269 GCForeground, &xgcv);
9270 gc = dpyinfo->scratch_cursor_gc;
9272 /* When on R2L character, show cursor at the right edge of the
9273 glyph, unless the cursor box is as wide as the glyph or wider
9274 (the latter happens when x-stretch-cursor is non-nil). */
9275 if ((cursor_glyph->resolved_level & 1) != 0
9276 && cursor_glyph->pixel_width > wd)
9278 x += cursor_glyph->pixel_width - wd;
9279 if (wd > 0)
9280 wd -= 1;
9282 /* Set clipping, draw the rectangle, and reset clipping again. */
9283 x_clip_to_row (w, row, TEXT_AREA, gc);
9284 x_draw_rectangle (f, gc, x, y, wd, h - 1);
9285 x_reset_clip_rectangles (f, gc);
9289 /* Draw a bar cursor on window W in glyph row ROW.
9291 Implementation note: One would like to draw a bar cursor with an
9292 angle equal to the one given by the font property XA_ITALIC_ANGLE.
9293 Unfortunately, I didn't find a font yet that has this property set.
9294 --gerd. */
9296 static void
9297 x_draw_bar_cursor (struct window *w, struct glyph_row *row, int width, enum text_cursor_kinds kind)
9299 struct frame *f = XFRAME (w->frame);
9300 struct glyph *cursor_glyph;
9302 /* If cursor is out of bounds, don't draw garbage. This can happen
9303 in mini-buffer windows when switching between echo area glyphs
9304 and mini-buffer. */
9305 cursor_glyph = get_phys_cursor_glyph (w);
9306 if (cursor_glyph == NULL)
9307 return;
9309 /* Experimental avoidance of cursor on xwidget. */
9310 if (cursor_glyph->type == XWIDGET_GLYPH)
9311 return;
9313 /* If on an image, draw like a normal cursor. That's usually better
9314 visible than drawing a bar, esp. if the image is large so that
9315 the bar might not be in the window. */
9316 if (cursor_glyph->type == IMAGE_GLYPH)
9318 struct glyph_row *r;
9319 r = MATRIX_ROW (w->current_matrix, w->phys_cursor.vpos);
9320 draw_phys_cursor_glyph (w, r, DRAW_CURSOR);
9322 else
9324 Display *dpy = FRAME_X_DISPLAY (f);
9325 Drawable drawable = FRAME_X_DRAWABLE (f);
9326 GC gc = FRAME_DISPLAY_INFO (f)->scratch_cursor_gc;
9327 unsigned long mask = GCForeground | GCBackground | GCGraphicsExposures;
9328 struct face *face = FACE_FROM_ID (f, cursor_glyph->face_id);
9329 XGCValues xgcv;
9331 /* If the glyph's background equals the color we normally draw
9332 the bars cursor in, the bar cursor in its normal color is
9333 invisible. Use the glyph's foreground color instead in this
9334 case, on the assumption that the glyph's colors are chosen so
9335 that the glyph is legible. */
9336 if (face->background == f->output_data.x->cursor_pixel)
9337 xgcv.background = xgcv.foreground = face->foreground;
9338 else
9339 xgcv.background = xgcv.foreground = f->output_data.x->cursor_pixel;
9340 xgcv.graphics_exposures = False;
9342 if (gc)
9343 XChangeGC (dpy, gc, mask, &xgcv);
9344 else
9346 gc = XCreateGC (dpy, drawable, mask, &xgcv);
9347 FRAME_DISPLAY_INFO (f)->scratch_cursor_gc = gc;
9350 x_clip_to_row (w, row, TEXT_AREA, gc);
9352 if (kind == BAR_CURSOR)
9354 int x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
9356 if (width < 0)
9357 width = FRAME_CURSOR_WIDTH (f);
9358 width = min (cursor_glyph->pixel_width, width);
9360 w->phys_cursor_width = width;
9362 /* If the character under cursor is R2L, draw the bar cursor
9363 on the right of its glyph, rather than on the left. */
9364 if ((cursor_glyph->resolved_level & 1) != 0)
9365 x += cursor_glyph->pixel_width - width;
9367 x_fill_rectangle (f, gc, x,
9368 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y),
9369 width, row->height);
9371 else /* HBAR_CURSOR */
9373 int dummy_x, dummy_y, dummy_h;
9374 int x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
9376 if (width < 0)
9377 width = row->height;
9379 width = min (row->height, width);
9381 get_phys_cursor_geometry (w, row, cursor_glyph, &dummy_x,
9382 &dummy_y, &dummy_h);
9384 if ((cursor_glyph->resolved_level & 1) != 0
9385 && cursor_glyph->pixel_width > w->phys_cursor_width - 1)
9386 x += cursor_glyph->pixel_width - w->phys_cursor_width + 1;
9387 x_fill_rectangle (f, gc, x,
9388 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y +
9389 row->height - width),
9390 w->phys_cursor_width - 1, width);
9393 x_reset_clip_rectangles (f, gc);
9398 /* RIF: Define cursor CURSOR on frame F. */
9400 static void
9401 x_define_frame_cursor (struct frame *f, Cursor cursor)
9403 if (!f->pointer_invisible
9404 && f->output_data.x->current_cursor != cursor)
9405 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), cursor);
9406 f->output_data.x->current_cursor = cursor;
9410 /* RIF: Clear area on frame F. */
9412 static void
9413 x_clear_frame_area (struct frame *f, int x, int y, int width, int height)
9415 x_clear_area (f, x, y, width, height);
9419 /* RIF: Draw cursor on window W. */
9421 static void
9422 x_draw_window_cursor (struct window *w, struct glyph_row *glyph_row, int x,
9423 int y, enum text_cursor_kinds cursor_type,
9424 int cursor_width, bool on_p, bool active_p)
9426 struct frame *f = XFRAME (WINDOW_FRAME (w));
9428 if (on_p)
9430 w->phys_cursor_type = cursor_type;
9431 w->phys_cursor_on_p = true;
9433 if (glyph_row->exact_window_width_line_p
9434 && (glyph_row->reversed_p
9435 ? (w->phys_cursor.hpos < 0)
9436 : (w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])))
9438 glyph_row->cursor_in_fringe_p = true;
9439 draw_fringe_bitmap (w, glyph_row, glyph_row->reversed_p);
9441 else
9443 switch (cursor_type)
9445 case HOLLOW_BOX_CURSOR:
9446 x_draw_hollow_cursor (w, glyph_row);
9447 break;
9449 case FILLED_BOX_CURSOR:
9450 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
9451 break;
9453 case BAR_CURSOR:
9454 x_draw_bar_cursor (w, glyph_row, cursor_width, BAR_CURSOR);
9455 break;
9457 case HBAR_CURSOR:
9458 x_draw_bar_cursor (w, glyph_row, cursor_width, HBAR_CURSOR);
9459 break;
9461 case NO_CURSOR:
9462 w->phys_cursor_width = 0;
9463 break;
9465 default:
9466 emacs_abort ();
9470 #ifdef HAVE_X_I18N
9471 if (w == XWINDOW (f->selected_window))
9472 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMPreeditPosition))
9473 xic_set_preeditarea (w, x, y);
9474 #endif
9477 XFlush (FRAME_X_DISPLAY (f));
9481 /* Icons. */
9483 /* Make the x-window of frame F use the gnu icon bitmap. */
9485 bool
9486 x_bitmap_icon (struct frame *f, Lisp_Object file)
9488 ptrdiff_t bitmap_id;
9490 if (FRAME_X_WINDOW (f) == 0)
9491 return true;
9493 /* Free up our existing icon bitmap and mask if any. */
9494 if (f->output_data.x->icon_bitmap > 0)
9495 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
9496 f->output_data.x->icon_bitmap = 0;
9498 if (STRINGP (file))
9500 #ifdef USE_GTK
9501 /* Use gtk_window_set_icon_from_file () if available,
9502 It's not restricted to bitmaps */
9503 if (xg_set_icon (f, file))
9504 return false;
9505 #endif /* USE_GTK */
9506 bitmap_id = x_create_bitmap_from_file (f, file);
9507 x_create_bitmap_mask (f, bitmap_id);
9509 else
9511 /* Create the GNU bitmap and mask if necessary. */
9512 if (FRAME_DISPLAY_INFO (f)->icon_bitmap_id < 0)
9514 ptrdiff_t rc = -1;
9516 #ifdef USE_GTK
9518 if (xg_set_icon (f, xg_default_icon_file)
9519 || xg_set_icon_from_xpm_data (f, gnu_xpm_bits))
9521 FRAME_DISPLAY_INFO (f)->icon_bitmap_id = -2;
9522 return false;
9525 #elif defined (HAVE_XPM) && defined (HAVE_X_WINDOWS)
9527 rc = x_create_bitmap_from_xpm_data (f, gnu_xpm_bits);
9528 if (rc != -1)
9529 FRAME_DISPLAY_INFO (f)->icon_bitmap_id = rc;
9531 #endif
9533 /* If all else fails, use the (black and white) xbm image. */
9534 if (rc == -1)
9536 rc = x_create_bitmap_from_data (f, (char *) gnu_xbm_bits,
9537 gnu_xbm_width, gnu_xbm_height);
9538 if (rc == -1)
9539 return true;
9541 FRAME_DISPLAY_INFO (f)->icon_bitmap_id = rc;
9542 x_create_bitmap_mask (f, FRAME_DISPLAY_INFO (f)->icon_bitmap_id);
9546 /* The first time we create the GNU bitmap and mask,
9547 this increments the ref-count one extra time.
9548 As a result, the GNU bitmap and mask are never freed.
9549 That way, we don't have to worry about allocating it again. */
9550 x_reference_bitmap (f, FRAME_DISPLAY_INFO (f)->icon_bitmap_id);
9552 bitmap_id = FRAME_DISPLAY_INFO (f)->icon_bitmap_id;
9555 x_wm_set_icon_pixmap (f, bitmap_id);
9556 f->output_data.x->icon_bitmap = bitmap_id;
9558 return false;
9562 /* Make the x-window of frame F use a rectangle with text.
9563 Use ICON_NAME as the text. */
9565 bool
9566 x_text_icon (struct frame *f, const char *icon_name)
9568 if (FRAME_X_WINDOW (f) == 0)
9569 return true;
9572 XTextProperty text;
9573 text.value = (unsigned char *) icon_name;
9574 text.encoding = XA_STRING;
9575 text.format = 8;
9576 text.nitems = strlen (icon_name);
9577 XSetWMIconName (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f), &text);
9580 if (f->output_data.x->icon_bitmap > 0)
9581 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
9582 f->output_data.x->icon_bitmap = 0;
9583 x_wm_set_icon_pixmap (f, 0);
9585 return false;
9588 #define X_ERROR_MESSAGE_SIZE 200
9590 /* If non-nil, this should be a string.
9591 It means catch X errors and store the error message in this string.
9593 The reason we use a stack is that x_catch_error/x_uncatch_error can
9594 be called from a signal handler.
9597 struct x_error_message_stack {
9598 char string[X_ERROR_MESSAGE_SIZE];
9599 Display *dpy;
9600 x_special_error_handler handler;
9601 void *handler_data;
9602 struct x_error_message_stack *prev;
9604 static struct x_error_message_stack *x_error_message;
9606 /* An X error handler which stores the error message in
9607 *x_error_message. This is called from x_error_handler if
9608 x_catch_errors is in effect. */
9610 static void
9611 x_error_catcher (Display *display, XErrorEvent *event)
9613 XGetErrorText (display, event->error_code,
9614 x_error_message->string,
9615 X_ERROR_MESSAGE_SIZE);
9616 if (x_error_message->handler)
9617 x_error_message->handler (display, event, x_error_message->string,
9618 x_error_message->handler_data);
9621 /* Begin trapping X errors for display DPY. Actually we trap X errors
9622 for all displays, but DPY should be the display you are actually
9623 operating on.
9625 After calling this function, X protocol errors no longer cause
9626 Emacs to exit; instead, they are recorded in the string
9627 stored in *x_error_message.
9629 Calling x_check_errors signals an Emacs error if an X error has
9630 occurred since the last call to x_catch_errors or x_check_errors.
9632 Calling x_uncatch_errors resumes the normal error handling.
9633 Calling x_uncatch_errors_after_check is similar, but skips an XSync
9634 to the server, and should be used only immediately after
9635 x_had_errors_p or x_check_errors. */
9637 void
9638 x_catch_errors_with_handler (Display *dpy, x_special_error_handler handler,
9639 void *handler_data)
9641 struct x_error_message_stack *data = xmalloc (sizeof *data);
9643 /* Make sure any errors from previous requests have been dealt with. */
9644 XSync (dpy, False);
9646 data->dpy = dpy;
9647 data->string[0] = 0;
9648 data->handler = handler;
9649 data->handler_data = handler_data;
9650 data->prev = x_error_message;
9651 x_error_message = data;
9654 void
9655 x_catch_errors (Display *dpy)
9657 x_catch_errors_with_handler (dpy, NULL, NULL);
9660 /* Undo the last x_catch_errors call.
9661 DPY should be the display that was passed to x_catch_errors.
9663 This version should be used only if the immediately preceding
9664 X-protocol-related thing was x_check_errors or x_had_error_p, both
9665 of which issue XSync calls, so we don't need to re-sync here. */
9667 void
9668 x_uncatch_errors_after_check (void)
9670 struct x_error_message_stack *tmp;
9672 block_input ();
9673 tmp = x_error_message;
9674 x_error_message = x_error_message->prev;
9675 xfree (tmp);
9676 unblock_input ();
9679 /* Undo the last x_catch_errors call.
9680 DPY should be the display that was passed to x_catch_errors. */
9682 void
9683 x_uncatch_errors (void)
9685 struct x_error_message_stack *tmp;
9687 block_input ();
9689 /* The display may have been closed before this function is called.
9690 Check if it is still open before calling XSync. */
9691 if (x_display_info_for_display (x_error_message->dpy) != 0)
9692 XSync (x_error_message->dpy, False);
9694 tmp = x_error_message;
9695 x_error_message = x_error_message->prev;
9696 xfree (tmp);
9697 unblock_input ();
9700 /* If any X protocol errors have arrived since the last call to
9701 x_catch_errors or x_check_errors, signal an Emacs error using
9702 sprintf (a buffer, FORMAT, the x error message text) as the text. */
9704 void
9705 x_check_errors (Display *dpy, const char *format)
9707 /* Make sure to catch any errors incurred so far. */
9708 XSync (dpy, False);
9710 if (x_error_message->string[0])
9712 char string[X_ERROR_MESSAGE_SIZE];
9713 memcpy (string, x_error_message->string, X_ERROR_MESSAGE_SIZE);
9714 x_uncatch_errors ();
9715 error (format, string);
9719 /* Nonzero if we had any X protocol errors
9720 since we did x_catch_errors on DPY. */
9722 bool
9723 x_had_errors_p (Display *dpy)
9725 /* Make sure to catch any errors incurred so far. */
9726 XSync (dpy, False);
9728 return x_error_message->string[0] != 0;
9731 /* Forget about any errors we have had, since we did x_catch_errors on DPY. */
9733 void
9734 x_clear_errors (Display *dpy)
9736 x_error_message->string[0] = 0;
9739 #if false
9740 /* See comment in unwind_to_catch why calling this is a bad
9741 * idea. --lorentey */
9742 /* Close off all unclosed x_catch_errors calls. */
9744 void
9745 x_fully_uncatch_errors (void)
9747 while (x_error_message)
9748 x_uncatch_errors ();
9750 #endif
9752 #if false
9753 static unsigned int x_wire_count;
9754 x_trace_wire (void)
9756 fprintf (stderr, "Lib call: %d\n", ++x_wire_count);
9758 #endif
9761 /************************************************************************
9762 Handling X errors
9763 ************************************************************************/
9765 /* Error message passed to x_connection_closed. */
9767 static char *error_msg;
9769 /* Handle the loss of connection to display DPY. ERROR_MESSAGE is
9770 the text of an error message that lead to the connection loss. */
9772 static _Noreturn void
9773 x_connection_closed (Display *dpy, const char *error_message, bool ioerror)
9775 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
9776 Lisp_Object frame, tail;
9777 ptrdiff_t idx = SPECPDL_INDEX ();
9779 error_msg = alloca (strlen (error_message) + 1);
9780 strcpy (error_msg, error_message);
9782 /* Inhibit redisplay while frames are being deleted. */
9783 specbind (Qinhibit_redisplay, Qt);
9785 if (dpyinfo)
9787 /* Protect display from being closed when we delete the last
9788 frame on it. */
9789 dpyinfo->reference_count++;
9790 dpyinfo->terminal->reference_count++;
9792 if (ioerror) dpyinfo->display = 0;
9794 /* First delete frames whose mini-buffers are on frames
9795 that are on the dead display. */
9796 FOR_EACH_FRAME (tail, frame)
9798 Lisp_Object minibuf_frame;
9799 minibuf_frame
9800 = WINDOW_FRAME (XWINDOW (FRAME_MINIBUF_WINDOW (XFRAME (frame))));
9801 if (FRAME_X_P (XFRAME (frame))
9802 && FRAME_X_P (XFRAME (minibuf_frame))
9803 && ! EQ (frame, minibuf_frame)
9804 && FRAME_DISPLAY_INFO (XFRAME (minibuf_frame)) == dpyinfo)
9805 delete_frame (frame, Qnoelisp);
9808 /* Now delete all remaining frames on the dead display.
9809 We are now sure none of these is used as the mini-buffer
9810 for another frame that we need to delete. */
9811 FOR_EACH_FRAME (tail, frame)
9812 if (FRAME_X_P (XFRAME (frame))
9813 && FRAME_DISPLAY_INFO (XFRAME (frame)) == dpyinfo)
9815 /* Set this to t so that delete_frame won't get confused
9816 trying to find a replacement. */
9817 kset_default_minibuffer_frame (FRAME_KBOARD (XFRAME (frame)), Qt);
9818 delete_frame (frame, Qnoelisp);
9821 /* If DPYINFO is null, this means we didn't open the display in the
9822 first place, so don't try to close it. */
9823 if (dpyinfo)
9825 /* We can not call XtCloseDisplay here because it calls XSync.
9826 XSync inside the error handler apparently hangs Emacs. On
9827 current Xt versions, this isn't needed either. */
9828 #ifdef USE_GTK
9829 /* A long-standing GTK bug prevents proper disconnect handling
9830 (https://bugzilla.gnome.org/show_bug.cgi?id=85715). Once,
9831 the resulting Glib error message loop filled a user's disk.
9832 To avoid this, kill Emacs unconditionally on disconnect. */
9833 shut_down_emacs (0, Qnil);
9834 fprintf (stderr, "%s\n\
9835 When compiled with GTK, Emacs cannot recover from X disconnects.\n\
9836 This is a GTK bug: https://bugzilla.gnome.org/show_bug.cgi?id=85715\n\
9837 For details, see etc/PROBLEMS.\n",
9838 error_msg);
9839 emacs_abort ();
9840 #endif /* USE_GTK */
9842 /* Indicate that this display is dead. */
9843 dpyinfo->display = 0;
9845 dpyinfo->reference_count--;
9846 dpyinfo->terminal->reference_count--;
9847 if (dpyinfo->reference_count != 0)
9848 /* We have just closed all frames on this display. */
9849 emacs_abort ();
9852 Lisp_Object tmp;
9853 XSETTERMINAL (tmp, dpyinfo->terminal);
9854 Fdelete_terminal (tmp, Qnoelisp);
9858 if (terminal_list == 0)
9860 fprintf (stderr, "%s\n", error_msg);
9861 Fkill_emacs (make_number (70));
9862 /* NOTREACHED */
9865 totally_unblock_input ();
9867 unbind_to (idx, Qnil);
9868 clear_waiting_for_input ();
9870 /* Here, we absolutely have to use a non-local exit (e.g. signal, throw,
9871 longjmp), because returning from this function would get us back into
9872 Xlib's code which will directly call `exit'. */
9873 error ("%s", error_msg);
9876 /* We specifically use it before defining it, so that gcc doesn't inline it,
9877 otherwise gdb doesn't know how to properly put a breakpoint on it. */
9878 static void x_error_quitter (Display *, XErrorEvent *);
9880 /* This is the first-level handler for X protocol errors.
9881 It calls x_error_quitter or x_error_catcher. */
9883 static int
9884 x_error_handler (Display *display, XErrorEvent *event)
9886 #if defined USE_GTK && defined HAVE_GTK3
9887 if ((event->error_code == BadMatch || event->error_code == BadWindow)
9888 && event->request_code == X_SetInputFocus)
9890 return 0;
9892 #endif
9894 if (x_error_message)
9895 x_error_catcher (display, event);
9896 else
9897 x_error_quitter (display, event);
9898 return 0;
9901 /* This is the usual handler for X protocol errors.
9902 It kills all frames on the display that we got the error for.
9903 If that was the only one, it prints an error message and kills Emacs. */
9905 /* .gdbinit puts a breakpoint here, so make sure it is not inlined. */
9907 /* On older GCC versions, just putting x_error_quitter
9908 after x_error_handler prevents inlining into the former. */
9910 static void NO_INLINE
9911 x_error_quitter (Display *display, XErrorEvent *event)
9913 char buf[256], buf1[356];
9915 /* Ignore BadName errors. They can happen because of fonts
9916 or colors that are not defined. */
9918 if (event->error_code == BadName)
9919 return;
9921 /* Note that there is no real way portable across R3/R4 to get the
9922 original error handler. */
9924 XGetErrorText (display, event->error_code, buf, sizeof (buf));
9925 sprintf (buf1, "X protocol error: %s on protocol request %d",
9926 buf, event->request_code);
9927 x_connection_closed (display, buf1, false);
9931 /* This is the handler for X IO errors, always.
9932 It kills all frames on the display that we lost touch with.
9933 If that was the only one, it prints an error message and kills Emacs. */
9935 static _Noreturn int
9936 x_io_error_quitter (Display *display)
9938 char buf[256];
9940 snprintf (buf, sizeof buf, "Connection lost to X server '%s'",
9941 DisplayString (display));
9942 x_connection_closed (display, buf, true);
9943 assume (false);
9946 /* Changing the font of the frame. */
9948 /* Give frame F the font FONT-OBJECT as its default font. The return
9949 value is FONT-OBJECT. FONTSET is an ID of the fontset for the
9950 frame. If it is negative, generate a new fontset from
9951 FONT-OBJECT. */
9953 Lisp_Object
9954 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
9956 struct font *font = XFONT_OBJECT (font_object);
9957 int unit, font_ascent, font_descent;
9958 #ifndef USE_X_TOOLKIT
9959 int old_menu_bar_height = FRAME_MENU_BAR_HEIGHT (f);
9960 Lisp_Object fullscreen;
9961 #endif
9963 if (fontset < 0)
9964 fontset = fontset_from_font (font_object);
9965 FRAME_FONTSET (f) = fontset;
9966 if (FRAME_FONT (f) == font)
9967 /* This font is already set in frame F. There's nothing more to
9968 do. */
9969 return font_object;
9971 FRAME_FONT (f) = font;
9972 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
9973 FRAME_COLUMN_WIDTH (f) = font->average_width;
9974 get_font_ascent_descent (font, &font_ascent, &font_descent);
9975 FRAME_LINE_HEIGHT (f) = font_ascent + font_descent;
9977 #ifndef USE_X_TOOLKIT
9978 FRAME_MENU_BAR_HEIGHT (f) = FRAME_MENU_BAR_LINES (f) * FRAME_LINE_HEIGHT (f);
9979 #endif
9981 /* Compute character columns occupied by scrollbar.
9983 Don't do things differently for non-toolkit scrollbars
9984 (Bug#17163). */
9985 unit = FRAME_COLUMN_WIDTH (f);
9986 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
9987 FRAME_CONFIG_SCROLL_BAR_COLS (f)
9988 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + unit - 1) / unit;
9989 else
9990 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + unit - 1) / unit;
9992 if (FRAME_X_WINDOW (f) != 0)
9994 /* Don't change the size of a tip frame; there's no point in
9995 doing it because it's done in Fx_show_tip, and it leads to
9996 problems because the tip frame has no widget. */
9997 if (!FRAME_TOOLTIP_P (f))
9999 adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
10000 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 3,
10001 false, Qfont);
10002 #ifndef USE_X_TOOLKIT
10003 if (FRAME_MENU_BAR_HEIGHT (f) != old_menu_bar_height
10004 && !f->after_make_frame
10005 && (EQ (frame_inhibit_implied_resize, Qt)
10006 || (CONSP (frame_inhibit_implied_resize)
10007 && NILP (Fmemq (Qfont, frame_inhibit_implied_resize))))
10008 && (NILP (fullscreen = get_frame_param (f, Qfullscreen))
10009 || EQ (fullscreen, Qfullwidth)))
10010 /* If the menu bar height changes, try to keep text height
10011 constant. */
10012 adjust_frame_size
10013 (f, -1, FRAME_TEXT_HEIGHT (f) + FRAME_MENU_BAR_HEIGHT (f)
10014 - old_menu_bar_height, 1, false, Qfont);
10015 #endif /* USE_X_TOOLKIT */
10019 #ifdef HAVE_X_I18N
10020 if (FRAME_XIC (f)
10021 && (FRAME_XIC_STYLE (f) & (XIMPreeditPosition | XIMStatusArea)))
10023 block_input ();
10024 xic_set_xfontset (f, SSDATA (fontset_ascii (fontset)));
10025 unblock_input ();
10027 #endif
10029 return font_object;
10033 /***********************************************************************
10034 X Input Methods
10035 ***********************************************************************/
10037 #ifdef HAVE_X_I18N
10039 #ifdef HAVE_X11R6
10041 /* XIM destroy callback function, which is called whenever the
10042 connection to input method XIM dies. CLIENT_DATA contains a
10043 pointer to the x_display_info structure corresponding to XIM. */
10045 static void
10046 xim_destroy_callback (XIM xim, XPointer client_data, XPointer call_data)
10048 struct x_display_info *dpyinfo = (struct x_display_info *) client_data;
10049 Lisp_Object frame, tail;
10051 block_input ();
10053 /* No need to call XDestroyIC.. */
10054 FOR_EACH_FRAME (tail, frame)
10056 struct frame *f = XFRAME (frame);
10057 if (FRAME_X_P (f) && FRAME_DISPLAY_INFO (f) == dpyinfo)
10059 FRAME_XIC (f) = NULL;
10060 xic_free_xfontset (f);
10064 /* No need to call XCloseIM. */
10065 dpyinfo->xim = NULL;
10066 XFree (dpyinfo->xim_styles);
10067 unblock_input ();
10070 #endif /* HAVE_X11R6 */
10072 /* Open the connection to the XIM server on display DPYINFO.
10073 RESOURCE_NAME is the resource name Emacs uses. */
10075 static void
10076 xim_open_dpy (struct x_display_info *dpyinfo, char *resource_name)
10078 XIM xim;
10080 #ifdef HAVE_XIM
10081 if (use_xim)
10083 if (dpyinfo->xim)
10084 XCloseIM (dpyinfo->xim);
10085 xim = XOpenIM (dpyinfo->display, dpyinfo->xrdb, resource_name,
10086 emacs_class);
10087 dpyinfo->xim = xim;
10089 if (xim)
10091 #ifdef HAVE_X11R6
10092 XIMCallback destroy;
10093 #endif
10095 /* Get supported styles and XIM values. */
10096 XGetIMValues (xim, XNQueryInputStyle, &dpyinfo->xim_styles, NULL);
10098 #ifdef HAVE_X11R6
10099 destroy.callback = xim_destroy_callback;
10100 destroy.client_data = (XPointer)dpyinfo;
10101 XSetIMValues (xim, XNDestroyCallback, &destroy, NULL);
10102 #endif
10106 else
10107 #endif /* HAVE_XIM */
10108 dpyinfo->xim = NULL;
10112 #ifdef HAVE_X11R6_XIM
10114 /* XIM instantiate callback function, which is called whenever an XIM
10115 server is available. DISPLAY is the display of the XIM.
10116 CLIENT_DATA contains a pointer to an xim_inst_t structure created
10117 when the callback was registered. */
10119 static void
10120 xim_instantiate_callback (Display *display, XPointer client_data, XPointer call_data)
10122 struct xim_inst_t *xim_inst = (struct xim_inst_t *) client_data;
10123 struct x_display_info *dpyinfo = xim_inst->dpyinfo;
10125 /* We don't support multiple XIM connections. */
10126 if (dpyinfo->xim)
10127 return;
10129 xim_open_dpy (dpyinfo, xim_inst->resource_name);
10131 /* Create XIC for the existing frames on the same display, as long
10132 as they have no XIC. */
10133 if (dpyinfo->xim && dpyinfo->reference_count > 0)
10135 Lisp_Object tail, frame;
10137 block_input ();
10138 FOR_EACH_FRAME (tail, frame)
10140 struct frame *f = XFRAME (frame);
10142 if (FRAME_X_P (f)
10143 && FRAME_DISPLAY_INFO (f) == xim_inst->dpyinfo)
10144 if (FRAME_XIC (f) == NULL)
10146 create_frame_xic (f);
10147 if (FRAME_XIC_STYLE (f) & XIMStatusArea)
10148 xic_set_statusarea (f);
10149 if (FRAME_XIC_STYLE (f) & XIMPreeditPosition)
10151 struct window *w = XWINDOW (f->selected_window);
10152 xic_set_preeditarea (w, w->cursor.x, w->cursor.y);
10157 unblock_input ();
10161 #endif /* HAVE_X11R6_XIM */
10164 /* Open a connection to the XIM server on display DPYINFO.
10165 RESOURCE_NAME is the resource name for Emacs. On X11R5, open the
10166 connection only at the first time. On X11R6, open the connection
10167 in the XIM instantiate callback function. */
10169 static void
10170 xim_initialize (struct x_display_info *dpyinfo, char *resource_name)
10172 dpyinfo->xim = NULL;
10173 #ifdef HAVE_XIM
10174 if (use_xim)
10176 #ifdef HAVE_X11R6_XIM
10177 struct xim_inst_t *xim_inst = xmalloc (sizeof *xim_inst);
10178 Bool ret;
10180 dpyinfo->xim_callback_data = xim_inst;
10181 xim_inst->dpyinfo = dpyinfo;
10182 xim_inst->resource_name = xstrdup (resource_name);
10183 ret = XRegisterIMInstantiateCallback
10184 (dpyinfo->display, dpyinfo->xrdb, xim_inst->resource_name,
10185 emacs_class, xim_instantiate_callback,
10186 /* This is XPointer in XFree86 but (XPointer *)
10187 on Tru64, at least, hence the configure test. */
10188 (XRegisterIMInstantiateCallback_arg6) xim_inst);
10189 eassert (ret == True);
10190 #else /* not HAVE_X11R6_XIM */
10191 xim_open_dpy (dpyinfo, resource_name);
10192 #endif /* not HAVE_X11R6_XIM */
10194 #endif /* HAVE_XIM */
10198 /* Close the connection to the XIM server on display DPYINFO. */
10200 static void
10201 xim_close_dpy (struct x_display_info *dpyinfo)
10203 #ifdef HAVE_XIM
10204 if (use_xim)
10206 #ifdef HAVE_X11R6_XIM
10207 struct xim_inst_t *xim_inst = dpyinfo->xim_callback_data;
10209 if (dpyinfo->display)
10211 Bool ret = XUnregisterIMInstantiateCallback
10212 (dpyinfo->display, dpyinfo->xrdb, xim_inst->resource_name,
10213 emacs_class, xim_instantiate_callback,
10214 (XRegisterIMInstantiateCallback_arg6) xim_inst);
10215 eassert (ret == True);
10217 xfree (xim_inst->resource_name);
10218 xfree (xim_inst);
10219 #endif /* HAVE_X11R6_XIM */
10220 if (dpyinfo->display)
10221 XCloseIM (dpyinfo->xim);
10222 dpyinfo->xim = NULL;
10223 XFree (dpyinfo->xim_styles);
10225 #endif /* HAVE_XIM */
10228 #endif /* not HAVE_X11R6_XIM */
10232 /* Calculate the absolute position in frame F
10233 from its current recorded position values and gravity. */
10235 static void
10236 x_calc_absolute_position (struct frame *f)
10238 int flags = f->size_hint_flags;
10239 struct frame *p = FRAME_PARENT_FRAME (f);
10241 /* We have nothing to do if the current position
10242 is already for the top-left corner. */
10243 if (! ((flags & XNegative) || (flags & YNegative)))
10244 return;
10246 /* Treat negative positions as relative to the leftmost bottommost
10247 position that fits on the screen. */
10248 if ((flags & XNegative) && (f->left_pos <= 0))
10250 int width = FRAME_PIXEL_WIDTH (f);
10252 /* A frame that has been visible at least once should have outer
10253 edges. */
10254 if (f->output_data.x->has_been_visible && !p)
10256 Lisp_Object frame;
10257 Lisp_Object edges = Qnil;
10259 XSETFRAME (frame, f);
10260 edges = Fx_frame_edges (frame, Qouter_edges);
10261 if (!NILP (edges))
10262 width = (XINT (Fnth (make_number (2), edges))
10263 - XINT (Fnth (make_number (0), edges)));
10266 if (p)
10267 f->left_pos = (FRAME_PIXEL_WIDTH (p) - width - 2 * f->border_width
10268 + f->left_pos);
10269 else
10270 f->left_pos = (x_display_pixel_width (FRAME_DISPLAY_INFO (f))
10271 - width + f->left_pos);
10275 if ((flags & YNegative) && (f->top_pos <= 0))
10277 int height = FRAME_PIXEL_HEIGHT (f);
10279 #if defined USE_X_TOOLKIT && defined USE_MOTIF
10280 /* Something is fishy here. When using Motif, starting Emacs with
10281 `-g -0-0', the frame appears too low by a few pixels.
10283 This seems to be so because initially, while Emacs is starting,
10284 the column widget's height and the frame's pixel height are
10285 different. The column widget's height is the right one. In
10286 later invocations, when Emacs is up, the frame's pixel height
10287 is right, though.
10289 It's not obvious where the initial small difference comes from.
10290 2000-12-01, gerd. */
10292 XtVaGetValues (f->output_data.x->column_widget, XtNheight, &height, NULL);
10293 #endif
10295 if (f->output_data.x->has_been_visible && !p)
10297 Lisp_Object frame;
10298 Lisp_Object edges = Qnil;
10300 XSETFRAME (frame, f);
10301 if (NILP (edges))
10302 edges = Fx_frame_edges (frame, Qouter_edges);
10303 if (!NILP (edges))
10304 height = (XINT (Fnth (make_number (3), edges))
10305 - XINT (Fnth (make_number (1), edges)));
10308 if (p)
10309 f->top_pos = (FRAME_PIXEL_HEIGHT (p) - height - 2 * f->border_width
10310 + f->top_pos);
10311 else
10312 f->top_pos = (x_display_pixel_height (FRAME_DISPLAY_INFO (f))
10313 - height + f->top_pos);
10316 /* The left_pos and top_pos
10317 are now relative to the top and left screen edges,
10318 so the flags should correspond. */
10319 f->size_hint_flags &= ~ (XNegative | YNegative);
10322 /* CHANGE_GRAVITY is 1 when calling from Fset_frame_position,
10323 to really change the position, and 0 when calling from
10324 x_make_frame_visible (in that case, XOFF and YOFF are the current
10325 position values). It is -1 when calling from x_set_frame_parameters,
10326 which means, do adjust for borders but don't change the gravity. */
10328 void
10329 x_set_offset (struct frame *f, register int xoff, register int yoff, int change_gravity)
10331 int modified_top, modified_left;
10332 #ifdef USE_GTK
10333 int scale = xg_get_scale (f);
10334 #endif
10336 if (change_gravity > 0)
10338 f->top_pos = yoff;
10339 f->left_pos = xoff;
10340 f->size_hint_flags &= ~ (XNegative | YNegative);
10341 if (xoff < 0)
10342 f->size_hint_flags |= XNegative;
10343 if (yoff < 0)
10344 f->size_hint_flags |= YNegative;
10345 f->win_gravity = NorthWestGravity;
10348 x_calc_absolute_position (f);
10350 block_input ();
10351 x_wm_set_size_hint (f, 0, false);
10353 #ifdef USE_GTK
10354 if (x_gtk_use_window_move)
10356 /* When a position change was requested and the outer GTK widget
10357 has been realized already, leave it to gtk_window_move to
10358 DTRT and return. Used for Bug#25851 and Bug#25943. Convert
10359 from X pixels to GTK scaled pixels. */
10360 if (change_gravity != 0 && FRAME_GTK_OUTER_WIDGET (f))
10361 gtk_window_move (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)),
10362 f->left_pos / scale, f->top_pos / scale);
10363 unblock_input ();
10364 return;
10366 #endif /* USE_GTK */
10368 modified_left = f->left_pos;
10369 modified_top = f->top_pos;
10371 if (change_gravity != 0 && FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A)
10373 /* Some WMs (twm, wmaker at least) has an offset that is smaller
10374 than the WM decorations. So we use the calculated offset instead
10375 of the WM decoration sizes here (x/y_pixels_outer_diff). */
10376 modified_left += FRAME_X_OUTPUT (f)->move_offset_left;
10377 modified_top += FRAME_X_OUTPUT (f)->move_offset_top;
10380 #ifdef USE_GTK
10381 /* Make sure we adjust for possible scaling. */
10382 gtk_window_move (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)),
10383 modified_left / scale, modified_top / scale);
10384 #else
10385 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
10386 modified_left, modified_top);
10387 #endif
10389 x_sync_with_move (f, f->left_pos, f->top_pos,
10390 FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN);
10392 /* change_gravity is non-zero when this function is called from Lisp to
10393 programmatically move a frame. In that case, we call
10394 x_check_expected_move to discover if we have a "Type A" or "Type B"
10395 window manager, and, for a "Type A" window manager, adjust the position
10396 of the frame.
10398 We call x_check_expected_move if a programmatic move occurred, and
10399 either the window manager type (A/B) is unknown or it is Type A but we
10400 need to compute the top/left offset adjustment for this frame. */
10402 if (change_gravity != 0
10403 && !FRAME_PARENT_FRAME (f)
10404 && (FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN
10405 || (FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A
10406 && (FRAME_X_OUTPUT (f)->move_offset_left == 0
10407 && FRAME_X_OUTPUT (f)->move_offset_top == 0))))
10408 x_check_expected_move (f, modified_left, modified_top);
10410 unblock_input ();
10413 /* Return true if _NET_SUPPORTING_WM_CHECK window exists and _NET_SUPPORTED
10414 on the root window for frame F contains ATOMNAME.
10415 This is how a WM check shall be done according to the Window Manager
10416 Specification/Extended Window Manager Hints at
10417 http://freedesktop.org/wiki/Specifications/wm-spec. */
10419 bool
10420 x_wm_supports (struct frame *f, Atom want_atom)
10422 Atom actual_type;
10423 unsigned long actual_size, bytes_remaining;
10424 int i, rc, actual_format;
10425 bool ret;
10426 Window wmcheck_window;
10427 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10428 Window target_window = dpyinfo->root_window;
10429 int max_len = 65536;
10430 Display *dpy = FRAME_X_DISPLAY (f);
10431 unsigned char *tmp_data = NULL;
10432 Atom target_type = XA_WINDOW;
10434 block_input ();
10436 x_catch_errors (dpy);
10437 rc = XGetWindowProperty (dpy, target_window,
10438 dpyinfo->Xatom_net_supporting_wm_check,
10439 0, max_len, False, target_type,
10440 &actual_type, &actual_format, &actual_size,
10441 &bytes_remaining, &tmp_data);
10443 if (rc != Success || actual_type != XA_WINDOW || x_had_errors_p (dpy))
10445 if (tmp_data) XFree (tmp_data);
10446 x_uncatch_errors ();
10447 unblock_input ();
10448 return false;
10451 wmcheck_window = *(Window *) tmp_data;
10452 XFree (tmp_data);
10454 /* Check if window exists. */
10455 XSelectInput (dpy, wmcheck_window, StructureNotifyMask);
10456 if (x_had_errors_p (dpy))
10458 x_uncatch_errors_after_check ();
10459 unblock_input ();
10460 return false;
10463 if (dpyinfo->net_supported_window != wmcheck_window)
10465 /* Window changed, reload atoms */
10466 if (dpyinfo->net_supported_atoms != NULL)
10467 XFree (dpyinfo->net_supported_atoms);
10468 dpyinfo->net_supported_atoms = NULL;
10469 dpyinfo->nr_net_supported_atoms = 0;
10470 dpyinfo->net_supported_window = 0;
10472 target_type = XA_ATOM;
10473 tmp_data = NULL;
10474 rc = XGetWindowProperty (dpy, target_window,
10475 dpyinfo->Xatom_net_supported,
10476 0, max_len, False, target_type,
10477 &actual_type, &actual_format, &actual_size,
10478 &bytes_remaining, &tmp_data);
10480 if (rc != Success || actual_type != XA_ATOM || x_had_errors_p (dpy))
10482 if (tmp_data) XFree (tmp_data);
10483 x_uncatch_errors ();
10484 unblock_input ();
10485 return false;
10488 dpyinfo->net_supported_atoms = (Atom *)tmp_data;
10489 dpyinfo->nr_net_supported_atoms = actual_size;
10490 dpyinfo->net_supported_window = wmcheck_window;
10493 ret = false;
10495 for (i = 0; !ret && i < dpyinfo->nr_net_supported_atoms; ++i)
10496 ret = dpyinfo->net_supported_atoms[i] == want_atom;
10498 x_uncatch_errors ();
10499 unblock_input ();
10501 return ret;
10504 static void
10505 set_wm_state (Lisp_Object frame, bool add, Atom atom, Atom value)
10507 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (XFRAME (frame));
10509 x_send_client_event (frame, make_number (0), frame,
10510 dpyinfo->Xatom_net_wm_state,
10511 make_number (32),
10512 /* 1 = add, 0 = remove */
10513 Fcons
10514 (make_number (add),
10515 Fcons
10516 (make_fixnum_or_float (atom),
10517 (value != 0
10518 ? list1 (make_fixnum_or_float (value))
10519 : Qnil))));
10522 void
10523 x_set_sticky (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
10525 Lisp_Object frame;
10526 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10528 XSETFRAME (frame, f);
10530 set_wm_state (frame, !NILP (new_value),
10531 dpyinfo->Xatom_net_wm_state_sticky, None);
10535 * x_set_skip_taskbar:
10537 * Set frame F's `skip-taskbar' parameter. If non-nil, this should
10538 * remove F's icon from the taskbar associated with the display of F's
10539 * window-system window and inhibit switching to F's window via
10540 * <Alt>-<TAB>. If nil, lift these restrictions.
10542 * Some window managers may not honor this parameter.
10544 void
10545 x_set_skip_taskbar (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
10547 if (!EQ (new_value, old_value))
10549 #ifdef USE_GTK
10550 xg_set_skip_taskbar (f, new_value);
10551 #else
10552 Lisp_Object frame;
10553 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10555 XSETFRAME (frame, f);
10556 set_wm_state (frame, !NILP (new_value),
10557 dpyinfo->Xatom_net_wm_state_skip_taskbar, None);
10558 #endif /* USE_GTK */
10559 FRAME_SKIP_TASKBAR (f) = !NILP (new_value);
10564 * x_set_z_group:
10566 * Set frame F's `z-group' parameter. If `above', F's window-system
10567 * window is displayed above all windows that do not have the `above'
10568 * property set. If nil, F's window is shown below all windows that
10569 * have the `above' property set and above all windows that have the
10570 * `below' property set. If `below', F's window is displayed below all
10571 * windows that do not have the `below' property set.
10573 * Some window managers may not honor this parameter.
10575 void
10576 x_set_z_group (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
10578 /* We don't care about old_value. The window manager might have
10579 reset the value without telling us. */
10580 Lisp_Object frame;
10581 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10583 XSETFRAME (frame, f);
10585 if (NILP (new_value))
10587 set_wm_state (frame, false,
10588 dpyinfo->Xatom_net_wm_state_above, None);
10589 set_wm_state (frame, false,
10590 dpyinfo->Xatom_net_wm_state_below, None);
10591 FRAME_Z_GROUP (f) = z_group_none;
10593 else if (EQ (new_value, Qabove))
10595 set_wm_state (frame, true,
10596 dpyinfo->Xatom_net_wm_state_above, None);
10597 set_wm_state (frame, false,
10598 dpyinfo->Xatom_net_wm_state_below, None);
10599 FRAME_Z_GROUP (f) = z_group_above;
10601 else if (EQ (new_value, Qbelow))
10603 set_wm_state (frame, false,
10604 dpyinfo->Xatom_net_wm_state_above, None);
10605 set_wm_state (frame, true,
10606 dpyinfo->Xatom_net_wm_state_below, None);
10607 FRAME_Z_GROUP (f) = z_group_below;
10609 else if (EQ (new_value, Qabove_suspended))
10611 set_wm_state (frame, false,
10612 dpyinfo->Xatom_net_wm_state_above, None);
10613 FRAME_Z_GROUP (f) = z_group_above_suspended;
10615 else
10616 error ("Invalid z-group specification");
10620 /* Return the current _NET_WM_STATE.
10621 SIZE_STATE is set to one of the FULLSCREEN_* values.
10622 Set *STICKY to the sticky state.
10624 Return true iff we are not hidden. */
10626 static bool
10627 get_current_wm_state (struct frame *f,
10628 Window window,
10629 int *size_state,
10630 bool *sticky)
10632 unsigned long actual_size;
10633 int i;
10634 bool is_hidden = false;
10635 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10636 long max_len = 65536;
10637 Atom target_type = XA_ATOM;
10638 /* If XCB is available, we can avoid three XSync calls. */
10639 #ifdef USE_XCB
10640 xcb_get_property_cookie_t prop_cookie;
10641 xcb_get_property_reply_t *prop;
10642 xcb_atom_t *reply_data;
10643 #else
10644 Display *dpy = FRAME_X_DISPLAY (f);
10645 unsigned long bytes_remaining;
10646 int rc, actual_format;
10647 Atom actual_type;
10648 unsigned char *tmp_data = NULL;
10649 Atom *reply_data;
10650 #endif
10652 *sticky = false;
10653 *size_state = FULLSCREEN_NONE;
10655 block_input ();
10657 #ifdef USE_XCB
10658 prop_cookie = xcb_get_property (dpyinfo->xcb_connection, 0, window,
10659 dpyinfo->Xatom_net_wm_state,
10660 target_type, 0, max_len);
10661 prop = xcb_get_property_reply (dpyinfo->xcb_connection, prop_cookie, NULL);
10662 if (prop && prop->type == target_type)
10664 int actual_bytes = xcb_get_property_value_length (prop);
10665 eassume (0 <= actual_bytes);
10666 actual_size = actual_bytes / sizeof *reply_data;
10667 reply_data = xcb_get_property_value (prop);
10669 else
10671 actual_size = 0;
10672 is_hidden = FRAME_ICONIFIED_P (f);
10674 #else
10675 x_catch_errors (dpy);
10676 rc = XGetWindowProperty (dpy, window, dpyinfo->Xatom_net_wm_state,
10677 0, max_len, False, target_type,
10678 &actual_type, &actual_format, &actual_size,
10679 &bytes_remaining, &tmp_data);
10681 if (rc == Success && actual_type == target_type && ! x_had_errors_p (dpy))
10682 reply_data = (Atom *) tmp_data;
10683 else
10685 actual_size = 0;
10686 is_hidden = FRAME_ICONIFIED_P (f);
10689 x_uncatch_errors ();
10690 #endif
10692 for (i = 0; i < actual_size; ++i)
10694 Atom a = reply_data[i];
10695 if (a == dpyinfo->Xatom_net_wm_state_hidden)
10696 is_hidden = true;
10697 else if (a == dpyinfo->Xatom_net_wm_state_maximized_horz)
10699 if (*size_state == FULLSCREEN_HEIGHT)
10700 *size_state = FULLSCREEN_MAXIMIZED;
10701 else
10702 *size_state = FULLSCREEN_WIDTH;
10704 else if (a == dpyinfo->Xatom_net_wm_state_maximized_vert)
10706 if (*size_state == FULLSCREEN_WIDTH)
10707 *size_state = FULLSCREEN_MAXIMIZED;
10708 else
10709 *size_state = FULLSCREEN_HEIGHT;
10711 else if (a == dpyinfo->Xatom_net_wm_state_fullscreen)
10712 *size_state = FULLSCREEN_BOTH;
10713 else if (a == dpyinfo->Xatom_net_wm_state_sticky)
10714 *sticky = true;
10717 #ifdef USE_XCB
10718 free (prop);
10719 #else
10720 if (tmp_data) XFree (tmp_data);
10721 #endif
10723 unblock_input ();
10724 return ! is_hidden;
10727 /* Do fullscreen as specified in extended window manager hints */
10729 static bool
10730 do_ewmh_fullscreen (struct frame *f)
10732 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10733 bool have_net_atom = x_wm_supports (f, dpyinfo->Xatom_net_wm_state);
10734 int cur;
10735 bool dummy;
10737 get_current_wm_state (f, FRAME_OUTER_WINDOW (f), &cur, &dummy);
10739 /* Some window managers don't say they support _NET_WM_STATE, but they do say
10740 they support _NET_WM_STATE_FULLSCREEN. Try that also. */
10741 if (!have_net_atom)
10742 have_net_atom = x_wm_supports (f, dpyinfo->Xatom_net_wm_state_fullscreen);
10744 if (have_net_atom && cur != f->want_fullscreen)
10746 Lisp_Object frame;
10748 XSETFRAME (frame, f);
10750 /* Keep number of calls to set_wm_state as low as possible.
10751 Some window managers, or possible Gtk+, hangs when too many
10752 are sent at once. */
10753 switch (f->want_fullscreen)
10755 case FULLSCREEN_BOTH:
10756 if (cur != FULLSCREEN_BOTH)
10757 set_wm_state (frame, true, dpyinfo->Xatom_net_wm_state_fullscreen,
10758 None);
10759 break;
10760 case FULLSCREEN_WIDTH:
10761 if (x_frame_normalize_before_maximize && cur == FULLSCREEN_MAXIMIZED)
10763 set_wm_state (frame, false,
10764 dpyinfo->Xatom_net_wm_state_maximized_horz,
10765 dpyinfo->Xatom_net_wm_state_maximized_vert);
10766 set_wm_state (frame, true,
10767 dpyinfo->Xatom_net_wm_state_maximized_horz, None);
10769 else
10771 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_HEIGHT
10772 || cur == FULLSCREEN_MAXIMIZED)
10773 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
10774 dpyinfo->Xatom_net_wm_state_maximized_vert);
10775 if (cur != FULLSCREEN_MAXIMIZED || x_frame_normalize_before_maximize)
10776 set_wm_state (frame, true,
10777 dpyinfo->Xatom_net_wm_state_maximized_horz, None);
10779 break;
10780 case FULLSCREEN_HEIGHT:
10781 if (x_frame_normalize_before_maximize && cur == FULLSCREEN_MAXIMIZED)
10783 set_wm_state (frame, false,
10784 dpyinfo->Xatom_net_wm_state_maximized_horz,
10785 dpyinfo->Xatom_net_wm_state_maximized_vert);
10786 set_wm_state (frame, true,
10787 dpyinfo->Xatom_net_wm_state_maximized_vert, None);
10789 else
10791 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_WIDTH
10792 || cur == FULLSCREEN_MAXIMIZED)
10793 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
10794 dpyinfo->Xatom_net_wm_state_maximized_horz);
10795 if (cur != FULLSCREEN_MAXIMIZED || x_frame_normalize_before_maximize)
10796 set_wm_state (frame, true,
10797 dpyinfo->Xatom_net_wm_state_maximized_vert, None);
10799 break;
10800 case FULLSCREEN_MAXIMIZED:
10801 if (x_frame_normalize_before_maximize && cur == FULLSCREEN_BOTH)
10803 set_wm_state (frame, false,
10804 dpyinfo->Xatom_net_wm_state_fullscreen, None);
10805 set_wm_state (frame, true,
10806 dpyinfo->Xatom_net_wm_state_maximized_horz,
10807 dpyinfo->Xatom_net_wm_state_maximized_vert);
10809 else if (x_frame_normalize_before_maximize && cur == FULLSCREEN_WIDTH)
10811 set_wm_state (frame, false,
10812 dpyinfo->Xatom_net_wm_state_maximized_horz, None);
10813 set_wm_state (frame, true,
10814 dpyinfo->Xatom_net_wm_state_maximized_horz,
10815 dpyinfo->Xatom_net_wm_state_maximized_vert);
10817 else if (x_frame_normalize_before_maximize && cur == FULLSCREEN_HEIGHT)
10819 set_wm_state (frame, false,
10820 dpyinfo->Xatom_net_wm_state_maximized_vert, None);
10821 set_wm_state (frame, true,
10822 dpyinfo->Xatom_net_wm_state_maximized_horz,
10823 dpyinfo->Xatom_net_wm_state_maximized_vert);
10825 else
10827 if (cur == FULLSCREEN_BOTH)
10828 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
10829 None);
10830 else if (cur == FULLSCREEN_HEIGHT)
10831 set_wm_state (frame, true,
10832 dpyinfo->Xatom_net_wm_state_maximized_horz, None);
10833 else if (cur == FULLSCREEN_WIDTH)
10834 set_wm_state (frame, true, None,
10835 dpyinfo->Xatom_net_wm_state_maximized_vert);
10836 else
10837 set_wm_state (frame, true,
10838 dpyinfo->Xatom_net_wm_state_maximized_horz,
10839 dpyinfo->Xatom_net_wm_state_maximized_vert);
10841 break;
10842 case FULLSCREEN_NONE:
10843 if (cur == FULLSCREEN_BOTH)
10844 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
10845 None);
10846 else
10847 set_wm_state (frame, false,
10848 dpyinfo->Xatom_net_wm_state_maximized_horz,
10849 dpyinfo->Xatom_net_wm_state_maximized_vert);
10852 f->want_fullscreen = FULLSCREEN_NONE;
10856 return have_net_atom;
10859 static void
10860 XTfullscreen_hook (struct frame *f)
10862 if (FRAME_VISIBLE_P (f))
10864 block_input ();
10865 x_check_fullscreen (f);
10866 x_sync (f);
10867 unblock_input ();
10872 static bool
10873 x_handle_net_wm_state (struct frame *f, const XPropertyEvent *event)
10875 int value = FULLSCREEN_NONE;
10876 Lisp_Object lval;
10877 bool sticky = false;
10878 bool not_hidden = get_current_wm_state (f, event->window, &value, &sticky);
10880 lval = Qnil;
10881 switch (value)
10883 case FULLSCREEN_WIDTH:
10884 lval = Qfullwidth;
10885 break;
10886 case FULLSCREEN_HEIGHT:
10887 lval = Qfullheight;
10888 break;
10889 case FULLSCREEN_BOTH:
10890 lval = Qfullboth;
10891 break;
10892 case FULLSCREEN_MAXIMIZED:
10893 lval = Qmaximized;
10894 break;
10897 frame_size_history_add
10898 (f, Qx_handle_net_wm_state, 0, 0,
10899 list2 (get_frame_param (f, Qfullscreen), lval));
10901 store_frame_param (f, Qfullscreen, lval);
10902 store_frame_param (f, Qsticky, sticky ? Qt : Qnil);
10904 return not_hidden;
10907 /* Check if we need to resize the frame due to a fullscreen request.
10908 If so needed, resize the frame. */
10909 static void
10910 x_check_fullscreen (struct frame *f)
10912 Lisp_Object lval = Qnil;
10914 if (do_ewmh_fullscreen (f))
10915 return;
10917 if (f->output_data.x->parent_desc != FRAME_DISPLAY_INFO (f)->root_window)
10918 return; /* Only fullscreen without WM or with EWM hints (above). */
10920 /* Setting fullscreen to nil doesn't do anything. We could save the
10921 last non-fullscreen size and restore it, but it seems like a
10922 lot of work for this unusual case (no window manager running). */
10924 if (f->want_fullscreen != FULLSCREEN_NONE)
10926 int width = FRAME_PIXEL_WIDTH (f), height = FRAME_PIXEL_HEIGHT (f);
10927 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10929 switch (f->want_fullscreen)
10931 /* No difference between these two when there is no WM */
10932 case FULLSCREEN_MAXIMIZED:
10933 lval = Qmaximized;
10934 width = x_display_pixel_width (dpyinfo);
10935 height = x_display_pixel_height (dpyinfo);
10936 break;
10937 case FULLSCREEN_BOTH:
10938 lval = Qfullboth;
10939 width = x_display_pixel_width (dpyinfo);
10940 height = x_display_pixel_height (dpyinfo);
10941 break;
10942 case FULLSCREEN_WIDTH:
10943 lval = Qfullwidth;
10944 width = x_display_pixel_width (dpyinfo);
10945 height = height + FRAME_MENUBAR_HEIGHT (f);
10946 break;
10947 case FULLSCREEN_HEIGHT:
10948 lval = Qfullheight;
10949 height = x_display_pixel_height (dpyinfo);
10950 break;
10951 default:
10952 emacs_abort ();
10955 frame_size_history_add
10956 (f, Qx_check_fullscreen, width, height, Qnil);
10958 x_wm_set_size_hint (f, 0, false);
10960 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
10961 width, height);
10963 if (FRAME_VISIBLE_P (f))
10964 x_wait_for_event (f, ConfigureNotify);
10965 else
10967 change_frame_size (f, width, height - FRAME_MENUBAR_HEIGHT (f),
10968 false, true, false, true);
10969 x_sync (f);
10973 /* `x_net_wm_state' might have reset the fullscreen frame parameter,
10974 restore it. */
10975 store_frame_param (f, Qfullscreen, lval);
10978 /* This function is called by x_set_offset to determine whether the window
10979 manager interfered with the positioning of the frame. Type A window
10980 managers position the surrounding window manager decorations a small
10981 amount above and left of the user-supplied position. Type B window
10982 managers position the surrounding window manager decorations at the
10983 user-specified position. If we detect a Type A window manager, we
10984 compensate by moving the window right and down by the proper amount. */
10986 static void
10987 x_check_expected_move (struct frame *f, int expected_left, int expected_top)
10989 int current_left = 0, current_top = 0;
10991 /* x_real_positions returns the left and top offsets of the outermost
10992 window manager window around the frame. */
10994 x_real_positions (f, &current_left, &current_top);
10996 if (current_left != expected_left || current_top != expected_top)
10998 /* It's a "Type A" window manager. */
11000 int adjusted_left;
11001 int adjusted_top;
11003 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_A;
11004 FRAME_X_OUTPUT (f)->move_offset_left = expected_left - current_left;
11005 FRAME_X_OUTPUT (f)->move_offset_top = expected_top - current_top;
11007 /* Now fix the mispositioned frame's location. */
11009 adjusted_left = expected_left + FRAME_X_OUTPUT (f)->move_offset_left;
11010 adjusted_top = expected_top + FRAME_X_OUTPUT (f)->move_offset_top;
11012 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11013 adjusted_left, adjusted_top);
11015 x_sync_with_move (f, expected_left, expected_top, false);
11017 else
11018 /* It's a "Type B" window manager. We don't have to adjust the
11019 frame's position. */
11021 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_B;
11025 /* Wait for XGetGeometry to return up-to-date position information for a
11026 recently-moved frame. Call this immediately after calling XMoveWindow.
11027 If FUZZY is non-zero, then LEFT and TOP are just estimates of where the
11028 frame has been moved to, so we use a fuzzy position comparison instead
11029 of an exact comparison. */
11031 static void
11032 x_sync_with_move (struct frame *f, int left, int top, bool fuzzy)
11034 int count = 0;
11036 while (count++ < 50)
11038 int current_left = 0, current_top = 0;
11040 /* In theory, this call to XSync only needs to happen once, but in
11041 practice, it doesn't seem to work, hence the need for the surrounding
11042 loop. */
11044 XSync (FRAME_X_DISPLAY (f), False);
11045 x_real_positions (f, &current_left, &current_top);
11047 if (fuzzy)
11049 /* The left fuzz-factor is 10 pixels. The top fuzz-factor is 40
11050 pixels. */
11052 if (eabs (current_left - left) <= 10
11053 && eabs (current_top - top) <= 40)
11054 return;
11056 else if (current_left == left && current_top == top)
11057 return;
11060 /* As a last resort, just wait 0.5 seconds and hope that XGetGeometry
11061 will then return up-to-date position info. */
11063 wait_reading_process_output (0, 500000000, 0, false, Qnil, NULL, 0);
11067 /* Wait for an event on frame F matching EVENTTYPE. */
11068 void
11069 x_wait_for_event (struct frame *f, int eventtype)
11071 if (!FLOATP (Vx_wait_for_event_timeout))
11072 return;
11074 int level = interrupt_input_blocked;
11075 fd_set fds;
11076 struct timespec tmo, tmo_at, time_now;
11077 int fd = ConnectionNumber (FRAME_X_DISPLAY (f));
11079 f->wait_event_type = eventtype;
11081 /* Default timeout is 0.1 second. Hopefully not noticeable. */
11082 double timeout = XFLOAT_DATA (Vx_wait_for_event_timeout);
11083 time_t timeout_seconds = (time_t) timeout;
11084 tmo = make_timespec
11085 (timeout_seconds, (long int) ((timeout - timeout_seconds)
11086 * 1000 * 1000 * 1000));
11087 tmo_at = timespec_add (current_timespec (), tmo);
11089 while (f->wait_event_type)
11091 pending_signals = true;
11092 totally_unblock_input ();
11093 /* XTread_socket is called after unblock. */
11094 block_input ();
11095 interrupt_input_blocked = level;
11097 FD_ZERO (&fds);
11098 FD_SET (fd, &fds);
11100 time_now = current_timespec ();
11101 if (timespec_cmp (tmo_at, time_now) < 0)
11102 break;
11104 tmo = timespec_sub (tmo_at, time_now);
11105 if (pselect (fd + 1, &fds, NULL, NULL, &tmo, NULL) == 0)
11106 break; /* Timeout */
11109 f->wait_event_type = 0;
11113 /* Change the size of frame F's X window to WIDTH/HEIGHT in the case F
11114 doesn't have a widget. If CHANGE_GRAVITY, change to
11115 top-left-corner window gravity for this size change and subsequent
11116 size changes. Otherwise leave the window gravity unchanged. */
11118 static void
11119 x_set_window_size_1 (struct frame *f, bool change_gravity,
11120 int width, int height)
11122 int pixelwidth = FRAME_TEXT_TO_PIXEL_WIDTH (f, width);
11123 int pixelheight = FRAME_TEXT_TO_PIXEL_HEIGHT (f, height);
11124 int old_width = FRAME_PIXEL_WIDTH (f);
11125 int old_height = FRAME_PIXEL_HEIGHT (f);
11126 Lisp_Object fullscreen = get_frame_param (f, Qfullscreen);
11128 if (change_gravity)
11129 f->win_gravity = NorthWestGravity;
11130 x_wm_set_size_hint (f, 0, false);
11132 /* When the frame is fullheight and we only want to change the width
11133 or it is fullwidth and we only want to change the height we should
11134 be able to preserve the fullscreen property. However, due to the
11135 fact that we have to send a resize request anyway, the window
11136 manager will abolish it. At least the respective size should
11137 remain unchanged but giving the frame back its normal size will
11138 be broken ... */
11139 if (EQ (fullscreen, Qfullwidth) && width == FRAME_TEXT_WIDTH (f))
11141 frame_size_history_add
11142 (f, Qx_set_window_size_1, width, height,
11143 list2 (make_number (old_height),
11144 make_number (pixelheight + FRAME_MENUBAR_HEIGHT (f))));
11146 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11147 old_width, pixelheight + FRAME_MENUBAR_HEIGHT (f));
11149 else if (EQ (fullscreen, Qfullheight) && height == FRAME_TEXT_HEIGHT (f))
11151 frame_size_history_add
11152 (f, Qx_set_window_size_2, width, height,
11153 list2 (make_number (old_width), make_number (pixelwidth)));
11155 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11156 pixelwidth, old_height);
11159 else
11161 frame_size_history_add
11162 (f, Qx_set_window_size_3, width, height,
11163 list3 (make_number (pixelwidth + FRAME_TOOLBAR_WIDTH (f)),
11164 make_number (pixelheight + FRAME_TOOLBAR_HEIGHT (f)
11165 + FRAME_MENUBAR_HEIGHT (f)),
11166 make_number (FRAME_MENUBAR_HEIGHT (f))));
11168 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11169 pixelwidth, pixelheight + FRAME_MENUBAR_HEIGHT (f));
11170 fullscreen = Qnil;
11175 /* We've set {FRAME,PIXEL}_{WIDTH,HEIGHT} to the values we hope to
11176 receive in the ConfigureNotify event; if we get what we asked
11177 for, then the event won't cause the screen to become garbaged, so
11178 we have to make sure to do it here. */
11179 SET_FRAME_GARBAGED (f);
11181 /* Now, strictly speaking, we can't be sure that this is accurate,
11182 but the window manager will get around to dealing with the size
11183 change request eventually, and we'll hear how it went when the
11184 ConfigureNotify event gets here.
11186 We could just not bother storing any of this information here,
11187 and let the ConfigureNotify event set everything up, but that
11188 might be kind of confusing to the Lisp code, since size changes
11189 wouldn't be reported in the frame parameters until some random
11190 point in the future when the ConfigureNotify event arrives.
11192 Pass true for DELAY since we can't run Lisp code inside of
11193 a BLOCK_INPUT. */
11195 /* But the ConfigureNotify may in fact never arrive, and then this is
11196 not right if the frame is visible. Instead wait (with timeout)
11197 for the ConfigureNotify. */
11198 if (FRAME_VISIBLE_P (f))
11200 x_wait_for_event (f, ConfigureNotify);
11202 if (!NILP (fullscreen))
11203 /* Try to restore fullscreen state. */
11205 store_frame_param (f, Qfullscreen, fullscreen);
11206 x_set_fullscreen (f, fullscreen, fullscreen);
11209 else
11211 change_frame_size (f, width, height, false, true, false, true);
11212 x_sync (f);
11217 /* Call this to change the size of frame F's x-window.
11218 If CHANGE_GRAVITY, change to top-left-corner window gravity
11219 for this size change and subsequent size changes.
11220 Otherwise we leave the window gravity unchanged. */
11222 void
11223 x_set_window_size (struct frame *f, bool change_gravity,
11224 int width, int height, bool pixelwise)
11226 block_input ();
11228 /* The following breaks our calculations. If it's really needed,
11229 think of something else. */
11230 #if false
11231 if (!FRAME_TOOLTIP_P (f))
11233 int text_width, text_height;
11235 /* When the frame is maximized/fullscreen or running under for
11236 example Xmonad, x_set_window_size_1 will be a no-op.
11237 In that case, the right thing to do is extend rows/width to
11238 the current frame size. We do that first if x_set_window_size_1
11239 turns out to not be a no-op (there is no way to know).
11240 The size will be adjusted again if the frame gets a
11241 ConfigureNotify event as a result of x_set_window_size. */
11242 int pixelh = FRAME_PIXEL_HEIGHT (f);
11243 #ifdef USE_X_TOOLKIT
11244 /* The menu bar is not part of text lines. The tool bar
11245 is however. */
11246 pixelh -= FRAME_MENUBAR_HEIGHT (f);
11247 #endif
11248 text_width = FRAME_PIXEL_TO_TEXT_WIDTH (f, FRAME_PIXEL_WIDTH (f));
11249 text_height = FRAME_PIXEL_TO_TEXT_HEIGHT (f, pixelh);
11251 change_frame_size (f, text_width, text_height, false, true, false, true);
11253 #endif
11255 /* Pixelize width and height, if necessary. */
11256 if (! pixelwise)
11258 width = width * FRAME_COLUMN_WIDTH (f);
11259 height = height * FRAME_LINE_HEIGHT (f);
11262 #ifdef USE_GTK
11263 if (FRAME_GTK_WIDGET (f))
11264 xg_frame_set_char_size (f, width, height);
11265 else
11266 x_set_window_size_1 (f, change_gravity, width, height);
11267 #else /* not USE_GTK */
11268 x_set_window_size_1 (f, change_gravity, width, height);
11269 x_clear_under_internal_border (f);
11270 #endif /* not USE_GTK */
11272 /* If cursor was outside the new size, mark it as off. */
11273 mark_window_cursors_off (XWINDOW (f->root_window));
11275 /* Clear out any recollection of where the mouse highlighting was,
11276 since it might be in a place that's outside the new frame size.
11277 Actually checking whether it is outside is a pain in the neck,
11278 so don't try--just let the highlighting be done afresh with new size. */
11279 cancel_mouse_face (f);
11281 unblock_input ();
11283 do_pending_window_change (false);
11286 /* Move the mouse to position pixel PIX_X, PIX_Y relative to frame F. */
11288 void
11289 frame_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
11291 block_input ();
11293 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
11294 0, 0, 0, 0, pix_x, pix_y);
11295 unblock_input ();
11298 /* Raise frame F. */
11300 void
11301 x_raise_frame (struct frame *f)
11303 block_input ();
11304 if (FRAME_VISIBLE_P (f))
11305 XRaiseWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
11306 XFlush (FRAME_X_DISPLAY (f));
11307 unblock_input ();
11310 /* Lower frame F. */
11312 static void
11313 x_lower_frame (struct frame *f)
11315 if (FRAME_VISIBLE_P (f))
11317 block_input ();
11318 XLowerWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
11319 XFlush (FRAME_X_DISPLAY (f));
11320 unblock_input ();
11324 /* Request focus with XEmbed */
11326 void
11327 xembed_request_focus (struct frame *f)
11329 /* See XEmbed Protocol Specification at
11330 http://freedesktop.org/wiki/Specifications/xembed-spec */
11331 if (FRAME_VISIBLE_P (f))
11332 xembed_send_message (f, CurrentTime,
11333 XEMBED_REQUEST_FOCUS, 0, 0, 0);
11336 /* Activate frame with Extended Window Manager Hints */
11338 void
11339 x_ewmh_activate_frame (struct frame *f)
11341 /* See Window Manager Specification/Extended Window Manager Hints at
11342 http://freedesktop.org/wiki/Specifications/wm-spec */
11344 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
11346 if (FRAME_VISIBLE_P (f) && x_wm_supports (f, dpyinfo->Xatom_net_active_window))
11348 Lisp_Object frame;
11349 XSETFRAME (frame, f);
11350 x_send_client_event (frame, make_number (0), frame,
11351 dpyinfo->Xatom_net_active_window,
11352 make_number (32),
11353 list2i (1, dpyinfo->last_user_time));
11357 static void
11358 XTframe_raise_lower (struct frame *f, bool raise_flag)
11360 if (raise_flag)
11361 x_raise_frame (f);
11362 else
11363 x_lower_frame (f);
11366 /* XEmbed implementation. */
11368 #if defined USE_X_TOOLKIT || ! defined USE_GTK
11370 /* XEmbed implementation. */
11372 #define XEMBED_VERSION 0
11374 static void
11375 xembed_set_info (struct frame *f, enum xembed_info flags)
11377 unsigned long data[2];
11378 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
11380 data[0] = XEMBED_VERSION;
11381 data[1] = flags;
11383 XChangeProperty (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11384 dpyinfo->Xatom_XEMBED_INFO, dpyinfo->Xatom_XEMBED_INFO,
11385 32, PropModeReplace, (unsigned char *) data, 2);
11387 #endif /* defined USE_X_TOOLKIT || ! defined USE_GTK */
11389 static void
11390 xembed_send_message (struct frame *f, Time t, enum xembed_message msg,
11391 long int detail, long int data1, long int data2)
11393 XEvent event;
11395 event.xclient.type = ClientMessage;
11396 event.xclient.window = FRAME_X_OUTPUT (f)->parent_desc;
11397 event.xclient.message_type = FRAME_DISPLAY_INFO (f)->Xatom_XEMBED;
11398 event.xclient.format = 32;
11399 event.xclient.data.l[0] = t;
11400 event.xclient.data.l[1] = msg;
11401 event.xclient.data.l[2] = detail;
11402 event.xclient.data.l[3] = data1;
11403 event.xclient.data.l[4] = data2;
11405 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_OUTPUT (f)->parent_desc,
11406 False, NoEventMask, &event);
11407 XSync (FRAME_X_DISPLAY (f), False);
11410 /* Change of visibility. */
11412 /* This tries to wait until the frame is really visible, depending on
11413 the value of Vx_wait_for_event_timeout.
11414 However, if the window manager asks the user where to position
11415 the frame, this will return before the user finishes doing that.
11416 The frame will not actually be visible at that time,
11417 but it will become visible later when the window manager
11418 finishes with it. */
11420 void
11421 x_make_frame_visible (struct frame *f)
11423 if (FRAME_PARENT_FRAME (f))
11425 if (!FRAME_VISIBLE_P (f))
11427 block_input ();
11428 #ifdef USE_GTK
11429 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
11430 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11431 f->left_pos, f->top_pos);
11432 #else
11433 XMapRaised (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
11434 #endif
11435 unblock_input ();
11437 SET_FRAME_VISIBLE (f, true);
11438 SET_FRAME_ICONIFIED (f, false);
11440 return;
11443 block_input ();
11445 x_set_bitmap_icon (f);
11447 if (! FRAME_VISIBLE_P (f))
11449 /* We test asked_for_visible here to make sure we don't
11450 call x_set_offset a second time
11451 if we get to x_make_frame_visible a second time
11452 before the window gets really visible. */
11453 if (! FRAME_ICONIFIED_P (f)
11454 && ! FRAME_X_EMBEDDED_P (f)
11455 && ! f->output_data.x->asked_for_visible)
11456 x_set_offset (f, f->left_pos, f->top_pos, 0);
11458 f->output_data.x->asked_for_visible = true;
11460 if (! EQ (Vx_no_window_manager, Qt))
11461 x_wm_set_window_state (f, NormalState);
11462 #ifdef USE_X_TOOLKIT
11463 if (FRAME_X_EMBEDDED_P (f))
11464 xembed_set_info (f, XEMBED_MAPPED);
11465 else
11467 /* This was XtPopup, but that did nothing for an iconified frame. */
11468 XtMapWidget (f->output_data.x->widget);
11470 #else /* not USE_X_TOOLKIT */
11471 #ifdef USE_GTK
11472 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
11473 gtk_window_deiconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
11474 #else
11475 if (FRAME_X_EMBEDDED_P (f))
11476 xembed_set_info (f, XEMBED_MAPPED);
11477 else
11478 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11479 #endif /* not USE_GTK */
11480 #endif /* not USE_X_TOOLKIT */
11483 XFlush (FRAME_X_DISPLAY (f));
11485 /* Synchronize to ensure Emacs knows the frame is visible
11486 before we do anything else. We do this loop with input not blocked
11487 so that incoming events are handled. */
11489 Lisp_Object frame;
11490 /* This must be before UNBLOCK_INPUT
11491 since events that arrive in response to the actions above
11492 will set it when they are handled. */
11493 bool previously_visible = f->output_data.x->has_been_visible;
11495 XSETFRAME (frame, f);
11497 int original_left = f->left_pos;
11498 int original_top = f->top_pos;
11500 /* This must come after we set COUNT. */
11501 unblock_input ();
11503 /* We unblock here so that arriving X events are processed. */
11505 /* Now move the window back to where it was "supposed to be".
11506 But don't do it if the gravity is negative.
11507 When the gravity is negative, this uses a position
11508 that is 3 pixels too low. Perhaps that's really the border width.
11510 Don't do this if the window has never been visible before,
11511 because the window manager may choose the position
11512 and we don't want to override it. */
11514 if (!FRAME_VISIBLE_P (f)
11515 && !FRAME_ICONIFIED_P (f)
11516 && !FRAME_X_EMBEDDED_P (f)
11517 && !FRAME_PARENT_FRAME (f)
11518 && f->win_gravity == NorthWestGravity
11519 && previously_visible)
11521 Drawable rootw;
11522 int x, y;
11523 unsigned int width, height, border, depth;
11525 block_input ();
11527 /* On some window managers (such as FVWM) moving an existing
11528 window, even to the same place, causes the window manager
11529 to introduce an offset. This can cause the window to move
11530 to an unexpected location. Check the geometry (a little
11531 slow here) and then verify that the window is in the right
11532 place. If the window is not in the right place, move it
11533 there, and take the potential window manager hit. */
11534 XGetGeometry (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11535 &rootw, &x, &y, &width, &height, &border, &depth);
11537 if (original_left != x || original_top != y)
11538 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11539 original_left, original_top);
11541 unblock_input ();
11544 /* Try to wait for a MapNotify event (that is what tells us when a
11545 frame becomes visible). */
11547 #ifdef CYGWIN
11548 /* On Cygwin, which uses input polling, we need to force input to
11549 be read. See
11550 https://lists.gnu.org/r/emacs-devel/2013-12/msg00351.html
11551 and https://debbugs.gnu.org/cgi/bugreport.cgi?bug=24091#131.
11552 Fake an alarm signal to let the handler know that there's
11553 something to be read.
11555 It could be confusing if a real alarm arrives while processing
11556 the fake one. Turn it off and let the handler reset it. */
11557 int old_poll_suppress_count = poll_suppress_count;
11558 poll_suppress_count = 1;
11559 poll_for_input_1 ();
11560 poll_suppress_count = old_poll_suppress_count;
11561 #endif
11562 if (! FRAME_VISIBLE_P (f))
11563 x_wait_for_event (f, MapNotify);
11567 /* Change from mapped state to withdrawn state. */
11569 /* Make the frame visible (mapped and not iconified). */
11571 void
11572 x_make_frame_invisible (struct frame *f)
11574 Window window;
11576 /* Use the frame's outermost window, not the one we normally draw on. */
11577 window = FRAME_OUTER_WINDOW (f);
11579 /* Don't keep the highlight on an invisible frame. */
11580 if (FRAME_DISPLAY_INFO (f)->x_highlight_frame == f)
11581 FRAME_DISPLAY_INFO (f)->x_highlight_frame = 0;
11583 block_input ();
11585 /* Before unmapping the window, update the WM_SIZE_HINTS property to claim
11586 that the current position of the window is user-specified, rather than
11587 program-specified, so that when the window is mapped again, it will be
11588 placed at the same location, without forcing the user to position it
11589 by hand again (they have already done that once for this window.) */
11590 x_wm_set_size_hint (f, 0, true);
11592 #ifdef USE_GTK
11593 if (FRAME_GTK_OUTER_WIDGET (f))
11594 gtk_widget_hide (FRAME_GTK_OUTER_WIDGET (f));
11595 else
11596 #else
11597 if (FRAME_X_EMBEDDED_P (f))
11598 xembed_set_info (f, 0);
11599 else
11600 #endif
11602 if (! XWithdrawWindow (FRAME_X_DISPLAY (f), window,
11603 DefaultScreen (FRAME_X_DISPLAY (f))))
11605 unblock_input ();
11606 error ("Can't notify window manager of window withdrawal");
11609 x_sync (f);
11611 /* We can't distinguish this from iconification
11612 just by the event that we get from the server.
11613 So we can't win using the usual strategy of letting
11614 FRAME_SAMPLE_VISIBILITY set this. So do it by hand,
11615 and synchronize with the server to make sure we agree. */
11616 SET_FRAME_VISIBLE (f, 0);
11617 SET_FRAME_ICONIFIED (f, false);
11619 unblock_input ();
11622 /* Change window state from mapped to iconified. */
11624 void
11625 x_iconify_frame (struct frame *f)
11627 #ifdef USE_X_TOOLKIT
11628 int result;
11629 #endif
11631 /* Don't keep the highlight on an invisible frame. */
11632 if (FRAME_DISPLAY_INFO (f)->x_highlight_frame == f)
11633 FRAME_DISPLAY_INFO (f)->x_highlight_frame = 0;
11635 if (FRAME_ICONIFIED_P (f))
11636 return;
11638 block_input ();
11640 x_set_bitmap_icon (f);
11642 #if defined (USE_GTK)
11643 if (FRAME_GTK_OUTER_WIDGET (f))
11645 if (! FRAME_VISIBLE_P (f))
11646 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
11648 gtk_window_iconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
11649 SET_FRAME_VISIBLE (f, 0);
11650 SET_FRAME_ICONIFIED (f, true);
11651 unblock_input ();
11652 return;
11654 #endif
11656 #ifdef USE_X_TOOLKIT
11658 if (! FRAME_VISIBLE_P (f))
11660 if (! EQ (Vx_no_window_manager, Qt))
11661 x_wm_set_window_state (f, IconicState);
11662 /* This was XtPopup, but that did nothing for an iconified frame. */
11663 XtMapWidget (f->output_data.x->widget);
11664 /* The server won't give us any event to indicate
11665 that an invisible frame was changed to an icon,
11666 so we have to record it here. */
11667 SET_FRAME_VISIBLE (f, 0);
11668 SET_FRAME_ICONIFIED (f, true);
11669 unblock_input ();
11670 return;
11673 result = XIconifyWindow (FRAME_X_DISPLAY (f),
11674 XtWindow (f->output_data.x->widget),
11675 DefaultScreen (FRAME_X_DISPLAY (f)));
11676 unblock_input ();
11678 if (!result)
11679 error ("Can't notify window manager of iconification");
11681 SET_FRAME_ICONIFIED (f, true);
11682 SET_FRAME_VISIBLE (f, 0);
11684 block_input ();
11685 XFlush (FRAME_X_DISPLAY (f));
11686 unblock_input ();
11687 #else /* not USE_X_TOOLKIT */
11689 /* Make sure the X server knows where the window should be positioned,
11690 in case the user deiconifies with the window manager. */
11691 if (! FRAME_VISIBLE_P (f)
11692 && ! FRAME_ICONIFIED_P (f)
11693 && ! FRAME_X_EMBEDDED_P (f))
11694 x_set_offset (f, f->left_pos, f->top_pos, 0);
11696 /* Since we don't know which revision of X we're running, we'll use both
11697 the X11R3 and X11R4 techniques. I don't know if this is a good idea. */
11699 /* X11R4: send a ClientMessage to the window manager using the
11700 WM_CHANGE_STATE type. */
11702 XEvent msg;
11704 msg.xclient.window = FRAME_X_WINDOW (f);
11705 msg.xclient.type = ClientMessage;
11706 msg.xclient.message_type = FRAME_DISPLAY_INFO (f)->Xatom_wm_change_state;
11707 msg.xclient.format = 32;
11708 msg.xclient.data.l[0] = IconicState;
11710 if (! XSendEvent (FRAME_X_DISPLAY (f),
11711 DefaultRootWindow (FRAME_X_DISPLAY (f)),
11712 False,
11713 SubstructureRedirectMask | SubstructureNotifyMask,
11714 &msg))
11716 unblock_input ();
11717 error ("Can't notify window manager of iconification");
11721 /* X11R3: set the initial_state field of the window manager hints to
11722 IconicState. */
11723 x_wm_set_window_state (f, IconicState);
11725 if (!FRAME_VISIBLE_P (f))
11727 /* If the frame was withdrawn, before, we must map it. */
11728 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11731 SET_FRAME_ICONIFIED (f, true);
11732 SET_FRAME_VISIBLE (f, 0);
11734 XFlush (FRAME_X_DISPLAY (f));
11735 unblock_input ();
11736 #endif /* not USE_X_TOOLKIT */
11740 /* Free X resources of frame F. */
11742 void
11743 x_free_frame_resources (struct frame *f)
11745 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
11746 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
11747 #ifdef USE_X_TOOLKIT
11748 Lisp_Object bar;
11749 struct scroll_bar *b;
11750 #endif
11752 block_input ();
11754 /* If a display connection is dead, don't try sending more
11755 commands to the X server. */
11756 if (dpyinfo->display)
11758 /* Always exit with visible pointer to avoid weird issue
11759 with Xfixes (Bug#17609). */
11760 if (f->pointer_invisible)
11761 FRAME_DISPLAY_INFO (f)->toggle_visible_pointer (f, 0);
11763 /* We must free faces before destroying windows because some
11764 font-driver (e.g. xft) access a window while finishing a
11765 face. */
11766 free_frame_faces (f);
11767 tear_down_x_back_buffer (f);
11769 if (f->output_data.x->icon_desc)
11770 XDestroyWindow (FRAME_X_DISPLAY (f), f->output_data.x->icon_desc);
11772 #ifdef USE_X_TOOLKIT
11773 /* Explicitly destroy the scroll bars of the frame. Without
11774 this, we get "BadDrawable" errors from the toolkit later on,
11775 presumably from expose events generated for the disappearing
11776 toolkit scroll bars. */
11777 for (bar = FRAME_SCROLL_BARS (f); !NILP (bar); bar = b->next)
11779 b = XSCROLL_BAR (bar);
11780 x_scroll_bar_remove (b);
11782 #endif
11784 #ifdef HAVE_X_I18N
11785 if (FRAME_XIC (f))
11786 free_frame_xic (f);
11787 #endif
11789 x_free_cr_resources (f);
11790 #ifdef USE_X_TOOLKIT
11791 if (f->output_data.x->widget)
11793 XtDestroyWidget (f->output_data.x->widget);
11794 f->output_data.x->widget = NULL;
11796 /* Tooltips don't have widgets, only a simple X window, even if
11797 we are using a toolkit. */
11798 else if (FRAME_X_WINDOW (f))
11799 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11801 free_frame_menubar (f);
11803 if (f->shell_position)
11804 xfree (f->shell_position);
11805 #else /* !USE_X_TOOLKIT */
11807 #ifdef USE_GTK
11808 xg_free_frame_widgets (f);
11809 #endif /* USE_GTK */
11811 tear_down_x_back_buffer (f);
11812 if (FRAME_X_WINDOW (f))
11813 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11814 #endif /* !USE_X_TOOLKIT */
11816 unload_color (f, FRAME_FOREGROUND_PIXEL (f));
11817 unload_color (f, FRAME_BACKGROUND_PIXEL (f));
11818 unload_color (f, f->output_data.x->cursor_pixel);
11819 unload_color (f, f->output_data.x->cursor_foreground_pixel);
11820 unload_color (f, f->output_data.x->border_pixel);
11821 unload_color (f, f->output_data.x->mouse_pixel);
11823 if (f->output_data.x->scroll_bar_background_pixel != -1)
11824 unload_color (f, f->output_data.x->scroll_bar_background_pixel);
11825 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
11826 unload_color (f, f->output_data.x->scroll_bar_foreground_pixel);
11827 #if defined (USE_LUCID) && defined (USE_TOOLKIT_SCROLL_BARS)
11828 /* Scrollbar shadow colors. */
11829 if (f->output_data.x->scroll_bar_top_shadow_pixel != -1)
11830 unload_color (f, f->output_data.x->scroll_bar_top_shadow_pixel);
11831 if (f->output_data.x->scroll_bar_bottom_shadow_pixel != -1)
11832 unload_color (f, f->output_data.x->scroll_bar_bottom_shadow_pixel);
11833 #endif /* USE_LUCID && USE_TOOLKIT_SCROLL_BARS */
11834 if (f->output_data.x->white_relief.pixel != -1)
11835 unload_color (f, f->output_data.x->white_relief.pixel);
11836 if (f->output_data.x->black_relief.pixel != -1)
11837 unload_color (f, f->output_data.x->black_relief.pixel);
11839 x_free_gcs (f);
11841 /* Free extra GCs allocated by x_setup_relief_colors. */
11842 if (f->output_data.x->white_relief.gc)
11844 XFreeGC (dpyinfo->display, f->output_data.x->white_relief.gc);
11845 f->output_data.x->white_relief.gc = 0;
11847 if (f->output_data.x->black_relief.gc)
11849 XFreeGC (dpyinfo->display, f->output_data.x->black_relief.gc);
11850 f->output_data.x->black_relief.gc = 0;
11853 /* Free cursors. */
11854 if (f->output_data.x->text_cursor != 0)
11855 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->text_cursor);
11856 if (f->output_data.x->nontext_cursor != 0)
11857 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->nontext_cursor);
11858 if (f->output_data.x->modeline_cursor != 0)
11859 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->modeline_cursor);
11860 if (f->output_data.x->hand_cursor != 0)
11861 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->hand_cursor);
11862 if (f->output_data.x->hourglass_cursor != 0)
11863 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->hourglass_cursor);
11864 if (f->output_data.x->horizontal_drag_cursor != 0)
11865 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->horizontal_drag_cursor);
11866 if (f->output_data.x->vertical_drag_cursor != 0)
11867 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->vertical_drag_cursor);
11868 if (f->output_data.x->left_edge_cursor != 0)
11869 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->left_edge_cursor);
11870 if (f->output_data.x->top_left_corner_cursor != 0)
11871 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->top_left_corner_cursor);
11872 if (f->output_data.x->top_edge_cursor != 0)
11873 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->top_edge_cursor);
11874 if (f->output_data.x->top_right_corner_cursor != 0)
11875 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->top_right_corner_cursor);
11876 if (f->output_data.x->right_edge_cursor != 0)
11877 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->right_edge_cursor);
11878 if (f->output_data.x->bottom_right_corner_cursor != 0)
11879 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->bottom_right_corner_cursor);
11880 if (f->output_data.x->bottom_edge_cursor != 0)
11881 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->bottom_edge_cursor);
11882 if (f->output_data.x->bottom_left_corner_cursor != 0)
11883 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->bottom_left_corner_cursor);
11885 XFlush (FRAME_X_DISPLAY (f));
11888 xfree (f->output_data.x->saved_menu_event);
11889 xfree (f->output_data.x);
11890 f->output_data.x = NULL;
11892 if (f == dpyinfo->x_focus_frame)
11893 dpyinfo->x_focus_frame = 0;
11894 if (f == dpyinfo->x_focus_event_frame)
11895 dpyinfo->x_focus_event_frame = 0;
11896 if (f == dpyinfo->x_highlight_frame)
11897 dpyinfo->x_highlight_frame = 0;
11898 if (f == hlinfo->mouse_face_mouse_frame)
11899 reset_mouse_highlight (hlinfo);
11901 unblock_input ();
11905 /* Destroy the X window of frame F. */
11907 static void
11908 x_destroy_window (struct frame *f)
11910 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
11912 /* If a display connection is dead, don't try sending more
11913 commands to the X server. */
11914 if (dpyinfo->display != 0)
11915 x_free_frame_resources (f);
11917 dpyinfo->reference_count--;
11921 /* Setting window manager hints. */
11923 /* Set the normal size hints for the window manager, for frame F.
11924 FLAGS is the flags word to use--or 0 meaning preserve the flags
11925 that the window now has.
11926 If USER_POSITION, set the USPosition
11927 flag (this is useful when FLAGS is 0).
11928 The GTK version is in gtkutils.c. */
11930 #ifndef USE_GTK
11931 void
11932 x_wm_set_size_hint (struct frame *f, long flags, bool user_position)
11934 XSizeHints size_hints;
11935 Window window = FRAME_OUTER_WINDOW (f);
11937 if (!window)
11938 return;
11940 #ifdef USE_X_TOOLKIT
11941 if (f->output_data.x->widget)
11943 widget_update_wm_size_hints (f->output_data.x->widget);
11944 return;
11946 #endif
11948 /* Setting PMaxSize caused various problems. */
11949 size_hints.flags = PResizeInc | PMinSize /* | PMaxSize */;
11951 size_hints.x = f->left_pos;
11952 size_hints.y = f->top_pos;
11954 size_hints.width = FRAME_PIXEL_WIDTH (f);
11955 size_hints.height = FRAME_PIXEL_HEIGHT (f);
11957 size_hints.width_inc = frame_resize_pixelwise ? 1 : FRAME_COLUMN_WIDTH (f);
11958 size_hints.height_inc = frame_resize_pixelwise ? 1 : FRAME_LINE_HEIGHT (f);
11960 size_hints.max_width = x_display_pixel_width (FRAME_DISPLAY_INFO (f))
11961 - FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
11962 size_hints.max_height = x_display_pixel_height (FRAME_DISPLAY_INFO (f))
11963 - FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
11965 /* Calculate the base and minimum sizes. */
11967 int base_width, base_height;
11969 base_width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
11970 base_height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
11972 /* The window manager uses the base width hints to calculate the
11973 current number of rows and columns in the frame while
11974 resizing; min_width and min_height aren't useful for this
11975 purpose, since they might not give the dimensions for a
11976 zero-row, zero-column frame. */
11978 size_hints.flags |= PBaseSize;
11979 size_hints.base_width = base_width;
11980 size_hints.base_height = base_height + FRAME_MENUBAR_HEIGHT (f);
11981 size_hints.min_width = base_width;
11982 size_hints.min_height = base_height;
11985 /* If we don't need the old flags, we don't need the old hint at all. */
11986 if (flags)
11988 size_hints.flags |= flags;
11989 goto no_read;
11993 XSizeHints hints; /* Sometimes I hate X Windows... */
11994 long supplied_return;
11995 int value;
11997 value = XGetWMNormalHints (FRAME_X_DISPLAY (f), window, &hints,
11998 &supplied_return);
12000 if (flags)
12001 size_hints.flags |= flags;
12002 else
12004 if (value == 0)
12005 hints.flags = 0;
12006 if (hints.flags & PSize)
12007 size_hints.flags |= PSize;
12008 if (hints.flags & PPosition)
12009 size_hints.flags |= PPosition;
12010 if (hints.flags & USPosition)
12011 size_hints.flags |= USPosition;
12012 if (hints.flags & USSize)
12013 size_hints.flags |= USSize;
12017 no_read:
12019 #ifdef PWinGravity
12020 size_hints.win_gravity = f->win_gravity;
12021 size_hints.flags |= PWinGravity;
12023 if (user_position)
12025 size_hints.flags &= ~ PPosition;
12026 size_hints.flags |= USPosition;
12028 #endif /* PWinGravity */
12030 XSetWMNormalHints (FRAME_X_DISPLAY (f), window, &size_hints);
12032 #endif /* not USE_GTK */
12034 /* Used for IconicState or NormalState */
12036 static void
12037 x_wm_set_window_state (struct frame *f, int state)
12039 #ifdef USE_X_TOOLKIT
12040 Arg al[1];
12042 XtSetArg (al[0], XtNinitialState, state);
12043 XtSetValues (f->output_data.x->widget, al, 1);
12044 #else /* not USE_X_TOOLKIT */
12045 Window window = FRAME_X_WINDOW (f);
12047 f->output_data.x->wm_hints.flags |= StateHint;
12048 f->output_data.x->wm_hints.initial_state = state;
12050 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
12051 #endif /* not USE_X_TOOLKIT */
12054 static void
12055 x_wm_set_icon_pixmap (struct frame *f, ptrdiff_t pixmap_id)
12057 Pixmap icon_pixmap, icon_mask;
12059 #if !defined USE_X_TOOLKIT && !defined USE_GTK
12060 Window window = FRAME_OUTER_WINDOW (f);
12061 #endif
12063 if (pixmap_id > 0)
12065 icon_pixmap = x_bitmap_pixmap (f, pixmap_id);
12066 f->output_data.x->wm_hints.icon_pixmap = icon_pixmap;
12067 icon_mask = x_bitmap_mask (f, pixmap_id);
12068 f->output_data.x->wm_hints.icon_mask = icon_mask;
12070 else
12072 /* It seems there is no way to turn off use of an icon
12073 pixmap. */
12074 return;
12078 #ifdef USE_GTK
12080 xg_set_frame_icon (f, icon_pixmap, icon_mask);
12081 return;
12084 #elif defined (USE_X_TOOLKIT) /* same as in x_wm_set_window_state. */
12087 Arg al[1];
12088 XtSetArg (al[0], XtNiconPixmap, icon_pixmap);
12089 XtSetValues (f->output_data.x->widget, al, 1);
12090 XtSetArg (al[0], XtNiconMask, icon_mask);
12091 XtSetValues (f->output_data.x->widget, al, 1);
12094 #else /* not USE_X_TOOLKIT && not USE_GTK */
12096 f->output_data.x->wm_hints.flags |= (IconPixmapHint | IconMaskHint);
12097 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
12099 #endif /* not USE_X_TOOLKIT && not USE_GTK */
12102 void
12103 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
12105 Window window = FRAME_OUTER_WINDOW (f);
12107 f->output_data.x->wm_hints.flags |= IconPositionHint;
12108 f->output_data.x->wm_hints.icon_x = icon_x;
12109 f->output_data.x->wm_hints.icon_y = icon_y;
12111 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
12115 /***********************************************************************
12116 Fonts
12117 ***********************************************************************/
12119 #ifdef GLYPH_DEBUG
12121 /* Check that FONT is valid on frame F. It is if it can be found in F's
12122 font table. */
12124 static void
12125 x_check_font (struct frame *f, struct font *font)
12127 eassert (font != NULL && ! NILP (font->props[FONT_TYPE_INDEX]));
12128 if (font->driver->check)
12129 eassert (font->driver->check (f, font) == 0);
12132 #endif /* GLYPH_DEBUG */
12135 /***********************************************************************
12136 Initialization
12137 ***********************************************************************/
12139 #ifdef USE_X_TOOLKIT
12140 static XrmOptionDescRec emacs_options[] = {
12141 {(char *) "-geometry", (char *) ".geometry", XrmoptionSepArg, NULL},
12142 {(char *) "-iconic", (char *) ".iconic", XrmoptionNoArg, (XtPointer) "yes"},
12144 {(char *) "-internal-border-width",
12145 (char *) "*EmacsScreen.internalBorderWidth", XrmoptionSepArg, NULL},
12146 {(char *) "-ib", (char *) "*EmacsScreen.internalBorderWidth",
12147 XrmoptionSepArg, NULL},
12148 {(char *) "-T", (char *) "*EmacsShell.title", XrmoptionSepArg, NULL},
12149 {(char *) "-wn", (char *) "*EmacsShell.title", XrmoptionSepArg, NULL},
12150 {(char *) "-title", (char *) "*EmacsShell.title", XrmoptionSepArg, NULL},
12151 {(char *) "-iconname", (char *) "*EmacsShell.iconName",
12152 XrmoptionSepArg, NULL},
12153 {(char *) "-in", (char *) "*EmacsShell.iconName", XrmoptionSepArg, NULL},
12154 {(char *) "-mc", (char *) "*pointerColor", XrmoptionSepArg, NULL},
12155 {(char *) "-cr", (char *) "*cursorColor", XrmoptionSepArg, NULL}
12158 /* Whether atimer for Xt timeouts is activated or not. */
12160 static bool x_timeout_atimer_activated_flag;
12162 #endif /* USE_X_TOOLKIT */
12164 static int x_initialized;
12166 /* Test whether two display-name strings agree up to the dot that separates
12167 the screen number from the server number. */
12168 static bool
12169 same_x_server (const char *name1, const char *name2)
12171 bool seen_colon = false;
12172 Lisp_Object sysname = Fsystem_name ();
12173 if (! STRINGP (sysname))
12174 sysname = empty_unibyte_string;
12175 const char *system_name = SSDATA (sysname);
12176 ptrdiff_t system_name_length = SBYTES (sysname);
12177 ptrdiff_t length_until_period = 0;
12179 while (system_name[length_until_period] != 0
12180 && system_name[length_until_period] != '.')
12181 length_until_period++;
12183 /* Treat `unix' like an empty host name. */
12184 if (! strncmp (name1, "unix:", 5))
12185 name1 += 4;
12186 if (! strncmp (name2, "unix:", 5))
12187 name2 += 4;
12188 /* Treat this host's name like an empty host name. */
12189 if (! strncmp (name1, system_name, system_name_length)
12190 && name1[system_name_length] == ':')
12191 name1 += system_name_length;
12192 if (! strncmp (name2, system_name, system_name_length)
12193 && name2[system_name_length] == ':')
12194 name2 += system_name_length;
12195 /* Treat this host's domainless name like an empty host name. */
12196 if (! strncmp (name1, system_name, length_until_period)
12197 && name1[length_until_period] == ':')
12198 name1 += length_until_period;
12199 if (! strncmp (name2, system_name, length_until_period)
12200 && name2[length_until_period] == ':')
12201 name2 += length_until_period;
12203 for (; *name1 != '\0' && *name1 == *name2; name1++, name2++)
12205 if (*name1 == ':')
12206 seen_colon = true;
12207 if (seen_colon && *name1 == '.')
12208 return true;
12210 return (seen_colon
12211 && (*name1 == '.' || *name1 == '\0')
12212 && (*name2 == '.' || *name2 == '\0'));
12215 /* Count number of set bits in mask and number of bits to shift to
12216 get to the first bit. With MASK 0x7e0, *BITS is set to 6, and *OFFSET
12217 to 5. */
12218 static void
12219 get_bits_and_offset (unsigned long mask, int *bits, int *offset)
12221 int nr = 0;
12222 int off = 0;
12224 while (!(mask & 1))
12226 off++;
12227 mask >>= 1;
12230 while (mask & 1)
12232 nr++;
12233 mask >>= 1;
12236 *offset = off;
12237 *bits = nr;
12240 /* Return true iff display DISPLAY is available for use.
12241 But don't permanently open it, just test its availability. */
12243 bool
12244 x_display_ok (const char *display)
12246 /* XOpenDisplay fails if it gets a signal. Block SIGIO which may arrive. */
12247 unrequest_sigio ();
12248 Display *dpy = XOpenDisplay (display);
12249 request_sigio ();
12250 if (!dpy)
12251 return false;
12252 XCloseDisplay (dpy);
12253 return true;
12256 #ifdef USE_GTK
12257 static void
12258 my_log_handler (const gchar *log_domain, GLogLevelFlags log_level,
12259 const gchar *msg, gpointer user_data)
12261 if (!strstr (msg, "g_set_prgname"))
12262 fprintf (stderr, "%s-WARNING **: %s\n", log_domain, msg);
12264 #endif
12266 /* Create invisible cursor on X display referred by DPYINFO. */
12268 static Cursor
12269 make_invisible_cursor (struct x_display_info *dpyinfo)
12271 Display *dpy = dpyinfo->display;
12272 static char const no_data[] = { 0 };
12273 Pixmap pix;
12274 XColor col;
12275 Cursor c = 0;
12277 x_catch_errors (dpy);
12278 pix = XCreateBitmapFromData (dpy, dpyinfo->root_window, no_data, 1, 1);
12279 if (! x_had_errors_p (dpy) && pix != None)
12281 Cursor pixc;
12282 col.pixel = 0;
12283 col.red = col.green = col.blue = 0;
12284 col.flags = DoRed | DoGreen | DoBlue;
12285 pixc = XCreatePixmapCursor (dpy, pix, pix, &col, &col, 0, 0);
12286 if (! x_had_errors_p (dpy) && pixc != None)
12287 c = pixc;
12288 XFreePixmap (dpy, pix);
12291 x_uncatch_errors ();
12293 return c;
12296 /* True if DPY supports Xfixes extension >= 4. */
12298 static bool
12299 x_probe_xfixes_extension (Display *dpy)
12301 #ifdef HAVE_XFIXES
12302 int major, minor;
12303 return XFixesQueryVersion (dpy, &major, &minor) && major >= 4;
12304 #else
12305 return false;
12306 #endif /* HAVE_XFIXES */
12309 /* Toggle mouse pointer visibility on frame F by using Xfixes functions. */
12311 static void
12312 xfixes_toggle_visible_pointer (struct frame *f, bool invisible)
12314 #ifdef HAVE_XFIXES
12315 if (invisible)
12316 XFixesHideCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
12317 else
12318 XFixesShowCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
12319 f->pointer_invisible = invisible;
12320 #else
12321 emacs_abort ();
12322 #endif /* HAVE_XFIXES */
12325 /* Toggle mouse pointer visibility on frame F by using invisible cursor. */
12327 static void
12328 x_toggle_visible_pointer (struct frame *f, bool invisible)
12330 eassert (FRAME_DISPLAY_INFO (f)->invisible_cursor != 0);
12331 if (invisible)
12332 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
12333 FRAME_DISPLAY_INFO (f)->invisible_cursor);
12334 else
12335 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
12336 f->output_data.x->current_cursor);
12337 f->pointer_invisible = invisible;
12340 /* Setup pointer blanking, prefer Xfixes if available. */
12342 static void
12343 x_setup_pointer_blanking (struct x_display_info *dpyinfo)
12345 /* FIXME: the brave tester should set EMACS_XFIXES because we're suspecting
12346 X server bug, see https://debbugs.gnu.org/cgi/bugreport.cgi?bug=17609. */
12347 if (egetenv ("EMACS_XFIXES") && x_probe_xfixes_extension (dpyinfo->display))
12348 dpyinfo->toggle_visible_pointer = xfixes_toggle_visible_pointer;
12349 else
12351 dpyinfo->toggle_visible_pointer = x_toggle_visible_pointer;
12352 dpyinfo->invisible_cursor = make_invisible_cursor (dpyinfo);
12356 /* Current X display connection identifier. Incremented for each next
12357 connection established. */
12358 static unsigned x_display_id;
12360 /* Open a connection to X display DISPLAY_NAME, and return
12361 the structure that describes the open display.
12362 If we cannot contact the display, return null. */
12364 struct x_display_info *
12365 x_term_init (Lisp_Object display_name, char *xrm_option, char *resource_name)
12367 Display *dpy;
12368 struct terminal *terminal;
12369 struct x_display_info *dpyinfo;
12370 XrmDatabase xrdb;
12371 #ifdef USE_XCB
12372 xcb_connection_t *xcb_conn;
12373 #endif
12375 block_input ();
12377 if (!x_initialized)
12379 x_initialize ();
12380 ++x_initialized;
12383 if (! x_display_ok (SSDATA (display_name)))
12384 error ("Display %s can't be opened", SSDATA (display_name));
12386 #ifdef USE_GTK
12388 #define NUM_ARGV 10
12389 int argc;
12390 char *argv[NUM_ARGV];
12391 char **argv2 = argv;
12392 guint id;
12394 if (x_initialized++ > 1)
12396 xg_display_open (SSDATA (display_name), &dpy);
12398 else
12400 static char display_opt[] = "--display";
12401 static char name_opt[] = "--name";
12403 for (argc = 0; argc < NUM_ARGV; ++argc)
12404 argv[argc] = 0;
12406 argc = 0;
12407 argv[argc++] = initial_argv[0];
12409 if (! NILP (display_name))
12411 argv[argc++] = display_opt;
12412 argv[argc++] = SSDATA (display_name);
12415 argv[argc++] = name_opt;
12416 argv[argc++] = resource_name;
12418 XSetLocaleModifiers ("");
12420 /* Work around GLib bug that outputs a faulty warning. See
12421 https://bugzilla.gnome.org/show_bug.cgi?id=563627. */
12422 id = g_log_set_handler ("GLib", G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
12423 | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
12425 /* NULL window -> events for all windows go to our function.
12426 Call before gtk_init so Gtk+ event filters comes after our. */
12427 gdk_window_add_filter (NULL, event_handler_gdk, NULL);
12429 /* gtk_init does set_locale. Fix locale before and after. */
12430 fixup_locale ();
12431 unrequest_sigio (); /* See comment in x_display_ok. */
12432 gtk_init (&argc, &argv2);
12433 request_sigio ();
12435 g_log_remove_handler ("GLib", id);
12437 xg_initialize ();
12439 /* Do this after the call to xg_initialize, because when
12440 Fontconfig is used, xg_initialize calls its initialization
12441 function which in some versions of Fontconfig calls setlocale. */
12442 fixup_locale ();
12444 dpy = DEFAULT_GDK_DISPLAY ();
12446 #if ! GTK_CHECK_VERSION (2, 90, 0)
12447 /* Load our own gtkrc if it exists. */
12449 const char *file = "~/.emacs.d/gtkrc";
12450 Lisp_Object s, abs_file;
12452 s = build_string (file);
12453 abs_file = Fexpand_file_name (s, Qnil);
12455 if (! NILP (abs_file) && !NILP (Ffile_readable_p (abs_file)))
12456 gtk_rc_parse (SSDATA (abs_file));
12458 #endif
12460 XSetErrorHandler (x_error_handler);
12461 XSetIOErrorHandler (x_io_error_quitter);
12464 #else /* not USE_GTK */
12465 #ifdef USE_X_TOOLKIT
12466 /* weiner@footloose.sps.mot.com reports that this causes
12467 errors with X11R5:
12468 X protocol error: BadAtom (invalid Atom parameter)
12469 on protocol request 18skiloaf.
12470 So let's not use it until R6. */
12471 #ifdef HAVE_X11XTR6
12472 XtSetLanguageProc (NULL, NULL, NULL);
12473 #endif
12476 int argc = 0;
12477 char *argv[3];
12479 argv[0] = (char *) "";
12480 argc = 1;
12481 if (xrm_option)
12483 argv[argc++] = (char *) "-xrm";
12484 argv[argc++] = xrm_option;
12486 turn_on_atimers (false);
12487 unrequest_sigio (); /* See comment in x_display_ok. */
12488 dpy = XtOpenDisplay (Xt_app_con, SSDATA (display_name),
12489 resource_name, EMACS_CLASS,
12490 emacs_options, XtNumber (emacs_options),
12491 &argc, argv);
12492 request_sigio ();
12493 turn_on_atimers (true);
12495 #ifdef HAVE_X11XTR6
12496 /* I think this is to compensate for XtSetLanguageProc. */
12497 fixup_locale ();
12498 #endif
12501 #else /* not USE_X_TOOLKIT */
12502 XSetLocaleModifiers ("");
12503 unrequest_sigio (); /* See comment in x_display_ok. */
12504 dpy = XOpenDisplay (SSDATA (display_name));
12505 request_sigio ();
12506 #endif /* not USE_X_TOOLKIT */
12507 #endif /* not USE_GTK*/
12509 /* Detect failure. */
12510 if (dpy == 0)
12512 unblock_input ();
12513 return 0;
12516 #ifdef USE_XCB
12517 xcb_conn = XGetXCBConnection (dpy);
12518 if (xcb_conn == 0)
12520 #ifdef USE_GTK
12521 xg_display_close (dpy);
12522 #else
12523 #ifdef USE_X_TOOLKIT
12524 XtCloseDisplay (dpy);
12525 #else
12526 XCloseDisplay (dpy);
12527 #endif
12528 #endif /* ! USE_GTK */
12530 unblock_input ();
12531 return 0;
12533 #endif
12535 /* We have definitely succeeded. Record the new connection. */
12537 dpyinfo = xzalloc (sizeof *dpyinfo);
12538 terminal = x_create_terminal (dpyinfo);
12541 struct x_display_info *share;
12543 for (share = x_display_list; share; share = share->next)
12544 if (same_x_server (SSDATA (XCAR (share->name_list_element)),
12545 SSDATA (display_name)))
12546 break;
12547 if (share)
12548 terminal->kboard = share->terminal->kboard;
12549 else
12551 terminal->kboard = allocate_kboard (Qx);
12553 if (!EQ (XSYMBOL (Qvendor_specific_keysyms)->u.s.function, Qunbound))
12555 char *vendor = ServerVendor (dpy);
12557 /* Temporarily hide the partially initialized terminal. */
12558 terminal_list = terminal->next_terminal;
12559 unblock_input ();
12560 kset_system_key_alist
12561 (terminal->kboard,
12562 call1 (Qvendor_specific_keysyms,
12563 vendor ? build_string (vendor) : empty_unibyte_string));
12564 block_input ();
12565 terminal->next_terminal = terminal_list;
12566 terminal_list = terminal;
12569 /* Don't let the initial kboard remain current longer than necessary.
12570 That would cause problems if a file loaded on startup tries to
12571 prompt in the mini-buffer. */
12572 if (current_kboard == initial_kboard)
12573 current_kboard = terminal->kboard;
12575 terminal->kboard->reference_count++;
12578 /* Put this display on the chain. */
12579 dpyinfo->next = x_display_list;
12580 x_display_list = dpyinfo;
12582 dpyinfo->name_list_element = Fcons (display_name, Qnil);
12583 dpyinfo->display = dpy;
12584 dpyinfo->connection = ConnectionNumber (dpyinfo->display);
12585 #ifdef USE_XCB
12586 dpyinfo->xcb_connection = xcb_conn;
12587 #endif
12589 /* https://lists.gnu.org/r/emacs-devel/2015-11/msg00194.html */
12590 dpyinfo->smallest_font_height = 1;
12591 dpyinfo->smallest_char_width = 1;
12593 /* Set the name of the terminal. */
12594 terminal->name = xlispstrdup (display_name);
12596 #if false
12597 XSetAfterFunction (x_current_display, x_trace_wire);
12598 #endif
12600 Lisp_Object system_name = Fsystem_name ();
12602 ptrdiff_t nbytes = SBYTES (Vinvocation_name) + 1;
12603 if (STRINGP (system_name)
12604 && INT_ADD_WRAPV (nbytes, SBYTES (system_name) + 1, &nbytes))
12605 memory_full (SIZE_MAX);
12606 dpyinfo->x_id = ++x_display_id;
12607 dpyinfo->x_id_name = xmalloc (nbytes);
12608 char *nametail = lispstpcpy (dpyinfo->x_id_name, Vinvocation_name);
12609 if (STRINGP (system_name))
12611 *nametail++ = '@';
12612 lispstpcpy (nametail, system_name);
12615 /* Figure out which modifier bits mean what. */
12616 x_find_modifier_meanings (dpyinfo);
12618 /* Get the scroll bar cursor. */
12619 #ifdef USE_GTK
12620 /* We must create a GTK cursor, it is required for GTK widgets. */
12621 dpyinfo->xg_cursor = xg_create_default_cursor (dpyinfo->display);
12622 #endif /* USE_GTK */
12624 dpyinfo->vertical_scroll_bar_cursor
12625 = XCreateFontCursor (dpyinfo->display, XC_sb_v_double_arrow);
12627 dpyinfo->horizontal_scroll_bar_cursor
12628 = XCreateFontCursor (dpyinfo->display, XC_sb_h_double_arrow);
12630 xrdb = x_load_resources (dpyinfo->display, xrm_option,
12631 resource_name, EMACS_CLASS);
12632 #ifdef HAVE_XRMSETDATABASE
12633 XrmSetDatabase (dpyinfo->display, xrdb);
12634 #else
12635 dpyinfo->display->db = xrdb;
12636 #endif
12637 /* Put the rdb where we can find it in a way that works on
12638 all versions. */
12639 dpyinfo->xrdb = xrdb;
12641 dpyinfo->screen = ScreenOfDisplay (dpyinfo->display,
12642 DefaultScreen (dpyinfo->display));
12643 select_visual (dpyinfo);
12644 dpyinfo->cmap = DefaultColormapOfScreen (dpyinfo->screen);
12645 dpyinfo->root_window = RootWindowOfScreen (dpyinfo->screen);
12646 dpyinfo->icon_bitmap_id = -1;
12647 dpyinfo->wm_type = X_WMTYPE_UNKNOWN;
12649 reset_mouse_highlight (&dpyinfo->mouse_highlight);
12651 /* See if we can construct pixel values from RGB values. */
12652 if (dpyinfo->visual->class == TrueColor)
12654 get_bits_and_offset (dpyinfo->visual->red_mask,
12655 &dpyinfo->red_bits, &dpyinfo->red_offset);
12656 get_bits_and_offset (dpyinfo->visual->blue_mask,
12657 &dpyinfo->blue_bits, &dpyinfo->blue_offset);
12658 get_bits_and_offset (dpyinfo->visual->green_mask,
12659 &dpyinfo->green_bits, &dpyinfo->green_offset);
12662 /* See if a private colormap is requested. */
12663 if (dpyinfo->visual == DefaultVisualOfScreen (dpyinfo->screen))
12665 if (dpyinfo->visual->class == PseudoColor)
12667 AUTO_STRING (privateColormap, "privateColormap");
12668 AUTO_STRING (PrivateColormap, "PrivateColormap");
12669 Lisp_Object value
12670 = display_x_get_resource (dpyinfo, privateColormap,
12671 PrivateColormap, Qnil, Qnil);
12672 if (STRINGP (value)
12673 && (!strcmp (SSDATA (value), "true")
12674 || !strcmp (SSDATA (value), "on")))
12675 dpyinfo->cmap = XCopyColormapAndFree (dpyinfo->display, dpyinfo->cmap);
12678 else
12679 dpyinfo->cmap = XCreateColormap (dpyinfo->display, dpyinfo->root_window,
12680 dpyinfo->visual, AllocNone);
12682 #ifdef HAVE_XDBE
12683 dpyinfo->supports_xdbe = false;
12684 int xdbe_major;
12685 int xdbe_minor;
12686 if (XdbeQueryExtension (dpyinfo->display, &xdbe_major, &xdbe_minor))
12687 dpyinfo->supports_xdbe = true;
12688 #endif
12690 #ifdef HAVE_XFT
12692 /* If we are using Xft, the following precautions should be made:
12694 1. Make sure that the Xrender extension is added before the Xft one.
12695 Otherwise, the close-display hook set by Xft is called after the one
12696 for Xrender, and the former tries to re-add the latter. This results
12697 in inconsistency of internal states and leads to X protocol error when
12698 one reconnects to the same X server (Bug#1696).
12700 2. Check dpi value in X resources. It is better we use it as well,
12701 since Xft will use it, as will all Gnome applications. If our real DPI
12702 is smaller or larger than the one Xft uses, our font will look smaller
12703 or larger than other for other applications, even if it is the same
12704 font name (monospace-10 for example). */
12706 int event_base, error_base;
12707 char *v;
12708 double d;
12710 XRenderQueryExtension (dpyinfo->display, &event_base, &error_base);
12712 v = XGetDefault (dpyinfo->display, "Xft", "dpi");
12713 if (v != NULL && sscanf (v, "%lf", &d) == 1)
12714 dpyinfo->resy = dpyinfo->resx = d;
12716 #endif
12718 if (dpyinfo->resy < 1)
12720 int screen_number = XScreenNumberOfScreen (dpyinfo->screen);
12721 double pixels = DisplayHeight (dpyinfo->display, screen_number);
12722 double mm = DisplayHeightMM (dpyinfo->display, screen_number);
12723 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
12724 dpyinfo->resy = (mm < 1) ? 100 : pixels * 25.4 / mm;
12725 pixels = DisplayWidth (dpyinfo->display, screen_number);
12726 mm = DisplayWidthMM (dpyinfo->display, screen_number);
12727 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
12728 dpyinfo->resx = (mm < 1) ? 100 : pixels * 25.4 / mm;
12732 static const struct
12734 const char *name;
12735 int offset;
12736 } atom_refs[] = {
12737 #define ATOM_REFS_INIT(string, member) \
12738 { string, offsetof (struct x_display_info, member) },
12739 ATOM_REFS_INIT ("WM_PROTOCOLS", Xatom_wm_protocols)
12740 ATOM_REFS_INIT ("WM_TAKE_FOCUS", Xatom_wm_take_focus)
12741 ATOM_REFS_INIT ("WM_SAVE_YOURSELF", Xatom_wm_save_yourself)
12742 ATOM_REFS_INIT ("WM_DELETE_WINDOW", Xatom_wm_delete_window)
12743 ATOM_REFS_INIT ("WM_CHANGE_STATE", Xatom_wm_change_state)
12744 ATOM_REFS_INIT ("WM_CONFIGURE_DENIED", Xatom_wm_configure_denied)
12745 ATOM_REFS_INIT ("WM_MOVED", Xatom_wm_window_moved)
12746 ATOM_REFS_INIT ("WM_CLIENT_LEADER", Xatom_wm_client_leader)
12747 ATOM_REFS_INIT ("Editres", Xatom_editres)
12748 ATOM_REFS_INIT ("CLIPBOARD", Xatom_CLIPBOARD)
12749 ATOM_REFS_INIT ("TIMESTAMP", Xatom_TIMESTAMP)
12750 ATOM_REFS_INIT ("TEXT", Xatom_TEXT)
12751 ATOM_REFS_INIT ("COMPOUND_TEXT", Xatom_COMPOUND_TEXT)
12752 ATOM_REFS_INIT ("UTF8_STRING", Xatom_UTF8_STRING)
12753 ATOM_REFS_INIT ("DELETE", Xatom_DELETE)
12754 ATOM_REFS_INIT ("MULTIPLE", Xatom_MULTIPLE)
12755 ATOM_REFS_INIT ("INCR", Xatom_INCR)
12756 ATOM_REFS_INIT ("_EMACS_TMP_", Xatom_EMACS_TMP)
12757 ATOM_REFS_INIT ("TARGETS", Xatom_TARGETS)
12758 ATOM_REFS_INIT ("NULL", Xatom_NULL)
12759 ATOM_REFS_INIT ("ATOM", Xatom_ATOM)
12760 ATOM_REFS_INIT ("ATOM_PAIR", Xatom_ATOM_PAIR)
12761 ATOM_REFS_INIT ("CLIPBOARD_MANAGER", Xatom_CLIPBOARD_MANAGER)
12762 ATOM_REFS_INIT ("_XEMBED_INFO", Xatom_XEMBED_INFO)
12763 /* For properties of font. */
12764 ATOM_REFS_INIT ("PIXEL_SIZE", Xatom_PIXEL_SIZE)
12765 ATOM_REFS_INIT ("AVERAGE_WIDTH", Xatom_AVERAGE_WIDTH)
12766 ATOM_REFS_INIT ("_MULE_BASELINE_OFFSET", Xatom_MULE_BASELINE_OFFSET)
12767 ATOM_REFS_INIT ("_MULE_RELATIVE_COMPOSE", Xatom_MULE_RELATIVE_COMPOSE)
12768 ATOM_REFS_INIT ("_MULE_DEFAULT_ASCENT", Xatom_MULE_DEFAULT_ASCENT)
12769 /* Ghostscript support. */
12770 ATOM_REFS_INIT ("DONE", Xatom_DONE)
12771 ATOM_REFS_INIT ("PAGE", Xatom_PAGE)
12772 ATOM_REFS_INIT ("SCROLLBAR", Xatom_Scrollbar)
12773 ATOM_REFS_INIT ("HORIZONTAL_SCROLLBAR", Xatom_Horizontal_Scrollbar)
12774 ATOM_REFS_INIT ("_XEMBED", Xatom_XEMBED)
12775 /* EWMH */
12776 ATOM_REFS_INIT ("_NET_WM_STATE", Xatom_net_wm_state)
12777 ATOM_REFS_INIT ("_NET_WM_STATE_FULLSCREEN", Xatom_net_wm_state_fullscreen)
12778 ATOM_REFS_INIT ("_NET_WM_STATE_MAXIMIZED_HORZ",
12779 Xatom_net_wm_state_maximized_horz)
12780 ATOM_REFS_INIT ("_NET_WM_STATE_MAXIMIZED_VERT",
12781 Xatom_net_wm_state_maximized_vert)
12782 ATOM_REFS_INIT ("_NET_WM_STATE_STICKY", Xatom_net_wm_state_sticky)
12783 ATOM_REFS_INIT ("_NET_WM_STATE_HIDDEN", Xatom_net_wm_state_hidden)
12784 ATOM_REFS_INIT ("_NET_WM_WINDOW_TYPE", Xatom_net_window_type)
12785 ATOM_REFS_INIT ("_NET_WM_WINDOW_TYPE_TOOLTIP",
12786 Xatom_net_window_type_tooltip)
12787 ATOM_REFS_INIT ("_NET_WM_ICON_NAME", Xatom_net_wm_icon_name)
12788 ATOM_REFS_INIT ("_NET_WM_NAME", Xatom_net_wm_name)
12789 ATOM_REFS_INIT ("_NET_SUPPORTED", Xatom_net_supported)
12790 ATOM_REFS_INIT ("_NET_SUPPORTING_WM_CHECK", Xatom_net_supporting_wm_check)
12791 ATOM_REFS_INIT ("_NET_WM_WINDOW_OPACITY", Xatom_net_wm_window_opacity)
12792 ATOM_REFS_INIT ("_NET_ACTIVE_WINDOW", Xatom_net_active_window)
12793 ATOM_REFS_INIT ("_NET_FRAME_EXTENTS", Xatom_net_frame_extents)
12794 ATOM_REFS_INIT ("_NET_CURRENT_DESKTOP", Xatom_net_current_desktop)
12795 ATOM_REFS_INIT ("_NET_WORKAREA", Xatom_net_workarea)
12796 /* Session management */
12797 ATOM_REFS_INIT ("SM_CLIENT_ID", Xatom_SM_CLIENT_ID)
12798 ATOM_REFS_INIT ("_XSETTINGS_SETTINGS", Xatom_xsettings_prop)
12799 ATOM_REFS_INIT ("MANAGER", Xatom_xsettings_mgr)
12800 ATOM_REFS_INIT ("_NET_WM_STATE_SKIP_TASKBAR", Xatom_net_wm_state_skip_taskbar)
12801 ATOM_REFS_INIT ("_NET_WM_STATE_ABOVE", Xatom_net_wm_state_above)
12802 ATOM_REFS_INIT ("_NET_WM_STATE_BELOW", Xatom_net_wm_state_below)
12805 int i;
12806 enum { atom_count = ARRAYELTS (atom_refs) };
12807 /* 1 for _XSETTINGS_SN. */
12808 enum { total_atom_count = 1 + atom_count };
12809 Atom atoms_return[total_atom_count];
12810 char *atom_names[total_atom_count];
12811 static char const xsettings_fmt[] = "_XSETTINGS_S%d";
12812 char xsettings_atom_name[sizeof xsettings_fmt - 2
12813 + INT_STRLEN_BOUND (int)];
12815 for (i = 0; i < atom_count; i++)
12816 atom_names[i] = (char *) atom_refs[i].name;
12818 /* Build _XSETTINGS_SN atom name. */
12819 sprintf (xsettings_atom_name, xsettings_fmt,
12820 XScreenNumberOfScreen (dpyinfo->screen));
12821 atom_names[i] = xsettings_atom_name;
12823 XInternAtoms (dpyinfo->display, atom_names, total_atom_count,
12824 False, atoms_return);
12826 for (i = 0; i < atom_count; i++)
12827 *(Atom *) ((char *) dpyinfo + atom_refs[i].offset) = atoms_return[i];
12829 /* Manually copy last atom. */
12830 dpyinfo->Xatom_xsettings_sel = atoms_return[i];
12833 dpyinfo->x_dnd_atoms_size = 8;
12834 dpyinfo->x_dnd_atoms = xmalloc (sizeof *dpyinfo->x_dnd_atoms
12835 * dpyinfo->x_dnd_atoms_size);
12836 dpyinfo->gray
12837 = XCreatePixmapFromBitmapData (dpyinfo->display, dpyinfo->root_window,
12838 gray_bits, gray_width, gray_height,
12839 1, 0, 1);
12841 x_setup_pointer_blanking (dpyinfo);
12843 #ifdef HAVE_X_I18N
12844 xim_initialize (dpyinfo, resource_name);
12845 #endif
12847 xsettings_initialize (dpyinfo);
12849 /* This is only needed for distinguishing keyboard and process input. */
12850 if (dpyinfo->connection != 0)
12851 add_keyboard_wait_descriptor (dpyinfo->connection);
12853 #ifdef F_SETOWN
12854 fcntl (dpyinfo->connection, F_SETOWN, getpid ());
12855 #endif /* ! defined (F_SETOWN) */
12857 if (interrupt_input)
12858 init_sigio (dpyinfo->connection);
12860 #ifdef USE_LUCID
12862 XrmValue d, fr, to;
12863 Font font;
12865 dpy = dpyinfo->display;
12866 d.addr = (XPointer)&dpy;
12867 d.size = sizeof (Display *);
12868 fr.addr = (char *) XtDefaultFont;
12869 fr.size = sizeof (XtDefaultFont);
12870 to.size = sizeof (Font *);
12871 to.addr = (XPointer)&font;
12872 x_catch_errors (dpy);
12873 if (!XtCallConverter (dpy, XtCvtStringToFont, &d, 1, &fr, &to, NULL))
12874 emacs_abort ();
12875 if (x_had_errors_p (dpy) || !XQueryFont (dpy, font))
12876 XrmPutLineResource (&xrdb, "Emacs.dialog.*.font: 9x15");
12877 /* Do not free XFontStruct returned by the above call to XQueryFont.
12878 This leads to X protocol errors at XtCloseDisplay (Bug#18403). */
12879 x_uncatch_errors ();
12881 #endif
12883 /* See if we should run in synchronous mode. This is useful
12884 for debugging X code. */
12886 AUTO_STRING (synchronous, "synchronous");
12887 AUTO_STRING (Synchronous, "Synchronous");
12888 Lisp_Object value = display_x_get_resource (dpyinfo, synchronous,
12889 Synchronous, Qnil, Qnil);
12890 if (STRINGP (value)
12891 && (!strcmp (SSDATA (value), "true")
12892 || !strcmp (SSDATA (value), "on")))
12893 XSynchronize (dpyinfo->display, True);
12897 AUTO_STRING (useXIM, "useXIM");
12898 AUTO_STRING (UseXIM, "UseXIM");
12899 Lisp_Object value = display_x_get_resource (dpyinfo, useXIM, UseXIM,
12900 Qnil, Qnil);
12901 #ifdef USE_XIM
12902 if (STRINGP (value)
12903 && (!strcmp (SSDATA (value), "false")
12904 || !strcmp (SSDATA (value), "off")))
12905 use_xim = false;
12906 #else
12907 if (STRINGP (value)
12908 && (!strcmp (SSDATA (value), "true")
12909 || !strcmp (SSDATA (value), "on")))
12910 use_xim = true;
12911 #endif
12914 #ifdef HAVE_X_SM
12915 /* Only do this for the very first display in the Emacs session.
12916 Ignore X session management when Emacs was first started on a
12917 tty or started as a daemon. */
12918 if (terminal->id == 1 && ! IS_DAEMON)
12919 x_session_initialize (dpyinfo);
12920 #endif
12922 #ifdef USE_CAIRO
12923 x_extension_initialize (dpyinfo);
12924 #endif
12926 unblock_input ();
12928 return dpyinfo;
12931 /* Get rid of display DPYINFO, deleting all frames on it,
12932 and without sending any more commands to the X server. */
12934 static void
12935 x_delete_display (struct x_display_info *dpyinfo)
12937 struct terminal *t;
12938 struct color_name_cache_entry *color_entry, *next_color_entry;
12940 /* Close all frames and delete the generic struct terminal for this
12941 X display. */
12942 for (t = terminal_list; t; t = t->next_terminal)
12943 if (t->type == output_x_window && t->display_info.x == dpyinfo)
12945 #ifdef HAVE_X_SM
12946 /* Close X session management when we close its display. */
12947 if (t->id == 1 && x_session_have_connection ())
12948 x_session_close ();
12949 #endif
12950 delete_terminal (t);
12951 break;
12954 if (next_noop_dpyinfo == dpyinfo)
12955 next_noop_dpyinfo = dpyinfo->next;
12957 if (x_display_list == dpyinfo)
12958 x_display_list = dpyinfo->next;
12959 else
12961 struct x_display_info *tail;
12963 for (tail = x_display_list; tail; tail = tail->next)
12964 if (tail->next == dpyinfo)
12965 tail->next = tail->next->next;
12968 for (color_entry = dpyinfo->color_names;
12969 color_entry;
12970 color_entry = next_color_entry)
12972 next_color_entry = color_entry->next;
12973 xfree (color_entry->name);
12974 xfree (color_entry);
12977 xfree (dpyinfo->x_id_name);
12978 xfree (dpyinfo->x_dnd_atoms);
12979 xfree (dpyinfo->color_cells);
12980 xfree (dpyinfo);
12983 #ifdef USE_X_TOOLKIT
12985 /* Atimer callback function for TIMER. Called every 0.1s to process
12986 Xt timeouts, if needed. We must avoid calling XtAppPending as
12987 much as possible because that function does an implicit XFlush
12988 that slows us down. */
12990 static void
12991 x_process_timeouts (struct atimer *timer)
12993 block_input ();
12994 x_timeout_atimer_activated_flag = false;
12995 if (toolkit_scroll_bar_interaction || popup_activated ())
12997 while (XtAppPending (Xt_app_con) & XtIMTimer)
12998 XtAppProcessEvent (Xt_app_con, XtIMTimer);
12999 /* Reactivate the atimer for next time. */
13000 x_activate_timeout_atimer ();
13002 unblock_input ();
13005 /* Install an asynchronous timer that processes Xt timeout events
13006 every 0.1s as long as either `toolkit_scroll_bar_interaction' or
13007 `popup_activated_flag' (in xmenu.c) is set. Make sure to call this
13008 function whenever these variables are set. This is necessary
13009 because some widget sets use timeouts internally, for example the
13010 LessTif menu bar, or the Xaw3d scroll bar. When Xt timeouts aren't
13011 processed, these widgets don't behave normally. */
13013 void
13014 x_activate_timeout_atimer (void)
13016 block_input ();
13017 if (!x_timeout_atimer_activated_flag)
13019 struct timespec interval = make_timespec (0, 100 * 1000 * 1000);
13020 start_atimer (ATIMER_RELATIVE, interval, x_process_timeouts, 0);
13021 x_timeout_atimer_activated_flag = true;
13023 unblock_input ();
13026 #endif /* USE_X_TOOLKIT */
13029 /* Set up use of X before we make the first connection. */
13031 static struct redisplay_interface x_redisplay_interface =
13033 x_frame_parm_handlers,
13034 x_produce_glyphs,
13035 x_write_glyphs,
13036 x_insert_glyphs,
13037 x_clear_end_of_line,
13038 x_scroll_run,
13039 x_after_update_window_line,
13040 x_update_window_begin,
13041 x_update_window_end,
13042 x_flip_and_flush,
13043 x_clear_window_mouse_face,
13044 x_get_glyph_overhangs,
13045 x_fix_overlapping_area,
13046 x_draw_fringe_bitmap,
13047 #ifdef USE_CAIRO
13048 x_cr_define_fringe_bitmap,
13049 x_cr_destroy_fringe_bitmap,
13050 #else
13051 0, /* define_fringe_bitmap */
13052 0, /* destroy_fringe_bitmap */
13053 #endif
13054 x_compute_glyph_string_overhangs,
13055 x_draw_glyph_string,
13056 x_define_frame_cursor,
13057 x_clear_frame_area,
13058 x_draw_window_cursor,
13059 x_draw_vertical_window_border,
13060 x_draw_window_divider,
13061 x_shift_glyphs_for_insert, /* Never called; see comment in function. */
13062 x_show_hourglass,
13063 x_hide_hourglass
13067 /* This function is called when the last frame on a display is deleted. */
13068 void
13069 x_delete_terminal (struct terminal *terminal)
13071 struct x_display_info *dpyinfo = terminal->display_info.x;
13073 /* Protect against recursive calls. delete_frame in
13074 delete_terminal calls us back when it deletes our last frame. */
13075 if (!terminal->name)
13076 return;
13078 block_input ();
13079 #ifdef HAVE_X_I18N
13080 /* We must close our connection to the XIM server before closing the
13081 X display. */
13082 if (dpyinfo->xim)
13083 xim_close_dpy (dpyinfo);
13084 #endif
13086 /* Normally, the display is available... */
13087 if (dpyinfo->display)
13089 x_destroy_all_bitmaps (dpyinfo);
13090 XSetCloseDownMode (dpyinfo->display, DestroyAll);
13092 /* Whether or not XCloseDisplay destroys the associated resource
13093 database depends on the version of libX11. To avoid both
13094 crash and memory leak, we dissociate the database from the
13095 display and then destroy dpyinfo->xrdb ourselves.
13097 Unfortunately, the above strategy does not work in some
13098 situations due to a bug in newer versions of libX11: because
13099 XrmSetDatabase doesn't clear the flag XlibDisplayDfltRMDB if
13100 dpy->db is NULL, XCloseDisplay destroys the associated
13101 database whereas it has not been created by XGetDefault
13102 (Bug#21974 in freedesktop.org Bugzilla). As a workaround, we
13103 don't destroy the database here in order to avoid the crash
13104 in the above situations for now, though that may cause memory
13105 leaks in other situations. */
13106 #if false
13107 #ifdef HAVE_XRMSETDATABASE
13108 XrmSetDatabase (dpyinfo->display, NULL);
13109 #else
13110 dpyinfo->display->db = NULL;
13111 #endif
13112 /* We used to call XrmDestroyDatabase from x_delete_display, but
13113 some older versions of libX11 crash if we call it after
13114 closing all the displays. */
13115 XrmDestroyDatabase (dpyinfo->xrdb);
13116 #endif
13118 #ifdef USE_GTK
13119 xg_display_close (dpyinfo->display);
13120 #else
13121 #ifdef USE_X_TOOLKIT
13122 XtCloseDisplay (dpyinfo->display);
13123 #else
13124 XCloseDisplay (dpyinfo->display);
13125 #endif
13126 #endif /* ! USE_GTK */
13127 /* Do not close the connection here because it's already closed
13128 by X(t)CloseDisplay (Bug#18403). */
13129 dpyinfo->display = NULL;
13132 /* ...but if called from x_connection_closed, the display may already
13133 be closed and dpyinfo->display was set to 0 to indicate that. Since
13134 X server is most likely gone, explicit close is the only reliable
13135 way to continue and avoid Bug#19147. */
13136 else if (dpyinfo->connection >= 0)
13137 emacs_close (dpyinfo->connection);
13139 /* No more input on this descriptor. */
13140 delete_keyboard_wait_descriptor (dpyinfo->connection);
13141 /* Mark as dead. */
13142 dpyinfo->connection = -1;
13144 x_delete_display (dpyinfo);
13145 unblock_input ();
13148 /* Create a struct terminal, initialize it with the X11 specific
13149 functions and make DISPLAY->TERMINAL point to it. */
13151 static struct terminal *
13152 x_create_terminal (struct x_display_info *dpyinfo)
13154 struct terminal *terminal;
13156 terminal = create_terminal (output_x_window, &x_redisplay_interface);
13158 terminal->display_info.x = dpyinfo;
13159 dpyinfo->terminal = terminal;
13161 /* kboard is initialized in x_term_init. */
13163 terminal->clear_frame_hook = x_clear_frame;
13164 terminal->ins_del_lines_hook = x_ins_del_lines;
13165 terminal->delete_glyphs_hook = x_delete_glyphs;
13166 terminal->ring_bell_hook = XTring_bell;
13167 terminal->toggle_invisible_pointer_hook = XTtoggle_invisible_pointer;
13168 terminal->update_begin_hook = x_update_begin;
13169 terminal->update_end_hook = x_update_end;
13170 terminal->read_socket_hook = XTread_socket;
13171 terminal->frame_up_to_date_hook = XTframe_up_to_date;
13172 terminal->buffer_flipping_unblocked_hook = XTbuffer_flipping_unblocked_hook;
13173 terminal->mouse_position_hook = XTmouse_position;
13174 terminal->frame_rehighlight_hook = XTframe_rehighlight;
13175 terminal->frame_raise_lower_hook = XTframe_raise_lower;
13176 terminal->fullscreen_hook = XTfullscreen_hook;
13177 terminal->menu_show_hook = x_menu_show;
13178 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
13179 terminal->popup_dialog_hook = xw_popup_dialog;
13180 #endif
13181 terminal->set_vertical_scroll_bar_hook = XTset_vertical_scroll_bar;
13182 terminal->set_horizontal_scroll_bar_hook = XTset_horizontal_scroll_bar;
13183 terminal->condemn_scroll_bars_hook = XTcondemn_scroll_bars;
13184 terminal->redeem_scroll_bar_hook = XTredeem_scroll_bar;
13185 terminal->judge_scroll_bars_hook = XTjudge_scroll_bars;
13186 terminal->delete_frame_hook = x_destroy_window;
13187 terminal->delete_terminal_hook = x_delete_terminal;
13188 /* Other hooks are NULL by default. */
13190 return terminal;
13193 static void
13194 x_initialize (void)
13196 baud_rate = 19200;
13198 x_noop_count = 0;
13199 any_help_event_p = false;
13200 ignore_next_mouse_click_timeout = 0;
13202 #ifdef USE_GTK
13203 current_count = -1;
13204 #endif
13206 /* Try to use interrupt input; if we can't, then start polling. */
13207 Fset_input_interrupt_mode (Qt);
13209 #if THREADS_ENABLED
13210 /* This must be called before any other Xlib routines. */
13211 if (XInitThreads () == 0)
13212 fprintf (stderr,
13213 "Warning: An error occurred initializing X11 thread support!\n");
13214 #endif
13216 #ifdef USE_X_TOOLKIT
13217 XtToolkitInitialize ();
13219 Xt_app_con = XtCreateApplicationContext ();
13221 /* Register a converter from strings to pixels, which uses
13222 Emacs' color allocation infrastructure. */
13223 XtAppSetTypeConverter (Xt_app_con,
13224 XtRString, XtRPixel, cvt_string_to_pixel,
13225 cvt_string_to_pixel_args,
13226 XtNumber (cvt_string_to_pixel_args),
13227 XtCacheByDisplay, cvt_pixel_dtor);
13229 XtAppSetFallbackResources (Xt_app_con, Xt_default_resources);
13230 #endif
13232 #ifdef USE_TOOLKIT_SCROLL_BARS
13233 #ifndef USE_GTK
13234 xaw3d_arrow_scroll = False;
13235 xaw3d_pick_top = True;
13236 #endif
13237 #endif
13239 #ifdef USE_CAIRO
13240 x_cr_init_fringe (&x_redisplay_interface);
13241 #endif
13243 /* Note that there is no real way portable across R3/R4 to get the
13244 original error handler. */
13245 XSetErrorHandler (x_error_handler);
13246 XSetIOErrorHandler (x_io_error_quitter);
13249 #ifdef USE_GTK
13250 void
13251 init_xterm (void)
13253 /* Emacs can handle only core input events, so make sure
13254 Gtk doesn't use Xinput or Xinput2 extensions. */
13255 xputenv ("GDK_CORE_DEVICE_EVENTS=1");
13257 #endif
13259 void
13260 syms_of_xterm (void)
13262 x_error_message = NULL;
13264 DEFSYM (Qvendor_specific_keysyms, "vendor-specific-keysyms");
13265 DEFSYM (Qlatin_1, "latin-1");
13267 #ifdef USE_GTK
13268 xg_default_icon_file = build_pure_c_string ("icons/hicolor/scalable/apps/emacs.svg");
13269 staticpro (&xg_default_icon_file);
13271 DEFSYM (Qx_gtk_map_stock, "x-gtk-map-stock");
13272 #endif
13274 DEFVAR_BOOL ("x-use-underline-position-properties",
13275 x_use_underline_position_properties,
13276 doc: /* Non-nil means make use of UNDERLINE_POSITION font properties.
13277 A value of nil means ignore them. If you encounter fonts with bogus
13278 UNDERLINE_POSITION font properties, set this to nil. You can also use
13279 `underline-minimum-offset' to override the font's UNDERLINE_POSITION for
13280 small font display sizes. */);
13281 x_use_underline_position_properties = true;
13282 DEFSYM (Qx_use_underline_position_properties,
13283 "x-use-underline-position-properties");
13285 DEFVAR_BOOL ("x-underline-at-descent-line",
13286 x_underline_at_descent_line,
13287 doc: /* Non-nil means to draw the underline at the same place as the descent line.
13288 (If `line-spacing' is in effect, that moves the underline lower by
13289 that many pixels.)
13290 A value of nil means to draw the underline according to the value of the
13291 variable `x-use-underline-position-properties', which is usually at the
13292 baseline level. The default value is nil. */);
13293 x_underline_at_descent_line = false;
13294 DEFSYM (Qx_underline_at_descent_line, "x-underline-at-descent-line");
13296 DEFVAR_BOOL ("x-mouse-click-focus-ignore-position",
13297 x_mouse_click_focus_ignore_position,
13298 doc: /* Non-nil means that a mouse click to focus a frame does not move point.
13299 This variable is only used when the window manager requires that you
13300 click on a frame to select it (give it focus). In that case, a value
13301 of nil, means that the selected window and cursor position changes to
13302 reflect the mouse click position, while a non-nil value means that the
13303 selected window or cursor position is preserved. */);
13304 x_mouse_click_focus_ignore_position = false;
13306 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
13307 doc: /* Which toolkit scroll bars Emacs uses, if any.
13308 A value of nil means Emacs doesn't use toolkit scroll bars.
13309 With the X Window system, the value is a symbol describing the
13310 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
13311 With MS Windows or Nextstep, the value is t. */);
13312 #ifdef USE_TOOLKIT_SCROLL_BARS
13313 #ifdef USE_MOTIF
13314 Vx_toolkit_scroll_bars = intern_c_string ("motif");
13315 #elif defined HAVE_XAW3D
13316 Vx_toolkit_scroll_bars = intern_c_string ("xaw3d");
13317 #elif USE_GTK
13318 Vx_toolkit_scroll_bars = intern_c_string ("gtk");
13319 #else
13320 Vx_toolkit_scroll_bars = intern_c_string ("xaw");
13321 #endif
13322 #else
13323 Vx_toolkit_scroll_bars = Qnil;
13324 #endif
13326 DEFSYM (Qmodifier_value, "modifier-value");
13327 DEFSYM (Qctrl, "ctrl");
13328 Fput (Qctrl, Qmodifier_value, make_number (ctrl_modifier));
13329 DEFSYM (Qalt, "alt");
13330 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
13331 DEFSYM (Qhyper, "hyper");
13332 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
13333 DEFSYM (Qmeta, "meta");
13334 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
13335 DEFSYM (Qsuper, "super");
13336 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
13338 DEFVAR_LISP ("x-ctrl-keysym", Vx_ctrl_keysym,
13339 doc: /* Which keys Emacs uses for the ctrl modifier.
13340 This should be one of the symbols `ctrl', `alt', `hyper', `meta',
13341 `super'. For example, `ctrl' means use the Ctrl_L and Ctrl_R keysyms.
13342 The default is nil, which is the same as `ctrl'. */);
13343 Vx_ctrl_keysym = Qnil;
13345 DEFVAR_LISP ("x-alt-keysym", Vx_alt_keysym,
13346 doc: /* Which keys Emacs uses for the alt modifier.
13347 This should be one of the symbols `ctrl', `alt', `hyper', `meta',
13348 `super'. For example, `alt' means use the Alt_L and Alt_R keysyms.
13349 The default is nil, which is the same as `alt'. */);
13350 Vx_alt_keysym = Qnil;
13352 DEFVAR_LISP ("x-hyper-keysym", Vx_hyper_keysym,
13353 doc: /* Which keys Emacs uses for the hyper modifier.
13354 This should be one of the symbols `ctrl', `alt', `hyper', `meta',
13355 `super'. For example, `hyper' means use the Hyper_L and Hyper_R
13356 keysyms. The default is nil, which is the same as `hyper'. */);
13357 Vx_hyper_keysym = Qnil;
13359 DEFVAR_LISP ("x-meta-keysym", Vx_meta_keysym,
13360 doc: /* Which keys Emacs uses for the meta modifier.
13361 This should be one of the symbols `ctrl', `alt', `hyper', `meta',
13362 `super'. For example, `meta' means use the Meta_L and Meta_R keysyms.
13363 The default is nil, which is the same as `meta'. */);
13364 Vx_meta_keysym = Qnil;
13366 DEFVAR_LISP ("x-super-keysym", Vx_super_keysym,
13367 doc: /* Which keys Emacs uses for the super modifier.
13368 This should be one of the symbols `ctrl', `alt', `hyper', `meta',
13369 `super'. For example, `super' means use the Super_L and Super_R
13370 keysyms. The default is nil, which is the same as `super'. */);
13371 Vx_super_keysym = Qnil;
13373 DEFVAR_LISP ("x-wait-for-event-timeout", Vx_wait_for_event_timeout,
13374 doc: /* How long to wait for X events.
13376 Emacs will wait up to this many seconds to receive X events after
13377 making changes which affect the state of the graphical interface.
13378 Under some window managers this can take an indefinite amount of time,
13379 so it is important to limit the wait.
13381 If set to a non-float value, there will be no wait at all. */);
13382 Vx_wait_for_event_timeout = make_float (0.1);
13384 DEFVAR_LISP ("x-keysym-table", Vx_keysym_table,
13385 doc: /* Hash table of character codes indexed by X keysym codes. */);
13386 Vx_keysym_table = make_hash_table (hashtest_eql, 900,
13387 DEFAULT_REHASH_SIZE,
13388 DEFAULT_REHASH_THRESHOLD,
13389 Qnil, false);
13391 DEFVAR_BOOL ("x-frame-normalize-before-maximize",
13392 x_frame_normalize_before_maximize,
13393 doc: /* Non-nil means normalize frame before maximizing.
13394 If this variable is t, Emacs first asks the window manager to give the
13395 frame its normal size, and only then the final state, whenever changing
13396 from a full-height, full-width or full-both state to the maximized one
13397 or when changing from the maximized to the full-height or full-width
13398 state.
13400 Set this variable only if your window manager cannot handle the
13401 transition between the various maximization states. */);
13402 x_frame_normalize_before_maximize = false;
13404 DEFVAR_BOOL ("x-gtk-use-window-move", x_gtk_use_window_move,
13405 doc: /* Non-nil means rely on gtk_window_move to set frame positions.
13406 If this variable is t (the default), the GTK build uses the function
13407 gtk_window_move to set or store frame positions and disables some time
13408 consuming frame position adjustments. In newer versions of GTK, Emacs
13409 always uses gtk_window_move and ignores the value of this variable. */);
13410 x_gtk_use_window_move = true;