Portability fixes in emacs-module-tests
[emacs.git] / src / xterm.c
blobf771631dafaaaec5692ce9f0eda1033b3b105ac8
1 /* X Communication module for terminals which understand the X protocol.
3 Copyright (C) 1989, 1993-2018 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or (at
10 your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>. */
20 /* New display code by Gerd Moellmann <gerd@gnu.org>. */
21 /* Xt features made by Fred Pierresteguy. */
23 #include <config.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <math.h>
28 #include "lisp.h"
29 #include "blockinput.h"
31 /* This may include sys/types.h, and that somehow loses
32 if this is not done before the other system files. */
33 #include "xterm.h"
34 #include <X11/cursorfont.h>
36 /* If we have Xfixes extension, use it for pointer blanking. */
37 #ifdef HAVE_XFIXES
38 #include <X11/extensions/Xfixes.h>
39 #endif
41 /* Using Xft implies that XRender is available. */
42 #ifdef HAVE_XFT
43 #include <X11/extensions/Xrender.h>
44 #endif
46 #ifdef HAVE_XDBE
47 #include <X11/extensions/Xdbe.h>
48 #endif
50 /* Load sys/types.h if not already loaded.
51 In some systems loading it twice is suicidal. */
52 #ifndef makedev
53 #include <sys/types.h>
54 #endif /* makedev */
56 #include <sys/ioctl.h>
58 #include "systime.h"
60 #include <fcntl.h>
61 #include <errno.h>
62 #include <sys/stat.h>
63 #include "character.h"
64 #include "coding.h"
65 #include "composite.h"
66 #include "frame.h"
67 #include "dispextern.h"
68 #include "xwidget.h"
69 #include "fontset.h"
70 #include "termhooks.h"
71 #include "termopts.h"
72 #include "termchar.h"
73 #include "emacs-icon.h"
74 #include "buffer.h"
75 #include "window.h"
76 #include "keyboard.h"
77 #include "atimer.h"
78 #include "font.h"
79 #include "xsettings.h"
80 #include "sysselect.h"
81 #include "menu.h"
83 #ifdef USE_X_TOOLKIT
84 #include <X11/Shell.h>
85 #endif
87 #include <unistd.h>
89 #ifdef USE_GTK
90 #include "gtkutil.h"
91 #ifdef HAVE_GTK3
92 #include <X11/Xproto.h>
93 #endif
94 #endif
96 #if defined (USE_LUCID) || defined (USE_MOTIF)
97 #include "../lwlib/xlwmenu.h"
98 #endif
100 #ifdef USE_X_TOOLKIT
102 /* Include toolkit specific headers for the scroll bar widget. */
104 #ifdef USE_TOOLKIT_SCROLL_BARS
105 #if defined USE_MOTIF
106 #include <Xm/Xm.h> /* For LESSTIF_VERSION */
107 #include <Xm/ScrollBar.h>
108 #else /* !USE_MOTIF i.e. use Xaw */
110 #ifdef HAVE_XAW3D
111 #include <X11/Xaw3d/Simple.h>
112 #include <X11/Xaw3d/Scrollbar.h>
113 #include <X11/Xaw3d/ThreeD.h>
114 #else /* !HAVE_XAW3D */
115 #include <X11/Xaw/Simple.h>
116 #include <X11/Xaw/Scrollbar.h>
117 #endif /* !HAVE_XAW3D */
118 #ifndef XtNpickTop
119 #define XtNpickTop "pickTop"
120 #endif /* !XtNpickTop */
121 #endif /* !USE_MOTIF */
122 #endif /* USE_TOOLKIT_SCROLL_BARS */
124 #endif /* USE_X_TOOLKIT */
126 #ifdef USE_X_TOOLKIT
127 #include "widget.h"
128 #ifndef XtNinitialState
129 #define XtNinitialState "initialState"
130 #endif
131 #endif
133 #include "bitmaps/gray.xbm"
135 #ifdef HAVE_XKB
136 #include <X11/XKBlib.h>
137 #endif
139 /* Default to using XIM if available. */
140 #ifdef USE_XIM
141 bool use_xim = true;
142 #else
143 bool use_xim = false; /* configure --without-xim */
144 #endif
146 /* Non-zero means that a HELP_EVENT has been generated since Emacs
147 start. */
149 static bool any_help_event_p;
151 /* This is a chain of structures for all the X displays currently in
152 use. */
154 struct x_display_info *x_display_list;
156 #ifdef USE_X_TOOLKIT
158 /* The application context for Xt use. */
159 XtAppContext Xt_app_con;
160 static String Xt_default_resources[] = {0};
162 /* Non-zero means user is interacting with a toolkit scroll bar. */
163 static bool toolkit_scroll_bar_interaction;
165 #endif /* USE_X_TOOLKIT */
167 /* Non-zero timeout value means ignore next mouse click if it arrives
168 before that timeout elapses (i.e. as part of the same sequence of
169 events resulting from clicking on a frame to select it). */
171 static Time ignore_next_mouse_click_timeout;
173 /* Used locally within XTread_socket. */
175 static int x_noop_count;
177 #ifdef USE_GTK
178 /* The name of the Emacs icon file. */
179 static Lisp_Object xg_default_icon_file;
180 #endif
182 /* Some functions take this as char *, not const char *. */
183 static char emacs_class[] = EMACS_CLASS;
185 enum xembed_info
187 XEMBED_MAPPED = 1 << 0
190 enum xembed_message
192 XEMBED_EMBEDDED_NOTIFY = 0,
193 XEMBED_WINDOW_ACTIVATE = 1,
194 XEMBED_WINDOW_DEACTIVATE = 2,
195 XEMBED_REQUEST_FOCUS = 3,
196 XEMBED_FOCUS_IN = 4,
197 XEMBED_FOCUS_OUT = 5,
198 XEMBED_FOCUS_NEXT = 6,
199 XEMBED_FOCUS_PREV = 7,
201 XEMBED_MODALITY_ON = 10,
202 XEMBED_MODALITY_OFF = 11,
203 XEMBED_REGISTER_ACCELERATOR = 12,
204 XEMBED_UNREGISTER_ACCELERATOR = 13,
205 XEMBED_ACTIVATE_ACCELERATOR = 14
208 static void x_free_cr_resources (struct frame *);
209 static bool x_alloc_nearest_color_1 (Display *, Colormap, XColor *);
210 static void x_raise_frame (struct frame *);
211 static void x_lower_frame (struct frame *);
212 static int x_io_error_quitter (Display *);
213 static struct terminal *x_create_terminal (struct x_display_info *);
214 static void x_frame_rehighlight (struct x_display_info *);
216 static void x_clip_to_row (struct window *, struct glyph_row *,
217 enum glyph_row_area, GC);
218 static struct scroll_bar *x_window_to_scroll_bar (Display *, Window, int);
219 static void x_scroll_bar_report_motion (struct frame **, Lisp_Object *,
220 enum scroll_bar_part *,
221 Lisp_Object *, Lisp_Object *,
222 Time *);
223 static void x_horizontal_scroll_bar_report_motion (struct frame **, Lisp_Object *,
224 enum scroll_bar_part *,
225 Lisp_Object *, Lisp_Object *,
226 Time *);
227 static bool x_handle_net_wm_state (struct frame *, const XPropertyEvent *);
228 static void x_check_fullscreen (struct frame *);
229 static void x_check_expected_move (struct frame *, int, int);
230 static void x_sync_with_move (struct frame *, int, int, bool);
231 static int handle_one_xevent (struct x_display_info *,
232 const XEvent *, int *,
233 struct input_event *);
234 #if ! (defined USE_X_TOOLKIT || defined USE_MOTIF) && defined USE_GTK
235 static int x_dispatch_event (XEvent *, Display *);
236 #endif
237 static void x_wm_set_window_state (struct frame *, int);
238 static void x_wm_set_icon_pixmap (struct frame *, ptrdiff_t);
239 static void x_initialize (void);
241 static bool get_current_wm_state (struct frame *, Window, int *, bool *);
243 /* Flush display of frame F. */
245 static void
246 x_flush (struct frame *f)
248 eassert (f && FRAME_X_P (f));
249 /* Don't call XFlush when it is not safe to redisplay; the X
250 connection may be broken. */
251 if (!NILP (Vinhibit_redisplay))
252 return;
254 block_input ();
255 XFlush (FRAME_X_DISPLAY (f));
256 unblock_input ();
260 /* Remove calls to XFlush by defining XFlush to an empty replacement.
261 Calls to XFlush should be unnecessary because the X output buffer
262 is flushed automatically as needed by calls to XPending,
263 XNextEvent, or XWindowEvent according to the XFlush man page.
264 XTread_socket calls XPending. Removing XFlush improves
265 performance. */
267 #define XFlush(DISPLAY) (void) 0
270 /***********************************************************************
271 Debugging
272 ***********************************************************************/
274 #if false
276 /* This is a function useful for recording debugging information about
277 the sequence of occurrences in this file. */
279 struct record
281 char *locus;
282 int type;
285 struct record event_record[100];
287 int event_record_index;
289 void
290 record_event (char *locus, int type)
292 if (event_record_index == ARRAYELTS (event_record))
293 event_record_index = 0;
295 event_record[event_record_index].locus = locus;
296 event_record[event_record_index].type = type;
297 event_record_index++;
300 #endif
302 #ifdef USE_CAIRO
304 #define FRAME_CR_CONTEXT(f) ((f)->output_data.x->cr_context)
305 #define FRAME_CR_SURFACE(f) ((f)->output_data.x->cr_surface)
307 static struct x_gc_ext_data *
308 x_gc_get_ext_data (struct frame *f, GC gc, int create_if_not_found_p)
310 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
311 XEDataObject object;
312 XExtData **head, *ext_data;
314 object.gc = gc;
315 head = XEHeadOfExtensionList (object);
316 ext_data = XFindOnExtensionList (head, dpyinfo->ext_codes->extension);
317 if (ext_data == NULL)
319 if (!create_if_not_found_p)
320 return NULL;
321 else
323 ext_data = xzalloc (sizeof (*ext_data));
324 ext_data->number = dpyinfo->ext_codes->extension;
325 ext_data->private_data = xzalloc (sizeof (struct x_gc_ext_data));
326 XAddToExtensionList (head, ext_data);
329 return (struct x_gc_ext_data *) ext_data->private_data;
332 static void
333 x_extension_initialize (struct x_display_info *dpyinfo)
335 XExtCodes *ext_codes = XAddExtension (dpyinfo->display);
337 dpyinfo->ext_codes = ext_codes;
340 static void
341 x_cr_destroy_surface (struct frame *f)
343 if (FRAME_CR_SURFACE (f))
345 cairo_t *cr = FRAME_CR_CONTEXT (f);
346 cairo_surface_destroy (FRAME_CR_SURFACE (f));
347 FRAME_CR_SURFACE (f) = 0;
348 if (cr) cairo_destroy (cr);
349 FRAME_CR_CONTEXT (f) = NULL;
353 cairo_t *
354 x_begin_cr_clip (struct frame *f, GC gc)
356 cairo_t *cr = FRAME_CR_CONTEXT (f);
358 if (!cr)
361 if (! FRAME_CR_SURFACE (f))
363 cairo_surface_t *surface;
364 surface = cairo_xlib_surface_create (FRAME_X_DISPLAY (f),
365 FRAME_X_DRAWABLE (f),
366 FRAME_DISPLAY_INFO (f)->visual,
367 FRAME_PIXEL_WIDTH (f),
368 FRAME_PIXEL_HEIGHT (f));
369 cr = cairo_create (surface);
370 cairo_surface_destroy (surface);
372 else
373 cr = cairo_create (FRAME_CR_SURFACE (f));
374 FRAME_CR_CONTEXT (f) = cr;
376 cairo_save (cr);
378 if (gc)
380 struct x_gc_ext_data *gc_ext = x_gc_get_ext_data (f, gc, 0);
382 if (gc_ext && gc_ext->n_clip_rects)
384 int i;
386 for (i = 0; i < gc_ext->n_clip_rects; i++)
387 cairo_rectangle (cr, gc_ext->clip_rects[i].x,
388 gc_ext->clip_rects[i].y,
389 gc_ext->clip_rects[i].width,
390 gc_ext->clip_rects[i].height);
391 cairo_clip (cr);
395 return cr;
398 void
399 x_end_cr_clip (struct frame *f)
401 cairo_restore (FRAME_CR_CONTEXT (f));
404 void
405 x_set_cr_source_with_gc_foreground (struct frame *f, GC gc)
407 XGCValues xgcv;
408 XColor color;
410 XGetGCValues (FRAME_X_DISPLAY (f), gc, GCForeground, &xgcv);
411 color.pixel = xgcv.foreground;
412 x_query_color (f, &color);
413 cairo_set_source_rgb (FRAME_CR_CONTEXT (f), color.red / 65535.0,
414 color.green / 65535.0, color.blue / 65535.0);
417 void
418 x_set_cr_source_with_gc_background (struct frame *f, GC gc)
420 XGCValues xgcv;
421 XColor color;
423 XGetGCValues (FRAME_X_DISPLAY (f), gc, GCBackground, &xgcv);
424 color.pixel = xgcv.background;
425 x_query_color (f, &color);
426 cairo_set_source_rgb (FRAME_CR_CONTEXT (f), color.red / 65535.0,
427 color.green / 65535.0, color.blue / 65535.0);
430 /* Fringe bitmaps. */
432 static int max_fringe_bmp = 0;
433 static cairo_pattern_t **fringe_bmp = 0;
435 static void
436 x_cr_define_fringe_bitmap (int which, unsigned short *bits, int h, int wd)
438 int i, stride;
439 cairo_surface_t *surface;
440 unsigned char *data;
441 cairo_pattern_t *pattern;
443 if (which >= max_fringe_bmp)
445 i = max_fringe_bmp;
446 max_fringe_bmp = which + 20;
447 fringe_bmp = (cairo_pattern_t **) xrealloc (fringe_bmp, max_fringe_bmp * sizeof (cairo_pattern_t *));
448 while (i < max_fringe_bmp)
449 fringe_bmp[i++] = 0;
452 block_input ();
454 surface = cairo_image_surface_create (CAIRO_FORMAT_A1, wd, h);
455 stride = cairo_image_surface_get_stride (surface);
456 data = cairo_image_surface_get_data (surface);
458 for (i = 0; i < h; i++)
460 *((unsigned short *) data) = bits[i];
461 data += stride;
464 cairo_surface_mark_dirty (surface);
465 pattern = cairo_pattern_create_for_surface (surface);
466 cairo_surface_destroy (surface);
468 unblock_input ();
470 fringe_bmp[which] = pattern;
473 static void
474 x_cr_destroy_fringe_bitmap (int which)
476 if (which >= max_fringe_bmp)
477 return;
479 if (fringe_bmp[which])
481 block_input ();
482 cairo_pattern_destroy (fringe_bmp[which]);
483 unblock_input ();
485 fringe_bmp[which] = 0;
488 static void
489 x_cr_draw_image (struct frame *f, GC gc, cairo_pattern_t *image,
490 int src_x, int src_y, int width, int height,
491 int dest_x, int dest_y, bool overlay_p)
493 cairo_t *cr;
494 cairo_matrix_t matrix;
495 cairo_surface_t *surface;
496 cairo_format_t format;
498 cr = x_begin_cr_clip (f, gc);
499 if (overlay_p)
500 cairo_rectangle (cr, dest_x, dest_y, width, height);
501 else
503 x_set_cr_source_with_gc_background (f, gc);
504 cairo_rectangle (cr, dest_x, dest_y, width, height);
505 cairo_fill_preserve (cr);
507 cairo_clip (cr);
508 cairo_matrix_init_translate (&matrix, src_x - dest_x, src_y - dest_y);
509 cairo_pattern_set_matrix (image, &matrix);
510 cairo_pattern_get_surface (image, &surface);
511 format = cairo_image_surface_get_format (surface);
512 if (format != CAIRO_FORMAT_A8 && format != CAIRO_FORMAT_A1)
514 cairo_set_source (cr, image);
515 cairo_fill (cr);
517 else
519 x_set_cr_source_with_gc_foreground (f, gc);
520 cairo_mask (cr, image);
522 x_end_cr_clip (f);
525 void
526 x_cr_draw_frame (cairo_t *cr, struct frame *f)
528 int width, height;
530 width = FRAME_PIXEL_WIDTH (f);
531 height = FRAME_PIXEL_HEIGHT (f);
533 x_free_cr_resources (f);
534 FRAME_CR_CONTEXT (f) = cr;
535 x_clear_area (f, 0, 0, width, height);
536 expose_frame (f, 0, 0, width, height);
537 FRAME_CR_CONTEXT (f) = NULL;
540 static cairo_status_t
541 x_cr_accumulate_data (void *closure, const unsigned char *data,
542 unsigned int length)
544 Lisp_Object *acc = (Lisp_Object *) closure;
546 *acc = Fcons (make_unibyte_string ((char const *) data, length), *acc);
548 return CAIRO_STATUS_SUCCESS;
551 static void
552 x_cr_destroy (Lisp_Object arg)
554 cairo_t *cr = (cairo_t *) XSAVE_POINTER (arg, 0);
556 block_input ();
557 cairo_destroy (cr);
558 unblock_input ();
561 Lisp_Object
562 x_cr_export_frames (Lisp_Object frames, cairo_surface_type_t surface_type)
564 struct frame *f;
565 cairo_surface_t *surface;
566 cairo_t *cr;
567 int width, height;
568 void (*surface_set_size_func) (cairo_surface_t *, double, double) = NULL;
569 Lisp_Object acc = Qnil;
570 ptrdiff_t count = SPECPDL_INDEX ();
572 specbind (Qredisplay_dont_pause, Qt);
573 redisplay_preserve_echo_area (31);
575 f = XFRAME (XCAR (frames));
576 frames = XCDR (frames);
577 width = FRAME_PIXEL_WIDTH (f);
578 height = FRAME_PIXEL_HEIGHT (f);
580 block_input ();
581 #ifdef CAIRO_HAS_PDF_SURFACE
582 if (surface_type == CAIRO_SURFACE_TYPE_PDF)
584 surface = cairo_pdf_surface_create_for_stream (x_cr_accumulate_data, &acc,
585 width, height);
586 surface_set_size_func = cairo_pdf_surface_set_size;
588 else
589 #endif
590 #ifdef CAIRO_HAS_PNG_FUNCTIONS
591 if (surface_type == CAIRO_SURFACE_TYPE_IMAGE)
592 surface = cairo_image_surface_create (CAIRO_FORMAT_RGB24, width, height);
593 else
594 #endif
595 #ifdef CAIRO_HAS_PS_SURFACE
596 if (surface_type == CAIRO_SURFACE_TYPE_PS)
598 surface = cairo_ps_surface_create_for_stream (x_cr_accumulate_data, &acc,
599 width, height);
600 surface_set_size_func = cairo_ps_surface_set_size;
602 else
603 #endif
604 #ifdef CAIRO_HAS_SVG_SURFACE
605 if (surface_type == CAIRO_SURFACE_TYPE_SVG)
606 surface = cairo_svg_surface_create_for_stream (x_cr_accumulate_data, &acc,
607 width, height);
608 else
609 #endif
610 abort ();
612 cr = cairo_create (surface);
613 cairo_surface_destroy (surface);
614 record_unwind_protect (x_cr_destroy, make_save_ptr (cr));
616 while (1)
618 x_free_cr_resources (f);
619 FRAME_CR_CONTEXT (f) = cr;
620 x_clear_area (f, 0, 0, width, height);
621 expose_frame (f, 0, 0, width, height);
622 FRAME_CR_CONTEXT (f) = NULL;
624 if (NILP (frames))
625 break;
627 cairo_surface_show_page (surface);
628 f = XFRAME (XCAR (frames));
629 frames = XCDR (frames);
630 width = FRAME_PIXEL_WIDTH (f);
631 height = FRAME_PIXEL_HEIGHT (f);
632 if (surface_set_size_func)
633 (*surface_set_size_func) (surface, width, height);
635 unblock_input ();
636 maybe_quit ();
637 block_input ();
640 #ifdef CAIRO_HAS_PNG_FUNCTIONS
641 if (surface_type == CAIRO_SURFACE_TYPE_IMAGE)
643 cairo_surface_flush (surface);
644 cairo_surface_write_to_png_stream (surface, x_cr_accumulate_data, &acc);
646 #endif
647 unblock_input ();
649 unbind_to (count, Qnil);
651 return CALLN (Fapply, intern ("concat"), Fnreverse (acc));
654 #endif /* USE_CAIRO */
656 static void
657 x_free_cr_resources (struct frame *f)
659 #ifdef USE_CAIRO
660 if (f == NULL)
662 Lisp_Object rest, frame;
663 FOR_EACH_FRAME (rest, frame)
664 if (FRAME_X_P (XFRAME (frame)))
665 x_free_cr_resources (XFRAME (frame));
667 else
669 cairo_t *cr = FRAME_CR_CONTEXT (f);
671 if (cr)
673 cairo_surface_t *surface = cairo_get_target (cr);
675 if (cairo_surface_get_type (surface) == CAIRO_SURFACE_TYPE_XLIB)
677 cairo_destroy (cr);
678 FRAME_CR_CONTEXT (f) = NULL;
682 #endif
685 static void
686 x_set_clip_rectangles (struct frame *f, GC gc, XRectangle *rectangles, int n)
688 XSetClipRectangles (FRAME_X_DISPLAY (f), gc, 0, 0, rectangles, n, Unsorted);
689 #ifdef USE_CAIRO
690 eassert (n >= 0 && n <= MAX_CLIP_RECTS);
693 struct x_gc_ext_data *gc_ext = x_gc_get_ext_data (f, gc, 1);
695 gc_ext->n_clip_rects = n;
696 memcpy (gc_ext->clip_rects, rectangles, sizeof (XRectangle) * n);
698 #endif
701 static void
702 x_reset_clip_rectangles (struct frame *f, GC gc)
704 XSetClipMask (FRAME_X_DISPLAY (f), gc, None);
705 #ifdef USE_CAIRO
707 struct x_gc_ext_data *gc_ext = x_gc_get_ext_data (f, gc, 0);
709 if (gc_ext)
710 gc_ext->n_clip_rects = 0;
712 #endif
715 static void
716 x_fill_rectangle (struct frame *f, GC gc, int x, int y, int width, int height)
718 #ifdef USE_CAIRO
719 cairo_t *cr;
721 cr = x_begin_cr_clip (f, gc);
722 x_set_cr_source_with_gc_foreground (f, gc);
723 cairo_rectangle (cr, x, y, width, height);
724 cairo_fill (cr);
725 x_end_cr_clip (f);
726 #else
727 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_DRAWABLE (f),
728 gc, x, y, width, height);
729 #endif
732 static void
733 x_draw_rectangle (struct frame *f, GC gc, int x, int y, int width, int height)
735 #ifdef USE_CAIRO
736 cairo_t *cr;
738 cr = x_begin_cr_clip (f, gc);
739 x_set_cr_source_with_gc_foreground (f, gc);
740 cairo_rectangle (cr, x + 0.5, y + 0.5, width, height);
741 cairo_set_line_width (cr, 1);
742 cairo_stroke (cr);
743 x_end_cr_clip (f);
744 #else
745 XDrawRectangle (FRAME_X_DISPLAY (f), FRAME_X_DRAWABLE (f),
746 gc, x, y, width, height);
747 #endif
750 static void
751 x_clear_window (struct frame *f)
753 #ifdef USE_CAIRO
754 cairo_t *cr;
756 cr = x_begin_cr_clip (f, NULL);
757 x_set_cr_source_with_gc_background (f, f->output_data.x->normal_gc);
758 cairo_paint (cr);
759 x_end_cr_clip (f);
760 #else
761 if (FRAME_X_DOUBLE_BUFFERED_P (f))
762 x_clear_area (f, 0, 0, FRAME_PIXEL_WIDTH (f), FRAME_PIXEL_HEIGHT (f));
763 else
764 XClearWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
765 #endif
768 #ifdef USE_CAIRO
769 static void
770 x_fill_trapezoid_for_relief (struct frame *f, GC gc, int x, int y,
771 int width, int height, int top_p)
773 cairo_t *cr;
775 cr = x_begin_cr_clip (f, gc);
776 x_set_cr_source_with_gc_foreground (f, gc);
777 cairo_move_to (cr, top_p ? x : x + height, y);
778 cairo_line_to (cr, x, y + height);
779 cairo_line_to (cr, top_p ? x + width - height : x + width, y + height);
780 cairo_line_to (cr, x + width, y);
781 cairo_fill (cr);
782 x_end_cr_clip (f);
785 enum corners
787 CORNER_BOTTOM_RIGHT, /* 0 -> pi/2 */
788 CORNER_BOTTOM_LEFT, /* pi/2 -> pi */
789 CORNER_TOP_LEFT, /* pi -> 3pi/2 */
790 CORNER_TOP_RIGHT, /* 3pi/2 -> 2pi */
791 CORNER_LAST
794 static void
795 x_erase_corners_for_relief (struct frame *f, GC gc, int x, int y,
796 int width, int height,
797 double radius, double margin, int corners)
799 cairo_t *cr;
800 int i;
802 cr = x_begin_cr_clip (f, gc);
803 x_set_cr_source_with_gc_background (f, gc);
804 for (i = 0; i < CORNER_LAST; i++)
805 if (corners & (1 << i))
807 double xm, ym, xc, yc;
809 if (i == CORNER_TOP_LEFT || i == CORNER_BOTTOM_LEFT)
810 xm = x - margin, xc = xm + radius;
811 else
812 xm = x + width + margin, xc = xm - radius;
813 if (i == CORNER_TOP_LEFT || i == CORNER_TOP_RIGHT)
814 ym = y - margin, yc = ym + radius;
815 else
816 ym = y + height + margin, yc = ym - radius;
818 cairo_move_to (cr, xm, ym);
819 cairo_arc (cr, xc, yc, radius, i * M_PI_2, (i + 1) * M_PI_2);
821 cairo_clip (cr);
822 cairo_rectangle (cr, x, y, width, height);
823 cairo_fill (cr);
824 x_end_cr_clip (f);
827 static void
828 x_draw_horizontal_wave (struct frame *f, GC gc, int x, int y,
829 int width, int height, int wave_length)
831 cairo_t *cr;
832 double dx = wave_length, dy = height - 1;
833 int xoffset, n;
835 cr = x_begin_cr_clip (f, gc);
836 x_set_cr_source_with_gc_foreground (f, gc);
837 cairo_rectangle (cr, x, y, width, height);
838 cairo_clip (cr);
840 if (x >= 0)
842 xoffset = x % (wave_length * 2);
843 if (xoffset == 0)
844 xoffset = wave_length * 2;
846 else
847 xoffset = x % (wave_length * 2) + wave_length * 2;
848 n = (width + xoffset) / wave_length + 1;
849 if (xoffset > wave_length)
851 xoffset -= wave_length;
852 --n;
853 y += height - 1;
854 dy = -dy;
857 cairo_move_to (cr, x - xoffset + 0.5, y + 0.5);
858 while (--n >= 0)
860 cairo_rel_line_to (cr, dx, dy);
861 dy = -dy;
863 cairo_set_line_width (cr, 1);
864 cairo_stroke (cr);
865 x_end_cr_clip (f);
867 #endif
870 /* Return the struct x_display_info corresponding to DPY. */
872 struct x_display_info *
873 x_display_info_for_display (Display *dpy)
875 struct x_display_info *dpyinfo;
877 for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
878 if (dpyinfo->display == dpy)
879 return dpyinfo;
881 return 0;
884 static Window
885 x_find_topmost_parent (struct frame *f)
887 struct x_output *x = f->output_data.x;
888 Window win = None, wi = x->parent_desc;
889 Display *dpy = FRAME_X_DISPLAY (f);
891 while (wi != FRAME_DISPLAY_INFO (f)->root_window)
893 Window root;
894 Window *children;
895 unsigned int nchildren;
897 win = wi;
898 if (XQueryTree (dpy, win, &root, &wi, &children, &nchildren))
899 XFree (children);
900 else
901 break;
904 return win;
907 #define OPAQUE 0xffffffff
909 void
910 x_set_frame_alpha (struct frame *f)
912 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
913 Display *dpy = FRAME_X_DISPLAY (f);
914 Window win = FRAME_OUTER_WINDOW (f);
915 double alpha = 1.0;
916 double alpha_min = 1.0;
917 unsigned long opac;
918 Window parent;
920 if (dpyinfo->x_highlight_frame == f)
921 alpha = f->alpha[0];
922 else
923 alpha = f->alpha[1];
925 if (FLOATP (Vframe_alpha_lower_limit))
926 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
927 else if (INTEGERP (Vframe_alpha_lower_limit))
928 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
930 if (alpha < 0.0)
931 return;
932 else if (alpha > 1.0)
933 alpha = 1.0;
934 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
935 alpha = alpha_min;
937 opac = alpha * OPAQUE;
939 x_catch_errors (dpy);
941 /* If there is a parent from the window manager, put the property there
942 also, to work around broken window managers that fail to do that.
943 Do this unconditionally as this function is called on reparent when
944 alpha has not changed on the frame. */
946 if (!FRAME_PARENT_FRAME (f))
948 parent = x_find_topmost_parent (f);
949 if (parent != None)
950 XChangeProperty (dpy, parent, dpyinfo->Xatom_net_wm_window_opacity,
951 XA_CARDINAL, 32, PropModeReplace,
952 (unsigned char *) &opac, 1);
955 /* return unless necessary */
957 unsigned char *data;
958 Atom actual;
959 int rc, format;
960 unsigned long n, left;
962 rc = XGetWindowProperty (dpy, win, dpyinfo->Xatom_net_wm_window_opacity,
963 0, 1, False, XA_CARDINAL,
964 &actual, &format, &n, &left,
965 &data);
967 if (rc == Success && actual != None)
969 unsigned long value = *(unsigned long *)data;
970 XFree (data);
971 if (value == opac)
973 x_uncatch_errors ();
974 return;
979 XChangeProperty (dpy, win, dpyinfo->Xatom_net_wm_window_opacity,
980 XA_CARDINAL, 32, PropModeReplace,
981 (unsigned char *) &opac, 1);
982 x_uncatch_errors ();
985 /***********************************************************************
986 Starting and ending an update
987 ***********************************************************************/
989 /* Start an update of frame F. This function is installed as a hook
990 for update_begin, i.e. it is called when update_begin is called.
991 This function is called prior to calls to x_update_window_begin for
992 each window being updated. Currently, there is nothing to do here
993 because all interesting stuff is done on a window basis. */
995 static void
996 x_update_begin (struct frame *f)
998 #ifdef USE_CAIRO
999 if (! NILP (tip_frame) && XFRAME (tip_frame) == f
1000 && ! FRAME_VISIBLE_P (f)
1001 #ifdef USE_GTK
1002 && !NILP (Fframe_parameter (tip_frame, Qtooltip))
1003 #endif
1005 return;
1007 if (! FRAME_CR_SURFACE (f))
1009 int width, height;
1010 #ifdef USE_GTK
1011 if (FRAME_GTK_WIDGET (f))
1013 GdkWindow *w = gtk_widget_get_window (FRAME_GTK_WIDGET (f));
1014 width = gdk_window_get_width (w);
1015 height = gdk_window_get_height (w);
1017 else
1018 #endif
1020 width = FRAME_PIXEL_WIDTH (f);
1021 height = FRAME_PIXEL_HEIGHT (f);
1022 if (! FRAME_EXTERNAL_TOOL_BAR (f))
1023 height += FRAME_TOOL_BAR_HEIGHT (f);
1024 if (! FRAME_EXTERNAL_MENU_BAR (f))
1025 height += FRAME_MENU_BAR_HEIGHT (f);
1028 if (width > 0 && height > 0)
1030 block_input();
1031 FRAME_CR_SURFACE (f) = cairo_image_surface_create
1032 (CAIRO_FORMAT_ARGB32, width, height);
1033 unblock_input();
1036 #endif /* USE_CAIRO */
1039 /* Start update of window W. */
1041 static void
1042 x_update_window_begin (struct window *w)
1044 struct frame *f = XFRAME (WINDOW_FRAME (w));
1045 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1047 w->output_cursor = w->cursor;
1049 block_input ();
1051 if (f == hlinfo->mouse_face_mouse_frame)
1053 /* Don't do highlighting for mouse motion during the update. */
1054 hlinfo->mouse_face_defer = true;
1056 /* If F needs to be redrawn, simply forget about any prior mouse
1057 highlighting. */
1058 if (FRAME_GARBAGED_P (f))
1059 hlinfo->mouse_face_window = Qnil;
1062 unblock_input ();
1066 /* Draw a vertical window border from (x,y0) to (x,y1) */
1068 static void
1069 x_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
1071 struct frame *f = XFRAME (WINDOW_FRAME (w));
1072 struct face *face;
1074 face = FACE_FROM_ID_OR_NULL (f, VERTICAL_BORDER_FACE_ID);
1075 if (face)
1076 XSetForeground (FRAME_X_DISPLAY (f), f->output_data.x->normal_gc,
1077 face->foreground);
1079 #ifdef USE_CAIRO
1080 x_fill_rectangle (f, f->output_data.x->normal_gc, x, y0, 1, y1 - y0);
1081 #else
1082 XDrawLine (FRAME_X_DISPLAY (f), FRAME_X_DRAWABLE (f),
1083 f->output_data.x->normal_gc, x, y0, x, y1);
1084 #endif
1087 /* Draw a window divider from (x0,y0) to (x1,y1) */
1089 static void
1090 x_draw_window_divider (struct window *w, int x0, int x1, int y0, int y1)
1092 struct frame *f = XFRAME (WINDOW_FRAME (w));
1093 struct face *face = FACE_FROM_ID_OR_NULL (f, WINDOW_DIVIDER_FACE_ID);
1094 struct face *face_first
1095 = FACE_FROM_ID_OR_NULL (f, WINDOW_DIVIDER_FIRST_PIXEL_FACE_ID);
1096 struct face *face_last
1097 = FACE_FROM_ID_OR_NULL (f, WINDOW_DIVIDER_LAST_PIXEL_FACE_ID);
1098 unsigned long color = face ? face->foreground : FRAME_FOREGROUND_PIXEL (f);
1099 unsigned long color_first = (face_first
1100 ? face_first->foreground
1101 : FRAME_FOREGROUND_PIXEL (f));
1102 unsigned long color_last = (face_last
1103 ? face_last->foreground
1104 : FRAME_FOREGROUND_PIXEL (f));
1105 Display *display = FRAME_X_DISPLAY (f);
1107 if ((y1 - y0 > x1 - x0) && (x1 - x0 >= 3))
1108 /* A vertical divider, at least three pixels wide: Draw first and
1109 last pixels differently. */
1111 XSetForeground (display, f->output_data.x->normal_gc, color_first);
1112 x_fill_rectangle (f, f->output_data.x->normal_gc,
1113 x0, y0, 1, y1 - y0);
1114 XSetForeground (display, f->output_data.x->normal_gc, color);
1115 x_fill_rectangle (f, f->output_data.x->normal_gc,
1116 x0 + 1, y0, x1 - x0 - 2, y1 - y0);
1117 XSetForeground (display, f->output_data.x->normal_gc, color_last);
1118 x_fill_rectangle (f, f->output_data.x->normal_gc,
1119 x1 - 1, y0, 1, y1 - y0);
1121 else if ((x1 - x0 > y1 - y0) && (y1 - y0 >= 3))
1122 /* A horizontal divider, at least three pixels high: Draw first and
1123 last pixels differently. */
1125 XSetForeground (display, f->output_data.x->normal_gc, color_first);
1126 x_fill_rectangle (f, f->output_data.x->normal_gc,
1127 x0, y0, x1 - x0, 1);
1128 XSetForeground (display, f->output_data.x->normal_gc, color);
1129 x_fill_rectangle (f, f->output_data.x->normal_gc,
1130 x0, y0 + 1, x1 - x0, y1 - y0 - 2);
1131 XSetForeground (display, f->output_data.x->normal_gc, color_last);
1132 x_fill_rectangle (f, f->output_data.x->normal_gc,
1133 x0, y1 - 1, x1 - x0, 1);
1135 else
1137 /* In any other case do not draw the first and last pixels
1138 differently. */
1139 XSetForeground (display, f->output_data.x->normal_gc, color);
1140 x_fill_rectangle (f, f->output_data.x->normal_gc,
1141 x0, y0, x1 - x0, y1 - y0);
1145 /* End update of window W.
1147 Draw vertical borders between horizontally adjacent windows, and
1148 display W's cursor if CURSOR_ON_P is non-zero.
1150 MOUSE_FACE_OVERWRITTEN_P non-zero means that some row containing
1151 glyphs in mouse-face were overwritten. In that case we have to
1152 make sure that the mouse-highlight is properly redrawn.
1154 W may be a menu bar pseudo-window in case we don't have X toolkit
1155 support. Such windows don't have a cursor, so don't display it
1156 here. */
1158 static void
1159 x_update_window_end (struct window *w, bool cursor_on_p,
1160 bool mouse_face_overwritten_p)
1162 if (!w->pseudo_window_p)
1164 block_input ();
1166 if (cursor_on_p)
1167 display_and_set_cursor (w, true,
1168 w->output_cursor.hpos, w->output_cursor.vpos,
1169 w->output_cursor.x, w->output_cursor.y);
1171 if (draw_window_fringes (w, true))
1173 if (WINDOW_RIGHT_DIVIDER_WIDTH (w))
1174 x_draw_right_divider (w);
1175 else
1176 x_draw_vertical_border (w);
1179 unblock_input ();
1182 /* If a row with mouse-face was overwritten, arrange for
1183 XTframe_up_to_date to redisplay the mouse highlight. */
1184 if (mouse_face_overwritten_p)
1186 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (XFRAME (w->frame));
1188 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
1189 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
1190 hlinfo->mouse_face_window = Qnil;
1194 /* Show the frame back buffer. If frame is double-buffered,
1195 atomically publish to the user's screen graphics updates made since
1196 the last call to show_back_buffer. */
1197 static void
1198 show_back_buffer (struct frame *f)
1200 block_input ();
1201 if (FRAME_X_DOUBLE_BUFFERED_P (f))
1203 #ifdef HAVE_XDBE
1204 XdbeSwapInfo swap_info;
1205 memset (&swap_info, 0, sizeof (swap_info));
1206 swap_info.swap_window = FRAME_X_WINDOW (f);
1207 swap_info.swap_action = XdbeCopied;
1208 XdbeSwapBuffers (FRAME_X_DISPLAY (f), &swap_info, 1);
1209 #else
1210 eassert (!"should have back-buffer only with XDBE");
1211 #endif
1213 FRAME_X_NEED_BUFFER_FLIP (f) = false;
1214 unblock_input ();
1217 /* Updates back buffer and flushes changes to display. Called from
1218 minibuf read code. Note that we display the back buffer even if
1219 buffer flipping is blocked. */
1220 static void
1221 x_flip_and_flush (struct frame *f)
1223 block_input ();
1224 if (FRAME_X_NEED_BUFFER_FLIP (f))
1225 show_back_buffer (f);
1226 x_flush (f);
1227 unblock_input ();
1230 /* End update of frame F. This function is installed as a hook in
1231 update_end. */
1233 static void
1234 x_update_end (struct frame *f)
1236 /* Mouse highlight may be displayed again. */
1237 MOUSE_HL_INFO (f)->mouse_face_defer = false;
1239 #ifdef USE_CAIRO
1240 if (FRAME_CR_SURFACE (f))
1242 cairo_t *cr = 0;
1243 block_input();
1244 #if defined (USE_GTK) && defined (HAVE_GTK3)
1245 if (FRAME_GTK_WIDGET (f))
1247 GdkWindow *w = gtk_widget_get_window (FRAME_GTK_WIDGET (f));
1248 cr = gdk_cairo_create (w);
1250 else
1251 #endif
1253 cairo_surface_t *surface;
1254 int width = FRAME_PIXEL_WIDTH (f);
1255 int height = FRAME_PIXEL_HEIGHT (f);
1256 if (! FRAME_EXTERNAL_TOOL_BAR (f))
1257 height += FRAME_TOOL_BAR_HEIGHT (f);
1258 if (! FRAME_EXTERNAL_MENU_BAR (f))
1259 height += FRAME_MENU_BAR_HEIGHT (f);
1260 surface = cairo_xlib_surface_create (FRAME_X_DISPLAY (f),
1261 FRAME_X_DRAWABLE (f),
1262 FRAME_DISPLAY_INFO (f)->visual,
1263 width,
1264 height);
1265 cr = cairo_create (surface);
1266 cairo_surface_destroy (surface);
1269 cairo_set_source_surface (cr, FRAME_CR_SURFACE (f), 0, 0);
1270 cairo_paint (cr);
1271 cairo_destroy (cr);
1272 unblock_input ();
1274 #endif
1276 #ifndef XFlush
1277 block_input ();
1278 XFlush (FRAME_X_DISPLAY (f));
1279 unblock_input ();
1280 #endif
1283 /* This function is called from various places in xdisp.c
1284 whenever a complete update has been performed. */
1286 static void
1287 XTframe_up_to_date (struct frame *f)
1289 eassert (FRAME_X_P (f));
1290 block_input ();
1291 FRAME_MOUSE_UPDATE (f);
1292 if (!buffer_flipping_blocked_p () && FRAME_X_NEED_BUFFER_FLIP (f))
1293 show_back_buffer (f);
1294 unblock_input ();
1297 static void
1298 XTbuffer_flipping_unblocked_hook (struct frame *f)
1300 if (FRAME_X_NEED_BUFFER_FLIP (f))
1301 show_back_buffer (f);
1305 * x_clear_under_internal_border:
1307 * Clear area of frame F's internal border. If the internal border face
1308 * of F has been specified (is not null), fill the area with that face.
1310 void
1311 x_clear_under_internal_border (struct frame *f)
1313 if (FRAME_INTERNAL_BORDER_WIDTH (f) > 0)
1315 int border = FRAME_INTERNAL_BORDER_WIDTH (f);
1316 int width = FRAME_PIXEL_WIDTH (f);
1317 int height = FRAME_PIXEL_HEIGHT (f);
1318 #ifdef USE_GTK
1319 int margin = 0;
1320 #else
1321 int margin = FRAME_TOP_MARGIN_HEIGHT (f);
1322 #endif
1323 struct face *face = FACE_FROM_ID_OR_NULL (f, INTERNAL_BORDER_FACE_ID);
1325 block_input ();
1327 if (face)
1329 unsigned long color = face->background;
1330 Display *display = FRAME_X_DISPLAY (f);
1331 GC gc = f->output_data.x->normal_gc;
1333 XSetForeground (display, gc, color);
1334 x_fill_rectangle (f, gc, 0, margin, width, border);
1335 x_fill_rectangle (f, gc, 0, 0, border, height);
1336 x_fill_rectangle (f, gc, width - border, 0, border, height);
1337 x_fill_rectangle (f, gc, 0, height - border, width, border);
1338 XSetForeground (display, gc, FRAME_FOREGROUND_PIXEL (f));
1340 else
1342 x_clear_area (f, 0, 0, border, height);
1343 x_clear_area (f, 0, margin, width, border);
1344 x_clear_area (f, width - border, 0, border, height);
1345 x_clear_area (f, 0, height - border, width, border);
1348 unblock_input ();
1352 /* Draw truncation mark bitmaps, continuation mark bitmaps, overlay
1353 arrow bitmaps, or clear the fringes if no bitmaps are required
1354 before DESIRED_ROW is made current. This function is called from
1355 update_window_line only if it is known that there are differences
1356 between bitmaps to be drawn between current row and DESIRED_ROW. */
1358 static void
1359 x_after_update_window_line (struct window *w, struct glyph_row *desired_row)
1361 eassert (w);
1363 if (!desired_row->mode_line_p && !w->pseudo_window_p)
1364 desired_row->redraw_fringe_bitmaps_p = true;
1366 #ifdef USE_X_TOOLKIT
1367 /* When a window has disappeared, make sure that no rest of
1368 full-width rows stays visible in the internal border. Could
1369 check here if updated window is the leftmost/rightmost window,
1370 but I guess it's not worth doing since vertically split windows
1371 are almost never used, internal border is rarely set, and the
1372 overhead is very small. */
1374 struct frame *f;
1375 int width, height;
1377 if (windows_or_buffers_changed
1378 && desired_row->full_width_p
1379 && (f = XFRAME (w->frame),
1380 width = FRAME_INTERNAL_BORDER_WIDTH (f),
1381 width != 0)
1382 && (height = desired_row->visible_height,
1383 height > 0))
1385 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
1386 struct face *face = FACE_FROM_ID_OR_NULL (f, INTERNAL_BORDER_FACE_ID);
1388 block_input ();
1389 if (face)
1391 unsigned long color = face->background;
1392 Display *display = FRAME_X_DISPLAY (f);
1393 GC gc = f->output_data.x->normal_gc;
1395 XSetForeground (display, gc, color);
1396 x_fill_rectangle (f, gc, 0, y, width, height);
1397 x_fill_rectangle (f, gc, FRAME_PIXEL_WIDTH (f) - width, y,
1398 width, height);
1399 XSetForeground (display, gc, FRAME_FOREGROUND_PIXEL (f));
1401 else
1403 x_clear_area (f, 0, y, width, height);
1404 x_clear_area (f, FRAME_PIXEL_WIDTH (f) - width, y, width, height);
1406 unblock_input ();
1409 #endif
1412 static void
1413 x_draw_fringe_bitmap (struct window *w, struct glyph_row *row, struct draw_fringe_bitmap_params *p)
1415 struct frame *f = XFRAME (WINDOW_FRAME (w));
1416 Display *display = FRAME_X_DISPLAY (f);
1417 GC gc = f->output_data.x->normal_gc;
1418 struct face *face = p->face;
1420 /* Must clip because of partially visible lines. */
1421 x_clip_to_row (w, row, ANY_AREA, gc);
1423 if (p->bx >= 0 && !p->overlay_p)
1425 /* In case the same realized face is used for fringes and
1426 for something displayed in the text (e.g. face `region' on
1427 mono-displays, the fill style may have been changed to
1428 FillSolid in x_draw_glyph_string_background. */
1429 if (face->stipple)
1430 XSetFillStyle (display, face->gc, FillOpaqueStippled);
1431 else
1432 XSetForeground (display, face->gc, face->background);
1434 x_fill_rectangle (f, face->gc, p->bx, p->by, p->nx, p->ny);
1436 if (!face->stipple)
1437 XSetForeground (display, face->gc, face->foreground);
1440 #ifdef USE_CAIRO
1441 if (p->which && p->which < max_fringe_bmp)
1443 XGCValues gcv;
1445 XGetGCValues (display, gc, GCForeground | GCBackground, &gcv);
1446 XSetForeground (display, gc, (p->cursor_p
1447 ? (p->overlay_p ? face->background
1448 : f->output_data.x->cursor_pixel)
1449 : face->foreground));
1450 XSetBackground (display, gc, face->background);
1451 x_cr_draw_image (f, gc, fringe_bmp[p->which], 0, p->dh,
1452 p->wd, p->h, p->x, p->y, p->overlay_p);
1453 XSetForeground (display, gc, gcv.foreground);
1454 XSetBackground (display, gc, gcv.background);
1456 #else /* not USE_CAIRO */
1457 if (p->which)
1459 Drawable drawable = FRAME_X_DRAWABLE (f);
1460 char *bits;
1461 Pixmap pixmap, clipmask = (Pixmap) 0;
1462 int depth = DefaultDepthOfScreen (FRAME_X_SCREEN (f));
1463 XGCValues gcv;
1465 if (p->wd > 8)
1466 bits = (char *) (p->bits + p->dh);
1467 else
1468 bits = (char *) p->bits + p->dh;
1470 /* Draw the bitmap. I believe these small pixmaps can be cached
1471 by the server. */
1472 pixmap = XCreatePixmapFromBitmapData (display, drawable, bits, p->wd, p->h,
1473 (p->cursor_p
1474 ? (p->overlay_p ? face->background
1475 : f->output_data.x->cursor_pixel)
1476 : face->foreground),
1477 face->background, depth);
1479 if (p->overlay_p)
1481 clipmask = XCreatePixmapFromBitmapData (display,
1482 FRAME_DISPLAY_INFO (f)->root_window,
1483 bits, p->wd, p->h,
1484 1, 0, 1);
1485 gcv.clip_mask = clipmask;
1486 gcv.clip_x_origin = p->x;
1487 gcv.clip_y_origin = p->y;
1488 XChangeGC (display, gc, GCClipMask | GCClipXOrigin | GCClipYOrigin, &gcv);
1491 XCopyArea (display, pixmap, drawable, gc, 0, 0,
1492 p->wd, p->h, p->x, p->y);
1493 XFreePixmap (display, pixmap);
1495 if (p->overlay_p)
1497 gcv.clip_mask = (Pixmap) 0;
1498 XChangeGC (display, gc, GCClipMask, &gcv);
1499 XFreePixmap (display, clipmask);
1502 #endif /* not USE_CAIRO */
1504 x_reset_clip_rectangles (f, gc);
1507 /***********************************************************************
1508 Glyph display
1509 ***********************************************************************/
1513 static void x_set_glyph_string_clipping (struct glyph_string *);
1514 static void x_set_glyph_string_gc (struct glyph_string *);
1515 static void x_draw_glyph_string_foreground (struct glyph_string *);
1516 static void x_draw_composite_glyph_string_foreground (struct glyph_string *);
1517 static void x_draw_glyph_string_box (struct glyph_string *);
1518 static void x_draw_glyph_string (struct glyph_string *);
1519 static _Noreturn void x_delete_glyphs (struct frame *, int);
1520 static void x_compute_glyph_string_overhangs (struct glyph_string *);
1521 static void x_set_cursor_gc (struct glyph_string *);
1522 static void x_set_mode_line_face_gc (struct glyph_string *);
1523 static void x_set_mouse_face_gc (struct glyph_string *);
1524 static bool x_alloc_lighter_color (struct frame *, Display *, Colormap,
1525 unsigned long *, double, int);
1526 static void x_setup_relief_color (struct frame *, struct relief *,
1527 double, int, unsigned long);
1528 static void x_setup_relief_colors (struct glyph_string *);
1529 static void x_draw_image_glyph_string (struct glyph_string *);
1530 static void x_draw_image_relief (struct glyph_string *);
1531 static void x_draw_image_foreground (struct glyph_string *);
1532 static void x_draw_image_foreground_1 (struct glyph_string *, Pixmap);
1533 static void x_clear_glyph_string_rect (struct glyph_string *, int,
1534 int, int, int);
1535 static void x_draw_relief_rect (struct frame *, int, int, int, int,
1536 int, bool, bool, bool, bool, bool,
1537 XRectangle *);
1538 static void x_draw_box_rect (struct glyph_string *, int, int, int, int,
1539 int, bool, bool, XRectangle *);
1540 static void x_scroll_bar_clear (struct frame *);
1542 #ifdef GLYPH_DEBUG
1543 static void x_check_font (struct frame *, struct font *);
1544 #endif
1547 /* Set S->gc to a suitable GC for drawing glyph string S in cursor
1548 face. */
1550 static void
1551 x_set_cursor_gc (struct glyph_string *s)
1553 if (s->font == FRAME_FONT (s->f)
1554 && s->face->background == FRAME_BACKGROUND_PIXEL (s->f)
1555 && s->face->foreground == FRAME_FOREGROUND_PIXEL (s->f)
1556 && !s->cmp)
1557 s->gc = s->f->output_data.x->cursor_gc;
1558 else
1560 /* Cursor on non-default face: must merge. */
1561 XGCValues xgcv;
1562 unsigned long mask;
1564 xgcv.background = s->f->output_data.x->cursor_pixel;
1565 xgcv.foreground = s->face->background;
1567 /* If the glyph would be invisible, try a different foreground. */
1568 if (xgcv.foreground == xgcv.background)
1569 xgcv.foreground = s->face->foreground;
1570 if (xgcv.foreground == xgcv.background)
1571 xgcv.foreground = s->f->output_data.x->cursor_foreground_pixel;
1572 if (xgcv.foreground == xgcv.background)
1573 xgcv.foreground = s->face->foreground;
1575 /* Make sure the cursor is distinct from text in this face. */
1576 if (xgcv.background == s->face->background
1577 && xgcv.foreground == s->face->foreground)
1579 xgcv.background = s->face->foreground;
1580 xgcv.foreground = s->face->background;
1583 IF_DEBUG (x_check_font (s->f, s->font));
1584 xgcv.graphics_exposures = False;
1585 mask = GCForeground | GCBackground | GCGraphicsExposures;
1587 if (FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc)
1588 XChangeGC (s->display, FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc,
1589 mask, &xgcv);
1590 else
1591 FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc
1592 = XCreateGC (s->display, FRAME_X_DRAWABLE (s->f), mask, &xgcv);
1594 s->gc = FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc;
1599 /* Set up S->gc of glyph string S for drawing text in mouse face. */
1601 static void
1602 x_set_mouse_face_gc (struct glyph_string *s)
1604 int face_id;
1605 struct face *face;
1607 /* What face has to be used last for the mouse face? */
1608 face_id = MOUSE_HL_INFO (s->f)->mouse_face_face_id;
1609 face = FACE_FROM_ID_OR_NULL (s->f, face_id);
1610 if (face == NULL)
1611 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
1613 if (s->first_glyph->type == CHAR_GLYPH)
1614 face_id = FACE_FOR_CHAR (s->f, face, s->first_glyph->u.ch, -1, Qnil);
1615 else
1616 face_id = FACE_FOR_CHAR (s->f, face, 0, -1, Qnil);
1617 s->face = FACE_FROM_ID (s->f, face_id);
1618 prepare_face_for_display (s->f, s->face);
1620 if (s->font == s->face->font)
1621 s->gc = s->face->gc;
1622 else
1624 /* Otherwise construct scratch_cursor_gc with values from FACE
1625 except for FONT. */
1626 XGCValues xgcv;
1627 unsigned long mask;
1629 xgcv.background = s->face->background;
1630 xgcv.foreground = s->face->foreground;
1631 xgcv.graphics_exposures = False;
1632 mask = GCForeground | GCBackground | GCGraphicsExposures;
1634 if (FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc)
1635 XChangeGC (s->display, FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc,
1636 mask, &xgcv);
1637 else
1638 FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc
1639 = XCreateGC (s->display, FRAME_X_DRAWABLE (s->f), mask, &xgcv);
1641 s->gc = FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc;
1644 eassert (s->gc != 0);
1648 /* Set S->gc of glyph string S to a GC suitable for drawing a mode line.
1649 Faces to use in the mode line have already been computed when the
1650 matrix was built, so there isn't much to do, here. */
1652 static void
1653 x_set_mode_line_face_gc (struct glyph_string *s)
1655 s->gc = s->face->gc;
1659 /* Set S->gc of glyph string S for drawing that glyph string. Set
1660 S->stippled_p to a non-zero value if the face of S has a stipple
1661 pattern. */
1663 static void
1664 x_set_glyph_string_gc (struct glyph_string *s)
1666 prepare_face_for_display (s->f, s->face);
1668 if (s->hl == DRAW_NORMAL_TEXT)
1670 s->gc = s->face->gc;
1671 s->stippled_p = s->face->stipple != 0;
1673 else if (s->hl == DRAW_INVERSE_VIDEO)
1675 x_set_mode_line_face_gc (s);
1676 s->stippled_p = s->face->stipple != 0;
1678 else if (s->hl == DRAW_CURSOR)
1680 x_set_cursor_gc (s);
1681 s->stippled_p = false;
1683 else if (s->hl == DRAW_MOUSE_FACE)
1685 x_set_mouse_face_gc (s);
1686 s->stippled_p = s->face->stipple != 0;
1688 else if (s->hl == DRAW_IMAGE_RAISED
1689 || s->hl == DRAW_IMAGE_SUNKEN)
1691 s->gc = s->face->gc;
1692 s->stippled_p = s->face->stipple != 0;
1694 else
1695 emacs_abort ();
1697 /* GC must have been set. */
1698 eassert (s->gc != 0);
1702 /* Set clipping for output of glyph string S. S may be part of a mode
1703 line or menu if we don't have X toolkit support. */
1705 static void
1706 x_set_glyph_string_clipping (struct glyph_string *s)
1708 XRectangle *r = s->clip;
1709 int n = get_glyph_string_clip_rects (s, r, 2);
1711 if (n > 0)
1712 x_set_clip_rectangles (s->f, s->gc, r, n);
1713 s->num_clips = n;
1717 /* Set SRC's clipping for output of glyph string DST. This is called
1718 when we are drawing DST's left_overhang or right_overhang only in
1719 the area of SRC. */
1721 static void
1722 x_set_glyph_string_clipping_exactly (struct glyph_string *src, struct glyph_string *dst)
1724 XRectangle r;
1726 r.x = src->x;
1727 r.width = src->width;
1728 r.y = src->y;
1729 r.height = src->height;
1730 dst->clip[0] = r;
1731 dst->num_clips = 1;
1732 x_set_clip_rectangles (dst->f, dst->gc, &r, 1);
1736 /* RIF:
1737 Compute left and right overhang of glyph string S. */
1739 static void
1740 x_compute_glyph_string_overhangs (struct glyph_string *s)
1742 if (s->cmp == NULL
1743 && (s->first_glyph->type == CHAR_GLYPH
1744 || s->first_glyph->type == COMPOSITE_GLYPH))
1746 struct font_metrics metrics;
1748 if (s->first_glyph->type == CHAR_GLYPH)
1750 unsigned *code = alloca (sizeof (unsigned) * s->nchars);
1751 struct font *font = s->font;
1752 int i;
1754 for (i = 0; i < s->nchars; i++)
1755 code[i] = (s->char2b[i].byte1 << 8) | s->char2b[i].byte2;
1756 font->driver->text_extents (font, code, s->nchars, &metrics);
1758 else
1760 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1762 composition_gstring_width (gstring, s->cmp_from, s->cmp_to, &metrics);
1764 s->right_overhang = (metrics.rbearing > metrics.width
1765 ? metrics.rbearing - metrics.width : 0);
1766 s->left_overhang = metrics.lbearing < 0 ? - metrics.lbearing : 0;
1768 else if (s->cmp)
1770 s->right_overhang = s->cmp->rbearing - s->cmp->pixel_width;
1771 s->left_overhang = - s->cmp->lbearing;
1776 /* Fill rectangle X, Y, W, H with background color of glyph string S. */
1778 static void
1779 x_clear_glyph_string_rect (struct glyph_string *s, int x, int y, int w, int h)
1781 XGCValues xgcv;
1782 XGetGCValues (s->display, s->gc, GCForeground | GCBackground, &xgcv);
1783 XSetForeground (s->display, s->gc, xgcv.background);
1784 x_fill_rectangle (s->f, s->gc, x, y, w, h);
1785 XSetForeground (s->display, s->gc, xgcv.foreground);
1789 /* Draw the background of glyph_string S. If S->background_filled_p
1790 is non-zero don't draw it. FORCE_P non-zero means draw the
1791 background even if it wouldn't be drawn normally. This is used
1792 when a string preceding S draws into the background of S, or S
1793 contains the first component of a composition. */
1795 static void
1796 x_draw_glyph_string_background (struct glyph_string *s, bool force_p)
1798 /* Nothing to do if background has already been drawn or if it
1799 shouldn't be drawn in the first place. */
1800 if (!s->background_filled_p)
1802 int box_line_width = max (s->face->box_line_width, 0);
1804 if (s->stippled_p)
1806 /* Fill background with a stipple pattern. */
1807 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
1808 x_fill_rectangle (s->f, s->gc, s->x,
1809 s->y + box_line_width,
1810 s->background_width,
1811 s->height - 2 * box_line_width);
1812 XSetFillStyle (s->display, s->gc, FillSolid);
1813 s->background_filled_p = true;
1815 else if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
1816 /* When xdisp.c ignores FONT_HEIGHT, we cannot trust
1817 font dimensions, since the actual glyphs might be
1818 much smaller. So in that case we always clear the
1819 rectangle with background color. */
1820 || FONT_TOO_HIGH (s->font)
1821 || s->font_not_found_p
1822 || s->extends_to_end_of_line_p
1823 || force_p)
1825 x_clear_glyph_string_rect (s, s->x, s->y + box_line_width,
1826 s->background_width,
1827 s->height - 2 * box_line_width);
1828 s->background_filled_p = true;
1834 /* Draw the foreground of glyph string S. */
1836 static void
1837 x_draw_glyph_string_foreground (struct glyph_string *s)
1839 int i, x;
1841 /* If first glyph of S has a left box line, start drawing the text
1842 of S to the right of that box line. */
1843 if (s->face->box != FACE_NO_BOX
1844 && s->first_glyph->left_box_line_p)
1845 x = s->x + eabs (s->face->box_line_width);
1846 else
1847 x = s->x;
1849 /* Draw characters of S as rectangles if S's font could not be
1850 loaded. */
1851 if (s->font_not_found_p)
1853 for (i = 0; i < s->nchars; ++i)
1855 struct glyph *g = s->first_glyph + i;
1856 x_draw_rectangle (s->f,
1857 s->gc, x, s->y, g->pixel_width - 1,
1858 s->height - 1);
1859 x += g->pixel_width;
1862 else
1864 struct font *font = s->font;
1865 int boff = font->baseline_offset;
1866 int y;
1868 if (font->vertical_centering)
1869 boff = VCENTER_BASELINE_OFFSET (font, s->f) - boff;
1871 y = s->ybase - boff;
1872 if (s->for_overlaps
1873 || (s->background_filled_p && s->hl != DRAW_CURSOR))
1874 font->driver->draw (s, 0, s->nchars, x, y, false);
1875 else
1876 font->driver->draw (s, 0, s->nchars, x, y, true);
1877 if (s->face->overstrike)
1878 font->driver->draw (s, 0, s->nchars, x + 1, y, false);
1882 /* Draw the foreground of composite glyph string S. */
1884 static void
1885 x_draw_composite_glyph_string_foreground (struct glyph_string *s)
1887 int i, j, x;
1888 struct font *font = s->font;
1890 /* If first glyph of S has a left box line, start drawing the text
1891 of S to the right of that box line. */
1892 if (s->face && s->face->box != FACE_NO_BOX
1893 && s->first_glyph->left_box_line_p)
1894 x = s->x + eabs (s->face->box_line_width);
1895 else
1896 x = s->x;
1898 /* S is a glyph string for a composition. S->cmp_from is the index
1899 of the first character drawn for glyphs of this composition.
1900 S->cmp_from == 0 means we are drawing the very first character of
1901 this composition. */
1903 /* Draw a rectangle for the composition if the font for the very
1904 first character of the composition could not be loaded. */
1905 if (s->font_not_found_p)
1907 if (s->cmp_from == 0)
1908 x_draw_rectangle (s->f, s->gc, x, s->y,
1909 s->width - 1, s->height - 1);
1911 else if (! s->first_glyph->u.cmp.automatic)
1913 int y = s->ybase;
1915 for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
1916 /* TAB in a composition means display glyphs with padding
1917 space on the left or right. */
1918 if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
1920 int xx = x + s->cmp->offsets[j * 2];
1921 int yy = y - s->cmp->offsets[j * 2 + 1];
1923 font->driver->draw (s, j, j + 1, xx, yy, false);
1924 if (s->face->overstrike)
1925 font->driver->draw (s, j, j + 1, xx + 1, yy, false);
1928 else
1930 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1931 Lisp_Object glyph;
1932 int y = s->ybase;
1933 int width = 0;
1935 for (i = j = s->cmp_from; i < s->cmp_to; i++)
1937 glyph = LGSTRING_GLYPH (gstring, i);
1938 if (NILP (LGLYPH_ADJUSTMENT (glyph)))
1939 width += LGLYPH_WIDTH (glyph);
1940 else
1942 int xoff, yoff, wadjust;
1944 if (j < i)
1946 font->driver->draw (s, j, i, x, y, false);
1947 if (s->face->overstrike)
1948 font->driver->draw (s, j, i, x + 1, y, false);
1949 x += width;
1951 xoff = LGLYPH_XOFF (glyph);
1952 yoff = LGLYPH_YOFF (glyph);
1953 wadjust = LGLYPH_WADJUST (glyph);
1954 font->driver->draw (s, i, i + 1, x + xoff, y + yoff, false);
1955 if (s->face->overstrike)
1956 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff,
1957 false);
1958 x += wadjust;
1959 j = i + 1;
1960 width = 0;
1963 if (j < i)
1965 font->driver->draw (s, j, i, x, y, false);
1966 if (s->face->overstrike)
1967 font->driver->draw (s, j, i, x + 1, y, false);
1973 /* Draw the foreground of glyph string S for glyphless characters. */
1975 static void
1976 x_draw_glyphless_glyph_string_foreground (struct glyph_string *s)
1978 struct glyph *glyph = s->first_glyph;
1979 XChar2b char2b[8];
1980 int x, i, j;
1982 /* If first glyph of S has a left box line, start drawing the text
1983 of S to the right of that box line. */
1984 if (s->face && s->face->box != FACE_NO_BOX
1985 && s->first_glyph->left_box_line_p)
1986 x = s->x + eabs (s->face->box_line_width);
1987 else
1988 x = s->x;
1990 s->char2b = char2b;
1992 for (i = 0; i < s->nchars; i++, glyph++)
1994 char buf[7], *str = NULL;
1995 int len = glyph->u.glyphless.len;
1997 if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_ACRONYM)
1999 if (len > 0
2000 && CHAR_TABLE_P (Vglyphless_char_display)
2001 && (CHAR_TABLE_EXTRA_SLOTS (XCHAR_TABLE (Vglyphless_char_display))
2002 >= 1))
2004 Lisp_Object acronym
2005 = (! glyph->u.glyphless.for_no_font
2006 ? CHAR_TABLE_REF (Vglyphless_char_display,
2007 glyph->u.glyphless.ch)
2008 : XCHAR_TABLE (Vglyphless_char_display)->extras[0]);
2009 if (STRINGP (acronym))
2010 str = SSDATA (acronym);
2013 else if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_HEX_CODE)
2015 unsigned int ch = glyph->u.glyphless.ch;
2016 eassume (ch <= MAX_CHAR);
2017 sprintf (buf, "%0*X", ch < 0x10000 ? 4 : 6, ch);
2018 str = buf;
2021 if (str)
2023 int upper_len = (len + 1) / 2;
2024 unsigned code;
2026 /* It is assured that all LEN characters in STR is ASCII. */
2027 for (j = 0; j < len; j++)
2029 code = s->font->driver->encode_char (s->font, str[j]);
2030 STORE_XCHAR2B (char2b + j, code >> 8, code & 0xFF);
2032 s->font->driver->draw (s, 0, upper_len,
2033 x + glyph->slice.glyphless.upper_xoff,
2034 s->ybase + glyph->slice.glyphless.upper_yoff,
2035 false);
2036 s->font->driver->draw (s, upper_len, len,
2037 x + glyph->slice.glyphless.lower_xoff,
2038 s->ybase + glyph->slice.glyphless.lower_yoff,
2039 false);
2041 if (glyph->u.glyphless.method != GLYPHLESS_DISPLAY_THIN_SPACE)
2042 x_draw_rectangle (s->f, s->gc,
2043 x, s->ybase - glyph->ascent,
2044 glyph->pixel_width - 1,
2045 glyph->ascent + glyph->descent - 1);
2046 x += glyph->pixel_width;
2050 #ifdef USE_X_TOOLKIT
2052 #ifdef USE_LUCID
2054 /* Return the frame on which widget WIDGET is used.. Abort if frame
2055 cannot be determined. */
2057 static struct frame *
2058 x_frame_of_widget (Widget widget)
2060 struct x_display_info *dpyinfo;
2061 Lisp_Object tail, frame;
2062 struct frame *f;
2064 dpyinfo = x_display_info_for_display (XtDisplay (widget));
2066 /* Find the top-level shell of the widget. Note that this function
2067 can be called when the widget is not yet realized, so XtWindow
2068 (widget) == 0. That's the reason we can't simply use
2069 x_any_window_to_frame. */
2070 while (!XtIsTopLevelShell (widget))
2071 widget = XtParent (widget);
2073 /* Look for a frame with that top-level widget. Allocate the color
2074 on that frame to get the right gamma correction value. */
2075 FOR_EACH_FRAME (tail, frame)
2077 f = XFRAME (frame);
2078 if (FRAME_X_P (f)
2079 && f->output_data.nothing != 1
2080 && FRAME_DISPLAY_INFO (f) == dpyinfo
2081 && f->output_data.x->widget == widget)
2082 return f;
2084 emacs_abort ();
2087 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
2088 or DELTA. Try a color with RGB values multiplied by FACTOR first.
2089 If this produces the same color as PIXEL, try a color where all RGB
2090 values have DELTA added. Return the allocated color in *PIXEL.
2091 DISPLAY is the X display, CMAP is the colormap to operate on.
2092 Value is true if successful. */
2094 bool
2095 x_alloc_lighter_color_for_widget (Widget widget, Display *display, Colormap cmap,
2096 unsigned long *pixel, double factor, int delta)
2098 struct frame *f = x_frame_of_widget (widget);
2099 return x_alloc_lighter_color (f, display, cmap, pixel, factor, delta);
2102 #endif /* USE_LUCID */
2105 /* Structure specifying which arguments should be passed by Xt to
2106 cvt_string_to_pixel. We want the widget's screen and colormap. */
2108 static XtConvertArgRec cvt_string_to_pixel_args[] =
2110 {XtWidgetBaseOffset, (XtPointer) offsetof (WidgetRec, core.screen),
2111 sizeof (Screen *)},
2112 {XtWidgetBaseOffset, (XtPointer) offsetof (WidgetRec, core.colormap),
2113 sizeof (Colormap)}
2117 /* The address of this variable is returned by
2118 cvt_string_to_pixel. */
2120 static Pixel cvt_string_to_pixel_value;
2123 /* Convert a color name to a pixel color.
2125 DPY is the display we are working on.
2127 ARGS is an array of *NARGS XrmValue structures holding additional
2128 information about the widget for which the conversion takes place.
2129 The contents of this array are determined by the specification
2130 in cvt_string_to_pixel_args.
2132 FROM is a pointer to an XrmValue which points to the color name to
2133 convert. TO is an XrmValue in which to return the pixel color.
2135 CLOSURE_RET is a pointer to user-data, in which we record if
2136 we allocated the color or not.
2138 Value is True if successful, False otherwise. */
2140 static Boolean
2141 cvt_string_to_pixel (Display *dpy, XrmValue *args, Cardinal *nargs,
2142 XrmValue *from, XrmValue *to,
2143 XtPointer *closure_ret)
2145 Screen *screen;
2146 Colormap cmap;
2147 Pixel pixel;
2148 String color_name;
2149 XColor color;
2151 if (*nargs != 2)
2153 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
2154 "wrongParameters", "cvt_string_to_pixel",
2155 "XtToolkitError",
2156 "Screen and colormap args required", NULL, NULL);
2157 return False;
2160 screen = *(Screen **) args[0].addr;
2161 cmap = *(Colormap *) args[1].addr;
2162 color_name = (String) from->addr;
2164 if (strcmp (color_name, XtDefaultBackground) == 0)
2166 *closure_ret = (XtPointer) False;
2167 pixel = WhitePixelOfScreen (screen);
2169 else if (strcmp (color_name, XtDefaultForeground) == 0)
2171 *closure_ret = (XtPointer) False;
2172 pixel = BlackPixelOfScreen (screen);
2174 else if (XParseColor (dpy, cmap, color_name, &color)
2175 && x_alloc_nearest_color_1 (dpy, cmap, &color))
2177 pixel = color.pixel;
2178 *closure_ret = (XtPointer) True;
2180 else
2182 String params[1];
2183 Cardinal nparams = 1;
2185 params[0] = color_name;
2186 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
2187 "badValue", "cvt_string_to_pixel",
2188 "XtToolkitError", "Invalid color '%s'",
2189 params, &nparams);
2190 return False;
2193 if (to->addr != NULL)
2195 if (to->size < sizeof (Pixel))
2197 to->size = sizeof (Pixel);
2198 return False;
2201 *(Pixel *) to->addr = pixel;
2203 else
2205 cvt_string_to_pixel_value = pixel;
2206 to->addr = (XtPointer) &cvt_string_to_pixel_value;
2209 to->size = sizeof (Pixel);
2210 return True;
2214 /* Free a pixel color which was previously allocated via
2215 cvt_string_to_pixel. This is registered as the destructor
2216 for this type of resource via XtSetTypeConverter.
2218 APP is the application context in which we work.
2220 TO is a pointer to an XrmValue holding the color to free.
2221 CLOSURE is the value we stored in CLOSURE_RET for this color
2222 in cvt_string_to_pixel.
2224 ARGS and NARGS are like for cvt_string_to_pixel. */
2226 static void
2227 cvt_pixel_dtor (XtAppContext app, XrmValuePtr to, XtPointer closure, XrmValuePtr args,
2228 Cardinal *nargs)
2230 if (*nargs != 2)
2232 XtAppWarningMsg (app, "wrongParameters", "cvt_pixel_dtor",
2233 "XtToolkitError",
2234 "Screen and colormap arguments required",
2235 NULL, NULL);
2237 else if (closure != NULL)
2239 /* We did allocate the pixel, so free it. */
2240 Screen *screen = *(Screen **) args[0].addr;
2241 Colormap cmap = *(Colormap *) args[1].addr;
2242 x_free_dpy_colors (DisplayOfScreen (screen), screen, cmap,
2243 (Pixel *) to->addr, 1);
2248 #endif /* USE_X_TOOLKIT */
2251 /* Value is an array of XColor structures for the contents of the
2252 color map of display DPY. Set *NCELLS to the size of the array.
2253 Note that this probably shouldn't be called for large color maps,
2254 say a 24-bit TrueColor map. */
2256 static const XColor *
2257 x_color_cells (Display *dpy, int *ncells)
2259 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
2260 eassume (dpyinfo);
2262 if (dpyinfo->color_cells == NULL)
2264 Screen *screen = dpyinfo->screen;
2265 int ncolor_cells = XDisplayCells (dpy, XScreenNumberOfScreen (screen));
2266 int i;
2268 dpyinfo->color_cells = xnmalloc (ncolor_cells,
2269 sizeof *dpyinfo->color_cells);
2270 dpyinfo->ncolor_cells = ncolor_cells;
2272 for (i = 0; i < ncolor_cells; ++i)
2273 dpyinfo->color_cells[i].pixel = i;
2275 XQueryColors (dpy, dpyinfo->cmap,
2276 dpyinfo->color_cells, ncolor_cells);
2279 *ncells = dpyinfo->ncolor_cells;
2280 return dpyinfo->color_cells;
2284 /* On frame F, translate pixel colors to RGB values for the NCOLORS
2285 colors in COLORS. Use cached information, if available. */
2287 void
2288 x_query_colors (struct frame *f, XColor *colors, int ncolors)
2290 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2292 if (dpyinfo->red_bits > 0)
2294 /* For TrueColor displays, we can decompose the RGB value
2295 directly. */
2296 int i;
2297 unsigned int rmult, gmult, bmult;
2298 unsigned int rmask, gmask, bmask;
2300 rmask = (1 << dpyinfo->red_bits) - 1;
2301 gmask = (1 << dpyinfo->green_bits) - 1;
2302 bmask = (1 << dpyinfo->blue_bits) - 1;
2303 /* If we're widening, for example, 8 bits in the pixel value to
2304 16 bits for the separate-color representation, we want to
2305 extrapolate the lower bits based on those bits available --
2306 in other words, we'd like 0xff to become 0xffff instead of
2307 the 0xff00 we'd get by just zero-filling the lower bits.
2309 We generate a 32-bit scaled-up value and shift it, in case
2310 the bit count doesn't divide 16 evenly (e.g., when dealing
2311 with a 3-3-2 bit RGB display), to get more of the lower bits
2312 correct.
2314 Should we cache the multipliers in dpyinfo? Maybe
2315 special-case the 8-8-8 common case? */
2316 rmult = 0xffffffff / rmask;
2317 gmult = 0xffffffff / gmask;
2318 bmult = 0xffffffff / bmask;
2320 for (i = 0; i < ncolors; ++i)
2322 unsigned int r, g, b;
2323 unsigned long pixel = colors[i].pixel;
2325 r = (pixel >> dpyinfo->red_offset) & rmask;
2326 g = (pixel >> dpyinfo->green_offset) & gmask;
2327 b = (pixel >> dpyinfo->blue_offset) & bmask;
2329 colors[i].red = (r * rmult) >> 16;
2330 colors[i].green = (g * gmult) >> 16;
2331 colors[i].blue = (b * bmult) >> 16;
2333 return;
2336 if (dpyinfo->color_cells)
2338 int i;
2339 for (i = 0; i < ncolors; ++i)
2341 unsigned long pixel = colors[i].pixel;
2342 eassert (pixel < dpyinfo->ncolor_cells);
2343 eassert (dpyinfo->color_cells[pixel].pixel == pixel);
2344 colors[i] = dpyinfo->color_cells[pixel];
2346 return;
2349 XQueryColors (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), colors, ncolors);
2353 /* On frame F, translate pixel color to RGB values for the color in
2354 COLOR. Use cached information, if available. */
2356 void
2357 x_query_color (struct frame *f, XColor *color)
2359 x_query_colors (f, color, 1);
2363 /* On frame F, translate the color name to RGB values. Use cached
2364 information, if possible.
2366 Note that there is currently no way to clean old entries out of the
2367 cache. However, it is limited to names in the server's database,
2368 and names we've actually looked up; list-colors-display is probably
2369 the most color-intensive case we're likely to hit. */
2371 Status x_parse_color (struct frame *f, const char *color_name,
2372 XColor *color)
2374 Display *dpy = FRAME_X_DISPLAY (f);
2375 Colormap cmap = FRAME_X_COLORMAP (f);
2376 struct color_name_cache_entry *cache_entry;
2378 if (color_name[0] == '#')
2380 /* The hex form is parsed directly by XParseColor without
2381 talking to the X server. No need for caching. */
2382 return XParseColor (dpy, cmap, color_name, color);
2385 for (cache_entry = FRAME_DISPLAY_INFO (f)->color_names; cache_entry;
2386 cache_entry = cache_entry->next)
2388 if (!xstrcasecmp(cache_entry->name, color_name))
2390 *color = cache_entry->rgb;
2391 return 1;
2395 if (XParseColor (dpy, cmap, color_name, color) == 0)
2396 /* No caching of negative results, currently. */
2397 return 0;
2399 cache_entry = xzalloc (sizeof *cache_entry);
2400 cache_entry->rgb = *color;
2401 cache_entry->name = xstrdup (color_name);
2402 cache_entry->next = FRAME_DISPLAY_INFO (f)->color_names;
2403 FRAME_DISPLAY_INFO (f)->color_names = cache_entry;
2404 return 1;
2408 /* Allocate the color COLOR->pixel on DISPLAY, colormap CMAP. If an
2409 exact match can't be allocated, try the nearest color available.
2410 Value is true if successful. Set *COLOR to the color
2411 allocated. */
2413 static bool
2414 x_alloc_nearest_color_1 (Display *dpy, Colormap cmap, XColor *color)
2416 bool rc;
2418 rc = XAllocColor (dpy, cmap, color) != 0;
2419 if (rc == 0)
2421 /* If we got to this point, the colormap is full, so we're going
2422 to try to get the next closest color. The algorithm used is
2423 a least-squares matching, which is what X uses for closest
2424 color matching with StaticColor visuals. */
2425 int nearest, i;
2426 int max_color_delta = 255;
2427 int max_delta = 3 * max_color_delta;
2428 int nearest_delta = max_delta + 1;
2429 int ncells;
2430 const XColor *cells = x_color_cells (dpy, &ncells);
2432 for (nearest = i = 0; i < ncells; ++i)
2434 int dred = (color->red >> 8) - (cells[i].red >> 8);
2435 int dgreen = (color->green >> 8) - (cells[i].green >> 8);
2436 int dblue = (color->blue >> 8) - (cells[i].blue >> 8);
2437 int delta = dred * dred + dgreen * dgreen + dblue * dblue;
2439 if (delta < nearest_delta)
2441 nearest = i;
2442 nearest_delta = delta;
2446 color->red = cells[nearest].red;
2447 color->green = cells[nearest].green;
2448 color->blue = cells[nearest].blue;
2449 rc = XAllocColor (dpy, cmap, color) != 0;
2451 else
2453 /* If allocation succeeded, and the allocated pixel color is not
2454 equal to a cached pixel color recorded earlier, there was a
2455 change in the colormap, so clear the color cache. */
2456 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
2457 eassume (dpyinfo);
2459 if (dpyinfo->color_cells)
2461 XColor *cached_color = &dpyinfo->color_cells[color->pixel];
2462 if (cached_color->red != color->red
2463 || cached_color->blue != color->blue
2464 || cached_color->green != color->green)
2466 xfree (dpyinfo->color_cells);
2467 dpyinfo->color_cells = NULL;
2468 dpyinfo->ncolor_cells = 0;
2473 #ifdef DEBUG_X_COLORS
2474 if (rc)
2475 register_color (color->pixel);
2476 #endif /* DEBUG_X_COLORS */
2478 return rc;
2482 /* Allocate the color COLOR->pixel on frame F, colormap CMAP, after
2483 gamma correction. If an exact match can't be allocated, try the
2484 nearest color available. Value is true if successful. Set *COLOR
2485 to the color allocated. */
2487 bool
2488 x_alloc_nearest_color (struct frame *f, Colormap cmap, XColor *color)
2490 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2492 gamma_correct (f, color);
2494 if (dpyinfo->red_bits > 0)
2496 color->pixel = x_make_truecolor_pixel (dpyinfo,
2497 color->red,
2498 color->green,
2499 color->blue);
2500 return true;
2503 return x_alloc_nearest_color_1 (FRAME_X_DISPLAY (f), cmap, color);
2507 /* Allocate color PIXEL on frame F. PIXEL must already be allocated.
2508 It's necessary to do this instead of just using PIXEL directly to
2509 get color reference counts right. */
2511 unsigned long
2512 x_copy_color (struct frame *f, unsigned long pixel)
2514 XColor color;
2516 /* If display has an immutable color map, freeing colors is not
2517 necessary and some servers don't allow it. Since we won't free a
2518 color once we've allocated it, we don't need to re-allocate it to
2519 maintain the server's reference count. */
2520 if (!x_mutable_colormap (FRAME_X_VISUAL (f)))
2521 return pixel;
2523 color.pixel = pixel;
2524 block_input ();
2525 /* The color could still be found in the color_cells array. */
2526 x_query_color (f, &color);
2527 XAllocColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &color);
2528 unblock_input ();
2529 #ifdef DEBUG_X_COLORS
2530 register_color (pixel);
2531 #endif
2532 return color.pixel;
2536 /* Brightness beyond which a color won't have its highlight brightness
2537 boosted.
2539 Nominally, highlight colors for `3d' faces are calculated by
2540 brightening an object's color by a constant scale factor, but this
2541 doesn't yield good results for dark colors, so for colors who's
2542 brightness is less than this value (on a scale of 0-65535) have an
2543 use an additional additive factor.
2545 The value here is set so that the default menu-bar/mode-line color
2546 (grey75) will not have its highlights changed at all. */
2547 #define HIGHLIGHT_COLOR_DARK_BOOST_LIMIT 48000
2550 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
2551 or DELTA. Try a color with RGB values multiplied by FACTOR first.
2552 If this produces the same color as PIXEL, try a color where all RGB
2553 values have DELTA added. Return the allocated color in *PIXEL.
2554 DISPLAY is the X display, CMAP is the colormap to operate on.
2555 Value is non-zero if successful. */
2557 static bool
2558 x_alloc_lighter_color (struct frame *f, Display *display, Colormap cmap,
2559 unsigned long *pixel, double factor, int delta)
2561 XColor color, new;
2562 long bright;
2563 bool success_p;
2565 /* Get RGB color values. */
2566 color.pixel = *pixel;
2567 x_query_color (f, &color);
2569 /* Change RGB values by specified FACTOR. Avoid overflow! */
2570 eassert (factor >= 0);
2571 new.red = min (0xffff, factor * color.red);
2572 new.green = min (0xffff, factor * color.green);
2573 new.blue = min (0xffff, factor * color.blue);
2575 /* Calculate brightness of COLOR. */
2576 bright = (2 * color.red + 3 * color.green + color.blue) / 6;
2578 /* We only boost colors that are darker than
2579 HIGHLIGHT_COLOR_DARK_BOOST_LIMIT. */
2580 if (bright < HIGHLIGHT_COLOR_DARK_BOOST_LIMIT)
2581 /* Make an additive adjustment to NEW, because it's dark enough so
2582 that scaling by FACTOR alone isn't enough. */
2584 /* How far below the limit this color is (0 - 1, 1 being darker). */
2585 double dimness = 1 - (double)bright / HIGHLIGHT_COLOR_DARK_BOOST_LIMIT;
2586 /* The additive adjustment. */
2587 int min_delta = delta * dimness * factor / 2;
2589 if (factor < 1)
2591 new.red = max (0, new.red - min_delta);
2592 new.green = max (0, new.green - min_delta);
2593 new.blue = max (0, new.blue - min_delta);
2595 else
2597 new.red = min (0xffff, min_delta + new.red);
2598 new.green = min (0xffff, min_delta + new.green);
2599 new.blue = min (0xffff, min_delta + new.blue);
2603 /* Try to allocate the color. */
2604 success_p = x_alloc_nearest_color (f, cmap, &new);
2605 if (success_p)
2607 if (new.pixel == *pixel)
2609 /* If we end up with the same color as before, try adding
2610 delta to the RGB values. */
2611 x_free_colors (f, &new.pixel, 1);
2613 new.red = min (0xffff, delta + color.red);
2614 new.green = min (0xffff, delta + color.green);
2615 new.blue = min (0xffff, delta + color.blue);
2616 success_p = x_alloc_nearest_color (f, cmap, &new);
2618 else
2619 success_p = true;
2620 *pixel = new.pixel;
2623 return success_p;
2627 /* Set up the foreground color for drawing relief lines of glyph
2628 string S. RELIEF is a pointer to a struct relief containing the GC
2629 with which lines will be drawn. Use a color that is FACTOR or
2630 DELTA lighter or darker than the relief's background which is found
2631 in S->f->output_data.x->relief_background. If such a color cannot
2632 be allocated, use DEFAULT_PIXEL, instead. */
2634 static void
2635 x_setup_relief_color (struct frame *f, struct relief *relief, double factor,
2636 int delta, unsigned long default_pixel)
2638 XGCValues xgcv;
2639 struct x_output *di = f->output_data.x;
2640 unsigned long mask = GCForeground | GCLineWidth | GCGraphicsExposures;
2641 unsigned long pixel;
2642 unsigned long background = di->relief_background;
2643 Colormap cmap = FRAME_X_COLORMAP (f);
2644 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2645 Display *dpy = FRAME_X_DISPLAY (f);
2647 xgcv.graphics_exposures = False;
2648 xgcv.line_width = 1;
2650 /* Free previously allocated color. The color cell will be reused
2651 when it has been freed as many times as it was allocated, so this
2652 doesn't affect faces using the same colors. */
2653 if (relief->gc && relief->pixel != -1)
2655 x_free_colors (f, &relief->pixel, 1);
2656 relief->pixel = -1;
2659 /* Allocate new color. */
2660 xgcv.foreground = default_pixel;
2661 pixel = background;
2662 if (dpyinfo->n_planes != 1
2663 && x_alloc_lighter_color (f, dpy, cmap, &pixel, factor, delta))
2664 xgcv.foreground = relief->pixel = pixel;
2666 if (relief->gc == 0)
2668 xgcv.stipple = dpyinfo->gray;
2669 mask |= GCStipple;
2670 relief->gc = XCreateGC (dpy, FRAME_X_DRAWABLE (f), mask, &xgcv);
2672 else
2673 XChangeGC (dpy, relief->gc, mask, &xgcv);
2677 /* Set up colors for the relief lines around glyph string S. */
2679 static void
2680 x_setup_relief_colors (struct glyph_string *s)
2682 struct x_output *di = s->f->output_data.x;
2683 unsigned long color;
2685 if (s->face->use_box_color_for_shadows_p)
2686 color = s->face->box_color;
2687 else if (s->first_glyph->type == IMAGE_GLYPH
2688 && s->img->pixmap
2689 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2690 color = IMAGE_BACKGROUND (s->img, s->f, 0);
2691 else
2693 XGCValues xgcv;
2695 /* Get the background color of the face. */
2696 XGetGCValues (s->display, s->gc, GCBackground, &xgcv);
2697 color = xgcv.background;
2700 if (di->white_relief.gc == 0
2701 || color != di->relief_background)
2703 di->relief_background = color;
2704 x_setup_relief_color (s->f, &di->white_relief, 1.2, 0x8000,
2705 WHITE_PIX_DEFAULT (s->f));
2706 x_setup_relief_color (s->f, &di->black_relief, 0.6, 0x4000,
2707 BLACK_PIX_DEFAULT (s->f));
2712 /* Draw a relief on frame F inside the rectangle given by LEFT_X,
2713 TOP_Y, RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the relief
2714 to draw, it must be >= 0. RAISED_P means draw a raised
2715 relief. LEFT_P means draw a relief on the left side of
2716 the rectangle. RIGHT_P means draw a relief on the right
2717 side of the rectangle. CLIP_RECT is the clipping rectangle to use
2718 when drawing. */
2720 static void
2721 x_draw_relief_rect (struct frame *f,
2722 int left_x, int top_y, int right_x, int bottom_y,
2723 int width, bool raised_p, bool top_p, bool bot_p,
2724 bool left_p, bool right_p,
2725 XRectangle *clip_rect)
2727 #ifdef USE_CAIRO
2728 GC top_left_gc, bottom_right_gc;
2729 int corners = 0;
2731 if (raised_p)
2733 top_left_gc = f->output_data.x->white_relief.gc;
2734 bottom_right_gc = f->output_data.x->black_relief.gc;
2736 else
2738 top_left_gc = f->output_data.x->black_relief.gc;
2739 bottom_right_gc = f->output_data.x->white_relief.gc;
2742 x_set_clip_rectangles (f, top_left_gc, clip_rect, 1);
2743 x_set_clip_rectangles (f, bottom_right_gc, clip_rect, 1);
2745 if (left_p)
2747 x_fill_rectangle (f, top_left_gc, left_x, top_y,
2748 width, bottom_y + 1 - top_y);
2749 if (top_p)
2750 corners |= 1 << CORNER_TOP_LEFT;
2751 if (bot_p)
2752 corners |= 1 << CORNER_BOTTOM_LEFT;
2754 if (right_p)
2756 x_fill_rectangle (f, bottom_right_gc, right_x + 1 - width, top_y,
2757 width, bottom_y + 1 - top_y);
2758 if (top_p)
2759 corners |= 1 << CORNER_TOP_RIGHT;
2760 if (bot_p)
2761 corners |= 1 << CORNER_BOTTOM_RIGHT;
2763 if (top_p)
2765 if (!right_p)
2766 x_fill_rectangle (f, top_left_gc, left_x, top_y,
2767 right_x + 1 - left_x, width);
2768 else
2769 x_fill_trapezoid_for_relief (f, top_left_gc, left_x, top_y,
2770 right_x + 1 - left_x, width, 1);
2772 if (bot_p)
2774 if (!left_p)
2775 x_fill_rectangle (f, bottom_right_gc, left_x, bottom_y + 1 - width,
2776 right_x + 1 - left_x, width);
2777 else
2778 x_fill_trapezoid_for_relief (f, bottom_right_gc,
2779 left_x, bottom_y + 1 - width,
2780 right_x + 1 - left_x, width, 0);
2782 if (left_p && width != 1)
2783 x_fill_rectangle (f, bottom_right_gc, left_x, top_y,
2784 1, bottom_y + 1 - top_y);
2785 if (top_p && width != 1)
2786 x_fill_rectangle (f, bottom_right_gc, left_x, top_y,
2787 right_x + 1 - left_x, 1);
2788 if (corners)
2790 XSetBackground (FRAME_X_DISPLAY (f), top_left_gc,
2791 FRAME_BACKGROUND_PIXEL (f));
2792 x_erase_corners_for_relief (f, top_left_gc, left_x, top_y,
2793 right_x - left_x + 1, bottom_y - top_y + 1,
2794 6, 1, corners);
2797 x_reset_clip_rectangles (f, top_left_gc);
2798 x_reset_clip_rectangles (f, bottom_right_gc);
2799 #else
2800 Display *dpy = FRAME_X_DISPLAY (f);
2801 Drawable drawable = FRAME_X_DRAWABLE (f);
2802 int i;
2803 GC gc;
2805 if (raised_p)
2806 gc = f->output_data.x->white_relief.gc;
2807 else
2808 gc = f->output_data.x->black_relief.gc;
2809 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
2811 /* This code is more complicated than it has to be, because of two
2812 minor hacks to make the boxes look nicer: (i) if width > 1, draw
2813 the outermost line using the black relief. (ii) Omit the four
2814 corner pixels. */
2816 /* Top. */
2817 if (top_p)
2819 if (width == 1)
2820 XDrawLine (dpy, drawable, gc,
2821 left_x + left_p, top_y,
2822 right_x + !right_p, top_y);
2824 for (i = 1; i < width; ++i)
2825 XDrawLine (dpy, drawable, gc,
2826 left_x + i * left_p, top_y + i,
2827 right_x + 1 - i * right_p, top_y + i);
2830 /* Left. */
2831 if (left_p)
2833 if (width == 1)
2834 XDrawLine (dpy, drawable, gc, left_x, top_y + 1, left_x, bottom_y);
2836 x_clear_area(f, left_x, top_y, 1, 1);
2837 x_clear_area(f, left_x, bottom_y, 1, 1);
2839 for (i = (width > 1 ? 1 : 0); i < width; ++i)
2840 XDrawLine (dpy, drawable, gc,
2841 left_x + i, top_y + (i + 1) * top_p,
2842 left_x + i, bottom_y + 1 - (i + 1) * bot_p);
2845 XSetClipMask (dpy, gc, None);
2846 if (raised_p)
2847 gc = f->output_data.x->black_relief.gc;
2848 else
2849 gc = f->output_data.x->white_relief.gc;
2850 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
2852 if (width > 1)
2854 /* Outermost top line. */
2855 if (top_p)
2856 XDrawLine (dpy, drawable, gc,
2857 left_x + left_p, top_y,
2858 right_x + !right_p, top_y);
2860 /* Outermost left line. */
2861 if (left_p)
2862 XDrawLine (dpy, drawable, gc, left_x, top_y + 1, left_x, bottom_y);
2865 /* Bottom. */
2866 if (bot_p)
2868 XDrawLine (dpy, drawable, gc,
2869 left_x + left_p, bottom_y,
2870 right_x + !right_p, bottom_y);
2871 for (i = 1; i < width; ++i)
2872 XDrawLine (dpy, drawable, gc,
2873 left_x + i * left_p, bottom_y - i,
2874 right_x + 1 - i * right_p, bottom_y - i);
2877 /* Right. */
2878 if (right_p)
2880 x_clear_area(f, right_x, top_y, 1, 1);
2881 x_clear_area(f, right_x, bottom_y, 1, 1);
2882 for (i = 0; i < width; ++i)
2883 XDrawLine (dpy, drawable, gc,
2884 right_x - i, top_y + (i + 1) * top_p,
2885 right_x - i, bottom_y + 1 - (i + 1) * bot_p);
2888 x_reset_clip_rectangles (f, gc);
2890 #endif
2894 /* Draw a box on frame F inside the rectangle given by LEFT_X, TOP_Y,
2895 RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the lines to
2896 draw, it must be >= 0. LEFT_P means draw a line on the
2897 left side of the rectangle. RIGHT_P means draw a line
2898 on the right side of the rectangle. CLIP_RECT is the clipping
2899 rectangle to use when drawing. */
2901 static void
2902 x_draw_box_rect (struct glyph_string *s,
2903 int left_x, int top_y, int right_x, int bottom_y, int width,
2904 bool left_p, bool right_p, XRectangle *clip_rect)
2906 XGCValues xgcv;
2908 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2909 XSetForeground (s->display, s->gc, s->face->box_color);
2910 x_set_clip_rectangles (s->f, s->gc, clip_rect, 1);
2912 /* Top. */
2913 x_fill_rectangle (s->f, s->gc,
2914 left_x, top_y, right_x - left_x + 1, width);
2916 /* Left. */
2917 if (left_p)
2918 x_fill_rectangle (s->f, s->gc,
2919 left_x, top_y, width, bottom_y - top_y + 1);
2921 /* Bottom. */
2922 x_fill_rectangle (s->f, s->gc,
2923 left_x, bottom_y - width + 1, right_x - left_x + 1, width);
2925 /* Right. */
2926 if (right_p)
2927 x_fill_rectangle (s->f, s->gc,
2928 right_x - width + 1, top_y, width, bottom_y - top_y + 1);
2930 XSetForeground (s->display, s->gc, xgcv.foreground);
2931 x_reset_clip_rectangles (s->f, s->gc);
2935 /* Draw a box around glyph string S. */
2937 static void
2938 x_draw_glyph_string_box (struct glyph_string *s)
2940 int width, left_x, right_x, top_y, bottom_y, last_x;
2941 bool raised_p, left_p, right_p;
2942 struct glyph *last_glyph;
2943 XRectangle clip_rect;
2945 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2946 ? WINDOW_RIGHT_EDGE_X (s->w)
2947 : window_box_right (s->w, s->area));
2949 /* The glyph that may have a right box line. */
2950 last_glyph = (s->cmp || s->img
2951 ? s->first_glyph
2952 : s->first_glyph + s->nchars - 1);
2954 width = eabs (s->face->box_line_width);
2955 raised_p = s->face->box == FACE_RAISED_BOX;
2956 left_x = s->x;
2957 right_x = (s->row->full_width_p && s->extends_to_end_of_line_p
2958 ? last_x - 1
2959 : min (last_x, s->x + s->background_width) - 1);
2960 top_y = s->y;
2961 bottom_y = top_y + s->height - 1;
2963 left_p = (s->first_glyph->left_box_line_p
2964 || (s->hl == DRAW_MOUSE_FACE
2965 && (s->prev == NULL
2966 || s->prev->hl != s->hl)));
2967 right_p = (last_glyph->right_box_line_p
2968 || (s->hl == DRAW_MOUSE_FACE
2969 && (s->next == NULL
2970 || s->next->hl != s->hl)));
2972 get_glyph_string_clip_rect (s, &clip_rect);
2974 if (s->face->box == FACE_SIMPLE_BOX)
2975 x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
2976 left_p, right_p, &clip_rect);
2977 else
2979 x_setup_relief_colors (s);
2980 x_draw_relief_rect (s->f, left_x, top_y, right_x, bottom_y,
2981 width, raised_p, true, true, left_p, right_p,
2982 &clip_rect);
2987 /* Draw foreground of image glyph string S. */
2989 static void
2990 x_draw_image_foreground (struct glyph_string *s)
2992 int x = s->x;
2993 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2995 /* If first glyph of S has a left box line, start drawing it to the
2996 right of that line. */
2997 if (s->face->box != FACE_NO_BOX
2998 && s->first_glyph->left_box_line_p
2999 && s->slice.x == 0)
3000 x += eabs (s->face->box_line_width);
3002 /* If there is a margin around the image, adjust x- and y-position
3003 by that margin. */
3004 if (s->slice.x == 0)
3005 x += s->img->hmargin;
3006 if (s->slice.y == 0)
3007 y += s->img->vmargin;
3009 if (s->img->pixmap)
3011 if (s->img->mask)
3013 /* We can't set both a clip mask and use XSetClipRectangles
3014 because the latter also sets a clip mask. We also can't
3015 trust on the shape extension to be available
3016 (XShapeCombineRegion). So, compute the rectangle to draw
3017 manually. */
3018 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
3019 | GCFunction);
3020 XGCValues xgcv;
3021 XRectangle clip_rect, image_rect, r;
3023 xgcv.clip_mask = s->img->mask;
3024 xgcv.clip_x_origin = x;
3025 xgcv.clip_y_origin = y;
3026 xgcv.function = GXcopy;
3027 XChangeGC (s->display, s->gc, mask, &xgcv);
3029 get_glyph_string_clip_rect (s, &clip_rect);
3030 image_rect.x = x;
3031 image_rect.y = y;
3032 image_rect.width = s->slice.width;
3033 image_rect.height = s->slice.height;
3034 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
3035 XCopyArea (s->display, s->img->pixmap,
3036 FRAME_X_DRAWABLE (s->f), s->gc,
3037 s->slice.x + r.x - x, s->slice.y + r.y - y,
3038 r.width, r.height, r.x, r.y);
3040 else
3042 XRectangle clip_rect, image_rect, r;
3044 get_glyph_string_clip_rect (s, &clip_rect);
3045 image_rect.x = x;
3046 image_rect.y = y;
3047 image_rect.width = s->slice.width;
3048 image_rect.height = s->slice.height;
3049 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
3050 XCopyArea (s->display, s->img->pixmap,
3051 FRAME_X_DRAWABLE (s->f), s->gc,
3052 s->slice.x + r.x - x, s->slice.y + r.y - y,
3053 r.width, r.height, r.x, r.y);
3055 /* When the image has a mask, we can expect that at
3056 least part of a mouse highlight or a block cursor will
3057 be visible. If the image doesn't have a mask, make
3058 a block cursor visible by drawing a rectangle around
3059 the image. I believe it's looking better if we do
3060 nothing here for mouse-face. */
3061 if (s->hl == DRAW_CURSOR)
3063 int relief = eabs (s->img->relief);
3064 x_draw_rectangle (s->f, s->gc,
3065 x - relief, y - relief,
3066 s->slice.width + relief*2 - 1,
3067 s->slice.height + relief*2 - 1);
3071 else
3072 /* Draw a rectangle if image could not be loaded. */
3073 x_draw_rectangle (s->f, s->gc, x, y,
3074 s->slice.width - 1, s->slice.height - 1);
3078 /* Draw a relief around the image glyph string S. */
3080 static void
3081 x_draw_image_relief (struct glyph_string *s)
3083 int x1, y1, thick;
3084 bool raised_p, top_p, bot_p, left_p, right_p;
3085 int extra_x, extra_y;
3086 XRectangle r;
3087 int x = s->x;
3088 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
3090 /* If first glyph of S has a left box line, start drawing it to the
3091 right of that line. */
3092 if (s->face->box != FACE_NO_BOX
3093 && s->first_glyph->left_box_line_p
3094 && s->slice.x == 0)
3095 x += eabs (s->face->box_line_width);
3097 /* If there is a margin around the image, adjust x- and y-position
3098 by that margin. */
3099 if (s->slice.x == 0)
3100 x += s->img->hmargin;
3101 if (s->slice.y == 0)
3102 y += s->img->vmargin;
3104 if (s->hl == DRAW_IMAGE_SUNKEN
3105 || s->hl == DRAW_IMAGE_RAISED)
3107 thick = tool_bar_button_relief >= 0 ? tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3108 raised_p = s->hl == DRAW_IMAGE_RAISED;
3110 else
3112 thick = eabs (s->img->relief);
3113 raised_p = s->img->relief > 0;
3116 x1 = x + s->slice.width - 1;
3117 y1 = y + s->slice.height - 1;
3119 extra_x = extra_y = 0;
3120 if (s->face->id == TOOL_BAR_FACE_ID)
3122 if (CONSP (Vtool_bar_button_margin)
3123 && INTEGERP (XCAR (Vtool_bar_button_margin))
3124 && INTEGERP (XCDR (Vtool_bar_button_margin)))
3126 extra_x = XINT (XCAR (Vtool_bar_button_margin));
3127 extra_y = XINT (XCDR (Vtool_bar_button_margin));
3129 else if (INTEGERP (Vtool_bar_button_margin))
3130 extra_x = extra_y = XINT (Vtool_bar_button_margin);
3133 top_p = bot_p = left_p = right_p = false;
3135 if (s->slice.x == 0)
3136 x -= thick + extra_x, left_p = true;
3137 if (s->slice.y == 0)
3138 y -= thick + extra_y, top_p = true;
3139 if (s->slice.x + s->slice.width == s->img->width)
3140 x1 += thick + extra_x, right_p = true;
3141 if (s->slice.y + s->slice.height == s->img->height)
3142 y1 += thick + extra_y, bot_p = true;
3144 x_setup_relief_colors (s);
3145 get_glyph_string_clip_rect (s, &r);
3146 x_draw_relief_rect (s->f, x, y, x1, y1, thick, raised_p,
3147 top_p, bot_p, left_p, right_p, &r);
3151 /* Draw the foreground of image glyph string S to PIXMAP. */
3153 static void
3154 x_draw_image_foreground_1 (struct glyph_string *s, Pixmap pixmap)
3156 int x = 0;
3157 int y = s->ybase - s->y - image_ascent (s->img, s->face, &s->slice);
3159 /* If first glyph of S has a left box line, start drawing it to the
3160 right of that line. */
3161 if (s->face->box != FACE_NO_BOX
3162 && s->first_glyph->left_box_line_p
3163 && s->slice.x == 0)
3164 x += eabs (s->face->box_line_width);
3166 /* If there is a margin around the image, adjust x- and y-position
3167 by that margin. */
3168 if (s->slice.x == 0)
3169 x += s->img->hmargin;
3170 if (s->slice.y == 0)
3171 y += s->img->vmargin;
3173 if (s->img->pixmap)
3175 if (s->img->mask)
3177 /* We can't set both a clip mask and use XSetClipRectangles
3178 because the latter also sets a clip mask. We also can't
3179 trust on the shape extension to be available
3180 (XShapeCombineRegion). So, compute the rectangle to draw
3181 manually. */
3182 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
3183 | GCFunction);
3184 XGCValues xgcv;
3186 xgcv.clip_mask = s->img->mask;
3187 xgcv.clip_x_origin = x - s->slice.x;
3188 xgcv.clip_y_origin = y - s->slice.y;
3189 xgcv.function = GXcopy;
3190 XChangeGC (s->display, s->gc, mask, &xgcv);
3192 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
3193 s->slice.x, s->slice.y,
3194 s->slice.width, s->slice.height, x, y);
3195 XSetClipMask (s->display, s->gc, None);
3197 else
3199 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
3200 s->slice.x, s->slice.y,
3201 s->slice.width, s->slice.height, x, y);
3203 /* When the image has a mask, we can expect that at
3204 least part of a mouse highlight or a block cursor will
3205 be visible. If the image doesn't have a mask, make
3206 a block cursor visible by drawing a rectangle around
3207 the image. I believe it's looking better if we do
3208 nothing here for mouse-face. */
3209 if (s->hl == DRAW_CURSOR)
3211 int r = eabs (s->img->relief);
3212 x_draw_rectangle (s->f, s->gc, x - r, y - r,
3213 s->slice.width + r*2 - 1,
3214 s->slice.height + r*2 - 1);
3218 else
3219 /* Draw a rectangle if image could not be loaded. */
3220 x_draw_rectangle (s->f, s->gc, x, y,
3221 s->slice.width - 1, s->slice.height - 1);
3225 /* Draw part of the background of glyph string S. X, Y, W, and H
3226 give the rectangle to draw. */
3228 static void
3229 x_draw_glyph_string_bg_rect (struct glyph_string *s, int x, int y, int w, int h)
3231 if (s->stippled_p)
3233 /* Fill background with a stipple pattern. */
3234 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
3235 x_fill_rectangle (s->f, s->gc, x, y, w, h);
3236 XSetFillStyle (s->display, s->gc, FillSolid);
3238 else
3239 x_clear_glyph_string_rect (s, x, y, w, h);
3243 /* Draw image glyph string S.
3245 s->y
3246 s->x +-------------------------
3247 | s->face->box
3249 | +-------------------------
3250 | | s->img->margin
3252 | | +-------------------
3253 | | | the image
3257 static void
3258 x_draw_image_glyph_string (struct glyph_string *s)
3260 int box_line_hwidth = eabs (s->face->box_line_width);
3261 int box_line_vwidth = max (s->face->box_line_width, 0);
3262 int height;
3263 Pixmap pixmap = None;
3265 height = s->height;
3266 if (s->slice.y == 0)
3267 height -= box_line_vwidth;
3268 if (s->slice.y + s->slice.height >= s->img->height)
3269 height -= box_line_vwidth;
3271 /* Fill background with face under the image. Do it only if row is
3272 taller than image or if image has a clip mask to reduce
3273 flickering. */
3274 s->stippled_p = s->face->stipple != 0;
3275 if (height > s->slice.height
3276 || s->img->hmargin
3277 || s->img->vmargin
3278 || s->img->mask
3279 || s->img->pixmap == 0
3280 || s->width != s->background_width)
3282 if (s->img->mask)
3284 /* Create a pixmap as large as the glyph string. Fill it
3285 with the background color. Copy the image to it, using
3286 its mask. Copy the temporary pixmap to the display. */
3287 Screen *screen = FRAME_X_SCREEN (s->f);
3288 int depth = DefaultDepthOfScreen (screen);
3290 /* Create a pixmap as large as the glyph string. */
3291 pixmap = XCreatePixmap (s->display, FRAME_X_DRAWABLE (s->f),
3292 s->background_width,
3293 s->height, depth);
3295 /* Don't clip in the following because we're working on the
3296 pixmap. */
3297 XSetClipMask (s->display, s->gc, None);
3299 /* Fill the pixmap with the background color/stipple. */
3300 if (s->stippled_p)
3302 /* Fill background with a stipple pattern. */
3303 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
3304 XSetTSOrigin (s->display, s->gc, - s->x, - s->y);
3305 XFillRectangle (s->display, pixmap, s->gc,
3306 0, 0, s->background_width, s->height);
3307 XSetFillStyle (s->display, s->gc, FillSolid);
3308 XSetTSOrigin (s->display, s->gc, 0, 0);
3310 else
3312 XGCValues xgcv;
3313 XGetGCValues (s->display, s->gc, GCForeground | GCBackground,
3314 &xgcv);
3315 XSetForeground (s->display, s->gc, xgcv.background);
3316 XFillRectangle (s->display, pixmap, s->gc,
3317 0, 0, s->background_width, s->height);
3318 XSetForeground (s->display, s->gc, xgcv.foreground);
3321 else
3323 int x = s->x;
3324 int y = s->y;
3325 int width = s->background_width;
3327 if (s->first_glyph->left_box_line_p
3328 && s->slice.x == 0)
3330 x += box_line_hwidth;
3331 width -= box_line_hwidth;
3334 if (s->slice.y == 0)
3335 y += box_line_vwidth;
3337 x_draw_glyph_string_bg_rect (s, x, y, width, height);
3340 s->background_filled_p = true;
3343 /* Draw the foreground. */
3344 #ifdef USE_CAIRO
3345 if (s->img->cr_data)
3347 cairo_t *cr = x_begin_cr_clip (s->f, s->gc);
3349 int x = s->x + s->img->hmargin;
3350 int y = s->y + s->img->vmargin;
3351 int width = s->background_width;
3353 cairo_set_source_surface (cr, s->img->cr_data,
3354 x - s->slice.x,
3355 y - s->slice.y);
3356 cairo_rectangle (cr, x, y, width, height);
3357 cairo_fill (cr);
3358 x_end_cr_clip (s->f);
3360 else
3361 #endif
3362 if (pixmap != None)
3364 x_draw_image_foreground_1 (s, pixmap);
3365 x_set_glyph_string_clipping (s);
3366 XCopyArea (s->display, pixmap, FRAME_X_DRAWABLE (s->f), s->gc,
3367 0, 0, s->background_width, s->height, s->x, s->y);
3368 XFreePixmap (s->display, pixmap);
3370 else
3371 x_draw_image_foreground (s);
3373 /* If we must draw a relief around the image, do it. */
3374 if (s->img->relief
3375 || s->hl == DRAW_IMAGE_RAISED
3376 || s->hl == DRAW_IMAGE_SUNKEN)
3377 x_draw_image_relief (s);
3381 /* Draw stretch glyph string S. */
3383 static void
3384 x_draw_stretch_glyph_string (struct glyph_string *s)
3386 eassert (s->first_glyph->type == STRETCH_GLYPH);
3388 if (s->hl == DRAW_CURSOR
3389 && !x_stretch_cursor_p)
3391 /* If `x-stretch-cursor' is nil, don't draw a block cursor as
3392 wide as the stretch glyph. */
3393 int width, background_width = s->background_width;
3394 int x = s->x;
3396 if (!s->row->reversed_p)
3398 int left_x = window_box_left_offset (s->w, TEXT_AREA);
3400 if (x < left_x)
3402 background_width -= left_x - x;
3403 x = left_x;
3406 else
3408 /* In R2L rows, draw the cursor on the right edge of the
3409 stretch glyph. */
3410 int right_x = window_box_right (s->w, TEXT_AREA);
3412 if (x + background_width > right_x)
3413 background_width -= x - right_x;
3414 x += background_width;
3416 width = min (FRAME_COLUMN_WIDTH (s->f), background_width);
3417 if (s->row->reversed_p)
3418 x -= width;
3420 /* Draw cursor. */
3421 x_draw_glyph_string_bg_rect (s, x, s->y, width, s->height);
3423 /* Clear rest using the GC of the original non-cursor face. */
3424 if (width < background_width)
3426 int y = s->y;
3427 int w = background_width - width, h = s->height;
3428 XRectangle r;
3429 GC gc;
3431 if (!s->row->reversed_p)
3432 x += width;
3433 else
3434 x = s->x;
3435 if (s->row->mouse_face_p
3436 && cursor_in_mouse_face_p (s->w))
3438 x_set_mouse_face_gc (s);
3439 gc = s->gc;
3441 else
3442 gc = s->face->gc;
3444 get_glyph_string_clip_rect (s, &r);
3445 x_set_clip_rectangles (s->f, gc, &r, 1);
3447 if (s->face->stipple)
3449 /* Fill background with a stipple pattern. */
3450 XSetFillStyle (s->display, gc, FillOpaqueStippled);
3451 x_fill_rectangle (s->f, gc, x, y, w, h);
3452 XSetFillStyle (s->display, gc, FillSolid);
3454 else
3456 XGCValues xgcv;
3457 XGetGCValues (s->display, gc, GCForeground | GCBackground, &xgcv);
3458 XSetForeground (s->display, gc, xgcv.background);
3459 x_fill_rectangle (s->f, gc, x, y, w, h);
3460 XSetForeground (s->display, gc, xgcv.foreground);
3463 x_reset_clip_rectangles (s->f, gc);
3466 else if (!s->background_filled_p)
3468 int background_width = s->background_width;
3469 int x = s->x, left_x = window_box_left_offset (s->w, TEXT_AREA);
3471 /* Don't draw into left margin, fringe or scrollbar area
3472 except for header line and mode line. */
3473 if (x < left_x && !s->row->mode_line_p)
3475 background_width -= left_x - x;
3476 x = left_x;
3478 if (background_width > 0)
3479 x_draw_glyph_string_bg_rect (s, x, s->y, background_width, s->height);
3482 s->background_filled_p = true;
3485 static void
3486 x_get_scale_factor(Display *disp, int *scale_x, int *scale_y)
3488 const int base_res = 96;
3489 struct x_display_info * dpyinfo = x_display_info_for_display (disp);
3491 *scale_x = *scale_y = 1;
3493 if (dpyinfo)
3495 if (dpyinfo->resx > base_res)
3496 *scale_x = floor (dpyinfo->resx / base_res);
3497 if (dpyinfo->resy > base_res)
3498 *scale_y = floor (dpyinfo->resy / base_res);
3503 Draw a wavy line under S. The wave fills wave_height pixels from y0.
3505 x0 wave_length = 2
3507 y0 * * * * *
3508 |* * * * * * * * *
3509 wave_height = 3 | * * * *
3512 static void
3513 x_draw_underwave (struct glyph_string *s)
3515 /* Adjust for scale/HiDPI. */
3516 int scale_x, scale_y;
3518 x_get_scale_factor (s->display, &scale_x, &scale_y);
3520 int wave_height = 3 * scale_y, wave_length = 2 * scale_x;
3522 #ifdef USE_CAIRO
3523 x_draw_horizontal_wave (s->f, s->gc, s->x, s->ybase - wave_height + 3,
3524 s->width, wave_height, wave_length);
3525 #else /* not USE_CAIRO */
3526 int dx, dy, x0, y0, width, x1, y1, x2, y2, xmax, thickness = scale_y;;
3527 bool odd;
3528 XRectangle wave_clip, string_clip, final_clip;
3530 dx = wave_length;
3531 dy = wave_height - 1;
3532 x0 = s->x;
3533 y0 = s->ybase + wave_height / 2 - scale_y;
3534 width = s->width;
3535 xmax = x0 + width;
3537 /* Find and set clipping rectangle */
3539 wave_clip.x = x0;
3540 wave_clip.y = y0;
3541 wave_clip.width = width;
3542 wave_clip.height = wave_height;
3543 get_glyph_string_clip_rect (s, &string_clip);
3545 if (!x_intersect_rectangles (&wave_clip, &string_clip, &final_clip))
3546 return;
3548 XSetClipRectangles (s->display, s->gc, 0, 0, &final_clip, 1, Unsorted);
3550 /* Draw the waves */
3552 x1 = x0 - (x0 % dx);
3553 x2 = x1 + dx;
3554 odd = (x1 / dx) & 1;
3555 y1 = y2 = y0;
3557 if (odd)
3558 y1 += dy;
3559 else
3560 y2 += dy;
3562 if (INT_MAX - dx < xmax)
3563 emacs_abort ();
3565 while (x1 <= xmax)
3567 XSetLineAttributes (s->display, s->gc, thickness, LineSolid, CapButt,
3568 JoinRound);
3569 XDrawLine (s->display, FRAME_X_DRAWABLE (s->f), s->gc, x1, y1, x2, y2);
3570 x1 = x2, y1 = y2;
3571 x2 += dx, y2 = y0 + odd*dy;
3572 odd = !odd;
3575 /* Restore previous clipping rectangle(s) */
3576 XSetClipRectangles (s->display, s->gc, 0, 0, s->clip, s->num_clips, Unsorted);
3577 #endif /* not USE_CAIRO */
3581 /* Draw glyph string S. */
3583 static void
3584 x_draw_glyph_string (struct glyph_string *s)
3586 bool relief_drawn_p = false;
3588 /* If S draws into the background of its successors, draw the
3589 background of the successors first so that S can draw into it.
3590 This makes S->next use XDrawString instead of XDrawImageString. */
3591 if (s->next && s->right_overhang && !s->for_overlaps)
3593 int width;
3594 struct glyph_string *next;
3596 for (width = 0, next = s->next;
3597 next && width < s->right_overhang;
3598 width += next->width, next = next->next)
3599 if (next->first_glyph->type != IMAGE_GLYPH)
3601 x_set_glyph_string_gc (next);
3602 x_set_glyph_string_clipping (next);
3603 if (next->first_glyph->type == STRETCH_GLYPH)
3604 x_draw_stretch_glyph_string (next);
3605 else
3606 x_draw_glyph_string_background (next, true);
3607 next->num_clips = 0;
3611 /* Set up S->gc, set clipping and draw S. */
3612 x_set_glyph_string_gc (s);
3614 /* Draw relief (if any) in advance for char/composition so that the
3615 glyph string can be drawn over it. */
3616 if (!s->for_overlaps
3617 && s->face->box != FACE_NO_BOX
3618 && (s->first_glyph->type == CHAR_GLYPH
3619 || s->first_glyph->type == COMPOSITE_GLYPH))
3622 x_set_glyph_string_clipping (s);
3623 x_draw_glyph_string_background (s, true);
3624 x_draw_glyph_string_box (s);
3625 x_set_glyph_string_clipping (s);
3626 relief_drawn_p = true;
3628 else if (!s->clip_head /* draw_glyphs didn't specify a clip mask. */
3629 && !s->clip_tail
3630 && ((s->prev && s->prev->hl != s->hl && s->left_overhang)
3631 || (s->next && s->next->hl != s->hl && s->right_overhang)))
3632 /* We must clip just this glyph. left_overhang part has already
3633 drawn when s->prev was drawn, and right_overhang part will be
3634 drawn later when s->next is drawn. */
3635 x_set_glyph_string_clipping_exactly (s, s);
3636 else
3637 x_set_glyph_string_clipping (s);
3639 switch (s->first_glyph->type)
3641 case IMAGE_GLYPH:
3642 x_draw_image_glyph_string (s);
3643 break;
3645 case XWIDGET_GLYPH:
3646 x_draw_xwidget_glyph_string (s);
3647 break;
3649 case STRETCH_GLYPH:
3650 x_draw_stretch_glyph_string (s);
3651 break;
3653 case CHAR_GLYPH:
3654 if (s->for_overlaps)
3655 s->background_filled_p = true;
3656 else
3657 x_draw_glyph_string_background (s, false);
3658 x_draw_glyph_string_foreground (s);
3659 break;
3661 case COMPOSITE_GLYPH:
3662 if (s->for_overlaps || (s->cmp_from > 0
3663 && ! s->first_glyph->u.cmp.automatic))
3664 s->background_filled_p = true;
3665 else
3666 x_draw_glyph_string_background (s, true);
3667 x_draw_composite_glyph_string_foreground (s);
3668 break;
3670 case GLYPHLESS_GLYPH:
3671 if (s->for_overlaps)
3672 s->background_filled_p = true;
3673 else
3674 x_draw_glyph_string_background (s, true);
3675 x_draw_glyphless_glyph_string_foreground (s);
3676 break;
3678 default:
3679 emacs_abort ();
3682 if (!s->for_overlaps)
3684 /* Draw underline. */
3685 if (s->face->underline_p)
3687 if (s->face->underline_type == FACE_UNDER_WAVE)
3689 if (s->face->underline_defaulted_p)
3690 x_draw_underwave (s);
3691 else
3693 XGCValues xgcv;
3694 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3695 XSetForeground (s->display, s->gc, s->face->underline_color);
3696 x_draw_underwave (s);
3697 XSetForeground (s->display, s->gc, xgcv.foreground);
3700 else if (s->face->underline_type == FACE_UNDER_LINE)
3702 unsigned long thickness, position;
3703 int y;
3705 if (s->prev && s->prev->face->underline_p
3706 && s->prev->face->underline_type == FACE_UNDER_LINE)
3708 /* We use the same underline style as the previous one. */
3709 thickness = s->prev->underline_thickness;
3710 position = s->prev->underline_position;
3712 else
3714 struct font *font = font_for_underline_metrics (s);
3716 /* Get the underline thickness. Default is 1 pixel. */
3717 if (font && font->underline_thickness > 0)
3718 thickness = font->underline_thickness;
3719 else
3720 thickness = 1;
3721 if (x_underline_at_descent_line)
3722 position = (s->height - thickness) - (s->ybase - s->y);
3723 else
3725 /* Get the underline position. This is the recommended
3726 vertical offset in pixels from the baseline to the top of
3727 the underline. This is a signed value according to the
3728 specs, and its default is
3730 ROUND ((maximum descent) / 2), with
3731 ROUND(x) = floor (x + 0.5) */
3733 if (x_use_underline_position_properties
3734 && font && font->underline_position >= 0)
3735 position = font->underline_position;
3736 else if (font)
3737 position = (font->descent + 1) / 2;
3738 else
3739 position = underline_minimum_offset;
3741 position = max (position, underline_minimum_offset);
3743 /* Check the sanity of thickness and position. We should
3744 avoid drawing underline out of the current line area. */
3745 if (s->y + s->height <= s->ybase + position)
3746 position = (s->height - 1) - (s->ybase - s->y);
3747 if (s->y + s->height < s->ybase + position + thickness)
3748 thickness = (s->y + s->height) - (s->ybase + position);
3749 s->underline_thickness = thickness;
3750 s->underline_position = position;
3751 y = s->ybase + position;
3752 if (s->face->underline_defaulted_p)
3753 x_fill_rectangle (s->f, s->gc,
3754 s->x, y, s->width, thickness);
3755 else
3757 XGCValues xgcv;
3758 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3759 XSetForeground (s->display, s->gc, s->face->underline_color);
3760 x_fill_rectangle (s->f, s->gc,
3761 s->x, y, s->width, thickness);
3762 XSetForeground (s->display, s->gc, xgcv.foreground);
3766 /* Draw overline. */
3767 if (s->face->overline_p)
3769 unsigned long dy = 0, h = 1;
3771 if (s->face->overline_color_defaulted_p)
3772 x_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3773 s->width, h);
3774 else
3776 XGCValues xgcv;
3777 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3778 XSetForeground (s->display, s->gc, s->face->overline_color);
3779 x_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3780 s->width, h);
3781 XSetForeground (s->display, s->gc, xgcv.foreground);
3785 /* Draw strike-through. */
3786 if (s->face->strike_through_p)
3788 /* Y-coordinate and height of the glyph string's first
3789 glyph. We cannot use s->y and s->height because those
3790 could be larger if there are taller display elements
3791 (e.g., characters displayed with a larger font) in the
3792 same glyph row. */
3793 int glyph_y = s->ybase - s->first_glyph->ascent;
3794 int glyph_height = s->first_glyph->ascent + s->first_glyph->descent;
3795 /* Strike-through width and offset from the glyph string's
3796 top edge. */
3797 unsigned long h = 1;
3798 unsigned long dy = (glyph_height - h) / 2;
3800 if (s->face->strike_through_color_defaulted_p)
3801 x_fill_rectangle (s->f, s->gc, s->x, glyph_y + dy,
3802 s->width, h);
3803 else
3805 XGCValues xgcv;
3806 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3807 XSetForeground (s->display, s->gc, s->face->strike_through_color);
3808 x_fill_rectangle (s->f, s->gc, s->x, glyph_y + dy,
3809 s->width, h);
3810 XSetForeground (s->display, s->gc, xgcv.foreground);
3814 /* Draw relief if not yet drawn. */
3815 if (!relief_drawn_p && s->face->box != FACE_NO_BOX)
3816 x_draw_glyph_string_box (s);
3818 if (s->prev)
3820 struct glyph_string *prev;
3822 for (prev = s->prev; prev; prev = prev->prev)
3823 if (prev->hl != s->hl
3824 && prev->x + prev->width + prev->right_overhang > s->x)
3826 /* As prev was drawn while clipped to its own area, we
3827 must draw the right_overhang part using s->hl now. */
3828 enum draw_glyphs_face save = prev->hl;
3830 prev->hl = s->hl;
3831 x_set_glyph_string_gc (prev);
3832 x_set_glyph_string_clipping_exactly (s, prev);
3833 if (prev->first_glyph->type == CHAR_GLYPH)
3834 x_draw_glyph_string_foreground (prev);
3835 else
3836 x_draw_composite_glyph_string_foreground (prev);
3837 x_reset_clip_rectangles (prev->f, prev->gc);
3838 prev->hl = save;
3839 prev->num_clips = 0;
3843 if (s->next)
3845 struct glyph_string *next;
3847 for (next = s->next; next; next = next->next)
3848 if (next->hl != s->hl
3849 && next->x - next->left_overhang < s->x + s->width)
3851 /* As next will be drawn while clipped to its own area,
3852 we must draw the left_overhang part using s->hl now. */
3853 enum draw_glyphs_face save = next->hl;
3855 next->hl = s->hl;
3856 x_set_glyph_string_gc (next);
3857 x_set_glyph_string_clipping_exactly (s, next);
3858 if (next->first_glyph->type == CHAR_GLYPH)
3859 x_draw_glyph_string_foreground (next);
3860 else
3861 x_draw_composite_glyph_string_foreground (next);
3862 x_reset_clip_rectangles (next->f, next->gc);
3863 next->hl = save;
3864 next->num_clips = 0;
3865 next->clip_head = s->next;
3870 /* Reset clipping. */
3871 x_reset_clip_rectangles (s->f, s->gc);
3872 s->num_clips = 0;
3875 /* Shift display to make room for inserted glyphs. */
3877 static void
3878 x_shift_glyphs_for_insert (struct frame *f, int x, int y, int width, int height, int shift_by)
3880 /* Never called on a GUI frame, see
3881 https://lists.gnu.org/r/emacs-devel/2015-05/msg00456.html
3883 XCopyArea (FRAME_X_DISPLAY (f), FRAME_X_DRAWABLE (f), FRAME_X_DRAWABLE (f),
3884 f->output_data.x->normal_gc,
3885 x, y, width, height,
3886 x + shift_by, y);
3889 /* Delete N glyphs at the nominal cursor position. Not implemented
3890 for X frames. */
3892 static void
3893 x_delete_glyphs (struct frame *f, register int n)
3895 emacs_abort ();
3899 /* Like XClearArea, but check that WIDTH and HEIGHT are reasonable.
3900 If they are <= 0, this is probably an error. */
3902 static ATTRIBUTE_UNUSED void
3903 x_clear_area1 (Display *dpy, Window window,
3904 int x, int y, int width, int height, int exposures)
3906 eassert (width > 0 && height > 0);
3907 XClearArea (dpy, window, x, y, width, height, exposures);
3910 void
3911 x_clear_area (struct frame *f, int x, int y, int width, int height)
3913 #ifdef USE_CAIRO
3914 cairo_t *cr;
3916 eassert (width > 0 && height > 0);
3918 cr = x_begin_cr_clip (f, NULL);
3919 x_set_cr_source_with_gc_background (f, f->output_data.x->normal_gc);
3920 cairo_rectangle (cr, x, y, width, height);
3921 cairo_fill (cr);
3922 x_end_cr_clip (f);
3923 #else
3924 if (FRAME_X_DOUBLE_BUFFERED_P (f))
3925 XFillRectangle (FRAME_X_DISPLAY (f),
3926 FRAME_X_DRAWABLE (f),
3927 f->output_data.x->reverse_gc,
3928 x, y, width, height);
3929 else
3930 x_clear_area1 (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3931 x, y, width, height, False);
3932 #endif
3936 /* Clear an entire frame. */
3938 static void
3939 x_clear_frame (struct frame *f)
3941 /* Clearing the frame will erase any cursor, so mark them all as no
3942 longer visible. */
3943 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
3945 block_input ();
3947 font_drop_xrender_surfaces (f);
3948 x_clear_window (f);
3950 /* We have to clear the scroll bars. If we have changed colors or
3951 something like that, then they should be notified. */
3952 x_scroll_bar_clear (f);
3954 XFlush (FRAME_X_DISPLAY (f));
3956 unblock_input ();
3959 /* RIF: Show hourglass cursor on frame F. */
3961 static void
3962 x_show_hourglass (struct frame *f)
3964 Display *dpy = FRAME_X_DISPLAY (f);
3966 if (dpy)
3968 struct x_output *x = FRAME_X_OUTPUT (f);
3969 #ifdef USE_X_TOOLKIT
3970 if (x->widget)
3971 #else
3972 if (FRAME_OUTER_WINDOW (f))
3973 #endif
3975 x->hourglass_p = true;
3977 if (!x->hourglass_window)
3979 unsigned long mask = CWCursor;
3980 XSetWindowAttributes attrs;
3981 #ifdef USE_GTK
3982 Window parent = FRAME_X_WINDOW (f);
3983 #else
3984 Window parent = FRAME_OUTER_WINDOW (f);
3985 #endif
3986 attrs.cursor = x->hourglass_cursor;
3988 x->hourglass_window = XCreateWindow
3989 (dpy, parent, 0, 0, 32000, 32000, 0, 0,
3990 InputOnly, CopyFromParent, mask, &attrs);
3993 XMapRaised (dpy, x->hourglass_window);
3994 XFlush (dpy);
3999 /* RIF: Cancel hourglass cursor on frame F. */
4001 static void
4002 x_hide_hourglass (struct frame *f)
4004 struct x_output *x = FRAME_X_OUTPUT (f);
4006 /* Watch out for newly created frames. */
4007 if (x->hourglass_window)
4009 XUnmapWindow (FRAME_X_DISPLAY (f), x->hourglass_window);
4010 /* Sync here because XTread_socket looks at the
4011 hourglass_p flag that is reset to zero below. */
4012 XSync (FRAME_X_DISPLAY (f), False);
4013 x->hourglass_p = false;
4017 /* Invert the middle quarter of the frame for .15 sec. */
4019 static void
4020 XTflash (struct frame *f)
4022 block_input ();
4025 #ifdef USE_GTK
4026 /* Use Gdk routines to draw. This way, we won't draw over scroll bars
4027 when the scroll bars and the edit widget share the same X window. */
4028 GdkWindow *window = gtk_widget_get_window (FRAME_GTK_WIDGET (f));
4029 #ifdef HAVE_GTK3
4030 #if GTK_CHECK_VERSION (3, 22, 0)
4031 cairo_region_t *region = gdk_window_get_visible_region (window);
4032 GdkDrawingContext *context = gdk_window_begin_draw_frame (window, region);
4033 cairo_t *cr = gdk_drawing_context_get_cairo_context (context);
4034 #else
4035 cairo_t *cr = gdk_cairo_create (window);
4036 #endif
4037 cairo_set_source_rgb (cr, 1, 1, 1);
4038 cairo_set_operator (cr, CAIRO_OPERATOR_DIFFERENCE);
4039 #define XFillRectangle(d, win, gc, x, y, w, h) \
4040 do { \
4041 cairo_rectangle (cr, x, y, w, h); \
4042 cairo_fill (cr); \
4044 while (false)
4045 #else /* ! HAVE_GTK3 */
4046 GdkGCValues vals;
4047 GdkGC *gc;
4048 vals.foreground.pixel = (FRAME_FOREGROUND_PIXEL (f)
4049 ^ FRAME_BACKGROUND_PIXEL (f));
4050 vals.function = GDK_XOR;
4051 gc = gdk_gc_new_with_values (window,
4052 &vals, GDK_GC_FUNCTION | GDK_GC_FOREGROUND);
4053 #define XFillRectangle(d, win, gc, x, y, w, h) \
4054 gdk_draw_rectangle (window, gc, true, x, y, w, h)
4055 #endif /* ! HAVE_GTK3 */
4056 #else /* ! USE_GTK */
4057 GC gc;
4059 /* Create a GC that will use the GXxor function to flip foreground
4060 pixels into background pixels. */
4062 XGCValues values;
4064 values.function = GXxor;
4065 values.foreground = (FRAME_FOREGROUND_PIXEL (f)
4066 ^ FRAME_BACKGROUND_PIXEL (f));
4068 gc = XCreateGC (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4069 GCFunction | GCForeground, &values);
4071 #endif
4073 /* Get the height not including a menu bar widget. */
4074 int height = FRAME_PIXEL_HEIGHT (f);
4075 /* Height of each line to flash. */
4076 int flash_height = FRAME_LINE_HEIGHT (f);
4077 /* These will be the left and right margins of the rectangles. */
4078 int flash_left = FRAME_INTERNAL_BORDER_WIDTH (f);
4079 int flash_right = FRAME_PIXEL_WIDTH (f) - FRAME_INTERNAL_BORDER_WIDTH (f);
4080 int width = flash_right - flash_left;
4082 /* If window is tall, flash top and bottom line. */
4083 if (height > 3 * FRAME_LINE_HEIGHT (f))
4085 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4086 flash_left,
4087 (FRAME_INTERNAL_BORDER_WIDTH (f)
4088 + FRAME_TOP_MARGIN_HEIGHT (f)),
4089 width, flash_height);
4090 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4091 flash_left,
4092 (height - flash_height
4093 - FRAME_INTERNAL_BORDER_WIDTH (f)),
4094 width, flash_height);
4097 else
4098 /* If it is short, flash it all. */
4099 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4100 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
4101 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
4103 x_flush (f);
4106 struct timespec delay = make_timespec (0, 150 * 1000 * 1000);
4107 struct timespec wakeup = timespec_add (current_timespec (), delay);
4109 /* Keep waiting until past the time wakeup or any input gets
4110 available. */
4111 while (! detect_input_pending ())
4113 struct timespec current = current_timespec ();
4114 struct timespec timeout;
4116 /* Break if result would not be positive. */
4117 if (timespec_cmp (wakeup, current) <= 0)
4118 break;
4120 /* How long `select' should wait. */
4121 timeout = make_timespec (0, 10 * 1000 * 1000);
4123 /* Try to wait that long--but we might wake up sooner. */
4124 pselect (0, NULL, NULL, NULL, &timeout, NULL);
4128 /* If window is tall, flash top and bottom line. */
4129 if (height > 3 * FRAME_LINE_HEIGHT (f))
4131 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4132 flash_left,
4133 (FRAME_INTERNAL_BORDER_WIDTH (f)
4134 + FRAME_TOP_MARGIN_HEIGHT (f)),
4135 width, flash_height);
4136 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4137 flash_left,
4138 (height - flash_height
4139 - FRAME_INTERNAL_BORDER_WIDTH (f)),
4140 width, flash_height);
4142 else
4143 /* If it is short, flash it all. */
4144 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4145 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
4146 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
4148 #ifdef USE_GTK
4149 #ifdef HAVE_GTK3
4150 #if GTK_CHECK_VERSION (3, 22, 0)
4151 gdk_window_end_draw_frame (window, context);
4152 cairo_region_destroy (region);
4153 #else
4154 cairo_destroy (cr);
4155 #endif
4156 #else
4157 g_object_unref (G_OBJECT (gc));
4158 #endif
4159 #undef XFillRectangle
4160 #else
4161 XFreeGC (FRAME_X_DISPLAY (f), gc);
4162 #endif
4163 x_flush (f);
4167 unblock_input ();
4171 static void
4172 XTtoggle_invisible_pointer (struct frame *f, bool invisible)
4174 block_input ();
4175 FRAME_DISPLAY_INFO (f)->toggle_visible_pointer (f, invisible);
4176 unblock_input ();
4180 /* Make audible bell. */
4182 static void
4183 XTring_bell (struct frame *f)
4185 if (FRAME_X_DISPLAY (f))
4187 if (visible_bell)
4188 XTflash (f);
4189 else
4191 block_input ();
4192 #ifdef HAVE_XKB
4193 XkbBell (FRAME_X_DISPLAY (f), None, 0, None);
4194 #else
4195 XBell (FRAME_X_DISPLAY (f), 0);
4196 #endif
4197 XFlush (FRAME_X_DISPLAY (f));
4198 unblock_input ();
4203 /***********************************************************************
4204 Line Dance
4205 ***********************************************************************/
4207 /* Perform an insert-lines or delete-lines operation, inserting N
4208 lines or deleting -N lines at vertical position VPOS. */
4210 static void
4211 x_ins_del_lines (struct frame *f, int vpos, int n)
4213 emacs_abort ();
4217 /* Scroll part of the display as described by RUN. */
4219 static void
4220 x_scroll_run (struct window *w, struct run *run)
4222 struct frame *f = XFRAME (w->frame);
4223 int x, y, width, height, from_y, to_y, bottom_y;
4225 /* Get frame-relative bounding box of the text display area of W,
4226 without mode lines. Include in this box the left and right
4227 fringe of W. */
4228 window_box (w, ANY_AREA, &x, &y, &width, &height);
4230 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
4231 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
4232 bottom_y = y + height;
4234 if (to_y < from_y)
4236 /* Scrolling up. Make sure we don't copy part of the mode
4237 line at the bottom. */
4238 if (from_y + run->height > bottom_y)
4239 height = bottom_y - from_y;
4240 else
4241 height = run->height;
4243 else
4245 /* Scrolling down. Make sure we don't copy over the mode line.
4246 at the bottom. */
4247 if (to_y + run->height > bottom_y)
4248 height = bottom_y - to_y;
4249 else
4250 height = run->height;
4253 block_input ();
4255 /* Cursor off. Will be switched on again in x_update_window_end. */
4256 x_clear_cursor (w);
4258 #ifdef USE_CAIRO
4259 SET_FRAME_GARBAGED (f);
4260 #else
4261 XCopyArea (FRAME_X_DISPLAY (f),
4262 FRAME_X_DRAWABLE (f), FRAME_X_DRAWABLE (f),
4263 f->output_data.x->normal_gc,
4264 x, from_y,
4265 width, height,
4266 x, to_y);
4267 #endif
4269 unblock_input ();
4274 /***********************************************************************
4275 Exposure Events
4276 ***********************************************************************/
4279 static void
4280 frame_highlight (struct frame *f)
4282 /* We used to only do this if Vx_no_window_manager was non-nil, but
4283 the ICCCM (section 4.1.6) says that the window's border pixmap
4284 and border pixel are window attributes which are "private to the
4285 client", so we can always change it to whatever we want. */
4286 block_input ();
4287 /* I recently started to get errors in this XSetWindowBorder, depending on
4288 the window-manager in use, tho something more is at play since I've been
4289 using that same window-manager binary for ever. Let's not crash just
4290 because of this (bug#9310). */
4291 x_catch_errors (FRAME_X_DISPLAY (f));
4292 XSetWindowBorder (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4293 f->output_data.x->border_pixel);
4294 x_uncatch_errors ();
4295 unblock_input ();
4296 x_update_cursor (f, true);
4297 x_set_frame_alpha (f);
4300 static void
4301 frame_unhighlight (struct frame *f)
4303 /* We used to only do this if Vx_no_window_manager was non-nil, but
4304 the ICCCM (section 4.1.6) says that the window's border pixmap
4305 and border pixel are window attributes which are "private to the
4306 client", so we can always change it to whatever we want. */
4307 block_input ();
4308 /* Same as above for XSetWindowBorder (bug#9310). */
4309 x_catch_errors (FRAME_X_DISPLAY (f));
4310 XSetWindowBorderPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4311 f->output_data.x->border_tile);
4312 x_uncatch_errors ();
4313 unblock_input ();
4314 x_update_cursor (f, true);
4315 x_set_frame_alpha (f);
4318 /* The focus has changed. Update the frames as necessary to reflect
4319 the new situation. Note that we can't change the selected frame
4320 here, because the Lisp code we are interrupting might become confused.
4321 Each event gets marked with the frame in which it occurred, so the
4322 Lisp code can tell when the switch took place by examining the events. */
4324 static void
4325 x_new_focus_frame (struct x_display_info *dpyinfo, struct frame *frame)
4327 struct frame *old_focus = dpyinfo->x_focus_frame;
4329 if (frame != dpyinfo->x_focus_frame)
4331 /* Set this before calling other routines, so that they see
4332 the correct value of x_focus_frame. */
4333 dpyinfo->x_focus_frame = frame;
4335 if (old_focus && old_focus->auto_lower)
4336 x_lower_frame (old_focus);
4338 if (dpyinfo->x_focus_frame && dpyinfo->x_focus_frame->auto_raise)
4339 dpyinfo->x_pending_autoraise_frame = dpyinfo->x_focus_frame;
4340 else
4341 dpyinfo->x_pending_autoraise_frame = NULL;
4344 x_frame_rehighlight (dpyinfo);
4347 /* Handle FocusIn and FocusOut state changes for FRAME.
4348 If FRAME has focus and there exists more than one frame, puts
4349 a FOCUS_IN_EVENT into *BUFP. */
4351 static void
4352 x_focus_changed (int type, int state, struct x_display_info *dpyinfo, struct frame *frame, struct input_event *bufp)
4354 if (type == FocusIn)
4356 if (dpyinfo->x_focus_event_frame != frame)
4358 x_new_focus_frame (dpyinfo, frame);
4359 dpyinfo->x_focus_event_frame = frame;
4361 /* Don't stop displaying the initial startup message
4362 for a switch-frame event we don't need. */
4363 /* When run as a daemon, Vterminal_frame is always NIL. */
4364 bufp->arg = (((NILP (Vterminal_frame)
4365 || ! FRAME_X_P (XFRAME (Vterminal_frame))
4366 || EQ (Fdaemonp (), Qt))
4367 && CONSP (Vframe_list)
4368 && !NILP (XCDR (Vframe_list)))
4369 ? Qt : Qnil);
4370 bufp->kind = FOCUS_IN_EVENT;
4371 XSETFRAME (bufp->frame_or_window, frame);
4374 frame->output_data.x->focus_state |= state;
4376 #ifdef HAVE_X_I18N
4377 if (FRAME_XIC (frame))
4378 XSetICFocus (FRAME_XIC (frame));
4379 #endif
4381 else if (type == FocusOut)
4383 frame->output_data.x->focus_state &= ~state;
4385 if (dpyinfo->x_focus_event_frame == frame)
4387 dpyinfo->x_focus_event_frame = 0;
4388 x_new_focus_frame (dpyinfo, 0);
4390 bufp->kind = FOCUS_OUT_EVENT;
4391 XSETFRAME (bufp->frame_or_window, frame);
4394 #ifdef HAVE_X_I18N
4395 if (FRAME_XIC (frame))
4396 XUnsetICFocus (FRAME_XIC (frame));
4397 #endif
4398 if (frame->pointer_invisible)
4399 XTtoggle_invisible_pointer (frame, false);
4403 /* Return the Emacs frame-object corresponding to an X window.
4404 It could be the frame's main window or an icon window. */
4406 static struct frame *
4407 x_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
4409 Lisp_Object tail, frame;
4410 struct frame *f;
4412 if (wdesc == None)
4413 return NULL;
4415 FOR_EACH_FRAME (tail, frame)
4417 f = XFRAME (frame);
4418 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
4419 continue;
4420 if (f->output_data.x->hourglass_window == wdesc)
4421 return f;
4422 #ifdef USE_X_TOOLKIT
4423 if ((f->output_data.x->edit_widget
4424 && XtWindow (f->output_data.x->edit_widget) == wdesc)
4425 /* A tooltip frame? */
4426 || (!f->output_data.x->edit_widget
4427 && FRAME_X_WINDOW (f) == wdesc)
4428 || f->output_data.x->icon_desc == wdesc)
4429 return f;
4430 #else /* not USE_X_TOOLKIT */
4431 #ifdef USE_GTK
4432 if (f->output_data.x->edit_widget)
4434 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
4435 struct x_output *x = f->output_data.x;
4436 if (gwdesc != 0 && gwdesc == x->edit_widget)
4437 return f;
4439 #endif /* USE_GTK */
4440 if (FRAME_X_WINDOW (f) == wdesc
4441 || f->output_data.x->icon_desc == wdesc)
4442 return f;
4443 #endif /* not USE_X_TOOLKIT */
4445 return 0;
4448 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
4450 /* Like x_window_to_frame but also compares the window with the widget's
4451 windows. */
4453 static struct frame *
4454 x_any_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
4456 Lisp_Object tail, frame;
4457 struct frame *f, *found = NULL;
4458 struct x_output *x;
4460 if (wdesc == None)
4461 return NULL;
4463 FOR_EACH_FRAME (tail, frame)
4465 if (found)
4466 break;
4467 f = XFRAME (frame);
4468 if (FRAME_X_P (f) && FRAME_DISPLAY_INFO (f) == dpyinfo)
4470 /* This frame matches if the window is any of its widgets. */
4471 x = f->output_data.x;
4472 if (x->hourglass_window == wdesc)
4473 found = f;
4474 else if (x->widget)
4476 #ifdef USE_GTK
4477 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
4478 if (gwdesc != 0
4479 && gtk_widget_get_toplevel (gwdesc) == x->widget)
4480 found = f;
4481 #else
4482 if (wdesc == XtWindow (x->widget)
4483 || wdesc == XtWindow (x->column_widget)
4484 || wdesc == XtWindow (x->edit_widget))
4485 found = f;
4486 /* Match if the window is this frame's menubar. */
4487 else if (lw_window_is_in_menubar (wdesc, x->menubar_widget))
4488 found = f;
4489 #endif
4491 else if (FRAME_X_WINDOW (f) == wdesc)
4492 /* A tooltip frame. */
4493 found = f;
4497 return found;
4500 /* Likewise, but consider only the menu bar widget. */
4502 static struct frame *
4503 x_menubar_window_to_frame (struct x_display_info *dpyinfo,
4504 const XEvent *event)
4506 Window wdesc = event->xany.window;
4507 Lisp_Object tail, frame;
4508 struct frame *f;
4509 struct x_output *x;
4511 if (wdesc == None)
4512 return NULL;
4514 FOR_EACH_FRAME (tail, frame)
4516 f = XFRAME (frame);
4517 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
4518 continue;
4519 x = f->output_data.x;
4520 #ifdef USE_GTK
4521 if (x->menubar_widget && xg_event_is_for_menubar (f, event))
4522 return f;
4523 #else
4524 /* Match if the window is this frame's menubar. */
4525 if (x->menubar_widget
4526 && lw_window_is_in_menubar (wdesc, x->menubar_widget))
4527 return f;
4528 #endif
4530 return 0;
4533 /* Return the frame whose principal (outermost) window is WDESC.
4534 If WDESC is some other (smaller) window, we return 0. */
4536 struct frame *
4537 x_top_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
4539 Lisp_Object tail, frame;
4540 struct frame *f;
4541 struct x_output *x;
4543 if (wdesc == None)
4544 return NULL;
4546 FOR_EACH_FRAME (tail, frame)
4548 f = XFRAME (frame);
4549 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
4550 continue;
4551 x = f->output_data.x;
4553 if (x->widget)
4555 /* This frame matches if the window is its topmost widget. */
4556 #ifdef USE_GTK
4557 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
4558 if (gwdesc == x->widget)
4559 return f;
4560 #else
4561 if (wdesc == XtWindow (x->widget))
4562 return f;
4563 #endif
4565 else if (FRAME_X_WINDOW (f) == wdesc)
4566 /* Tooltip frame. */
4567 return f;
4569 return 0;
4572 #else /* !USE_X_TOOLKIT && !USE_GTK */
4574 #define x_any_window_to_frame(d, i) x_window_to_frame (d, i)
4575 #define x_top_window_to_frame(d, i) x_window_to_frame (d, i)
4577 #endif /* USE_X_TOOLKIT || USE_GTK */
4579 /* The focus may have changed. Figure out if it is a real focus change,
4580 by checking both FocusIn/Out and Enter/LeaveNotify events.
4582 Returns FOCUS_IN_EVENT event in *BUFP. */
4584 static void
4585 x_detect_focus_change (struct x_display_info *dpyinfo, struct frame *frame,
4586 const XEvent *event, struct input_event *bufp)
4588 if (!frame)
4589 return;
4591 switch (event->type)
4593 case EnterNotify:
4594 case LeaveNotify:
4596 struct frame *focus_frame = dpyinfo->x_focus_event_frame;
4597 int focus_state
4598 = focus_frame ? focus_frame->output_data.x->focus_state : 0;
4600 if (event->xcrossing.detail != NotifyInferior
4601 && event->xcrossing.focus
4602 && ! (focus_state & FOCUS_EXPLICIT))
4603 x_focus_changed ((event->type == EnterNotify ? FocusIn : FocusOut),
4604 FOCUS_IMPLICIT,
4605 dpyinfo, frame, bufp);
4607 break;
4609 case FocusIn:
4610 case FocusOut:
4611 x_focus_changed (event->type,
4612 (event->xfocus.detail == NotifyPointer ?
4613 FOCUS_IMPLICIT : FOCUS_EXPLICIT),
4614 dpyinfo, frame, bufp);
4615 break;
4617 case ClientMessage:
4618 if (event->xclient.message_type == dpyinfo->Xatom_XEMBED)
4620 enum xembed_message msg = event->xclient.data.l[1];
4621 x_focus_changed ((msg == XEMBED_FOCUS_IN ? FocusIn : FocusOut),
4622 FOCUS_EXPLICIT, dpyinfo, frame, bufp);
4624 break;
4629 #if !defined USE_X_TOOLKIT && !defined USE_GTK
4630 /* Handle an event saying the mouse has moved out of an Emacs frame. */
4632 void
4633 x_mouse_leave (struct x_display_info *dpyinfo)
4635 x_new_focus_frame (dpyinfo, dpyinfo->x_focus_event_frame);
4637 #endif
4639 /* The focus has changed, or we have redirected a frame's focus to
4640 another frame (this happens when a frame uses a surrogate
4641 mini-buffer frame). Shift the highlight as appropriate.
4643 The FRAME argument doesn't necessarily have anything to do with which
4644 frame is being highlighted or un-highlighted; we only use it to find
4645 the appropriate X display info. */
4647 static void
4648 XTframe_rehighlight (struct frame *frame)
4650 x_frame_rehighlight (FRAME_DISPLAY_INFO (frame));
4653 static void
4654 x_frame_rehighlight (struct x_display_info *dpyinfo)
4656 struct frame *old_highlight = dpyinfo->x_highlight_frame;
4658 if (dpyinfo->x_focus_frame)
4660 dpyinfo->x_highlight_frame
4661 = ((FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame)))
4662 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
4663 : dpyinfo->x_focus_frame);
4664 if (! FRAME_LIVE_P (dpyinfo->x_highlight_frame))
4666 fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
4667 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
4670 else
4671 dpyinfo->x_highlight_frame = 0;
4673 if (dpyinfo->x_highlight_frame != old_highlight)
4675 if (old_highlight)
4676 frame_unhighlight (old_highlight);
4677 if (dpyinfo->x_highlight_frame)
4678 frame_highlight (dpyinfo->x_highlight_frame);
4684 /* Keyboard processing - modifier keys, vendor-specific keysyms, etc. */
4686 /* Initialize mode_switch_bit and modifier_meaning. */
4687 static void
4688 x_find_modifier_meanings (struct x_display_info *dpyinfo)
4690 int min_code, max_code;
4691 KeySym *syms;
4692 int syms_per_code;
4693 XModifierKeymap *mods;
4695 dpyinfo->meta_mod_mask = 0;
4696 dpyinfo->shift_lock_mask = 0;
4697 dpyinfo->alt_mod_mask = 0;
4698 dpyinfo->super_mod_mask = 0;
4699 dpyinfo->hyper_mod_mask = 0;
4701 XDisplayKeycodes (dpyinfo->display, &min_code, &max_code);
4703 syms = XGetKeyboardMapping (dpyinfo->display,
4704 min_code, max_code - min_code + 1,
4705 &syms_per_code);
4706 mods = XGetModifierMapping (dpyinfo->display);
4708 /* Scan the modifier table to see which modifier bits the Meta and
4709 Alt keysyms are on. */
4711 int row, col; /* The row and column in the modifier table. */
4712 bool found_alt_or_meta;
4714 for (row = 3; row < 8; row++)
4716 found_alt_or_meta = false;
4717 for (col = 0; col < mods->max_keypermod; col++)
4719 KeyCode code = mods->modifiermap[(row * mods->max_keypermod) + col];
4721 /* Zeroes are used for filler. Skip them. */
4722 if (code == 0)
4723 continue;
4725 /* Are any of this keycode's keysyms a meta key? */
4727 int code_col;
4729 for (code_col = 0; code_col < syms_per_code; code_col++)
4731 int sym = syms[((code - min_code) * syms_per_code) + code_col];
4733 switch (sym)
4735 case XK_Meta_L:
4736 case XK_Meta_R:
4737 found_alt_or_meta = true;
4738 dpyinfo->meta_mod_mask |= (1 << row);
4739 break;
4741 case XK_Alt_L:
4742 case XK_Alt_R:
4743 found_alt_or_meta = true;
4744 dpyinfo->alt_mod_mask |= (1 << row);
4745 break;
4747 case XK_Hyper_L:
4748 case XK_Hyper_R:
4749 if (!found_alt_or_meta)
4750 dpyinfo->hyper_mod_mask |= (1 << row);
4751 code_col = syms_per_code;
4752 col = mods->max_keypermod;
4753 break;
4755 case XK_Super_L:
4756 case XK_Super_R:
4757 if (!found_alt_or_meta)
4758 dpyinfo->super_mod_mask |= (1 << row);
4759 code_col = syms_per_code;
4760 col = mods->max_keypermod;
4761 break;
4763 case XK_Shift_Lock:
4764 /* Ignore this if it's not on the lock modifier. */
4765 if (!found_alt_or_meta && ((1 << row) == LockMask))
4766 dpyinfo->shift_lock_mask = LockMask;
4767 code_col = syms_per_code;
4768 col = mods->max_keypermod;
4769 break;
4777 /* If we couldn't find any meta keys, accept any alt keys as meta keys. */
4778 if (! dpyinfo->meta_mod_mask)
4780 dpyinfo->meta_mod_mask = dpyinfo->alt_mod_mask;
4781 dpyinfo->alt_mod_mask = 0;
4784 /* If some keys are both alt and meta,
4785 make them just meta, not alt. */
4786 if (dpyinfo->alt_mod_mask & dpyinfo->meta_mod_mask)
4788 dpyinfo->alt_mod_mask &= ~dpyinfo->meta_mod_mask;
4791 XFree (syms);
4792 XFreeModifiermap (mods);
4795 /* Convert between the modifier bits X uses and the modifier bits
4796 Emacs uses. */
4799 x_x_to_emacs_modifiers (struct x_display_info *dpyinfo, int state)
4801 int mod_ctrl = ctrl_modifier;
4802 int mod_meta = meta_modifier;
4803 int mod_alt = alt_modifier;
4804 int mod_hyper = hyper_modifier;
4805 int mod_super = super_modifier;
4806 Lisp_Object tem;
4808 tem = Fget (Vx_ctrl_keysym, Qmodifier_value);
4809 if (INTEGERP (tem)) mod_ctrl = XINT (tem) & INT_MAX;
4810 tem = Fget (Vx_alt_keysym, Qmodifier_value);
4811 if (INTEGERP (tem)) mod_alt = XINT (tem) & INT_MAX;
4812 tem = Fget (Vx_meta_keysym, Qmodifier_value);
4813 if (INTEGERP (tem)) mod_meta = XINT (tem) & INT_MAX;
4814 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
4815 if (INTEGERP (tem)) mod_hyper = XINT (tem) & INT_MAX;
4816 tem = Fget (Vx_super_keysym, Qmodifier_value);
4817 if (INTEGERP (tem)) mod_super = XINT (tem) & INT_MAX;
4819 return ( ((state & (ShiftMask | dpyinfo->shift_lock_mask)) ? shift_modifier : 0)
4820 | ((state & ControlMask) ? mod_ctrl : 0)
4821 | ((state & dpyinfo->meta_mod_mask) ? mod_meta : 0)
4822 | ((state & dpyinfo->alt_mod_mask) ? mod_alt : 0)
4823 | ((state & dpyinfo->super_mod_mask) ? mod_super : 0)
4824 | ((state & dpyinfo->hyper_mod_mask) ? mod_hyper : 0));
4827 static int
4828 x_emacs_to_x_modifiers (struct x_display_info *dpyinfo, EMACS_INT state)
4830 EMACS_INT mod_ctrl = ctrl_modifier;
4831 EMACS_INT mod_meta = meta_modifier;
4832 EMACS_INT mod_alt = alt_modifier;
4833 EMACS_INT mod_hyper = hyper_modifier;
4834 EMACS_INT mod_super = super_modifier;
4836 Lisp_Object tem;
4838 tem = Fget (Vx_ctrl_keysym, Qmodifier_value);
4839 if (INTEGERP (tem)) mod_ctrl = XINT (tem);
4840 tem = Fget (Vx_alt_keysym, Qmodifier_value);
4841 if (INTEGERP (tem)) mod_alt = XINT (tem);
4842 tem = Fget (Vx_meta_keysym, Qmodifier_value);
4843 if (INTEGERP (tem)) mod_meta = XINT (tem);
4844 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
4845 if (INTEGERP (tem)) mod_hyper = XINT (tem);
4846 tem = Fget (Vx_super_keysym, Qmodifier_value);
4847 if (INTEGERP (tem)) mod_super = XINT (tem);
4850 return ( ((state & mod_alt) ? dpyinfo->alt_mod_mask : 0)
4851 | ((state & mod_super) ? dpyinfo->super_mod_mask : 0)
4852 | ((state & mod_hyper) ? dpyinfo->hyper_mod_mask : 0)
4853 | ((state & shift_modifier) ? ShiftMask : 0)
4854 | ((state & mod_ctrl) ? ControlMask : 0)
4855 | ((state & mod_meta) ? dpyinfo->meta_mod_mask : 0));
4858 /* Convert a keysym to its name. */
4860 char *
4861 x_get_keysym_name (int keysym)
4863 char *value;
4865 block_input ();
4866 value = XKeysymToString (keysym);
4867 unblock_input ();
4869 return value;
4872 /* Mouse clicks and mouse movement. Rah.
4874 Formerly, we used PointerMotionHintMask (in standard_event_mask)
4875 so that we would have to call XQueryPointer after each MotionNotify
4876 event to ask for another such event. However, this made mouse tracking
4877 slow, and there was a bug that made it eventually stop.
4879 Simply asking for MotionNotify all the time seems to work better.
4881 In order to avoid asking for motion events and then throwing most
4882 of them away or busy-polling the server for mouse positions, we ask
4883 the server for pointer motion hints. This means that we get only
4884 one event per group of mouse movements. "Groups" are delimited by
4885 other kinds of events (focus changes and button clicks, for
4886 example), or by XQueryPointer calls; when one of these happens, we
4887 get another MotionNotify event the next time the mouse moves. This
4888 is at least as efficient as getting motion events when mouse
4889 tracking is on, and I suspect only negligibly worse when tracking
4890 is off. */
4892 /* Prepare a mouse-event in *RESULT for placement in the input queue.
4894 If the event is a button press, then note that we have grabbed
4895 the mouse. */
4897 static Lisp_Object
4898 construct_mouse_click (struct input_event *result,
4899 const XButtonEvent *event,
4900 struct frame *f)
4902 /* Make the event type NO_EVENT; we'll change that when we decide
4903 otherwise. */
4904 result->kind = MOUSE_CLICK_EVENT;
4905 result->code = event->button - Button1;
4906 result->timestamp = event->time;
4907 result->modifiers = (x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO (f),
4908 event->state)
4909 | (event->type == ButtonRelease
4910 ? up_modifier
4911 : down_modifier));
4913 XSETINT (result->x, event->x);
4914 XSETINT (result->y, event->y);
4915 XSETFRAME (result->frame_or_window, f);
4916 result->arg = Qnil;
4917 return Qnil;
4920 /* Function to report a mouse movement to the mainstream Emacs code.
4921 The input handler calls this.
4923 We have received a mouse movement event, which is given in *event.
4924 If the mouse is over a different glyph than it was last time, tell
4925 the mainstream emacs code by setting mouse_moved. If not, ask for
4926 another motion event, so we can check again the next time it moves. */
4928 static bool
4929 note_mouse_movement (struct frame *frame, const XMotionEvent *event)
4931 XRectangle *r;
4932 struct x_display_info *dpyinfo;
4934 if (!FRAME_X_OUTPUT (frame))
4935 return false;
4937 dpyinfo = FRAME_DISPLAY_INFO (frame);
4938 dpyinfo->last_mouse_movement_time = event->time;
4939 dpyinfo->last_mouse_motion_frame = frame;
4940 dpyinfo->last_mouse_motion_x = event->x;
4941 dpyinfo->last_mouse_motion_y = event->y;
4943 if (event->window != FRAME_X_WINDOW (frame))
4945 frame->mouse_moved = true;
4946 dpyinfo->last_mouse_scroll_bar = NULL;
4947 note_mouse_highlight (frame, -1, -1);
4948 dpyinfo->last_mouse_glyph_frame = NULL;
4949 return true;
4953 /* Has the mouse moved off the glyph it was on at the last sighting? */
4954 r = &dpyinfo->last_mouse_glyph;
4955 if (frame != dpyinfo->last_mouse_glyph_frame
4956 || event->x < r->x || event->x >= r->x + r->width
4957 || event->y < r->y || event->y >= r->y + r->height)
4959 frame->mouse_moved = true;
4960 dpyinfo->last_mouse_scroll_bar = NULL;
4961 note_mouse_highlight (frame, event->x, event->y);
4962 /* Remember which glyph we're now on. */
4963 remember_mouse_glyph (frame, event->x, event->y, r);
4964 dpyinfo->last_mouse_glyph_frame = frame;
4965 return true;
4968 return false;
4971 /* Return the current position of the mouse.
4972 *FP should be a frame which indicates which display to ask about.
4974 If the mouse movement started in a scroll bar, set *FP, *BAR_WINDOW,
4975 and *PART to the frame, window, and scroll bar part that the mouse
4976 is over. Set *X and *Y to the portion and whole of the mouse's
4977 position on the scroll bar.
4979 If the mouse movement started elsewhere, set *FP to the frame the
4980 mouse is on, *BAR_WINDOW to nil, and *X and *Y to the character cell
4981 the mouse is over.
4983 Set *TIMESTAMP to the server time-stamp for the time at which the mouse
4984 was at this position.
4986 Don't store anything if we don't have a valid set of values to report.
4988 This clears the mouse_moved flag, so we can wait for the next mouse
4989 movement. */
4991 static void
4992 XTmouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
4993 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
4994 Time *timestamp)
4996 struct frame *f1;
4997 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (*fp);
4999 block_input ();
5001 if (dpyinfo->last_mouse_scroll_bar && insist == 0)
5003 struct scroll_bar *bar = dpyinfo->last_mouse_scroll_bar;
5005 if (bar->horizontal)
5006 x_horizontal_scroll_bar_report_motion (fp, bar_window, part, x, y, timestamp);
5007 else
5008 x_scroll_bar_report_motion (fp, bar_window, part, x, y, timestamp);
5010 else
5012 Window root;
5013 int root_x, root_y;
5015 Window dummy_window;
5016 int dummy;
5018 Lisp_Object frame, tail;
5020 /* Clear the mouse-moved flag for every frame on this display. */
5021 FOR_EACH_FRAME (tail, frame)
5022 if (FRAME_X_P (XFRAME (frame))
5023 && FRAME_X_DISPLAY (XFRAME (frame)) == FRAME_X_DISPLAY (*fp))
5024 XFRAME (frame)->mouse_moved = false;
5026 dpyinfo->last_mouse_scroll_bar = NULL;
5028 /* Figure out which root window we're on. */
5029 XQueryPointer (FRAME_X_DISPLAY (*fp),
5030 DefaultRootWindow (FRAME_X_DISPLAY (*fp)),
5032 /* The root window which contains the pointer. */
5033 &root,
5035 /* Trash which we can't trust if the pointer is on
5036 a different screen. */
5037 &dummy_window,
5039 /* The position on that root window. */
5040 &root_x, &root_y,
5042 /* More trash we can't trust. */
5043 &dummy, &dummy,
5045 /* Modifier keys and pointer buttons, about which
5046 we don't care. */
5047 (unsigned int *) &dummy);
5049 /* Now we have a position on the root; find the innermost window
5050 containing the pointer. */
5052 Window win, child;
5053 #ifdef USE_GTK
5054 Window first_win = 0;
5055 #endif
5056 int win_x, win_y;
5057 int parent_x = 0, parent_y = 0;
5059 win = root;
5061 /* XTranslateCoordinates can get errors if the window
5062 structure is changing at the same time this function
5063 is running. So at least we must not crash from them. */
5065 x_catch_errors (FRAME_X_DISPLAY (*fp));
5067 if (x_mouse_grabbed (dpyinfo))
5069 /* If mouse was grabbed on a frame, give coords for that frame
5070 even if the mouse is now outside it. */
5071 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
5073 /* From-window. */
5074 root,
5076 /* To-window. */
5077 FRAME_X_WINDOW (dpyinfo->last_mouse_frame),
5079 /* From-position, to-position. */
5080 root_x, root_y, &win_x, &win_y,
5082 /* Child of win. */
5083 &child);
5084 f1 = dpyinfo->last_mouse_frame;
5086 else
5088 while (true)
5090 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
5092 /* From-window, to-window. */
5093 root, win,
5095 /* From-position, to-position. */
5096 root_x, root_y, &win_x, &win_y,
5098 /* Child of win. */
5099 &child);
5101 if (child == None || child == win)
5103 #ifdef USE_GTK
5104 /* On GTK we have not inspected WIN yet. If it has
5105 a frame and that frame has a parent, use it. */
5106 struct frame *f = x_window_to_frame (dpyinfo, win);
5108 if (f && FRAME_PARENT_FRAME (f))
5109 first_win = win;
5110 #endif
5111 break;
5113 #ifdef USE_GTK
5114 /* We don't wan't to know the innermost window. We
5115 want the edit window. For non-Gtk+ the innermost
5116 window is the edit window. For Gtk+ it might not
5117 be. It might be the tool bar for example. */
5118 if (x_window_to_frame (dpyinfo, win))
5119 /* But don't hurry. We might find a child frame
5120 beneath. */
5121 first_win = win;
5122 #endif
5123 win = child;
5124 parent_x = win_x;
5125 parent_y = win_y;
5128 #ifdef USE_GTK
5129 if (first_win)
5130 win = first_win;
5131 #endif
5133 /* Now we know that:
5134 win is the innermost window containing the pointer
5135 (XTC says it has no child containing the pointer),
5136 win_x and win_y are the pointer's position in it
5137 (XTC did this the last time through), and
5138 parent_x and parent_y are the pointer's position in win's parent.
5139 (They are what win_x and win_y were when win was child.
5140 If win is the root window, it has no parent, and
5141 parent_{x,y} are invalid, but that's okay, because we'll
5142 never use them in that case.) */
5144 #ifdef USE_GTK
5145 /* We don't wan't to know the innermost window. We
5146 want the edit window. */
5147 f1 = x_window_to_frame (dpyinfo, win);
5148 #else
5149 /* Is win one of our frames? */
5150 f1 = x_any_window_to_frame (dpyinfo, win);
5151 #endif
5153 #ifdef USE_X_TOOLKIT
5154 /* If we end up with the menu bar window, say it's not
5155 on the frame. */
5156 if (f1 != NULL
5157 && f1->output_data.x->menubar_widget
5158 && win == XtWindow (f1->output_data.x->menubar_widget))
5159 f1 = NULL;
5160 #endif /* USE_X_TOOLKIT */
5163 if (x_had_errors_p (FRAME_X_DISPLAY (*fp)))
5164 f1 = 0;
5166 x_uncatch_errors_after_check ();
5168 /* If not, is it one of our scroll bars? */
5169 if (! f1)
5171 struct scroll_bar *bar;
5173 bar = x_window_to_scroll_bar (FRAME_X_DISPLAY (*fp), win, 2);
5175 if (bar)
5177 f1 = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5178 win_x = parent_x;
5179 win_y = parent_y;
5183 if (f1 == 0 && insist > 0)
5184 f1 = SELECTED_FRAME ();
5186 if (f1)
5188 /* Ok, we found a frame. Store all the values.
5189 last_mouse_glyph is a rectangle used to reduce the
5190 generation of mouse events. To not miss any motion
5191 events, we must divide the frame into rectangles of the
5192 size of the smallest character that could be displayed
5193 on it, i.e. into the same rectangles that matrices on
5194 the frame are divided into. */
5196 /* FIXME: what if F1 is not an X frame? */
5197 dpyinfo = FRAME_DISPLAY_INFO (f1);
5198 remember_mouse_glyph (f1, win_x, win_y, &dpyinfo->last_mouse_glyph);
5199 dpyinfo->last_mouse_glyph_frame = f1;
5201 *bar_window = Qnil;
5202 *part = 0;
5203 *fp = f1;
5204 XSETINT (*x, win_x);
5205 XSETINT (*y, win_y);
5206 *timestamp = dpyinfo->last_mouse_movement_time;
5211 unblock_input ();
5216 /***********************************************************************
5217 Scroll bars
5218 ***********************************************************************/
5220 /* Scroll bar support. */
5222 /* Given an X window ID and a DISPLAY, find the struct scroll_bar which
5223 manages it.
5224 This can be called in GC, so we have to make sure to strip off mark
5225 bits. */
5227 static struct scroll_bar *
5228 x_window_to_scroll_bar (Display *display, Window window_id, int type)
5230 Lisp_Object tail, frame;
5232 #if defined (USE_GTK) && defined (USE_TOOLKIT_SCROLL_BARS)
5233 window_id = (Window) xg_get_scroll_id_for_window (display, window_id);
5234 #endif /* USE_GTK && USE_TOOLKIT_SCROLL_BARS */
5236 FOR_EACH_FRAME (tail, frame)
5238 Lisp_Object bar, condemned;
5240 if (! FRAME_X_P (XFRAME (frame)))
5241 continue;
5243 /* Scan this frame's scroll bar list for a scroll bar with the
5244 right window ID. */
5245 condemned = FRAME_CONDEMNED_SCROLL_BARS (XFRAME (frame));
5246 for (bar = FRAME_SCROLL_BARS (XFRAME (frame));
5247 /* This trick allows us to search both the ordinary and
5248 condemned scroll bar lists with one loop. */
5249 ! NILP (bar) || (bar = condemned,
5250 condemned = Qnil,
5251 ! NILP (bar));
5252 bar = XSCROLL_BAR (bar)->next)
5253 if (XSCROLL_BAR (bar)->x_window == window_id
5254 && FRAME_X_DISPLAY (XFRAME (frame)) == display
5255 && (type = 2
5256 || (type == 1 && XSCROLL_BAR (bar)->horizontal)
5257 || (type == 0 && !XSCROLL_BAR (bar)->horizontal)))
5258 return XSCROLL_BAR (bar);
5261 return NULL;
5265 #if defined USE_LUCID
5267 /* Return the Lucid menu bar WINDOW is part of. Return null
5268 if WINDOW is not part of a menu bar. */
5270 static Widget
5271 x_window_to_menu_bar (Window window)
5273 Lisp_Object tail, frame;
5275 FOR_EACH_FRAME (tail, frame)
5276 if (FRAME_X_P (XFRAME (frame)))
5278 Widget menu_bar = XFRAME (frame)->output_data.x->menubar_widget;
5280 if (menu_bar && xlwmenu_window_p (menu_bar, window))
5281 return menu_bar;
5283 return NULL;
5286 #endif /* USE_LUCID */
5289 /************************************************************************
5290 Toolkit scroll bars
5291 ************************************************************************/
5293 #ifdef USE_TOOLKIT_SCROLL_BARS
5295 static void x_send_scroll_bar_event (Lisp_Object, enum scroll_bar_part,
5296 int, int, bool);
5298 /* Lisp window being scrolled. Set when starting to interact with
5299 a toolkit scroll bar, reset to nil when ending the interaction. */
5301 static Lisp_Object window_being_scrolled;
5303 /* Whether this is an Xaw with arrow-scrollbars. This should imply
5304 that movements of 1/20 of the screen size are mapped to up/down. */
5306 #ifndef USE_GTK
5307 /* Id of action hook installed for scroll bars. */
5309 static XtActionHookId action_hook_id;
5310 static XtActionHookId horizontal_action_hook_id;
5312 static Boolean xaw3d_arrow_scroll;
5314 /* Whether the drag scrolling maintains the mouse at the top of the
5315 thumb. If not, resizing the thumb needs to be done more carefully
5316 to avoid jerkiness. */
5318 static Boolean xaw3d_pick_top;
5320 /* Action hook installed via XtAppAddActionHook when toolkit scroll
5321 bars are used.. The hook is responsible for detecting when
5322 the user ends an interaction with the scroll bar, and generates
5323 a `end-scroll' SCROLL_BAR_CLICK_EVENT' event if so. */
5325 static void
5326 xt_action_hook (Widget widget, XtPointer client_data, String action_name,
5327 XEvent *event, String *params, Cardinal *num_params)
5329 bool scroll_bar_p;
5330 const char *end_action;
5332 #ifdef USE_MOTIF
5333 scroll_bar_p = XmIsScrollBar (widget);
5334 end_action = "Release";
5335 #else /* !USE_MOTIF i.e. use Xaw */
5336 scroll_bar_p = XtIsSubclass (widget, scrollbarWidgetClass);
5337 end_action = "EndScroll";
5338 #endif /* USE_MOTIF */
5340 if (scroll_bar_p
5341 && strcmp (action_name, end_action) == 0
5342 && WINDOWP (window_being_scrolled))
5344 struct window *w;
5345 struct scroll_bar *bar;
5347 x_send_scroll_bar_event (window_being_scrolled,
5348 scroll_bar_end_scroll, 0, 0, false);
5349 w = XWINDOW (window_being_scrolled);
5350 bar = XSCROLL_BAR (w->vertical_scroll_bar);
5352 if (bar->dragging != -1)
5354 bar->dragging = -1;
5355 /* The thumb size is incorrect while dragging: fix it. */
5356 set_vertical_scroll_bar (w);
5358 window_being_scrolled = Qnil;
5359 #if defined (USE_LUCID)
5360 bar->last_seen_part = scroll_bar_nowhere;
5361 #endif
5362 /* Xt timeouts no longer needed. */
5363 toolkit_scroll_bar_interaction = false;
5368 static void
5369 xt_horizontal_action_hook (Widget widget, XtPointer client_data, String action_name,
5370 XEvent *event, String *params, Cardinal *num_params)
5372 bool scroll_bar_p;
5373 const char *end_action;
5375 #ifdef USE_MOTIF
5376 scroll_bar_p = XmIsScrollBar (widget);
5377 end_action = "Release";
5378 #else /* !USE_MOTIF i.e. use Xaw */
5379 scroll_bar_p = XtIsSubclass (widget, scrollbarWidgetClass);
5380 end_action = "EndScroll";
5381 #endif /* USE_MOTIF */
5383 if (scroll_bar_p
5384 && strcmp (action_name, end_action) == 0
5385 && WINDOWP (window_being_scrolled))
5387 struct window *w;
5388 struct scroll_bar *bar;
5390 x_send_scroll_bar_event (window_being_scrolled,
5391 scroll_bar_end_scroll, 0, 0, true);
5392 w = XWINDOW (window_being_scrolled);
5393 if (!NILP (w->horizontal_scroll_bar))
5395 bar = XSCROLL_BAR (w->horizontal_scroll_bar);
5396 if (bar->dragging != -1)
5398 bar->dragging = -1;
5399 /* The thumb size is incorrect while dragging: fix it. */
5400 set_horizontal_scroll_bar (w);
5402 window_being_scrolled = Qnil;
5403 #if defined (USE_LUCID)
5404 bar->last_seen_part = scroll_bar_nowhere;
5405 #endif
5406 /* Xt timeouts no longer needed. */
5407 toolkit_scroll_bar_interaction = false;
5411 #endif /* not USE_GTK */
5413 /* Send a client message with message type Xatom_Scrollbar for a
5414 scroll action to the frame of WINDOW. PART is a value identifying
5415 the part of the scroll bar that was clicked on. PORTION is the
5416 amount to scroll of a whole of WHOLE. */
5418 static void
5419 x_send_scroll_bar_event (Lisp_Object window, enum scroll_bar_part part,
5420 int portion, int whole, bool horizontal)
5422 XEvent event;
5423 XClientMessageEvent *ev = &event.xclient;
5424 struct window *w = XWINDOW (window);
5425 struct frame *f = XFRAME (w->frame);
5426 intptr_t iw = (intptr_t) w;
5427 verify (INTPTR_WIDTH <= 64);
5428 int sign_shift = INTPTR_WIDTH - 32;
5430 block_input ();
5432 /* Construct a ClientMessage event to send to the frame. */
5433 ev->type = ClientMessage;
5434 ev->message_type = (horizontal
5435 ? FRAME_DISPLAY_INFO (f)->Xatom_Horizontal_Scrollbar
5436 : FRAME_DISPLAY_INFO (f)->Xatom_Scrollbar);
5437 ev->display = FRAME_X_DISPLAY (f);
5438 ev->window = FRAME_X_WINDOW (f);
5439 ev->format = 32;
5441 /* A 32-bit X client on a 64-bit X server can pass a window pointer
5442 as-is. A 64-bit client on a 32-bit X server is in trouble
5443 because a pointer does not fit and would be truncated while
5444 passing through the server. So use two slots and hope that X12
5445 will resolve such issues someday. */
5446 ev->data.l[0] = iw >> 31 >> 1;
5447 ev->data.l[1] = sign_shift <= 0 ? iw : iw << sign_shift >> sign_shift;
5448 ev->data.l[2] = part;
5449 ev->data.l[3] = portion;
5450 ev->data.l[4] = whole;
5452 /* Make Xt timeouts work while the scroll bar is active. */
5453 #ifdef USE_X_TOOLKIT
5454 toolkit_scroll_bar_interaction = true;
5455 x_activate_timeout_atimer ();
5456 #endif
5458 /* Setting the event mask to zero means that the message will
5459 be sent to the client that created the window, and if that
5460 window no longer exists, no event will be sent. */
5461 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), False, 0, &event);
5462 unblock_input ();
5466 /* Transform a scroll bar ClientMessage EVENT to an Emacs input event
5467 in *IEVENT. */
5469 static void
5470 x_scroll_bar_to_input_event (const XEvent *event,
5471 struct input_event *ievent)
5473 const XClientMessageEvent *ev = &event->xclient;
5474 Lisp_Object window;
5475 struct window *w;
5477 /* See the comment in the function above. */
5478 intptr_t iw0 = ev->data.l[0];
5479 intptr_t iw1 = ev->data.l[1];
5480 intptr_t iw = (iw0 << 31 << 1) + (iw1 & 0xffffffffu);
5481 w = (struct window *) iw;
5483 XSETWINDOW (window, w);
5485 ievent->kind = SCROLL_BAR_CLICK_EVENT;
5486 ievent->frame_or_window = window;
5487 ievent->arg = Qnil;
5488 #ifdef USE_GTK
5489 ievent->timestamp = CurrentTime;
5490 #else
5491 ievent->timestamp =
5492 XtLastTimestampProcessed (FRAME_X_DISPLAY (XFRAME (w->frame)));
5493 #endif
5494 ievent->code = 0;
5495 ievent->part = ev->data.l[2];
5496 ievent->x = make_number (ev->data.l[3]);
5497 ievent->y = make_number (ev->data.l[4]);
5498 ievent->modifiers = 0;
5501 /* Transform a horizontal scroll bar ClientMessage EVENT to an Emacs
5502 input event in *IEVENT. */
5504 static void
5505 x_horizontal_scroll_bar_to_input_event (const XEvent *event,
5506 struct input_event *ievent)
5508 const XClientMessageEvent *ev = &event->xclient;
5509 Lisp_Object window;
5510 struct window *w;
5512 /* See the comment in the function above. */
5513 intptr_t iw0 = ev->data.l[0];
5514 intptr_t iw1 = ev->data.l[1];
5515 intptr_t iw = (iw0 << 31 << 1) + (iw1 & 0xffffffffu);
5516 w = (struct window *) iw;
5518 XSETWINDOW (window, w);
5520 ievent->kind = HORIZONTAL_SCROLL_BAR_CLICK_EVENT;
5521 ievent->frame_or_window = window;
5522 ievent->arg = Qnil;
5523 #ifdef USE_GTK
5524 ievent->timestamp = CurrentTime;
5525 #else
5526 ievent->timestamp =
5527 XtLastTimestampProcessed (FRAME_X_DISPLAY (XFRAME (w->frame)));
5528 #endif
5529 ievent->code = 0;
5530 ievent->part = ev->data.l[2];
5531 ievent->x = make_number (ev->data.l[3]);
5532 ievent->y = make_number (ev->data.l[4]);
5533 ievent->modifiers = 0;
5537 #ifdef USE_MOTIF
5539 /* Minimum and maximum values used for Motif scroll bars. */
5541 #define XM_SB_MAX 10000000
5543 /* Scroll bar callback for Motif scroll bars. WIDGET is the scroll
5544 bar widget. CLIENT_DATA is a pointer to the scroll_bar structure.
5545 CALL_DATA is a pointer to a XmScrollBarCallbackStruct. */
5547 static void
5548 xm_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
5550 struct scroll_bar *bar = client_data;
5551 XmScrollBarCallbackStruct *cs = call_data;
5552 enum scroll_bar_part part = scroll_bar_nowhere;
5553 bool horizontal = bar->horizontal;
5554 int whole = 0, portion = 0;
5556 switch (cs->reason)
5558 case XmCR_DECREMENT:
5559 bar->dragging = -1;
5560 part = horizontal ? scroll_bar_left_arrow : scroll_bar_up_arrow;
5561 break;
5563 case XmCR_INCREMENT:
5564 bar->dragging = -1;
5565 part = horizontal ? scroll_bar_right_arrow : scroll_bar_down_arrow;
5566 break;
5568 case XmCR_PAGE_DECREMENT:
5569 bar->dragging = -1;
5570 part = horizontal ? scroll_bar_before_handle : scroll_bar_above_handle;
5571 break;
5573 case XmCR_PAGE_INCREMENT:
5574 bar->dragging = -1;
5575 part = horizontal ? scroll_bar_after_handle : scroll_bar_below_handle;
5576 break;
5578 case XmCR_TO_TOP:
5579 bar->dragging = -1;
5580 part = horizontal ? scroll_bar_to_leftmost : scroll_bar_to_top;
5581 break;
5583 case XmCR_TO_BOTTOM:
5584 bar->dragging = -1;
5585 part = horizontal ? scroll_bar_to_rightmost : scroll_bar_to_bottom;
5586 break;
5588 case XmCR_DRAG:
5590 int slider_size;
5592 block_input ();
5593 XtVaGetValues (widget, XmNsliderSize, &slider_size, NULL);
5594 unblock_input ();
5596 if (horizontal)
5598 portion = bar->whole * ((float)cs->value / XM_SB_MAX);
5599 whole = bar->whole * ((float)(XM_SB_MAX - slider_size) / XM_SB_MAX);
5600 portion = min (portion, whole);
5601 part = scroll_bar_horizontal_handle;
5603 else
5605 whole = XM_SB_MAX - slider_size;
5606 portion = min (cs->value, whole);
5607 part = scroll_bar_handle;
5610 bar->dragging = cs->value;
5612 break;
5614 case XmCR_VALUE_CHANGED:
5615 break;
5618 if (part != scroll_bar_nowhere)
5620 window_being_scrolled = bar->window;
5621 x_send_scroll_bar_event (bar->window, part, portion, whole,
5622 bar->horizontal);
5626 #elif defined USE_GTK
5628 /* Scroll bar callback for GTK scroll bars. WIDGET is the scroll
5629 bar widget. DATA is a pointer to the scroll_bar structure. */
5631 static gboolean
5632 xg_scroll_callback (GtkRange *range,
5633 GtkScrollType scroll,
5634 gdouble value,
5635 gpointer user_data)
5637 int whole = 0, portion = 0;
5638 struct scroll_bar *bar = user_data;
5639 enum scroll_bar_part part = scroll_bar_nowhere;
5640 GtkAdjustment *adj = GTK_ADJUSTMENT (gtk_range_get_adjustment (range));
5641 struct frame *f = g_object_get_data (G_OBJECT (range), XG_FRAME_DATA);
5643 if (xg_ignore_gtk_scrollbar) return false;
5645 switch (scroll)
5647 case GTK_SCROLL_JUMP:
5648 /* Buttons 1 2 or 3 must be grabbed. */
5649 if (FRAME_DISPLAY_INFO (f)->grabbed != 0
5650 && FRAME_DISPLAY_INFO (f)->grabbed < (1 << 4))
5652 if (bar->horizontal)
5654 part = scroll_bar_horizontal_handle;
5655 whole = (int)(gtk_adjustment_get_upper (adj) -
5656 gtk_adjustment_get_page_size (adj));
5657 portion = min ((int)value, whole);
5658 bar->dragging = portion;
5660 else
5662 part = scroll_bar_handle;
5663 whole = gtk_adjustment_get_upper (adj) -
5664 gtk_adjustment_get_page_size (adj);
5665 portion = min ((int)value, whole);
5666 bar->dragging = portion;
5669 break;
5670 case GTK_SCROLL_STEP_BACKWARD:
5671 part = (bar->horizontal
5672 ? scroll_bar_left_arrow : scroll_bar_up_arrow);
5673 bar->dragging = -1;
5674 break;
5675 case GTK_SCROLL_STEP_FORWARD:
5676 part = (bar->horizontal
5677 ? scroll_bar_right_arrow : scroll_bar_down_arrow);
5678 bar->dragging = -1;
5679 break;
5680 case GTK_SCROLL_PAGE_BACKWARD:
5681 part = (bar->horizontal
5682 ? scroll_bar_before_handle : scroll_bar_above_handle);
5683 bar->dragging = -1;
5684 break;
5685 case GTK_SCROLL_PAGE_FORWARD:
5686 part = (bar->horizontal
5687 ? scroll_bar_after_handle : scroll_bar_below_handle);
5688 bar->dragging = -1;
5689 break;
5690 default:
5691 break;
5694 if (part != scroll_bar_nowhere)
5696 window_being_scrolled = bar->window;
5697 x_send_scroll_bar_event (bar->window, part, portion, whole,
5698 bar->horizontal);
5701 return false;
5704 /* Callback for button release. Sets dragging to -1 when dragging is done. */
5706 static gboolean
5707 xg_end_scroll_callback (GtkWidget *widget,
5708 GdkEventButton *event,
5709 gpointer user_data)
5711 struct scroll_bar *bar = user_data;
5712 bar->dragging = -1;
5713 if (WINDOWP (window_being_scrolled))
5715 x_send_scroll_bar_event (window_being_scrolled,
5716 scroll_bar_end_scroll, 0, 0, bar->horizontal);
5717 window_being_scrolled = Qnil;
5720 return false;
5724 #else /* not USE_GTK and not USE_MOTIF */
5726 /* Xaw scroll bar callback. Invoked when the thumb is dragged.
5727 WIDGET is the scroll bar widget. CLIENT_DATA is a pointer to the
5728 scroll bar struct. CALL_DATA is a pointer to a float saying where
5729 the thumb is. */
5731 static void
5732 xaw_jump_callback (Widget widget, XtPointer client_data, XtPointer call_data)
5734 struct scroll_bar *bar = client_data;
5735 float *top_addr = call_data;
5736 float top = *top_addr;
5737 float shown;
5738 int whole, portion, height, width;
5739 enum scroll_bar_part part;
5740 bool horizontal = bar->horizontal;
5742 if (horizontal)
5744 /* Get the size of the thumb, a value between 0 and 1. */
5745 block_input ();
5746 XtVaGetValues (widget, XtNshown, &shown, XtNwidth, &width, NULL);
5747 unblock_input ();
5749 if (shown < 1)
5751 whole = bar->whole - (shown * bar->whole);
5752 portion = min (top * bar->whole, whole);
5754 else
5756 whole = bar->whole;
5757 portion = 0;
5760 part = scroll_bar_horizontal_handle;
5762 else
5764 /* Get the size of the thumb, a value between 0 and 1. */
5765 block_input ();
5766 XtVaGetValues (widget, XtNshown, &shown, XtNheight, &height, NULL);
5767 unblock_input ();
5769 whole = 10000000;
5770 portion = shown < 1 ? top * whole : 0;
5772 if (shown < 1 && (eabs (top + shown - 1) < 1.0f / height))
5773 /* Some derivatives of Xaw refuse to shrink the thumb when you reach
5774 the bottom, so we force the scrolling whenever we see that we're
5775 too close to the bottom (in x_set_toolkit_scroll_bar_thumb
5776 we try to ensure that we always stay two pixels away from the
5777 bottom). */
5778 part = scroll_bar_down_arrow;
5779 else
5780 part = scroll_bar_handle;
5783 window_being_scrolled = bar->window;
5784 bar->dragging = portion;
5785 bar->last_seen_part = part;
5786 x_send_scroll_bar_event (bar->window, part, portion, whole, bar->horizontal);
5790 /* Xaw scroll bar callback. Invoked for incremental scrolling.,
5791 i.e. line or page up or down. WIDGET is the Xaw scroll bar
5792 widget. CLIENT_DATA is a pointer to the scroll_bar structure for
5793 the scroll bar. CALL_DATA is an integer specifying the action that
5794 has taken place. Its magnitude is in the range 0..height of the
5795 scroll bar. Negative values mean scroll towards buffer start.
5796 Values < height of scroll bar mean line-wise movement. */
5798 static void
5799 xaw_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
5801 struct scroll_bar *bar = client_data;
5802 /* The position really is stored cast to a pointer. */
5803 int position = (intptr_t) call_data;
5804 Dimension height, width;
5805 enum scroll_bar_part part;
5807 if (bar->horizontal)
5809 /* Get the width of the scroll bar. */
5810 block_input ();
5811 XtVaGetValues (widget, XtNwidth, &width, NULL);
5812 unblock_input ();
5814 if (eabs (position) >= width)
5815 part = (position < 0) ? scroll_bar_before_handle : scroll_bar_after_handle;
5817 /* If Xaw3d was compiled with ARROW_SCROLLBAR,
5818 it maps line-movement to call_data = max(5, height/20). */
5819 else if (xaw3d_arrow_scroll && eabs (position) <= max (5, width / 20))
5820 part = (position < 0) ? scroll_bar_left_arrow : scroll_bar_right_arrow;
5821 else
5822 part = scroll_bar_move_ratio;
5824 window_being_scrolled = bar->window;
5825 bar->dragging = -1;
5826 bar->last_seen_part = part;
5827 x_send_scroll_bar_event (bar->window, part, position, width,
5828 bar->horizontal);
5830 else
5833 /* Get the height of the scroll bar. */
5834 block_input ();
5835 XtVaGetValues (widget, XtNheight, &height, NULL);
5836 unblock_input ();
5838 if (eabs (position) >= height)
5839 part = (position < 0) ? scroll_bar_above_handle : scroll_bar_below_handle;
5841 /* If Xaw3d was compiled with ARROW_SCROLLBAR,
5842 it maps line-movement to call_data = max(5, height/20). */
5843 else if (xaw3d_arrow_scroll && eabs (position) <= max (5, height / 20))
5844 part = (position < 0) ? scroll_bar_up_arrow : scroll_bar_down_arrow;
5845 else
5846 part = scroll_bar_move_ratio;
5848 window_being_scrolled = bar->window;
5849 bar->dragging = -1;
5850 bar->last_seen_part = part;
5851 x_send_scroll_bar_event (bar->window, part, position, height,
5852 bar->horizontal);
5856 #endif /* not USE_GTK and not USE_MOTIF */
5858 #define SCROLL_BAR_NAME "verticalScrollBar"
5859 #define SCROLL_BAR_HORIZONTAL_NAME "horizontalScrollBar"
5861 /* Create the widget for scroll bar BAR on frame F. Record the widget
5862 and X window of the scroll bar in BAR. */
5864 #ifdef USE_GTK
5865 static void
5866 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
5868 const char *scroll_bar_name = SCROLL_BAR_NAME;
5870 block_input ();
5871 xg_create_scroll_bar (f, bar, G_CALLBACK (xg_scroll_callback),
5872 G_CALLBACK (xg_end_scroll_callback),
5873 scroll_bar_name);
5874 unblock_input ();
5877 static void
5878 x_create_horizontal_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
5880 const char *scroll_bar_name = SCROLL_BAR_HORIZONTAL_NAME;
5882 block_input ();
5883 xg_create_horizontal_scroll_bar (f, bar, G_CALLBACK (xg_scroll_callback),
5884 G_CALLBACK (xg_end_scroll_callback),
5885 scroll_bar_name);
5886 unblock_input ();
5889 #else /* not USE_GTK */
5891 static void
5892 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
5894 Window xwindow;
5895 Widget widget;
5896 Arg av[20];
5897 int ac = 0;
5898 const char *scroll_bar_name = SCROLL_BAR_NAME;
5899 unsigned long pixel;
5901 block_input ();
5903 #ifdef USE_MOTIF
5904 /* Set resources. Create the widget. */
5905 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
5906 XtSetArg (av[ac], XmNminimum, 0); ++ac;
5907 XtSetArg (av[ac], XmNmaximum, XM_SB_MAX); ++ac;
5908 XtSetArg (av[ac], XmNorientation, XmVERTICAL); ++ac;
5909 XtSetArg (av[ac], XmNprocessingDirection, XmMAX_ON_BOTTOM), ++ac;
5910 XtSetArg (av[ac], XmNincrement, 1); ++ac;
5911 XtSetArg (av[ac], XmNpageIncrement, 1); ++ac;
5913 pixel = f->output_data.x->scroll_bar_foreground_pixel;
5914 if (pixel != -1)
5916 XtSetArg (av[ac], XmNforeground, pixel);
5917 ++ac;
5920 pixel = f->output_data.x->scroll_bar_background_pixel;
5921 if (pixel != -1)
5923 XtSetArg (av[ac], XmNbackground, pixel);
5924 ++ac;
5927 widget = XmCreateScrollBar (f->output_data.x->edit_widget,
5928 (char *) scroll_bar_name, av, ac);
5930 /* Add one callback for everything that can happen. */
5931 XtAddCallback (widget, XmNdecrementCallback, xm_scroll_callback,
5932 (XtPointer) bar);
5933 XtAddCallback (widget, XmNdragCallback, xm_scroll_callback,
5934 (XtPointer) bar);
5935 XtAddCallback (widget, XmNincrementCallback, xm_scroll_callback,
5936 (XtPointer) bar);
5937 XtAddCallback (widget, XmNpageDecrementCallback, xm_scroll_callback,
5938 (XtPointer) bar);
5939 XtAddCallback (widget, XmNpageIncrementCallback, xm_scroll_callback,
5940 (XtPointer) bar);
5941 XtAddCallback (widget, XmNtoBottomCallback, xm_scroll_callback,
5942 (XtPointer) bar);
5943 XtAddCallback (widget, XmNtoTopCallback, xm_scroll_callback,
5944 (XtPointer) bar);
5946 /* Realize the widget. Only after that is the X window created. */
5947 XtRealizeWidget (widget);
5949 /* Set the cursor to an arrow. I didn't find a resource to do that.
5950 And I'm wondering why it hasn't an arrow cursor by default. */
5951 XDefineCursor (XtDisplay (widget), XtWindow (widget),
5952 f->output_data.x->nontext_cursor);
5954 #else /* !USE_MOTIF i.e. use Xaw */
5956 /* Set resources. Create the widget. The background of the
5957 Xaw3d scroll bar widget is a little bit light for my taste.
5958 We don't alter it here to let users change it according
5959 to their taste with `emacs*verticalScrollBar.background: xxx'. */
5960 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
5961 XtSetArg (av[ac], XtNorientation, XtorientVertical); ++ac;
5962 /* For smoother scrolling with Xaw3d -sm */
5963 /* XtSetArg (av[ac], XtNpickTop, True); ++ac; */
5965 pixel = f->output_data.x->scroll_bar_foreground_pixel;
5966 if (pixel != -1)
5968 XtSetArg (av[ac], XtNforeground, pixel);
5969 ++ac;
5972 pixel = f->output_data.x->scroll_bar_background_pixel;
5973 if (pixel != -1)
5975 XtSetArg (av[ac], XtNbackground, pixel);
5976 ++ac;
5979 /* Top/bottom shadow colors. */
5981 /* Allocate them, if necessary. */
5982 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1)
5984 pixel = f->output_data.x->scroll_bar_background_pixel;
5985 if (pixel != -1)
5987 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
5988 FRAME_X_COLORMAP (f),
5989 &pixel, 1.2, 0x8000))
5990 pixel = -1;
5991 f->output_data.x->scroll_bar_top_shadow_pixel = pixel;
5994 if (f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
5996 pixel = f->output_data.x->scroll_bar_background_pixel;
5997 if (pixel != -1)
5999 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
6000 FRAME_X_COLORMAP (f),
6001 &pixel, 0.6, 0x4000))
6002 pixel = -1;
6003 f->output_data.x->scroll_bar_bottom_shadow_pixel = pixel;
6007 #ifdef XtNbeNiceToColormap
6008 /* Tell the toolkit about them. */
6009 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1
6010 || f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
6011 /* We tried to allocate a color for the top/bottom shadow, and
6012 failed, so tell Xaw3d to use dithering instead. */
6013 /* But only if we have a small colormap. Xaw3d can allocate nice
6014 colors itself. */
6016 XtSetArg (av[ac], XtNbeNiceToColormap,
6017 DefaultDepthOfScreen (FRAME_X_SCREEN (f)) < 16);
6018 ++ac;
6020 else
6021 /* Tell what colors Xaw3d should use for the top/bottom shadow, to
6022 be more consistent with other emacs 3d colors, and since Xaw3d is
6023 not good at dealing with allocation failure. */
6025 /* This tells Xaw3d to use real colors instead of dithering for
6026 the shadows. */
6027 XtSetArg (av[ac], XtNbeNiceToColormap, False);
6028 ++ac;
6030 /* Specify the colors. */
6031 pixel = f->output_data.x->scroll_bar_top_shadow_pixel;
6032 if (pixel != -1)
6034 XtSetArg (av[ac], XtNtopShadowPixel, pixel);
6035 ++ac;
6037 pixel = f->output_data.x->scroll_bar_bottom_shadow_pixel;
6038 if (pixel != -1)
6040 XtSetArg (av[ac], XtNbottomShadowPixel, pixel);
6041 ++ac;
6044 #endif
6046 widget = XtCreateWidget (scroll_bar_name, scrollbarWidgetClass,
6047 f->output_data.x->edit_widget, av, ac);
6050 char const *initial = "";
6051 char const *val = initial;
6052 XtVaGetValues (widget, XtNscrollVCursor, (XtPointer) &val,
6053 #ifdef XtNarrowScrollbars
6054 XtNarrowScrollbars, (XtPointer) &xaw3d_arrow_scroll,
6055 #endif
6056 XtNpickTop, (XtPointer) &xaw3d_pick_top, NULL);
6057 if (xaw3d_arrow_scroll || val == initial)
6058 { /* ARROW_SCROLL */
6059 xaw3d_arrow_scroll = True;
6060 /* Isn't that just a personal preference ? --Stef */
6061 XtVaSetValues (widget, XtNcursorName, "top_left_arrow", NULL);
6065 /* Define callbacks. */
6066 XtAddCallback (widget, XtNjumpProc, xaw_jump_callback, (XtPointer) bar);
6067 XtAddCallback (widget, XtNscrollProc, xaw_scroll_callback,
6068 (XtPointer) bar);
6070 /* Realize the widget. Only after that is the X window created. */
6071 XtRealizeWidget (widget);
6073 #endif /* !USE_MOTIF */
6075 /* Install an action hook that lets us detect when the user
6076 finishes interacting with a scroll bar. */
6077 if (action_hook_id == 0)
6078 action_hook_id = XtAppAddActionHook (Xt_app_con, xt_action_hook, 0);
6080 /* Remember X window and widget in the scroll bar vector. */
6081 SET_SCROLL_BAR_X_WIDGET (bar, widget);
6082 xwindow = XtWindow (widget);
6083 bar->x_window = xwindow;
6084 bar->whole = 1;
6085 bar->horizontal = false;
6087 unblock_input ();
6090 static void
6091 x_create_horizontal_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
6093 Window xwindow;
6094 Widget widget;
6095 Arg av[20];
6096 int ac = 0;
6097 const char *scroll_bar_name = SCROLL_BAR_HORIZONTAL_NAME;
6098 unsigned long pixel;
6100 block_input ();
6102 #ifdef USE_MOTIF
6103 /* Set resources. Create the widget. */
6104 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
6105 XtSetArg (av[ac], XmNminimum, 0); ++ac;
6106 XtSetArg (av[ac], XmNmaximum, XM_SB_MAX); ++ac;
6107 XtSetArg (av[ac], XmNorientation, XmHORIZONTAL); ++ac;
6108 XtSetArg (av[ac], XmNprocessingDirection, XmMAX_ON_RIGHT), ++ac;
6109 XtSetArg (av[ac], XmNincrement, 1); ++ac;
6110 XtSetArg (av[ac], XmNpageIncrement, 1); ++ac;
6112 pixel = f->output_data.x->scroll_bar_foreground_pixel;
6113 if (pixel != -1)
6115 XtSetArg (av[ac], XmNforeground, pixel);
6116 ++ac;
6119 pixel = f->output_data.x->scroll_bar_background_pixel;
6120 if (pixel != -1)
6122 XtSetArg (av[ac], XmNbackground, pixel);
6123 ++ac;
6126 widget = XmCreateScrollBar (f->output_data.x->edit_widget,
6127 (char *) scroll_bar_name, av, ac);
6129 /* Add one callback for everything that can happen. */
6130 XtAddCallback (widget, XmNdecrementCallback, xm_scroll_callback,
6131 (XtPointer) bar);
6132 XtAddCallback (widget, XmNdragCallback, xm_scroll_callback,
6133 (XtPointer) bar);
6134 XtAddCallback (widget, XmNincrementCallback, xm_scroll_callback,
6135 (XtPointer) bar);
6136 XtAddCallback (widget, XmNpageDecrementCallback, xm_scroll_callback,
6137 (XtPointer) bar);
6138 XtAddCallback (widget, XmNpageIncrementCallback, xm_scroll_callback,
6139 (XtPointer) bar);
6140 XtAddCallback (widget, XmNtoBottomCallback, xm_scroll_callback,
6141 (XtPointer) bar);
6142 XtAddCallback (widget, XmNtoTopCallback, xm_scroll_callback,
6143 (XtPointer) bar);
6145 /* Realize the widget. Only after that is the X window created. */
6146 XtRealizeWidget (widget);
6148 /* Set the cursor to an arrow. I didn't find a resource to do that.
6149 And I'm wondering why it hasn't an arrow cursor by default. */
6150 XDefineCursor (XtDisplay (widget), XtWindow (widget),
6151 f->output_data.x->nontext_cursor);
6153 #else /* !USE_MOTIF i.e. use Xaw */
6155 /* Set resources. Create the widget. The background of the
6156 Xaw3d scroll bar widget is a little bit light for my taste.
6157 We don't alter it here to let users change it according
6158 to their taste with `emacs*verticalScrollBar.background: xxx'. */
6159 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
6160 XtSetArg (av[ac], XtNorientation, XtorientHorizontal); ++ac;
6161 /* For smoother scrolling with Xaw3d -sm */
6162 /* XtSetArg (av[ac], XtNpickTop, True); ++ac; */
6164 pixel = f->output_data.x->scroll_bar_foreground_pixel;
6165 if (pixel != -1)
6167 XtSetArg (av[ac], XtNforeground, pixel);
6168 ++ac;
6171 pixel = f->output_data.x->scroll_bar_background_pixel;
6172 if (pixel != -1)
6174 XtSetArg (av[ac], XtNbackground, pixel);
6175 ++ac;
6178 /* Top/bottom shadow colors. */
6180 /* Allocate them, if necessary. */
6181 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1)
6183 pixel = f->output_data.x->scroll_bar_background_pixel;
6184 if (pixel != -1)
6186 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
6187 FRAME_X_COLORMAP (f),
6188 &pixel, 1.2, 0x8000))
6189 pixel = -1;
6190 f->output_data.x->scroll_bar_top_shadow_pixel = pixel;
6193 if (f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
6195 pixel = f->output_data.x->scroll_bar_background_pixel;
6196 if (pixel != -1)
6198 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
6199 FRAME_X_COLORMAP (f),
6200 &pixel, 0.6, 0x4000))
6201 pixel = -1;
6202 f->output_data.x->scroll_bar_bottom_shadow_pixel = pixel;
6206 #ifdef XtNbeNiceToColormap
6207 /* Tell the toolkit about them. */
6208 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1
6209 || f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
6210 /* We tried to allocate a color for the top/bottom shadow, and
6211 failed, so tell Xaw3d to use dithering instead. */
6212 /* But only if we have a small colormap. Xaw3d can allocate nice
6213 colors itself. */
6215 XtSetArg (av[ac], XtNbeNiceToColormap,
6216 DefaultDepthOfScreen (FRAME_X_SCREEN (f)) < 16);
6217 ++ac;
6219 else
6220 /* Tell what colors Xaw3d should use for the top/bottom shadow, to
6221 be more consistent with other emacs 3d colors, and since Xaw3d is
6222 not good at dealing with allocation failure. */
6224 /* This tells Xaw3d to use real colors instead of dithering for
6225 the shadows. */
6226 XtSetArg (av[ac], XtNbeNiceToColormap, False);
6227 ++ac;
6229 /* Specify the colors. */
6230 pixel = f->output_data.x->scroll_bar_top_shadow_pixel;
6231 if (pixel != -1)
6233 XtSetArg (av[ac], XtNtopShadowPixel, pixel);
6234 ++ac;
6236 pixel = f->output_data.x->scroll_bar_bottom_shadow_pixel;
6237 if (pixel != -1)
6239 XtSetArg (av[ac], XtNbottomShadowPixel, pixel);
6240 ++ac;
6243 #endif
6245 widget = XtCreateWidget (scroll_bar_name, scrollbarWidgetClass,
6246 f->output_data.x->edit_widget, av, ac);
6249 char const *initial = "";
6250 char const *val = initial;
6251 XtVaGetValues (widget, XtNscrollVCursor, (XtPointer) &val,
6252 #ifdef XtNarrowScrollbars
6253 XtNarrowScrollbars, (XtPointer) &xaw3d_arrow_scroll,
6254 #endif
6255 XtNpickTop, (XtPointer) &xaw3d_pick_top, NULL);
6256 if (xaw3d_arrow_scroll || val == initial)
6257 { /* ARROW_SCROLL */
6258 xaw3d_arrow_scroll = True;
6259 /* Isn't that just a personal preference ? --Stef */
6260 XtVaSetValues (widget, XtNcursorName, "top_left_arrow", NULL);
6264 /* Define callbacks. */
6265 XtAddCallback (widget, XtNjumpProc, xaw_jump_callback, (XtPointer) bar);
6266 XtAddCallback (widget, XtNscrollProc, xaw_scroll_callback,
6267 (XtPointer) bar);
6269 /* Realize the widget. Only after that is the X window created. */
6270 XtRealizeWidget (widget);
6272 #endif /* !USE_MOTIF */
6274 /* Install an action hook that lets us detect when the user
6275 finishes interacting with a scroll bar. */
6276 if (horizontal_action_hook_id == 0)
6277 horizontal_action_hook_id
6278 = XtAppAddActionHook (Xt_app_con, xt_horizontal_action_hook, 0);
6280 /* Remember X window and widget in the scroll bar vector. */
6281 SET_SCROLL_BAR_X_WIDGET (bar, widget);
6282 xwindow = XtWindow (widget);
6283 bar->x_window = xwindow;
6284 bar->whole = 1;
6285 bar->horizontal = true;
6287 unblock_input ();
6289 #endif /* not USE_GTK */
6292 /* Set the thumb size and position of scroll bar BAR. We are currently
6293 displaying PORTION out of a whole WHOLE, and our position POSITION. */
6295 #ifdef USE_GTK
6296 static void
6297 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position, int whole)
6299 xg_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
6302 static void
6303 x_set_toolkit_horizontal_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position, int whole)
6305 xg_set_toolkit_horizontal_scroll_bar_thumb (bar, portion, position, whole);
6308 #else /* not USE_GTK */
6309 static void
6310 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position,
6311 int whole)
6313 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6314 Widget widget = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
6315 float top, shown;
6317 block_input ();
6319 #ifdef USE_MOTIF
6321 if (scroll_bar_adjust_thumb_portion_p)
6323 /* We use an estimate of 30 chars per line rather than the real
6324 `portion' value. This has the disadvantage that the thumb size
6325 is not very representative, but it makes our life a lot easier.
6326 Otherwise, we have to constantly adjust the thumb size, which
6327 we can't always do quickly enough: while dragging, the size of
6328 the thumb might prevent the user from dragging the thumb all the
6329 way to the end. but Motif and some versions of Xaw3d don't allow
6330 updating the thumb size while dragging. Also, even if we can update
6331 its size, the update will often happen too late.
6332 If you don't believe it, check out revision 1.650 of xterm.c to see
6333 what hoops we were going through and the still poor behavior we got. */
6334 portion = WINDOW_TOTAL_LINES (XWINDOW (bar->window)) * 30;
6335 /* When the thumb is at the bottom, position == whole.
6336 So we need to increase `whole' to make space for the thumb. */
6337 whole += portion;
6340 if (whole <= 0)
6341 top = 0, shown = 1;
6342 else
6344 top = (float) position / whole;
6345 shown = (float) portion / whole;
6348 if (bar->dragging == -1)
6350 int size, value;
6352 /* Slider size. Must be in the range [1 .. MAX - MIN] where MAX
6353 is the scroll bar's maximum and MIN is the scroll bar's minimum
6354 value. */
6355 size = clip_to_bounds (1, shown * XM_SB_MAX, XM_SB_MAX);
6357 /* Position. Must be in the range [MIN .. MAX - SLIDER_SIZE]. */
6358 value = top * XM_SB_MAX;
6359 value = min (value, XM_SB_MAX - size);
6361 XmScrollBarSetValues (widget, value, size, 0, 0, False);
6363 #else /* !USE_MOTIF i.e. use Xaw */
6365 if (whole == 0)
6366 top = 0, shown = 1;
6367 else
6369 top = (float) position / whole;
6370 shown = (float) portion / whole;
6374 float old_top, old_shown;
6375 Dimension height;
6376 XtVaGetValues (widget,
6377 XtNtopOfThumb, &old_top,
6378 XtNshown, &old_shown,
6379 XtNheight, &height,
6380 NULL);
6382 /* Massage the top+shown values. */
6383 if (bar->dragging == -1 || bar->last_seen_part == scroll_bar_down_arrow)
6384 top = max (0, min (1, top));
6385 else
6386 top = old_top;
6387 #if ! defined (HAVE_XAW3D)
6388 /* With Xaw, 'top' values too closer to 1.0 may
6389 cause the thumb to disappear. Fix that. */
6390 top = min (top, 0.99f);
6391 #endif
6392 /* Keep two pixels available for moving the thumb down. */
6393 shown = max (0, min (1 - top - (2.0f / height), shown));
6394 #if ! defined (HAVE_XAW3D)
6395 /* Likewise with too small 'shown'. */
6396 shown = max (shown, 0.01f);
6397 #endif
6399 /* If the call to XawScrollbarSetThumb below doesn't seem to
6400 work, check that 'NARROWPROTO' is defined in src/config.h.
6401 If this is not so, most likely you need to fix configure. */
6402 if (top != old_top || shown != old_shown)
6404 if (bar->dragging == -1)
6405 XawScrollbarSetThumb (widget, top, shown);
6406 else
6408 /* Try to make the scrolling a tad smoother. */
6409 if (!xaw3d_pick_top)
6410 shown = min (shown, old_shown);
6412 XawScrollbarSetThumb (widget, top, shown);
6416 #endif /* !USE_MOTIF */
6418 unblock_input ();
6421 static void
6422 x_set_toolkit_horizontal_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position,
6423 int whole)
6425 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6426 Widget widget = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
6427 float top, shown;
6429 block_input ();
6431 #ifdef USE_MOTIF
6432 bar->whole = whole;
6433 shown = (float) portion / whole;
6434 top = (float) position / (whole - portion);
6436 int size = clip_to_bounds (1, shown * XM_SB_MAX, XM_SB_MAX);
6437 int value = clip_to_bounds (0, top * (XM_SB_MAX - size), XM_SB_MAX - size);
6439 XmScrollBarSetValues (widget, value, size, 0, 0, False);
6441 #else /* !USE_MOTIF i.e. use Xaw */
6442 bar->whole = whole;
6443 if (whole == 0)
6444 top = 0, shown = 1;
6445 else
6447 top = (float) position / whole;
6448 shown = (float) portion / whole;
6452 float old_top, old_shown;
6453 Dimension height;
6454 XtVaGetValues (widget,
6455 XtNtopOfThumb, &old_top,
6456 XtNshown, &old_shown,
6457 XtNheight, &height,
6458 NULL);
6460 #if false
6461 /* Massage the top+shown values. */
6462 if (bar->dragging == -1 || bar->last_seen_part == scroll_bar_down_arrow)
6463 top = max (0, min (1, top));
6464 else
6465 top = old_top;
6466 #if ! defined (HAVE_XAW3D)
6467 /* With Xaw, 'top' values too closer to 1.0 may
6468 cause the thumb to disappear. Fix that. */
6469 top = min (top, 0.99f);
6470 #endif
6471 /* Keep two pixels available for moving the thumb down. */
6472 shown = max (0, min (1 - top - (2.0f / height), shown));
6473 #if ! defined (HAVE_XAW3D)
6474 /* Likewise with too small 'shown'. */
6475 shown = max (shown, 0.01f);
6476 #endif
6477 #endif
6479 /* If the call to XawScrollbarSetThumb below doesn't seem to
6480 work, check that 'NARROWPROTO' is defined in src/config.h.
6481 If this is not so, most likely you need to fix configure. */
6482 XawScrollbarSetThumb (widget, top, shown);
6483 #if false
6484 if (top != old_top || shown != old_shown)
6486 if (bar->dragging == -1)
6487 XawScrollbarSetThumb (widget, top, shown);
6488 else
6490 /* Try to make the scrolling a tad smoother. */
6491 if (!xaw3d_pick_top)
6492 shown = min (shown, old_shown);
6494 XawScrollbarSetThumb (widget, top, shown);
6497 #endif
6499 #endif /* !USE_MOTIF */
6501 unblock_input ();
6503 #endif /* not USE_GTK */
6505 #endif /* USE_TOOLKIT_SCROLL_BARS */
6509 /************************************************************************
6510 Scroll bars, general
6511 ************************************************************************/
6513 /* Create a scroll bar and return the scroll bar vector for it. W is
6514 the Emacs window on which to create the scroll bar. TOP, LEFT,
6515 WIDTH and HEIGHT are the pixel coordinates and dimensions of the
6516 scroll bar. */
6518 static struct scroll_bar *
6519 x_scroll_bar_create (struct window *w, int top, int left,
6520 int width, int height, bool horizontal)
6522 struct frame *f = XFRAME (w->frame);
6523 struct scroll_bar *bar
6524 = ALLOCATE_PSEUDOVECTOR (struct scroll_bar, x_window, PVEC_OTHER);
6525 Lisp_Object barobj;
6527 block_input ();
6529 #ifdef USE_TOOLKIT_SCROLL_BARS
6530 if (horizontal)
6531 x_create_horizontal_toolkit_scroll_bar (f, bar);
6532 else
6533 x_create_toolkit_scroll_bar (f, bar);
6534 #else /* not USE_TOOLKIT_SCROLL_BARS */
6536 XSetWindowAttributes a;
6537 unsigned long mask;
6538 Window window;
6540 a.background_pixel = f->output_data.x->scroll_bar_background_pixel;
6541 if (a.background_pixel == -1)
6542 a.background_pixel = FRAME_BACKGROUND_PIXEL (f);
6544 a.event_mask = (ButtonPressMask | ButtonReleaseMask
6545 | ButtonMotionMask | PointerMotionHintMask
6546 | ExposureMask);
6547 a.cursor = FRAME_DISPLAY_INFO (f)->vertical_scroll_bar_cursor;
6549 mask = (CWBackPixel | CWEventMask | CWCursor);
6551 /* Clear the area of W that will serve as a scroll bar. This is
6552 for the case that a window has been split horizontally. In
6553 this case, no clear_frame is generated to reduce flickering. */
6554 if (width > 0 && window_box_height (w) > 0)
6555 x_clear_area (f, left, top, width, window_box_height (w));
6557 window = XCreateWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
6558 /* Position and size of scroll bar. */
6559 left, top, width, height,
6560 /* Border width, depth, class, and visual. */
6562 CopyFromParent,
6563 CopyFromParent,
6564 CopyFromParent,
6565 /* Attributes. */
6566 mask, &a);
6567 bar->x_window = window;
6569 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6571 XSETWINDOW (bar->window, w);
6572 bar->top = top;
6573 bar->left = left;
6574 bar->width = width;
6575 bar->height = height;
6576 bar->start = 0;
6577 bar->end = 0;
6578 bar->dragging = -1;
6579 bar->horizontal = horizontal;
6580 #if defined (USE_TOOLKIT_SCROLL_BARS) && defined (USE_LUCID)
6581 bar->last_seen_part = scroll_bar_nowhere;
6582 #endif
6584 /* Add bar to its frame's list of scroll bars. */
6585 bar->next = FRAME_SCROLL_BARS (f);
6586 bar->prev = Qnil;
6587 XSETVECTOR (barobj, bar);
6588 fset_scroll_bars (f, barobj);
6589 if (!NILP (bar->next))
6590 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
6592 /* Map the window/widget. */
6593 #ifdef USE_TOOLKIT_SCROLL_BARS
6595 #ifdef USE_GTK
6596 if (horizontal)
6597 xg_update_horizontal_scrollbar_pos (f, bar->x_window, top,
6598 left, width, max (height, 1));
6599 else
6600 xg_update_scrollbar_pos (f, bar->x_window, top,
6601 left, width, max (height, 1));
6602 #else /* not USE_GTK */
6603 Widget scroll_bar = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
6604 XtConfigureWidget (scroll_bar, left, top, width, max (height, 1), 0);
6605 XtMapWidget (scroll_bar);
6606 /* Don't obscure any child frames. */
6607 XLowerWindow (FRAME_X_DISPLAY (f), bar->x_window);
6608 #endif /* not USE_GTK */
6610 #else /* not USE_TOOLKIT_SCROLL_BARS */
6611 XMapWindow (FRAME_X_DISPLAY (f), bar->x_window);
6612 /* Don't obscure any child frames. */
6613 XLowerWindow (FRAME_X_DISPLAY (f), bar->x_window);
6614 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6616 unblock_input ();
6617 return bar;
6621 #ifndef USE_TOOLKIT_SCROLL_BARS
6623 /* Draw BAR's handle in the proper position.
6625 If the handle is already drawn from START to END, don't bother
6626 redrawing it, unless REBUILD; in that case, always
6627 redraw it. (REBUILD is handy for drawing the handle after expose
6628 events.)
6630 Normally, we want to constrain the start and end of the handle to
6631 fit inside its rectangle, but if the user is dragging the scroll
6632 bar handle, we want to let them drag it down all the way, so that
6633 the bar's top is as far down as it goes; otherwise, there's no way
6634 to move to the very end of the buffer. */
6636 static void
6637 x_scroll_bar_set_handle (struct scroll_bar *bar, int start, int end,
6638 bool rebuild)
6640 bool dragging = bar->dragging != -1;
6641 Window w = bar->x_window;
6642 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6643 GC gc = f->output_data.x->normal_gc;
6645 /* If the display is already accurate, do nothing. */
6646 if (! rebuild
6647 && start == bar->start
6648 && end == bar->end)
6649 return;
6651 block_input ();
6654 int inside_width = VERTICAL_SCROLL_BAR_INSIDE_WIDTH (f, bar->width);
6655 int inside_height = VERTICAL_SCROLL_BAR_INSIDE_HEIGHT (f, bar->height);
6656 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
6658 /* Make sure the values are reasonable, and try to preserve
6659 the distance between start and end. */
6661 int length = end - start;
6663 if (start < 0)
6664 start = 0;
6665 else if (start > top_range)
6666 start = top_range;
6667 end = start + length;
6669 if (end < start)
6670 end = start;
6671 else if (end > top_range && ! dragging)
6672 end = top_range;
6675 /* Store the adjusted setting in the scroll bar. */
6676 bar->start = start;
6677 bar->end = end;
6679 /* Clip the end position, just for display. */
6680 if (end > top_range)
6681 end = top_range;
6683 /* Draw bottom positions VERTICAL_SCROLL_BAR_MIN_HANDLE pixels
6684 below top positions, to make sure the handle is always at least
6685 that many pixels tall. */
6686 end += VERTICAL_SCROLL_BAR_MIN_HANDLE;
6688 /* Draw the empty space above the handle. Note that we can't clear
6689 zero-height areas; that means "clear to end of window." */
6690 if ((inside_width > 0) && (start > 0))
6691 x_clear_area1 (FRAME_X_DISPLAY (f), w,
6692 VERTICAL_SCROLL_BAR_LEFT_BORDER,
6693 VERTICAL_SCROLL_BAR_TOP_BORDER,
6694 inside_width, start, False);
6696 /* Change to proper foreground color if one is specified. */
6697 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
6698 XSetForeground (FRAME_X_DISPLAY (f), gc,
6699 f->output_data.x->scroll_bar_foreground_pixel);
6701 /* Draw the handle itself. */
6702 XFillRectangle (FRAME_X_DISPLAY (f), w, gc,
6703 /* x, y, width, height */
6704 VERTICAL_SCROLL_BAR_LEFT_BORDER,
6705 VERTICAL_SCROLL_BAR_TOP_BORDER + start,
6706 inside_width, end - start);
6708 /* Restore the foreground color of the GC if we changed it above. */
6709 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
6710 XSetForeground (FRAME_X_DISPLAY (f), gc,
6711 FRAME_FOREGROUND_PIXEL (f));
6713 /* Draw the empty space below the handle. Note that we can't
6714 clear zero-height areas; that means "clear to end of window." */
6715 if ((inside_width > 0) && (end < inside_height))
6716 x_clear_area1 (FRAME_X_DISPLAY (f), w,
6717 VERTICAL_SCROLL_BAR_LEFT_BORDER,
6718 VERTICAL_SCROLL_BAR_TOP_BORDER + end,
6719 inside_width, inside_height - end, False);
6722 unblock_input ();
6725 #endif /* !USE_TOOLKIT_SCROLL_BARS */
6727 /* Destroy scroll bar BAR, and set its Emacs window's scroll bar to
6728 nil. */
6730 static void
6731 x_scroll_bar_remove (struct scroll_bar *bar)
6733 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6734 block_input ();
6736 #ifdef USE_TOOLKIT_SCROLL_BARS
6737 #ifdef USE_GTK
6738 xg_remove_scroll_bar (f, bar->x_window);
6739 #else /* not USE_GTK */
6740 XtDestroyWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar));
6741 #endif /* not USE_GTK */
6742 #else
6743 XDestroyWindow (FRAME_X_DISPLAY (f), bar->x_window);
6744 #endif
6746 /* Dissociate this scroll bar from its window. */
6747 if (bar->horizontal)
6748 wset_horizontal_scroll_bar (XWINDOW (bar->window), Qnil);
6749 else
6750 wset_vertical_scroll_bar (XWINDOW (bar->window), Qnil);
6752 unblock_input ();
6756 /* Set the handle of the vertical scroll bar for WINDOW to indicate
6757 that we are displaying PORTION characters out of a total of WHOLE
6758 characters, starting at POSITION. If WINDOW has no scroll bar,
6759 create one. */
6761 static void
6762 XTset_vertical_scroll_bar (struct window *w, int portion, int whole, int position)
6764 struct frame *f = XFRAME (w->frame);
6765 Lisp_Object barobj;
6766 struct scroll_bar *bar;
6767 int top, height, left, width;
6768 int window_y, window_height;
6770 /* Get window dimensions. */
6771 window_box (w, ANY_AREA, 0, &window_y, 0, &window_height);
6772 top = window_y;
6773 height = window_height;
6774 left = WINDOW_SCROLL_BAR_AREA_X (w);
6775 width = WINDOW_SCROLL_BAR_AREA_WIDTH (w);
6777 /* Does the scroll bar exist yet? */
6778 if (NILP (w->vertical_scroll_bar))
6780 if (width > 0 && height > 0)
6782 block_input ();
6783 x_clear_area (f, left, top, width, height);
6784 unblock_input ();
6787 bar = x_scroll_bar_create (w, top, left, width, max (height, 1), false);
6789 else
6791 /* It may just need to be moved and resized. */
6792 unsigned int mask = 0;
6794 bar = XSCROLL_BAR (w->vertical_scroll_bar);
6796 block_input ();
6798 if (left != bar->left)
6799 mask |= CWX;
6800 if (top != bar->top)
6801 mask |= CWY;
6802 if (width != bar->width)
6803 mask |= CWWidth;
6804 if (height != bar->height)
6805 mask |= CWHeight;
6807 #ifdef USE_TOOLKIT_SCROLL_BARS
6809 /* Move/size the scroll bar widget. */
6810 if (mask)
6812 /* Since toolkit scroll bars are smaller than the space reserved
6813 for them on the frame, we have to clear "under" them. */
6814 if (width > 0 && height > 0)
6815 x_clear_area (f, left, top, width, height);
6816 #ifdef USE_GTK
6817 xg_update_scrollbar_pos (f, bar->x_window, top,
6818 left, width, max (height, 1));
6819 #else /* not USE_GTK */
6820 XtConfigureWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar),
6821 left, top, width, max (height, 1), 0);
6822 #endif /* not USE_GTK */
6824 #else /* not USE_TOOLKIT_SCROLL_BARS */
6826 /* Move/size the scroll bar window. */
6827 if (mask)
6829 XWindowChanges wc;
6831 wc.x = left;
6832 wc.y = top;
6833 wc.width = width;
6834 wc.height = height;
6835 XConfigureWindow (FRAME_X_DISPLAY (f), bar->x_window,
6836 mask, &wc);
6839 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6841 /* Remember new settings. */
6842 bar->left = left;
6843 bar->top = top;
6844 bar->width = width;
6845 bar->height = height;
6847 unblock_input ();
6850 #ifdef USE_TOOLKIT_SCROLL_BARS
6851 x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
6852 #else /* not USE_TOOLKIT_SCROLL_BARS */
6853 /* Set the scroll bar's current state, unless we're currently being
6854 dragged. */
6855 if (bar->dragging == -1)
6857 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, height);
6859 if (whole == 0)
6860 x_scroll_bar_set_handle (bar, 0, top_range, false);
6861 else
6863 int start = ((double) position * top_range) / whole;
6864 int end = ((double) (position + portion) * top_range) / whole;
6865 x_scroll_bar_set_handle (bar, start, end, false);
6868 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6870 XSETVECTOR (barobj, bar);
6871 wset_vertical_scroll_bar (w, barobj);
6875 static void
6876 XTset_horizontal_scroll_bar (struct window *w, int portion, int whole, int position)
6878 struct frame *f = XFRAME (w->frame);
6879 Lisp_Object barobj;
6880 struct scroll_bar *bar;
6881 int top, height, left, width;
6882 int window_x, window_width;
6883 int pixel_width = WINDOW_PIXEL_WIDTH (w);
6885 /* Get window dimensions. */
6886 window_box (w, ANY_AREA, &window_x, 0, &window_width, 0);
6887 left = window_x;
6888 width = window_width;
6889 top = WINDOW_SCROLL_BAR_AREA_Y (w);
6890 height = WINDOW_SCROLL_BAR_AREA_HEIGHT (w);
6892 /* Does the scroll bar exist yet? */
6893 if (NILP (w->horizontal_scroll_bar))
6895 if (width > 0 && height > 0)
6897 block_input ();
6899 /* Clear also part between window_width and
6900 WINDOW_PIXEL_WIDTH. */
6901 x_clear_area (f, left, top, pixel_width, height);
6902 unblock_input ();
6905 bar = x_scroll_bar_create (w, top, left, width, height, true);
6907 else
6909 /* It may just need to be moved and resized. */
6910 unsigned int mask = 0;
6912 bar = XSCROLL_BAR (w->horizontal_scroll_bar);
6914 block_input ();
6916 if (left != bar->left)
6917 mask |= CWX;
6918 if (top != bar->top)
6919 mask |= CWY;
6920 if (width != bar->width)
6921 mask |= CWWidth;
6922 if (height != bar->height)
6923 mask |= CWHeight;
6925 #ifdef USE_TOOLKIT_SCROLL_BARS
6926 /* Move/size the scroll bar widget. */
6927 if (mask)
6929 /* Since toolkit scroll bars are smaller than the space reserved
6930 for them on the frame, we have to clear "under" them. */
6931 if (width > 0 && height > 0)
6932 x_clear_area (f,
6933 WINDOW_LEFT_EDGE_X (w), top,
6934 pixel_width - WINDOW_RIGHT_DIVIDER_WIDTH (w), height);
6935 #ifdef USE_GTK
6936 xg_update_horizontal_scrollbar_pos (f, bar->x_window, top, left,
6937 width, height);
6938 #else /* not USE_GTK */
6939 XtConfigureWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar),
6940 left, top, width, height, 0);
6941 #endif /* not USE_GTK */
6943 #else /* not USE_TOOLKIT_SCROLL_BARS */
6945 /* Clear areas not covered by the scroll bar because it's not as
6946 wide as the area reserved for it. This makes sure a
6947 previous mode line display is cleared after C-x 2 C-x 1, for
6948 example. */
6950 int area_height = WINDOW_CONFIG_SCROLL_BAR_HEIGHT (w);
6951 int rest = area_height - height;
6952 if (rest > 0 && width > 0)
6953 x_clear_area (f, left, top, width, rest);
6956 /* Move/size the scroll bar window. */
6957 if (mask)
6959 XWindowChanges wc;
6961 wc.x = left;
6962 wc.y = top;
6963 wc.width = width;
6964 wc.height = height;
6965 XConfigureWindow (FRAME_X_DISPLAY (f), bar->x_window,
6966 mask, &wc);
6969 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6971 /* Remember new settings. */
6972 bar->left = left;
6973 bar->top = top;
6974 bar->width = width;
6975 bar->height = height;
6977 unblock_input ();
6980 #ifdef USE_TOOLKIT_SCROLL_BARS
6981 x_set_toolkit_horizontal_scroll_bar_thumb (bar, portion, position, whole);
6982 #else /* not USE_TOOLKIT_SCROLL_BARS */
6983 /* Set the scroll bar's current state, unless we're currently being
6984 dragged. */
6985 if (bar->dragging == -1)
6987 int left_range = HORIZONTAL_SCROLL_BAR_LEFT_RANGE (f, width);
6989 if (whole == 0)
6990 x_scroll_bar_set_handle (bar, 0, left_range, false);
6991 else
6993 int start = ((double) position * left_range) / whole;
6994 int end = ((double) (position + portion) * left_range) / whole;
6995 x_scroll_bar_set_handle (bar, start, end, false);
6998 #endif /* not USE_TOOLKIT_SCROLL_BARS */
7000 XSETVECTOR (barobj, bar);
7001 wset_horizontal_scroll_bar (w, barobj);
7005 /* The following three hooks are used when we're doing a thorough
7006 redisplay of the frame. We don't explicitly know which scroll bars
7007 are going to be deleted, because keeping track of when windows go
7008 away is a real pain - "Can you say set-window-configuration, boys
7009 and girls?" Instead, we just assert at the beginning of redisplay
7010 that *all* scroll bars are to be removed, and then save a scroll bar
7011 from the fiery pit when we actually redisplay its window. */
7013 /* Arrange for all scroll bars on FRAME to be removed at the next call
7014 to `*judge_scroll_bars_hook'. A scroll bar may be spared if
7015 `*redeem_scroll_bar_hook' is applied to its window before the judgment. */
7017 static void
7018 XTcondemn_scroll_bars (struct frame *frame)
7020 if (!NILP (FRAME_SCROLL_BARS (frame)))
7022 if (!NILP (FRAME_CONDEMNED_SCROLL_BARS (frame)))
7024 /* Prepend scrollbars to already condemned ones. */
7025 Lisp_Object last = FRAME_SCROLL_BARS (frame);
7027 while (!NILP (XSCROLL_BAR (last)->next))
7028 last = XSCROLL_BAR (last)->next;
7030 XSCROLL_BAR (last)->next = FRAME_CONDEMNED_SCROLL_BARS (frame);
7031 XSCROLL_BAR (FRAME_CONDEMNED_SCROLL_BARS (frame))->prev = last;
7034 fset_condemned_scroll_bars (frame, FRAME_SCROLL_BARS (frame));
7035 fset_scroll_bars (frame, Qnil);
7040 /* Un-mark WINDOW's scroll bar for deletion in this judgment cycle.
7041 Note that WINDOW isn't necessarily condemned at all. */
7043 static void
7044 XTredeem_scroll_bar (struct window *w)
7046 struct scroll_bar *bar;
7047 Lisp_Object barobj;
7048 struct frame *f;
7050 /* We can't redeem this window's scroll bar if it doesn't have one. */
7051 if (NILP (w->vertical_scroll_bar) && NILP (w->horizontal_scroll_bar))
7052 emacs_abort ();
7054 if (!NILP (w->vertical_scroll_bar) && WINDOW_HAS_VERTICAL_SCROLL_BAR (w))
7056 bar = XSCROLL_BAR (w->vertical_scroll_bar);
7057 /* Unlink it from the condemned list. */
7058 f = XFRAME (WINDOW_FRAME (w));
7059 if (NILP (bar->prev))
7061 /* If the prev pointer is nil, it must be the first in one of
7062 the lists. */
7063 if (EQ (FRAME_SCROLL_BARS (f), w->vertical_scroll_bar))
7064 /* It's not condemned. Everything's fine. */
7065 goto horizontal;
7066 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
7067 w->vertical_scroll_bar))
7068 fset_condemned_scroll_bars (f, bar->next);
7069 else
7070 /* If its prev pointer is nil, it must be at the front of
7071 one or the other! */
7072 emacs_abort ();
7074 else
7075 XSCROLL_BAR (bar->prev)->next = bar->next;
7077 if (! NILP (bar->next))
7078 XSCROLL_BAR (bar->next)->prev = bar->prev;
7080 bar->next = FRAME_SCROLL_BARS (f);
7081 bar->prev = Qnil;
7082 XSETVECTOR (barobj, bar);
7083 fset_scroll_bars (f, barobj);
7084 if (! NILP (bar->next))
7085 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
7088 horizontal:
7089 if (!NILP (w->horizontal_scroll_bar) && WINDOW_HAS_HORIZONTAL_SCROLL_BAR (w))
7091 bar = XSCROLL_BAR (w->horizontal_scroll_bar);
7092 /* Unlink it from the condemned list. */
7093 f = XFRAME (WINDOW_FRAME (w));
7094 if (NILP (bar->prev))
7096 /* If the prev pointer is nil, it must be the first in one of
7097 the lists. */
7098 if (EQ (FRAME_SCROLL_BARS (f), w->horizontal_scroll_bar))
7099 /* It's not condemned. Everything's fine. */
7100 return;
7101 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
7102 w->horizontal_scroll_bar))
7103 fset_condemned_scroll_bars (f, bar->next);
7104 else
7105 /* If its prev pointer is nil, it must be at the front of
7106 one or the other! */
7107 emacs_abort ();
7109 else
7110 XSCROLL_BAR (bar->prev)->next = bar->next;
7112 if (! NILP (bar->next))
7113 XSCROLL_BAR (bar->next)->prev = bar->prev;
7115 bar->next = FRAME_SCROLL_BARS (f);
7116 bar->prev = Qnil;
7117 XSETVECTOR (barobj, bar);
7118 fset_scroll_bars (f, barobj);
7119 if (! NILP (bar->next))
7120 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
7124 /* Remove all scroll bars on FRAME that haven't been saved since the
7125 last call to `*condemn_scroll_bars_hook'. */
7127 static void
7128 XTjudge_scroll_bars (struct frame *f)
7130 Lisp_Object bar, next;
7132 bar = FRAME_CONDEMNED_SCROLL_BARS (f);
7134 /* Clear out the condemned list now so we won't try to process any
7135 more events on the hapless scroll bars. */
7136 fset_condemned_scroll_bars (f, Qnil);
7138 for (; ! NILP (bar); bar = next)
7140 struct scroll_bar *b = XSCROLL_BAR (bar);
7142 x_scroll_bar_remove (b);
7144 next = b->next;
7145 b->next = b->prev = Qnil;
7148 /* Now there should be no references to the condemned scroll bars,
7149 and they should get garbage-collected. */
7153 #ifndef USE_TOOLKIT_SCROLL_BARS
7154 /* Handle an Expose or GraphicsExpose event on a scroll bar. This
7155 is a no-op when using toolkit scroll bars.
7157 This may be called from a signal handler, so we have to ignore GC
7158 mark bits. */
7160 static void
7161 x_scroll_bar_expose (struct scroll_bar *bar, const XEvent *event)
7163 Window w = bar->x_window;
7164 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
7165 GC gc = f->output_data.x->normal_gc;
7167 block_input ();
7169 x_scroll_bar_set_handle (bar, bar->start, bar->end, true);
7171 /* Switch to scroll bar foreground color. */
7172 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
7173 XSetForeground (FRAME_X_DISPLAY (f), gc,
7174 f->output_data.x->scroll_bar_foreground_pixel);
7176 /* Draw a one-pixel border just inside the edges of the scroll bar. */
7177 XDrawRectangle (FRAME_X_DISPLAY (f), w, gc,
7178 /* x, y, width, height */
7179 0, 0, bar->width - 1, bar->height - 1);
7181 /* Restore the foreground color of the GC if we changed it above. */
7182 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
7183 XSetForeground (FRAME_X_DISPLAY (f), gc,
7184 FRAME_FOREGROUND_PIXEL (f));
7186 unblock_input ();
7189 #endif /* not USE_TOOLKIT_SCROLL_BARS */
7191 /* Handle a mouse click on the scroll bar BAR. If *EMACS_EVENT's kind
7192 is set to something other than NO_EVENT, it is enqueued.
7194 This may be called from a signal handler, so we have to ignore GC
7195 mark bits. */
7198 static void
7199 x_scroll_bar_handle_click (struct scroll_bar *bar,
7200 const XEvent *event,
7201 struct input_event *emacs_event)
7203 if (! WINDOWP (bar->window))
7204 emacs_abort ();
7206 emacs_event->kind = (bar->horizontal
7207 ? HORIZONTAL_SCROLL_BAR_CLICK_EVENT
7208 : SCROLL_BAR_CLICK_EVENT);
7209 emacs_event->code = event->xbutton.button - Button1;
7210 emacs_event->modifiers
7211 = (x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO
7212 (XFRAME (WINDOW_FRAME (XWINDOW (bar->window)))),
7213 event->xbutton.state)
7214 | (event->type == ButtonRelease
7215 ? up_modifier
7216 : down_modifier));
7217 emacs_event->frame_or_window = bar->window;
7218 emacs_event->arg = Qnil;
7219 emacs_event->timestamp = event->xbutton.time;
7220 if (bar->horizontal)
7222 int left_range
7223 = HORIZONTAL_SCROLL_BAR_LEFT_RANGE (f, bar->width);
7224 int x = event->xbutton.x - HORIZONTAL_SCROLL_BAR_LEFT_BORDER;
7226 if (x < 0) x = 0;
7227 if (x > left_range) x = left_range;
7229 if (x < bar->start)
7230 emacs_event->part = scroll_bar_before_handle;
7231 else if (x < bar->end + HORIZONTAL_SCROLL_BAR_MIN_HANDLE)
7232 emacs_event->part = scroll_bar_horizontal_handle;
7233 else
7234 emacs_event->part = scroll_bar_after_handle;
7236 #ifndef USE_TOOLKIT_SCROLL_BARS
7237 /* If the user has released the handle, set it to its final position. */
7238 if (event->type == ButtonRelease && bar->dragging != -1)
7240 int new_start = - bar->dragging;
7241 int new_end = new_start + bar->end - bar->start;
7243 x_scroll_bar_set_handle (bar, new_start, new_end, false);
7244 bar->dragging = -1;
7246 #endif
7248 XSETINT (emacs_event->x, left_range);
7249 XSETINT (emacs_event->y, x);
7251 else
7253 int top_range
7254 = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
7255 int y = event->xbutton.y - VERTICAL_SCROLL_BAR_TOP_BORDER;
7257 if (y < 0) y = 0;
7258 if (y > top_range) y = top_range;
7260 if (y < bar->start)
7261 emacs_event->part = scroll_bar_above_handle;
7262 else if (y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
7263 emacs_event->part = scroll_bar_handle;
7264 else
7265 emacs_event->part = scroll_bar_below_handle;
7267 #ifndef USE_TOOLKIT_SCROLL_BARS
7268 /* If the user has released the handle, set it to its final position. */
7269 if (event->type == ButtonRelease && bar->dragging != -1)
7271 int new_start = y - bar->dragging;
7272 int new_end = new_start + bar->end - bar->start;
7274 x_scroll_bar_set_handle (bar, new_start, new_end, false);
7275 bar->dragging = -1;
7277 #endif
7279 XSETINT (emacs_event->x, y);
7280 XSETINT (emacs_event->y, top_range);
7284 #ifndef USE_TOOLKIT_SCROLL_BARS
7286 /* Handle some mouse motion while someone is dragging the scroll bar.
7288 This may be called from a signal handler, so we have to ignore GC
7289 mark bits. */
7291 static void
7292 x_scroll_bar_note_movement (struct scroll_bar *bar,
7293 const XMotionEvent *event)
7295 struct frame *f = XFRAME (XWINDOW (bar->window)->frame);
7296 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
7298 dpyinfo->last_mouse_movement_time = event->time;
7299 dpyinfo->last_mouse_scroll_bar = bar;
7300 f->mouse_moved = true;
7302 /* If we're dragging the bar, display it. */
7303 if (bar->dragging != -1)
7305 /* Where should the handle be now? */
7306 int new_start = event->y - bar->dragging;
7308 if (new_start != bar->start)
7310 int new_end = new_start + bar->end - bar->start;
7312 x_scroll_bar_set_handle (bar, new_start, new_end, false);
7317 #endif /* !USE_TOOLKIT_SCROLL_BARS */
7319 /* Return information to the user about the current position of the mouse
7320 on the scroll bar. */
7322 static void
7323 x_scroll_bar_report_motion (struct frame **fp, Lisp_Object *bar_window,
7324 enum scroll_bar_part *part, Lisp_Object *x,
7325 Lisp_Object *y, Time *timestamp)
7327 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (*fp);
7328 struct scroll_bar *bar = dpyinfo->last_mouse_scroll_bar;
7329 Window w = bar->x_window;
7330 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
7331 int win_x, win_y;
7332 Window dummy_window;
7333 int dummy_coord;
7334 unsigned int dummy_mask;
7336 block_input ();
7338 /* Get the mouse's position relative to the scroll bar window, and
7339 report that. */
7340 if (XQueryPointer (FRAME_X_DISPLAY (f), w,
7342 /* Root, child, root x and root y. */
7343 &dummy_window, &dummy_window,
7344 &dummy_coord, &dummy_coord,
7346 /* Position relative to scroll bar. */
7347 &win_x, &win_y,
7349 /* Mouse buttons and modifier keys. */
7350 &dummy_mask))
7352 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
7354 win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
7356 if (bar->dragging != -1)
7357 win_y -= bar->dragging;
7359 if (win_y < 0)
7360 win_y = 0;
7361 if (win_y > top_range)
7362 win_y = top_range;
7364 *fp = f;
7365 *bar_window = bar->window;
7367 if (bar->dragging != -1)
7368 *part = scroll_bar_handle;
7369 else if (win_y < bar->start)
7370 *part = scroll_bar_above_handle;
7371 else if (win_y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
7372 *part = scroll_bar_handle;
7373 else
7374 *part = scroll_bar_below_handle;
7376 XSETINT (*x, win_y);
7377 XSETINT (*y, top_range);
7379 f->mouse_moved = false;
7380 dpyinfo->last_mouse_scroll_bar = NULL;
7381 *timestamp = dpyinfo->last_mouse_movement_time;
7384 unblock_input ();
7388 /* Return information to the user about the current position of the mouse
7389 on the scroll bar. */
7391 static void
7392 x_horizontal_scroll_bar_report_motion (struct frame **fp, Lisp_Object *bar_window,
7393 enum scroll_bar_part *part, Lisp_Object *x,
7394 Lisp_Object *y, Time *timestamp)
7396 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (*fp);
7397 struct scroll_bar *bar = dpyinfo->last_mouse_scroll_bar;
7398 Window w = bar->x_window;
7399 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
7400 int win_x, win_y;
7401 Window dummy_window;
7402 int dummy_coord;
7403 unsigned int dummy_mask;
7405 block_input ();
7407 /* Get the mouse's position relative to the scroll bar window, and
7408 report that. */
7409 if (XQueryPointer (FRAME_X_DISPLAY (f), w,
7411 /* Root, child, root x and root y. */
7412 &dummy_window, &dummy_window,
7413 &dummy_coord, &dummy_coord,
7415 /* Position relative to scroll bar. */
7416 &win_x, &win_y,
7418 /* Mouse buttons and modifier keys. */
7419 &dummy_mask))
7421 int left_range = HORIZONTAL_SCROLL_BAR_LEFT_RANGE (f, bar->width);
7423 win_x -= HORIZONTAL_SCROLL_BAR_LEFT_BORDER;
7425 if (bar->dragging != -1)
7426 win_x -= bar->dragging;
7428 if (win_x < 0)
7429 win_x = 0;
7430 if (win_x > left_range)
7431 win_x = left_range;
7433 *fp = f;
7434 *bar_window = bar->window;
7436 if (bar->dragging != -1)
7437 *part = scroll_bar_horizontal_handle;
7438 else if (win_x < bar->start)
7439 *part = scroll_bar_before_handle;
7440 else if (win_x < bar->end + HORIZONTAL_SCROLL_BAR_MIN_HANDLE)
7441 *part = scroll_bar_handle;
7442 else
7443 *part = scroll_bar_after_handle;
7445 XSETINT (*y, win_x);
7446 XSETINT (*x, left_range);
7448 f->mouse_moved = false;
7449 dpyinfo->last_mouse_scroll_bar = NULL;
7450 *timestamp = dpyinfo->last_mouse_movement_time;
7453 unblock_input ();
7457 /* The screen has been cleared so we may have changed foreground or
7458 background colors, and the scroll bars may need to be redrawn.
7459 Clear out the scroll bars, and ask for expose events, so we can
7460 redraw them. */
7462 static void
7463 x_scroll_bar_clear (struct frame *f)
7465 #ifndef USE_TOOLKIT_SCROLL_BARS
7466 Lisp_Object bar;
7468 /* We can have scroll bars even if this is 0,
7469 if we just turned off scroll bar mode.
7470 But in that case we should not clear them. */
7471 if (FRAME_HAS_VERTICAL_SCROLL_BARS (f))
7472 for (bar = FRAME_SCROLL_BARS (f); VECTORP (bar);
7473 bar = XSCROLL_BAR (bar)->next)
7474 XClearArea (FRAME_X_DISPLAY (f),
7475 XSCROLL_BAR (bar)->x_window,
7476 0, 0, 0, 0, True);
7477 #endif /* not USE_TOOLKIT_SCROLL_BARS */
7480 #ifdef ENABLE_CHECKING
7482 /* Record the last 100 characters stored
7483 to help debug the loss-of-chars-during-GC problem. */
7485 static int temp_index;
7486 static short temp_buffer[100];
7488 #define STORE_KEYSYM_FOR_DEBUG(keysym) \
7489 if (temp_index == ARRAYELTS (temp_buffer)) \
7490 temp_index = 0; \
7491 temp_buffer[temp_index++] = (keysym)
7493 #else /* not ENABLE_CHECKING */
7495 #define STORE_KEYSYM_FOR_DEBUG(keysym) ((void)0)
7497 #endif /* ENABLE_CHECKING */
7499 /* Set this to nonzero to fake an "X I/O error"
7500 on a particular display. */
7502 static struct x_display_info *XTread_socket_fake_io_error;
7504 /* When we find no input here, we occasionally do a no-op command
7505 to verify that the X server is still running and we can still talk with it.
7506 We try all the open displays, one by one.
7507 This variable is used for cycling thru the displays. */
7509 static struct x_display_info *next_noop_dpyinfo;
7511 enum
7513 X_EVENT_NORMAL,
7514 X_EVENT_GOTO_OUT,
7515 X_EVENT_DROP
7518 /* Filter events for the current X input method.
7519 DPYINFO is the display this event is for.
7520 EVENT is the X event to filter.
7522 Returns non-zero if the event was filtered, caller shall not process
7523 this event further.
7524 Returns zero if event is wasn't filtered. */
7526 #ifdef HAVE_X_I18N
7527 static int
7528 x_filter_event (struct x_display_info *dpyinfo, XEvent *event)
7530 /* XFilterEvent returns non-zero if the input method has
7531 consumed the event. We pass the frame's X window to
7532 XFilterEvent because that's the one for which the IC
7533 was created. */
7535 struct frame *f1 = x_any_window_to_frame (dpyinfo,
7536 event->xclient.window);
7538 return XFilterEvent (event, f1 ? FRAME_X_WINDOW (f1) : None);
7540 #endif
7542 #ifdef USE_GTK
7543 static int current_count;
7544 static int current_finish;
7545 static struct input_event *current_hold_quit;
7547 /* This is the filter function invoked by the GTK event loop.
7548 It is invoked before the XEvent is translated to a GdkEvent,
7549 so we have a chance to act on the event before GTK. */
7550 static GdkFilterReturn
7551 event_handler_gdk (GdkXEvent *gxev, GdkEvent *ev, gpointer data)
7553 XEvent *xev = (XEvent *) gxev;
7555 block_input ();
7556 if (current_count >= 0)
7558 struct x_display_info *dpyinfo;
7560 dpyinfo = x_display_info_for_display (xev->xany.display);
7562 #ifdef HAVE_X_I18N
7563 /* Filter events for the current X input method.
7564 GTK calls XFilterEvent but not for key press and release,
7565 so we do it here. */
7566 if ((xev->type == KeyPress || xev->type == KeyRelease)
7567 && dpyinfo
7568 && x_filter_event (dpyinfo, xev))
7570 unblock_input ();
7571 return GDK_FILTER_REMOVE;
7573 #endif
7575 if (! dpyinfo)
7576 current_finish = X_EVENT_NORMAL;
7577 else
7578 current_count
7579 += handle_one_xevent (dpyinfo, xev, &current_finish,
7580 current_hold_quit);
7582 else
7583 current_finish = x_dispatch_event (xev, xev->xany.display);
7585 unblock_input ();
7587 if (current_finish == X_EVENT_GOTO_OUT || current_finish == X_EVENT_DROP)
7588 return GDK_FILTER_REMOVE;
7590 return GDK_FILTER_CONTINUE;
7592 #endif /* USE_GTK */
7595 static void xembed_send_message (struct frame *f, Time,
7596 enum xembed_message,
7597 long detail, long data1, long data2);
7599 static void
7600 x_net_wm_state (struct frame *f, Window window)
7602 int value = FULLSCREEN_NONE;
7603 Lisp_Object lval = Qnil;
7604 bool sticky = false;
7606 get_current_wm_state (f, window, &value, &sticky);
7608 switch (value)
7610 case FULLSCREEN_WIDTH:
7611 lval = Qfullwidth;
7612 break;
7613 case FULLSCREEN_HEIGHT:
7614 lval = Qfullheight;
7615 break;
7616 case FULLSCREEN_BOTH:
7617 lval = Qfullboth;
7618 break;
7619 case FULLSCREEN_MAXIMIZED:
7620 lval = Qmaximized;
7621 break;
7624 frame_size_history_add
7625 (f, Qx_net_wm_state, 0, 0,
7626 list2 (get_frame_param (f, Qfullscreen), lval));
7628 store_frame_param (f, Qfullscreen, lval);
7629 /** store_frame_param (f, Qsticky, sticky ? Qt : Qnil); **/
7632 /* Flip back buffers on any frames with undrawn content. */
7633 static void
7634 flush_dirty_back_buffers (void)
7636 block_input ();
7637 Lisp_Object tail, frame;
7638 FOR_EACH_FRAME (tail, frame)
7640 struct frame *f = XFRAME (frame);
7641 if (FRAME_LIVE_P (f) &&
7642 FRAME_X_P (f) &&
7643 FRAME_X_WINDOW (f) &&
7644 !FRAME_GARBAGED_P (f) &&
7645 !buffer_flipping_blocked_p () &&
7646 FRAME_X_NEED_BUFFER_FLIP (f))
7647 show_back_buffer (f);
7649 unblock_input ();
7652 /* Handles the XEvent EVENT on display DPYINFO.
7654 *FINISH is X_EVENT_GOTO_OUT if caller should stop reading events.
7655 *FINISH is zero if caller should continue reading events.
7656 *FINISH is X_EVENT_DROP if event should not be passed to the toolkit.
7657 *EVENT is unchanged unless we're processing KeyPress event.
7659 We return the number of characters stored into the buffer. */
7661 static int
7662 handle_one_xevent (struct x_display_info *dpyinfo,
7663 const XEvent *event,
7664 int *finish, struct input_event *hold_quit)
7666 union buffered_input_event inev;
7667 int count = 0;
7668 int do_help = 0;
7669 ptrdiff_t nbytes = 0;
7670 struct frame *any, *f = NULL;
7671 struct coding_system coding;
7672 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
7673 /* This holds the state XLookupString needs to implement dead keys
7674 and other tricks known as "compose processing". _X Window System_
7675 says that a portable program can't use this, but Stephen Gildea assures
7676 me that letting the compiler initialize it to zeros will work okay. */
7677 static XComposeStatus compose_status;
7678 XEvent configureEvent;
7679 XEvent next_event;
7681 USE_SAFE_ALLOCA;
7683 *finish = X_EVENT_NORMAL;
7685 EVENT_INIT (inev.ie);
7686 inev.ie.kind = NO_EVENT;
7687 inev.ie.arg = Qnil;
7689 any = x_any_window_to_frame (dpyinfo, event->xany.window);
7691 if (any && any->wait_event_type == event->type)
7692 any->wait_event_type = 0; /* Indicates we got it. */
7694 switch (event->type)
7696 case ClientMessage:
7698 if (event->xclient.message_type == dpyinfo->Xatom_wm_protocols
7699 && event->xclient.format == 32)
7701 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_take_focus)
7703 /* Use the value returned by x_any_window_to_frame
7704 because this could be the shell widget window
7705 if the frame has no title bar. */
7706 f = any;
7707 #ifdef HAVE_X_I18N
7708 /* Not quite sure this is needed -pd */
7709 if (f && FRAME_XIC (f))
7710 XSetICFocus (FRAME_XIC (f));
7711 #endif
7712 #if false
7713 /* Emacs sets WM hints whose `input' field is `true'. This
7714 instructs the WM to set the input focus automatically for
7715 Emacs with a call to XSetInputFocus. Setting WM_TAKE_FOCUS
7716 tells the WM to send us a ClientMessage WM_TAKE_FOCUS after
7717 it has set the focus. So, XSetInputFocus below is not
7718 needed.
7720 The call to XSetInputFocus below has also caused trouble. In
7721 cases where the XSetInputFocus done by the WM and the one
7722 below are temporally close (on a fast machine), the call
7723 below can generate additional FocusIn events which confuse
7724 Emacs. */
7726 /* Since we set WM_TAKE_FOCUS, we must call
7727 XSetInputFocus explicitly. But not if f is null,
7728 since that might be an event for a deleted frame. */
7729 if (f)
7731 Display *d = event->xclient.display;
7732 /* Catch and ignore errors, in case window has been
7733 iconified by a window manager such as GWM. */
7734 x_catch_errors (d);
7735 XSetInputFocus (d, event->xclient.window,
7736 /* The ICCCM says this is
7737 the only valid choice. */
7738 RevertToParent,
7739 event->xclient.data.l[1]);
7740 x_uncatch_errors ();
7742 /* Not certain about handling scroll bars here */
7743 #endif
7744 goto done;
7747 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_save_yourself)
7749 /* Save state modify the WM_COMMAND property to
7750 something which can reinstate us. This notifies
7751 the session manager, who's looking for such a
7752 PropertyNotify. Can restart processing when
7753 a keyboard or mouse event arrives. */
7754 /* If we have a session manager, don't set this.
7755 KDE will then start two Emacsen, one for the
7756 session manager and one for this. */
7757 #ifdef HAVE_X_SM
7758 if (! x_session_have_connection ())
7759 #endif
7761 f = x_top_window_to_frame (dpyinfo,
7762 event->xclient.window);
7763 /* This is just so we only give real data once
7764 for a single Emacs process. */
7765 if (f == SELECTED_FRAME ())
7766 XSetCommand (FRAME_X_DISPLAY (f),
7767 event->xclient.window,
7768 initial_argv, initial_argc);
7769 else if (f)
7770 XSetCommand (FRAME_X_DISPLAY (f),
7771 event->xclient.window,
7772 0, 0);
7774 goto done;
7777 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_delete_window)
7779 f = any;
7780 if (!f)
7781 goto OTHER; /* May be a dialog that is to be removed */
7783 inev.ie.kind = DELETE_WINDOW_EVENT;
7784 XSETFRAME (inev.ie.frame_or_window, f);
7785 goto done;
7788 goto done;
7791 if (event->xclient.message_type == dpyinfo->Xatom_wm_configure_denied)
7792 goto done;
7794 if (event->xclient.message_type == dpyinfo->Xatom_wm_window_moved)
7796 int new_x, new_y;
7797 f = x_window_to_frame (dpyinfo, event->xclient.window);
7799 new_x = event->xclient.data.s[0];
7800 new_y = event->xclient.data.s[1];
7802 if (f)
7804 f->left_pos = new_x;
7805 f->top_pos = new_y;
7807 goto done;
7810 #ifdef X_TOOLKIT_EDITRES
7811 if (event->xclient.message_type == dpyinfo->Xatom_editres)
7813 f = any;
7814 if (f)
7815 _XEditResCheckMessages (f->output_data.x->widget,
7816 NULL, (XEvent *) event, NULL);
7817 goto done;
7819 #endif /* X_TOOLKIT_EDITRES */
7821 if (event->xclient.message_type == dpyinfo->Xatom_DONE
7822 || event->xclient.message_type == dpyinfo->Xatom_PAGE)
7824 /* Ghostview job completed. Kill it. We could
7825 reply with "Next" if we received "Page", but we
7826 currently never do because we are interested in
7827 images, only, which should have 1 page. */
7828 Pixmap pixmap = (Pixmap) event->xclient.data.l[1];
7829 f = x_window_to_frame (dpyinfo, event->xclient.window);
7830 if (!f)
7831 goto OTHER;
7832 x_kill_gs_process (pixmap, f);
7833 expose_frame (f, 0, 0, 0, 0);
7834 goto done;
7837 #ifdef USE_TOOLKIT_SCROLL_BARS
7838 /* Scroll bar callbacks send a ClientMessage from which
7839 we construct an input_event. */
7840 if (event->xclient.message_type == dpyinfo->Xatom_Scrollbar)
7842 x_scroll_bar_to_input_event (event, &inev.ie);
7843 *finish = X_EVENT_GOTO_OUT;
7844 goto done;
7846 else if (event->xclient.message_type == dpyinfo->Xatom_Horizontal_Scrollbar)
7848 x_horizontal_scroll_bar_to_input_event (event, &inev.ie);
7849 *finish = X_EVENT_GOTO_OUT;
7850 goto done;
7852 #endif /* USE_TOOLKIT_SCROLL_BARS */
7854 /* XEmbed messages from the embedder (if any). */
7855 if (event->xclient.message_type == dpyinfo->Xatom_XEMBED)
7857 enum xembed_message msg = event->xclient.data.l[1];
7858 if (msg == XEMBED_FOCUS_IN || msg == XEMBED_FOCUS_OUT)
7859 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
7861 *finish = X_EVENT_GOTO_OUT;
7862 goto done;
7865 xft_settings_event (dpyinfo, event);
7867 f = any;
7868 if (!f)
7869 goto OTHER;
7870 if (x_handle_dnd_message (f, &event->xclient, dpyinfo, &inev.ie))
7871 *finish = X_EVENT_DROP;
7873 break;
7875 case SelectionNotify:
7876 x_display_set_last_user_time (dpyinfo, event->xselection.time);
7877 #ifdef USE_X_TOOLKIT
7878 if (! x_window_to_frame (dpyinfo, event->xselection.requestor))
7879 goto OTHER;
7880 #endif /* not USE_X_TOOLKIT */
7881 x_handle_selection_notify (&event->xselection);
7882 break;
7884 case SelectionClear: /* Someone has grabbed ownership. */
7885 x_display_set_last_user_time (dpyinfo, event->xselectionclear.time);
7886 #ifdef USE_X_TOOLKIT
7887 if (! x_window_to_frame (dpyinfo, event->xselectionclear.window))
7888 goto OTHER;
7889 #endif /* USE_X_TOOLKIT */
7891 const XSelectionClearEvent *eventp = &event->xselectionclear;
7893 inev.sie.kind = SELECTION_CLEAR_EVENT;
7894 SELECTION_EVENT_DPYINFO (&inev.sie) = dpyinfo;
7895 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
7896 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
7898 break;
7900 case SelectionRequest: /* Someone wants our selection. */
7901 x_display_set_last_user_time (dpyinfo, event->xselectionrequest.time);
7902 #ifdef USE_X_TOOLKIT
7903 if (!x_window_to_frame (dpyinfo, event->xselectionrequest.owner))
7904 goto OTHER;
7905 #endif /* USE_X_TOOLKIT */
7907 const XSelectionRequestEvent *eventp = &event->xselectionrequest;
7909 inev.sie.kind = SELECTION_REQUEST_EVENT;
7910 SELECTION_EVENT_DPYINFO (&inev.sie) = dpyinfo;
7911 SELECTION_EVENT_REQUESTOR (&inev.sie) = eventp->requestor;
7912 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
7913 SELECTION_EVENT_TARGET (&inev.sie) = eventp->target;
7914 SELECTION_EVENT_PROPERTY (&inev.sie) = eventp->property;
7915 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
7917 break;
7919 case PropertyNotify:
7920 x_display_set_last_user_time (dpyinfo, event->xproperty.time);
7921 f = x_top_window_to_frame (dpyinfo, event->xproperty.window);
7922 if (f && event->xproperty.atom == dpyinfo->Xatom_net_wm_state)
7924 bool not_hidden = x_handle_net_wm_state (f, &event->xproperty);
7925 if (not_hidden && FRAME_ICONIFIED_P (f))
7927 /* Gnome shell does not iconify us when C-z is pressed.
7928 It hides the frame. So if our state says we aren't
7929 hidden anymore, treat it as deiconified. */
7930 SET_FRAME_VISIBLE (f, 1);
7931 SET_FRAME_ICONIFIED (f, false);
7932 f->output_data.x->has_been_visible = true;
7933 inev.ie.kind = DEICONIFY_EVENT;
7934 XSETFRAME (inev.ie.frame_or_window, f);
7936 else if (! not_hidden && ! FRAME_ICONIFIED_P (f))
7938 SET_FRAME_VISIBLE (f, 0);
7939 SET_FRAME_ICONIFIED (f, true);
7940 inev.ie.kind = ICONIFY_EVENT;
7941 XSETFRAME (inev.ie.frame_or_window, f);
7945 x_handle_property_notify (&event->xproperty);
7946 xft_settings_event (dpyinfo, event);
7947 goto OTHER;
7949 case ReparentNotify:
7950 f = x_top_window_to_frame (dpyinfo, event->xreparent.window);
7951 if (f)
7953 /* Maybe we shouldn't set this for child frames ?? */
7954 f->output_data.x->parent_desc = event->xreparent.parent;
7955 if (!FRAME_PARENT_FRAME (f))
7956 x_real_positions (f, &f->left_pos, &f->top_pos);
7957 else
7959 Window root;
7960 unsigned int dummy_uint;
7962 block_input ();
7963 XGetGeometry (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
7964 &root, &f->left_pos, &f->top_pos,
7965 &dummy_uint, &dummy_uint, &dummy_uint, &dummy_uint);
7966 unblock_input ();
7969 /* Perhaps reparented due to a WM restart. Reset this. */
7970 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_UNKNOWN;
7971 FRAME_DISPLAY_INFO (f)->net_supported_window = 0;
7973 x_set_frame_alpha (f);
7975 goto OTHER;
7977 case Expose:
7978 f = x_window_to_frame (dpyinfo, event->xexpose.window);
7979 if (f)
7981 if (!FRAME_VISIBLE_P (f))
7983 block_input ();
7984 SET_FRAME_VISIBLE (f, 1);
7985 SET_FRAME_ICONIFIED (f, false);
7986 if (FRAME_X_DOUBLE_BUFFERED_P (f))
7987 font_drop_xrender_surfaces (f);
7988 f->output_data.x->has_been_visible = true;
7989 SET_FRAME_GARBAGED (f);
7990 unblock_input ();
7992 else if (FRAME_GARBAGED_P (f))
7994 #ifdef USE_GTK
7995 /* Go around the back buffer and manually clear the
7996 window the first time we show it. This way, we avoid
7997 showing users the sanity-defying horror of whatever
7998 GtkWindow is rendering beneath us. We've garbaged
7999 the frame, so we'll redraw the whole thing on next
8000 redisplay anyway. Yuck. */
8001 x_clear_area1 (
8002 FRAME_X_DISPLAY (f),
8003 FRAME_X_WINDOW (f),
8004 event->xexpose.x, event->xexpose.y,
8005 event->xexpose.width, event->xexpose.height,
8007 x_clear_under_internal_border (f);
8008 #endif
8012 if (!FRAME_GARBAGED_P (f))
8014 #ifdef USE_GTK
8015 /* This seems to be needed for GTK 2.6 and later, see
8016 https://debbugs.gnu.org/cgi/bugreport.cgi?bug=15398. */
8017 x_clear_area (f,
8018 event->xexpose.x, event->xexpose.y,
8019 event->xexpose.width, event->xexpose.height);
8020 #endif
8021 expose_frame (f, event->xexpose.x, event->xexpose.y,
8022 event->xexpose.width, event->xexpose.height);
8023 #ifdef USE_GTK
8024 x_clear_under_internal_border (f);
8025 #endif
8028 if (!FRAME_GARBAGED_P (f))
8029 show_back_buffer (f);
8031 else
8033 #ifndef USE_TOOLKIT_SCROLL_BARS
8034 struct scroll_bar *bar;
8035 #endif
8036 #if defined USE_LUCID
8037 /* Submenus of the Lucid menu bar aren't widgets
8038 themselves, so there's no way to dispatch events
8039 to them. Recognize this case separately. */
8041 Widget widget = x_window_to_menu_bar (event->xexpose.window);
8042 if (widget)
8043 xlwmenu_redisplay (widget);
8045 #endif /* USE_LUCID */
8047 #ifdef USE_TOOLKIT_SCROLL_BARS
8048 /* Dispatch event to the widget. */
8049 goto OTHER;
8050 #else /* not USE_TOOLKIT_SCROLL_BARS */
8051 bar = x_window_to_scroll_bar (event->xexpose.display,
8052 event->xexpose.window, 2);
8054 if (bar)
8055 x_scroll_bar_expose (bar, event);
8056 #ifdef USE_X_TOOLKIT
8057 else
8058 goto OTHER;
8059 #endif /* USE_X_TOOLKIT */
8060 #endif /* not USE_TOOLKIT_SCROLL_BARS */
8062 break;
8064 case GraphicsExpose: /* This occurs when an XCopyArea's
8065 source area was obscured or not
8066 available. */
8067 f = x_window_to_frame (dpyinfo, event->xgraphicsexpose.drawable);
8068 if (f)
8070 expose_frame (f, event->xgraphicsexpose.x,
8071 event->xgraphicsexpose.y,
8072 event->xgraphicsexpose.width,
8073 event->xgraphicsexpose.height);
8074 #ifdef USE_GTK
8075 x_clear_under_internal_border (f);
8076 #endif
8077 show_back_buffer (f);
8079 #ifdef USE_X_TOOLKIT
8080 else
8081 goto OTHER;
8082 #endif /* USE_X_TOOLKIT */
8083 break;
8085 case NoExpose: /* This occurs when an XCopyArea's
8086 source area was completely
8087 available. */
8088 break;
8090 case UnmapNotify:
8091 /* Redo the mouse-highlight after the tooltip has gone. */
8092 if (event->xunmap.window == tip_window)
8094 tip_window = 0;
8095 x_redo_mouse_highlight (dpyinfo);
8098 f = x_top_window_to_frame (dpyinfo, event->xunmap.window);
8099 if (f) /* F may no longer exist if
8100 the frame was deleted. */
8102 bool visible = FRAME_VISIBLE_P (f);
8103 /* While a frame is unmapped, display generation is
8104 disabled; you don't want to spend time updating a
8105 display that won't ever be seen. */
8106 SET_FRAME_VISIBLE (f, 0);
8107 /* We can't distinguish, from the event, whether the window
8108 has become iconified or invisible. So assume, if it
8109 was previously visible, than now it is iconified.
8110 But x_make_frame_invisible clears both
8111 the visible flag and the iconified flag;
8112 and that way, we know the window is not iconified now. */
8113 if (visible || FRAME_ICONIFIED_P (f))
8115 SET_FRAME_ICONIFIED (f, true);
8116 inev.ie.kind = ICONIFY_EVENT;
8117 XSETFRAME (inev.ie.frame_or_window, f);
8120 goto OTHER;
8122 case MapNotify:
8123 /* We use x_top_window_to_frame because map events can
8124 come for sub-windows and they don't mean that the
8125 frame is visible. */
8126 f = x_top_window_to_frame (dpyinfo, event->xmap.window);
8127 if (f)
8129 bool iconified = FRAME_ICONIFIED_P (f);
8131 /* Check if fullscreen was specified before we where mapped the
8132 first time, i.e. from the command line. */
8133 if (!f->output_data.x->has_been_visible)
8136 x_check_fullscreen (f);
8137 #ifndef USE_GTK
8138 /* For systems that cannot synthesize `skip_taskbar' for
8139 unmapped windows do the following. */
8140 if (FRAME_SKIP_TASKBAR (f))
8141 x_set_skip_taskbar (f, Qt, Qnil);
8142 #endif /* Not USE_GTK */
8145 if (!iconified)
8147 /* The `z-group' is reset every time a frame becomes
8148 invisible. Handle this here. */
8149 if (FRAME_Z_GROUP (f) == z_group_above)
8150 x_set_z_group (f, Qabove, Qnil);
8151 else if (FRAME_Z_GROUP (f) == z_group_below)
8152 x_set_z_group (f, Qbelow, Qnil);
8155 SET_FRAME_VISIBLE (f, 1);
8156 SET_FRAME_ICONIFIED (f, false);
8157 f->output_data.x->has_been_visible = true;
8159 if (iconified)
8161 inev.ie.kind = DEICONIFY_EVENT;
8162 XSETFRAME (inev.ie.frame_or_window, f);
8164 else if (! NILP (Vframe_list) && ! NILP (XCDR (Vframe_list)))
8165 /* Force a redisplay sooner or later to update the
8166 frame titles in case this is the second frame. */
8167 record_asynch_buffer_change ();
8169 goto OTHER;
8171 case KeyPress:
8173 x_display_set_last_user_time (dpyinfo, event->xkey.time);
8174 ignore_next_mouse_click_timeout = 0;
8176 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
8177 /* Dispatch KeyPress events when in menu. */
8178 if (popup_activated ())
8179 goto OTHER;
8180 #endif
8182 f = any;
8184 /* If mouse-highlight is an integer, input clears out
8185 mouse highlighting. */
8186 if (!hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight)
8187 #if ! defined (USE_GTK)
8188 && (f == 0
8189 || !EQ (f->tool_bar_window, hlinfo->mouse_face_window))
8190 #endif
8193 clear_mouse_face (hlinfo);
8194 hlinfo->mouse_face_hidden = true;
8197 #if defined USE_MOTIF && defined USE_TOOLKIT_SCROLL_BARS
8198 if (f == 0)
8200 /* Scroll bars consume key events, but we want
8201 the keys to go to the scroll bar's frame. */
8202 Widget widget = XtWindowToWidget (dpyinfo->display,
8203 event->xkey.window);
8204 if (widget && XmIsScrollBar (widget))
8206 widget = XtParent (widget);
8207 f = x_any_window_to_frame (dpyinfo, XtWindow (widget));
8210 #endif /* USE_MOTIF and USE_TOOLKIT_SCROLL_BARS */
8212 if (f != 0)
8214 KeySym keysym, orig_keysym;
8215 /* al%imercury@uunet.uu.net says that making this 81
8216 instead of 80 fixed a bug whereby meta chars made
8217 his Emacs hang.
8219 It seems that some version of XmbLookupString has
8220 a bug of not returning XBufferOverflow in
8221 status_return even if the input is too long to
8222 fit in 81 bytes. So, we must prepare sufficient
8223 bytes for copy_buffer. 513 bytes (256 chars for
8224 two-byte character set) seems to be a fairly good
8225 approximation. -- 2000.8.10 handa@etl.go.jp */
8226 unsigned char copy_buffer[513];
8227 unsigned char *copy_bufptr = copy_buffer;
8228 int copy_bufsiz = sizeof (copy_buffer);
8229 int modifiers;
8230 Lisp_Object coding_system = Qlatin_1;
8231 Lisp_Object c;
8232 /* Event will be modified. */
8233 XKeyEvent xkey = event->xkey;
8235 #ifdef USE_GTK
8236 /* Don't pass keys to GTK. A Tab will shift focus to the
8237 tool bar in GTK 2.4. Keys will still go to menus and
8238 dialogs because in that case popup_activated is nonzero
8239 (see above). */
8240 *finish = X_EVENT_DROP;
8241 #endif
8243 xkey.state |= x_emacs_to_x_modifiers (FRAME_DISPLAY_INFO (f),
8244 extra_keyboard_modifiers);
8245 modifiers = xkey.state;
8247 /* This will have to go some day... */
8249 /* make_lispy_event turns chars into control chars.
8250 Don't do it here because XLookupString is too eager. */
8251 xkey.state &= ~ControlMask;
8252 xkey.state &= ~(dpyinfo->meta_mod_mask
8253 | dpyinfo->super_mod_mask
8254 | dpyinfo->hyper_mod_mask
8255 | dpyinfo->alt_mod_mask);
8257 /* In case Meta is ComposeCharacter,
8258 clear its status. According to Markus Ehrnsperger
8259 Markus.Ehrnsperger@lehrstuhl-bross.physik.uni-muenchen.de
8260 this enables ComposeCharacter to work whether or
8261 not it is combined with Meta. */
8262 if (modifiers & dpyinfo->meta_mod_mask)
8263 memset (&compose_status, 0, sizeof (compose_status));
8265 #ifdef HAVE_X_I18N
8266 if (FRAME_XIC (f))
8268 Status status_return;
8270 coding_system = Vlocale_coding_system;
8271 nbytes = XmbLookupString (FRAME_XIC (f),
8272 &xkey, (char *) copy_bufptr,
8273 copy_bufsiz, &keysym,
8274 &status_return);
8275 if (status_return == XBufferOverflow)
8277 copy_bufsiz = nbytes + 1;
8278 copy_bufptr = alloca (copy_bufsiz);
8279 nbytes = XmbLookupString (FRAME_XIC (f),
8280 &xkey, (char *) copy_bufptr,
8281 copy_bufsiz, &keysym,
8282 &status_return);
8284 /* Xutf8LookupString is a new but already deprecated interface. -stef */
8285 if (status_return == XLookupNone)
8286 break;
8287 else if (status_return == XLookupChars)
8289 keysym = NoSymbol;
8290 modifiers = 0;
8292 else if (status_return != XLookupKeySym
8293 && status_return != XLookupBoth)
8294 emacs_abort ();
8296 else
8297 nbytes = XLookupString (&xkey, (char *) copy_bufptr,
8298 copy_bufsiz, &keysym,
8299 &compose_status);
8300 #else
8301 nbytes = XLookupString (&xkey, (char *) copy_bufptr,
8302 copy_bufsiz, &keysym,
8303 &compose_status);
8304 #endif
8306 /* If not using XIM/XIC, and a compose sequence is in progress,
8307 we break here. Otherwise, chars_matched is always 0. */
8308 if (compose_status.chars_matched > 0 && nbytes == 0)
8309 break;
8311 memset (&compose_status, 0, sizeof (compose_status));
8312 orig_keysym = keysym;
8314 /* Common for all keysym input events. */
8315 XSETFRAME (inev.ie.frame_or_window, f);
8316 inev.ie.modifiers
8317 = x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO (f), modifiers);
8318 inev.ie.timestamp = xkey.time;
8320 /* First deal with keysyms which have defined
8321 translations to characters. */
8322 if (keysym >= 32 && keysym < 128)
8323 /* Avoid explicitly decoding each ASCII character. */
8325 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
8326 inev.ie.code = keysym;
8327 goto done_keysym;
8330 /* Keysyms directly mapped to Unicode characters. */
8331 if (keysym >= 0x01000000 && keysym <= 0x0110FFFF)
8333 if (keysym < 0x01000080)
8334 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
8335 else
8336 inev.ie.kind = MULTIBYTE_CHAR_KEYSTROKE_EVENT;
8337 inev.ie.code = keysym & 0xFFFFFF;
8338 goto done_keysym;
8341 /* Now non-ASCII. */
8342 if (HASH_TABLE_P (Vx_keysym_table)
8343 && (c = Fgethash (make_number (keysym),
8344 Vx_keysym_table,
8345 Qnil),
8346 NATNUMP (c)))
8348 inev.ie.kind = (SINGLE_BYTE_CHAR_P (XFASTINT (c))
8349 ? ASCII_KEYSTROKE_EVENT
8350 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
8351 inev.ie.code = XFASTINT (c);
8352 goto done_keysym;
8355 /* Random non-modifier sorts of keysyms. */
8356 if (((keysym >= XK_BackSpace && keysym <= XK_Escape)
8357 || keysym == XK_Delete
8358 #ifdef XK_ISO_Left_Tab
8359 || (keysym >= XK_ISO_Left_Tab
8360 && keysym <= XK_ISO_Enter)
8361 #endif
8362 || IsCursorKey (keysym) /* 0xff50 <= x < 0xff60 */
8363 || IsMiscFunctionKey (keysym) /* 0xff60 <= x < VARIES */
8364 #ifdef HPUX
8365 /* This recognizes the "extended function
8366 keys". It seems there's no cleaner way.
8367 Test IsModifierKey to avoid handling
8368 mode_switch incorrectly. */
8369 || (XK_Select <= keysym && keysym < XK_KP_Space)
8370 #endif
8371 #ifdef XK_dead_circumflex
8372 || orig_keysym == XK_dead_circumflex
8373 #endif
8374 #ifdef XK_dead_grave
8375 || orig_keysym == XK_dead_grave
8376 #endif
8377 #ifdef XK_dead_tilde
8378 || orig_keysym == XK_dead_tilde
8379 #endif
8380 #ifdef XK_dead_diaeresis
8381 || orig_keysym == XK_dead_diaeresis
8382 #endif
8383 #ifdef XK_dead_macron
8384 || orig_keysym == XK_dead_macron
8385 #endif
8386 #ifdef XK_dead_degree
8387 || orig_keysym == XK_dead_degree
8388 #endif
8389 #ifdef XK_dead_acute
8390 || orig_keysym == XK_dead_acute
8391 #endif
8392 #ifdef XK_dead_cedilla
8393 || orig_keysym == XK_dead_cedilla
8394 #endif
8395 #ifdef XK_dead_breve
8396 || orig_keysym == XK_dead_breve
8397 #endif
8398 #ifdef XK_dead_ogonek
8399 || orig_keysym == XK_dead_ogonek
8400 #endif
8401 #ifdef XK_dead_caron
8402 || orig_keysym == XK_dead_caron
8403 #endif
8404 #ifdef XK_dead_doubleacute
8405 || orig_keysym == XK_dead_doubleacute
8406 #endif
8407 #ifdef XK_dead_abovedot
8408 || orig_keysym == XK_dead_abovedot
8409 #endif
8410 || IsKeypadKey (keysym) /* 0xff80 <= x < 0xffbe */
8411 || IsFunctionKey (keysym) /* 0xffbe <= x < 0xffe1 */
8412 /* Any "vendor-specific" key is ok. */
8413 || (orig_keysym & (1 << 28))
8414 || (keysym != NoSymbol && nbytes == 0))
8415 && ! (IsModifierKey (orig_keysym)
8416 /* The symbols from XK_ISO_Lock
8417 to XK_ISO_Last_Group_Lock
8418 don't have real modifiers but
8419 should be treated similarly to
8420 Mode_switch by Emacs. */
8421 #if defined XK_ISO_Lock && defined XK_ISO_Last_Group_Lock
8422 || (XK_ISO_Lock <= orig_keysym
8423 && orig_keysym <= XK_ISO_Last_Group_Lock)
8424 #endif
8427 STORE_KEYSYM_FOR_DEBUG (keysym);
8428 /* make_lispy_event will convert this to a symbolic
8429 key. */
8430 inev.ie.kind = NON_ASCII_KEYSTROKE_EVENT;
8431 inev.ie.code = keysym;
8432 goto done_keysym;
8435 { /* Raw bytes, not keysym. */
8436 ptrdiff_t i;
8437 int nchars, len;
8439 for (i = 0, nchars = 0; i < nbytes; i++)
8441 if (ASCII_CHAR_P (copy_bufptr[i]))
8442 nchars++;
8443 STORE_KEYSYM_FOR_DEBUG (copy_bufptr[i]);
8446 if (nchars < nbytes)
8448 /* Decode the input data. */
8450 /* The input should be decoded with `coding_system'
8451 which depends on which X*LookupString function
8452 we used just above and the locale. */
8453 setup_coding_system (coding_system, &coding);
8454 coding.src_multibyte = false;
8455 coding.dst_multibyte = true;
8456 /* The input is converted to events, thus we can't
8457 handle composition. Anyway, there's no XIM that
8458 gives us composition information. */
8459 coding.common_flags &= ~CODING_ANNOTATION_MASK;
8461 SAFE_NALLOCA (coding.destination, MAX_MULTIBYTE_LENGTH,
8462 nbytes);
8463 coding.dst_bytes = MAX_MULTIBYTE_LENGTH * nbytes;
8464 coding.mode |= CODING_MODE_LAST_BLOCK;
8465 decode_coding_c_string (&coding, copy_bufptr, nbytes, Qnil);
8466 nbytes = coding.produced;
8467 nchars = coding.produced_char;
8468 copy_bufptr = coding.destination;
8471 /* Convert the input data to a sequence of
8472 character events. */
8473 for (i = 0; i < nbytes; i += len)
8475 int ch;
8476 if (nchars == nbytes)
8477 ch = copy_bufptr[i], len = 1;
8478 else
8479 ch = STRING_CHAR_AND_LENGTH (copy_bufptr + i, len);
8480 inev.ie.kind = (SINGLE_BYTE_CHAR_P (ch)
8481 ? ASCII_KEYSTROKE_EVENT
8482 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
8483 inev.ie.code = ch;
8484 kbd_buffer_store_buffered_event (&inev, hold_quit);
8487 count += nchars;
8489 inev.ie.kind = NO_EVENT; /* Already stored above. */
8491 if (keysym == NoSymbol)
8492 break;
8494 /* FIXME: check side effects and remove this. */
8495 ((XEvent *) event)->xkey = xkey;
8497 done_keysym:
8498 #ifdef HAVE_X_I18N
8499 /* Don't dispatch this event since XtDispatchEvent calls
8500 XFilterEvent, and two calls in a row may freeze the
8501 client. */
8502 break;
8503 #else
8504 goto OTHER;
8505 #endif
8507 case KeyRelease:
8508 x_display_set_last_user_time (dpyinfo, event->xkey.time);
8509 #ifdef HAVE_X_I18N
8510 /* Don't dispatch this event since XtDispatchEvent calls
8511 XFilterEvent, and two calls in a row may freeze the
8512 client. */
8513 break;
8514 #else
8515 goto OTHER;
8516 #endif
8518 case EnterNotify:
8519 x_display_set_last_user_time (dpyinfo, event->xcrossing.time);
8520 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
8522 f = any;
8524 if (f && x_mouse_click_focus_ignore_position)
8525 ignore_next_mouse_click_timeout = event->xmotion.time + 200;
8527 /* EnterNotify counts as mouse movement,
8528 so update things that depend on mouse position. */
8529 if (f && !f->output_data.x->hourglass_p)
8530 note_mouse_movement (f, &event->xmotion);
8531 #ifdef USE_GTK
8532 /* We may get an EnterNotify on the buttons in the toolbar. In that
8533 case we moved out of any highlighted area and need to note this. */
8534 if (!f && dpyinfo->last_mouse_glyph_frame)
8535 note_mouse_movement (dpyinfo->last_mouse_glyph_frame, &event->xmotion);
8536 #endif
8537 goto OTHER;
8539 case FocusIn:
8540 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
8541 goto OTHER;
8543 case LeaveNotify:
8544 x_display_set_last_user_time (dpyinfo, event->xcrossing.time);
8545 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
8547 f = x_top_window_to_frame (dpyinfo, event->xcrossing.window);
8548 if (f)
8550 if (f == hlinfo->mouse_face_mouse_frame)
8552 /* If we move outside the frame, then we're
8553 certainly no longer on any text in the frame. */
8554 clear_mouse_face (hlinfo);
8555 hlinfo->mouse_face_mouse_frame = 0;
8558 /* Generate a nil HELP_EVENT to cancel a help-echo.
8559 Do it only if there's something to cancel.
8560 Otherwise, the startup message is cleared when
8561 the mouse leaves the frame. */
8562 if (any_help_event_p)
8563 do_help = -1;
8565 #ifdef USE_GTK
8566 /* See comment in EnterNotify above */
8567 else if (dpyinfo->last_mouse_glyph_frame)
8568 note_mouse_movement (dpyinfo->last_mouse_glyph_frame, &event->xmotion);
8569 #endif
8570 goto OTHER;
8572 case FocusOut:
8573 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
8574 goto OTHER;
8576 case MotionNotify:
8578 x_display_set_last_user_time (dpyinfo, event->xmotion.time);
8579 previous_help_echo_string = help_echo_string;
8580 help_echo_string = Qnil;
8582 f = (x_mouse_grabbed (dpyinfo) ? dpyinfo->last_mouse_frame
8583 : x_window_to_frame (dpyinfo, event->xmotion.window));
8585 if (hlinfo->mouse_face_hidden)
8587 hlinfo->mouse_face_hidden = false;
8588 clear_mouse_face (hlinfo);
8591 #ifdef USE_GTK
8592 if (f && xg_event_is_for_scrollbar (f, event))
8593 f = 0;
8594 #endif
8595 if (f)
8597 /* Maybe generate a SELECT_WINDOW_EVENT for
8598 `mouse-autoselect-window' but don't let popup menus
8599 interfere with this (Bug#1261). */
8600 if (!NILP (Vmouse_autoselect_window)
8601 && !popup_activated ()
8602 /* Don't switch if we're currently in the minibuffer.
8603 This tries to work around problems where the
8604 minibuffer gets unselected unexpectedly, and where
8605 you then have to move your mouse all the way down to
8606 the minibuffer to select it. */
8607 && !MINI_WINDOW_P (XWINDOW (selected_window))
8608 /* With `focus-follows-mouse' non-nil create an event
8609 also when the target window is on another frame. */
8610 && (f == XFRAME (selected_frame)
8611 || !NILP (focus_follows_mouse)))
8613 static Lisp_Object last_mouse_window;
8614 Lisp_Object window = window_from_coordinates
8615 (f, event->xmotion.x, event->xmotion.y, 0, false);
8617 /* A window will be autoselected only when it is not
8618 selected now and the last mouse movement event was
8619 not in it. The remainder of the code is a bit vague
8620 wrt what a "window" is. For immediate autoselection,
8621 the window is usually the entire window but for GTK
8622 where the scroll bars don't count. For delayed
8623 autoselection the window is usually the window's text
8624 area including the margins. */
8625 if (WINDOWP (window)
8626 && !EQ (window, last_mouse_window)
8627 && !EQ (window, selected_window))
8629 inev.ie.kind = SELECT_WINDOW_EVENT;
8630 inev.ie.frame_or_window = window;
8633 /* Remember the last window where we saw the mouse. */
8634 last_mouse_window = window;
8637 if (!note_mouse_movement (f, &event->xmotion))
8638 help_echo_string = previous_help_echo_string;
8640 else
8642 #ifndef USE_TOOLKIT_SCROLL_BARS
8643 struct scroll_bar *bar
8644 = x_window_to_scroll_bar (event->xmotion.display,
8645 event->xmotion.window, 2);
8647 if (bar)
8648 x_scroll_bar_note_movement (bar, &event->xmotion);
8649 #endif /* USE_TOOLKIT_SCROLL_BARS */
8651 /* If we move outside the frame, then we're
8652 certainly no longer on any text in the frame. */
8653 clear_mouse_face (hlinfo);
8656 /* If the contents of the global variable help_echo_string
8657 has changed, generate a HELP_EVENT. */
8658 if (!NILP (help_echo_string)
8659 || !NILP (previous_help_echo_string))
8660 do_help = 1;
8661 goto OTHER;
8664 case ConfigureNotify:
8665 /* An opaque move can generate a stream of events as the window
8666 is dragged around. If the connection round trip time isn't
8667 really short, they may come faster than we can respond to
8668 them, given the multiple queries we can do to check window
8669 manager state, translate coordinates, etc.
8671 So if this ConfigureNotify is immediately followed by another
8672 for the same window, use the info from the latest update, and
8673 consider the events all handled. */
8674 /* Opaque resize may be trickier; ConfigureNotify events are
8675 mixed with Expose events for multiple windows. */
8676 configureEvent = *event;
8677 while (XPending (dpyinfo->display))
8679 XNextEvent (dpyinfo->display, &next_event);
8680 if (next_event.type != ConfigureNotify
8681 || next_event.xconfigure.window != event->xconfigure.window
8682 /* Skipping events with different sizes can lead to a
8683 mispositioned mode line at initial window creation.
8684 Only drop window motion events for now. */
8685 || next_event.xconfigure.width != event->xconfigure.width
8686 || next_event.xconfigure.height != event->xconfigure.height)
8688 XPutBackEvent (dpyinfo->display, &next_event);
8689 break;
8691 else
8692 configureEvent = next_event;
8695 f = x_top_window_to_frame (dpyinfo, configureEvent.xconfigure.window);
8696 /* Unfortunately, we need to call font_drop_xrender_surfaces for
8697 _all_ ConfigureNotify events, otherwise we miss some and
8698 flicker. Don't try to optimize these calls by looking only
8699 for size changes: that's not sufficient. We miss some
8700 surface invalidations and flicker. */
8701 block_input ();
8702 if (f && FRAME_X_DOUBLE_BUFFERED_P (f))
8703 font_drop_xrender_surfaces (f);
8704 unblock_input ();
8705 #ifdef USE_CAIRO
8706 if (f) x_cr_destroy_surface (f);
8707 #endif
8708 #ifdef USE_GTK
8709 if (!f
8710 && (f = any)
8711 && configureEvent.xconfigure.window == FRAME_X_WINDOW (f))
8713 block_input ();
8714 if (FRAME_X_DOUBLE_BUFFERED_P (f))
8715 font_drop_xrender_surfaces (f);
8716 unblock_input ();
8717 xg_frame_resized (f, configureEvent.xconfigure.width,
8718 configureEvent.xconfigure.height);
8719 #ifdef USE_CAIRO
8720 x_cr_destroy_surface (f);
8721 #endif
8722 f = 0;
8724 #endif
8725 if (f)
8727 #ifdef USE_GTK
8728 /* For GTK+ don't call x_net_wm_state for the scroll bar
8729 window. (Bug#24963, Bug#25887) */
8730 if (configureEvent.xconfigure.window == FRAME_X_WINDOW (f))
8731 #endif
8732 x_net_wm_state (f, configureEvent.xconfigure.window);
8734 #ifdef USE_X_TOOLKIT
8735 /* Tip frames are pure X window, set size for them. */
8736 if (! NILP (tip_frame) && XFRAME (tip_frame) == f)
8738 if (FRAME_PIXEL_HEIGHT (f) != configureEvent.xconfigure.height
8739 || FRAME_PIXEL_WIDTH (f) != configureEvent.xconfigure.width)
8741 SET_FRAME_GARBAGED (f);
8743 FRAME_PIXEL_HEIGHT (f) = configureEvent.xconfigure.height;
8744 FRAME_PIXEL_WIDTH (f) = configureEvent.xconfigure.width;
8746 #endif
8748 #ifndef USE_X_TOOLKIT
8749 #ifndef USE_GTK
8750 int width =
8751 FRAME_PIXEL_TO_TEXT_WIDTH (f, configureEvent.xconfigure.width);
8752 int height =
8753 FRAME_PIXEL_TO_TEXT_HEIGHT (f, configureEvent.xconfigure.height);
8755 /* In the toolkit version, change_frame_size
8756 is called by the code that handles resizing
8757 of the EmacsFrame widget. */
8759 /* Even if the number of character rows and columns has
8760 not changed, the font size may have changed, so we need
8761 to check the pixel dimensions as well. */
8762 if (width != FRAME_TEXT_WIDTH (f)
8763 || height != FRAME_TEXT_HEIGHT (f)
8764 || configureEvent.xconfigure.width != FRAME_PIXEL_WIDTH (f)
8765 || configureEvent.xconfigure.height != FRAME_PIXEL_HEIGHT (f))
8767 change_frame_size (f, width, height, false, true, false, true);
8768 x_clear_under_internal_border (f);
8769 SET_FRAME_GARBAGED (f);
8770 cancel_mouse_face (f);
8772 #endif /* not USE_GTK */
8773 #endif
8775 #ifdef USE_GTK
8776 /* GTK creates windows but doesn't map them.
8777 Only get real positions when mapped. */
8778 if (FRAME_GTK_OUTER_WIDGET (f)
8779 && gtk_widget_get_mapped (FRAME_GTK_OUTER_WIDGET (f)))
8780 #endif
8782 int old_left = f->left_pos;
8783 int old_top = f->top_pos;
8784 Lisp_Object frame = Qnil;
8786 XSETFRAME (frame, f);
8788 if (!FRAME_PARENT_FRAME (f))
8789 x_real_positions (f, &f->left_pos, &f->top_pos);
8790 else
8792 Window root;
8793 unsigned int dummy_uint;
8795 block_input ();
8796 XGetGeometry (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8797 &root, &f->left_pos, &f->top_pos,
8798 &dummy_uint, &dummy_uint, &dummy_uint, &dummy_uint);
8799 unblock_input ();
8802 if (old_left != f->left_pos || old_top != f->top_pos)
8804 inev.ie.kind = MOVE_FRAME_EVENT;
8805 XSETFRAME (inev.ie.frame_or_window, f);
8810 #ifdef HAVE_X_I18N
8811 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMStatusArea))
8812 xic_set_statusarea (f);
8813 #endif
8816 goto OTHER;
8818 case ButtonRelease:
8819 case ButtonPress:
8821 /* If we decide we want to generate an event to be seen
8822 by the rest of Emacs, we put it here. */
8823 bool tool_bar_p = false;
8825 memset (&compose_status, 0, sizeof (compose_status));
8826 dpyinfo->last_mouse_glyph_frame = NULL;
8827 x_display_set_last_user_time (dpyinfo, event->xbutton.time);
8829 if (x_mouse_grabbed (dpyinfo))
8830 f = dpyinfo->last_mouse_frame;
8831 else
8833 f = x_window_to_frame (dpyinfo, event->xbutton.window);
8835 if (f && event->xbutton.type == ButtonPress
8836 && !popup_activated ()
8837 && !x_window_to_scroll_bar (event->xbutton.display,
8838 event->xbutton.window, 2)
8839 && !FRAME_NO_ACCEPT_FOCUS (f))
8841 /* When clicking into a child frame or when clicking
8842 into a parent frame with the child frame selected and
8843 `no-accept-focus' is not set, select the clicked
8844 frame. */
8845 struct frame *hf = dpyinfo->x_highlight_frame;
8847 if (FRAME_PARENT_FRAME (f) || (hf && frame_ancestor_p (f, hf)))
8849 block_input ();
8850 XSetInputFocus (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8851 RevertToParent, CurrentTime);
8852 if (FRAME_PARENT_FRAME (f))
8853 XRaiseWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
8854 unblock_input ();
8859 #ifdef USE_GTK
8860 if (f && xg_event_is_for_scrollbar (f, event))
8861 f = 0;
8862 #endif
8863 if (f)
8865 #if ! defined (USE_GTK)
8866 /* Is this in the tool-bar? */
8867 if (WINDOWP (f->tool_bar_window)
8868 && WINDOW_TOTAL_LINES (XWINDOW (f->tool_bar_window)))
8870 Lisp_Object window;
8871 int x = event->xbutton.x;
8872 int y = event->xbutton.y;
8874 window = window_from_coordinates (f, x, y, 0, true);
8875 tool_bar_p = EQ (window, f->tool_bar_window);
8877 if (tool_bar_p && event->xbutton.button < 4)
8878 handle_tool_bar_click
8879 (f, x, y, event->xbutton.type == ButtonPress,
8880 x_x_to_emacs_modifiers (dpyinfo, event->xbutton.state));
8882 #endif /* !USE_GTK */
8884 if (!tool_bar_p)
8885 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
8886 if (! popup_activated ())
8887 #endif
8889 if (ignore_next_mouse_click_timeout)
8891 if (event->type == ButtonPress
8892 && event->xbutton.time > ignore_next_mouse_click_timeout)
8894 ignore_next_mouse_click_timeout = 0;
8895 construct_mouse_click (&inev.ie, &event->xbutton, f);
8897 if (event->type == ButtonRelease)
8898 ignore_next_mouse_click_timeout = 0;
8900 else
8901 construct_mouse_click (&inev.ie, &event->xbutton, f);
8903 if (FRAME_X_EMBEDDED_P (f))
8904 xembed_send_message (f, event->xbutton.time,
8905 XEMBED_REQUEST_FOCUS, 0, 0, 0);
8907 else
8909 struct scroll_bar *bar
8910 = x_window_to_scroll_bar (event->xbutton.display,
8911 event->xbutton.window, 2);
8913 #ifdef USE_TOOLKIT_SCROLL_BARS
8914 /* Make the "Ctrl-Mouse-2 splits window" work for toolkit
8915 scroll bars. */
8916 if (bar && event->xbutton.state & ControlMask)
8918 x_scroll_bar_handle_click (bar, event, &inev.ie);
8919 *finish = X_EVENT_DROP;
8921 #else /* not USE_TOOLKIT_SCROLL_BARS */
8922 if (bar)
8923 x_scroll_bar_handle_click (bar, event, &inev.ie);
8924 #endif /* not USE_TOOLKIT_SCROLL_BARS */
8927 if (event->type == ButtonPress)
8929 dpyinfo->grabbed |= (1 << event->xbutton.button);
8930 dpyinfo->last_mouse_frame = f;
8931 #if ! defined (USE_GTK)
8932 if (f && !tool_bar_p)
8933 f->last_tool_bar_item = -1;
8934 #endif /* not USE_GTK */
8936 else
8937 dpyinfo->grabbed &= ~(1 << event->xbutton.button);
8939 /* Ignore any mouse motion that happened before this event;
8940 any subsequent mouse-movement Emacs events should reflect
8941 only motion after the ButtonPress/Release. */
8942 if (f != 0)
8943 f->mouse_moved = false;
8945 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
8946 f = x_menubar_window_to_frame (dpyinfo, event);
8947 /* For a down-event in the menu bar,
8948 don't pass it to Xt right now.
8949 Instead, save it away
8950 and we will pass it to Xt from kbd_buffer_get_event.
8951 That way, we can run some Lisp code first. */
8952 if (! popup_activated ()
8953 #ifdef USE_GTK
8954 /* Gtk+ menus only react to the first three buttons. */
8955 && event->xbutton.button < 3
8956 #endif
8957 && f && event->type == ButtonPress
8958 /* Verify the event is really within the menu bar
8959 and not just sent to it due to grabbing. */
8960 && event->xbutton.x >= 0
8961 && event->xbutton.x < FRAME_PIXEL_WIDTH (f)
8962 && event->xbutton.y >= 0
8963 && event->xbutton.y < FRAME_MENUBAR_HEIGHT (f)
8964 && event->xbutton.same_screen)
8966 if (!f->output_data.x->saved_menu_event)
8967 f->output_data.x->saved_menu_event = xmalloc (sizeof *event);
8968 *f->output_data.x->saved_menu_event = *event;
8969 inev.ie.kind = MENU_BAR_ACTIVATE_EVENT;
8970 XSETFRAME (inev.ie.frame_or_window, f);
8971 *finish = X_EVENT_DROP;
8973 else
8974 goto OTHER;
8975 #endif /* USE_X_TOOLKIT || USE_GTK */
8977 break;
8979 case CirculateNotify:
8980 goto OTHER;
8982 case CirculateRequest:
8983 goto OTHER;
8985 case VisibilityNotify:
8986 goto OTHER;
8988 case MappingNotify:
8989 /* Someone has changed the keyboard mapping - update the
8990 local cache. */
8991 switch (event->xmapping.request)
8993 case MappingModifier:
8994 x_find_modifier_meanings (dpyinfo);
8995 FALLTHROUGH;
8996 case MappingKeyboard:
8997 XRefreshKeyboardMapping ((XMappingEvent *) &event->xmapping);
8999 goto OTHER;
9001 case DestroyNotify:
9002 xft_settings_event (dpyinfo, event);
9003 break;
9005 default:
9006 OTHER:
9007 #ifdef USE_X_TOOLKIT
9008 block_input ();
9009 if (*finish != X_EVENT_DROP)
9010 XtDispatchEvent ((XEvent *) event);
9011 unblock_input ();
9012 #endif /* USE_X_TOOLKIT */
9013 break;
9016 done:
9017 if (inev.ie.kind != NO_EVENT)
9019 kbd_buffer_store_buffered_event (&inev, hold_quit);
9020 count++;
9023 if (do_help
9024 && !(hold_quit && hold_quit->kind != NO_EVENT))
9026 Lisp_Object frame;
9028 if (f)
9029 XSETFRAME (frame, f);
9030 else
9031 frame = Qnil;
9033 if (do_help > 0)
9035 any_help_event_p = true;
9036 gen_help_event (help_echo_string, frame, help_echo_window,
9037 help_echo_object, help_echo_pos);
9039 else
9041 help_echo_string = Qnil;
9042 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
9044 count++;
9047 /* Sometimes event processing draws to the frame outside redisplay.
9048 To ensure that these changes become visible, draw them here. */
9049 flush_dirty_back_buffers ();
9050 SAFE_FREE ();
9051 return count;
9054 #if defined USE_X_TOOLKIT || defined USE_MOTIF || defined USE_GTK
9056 /* Handles the XEvent EVENT on display DISPLAY.
9057 This is used for event loops outside the normal event handling,
9058 i.e. looping while a popup menu or a dialog is posted.
9060 Returns the value handle_one_xevent sets in the finish argument. */
9062 x_dispatch_event (XEvent *event, Display *display)
9064 struct x_display_info *dpyinfo;
9065 int finish = X_EVENT_NORMAL;
9067 dpyinfo = x_display_info_for_display (display);
9069 if (dpyinfo)
9070 handle_one_xevent (dpyinfo, event, &finish, 0);
9072 return finish;
9074 #endif
9076 /* Read events coming from the X server.
9077 Return as soon as there are no more events to be read.
9079 Return the number of characters stored into the buffer,
9080 thus pretending to be `read' (except the characters we store
9081 in the keyboard buffer can be multibyte, so are not necessarily
9082 C chars). */
9084 static int
9085 XTread_socket (struct terminal *terminal, struct input_event *hold_quit)
9087 int count = 0;
9088 bool event_found = false;
9089 struct x_display_info *dpyinfo = terminal->display_info.x;
9091 block_input ();
9093 /* For debugging, this gives a way to fake an I/O error. */
9094 if (dpyinfo == XTread_socket_fake_io_error)
9096 XTread_socket_fake_io_error = 0;
9097 x_io_error_quitter (dpyinfo->display);
9100 #ifndef USE_GTK
9101 while (XPending (dpyinfo->display))
9103 int finish;
9104 XEvent event;
9106 XNextEvent (dpyinfo->display, &event);
9108 #ifdef HAVE_X_I18N
9109 /* Filter events for the current X input method. */
9110 if (x_filter_event (dpyinfo, &event))
9111 continue;
9112 #endif
9113 event_found = true;
9115 count += handle_one_xevent (dpyinfo, &event, &finish, hold_quit);
9117 if (finish == X_EVENT_GOTO_OUT)
9118 break;
9121 #else /* USE_GTK */
9123 /* For GTK we must use the GTK event loop. But XEvents gets passed
9124 to our filter function above, and then to the big event switch.
9125 We use a bunch of globals to communicate with our filter function,
9126 that is kind of ugly, but it works.
9128 There is no way to do one display at the time, GTK just does events
9129 from all displays. */
9131 while (gtk_events_pending ())
9133 current_count = count;
9134 current_hold_quit = hold_quit;
9136 gtk_main_iteration ();
9138 count = current_count;
9139 current_count = -1;
9140 current_hold_quit = 0;
9142 if (current_finish == X_EVENT_GOTO_OUT)
9143 break;
9145 #endif /* USE_GTK */
9147 /* On some systems, an X bug causes Emacs to get no more events
9148 when the window is destroyed. Detect that. (1994.) */
9149 if (! event_found)
9151 /* Emacs and the X Server eats up CPU time if XNoOp is done every time.
9152 One XNOOP in 100 loops will make Emacs terminate.
9153 B. Bretthauer, 1994 */
9154 x_noop_count++;
9155 if (x_noop_count >= 100)
9157 x_noop_count=0;
9159 if (next_noop_dpyinfo == 0)
9160 next_noop_dpyinfo = x_display_list;
9162 XNoOp (next_noop_dpyinfo->display);
9164 /* Each time we get here, cycle through the displays now open. */
9165 next_noop_dpyinfo = next_noop_dpyinfo->next;
9169 /* If the focus was just given to an auto-raising frame,
9170 raise it now. FIXME: handle more than one such frame. */
9171 if (dpyinfo->x_pending_autoraise_frame)
9173 x_raise_frame (dpyinfo->x_pending_autoraise_frame);
9174 dpyinfo->x_pending_autoraise_frame = NULL;
9177 unblock_input ();
9179 return count;
9185 /***********************************************************************
9186 Text Cursor
9187 ***********************************************************************/
9189 /* Set clipping for output in glyph row ROW. W is the window in which
9190 we operate. GC is the graphics context to set clipping in.
9192 ROW may be a text row or, e.g., a mode line. Text rows must be
9193 clipped to the interior of the window dedicated to text display,
9194 mode lines must be clipped to the whole window. */
9196 static void
9197 x_clip_to_row (struct window *w, struct glyph_row *row,
9198 enum glyph_row_area area, GC gc)
9200 struct frame *f = XFRAME (WINDOW_FRAME (w));
9201 XRectangle clip_rect;
9202 int window_x, window_y, window_width;
9204 window_box (w, area, &window_x, &window_y, &window_width, 0);
9206 clip_rect.x = window_x;
9207 clip_rect.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
9208 clip_rect.y = max (clip_rect.y, window_y);
9209 clip_rect.width = window_width;
9210 clip_rect.height = row->visible_height;
9212 x_set_clip_rectangles (f, gc, &clip_rect, 1);
9216 /* Draw a hollow box cursor on window W in glyph row ROW. */
9218 static void
9219 x_draw_hollow_cursor (struct window *w, struct glyph_row *row)
9221 struct frame *f = XFRAME (WINDOW_FRAME (w));
9222 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
9223 Display *dpy = FRAME_X_DISPLAY (f);
9224 int x, y, wd, h;
9225 XGCValues xgcv;
9226 struct glyph *cursor_glyph;
9227 GC gc;
9229 /* Get the glyph the cursor is on. If we can't tell because
9230 the current matrix is invalid or such, give up. */
9231 cursor_glyph = get_phys_cursor_glyph (w);
9232 if (cursor_glyph == NULL)
9233 return;
9235 /* Compute frame-relative coordinates for phys cursor. */
9236 get_phys_cursor_geometry (w, row, cursor_glyph, &x, &y, &h);
9237 wd = w->phys_cursor_width - 1;
9239 /* The foreground of cursor_gc is typically the same as the normal
9240 background color, which can cause the cursor box to be invisible. */
9241 xgcv.foreground = f->output_data.x->cursor_pixel;
9242 if (dpyinfo->scratch_cursor_gc)
9243 XChangeGC (dpy, dpyinfo->scratch_cursor_gc, GCForeground, &xgcv);
9244 else
9245 dpyinfo->scratch_cursor_gc = XCreateGC (dpy, FRAME_X_DRAWABLE (f),
9246 GCForeground, &xgcv);
9247 gc = dpyinfo->scratch_cursor_gc;
9249 /* When on R2L character, show cursor at the right edge of the
9250 glyph, unless the cursor box is as wide as the glyph or wider
9251 (the latter happens when x-stretch-cursor is non-nil). */
9252 if ((cursor_glyph->resolved_level & 1) != 0
9253 && cursor_glyph->pixel_width > wd)
9255 x += cursor_glyph->pixel_width - wd;
9256 if (wd > 0)
9257 wd -= 1;
9259 /* Set clipping, draw the rectangle, and reset clipping again. */
9260 x_clip_to_row (w, row, TEXT_AREA, gc);
9261 x_draw_rectangle (f, gc, x, y, wd, h - 1);
9262 x_reset_clip_rectangles (f, gc);
9266 /* Draw a bar cursor on window W in glyph row ROW.
9268 Implementation note: One would like to draw a bar cursor with an
9269 angle equal to the one given by the font property XA_ITALIC_ANGLE.
9270 Unfortunately, I didn't find a font yet that has this property set.
9271 --gerd. */
9273 static void
9274 x_draw_bar_cursor (struct window *w, struct glyph_row *row, int width, enum text_cursor_kinds kind)
9276 struct frame *f = XFRAME (w->frame);
9277 struct glyph *cursor_glyph;
9279 /* If cursor is out of bounds, don't draw garbage. This can happen
9280 in mini-buffer windows when switching between echo area glyphs
9281 and mini-buffer. */
9282 cursor_glyph = get_phys_cursor_glyph (w);
9283 if (cursor_glyph == NULL)
9284 return;
9286 /* Experimental avoidance of cursor on xwidget. */
9287 if (cursor_glyph->type == XWIDGET_GLYPH)
9288 return;
9290 /* If on an image, draw like a normal cursor. That's usually better
9291 visible than drawing a bar, esp. if the image is large so that
9292 the bar might not be in the window. */
9293 if (cursor_glyph->type == IMAGE_GLYPH)
9295 struct glyph_row *r;
9296 r = MATRIX_ROW (w->current_matrix, w->phys_cursor.vpos);
9297 draw_phys_cursor_glyph (w, r, DRAW_CURSOR);
9299 else
9301 Display *dpy = FRAME_X_DISPLAY (f);
9302 Drawable drawable = FRAME_X_DRAWABLE (f);
9303 GC gc = FRAME_DISPLAY_INFO (f)->scratch_cursor_gc;
9304 unsigned long mask = GCForeground | GCBackground | GCGraphicsExposures;
9305 struct face *face = FACE_FROM_ID (f, cursor_glyph->face_id);
9306 XGCValues xgcv;
9308 /* If the glyph's background equals the color we normally draw
9309 the bars cursor in, the bar cursor in its normal color is
9310 invisible. Use the glyph's foreground color instead in this
9311 case, on the assumption that the glyph's colors are chosen so
9312 that the glyph is legible. */
9313 if (face->background == f->output_data.x->cursor_pixel)
9314 xgcv.background = xgcv.foreground = face->foreground;
9315 else
9316 xgcv.background = xgcv.foreground = f->output_data.x->cursor_pixel;
9317 xgcv.graphics_exposures = False;
9319 if (gc)
9320 XChangeGC (dpy, gc, mask, &xgcv);
9321 else
9323 gc = XCreateGC (dpy, drawable, mask, &xgcv);
9324 FRAME_DISPLAY_INFO (f)->scratch_cursor_gc = gc;
9327 x_clip_to_row (w, row, TEXT_AREA, gc);
9329 if (kind == BAR_CURSOR)
9331 int x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
9333 if (width < 0)
9334 width = FRAME_CURSOR_WIDTH (f);
9335 width = min (cursor_glyph->pixel_width, width);
9337 w->phys_cursor_width = width;
9339 /* If the character under cursor is R2L, draw the bar cursor
9340 on the right of its glyph, rather than on the left. */
9341 if ((cursor_glyph->resolved_level & 1) != 0)
9342 x += cursor_glyph->pixel_width - width;
9344 x_fill_rectangle (f, gc, x,
9345 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y),
9346 width, row->height);
9348 else /* HBAR_CURSOR */
9350 int dummy_x, dummy_y, dummy_h;
9351 int x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
9353 if (width < 0)
9354 width = row->height;
9356 width = min (row->height, width);
9358 get_phys_cursor_geometry (w, row, cursor_glyph, &dummy_x,
9359 &dummy_y, &dummy_h);
9361 if ((cursor_glyph->resolved_level & 1) != 0
9362 && cursor_glyph->pixel_width > w->phys_cursor_width - 1)
9363 x += cursor_glyph->pixel_width - w->phys_cursor_width + 1;
9364 x_fill_rectangle (f, gc, x,
9365 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y +
9366 row->height - width),
9367 w->phys_cursor_width - 1, width);
9370 x_reset_clip_rectangles (f, gc);
9375 /* RIF: Define cursor CURSOR on frame F. */
9377 static void
9378 x_define_frame_cursor (struct frame *f, Cursor cursor)
9380 if (!f->pointer_invisible
9381 && f->output_data.x->current_cursor != cursor)
9382 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), cursor);
9383 f->output_data.x->current_cursor = cursor;
9387 /* RIF: Clear area on frame F. */
9389 static void
9390 x_clear_frame_area (struct frame *f, int x, int y, int width, int height)
9392 x_clear_area (f, x, y, width, height);
9396 /* RIF: Draw cursor on window W. */
9398 static void
9399 x_draw_window_cursor (struct window *w, struct glyph_row *glyph_row, int x,
9400 int y, enum text_cursor_kinds cursor_type,
9401 int cursor_width, bool on_p, bool active_p)
9403 struct frame *f = XFRAME (WINDOW_FRAME (w));
9405 if (on_p)
9407 w->phys_cursor_type = cursor_type;
9408 w->phys_cursor_on_p = true;
9410 if (glyph_row->exact_window_width_line_p
9411 && (glyph_row->reversed_p
9412 ? (w->phys_cursor.hpos < 0)
9413 : (w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])))
9415 glyph_row->cursor_in_fringe_p = true;
9416 draw_fringe_bitmap (w, glyph_row, glyph_row->reversed_p);
9418 else
9420 switch (cursor_type)
9422 case HOLLOW_BOX_CURSOR:
9423 x_draw_hollow_cursor (w, glyph_row);
9424 break;
9426 case FILLED_BOX_CURSOR:
9427 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
9428 break;
9430 case BAR_CURSOR:
9431 x_draw_bar_cursor (w, glyph_row, cursor_width, BAR_CURSOR);
9432 break;
9434 case HBAR_CURSOR:
9435 x_draw_bar_cursor (w, glyph_row, cursor_width, HBAR_CURSOR);
9436 break;
9438 case NO_CURSOR:
9439 w->phys_cursor_width = 0;
9440 break;
9442 default:
9443 emacs_abort ();
9447 #ifdef HAVE_X_I18N
9448 if (w == XWINDOW (f->selected_window))
9449 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMPreeditPosition))
9450 xic_set_preeditarea (w, x, y);
9451 #endif
9454 XFlush (FRAME_X_DISPLAY (f));
9458 /* Icons. */
9460 /* Make the x-window of frame F use the gnu icon bitmap. */
9462 bool
9463 x_bitmap_icon (struct frame *f, Lisp_Object file)
9465 ptrdiff_t bitmap_id;
9467 if (FRAME_X_WINDOW (f) == 0)
9468 return true;
9470 /* Free up our existing icon bitmap and mask if any. */
9471 if (f->output_data.x->icon_bitmap > 0)
9472 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
9473 f->output_data.x->icon_bitmap = 0;
9475 if (STRINGP (file))
9477 #ifdef USE_GTK
9478 /* Use gtk_window_set_icon_from_file () if available,
9479 It's not restricted to bitmaps */
9480 if (xg_set_icon (f, file))
9481 return false;
9482 #endif /* USE_GTK */
9483 bitmap_id = x_create_bitmap_from_file (f, file);
9484 x_create_bitmap_mask (f, bitmap_id);
9486 else
9488 /* Create the GNU bitmap and mask if necessary. */
9489 if (FRAME_DISPLAY_INFO (f)->icon_bitmap_id < 0)
9491 ptrdiff_t rc = -1;
9493 #ifdef USE_GTK
9495 if (xg_set_icon (f, xg_default_icon_file)
9496 || xg_set_icon_from_xpm_data (f, gnu_xpm_bits))
9498 FRAME_DISPLAY_INFO (f)->icon_bitmap_id = -2;
9499 return false;
9502 #elif defined (HAVE_XPM) && defined (HAVE_X_WINDOWS)
9504 rc = x_create_bitmap_from_xpm_data (f, gnu_xpm_bits);
9505 if (rc != -1)
9506 FRAME_DISPLAY_INFO (f)->icon_bitmap_id = rc;
9508 #endif
9510 /* If all else fails, use the (black and white) xbm image. */
9511 if (rc == -1)
9513 rc = x_create_bitmap_from_data (f, (char *) gnu_xbm_bits,
9514 gnu_xbm_width, gnu_xbm_height);
9515 if (rc == -1)
9516 return true;
9518 FRAME_DISPLAY_INFO (f)->icon_bitmap_id = rc;
9519 x_create_bitmap_mask (f, FRAME_DISPLAY_INFO (f)->icon_bitmap_id);
9523 /* The first time we create the GNU bitmap and mask,
9524 this increments the ref-count one extra time.
9525 As a result, the GNU bitmap and mask are never freed.
9526 That way, we don't have to worry about allocating it again. */
9527 x_reference_bitmap (f, FRAME_DISPLAY_INFO (f)->icon_bitmap_id);
9529 bitmap_id = FRAME_DISPLAY_INFO (f)->icon_bitmap_id;
9532 x_wm_set_icon_pixmap (f, bitmap_id);
9533 f->output_data.x->icon_bitmap = bitmap_id;
9535 return false;
9539 /* Make the x-window of frame F use a rectangle with text.
9540 Use ICON_NAME as the text. */
9542 bool
9543 x_text_icon (struct frame *f, const char *icon_name)
9545 if (FRAME_X_WINDOW (f) == 0)
9546 return true;
9549 XTextProperty text;
9550 text.value = (unsigned char *) icon_name;
9551 text.encoding = XA_STRING;
9552 text.format = 8;
9553 text.nitems = strlen (icon_name);
9554 XSetWMIconName (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f), &text);
9557 if (f->output_data.x->icon_bitmap > 0)
9558 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
9559 f->output_data.x->icon_bitmap = 0;
9560 x_wm_set_icon_pixmap (f, 0);
9562 return false;
9565 #define X_ERROR_MESSAGE_SIZE 200
9567 /* If non-nil, this should be a string.
9568 It means catch X errors and store the error message in this string.
9570 The reason we use a stack is that x_catch_error/x_uncatch_error can
9571 be called from a signal handler.
9574 struct x_error_message_stack {
9575 char string[X_ERROR_MESSAGE_SIZE];
9576 Display *dpy;
9577 x_special_error_handler handler;
9578 void *handler_data;
9579 struct x_error_message_stack *prev;
9581 static struct x_error_message_stack *x_error_message;
9583 /* An X error handler which stores the error message in
9584 *x_error_message. This is called from x_error_handler if
9585 x_catch_errors is in effect. */
9587 static void
9588 x_error_catcher (Display *display, XErrorEvent *event)
9590 XGetErrorText (display, event->error_code,
9591 x_error_message->string,
9592 X_ERROR_MESSAGE_SIZE);
9593 if (x_error_message->handler)
9594 x_error_message->handler (display, event, x_error_message->string,
9595 x_error_message->handler_data);
9598 /* Begin trapping X errors for display DPY. Actually we trap X errors
9599 for all displays, but DPY should be the display you are actually
9600 operating on.
9602 After calling this function, X protocol errors no longer cause
9603 Emacs to exit; instead, they are recorded in the string
9604 stored in *x_error_message.
9606 Calling x_check_errors signals an Emacs error if an X error has
9607 occurred since the last call to x_catch_errors or x_check_errors.
9609 Calling x_uncatch_errors resumes the normal error handling.
9610 Calling x_uncatch_errors_after_check is similar, but skips an XSync
9611 to the server, and should be used only immediately after
9612 x_had_errors_p or x_check_errors. */
9614 void
9615 x_catch_errors_with_handler (Display *dpy, x_special_error_handler handler,
9616 void *handler_data)
9618 struct x_error_message_stack *data = xmalloc (sizeof *data);
9620 /* Make sure any errors from previous requests have been dealt with. */
9621 XSync (dpy, False);
9623 data->dpy = dpy;
9624 data->string[0] = 0;
9625 data->handler = handler;
9626 data->handler_data = handler_data;
9627 data->prev = x_error_message;
9628 x_error_message = data;
9631 void
9632 x_catch_errors (Display *dpy)
9634 x_catch_errors_with_handler (dpy, NULL, NULL);
9637 /* Undo the last x_catch_errors call.
9638 DPY should be the display that was passed to x_catch_errors.
9640 This version should be used only if the immediately preceding
9641 X-protocol-related thing was x_check_errors or x_had_error_p, both
9642 of which issue XSync calls, so we don't need to re-sync here. */
9644 void
9645 x_uncatch_errors_after_check (void)
9647 struct x_error_message_stack *tmp;
9649 block_input ();
9650 tmp = x_error_message;
9651 x_error_message = x_error_message->prev;
9652 xfree (tmp);
9653 unblock_input ();
9656 /* Undo the last x_catch_errors call.
9657 DPY should be the display that was passed to x_catch_errors. */
9659 void
9660 x_uncatch_errors (void)
9662 struct x_error_message_stack *tmp;
9664 block_input ();
9666 /* The display may have been closed before this function is called.
9667 Check if it is still open before calling XSync. */
9668 if (x_display_info_for_display (x_error_message->dpy) != 0)
9669 XSync (x_error_message->dpy, False);
9671 tmp = x_error_message;
9672 x_error_message = x_error_message->prev;
9673 xfree (tmp);
9674 unblock_input ();
9677 /* If any X protocol errors have arrived since the last call to
9678 x_catch_errors or x_check_errors, signal an Emacs error using
9679 sprintf (a buffer, FORMAT, the x error message text) as the text. */
9681 void
9682 x_check_errors (Display *dpy, const char *format)
9684 /* Make sure to catch any errors incurred so far. */
9685 XSync (dpy, False);
9687 if (x_error_message->string[0])
9689 char string[X_ERROR_MESSAGE_SIZE];
9690 memcpy (string, x_error_message->string, X_ERROR_MESSAGE_SIZE);
9691 x_uncatch_errors ();
9692 error (format, string);
9696 /* Nonzero if we had any X protocol errors
9697 since we did x_catch_errors on DPY. */
9699 bool
9700 x_had_errors_p (Display *dpy)
9702 /* Make sure to catch any errors incurred so far. */
9703 XSync (dpy, False);
9705 return x_error_message->string[0] != 0;
9708 /* Forget about any errors we have had, since we did x_catch_errors on DPY. */
9710 void
9711 x_clear_errors (Display *dpy)
9713 x_error_message->string[0] = 0;
9716 #if false
9717 /* See comment in unwind_to_catch why calling this is a bad
9718 * idea. --lorentey */
9719 /* Close off all unclosed x_catch_errors calls. */
9721 void
9722 x_fully_uncatch_errors (void)
9724 while (x_error_message)
9725 x_uncatch_errors ();
9727 #endif
9729 #if false
9730 static unsigned int x_wire_count;
9731 x_trace_wire (void)
9733 fprintf (stderr, "Lib call: %d\n", ++x_wire_count);
9735 #endif
9738 /************************************************************************
9739 Handling X errors
9740 ************************************************************************/
9742 /* Error message passed to x_connection_closed. */
9744 static char *error_msg;
9746 /* Handle the loss of connection to display DPY. ERROR_MESSAGE is
9747 the text of an error message that lead to the connection loss. */
9749 static _Noreturn void
9750 x_connection_closed (Display *dpy, const char *error_message, bool ioerror)
9752 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
9753 Lisp_Object frame, tail;
9754 ptrdiff_t idx = SPECPDL_INDEX ();
9756 error_msg = alloca (strlen (error_message) + 1);
9757 strcpy (error_msg, error_message);
9759 /* Inhibit redisplay while frames are being deleted. */
9760 specbind (Qinhibit_redisplay, Qt);
9762 if (dpyinfo)
9764 /* Protect display from being closed when we delete the last
9765 frame on it. */
9766 dpyinfo->reference_count++;
9767 dpyinfo->terminal->reference_count++;
9769 if (ioerror) dpyinfo->display = 0;
9771 /* First delete frames whose mini-buffers are on frames
9772 that are on the dead display. */
9773 FOR_EACH_FRAME (tail, frame)
9775 Lisp_Object minibuf_frame;
9776 minibuf_frame
9777 = WINDOW_FRAME (XWINDOW (FRAME_MINIBUF_WINDOW (XFRAME (frame))));
9778 if (FRAME_X_P (XFRAME (frame))
9779 && FRAME_X_P (XFRAME (minibuf_frame))
9780 && ! EQ (frame, minibuf_frame)
9781 && FRAME_DISPLAY_INFO (XFRAME (minibuf_frame)) == dpyinfo)
9782 delete_frame (frame, Qnoelisp);
9785 /* Now delete all remaining frames on the dead display.
9786 We are now sure none of these is used as the mini-buffer
9787 for another frame that we need to delete. */
9788 FOR_EACH_FRAME (tail, frame)
9789 if (FRAME_X_P (XFRAME (frame))
9790 && FRAME_DISPLAY_INFO (XFRAME (frame)) == dpyinfo)
9792 /* Set this to t so that delete_frame won't get confused
9793 trying to find a replacement. */
9794 kset_default_minibuffer_frame (FRAME_KBOARD (XFRAME (frame)), Qt);
9795 delete_frame (frame, Qnoelisp);
9798 /* If DPYINFO is null, this means we didn't open the display in the
9799 first place, so don't try to close it. */
9800 if (dpyinfo)
9802 /* We can not call XtCloseDisplay here because it calls XSync.
9803 XSync inside the error handler apparently hangs Emacs. On
9804 current Xt versions, this isn't needed either. */
9805 #ifdef USE_GTK
9806 /* A long-standing GTK bug prevents proper disconnect handling
9807 (https://bugzilla.gnome.org/show_bug.cgi?id=85715). Once,
9808 the resulting Glib error message loop filled a user's disk.
9809 To avoid this, kill Emacs unconditionally on disconnect. */
9810 shut_down_emacs (0, Qnil);
9811 fprintf (stderr, "%s\n\
9812 When compiled with GTK, Emacs cannot recover from X disconnects.\n\
9813 This is a GTK bug: https://bugzilla.gnome.org/show_bug.cgi?id=85715\n\
9814 For details, see etc/PROBLEMS.\n",
9815 error_msg);
9816 emacs_abort ();
9817 #endif /* USE_GTK */
9819 /* Indicate that this display is dead. */
9820 dpyinfo->display = 0;
9822 dpyinfo->reference_count--;
9823 dpyinfo->terminal->reference_count--;
9824 if (dpyinfo->reference_count != 0)
9825 /* We have just closed all frames on this display. */
9826 emacs_abort ();
9829 Lisp_Object tmp;
9830 XSETTERMINAL (tmp, dpyinfo->terminal);
9831 Fdelete_terminal (tmp, Qnoelisp);
9835 if (terminal_list == 0)
9837 fprintf (stderr, "%s\n", error_msg);
9838 Fkill_emacs (make_number (70));
9839 /* NOTREACHED */
9842 totally_unblock_input ();
9844 unbind_to (idx, Qnil);
9845 clear_waiting_for_input ();
9847 /* Here, we absolutely have to use a non-local exit (e.g. signal, throw,
9848 longjmp), because returning from this function would get us back into
9849 Xlib's code which will directly call `exit'. */
9850 error ("%s", error_msg);
9853 /* We specifically use it before defining it, so that gcc doesn't inline it,
9854 otherwise gdb doesn't know how to properly put a breakpoint on it. */
9855 static void x_error_quitter (Display *, XErrorEvent *);
9857 /* This is the first-level handler for X protocol errors.
9858 It calls x_error_quitter or x_error_catcher. */
9860 static int
9861 x_error_handler (Display *display, XErrorEvent *event)
9863 #if defined USE_GTK && defined HAVE_GTK3
9864 if ((event->error_code == BadMatch || event->error_code == BadWindow)
9865 && event->request_code == X_SetInputFocus)
9867 return 0;
9869 #endif
9871 if (x_error_message)
9872 x_error_catcher (display, event);
9873 else
9874 x_error_quitter (display, event);
9875 return 0;
9878 /* This is the usual handler for X protocol errors.
9879 It kills all frames on the display that we got the error for.
9880 If that was the only one, it prints an error message and kills Emacs. */
9882 /* .gdbinit puts a breakpoint here, so make sure it is not inlined. */
9884 /* On older GCC versions, just putting x_error_quitter
9885 after x_error_handler prevents inlining into the former. */
9887 static void NO_INLINE
9888 x_error_quitter (Display *display, XErrorEvent *event)
9890 char buf[256], buf1[356];
9892 /* Ignore BadName errors. They can happen because of fonts
9893 or colors that are not defined. */
9895 if (event->error_code == BadName)
9896 return;
9898 /* Note that there is no real way portable across R3/R4 to get the
9899 original error handler. */
9901 XGetErrorText (display, event->error_code, buf, sizeof (buf));
9902 sprintf (buf1, "X protocol error: %s on protocol request %d",
9903 buf, event->request_code);
9904 x_connection_closed (display, buf1, false);
9908 /* This is the handler for X IO errors, always.
9909 It kills all frames on the display that we lost touch with.
9910 If that was the only one, it prints an error message and kills Emacs. */
9912 static _Noreturn int
9913 x_io_error_quitter (Display *display)
9915 char buf[256];
9917 snprintf (buf, sizeof buf, "Connection lost to X server '%s'",
9918 DisplayString (display));
9919 x_connection_closed (display, buf, true);
9920 assume (false);
9923 /* Changing the font of the frame. */
9925 /* Give frame F the font FONT-OBJECT as its default font. The return
9926 value is FONT-OBJECT. FONTSET is an ID of the fontset for the
9927 frame. If it is negative, generate a new fontset from
9928 FONT-OBJECT. */
9930 Lisp_Object
9931 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
9933 struct font *font = XFONT_OBJECT (font_object);
9934 int unit, font_ascent, font_descent;
9935 #ifndef USE_X_TOOLKIT
9936 int old_menu_bar_height = FRAME_MENU_BAR_HEIGHT (f);
9937 Lisp_Object fullscreen;
9938 #endif
9940 if (fontset < 0)
9941 fontset = fontset_from_font (font_object);
9942 FRAME_FONTSET (f) = fontset;
9943 if (FRAME_FONT (f) == font)
9944 /* This font is already set in frame F. There's nothing more to
9945 do. */
9946 return font_object;
9948 FRAME_FONT (f) = font;
9949 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
9950 FRAME_COLUMN_WIDTH (f) = font->average_width;
9951 get_font_ascent_descent (font, &font_ascent, &font_descent);
9952 FRAME_LINE_HEIGHT (f) = font_ascent + font_descent;
9954 #ifndef USE_X_TOOLKIT
9955 FRAME_MENU_BAR_HEIGHT (f) = FRAME_MENU_BAR_LINES (f) * FRAME_LINE_HEIGHT (f);
9956 #endif
9958 /* Compute character columns occupied by scrollbar.
9960 Don't do things differently for non-toolkit scrollbars
9961 (Bug#17163). */
9962 unit = FRAME_COLUMN_WIDTH (f);
9963 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
9964 FRAME_CONFIG_SCROLL_BAR_COLS (f)
9965 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + unit - 1) / unit;
9966 else
9967 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + unit - 1) / unit;
9969 if (FRAME_X_WINDOW (f) != 0)
9971 /* Don't change the size of a tip frame; there's no point in
9972 doing it because it's done in Fx_show_tip, and it leads to
9973 problems because the tip frame has no widget. */
9974 if (NILP (tip_frame) || XFRAME (tip_frame) != f
9975 #ifdef USE_GTK
9976 || NILP (Fframe_parameter (tip_frame, Qtooltip))
9977 #endif
9980 adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
9981 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 3,
9982 false, Qfont);
9983 #ifndef USE_X_TOOLKIT
9984 if (FRAME_MENU_BAR_HEIGHT (f) != old_menu_bar_height
9985 && !f->after_make_frame
9986 && (EQ (frame_inhibit_implied_resize, Qt)
9987 || (CONSP (frame_inhibit_implied_resize)
9988 && NILP (Fmemq (Qfont, frame_inhibit_implied_resize))))
9989 && (NILP (fullscreen = get_frame_param (f, Qfullscreen))
9990 || EQ (fullscreen, Qfullwidth)))
9991 /* If the menu bar height changes, try to keep text height
9992 constant. */
9993 adjust_frame_size
9994 (f, -1, FRAME_TEXT_HEIGHT (f) + FRAME_MENU_BAR_HEIGHT (f)
9995 - old_menu_bar_height, 1, false, Qfont);
9996 #endif /* USE_X_TOOLKIT */
10000 #ifdef HAVE_X_I18N
10001 if (FRAME_XIC (f)
10002 && (FRAME_XIC_STYLE (f) & (XIMPreeditPosition | XIMStatusArea)))
10004 block_input ();
10005 xic_set_xfontset (f, SSDATA (fontset_ascii (fontset)));
10006 unblock_input ();
10008 #endif
10010 return font_object;
10014 /***********************************************************************
10015 X Input Methods
10016 ***********************************************************************/
10018 #ifdef HAVE_X_I18N
10020 #ifdef HAVE_X11R6
10022 /* XIM destroy callback function, which is called whenever the
10023 connection to input method XIM dies. CLIENT_DATA contains a
10024 pointer to the x_display_info structure corresponding to XIM. */
10026 static void
10027 xim_destroy_callback (XIM xim, XPointer client_data, XPointer call_data)
10029 struct x_display_info *dpyinfo = (struct x_display_info *) client_data;
10030 Lisp_Object frame, tail;
10032 block_input ();
10034 /* No need to call XDestroyIC.. */
10035 FOR_EACH_FRAME (tail, frame)
10037 struct frame *f = XFRAME (frame);
10038 if (FRAME_X_P (f) && FRAME_DISPLAY_INFO (f) == dpyinfo)
10040 FRAME_XIC (f) = NULL;
10041 xic_free_xfontset (f);
10045 /* No need to call XCloseIM. */
10046 dpyinfo->xim = NULL;
10047 XFree (dpyinfo->xim_styles);
10048 unblock_input ();
10051 #endif /* HAVE_X11R6 */
10053 /* Open the connection to the XIM server on display DPYINFO.
10054 RESOURCE_NAME is the resource name Emacs uses. */
10056 static void
10057 xim_open_dpy (struct x_display_info *dpyinfo, char *resource_name)
10059 XIM xim;
10061 #ifdef HAVE_XIM
10062 if (use_xim)
10064 if (dpyinfo->xim)
10065 XCloseIM (dpyinfo->xim);
10066 xim = XOpenIM (dpyinfo->display, dpyinfo->xrdb, resource_name,
10067 emacs_class);
10068 dpyinfo->xim = xim;
10070 if (xim)
10072 #ifdef HAVE_X11R6
10073 XIMCallback destroy;
10074 #endif
10076 /* Get supported styles and XIM values. */
10077 XGetIMValues (xim, XNQueryInputStyle, &dpyinfo->xim_styles, NULL);
10079 #ifdef HAVE_X11R6
10080 destroy.callback = xim_destroy_callback;
10081 destroy.client_data = (XPointer)dpyinfo;
10082 XSetIMValues (xim, XNDestroyCallback, &destroy, NULL);
10083 #endif
10087 else
10088 #endif /* HAVE_XIM */
10089 dpyinfo->xim = NULL;
10093 #ifdef HAVE_X11R6_XIM
10095 /* XIM instantiate callback function, which is called whenever an XIM
10096 server is available. DISPLAY is the display of the XIM.
10097 CLIENT_DATA contains a pointer to an xim_inst_t structure created
10098 when the callback was registered. */
10100 static void
10101 xim_instantiate_callback (Display *display, XPointer client_data, XPointer call_data)
10103 struct xim_inst_t *xim_inst = (struct xim_inst_t *) client_data;
10104 struct x_display_info *dpyinfo = xim_inst->dpyinfo;
10106 /* We don't support multiple XIM connections. */
10107 if (dpyinfo->xim)
10108 return;
10110 xim_open_dpy (dpyinfo, xim_inst->resource_name);
10112 /* Create XIC for the existing frames on the same display, as long
10113 as they have no XIC. */
10114 if (dpyinfo->xim && dpyinfo->reference_count > 0)
10116 Lisp_Object tail, frame;
10118 block_input ();
10119 FOR_EACH_FRAME (tail, frame)
10121 struct frame *f = XFRAME (frame);
10123 if (FRAME_X_P (f)
10124 && FRAME_DISPLAY_INFO (f) == xim_inst->dpyinfo)
10125 if (FRAME_XIC (f) == NULL)
10127 create_frame_xic (f);
10128 if (FRAME_XIC_STYLE (f) & XIMStatusArea)
10129 xic_set_statusarea (f);
10130 if (FRAME_XIC_STYLE (f) & XIMPreeditPosition)
10132 struct window *w = XWINDOW (f->selected_window);
10133 xic_set_preeditarea (w, w->cursor.x, w->cursor.y);
10138 unblock_input ();
10142 #endif /* HAVE_X11R6_XIM */
10145 /* Open a connection to the XIM server on display DPYINFO.
10146 RESOURCE_NAME is the resource name for Emacs. On X11R5, open the
10147 connection only at the first time. On X11R6, open the connection
10148 in the XIM instantiate callback function. */
10150 static void
10151 xim_initialize (struct x_display_info *dpyinfo, char *resource_name)
10153 dpyinfo->xim = NULL;
10154 #ifdef HAVE_XIM
10155 if (use_xim)
10157 #ifdef HAVE_X11R6_XIM
10158 struct xim_inst_t *xim_inst = xmalloc (sizeof *xim_inst);
10159 Bool ret;
10161 dpyinfo->xim_callback_data = xim_inst;
10162 xim_inst->dpyinfo = dpyinfo;
10163 xim_inst->resource_name = xstrdup (resource_name);
10164 ret = XRegisterIMInstantiateCallback
10165 (dpyinfo->display, dpyinfo->xrdb, xim_inst->resource_name,
10166 emacs_class, xim_instantiate_callback,
10167 /* This is XPointer in XFree86 but (XPointer *)
10168 on Tru64, at least, hence the configure test. */
10169 (XRegisterIMInstantiateCallback_arg6) xim_inst);
10170 eassert (ret == True);
10171 #else /* not HAVE_X11R6_XIM */
10172 xim_open_dpy (dpyinfo, resource_name);
10173 #endif /* not HAVE_X11R6_XIM */
10175 #endif /* HAVE_XIM */
10179 /* Close the connection to the XIM server on display DPYINFO. */
10181 static void
10182 xim_close_dpy (struct x_display_info *dpyinfo)
10184 #ifdef HAVE_XIM
10185 if (use_xim)
10187 #ifdef HAVE_X11R6_XIM
10188 struct xim_inst_t *xim_inst = dpyinfo->xim_callback_data;
10190 if (dpyinfo->display)
10192 Bool ret = XUnregisterIMInstantiateCallback
10193 (dpyinfo->display, dpyinfo->xrdb, xim_inst->resource_name,
10194 emacs_class, xim_instantiate_callback,
10195 (XRegisterIMInstantiateCallback_arg6) xim_inst);
10196 eassert (ret == True);
10198 xfree (xim_inst->resource_name);
10199 xfree (xim_inst);
10200 #endif /* HAVE_X11R6_XIM */
10201 if (dpyinfo->display)
10202 XCloseIM (dpyinfo->xim);
10203 dpyinfo->xim = NULL;
10204 XFree (dpyinfo->xim_styles);
10206 #endif /* HAVE_XIM */
10209 #endif /* not HAVE_X11R6_XIM */
10213 /* Calculate the absolute position in frame F
10214 from its current recorded position values and gravity. */
10216 static void
10217 x_calc_absolute_position (struct frame *f)
10219 int flags = f->size_hint_flags;
10220 struct frame *p = FRAME_PARENT_FRAME (f);
10222 /* We have nothing to do if the current position
10223 is already for the top-left corner. */
10224 if (! ((flags & XNegative) || (flags & YNegative)))
10225 return;
10227 /* Treat negative positions as relative to the leftmost bottommost
10228 position that fits on the screen. */
10229 if ((flags & XNegative) && (f->left_pos <= 0))
10231 int width = FRAME_PIXEL_WIDTH (f);
10233 /* A frame that has been visible at least once should have outer
10234 edges. */
10235 if (f->output_data.x->has_been_visible && !p)
10237 Lisp_Object frame;
10238 Lisp_Object edges = Qnil;
10240 XSETFRAME (frame, f);
10241 edges = Fx_frame_edges (frame, Qouter_edges);
10242 if (!NILP (edges))
10243 width = (XINT (Fnth (make_number (2), edges))
10244 - XINT (Fnth (make_number (0), edges)));
10247 if (p)
10248 f->left_pos = (FRAME_PIXEL_WIDTH (p) - width - 2 * f->border_width
10249 + f->left_pos);
10250 else
10251 f->left_pos = (x_display_pixel_width (FRAME_DISPLAY_INFO (f))
10252 - width + f->left_pos);
10256 if ((flags & YNegative) && (f->top_pos <= 0))
10258 int height = FRAME_PIXEL_HEIGHT (f);
10260 #if defined USE_X_TOOLKIT && defined USE_MOTIF
10261 /* Something is fishy here. When using Motif, starting Emacs with
10262 `-g -0-0', the frame appears too low by a few pixels.
10264 This seems to be so because initially, while Emacs is starting,
10265 the column widget's height and the frame's pixel height are
10266 different. The column widget's height is the right one. In
10267 later invocations, when Emacs is up, the frame's pixel height
10268 is right, though.
10270 It's not obvious where the initial small difference comes from.
10271 2000-12-01, gerd. */
10273 XtVaGetValues (f->output_data.x->column_widget, XtNheight, &height, NULL);
10274 #endif
10276 if (f->output_data.x->has_been_visible && !p)
10278 Lisp_Object frame;
10279 Lisp_Object edges = Qnil;
10281 XSETFRAME (frame, f);
10282 if (NILP (edges))
10283 edges = Fx_frame_edges (frame, Qouter_edges);
10284 if (!NILP (edges))
10285 height = (XINT (Fnth (make_number (3), edges))
10286 - XINT (Fnth (make_number (1), edges)));
10289 if (p)
10290 f->top_pos = (FRAME_PIXEL_HEIGHT (p) - height - 2 * f->border_width
10291 + f->top_pos);
10292 else
10293 f->top_pos = (x_display_pixel_height (FRAME_DISPLAY_INFO (f))
10294 - height + f->top_pos);
10297 /* The left_pos and top_pos
10298 are now relative to the top and left screen edges,
10299 so the flags should correspond. */
10300 f->size_hint_flags &= ~ (XNegative | YNegative);
10303 /* CHANGE_GRAVITY is 1 when calling from Fset_frame_position,
10304 to really change the position, and 0 when calling from
10305 x_make_frame_visible (in that case, XOFF and YOFF are the current
10306 position values). It is -1 when calling from x_set_frame_parameters,
10307 which means, do adjust for borders but don't change the gravity. */
10309 void
10310 x_set_offset (struct frame *f, register int xoff, register int yoff, int change_gravity)
10312 int modified_top, modified_left;
10314 if (change_gravity > 0)
10316 f->top_pos = yoff;
10317 f->left_pos = xoff;
10318 f->size_hint_flags &= ~ (XNegative | YNegative);
10319 if (xoff < 0)
10320 f->size_hint_flags |= XNegative;
10321 if (yoff < 0)
10322 f->size_hint_flags |= YNegative;
10323 f->win_gravity = NorthWestGravity;
10326 x_calc_absolute_position (f);
10328 block_input ();
10329 x_wm_set_size_hint (f, 0, false);
10331 #ifdef USE_GTK
10332 if (x_gtk_use_window_move)
10334 /* When a position change was requested and the outer GTK widget
10335 has been realized already, leave it to gtk_window_move to DTRT
10336 and return. Used for Bug#25851 and Bug#25943. */
10337 if (change_gravity != 0 && FRAME_GTK_OUTER_WIDGET (f))
10338 gtk_window_move (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)),
10339 f->left_pos, f->top_pos);
10340 unblock_input ();
10341 return;
10343 #endif /* USE_GTK */
10345 modified_left = f->left_pos;
10346 modified_top = f->top_pos;
10348 if (change_gravity != 0 && FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A)
10350 /* Some WMs (twm, wmaker at least) has an offset that is smaller
10351 than the WM decorations. So we use the calculated offset instead
10352 of the WM decoration sizes here (x/y_pixels_outer_diff). */
10353 modified_left += FRAME_X_OUTPUT (f)->move_offset_left;
10354 modified_top += FRAME_X_OUTPUT (f)->move_offset_top;
10357 #ifdef USE_GTK
10358 gtk_window_move (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)),
10359 modified_left, modified_top);
10360 #else
10361 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
10362 modified_left, modified_top);
10363 #endif
10365 x_sync_with_move (f, f->left_pos, f->top_pos,
10366 FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN);
10368 /* change_gravity is non-zero when this function is called from Lisp to
10369 programmatically move a frame. In that case, we call
10370 x_check_expected_move to discover if we have a "Type A" or "Type B"
10371 window manager, and, for a "Type A" window manager, adjust the position
10372 of the frame.
10374 We call x_check_expected_move if a programmatic move occurred, and
10375 either the window manager type (A/B) is unknown or it is Type A but we
10376 need to compute the top/left offset adjustment for this frame. */
10378 if (change_gravity != 0
10379 && !FRAME_PARENT_FRAME (f)
10380 && (FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN
10381 || (FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A
10382 && (FRAME_X_OUTPUT (f)->move_offset_left == 0
10383 && FRAME_X_OUTPUT (f)->move_offset_top == 0))))
10384 x_check_expected_move (f, modified_left, modified_top);
10386 unblock_input ();
10389 /* Return true if _NET_SUPPORTING_WM_CHECK window exists and _NET_SUPPORTED
10390 on the root window for frame F contains ATOMNAME.
10391 This is how a WM check shall be done according to the Window Manager
10392 Specification/Extended Window Manager Hints at
10393 http://freedesktop.org/wiki/Specifications/wm-spec. */
10395 bool
10396 x_wm_supports (struct frame *f, Atom want_atom)
10398 Atom actual_type;
10399 unsigned long actual_size, bytes_remaining;
10400 int i, rc, actual_format;
10401 bool ret;
10402 Window wmcheck_window;
10403 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10404 Window target_window = dpyinfo->root_window;
10405 int max_len = 65536;
10406 Display *dpy = FRAME_X_DISPLAY (f);
10407 unsigned char *tmp_data = NULL;
10408 Atom target_type = XA_WINDOW;
10410 block_input ();
10412 x_catch_errors (dpy);
10413 rc = XGetWindowProperty (dpy, target_window,
10414 dpyinfo->Xatom_net_supporting_wm_check,
10415 0, max_len, False, target_type,
10416 &actual_type, &actual_format, &actual_size,
10417 &bytes_remaining, &tmp_data);
10419 if (rc != Success || actual_type != XA_WINDOW || x_had_errors_p (dpy))
10421 if (tmp_data) XFree (tmp_data);
10422 x_uncatch_errors ();
10423 unblock_input ();
10424 return false;
10427 wmcheck_window = *(Window *) tmp_data;
10428 XFree (tmp_data);
10430 /* Check if window exists. */
10431 XSelectInput (dpy, wmcheck_window, StructureNotifyMask);
10432 if (x_had_errors_p (dpy))
10434 x_uncatch_errors_after_check ();
10435 unblock_input ();
10436 return false;
10439 if (dpyinfo->net_supported_window != wmcheck_window)
10441 /* Window changed, reload atoms */
10442 if (dpyinfo->net_supported_atoms != NULL)
10443 XFree (dpyinfo->net_supported_atoms);
10444 dpyinfo->net_supported_atoms = NULL;
10445 dpyinfo->nr_net_supported_atoms = 0;
10446 dpyinfo->net_supported_window = 0;
10448 target_type = XA_ATOM;
10449 tmp_data = NULL;
10450 rc = XGetWindowProperty (dpy, target_window,
10451 dpyinfo->Xatom_net_supported,
10452 0, max_len, False, target_type,
10453 &actual_type, &actual_format, &actual_size,
10454 &bytes_remaining, &tmp_data);
10456 if (rc != Success || actual_type != XA_ATOM || x_had_errors_p (dpy))
10458 if (tmp_data) XFree (tmp_data);
10459 x_uncatch_errors ();
10460 unblock_input ();
10461 return false;
10464 dpyinfo->net_supported_atoms = (Atom *)tmp_data;
10465 dpyinfo->nr_net_supported_atoms = actual_size;
10466 dpyinfo->net_supported_window = wmcheck_window;
10469 ret = false;
10471 for (i = 0; !ret && i < dpyinfo->nr_net_supported_atoms; ++i)
10472 ret = dpyinfo->net_supported_atoms[i] == want_atom;
10474 x_uncatch_errors ();
10475 unblock_input ();
10477 return ret;
10480 static void
10481 set_wm_state (Lisp_Object frame, bool add, Atom atom, Atom value)
10483 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (XFRAME (frame));
10485 x_send_client_event (frame, make_number (0), frame,
10486 dpyinfo->Xatom_net_wm_state,
10487 make_number (32),
10488 /* 1 = add, 0 = remove */
10489 Fcons
10490 (make_number (add),
10491 Fcons
10492 (make_fixnum_or_float (atom),
10493 (value != 0
10494 ? list1 (make_fixnum_or_float (value))
10495 : Qnil))));
10498 void
10499 x_set_sticky (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
10501 Lisp_Object frame;
10502 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10504 XSETFRAME (frame, f);
10506 set_wm_state (frame, !NILP (new_value),
10507 dpyinfo->Xatom_net_wm_state_sticky, None);
10511 * x_set_skip_taskbar:
10513 * Set frame F's `skip-taskbar' parameter. If non-nil, this should
10514 * remove F's icon from the taskbar associated with the display of F's
10515 * window-system window and inhibit switching to F's window via
10516 * <Alt>-<TAB>. If nil, lift these restrictions.
10518 * Some window managers may not honor this parameter.
10520 void
10521 x_set_skip_taskbar (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
10523 if (!EQ (new_value, old_value))
10525 #ifdef USE_GTK
10526 xg_set_skip_taskbar (f, new_value);
10527 #else
10528 Lisp_Object frame;
10529 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10531 XSETFRAME (frame, f);
10532 set_wm_state (frame, !NILP (new_value),
10533 dpyinfo->Xatom_net_wm_state_skip_taskbar, None);
10534 #endif /* USE_GTK */
10535 FRAME_SKIP_TASKBAR (f) = !NILP (new_value);
10540 * x_set_z_group:
10542 * Set frame F's `z-group' parameter. If `above', F's window-system
10543 * window is displayed above all windows that do not have the `above'
10544 * property set. If nil, F's window is shown below all windows that
10545 * have the `above' property set and above all windows that have the
10546 * `below' property set. If `below', F's window is displayed below all
10547 * windows that do not have the `below' property set.
10549 * Some window managers may not honor this parameter.
10551 void
10552 x_set_z_group (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
10554 /* We don't care about old_value. The window manager might have
10555 reset the value without telling us. */
10556 Lisp_Object frame;
10557 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10559 XSETFRAME (frame, f);
10561 if (NILP (new_value))
10563 set_wm_state (frame, false,
10564 dpyinfo->Xatom_net_wm_state_above, None);
10565 set_wm_state (frame, false,
10566 dpyinfo->Xatom_net_wm_state_below, None);
10567 FRAME_Z_GROUP (f) = z_group_none;
10569 else if (EQ (new_value, Qabove))
10571 set_wm_state (frame, true,
10572 dpyinfo->Xatom_net_wm_state_above, None);
10573 set_wm_state (frame, false,
10574 dpyinfo->Xatom_net_wm_state_below, None);
10575 FRAME_Z_GROUP (f) = z_group_above;
10577 else if (EQ (new_value, Qbelow))
10579 set_wm_state (frame, false,
10580 dpyinfo->Xatom_net_wm_state_above, None);
10581 set_wm_state (frame, true,
10582 dpyinfo->Xatom_net_wm_state_below, None);
10583 FRAME_Z_GROUP (f) = z_group_below;
10585 else if (EQ (new_value, Qabove_suspended))
10587 set_wm_state (frame, false,
10588 dpyinfo->Xatom_net_wm_state_above, None);
10589 FRAME_Z_GROUP (f) = z_group_above_suspended;
10591 else
10592 error ("Invalid z-group specification");
10596 /* Return the current _NET_WM_STATE.
10597 SIZE_STATE is set to one of the FULLSCREEN_* values.
10598 Set *STICKY to the sticky state.
10600 Return true iff we are not hidden. */
10602 static bool
10603 get_current_wm_state (struct frame *f,
10604 Window window,
10605 int *size_state,
10606 bool *sticky)
10608 unsigned long actual_size;
10609 int i;
10610 bool is_hidden = false;
10611 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10612 long max_len = 65536;
10613 Atom target_type = XA_ATOM;
10614 /* If XCB is available, we can avoid three XSync calls. */
10615 #ifdef USE_XCB
10616 xcb_get_property_cookie_t prop_cookie;
10617 xcb_get_property_reply_t *prop;
10618 xcb_atom_t *reply_data;
10619 #else
10620 Display *dpy = FRAME_X_DISPLAY (f);
10621 unsigned long bytes_remaining;
10622 int rc, actual_format;
10623 Atom actual_type;
10624 unsigned char *tmp_data = NULL;
10625 Atom *reply_data;
10626 #endif
10628 *sticky = false;
10629 *size_state = FULLSCREEN_NONE;
10631 block_input ();
10633 #ifdef USE_XCB
10634 prop_cookie = xcb_get_property (dpyinfo->xcb_connection, 0, window,
10635 dpyinfo->Xatom_net_wm_state,
10636 target_type, 0, max_len);
10637 prop = xcb_get_property_reply (dpyinfo->xcb_connection, prop_cookie, NULL);
10638 if (prop && prop->type == target_type)
10640 int actual_bytes = xcb_get_property_value_length (prop);
10641 eassume (0 <= actual_bytes);
10642 actual_size = actual_bytes / sizeof *reply_data;
10643 reply_data = xcb_get_property_value (prop);
10645 else
10647 actual_size = 0;
10648 is_hidden = FRAME_ICONIFIED_P (f);
10650 #else
10651 x_catch_errors (dpy);
10652 rc = XGetWindowProperty (dpy, window, dpyinfo->Xatom_net_wm_state,
10653 0, max_len, False, target_type,
10654 &actual_type, &actual_format, &actual_size,
10655 &bytes_remaining, &tmp_data);
10657 if (rc == Success && actual_type == target_type && ! x_had_errors_p (dpy))
10658 reply_data = (Atom *) tmp_data;
10659 else
10661 actual_size = 0;
10662 is_hidden = FRAME_ICONIFIED_P (f);
10665 x_uncatch_errors ();
10666 #endif
10668 for (i = 0; i < actual_size; ++i)
10670 Atom a = reply_data[i];
10671 if (a == dpyinfo->Xatom_net_wm_state_hidden)
10672 is_hidden = true;
10673 else if (a == dpyinfo->Xatom_net_wm_state_maximized_horz)
10675 if (*size_state == FULLSCREEN_HEIGHT)
10676 *size_state = FULLSCREEN_MAXIMIZED;
10677 else
10678 *size_state = FULLSCREEN_WIDTH;
10680 else if (a == dpyinfo->Xatom_net_wm_state_maximized_vert)
10682 if (*size_state == FULLSCREEN_WIDTH)
10683 *size_state = FULLSCREEN_MAXIMIZED;
10684 else
10685 *size_state = FULLSCREEN_HEIGHT;
10687 else if (a == dpyinfo->Xatom_net_wm_state_fullscreen)
10688 *size_state = FULLSCREEN_BOTH;
10689 else if (a == dpyinfo->Xatom_net_wm_state_sticky)
10690 *sticky = true;
10693 #ifdef USE_XCB
10694 free (prop);
10695 #else
10696 if (tmp_data) XFree (tmp_data);
10697 #endif
10699 unblock_input ();
10700 return ! is_hidden;
10703 /* Do fullscreen as specified in extended window manager hints */
10705 static bool
10706 do_ewmh_fullscreen (struct frame *f)
10708 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10709 bool have_net_atom = x_wm_supports (f, dpyinfo->Xatom_net_wm_state);
10710 int cur;
10711 bool dummy;
10713 get_current_wm_state (f, FRAME_OUTER_WINDOW (f), &cur, &dummy);
10715 /* Some window managers don't say they support _NET_WM_STATE, but they do say
10716 they support _NET_WM_STATE_FULLSCREEN. Try that also. */
10717 if (!have_net_atom)
10718 have_net_atom = x_wm_supports (f, dpyinfo->Xatom_net_wm_state_fullscreen);
10720 if (have_net_atom && cur != f->want_fullscreen)
10722 Lisp_Object frame;
10724 XSETFRAME (frame, f);
10726 /* Keep number of calls to set_wm_state as low as possible.
10727 Some window managers, or possible Gtk+, hangs when too many
10728 are sent at once. */
10729 switch (f->want_fullscreen)
10731 case FULLSCREEN_BOTH:
10732 if (cur != FULLSCREEN_BOTH)
10733 set_wm_state (frame, true, dpyinfo->Xatom_net_wm_state_fullscreen,
10734 None);
10735 break;
10736 case FULLSCREEN_WIDTH:
10737 if (x_frame_normalize_before_maximize && cur == FULLSCREEN_MAXIMIZED)
10739 set_wm_state (frame, false,
10740 dpyinfo->Xatom_net_wm_state_maximized_horz,
10741 dpyinfo->Xatom_net_wm_state_maximized_vert);
10742 set_wm_state (frame, true,
10743 dpyinfo->Xatom_net_wm_state_maximized_horz, None);
10745 else
10747 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_HEIGHT
10748 || cur == FULLSCREEN_MAXIMIZED)
10749 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
10750 dpyinfo->Xatom_net_wm_state_maximized_vert);
10751 if (cur != FULLSCREEN_MAXIMIZED || x_frame_normalize_before_maximize)
10752 set_wm_state (frame, true,
10753 dpyinfo->Xatom_net_wm_state_maximized_horz, None);
10755 break;
10756 case FULLSCREEN_HEIGHT:
10757 if (x_frame_normalize_before_maximize && cur == FULLSCREEN_MAXIMIZED)
10759 set_wm_state (frame, false,
10760 dpyinfo->Xatom_net_wm_state_maximized_horz,
10761 dpyinfo->Xatom_net_wm_state_maximized_vert);
10762 set_wm_state (frame, true,
10763 dpyinfo->Xatom_net_wm_state_maximized_vert, None);
10765 else
10767 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_WIDTH
10768 || cur == FULLSCREEN_MAXIMIZED)
10769 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
10770 dpyinfo->Xatom_net_wm_state_maximized_horz);
10771 if (cur != FULLSCREEN_MAXIMIZED || x_frame_normalize_before_maximize)
10772 set_wm_state (frame, true,
10773 dpyinfo->Xatom_net_wm_state_maximized_vert, None);
10775 break;
10776 case FULLSCREEN_MAXIMIZED:
10777 if (x_frame_normalize_before_maximize && cur == FULLSCREEN_BOTH)
10779 set_wm_state (frame, false,
10780 dpyinfo->Xatom_net_wm_state_fullscreen, None);
10781 set_wm_state (frame, true,
10782 dpyinfo->Xatom_net_wm_state_maximized_horz,
10783 dpyinfo->Xatom_net_wm_state_maximized_vert);
10785 else if (x_frame_normalize_before_maximize && cur == FULLSCREEN_WIDTH)
10787 set_wm_state (frame, false,
10788 dpyinfo->Xatom_net_wm_state_maximized_horz, None);
10789 set_wm_state (frame, true,
10790 dpyinfo->Xatom_net_wm_state_maximized_horz,
10791 dpyinfo->Xatom_net_wm_state_maximized_vert);
10793 else if (x_frame_normalize_before_maximize && cur == FULLSCREEN_HEIGHT)
10795 set_wm_state (frame, false,
10796 dpyinfo->Xatom_net_wm_state_maximized_vert, None);
10797 set_wm_state (frame, true,
10798 dpyinfo->Xatom_net_wm_state_maximized_horz,
10799 dpyinfo->Xatom_net_wm_state_maximized_vert);
10801 else
10803 if (cur == FULLSCREEN_BOTH)
10804 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
10805 None);
10806 else if (cur == FULLSCREEN_HEIGHT)
10807 set_wm_state (frame, true,
10808 dpyinfo->Xatom_net_wm_state_maximized_horz, None);
10809 else if (cur == FULLSCREEN_WIDTH)
10810 set_wm_state (frame, true, None,
10811 dpyinfo->Xatom_net_wm_state_maximized_vert);
10812 else
10813 set_wm_state (frame, true,
10814 dpyinfo->Xatom_net_wm_state_maximized_horz,
10815 dpyinfo->Xatom_net_wm_state_maximized_vert);
10817 break;
10818 case FULLSCREEN_NONE:
10819 if (cur == FULLSCREEN_BOTH)
10820 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
10821 None);
10822 else
10823 set_wm_state (frame, false,
10824 dpyinfo->Xatom_net_wm_state_maximized_horz,
10825 dpyinfo->Xatom_net_wm_state_maximized_vert);
10828 f->want_fullscreen = FULLSCREEN_NONE;
10832 return have_net_atom;
10835 static void
10836 XTfullscreen_hook (struct frame *f)
10838 if (FRAME_VISIBLE_P (f))
10840 block_input ();
10841 x_check_fullscreen (f);
10842 x_sync (f);
10843 unblock_input ();
10848 static bool
10849 x_handle_net_wm_state (struct frame *f, const XPropertyEvent *event)
10851 int value = FULLSCREEN_NONE;
10852 Lisp_Object lval;
10853 bool sticky = false;
10854 bool not_hidden = get_current_wm_state (f, event->window, &value, &sticky);
10856 lval = Qnil;
10857 switch (value)
10859 case FULLSCREEN_WIDTH:
10860 lval = Qfullwidth;
10861 break;
10862 case FULLSCREEN_HEIGHT:
10863 lval = Qfullheight;
10864 break;
10865 case FULLSCREEN_BOTH:
10866 lval = Qfullboth;
10867 break;
10868 case FULLSCREEN_MAXIMIZED:
10869 lval = Qmaximized;
10870 break;
10873 frame_size_history_add
10874 (f, Qx_handle_net_wm_state, 0, 0,
10875 list2 (get_frame_param (f, Qfullscreen), lval));
10877 store_frame_param (f, Qfullscreen, lval);
10878 store_frame_param (f, Qsticky, sticky ? Qt : Qnil);
10880 return not_hidden;
10883 /* Check if we need to resize the frame due to a fullscreen request.
10884 If so needed, resize the frame. */
10885 static void
10886 x_check_fullscreen (struct frame *f)
10888 Lisp_Object lval = Qnil;
10890 if (do_ewmh_fullscreen (f))
10891 return;
10893 if (f->output_data.x->parent_desc != FRAME_DISPLAY_INFO (f)->root_window)
10894 return; /* Only fullscreen without WM or with EWM hints (above). */
10896 /* Setting fullscreen to nil doesn't do anything. We could save the
10897 last non-fullscreen size and restore it, but it seems like a
10898 lot of work for this unusual case (no window manager running). */
10900 if (f->want_fullscreen != FULLSCREEN_NONE)
10902 int width = FRAME_PIXEL_WIDTH (f), height = FRAME_PIXEL_HEIGHT (f);
10903 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10905 switch (f->want_fullscreen)
10907 /* No difference between these two when there is no WM */
10908 case FULLSCREEN_MAXIMIZED:
10909 lval = Qmaximized;
10910 width = x_display_pixel_width (dpyinfo);
10911 height = x_display_pixel_height (dpyinfo);
10912 break;
10913 case FULLSCREEN_BOTH:
10914 lval = Qfullboth;
10915 width = x_display_pixel_width (dpyinfo);
10916 height = x_display_pixel_height (dpyinfo);
10917 break;
10918 case FULLSCREEN_WIDTH:
10919 lval = Qfullwidth;
10920 width = x_display_pixel_width (dpyinfo);
10921 height = height + FRAME_MENUBAR_HEIGHT (f);
10922 break;
10923 case FULLSCREEN_HEIGHT:
10924 lval = Qfullheight;
10925 height = x_display_pixel_height (dpyinfo);
10926 break;
10927 default:
10928 emacs_abort ();
10931 frame_size_history_add
10932 (f, Qx_check_fullscreen, width, height, Qnil);
10934 x_wm_set_size_hint (f, 0, false);
10936 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
10937 width, height);
10939 if (FRAME_VISIBLE_P (f))
10940 x_wait_for_event (f, ConfigureNotify);
10941 else
10943 change_frame_size (f, width, height - FRAME_MENUBAR_HEIGHT (f),
10944 false, true, false, true);
10945 x_sync (f);
10949 /* `x_net_wm_state' might have reset the fullscreen frame parameter,
10950 restore it. */
10951 store_frame_param (f, Qfullscreen, lval);
10954 /* This function is called by x_set_offset to determine whether the window
10955 manager interfered with the positioning of the frame. Type A window
10956 managers position the surrounding window manager decorations a small
10957 amount above and left of the user-supplied position. Type B window
10958 managers position the surrounding window manager decorations at the
10959 user-specified position. If we detect a Type A window manager, we
10960 compensate by moving the window right and down by the proper amount. */
10962 static void
10963 x_check_expected_move (struct frame *f, int expected_left, int expected_top)
10965 int current_left = 0, current_top = 0;
10967 /* x_real_positions returns the left and top offsets of the outermost
10968 window manager window around the frame. */
10970 x_real_positions (f, &current_left, &current_top);
10972 if (current_left != expected_left || current_top != expected_top)
10974 /* It's a "Type A" window manager. */
10976 int adjusted_left;
10977 int adjusted_top;
10979 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_A;
10980 FRAME_X_OUTPUT (f)->move_offset_left = expected_left - current_left;
10981 FRAME_X_OUTPUT (f)->move_offset_top = expected_top - current_top;
10983 /* Now fix the mispositioned frame's location. */
10985 adjusted_left = expected_left + FRAME_X_OUTPUT (f)->move_offset_left;
10986 adjusted_top = expected_top + FRAME_X_OUTPUT (f)->move_offset_top;
10988 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
10989 adjusted_left, adjusted_top);
10991 x_sync_with_move (f, expected_left, expected_top, false);
10993 else
10994 /* It's a "Type B" window manager. We don't have to adjust the
10995 frame's position. */
10997 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_B;
11001 /* Wait for XGetGeometry to return up-to-date position information for a
11002 recently-moved frame. Call this immediately after calling XMoveWindow.
11003 If FUZZY is non-zero, then LEFT and TOP are just estimates of where the
11004 frame has been moved to, so we use a fuzzy position comparison instead
11005 of an exact comparison. */
11007 static void
11008 x_sync_with_move (struct frame *f, int left, int top, bool fuzzy)
11010 int count = 0;
11012 while (count++ < 50)
11014 int current_left = 0, current_top = 0;
11016 /* In theory, this call to XSync only needs to happen once, but in
11017 practice, it doesn't seem to work, hence the need for the surrounding
11018 loop. */
11020 XSync (FRAME_X_DISPLAY (f), False);
11021 x_real_positions (f, &current_left, &current_top);
11023 if (fuzzy)
11025 /* The left fuzz-factor is 10 pixels. The top fuzz-factor is 40
11026 pixels. */
11028 if (eabs (current_left - left) <= 10
11029 && eabs (current_top - top) <= 40)
11030 return;
11032 else if (current_left == left && current_top == top)
11033 return;
11036 /* As a last resort, just wait 0.5 seconds and hope that XGetGeometry
11037 will then return up-to-date position info. */
11039 wait_reading_process_output (0, 500000000, 0, false, Qnil, NULL, 0);
11043 /* Wait for an event on frame F matching EVENTTYPE. */
11044 void
11045 x_wait_for_event (struct frame *f, int eventtype)
11047 if (!FLOATP (Vx_wait_for_event_timeout))
11048 return;
11050 int level = interrupt_input_blocked;
11051 fd_set fds;
11052 struct timespec tmo, tmo_at, time_now;
11053 int fd = ConnectionNumber (FRAME_X_DISPLAY (f));
11055 f->wait_event_type = eventtype;
11057 /* Default timeout is 0.1 second. Hopefully not noticeable. */
11058 double timeout = XFLOAT_DATA (Vx_wait_for_event_timeout);
11059 time_t timeout_seconds = (time_t) timeout;
11060 tmo = make_timespec
11061 (timeout_seconds, (long int) ((timeout - timeout_seconds)
11062 * 1000 * 1000 * 1000));
11063 tmo_at = timespec_add (current_timespec (), tmo);
11065 while (f->wait_event_type)
11067 pending_signals = true;
11068 totally_unblock_input ();
11069 /* XTread_socket is called after unblock. */
11070 block_input ();
11071 interrupt_input_blocked = level;
11073 FD_ZERO (&fds);
11074 FD_SET (fd, &fds);
11076 time_now = current_timespec ();
11077 if (timespec_cmp (tmo_at, time_now) < 0)
11078 break;
11080 tmo = timespec_sub (tmo_at, time_now);
11081 if (pselect (fd + 1, &fds, NULL, NULL, &tmo, NULL) == 0)
11082 break; /* Timeout */
11085 f->wait_event_type = 0;
11089 /* Change the size of frame F's X window to WIDTH/HEIGHT in the case F
11090 doesn't have a widget. If CHANGE_GRAVITY, change to
11091 top-left-corner window gravity for this size change and subsequent
11092 size changes. Otherwise leave the window gravity unchanged. */
11094 static void
11095 x_set_window_size_1 (struct frame *f, bool change_gravity,
11096 int width, int height)
11098 int pixelwidth = FRAME_TEXT_TO_PIXEL_WIDTH (f, width);
11099 int pixelheight = FRAME_TEXT_TO_PIXEL_HEIGHT (f, height);
11100 int old_width = FRAME_PIXEL_WIDTH (f);
11101 int old_height = FRAME_PIXEL_HEIGHT (f);
11102 Lisp_Object fullscreen = get_frame_param (f, Qfullscreen);
11104 if (change_gravity)
11105 f->win_gravity = NorthWestGravity;
11106 x_wm_set_size_hint (f, 0, false);
11108 /* When the frame is fullheight and we only want to change the width
11109 or it is fullwidth and we only want to change the height we should
11110 be able to preserve the fullscreen property. However, due to the
11111 fact that we have to send a resize request anyway, the window
11112 manager will abolish it. At least the respective size should
11113 remain unchanged but giving the frame back its normal size will
11114 be broken ... */
11115 if (EQ (fullscreen, Qfullwidth) && width == FRAME_TEXT_WIDTH (f))
11117 frame_size_history_add
11118 (f, Qx_set_window_size_1, width, height,
11119 list2 (make_number (old_height),
11120 make_number (pixelheight + FRAME_MENUBAR_HEIGHT (f))));
11122 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11123 old_width, pixelheight + FRAME_MENUBAR_HEIGHT (f));
11125 else if (EQ (fullscreen, Qfullheight) && height == FRAME_TEXT_HEIGHT (f))
11127 frame_size_history_add
11128 (f, Qx_set_window_size_2, width, height,
11129 list2 (make_number (old_width), make_number (pixelwidth)));
11131 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11132 pixelwidth, old_height);
11135 else
11137 frame_size_history_add
11138 (f, Qx_set_window_size_3, width, height,
11139 list3 (make_number (pixelwidth + FRAME_TOOLBAR_WIDTH (f)),
11140 make_number (pixelheight + FRAME_TOOLBAR_HEIGHT (f)
11141 + FRAME_MENUBAR_HEIGHT (f)),
11142 make_number (FRAME_MENUBAR_HEIGHT (f))));
11144 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11145 pixelwidth, pixelheight + FRAME_MENUBAR_HEIGHT (f));
11146 fullscreen = Qnil;
11151 /* We've set {FRAME,PIXEL}_{WIDTH,HEIGHT} to the values we hope to
11152 receive in the ConfigureNotify event; if we get what we asked
11153 for, then the event won't cause the screen to become garbaged, so
11154 we have to make sure to do it here. */
11155 SET_FRAME_GARBAGED (f);
11157 /* Now, strictly speaking, we can't be sure that this is accurate,
11158 but the window manager will get around to dealing with the size
11159 change request eventually, and we'll hear how it went when the
11160 ConfigureNotify event gets here.
11162 We could just not bother storing any of this information here,
11163 and let the ConfigureNotify event set everything up, but that
11164 might be kind of confusing to the Lisp code, since size changes
11165 wouldn't be reported in the frame parameters until some random
11166 point in the future when the ConfigureNotify event arrives.
11168 Pass true for DELAY since we can't run Lisp code inside of
11169 a BLOCK_INPUT. */
11171 /* But the ConfigureNotify may in fact never arrive, and then this is
11172 not right if the frame is visible. Instead wait (with timeout)
11173 for the ConfigureNotify. */
11174 if (FRAME_VISIBLE_P (f))
11176 x_wait_for_event (f, ConfigureNotify);
11178 if (!NILP (fullscreen))
11179 /* Try to restore fullscreen state. */
11181 store_frame_param (f, Qfullscreen, fullscreen);
11182 x_set_fullscreen (f, fullscreen, fullscreen);
11185 else
11187 change_frame_size (f, width, height, false, true, false, true);
11188 x_sync (f);
11193 /* Call this to change the size of frame F's x-window.
11194 If CHANGE_GRAVITY, change to top-left-corner window gravity
11195 for this size change and subsequent size changes.
11196 Otherwise we leave the window gravity unchanged. */
11198 void
11199 x_set_window_size (struct frame *f, bool change_gravity,
11200 int width, int height, bool pixelwise)
11202 block_input ();
11204 /* The following breaks our calculations. If it's really needed,
11205 think of something else. */
11206 #if false
11207 if (NILP (tip_frame) || XFRAME (tip_frame) != f)
11209 int text_width, text_height;
11211 /* When the frame is maximized/fullscreen or running under for
11212 example Xmonad, x_set_window_size_1 will be a no-op.
11213 In that case, the right thing to do is extend rows/width to
11214 the current frame size. We do that first if x_set_window_size_1
11215 turns out to not be a no-op (there is no way to know).
11216 The size will be adjusted again if the frame gets a
11217 ConfigureNotify event as a result of x_set_window_size. */
11218 int pixelh = FRAME_PIXEL_HEIGHT (f);
11219 #ifdef USE_X_TOOLKIT
11220 /* The menu bar is not part of text lines. The tool bar
11221 is however. */
11222 pixelh -= FRAME_MENUBAR_HEIGHT (f);
11223 #endif
11224 text_width = FRAME_PIXEL_TO_TEXT_WIDTH (f, FRAME_PIXEL_WIDTH (f));
11225 text_height = FRAME_PIXEL_TO_TEXT_HEIGHT (f, pixelh);
11227 change_frame_size (f, text_width, text_height, false, true, false, true);
11229 #endif
11231 /* Pixelize width and height, if necessary. */
11232 if (! pixelwise)
11234 width = width * FRAME_COLUMN_WIDTH (f);
11235 height = height * FRAME_LINE_HEIGHT (f);
11238 #ifdef USE_GTK
11239 if (FRAME_GTK_WIDGET (f))
11240 xg_frame_set_char_size (f, width, height);
11241 else
11242 x_set_window_size_1 (f, change_gravity, width, height);
11243 #else /* not USE_GTK */
11244 x_set_window_size_1 (f, change_gravity, width, height);
11245 x_clear_under_internal_border (f);
11246 #endif /* not USE_GTK */
11248 /* If cursor was outside the new size, mark it as off. */
11249 mark_window_cursors_off (XWINDOW (f->root_window));
11251 /* Clear out any recollection of where the mouse highlighting was,
11252 since it might be in a place that's outside the new frame size.
11253 Actually checking whether it is outside is a pain in the neck,
11254 so don't try--just let the highlighting be done afresh with new size. */
11255 cancel_mouse_face (f);
11257 unblock_input ();
11259 do_pending_window_change (false);
11262 /* Move the mouse to position pixel PIX_X, PIX_Y relative to frame F. */
11264 void
11265 frame_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
11267 block_input ();
11269 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
11270 0, 0, 0, 0, pix_x, pix_y);
11271 unblock_input ();
11274 /* Raise frame F. */
11276 void
11277 x_raise_frame (struct frame *f)
11279 block_input ();
11280 if (FRAME_VISIBLE_P (f))
11281 XRaiseWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
11282 XFlush (FRAME_X_DISPLAY (f));
11283 unblock_input ();
11286 /* Lower frame F. */
11288 static void
11289 x_lower_frame (struct frame *f)
11291 if (FRAME_VISIBLE_P (f))
11293 block_input ();
11294 XLowerWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
11295 XFlush (FRAME_X_DISPLAY (f));
11296 unblock_input ();
11300 /* Request focus with XEmbed */
11302 void
11303 xembed_request_focus (struct frame *f)
11305 /* See XEmbed Protocol Specification at
11306 http://freedesktop.org/wiki/Specifications/xembed-spec */
11307 if (FRAME_VISIBLE_P (f))
11308 xembed_send_message (f, CurrentTime,
11309 XEMBED_REQUEST_FOCUS, 0, 0, 0);
11312 /* Activate frame with Extended Window Manager Hints */
11314 void
11315 x_ewmh_activate_frame (struct frame *f)
11317 /* See Window Manager Specification/Extended Window Manager Hints at
11318 http://freedesktop.org/wiki/Specifications/wm-spec */
11320 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
11322 if (FRAME_VISIBLE_P (f) && x_wm_supports (f, dpyinfo->Xatom_net_active_window))
11324 Lisp_Object frame;
11325 XSETFRAME (frame, f);
11326 x_send_client_event (frame, make_number (0), frame,
11327 dpyinfo->Xatom_net_active_window,
11328 make_number (32),
11329 list2i (1, dpyinfo->last_user_time));
11333 static void
11334 XTframe_raise_lower (struct frame *f, bool raise_flag)
11336 if (raise_flag)
11337 x_raise_frame (f);
11338 else
11339 x_lower_frame (f);
11342 /* XEmbed implementation. */
11344 #if defined USE_X_TOOLKIT || ! defined USE_GTK
11346 /* XEmbed implementation. */
11348 #define XEMBED_VERSION 0
11350 static void
11351 xembed_set_info (struct frame *f, enum xembed_info flags)
11353 unsigned long data[2];
11354 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
11356 data[0] = XEMBED_VERSION;
11357 data[1] = flags;
11359 XChangeProperty (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11360 dpyinfo->Xatom_XEMBED_INFO, dpyinfo->Xatom_XEMBED_INFO,
11361 32, PropModeReplace, (unsigned char *) data, 2);
11363 #endif /* defined USE_X_TOOLKIT || ! defined USE_GTK */
11365 static void
11366 xembed_send_message (struct frame *f, Time t, enum xembed_message msg,
11367 long int detail, long int data1, long int data2)
11369 XEvent event;
11371 event.xclient.type = ClientMessage;
11372 event.xclient.window = FRAME_X_OUTPUT (f)->parent_desc;
11373 event.xclient.message_type = FRAME_DISPLAY_INFO (f)->Xatom_XEMBED;
11374 event.xclient.format = 32;
11375 event.xclient.data.l[0] = t;
11376 event.xclient.data.l[1] = msg;
11377 event.xclient.data.l[2] = detail;
11378 event.xclient.data.l[3] = data1;
11379 event.xclient.data.l[4] = data2;
11381 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_OUTPUT (f)->parent_desc,
11382 False, NoEventMask, &event);
11383 XSync (FRAME_X_DISPLAY (f), False);
11386 /* Change of visibility. */
11388 /* This tries to wait until the frame is really visible, depending on
11389 the value of Vx_wait_for_event_timeout.
11390 However, if the window manager asks the user where to position
11391 the frame, this will return before the user finishes doing that.
11392 The frame will not actually be visible at that time,
11393 but it will become visible later when the window manager
11394 finishes with it. */
11396 void
11397 x_make_frame_visible (struct frame *f)
11399 if (FRAME_PARENT_FRAME (f))
11401 if (!FRAME_VISIBLE_P (f))
11403 block_input ();
11404 #ifdef USE_GTK
11405 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
11406 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11407 f->left_pos, f->top_pos);
11408 #else
11409 XMapRaised (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
11410 #endif
11411 unblock_input ();
11413 SET_FRAME_VISIBLE (f, true);
11414 SET_FRAME_ICONIFIED (f, false);
11416 return;
11419 block_input ();
11421 x_set_bitmap_icon (f);
11423 if (! FRAME_VISIBLE_P (f))
11425 /* We test asked_for_visible here to make sure we don't
11426 call x_set_offset a second time
11427 if we get to x_make_frame_visible a second time
11428 before the window gets really visible. */
11429 if (! FRAME_ICONIFIED_P (f)
11430 && ! FRAME_X_EMBEDDED_P (f)
11431 && ! f->output_data.x->asked_for_visible)
11432 x_set_offset (f, f->left_pos, f->top_pos, 0);
11434 f->output_data.x->asked_for_visible = true;
11436 if (! EQ (Vx_no_window_manager, Qt))
11437 x_wm_set_window_state (f, NormalState);
11438 #ifdef USE_X_TOOLKIT
11439 if (FRAME_X_EMBEDDED_P (f))
11440 xembed_set_info (f, XEMBED_MAPPED);
11441 else
11443 /* This was XtPopup, but that did nothing for an iconified frame. */
11444 XtMapWidget (f->output_data.x->widget);
11446 #else /* not USE_X_TOOLKIT */
11447 #ifdef USE_GTK
11448 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
11449 gtk_window_deiconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
11450 #else
11451 if (FRAME_X_EMBEDDED_P (f))
11452 xembed_set_info (f, XEMBED_MAPPED);
11453 else
11454 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11455 #endif /* not USE_GTK */
11456 #endif /* not USE_X_TOOLKIT */
11459 XFlush (FRAME_X_DISPLAY (f));
11461 /* Synchronize to ensure Emacs knows the frame is visible
11462 before we do anything else. We do this loop with input not blocked
11463 so that incoming events are handled. */
11465 Lisp_Object frame;
11466 /* This must be before UNBLOCK_INPUT
11467 since events that arrive in response to the actions above
11468 will set it when they are handled. */
11469 bool previously_visible = f->output_data.x->has_been_visible;
11471 XSETFRAME (frame, f);
11473 int original_left = f->left_pos;
11474 int original_top = f->top_pos;
11476 /* This must come after we set COUNT. */
11477 unblock_input ();
11479 /* We unblock here so that arriving X events are processed. */
11481 /* Now move the window back to where it was "supposed to be".
11482 But don't do it if the gravity is negative.
11483 When the gravity is negative, this uses a position
11484 that is 3 pixels too low. Perhaps that's really the border width.
11486 Don't do this if the window has never been visible before,
11487 because the window manager may choose the position
11488 and we don't want to override it. */
11490 if (!FRAME_VISIBLE_P (f)
11491 && !FRAME_ICONIFIED_P (f)
11492 && !FRAME_X_EMBEDDED_P (f)
11493 && !FRAME_PARENT_FRAME (f)
11494 && f->win_gravity == NorthWestGravity
11495 && previously_visible)
11497 Drawable rootw;
11498 int x, y;
11499 unsigned int width, height, border, depth;
11501 block_input ();
11503 /* On some window managers (such as FVWM) moving an existing
11504 window, even to the same place, causes the window manager
11505 to introduce an offset. This can cause the window to move
11506 to an unexpected location. Check the geometry (a little
11507 slow here) and then verify that the window is in the right
11508 place. If the window is not in the right place, move it
11509 there, and take the potential window manager hit. */
11510 XGetGeometry (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11511 &rootw, &x, &y, &width, &height, &border, &depth);
11513 if (original_left != x || original_top != y)
11514 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11515 original_left, original_top);
11517 unblock_input ();
11520 /* Try to wait for a MapNotify event (that is what tells us when a
11521 frame becomes visible). */
11523 #ifdef CYGWIN
11524 /* On Cygwin, which uses input polling, we need to force input to
11525 be read. See
11526 https://lists.gnu.org/r/emacs-devel/2013-12/msg00351.html
11527 and https://debbugs.gnu.org/cgi/bugreport.cgi?bug=24091#131.
11528 Fake an alarm signal to let the handler know that there's
11529 something to be read.
11531 It could be confusing if a real alarm arrives while processing
11532 the fake one. Turn it off and let the handler reset it. */
11533 int old_poll_suppress_count = poll_suppress_count;
11534 poll_suppress_count = 1;
11535 poll_for_input_1 ();
11536 poll_suppress_count = old_poll_suppress_count;
11537 #endif
11538 x_wait_for_event (f, MapNotify);
11542 /* Change from mapped state to withdrawn state. */
11544 /* Make the frame visible (mapped and not iconified). */
11546 void
11547 x_make_frame_invisible (struct frame *f)
11549 Window window;
11551 /* Use the frame's outermost window, not the one we normally draw on. */
11552 window = FRAME_OUTER_WINDOW (f);
11554 /* Don't keep the highlight on an invisible frame. */
11555 if (FRAME_DISPLAY_INFO (f)->x_highlight_frame == f)
11556 FRAME_DISPLAY_INFO (f)->x_highlight_frame = 0;
11558 block_input ();
11560 /* Before unmapping the window, update the WM_SIZE_HINTS property to claim
11561 that the current position of the window is user-specified, rather than
11562 program-specified, so that when the window is mapped again, it will be
11563 placed at the same location, without forcing the user to position it
11564 by hand again (they have already done that once for this window.) */
11565 x_wm_set_size_hint (f, 0, true);
11567 #ifdef USE_GTK
11568 if (FRAME_GTK_OUTER_WIDGET (f))
11569 gtk_widget_hide (FRAME_GTK_OUTER_WIDGET (f));
11570 else
11571 #else
11572 if (FRAME_X_EMBEDDED_P (f))
11573 xembed_set_info (f, 0);
11574 else
11575 #endif
11577 if (! XWithdrawWindow (FRAME_X_DISPLAY (f), window,
11578 DefaultScreen (FRAME_X_DISPLAY (f))))
11580 unblock_input ();
11581 error ("Can't notify window manager of window withdrawal");
11584 x_sync (f);
11586 /* We can't distinguish this from iconification
11587 just by the event that we get from the server.
11588 So we can't win using the usual strategy of letting
11589 FRAME_SAMPLE_VISIBILITY set this. So do it by hand,
11590 and synchronize with the server to make sure we agree. */
11591 SET_FRAME_VISIBLE (f, 0);
11592 SET_FRAME_ICONIFIED (f, false);
11594 unblock_input ();
11597 /* Change window state from mapped to iconified. */
11599 void
11600 x_iconify_frame (struct frame *f)
11602 #ifdef USE_X_TOOLKIT
11603 int result;
11604 #endif
11606 /* Don't keep the highlight on an invisible frame. */
11607 if (FRAME_DISPLAY_INFO (f)->x_highlight_frame == f)
11608 FRAME_DISPLAY_INFO (f)->x_highlight_frame = 0;
11610 if (FRAME_ICONIFIED_P (f))
11611 return;
11613 block_input ();
11615 x_set_bitmap_icon (f);
11617 #if defined (USE_GTK)
11618 if (FRAME_GTK_OUTER_WIDGET (f))
11620 if (! FRAME_VISIBLE_P (f))
11621 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
11623 gtk_window_iconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
11624 SET_FRAME_VISIBLE (f, 0);
11625 SET_FRAME_ICONIFIED (f, true);
11626 unblock_input ();
11627 return;
11629 #endif
11631 #ifdef USE_X_TOOLKIT
11633 if (! FRAME_VISIBLE_P (f))
11635 if (! EQ (Vx_no_window_manager, Qt))
11636 x_wm_set_window_state (f, IconicState);
11637 /* This was XtPopup, but that did nothing for an iconified frame. */
11638 XtMapWidget (f->output_data.x->widget);
11639 /* The server won't give us any event to indicate
11640 that an invisible frame was changed to an icon,
11641 so we have to record it here. */
11642 SET_FRAME_VISIBLE (f, 0);
11643 SET_FRAME_ICONIFIED (f, true);
11644 unblock_input ();
11645 return;
11648 result = XIconifyWindow (FRAME_X_DISPLAY (f),
11649 XtWindow (f->output_data.x->widget),
11650 DefaultScreen (FRAME_X_DISPLAY (f)));
11651 unblock_input ();
11653 if (!result)
11654 error ("Can't notify window manager of iconification");
11656 SET_FRAME_ICONIFIED (f, true);
11657 SET_FRAME_VISIBLE (f, 0);
11659 block_input ();
11660 XFlush (FRAME_X_DISPLAY (f));
11661 unblock_input ();
11662 #else /* not USE_X_TOOLKIT */
11664 /* Make sure the X server knows where the window should be positioned,
11665 in case the user deiconifies with the window manager. */
11666 if (! FRAME_VISIBLE_P (f)
11667 && ! FRAME_ICONIFIED_P (f)
11668 && ! FRAME_X_EMBEDDED_P (f))
11669 x_set_offset (f, f->left_pos, f->top_pos, 0);
11671 /* Since we don't know which revision of X we're running, we'll use both
11672 the X11R3 and X11R4 techniques. I don't know if this is a good idea. */
11674 /* X11R4: send a ClientMessage to the window manager using the
11675 WM_CHANGE_STATE type. */
11677 XEvent msg;
11679 msg.xclient.window = FRAME_X_WINDOW (f);
11680 msg.xclient.type = ClientMessage;
11681 msg.xclient.message_type = FRAME_DISPLAY_INFO (f)->Xatom_wm_change_state;
11682 msg.xclient.format = 32;
11683 msg.xclient.data.l[0] = IconicState;
11685 if (! XSendEvent (FRAME_X_DISPLAY (f),
11686 DefaultRootWindow (FRAME_X_DISPLAY (f)),
11687 False,
11688 SubstructureRedirectMask | SubstructureNotifyMask,
11689 &msg))
11691 unblock_input ();
11692 error ("Can't notify window manager of iconification");
11696 /* X11R3: set the initial_state field of the window manager hints to
11697 IconicState. */
11698 x_wm_set_window_state (f, IconicState);
11700 if (!FRAME_VISIBLE_P (f))
11702 /* If the frame was withdrawn, before, we must map it. */
11703 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11706 SET_FRAME_ICONIFIED (f, true);
11707 SET_FRAME_VISIBLE (f, 0);
11709 XFlush (FRAME_X_DISPLAY (f));
11710 unblock_input ();
11711 #endif /* not USE_X_TOOLKIT */
11715 /* Free X resources of frame F. */
11717 void
11718 x_free_frame_resources (struct frame *f)
11720 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
11721 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
11722 #ifdef USE_X_TOOLKIT
11723 Lisp_Object bar;
11724 struct scroll_bar *b;
11725 #endif
11727 block_input ();
11729 /* If a display connection is dead, don't try sending more
11730 commands to the X server. */
11731 if (dpyinfo->display)
11733 /* Always exit with visible pointer to avoid weird issue
11734 with Xfixes (Bug#17609). */
11735 if (f->pointer_invisible)
11736 FRAME_DISPLAY_INFO (f)->toggle_visible_pointer (f, 0);
11738 /* We must free faces before destroying windows because some
11739 font-driver (e.g. xft) access a window while finishing a
11740 face. */
11741 free_frame_faces (f);
11742 tear_down_x_back_buffer (f);
11744 if (f->output_data.x->icon_desc)
11745 XDestroyWindow (FRAME_X_DISPLAY (f), f->output_data.x->icon_desc);
11747 #ifdef USE_X_TOOLKIT
11748 /* Explicitly destroy the scroll bars of the frame. Without
11749 this, we get "BadDrawable" errors from the toolkit later on,
11750 presumably from expose events generated for the disappearing
11751 toolkit scroll bars. */
11752 for (bar = FRAME_SCROLL_BARS (f); !NILP (bar); bar = b->next)
11754 b = XSCROLL_BAR (bar);
11755 x_scroll_bar_remove (b);
11757 #endif
11759 #ifdef HAVE_X_I18N
11760 if (FRAME_XIC (f))
11761 free_frame_xic (f);
11762 #endif
11764 x_free_cr_resources (f);
11765 #ifdef USE_X_TOOLKIT
11766 if (f->output_data.x->widget)
11768 XtDestroyWidget (f->output_data.x->widget);
11769 f->output_data.x->widget = NULL;
11771 /* Tooltips don't have widgets, only a simple X window, even if
11772 we are using a toolkit. */
11773 else if (FRAME_X_WINDOW (f))
11774 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11776 free_frame_menubar (f);
11778 if (f->shell_position)
11779 xfree (f->shell_position);
11780 #else /* !USE_X_TOOLKIT */
11782 #ifdef USE_GTK
11783 xg_free_frame_widgets (f);
11784 #endif /* USE_GTK */
11786 tear_down_x_back_buffer (f);
11787 if (FRAME_X_WINDOW (f))
11788 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11789 #endif /* !USE_X_TOOLKIT */
11791 unload_color (f, FRAME_FOREGROUND_PIXEL (f));
11792 unload_color (f, FRAME_BACKGROUND_PIXEL (f));
11793 unload_color (f, f->output_data.x->cursor_pixel);
11794 unload_color (f, f->output_data.x->cursor_foreground_pixel);
11795 unload_color (f, f->output_data.x->border_pixel);
11796 unload_color (f, f->output_data.x->mouse_pixel);
11798 if (f->output_data.x->scroll_bar_background_pixel != -1)
11799 unload_color (f, f->output_data.x->scroll_bar_background_pixel);
11800 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
11801 unload_color (f, f->output_data.x->scroll_bar_foreground_pixel);
11802 #if defined (USE_LUCID) && defined (USE_TOOLKIT_SCROLL_BARS)
11803 /* Scrollbar shadow colors. */
11804 if (f->output_data.x->scroll_bar_top_shadow_pixel != -1)
11805 unload_color (f, f->output_data.x->scroll_bar_top_shadow_pixel);
11806 if (f->output_data.x->scroll_bar_bottom_shadow_pixel != -1)
11807 unload_color (f, f->output_data.x->scroll_bar_bottom_shadow_pixel);
11808 #endif /* USE_LUCID && USE_TOOLKIT_SCROLL_BARS */
11809 if (f->output_data.x->white_relief.pixel != -1)
11810 unload_color (f, f->output_data.x->white_relief.pixel);
11811 if (f->output_data.x->black_relief.pixel != -1)
11812 unload_color (f, f->output_data.x->black_relief.pixel);
11814 x_free_gcs (f);
11816 /* Free extra GCs allocated by x_setup_relief_colors. */
11817 if (f->output_data.x->white_relief.gc)
11819 XFreeGC (dpyinfo->display, f->output_data.x->white_relief.gc);
11820 f->output_data.x->white_relief.gc = 0;
11822 if (f->output_data.x->black_relief.gc)
11824 XFreeGC (dpyinfo->display, f->output_data.x->black_relief.gc);
11825 f->output_data.x->black_relief.gc = 0;
11828 /* Free cursors. */
11829 if (f->output_data.x->text_cursor != 0)
11830 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->text_cursor);
11831 if (f->output_data.x->nontext_cursor != 0)
11832 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->nontext_cursor);
11833 if (f->output_data.x->modeline_cursor != 0)
11834 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->modeline_cursor);
11835 if (f->output_data.x->hand_cursor != 0)
11836 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->hand_cursor);
11837 if (f->output_data.x->hourglass_cursor != 0)
11838 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->hourglass_cursor);
11839 if (f->output_data.x->horizontal_drag_cursor != 0)
11840 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->horizontal_drag_cursor);
11841 if (f->output_data.x->vertical_drag_cursor != 0)
11842 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->vertical_drag_cursor);
11843 if (f->output_data.x->left_edge_cursor != 0)
11844 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->left_edge_cursor);
11845 if (f->output_data.x->top_left_corner_cursor != 0)
11846 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->top_left_corner_cursor);
11847 if (f->output_data.x->top_edge_cursor != 0)
11848 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->top_edge_cursor);
11849 if (f->output_data.x->top_right_corner_cursor != 0)
11850 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->top_right_corner_cursor);
11851 if (f->output_data.x->right_edge_cursor != 0)
11852 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->right_edge_cursor);
11853 if (f->output_data.x->bottom_right_corner_cursor != 0)
11854 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->bottom_right_corner_cursor);
11855 if (f->output_data.x->bottom_edge_cursor != 0)
11856 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->bottom_edge_cursor);
11857 if (f->output_data.x->bottom_left_corner_cursor != 0)
11858 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->bottom_left_corner_cursor);
11860 XFlush (FRAME_X_DISPLAY (f));
11863 xfree (f->output_data.x->saved_menu_event);
11864 xfree (f->output_data.x);
11865 f->output_data.x = NULL;
11867 if (f == dpyinfo->x_focus_frame)
11868 dpyinfo->x_focus_frame = 0;
11869 if (f == dpyinfo->x_focus_event_frame)
11870 dpyinfo->x_focus_event_frame = 0;
11871 if (f == dpyinfo->x_highlight_frame)
11872 dpyinfo->x_highlight_frame = 0;
11873 if (f == hlinfo->mouse_face_mouse_frame)
11874 reset_mouse_highlight (hlinfo);
11876 unblock_input ();
11880 /* Destroy the X window of frame F. */
11882 static void
11883 x_destroy_window (struct frame *f)
11885 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
11887 /* If a display connection is dead, don't try sending more
11888 commands to the X server. */
11889 if (dpyinfo->display != 0)
11890 x_free_frame_resources (f);
11892 dpyinfo->reference_count--;
11896 /* Setting window manager hints. */
11898 /* Set the normal size hints for the window manager, for frame F.
11899 FLAGS is the flags word to use--or 0 meaning preserve the flags
11900 that the window now has.
11901 If USER_POSITION, set the USPosition
11902 flag (this is useful when FLAGS is 0).
11903 The GTK version is in gtkutils.c. */
11905 #ifndef USE_GTK
11906 void
11907 x_wm_set_size_hint (struct frame *f, long flags, bool user_position)
11909 XSizeHints size_hints;
11910 Window window = FRAME_OUTER_WINDOW (f);
11912 if (!window)
11913 return;
11915 #ifdef USE_X_TOOLKIT
11916 if (f->output_data.x->widget)
11918 widget_update_wm_size_hints (f->output_data.x->widget);
11919 return;
11921 #endif
11923 /* Setting PMaxSize caused various problems. */
11924 size_hints.flags = PResizeInc | PMinSize /* | PMaxSize */;
11926 size_hints.x = f->left_pos;
11927 size_hints.y = f->top_pos;
11929 size_hints.width = FRAME_PIXEL_WIDTH (f);
11930 size_hints.height = FRAME_PIXEL_HEIGHT (f);
11932 size_hints.width_inc = frame_resize_pixelwise ? 1 : FRAME_COLUMN_WIDTH (f);
11933 size_hints.height_inc = frame_resize_pixelwise ? 1 : FRAME_LINE_HEIGHT (f);
11935 size_hints.max_width = x_display_pixel_width (FRAME_DISPLAY_INFO (f))
11936 - FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
11937 size_hints.max_height = x_display_pixel_height (FRAME_DISPLAY_INFO (f))
11938 - FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
11940 /* Calculate the base and minimum sizes. */
11942 int base_width, base_height;
11944 base_width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
11945 base_height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
11947 /* The window manager uses the base width hints to calculate the
11948 current number of rows and columns in the frame while
11949 resizing; min_width and min_height aren't useful for this
11950 purpose, since they might not give the dimensions for a
11951 zero-row, zero-column frame. */
11953 size_hints.flags |= PBaseSize;
11954 size_hints.base_width = base_width;
11955 size_hints.base_height = base_height + FRAME_MENUBAR_HEIGHT (f);
11956 size_hints.min_width = base_width;
11957 size_hints.min_height = base_height;
11960 /* If we don't need the old flags, we don't need the old hint at all. */
11961 if (flags)
11963 size_hints.flags |= flags;
11964 goto no_read;
11968 XSizeHints hints; /* Sometimes I hate X Windows... */
11969 long supplied_return;
11970 int value;
11972 value = XGetWMNormalHints (FRAME_X_DISPLAY (f), window, &hints,
11973 &supplied_return);
11975 if (flags)
11976 size_hints.flags |= flags;
11977 else
11979 if (value == 0)
11980 hints.flags = 0;
11981 if (hints.flags & PSize)
11982 size_hints.flags |= PSize;
11983 if (hints.flags & PPosition)
11984 size_hints.flags |= PPosition;
11985 if (hints.flags & USPosition)
11986 size_hints.flags |= USPosition;
11987 if (hints.flags & USSize)
11988 size_hints.flags |= USSize;
11992 no_read:
11994 #ifdef PWinGravity
11995 size_hints.win_gravity = f->win_gravity;
11996 size_hints.flags |= PWinGravity;
11998 if (user_position)
12000 size_hints.flags &= ~ PPosition;
12001 size_hints.flags |= USPosition;
12003 #endif /* PWinGravity */
12005 XSetWMNormalHints (FRAME_X_DISPLAY (f), window, &size_hints);
12007 #endif /* not USE_GTK */
12009 /* Used for IconicState or NormalState */
12011 static void
12012 x_wm_set_window_state (struct frame *f, int state)
12014 #ifdef USE_X_TOOLKIT
12015 Arg al[1];
12017 XtSetArg (al[0], XtNinitialState, state);
12018 XtSetValues (f->output_data.x->widget, al, 1);
12019 #else /* not USE_X_TOOLKIT */
12020 Window window = FRAME_X_WINDOW (f);
12022 f->output_data.x->wm_hints.flags |= StateHint;
12023 f->output_data.x->wm_hints.initial_state = state;
12025 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
12026 #endif /* not USE_X_TOOLKIT */
12029 static void
12030 x_wm_set_icon_pixmap (struct frame *f, ptrdiff_t pixmap_id)
12032 Pixmap icon_pixmap, icon_mask;
12034 #if !defined USE_X_TOOLKIT && !defined USE_GTK
12035 Window window = FRAME_OUTER_WINDOW (f);
12036 #endif
12038 if (pixmap_id > 0)
12040 icon_pixmap = x_bitmap_pixmap (f, pixmap_id);
12041 f->output_data.x->wm_hints.icon_pixmap = icon_pixmap;
12042 icon_mask = x_bitmap_mask (f, pixmap_id);
12043 f->output_data.x->wm_hints.icon_mask = icon_mask;
12045 else
12047 /* It seems there is no way to turn off use of an icon
12048 pixmap. */
12049 return;
12053 #ifdef USE_GTK
12055 xg_set_frame_icon (f, icon_pixmap, icon_mask);
12056 return;
12059 #elif defined (USE_X_TOOLKIT) /* same as in x_wm_set_window_state. */
12062 Arg al[1];
12063 XtSetArg (al[0], XtNiconPixmap, icon_pixmap);
12064 XtSetValues (f->output_data.x->widget, al, 1);
12065 XtSetArg (al[0], XtNiconMask, icon_mask);
12066 XtSetValues (f->output_data.x->widget, al, 1);
12069 #else /* not USE_X_TOOLKIT && not USE_GTK */
12071 f->output_data.x->wm_hints.flags |= (IconPixmapHint | IconMaskHint);
12072 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
12074 #endif /* not USE_X_TOOLKIT && not USE_GTK */
12077 void
12078 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
12080 Window window = FRAME_OUTER_WINDOW (f);
12082 f->output_data.x->wm_hints.flags |= IconPositionHint;
12083 f->output_data.x->wm_hints.icon_x = icon_x;
12084 f->output_data.x->wm_hints.icon_y = icon_y;
12086 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
12090 /***********************************************************************
12091 Fonts
12092 ***********************************************************************/
12094 #ifdef GLYPH_DEBUG
12096 /* Check that FONT is valid on frame F. It is if it can be found in F's
12097 font table. */
12099 static void
12100 x_check_font (struct frame *f, struct font *font)
12102 eassert (font != NULL && ! NILP (font->props[FONT_TYPE_INDEX]));
12103 if (font->driver->check)
12104 eassert (font->driver->check (f, font) == 0);
12107 #endif /* GLYPH_DEBUG */
12110 /***********************************************************************
12111 Initialization
12112 ***********************************************************************/
12114 #ifdef USE_X_TOOLKIT
12115 static XrmOptionDescRec emacs_options[] = {
12116 {(char *) "-geometry", (char *) ".geometry", XrmoptionSepArg, NULL},
12117 {(char *) "-iconic", (char *) ".iconic", XrmoptionNoArg, (XtPointer) "yes"},
12119 {(char *) "-internal-border-width",
12120 (char *) "*EmacsScreen.internalBorderWidth", XrmoptionSepArg, NULL},
12121 {(char *) "-ib", (char *) "*EmacsScreen.internalBorderWidth",
12122 XrmoptionSepArg, NULL},
12123 {(char *) "-T", (char *) "*EmacsShell.title", XrmoptionSepArg, NULL},
12124 {(char *) "-wn", (char *) "*EmacsShell.title", XrmoptionSepArg, NULL},
12125 {(char *) "-title", (char *) "*EmacsShell.title", XrmoptionSepArg, NULL},
12126 {(char *) "-iconname", (char *) "*EmacsShell.iconName",
12127 XrmoptionSepArg, NULL},
12128 {(char *) "-in", (char *) "*EmacsShell.iconName", XrmoptionSepArg, NULL},
12129 {(char *) "-mc", (char *) "*pointerColor", XrmoptionSepArg, NULL},
12130 {(char *) "-cr", (char *) "*cursorColor", XrmoptionSepArg, NULL}
12133 /* Whether atimer for Xt timeouts is activated or not. */
12135 static bool x_timeout_atimer_activated_flag;
12137 #endif /* USE_X_TOOLKIT */
12139 static int x_initialized;
12141 /* Test whether two display-name strings agree up to the dot that separates
12142 the screen number from the server number. */
12143 static bool
12144 same_x_server (const char *name1, const char *name2)
12146 bool seen_colon = false;
12147 Lisp_Object sysname = Fsystem_name ();
12148 const char *system_name = SSDATA (sysname);
12149 ptrdiff_t system_name_length = SBYTES (sysname);
12150 ptrdiff_t length_until_period = 0;
12152 while (system_name[length_until_period] != 0
12153 && system_name[length_until_period] != '.')
12154 length_until_period++;
12156 /* Treat `unix' like an empty host name. */
12157 if (! strncmp (name1, "unix:", 5))
12158 name1 += 4;
12159 if (! strncmp (name2, "unix:", 5))
12160 name2 += 4;
12161 /* Treat this host's name like an empty host name. */
12162 if (! strncmp (name1, system_name, system_name_length)
12163 && name1[system_name_length] == ':')
12164 name1 += system_name_length;
12165 if (! strncmp (name2, system_name, system_name_length)
12166 && name2[system_name_length] == ':')
12167 name2 += system_name_length;
12168 /* Treat this host's domainless name like an empty host name. */
12169 if (! strncmp (name1, system_name, length_until_period)
12170 && name1[length_until_period] == ':')
12171 name1 += length_until_period;
12172 if (! strncmp (name2, system_name, length_until_period)
12173 && name2[length_until_period] == ':')
12174 name2 += length_until_period;
12176 for (; *name1 != '\0' && *name1 == *name2; name1++, name2++)
12178 if (*name1 == ':')
12179 seen_colon = true;
12180 if (seen_colon && *name1 == '.')
12181 return true;
12183 return (seen_colon
12184 && (*name1 == '.' || *name1 == '\0')
12185 && (*name2 == '.' || *name2 == '\0'));
12188 /* Count number of set bits in mask and number of bits to shift to
12189 get to the first bit. With MASK 0x7e0, *BITS is set to 6, and *OFFSET
12190 to 5. */
12191 static void
12192 get_bits_and_offset (unsigned long mask, int *bits, int *offset)
12194 int nr = 0;
12195 int off = 0;
12197 while (!(mask & 1))
12199 off++;
12200 mask >>= 1;
12203 while (mask & 1)
12205 nr++;
12206 mask >>= 1;
12209 *offset = off;
12210 *bits = nr;
12213 /* Return true iff display DISPLAY is available for use.
12214 But don't permanently open it, just test its availability. */
12216 bool
12217 x_display_ok (const char *display)
12219 /* XOpenDisplay fails if it gets a signal. Block SIGIO which may arrive. */
12220 unrequest_sigio ();
12221 Display *dpy = XOpenDisplay (display);
12222 request_sigio ();
12223 if (!dpy)
12224 return false;
12225 XCloseDisplay (dpy);
12226 return true;
12229 #ifdef USE_GTK
12230 static void
12231 my_log_handler (const gchar *log_domain, GLogLevelFlags log_level,
12232 const gchar *msg, gpointer user_data)
12234 if (!strstr (msg, "g_set_prgname"))
12235 fprintf (stderr, "%s-WARNING **: %s\n", log_domain, msg);
12237 #endif
12239 /* Create invisible cursor on X display referred by DPYINFO. */
12241 static Cursor
12242 make_invisible_cursor (struct x_display_info *dpyinfo)
12244 Display *dpy = dpyinfo->display;
12245 static char const no_data[] = { 0 };
12246 Pixmap pix;
12247 XColor col;
12248 Cursor c = 0;
12250 x_catch_errors (dpy);
12251 pix = XCreateBitmapFromData (dpy, dpyinfo->root_window, no_data, 1, 1);
12252 if (! x_had_errors_p (dpy) && pix != None)
12254 Cursor pixc;
12255 col.pixel = 0;
12256 col.red = col.green = col.blue = 0;
12257 col.flags = DoRed | DoGreen | DoBlue;
12258 pixc = XCreatePixmapCursor (dpy, pix, pix, &col, &col, 0, 0);
12259 if (! x_had_errors_p (dpy) && pixc != None)
12260 c = pixc;
12261 XFreePixmap (dpy, pix);
12264 x_uncatch_errors ();
12266 return c;
12269 /* True if DPY supports Xfixes extension >= 4. */
12271 static bool
12272 x_probe_xfixes_extension (Display *dpy)
12274 #ifdef HAVE_XFIXES
12275 int major, minor;
12276 return XFixesQueryVersion (dpy, &major, &minor) && major >= 4;
12277 #else
12278 return false;
12279 #endif /* HAVE_XFIXES */
12282 /* Toggle mouse pointer visibility on frame F by using Xfixes functions. */
12284 static void
12285 xfixes_toggle_visible_pointer (struct frame *f, bool invisible)
12287 #ifdef HAVE_XFIXES
12288 if (invisible)
12289 XFixesHideCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
12290 else
12291 XFixesShowCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
12292 f->pointer_invisible = invisible;
12293 #else
12294 emacs_abort ();
12295 #endif /* HAVE_XFIXES */
12298 /* Toggle mouse pointer visibility on frame F by using invisible cursor. */
12300 static void
12301 x_toggle_visible_pointer (struct frame *f, bool invisible)
12303 eassert (FRAME_DISPLAY_INFO (f)->invisible_cursor != 0);
12304 if (invisible)
12305 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
12306 FRAME_DISPLAY_INFO (f)->invisible_cursor);
12307 else
12308 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
12309 f->output_data.x->current_cursor);
12310 f->pointer_invisible = invisible;
12313 /* Setup pointer blanking, prefer Xfixes if available. */
12315 static void
12316 x_setup_pointer_blanking (struct x_display_info *dpyinfo)
12318 /* FIXME: the brave tester should set EMACS_XFIXES because we're suspecting
12319 X server bug, see https://debbugs.gnu.org/cgi/bugreport.cgi?bug=17609. */
12320 if (egetenv ("EMACS_XFIXES") && x_probe_xfixes_extension (dpyinfo->display))
12321 dpyinfo->toggle_visible_pointer = xfixes_toggle_visible_pointer;
12322 else
12324 dpyinfo->toggle_visible_pointer = x_toggle_visible_pointer;
12325 dpyinfo->invisible_cursor = make_invisible_cursor (dpyinfo);
12329 /* Current X display connection identifier. Incremented for each next
12330 connection established. */
12331 static unsigned x_display_id;
12333 /* Open a connection to X display DISPLAY_NAME, and return
12334 the structure that describes the open display.
12335 If we cannot contact the display, return null. */
12337 struct x_display_info *
12338 x_term_init (Lisp_Object display_name, char *xrm_option, char *resource_name)
12340 Display *dpy;
12341 struct terminal *terminal;
12342 struct x_display_info *dpyinfo;
12343 XrmDatabase xrdb;
12344 #ifdef USE_XCB
12345 xcb_connection_t *xcb_conn;
12346 #endif
12348 block_input ();
12350 if (!x_initialized)
12352 x_initialize ();
12353 ++x_initialized;
12356 if (! x_display_ok (SSDATA (display_name)))
12357 error ("Display %s can't be opened", SSDATA (display_name));
12359 #ifdef USE_GTK
12361 #define NUM_ARGV 10
12362 int argc;
12363 char *argv[NUM_ARGV];
12364 char **argv2 = argv;
12365 guint id;
12367 if (x_initialized++ > 1)
12369 xg_display_open (SSDATA (display_name), &dpy);
12371 else
12373 static char display_opt[] = "--display";
12374 static char name_opt[] = "--name";
12376 for (argc = 0; argc < NUM_ARGV; ++argc)
12377 argv[argc] = 0;
12379 argc = 0;
12380 argv[argc++] = initial_argv[0];
12382 if (! NILP (display_name))
12384 argv[argc++] = display_opt;
12385 argv[argc++] = SSDATA (display_name);
12388 argv[argc++] = name_opt;
12389 argv[argc++] = resource_name;
12391 XSetLocaleModifiers ("");
12393 /* Work around GLib bug that outputs a faulty warning. See
12394 https://bugzilla.gnome.org/show_bug.cgi?id=563627. */
12395 id = g_log_set_handler ("GLib", G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
12396 | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
12398 /* NULL window -> events for all windows go to our function.
12399 Call before gtk_init so Gtk+ event filters comes after our. */
12400 gdk_window_add_filter (NULL, event_handler_gdk, NULL);
12402 /* gtk_init does set_locale. Fix locale before and after. */
12403 fixup_locale ();
12404 unrequest_sigio (); /* See comment in x_display_ok. */
12405 gtk_init (&argc, &argv2);
12406 request_sigio ();
12407 fixup_locale ();
12409 g_log_remove_handler ("GLib", id);
12411 xg_initialize ();
12413 dpy = DEFAULT_GDK_DISPLAY ();
12415 #if ! GTK_CHECK_VERSION (2, 90, 0)
12416 /* Load our own gtkrc if it exists. */
12418 const char *file = "~/.emacs.d/gtkrc";
12419 Lisp_Object s, abs_file;
12421 s = build_string (file);
12422 abs_file = Fexpand_file_name (s, Qnil);
12424 if (! NILP (abs_file) && !NILP (Ffile_readable_p (abs_file)))
12425 gtk_rc_parse (SSDATA (abs_file));
12427 #endif
12429 XSetErrorHandler (x_error_handler);
12430 XSetIOErrorHandler (x_io_error_quitter);
12433 #else /* not USE_GTK */
12434 #ifdef USE_X_TOOLKIT
12435 /* weiner@footloose.sps.mot.com reports that this causes
12436 errors with X11R5:
12437 X protocol error: BadAtom (invalid Atom parameter)
12438 on protocol request 18skiloaf.
12439 So let's not use it until R6. */
12440 #ifdef HAVE_X11XTR6
12441 XtSetLanguageProc (NULL, NULL, NULL);
12442 #endif
12445 int argc = 0;
12446 char *argv[3];
12448 argv[0] = (char *) "";
12449 argc = 1;
12450 if (xrm_option)
12452 argv[argc++] = (char *) "-xrm";
12453 argv[argc++] = xrm_option;
12455 turn_on_atimers (false);
12456 unrequest_sigio (); /* See comment in x_display_ok. */
12457 dpy = XtOpenDisplay (Xt_app_con, SSDATA (display_name),
12458 resource_name, EMACS_CLASS,
12459 emacs_options, XtNumber (emacs_options),
12460 &argc, argv);
12461 request_sigio ();
12462 turn_on_atimers (true);
12464 #ifdef HAVE_X11XTR6
12465 /* I think this is to compensate for XtSetLanguageProc. */
12466 fixup_locale ();
12467 #endif
12470 #else /* not USE_X_TOOLKIT */
12471 XSetLocaleModifiers ("");
12472 unrequest_sigio (); /* See comment in x_display_ok. */
12473 dpy = XOpenDisplay (SSDATA (display_name));
12474 request_sigio ();
12475 #endif /* not USE_X_TOOLKIT */
12476 #endif /* not USE_GTK*/
12478 /* Detect failure. */
12479 if (dpy == 0)
12481 unblock_input ();
12482 return 0;
12485 #ifdef USE_XCB
12486 xcb_conn = XGetXCBConnection (dpy);
12487 if (xcb_conn == 0)
12489 #ifdef USE_GTK
12490 xg_display_close (dpy);
12491 #else
12492 #ifdef USE_X_TOOLKIT
12493 XtCloseDisplay (dpy);
12494 #else
12495 XCloseDisplay (dpy);
12496 #endif
12497 #endif /* ! USE_GTK */
12499 unblock_input ();
12500 return 0;
12502 #endif
12504 /* We have definitely succeeded. Record the new connection. */
12506 dpyinfo = xzalloc (sizeof *dpyinfo);
12507 terminal = x_create_terminal (dpyinfo);
12510 struct x_display_info *share;
12512 for (share = x_display_list; share; share = share->next)
12513 if (same_x_server (SSDATA (XCAR (share->name_list_element)),
12514 SSDATA (display_name)))
12515 break;
12516 if (share)
12517 terminal->kboard = share->terminal->kboard;
12518 else
12520 terminal->kboard = allocate_kboard (Qx);
12522 if (!EQ (XSYMBOL (Qvendor_specific_keysyms)->u.s.function, Qunbound))
12524 char *vendor = ServerVendor (dpy);
12526 /* Temporarily hide the partially initialized terminal. */
12527 terminal_list = terminal->next_terminal;
12528 unblock_input ();
12529 kset_system_key_alist
12530 (terminal->kboard,
12531 call1 (Qvendor_specific_keysyms,
12532 vendor ? build_string (vendor) : empty_unibyte_string));
12533 block_input ();
12534 terminal->next_terminal = terminal_list;
12535 terminal_list = terminal;
12538 /* Don't let the initial kboard remain current longer than necessary.
12539 That would cause problems if a file loaded on startup tries to
12540 prompt in the mini-buffer. */
12541 if (current_kboard == initial_kboard)
12542 current_kboard = terminal->kboard;
12544 terminal->kboard->reference_count++;
12547 /* Put this display on the chain. */
12548 dpyinfo->next = x_display_list;
12549 x_display_list = dpyinfo;
12551 dpyinfo->name_list_element = Fcons (display_name, Qnil);
12552 dpyinfo->display = dpy;
12553 dpyinfo->connection = ConnectionNumber (dpyinfo->display);
12554 #ifdef USE_XCB
12555 dpyinfo->xcb_connection = xcb_conn;
12556 #endif
12558 /* https://lists.gnu.org/r/emacs-devel/2015-11/msg00194.html */
12559 dpyinfo->smallest_font_height = 1;
12560 dpyinfo->smallest_char_width = 1;
12562 /* Set the name of the terminal. */
12563 terminal->name = xlispstrdup (display_name);
12565 #if false
12566 XSetAfterFunction (x_current_display, x_trace_wire);
12567 #endif
12569 Lisp_Object system_name = Fsystem_name ();
12570 ptrdiff_t nbytes;
12571 if (INT_ADD_WRAPV (SBYTES (Vinvocation_name), SBYTES (system_name) + 2,
12572 &nbytes))
12573 memory_full (SIZE_MAX);
12574 dpyinfo->x_id = ++x_display_id;
12575 dpyinfo->x_id_name = xmalloc (nbytes);
12576 char *nametail = lispstpcpy (dpyinfo->x_id_name, Vinvocation_name);
12577 *nametail++ = '@';
12578 lispstpcpy (nametail, system_name);
12580 /* Figure out which modifier bits mean what. */
12581 x_find_modifier_meanings (dpyinfo);
12583 /* Get the scroll bar cursor. */
12584 #ifdef USE_GTK
12585 /* We must create a GTK cursor, it is required for GTK widgets. */
12586 dpyinfo->xg_cursor = xg_create_default_cursor (dpyinfo->display);
12587 #endif /* USE_GTK */
12589 dpyinfo->vertical_scroll_bar_cursor
12590 = XCreateFontCursor (dpyinfo->display, XC_sb_v_double_arrow);
12592 dpyinfo->horizontal_scroll_bar_cursor
12593 = XCreateFontCursor (dpyinfo->display, XC_sb_h_double_arrow);
12595 xrdb = x_load_resources (dpyinfo->display, xrm_option,
12596 resource_name, EMACS_CLASS);
12597 #ifdef HAVE_XRMSETDATABASE
12598 XrmSetDatabase (dpyinfo->display, xrdb);
12599 #else
12600 dpyinfo->display->db = xrdb;
12601 #endif
12602 /* Put the rdb where we can find it in a way that works on
12603 all versions. */
12604 dpyinfo->xrdb = xrdb;
12606 dpyinfo->screen = ScreenOfDisplay (dpyinfo->display,
12607 DefaultScreen (dpyinfo->display));
12608 select_visual (dpyinfo);
12609 dpyinfo->cmap = DefaultColormapOfScreen (dpyinfo->screen);
12610 dpyinfo->root_window = RootWindowOfScreen (dpyinfo->screen);
12611 dpyinfo->icon_bitmap_id = -1;
12612 dpyinfo->wm_type = X_WMTYPE_UNKNOWN;
12614 reset_mouse_highlight (&dpyinfo->mouse_highlight);
12616 /* See if we can construct pixel values from RGB values. */
12617 if (dpyinfo->visual->class == TrueColor)
12619 get_bits_and_offset (dpyinfo->visual->red_mask,
12620 &dpyinfo->red_bits, &dpyinfo->red_offset);
12621 get_bits_and_offset (dpyinfo->visual->blue_mask,
12622 &dpyinfo->blue_bits, &dpyinfo->blue_offset);
12623 get_bits_and_offset (dpyinfo->visual->green_mask,
12624 &dpyinfo->green_bits, &dpyinfo->green_offset);
12627 /* See if a private colormap is requested. */
12628 if (dpyinfo->visual == DefaultVisualOfScreen (dpyinfo->screen))
12630 if (dpyinfo->visual->class == PseudoColor)
12632 AUTO_STRING (privateColormap, "privateColormap");
12633 AUTO_STRING (PrivateColormap, "PrivateColormap");
12634 Lisp_Object value
12635 = display_x_get_resource (dpyinfo, privateColormap,
12636 PrivateColormap, Qnil, Qnil);
12637 if (STRINGP (value)
12638 && (!strcmp (SSDATA (value), "true")
12639 || !strcmp (SSDATA (value), "on")))
12640 dpyinfo->cmap = XCopyColormapAndFree (dpyinfo->display, dpyinfo->cmap);
12643 else
12644 dpyinfo->cmap = XCreateColormap (dpyinfo->display, dpyinfo->root_window,
12645 dpyinfo->visual, AllocNone);
12647 #ifdef HAVE_XDBE
12648 dpyinfo->supports_xdbe = false;
12649 int xdbe_major;
12650 int xdbe_minor;
12651 if (XdbeQueryExtension (dpyinfo->display, &xdbe_major, &xdbe_minor))
12652 dpyinfo->supports_xdbe = true;
12653 #endif
12655 #ifdef HAVE_XFT
12657 /* If we are using Xft, the following precautions should be made:
12659 1. Make sure that the Xrender extension is added before the Xft one.
12660 Otherwise, the close-display hook set by Xft is called after the one
12661 for Xrender, and the former tries to re-add the latter. This results
12662 in inconsistency of internal states and leads to X protocol error when
12663 one reconnects to the same X server (Bug#1696).
12665 2. Check dpi value in X resources. It is better we use it as well,
12666 since Xft will use it, as will all Gnome applications. If our real DPI
12667 is smaller or larger than the one Xft uses, our font will look smaller
12668 or larger than other for other applications, even if it is the same
12669 font name (monospace-10 for example). */
12671 int event_base, error_base;
12672 char *v;
12673 double d;
12675 XRenderQueryExtension (dpyinfo->display, &event_base, &error_base);
12677 v = XGetDefault (dpyinfo->display, "Xft", "dpi");
12678 if (v != NULL && sscanf (v, "%lf", &d) == 1)
12679 dpyinfo->resy = dpyinfo->resx = d;
12681 #endif
12683 if (dpyinfo->resy < 1)
12685 int screen_number = XScreenNumberOfScreen (dpyinfo->screen);
12686 double pixels = DisplayHeight (dpyinfo->display, screen_number);
12687 double mm = DisplayHeightMM (dpyinfo->display, screen_number);
12688 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
12689 dpyinfo->resy = (mm < 1) ? 100 : pixels * 25.4 / mm;
12690 pixels = DisplayWidth (dpyinfo->display, screen_number);
12691 mm = DisplayWidthMM (dpyinfo->display, screen_number);
12692 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
12693 dpyinfo->resx = (mm < 1) ? 100 : pixels * 25.4 / mm;
12697 static const struct
12699 const char *name;
12700 int offset;
12701 } atom_refs[] = {
12702 #define ATOM_REFS_INIT(string, member) \
12703 { string, offsetof (struct x_display_info, member) },
12704 ATOM_REFS_INIT ("WM_PROTOCOLS", Xatom_wm_protocols)
12705 ATOM_REFS_INIT ("WM_TAKE_FOCUS", Xatom_wm_take_focus)
12706 ATOM_REFS_INIT ("WM_SAVE_YOURSELF", Xatom_wm_save_yourself)
12707 ATOM_REFS_INIT ("WM_DELETE_WINDOW", Xatom_wm_delete_window)
12708 ATOM_REFS_INIT ("WM_CHANGE_STATE", Xatom_wm_change_state)
12709 ATOM_REFS_INIT ("WM_CONFIGURE_DENIED", Xatom_wm_configure_denied)
12710 ATOM_REFS_INIT ("WM_MOVED", Xatom_wm_window_moved)
12711 ATOM_REFS_INIT ("WM_CLIENT_LEADER", Xatom_wm_client_leader)
12712 ATOM_REFS_INIT ("Editres", Xatom_editres)
12713 ATOM_REFS_INIT ("CLIPBOARD", Xatom_CLIPBOARD)
12714 ATOM_REFS_INIT ("TIMESTAMP", Xatom_TIMESTAMP)
12715 ATOM_REFS_INIT ("TEXT", Xatom_TEXT)
12716 ATOM_REFS_INIT ("COMPOUND_TEXT", Xatom_COMPOUND_TEXT)
12717 ATOM_REFS_INIT ("UTF8_STRING", Xatom_UTF8_STRING)
12718 ATOM_REFS_INIT ("DELETE", Xatom_DELETE)
12719 ATOM_REFS_INIT ("MULTIPLE", Xatom_MULTIPLE)
12720 ATOM_REFS_INIT ("INCR", Xatom_INCR)
12721 ATOM_REFS_INIT ("_EMACS_TMP_", Xatom_EMACS_TMP)
12722 ATOM_REFS_INIT ("TARGETS", Xatom_TARGETS)
12723 ATOM_REFS_INIT ("NULL", Xatom_NULL)
12724 ATOM_REFS_INIT ("ATOM", Xatom_ATOM)
12725 ATOM_REFS_INIT ("ATOM_PAIR", Xatom_ATOM_PAIR)
12726 ATOM_REFS_INIT ("CLIPBOARD_MANAGER", Xatom_CLIPBOARD_MANAGER)
12727 ATOM_REFS_INIT ("_XEMBED_INFO", Xatom_XEMBED_INFO)
12728 /* For properties of font. */
12729 ATOM_REFS_INIT ("PIXEL_SIZE", Xatom_PIXEL_SIZE)
12730 ATOM_REFS_INIT ("AVERAGE_WIDTH", Xatom_AVERAGE_WIDTH)
12731 ATOM_REFS_INIT ("_MULE_BASELINE_OFFSET", Xatom_MULE_BASELINE_OFFSET)
12732 ATOM_REFS_INIT ("_MULE_RELATIVE_COMPOSE", Xatom_MULE_RELATIVE_COMPOSE)
12733 ATOM_REFS_INIT ("_MULE_DEFAULT_ASCENT", Xatom_MULE_DEFAULT_ASCENT)
12734 /* Ghostscript support. */
12735 ATOM_REFS_INIT ("DONE", Xatom_DONE)
12736 ATOM_REFS_INIT ("PAGE", Xatom_PAGE)
12737 ATOM_REFS_INIT ("SCROLLBAR", Xatom_Scrollbar)
12738 ATOM_REFS_INIT ("HORIZONTAL_SCROLLBAR", Xatom_Horizontal_Scrollbar)
12739 ATOM_REFS_INIT ("_XEMBED", Xatom_XEMBED)
12740 /* EWMH */
12741 ATOM_REFS_INIT ("_NET_WM_STATE", Xatom_net_wm_state)
12742 ATOM_REFS_INIT ("_NET_WM_STATE_FULLSCREEN", Xatom_net_wm_state_fullscreen)
12743 ATOM_REFS_INIT ("_NET_WM_STATE_MAXIMIZED_HORZ",
12744 Xatom_net_wm_state_maximized_horz)
12745 ATOM_REFS_INIT ("_NET_WM_STATE_MAXIMIZED_VERT",
12746 Xatom_net_wm_state_maximized_vert)
12747 ATOM_REFS_INIT ("_NET_WM_STATE_STICKY", Xatom_net_wm_state_sticky)
12748 ATOM_REFS_INIT ("_NET_WM_STATE_HIDDEN", Xatom_net_wm_state_hidden)
12749 ATOM_REFS_INIT ("_NET_WM_WINDOW_TYPE", Xatom_net_window_type)
12750 ATOM_REFS_INIT ("_NET_WM_WINDOW_TYPE_TOOLTIP",
12751 Xatom_net_window_type_tooltip)
12752 ATOM_REFS_INIT ("_NET_WM_ICON_NAME", Xatom_net_wm_icon_name)
12753 ATOM_REFS_INIT ("_NET_WM_NAME", Xatom_net_wm_name)
12754 ATOM_REFS_INIT ("_NET_SUPPORTED", Xatom_net_supported)
12755 ATOM_REFS_INIT ("_NET_SUPPORTING_WM_CHECK", Xatom_net_supporting_wm_check)
12756 ATOM_REFS_INIT ("_NET_WM_WINDOW_OPACITY", Xatom_net_wm_window_opacity)
12757 ATOM_REFS_INIT ("_NET_ACTIVE_WINDOW", Xatom_net_active_window)
12758 ATOM_REFS_INIT ("_NET_FRAME_EXTENTS", Xatom_net_frame_extents)
12759 ATOM_REFS_INIT ("_NET_CURRENT_DESKTOP", Xatom_net_current_desktop)
12760 ATOM_REFS_INIT ("_NET_WORKAREA", Xatom_net_workarea)
12761 /* Session management */
12762 ATOM_REFS_INIT ("SM_CLIENT_ID", Xatom_SM_CLIENT_ID)
12763 ATOM_REFS_INIT ("_XSETTINGS_SETTINGS", Xatom_xsettings_prop)
12764 ATOM_REFS_INIT ("MANAGER", Xatom_xsettings_mgr)
12765 ATOM_REFS_INIT ("_NET_WM_STATE_SKIP_TASKBAR", Xatom_net_wm_state_skip_taskbar)
12766 ATOM_REFS_INIT ("_NET_WM_STATE_ABOVE", Xatom_net_wm_state_above)
12767 ATOM_REFS_INIT ("_NET_WM_STATE_BELOW", Xatom_net_wm_state_below)
12770 int i;
12771 enum { atom_count = ARRAYELTS (atom_refs) };
12772 /* 1 for _XSETTINGS_SN. */
12773 enum { total_atom_count = 1 + atom_count };
12774 Atom atoms_return[total_atom_count];
12775 char *atom_names[total_atom_count];
12776 static char const xsettings_fmt[] = "_XSETTINGS_S%d";
12777 char xsettings_atom_name[sizeof xsettings_fmt - 2
12778 + INT_STRLEN_BOUND (int)];
12780 for (i = 0; i < atom_count; i++)
12781 atom_names[i] = (char *) atom_refs[i].name;
12783 /* Build _XSETTINGS_SN atom name. */
12784 sprintf (xsettings_atom_name, xsettings_fmt,
12785 XScreenNumberOfScreen (dpyinfo->screen));
12786 atom_names[i] = xsettings_atom_name;
12788 XInternAtoms (dpyinfo->display, atom_names, total_atom_count,
12789 False, atoms_return);
12791 for (i = 0; i < atom_count; i++)
12792 *(Atom *) ((char *) dpyinfo + atom_refs[i].offset) = atoms_return[i];
12794 /* Manually copy last atom. */
12795 dpyinfo->Xatom_xsettings_sel = atoms_return[i];
12798 dpyinfo->x_dnd_atoms_size = 8;
12799 dpyinfo->x_dnd_atoms = xmalloc (sizeof *dpyinfo->x_dnd_atoms
12800 * dpyinfo->x_dnd_atoms_size);
12801 dpyinfo->gray
12802 = XCreatePixmapFromBitmapData (dpyinfo->display, dpyinfo->root_window,
12803 gray_bits, gray_width, gray_height,
12804 1, 0, 1);
12806 x_setup_pointer_blanking (dpyinfo);
12808 #ifdef HAVE_X_I18N
12809 xim_initialize (dpyinfo, resource_name);
12810 #endif
12812 xsettings_initialize (dpyinfo);
12814 /* This is only needed for distinguishing keyboard and process input. */
12815 if (dpyinfo->connection != 0)
12816 add_keyboard_wait_descriptor (dpyinfo->connection);
12818 #ifdef F_SETOWN
12819 fcntl (dpyinfo->connection, F_SETOWN, getpid ());
12820 #endif /* ! defined (F_SETOWN) */
12822 if (interrupt_input)
12823 init_sigio (dpyinfo->connection);
12825 #ifdef USE_LUCID
12827 XrmValue d, fr, to;
12828 Font font;
12830 dpy = dpyinfo->display;
12831 d.addr = (XPointer)&dpy;
12832 d.size = sizeof (Display *);
12833 fr.addr = (char *) XtDefaultFont;
12834 fr.size = sizeof (XtDefaultFont);
12835 to.size = sizeof (Font *);
12836 to.addr = (XPointer)&font;
12837 x_catch_errors (dpy);
12838 if (!XtCallConverter (dpy, XtCvtStringToFont, &d, 1, &fr, &to, NULL))
12839 emacs_abort ();
12840 if (x_had_errors_p (dpy) || !XQueryFont (dpy, font))
12841 XrmPutLineResource (&xrdb, "Emacs.dialog.*.font: 9x15");
12842 /* Do not free XFontStruct returned by the above call to XQueryFont.
12843 This leads to X protocol errors at XtCloseDisplay (Bug#18403). */
12844 x_uncatch_errors ();
12846 #endif
12848 /* See if we should run in synchronous mode. This is useful
12849 for debugging X code. */
12851 AUTO_STRING (synchronous, "synchronous");
12852 AUTO_STRING (Synchronous, "Synchronous");
12853 Lisp_Object value = display_x_get_resource (dpyinfo, synchronous,
12854 Synchronous, Qnil, Qnil);
12855 if (STRINGP (value)
12856 && (!strcmp (SSDATA (value), "true")
12857 || !strcmp (SSDATA (value), "on")))
12858 XSynchronize (dpyinfo->display, True);
12862 AUTO_STRING (useXIM, "useXIM");
12863 AUTO_STRING (UseXIM, "UseXIM");
12864 Lisp_Object value = display_x_get_resource (dpyinfo, useXIM, UseXIM,
12865 Qnil, Qnil);
12866 #ifdef USE_XIM
12867 if (STRINGP (value)
12868 && (!strcmp (SSDATA (value), "false")
12869 || !strcmp (SSDATA (value), "off")))
12870 use_xim = false;
12871 #else
12872 if (STRINGP (value)
12873 && (!strcmp (SSDATA (value), "true")
12874 || !strcmp (SSDATA (value), "on")))
12875 use_xim = true;
12876 #endif
12879 #ifdef HAVE_X_SM
12880 /* Only do this for the very first display in the Emacs session.
12881 Ignore X session management when Emacs was first started on a
12882 tty or started as a daemon. */
12883 if (terminal->id == 1 && ! IS_DAEMON)
12884 x_session_initialize (dpyinfo);
12885 #endif
12887 #ifdef USE_CAIRO
12888 x_extension_initialize (dpyinfo);
12889 #endif
12891 unblock_input ();
12893 return dpyinfo;
12896 /* Get rid of display DPYINFO, deleting all frames on it,
12897 and without sending any more commands to the X server. */
12899 static void
12900 x_delete_display (struct x_display_info *dpyinfo)
12902 struct terminal *t;
12903 struct color_name_cache_entry *color_entry, *next_color_entry;
12905 /* Close all frames and delete the generic struct terminal for this
12906 X display. */
12907 for (t = terminal_list; t; t = t->next_terminal)
12908 if (t->type == output_x_window && t->display_info.x == dpyinfo)
12910 #ifdef HAVE_X_SM
12911 /* Close X session management when we close its display. */
12912 if (t->id == 1 && x_session_have_connection ())
12913 x_session_close ();
12914 #endif
12915 delete_terminal (t);
12916 break;
12919 if (next_noop_dpyinfo == dpyinfo)
12920 next_noop_dpyinfo = dpyinfo->next;
12922 if (x_display_list == dpyinfo)
12923 x_display_list = dpyinfo->next;
12924 else
12926 struct x_display_info *tail;
12928 for (tail = x_display_list; tail; tail = tail->next)
12929 if (tail->next == dpyinfo)
12930 tail->next = tail->next->next;
12933 for (color_entry = dpyinfo->color_names;
12934 color_entry;
12935 color_entry = next_color_entry)
12937 next_color_entry = color_entry->next;
12938 xfree (color_entry->name);
12939 xfree (color_entry);
12942 xfree (dpyinfo->x_id_name);
12943 xfree (dpyinfo->x_dnd_atoms);
12944 xfree (dpyinfo->color_cells);
12945 xfree (dpyinfo);
12948 #ifdef USE_X_TOOLKIT
12950 /* Atimer callback function for TIMER. Called every 0.1s to process
12951 Xt timeouts, if needed. We must avoid calling XtAppPending as
12952 much as possible because that function does an implicit XFlush
12953 that slows us down. */
12955 static void
12956 x_process_timeouts (struct atimer *timer)
12958 block_input ();
12959 x_timeout_atimer_activated_flag = false;
12960 if (toolkit_scroll_bar_interaction || popup_activated ())
12962 while (XtAppPending (Xt_app_con) & XtIMTimer)
12963 XtAppProcessEvent (Xt_app_con, XtIMTimer);
12964 /* Reactivate the atimer for next time. */
12965 x_activate_timeout_atimer ();
12967 unblock_input ();
12970 /* Install an asynchronous timer that processes Xt timeout events
12971 every 0.1s as long as either `toolkit_scroll_bar_interaction' or
12972 `popup_activated_flag' (in xmenu.c) is set. Make sure to call this
12973 function whenever these variables are set. This is necessary
12974 because some widget sets use timeouts internally, for example the
12975 LessTif menu bar, or the Xaw3d scroll bar. When Xt timeouts aren't
12976 processed, these widgets don't behave normally. */
12978 void
12979 x_activate_timeout_atimer (void)
12981 block_input ();
12982 if (!x_timeout_atimer_activated_flag)
12984 struct timespec interval = make_timespec (0, 100 * 1000 * 1000);
12985 start_atimer (ATIMER_RELATIVE, interval, x_process_timeouts, 0);
12986 x_timeout_atimer_activated_flag = true;
12988 unblock_input ();
12991 #endif /* USE_X_TOOLKIT */
12994 /* Set up use of X before we make the first connection. */
12996 static struct redisplay_interface x_redisplay_interface =
12998 x_frame_parm_handlers,
12999 x_produce_glyphs,
13000 x_write_glyphs,
13001 x_insert_glyphs,
13002 x_clear_end_of_line,
13003 x_scroll_run,
13004 x_after_update_window_line,
13005 x_update_window_begin,
13006 x_update_window_end,
13007 x_flip_and_flush,
13008 x_clear_window_mouse_face,
13009 x_get_glyph_overhangs,
13010 x_fix_overlapping_area,
13011 x_draw_fringe_bitmap,
13012 #ifdef USE_CAIRO
13013 x_cr_define_fringe_bitmap,
13014 x_cr_destroy_fringe_bitmap,
13015 #else
13016 0, /* define_fringe_bitmap */
13017 0, /* destroy_fringe_bitmap */
13018 #endif
13019 x_compute_glyph_string_overhangs,
13020 x_draw_glyph_string,
13021 x_define_frame_cursor,
13022 x_clear_frame_area,
13023 x_draw_window_cursor,
13024 x_draw_vertical_window_border,
13025 x_draw_window_divider,
13026 x_shift_glyphs_for_insert, /* Never called; see comment in function. */
13027 x_show_hourglass,
13028 x_hide_hourglass
13032 /* This function is called when the last frame on a display is deleted. */
13033 void
13034 x_delete_terminal (struct terminal *terminal)
13036 struct x_display_info *dpyinfo = terminal->display_info.x;
13038 /* Protect against recursive calls. delete_frame in
13039 delete_terminal calls us back when it deletes our last frame. */
13040 if (!terminal->name)
13041 return;
13043 block_input ();
13044 #ifdef HAVE_X_I18N
13045 /* We must close our connection to the XIM server before closing the
13046 X display. */
13047 if (dpyinfo->xim)
13048 xim_close_dpy (dpyinfo);
13049 #endif
13051 /* Normally, the display is available... */
13052 if (dpyinfo->display)
13054 x_destroy_all_bitmaps (dpyinfo);
13055 XSetCloseDownMode (dpyinfo->display, DestroyAll);
13057 /* Whether or not XCloseDisplay destroys the associated resource
13058 database depends on the version of libX11. To avoid both
13059 crash and memory leak, we dissociate the database from the
13060 display and then destroy dpyinfo->xrdb ourselves.
13062 Unfortunately, the above strategy does not work in some
13063 situations due to a bug in newer versions of libX11: because
13064 XrmSetDatabase doesn't clear the flag XlibDisplayDfltRMDB if
13065 dpy->db is NULL, XCloseDisplay destroys the associated
13066 database whereas it has not been created by XGetDefault
13067 (Bug#21974 in freedesktop.org Bugzilla). As a workaround, we
13068 don't destroy the database here in order to avoid the crash
13069 in the above situations for now, though that may cause memory
13070 leaks in other situations. */
13071 #if false
13072 #ifdef HAVE_XRMSETDATABASE
13073 XrmSetDatabase (dpyinfo->display, NULL);
13074 #else
13075 dpyinfo->display->db = NULL;
13076 #endif
13077 /* We used to call XrmDestroyDatabase from x_delete_display, but
13078 some older versions of libX11 crash if we call it after
13079 closing all the displays. */
13080 XrmDestroyDatabase (dpyinfo->xrdb);
13081 #endif
13083 #ifdef USE_GTK
13084 xg_display_close (dpyinfo->display);
13085 #else
13086 #ifdef USE_X_TOOLKIT
13087 XtCloseDisplay (dpyinfo->display);
13088 #else
13089 XCloseDisplay (dpyinfo->display);
13090 #endif
13091 #endif /* ! USE_GTK */
13092 /* Do not close the connection here because it's already closed
13093 by X(t)CloseDisplay (Bug#18403). */
13094 dpyinfo->display = NULL;
13097 /* ...but if called from x_connection_closed, the display may already
13098 be closed and dpyinfo->display was set to 0 to indicate that. Since
13099 X server is most likely gone, explicit close is the only reliable
13100 way to continue and avoid Bug#19147. */
13101 else if (dpyinfo->connection >= 0)
13102 emacs_close (dpyinfo->connection);
13104 /* No more input on this descriptor. */
13105 delete_keyboard_wait_descriptor (dpyinfo->connection);
13106 /* Mark as dead. */
13107 dpyinfo->connection = -1;
13109 x_delete_display (dpyinfo);
13110 unblock_input ();
13113 /* Create a struct terminal, initialize it with the X11 specific
13114 functions and make DISPLAY->TERMINAL point to it. */
13116 static struct terminal *
13117 x_create_terminal (struct x_display_info *dpyinfo)
13119 struct terminal *terminal;
13121 terminal = create_terminal (output_x_window, &x_redisplay_interface);
13123 terminal->display_info.x = dpyinfo;
13124 dpyinfo->terminal = terminal;
13126 /* kboard is initialized in x_term_init. */
13128 terminal->clear_frame_hook = x_clear_frame;
13129 terminal->ins_del_lines_hook = x_ins_del_lines;
13130 terminal->delete_glyphs_hook = x_delete_glyphs;
13131 terminal->ring_bell_hook = XTring_bell;
13132 terminal->toggle_invisible_pointer_hook = XTtoggle_invisible_pointer;
13133 terminal->update_begin_hook = x_update_begin;
13134 terminal->update_end_hook = x_update_end;
13135 terminal->read_socket_hook = XTread_socket;
13136 terminal->frame_up_to_date_hook = XTframe_up_to_date;
13137 terminal->buffer_flipping_unblocked_hook = XTbuffer_flipping_unblocked_hook;
13138 terminal->mouse_position_hook = XTmouse_position;
13139 terminal->frame_rehighlight_hook = XTframe_rehighlight;
13140 terminal->frame_raise_lower_hook = XTframe_raise_lower;
13141 terminal->fullscreen_hook = XTfullscreen_hook;
13142 terminal->menu_show_hook = x_menu_show;
13143 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
13144 terminal->popup_dialog_hook = xw_popup_dialog;
13145 #endif
13146 terminal->set_vertical_scroll_bar_hook = XTset_vertical_scroll_bar;
13147 terminal->set_horizontal_scroll_bar_hook = XTset_horizontal_scroll_bar;
13148 terminal->condemn_scroll_bars_hook = XTcondemn_scroll_bars;
13149 terminal->redeem_scroll_bar_hook = XTredeem_scroll_bar;
13150 terminal->judge_scroll_bars_hook = XTjudge_scroll_bars;
13151 terminal->delete_frame_hook = x_destroy_window;
13152 terminal->delete_terminal_hook = x_delete_terminal;
13153 /* Other hooks are NULL by default. */
13155 return terminal;
13158 static void
13159 x_initialize (void)
13161 baud_rate = 19200;
13163 x_noop_count = 0;
13164 any_help_event_p = false;
13165 ignore_next_mouse_click_timeout = 0;
13167 #ifdef USE_GTK
13168 current_count = -1;
13169 #endif
13171 /* Try to use interrupt input; if we can't, then start polling. */
13172 Fset_input_interrupt_mode (Qt);
13174 #if THREADS_ENABLED
13175 /* This must be called before any other Xlib routines. */
13176 if (XInitThreads () == 0)
13177 fprintf (stderr,
13178 "Warning: An error occurred initializing X11 thread support!\n");
13179 #endif
13181 #ifdef USE_X_TOOLKIT
13182 XtToolkitInitialize ();
13184 Xt_app_con = XtCreateApplicationContext ();
13186 /* Register a converter from strings to pixels, which uses
13187 Emacs' color allocation infrastructure. */
13188 XtAppSetTypeConverter (Xt_app_con,
13189 XtRString, XtRPixel, cvt_string_to_pixel,
13190 cvt_string_to_pixel_args,
13191 XtNumber (cvt_string_to_pixel_args),
13192 XtCacheByDisplay, cvt_pixel_dtor);
13194 XtAppSetFallbackResources (Xt_app_con, Xt_default_resources);
13195 #endif
13197 #ifdef USE_TOOLKIT_SCROLL_BARS
13198 #ifndef USE_GTK
13199 xaw3d_arrow_scroll = False;
13200 xaw3d_pick_top = True;
13201 #endif
13202 #endif
13204 #ifdef USE_CAIRO
13205 x_cr_init_fringe (&x_redisplay_interface);
13206 #endif
13208 /* Note that there is no real way portable across R3/R4 to get the
13209 original error handler. */
13210 XSetErrorHandler (x_error_handler);
13211 XSetIOErrorHandler (x_io_error_quitter);
13214 #ifdef USE_GTK
13215 void
13216 init_xterm (void)
13218 /* Emacs can handle only core input events, so make sure
13219 Gtk doesn't use Xinput or Xinput2 extensions. */
13220 xputenv ("GDK_CORE_DEVICE_EVENTS=1");
13222 #endif
13224 void
13225 syms_of_xterm (void)
13227 x_error_message = NULL;
13229 DEFSYM (Qvendor_specific_keysyms, "vendor-specific-keysyms");
13230 DEFSYM (Qlatin_1, "latin-1");
13232 #ifdef USE_GTK
13233 xg_default_icon_file = build_pure_c_string ("icons/hicolor/scalable/apps/emacs.svg");
13234 staticpro (&xg_default_icon_file);
13236 DEFSYM (Qx_gtk_map_stock, "x-gtk-map-stock");
13237 #endif
13239 DEFVAR_BOOL ("x-use-underline-position-properties",
13240 x_use_underline_position_properties,
13241 doc: /* Non-nil means make use of UNDERLINE_POSITION font properties.
13242 A value of nil means ignore them. If you encounter fonts with bogus
13243 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
13244 to 4.1, set this to nil. You can also use `underline-minimum-offset'
13245 to override the font's UNDERLINE_POSITION for small font display
13246 sizes. */);
13247 x_use_underline_position_properties = true;
13249 DEFVAR_BOOL ("x-underline-at-descent-line",
13250 x_underline_at_descent_line,
13251 doc: /* Non-nil means to draw the underline at the same place as the descent line.
13252 A value of nil means to draw the underline according to the value of the
13253 variable `x-use-underline-position-properties', which is usually at the
13254 baseline level. The default value is nil. */);
13255 x_underline_at_descent_line = false;
13257 DEFVAR_BOOL ("x-mouse-click-focus-ignore-position",
13258 x_mouse_click_focus_ignore_position,
13259 doc: /* Non-nil means that a mouse click to focus a frame does not move point.
13260 This variable is only used when the window manager requires that you
13261 click on a frame to select it (give it focus). In that case, a value
13262 of nil, means that the selected window and cursor position changes to
13263 reflect the mouse click position, while a non-nil value means that the
13264 selected window or cursor position is preserved. */);
13265 x_mouse_click_focus_ignore_position = false;
13267 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
13268 doc: /* Which toolkit scroll bars Emacs uses, if any.
13269 A value of nil means Emacs doesn't use toolkit scroll bars.
13270 With the X Window system, the value is a symbol describing the
13271 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
13272 With MS Windows or Nextstep, the value is t. */);
13273 #ifdef USE_TOOLKIT_SCROLL_BARS
13274 #ifdef USE_MOTIF
13275 Vx_toolkit_scroll_bars = intern_c_string ("motif");
13276 #elif defined HAVE_XAW3D
13277 Vx_toolkit_scroll_bars = intern_c_string ("xaw3d");
13278 #elif USE_GTK
13279 Vx_toolkit_scroll_bars = intern_c_string ("gtk");
13280 #else
13281 Vx_toolkit_scroll_bars = intern_c_string ("xaw");
13282 #endif
13283 #else
13284 Vx_toolkit_scroll_bars = Qnil;
13285 #endif
13287 DEFSYM (Qmodifier_value, "modifier-value");
13288 DEFSYM (Qctrl, "ctrl");
13289 Fput (Qctrl, Qmodifier_value, make_number (ctrl_modifier));
13290 DEFSYM (Qalt, "alt");
13291 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
13292 DEFSYM (Qhyper, "hyper");
13293 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
13294 DEFSYM (Qmeta, "meta");
13295 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
13296 DEFSYM (Qsuper, "super");
13297 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
13299 DEFVAR_LISP ("x-ctrl-keysym", Vx_ctrl_keysym,
13300 doc: /* Which keys Emacs uses for the ctrl modifier.
13301 This should be one of the symbols `ctrl', `alt', `hyper', `meta',
13302 `super'. For example, `ctrl' means use the Ctrl_L and Ctrl_R keysyms.
13303 The default is nil, which is the same as `ctrl'. */);
13304 Vx_ctrl_keysym = Qnil;
13306 DEFVAR_LISP ("x-alt-keysym", Vx_alt_keysym,
13307 doc: /* Which keys Emacs uses for the alt modifier.
13308 This should be one of the symbols `ctrl', `alt', `hyper', `meta',
13309 `super'. For example, `alt' means use the Alt_L and Alt_R keysyms.
13310 The default is nil, which is the same as `alt'. */);
13311 Vx_alt_keysym = Qnil;
13313 DEFVAR_LISP ("x-hyper-keysym", Vx_hyper_keysym,
13314 doc: /* Which keys Emacs uses for the hyper modifier.
13315 This should be one of the symbols `ctrl', `alt', `hyper', `meta',
13316 `super'. For example, `hyper' means use the Hyper_L and Hyper_R
13317 keysyms. The default is nil, which is the same as `hyper'. */);
13318 Vx_hyper_keysym = Qnil;
13320 DEFVAR_LISP ("x-meta-keysym", Vx_meta_keysym,
13321 doc: /* Which keys Emacs uses for the meta modifier.
13322 This should be one of the symbols `ctrl', `alt', `hyper', `meta',
13323 `super'. For example, `meta' means use the Meta_L and Meta_R keysyms.
13324 The default is nil, which is the same as `meta'. */);
13325 Vx_meta_keysym = Qnil;
13327 DEFVAR_LISP ("x-super-keysym", Vx_super_keysym,
13328 doc: /* Which keys Emacs uses for the super modifier.
13329 This should be one of the symbols `ctrl', `alt', `hyper', `meta',
13330 `super'. For example, `super' means use the Super_L and Super_R
13331 keysyms. The default is nil, which is the same as `super'. */);
13332 Vx_super_keysym = Qnil;
13334 DEFVAR_LISP ("x-wait-for-event-timeout", Vx_wait_for_event_timeout,
13335 doc: /* How long to wait for X events.
13337 Emacs will wait up to this many seconds to receive X events after
13338 making changes which affect the state of the graphical interface.
13339 Under some window managers this can take an indefinite amount of time,
13340 so it is important to limit the wait.
13342 If set to a non-float value, there will be no wait at all. */);
13343 Vx_wait_for_event_timeout = make_float (0.1);
13345 DEFVAR_LISP ("x-keysym-table", Vx_keysym_table,
13346 doc: /* Hash table of character codes indexed by X keysym codes. */);
13347 Vx_keysym_table = make_hash_table (hashtest_eql, 900,
13348 DEFAULT_REHASH_SIZE,
13349 DEFAULT_REHASH_THRESHOLD,
13350 Qnil, false);
13352 DEFVAR_BOOL ("x-frame-normalize-before-maximize",
13353 x_frame_normalize_before_maximize,
13354 doc: /* Non-nil means normalize frame before maximizing.
13355 If this variable is t, Emacs first asks the window manager to give the
13356 frame its normal size, and only then the final state, whenever changing
13357 from a full-height, full-width or full-both state to the maximized one
13358 or when changing from the maximized to the full-height or full-width
13359 state.
13361 Set this variable only if your window manager cannot handle the
13362 transition between the various maximization states. */);
13363 x_frame_normalize_before_maximize = false;
13365 DEFVAR_BOOL ("x-gtk-use-window-move", x_gtk_use_window_move,
13366 doc: /* Non-nil means rely on gtk_window_move to set frame positions.
13367 If this variable is t (the default), the GTK build uses the function
13368 gtk_window_move to set or store frame positions and disables some time
13369 consuming frame position adjustments. In newer versions of GTK, Emacs
13370 always uses gtk_window_move and ignores the value of this variable. */);
13371 x_gtk_use_window_move = true;