Avoid floating-point exceptions while drawing underwave
[emacs.git] / src / xterm.c
blob77daa22ae0d59e130385f01bdfb6e4a4df868417
1 /* X Communication module for terminals which understand the X protocol.
3 Copyright (C) 1989, 1993-2017 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 <http://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)
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 return;
1003 if (! FRAME_CR_SURFACE (f))
1005 int width, height;
1006 #ifdef USE_GTK
1007 if (FRAME_GTK_WIDGET (f))
1009 GdkWindow *w = gtk_widget_get_window (FRAME_GTK_WIDGET (f));
1010 width = gdk_window_get_width (w);
1011 height = gdk_window_get_height (w);
1013 else
1014 #endif
1016 width = FRAME_PIXEL_WIDTH (f);
1017 height = FRAME_PIXEL_HEIGHT (f);
1018 if (! FRAME_EXTERNAL_TOOL_BAR (f))
1019 height += FRAME_TOOL_BAR_HEIGHT (f);
1020 if (! FRAME_EXTERNAL_MENU_BAR (f))
1021 height += FRAME_MENU_BAR_HEIGHT (f);
1024 if (width > 0 && height > 0)
1026 block_input();
1027 FRAME_CR_SURFACE (f) = cairo_image_surface_create
1028 (CAIRO_FORMAT_ARGB32, width, height);
1029 unblock_input();
1032 #endif /* USE_CAIRO */
1035 /* Start update of window W. */
1037 static void
1038 x_update_window_begin (struct window *w)
1040 struct frame *f = XFRAME (WINDOW_FRAME (w));
1041 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1043 w->output_cursor = w->cursor;
1045 block_input ();
1047 if (f == hlinfo->mouse_face_mouse_frame)
1049 /* Don't do highlighting for mouse motion during the update. */
1050 hlinfo->mouse_face_defer = true;
1052 /* If F needs to be redrawn, simply forget about any prior mouse
1053 highlighting. */
1054 if (FRAME_GARBAGED_P (f))
1055 hlinfo->mouse_face_window = Qnil;
1058 unblock_input ();
1062 /* Draw a vertical window border from (x,y0) to (x,y1) */
1064 static void
1065 x_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
1067 struct frame *f = XFRAME (WINDOW_FRAME (w));
1068 struct face *face;
1070 face = FACE_FROM_ID_OR_NULL (f, VERTICAL_BORDER_FACE_ID);
1071 if (face)
1072 XSetForeground (FRAME_X_DISPLAY (f), f->output_data.x->normal_gc,
1073 face->foreground);
1075 #ifdef USE_CAIRO
1076 x_fill_rectangle (f, f->output_data.x->normal_gc, x, y0, 1, y1 - y0);
1077 #else
1078 XDrawLine (FRAME_X_DISPLAY (f), FRAME_X_DRAWABLE (f),
1079 f->output_data.x->normal_gc, x, y0, x, y1);
1080 #endif
1083 /* Draw a window divider from (x0,y0) to (x1,y1) */
1085 static void
1086 x_draw_window_divider (struct window *w, int x0, int x1, int y0, int y1)
1088 struct frame *f = XFRAME (WINDOW_FRAME (w));
1089 struct face *face = FACE_FROM_ID_OR_NULL (f, WINDOW_DIVIDER_FACE_ID);
1090 struct face *face_first
1091 = FACE_FROM_ID_OR_NULL (f, WINDOW_DIVIDER_FIRST_PIXEL_FACE_ID);
1092 struct face *face_last
1093 = FACE_FROM_ID_OR_NULL (f, WINDOW_DIVIDER_LAST_PIXEL_FACE_ID);
1094 unsigned long color = face ? face->foreground : FRAME_FOREGROUND_PIXEL (f);
1095 unsigned long color_first = (face_first
1096 ? face_first->foreground
1097 : FRAME_FOREGROUND_PIXEL (f));
1098 unsigned long color_last = (face_last
1099 ? face_last->foreground
1100 : FRAME_FOREGROUND_PIXEL (f));
1101 Display *display = FRAME_X_DISPLAY (f);
1103 if (y1 - y0 > x1 - x0 && x1 - x0 > 2)
1104 /* Vertical. */
1106 XSetForeground (display, f->output_data.x->normal_gc, color_first);
1107 x_fill_rectangle (f, f->output_data.x->normal_gc,
1108 x0, y0, 1, y1 - y0);
1109 XSetForeground (display, f->output_data.x->normal_gc, color);
1110 x_fill_rectangle (f, f->output_data.x->normal_gc,
1111 x0 + 1, y0, x1 - x0 - 2, y1 - y0);
1112 XSetForeground (display, f->output_data.x->normal_gc, color_last);
1113 x_fill_rectangle (f, f->output_data.x->normal_gc,
1114 x1 - 1, y0, 1, y1 - y0);
1116 else if (x1 - x0 > y1 - y0 && y1 - y0 > 3)
1117 /* Horizontal. */
1119 XSetForeground (display, f->output_data.x->normal_gc, color_first);
1120 x_fill_rectangle (f, f->output_data.x->normal_gc,
1121 x0, y0, x1 - x0, 1);
1122 XSetForeground (display, f->output_data.x->normal_gc, color);
1123 x_fill_rectangle (f, f->output_data.x->normal_gc,
1124 x0, y0 + 1, x1 - x0, y1 - y0 - 2);
1125 XSetForeground (display, f->output_data.x->normal_gc, color_last);
1126 x_fill_rectangle (f, f->output_data.x->normal_gc,
1127 x0, y1 - 1, x1 - x0, 1);
1129 else
1131 XSetForeground (display, f->output_data.x->normal_gc, color);
1132 x_fill_rectangle (f, f->output_data.x->normal_gc,
1133 x0, y0, x1 - x0, y1 - y0);
1137 /* End update of window W.
1139 Draw vertical borders between horizontally adjacent windows, and
1140 display W's cursor if CURSOR_ON_P is non-zero.
1142 MOUSE_FACE_OVERWRITTEN_P non-zero means that some row containing
1143 glyphs in mouse-face were overwritten. In that case we have to
1144 make sure that the mouse-highlight is properly redrawn.
1146 W may be a menu bar pseudo-window in case we don't have X toolkit
1147 support. Such windows don't have a cursor, so don't display it
1148 here. */
1150 static void
1151 x_update_window_end (struct window *w, bool cursor_on_p,
1152 bool mouse_face_overwritten_p)
1154 if (!w->pseudo_window_p)
1156 block_input ();
1158 if (cursor_on_p)
1159 display_and_set_cursor (w, true,
1160 w->output_cursor.hpos, w->output_cursor.vpos,
1161 w->output_cursor.x, w->output_cursor.y);
1163 if (draw_window_fringes (w, true))
1165 if (WINDOW_RIGHT_DIVIDER_WIDTH (w))
1166 x_draw_right_divider (w);
1167 else
1168 x_draw_vertical_border (w);
1171 unblock_input ();
1174 /* If a row with mouse-face was overwritten, arrange for
1175 XTframe_up_to_date to redisplay the mouse highlight. */
1176 if (mouse_face_overwritten_p)
1178 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (XFRAME (w->frame));
1180 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
1181 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
1182 hlinfo->mouse_face_window = Qnil;
1186 /* Show the frame back buffer. If frame is double-buffered,
1187 atomically publish to the user's screen graphics updates made since
1188 the last call to show_back_buffer. */
1189 static void
1190 show_back_buffer (struct frame *f)
1192 block_input ();
1193 if (FRAME_X_DOUBLE_BUFFERED_P (f))
1195 #ifdef HAVE_XDBE
1196 XdbeSwapInfo swap_info;
1197 memset (&swap_info, 0, sizeof (swap_info));
1198 swap_info.swap_window = FRAME_X_WINDOW (f);
1199 swap_info.swap_action = XdbeCopied;
1200 XdbeSwapBuffers (FRAME_X_DISPLAY (f), &swap_info, 1);
1201 #else
1202 eassert (!"should have back-buffer only with XDBE");
1203 #endif
1205 FRAME_X_NEED_BUFFER_FLIP (f) = false;
1206 unblock_input ();
1209 /* Updates back buffer and flushes changes to display. Called from
1210 minibuf read code. Note that we display the back buffer even if
1211 buffer flipping is blocked. */
1212 static void
1213 x_flip_and_flush (struct frame *f)
1215 block_input ();
1216 if (FRAME_X_NEED_BUFFER_FLIP (f))
1217 show_back_buffer (f);
1218 x_flush (f);
1219 unblock_input ();
1222 /* End update of frame F. This function is installed as a hook in
1223 update_end. */
1225 static void
1226 x_update_end (struct frame *f)
1228 /* Mouse highlight may be displayed again. */
1229 MOUSE_HL_INFO (f)->mouse_face_defer = false;
1231 #ifdef USE_CAIRO
1232 if (FRAME_CR_SURFACE (f))
1234 cairo_t *cr = 0;
1235 block_input();
1236 #if defined (USE_GTK) && defined (HAVE_GTK3)
1237 if (FRAME_GTK_WIDGET (f))
1239 GdkWindow *w = gtk_widget_get_window (FRAME_GTK_WIDGET (f));
1240 cr = gdk_cairo_create (w);
1242 else
1243 #endif
1245 cairo_surface_t *surface;
1246 int width = FRAME_PIXEL_WIDTH (f);
1247 int height = FRAME_PIXEL_HEIGHT (f);
1248 if (! FRAME_EXTERNAL_TOOL_BAR (f))
1249 height += FRAME_TOOL_BAR_HEIGHT (f);
1250 if (! FRAME_EXTERNAL_MENU_BAR (f))
1251 height += FRAME_MENU_BAR_HEIGHT (f);
1252 surface = cairo_xlib_surface_create (FRAME_X_DISPLAY (f),
1253 FRAME_X_DRAWABLE (f),
1254 FRAME_DISPLAY_INFO (f)->visual,
1255 width,
1256 height);
1257 cr = cairo_create (surface);
1258 cairo_surface_destroy (surface);
1261 cairo_set_source_surface (cr, FRAME_CR_SURFACE (f), 0, 0);
1262 cairo_paint (cr);
1263 cairo_destroy (cr);
1264 unblock_input ();
1266 #endif
1268 #ifndef XFlush
1269 block_input ();
1270 XFlush (FRAME_X_DISPLAY (f));
1271 unblock_input ();
1272 #endif
1275 /* This function is called from various places in xdisp.c
1276 whenever a complete update has been performed. */
1278 static void
1279 XTframe_up_to_date (struct frame *f)
1281 eassert (FRAME_X_P (f));
1282 block_input ();
1283 FRAME_MOUSE_UPDATE (f);
1284 if (!buffer_flipping_blocked_p () && FRAME_X_NEED_BUFFER_FLIP (f))
1285 show_back_buffer (f);
1286 unblock_input ();
1289 static void
1290 XTbuffer_flipping_unblocked_hook (struct frame *f)
1292 if (FRAME_X_NEED_BUFFER_FLIP (f))
1293 show_back_buffer (f);
1297 * x_clear_under_internal_border:
1299 * Clear area of frame F's internal border. If the internal border face
1300 * of F has been specified (is not null), fill the area with that face.
1302 void
1303 x_clear_under_internal_border (struct frame *f)
1305 if (FRAME_INTERNAL_BORDER_WIDTH (f) > 0)
1307 int border = FRAME_INTERNAL_BORDER_WIDTH (f);
1308 int width = FRAME_PIXEL_WIDTH (f);
1309 int height = FRAME_PIXEL_HEIGHT (f);
1310 #ifdef USE_GTK
1311 int margin = 0;
1312 #else
1313 int margin = FRAME_TOP_MARGIN_HEIGHT (f);
1314 #endif
1315 struct face *face = FACE_FROM_ID_OR_NULL (f, INTERNAL_BORDER_FACE_ID);
1317 block_input ();
1319 if (face)
1321 unsigned long color = face->background;
1322 Display *display = FRAME_X_DISPLAY (f);
1323 GC gc = f->output_data.x->normal_gc;
1325 XSetForeground (display, gc, color);
1326 x_fill_rectangle (f, gc, 0, margin, width, border);
1327 x_fill_rectangle (f, gc, 0, 0, border, height);
1328 x_fill_rectangle (f, gc, width - border, 0, border, height);
1329 x_fill_rectangle (f, gc, 0, height - border, width, border);
1330 XSetForeground (display, gc, FRAME_FOREGROUND_PIXEL (f));
1332 else
1334 x_clear_area (f, 0, 0, border, height);
1335 x_clear_area (f, 0, margin, width, border);
1336 x_clear_area (f, width - border, 0, border, height);
1337 x_clear_area (f, 0, height - border, width, border);
1340 unblock_input ();
1344 /* Draw truncation mark bitmaps, continuation mark bitmaps, overlay
1345 arrow bitmaps, or clear the fringes if no bitmaps are required
1346 before DESIRED_ROW is made current. This function is called from
1347 update_window_line only if it is known that there are differences
1348 between bitmaps to be drawn between current row and DESIRED_ROW. */
1350 static void
1351 x_after_update_window_line (struct window *w, struct glyph_row *desired_row)
1353 eassert (w);
1355 if (!desired_row->mode_line_p && !w->pseudo_window_p)
1356 desired_row->redraw_fringe_bitmaps_p = true;
1358 #ifdef USE_X_TOOLKIT
1359 /* When a window has disappeared, make sure that no rest of
1360 full-width rows stays visible in the internal border. Could
1361 check here if updated window is the leftmost/rightmost window,
1362 but I guess it's not worth doing since vertically split windows
1363 are almost never used, internal border is rarely set, and the
1364 overhead is very small. */
1366 struct frame *f;
1367 int width, height;
1369 if (windows_or_buffers_changed
1370 && desired_row->full_width_p
1371 && (f = XFRAME (w->frame),
1372 width = FRAME_INTERNAL_BORDER_WIDTH (f),
1373 width != 0)
1374 && (height = desired_row->visible_height,
1375 height > 0))
1377 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
1378 struct face *face = FACE_FROM_ID_OR_NULL (f, INTERNAL_BORDER_FACE_ID);
1380 block_input ();
1381 if (face)
1383 unsigned long color = face->background;
1384 Display *display = FRAME_X_DISPLAY (f);
1386 XSetForeground (display, f->output_data.x->normal_gc, color);
1387 x_fill_rectangle (f, f->output_data.x->normal_gc,
1388 0, y, width, height);
1389 x_fill_rectangle (f, f->output_data.x->normal_gc,
1390 FRAME_PIXEL_WIDTH (f) - width, y, width, height);
1392 else
1394 x_clear_area (f, 0, y, width, height);
1395 x_clear_area (f, FRAME_PIXEL_WIDTH (f) - width, y, width, height);
1397 unblock_input ();
1400 #endif
1403 static void
1404 x_draw_fringe_bitmap (struct window *w, struct glyph_row *row, struct draw_fringe_bitmap_params *p)
1406 struct frame *f = XFRAME (WINDOW_FRAME (w));
1407 Display *display = FRAME_X_DISPLAY (f);
1408 GC gc = f->output_data.x->normal_gc;
1409 struct face *face = p->face;
1411 /* Must clip because of partially visible lines. */
1412 x_clip_to_row (w, row, ANY_AREA, gc);
1414 if (p->bx >= 0 && !p->overlay_p)
1416 /* In case the same realized face is used for fringes and
1417 for something displayed in the text (e.g. face `region' on
1418 mono-displays, the fill style may have been changed to
1419 FillSolid in x_draw_glyph_string_background. */
1420 if (face->stipple)
1421 XSetFillStyle (display, face->gc, FillOpaqueStippled);
1422 else
1423 XSetForeground (display, face->gc, face->background);
1425 x_fill_rectangle (f, face->gc, p->bx, p->by, p->nx, p->ny);
1427 if (!face->stipple)
1428 XSetForeground (display, face->gc, face->foreground);
1431 #ifdef USE_CAIRO
1432 if (p->which && p->which < max_fringe_bmp)
1434 XGCValues gcv;
1436 XGetGCValues (display, gc, GCForeground | GCBackground, &gcv);
1437 XSetForeground (display, gc, (p->cursor_p
1438 ? (p->overlay_p ? face->background
1439 : f->output_data.x->cursor_pixel)
1440 : face->foreground));
1441 XSetBackground (display, gc, face->background);
1442 x_cr_draw_image (f, gc, fringe_bmp[p->which], 0, p->dh,
1443 p->wd, p->h, p->x, p->y, p->overlay_p);
1444 XSetForeground (display, gc, gcv.foreground);
1445 XSetBackground (display, gc, gcv.background);
1447 #else /* not USE_CAIRO */
1448 if (p->which)
1450 Drawable drawable = FRAME_X_DRAWABLE (f);
1451 char *bits;
1452 Pixmap pixmap, clipmask = (Pixmap) 0;
1453 int depth = DefaultDepthOfScreen (FRAME_X_SCREEN (f));
1454 XGCValues gcv;
1456 if (p->wd > 8)
1457 bits = (char *) (p->bits + p->dh);
1458 else
1459 bits = (char *) p->bits + p->dh;
1461 /* Draw the bitmap. I believe these small pixmaps can be cached
1462 by the server. */
1463 pixmap = XCreatePixmapFromBitmapData (display, drawable, bits, p->wd, p->h,
1464 (p->cursor_p
1465 ? (p->overlay_p ? face->background
1466 : f->output_data.x->cursor_pixel)
1467 : face->foreground),
1468 face->background, depth);
1470 if (p->overlay_p)
1472 clipmask = XCreatePixmapFromBitmapData (display,
1473 FRAME_DISPLAY_INFO (f)->root_window,
1474 bits, p->wd, p->h,
1475 1, 0, 1);
1476 gcv.clip_mask = clipmask;
1477 gcv.clip_x_origin = p->x;
1478 gcv.clip_y_origin = p->y;
1479 XChangeGC (display, gc, GCClipMask | GCClipXOrigin | GCClipYOrigin, &gcv);
1482 XCopyArea (display, pixmap, drawable, gc, 0, 0,
1483 p->wd, p->h, p->x, p->y);
1484 XFreePixmap (display, pixmap);
1486 if (p->overlay_p)
1488 gcv.clip_mask = (Pixmap) 0;
1489 XChangeGC (display, gc, GCClipMask, &gcv);
1490 XFreePixmap (display, clipmask);
1493 #endif /* not USE_CAIRO */
1495 x_reset_clip_rectangles (f, gc);
1498 /***********************************************************************
1499 Glyph display
1500 ***********************************************************************/
1504 static void x_set_glyph_string_clipping (struct glyph_string *);
1505 static void x_set_glyph_string_gc (struct glyph_string *);
1506 static void x_draw_glyph_string_foreground (struct glyph_string *);
1507 static void x_draw_composite_glyph_string_foreground (struct glyph_string *);
1508 static void x_draw_glyph_string_box (struct glyph_string *);
1509 static void x_draw_glyph_string (struct glyph_string *);
1510 static _Noreturn void x_delete_glyphs (struct frame *, int);
1511 static void x_compute_glyph_string_overhangs (struct glyph_string *);
1512 static void x_set_cursor_gc (struct glyph_string *);
1513 static void x_set_mode_line_face_gc (struct glyph_string *);
1514 static void x_set_mouse_face_gc (struct glyph_string *);
1515 static bool x_alloc_lighter_color (struct frame *, Display *, Colormap,
1516 unsigned long *, double, int);
1517 static void x_setup_relief_color (struct frame *, struct relief *,
1518 double, int, unsigned long);
1519 static void x_setup_relief_colors (struct glyph_string *);
1520 static void x_draw_image_glyph_string (struct glyph_string *);
1521 static void x_draw_image_relief (struct glyph_string *);
1522 static void x_draw_image_foreground (struct glyph_string *);
1523 static void x_draw_image_foreground_1 (struct glyph_string *, Pixmap);
1524 static void x_clear_glyph_string_rect (struct glyph_string *, int,
1525 int, int, int);
1526 static void x_draw_relief_rect (struct frame *, int, int, int, int,
1527 int, bool, bool, bool, bool, bool,
1528 XRectangle *);
1529 static void x_draw_box_rect (struct glyph_string *, int, int, int, int,
1530 int, bool, bool, XRectangle *);
1531 static void x_scroll_bar_clear (struct frame *);
1533 #ifdef GLYPH_DEBUG
1534 static void x_check_font (struct frame *, struct font *);
1535 #endif
1538 /* Set S->gc to a suitable GC for drawing glyph string S in cursor
1539 face. */
1541 static void
1542 x_set_cursor_gc (struct glyph_string *s)
1544 if (s->font == FRAME_FONT (s->f)
1545 && s->face->background == FRAME_BACKGROUND_PIXEL (s->f)
1546 && s->face->foreground == FRAME_FOREGROUND_PIXEL (s->f)
1547 && !s->cmp)
1548 s->gc = s->f->output_data.x->cursor_gc;
1549 else
1551 /* Cursor on non-default face: must merge. */
1552 XGCValues xgcv;
1553 unsigned long mask;
1555 xgcv.background = s->f->output_data.x->cursor_pixel;
1556 xgcv.foreground = s->face->background;
1558 /* If the glyph would be invisible, try a different foreground. */
1559 if (xgcv.foreground == xgcv.background)
1560 xgcv.foreground = s->face->foreground;
1561 if (xgcv.foreground == xgcv.background)
1562 xgcv.foreground = s->f->output_data.x->cursor_foreground_pixel;
1563 if (xgcv.foreground == xgcv.background)
1564 xgcv.foreground = s->face->foreground;
1566 /* Make sure the cursor is distinct from text in this face. */
1567 if (xgcv.background == s->face->background
1568 && xgcv.foreground == s->face->foreground)
1570 xgcv.background = s->face->foreground;
1571 xgcv.foreground = s->face->background;
1574 IF_DEBUG (x_check_font (s->f, s->font));
1575 xgcv.graphics_exposures = False;
1576 mask = GCForeground | GCBackground | GCGraphicsExposures;
1578 if (FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc)
1579 XChangeGC (s->display, FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc,
1580 mask, &xgcv);
1581 else
1582 FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc
1583 = XCreateGC (s->display, FRAME_X_DRAWABLE (s->f), mask, &xgcv);
1585 s->gc = FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc;
1590 /* Set up S->gc of glyph string S for drawing text in mouse face. */
1592 static void
1593 x_set_mouse_face_gc (struct glyph_string *s)
1595 int face_id;
1596 struct face *face;
1598 /* What face has to be used last for the mouse face? */
1599 face_id = MOUSE_HL_INFO (s->f)->mouse_face_face_id;
1600 face = FACE_FROM_ID_OR_NULL (s->f, face_id);
1601 if (face == NULL)
1602 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
1604 if (s->first_glyph->type == CHAR_GLYPH)
1605 face_id = FACE_FOR_CHAR (s->f, face, s->first_glyph->u.ch, -1, Qnil);
1606 else
1607 face_id = FACE_FOR_CHAR (s->f, face, 0, -1, Qnil);
1608 s->face = FACE_FROM_ID (s->f, face_id);
1609 prepare_face_for_display (s->f, s->face);
1611 if (s->font == s->face->font)
1612 s->gc = s->face->gc;
1613 else
1615 /* Otherwise construct scratch_cursor_gc with values from FACE
1616 except for FONT. */
1617 XGCValues xgcv;
1618 unsigned long mask;
1620 xgcv.background = s->face->background;
1621 xgcv.foreground = s->face->foreground;
1622 xgcv.graphics_exposures = False;
1623 mask = GCForeground | GCBackground | GCGraphicsExposures;
1625 if (FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc)
1626 XChangeGC (s->display, FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc,
1627 mask, &xgcv);
1628 else
1629 FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc
1630 = XCreateGC (s->display, FRAME_X_DRAWABLE (s->f), mask, &xgcv);
1632 s->gc = FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc;
1635 eassert (s->gc != 0);
1639 /* Set S->gc of glyph string S to a GC suitable for drawing a mode line.
1640 Faces to use in the mode line have already been computed when the
1641 matrix was built, so there isn't much to do, here. */
1643 static void
1644 x_set_mode_line_face_gc (struct glyph_string *s)
1646 s->gc = s->face->gc;
1650 /* Set S->gc of glyph string S for drawing that glyph string. Set
1651 S->stippled_p to a non-zero value if the face of S has a stipple
1652 pattern. */
1654 static void
1655 x_set_glyph_string_gc (struct glyph_string *s)
1657 prepare_face_for_display (s->f, s->face);
1659 if (s->hl == DRAW_NORMAL_TEXT)
1661 s->gc = s->face->gc;
1662 s->stippled_p = s->face->stipple != 0;
1664 else if (s->hl == DRAW_INVERSE_VIDEO)
1666 x_set_mode_line_face_gc (s);
1667 s->stippled_p = s->face->stipple != 0;
1669 else if (s->hl == DRAW_CURSOR)
1671 x_set_cursor_gc (s);
1672 s->stippled_p = false;
1674 else if (s->hl == DRAW_MOUSE_FACE)
1676 x_set_mouse_face_gc (s);
1677 s->stippled_p = s->face->stipple != 0;
1679 else if (s->hl == DRAW_IMAGE_RAISED
1680 || s->hl == DRAW_IMAGE_SUNKEN)
1682 s->gc = s->face->gc;
1683 s->stippled_p = s->face->stipple != 0;
1685 else
1686 emacs_abort ();
1688 /* GC must have been set. */
1689 eassert (s->gc != 0);
1693 /* Set clipping for output of glyph string S. S may be part of a mode
1694 line or menu if we don't have X toolkit support. */
1696 static void
1697 x_set_glyph_string_clipping (struct glyph_string *s)
1699 XRectangle *r = s->clip;
1700 int n = get_glyph_string_clip_rects (s, r, 2);
1702 if (n > 0)
1703 x_set_clip_rectangles (s->f, s->gc, r, n);
1704 s->num_clips = n;
1708 /* Set SRC's clipping for output of glyph string DST. This is called
1709 when we are drawing DST's left_overhang or right_overhang only in
1710 the area of SRC. */
1712 static void
1713 x_set_glyph_string_clipping_exactly (struct glyph_string *src, struct glyph_string *dst)
1715 XRectangle r;
1717 r.x = src->x;
1718 r.width = src->width;
1719 r.y = src->y;
1720 r.height = src->height;
1721 dst->clip[0] = r;
1722 dst->num_clips = 1;
1723 x_set_clip_rectangles (dst->f, dst->gc, &r, 1);
1727 /* RIF:
1728 Compute left and right overhang of glyph string S. */
1730 static void
1731 x_compute_glyph_string_overhangs (struct glyph_string *s)
1733 if (s->cmp == NULL
1734 && (s->first_glyph->type == CHAR_GLYPH
1735 || s->first_glyph->type == COMPOSITE_GLYPH))
1737 struct font_metrics metrics;
1739 if (s->first_glyph->type == CHAR_GLYPH)
1741 unsigned *code = alloca (sizeof (unsigned) * s->nchars);
1742 struct font *font = s->font;
1743 int i;
1745 for (i = 0; i < s->nchars; i++)
1746 code[i] = (s->char2b[i].byte1 << 8) | s->char2b[i].byte2;
1747 font->driver->text_extents (font, code, s->nchars, &metrics);
1749 else
1751 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1753 composition_gstring_width (gstring, s->cmp_from, s->cmp_to, &metrics);
1755 s->right_overhang = (metrics.rbearing > metrics.width
1756 ? metrics.rbearing - metrics.width : 0);
1757 s->left_overhang = metrics.lbearing < 0 ? - metrics.lbearing : 0;
1759 else if (s->cmp)
1761 s->right_overhang = s->cmp->rbearing - s->cmp->pixel_width;
1762 s->left_overhang = - s->cmp->lbearing;
1767 /* Fill rectangle X, Y, W, H with background color of glyph string S. */
1769 static void
1770 x_clear_glyph_string_rect (struct glyph_string *s, int x, int y, int w, int h)
1772 XGCValues xgcv;
1773 XGetGCValues (s->display, s->gc, GCForeground | GCBackground, &xgcv);
1774 XSetForeground (s->display, s->gc, xgcv.background);
1775 x_fill_rectangle (s->f, s->gc, x, y, w, h);
1776 XSetForeground (s->display, s->gc, xgcv.foreground);
1780 /* Draw the background of glyph_string S. If S->background_filled_p
1781 is non-zero don't draw it. FORCE_P non-zero means draw the
1782 background even if it wouldn't be drawn normally. This is used
1783 when a string preceding S draws into the background of S, or S
1784 contains the first component of a composition. */
1786 static void
1787 x_draw_glyph_string_background (struct glyph_string *s, bool force_p)
1789 /* Nothing to do if background has already been drawn or if it
1790 shouldn't be drawn in the first place. */
1791 if (!s->background_filled_p)
1793 int box_line_width = max (s->face->box_line_width, 0);
1795 if (s->stippled_p)
1797 /* Fill background with a stipple pattern. */
1798 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
1799 x_fill_rectangle (s->f, s->gc, s->x,
1800 s->y + box_line_width,
1801 s->background_width,
1802 s->height - 2 * box_line_width);
1803 XSetFillStyle (s->display, s->gc, FillSolid);
1804 s->background_filled_p = true;
1806 else if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
1807 /* When xdisp.c ignores FONT_HEIGHT, we cannot trust
1808 font dimensions, since the actual glyphs might be
1809 much smaller. So in that case we always clear the
1810 rectangle with background color. */
1811 || FONT_TOO_HIGH (s->font)
1812 || s->font_not_found_p
1813 || s->extends_to_end_of_line_p
1814 || force_p)
1816 x_clear_glyph_string_rect (s, s->x, s->y + box_line_width,
1817 s->background_width,
1818 s->height - 2 * box_line_width);
1819 s->background_filled_p = true;
1825 /* Draw the foreground of glyph string S. */
1827 static void
1828 x_draw_glyph_string_foreground (struct glyph_string *s)
1830 int i, x;
1832 /* If first glyph of S has a left box line, start drawing the text
1833 of S to the right of that box line. */
1834 if (s->face->box != FACE_NO_BOX
1835 && s->first_glyph->left_box_line_p)
1836 x = s->x + eabs (s->face->box_line_width);
1837 else
1838 x = s->x;
1840 /* Draw characters of S as rectangles if S's font could not be
1841 loaded. */
1842 if (s->font_not_found_p)
1844 for (i = 0; i < s->nchars; ++i)
1846 struct glyph *g = s->first_glyph + i;
1847 x_draw_rectangle (s->f,
1848 s->gc, x, s->y, g->pixel_width - 1,
1849 s->height - 1);
1850 x += g->pixel_width;
1853 else
1855 struct font *font = s->font;
1856 int boff = font->baseline_offset;
1857 int y;
1859 if (font->vertical_centering)
1860 boff = VCENTER_BASELINE_OFFSET (font, s->f) - boff;
1862 y = s->ybase - boff;
1863 if (s->for_overlaps
1864 || (s->background_filled_p && s->hl != DRAW_CURSOR))
1865 font->driver->draw (s, 0, s->nchars, x, y, false);
1866 else
1867 font->driver->draw (s, 0, s->nchars, x, y, true);
1868 if (s->face->overstrike)
1869 font->driver->draw (s, 0, s->nchars, x + 1, y, false);
1873 /* Draw the foreground of composite glyph string S. */
1875 static void
1876 x_draw_composite_glyph_string_foreground (struct glyph_string *s)
1878 int i, j, x;
1879 struct font *font = s->font;
1881 /* If first glyph of S has a left box line, start drawing the text
1882 of S to the right of that box line. */
1883 if (s->face && s->face->box != FACE_NO_BOX
1884 && s->first_glyph->left_box_line_p)
1885 x = s->x + eabs (s->face->box_line_width);
1886 else
1887 x = s->x;
1889 /* S is a glyph string for a composition. S->cmp_from is the index
1890 of the first character drawn for glyphs of this composition.
1891 S->cmp_from == 0 means we are drawing the very first character of
1892 this composition. */
1894 /* Draw a rectangle for the composition if the font for the very
1895 first character of the composition could not be loaded. */
1896 if (s->font_not_found_p)
1898 if (s->cmp_from == 0)
1899 x_draw_rectangle (s->f, s->gc, x, s->y,
1900 s->width - 1, s->height - 1);
1902 else if (! s->first_glyph->u.cmp.automatic)
1904 int y = s->ybase;
1906 for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
1907 /* TAB in a composition means display glyphs with padding
1908 space on the left or right. */
1909 if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
1911 int xx = x + s->cmp->offsets[j * 2];
1912 int yy = y - s->cmp->offsets[j * 2 + 1];
1914 font->driver->draw (s, j, j + 1, xx, yy, false);
1915 if (s->face->overstrike)
1916 font->driver->draw (s, j, j + 1, xx + 1, yy, false);
1919 else
1921 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1922 Lisp_Object glyph;
1923 int y = s->ybase;
1924 int width = 0;
1926 for (i = j = s->cmp_from; i < s->cmp_to; i++)
1928 glyph = LGSTRING_GLYPH (gstring, i);
1929 if (NILP (LGLYPH_ADJUSTMENT (glyph)))
1930 width += LGLYPH_WIDTH (glyph);
1931 else
1933 int xoff, yoff, wadjust;
1935 if (j < i)
1937 font->driver->draw (s, j, i, x, y, false);
1938 if (s->face->overstrike)
1939 font->driver->draw (s, j, i, x + 1, y, false);
1940 x += width;
1942 xoff = LGLYPH_XOFF (glyph);
1943 yoff = LGLYPH_YOFF (glyph);
1944 wadjust = LGLYPH_WADJUST (glyph);
1945 font->driver->draw (s, i, i + 1, x + xoff, y + yoff, false);
1946 if (s->face->overstrike)
1947 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff,
1948 false);
1949 x += wadjust;
1950 j = i + 1;
1951 width = 0;
1954 if (j < i)
1956 font->driver->draw (s, j, i, x, y, false);
1957 if (s->face->overstrike)
1958 font->driver->draw (s, j, i, x + 1, y, false);
1964 /* Draw the foreground of glyph string S for glyphless characters. */
1966 static void
1967 x_draw_glyphless_glyph_string_foreground (struct glyph_string *s)
1969 struct glyph *glyph = s->first_glyph;
1970 XChar2b char2b[8];
1971 int x, i, j;
1973 /* If first glyph of S has a left box line, start drawing the text
1974 of S to the right of that box line. */
1975 if (s->face && s->face->box != FACE_NO_BOX
1976 && s->first_glyph->left_box_line_p)
1977 x = s->x + eabs (s->face->box_line_width);
1978 else
1979 x = s->x;
1981 s->char2b = char2b;
1983 for (i = 0; i < s->nchars; i++, glyph++)
1985 char buf[7], *str = NULL;
1986 int len = glyph->u.glyphless.len;
1988 if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_ACRONYM)
1990 if (len > 0
1991 && CHAR_TABLE_P (Vglyphless_char_display)
1992 && (CHAR_TABLE_EXTRA_SLOTS (XCHAR_TABLE (Vglyphless_char_display))
1993 >= 1))
1995 Lisp_Object acronym
1996 = (! glyph->u.glyphless.for_no_font
1997 ? CHAR_TABLE_REF (Vglyphless_char_display,
1998 glyph->u.glyphless.ch)
1999 : XCHAR_TABLE (Vglyphless_char_display)->extras[0]);
2000 if (STRINGP (acronym))
2001 str = SSDATA (acronym);
2004 else if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_HEX_CODE)
2006 unsigned int ch = glyph->u.glyphless.ch;
2007 eassume (ch <= MAX_CHAR);
2008 sprintf (buf, "%0*X", ch < 0x10000 ? 4 : 6, ch);
2009 str = buf;
2012 if (str)
2014 int upper_len = (len + 1) / 2;
2015 unsigned code;
2017 /* It is assured that all LEN characters in STR is ASCII. */
2018 for (j = 0; j < len; j++)
2020 code = s->font->driver->encode_char (s->font, str[j]);
2021 STORE_XCHAR2B (char2b + j, code >> 8, code & 0xFF);
2023 s->font->driver->draw (s, 0, upper_len,
2024 x + glyph->slice.glyphless.upper_xoff,
2025 s->ybase + glyph->slice.glyphless.upper_yoff,
2026 false);
2027 s->font->driver->draw (s, upper_len, len,
2028 x + glyph->slice.glyphless.lower_xoff,
2029 s->ybase + glyph->slice.glyphless.lower_yoff,
2030 false);
2032 if (glyph->u.glyphless.method != GLYPHLESS_DISPLAY_THIN_SPACE)
2033 x_draw_rectangle (s->f, s->gc,
2034 x, s->ybase - glyph->ascent,
2035 glyph->pixel_width - 1,
2036 glyph->ascent + glyph->descent - 1);
2037 x += glyph->pixel_width;
2041 #ifdef USE_X_TOOLKIT
2043 #ifdef USE_LUCID
2045 /* Return the frame on which widget WIDGET is used.. Abort if frame
2046 cannot be determined. */
2048 static struct frame *
2049 x_frame_of_widget (Widget widget)
2051 struct x_display_info *dpyinfo;
2052 Lisp_Object tail, frame;
2053 struct frame *f;
2055 dpyinfo = x_display_info_for_display (XtDisplay (widget));
2057 /* Find the top-level shell of the widget. Note that this function
2058 can be called when the widget is not yet realized, so XtWindow
2059 (widget) == 0. That's the reason we can't simply use
2060 x_any_window_to_frame. */
2061 while (!XtIsTopLevelShell (widget))
2062 widget = XtParent (widget);
2064 /* Look for a frame with that top-level widget. Allocate the color
2065 on that frame to get the right gamma correction value. */
2066 FOR_EACH_FRAME (tail, frame)
2068 f = XFRAME (frame);
2069 if (FRAME_X_P (f)
2070 && f->output_data.nothing != 1
2071 && FRAME_DISPLAY_INFO (f) == dpyinfo
2072 && f->output_data.x->widget == widget)
2073 return f;
2075 emacs_abort ();
2078 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
2079 or DELTA. Try a color with RGB values multiplied by FACTOR first.
2080 If this produces the same color as PIXEL, try a color where all RGB
2081 values have DELTA added. Return the allocated color in *PIXEL.
2082 DISPLAY is the X display, CMAP is the colormap to operate on.
2083 Value is true if successful. */
2085 bool
2086 x_alloc_lighter_color_for_widget (Widget widget, Display *display, Colormap cmap,
2087 unsigned long *pixel, double factor, int delta)
2089 struct frame *f = x_frame_of_widget (widget);
2090 return x_alloc_lighter_color (f, display, cmap, pixel, factor, delta);
2093 #endif /* USE_LUCID */
2096 /* Structure specifying which arguments should be passed by Xt to
2097 cvt_string_to_pixel. We want the widget's screen and colormap. */
2099 static XtConvertArgRec cvt_string_to_pixel_args[] =
2101 {XtWidgetBaseOffset, (XtPointer) offsetof (WidgetRec, core.screen),
2102 sizeof (Screen *)},
2103 {XtWidgetBaseOffset, (XtPointer) offsetof (WidgetRec, core.colormap),
2104 sizeof (Colormap)}
2108 /* The address of this variable is returned by
2109 cvt_string_to_pixel. */
2111 static Pixel cvt_string_to_pixel_value;
2114 /* Convert a color name to a pixel color.
2116 DPY is the display we are working on.
2118 ARGS is an array of *NARGS XrmValue structures holding additional
2119 information about the widget for which the conversion takes place.
2120 The contents of this array are determined by the specification
2121 in cvt_string_to_pixel_args.
2123 FROM is a pointer to an XrmValue which points to the color name to
2124 convert. TO is an XrmValue in which to return the pixel color.
2126 CLOSURE_RET is a pointer to user-data, in which we record if
2127 we allocated the color or not.
2129 Value is True if successful, False otherwise. */
2131 static Boolean
2132 cvt_string_to_pixel (Display *dpy, XrmValue *args, Cardinal *nargs,
2133 XrmValue *from, XrmValue *to,
2134 XtPointer *closure_ret)
2136 Screen *screen;
2137 Colormap cmap;
2138 Pixel pixel;
2139 String color_name;
2140 XColor color;
2142 if (*nargs != 2)
2144 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
2145 "wrongParameters", "cvt_string_to_pixel",
2146 "XtToolkitError",
2147 "Screen and colormap args required", NULL, NULL);
2148 return False;
2151 screen = *(Screen **) args[0].addr;
2152 cmap = *(Colormap *) args[1].addr;
2153 color_name = (String) from->addr;
2155 if (strcmp (color_name, XtDefaultBackground) == 0)
2157 *closure_ret = (XtPointer) False;
2158 pixel = WhitePixelOfScreen (screen);
2160 else if (strcmp (color_name, XtDefaultForeground) == 0)
2162 *closure_ret = (XtPointer) False;
2163 pixel = BlackPixelOfScreen (screen);
2165 else if (XParseColor (dpy, cmap, color_name, &color)
2166 && x_alloc_nearest_color_1 (dpy, cmap, &color))
2168 pixel = color.pixel;
2169 *closure_ret = (XtPointer) True;
2171 else
2173 String params[1];
2174 Cardinal nparams = 1;
2176 params[0] = color_name;
2177 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
2178 "badValue", "cvt_string_to_pixel",
2179 "XtToolkitError", "Invalid color '%s'",
2180 params, &nparams);
2181 return False;
2184 if (to->addr != NULL)
2186 if (to->size < sizeof (Pixel))
2188 to->size = sizeof (Pixel);
2189 return False;
2192 *(Pixel *) to->addr = pixel;
2194 else
2196 cvt_string_to_pixel_value = pixel;
2197 to->addr = (XtPointer) &cvt_string_to_pixel_value;
2200 to->size = sizeof (Pixel);
2201 return True;
2205 /* Free a pixel color which was previously allocated via
2206 cvt_string_to_pixel. This is registered as the destructor
2207 for this type of resource via XtSetTypeConverter.
2209 APP is the application context in which we work.
2211 TO is a pointer to an XrmValue holding the color to free.
2212 CLOSURE is the value we stored in CLOSURE_RET for this color
2213 in cvt_string_to_pixel.
2215 ARGS and NARGS are like for cvt_string_to_pixel. */
2217 static void
2218 cvt_pixel_dtor (XtAppContext app, XrmValuePtr to, XtPointer closure, XrmValuePtr args,
2219 Cardinal *nargs)
2221 if (*nargs != 2)
2223 XtAppWarningMsg (app, "wrongParameters", "cvt_pixel_dtor",
2224 "XtToolkitError",
2225 "Screen and colormap arguments required",
2226 NULL, NULL);
2228 else if (closure != NULL)
2230 /* We did allocate the pixel, so free it. */
2231 Screen *screen = *(Screen **) args[0].addr;
2232 Colormap cmap = *(Colormap *) args[1].addr;
2233 x_free_dpy_colors (DisplayOfScreen (screen), screen, cmap,
2234 (Pixel *) to->addr, 1);
2239 #endif /* USE_X_TOOLKIT */
2242 /* Value is an array of XColor structures for the contents of the
2243 color map of display DPY. Set *NCELLS to the size of the array.
2244 Note that this probably shouldn't be called for large color maps,
2245 say a 24-bit TrueColor map. */
2247 static const XColor *
2248 x_color_cells (Display *dpy, int *ncells)
2250 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
2251 eassume (dpyinfo);
2253 if (dpyinfo->color_cells == NULL)
2255 Screen *screen = dpyinfo->screen;
2256 int ncolor_cells = XDisplayCells (dpy, XScreenNumberOfScreen (screen));
2257 int i;
2259 dpyinfo->color_cells = xnmalloc (ncolor_cells,
2260 sizeof *dpyinfo->color_cells);
2261 dpyinfo->ncolor_cells = ncolor_cells;
2263 for (i = 0; i < ncolor_cells; ++i)
2264 dpyinfo->color_cells[i].pixel = i;
2266 XQueryColors (dpy, dpyinfo->cmap,
2267 dpyinfo->color_cells, ncolor_cells);
2270 *ncells = dpyinfo->ncolor_cells;
2271 return dpyinfo->color_cells;
2275 /* On frame F, translate pixel colors to RGB values for the NCOLORS
2276 colors in COLORS. Use cached information, if available. */
2278 void
2279 x_query_colors (struct frame *f, XColor *colors, int ncolors)
2281 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2283 if (dpyinfo->red_bits > 0)
2285 /* For TrueColor displays, we can decompose the RGB value
2286 directly. */
2287 int i;
2288 unsigned int rmult, gmult, bmult;
2289 unsigned int rmask, gmask, bmask;
2291 rmask = (1 << dpyinfo->red_bits) - 1;
2292 gmask = (1 << dpyinfo->green_bits) - 1;
2293 bmask = (1 << dpyinfo->blue_bits) - 1;
2294 /* If we're widening, for example, 8 bits in the pixel value to
2295 16 bits for the separate-color representation, we want to
2296 extrapolate the lower bits based on those bits available --
2297 in other words, we'd like 0xff to become 0xffff instead of
2298 the 0xff00 we'd get by just zero-filling the lower bits.
2300 We generate a 32-bit scaled-up value and shift it, in case
2301 the bit count doesn't divide 16 evenly (e.g., when dealing
2302 with a 3-3-2 bit RGB display), to get more of the lower bits
2303 correct.
2305 Should we cache the multipliers in dpyinfo? Maybe
2306 special-case the 8-8-8 common case? */
2307 rmult = 0xffffffff / rmask;
2308 gmult = 0xffffffff / gmask;
2309 bmult = 0xffffffff / bmask;
2311 for (i = 0; i < ncolors; ++i)
2313 unsigned int r, g, b;
2314 unsigned long pixel = colors[i].pixel;
2316 r = (pixel >> dpyinfo->red_offset) & rmask;
2317 g = (pixel >> dpyinfo->green_offset) & gmask;
2318 b = (pixel >> dpyinfo->blue_offset) & bmask;
2320 colors[i].red = (r * rmult) >> 16;
2321 colors[i].green = (g * gmult) >> 16;
2322 colors[i].blue = (b * bmult) >> 16;
2324 return;
2327 if (dpyinfo->color_cells)
2329 int i;
2330 for (i = 0; i < ncolors; ++i)
2332 unsigned long pixel = colors[i].pixel;
2333 eassert (pixel < dpyinfo->ncolor_cells);
2334 eassert (dpyinfo->color_cells[pixel].pixel == pixel);
2335 colors[i] = dpyinfo->color_cells[pixel];
2337 return;
2340 XQueryColors (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), colors, ncolors);
2344 /* On frame F, translate pixel color to RGB values for the color in
2345 COLOR. Use cached information, if available. */
2347 void
2348 x_query_color (struct frame *f, XColor *color)
2350 x_query_colors (f, color, 1);
2354 /* On frame F, translate the color name to RGB values. Use cached
2355 information, if possible.
2357 Note that there is currently no way to clean old entries out of the
2358 cache. However, it is limited to names in the server's database,
2359 and names we've actually looked up; list-colors-display is probably
2360 the most color-intensive case we're likely to hit. */
2362 Status x_parse_color (struct frame *f, const char *color_name,
2363 XColor *color)
2365 Display *dpy = FRAME_X_DISPLAY (f);
2366 Colormap cmap = FRAME_X_COLORMAP (f);
2367 struct color_name_cache_entry *cache_entry;
2369 if (color_name[0] == '#')
2371 /* The hex form is parsed directly by XParseColor without
2372 talking to the X server. No need for caching. */
2373 return XParseColor (dpy, cmap, color_name, color);
2376 for (cache_entry = FRAME_DISPLAY_INFO (f)->color_names; cache_entry;
2377 cache_entry = cache_entry->next)
2379 if (!xstrcasecmp(cache_entry->name, color_name))
2381 *color = cache_entry->rgb;
2382 return 1;
2386 if (XParseColor (dpy, cmap, color_name, color) == 0)
2387 /* No caching of negative results, currently. */
2388 return 0;
2390 cache_entry = xzalloc (sizeof *cache_entry);
2391 cache_entry->rgb = *color;
2392 cache_entry->name = xstrdup (color_name);
2393 cache_entry->next = FRAME_DISPLAY_INFO (f)->color_names;
2394 FRAME_DISPLAY_INFO (f)->color_names = cache_entry;
2395 return 1;
2399 /* Allocate the color COLOR->pixel on DISPLAY, colormap CMAP. If an
2400 exact match can't be allocated, try the nearest color available.
2401 Value is true if successful. Set *COLOR to the color
2402 allocated. */
2404 static bool
2405 x_alloc_nearest_color_1 (Display *dpy, Colormap cmap, XColor *color)
2407 bool rc;
2409 rc = XAllocColor (dpy, cmap, color) != 0;
2410 if (rc == 0)
2412 /* If we got to this point, the colormap is full, so we're going
2413 to try to get the next closest color. The algorithm used is
2414 a least-squares matching, which is what X uses for closest
2415 color matching with StaticColor visuals. */
2416 int nearest, i;
2417 int max_color_delta = 255;
2418 int max_delta = 3 * max_color_delta;
2419 int nearest_delta = max_delta + 1;
2420 int ncells;
2421 const XColor *cells = x_color_cells (dpy, &ncells);
2423 for (nearest = i = 0; i < ncells; ++i)
2425 int dred = (color->red >> 8) - (cells[i].red >> 8);
2426 int dgreen = (color->green >> 8) - (cells[i].green >> 8);
2427 int dblue = (color->blue >> 8) - (cells[i].blue >> 8);
2428 int delta = dred * dred + dgreen * dgreen + dblue * dblue;
2430 if (delta < nearest_delta)
2432 nearest = i;
2433 nearest_delta = delta;
2437 color->red = cells[nearest].red;
2438 color->green = cells[nearest].green;
2439 color->blue = cells[nearest].blue;
2440 rc = XAllocColor (dpy, cmap, color) != 0;
2442 else
2444 /* If allocation succeeded, and the allocated pixel color is not
2445 equal to a cached pixel color recorded earlier, there was a
2446 change in the colormap, so clear the color cache. */
2447 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
2448 eassume (dpyinfo);
2450 if (dpyinfo->color_cells)
2452 XColor *cached_color = &dpyinfo->color_cells[color->pixel];
2453 if (cached_color->red != color->red
2454 || cached_color->blue != color->blue
2455 || cached_color->green != color->green)
2457 xfree (dpyinfo->color_cells);
2458 dpyinfo->color_cells = NULL;
2459 dpyinfo->ncolor_cells = 0;
2464 #ifdef DEBUG_X_COLORS
2465 if (rc)
2466 register_color (color->pixel);
2467 #endif /* DEBUG_X_COLORS */
2469 return rc;
2473 /* Allocate the color COLOR->pixel on frame F, colormap CMAP, after
2474 gamma correction. If an exact match can't be allocated, try the
2475 nearest color available. Value is true if successful. Set *COLOR
2476 to the color allocated. */
2478 bool
2479 x_alloc_nearest_color (struct frame *f, Colormap cmap, XColor *color)
2481 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2483 gamma_correct (f, color);
2485 if (dpyinfo->red_bits > 0)
2487 color->pixel = x_make_truecolor_pixel (dpyinfo,
2488 color->red,
2489 color->green,
2490 color->blue);
2491 return true;
2494 return x_alloc_nearest_color_1 (FRAME_X_DISPLAY (f), cmap, color);
2498 /* Allocate color PIXEL on frame F. PIXEL must already be allocated.
2499 It's necessary to do this instead of just using PIXEL directly to
2500 get color reference counts right. */
2502 unsigned long
2503 x_copy_color (struct frame *f, unsigned long pixel)
2505 XColor color;
2507 /* If display has an immutable color map, freeing colors is not
2508 necessary and some servers don't allow it. Since we won't free a
2509 color once we've allocated it, we don't need to re-allocate it to
2510 maintain the server's reference count. */
2511 if (!x_mutable_colormap (FRAME_X_VISUAL (f)))
2512 return pixel;
2514 color.pixel = pixel;
2515 block_input ();
2516 /* The color could still be found in the color_cells array. */
2517 x_query_color (f, &color);
2518 XAllocColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &color);
2519 unblock_input ();
2520 #ifdef DEBUG_X_COLORS
2521 register_color (pixel);
2522 #endif
2523 return color.pixel;
2527 /* Brightness beyond which a color won't have its highlight brightness
2528 boosted.
2530 Nominally, highlight colors for `3d' faces are calculated by
2531 brightening an object's color by a constant scale factor, but this
2532 doesn't yield good results for dark colors, so for colors who's
2533 brightness is less than this value (on a scale of 0-65535) have an
2534 use an additional additive factor.
2536 The value here is set so that the default menu-bar/mode-line color
2537 (grey75) will not have its highlights changed at all. */
2538 #define HIGHLIGHT_COLOR_DARK_BOOST_LIMIT 48000
2541 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
2542 or DELTA. Try a color with RGB values multiplied by FACTOR first.
2543 If this produces the same color as PIXEL, try a color where all RGB
2544 values have DELTA added. Return the allocated color in *PIXEL.
2545 DISPLAY is the X display, CMAP is the colormap to operate on.
2546 Value is non-zero if successful. */
2548 static bool
2549 x_alloc_lighter_color (struct frame *f, Display *display, Colormap cmap,
2550 unsigned long *pixel, double factor, int delta)
2552 XColor color, new;
2553 long bright;
2554 bool success_p;
2556 /* Get RGB color values. */
2557 color.pixel = *pixel;
2558 x_query_color (f, &color);
2560 /* Change RGB values by specified FACTOR. Avoid overflow! */
2561 eassert (factor >= 0);
2562 new.red = min (0xffff, factor * color.red);
2563 new.green = min (0xffff, factor * color.green);
2564 new.blue = min (0xffff, factor * color.blue);
2566 /* Calculate brightness of COLOR. */
2567 bright = (2 * color.red + 3 * color.green + color.blue) / 6;
2569 /* We only boost colors that are darker than
2570 HIGHLIGHT_COLOR_DARK_BOOST_LIMIT. */
2571 if (bright < HIGHLIGHT_COLOR_DARK_BOOST_LIMIT)
2572 /* Make an additive adjustment to NEW, because it's dark enough so
2573 that scaling by FACTOR alone isn't enough. */
2575 /* How far below the limit this color is (0 - 1, 1 being darker). */
2576 double dimness = 1 - (double)bright / HIGHLIGHT_COLOR_DARK_BOOST_LIMIT;
2577 /* The additive adjustment. */
2578 int min_delta = delta * dimness * factor / 2;
2580 if (factor < 1)
2582 new.red = max (0, new.red - min_delta);
2583 new.green = max (0, new.green - min_delta);
2584 new.blue = max (0, new.blue - min_delta);
2586 else
2588 new.red = min (0xffff, min_delta + new.red);
2589 new.green = min (0xffff, min_delta + new.green);
2590 new.blue = min (0xffff, min_delta + new.blue);
2594 /* Try to allocate the color. */
2595 success_p = x_alloc_nearest_color (f, cmap, &new);
2596 if (success_p)
2598 if (new.pixel == *pixel)
2600 /* If we end up with the same color as before, try adding
2601 delta to the RGB values. */
2602 x_free_colors (f, &new.pixel, 1);
2604 new.red = min (0xffff, delta + color.red);
2605 new.green = min (0xffff, delta + color.green);
2606 new.blue = min (0xffff, delta + color.blue);
2607 success_p = x_alloc_nearest_color (f, cmap, &new);
2609 else
2610 success_p = true;
2611 *pixel = new.pixel;
2614 return success_p;
2618 /* Set up the foreground color for drawing relief lines of glyph
2619 string S. RELIEF is a pointer to a struct relief containing the GC
2620 with which lines will be drawn. Use a color that is FACTOR or
2621 DELTA lighter or darker than the relief's background which is found
2622 in S->f->output_data.x->relief_background. If such a color cannot
2623 be allocated, use DEFAULT_PIXEL, instead. */
2625 static void
2626 x_setup_relief_color (struct frame *f, struct relief *relief, double factor,
2627 int delta, unsigned long default_pixel)
2629 XGCValues xgcv;
2630 struct x_output *di = f->output_data.x;
2631 unsigned long mask = GCForeground | GCLineWidth | GCGraphicsExposures;
2632 unsigned long pixel;
2633 unsigned long background = di->relief_background;
2634 Colormap cmap = FRAME_X_COLORMAP (f);
2635 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2636 Display *dpy = FRAME_X_DISPLAY (f);
2638 xgcv.graphics_exposures = False;
2639 xgcv.line_width = 1;
2641 /* Free previously allocated color. The color cell will be reused
2642 when it has been freed as many times as it was allocated, so this
2643 doesn't affect faces using the same colors. */
2644 if (relief->gc && relief->pixel != -1)
2646 x_free_colors (f, &relief->pixel, 1);
2647 relief->pixel = -1;
2650 /* Allocate new color. */
2651 xgcv.foreground = default_pixel;
2652 pixel = background;
2653 if (dpyinfo->n_planes != 1
2654 && x_alloc_lighter_color (f, dpy, cmap, &pixel, factor, delta))
2655 xgcv.foreground = relief->pixel = pixel;
2657 if (relief->gc == 0)
2659 xgcv.stipple = dpyinfo->gray;
2660 mask |= GCStipple;
2661 relief->gc = XCreateGC (dpy, FRAME_X_DRAWABLE (f), mask, &xgcv);
2663 else
2664 XChangeGC (dpy, relief->gc, mask, &xgcv);
2668 /* Set up colors for the relief lines around glyph string S. */
2670 static void
2671 x_setup_relief_colors (struct glyph_string *s)
2673 struct x_output *di = s->f->output_data.x;
2674 unsigned long color;
2676 if (s->face->use_box_color_for_shadows_p)
2677 color = s->face->box_color;
2678 else if (s->first_glyph->type == IMAGE_GLYPH
2679 && s->img->pixmap
2680 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2681 color = IMAGE_BACKGROUND (s->img, s->f, 0);
2682 else
2684 XGCValues xgcv;
2686 /* Get the background color of the face. */
2687 XGetGCValues (s->display, s->gc, GCBackground, &xgcv);
2688 color = xgcv.background;
2691 if (di->white_relief.gc == 0
2692 || color != di->relief_background)
2694 di->relief_background = color;
2695 x_setup_relief_color (s->f, &di->white_relief, 1.2, 0x8000,
2696 WHITE_PIX_DEFAULT (s->f));
2697 x_setup_relief_color (s->f, &di->black_relief, 0.6, 0x4000,
2698 BLACK_PIX_DEFAULT (s->f));
2703 /* Draw a relief on frame F inside the rectangle given by LEFT_X,
2704 TOP_Y, RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the relief
2705 to draw, it must be >= 0. RAISED_P means draw a raised
2706 relief. LEFT_P means draw a relief on the left side of
2707 the rectangle. RIGHT_P means draw a relief on the right
2708 side of the rectangle. CLIP_RECT is the clipping rectangle to use
2709 when drawing. */
2711 static void
2712 x_draw_relief_rect (struct frame *f,
2713 int left_x, int top_y, int right_x, int bottom_y,
2714 int width, bool raised_p, bool top_p, bool bot_p,
2715 bool left_p, bool right_p,
2716 XRectangle *clip_rect)
2718 #ifdef USE_CAIRO
2719 GC top_left_gc, bottom_right_gc;
2720 int corners = 0;
2722 if (raised_p)
2724 top_left_gc = f->output_data.x->white_relief.gc;
2725 bottom_right_gc = f->output_data.x->black_relief.gc;
2727 else
2729 top_left_gc = f->output_data.x->black_relief.gc;
2730 bottom_right_gc = f->output_data.x->white_relief.gc;
2733 x_set_clip_rectangles (f, top_left_gc, clip_rect, 1);
2734 x_set_clip_rectangles (f, bottom_right_gc, clip_rect, 1);
2736 if (left_p)
2738 x_fill_rectangle (f, top_left_gc, left_x, top_y,
2739 width, bottom_y + 1 - top_y);
2740 if (top_p)
2741 corners |= 1 << CORNER_TOP_LEFT;
2742 if (bot_p)
2743 corners |= 1 << CORNER_BOTTOM_LEFT;
2745 if (right_p)
2747 x_fill_rectangle (f, bottom_right_gc, right_x + 1 - width, top_y,
2748 width, bottom_y + 1 - top_y);
2749 if (top_p)
2750 corners |= 1 << CORNER_TOP_RIGHT;
2751 if (bot_p)
2752 corners |= 1 << CORNER_BOTTOM_RIGHT;
2754 if (top_p)
2756 if (!right_p)
2757 x_fill_rectangle (f, top_left_gc, left_x, top_y,
2758 right_x + 1 - left_x, width);
2759 else
2760 x_fill_trapezoid_for_relief (f, top_left_gc, left_x, top_y,
2761 right_x + 1 - left_x, width, 1);
2763 if (bot_p)
2765 if (!left_p)
2766 x_fill_rectangle (f, bottom_right_gc, left_x, bottom_y + 1 - width,
2767 right_x + 1 - left_x, width);
2768 else
2769 x_fill_trapezoid_for_relief (f, bottom_right_gc,
2770 left_x, bottom_y + 1 - width,
2771 right_x + 1 - left_x, width, 0);
2773 if (left_p && width != 1)
2774 x_fill_rectangle (f, bottom_right_gc, left_x, top_y,
2775 1, bottom_y + 1 - top_y);
2776 if (top_p && width != 1)
2777 x_fill_rectangle (f, bottom_right_gc, left_x, top_y,
2778 right_x + 1 - left_x, 1);
2779 if (corners)
2781 XSetBackground (FRAME_X_DISPLAY (f), top_left_gc,
2782 FRAME_BACKGROUND_PIXEL (f));
2783 x_erase_corners_for_relief (f, top_left_gc, left_x, top_y,
2784 right_x - left_x + 1, bottom_y - top_y + 1,
2785 6, 1, corners);
2788 x_reset_clip_rectangles (f, top_left_gc);
2789 x_reset_clip_rectangles (f, bottom_right_gc);
2790 #else
2791 Display *dpy = FRAME_X_DISPLAY (f);
2792 Drawable drawable = FRAME_X_DRAWABLE (f);
2793 int i;
2794 GC gc;
2796 if (raised_p)
2797 gc = f->output_data.x->white_relief.gc;
2798 else
2799 gc = f->output_data.x->black_relief.gc;
2800 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
2802 /* This code is more complicated than it has to be, because of two
2803 minor hacks to make the boxes look nicer: (i) if width > 1, draw
2804 the outermost line using the black relief. (ii) Omit the four
2805 corner pixels. */
2807 /* Top. */
2808 if (top_p)
2810 if (width == 1)
2811 XDrawLine (dpy, drawable, gc,
2812 left_x + left_p, top_y,
2813 right_x + !right_p, top_y);
2815 for (i = 1; i < width; ++i)
2816 XDrawLine (dpy, drawable, gc,
2817 left_x + i * left_p, top_y + i,
2818 right_x + 1 - i * right_p, top_y + i);
2821 /* Left. */
2822 if (left_p)
2824 if (width == 1)
2825 XDrawLine (dpy, drawable, gc, left_x, top_y + 1, left_x, bottom_y);
2827 x_clear_area(f, left_x, top_y, 1, 1);
2828 x_clear_area(f, left_x, bottom_y, 1, 1);
2830 for (i = (width > 1 ? 1 : 0); i < width; ++i)
2831 XDrawLine (dpy, drawable, gc,
2832 left_x + i, top_y + (i + 1) * top_p,
2833 left_x + i, bottom_y + 1 - (i + 1) * bot_p);
2836 XSetClipMask (dpy, gc, None);
2837 if (raised_p)
2838 gc = f->output_data.x->black_relief.gc;
2839 else
2840 gc = f->output_data.x->white_relief.gc;
2841 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
2843 if (width > 1)
2845 /* Outermost top line. */
2846 if (top_p)
2847 XDrawLine (dpy, drawable, gc,
2848 left_x + left_p, top_y,
2849 right_x + !right_p, top_y);
2851 /* Outermost left line. */
2852 if (left_p)
2853 XDrawLine (dpy, drawable, gc, left_x, top_y + 1, left_x, bottom_y);
2856 /* Bottom. */
2857 if (bot_p)
2859 XDrawLine (dpy, drawable, gc,
2860 left_x + left_p, bottom_y,
2861 right_x + !right_p, bottom_y);
2862 for (i = 1; i < width; ++i)
2863 XDrawLine (dpy, drawable, gc,
2864 left_x + i * left_p, bottom_y - i,
2865 right_x + 1 - i * right_p, bottom_y - i);
2868 /* Right. */
2869 if (right_p)
2871 x_clear_area(f, right_x, top_y, 1, 1);
2872 x_clear_area(f, right_x, bottom_y, 1, 1);
2873 for (i = 0; i < width; ++i)
2874 XDrawLine (dpy, drawable, gc,
2875 right_x - i, top_y + (i + 1) * top_p,
2876 right_x - i, bottom_y + 1 - (i + 1) * bot_p);
2879 x_reset_clip_rectangles (f, gc);
2881 #endif
2885 /* Draw a box on frame F inside the rectangle given by LEFT_X, TOP_Y,
2886 RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the lines to
2887 draw, it must be >= 0. LEFT_P means draw a line on the
2888 left side of the rectangle. RIGHT_P means draw a line
2889 on the right side of the rectangle. CLIP_RECT is the clipping
2890 rectangle to use when drawing. */
2892 static void
2893 x_draw_box_rect (struct glyph_string *s,
2894 int left_x, int top_y, int right_x, int bottom_y, int width,
2895 bool left_p, bool right_p, XRectangle *clip_rect)
2897 XGCValues xgcv;
2899 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2900 XSetForeground (s->display, s->gc, s->face->box_color);
2901 x_set_clip_rectangles (s->f, s->gc, clip_rect, 1);
2903 /* Top. */
2904 x_fill_rectangle (s->f, s->gc,
2905 left_x, top_y, right_x - left_x + 1, width);
2907 /* Left. */
2908 if (left_p)
2909 x_fill_rectangle (s->f, s->gc,
2910 left_x, top_y, width, bottom_y - top_y + 1);
2912 /* Bottom. */
2913 x_fill_rectangle (s->f, s->gc,
2914 left_x, bottom_y - width + 1, right_x - left_x + 1, width);
2916 /* Right. */
2917 if (right_p)
2918 x_fill_rectangle (s->f, s->gc,
2919 right_x - width + 1, top_y, width, bottom_y - top_y + 1);
2921 XSetForeground (s->display, s->gc, xgcv.foreground);
2922 x_reset_clip_rectangles (s->f, s->gc);
2926 /* Draw a box around glyph string S. */
2928 static void
2929 x_draw_glyph_string_box (struct glyph_string *s)
2931 int width, left_x, right_x, top_y, bottom_y, last_x;
2932 bool raised_p, left_p, right_p;
2933 struct glyph *last_glyph;
2934 XRectangle clip_rect;
2936 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2937 ? WINDOW_RIGHT_EDGE_X (s->w)
2938 : window_box_right (s->w, s->area));
2940 /* The glyph that may have a right box line. */
2941 last_glyph = (s->cmp || s->img
2942 ? s->first_glyph
2943 : s->first_glyph + s->nchars - 1);
2945 width = eabs (s->face->box_line_width);
2946 raised_p = s->face->box == FACE_RAISED_BOX;
2947 left_x = s->x;
2948 right_x = (s->row->full_width_p && s->extends_to_end_of_line_p
2949 ? last_x - 1
2950 : min (last_x, s->x + s->background_width) - 1);
2951 top_y = s->y;
2952 bottom_y = top_y + s->height - 1;
2954 left_p = (s->first_glyph->left_box_line_p
2955 || (s->hl == DRAW_MOUSE_FACE
2956 && (s->prev == NULL
2957 || s->prev->hl != s->hl)));
2958 right_p = (last_glyph->right_box_line_p
2959 || (s->hl == DRAW_MOUSE_FACE
2960 && (s->next == NULL
2961 || s->next->hl != s->hl)));
2963 get_glyph_string_clip_rect (s, &clip_rect);
2965 if (s->face->box == FACE_SIMPLE_BOX)
2966 x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
2967 left_p, right_p, &clip_rect);
2968 else
2970 x_setup_relief_colors (s);
2971 x_draw_relief_rect (s->f, left_x, top_y, right_x, bottom_y,
2972 width, raised_p, true, true, left_p, right_p,
2973 &clip_rect);
2978 /* Draw foreground of image glyph string S. */
2980 static void
2981 x_draw_image_foreground (struct glyph_string *s)
2983 int x = s->x;
2984 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2986 /* If first glyph of S has a left box line, start drawing it to the
2987 right of that line. */
2988 if (s->face->box != FACE_NO_BOX
2989 && s->first_glyph->left_box_line_p
2990 && s->slice.x == 0)
2991 x += eabs (s->face->box_line_width);
2993 /* If there is a margin around the image, adjust x- and y-position
2994 by that margin. */
2995 if (s->slice.x == 0)
2996 x += s->img->hmargin;
2997 if (s->slice.y == 0)
2998 y += s->img->vmargin;
3000 if (s->img->pixmap)
3002 if (s->img->mask)
3004 /* We can't set both a clip mask and use XSetClipRectangles
3005 because the latter also sets a clip mask. We also can't
3006 trust on the shape extension to be available
3007 (XShapeCombineRegion). So, compute the rectangle to draw
3008 manually. */
3009 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
3010 | GCFunction);
3011 XGCValues xgcv;
3012 XRectangle clip_rect, image_rect, r;
3014 xgcv.clip_mask = s->img->mask;
3015 xgcv.clip_x_origin = x;
3016 xgcv.clip_y_origin = y;
3017 xgcv.function = GXcopy;
3018 XChangeGC (s->display, s->gc, mask, &xgcv);
3020 get_glyph_string_clip_rect (s, &clip_rect);
3021 image_rect.x = x;
3022 image_rect.y = y;
3023 image_rect.width = s->slice.width;
3024 image_rect.height = s->slice.height;
3025 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
3026 XCopyArea (s->display, s->img->pixmap,
3027 FRAME_X_DRAWABLE (s->f), s->gc,
3028 s->slice.x + r.x - x, s->slice.y + r.y - y,
3029 r.width, r.height, r.x, r.y);
3031 else
3033 XRectangle clip_rect, image_rect, r;
3035 get_glyph_string_clip_rect (s, &clip_rect);
3036 image_rect.x = x;
3037 image_rect.y = y;
3038 image_rect.width = s->slice.width;
3039 image_rect.height = s->slice.height;
3040 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
3041 XCopyArea (s->display, s->img->pixmap,
3042 FRAME_X_DRAWABLE (s->f), s->gc,
3043 s->slice.x + r.x - x, s->slice.y + r.y - y,
3044 r.width, r.height, r.x, r.y);
3046 /* When the image has a mask, we can expect that at
3047 least part of a mouse highlight or a block cursor will
3048 be visible. If the image doesn't have a mask, make
3049 a block cursor visible by drawing a rectangle around
3050 the image. I believe it's looking better if we do
3051 nothing here for mouse-face. */
3052 if (s->hl == DRAW_CURSOR)
3054 int relief = eabs (s->img->relief);
3055 x_draw_rectangle (s->f, s->gc,
3056 x - relief, y - relief,
3057 s->slice.width + relief*2 - 1,
3058 s->slice.height + relief*2 - 1);
3062 else
3063 /* Draw a rectangle if image could not be loaded. */
3064 x_draw_rectangle (s->f, s->gc, x, y,
3065 s->slice.width - 1, s->slice.height - 1);
3069 /* Draw a relief around the image glyph string S. */
3071 static void
3072 x_draw_image_relief (struct glyph_string *s)
3074 int x1, y1, thick;
3075 bool raised_p, top_p, bot_p, left_p, right_p;
3076 int extra_x, extra_y;
3077 XRectangle r;
3078 int x = s->x;
3079 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
3081 /* If first glyph of S has a left box line, start drawing it to the
3082 right of that line. */
3083 if (s->face->box != FACE_NO_BOX
3084 && s->first_glyph->left_box_line_p
3085 && s->slice.x == 0)
3086 x += eabs (s->face->box_line_width);
3088 /* If there is a margin around the image, adjust x- and y-position
3089 by that margin. */
3090 if (s->slice.x == 0)
3091 x += s->img->hmargin;
3092 if (s->slice.y == 0)
3093 y += s->img->vmargin;
3095 if (s->hl == DRAW_IMAGE_SUNKEN
3096 || s->hl == DRAW_IMAGE_RAISED)
3098 thick = tool_bar_button_relief >= 0 ? tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3099 raised_p = s->hl == DRAW_IMAGE_RAISED;
3101 else
3103 thick = eabs (s->img->relief);
3104 raised_p = s->img->relief > 0;
3107 x1 = x + s->slice.width - 1;
3108 y1 = y + s->slice.height - 1;
3110 extra_x = extra_y = 0;
3111 if (s->face->id == TOOL_BAR_FACE_ID)
3113 if (CONSP (Vtool_bar_button_margin)
3114 && INTEGERP (XCAR (Vtool_bar_button_margin))
3115 && INTEGERP (XCDR (Vtool_bar_button_margin)))
3117 extra_x = XINT (XCAR (Vtool_bar_button_margin));
3118 extra_y = XINT (XCDR (Vtool_bar_button_margin));
3120 else if (INTEGERP (Vtool_bar_button_margin))
3121 extra_x = extra_y = XINT (Vtool_bar_button_margin);
3124 top_p = bot_p = left_p = right_p = false;
3126 if (s->slice.x == 0)
3127 x -= thick + extra_x, left_p = true;
3128 if (s->slice.y == 0)
3129 y -= thick + extra_y, top_p = true;
3130 if (s->slice.x + s->slice.width == s->img->width)
3131 x1 += thick + extra_x, right_p = true;
3132 if (s->slice.y + s->slice.height == s->img->height)
3133 y1 += thick + extra_y, bot_p = true;
3135 x_setup_relief_colors (s);
3136 get_glyph_string_clip_rect (s, &r);
3137 x_draw_relief_rect (s->f, x, y, x1, y1, thick, raised_p,
3138 top_p, bot_p, left_p, right_p, &r);
3142 /* Draw the foreground of image glyph string S to PIXMAP. */
3144 static void
3145 x_draw_image_foreground_1 (struct glyph_string *s, Pixmap pixmap)
3147 int x = 0;
3148 int y = s->ybase - s->y - image_ascent (s->img, s->face, &s->slice);
3150 /* If first glyph of S has a left box line, start drawing it to the
3151 right of that line. */
3152 if (s->face->box != FACE_NO_BOX
3153 && s->first_glyph->left_box_line_p
3154 && s->slice.x == 0)
3155 x += eabs (s->face->box_line_width);
3157 /* If there is a margin around the image, adjust x- and y-position
3158 by that margin. */
3159 if (s->slice.x == 0)
3160 x += s->img->hmargin;
3161 if (s->slice.y == 0)
3162 y += s->img->vmargin;
3164 if (s->img->pixmap)
3166 if (s->img->mask)
3168 /* We can't set both a clip mask and use XSetClipRectangles
3169 because the latter also sets a clip mask. We also can't
3170 trust on the shape extension to be available
3171 (XShapeCombineRegion). So, compute the rectangle to draw
3172 manually. */
3173 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
3174 | GCFunction);
3175 XGCValues xgcv;
3177 xgcv.clip_mask = s->img->mask;
3178 xgcv.clip_x_origin = x - s->slice.x;
3179 xgcv.clip_y_origin = y - s->slice.y;
3180 xgcv.function = GXcopy;
3181 XChangeGC (s->display, s->gc, mask, &xgcv);
3183 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
3184 s->slice.x, s->slice.y,
3185 s->slice.width, s->slice.height, x, y);
3186 XSetClipMask (s->display, s->gc, None);
3188 else
3190 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
3191 s->slice.x, s->slice.y,
3192 s->slice.width, s->slice.height, x, y);
3194 /* When the image has a mask, we can expect that at
3195 least part of a mouse highlight or a block cursor will
3196 be visible. If the image doesn't have a mask, make
3197 a block cursor visible by drawing a rectangle around
3198 the image. I believe it's looking better if we do
3199 nothing here for mouse-face. */
3200 if (s->hl == DRAW_CURSOR)
3202 int r = eabs (s->img->relief);
3203 x_draw_rectangle (s->f, s->gc, x - r, y - r,
3204 s->slice.width + r*2 - 1,
3205 s->slice.height + r*2 - 1);
3209 else
3210 /* Draw a rectangle if image could not be loaded. */
3211 x_draw_rectangle (s->f, s->gc, x, y,
3212 s->slice.width - 1, s->slice.height - 1);
3216 /* Draw part of the background of glyph string S. X, Y, W, and H
3217 give the rectangle to draw. */
3219 static void
3220 x_draw_glyph_string_bg_rect (struct glyph_string *s, int x, int y, int w, int h)
3222 if (s->stippled_p)
3224 /* Fill background with a stipple pattern. */
3225 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
3226 x_fill_rectangle (s->f, s->gc, x, y, w, h);
3227 XSetFillStyle (s->display, s->gc, FillSolid);
3229 else
3230 x_clear_glyph_string_rect (s, x, y, w, h);
3234 /* Draw image glyph string S.
3236 s->y
3237 s->x +-------------------------
3238 | s->face->box
3240 | +-------------------------
3241 | | s->img->margin
3243 | | +-------------------
3244 | | | the image
3248 static void
3249 x_draw_image_glyph_string (struct glyph_string *s)
3251 int box_line_hwidth = eabs (s->face->box_line_width);
3252 int box_line_vwidth = max (s->face->box_line_width, 0);
3253 int height;
3254 Pixmap pixmap = None;
3256 height = s->height;
3257 if (s->slice.y == 0)
3258 height -= box_line_vwidth;
3259 if (s->slice.y + s->slice.height >= s->img->height)
3260 height -= box_line_vwidth;
3262 /* Fill background with face under the image. Do it only if row is
3263 taller than image or if image has a clip mask to reduce
3264 flickering. */
3265 s->stippled_p = s->face->stipple != 0;
3266 if (height > s->slice.height
3267 || s->img->hmargin
3268 || s->img->vmargin
3269 || s->img->mask
3270 || s->img->pixmap == 0
3271 || s->width != s->background_width)
3273 if (s->img->mask)
3275 /* Create a pixmap as large as the glyph string. Fill it
3276 with the background color. Copy the image to it, using
3277 its mask. Copy the temporary pixmap to the display. */
3278 Screen *screen = FRAME_X_SCREEN (s->f);
3279 int depth = DefaultDepthOfScreen (screen);
3281 /* Create a pixmap as large as the glyph string. */
3282 pixmap = XCreatePixmap (s->display, FRAME_X_DRAWABLE (s->f),
3283 s->background_width,
3284 s->height, depth);
3286 /* Don't clip in the following because we're working on the
3287 pixmap. */
3288 XSetClipMask (s->display, s->gc, None);
3290 /* Fill the pixmap with the background color/stipple. */
3291 if (s->stippled_p)
3293 /* Fill background with a stipple pattern. */
3294 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
3295 XSetTSOrigin (s->display, s->gc, - s->x, - s->y);
3296 XFillRectangle (s->display, pixmap, s->gc,
3297 0, 0, s->background_width, s->height);
3298 XSetFillStyle (s->display, s->gc, FillSolid);
3299 XSetTSOrigin (s->display, s->gc, 0, 0);
3301 else
3303 XGCValues xgcv;
3304 XGetGCValues (s->display, s->gc, GCForeground | GCBackground,
3305 &xgcv);
3306 XSetForeground (s->display, s->gc, xgcv.background);
3307 XFillRectangle (s->display, pixmap, s->gc,
3308 0, 0, s->background_width, s->height);
3309 XSetForeground (s->display, s->gc, xgcv.foreground);
3312 else
3314 int x = s->x;
3315 int y = s->y;
3316 int width = s->background_width;
3318 if (s->first_glyph->left_box_line_p
3319 && s->slice.x == 0)
3321 x += box_line_hwidth;
3322 width -= box_line_hwidth;
3325 if (s->slice.y == 0)
3326 y += box_line_vwidth;
3328 x_draw_glyph_string_bg_rect (s, x, y, width, height);
3331 s->background_filled_p = true;
3334 /* Draw the foreground. */
3335 #ifdef USE_CAIRO
3336 if (s->img->cr_data)
3338 cairo_t *cr = x_begin_cr_clip (s->f, s->gc);
3340 int x = s->x + s->img->hmargin;
3341 int y = s->y + s->img->vmargin;
3342 int width = s->background_width;
3344 cairo_set_source_surface (cr, s->img->cr_data,
3345 x - s->slice.x,
3346 y - s->slice.y);
3347 cairo_rectangle (cr, x, y, width, height);
3348 cairo_fill (cr);
3349 x_end_cr_clip (s->f);
3351 else
3352 #endif
3353 if (pixmap != None)
3355 x_draw_image_foreground_1 (s, pixmap);
3356 x_set_glyph_string_clipping (s);
3357 XCopyArea (s->display, pixmap, FRAME_X_DRAWABLE (s->f), s->gc,
3358 0, 0, s->background_width, s->height, s->x, s->y);
3359 XFreePixmap (s->display, pixmap);
3361 else
3362 x_draw_image_foreground (s);
3364 /* If we must draw a relief around the image, do it. */
3365 if (s->img->relief
3366 || s->hl == DRAW_IMAGE_RAISED
3367 || s->hl == DRAW_IMAGE_SUNKEN)
3368 x_draw_image_relief (s);
3372 /* Draw stretch glyph string S. */
3374 static void
3375 x_draw_stretch_glyph_string (struct glyph_string *s)
3377 eassert (s->first_glyph->type == STRETCH_GLYPH);
3379 if (s->hl == DRAW_CURSOR
3380 && !x_stretch_cursor_p)
3382 /* If `x-stretch-cursor' is nil, don't draw a block cursor as
3383 wide as the stretch glyph. */
3384 int width, background_width = s->background_width;
3385 int x = s->x;
3387 if (!s->row->reversed_p)
3389 int left_x = window_box_left_offset (s->w, TEXT_AREA);
3391 if (x < left_x)
3393 background_width -= left_x - x;
3394 x = left_x;
3397 else
3399 /* In R2L rows, draw the cursor on the right edge of the
3400 stretch glyph. */
3401 int right_x = window_box_right (s->w, TEXT_AREA);
3403 if (x + background_width > right_x)
3404 background_width -= x - right_x;
3405 x += background_width;
3407 width = min (FRAME_COLUMN_WIDTH (s->f), background_width);
3408 if (s->row->reversed_p)
3409 x -= width;
3411 /* Draw cursor. */
3412 x_draw_glyph_string_bg_rect (s, x, s->y, width, s->height);
3414 /* Clear rest using the GC of the original non-cursor face. */
3415 if (width < background_width)
3417 int y = s->y;
3418 int w = background_width - width, h = s->height;
3419 XRectangle r;
3420 GC gc;
3422 if (!s->row->reversed_p)
3423 x += width;
3424 else
3425 x = s->x;
3426 if (s->row->mouse_face_p
3427 && cursor_in_mouse_face_p (s->w))
3429 x_set_mouse_face_gc (s);
3430 gc = s->gc;
3432 else
3433 gc = s->face->gc;
3435 get_glyph_string_clip_rect (s, &r);
3436 x_set_clip_rectangles (s->f, gc, &r, 1);
3438 if (s->face->stipple)
3440 /* Fill background with a stipple pattern. */
3441 XSetFillStyle (s->display, gc, FillOpaqueStippled);
3442 x_fill_rectangle (s->f, gc, x, y, w, h);
3443 XSetFillStyle (s->display, gc, FillSolid);
3445 else
3447 XGCValues xgcv;
3448 XGetGCValues (s->display, gc, GCForeground | GCBackground, &xgcv);
3449 XSetForeground (s->display, gc, xgcv.background);
3450 x_fill_rectangle (s->f, gc, x, y, w, h);
3451 XSetForeground (s->display, gc, xgcv.foreground);
3454 x_reset_clip_rectangles (s->f, gc);
3457 else if (!s->background_filled_p)
3459 int background_width = s->background_width;
3460 int x = s->x, left_x = window_box_left_offset (s->w, TEXT_AREA);
3462 /* Don't draw into left margin, fringe or scrollbar area
3463 except for header line and mode line. */
3464 if (x < left_x && !s->row->mode_line_p)
3466 background_width -= left_x - x;
3467 x = left_x;
3469 if (background_width > 0)
3470 x_draw_glyph_string_bg_rect (s, x, s->y, background_width, s->height);
3473 s->background_filled_p = true;
3476 static void
3477 x_get_scale_factor(Display *disp, int *scale_x, int *scale_y)
3479 const int base_res = 96;
3480 struct x_display_info * dpyinfo = x_display_info_for_display (disp);
3482 *scale_x = *scale_y = 1;
3484 if (dpyinfo)
3486 if (dpyinfo->resx > base_res)
3487 *scale_x = floor (dpyinfo->resx / base_res);
3488 if (dpyinfo->resy > base_res)
3489 *scale_y = floor (dpyinfo->resy / base_res);
3494 Draw a wavy line under S. The wave fills wave_height pixels from y0.
3496 x0 wave_length = 2
3498 y0 * * * * *
3499 |* * * * * * * * *
3500 wave_height = 3 | * * * *
3503 static void
3504 x_draw_underwave (struct glyph_string *s)
3506 /* Adjust for scale/HiDPI. */
3507 int scale_x, scale_y;
3509 x_get_scale_factor (s->display, &scale_x, &scale_y);
3511 int wave_height = 3 * scale_y, wave_length = 2 * scale_x, thickness = scale_y;
3513 #ifdef USE_CAIRO
3514 x_draw_horizontal_wave (s->f, s->gc, s->x, s->ybase - wave_height + 3,
3515 s->width, wave_height, wave_length);
3516 #else /* not USE_CAIRO */
3517 int dx, dy, x0, y0, width, x1, y1, x2, y2, xmax;
3518 bool odd;
3519 XRectangle wave_clip, string_clip, final_clip;
3521 dx = wave_length;
3522 dy = wave_height - 1;
3523 x0 = s->x;
3524 y0 = s->ybase + wave_height / 2 - scale_y;
3525 width = s->width;
3526 xmax = x0 + width;
3528 /* Find and set clipping rectangle */
3530 wave_clip.x = x0;
3531 wave_clip.y = y0;
3532 wave_clip.width = width;
3533 wave_clip.height = wave_height;
3534 get_glyph_string_clip_rect (s, &string_clip);
3536 if (!x_intersect_rectangles (&wave_clip, &string_clip, &final_clip))
3537 return;
3539 XSetClipRectangles (s->display, s->gc, 0, 0, &final_clip, 1, Unsorted);
3541 /* Draw the waves */
3543 x1 = x0 - (x0 % dx);
3544 x2 = x1 + dx;
3545 odd = (x1 / dx) & 1;
3546 y1 = y2 = y0;
3548 if (odd)
3549 y1 += dy;
3550 else
3551 y2 += dy;
3553 if (INT_MAX - dx < xmax)
3554 emacs_abort ();
3556 while (x1 <= xmax)
3558 XSetLineAttributes (s->display, s->gc, thickness, LineSolid, CapButt,
3559 JoinRound);
3560 XDrawLine (s->display, FRAME_X_DRAWABLE (s->f), s->gc, x1, y1, x2, y2);
3561 x1 = x2, y1 = y2;
3562 x2 += dx, y2 = y0 + odd*dy;
3563 odd = !odd;
3566 /* Restore previous clipping rectangle(s) */
3567 XSetClipRectangles (s->display, s->gc, 0, 0, s->clip, s->num_clips, Unsorted);
3568 #endif /* not USE_CAIRO */
3572 /* Draw glyph string S. */
3574 static void
3575 x_draw_glyph_string (struct glyph_string *s)
3577 bool relief_drawn_p = false;
3579 /* If S draws into the background of its successors, draw the
3580 background of the successors first so that S can draw into it.
3581 This makes S->next use XDrawString instead of XDrawImageString. */
3582 if (s->next && s->right_overhang && !s->for_overlaps)
3584 int width;
3585 struct glyph_string *next;
3587 for (width = 0, next = s->next;
3588 next && width < s->right_overhang;
3589 width += next->width, next = next->next)
3590 if (next->first_glyph->type != IMAGE_GLYPH)
3592 x_set_glyph_string_gc (next);
3593 x_set_glyph_string_clipping (next);
3594 if (next->first_glyph->type == STRETCH_GLYPH)
3595 x_draw_stretch_glyph_string (next);
3596 else
3597 x_draw_glyph_string_background (next, true);
3598 next->num_clips = 0;
3602 /* Set up S->gc, set clipping and draw S. */
3603 x_set_glyph_string_gc (s);
3605 /* Draw relief (if any) in advance for char/composition so that the
3606 glyph string can be drawn over it. */
3607 if (!s->for_overlaps
3608 && s->face->box != FACE_NO_BOX
3609 && (s->first_glyph->type == CHAR_GLYPH
3610 || s->first_glyph->type == COMPOSITE_GLYPH))
3613 x_set_glyph_string_clipping (s);
3614 x_draw_glyph_string_background (s, true);
3615 x_draw_glyph_string_box (s);
3616 x_set_glyph_string_clipping (s);
3617 relief_drawn_p = true;
3619 else if (!s->clip_head /* draw_glyphs didn't specify a clip mask. */
3620 && !s->clip_tail
3621 && ((s->prev && s->prev->hl != s->hl && s->left_overhang)
3622 || (s->next && s->next->hl != s->hl && s->right_overhang)))
3623 /* We must clip just this glyph. left_overhang part has already
3624 drawn when s->prev was drawn, and right_overhang part will be
3625 drawn later when s->next is drawn. */
3626 x_set_glyph_string_clipping_exactly (s, s);
3627 else
3628 x_set_glyph_string_clipping (s);
3630 switch (s->first_glyph->type)
3632 case IMAGE_GLYPH:
3633 x_draw_image_glyph_string (s);
3634 break;
3636 case XWIDGET_GLYPH:
3637 x_draw_xwidget_glyph_string (s);
3638 break;
3640 case STRETCH_GLYPH:
3641 x_draw_stretch_glyph_string (s);
3642 break;
3644 case CHAR_GLYPH:
3645 if (s->for_overlaps)
3646 s->background_filled_p = true;
3647 else
3648 x_draw_glyph_string_background (s, false);
3649 x_draw_glyph_string_foreground (s);
3650 break;
3652 case COMPOSITE_GLYPH:
3653 if (s->for_overlaps || (s->cmp_from > 0
3654 && ! s->first_glyph->u.cmp.automatic))
3655 s->background_filled_p = true;
3656 else
3657 x_draw_glyph_string_background (s, true);
3658 x_draw_composite_glyph_string_foreground (s);
3659 break;
3661 case GLYPHLESS_GLYPH:
3662 if (s->for_overlaps)
3663 s->background_filled_p = true;
3664 else
3665 x_draw_glyph_string_background (s, true);
3666 x_draw_glyphless_glyph_string_foreground (s);
3667 break;
3669 default:
3670 emacs_abort ();
3673 if (!s->for_overlaps)
3675 /* Draw underline. */
3676 if (s->face->underline_p)
3678 if (s->face->underline_type == FACE_UNDER_WAVE)
3680 if (s->face->underline_defaulted_p)
3681 x_draw_underwave (s);
3682 else
3684 XGCValues xgcv;
3685 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3686 XSetForeground (s->display, s->gc, s->face->underline_color);
3687 x_draw_underwave (s);
3688 XSetForeground (s->display, s->gc, xgcv.foreground);
3691 else if (s->face->underline_type == FACE_UNDER_LINE)
3693 unsigned long thickness, position;
3694 int y;
3696 if (s->prev && s->prev->face->underline_p
3697 && s->prev->face->underline_type == FACE_UNDER_LINE)
3699 /* We use the same underline style as the previous one. */
3700 thickness = s->prev->underline_thickness;
3701 position = s->prev->underline_position;
3703 else
3705 struct font *font = font_for_underline_metrics (s);
3707 /* Get the underline thickness. Default is 1 pixel. */
3708 if (font && font->underline_thickness > 0)
3709 thickness = font->underline_thickness;
3710 else
3711 thickness = 1;
3712 if (x_underline_at_descent_line)
3713 position = (s->height - thickness) - (s->ybase - s->y);
3714 else
3716 /* Get the underline position. This is the recommended
3717 vertical offset in pixels from the baseline to the top of
3718 the underline. This is a signed value according to the
3719 specs, and its default is
3721 ROUND ((maximum descent) / 2), with
3722 ROUND(x) = floor (x + 0.5) */
3724 if (x_use_underline_position_properties
3725 && font && font->underline_position >= 0)
3726 position = font->underline_position;
3727 else if (font)
3728 position = (font->descent + 1) / 2;
3729 else
3730 position = underline_minimum_offset;
3732 position = max (position, underline_minimum_offset);
3734 /* Check the sanity of thickness and position. We should
3735 avoid drawing underline out of the current line area. */
3736 if (s->y + s->height <= s->ybase + position)
3737 position = (s->height - 1) - (s->ybase - s->y);
3738 if (s->y + s->height < s->ybase + position + thickness)
3739 thickness = (s->y + s->height) - (s->ybase + position);
3740 s->underline_thickness = thickness;
3741 s->underline_position = position;
3742 y = s->ybase + position;
3743 if (s->face->underline_defaulted_p)
3744 x_fill_rectangle (s->f, s->gc,
3745 s->x, y, s->width, thickness);
3746 else
3748 XGCValues xgcv;
3749 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3750 XSetForeground (s->display, s->gc, s->face->underline_color);
3751 x_fill_rectangle (s->f, s->gc,
3752 s->x, y, s->width, thickness);
3753 XSetForeground (s->display, s->gc, xgcv.foreground);
3757 /* Draw overline. */
3758 if (s->face->overline_p)
3760 unsigned long dy = 0, h = 1;
3762 if (s->face->overline_color_defaulted_p)
3763 x_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3764 s->width, h);
3765 else
3767 XGCValues xgcv;
3768 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3769 XSetForeground (s->display, s->gc, s->face->overline_color);
3770 x_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3771 s->width, h);
3772 XSetForeground (s->display, s->gc, xgcv.foreground);
3776 /* Draw strike-through. */
3777 if (s->face->strike_through_p)
3779 /* Y-coordinate and height of the glyph string's first
3780 glyph. We cannot use s->y and s->height because those
3781 could be larger if there are taller display elements
3782 (e.g., characters displayed with a larger font) in the
3783 same glyph row. */
3784 int glyph_y = s->ybase - s->first_glyph->ascent;
3785 int glyph_height = s->first_glyph->ascent + s->first_glyph->descent;
3786 /* Strike-through width and offset from the glyph string's
3787 top edge. */
3788 unsigned long h = 1;
3789 unsigned long dy = (glyph_height - h) / 2;
3791 if (s->face->strike_through_color_defaulted_p)
3792 x_fill_rectangle (s->f, s->gc, s->x, glyph_y + dy,
3793 s->width, h);
3794 else
3796 XGCValues xgcv;
3797 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3798 XSetForeground (s->display, s->gc, s->face->strike_through_color);
3799 x_fill_rectangle (s->f, s->gc, s->x, glyph_y + dy,
3800 s->width, h);
3801 XSetForeground (s->display, s->gc, xgcv.foreground);
3805 /* Draw relief if not yet drawn. */
3806 if (!relief_drawn_p && s->face->box != FACE_NO_BOX)
3807 x_draw_glyph_string_box (s);
3809 if (s->prev)
3811 struct glyph_string *prev;
3813 for (prev = s->prev; prev; prev = prev->prev)
3814 if (prev->hl != s->hl
3815 && prev->x + prev->width + prev->right_overhang > s->x)
3817 /* As prev was drawn while clipped to its own area, we
3818 must draw the right_overhang part using s->hl now. */
3819 enum draw_glyphs_face save = prev->hl;
3821 prev->hl = s->hl;
3822 x_set_glyph_string_gc (prev);
3823 x_set_glyph_string_clipping_exactly (s, prev);
3824 if (prev->first_glyph->type == CHAR_GLYPH)
3825 x_draw_glyph_string_foreground (prev);
3826 else
3827 x_draw_composite_glyph_string_foreground (prev);
3828 x_reset_clip_rectangles (prev->f, prev->gc);
3829 prev->hl = save;
3830 prev->num_clips = 0;
3834 if (s->next)
3836 struct glyph_string *next;
3838 for (next = s->next; next; next = next->next)
3839 if (next->hl != s->hl
3840 && next->x - next->left_overhang < s->x + s->width)
3842 /* As next will be drawn while clipped to its own area,
3843 we must draw the left_overhang part using s->hl now. */
3844 enum draw_glyphs_face save = next->hl;
3846 next->hl = s->hl;
3847 x_set_glyph_string_gc (next);
3848 x_set_glyph_string_clipping_exactly (s, next);
3849 if (next->first_glyph->type == CHAR_GLYPH)
3850 x_draw_glyph_string_foreground (next);
3851 else
3852 x_draw_composite_glyph_string_foreground (next);
3853 x_reset_clip_rectangles (next->f, next->gc);
3854 next->hl = save;
3855 next->num_clips = 0;
3856 next->clip_head = s->next;
3861 /* Reset clipping. */
3862 x_reset_clip_rectangles (s->f, s->gc);
3863 s->num_clips = 0;
3866 /* Shift display to make room for inserted glyphs. */
3868 static void
3869 x_shift_glyphs_for_insert (struct frame *f, int x, int y, int width, int height, int shift_by)
3871 /* Never called on a GUI frame, see
3872 http://lists.gnu.org/archive/html/emacs-devel/2015-05/msg00456.html
3874 XCopyArea (FRAME_X_DISPLAY (f), FRAME_X_DRAWABLE (f), FRAME_X_DRAWABLE (f),
3875 f->output_data.x->normal_gc,
3876 x, y, width, height,
3877 x + shift_by, y);
3880 /* Delete N glyphs at the nominal cursor position. Not implemented
3881 for X frames. */
3883 static void
3884 x_delete_glyphs (struct frame *f, register int n)
3886 emacs_abort ();
3890 /* Like XClearArea, but check that WIDTH and HEIGHT are reasonable.
3891 If they are <= 0, this is probably an error. */
3893 static ATTRIBUTE_UNUSED void
3894 x_clear_area1 (Display *dpy, Window window,
3895 int x, int y, int width, int height, int exposures)
3897 eassert (width > 0 && height > 0);
3898 XClearArea (dpy, window, x, y, width, height, exposures);
3901 void
3902 x_clear_area (struct frame *f, int x, int y, int width, int height)
3904 #ifdef USE_CAIRO
3905 cairo_t *cr;
3907 eassert (width > 0 && height > 0);
3909 cr = x_begin_cr_clip (f, NULL);
3910 x_set_cr_source_with_gc_background (f, f->output_data.x->normal_gc);
3911 cairo_rectangle (cr, x, y, width, height);
3912 cairo_fill (cr);
3913 x_end_cr_clip (f);
3914 #else
3915 if (FRAME_X_DOUBLE_BUFFERED_P (f))
3916 XFillRectangle (FRAME_X_DISPLAY (f),
3917 FRAME_X_DRAWABLE (f),
3918 f->output_data.x->reverse_gc,
3919 x, y, width, height);
3920 else
3921 x_clear_area1 (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3922 x, y, width, height, False);
3923 #endif
3927 /* Clear an entire frame. */
3929 static void
3930 x_clear_frame (struct frame *f)
3932 /* Clearing the frame will erase any cursor, so mark them all as no
3933 longer visible. */
3934 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
3936 block_input ();
3938 font_drop_xrender_surfaces (f);
3939 x_clear_window (f);
3941 /* We have to clear the scroll bars. If we have changed colors or
3942 something like that, then they should be notified. */
3943 x_scroll_bar_clear (f);
3945 XFlush (FRAME_X_DISPLAY (f));
3947 unblock_input ();
3950 /* RIF: Show hourglass cursor on frame F. */
3952 static void
3953 x_show_hourglass (struct frame *f)
3955 Display *dpy = FRAME_X_DISPLAY (f);
3957 if (dpy)
3959 struct x_output *x = FRAME_X_OUTPUT (f);
3960 #ifdef USE_X_TOOLKIT
3961 if (x->widget)
3962 #else
3963 if (FRAME_OUTER_WINDOW (f))
3964 #endif
3966 x->hourglass_p = true;
3968 if (!x->hourglass_window)
3970 unsigned long mask = CWCursor;
3971 XSetWindowAttributes attrs;
3972 #ifdef USE_GTK
3973 Window parent = FRAME_X_WINDOW (f);
3974 #else
3975 Window parent = FRAME_OUTER_WINDOW (f);
3976 #endif
3977 attrs.cursor = x->hourglass_cursor;
3979 x->hourglass_window = XCreateWindow
3980 (dpy, parent, 0, 0, 32000, 32000, 0, 0,
3981 InputOnly, CopyFromParent, mask, &attrs);
3984 XMapRaised (dpy, x->hourglass_window);
3985 XFlush (dpy);
3990 /* RIF: Cancel hourglass cursor on frame F. */
3992 static void
3993 x_hide_hourglass (struct frame *f)
3995 struct x_output *x = FRAME_X_OUTPUT (f);
3997 /* Watch out for newly created frames. */
3998 if (x->hourglass_window)
4000 XUnmapWindow (FRAME_X_DISPLAY (f), x->hourglass_window);
4001 /* Sync here because XTread_socket looks at the
4002 hourglass_p flag that is reset to zero below. */
4003 XSync (FRAME_X_DISPLAY (f), False);
4004 x->hourglass_p = false;
4008 /* Invert the middle quarter of the frame for .15 sec. */
4010 static void
4011 XTflash (struct frame *f)
4013 block_input ();
4016 #ifdef USE_GTK
4017 /* Use Gdk routines to draw. This way, we won't draw over scroll bars
4018 when the scroll bars and the edit widget share the same X window. */
4019 GdkWindow *window = gtk_widget_get_window (FRAME_GTK_WIDGET (f));
4020 #ifdef HAVE_GTK3
4021 cairo_t *cr = gdk_cairo_create (window);
4022 cairo_set_source_rgb (cr, 1, 1, 1);
4023 cairo_set_operator (cr, CAIRO_OPERATOR_DIFFERENCE);
4024 #define XFillRectangle(d, win, gc, x, y, w, h) \
4025 do { \
4026 cairo_rectangle (cr, x, y, w, h); \
4027 cairo_fill (cr); \
4029 while (false)
4030 #else /* ! HAVE_GTK3 */
4031 GdkGCValues vals;
4032 GdkGC *gc;
4033 vals.foreground.pixel = (FRAME_FOREGROUND_PIXEL (f)
4034 ^ FRAME_BACKGROUND_PIXEL (f));
4035 vals.function = GDK_XOR;
4036 gc = gdk_gc_new_with_values (window,
4037 &vals, GDK_GC_FUNCTION | GDK_GC_FOREGROUND);
4038 #define XFillRectangle(d, win, gc, x, y, w, h) \
4039 gdk_draw_rectangle (window, gc, true, x, y, w, h)
4040 #endif /* ! HAVE_GTK3 */
4041 #else /* ! USE_GTK */
4042 GC gc;
4044 /* Create a GC that will use the GXxor function to flip foreground
4045 pixels into background pixels. */
4047 XGCValues values;
4049 values.function = GXxor;
4050 values.foreground = (FRAME_FOREGROUND_PIXEL (f)
4051 ^ FRAME_BACKGROUND_PIXEL (f));
4053 gc = XCreateGC (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4054 GCFunction | GCForeground, &values);
4056 #endif
4058 /* Get the height not including a menu bar widget. */
4059 int height = FRAME_PIXEL_HEIGHT (f);
4060 /* Height of each line to flash. */
4061 int flash_height = FRAME_LINE_HEIGHT (f);
4062 /* These will be the left and right margins of the rectangles. */
4063 int flash_left = FRAME_INTERNAL_BORDER_WIDTH (f);
4064 int flash_right = FRAME_PIXEL_WIDTH (f) - FRAME_INTERNAL_BORDER_WIDTH (f);
4065 int width = flash_right - flash_left;
4067 /* If window is tall, flash top and bottom line. */
4068 if (height > 3 * FRAME_LINE_HEIGHT (f))
4070 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4071 flash_left,
4072 (FRAME_INTERNAL_BORDER_WIDTH (f)
4073 + FRAME_TOP_MARGIN_HEIGHT (f)),
4074 width, flash_height);
4075 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4076 flash_left,
4077 (height - flash_height
4078 - FRAME_INTERNAL_BORDER_WIDTH (f)),
4079 width, flash_height);
4082 else
4083 /* If it is short, flash it all. */
4084 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4085 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
4086 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
4088 x_flush (f);
4091 struct timespec delay = make_timespec (0, 150 * 1000 * 1000);
4092 struct timespec wakeup = timespec_add (current_timespec (), delay);
4094 /* Keep waiting until past the time wakeup or any input gets
4095 available. */
4096 while (! detect_input_pending ())
4098 struct timespec current = current_timespec ();
4099 struct timespec timeout;
4101 /* Break if result would not be positive. */
4102 if (timespec_cmp (wakeup, current) <= 0)
4103 break;
4105 /* How long `select' should wait. */
4106 timeout = make_timespec (0, 10 * 1000 * 1000);
4108 /* Try to wait that long--but we might wake up sooner. */
4109 pselect (0, NULL, NULL, NULL, &timeout, NULL);
4113 /* If window is tall, flash top and bottom line. */
4114 if (height > 3 * FRAME_LINE_HEIGHT (f))
4116 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4117 flash_left,
4118 (FRAME_INTERNAL_BORDER_WIDTH (f)
4119 + FRAME_TOP_MARGIN_HEIGHT (f)),
4120 width, flash_height);
4121 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4122 flash_left,
4123 (height - flash_height
4124 - FRAME_INTERNAL_BORDER_WIDTH (f)),
4125 width, flash_height);
4127 else
4128 /* If it is short, flash it all. */
4129 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4130 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
4131 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
4133 #ifdef USE_GTK
4134 #ifdef HAVE_GTK3
4135 cairo_destroy (cr);
4136 #else
4137 g_object_unref (G_OBJECT (gc));
4138 #endif
4139 #undef XFillRectangle
4140 #else
4141 XFreeGC (FRAME_X_DISPLAY (f), gc);
4142 #endif
4143 x_flush (f);
4147 unblock_input ();
4151 static void
4152 XTtoggle_invisible_pointer (struct frame *f, bool invisible)
4154 block_input ();
4155 FRAME_DISPLAY_INFO (f)->toggle_visible_pointer (f, invisible);
4156 unblock_input ();
4160 /* Make audible bell. */
4162 static void
4163 XTring_bell (struct frame *f)
4165 if (FRAME_X_DISPLAY (f))
4167 if (visible_bell)
4168 XTflash (f);
4169 else
4171 block_input ();
4172 #ifdef HAVE_XKB
4173 XkbBell (FRAME_X_DISPLAY (f), None, 0, None);
4174 #else
4175 XBell (FRAME_X_DISPLAY (f), 0);
4176 #endif
4177 XFlush (FRAME_X_DISPLAY (f));
4178 unblock_input ();
4183 /***********************************************************************
4184 Line Dance
4185 ***********************************************************************/
4187 /* Perform an insert-lines or delete-lines operation, inserting N
4188 lines or deleting -N lines at vertical position VPOS. */
4190 static void
4191 x_ins_del_lines (struct frame *f, int vpos, int n)
4193 emacs_abort ();
4197 /* Scroll part of the display as described by RUN. */
4199 static void
4200 x_scroll_run (struct window *w, struct run *run)
4202 struct frame *f = XFRAME (w->frame);
4203 int x, y, width, height, from_y, to_y, bottom_y;
4205 /* Get frame-relative bounding box of the text display area of W,
4206 without mode lines. Include in this box the left and right
4207 fringe of W. */
4208 window_box (w, ANY_AREA, &x, &y, &width, &height);
4210 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
4211 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
4212 bottom_y = y + height;
4214 if (to_y < from_y)
4216 /* Scrolling up. Make sure we don't copy part of the mode
4217 line at the bottom. */
4218 if (from_y + run->height > bottom_y)
4219 height = bottom_y - from_y;
4220 else
4221 height = run->height;
4223 else
4225 /* Scrolling down. Make sure we don't copy over the mode line.
4226 at the bottom. */
4227 if (to_y + run->height > bottom_y)
4228 height = bottom_y - to_y;
4229 else
4230 height = run->height;
4233 block_input ();
4235 /* Cursor off. Will be switched on again in x_update_window_end. */
4236 x_clear_cursor (w);
4238 #ifdef USE_CAIRO
4239 SET_FRAME_GARBAGED (f);
4240 #else
4241 XCopyArea (FRAME_X_DISPLAY (f),
4242 FRAME_X_DRAWABLE (f), FRAME_X_DRAWABLE (f),
4243 f->output_data.x->normal_gc,
4244 x, from_y,
4245 width, height,
4246 x, to_y);
4247 #endif
4249 unblock_input ();
4254 /***********************************************************************
4255 Exposure Events
4256 ***********************************************************************/
4259 static void
4260 frame_highlight (struct frame *f)
4262 /* We used to only do this if Vx_no_window_manager was non-nil, but
4263 the ICCCM (section 4.1.6) says that the window's border pixmap
4264 and border pixel are window attributes which are "private to the
4265 client", so we can always change it to whatever we want. */
4266 block_input ();
4267 /* I recently started to get errors in this XSetWindowBorder, depending on
4268 the window-manager in use, tho something more is at play since I've been
4269 using that same window-manager binary for ever. Let's not crash just
4270 because of this (bug#9310). */
4271 x_catch_errors (FRAME_X_DISPLAY (f));
4272 XSetWindowBorder (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4273 f->output_data.x->border_pixel);
4274 x_uncatch_errors ();
4275 unblock_input ();
4276 x_update_cursor (f, true);
4277 x_set_frame_alpha (f);
4280 static void
4281 frame_unhighlight (struct frame *f)
4283 /* We used to only do this if Vx_no_window_manager was non-nil, but
4284 the ICCCM (section 4.1.6) says that the window's border pixmap
4285 and border pixel are window attributes which are "private to the
4286 client", so we can always change it to whatever we want. */
4287 block_input ();
4288 /* Same as above for XSetWindowBorder (bug#9310). */
4289 x_catch_errors (FRAME_X_DISPLAY (f));
4290 XSetWindowBorderPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4291 f->output_data.x->border_tile);
4292 x_uncatch_errors ();
4293 unblock_input ();
4294 x_update_cursor (f, true);
4295 x_set_frame_alpha (f);
4298 /* The focus has changed. Update the frames as necessary to reflect
4299 the new situation. Note that we can't change the selected frame
4300 here, because the Lisp code we are interrupting might become confused.
4301 Each event gets marked with the frame in which it occurred, so the
4302 Lisp code can tell when the switch took place by examining the events. */
4304 static void
4305 x_new_focus_frame (struct x_display_info *dpyinfo, struct frame *frame)
4307 struct frame *old_focus = dpyinfo->x_focus_frame;
4309 if (frame != dpyinfo->x_focus_frame)
4311 /* Set this before calling other routines, so that they see
4312 the correct value of x_focus_frame. */
4313 dpyinfo->x_focus_frame = frame;
4315 if (old_focus && old_focus->auto_lower)
4316 x_lower_frame (old_focus);
4318 if (dpyinfo->x_focus_frame && dpyinfo->x_focus_frame->auto_raise)
4319 dpyinfo->x_pending_autoraise_frame = dpyinfo->x_focus_frame;
4320 else
4321 dpyinfo->x_pending_autoraise_frame = NULL;
4324 x_frame_rehighlight (dpyinfo);
4327 /* Handle FocusIn and FocusOut state changes for FRAME.
4328 If FRAME has focus and there exists more than one frame, puts
4329 a FOCUS_IN_EVENT into *BUFP. */
4331 static void
4332 x_focus_changed (int type, int state, struct x_display_info *dpyinfo, struct frame *frame, struct input_event *bufp)
4334 if (type == FocusIn)
4336 if (dpyinfo->x_focus_event_frame != frame)
4338 x_new_focus_frame (dpyinfo, frame);
4339 dpyinfo->x_focus_event_frame = frame;
4341 /* Don't stop displaying the initial startup message
4342 for a switch-frame event we don't need. */
4343 /* When run as a daemon, Vterminal_frame is always NIL. */
4344 bufp->arg = (((NILP (Vterminal_frame)
4345 || ! FRAME_X_P (XFRAME (Vterminal_frame))
4346 || EQ (Fdaemonp (), Qt))
4347 && CONSP (Vframe_list)
4348 && !NILP (XCDR (Vframe_list)))
4349 ? Qt : Qnil);
4350 bufp->kind = FOCUS_IN_EVENT;
4351 XSETFRAME (bufp->frame_or_window, frame);
4354 frame->output_data.x->focus_state |= state;
4356 #ifdef HAVE_X_I18N
4357 if (FRAME_XIC (frame))
4358 XSetICFocus (FRAME_XIC (frame));
4359 #endif
4361 else if (type == FocusOut)
4363 frame->output_data.x->focus_state &= ~state;
4365 if (dpyinfo->x_focus_event_frame == frame)
4367 dpyinfo->x_focus_event_frame = 0;
4368 x_new_focus_frame (dpyinfo, 0);
4370 bufp->kind = FOCUS_OUT_EVENT;
4371 XSETFRAME (bufp->frame_or_window, frame);
4374 #ifdef HAVE_X_I18N
4375 if (FRAME_XIC (frame))
4376 XUnsetICFocus (FRAME_XIC (frame));
4377 #endif
4378 if (frame->pointer_invisible)
4379 XTtoggle_invisible_pointer (frame, false);
4383 /* Return the Emacs frame-object corresponding to an X window.
4384 It could be the frame's main window or an icon window. */
4386 static struct frame *
4387 x_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
4389 Lisp_Object tail, frame;
4390 struct frame *f;
4392 if (wdesc == None)
4393 return NULL;
4395 FOR_EACH_FRAME (tail, frame)
4397 f = XFRAME (frame);
4398 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
4399 continue;
4400 if (f->output_data.x->hourglass_window == wdesc)
4401 return f;
4402 #ifdef USE_X_TOOLKIT
4403 if ((f->output_data.x->edit_widget
4404 && XtWindow (f->output_data.x->edit_widget) == wdesc)
4405 /* A tooltip frame? */
4406 || (!f->output_data.x->edit_widget
4407 && FRAME_X_WINDOW (f) == wdesc)
4408 || f->output_data.x->icon_desc == wdesc)
4409 return f;
4410 #else /* not USE_X_TOOLKIT */
4411 #ifdef USE_GTK
4412 if (f->output_data.x->edit_widget)
4414 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
4415 struct x_output *x = f->output_data.x;
4416 if (gwdesc != 0 && gwdesc == x->edit_widget)
4417 return f;
4419 #endif /* USE_GTK */
4420 if (FRAME_X_WINDOW (f) == wdesc
4421 || f->output_data.x->icon_desc == wdesc)
4422 return f;
4423 #endif /* not USE_X_TOOLKIT */
4425 return 0;
4428 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
4430 /* Like x_window_to_frame but also compares the window with the widget's
4431 windows. */
4433 static struct frame *
4434 x_any_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
4436 Lisp_Object tail, frame;
4437 struct frame *f, *found = NULL;
4438 struct x_output *x;
4440 if (wdesc == None)
4441 return NULL;
4443 FOR_EACH_FRAME (tail, frame)
4445 if (found)
4446 break;
4447 f = XFRAME (frame);
4448 if (FRAME_X_P (f) && FRAME_DISPLAY_INFO (f) == dpyinfo)
4450 /* This frame matches if the window is any of its widgets. */
4451 x = f->output_data.x;
4452 if (x->hourglass_window == wdesc)
4453 found = f;
4454 else if (x->widget)
4456 #ifdef USE_GTK
4457 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
4458 if (gwdesc != 0
4459 && gtk_widget_get_toplevel (gwdesc) == x->widget)
4460 found = f;
4461 #else
4462 if (wdesc == XtWindow (x->widget)
4463 || wdesc == XtWindow (x->column_widget)
4464 || wdesc == XtWindow (x->edit_widget))
4465 found = f;
4466 /* Match if the window is this frame's menubar. */
4467 else if (lw_window_is_in_menubar (wdesc, x->menubar_widget))
4468 found = f;
4469 #endif
4471 else if (FRAME_X_WINDOW (f) == wdesc)
4472 /* A tooltip frame. */
4473 found = f;
4477 return found;
4480 /* Likewise, but consider only the menu bar widget. */
4482 static struct frame *
4483 x_menubar_window_to_frame (struct x_display_info *dpyinfo,
4484 const XEvent *event)
4486 Window wdesc = event->xany.window;
4487 Lisp_Object tail, frame;
4488 struct frame *f;
4489 struct x_output *x;
4491 if (wdesc == None)
4492 return NULL;
4494 FOR_EACH_FRAME (tail, frame)
4496 f = XFRAME (frame);
4497 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
4498 continue;
4499 x = f->output_data.x;
4500 #ifdef USE_GTK
4501 if (x->menubar_widget && xg_event_is_for_menubar (f, event))
4502 return f;
4503 #else
4504 /* Match if the window is this frame's menubar. */
4505 if (x->menubar_widget
4506 && lw_window_is_in_menubar (wdesc, x->menubar_widget))
4507 return f;
4508 #endif
4510 return 0;
4513 /* Return the frame whose principal (outermost) window is WDESC.
4514 If WDESC is some other (smaller) window, we return 0. */
4516 struct frame *
4517 x_top_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
4519 Lisp_Object tail, frame;
4520 struct frame *f;
4521 struct x_output *x;
4523 if (wdesc == None)
4524 return NULL;
4526 FOR_EACH_FRAME (tail, frame)
4528 f = XFRAME (frame);
4529 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
4530 continue;
4531 x = f->output_data.x;
4533 if (x->widget)
4535 /* This frame matches if the window is its topmost widget. */
4536 #ifdef USE_GTK
4537 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
4538 if (gwdesc == x->widget)
4539 return f;
4540 #else
4541 if (wdesc == XtWindow (x->widget))
4542 return f;
4543 #endif
4545 else if (FRAME_X_WINDOW (f) == wdesc)
4546 /* Tooltip frame. */
4547 return f;
4549 return 0;
4552 #else /* !USE_X_TOOLKIT && !USE_GTK */
4554 #define x_any_window_to_frame(d, i) x_window_to_frame (d, i)
4555 #define x_top_window_to_frame(d, i) x_window_to_frame (d, i)
4557 #endif /* USE_X_TOOLKIT || USE_GTK */
4559 /* The focus may have changed. Figure out if it is a real focus change,
4560 by checking both FocusIn/Out and Enter/LeaveNotify events.
4562 Returns FOCUS_IN_EVENT event in *BUFP. */
4564 static void
4565 x_detect_focus_change (struct x_display_info *dpyinfo, struct frame *frame,
4566 const XEvent *event, struct input_event *bufp)
4568 if (!frame)
4569 return;
4571 switch (event->type)
4573 case EnterNotify:
4574 case LeaveNotify:
4576 struct frame *focus_frame = dpyinfo->x_focus_event_frame;
4577 int focus_state
4578 = focus_frame ? focus_frame->output_data.x->focus_state : 0;
4580 if (event->xcrossing.detail != NotifyInferior
4581 && event->xcrossing.focus
4582 && ! (focus_state & FOCUS_EXPLICIT))
4583 x_focus_changed ((event->type == EnterNotify ? FocusIn : FocusOut),
4584 FOCUS_IMPLICIT,
4585 dpyinfo, frame, bufp);
4587 break;
4589 case FocusIn:
4590 case FocusOut:
4591 x_focus_changed (event->type,
4592 (event->xfocus.detail == NotifyPointer ?
4593 FOCUS_IMPLICIT : FOCUS_EXPLICIT),
4594 dpyinfo, frame, bufp);
4595 break;
4597 case ClientMessage:
4598 if (event->xclient.message_type == dpyinfo->Xatom_XEMBED)
4600 enum xembed_message msg = event->xclient.data.l[1];
4601 x_focus_changed ((msg == XEMBED_FOCUS_IN ? FocusIn : FocusOut),
4602 FOCUS_EXPLICIT, dpyinfo, frame, bufp);
4604 break;
4609 #if !defined USE_X_TOOLKIT && !defined USE_GTK
4610 /* Handle an event saying the mouse has moved out of an Emacs frame. */
4612 void
4613 x_mouse_leave (struct x_display_info *dpyinfo)
4615 x_new_focus_frame (dpyinfo, dpyinfo->x_focus_event_frame);
4617 #endif
4619 /* The focus has changed, or we have redirected a frame's focus to
4620 another frame (this happens when a frame uses a surrogate
4621 mini-buffer frame). Shift the highlight as appropriate.
4623 The FRAME argument doesn't necessarily have anything to do with which
4624 frame is being highlighted or un-highlighted; we only use it to find
4625 the appropriate X display info. */
4627 static void
4628 XTframe_rehighlight (struct frame *frame)
4630 x_frame_rehighlight (FRAME_DISPLAY_INFO (frame));
4633 static void
4634 x_frame_rehighlight (struct x_display_info *dpyinfo)
4636 struct frame *old_highlight = dpyinfo->x_highlight_frame;
4638 if (dpyinfo->x_focus_frame)
4640 dpyinfo->x_highlight_frame
4641 = ((FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame)))
4642 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
4643 : dpyinfo->x_focus_frame);
4644 if (! FRAME_LIVE_P (dpyinfo->x_highlight_frame))
4646 fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
4647 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
4650 else
4651 dpyinfo->x_highlight_frame = 0;
4653 if (dpyinfo->x_highlight_frame != old_highlight)
4655 if (old_highlight)
4656 frame_unhighlight (old_highlight);
4657 if (dpyinfo->x_highlight_frame)
4658 frame_highlight (dpyinfo->x_highlight_frame);
4664 /* Keyboard processing - modifier keys, vendor-specific keysyms, etc. */
4666 /* Initialize mode_switch_bit and modifier_meaning. */
4667 static void
4668 x_find_modifier_meanings (struct x_display_info *dpyinfo)
4670 int min_code, max_code;
4671 KeySym *syms;
4672 int syms_per_code;
4673 XModifierKeymap *mods;
4675 dpyinfo->meta_mod_mask = 0;
4676 dpyinfo->shift_lock_mask = 0;
4677 dpyinfo->alt_mod_mask = 0;
4678 dpyinfo->super_mod_mask = 0;
4679 dpyinfo->hyper_mod_mask = 0;
4681 XDisplayKeycodes (dpyinfo->display, &min_code, &max_code);
4683 syms = XGetKeyboardMapping (dpyinfo->display,
4684 min_code, max_code - min_code + 1,
4685 &syms_per_code);
4686 mods = XGetModifierMapping (dpyinfo->display);
4688 /* Scan the modifier table to see which modifier bits the Meta and
4689 Alt keysyms are on. */
4691 int row, col; /* The row and column in the modifier table. */
4692 bool found_alt_or_meta;
4694 for (row = 3; row < 8; row++)
4696 found_alt_or_meta = false;
4697 for (col = 0; col < mods->max_keypermod; col++)
4699 KeyCode code = mods->modifiermap[(row * mods->max_keypermod) + col];
4701 /* Zeroes are used for filler. Skip them. */
4702 if (code == 0)
4703 continue;
4705 /* Are any of this keycode's keysyms a meta key? */
4707 int code_col;
4709 for (code_col = 0; code_col < syms_per_code; code_col++)
4711 int sym = syms[((code - min_code) * syms_per_code) + code_col];
4713 switch (sym)
4715 case XK_Meta_L:
4716 case XK_Meta_R:
4717 found_alt_or_meta = true;
4718 dpyinfo->meta_mod_mask |= (1 << row);
4719 break;
4721 case XK_Alt_L:
4722 case XK_Alt_R:
4723 found_alt_or_meta = true;
4724 dpyinfo->alt_mod_mask |= (1 << row);
4725 break;
4727 case XK_Hyper_L:
4728 case XK_Hyper_R:
4729 if (!found_alt_or_meta)
4730 dpyinfo->hyper_mod_mask |= (1 << row);
4731 code_col = syms_per_code;
4732 col = mods->max_keypermod;
4733 break;
4735 case XK_Super_L:
4736 case XK_Super_R:
4737 if (!found_alt_or_meta)
4738 dpyinfo->super_mod_mask |= (1 << row);
4739 code_col = syms_per_code;
4740 col = mods->max_keypermod;
4741 break;
4743 case XK_Shift_Lock:
4744 /* Ignore this if it's not on the lock modifier. */
4745 if (!found_alt_or_meta && ((1 << row) == LockMask))
4746 dpyinfo->shift_lock_mask = LockMask;
4747 code_col = syms_per_code;
4748 col = mods->max_keypermod;
4749 break;
4757 /* If we couldn't find any meta keys, accept any alt keys as meta keys. */
4758 if (! dpyinfo->meta_mod_mask)
4760 dpyinfo->meta_mod_mask = dpyinfo->alt_mod_mask;
4761 dpyinfo->alt_mod_mask = 0;
4764 /* If some keys are both alt and meta,
4765 make them just meta, not alt. */
4766 if (dpyinfo->alt_mod_mask & dpyinfo->meta_mod_mask)
4768 dpyinfo->alt_mod_mask &= ~dpyinfo->meta_mod_mask;
4771 XFree (syms);
4772 XFreeModifiermap (mods);
4775 /* Convert between the modifier bits X uses and the modifier bits
4776 Emacs uses. */
4779 x_x_to_emacs_modifiers (struct x_display_info *dpyinfo, int state)
4781 int mod_ctrl = ctrl_modifier;
4782 int mod_meta = meta_modifier;
4783 int mod_alt = alt_modifier;
4784 int mod_hyper = hyper_modifier;
4785 int mod_super = super_modifier;
4786 Lisp_Object tem;
4788 tem = Fget (Vx_ctrl_keysym, Qmodifier_value);
4789 if (INTEGERP (tem)) mod_ctrl = XINT (tem) & INT_MAX;
4790 tem = Fget (Vx_alt_keysym, Qmodifier_value);
4791 if (INTEGERP (tem)) mod_alt = XINT (tem) & INT_MAX;
4792 tem = Fget (Vx_meta_keysym, Qmodifier_value);
4793 if (INTEGERP (tem)) mod_meta = XINT (tem) & INT_MAX;
4794 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
4795 if (INTEGERP (tem)) mod_hyper = XINT (tem) & INT_MAX;
4796 tem = Fget (Vx_super_keysym, Qmodifier_value);
4797 if (INTEGERP (tem)) mod_super = XINT (tem) & INT_MAX;
4799 return ( ((state & (ShiftMask | dpyinfo->shift_lock_mask)) ? shift_modifier : 0)
4800 | ((state & ControlMask) ? mod_ctrl : 0)
4801 | ((state & dpyinfo->meta_mod_mask) ? mod_meta : 0)
4802 | ((state & dpyinfo->alt_mod_mask) ? mod_alt : 0)
4803 | ((state & dpyinfo->super_mod_mask) ? mod_super : 0)
4804 | ((state & dpyinfo->hyper_mod_mask) ? mod_hyper : 0));
4807 static int
4808 x_emacs_to_x_modifiers (struct x_display_info *dpyinfo, EMACS_INT state)
4810 EMACS_INT mod_ctrl = ctrl_modifier;
4811 EMACS_INT mod_meta = meta_modifier;
4812 EMACS_INT mod_alt = alt_modifier;
4813 EMACS_INT mod_hyper = hyper_modifier;
4814 EMACS_INT mod_super = super_modifier;
4816 Lisp_Object tem;
4818 tem = Fget (Vx_ctrl_keysym, Qmodifier_value);
4819 if (INTEGERP (tem)) mod_ctrl = XINT (tem);
4820 tem = Fget (Vx_alt_keysym, Qmodifier_value);
4821 if (INTEGERP (tem)) mod_alt = XINT (tem);
4822 tem = Fget (Vx_meta_keysym, Qmodifier_value);
4823 if (INTEGERP (tem)) mod_meta = XINT (tem);
4824 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
4825 if (INTEGERP (tem)) mod_hyper = XINT (tem);
4826 tem = Fget (Vx_super_keysym, Qmodifier_value);
4827 if (INTEGERP (tem)) mod_super = XINT (tem);
4830 return ( ((state & mod_alt) ? dpyinfo->alt_mod_mask : 0)
4831 | ((state & mod_super) ? dpyinfo->super_mod_mask : 0)
4832 | ((state & mod_hyper) ? dpyinfo->hyper_mod_mask : 0)
4833 | ((state & shift_modifier) ? ShiftMask : 0)
4834 | ((state & mod_ctrl) ? ControlMask : 0)
4835 | ((state & mod_meta) ? dpyinfo->meta_mod_mask : 0));
4838 /* Convert a keysym to its name. */
4840 char *
4841 x_get_keysym_name (int keysym)
4843 char *value;
4845 block_input ();
4846 value = XKeysymToString (keysym);
4847 unblock_input ();
4849 return value;
4852 /* Mouse clicks and mouse movement. Rah.
4854 Formerly, we used PointerMotionHintMask (in standard_event_mask)
4855 so that we would have to call XQueryPointer after each MotionNotify
4856 event to ask for another such event. However, this made mouse tracking
4857 slow, and there was a bug that made it eventually stop.
4859 Simply asking for MotionNotify all the time seems to work better.
4861 In order to avoid asking for motion events and then throwing most
4862 of them away or busy-polling the server for mouse positions, we ask
4863 the server for pointer motion hints. This means that we get only
4864 one event per group of mouse movements. "Groups" are delimited by
4865 other kinds of events (focus changes and button clicks, for
4866 example), or by XQueryPointer calls; when one of these happens, we
4867 get another MotionNotify event the next time the mouse moves. This
4868 is at least as efficient as getting motion events when mouse
4869 tracking is on, and I suspect only negligibly worse when tracking
4870 is off. */
4872 /* Prepare a mouse-event in *RESULT for placement in the input queue.
4874 If the event is a button press, then note that we have grabbed
4875 the mouse. */
4877 static Lisp_Object
4878 construct_mouse_click (struct input_event *result,
4879 const XButtonEvent *event,
4880 struct frame *f)
4882 /* Make the event type NO_EVENT; we'll change that when we decide
4883 otherwise. */
4884 result->kind = MOUSE_CLICK_EVENT;
4885 result->code = event->button - Button1;
4886 result->timestamp = event->time;
4887 result->modifiers = (x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO (f),
4888 event->state)
4889 | (event->type == ButtonRelease
4890 ? up_modifier
4891 : down_modifier));
4893 XSETINT (result->x, event->x);
4894 XSETINT (result->y, event->y);
4895 XSETFRAME (result->frame_or_window, f);
4896 result->arg = Qnil;
4897 return Qnil;
4900 /* Function to report a mouse movement to the mainstream Emacs code.
4901 The input handler calls this.
4903 We have received a mouse movement event, which is given in *event.
4904 If the mouse is over a different glyph than it was last time, tell
4905 the mainstream emacs code by setting mouse_moved. If not, ask for
4906 another motion event, so we can check again the next time it moves. */
4908 static bool
4909 note_mouse_movement (struct frame *frame, const XMotionEvent *event)
4911 XRectangle *r;
4912 struct x_display_info *dpyinfo;
4914 if (!FRAME_X_OUTPUT (frame))
4915 return false;
4917 dpyinfo = FRAME_DISPLAY_INFO (frame);
4918 dpyinfo->last_mouse_movement_time = event->time;
4919 dpyinfo->last_mouse_motion_frame = frame;
4920 dpyinfo->last_mouse_motion_x = event->x;
4921 dpyinfo->last_mouse_motion_y = event->y;
4923 if (event->window != FRAME_X_WINDOW (frame))
4925 frame->mouse_moved = true;
4926 dpyinfo->last_mouse_scroll_bar = NULL;
4927 note_mouse_highlight (frame, -1, -1);
4928 dpyinfo->last_mouse_glyph_frame = NULL;
4929 return true;
4933 /* Has the mouse moved off the glyph it was on at the last sighting? */
4934 r = &dpyinfo->last_mouse_glyph;
4935 if (frame != dpyinfo->last_mouse_glyph_frame
4936 || event->x < r->x || event->x >= r->x + r->width
4937 || event->y < r->y || event->y >= r->y + r->height)
4939 frame->mouse_moved = true;
4940 dpyinfo->last_mouse_scroll_bar = NULL;
4941 note_mouse_highlight (frame, event->x, event->y);
4942 /* Remember which glyph we're now on. */
4943 remember_mouse_glyph (frame, event->x, event->y, r);
4944 dpyinfo->last_mouse_glyph_frame = frame;
4945 return true;
4948 return false;
4951 /* Return the current position of the mouse.
4952 *FP should be a frame which indicates which display to ask about.
4954 If the mouse movement started in a scroll bar, set *FP, *BAR_WINDOW,
4955 and *PART to the frame, window, and scroll bar part that the mouse
4956 is over. Set *X and *Y to the portion and whole of the mouse's
4957 position on the scroll bar.
4959 If the mouse movement started elsewhere, set *FP to the frame the
4960 mouse is on, *BAR_WINDOW to nil, and *X and *Y to the character cell
4961 the mouse is over.
4963 Set *TIMESTAMP to the server time-stamp for the time at which the mouse
4964 was at this position.
4966 Don't store anything if we don't have a valid set of values to report.
4968 This clears the mouse_moved flag, so we can wait for the next mouse
4969 movement. */
4971 static void
4972 XTmouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
4973 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
4974 Time *timestamp)
4976 struct frame *f1;
4977 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (*fp);
4979 block_input ();
4981 if (dpyinfo->last_mouse_scroll_bar && insist == 0)
4983 struct scroll_bar *bar = dpyinfo->last_mouse_scroll_bar;
4985 if (bar->horizontal)
4986 x_horizontal_scroll_bar_report_motion (fp, bar_window, part, x, y, timestamp);
4987 else
4988 x_scroll_bar_report_motion (fp, bar_window, part, x, y, timestamp);
4990 else
4992 Window root;
4993 int root_x, root_y;
4995 Window dummy_window;
4996 int dummy;
4998 Lisp_Object frame, tail;
5000 /* Clear the mouse-moved flag for every frame on this display. */
5001 FOR_EACH_FRAME (tail, frame)
5002 if (FRAME_X_P (XFRAME (frame))
5003 && FRAME_X_DISPLAY (XFRAME (frame)) == FRAME_X_DISPLAY (*fp))
5004 XFRAME (frame)->mouse_moved = false;
5006 dpyinfo->last_mouse_scroll_bar = NULL;
5008 /* Figure out which root window we're on. */
5009 XQueryPointer (FRAME_X_DISPLAY (*fp),
5010 DefaultRootWindow (FRAME_X_DISPLAY (*fp)),
5012 /* The root window which contains the pointer. */
5013 &root,
5015 /* Trash which we can't trust if the pointer is on
5016 a different screen. */
5017 &dummy_window,
5019 /* The position on that root window. */
5020 &root_x, &root_y,
5022 /* More trash we can't trust. */
5023 &dummy, &dummy,
5025 /* Modifier keys and pointer buttons, about which
5026 we don't care. */
5027 (unsigned int *) &dummy);
5029 /* Now we have a position on the root; find the innermost window
5030 containing the pointer. */
5032 Window win, child;
5033 #ifdef USE_GTK
5034 Window first_win = 0;
5035 #endif
5036 int win_x, win_y;
5037 int parent_x = 0, parent_y = 0;
5039 win = root;
5041 /* XTranslateCoordinates can get errors if the window
5042 structure is changing at the same time this function
5043 is running. So at least we must not crash from them. */
5045 x_catch_errors (FRAME_X_DISPLAY (*fp));
5047 if (x_mouse_grabbed (dpyinfo))
5049 /* If mouse was grabbed on a frame, give coords for that frame
5050 even if the mouse is now outside it. */
5051 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
5053 /* From-window. */
5054 root,
5056 /* To-window. */
5057 FRAME_X_WINDOW (dpyinfo->last_mouse_frame),
5059 /* From-position, to-position. */
5060 root_x, root_y, &win_x, &win_y,
5062 /* Child of win. */
5063 &child);
5064 f1 = dpyinfo->last_mouse_frame;
5066 else
5068 while (true)
5070 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
5072 /* From-window, to-window. */
5073 root, win,
5075 /* From-position, to-position. */
5076 root_x, root_y, &win_x, &win_y,
5078 /* Child of win. */
5079 &child);
5081 if (child == None || child == win)
5083 #ifdef USE_GTK
5084 /* On GTK we have not inspected WIN yet. If it has
5085 a frame and that frame has a parent, use it. */
5086 struct frame *f = x_window_to_frame (dpyinfo, win);
5088 if (f && FRAME_PARENT_FRAME (f))
5089 first_win = win;
5090 #endif
5091 break;
5093 #ifdef USE_GTK
5094 /* We don't wan't to know the innermost window. We
5095 want the edit window. For non-Gtk+ the innermost
5096 window is the edit window. For Gtk+ it might not
5097 be. It might be the tool bar for example. */
5098 if (x_window_to_frame (dpyinfo, win))
5099 /* But don't hurry. We might find a child frame
5100 beneath. */
5101 first_win = win;
5102 #endif
5103 win = child;
5104 parent_x = win_x;
5105 parent_y = win_y;
5108 #ifdef USE_GTK
5109 if (first_win)
5110 win = first_win;
5111 #endif
5113 /* Now we know that:
5114 win is the innermost window containing the pointer
5115 (XTC says it has no child containing the pointer),
5116 win_x and win_y are the pointer's position in it
5117 (XTC did this the last time through), and
5118 parent_x and parent_y are the pointer's position in win's parent.
5119 (They are what win_x and win_y were when win was child.
5120 If win is the root window, it has no parent, and
5121 parent_{x,y} are invalid, but that's okay, because we'll
5122 never use them in that case.) */
5124 #ifdef USE_GTK
5125 /* We don't wan't to know the innermost window. We
5126 want the edit window. */
5127 f1 = x_window_to_frame (dpyinfo, win);
5128 #else
5129 /* Is win one of our frames? */
5130 f1 = x_any_window_to_frame (dpyinfo, win);
5131 #endif
5133 #ifdef USE_X_TOOLKIT
5134 /* If we end up with the menu bar window, say it's not
5135 on the frame. */
5136 if (f1 != NULL
5137 && f1->output_data.x->menubar_widget
5138 && win == XtWindow (f1->output_data.x->menubar_widget))
5139 f1 = NULL;
5140 #endif /* USE_X_TOOLKIT */
5143 if (x_had_errors_p (FRAME_X_DISPLAY (*fp)))
5144 f1 = 0;
5146 x_uncatch_errors_after_check ();
5148 /* If not, is it one of our scroll bars? */
5149 if (! f1)
5151 struct scroll_bar *bar;
5153 bar = x_window_to_scroll_bar (FRAME_X_DISPLAY (*fp), win, 2);
5155 if (bar)
5157 f1 = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5158 win_x = parent_x;
5159 win_y = parent_y;
5163 if (f1 == 0 && insist > 0)
5164 f1 = SELECTED_FRAME ();
5166 if (f1)
5168 /* Ok, we found a frame. Store all the values.
5169 last_mouse_glyph is a rectangle used to reduce the
5170 generation of mouse events. To not miss any motion
5171 events, we must divide the frame into rectangles of the
5172 size of the smallest character that could be displayed
5173 on it, i.e. into the same rectangles that matrices on
5174 the frame are divided into. */
5176 /* FIXME: what if F1 is not an X frame? */
5177 dpyinfo = FRAME_DISPLAY_INFO (f1);
5178 remember_mouse_glyph (f1, win_x, win_y, &dpyinfo->last_mouse_glyph);
5179 dpyinfo->last_mouse_glyph_frame = f1;
5181 *bar_window = Qnil;
5182 *part = 0;
5183 *fp = f1;
5184 XSETINT (*x, win_x);
5185 XSETINT (*y, win_y);
5186 *timestamp = dpyinfo->last_mouse_movement_time;
5191 unblock_input ();
5196 /***********************************************************************
5197 Scroll bars
5198 ***********************************************************************/
5200 /* Scroll bar support. */
5202 /* Given an X window ID and a DISPLAY, find the struct scroll_bar which
5203 manages it.
5204 This can be called in GC, so we have to make sure to strip off mark
5205 bits. */
5207 static struct scroll_bar *
5208 x_window_to_scroll_bar (Display *display, Window window_id, int type)
5210 Lisp_Object tail, frame;
5212 #if defined (USE_GTK) && defined (USE_TOOLKIT_SCROLL_BARS)
5213 window_id = (Window) xg_get_scroll_id_for_window (display, window_id);
5214 #endif /* USE_GTK && USE_TOOLKIT_SCROLL_BARS */
5216 FOR_EACH_FRAME (tail, frame)
5218 Lisp_Object bar, condemned;
5220 if (! FRAME_X_P (XFRAME (frame)))
5221 continue;
5223 /* Scan this frame's scroll bar list for a scroll bar with the
5224 right window ID. */
5225 condemned = FRAME_CONDEMNED_SCROLL_BARS (XFRAME (frame));
5226 for (bar = FRAME_SCROLL_BARS (XFRAME (frame));
5227 /* This trick allows us to search both the ordinary and
5228 condemned scroll bar lists with one loop. */
5229 ! NILP (bar) || (bar = condemned,
5230 condemned = Qnil,
5231 ! NILP (bar));
5232 bar = XSCROLL_BAR (bar)->next)
5233 if (XSCROLL_BAR (bar)->x_window == window_id
5234 && FRAME_X_DISPLAY (XFRAME (frame)) == display
5235 && (type = 2
5236 || (type == 1 && XSCROLL_BAR (bar)->horizontal)
5237 || (type == 0 && !XSCROLL_BAR (bar)->horizontal)))
5238 return XSCROLL_BAR (bar);
5241 return NULL;
5245 #if defined USE_LUCID
5247 /* Return the Lucid menu bar WINDOW is part of. Return null
5248 if WINDOW is not part of a menu bar. */
5250 static Widget
5251 x_window_to_menu_bar (Window window)
5253 Lisp_Object tail, frame;
5255 FOR_EACH_FRAME (tail, frame)
5256 if (FRAME_X_P (XFRAME (frame)))
5258 Widget menu_bar = XFRAME (frame)->output_data.x->menubar_widget;
5260 if (menu_bar && xlwmenu_window_p (menu_bar, window))
5261 return menu_bar;
5263 return NULL;
5266 #endif /* USE_LUCID */
5269 /************************************************************************
5270 Toolkit scroll bars
5271 ************************************************************************/
5273 #ifdef USE_TOOLKIT_SCROLL_BARS
5275 static void x_send_scroll_bar_event (Lisp_Object, enum scroll_bar_part,
5276 int, int, bool);
5278 /* Lisp window being scrolled. Set when starting to interact with
5279 a toolkit scroll bar, reset to nil when ending the interaction. */
5281 static Lisp_Object window_being_scrolled;
5283 /* Whether this is an Xaw with arrow-scrollbars. This should imply
5284 that movements of 1/20 of the screen size are mapped to up/down. */
5286 #ifndef USE_GTK
5287 /* Id of action hook installed for scroll bars. */
5289 static XtActionHookId action_hook_id;
5290 static XtActionHookId horizontal_action_hook_id;
5292 static Boolean xaw3d_arrow_scroll;
5294 /* Whether the drag scrolling maintains the mouse at the top of the
5295 thumb. If not, resizing the thumb needs to be done more carefully
5296 to avoid jerkiness. */
5298 static Boolean xaw3d_pick_top;
5300 /* Action hook installed via XtAppAddActionHook when toolkit scroll
5301 bars are used.. The hook is responsible for detecting when
5302 the user ends an interaction with the scroll bar, and generates
5303 a `end-scroll' SCROLL_BAR_CLICK_EVENT' event if so. */
5305 static void
5306 xt_action_hook (Widget widget, XtPointer client_data, String action_name,
5307 XEvent *event, String *params, Cardinal *num_params)
5309 bool scroll_bar_p;
5310 const char *end_action;
5312 #ifdef USE_MOTIF
5313 scroll_bar_p = XmIsScrollBar (widget);
5314 end_action = "Release";
5315 #else /* !USE_MOTIF i.e. use Xaw */
5316 scroll_bar_p = XtIsSubclass (widget, scrollbarWidgetClass);
5317 end_action = "EndScroll";
5318 #endif /* USE_MOTIF */
5320 if (scroll_bar_p
5321 && strcmp (action_name, end_action) == 0
5322 && WINDOWP (window_being_scrolled))
5324 struct window *w;
5325 struct scroll_bar *bar;
5327 x_send_scroll_bar_event (window_being_scrolled,
5328 scroll_bar_end_scroll, 0, 0, false);
5329 w = XWINDOW (window_being_scrolled);
5330 bar = XSCROLL_BAR (w->vertical_scroll_bar);
5332 if (bar->dragging != -1)
5334 bar->dragging = -1;
5335 /* The thumb size is incorrect while dragging: fix it. */
5336 set_vertical_scroll_bar (w);
5338 window_being_scrolled = Qnil;
5339 #if defined (USE_LUCID)
5340 bar->last_seen_part = scroll_bar_nowhere;
5341 #endif
5342 /* Xt timeouts no longer needed. */
5343 toolkit_scroll_bar_interaction = false;
5348 static void
5349 xt_horizontal_action_hook (Widget widget, XtPointer client_data, String action_name,
5350 XEvent *event, String *params, Cardinal *num_params)
5352 bool scroll_bar_p;
5353 const char *end_action;
5355 #ifdef USE_MOTIF
5356 scroll_bar_p = XmIsScrollBar (widget);
5357 end_action = "Release";
5358 #else /* !USE_MOTIF i.e. use Xaw */
5359 scroll_bar_p = XtIsSubclass (widget, scrollbarWidgetClass);
5360 end_action = "EndScroll";
5361 #endif /* USE_MOTIF */
5363 if (scroll_bar_p
5364 && strcmp (action_name, end_action) == 0
5365 && WINDOWP (window_being_scrolled))
5367 struct window *w;
5368 struct scroll_bar *bar;
5370 x_send_scroll_bar_event (window_being_scrolled,
5371 scroll_bar_end_scroll, 0, 0, true);
5372 w = XWINDOW (window_being_scrolled);
5373 if (!NILP (w->horizontal_scroll_bar))
5375 bar = XSCROLL_BAR (w->horizontal_scroll_bar);
5376 if (bar->dragging != -1)
5378 bar->dragging = -1;
5379 /* The thumb size is incorrect while dragging: fix it. */
5380 set_horizontal_scroll_bar (w);
5382 window_being_scrolled = Qnil;
5383 #if defined (USE_LUCID)
5384 bar->last_seen_part = scroll_bar_nowhere;
5385 #endif
5386 /* Xt timeouts no longer needed. */
5387 toolkit_scroll_bar_interaction = false;
5391 #endif /* not USE_GTK */
5393 /* Send a client message with message type Xatom_Scrollbar for a
5394 scroll action to the frame of WINDOW. PART is a value identifying
5395 the part of the scroll bar that was clicked on. PORTION is the
5396 amount to scroll of a whole of WHOLE. */
5398 static void
5399 x_send_scroll_bar_event (Lisp_Object window, enum scroll_bar_part part,
5400 int portion, int whole, bool horizontal)
5402 XEvent event;
5403 XClientMessageEvent *ev = &event.xclient;
5404 struct window *w = XWINDOW (window);
5405 struct frame *f = XFRAME (w->frame);
5406 intptr_t iw = (intptr_t) w;
5407 verify (INTPTR_WIDTH <= 64);
5408 int sign_shift = INTPTR_WIDTH - 32;
5410 block_input ();
5412 /* Construct a ClientMessage event to send to the frame. */
5413 ev->type = ClientMessage;
5414 ev->message_type = (horizontal
5415 ? FRAME_DISPLAY_INFO (f)->Xatom_Horizontal_Scrollbar
5416 : FRAME_DISPLAY_INFO (f)->Xatom_Scrollbar);
5417 ev->display = FRAME_X_DISPLAY (f);
5418 ev->window = FRAME_X_WINDOW (f);
5419 ev->format = 32;
5421 /* A 32-bit X client on a 64-bit X server can pass a window pointer
5422 as-is. A 64-bit client on a 32-bit X server is in trouble
5423 because a pointer does not fit and would be truncated while
5424 passing through the server. So use two slots and hope that X12
5425 will resolve such issues someday. */
5426 ev->data.l[0] = iw >> 31 >> 1;
5427 ev->data.l[1] = sign_shift <= 0 ? iw : iw << sign_shift >> sign_shift;
5428 ev->data.l[2] = part;
5429 ev->data.l[3] = portion;
5430 ev->data.l[4] = whole;
5432 /* Make Xt timeouts work while the scroll bar is active. */
5433 #ifdef USE_X_TOOLKIT
5434 toolkit_scroll_bar_interaction = true;
5435 x_activate_timeout_atimer ();
5436 #endif
5438 /* Setting the event mask to zero means that the message will
5439 be sent to the client that created the window, and if that
5440 window no longer exists, no event will be sent. */
5441 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), False, 0, &event);
5442 unblock_input ();
5446 /* Transform a scroll bar ClientMessage EVENT to an Emacs input event
5447 in *IEVENT. */
5449 static void
5450 x_scroll_bar_to_input_event (const XEvent *event,
5451 struct input_event *ievent)
5453 const XClientMessageEvent *ev = &event->xclient;
5454 Lisp_Object window;
5455 struct window *w;
5457 /* See the comment in the function above. */
5458 intptr_t iw0 = ev->data.l[0];
5459 intptr_t iw1 = ev->data.l[1];
5460 intptr_t iw = (iw0 << 31 << 1) + (iw1 & 0xffffffffu);
5461 w = (struct window *) iw;
5463 XSETWINDOW (window, w);
5465 ievent->kind = SCROLL_BAR_CLICK_EVENT;
5466 ievent->frame_or_window = window;
5467 ievent->arg = Qnil;
5468 #ifdef USE_GTK
5469 ievent->timestamp = CurrentTime;
5470 #else
5471 ievent->timestamp =
5472 XtLastTimestampProcessed (FRAME_X_DISPLAY (XFRAME (w->frame)));
5473 #endif
5474 ievent->code = 0;
5475 ievent->part = ev->data.l[2];
5476 ievent->x = make_number (ev->data.l[3]);
5477 ievent->y = make_number (ev->data.l[4]);
5478 ievent->modifiers = 0;
5481 /* Transform a horizontal scroll bar ClientMessage EVENT to an Emacs
5482 input event in *IEVENT. */
5484 static void
5485 x_horizontal_scroll_bar_to_input_event (const XEvent *event,
5486 struct input_event *ievent)
5488 const XClientMessageEvent *ev = &event->xclient;
5489 Lisp_Object window;
5490 struct window *w;
5492 /* See the comment in the function above. */
5493 intptr_t iw0 = ev->data.l[0];
5494 intptr_t iw1 = ev->data.l[1];
5495 intptr_t iw = (iw0 << 31 << 1) + (iw1 & 0xffffffffu);
5496 w = (struct window *) iw;
5498 XSETWINDOW (window, w);
5500 ievent->kind = HORIZONTAL_SCROLL_BAR_CLICK_EVENT;
5501 ievent->frame_or_window = window;
5502 ievent->arg = Qnil;
5503 #ifdef USE_GTK
5504 ievent->timestamp = CurrentTime;
5505 #else
5506 ievent->timestamp =
5507 XtLastTimestampProcessed (FRAME_X_DISPLAY (XFRAME (w->frame)));
5508 #endif
5509 ievent->code = 0;
5510 ievent->part = ev->data.l[2];
5511 ievent->x = make_number (ev->data.l[3]);
5512 ievent->y = make_number (ev->data.l[4]);
5513 ievent->modifiers = 0;
5517 #ifdef USE_MOTIF
5519 /* Minimum and maximum values used for Motif scroll bars. */
5521 #define XM_SB_MAX 10000000
5523 /* Scroll bar callback for Motif scroll bars. WIDGET is the scroll
5524 bar widget. CLIENT_DATA is a pointer to the scroll_bar structure.
5525 CALL_DATA is a pointer to a XmScrollBarCallbackStruct. */
5527 static void
5528 xm_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
5530 struct scroll_bar *bar = client_data;
5531 XmScrollBarCallbackStruct *cs = call_data;
5532 enum scroll_bar_part part = scroll_bar_nowhere;
5533 bool horizontal = bar->horizontal;
5534 int whole = 0, portion = 0;
5536 switch (cs->reason)
5538 case XmCR_DECREMENT:
5539 bar->dragging = -1;
5540 part = horizontal ? scroll_bar_left_arrow : scroll_bar_up_arrow;
5541 break;
5543 case XmCR_INCREMENT:
5544 bar->dragging = -1;
5545 part = horizontal ? scroll_bar_right_arrow : scroll_bar_down_arrow;
5546 break;
5548 case XmCR_PAGE_DECREMENT:
5549 bar->dragging = -1;
5550 part = horizontal ? scroll_bar_before_handle : scroll_bar_above_handle;
5551 break;
5553 case XmCR_PAGE_INCREMENT:
5554 bar->dragging = -1;
5555 part = horizontal ? scroll_bar_after_handle : scroll_bar_below_handle;
5556 break;
5558 case XmCR_TO_TOP:
5559 bar->dragging = -1;
5560 part = horizontal ? scroll_bar_to_leftmost : scroll_bar_to_top;
5561 break;
5563 case XmCR_TO_BOTTOM:
5564 bar->dragging = -1;
5565 part = horizontal ? scroll_bar_to_rightmost : scroll_bar_to_bottom;
5566 break;
5568 case XmCR_DRAG:
5570 int slider_size;
5572 block_input ();
5573 XtVaGetValues (widget, XmNsliderSize, &slider_size, NULL);
5574 unblock_input ();
5576 if (horizontal)
5578 portion = bar->whole * ((float)cs->value / XM_SB_MAX);
5579 whole = bar->whole * ((float)(XM_SB_MAX - slider_size) / XM_SB_MAX);
5580 portion = min (portion, whole);
5581 part = scroll_bar_horizontal_handle;
5583 else
5585 whole = XM_SB_MAX - slider_size;
5586 portion = min (cs->value, whole);
5587 part = scroll_bar_handle;
5590 bar->dragging = cs->value;
5592 break;
5594 case XmCR_VALUE_CHANGED:
5595 break;
5598 if (part != scroll_bar_nowhere)
5600 window_being_scrolled = bar->window;
5601 x_send_scroll_bar_event (bar->window, part, portion, whole,
5602 bar->horizontal);
5606 #elif defined USE_GTK
5608 /* Scroll bar callback for GTK scroll bars. WIDGET is the scroll
5609 bar widget. DATA is a pointer to the scroll_bar structure. */
5611 static gboolean
5612 xg_scroll_callback (GtkRange *range,
5613 GtkScrollType scroll,
5614 gdouble value,
5615 gpointer user_data)
5617 int whole = 0, portion = 0;
5618 struct scroll_bar *bar = user_data;
5619 enum scroll_bar_part part = scroll_bar_nowhere;
5620 GtkAdjustment *adj = GTK_ADJUSTMENT (gtk_range_get_adjustment (range));
5621 struct frame *f = g_object_get_data (G_OBJECT (range), XG_FRAME_DATA);
5623 if (xg_ignore_gtk_scrollbar) return false;
5625 switch (scroll)
5627 case GTK_SCROLL_JUMP:
5628 /* Buttons 1 2 or 3 must be grabbed. */
5629 if (FRAME_DISPLAY_INFO (f)->grabbed != 0
5630 && FRAME_DISPLAY_INFO (f)->grabbed < (1 << 4))
5632 if (bar->horizontal)
5634 part = scroll_bar_horizontal_handle;
5635 whole = (int)(gtk_adjustment_get_upper (adj) -
5636 gtk_adjustment_get_page_size (adj));
5637 portion = min ((int)value, whole);
5638 bar->dragging = portion;
5640 else
5642 part = scroll_bar_handle;
5643 whole = gtk_adjustment_get_upper (adj) -
5644 gtk_adjustment_get_page_size (adj);
5645 portion = min ((int)value, whole);
5646 bar->dragging = portion;
5649 break;
5650 case GTK_SCROLL_STEP_BACKWARD:
5651 part = (bar->horizontal
5652 ? scroll_bar_left_arrow : scroll_bar_up_arrow);
5653 bar->dragging = -1;
5654 break;
5655 case GTK_SCROLL_STEP_FORWARD:
5656 part = (bar->horizontal
5657 ? scroll_bar_right_arrow : scroll_bar_down_arrow);
5658 bar->dragging = -1;
5659 break;
5660 case GTK_SCROLL_PAGE_BACKWARD:
5661 part = (bar->horizontal
5662 ? scroll_bar_before_handle : scroll_bar_above_handle);
5663 bar->dragging = -1;
5664 break;
5665 case GTK_SCROLL_PAGE_FORWARD:
5666 part = (bar->horizontal
5667 ? scroll_bar_after_handle : scroll_bar_below_handle);
5668 bar->dragging = -1;
5669 break;
5670 default:
5671 break;
5674 if (part != scroll_bar_nowhere)
5676 window_being_scrolled = bar->window;
5677 x_send_scroll_bar_event (bar->window, part, portion, whole,
5678 bar->horizontal);
5681 return false;
5684 /* Callback for button release. Sets dragging to -1 when dragging is done. */
5686 static gboolean
5687 xg_end_scroll_callback (GtkWidget *widget,
5688 GdkEventButton *event,
5689 gpointer user_data)
5691 struct scroll_bar *bar = user_data;
5692 bar->dragging = -1;
5693 if (WINDOWP (window_being_scrolled))
5695 x_send_scroll_bar_event (window_being_scrolled,
5696 scroll_bar_end_scroll, 0, 0, bar->horizontal);
5697 window_being_scrolled = Qnil;
5700 return false;
5704 #else /* not USE_GTK and not USE_MOTIF */
5706 /* Xaw scroll bar callback. Invoked when the thumb is dragged.
5707 WIDGET is the scroll bar widget. CLIENT_DATA is a pointer to the
5708 scroll bar struct. CALL_DATA is a pointer to a float saying where
5709 the thumb is. */
5711 static void
5712 xaw_jump_callback (Widget widget, XtPointer client_data, XtPointer call_data)
5714 struct scroll_bar *bar = client_data;
5715 float *top_addr = call_data;
5716 float top = *top_addr;
5717 float shown;
5718 int whole, portion, height, width;
5719 enum scroll_bar_part part;
5720 bool horizontal = bar->horizontal;
5723 if (horizontal)
5725 /* Get the size of the thumb, a value between 0 and 1. */
5726 block_input ();
5727 XtVaGetValues (widget, XtNshown, &shown, XtNwidth, &width, NULL);
5728 unblock_input ();
5730 if (shown < 1)
5732 whole = bar->whole - (shown * bar->whole);
5733 portion = min (top * bar->whole, whole);
5735 else
5737 whole = bar->whole;
5738 portion = 0;
5741 part = scroll_bar_horizontal_handle;
5743 else
5745 /* Get the size of the thumb, a value between 0 and 1. */
5746 block_input ();
5747 XtVaGetValues (widget, XtNshown, &shown, XtNheight, &height, NULL);
5748 unblock_input ();
5750 whole = 10000000;
5751 portion = shown < 1 ? top * whole : 0;
5753 if (shown < 1 && (eabs (top + shown - 1) < 1.0f / height))
5754 /* Some derivatives of Xaw refuse to shrink the thumb when you reach
5755 the bottom, so we force the scrolling whenever we see that we're
5756 too close to the bottom (in x_set_toolkit_scroll_bar_thumb
5757 we try to ensure that we always stay two pixels away from the
5758 bottom). */
5759 part = scroll_bar_down_arrow;
5760 else
5761 part = scroll_bar_handle;
5764 window_being_scrolled = bar->window;
5765 bar->dragging = portion;
5766 bar->last_seen_part = part;
5767 x_send_scroll_bar_event (bar->window, part, portion, whole, bar->horizontal);
5771 /* Xaw scroll bar callback. Invoked for incremental scrolling.,
5772 i.e. line or page up or down. WIDGET is the Xaw scroll bar
5773 widget. CLIENT_DATA is a pointer to the scroll_bar structure for
5774 the scroll bar. CALL_DATA is an integer specifying the action that
5775 has taken place. Its magnitude is in the range 0..height of the
5776 scroll bar. Negative values mean scroll towards buffer start.
5777 Values < height of scroll bar mean line-wise movement. */
5779 static void
5780 xaw_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
5782 struct scroll_bar *bar = client_data;
5783 /* The position really is stored cast to a pointer. */
5784 int position = (intptr_t) call_data;
5785 Dimension height, width;
5786 enum scroll_bar_part part;
5788 if (bar->horizontal)
5790 /* Get the width of the scroll bar. */
5791 block_input ();
5792 XtVaGetValues (widget, XtNwidth, &width, NULL);
5793 unblock_input ();
5795 if (eabs (position) >= width)
5796 part = (position < 0) ? scroll_bar_before_handle : scroll_bar_after_handle;
5798 /* If Xaw3d was compiled with ARROW_SCROLLBAR,
5799 it maps line-movement to call_data = max(5, height/20). */
5800 else if (xaw3d_arrow_scroll && eabs (position) <= max (5, width / 20))
5801 part = (position < 0) ? scroll_bar_left_arrow : scroll_bar_right_arrow;
5802 else
5803 part = scroll_bar_move_ratio;
5805 window_being_scrolled = bar->window;
5806 bar->dragging = -1;
5807 bar->last_seen_part = part;
5808 x_send_scroll_bar_event (bar->window, part, position, width,
5809 bar->horizontal);
5811 else
5814 /* Get the height of the scroll bar. */
5815 block_input ();
5816 XtVaGetValues (widget, XtNheight, &height, NULL);
5817 unblock_input ();
5819 if (eabs (position) >= height)
5820 part = (position < 0) ? scroll_bar_above_handle : scroll_bar_below_handle;
5822 /* If Xaw3d was compiled with ARROW_SCROLLBAR,
5823 it maps line-movement to call_data = max(5, height/20). */
5824 else if (xaw3d_arrow_scroll && eabs (position) <= max (5, height / 20))
5825 part = (position < 0) ? scroll_bar_up_arrow : scroll_bar_down_arrow;
5826 else
5827 part = scroll_bar_move_ratio;
5829 window_being_scrolled = bar->window;
5830 bar->dragging = -1;
5831 bar->last_seen_part = part;
5832 x_send_scroll_bar_event (bar->window, part, position, height,
5833 bar->horizontal);
5837 #endif /* not USE_GTK and not USE_MOTIF */
5839 #define SCROLL_BAR_NAME "verticalScrollBar"
5840 #define SCROLL_BAR_HORIZONTAL_NAME "horizontalScrollBar"
5842 /* Create the widget for scroll bar BAR on frame F. Record the widget
5843 and X window of the scroll bar in BAR. */
5845 #ifdef USE_GTK
5846 static void
5847 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
5849 const char *scroll_bar_name = SCROLL_BAR_NAME;
5851 block_input ();
5852 xg_create_scroll_bar (f, bar, G_CALLBACK (xg_scroll_callback),
5853 G_CALLBACK (xg_end_scroll_callback),
5854 scroll_bar_name);
5855 unblock_input ();
5858 static void
5859 x_create_horizontal_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
5861 const char *scroll_bar_name = SCROLL_BAR_HORIZONTAL_NAME;
5863 block_input ();
5864 xg_create_horizontal_scroll_bar (f, bar, G_CALLBACK (xg_scroll_callback),
5865 G_CALLBACK (xg_end_scroll_callback),
5866 scroll_bar_name);
5867 unblock_input ();
5870 #else /* not USE_GTK */
5872 static void
5873 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
5875 Window xwindow;
5876 Widget widget;
5877 Arg av[20];
5878 int ac = 0;
5879 const char *scroll_bar_name = SCROLL_BAR_NAME;
5880 unsigned long pixel;
5882 block_input ();
5884 #ifdef USE_MOTIF
5885 /* Set resources. Create the widget. */
5886 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
5887 XtSetArg (av[ac], XmNminimum, 0); ++ac;
5888 XtSetArg (av[ac], XmNmaximum, XM_SB_MAX); ++ac;
5889 XtSetArg (av[ac], XmNorientation, XmVERTICAL); ++ac;
5890 XtSetArg (av[ac], XmNprocessingDirection, XmMAX_ON_BOTTOM), ++ac;
5891 XtSetArg (av[ac], XmNincrement, 1); ++ac;
5892 XtSetArg (av[ac], XmNpageIncrement, 1); ++ac;
5894 pixel = f->output_data.x->scroll_bar_foreground_pixel;
5895 if (pixel != -1)
5897 XtSetArg (av[ac], XmNforeground, pixel);
5898 ++ac;
5901 pixel = f->output_data.x->scroll_bar_background_pixel;
5902 if (pixel != -1)
5904 XtSetArg (av[ac], XmNbackground, pixel);
5905 ++ac;
5908 widget = XmCreateScrollBar (f->output_data.x->edit_widget,
5909 (char *) scroll_bar_name, av, ac);
5911 /* Add one callback for everything that can happen. */
5912 XtAddCallback (widget, XmNdecrementCallback, xm_scroll_callback,
5913 (XtPointer) bar);
5914 XtAddCallback (widget, XmNdragCallback, xm_scroll_callback,
5915 (XtPointer) bar);
5916 XtAddCallback (widget, XmNincrementCallback, xm_scroll_callback,
5917 (XtPointer) bar);
5918 XtAddCallback (widget, XmNpageDecrementCallback, xm_scroll_callback,
5919 (XtPointer) bar);
5920 XtAddCallback (widget, XmNpageIncrementCallback, xm_scroll_callback,
5921 (XtPointer) bar);
5922 XtAddCallback (widget, XmNtoBottomCallback, xm_scroll_callback,
5923 (XtPointer) bar);
5924 XtAddCallback (widget, XmNtoTopCallback, xm_scroll_callback,
5925 (XtPointer) bar);
5927 /* Realize the widget. Only after that is the X window created. */
5928 XtRealizeWidget (widget);
5930 /* Set the cursor to an arrow. I didn't find a resource to do that.
5931 And I'm wondering why it hasn't an arrow cursor by default. */
5932 XDefineCursor (XtDisplay (widget), XtWindow (widget),
5933 f->output_data.x->nontext_cursor);
5935 #else /* !USE_MOTIF i.e. use Xaw */
5937 /* Set resources. Create the widget. The background of the
5938 Xaw3d scroll bar widget is a little bit light for my taste.
5939 We don't alter it here to let users change it according
5940 to their taste with `emacs*verticalScrollBar.background: xxx'. */
5941 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
5942 XtSetArg (av[ac], XtNorientation, XtorientVertical); ++ac;
5943 /* For smoother scrolling with Xaw3d -sm */
5944 /* XtSetArg (av[ac], XtNpickTop, True); ++ac; */
5946 pixel = f->output_data.x->scroll_bar_foreground_pixel;
5947 if (pixel != -1)
5949 XtSetArg (av[ac], XtNforeground, pixel);
5950 ++ac;
5953 pixel = f->output_data.x->scroll_bar_background_pixel;
5954 if (pixel != -1)
5956 XtSetArg (av[ac], XtNbackground, pixel);
5957 ++ac;
5960 /* Top/bottom shadow colors. */
5962 /* Allocate them, if necessary. */
5963 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1)
5965 pixel = f->output_data.x->scroll_bar_background_pixel;
5966 if (pixel != -1)
5968 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
5969 FRAME_X_COLORMAP (f),
5970 &pixel, 1.2, 0x8000))
5971 pixel = -1;
5972 f->output_data.x->scroll_bar_top_shadow_pixel = pixel;
5975 if (f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
5977 pixel = f->output_data.x->scroll_bar_background_pixel;
5978 if (pixel != -1)
5980 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
5981 FRAME_X_COLORMAP (f),
5982 &pixel, 0.6, 0x4000))
5983 pixel = -1;
5984 f->output_data.x->scroll_bar_bottom_shadow_pixel = pixel;
5988 #ifdef XtNbeNiceToColormap
5989 /* Tell the toolkit about them. */
5990 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1
5991 || f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
5992 /* We tried to allocate a color for the top/bottom shadow, and
5993 failed, so tell Xaw3d to use dithering instead. */
5994 /* But only if we have a small colormap. Xaw3d can allocate nice
5995 colors itself. */
5997 XtSetArg (av[ac], XtNbeNiceToColormap,
5998 DefaultDepthOfScreen (FRAME_X_SCREEN (f)) < 16);
5999 ++ac;
6001 else
6002 /* Tell what colors Xaw3d should use for the top/bottom shadow, to
6003 be more consistent with other emacs 3d colors, and since Xaw3d is
6004 not good at dealing with allocation failure. */
6006 /* This tells Xaw3d to use real colors instead of dithering for
6007 the shadows. */
6008 XtSetArg (av[ac], XtNbeNiceToColormap, False);
6009 ++ac;
6011 /* Specify the colors. */
6012 pixel = f->output_data.x->scroll_bar_top_shadow_pixel;
6013 if (pixel != -1)
6015 XtSetArg (av[ac], XtNtopShadowPixel, pixel);
6016 ++ac;
6018 pixel = f->output_data.x->scroll_bar_bottom_shadow_pixel;
6019 if (pixel != -1)
6021 XtSetArg (av[ac], XtNbottomShadowPixel, pixel);
6022 ++ac;
6025 #endif
6027 widget = XtCreateWidget (scroll_bar_name, scrollbarWidgetClass,
6028 f->output_data.x->edit_widget, av, ac);
6031 char const *initial = "";
6032 char const *val = initial;
6033 XtVaGetValues (widget, XtNscrollVCursor, (XtPointer) &val,
6034 #ifdef XtNarrowScrollbars
6035 XtNarrowScrollbars, (XtPointer) &xaw3d_arrow_scroll,
6036 #endif
6037 XtNpickTop, (XtPointer) &xaw3d_pick_top, NULL);
6038 if (xaw3d_arrow_scroll || val == initial)
6039 { /* ARROW_SCROLL */
6040 xaw3d_arrow_scroll = True;
6041 /* Isn't that just a personal preference ? --Stef */
6042 XtVaSetValues (widget, XtNcursorName, "top_left_arrow", NULL);
6046 /* Define callbacks. */
6047 XtAddCallback (widget, XtNjumpProc, xaw_jump_callback, (XtPointer) bar);
6048 XtAddCallback (widget, XtNscrollProc, xaw_scroll_callback,
6049 (XtPointer) bar);
6051 /* Realize the widget. Only after that is the X window created. */
6052 XtRealizeWidget (widget);
6054 #endif /* !USE_MOTIF */
6056 /* Install an action hook that lets us detect when the user
6057 finishes interacting with a scroll bar. */
6058 if (action_hook_id == 0)
6059 action_hook_id = XtAppAddActionHook (Xt_app_con, xt_action_hook, 0);
6061 /* Remember X window and widget in the scroll bar vector. */
6062 SET_SCROLL_BAR_X_WIDGET (bar, widget);
6063 xwindow = XtWindow (widget);
6064 bar->x_window = xwindow;
6065 bar->whole = 1;
6066 bar->horizontal = false;
6068 unblock_input ();
6071 static void
6072 x_create_horizontal_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
6074 Window xwindow;
6075 Widget widget;
6076 Arg av[20];
6077 int ac = 0;
6078 const char *scroll_bar_name = SCROLL_BAR_HORIZONTAL_NAME;
6079 unsigned long pixel;
6081 block_input ();
6083 #ifdef USE_MOTIF
6084 /* Set resources. Create the widget. */
6085 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
6086 XtSetArg (av[ac], XmNminimum, 0); ++ac;
6087 XtSetArg (av[ac], XmNmaximum, XM_SB_MAX); ++ac;
6088 XtSetArg (av[ac], XmNorientation, XmHORIZONTAL); ++ac;
6089 XtSetArg (av[ac], XmNprocessingDirection, XmMAX_ON_RIGHT), ++ac;
6090 XtSetArg (av[ac], XmNincrement, 1); ++ac;
6091 XtSetArg (av[ac], XmNpageIncrement, 1); ++ac;
6093 pixel = f->output_data.x->scroll_bar_foreground_pixel;
6094 if (pixel != -1)
6096 XtSetArg (av[ac], XmNforeground, pixel);
6097 ++ac;
6100 pixel = f->output_data.x->scroll_bar_background_pixel;
6101 if (pixel != -1)
6103 XtSetArg (av[ac], XmNbackground, pixel);
6104 ++ac;
6107 widget = XmCreateScrollBar (f->output_data.x->edit_widget,
6108 (char *) scroll_bar_name, av, ac);
6110 /* Add one callback for everything that can happen. */
6111 XtAddCallback (widget, XmNdecrementCallback, xm_scroll_callback,
6112 (XtPointer) bar);
6113 XtAddCallback (widget, XmNdragCallback, xm_scroll_callback,
6114 (XtPointer) bar);
6115 XtAddCallback (widget, XmNincrementCallback, xm_scroll_callback,
6116 (XtPointer) bar);
6117 XtAddCallback (widget, XmNpageDecrementCallback, xm_scroll_callback,
6118 (XtPointer) bar);
6119 XtAddCallback (widget, XmNpageIncrementCallback, xm_scroll_callback,
6120 (XtPointer) bar);
6121 XtAddCallback (widget, XmNtoBottomCallback, xm_scroll_callback,
6122 (XtPointer) bar);
6123 XtAddCallback (widget, XmNtoTopCallback, xm_scroll_callback,
6124 (XtPointer) bar);
6126 /* Realize the widget. Only after that is the X window created. */
6127 XtRealizeWidget (widget);
6129 /* Set the cursor to an arrow. I didn't find a resource to do that.
6130 And I'm wondering why it hasn't an arrow cursor by default. */
6131 XDefineCursor (XtDisplay (widget), XtWindow (widget),
6132 f->output_data.x->nontext_cursor);
6134 #else /* !USE_MOTIF i.e. use Xaw */
6136 /* Set resources. Create the widget. The background of the
6137 Xaw3d scroll bar widget is a little bit light for my taste.
6138 We don't alter it here to let users change it according
6139 to their taste with `emacs*verticalScrollBar.background: xxx'. */
6140 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
6141 XtSetArg (av[ac], XtNorientation, XtorientHorizontal); ++ac;
6142 /* For smoother scrolling with Xaw3d -sm */
6143 /* XtSetArg (av[ac], XtNpickTop, True); ++ac; */
6145 pixel = f->output_data.x->scroll_bar_foreground_pixel;
6146 if (pixel != -1)
6148 XtSetArg (av[ac], XtNforeground, pixel);
6149 ++ac;
6152 pixel = f->output_data.x->scroll_bar_background_pixel;
6153 if (pixel != -1)
6155 XtSetArg (av[ac], XtNbackground, pixel);
6156 ++ac;
6159 /* Top/bottom shadow colors. */
6161 /* Allocate them, if necessary. */
6162 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1)
6164 pixel = f->output_data.x->scroll_bar_background_pixel;
6165 if (pixel != -1)
6167 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
6168 FRAME_X_COLORMAP (f),
6169 &pixel, 1.2, 0x8000))
6170 pixel = -1;
6171 f->output_data.x->scroll_bar_top_shadow_pixel = pixel;
6174 if (f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
6176 pixel = f->output_data.x->scroll_bar_background_pixel;
6177 if (pixel != -1)
6179 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
6180 FRAME_X_COLORMAP (f),
6181 &pixel, 0.6, 0x4000))
6182 pixel = -1;
6183 f->output_data.x->scroll_bar_bottom_shadow_pixel = pixel;
6187 #ifdef XtNbeNiceToColormap
6188 /* Tell the toolkit about them. */
6189 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1
6190 || f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
6191 /* We tried to allocate a color for the top/bottom shadow, and
6192 failed, so tell Xaw3d to use dithering instead. */
6193 /* But only if we have a small colormap. Xaw3d can allocate nice
6194 colors itself. */
6196 XtSetArg (av[ac], XtNbeNiceToColormap,
6197 DefaultDepthOfScreen (FRAME_X_SCREEN (f)) < 16);
6198 ++ac;
6200 else
6201 /* Tell what colors Xaw3d should use for the top/bottom shadow, to
6202 be more consistent with other emacs 3d colors, and since Xaw3d is
6203 not good at dealing with allocation failure. */
6205 /* This tells Xaw3d to use real colors instead of dithering for
6206 the shadows. */
6207 XtSetArg (av[ac], XtNbeNiceToColormap, False);
6208 ++ac;
6210 /* Specify the colors. */
6211 pixel = f->output_data.x->scroll_bar_top_shadow_pixel;
6212 if (pixel != -1)
6214 XtSetArg (av[ac], XtNtopShadowPixel, pixel);
6215 ++ac;
6217 pixel = f->output_data.x->scroll_bar_bottom_shadow_pixel;
6218 if (pixel != -1)
6220 XtSetArg (av[ac], XtNbottomShadowPixel, pixel);
6221 ++ac;
6224 #endif
6226 widget = XtCreateWidget (scroll_bar_name, scrollbarWidgetClass,
6227 f->output_data.x->edit_widget, av, ac);
6230 char const *initial = "";
6231 char const *val = initial;
6232 XtVaGetValues (widget, XtNscrollVCursor, (XtPointer) &val,
6233 #ifdef XtNarrowScrollbars
6234 XtNarrowScrollbars, (XtPointer) &xaw3d_arrow_scroll,
6235 #endif
6236 XtNpickTop, (XtPointer) &xaw3d_pick_top, NULL);
6237 if (xaw3d_arrow_scroll || val == initial)
6238 { /* ARROW_SCROLL */
6239 xaw3d_arrow_scroll = True;
6240 /* Isn't that just a personal preference ? --Stef */
6241 XtVaSetValues (widget, XtNcursorName, "top_left_arrow", NULL);
6245 /* Define callbacks. */
6246 XtAddCallback (widget, XtNjumpProc, xaw_jump_callback, (XtPointer) bar);
6247 XtAddCallback (widget, XtNscrollProc, xaw_scroll_callback,
6248 (XtPointer) bar);
6250 /* Realize the widget. Only after that is the X window created. */
6251 XtRealizeWidget (widget);
6253 #endif /* !USE_MOTIF */
6255 /* Install an action hook that lets us detect when the user
6256 finishes interacting with a scroll bar. */
6257 if (horizontal_action_hook_id == 0)
6258 horizontal_action_hook_id
6259 = XtAppAddActionHook (Xt_app_con, xt_horizontal_action_hook, 0);
6261 /* Remember X window and widget in the scroll bar vector. */
6262 SET_SCROLL_BAR_X_WIDGET (bar, widget);
6263 xwindow = XtWindow (widget);
6264 bar->x_window = xwindow;
6265 bar->whole = 1;
6266 bar->horizontal = true;
6268 unblock_input ();
6270 #endif /* not USE_GTK */
6273 /* Set the thumb size and position of scroll bar BAR. We are currently
6274 displaying PORTION out of a whole WHOLE, and our position POSITION. */
6276 #ifdef USE_GTK
6277 static void
6278 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position, int whole)
6280 xg_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
6283 static void
6284 x_set_toolkit_horizontal_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position, int whole)
6286 xg_set_toolkit_horizontal_scroll_bar_thumb (bar, portion, position, whole);
6289 #else /* not USE_GTK */
6290 static void
6291 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position,
6292 int whole)
6294 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6295 Widget widget = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
6296 float top, shown;
6298 block_input ();
6300 #ifdef USE_MOTIF
6302 if (scroll_bar_adjust_thumb_portion_p)
6304 /* We use an estimate of 30 chars per line rather than the real
6305 `portion' value. This has the disadvantage that the thumb size
6306 is not very representative, but it makes our life a lot easier.
6307 Otherwise, we have to constantly adjust the thumb size, which
6308 we can't always do quickly enough: while dragging, the size of
6309 the thumb might prevent the user from dragging the thumb all the
6310 way to the end. but Motif and some versions of Xaw3d don't allow
6311 updating the thumb size while dragging. Also, even if we can update
6312 its size, the update will often happen too late.
6313 If you don't believe it, check out revision 1.650 of xterm.c to see
6314 what hoops we were going through and the still poor behavior we got. */
6315 portion = WINDOW_TOTAL_LINES (XWINDOW (bar->window)) * 30;
6316 /* When the thumb is at the bottom, position == whole.
6317 So we need to increase `whole' to make space for the thumb. */
6318 whole += portion;
6321 if (whole <= 0)
6322 top = 0, shown = 1;
6323 else
6325 top = (float) position / whole;
6326 shown = (float) portion / whole;
6329 if (bar->dragging == -1)
6331 int size, value;
6333 /* Slider size. Must be in the range [1 .. MAX - MIN] where MAX
6334 is the scroll bar's maximum and MIN is the scroll bar's minimum
6335 value. */
6336 size = clip_to_bounds (1, shown * XM_SB_MAX, XM_SB_MAX);
6338 /* Position. Must be in the range [MIN .. MAX - SLIDER_SIZE]. */
6339 value = top * XM_SB_MAX;
6340 value = min (value, XM_SB_MAX - size);
6342 XmScrollBarSetValues (widget, value, size, 0, 0, False);
6344 #else /* !USE_MOTIF i.e. use Xaw */
6346 if (whole == 0)
6347 top = 0, shown = 1;
6348 else
6350 top = (float) position / whole;
6351 shown = (float) portion / whole;
6355 float old_top, old_shown;
6356 Dimension height;
6357 XtVaGetValues (widget,
6358 XtNtopOfThumb, &old_top,
6359 XtNshown, &old_shown,
6360 XtNheight, &height,
6361 NULL);
6363 /* Massage the top+shown values. */
6364 if (bar->dragging == -1 || bar->last_seen_part == scroll_bar_down_arrow)
6365 top = max (0, min (1, top));
6366 else
6367 top = old_top;
6368 #if ! defined (HAVE_XAW3D)
6369 /* With Xaw, 'top' values too closer to 1.0 may
6370 cause the thumb to disappear. Fix that. */
6371 top = min (top, 0.99f);
6372 #endif
6373 /* Keep two pixels available for moving the thumb down. */
6374 shown = max (0, min (1 - top - (2.0f / height), shown));
6375 #if ! defined (HAVE_XAW3D)
6376 /* Likewise with too small 'shown'. */
6377 shown = max (shown, 0.01f);
6378 #endif
6380 /* If the call to XawScrollbarSetThumb below doesn't seem to
6381 work, check that 'NARROWPROTO' is defined in src/config.h.
6382 If this is not so, most likely you need to fix configure. */
6383 if (top != old_top || shown != old_shown)
6385 if (bar->dragging == -1)
6386 XawScrollbarSetThumb (widget, top, shown);
6387 else
6389 /* Try to make the scrolling a tad smoother. */
6390 if (!xaw3d_pick_top)
6391 shown = min (shown, old_shown);
6393 XawScrollbarSetThumb (widget, top, shown);
6397 #endif /* !USE_MOTIF */
6399 unblock_input ();
6402 static void
6403 x_set_toolkit_horizontal_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position,
6404 int whole)
6406 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6407 Widget widget = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
6408 float top, shown;
6410 block_input ();
6412 #ifdef USE_MOTIF
6413 bar->whole = whole;
6414 shown = (float) portion / whole;
6415 top = (float) position / (whole - portion);
6417 int size = clip_to_bounds (1, shown * XM_SB_MAX, XM_SB_MAX);
6418 int value = clip_to_bounds (0, top * (XM_SB_MAX - size), XM_SB_MAX - size);
6420 XmScrollBarSetValues (widget, value, size, 0, 0, False);
6422 #else /* !USE_MOTIF i.e. use Xaw */
6423 bar->whole = whole;
6424 if (whole == 0)
6425 top = 0, shown = 1;
6426 else
6428 top = (float) position / whole;
6429 shown = (float) portion / whole;
6433 float old_top, old_shown;
6434 Dimension height;
6435 XtVaGetValues (widget,
6436 XtNtopOfThumb, &old_top,
6437 XtNshown, &old_shown,
6438 XtNheight, &height,
6439 NULL);
6441 #if false
6442 /* Massage the top+shown values. */
6443 if (bar->dragging == -1 || bar->last_seen_part == scroll_bar_down_arrow)
6444 top = max (0, min (1, top));
6445 else
6446 top = old_top;
6447 #if ! defined (HAVE_XAW3D)
6448 /* With Xaw, 'top' values too closer to 1.0 may
6449 cause the thumb to disappear. Fix that. */
6450 top = min (top, 0.99f);
6451 #endif
6452 /* Keep two pixels available for moving the thumb down. */
6453 shown = max (0, min (1 - top - (2.0f / height), shown));
6454 #if ! defined (HAVE_XAW3D)
6455 /* Likewise with too small 'shown'. */
6456 shown = max (shown, 0.01f);
6457 #endif
6458 #endif
6460 /* If the call to XawScrollbarSetThumb below doesn't seem to
6461 work, check that 'NARROWPROTO' is defined in src/config.h.
6462 If this is not so, most likely you need to fix configure. */
6463 XawScrollbarSetThumb (widget, top, shown);
6464 #if false
6465 if (top != old_top || shown != old_shown)
6467 if (bar->dragging == -1)
6468 XawScrollbarSetThumb (widget, top, shown);
6469 else
6471 /* Try to make the scrolling a tad smoother. */
6472 if (!xaw3d_pick_top)
6473 shown = min (shown, old_shown);
6475 XawScrollbarSetThumb (widget, top, shown);
6478 #endif
6480 #endif /* !USE_MOTIF */
6482 unblock_input ();
6484 #endif /* not USE_GTK */
6486 #endif /* USE_TOOLKIT_SCROLL_BARS */
6490 /************************************************************************
6491 Scroll bars, general
6492 ************************************************************************/
6494 /* Create a scroll bar and return the scroll bar vector for it. W is
6495 the Emacs window on which to create the scroll bar. TOP, LEFT,
6496 WIDTH and HEIGHT are the pixel coordinates and dimensions of the
6497 scroll bar. */
6499 static struct scroll_bar *
6500 x_scroll_bar_create (struct window *w, int top, int left,
6501 int width, int height, bool horizontal)
6503 struct frame *f = XFRAME (w->frame);
6504 struct scroll_bar *bar
6505 = ALLOCATE_PSEUDOVECTOR (struct scroll_bar, x_window, PVEC_OTHER);
6506 Lisp_Object barobj;
6508 block_input ();
6510 #ifdef USE_TOOLKIT_SCROLL_BARS
6511 if (horizontal)
6512 x_create_horizontal_toolkit_scroll_bar (f, bar);
6513 else
6514 x_create_toolkit_scroll_bar (f, bar);
6515 #else /* not USE_TOOLKIT_SCROLL_BARS */
6517 XSetWindowAttributes a;
6518 unsigned long mask;
6519 Window window;
6521 a.background_pixel = f->output_data.x->scroll_bar_background_pixel;
6522 if (a.background_pixel == -1)
6523 a.background_pixel = FRAME_BACKGROUND_PIXEL (f);
6525 a.event_mask = (ButtonPressMask | ButtonReleaseMask
6526 | ButtonMotionMask | PointerMotionHintMask
6527 | ExposureMask);
6528 a.cursor = FRAME_DISPLAY_INFO (f)->vertical_scroll_bar_cursor;
6530 mask = (CWBackPixel | CWEventMask | CWCursor);
6532 /* Clear the area of W that will serve as a scroll bar. This is
6533 for the case that a window has been split horizontally. In
6534 this case, no clear_frame is generated to reduce flickering. */
6535 if (width > 0 && window_box_height (w) > 0)
6536 x_clear_area (f, left, top, width, window_box_height (w));
6538 window = XCreateWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
6539 /* Position and size of scroll bar. */
6540 left, top, width, height,
6541 /* Border width, depth, class, and visual. */
6543 CopyFromParent,
6544 CopyFromParent,
6545 CopyFromParent,
6546 /* Attributes. */
6547 mask, &a);
6548 bar->x_window = window;
6550 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6552 XSETWINDOW (bar->window, w);
6553 bar->top = top;
6554 bar->left = left;
6555 bar->width = width;
6556 bar->height = height;
6557 bar->start = 0;
6558 bar->end = 0;
6559 bar->dragging = -1;
6560 bar->horizontal = horizontal;
6561 #if defined (USE_TOOLKIT_SCROLL_BARS) && defined (USE_LUCID)
6562 bar->last_seen_part = scroll_bar_nowhere;
6563 #endif
6565 /* Add bar to its frame's list of scroll bars. */
6566 bar->next = FRAME_SCROLL_BARS (f);
6567 bar->prev = Qnil;
6568 XSETVECTOR (barobj, bar);
6569 fset_scroll_bars (f, barobj);
6570 if (!NILP (bar->next))
6571 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
6573 /* Map the window/widget. */
6574 #ifdef USE_TOOLKIT_SCROLL_BARS
6576 #ifdef USE_GTK
6577 if (horizontal)
6578 xg_update_horizontal_scrollbar_pos (f, bar->x_window, top,
6579 left, width, max (height, 1));
6580 else
6581 xg_update_scrollbar_pos (f, bar->x_window, top,
6582 left, width, max (height, 1));
6583 #else /* not USE_GTK */
6584 Widget scroll_bar = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
6585 XtConfigureWidget (scroll_bar, left, top, width, max (height, 1), 0);
6586 XtMapWidget (scroll_bar);
6587 /* Don't obscure any child frames. */
6588 XLowerWindow (FRAME_X_DISPLAY (f), bar->x_window);
6589 #endif /* not USE_GTK */
6591 #else /* not USE_TOOLKIT_SCROLL_BARS */
6592 XMapWindow (FRAME_X_DISPLAY (f), bar->x_window);
6593 /* Don't obscure any child frames. */
6594 XLowerWindow (FRAME_X_DISPLAY (f), bar->x_window);
6595 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6597 unblock_input ();
6598 return bar;
6602 #ifndef USE_TOOLKIT_SCROLL_BARS
6604 /* Draw BAR's handle in the proper position.
6606 If the handle is already drawn from START to END, don't bother
6607 redrawing it, unless REBUILD; in that case, always
6608 redraw it. (REBUILD is handy for drawing the handle after expose
6609 events.)
6611 Normally, we want to constrain the start and end of the handle to
6612 fit inside its rectangle, but if the user is dragging the scroll
6613 bar handle, we want to let them drag it down all the way, so that
6614 the bar's top is as far down as it goes; otherwise, there's no way
6615 to move to the very end of the buffer. */
6617 static void
6618 x_scroll_bar_set_handle (struct scroll_bar *bar, int start, int end,
6619 bool rebuild)
6621 bool dragging = bar->dragging != -1;
6622 Window w = bar->x_window;
6623 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6624 GC gc = f->output_data.x->normal_gc;
6626 /* If the display is already accurate, do nothing. */
6627 if (! rebuild
6628 && start == bar->start
6629 && end == bar->end)
6630 return;
6632 block_input ();
6635 int inside_width = VERTICAL_SCROLL_BAR_INSIDE_WIDTH (f, bar->width);
6636 int inside_height = VERTICAL_SCROLL_BAR_INSIDE_HEIGHT (f, bar->height);
6637 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
6639 /* Make sure the values are reasonable, and try to preserve
6640 the distance between start and end. */
6642 int length = end - start;
6644 if (start < 0)
6645 start = 0;
6646 else if (start > top_range)
6647 start = top_range;
6648 end = start + length;
6650 if (end < start)
6651 end = start;
6652 else if (end > top_range && ! dragging)
6653 end = top_range;
6656 /* Store the adjusted setting in the scroll bar. */
6657 bar->start = start;
6658 bar->end = end;
6660 /* Clip the end position, just for display. */
6661 if (end > top_range)
6662 end = top_range;
6664 /* Draw bottom positions VERTICAL_SCROLL_BAR_MIN_HANDLE pixels
6665 below top positions, to make sure the handle is always at least
6666 that many pixels tall. */
6667 end += VERTICAL_SCROLL_BAR_MIN_HANDLE;
6669 /* Draw the empty space above the handle. Note that we can't clear
6670 zero-height areas; that means "clear to end of window." */
6671 if ((inside_width > 0) && (start > 0))
6672 x_clear_area1 (FRAME_X_DISPLAY (f), w,
6673 VERTICAL_SCROLL_BAR_LEFT_BORDER,
6674 VERTICAL_SCROLL_BAR_TOP_BORDER,
6675 inside_width, start, False);
6677 /* Change to proper foreground color if one is specified. */
6678 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
6679 XSetForeground (FRAME_X_DISPLAY (f), gc,
6680 f->output_data.x->scroll_bar_foreground_pixel);
6682 /* Draw the handle itself. */
6683 XFillRectangle (FRAME_X_DISPLAY (f), w, gc,
6684 /* x, y, width, height */
6685 VERTICAL_SCROLL_BAR_LEFT_BORDER,
6686 VERTICAL_SCROLL_BAR_TOP_BORDER + start,
6687 inside_width, end - start);
6689 /* Restore the foreground color of the GC if we changed it above. */
6690 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
6691 XSetForeground (FRAME_X_DISPLAY (f), gc,
6692 FRAME_FOREGROUND_PIXEL (f));
6694 /* Draw the empty space below the handle. Note that we can't
6695 clear zero-height areas; that means "clear to end of window." */
6696 if ((inside_width > 0) && (end < inside_height))
6697 x_clear_area1 (FRAME_X_DISPLAY (f), w,
6698 VERTICAL_SCROLL_BAR_LEFT_BORDER,
6699 VERTICAL_SCROLL_BAR_TOP_BORDER + end,
6700 inside_width, inside_height - end, False);
6703 unblock_input ();
6706 #endif /* !USE_TOOLKIT_SCROLL_BARS */
6708 /* Destroy scroll bar BAR, and set its Emacs window's scroll bar to
6709 nil. */
6711 static void
6712 x_scroll_bar_remove (struct scroll_bar *bar)
6714 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6715 block_input ();
6717 #ifdef USE_TOOLKIT_SCROLL_BARS
6718 #ifdef USE_GTK
6719 xg_remove_scroll_bar (f, bar->x_window);
6720 #else /* not USE_GTK */
6721 XtDestroyWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar));
6722 #endif /* not USE_GTK */
6723 #else
6724 XDestroyWindow (FRAME_X_DISPLAY (f), bar->x_window);
6725 #endif
6727 /* Dissociate this scroll bar from its window. */
6728 if (bar->horizontal)
6729 wset_horizontal_scroll_bar (XWINDOW (bar->window), Qnil);
6730 else
6731 wset_vertical_scroll_bar (XWINDOW (bar->window), Qnil);
6733 unblock_input ();
6737 /* Set the handle of the vertical scroll bar for WINDOW to indicate
6738 that we are displaying PORTION characters out of a total of WHOLE
6739 characters, starting at POSITION. If WINDOW has no scroll bar,
6740 create one. */
6742 static void
6743 XTset_vertical_scroll_bar (struct window *w, int portion, int whole, int position)
6745 struct frame *f = XFRAME (w->frame);
6746 Lisp_Object barobj;
6747 struct scroll_bar *bar;
6748 int top, height, left, width;
6749 int window_y, window_height;
6751 /* Get window dimensions. */
6752 window_box (w, ANY_AREA, 0, &window_y, 0, &window_height);
6753 top = window_y;
6754 height = window_height;
6755 left = WINDOW_SCROLL_BAR_AREA_X (w);
6756 width = WINDOW_SCROLL_BAR_AREA_WIDTH (w);
6758 /* Does the scroll bar exist yet? */
6759 if (NILP (w->vertical_scroll_bar))
6761 if (width > 0 && height > 0)
6763 block_input ();
6764 x_clear_area (f, left, top, width, height);
6765 unblock_input ();
6768 bar = x_scroll_bar_create (w, top, left, width, max (height, 1), false);
6770 else
6772 /* It may just need to be moved and resized. */
6773 unsigned int mask = 0;
6775 bar = XSCROLL_BAR (w->vertical_scroll_bar);
6777 block_input ();
6779 if (left != bar->left)
6780 mask |= CWX;
6781 if (top != bar->top)
6782 mask |= CWY;
6783 if (width != bar->width)
6784 mask |= CWWidth;
6785 if (height != bar->height)
6786 mask |= CWHeight;
6788 #ifdef USE_TOOLKIT_SCROLL_BARS
6790 /* Move/size the scroll bar widget. */
6791 if (mask)
6793 /* Since toolkit scroll bars are smaller than the space reserved
6794 for them on the frame, we have to clear "under" them. */
6795 if (width > 0 && height > 0)
6796 x_clear_area (f, left, top, width, height);
6797 #ifdef USE_GTK
6798 xg_update_scrollbar_pos (f, bar->x_window, top,
6799 left, width, max (height, 1));
6800 #else /* not USE_GTK */
6801 XtConfigureWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar),
6802 left, top, width, max (height, 1), 0);
6803 #endif /* not USE_GTK */
6805 #else /* not USE_TOOLKIT_SCROLL_BARS */
6807 /* Move/size the scroll bar window. */
6808 if (mask)
6810 XWindowChanges wc;
6812 wc.x = left;
6813 wc.y = top;
6814 wc.width = width;
6815 wc.height = height;
6816 XConfigureWindow (FRAME_X_DISPLAY (f), bar->x_window,
6817 mask, &wc);
6820 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6822 /* Remember new settings. */
6823 bar->left = left;
6824 bar->top = top;
6825 bar->width = width;
6826 bar->height = height;
6828 unblock_input ();
6831 #ifdef USE_TOOLKIT_SCROLL_BARS
6832 x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
6833 #else /* not USE_TOOLKIT_SCROLL_BARS */
6834 /* Set the scroll bar's current state, unless we're currently being
6835 dragged. */
6836 if (bar->dragging == -1)
6838 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, height);
6840 if (whole == 0)
6841 x_scroll_bar_set_handle (bar, 0, top_range, false);
6842 else
6844 int start = ((double) position * top_range) / whole;
6845 int end = ((double) (position + portion) * top_range) / whole;
6846 x_scroll_bar_set_handle (bar, start, end, false);
6849 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6851 XSETVECTOR (barobj, bar);
6852 wset_vertical_scroll_bar (w, barobj);
6856 static void
6857 XTset_horizontal_scroll_bar (struct window *w, int portion, int whole, int position)
6859 struct frame *f = XFRAME (w->frame);
6860 Lisp_Object barobj;
6861 struct scroll_bar *bar;
6862 int top, height, left, width;
6863 int window_x, window_width;
6864 int pixel_width = WINDOW_PIXEL_WIDTH (w);
6866 /* Get window dimensions. */
6867 window_box (w, ANY_AREA, &window_x, 0, &window_width, 0);
6868 left = window_x;
6869 width = window_width;
6870 top = WINDOW_SCROLL_BAR_AREA_Y (w);
6871 height = WINDOW_SCROLL_BAR_AREA_HEIGHT (w);
6873 /* Does the scroll bar exist yet? */
6874 if (NILP (w->horizontal_scroll_bar))
6876 if (width > 0 && height > 0)
6878 block_input ();
6880 /* Clear also part between window_width and
6881 WINDOW_PIXEL_WIDTH. */
6882 x_clear_area (f, left, top, pixel_width, height);
6883 unblock_input ();
6886 bar = x_scroll_bar_create (w, top, left, width, height, true);
6888 else
6890 /* It may just need to be moved and resized. */
6891 unsigned int mask = 0;
6893 bar = XSCROLL_BAR (w->horizontal_scroll_bar);
6895 block_input ();
6897 if (left != bar->left)
6898 mask |= CWX;
6899 if (top != bar->top)
6900 mask |= CWY;
6901 if (width != bar->width)
6902 mask |= CWWidth;
6903 if (height != bar->height)
6904 mask |= CWHeight;
6906 #ifdef USE_TOOLKIT_SCROLL_BARS
6907 /* Move/size the scroll bar widget. */
6908 if (mask)
6910 /* Since toolkit scroll bars are smaller than the space reserved
6911 for them on the frame, we have to clear "under" them. */
6912 if (width > 0 && height > 0)
6913 x_clear_area (f,
6914 WINDOW_LEFT_EDGE_X (w), top,
6915 pixel_width - WINDOW_RIGHT_DIVIDER_WIDTH (w), height);
6916 #ifdef USE_GTK
6917 xg_update_horizontal_scrollbar_pos (f, bar->x_window, top, left,
6918 width, height);
6919 #else /* not USE_GTK */
6920 XtConfigureWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar),
6921 left, top, width, height, 0);
6922 #endif /* not USE_GTK */
6924 #else /* not USE_TOOLKIT_SCROLL_BARS */
6926 /* Clear areas not covered by the scroll bar because it's not as
6927 wide as the area reserved for it. This makes sure a
6928 previous mode line display is cleared after C-x 2 C-x 1, for
6929 example. */
6931 int area_height = WINDOW_CONFIG_SCROLL_BAR_HEIGHT (w);
6932 int rest = area_height - height;
6933 if (rest > 0 && width > 0)
6934 x_clear_area (f, left, top, width, rest);
6937 /* Move/size the scroll bar window. */
6938 if (mask)
6940 XWindowChanges wc;
6942 wc.x = left;
6943 wc.y = top;
6944 wc.width = width;
6945 wc.height = height;
6946 XConfigureWindow (FRAME_X_DISPLAY (f), bar->x_window,
6947 mask, &wc);
6950 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6952 /* Remember new settings. */
6953 bar->left = left;
6954 bar->top = top;
6955 bar->width = width;
6956 bar->height = height;
6958 unblock_input ();
6961 #ifdef USE_TOOLKIT_SCROLL_BARS
6962 x_set_toolkit_horizontal_scroll_bar_thumb (bar, portion, position, whole);
6963 #else /* not USE_TOOLKIT_SCROLL_BARS */
6964 /* Set the scroll bar's current state, unless we're currently being
6965 dragged. */
6966 if (bar->dragging == -1)
6968 int left_range = HORIZONTAL_SCROLL_BAR_LEFT_RANGE (f, width);
6970 if (whole == 0)
6971 x_scroll_bar_set_handle (bar, 0, left_range, false);
6972 else
6974 int start = ((double) position * left_range) / whole;
6975 int end = ((double) (position + portion) * left_range) / whole;
6976 x_scroll_bar_set_handle (bar, start, end, false);
6979 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6981 XSETVECTOR (barobj, bar);
6982 wset_horizontal_scroll_bar (w, barobj);
6986 /* The following three hooks are used when we're doing a thorough
6987 redisplay of the frame. We don't explicitly know which scroll bars
6988 are going to be deleted, because keeping track of when windows go
6989 away is a real pain - "Can you say set-window-configuration, boys
6990 and girls?" Instead, we just assert at the beginning of redisplay
6991 that *all* scroll bars are to be removed, and then save a scroll bar
6992 from the fiery pit when we actually redisplay its window. */
6994 /* Arrange for all scroll bars on FRAME to be removed at the next call
6995 to `*judge_scroll_bars_hook'. A scroll bar may be spared if
6996 `*redeem_scroll_bar_hook' is applied to its window before the judgment. */
6998 static void
6999 XTcondemn_scroll_bars (struct frame *frame)
7001 if (!NILP (FRAME_SCROLL_BARS (frame)))
7003 if (!NILP (FRAME_CONDEMNED_SCROLL_BARS (frame)))
7005 /* Prepend scrollbars to already condemned ones. */
7006 Lisp_Object last = FRAME_SCROLL_BARS (frame);
7008 while (!NILP (XSCROLL_BAR (last)->next))
7009 last = XSCROLL_BAR (last)->next;
7011 XSCROLL_BAR (last)->next = FRAME_CONDEMNED_SCROLL_BARS (frame);
7012 XSCROLL_BAR (FRAME_CONDEMNED_SCROLL_BARS (frame))->prev = last;
7015 fset_condemned_scroll_bars (frame, FRAME_SCROLL_BARS (frame));
7016 fset_scroll_bars (frame, Qnil);
7021 /* Un-mark WINDOW's scroll bar for deletion in this judgment cycle.
7022 Note that WINDOW isn't necessarily condemned at all. */
7024 static void
7025 XTredeem_scroll_bar (struct window *w)
7027 struct scroll_bar *bar;
7028 Lisp_Object barobj;
7029 struct frame *f;
7031 /* We can't redeem this window's scroll bar if it doesn't have one. */
7032 if (NILP (w->vertical_scroll_bar) && NILP (w->horizontal_scroll_bar))
7033 emacs_abort ();
7035 if (!NILP (w->vertical_scroll_bar) && WINDOW_HAS_VERTICAL_SCROLL_BAR (w))
7037 bar = XSCROLL_BAR (w->vertical_scroll_bar);
7038 /* Unlink it from the condemned list. */
7039 f = XFRAME (WINDOW_FRAME (w));
7040 if (NILP (bar->prev))
7042 /* If the prev pointer is nil, it must be the first in one of
7043 the lists. */
7044 if (EQ (FRAME_SCROLL_BARS (f), w->vertical_scroll_bar))
7045 /* It's not condemned. Everything's fine. */
7046 goto horizontal;
7047 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
7048 w->vertical_scroll_bar))
7049 fset_condemned_scroll_bars (f, bar->next);
7050 else
7051 /* If its prev pointer is nil, it must be at the front of
7052 one or the other! */
7053 emacs_abort ();
7055 else
7056 XSCROLL_BAR (bar->prev)->next = bar->next;
7058 if (! NILP (bar->next))
7059 XSCROLL_BAR (bar->next)->prev = bar->prev;
7061 bar->next = FRAME_SCROLL_BARS (f);
7062 bar->prev = Qnil;
7063 XSETVECTOR (barobj, bar);
7064 fset_scroll_bars (f, barobj);
7065 if (! NILP (bar->next))
7066 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
7069 horizontal:
7070 if (!NILP (w->horizontal_scroll_bar) && WINDOW_HAS_HORIZONTAL_SCROLL_BAR (w))
7072 bar = XSCROLL_BAR (w->horizontal_scroll_bar);
7073 /* Unlink it from the condemned list. */
7074 f = XFRAME (WINDOW_FRAME (w));
7075 if (NILP (bar->prev))
7077 /* If the prev pointer is nil, it must be the first in one of
7078 the lists. */
7079 if (EQ (FRAME_SCROLL_BARS (f), w->horizontal_scroll_bar))
7080 /* It's not condemned. Everything's fine. */
7081 return;
7082 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
7083 w->horizontal_scroll_bar))
7084 fset_condemned_scroll_bars (f, bar->next);
7085 else
7086 /* If its prev pointer is nil, it must be at the front of
7087 one or the other! */
7088 emacs_abort ();
7090 else
7091 XSCROLL_BAR (bar->prev)->next = bar->next;
7093 if (! NILP (bar->next))
7094 XSCROLL_BAR (bar->next)->prev = bar->prev;
7096 bar->next = FRAME_SCROLL_BARS (f);
7097 bar->prev = Qnil;
7098 XSETVECTOR (barobj, bar);
7099 fset_scroll_bars (f, barobj);
7100 if (! NILP (bar->next))
7101 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
7105 /* Remove all scroll bars on FRAME that haven't been saved since the
7106 last call to `*condemn_scroll_bars_hook'. */
7108 static void
7109 XTjudge_scroll_bars (struct frame *f)
7111 Lisp_Object bar, next;
7113 bar = FRAME_CONDEMNED_SCROLL_BARS (f);
7115 /* Clear out the condemned list now so we won't try to process any
7116 more events on the hapless scroll bars. */
7117 fset_condemned_scroll_bars (f, Qnil);
7119 for (; ! NILP (bar); bar = next)
7121 struct scroll_bar *b = XSCROLL_BAR (bar);
7123 x_scroll_bar_remove (b);
7125 next = b->next;
7126 b->next = b->prev = Qnil;
7129 /* Now there should be no references to the condemned scroll bars,
7130 and they should get garbage-collected. */
7134 #ifndef USE_TOOLKIT_SCROLL_BARS
7135 /* Handle an Expose or GraphicsExpose event on a scroll bar. This
7136 is a no-op when using toolkit scroll bars.
7138 This may be called from a signal handler, so we have to ignore GC
7139 mark bits. */
7141 static void
7142 x_scroll_bar_expose (struct scroll_bar *bar, const XEvent *event)
7144 Window w = bar->x_window;
7145 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
7146 GC gc = f->output_data.x->normal_gc;
7148 block_input ();
7150 x_scroll_bar_set_handle (bar, bar->start, bar->end, true);
7152 /* Switch to scroll bar foreground color. */
7153 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
7154 XSetForeground (FRAME_X_DISPLAY (f), gc,
7155 f->output_data.x->scroll_bar_foreground_pixel);
7157 /* Draw a one-pixel border just inside the edges of the scroll bar. */
7158 XDrawRectangle (FRAME_X_DISPLAY (f), w, gc,
7159 /* x, y, width, height */
7160 0, 0, bar->width - 1, bar->height - 1);
7162 /* Restore the foreground color of the GC if we changed it above. */
7163 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
7164 XSetForeground (FRAME_X_DISPLAY (f), gc,
7165 FRAME_FOREGROUND_PIXEL (f));
7167 unblock_input ();
7170 #endif /* not USE_TOOLKIT_SCROLL_BARS */
7172 /* Handle a mouse click on the scroll bar BAR. If *EMACS_EVENT's kind
7173 is set to something other than NO_EVENT, it is enqueued.
7175 This may be called from a signal handler, so we have to ignore GC
7176 mark bits. */
7179 static void
7180 x_scroll_bar_handle_click (struct scroll_bar *bar,
7181 const XEvent *event,
7182 struct input_event *emacs_event)
7184 if (! WINDOWP (bar->window))
7185 emacs_abort ();
7187 emacs_event->kind = (bar->horizontal
7188 ? HORIZONTAL_SCROLL_BAR_CLICK_EVENT
7189 : SCROLL_BAR_CLICK_EVENT);
7190 emacs_event->code = event->xbutton.button - Button1;
7191 emacs_event->modifiers
7192 = (x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO
7193 (XFRAME (WINDOW_FRAME (XWINDOW (bar->window)))),
7194 event->xbutton.state)
7195 | (event->type == ButtonRelease
7196 ? up_modifier
7197 : down_modifier));
7198 emacs_event->frame_or_window = bar->window;
7199 emacs_event->arg = Qnil;
7200 emacs_event->timestamp = event->xbutton.time;
7201 if (bar->horizontal)
7203 int left_range
7204 = HORIZONTAL_SCROLL_BAR_LEFT_RANGE (f, bar->width);
7205 int x = event->xbutton.x - HORIZONTAL_SCROLL_BAR_LEFT_BORDER;
7207 if (x < 0) x = 0;
7208 if (x > left_range) x = left_range;
7210 if (x < bar->start)
7211 emacs_event->part = scroll_bar_before_handle;
7212 else if (x < bar->end + HORIZONTAL_SCROLL_BAR_MIN_HANDLE)
7213 emacs_event->part = scroll_bar_horizontal_handle;
7214 else
7215 emacs_event->part = scroll_bar_after_handle;
7217 #ifndef USE_TOOLKIT_SCROLL_BARS
7218 /* If the user has released the handle, set it to its final position. */
7219 if (event->type == ButtonRelease && bar->dragging != -1)
7221 int new_start = - bar->dragging;
7222 int new_end = new_start + bar->end - bar->start;
7224 x_scroll_bar_set_handle (bar, new_start, new_end, false);
7225 bar->dragging = -1;
7227 #endif
7229 XSETINT (emacs_event->x, left_range);
7230 XSETINT (emacs_event->y, x);
7232 else
7234 int top_range
7235 = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
7236 int y = event->xbutton.y - VERTICAL_SCROLL_BAR_TOP_BORDER;
7238 if (y < 0) y = 0;
7239 if (y > top_range) y = top_range;
7241 if (y < bar->start)
7242 emacs_event->part = scroll_bar_above_handle;
7243 else if (y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
7244 emacs_event->part = scroll_bar_handle;
7245 else
7246 emacs_event->part = scroll_bar_below_handle;
7248 #ifndef USE_TOOLKIT_SCROLL_BARS
7249 /* If the user has released the handle, set it to its final position. */
7250 if (event->type == ButtonRelease && bar->dragging != -1)
7252 int new_start = y - bar->dragging;
7253 int new_end = new_start + bar->end - bar->start;
7255 x_scroll_bar_set_handle (bar, new_start, new_end, false);
7256 bar->dragging = -1;
7258 #endif
7260 XSETINT (emacs_event->x, y);
7261 XSETINT (emacs_event->y, top_range);
7265 #ifndef USE_TOOLKIT_SCROLL_BARS
7267 /* Handle some mouse motion while someone is dragging the scroll bar.
7269 This may be called from a signal handler, so we have to ignore GC
7270 mark bits. */
7272 static void
7273 x_scroll_bar_note_movement (struct scroll_bar *bar,
7274 const XMotionEvent *event)
7276 struct frame *f = XFRAME (XWINDOW (bar->window)->frame);
7277 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
7279 dpyinfo->last_mouse_movement_time = event->time;
7280 dpyinfo->last_mouse_scroll_bar = bar;
7281 f->mouse_moved = true;
7283 /* If we're dragging the bar, display it. */
7284 if (bar->dragging != -1)
7286 /* Where should the handle be now? */
7287 int new_start = event->y - bar->dragging;
7289 if (new_start != bar->start)
7291 int new_end = new_start + bar->end - bar->start;
7293 x_scroll_bar_set_handle (bar, new_start, new_end, false);
7298 #endif /* !USE_TOOLKIT_SCROLL_BARS */
7300 /* Return information to the user about the current position of the mouse
7301 on the scroll bar. */
7303 static void
7304 x_scroll_bar_report_motion (struct frame **fp, Lisp_Object *bar_window,
7305 enum scroll_bar_part *part, Lisp_Object *x,
7306 Lisp_Object *y, Time *timestamp)
7308 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (*fp);
7309 struct scroll_bar *bar = dpyinfo->last_mouse_scroll_bar;
7310 Window w = bar->x_window;
7311 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
7312 int win_x, win_y;
7313 Window dummy_window;
7314 int dummy_coord;
7315 unsigned int dummy_mask;
7317 block_input ();
7319 /* Get the mouse's position relative to the scroll bar window, and
7320 report that. */
7321 if (XQueryPointer (FRAME_X_DISPLAY (f), w,
7323 /* Root, child, root x and root y. */
7324 &dummy_window, &dummy_window,
7325 &dummy_coord, &dummy_coord,
7327 /* Position relative to scroll bar. */
7328 &win_x, &win_y,
7330 /* Mouse buttons and modifier keys. */
7331 &dummy_mask))
7333 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
7335 win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
7337 if (bar->dragging != -1)
7338 win_y -= bar->dragging;
7340 if (win_y < 0)
7341 win_y = 0;
7342 if (win_y > top_range)
7343 win_y = top_range;
7345 *fp = f;
7346 *bar_window = bar->window;
7348 if (bar->dragging != -1)
7349 *part = scroll_bar_handle;
7350 else if (win_y < bar->start)
7351 *part = scroll_bar_above_handle;
7352 else if (win_y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
7353 *part = scroll_bar_handle;
7354 else
7355 *part = scroll_bar_below_handle;
7357 XSETINT (*x, win_y);
7358 XSETINT (*y, top_range);
7360 f->mouse_moved = false;
7361 dpyinfo->last_mouse_scroll_bar = NULL;
7362 *timestamp = dpyinfo->last_mouse_movement_time;
7365 unblock_input ();
7369 /* Return information to the user about the current position of the mouse
7370 on the scroll bar. */
7372 static void
7373 x_horizontal_scroll_bar_report_motion (struct frame **fp, Lisp_Object *bar_window,
7374 enum scroll_bar_part *part, Lisp_Object *x,
7375 Lisp_Object *y, Time *timestamp)
7377 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (*fp);
7378 struct scroll_bar *bar = dpyinfo->last_mouse_scroll_bar;
7379 Window w = bar->x_window;
7380 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
7381 int win_x, win_y;
7382 Window dummy_window;
7383 int dummy_coord;
7384 unsigned int dummy_mask;
7386 block_input ();
7388 /* Get the mouse's position relative to the scroll bar window, and
7389 report that. */
7390 if (XQueryPointer (FRAME_X_DISPLAY (f), w,
7392 /* Root, child, root x and root y. */
7393 &dummy_window, &dummy_window,
7394 &dummy_coord, &dummy_coord,
7396 /* Position relative to scroll bar. */
7397 &win_x, &win_y,
7399 /* Mouse buttons and modifier keys. */
7400 &dummy_mask))
7402 int left_range = HORIZONTAL_SCROLL_BAR_LEFT_RANGE (f, bar->width);
7404 win_x -= HORIZONTAL_SCROLL_BAR_LEFT_BORDER;
7406 if (bar->dragging != -1)
7407 win_x -= bar->dragging;
7409 if (win_x < 0)
7410 win_x = 0;
7411 if (win_x > left_range)
7412 win_x = left_range;
7414 *fp = f;
7415 *bar_window = bar->window;
7417 if (bar->dragging != -1)
7418 *part = scroll_bar_horizontal_handle;
7419 else if (win_x < bar->start)
7420 *part = scroll_bar_before_handle;
7421 else if (win_x < bar->end + HORIZONTAL_SCROLL_BAR_MIN_HANDLE)
7422 *part = scroll_bar_handle;
7423 else
7424 *part = scroll_bar_after_handle;
7426 XSETINT (*y, win_x);
7427 XSETINT (*x, left_range);
7429 f->mouse_moved = false;
7430 dpyinfo->last_mouse_scroll_bar = NULL;
7431 *timestamp = dpyinfo->last_mouse_movement_time;
7434 unblock_input ();
7438 /* The screen has been cleared so we may have changed foreground or
7439 background colors, and the scroll bars may need to be redrawn.
7440 Clear out the scroll bars, and ask for expose events, so we can
7441 redraw them. */
7443 static void
7444 x_scroll_bar_clear (struct frame *f)
7446 #ifndef USE_TOOLKIT_SCROLL_BARS
7447 Lisp_Object bar;
7449 /* We can have scroll bars even if this is 0,
7450 if we just turned off scroll bar mode.
7451 But in that case we should not clear them. */
7452 if (FRAME_HAS_VERTICAL_SCROLL_BARS (f))
7453 for (bar = FRAME_SCROLL_BARS (f); VECTORP (bar);
7454 bar = XSCROLL_BAR (bar)->next)
7455 XClearArea (FRAME_X_DISPLAY (f),
7456 XSCROLL_BAR (bar)->x_window,
7457 0, 0, 0, 0, True);
7458 #endif /* not USE_TOOLKIT_SCROLL_BARS */
7461 #ifdef ENABLE_CHECKING
7463 /* Record the last 100 characters stored
7464 to help debug the loss-of-chars-during-GC problem. */
7466 static int temp_index;
7467 static short temp_buffer[100];
7469 #define STORE_KEYSYM_FOR_DEBUG(keysym) \
7470 if (temp_index == ARRAYELTS (temp_buffer)) \
7471 temp_index = 0; \
7472 temp_buffer[temp_index++] = (keysym)
7474 #else /* not ENABLE_CHECKING */
7476 #define STORE_KEYSYM_FOR_DEBUG(keysym) ((void)0)
7478 #endif /* ENABLE_CHECKING */
7480 /* Set this to nonzero to fake an "X I/O error"
7481 on a particular display. */
7483 static struct x_display_info *XTread_socket_fake_io_error;
7485 /* When we find no input here, we occasionally do a no-op command
7486 to verify that the X server is still running and we can still talk with it.
7487 We try all the open displays, one by one.
7488 This variable is used for cycling thru the displays. */
7490 static struct x_display_info *next_noop_dpyinfo;
7492 enum
7494 X_EVENT_NORMAL,
7495 X_EVENT_GOTO_OUT,
7496 X_EVENT_DROP
7499 /* Filter events for the current X input method.
7500 DPYINFO is the display this event is for.
7501 EVENT is the X event to filter.
7503 Returns non-zero if the event was filtered, caller shall not process
7504 this event further.
7505 Returns zero if event is wasn't filtered. */
7507 #ifdef HAVE_X_I18N
7508 static int
7509 x_filter_event (struct x_display_info *dpyinfo, XEvent *event)
7511 /* XFilterEvent returns non-zero if the input method has
7512 consumed the event. We pass the frame's X window to
7513 XFilterEvent because that's the one for which the IC
7514 was created. */
7516 struct frame *f1 = x_any_window_to_frame (dpyinfo,
7517 event->xclient.window);
7519 return XFilterEvent (event, f1 ? FRAME_X_WINDOW (f1) : None);
7521 #endif
7523 #ifdef USE_GTK
7524 static int current_count;
7525 static int current_finish;
7526 static struct input_event *current_hold_quit;
7528 /* This is the filter function invoked by the GTK event loop.
7529 It is invoked before the XEvent is translated to a GdkEvent,
7530 so we have a chance to act on the event before GTK. */
7531 static GdkFilterReturn
7532 event_handler_gdk (GdkXEvent *gxev, GdkEvent *ev, gpointer data)
7534 XEvent *xev = (XEvent *) gxev;
7536 block_input ();
7537 if (current_count >= 0)
7539 struct x_display_info *dpyinfo;
7541 dpyinfo = x_display_info_for_display (xev->xany.display);
7543 #ifdef HAVE_X_I18N
7544 /* Filter events for the current X input method.
7545 GTK calls XFilterEvent but not for key press and release,
7546 so we do it here. */
7547 if ((xev->type == KeyPress || xev->type == KeyRelease)
7548 && dpyinfo
7549 && x_filter_event (dpyinfo, xev))
7551 unblock_input ();
7552 return GDK_FILTER_REMOVE;
7554 #endif
7556 if (! dpyinfo)
7557 current_finish = X_EVENT_NORMAL;
7558 else
7559 current_count
7560 += handle_one_xevent (dpyinfo, xev, &current_finish,
7561 current_hold_quit);
7563 else
7564 current_finish = x_dispatch_event (xev, xev->xany.display);
7566 unblock_input ();
7568 if (current_finish == X_EVENT_GOTO_OUT || current_finish == X_EVENT_DROP)
7569 return GDK_FILTER_REMOVE;
7571 return GDK_FILTER_CONTINUE;
7573 #endif /* USE_GTK */
7576 static void xembed_send_message (struct frame *f, Time,
7577 enum xembed_message,
7578 long detail, long data1, long data2);
7580 static void
7581 x_net_wm_state (struct frame *f, Window window)
7583 int value = FULLSCREEN_NONE;
7584 Lisp_Object lval = Qnil;
7585 bool sticky = false;
7587 get_current_wm_state (f, window, &value, &sticky);
7589 switch (value)
7591 case FULLSCREEN_WIDTH:
7592 lval = Qfullwidth;
7593 break;
7594 case FULLSCREEN_HEIGHT:
7595 lval = Qfullheight;
7596 break;
7597 case FULLSCREEN_BOTH:
7598 lval = Qfullboth;
7599 break;
7600 case FULLSCREEN_MAXIMIZED:
7601 lval = Qmaximized;
7602 break;
7605 frame_size_history_add
7606 (f, Qx_net_wm_state, 0, 0,
7607 list2 (get_frame_param (f, Qfullscreen), lval));
7609 store_frame_param (f, Qfullscreen, lval);
7610 /** store_frame_param (f, Qsticky, sticky ? Qt : Qnil); **/
7613 /* Flip back buffers on any frames with undrawn content. */
7614 static void
7615 flush_dirty_back_buffers (void)
7617 block_input ();
7618 Lisp_Object tail, frame;
7619 FOR_EACH_FRAME (tail, frame)
7621 struct frame *f = XFRAME (frame);
7622 if (FRAME_LIVE_P (f) &&
7623 FRAME_X_P (f) &&
7624 FRAME_X_WINDOW (f) &&
7625 !FRAME_GARBAGED_P (f) &&
7626 !buffer_flipping_blocked_p () &&
7627 FRAME_X_NEED_BUFFER_FLIP (f))
7628 show_back_buffer (f);
7630 unblock_input ();
7633 /* Handles the XEvent EVENT on display DPYINFO.
7635 *FINISH is X_EVENT_GOTO_OUT if caller should stop reading events.
7636 *FINISH is zero if caller should continue reading events.
7637 *FINISH is X_EVENT_DROP if event should not be passed to the toolkit.
7638 *EVENT is unchanged unless we're processing KeyPress event.
7640 We return the number of characters stored into the buffer. */
7642 static int
7643 handle_one_xevent (struct x_display_info *dpyinfo,
7644 const XEvent *event,
7645 int *finish, struct input_event *hold_quit)
7647 union buffered_input_event inev;
7648 int count = 0;
7649 int do_help = 0;
7650 ptrdiff_t nbytes = 0;
7651 struct frame *any, *f = NULL;
7652 struct coding_system coding;
7653 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
7654 /* This holds the state XLookupString needs to implement dead keys
7655 and other tricks known as "compose processing". _X Window System_
7656 says that a portable program can't use this, but Stephen Gildea assures
7657 me that letting the compiler initialize it to zeros will work okay. */
7658 static XComposeStatus compose_status;
7659 XEvent configureEvent;
7660 XEvent next_event;
7662 USE_SAFE_ALLOCA;
7664 *finish = X_EVENT_NORMAL;
7666 EVENT_INIT (inev.ie);
7667 inev.ie.kind = NO_EVENT;
7668 inev.ie.arg = Qnil;
7670 any = x_any_window_to_frame (dpyinfo, event->xany.window);
7672 if (any && any->wait_event_type == event->type)
7673 any->wait_event_type = 0; /* Indicates we got it. */
7675 switch (event->type)
7677 case ClientMessage:
7679 if (event->xclient.message_type == dpyinfo->Xatom_wm_protocols
7680 && event->xclient.format == 32)
7682 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_take_focus)
7684 /* Use the value returned by x_any_window_to_frame
7685 because this could be the shell widget window
7686 if the frame has no title bar. */
7687 f = any;
7688 #ifdef HAVE_X_I18N
7689 /* Not quite sure this is needed -pd */
7690 if (f && FRAME_XIC (f))
7691 XSetICFocus (FRAME_XIC (f));
7692 #endif
7693 #if false
7694 /* Emacs sets WM hints whose `input' field is `true'. This
7695 instructs the WM to set the input focus automatically for
7696 Emacs with a call to XSetInputFocus. Setting WM_TAKE_FOCUS
7697 tells the WM to send us a ClientMessage WM_TAKE_FOCUS after
7698 it has set the focus. So, XSetInputFocus below is not
7699 needed.
7701 The call to XSetInputFocus below has also caused trouble. In
7702 cases where the XSetInputFocus done by the WM and the one
7703 below are temporally close (on a fast machine), the call
7704 below can generate additional FocusIn events which confuse
7705 Emacs. */
7707 /* Since we set WM_TAKE_FOCUS, we must call
7708 XSetInputFocus explicitly. But not if f is null,
7709 since that might be an event for a deleted frame. */
7710 if (f)
7712 Display *d = event->xclient.display;
7713 /* Catch and ignore errors, in case window has been
7714 iconified by a window manager such as GWM. */
7715 x_catch_errors (d);
7716 XSetInputFocus (d, event->xclient.window,
7717 /* The ICCCM says this is
7718 the only valid choice. */
7719 RevertToParent,
7720 event->xclient.data.l[1]);
7721 x_uncatch_errors ();
7723 /* Not certain about handling scroll bars here */
7724 #endif
7725 goto done;
7728 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_save_yourself)
7730 /* Save state modify the WM_COMMAND property to
7731 something which can reinstate us. This notifies
7732 the session manager, who's looking for such a
7733 PropertyNotify. Can restart processing when
7734 a keyboard or mouse event arrives. */
7735 /* If we have a session manager, don't set this.
7736 KDE will then start two Emacsen, one for the
7737 session manager and one for this. */
7738 #ifdef HAVE_X_SM
7739 if (! x_session_have_connection ())
7740 #endif
7742 f = x_top_window_to_frame (dpyinfo,
7743 event->xclient.window);
7744 /* This is just so we only give real data once
7745 for a single Emacs process. */
7746 if (f == SELECTED_FRAME ())
7747 XSetCommand (FRAME_X_DISPLAY (f),
7748 event->xclient.window,
7749 initial_argv, initial_argc);
7750 else if (f)
7751 XSetCommand (FRAME_X_DISPLAY (f),
7752 event->xclient.window,
7753 0, 0);
7755 goto done;
7758 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_delete_window)
7760 f = any;
7761 if (!f)
7762 goto OTHER; /* May be a dialog that is to be removed */
7764 inev.ie.kind = DELETE_WINDOW_EVENT;
7765 XSETFRAME (inev.ie.frame_or_window, f);
7766 goto done;
7769 goto done;
7772 if (event->xclient.message_type == dpyinfo->Xatom_wm_configure_denied)
7773 goto done;
7775 if (event->xclient.message_type == dpyinfo->Xatom_wm_window_moved)
7777 int new_x, new_y;
7778 f = x_window_to_frame (dpyinfo, event->xclient.window);
7780 new_x = event->xclient.data.s[0];
7781 new_y = event->xclient.data.s[1];
7783 if (f)
7785 f->left_pos = new_x;
7786 f->top_pos = new_y;
7788 goto done;
7791 #ifdef X_TOOLKIT_EDITRES
7792 if (event->xclient.message_type == dpyinfo->Xatom_editres)
7794 f = any;
7795 if (f)
7796 _XEditResCheckMessages (f->output_data.x->widget,
7797 NULL, (XEvent *) event, NULL);
7798 goto done;
7800 #endif /* X_TOOLKIT_EDITRES */
7802 if (event->xclient.message_type == dpyinfo->Xatom_DONE
7803 || event->xclient.message_type == dpyinfo->Xatom_PAGE)
7805 /* Ghostview job completed. Kill it. We could
7806 reply with "Next" if we received "Page", but we
7807 currently never do because we are interested in
7808 images, only, which should have 1 page. */
7809 Pixmap pixmap = (Pixmap) event->xclient.data.l[1];
7810 f = x_window_to_frame (dpyinfo, event->xclient.window);
7811 if (!f)
7812 goto OTHER;
7813 x_kill_gs_process (pixmap, f);
7814 expose_frame (f, 0, 0, 0, 0);
7815 goto done;
7818 #ifdef USE_TOOLKIT_SCROLL_BARS
7819 /* Scroll bar callbacks send a ClientMessage from which
7820 we construct an input_event. */
7821 if (event->xclient.message_type == dpyinfo->Xatom_Scrollbar)
7823 x_scroll_bar_to_input_event (event, &inev.ie);
7824 *finish = X_EVENT_GOTO_OUT;
7825 goto done;
7827 else if (event->xclient.message_type == dpyinfo->Xatom_Horizontal_Scrollbar)
7829 x_horizontal_scroll_bar_to_input_event (event, &inev.ie);
7830 *finish = X_EVENT_GOTO_OUT;
7831 goto done;
7833 #endif /* USE_TOOLKIT_SCROLL_BARS */
7835 /* XEmbed messages from the embedder (if any). */
7836 if (event->xclient.message_type == dpyinfo->Xatom_XEMBED)
7838 enum xembed_message msg = event->xclient.data.l[1];
7839 if (msg == XEMBED_FOCUS_IN || msg == XEMBED_FOCUS_OUT)
7840 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
7842 *finish = X_EVENT_GOTO_OUT;
7843 goto done;
7846 xft_settings_event (dpyinfo, event);
7848 f = any;
7849 if (!f)
7850 goto OTHER;
7851 if (x_handle_dnd_message (f, &event->xclient, dpyinfo, &inev.ie))
7852 *finish = X_EVENT_DROP;
7854 break;
7856 case SelectionNotify:
7857 x_display_set_last_user_time (dpyinfo, event->xselection.time);
7858 #ifdef USE_X_TOOLKIT
7859 if (! x_window_to_frame (dpyinfo, event->xselection.requestor))
7860 goto OTHER;
7861 #endif /* not USE_X_TOOLKIT */
7862 x_handle_selection_notify (&event->xselection);
7863 break;
7865 case SelectionClear: /* Someone has grabbed ownership. */
7866 x_display_set_last_user_time (dpyinfo, event->xselectionclear.time);
7867 #ifdef USE_X_TOOLKIT
7868 if (! x_window_to_frame (dpyinfo, event->xselectionclear.window))
7869 goto OTHER;
7870 #endif /* USE_X_TOOLKIT */
7872 const XSelectionClearEvent *eventp = &event->xselectionclear;
7874 inev.sie.kind = SELECTION_CLEAR_EVENT;
7875 SELECTION_EVENT_DPYINFO (&inev.sie) = dpyinfo;
7876 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
7877 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
7879 break;
7881 case SelectionRequest: /* Someone wants our selection. */
7882 x_display_set_last_user_time (dpyinfo, event->xselectionrequest.time);
7883 #ifdef USE_X_TOOLKIT
7884 if (!x_window_to_frame (dpyinfo, event->xselectionrequest.owner))
7885 goto OTHER;
7886 #endif /* USE_X_TOOLKIT */
7888 const XSelectionRequestEvent *eventp = &event->xselectionrequest;
7890 inev.sie.kind = SELECTION_REQUEST_EVENT;
7891 SELECTION_EVENT_DPYINFO (&inev.sie) = dpyinfo;
7892 SELECTION_EVENT_REQUESTOR (&inev.sie) = eventp->requestor;
7893 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
7894 SELECTION_EVENT_TARGET (&inev.sie) = eventp->target;
7895 SELECTION_EVENT_PROPERTY (&inev.sie) = eventp->property;
7896 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
7898 break;
7900 case PropertyNotify:
7901 x_display_set_last_user_time (dpyinfo, event->xproperty.time);
7902 f = x_top_window_to_frame (dpyinfo, event->xproperty.window);
7903 if (f && event->xproperty.atom == dpyinfo->Xatom_net_wm_state)
7905 bool not_hidden = x_handle_net_wm_state (f, &event->xproperty);
7906 if (not_hidden && FRAME_ICONIFIED_P (f))
7908 /* Gnome shell does not iconify us when C-z is pressed.
7909 It hides the frame. So if our state says we aren't
7910 hidden anymore, treat it as deiconified. */
7911 SET_FRAME_VISIBLE (f, 1);
7912 SET_FRAME_ICONIFIED (f, false);
7913 f->output_data.x->has_been_visible = true;
7914 inev.ie.kind = DEICONIFY_EVENT;
7915 XSETFRAME (inev.ie.frame_or_window, f);
7917 else if (! not_hidden && ! FRAME_ICONIFIED_P (f))
7919 SET_FRAME_VISIBLE (f, 0);
7920 SET_FRAME_ICONIFIED (f, true);
7921 inev.ie.kind = ICONIFY_EVENT;
7922 XSETFRAME (inev.ie.frame_or_window, f);
7926 x_handle_property_notify (&event->xproperty);
7927 xft_settings_event (dpyinfo, event);
7928 goto OTHER;
7930 case ReparentNotify:
7931 f = x_top_window_to_frame (dpyinfo, event->xreparent.window);
7932 if (f)
7934 /* Maybe we shouldn't set this for child frames ?? */
7935 f->output_data.x->parent_desc = event->xreparent.parent;
7936 if (!FRAME_PARENT_FRAME (f))
7937 x_real_positions (f, &f->left_pos, &f->top_pos);
7938 else
7940 Window root;
7941 unsigned int dummy_uint;
7943 block_input ();
7944 XGetGeometry (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
7945 &root, &f->left_pos, &f->top_pos,
7946 &dummy_uint, &dummy_uint, &dummy_uint, &dummy_uint);
7947 unblock_input ();
7950 /* Perhaps reparented due to a WM restart. Reset this. */
7951 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_UNKNOWN;
7952 FRAME_DISPLAY_INFO (f)->net_supported_window = 0;
7954 x_set_frame_alpha (f);
7956 goto OTHER;
7958 case Expose:
7959 f = x_window_to_frame (dpyinfo, event->xexpose.window);
7960 if (f)
7962 if (!FRAME_VISIBLE_P (f))
7964 block_input ();
7965 SET_FRAME_VISIBLE (f, 1);
7966 SET_FRAME_ICONIFIED (f, false);
7967 if (FRAME_X_DOUBLE_BUFFERED_P (f))
7968 font_drop_xrender_surfaces (f);
7969 f->output_data.x->has_been_visible = true;
7970 SET_FRAME_GARBAGED (f);
7971 unblock_input ();
7973 else if (FRAME_GARBAGED_P (f))
7975 #ifdef USE_GTK
7976 /* Go around the back buffer and manually clear the
7977 window the first time we show it. This way, we avoid
7978 showing users the sanity-defying horror of whatever
7979 GtkWindow is rendering beneath us. We've garbaged
7980 the frame, so we'll redraw the whole thing on next
7981 redisplay anyway. Yuck. */
7982 x_clear_area1 (
7983 FRAME_X_DISPLAY (f),
7984 FRAME_X_WINDOW (f),
7985 event->xexpose.x, event->xexpose.y,
7986 event->xexpose.width, event->xexpose.height,
7988 x_clear_under_internal_border (f);
7989 #endif
7993 if (!FRAME_GARBAGED_P (f))
7995 #ifdef USE_GTK
7996 /* This seems to be needed for GTK 2.6 and later, see
7997 http://debbugs.gnu.org/cgi/bugreport.cgi?bug=15398. */
7998 x_clear_area (f,
7999 event->xexpose.x, event->xexpose.y,
8000 event->xexpose.width, event->xexpose.height);
8001 #endif
8002 expose_frame (f, event->xexpose.x, event->xexpose.y,
8003 event->xexpose.width, event->xexpose.height);
8004 #ifdef USE_GTK
8005 x_clear_under_internal_border (f);
8006 #endif
8009 if (!FRAME_GARBAGED_P (f))
8010 show_back_buffer (f);
8012 else
8014 #ifndef USE_TOOLKIT_SCROLL_BARS
8015 struct scroll_bar *bar;
8016 #endif
8017 #if defined USE_LUCID
8018 /* Submenus of the Lucid menu bar aren't widgets
8019 themselves, so there's no way to dispatch events
8020 to them. Recognize this case separately. */
8022 Widget widget = x_window_to_menu_bar (event->xexpose.window);
8023 if (widget)
8024 xlwmenu_redisplay (widget);
8026 #endif /* USE_LUCID */
8028 #ifdef USE_TOOLKIT_SCROLL_BARS
8029 /* Dispatch event to the widget. */
8030 goto OTHER;
8031 #else /* not USE_TOOLKIT_SCROLL_BARS */
8032 bar = x_window_to_scroll_bar (event->xexpose.display,
8033 event->xexpose.window, 2);
8035 if (bar)
8036 x_scroll_bar_expose (bar, event);
8037 #ifdef USE_X_TOOLKIT
8038 else
8039 goto OTHER;
8040 #endif /* USE_X_TOOLKIT */
8041 #endif /* not USE_TOOLKIT_SCROLL_BARS */
8043 break;
8045 case GraphicsExpose: /* This occurs when an XCopyArea's
8046 source area was obscured or not
8047 available. */
8048 f = x_window_to_frame (dpyinfo, event->xgraphicsexpose.drawable);
8049 if (f)
8051 expose_frame (f, event->xgraphicsexpose.x,
8052 event->xgraphicsexpose.y,
8053 event->xgraphicsexpose.width,
8054 event->xgraphicsexpose.height);
8055 #ifdef USE_GTK
8056 x_clear_under_internal_border (f);
8057 #endif
8058 show_back_buffer (f);
8060 #ifdef USE_X_TOOLKIT
8061 else
8062 goto OTHER;
8063 #endif /* USE_X_TOOLKIT */
8064 break;
8066 case NoExpose: /* This occurs when an XCopyArea's
8067 source area was completely
8068 available. */
8069 break;
8071 case UnmapNotify:
8072 /* Redo the mouse-highlight after the tooltip has gone. */
8073 if (event->xunmap.window == tip_window)
8075 tip_window = 0;
8076 x_redo_mouse_highlight (dpyinfo);
8079 f = x_top_window_to_frame (dpyinfo, event->xunmap.window);
8080 if (f) /* F may no longer exist if
8081 the frame was deleted. */
8083 bool visible = FRAME_VISIBLE_P (f);
8084 /* While a frame is unmapped, display generation is
8085 disabled; you don't want to spend time updating a
8086 display that won't ever be seen. */
8087 SET_FRAME_VISIBLE (f, 0);
8088 /* We can't distinguish, from the event, whether the window
8089 has become iconified or invisible. So assume, if it
8090 was previously visible, than now it is iconified.
8091 But x_make_frame_invisible clears both
8092 the visible flag and the iconified flag;
8093 and that way, we know the window is not iconified now. */
8094 if (visible || FRAME_ICONIFIED_P (f))
8096 SET_FRAME_ICONIFIED (f, true);
8097 inev.ie.kind = ICONIFY_EVENT;
8098 XSETFRAME (inev.ie.frame_or_window, f);
8101 goto OTHER;
8103 case MapNotify:
8104 /* We use x_top_window_to_frame because map events can
8105 come for sub-windows and they don't mean that the
8106 frame is visible. */
8107 f = x_top_window_to_frame (dpyinfo, event->xmap.window);
8108 if (f)
8110 bool iconified = FRAME_ICONIFIED_P (f);
8112 /* Check if fullscreen was specified before we where mapped the
8113 first time, i.e. from the command line. */
8114 if (!f->output_data.x->has_been_visible)
8117 x_check_fullscreen (f);
8118 #ifndef USE_GTK
8119 /* For systems that cannot synthesize `skip_taskbar' for
8120 unmapped windows do the following. */
8121 if (FRAME_SKIP_TASKBAR (f))
8122 x_set_skip_taskbar (f, Qt, Qnil);
8123 #endif /* Not USE_GTK */
8126 if (!iconified)
8128 /* The `z-group' is reset every time a frame becomes
8129 invisible. Handle this here. */
8130 if (FRAME_Z_GROUP (f) == z_group_above)
8131 x_set_z_group (f, Qabove, Qnil);
8132 else if (FRAME_Z_GROUP (f) == z_group_below)
8133 x_set_z_group (f, Qbelow, Qnil);
8136 SET_FRAME_VISIBLE (f, 1);
8137 SET_FRAME_ICONIFIED (f, false);
8138 f->output_data.x->has_been_visible = true;
8140 if (iconified)
8142 inev.ie.kind = DEICONIFY_EVENT;
8143 XSETFRAME (inev.ie.frame_or_window, f);
8145 else if (! NILP (Vframe_list) && ! NILP (XCDR (Vframe_list)))
8146 /* Force a redisplay sooner or later to update the
8147 frame titles in case this is the second frame. */
8148 record_asynch_buffer_change ();
8150 goto OTHER;
8152 case KeyPress:
8154 x_display_set_last_user_time (dpyinfo, event->xkey.time);
8155 ignore_next_mouse_click_timeout = 0;
8157 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
8158 /* Dispatch KeyPress events when in menu. */
8159 if (popup_activated ())
8160 goto OTHER;
8161 #endif
8163 f = any;
8165 /* If mouse-highlight is an integer, input clears out
8166 mouse highlighting. */
8167 if (!hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight)
8168 #if ! defined (USE_GTK)
8169 && (f == 0
8170 || !EQ (f->tool_bar_window, hlinfo->mouse_face_window))
8171 #endif
8174 clear_mouse_face (hlinfo);
8175 hlinfo->mouse_face_hidden = true;
8178 #if defined USE_MOTIF && defined USE_TOOLKIT_SCROLL_BARS
8179 if (f == 0)
8181 /* Scroll bars consume key events, but we want
8182 the keys to go to the scroll bar's frame. */
8183 Widget widget = XtWindowToWidget (dpyinfo->display,
8184 event->xkey.window);
8185 if (widget && XmIsScrollBar (widget))
8187 widget = XtParent (widget);
8188 f = x_any_window_to_frame (dpyinfo, XtWindow (widget));
8191 #endif /* USE_MOTIF and USE_TOOLKIT_SCROLL_BARS */
8193 if (f != 0)
8195 KeySym keysym, orig_keysym;
8196 /* al%imercury@uunet.uu.net says that making this 81
8197 instead of 80 fixed a bug whereby meta chars made
8198 his Emacs hang.
8200 It seems that some version of XmbLookupString has
8201 a bug of not returning XBufferOverflow in
8202 status_return even if the input is too long to
8203 fit in 81 bytes. So, we must prepare sufficient
8204 bytes for copy_buffer. 513 bytes (256 chars for
8205 two-byte character set) seems to be a fairly good
8206 approximation. -- 2000.8.10 handa@etl.go.jp */
8207 unsigned char copy_buffer[513];
8208 unsigned char *copy_bufptr = copy_buffer;
8209 int copy_bufsiz = sizeof (copy_buffer);
8210 int modifiers;
8211 Lisp_Object coding_system = Qlatin_1;
8212 Lisp_Object c;
8213 /* Event will be modified. */
8214 XKeyEvent xkey = event->xkey;
8216 #ifdef USE_GTK
8217 /* Don't pass keys to GTK. A Tab will shift focus to the
8218 tool bar in GTK 2.4. Keys will still go to menus and
8219 dialogs because in that case popup_activated is nonzero
8220 (see above). */
8221 *finish = X_EVENT_DROP;
8222 #endif
8224 xkey.state |= x_emacs_to_x_modifiers (FRAME_DISPLAY_INFO (f),
8225 extra_keyboard_modifiers);
8226 modifiers = xkey.state;
8228 /* This will have to go some day... */
8230 /* make_lispy_event turns chars into control chars.
8231 Don't do it here because XLookupString is too eager. */
8232 xkey.state &= ~ControlMask;
8233 xkey.state &= ~(dpyinfo->meta_mod_mask
8234 | dpyinfo->super_mod_mask
8235 | dpyinfo->hyper_mod_mask
8236 | dpyinfo->alt_mod_mask);
8238 /* In case Meta is ComposeCharacter,
8239 clear its status. According to Markus Ehrnsperger
8240 Markus.Ehrnsperger@lehrstuhl-bross.physik.uni-muenchen.de
8241 this enables ComposeCharacter to work whether or
8242 not it is combined with Meta. */
8243 if (modifiers & dpyinfo->meta_mod_mask)
8244 memset (&compose_status, 0, sizeof (compose_status));
8246 #ifdef HAVE_X_I18N
8247 if (FRAME_XIC (f))
8249 Status status_return;
8251 coding_system = Vlocale_coding_system;
8252 nbytes = XmbLookupString (FRAME_XIC (f),
8253 &xkey, (char *) copy_bufptr,
8254 copy_bufsiz, &keysym,
8255 &status_return);
8256 if (status_return == XBufferOverflow)
8258 copy_bufsiz = nbytes + 1;
8259 copy_bufptr = alloca (copy_bufsiz);
8260 nbytes = XmbLookupString (FRAME_XIC (f),
8261 &xkey, (char *) copy_bufptr,
8262 copy_bufsiz, &keysym,
8263 &status_return);
8265 /* Xutf8LookupString is a new but already deprecated interface. -stef */
8266 if (status_return == XLookupNone)
8267 break;
8268 else if (status_return == XLookupChars)
8270 keysym = NoSymbol;
8271 modifiers = 0;
8273 else if (status_return != XLookupKeySym
8274 && status_return != XLookupBoth)
8275 emacs_abort ();
8277 else
8278 nbytes = XLookupString (&xkey, (char *) copy_bufptr,
8279 copy_bufsiz, &keysym,
8280 &compose_status);
8281 #else
8282 nbytes = XLookupString (&xkey, (char *) copy_bufptr,
8283 copy_bufsiz, &keysym,
8284 &compose_status);
8285 #endif
8287 /* If not using XIM/XIC, and a compose sequence is in progress,
8288 we break here. Otherwise, chars_matched is always 0. */
8289 if (compose_status.chars_matched > 0 && nbytes == 0)
8290 break;
8292 memset (&compose_status, 0, sizeof (compose_status));
8293 orig_keysym = keysym;
8295 /* Common for all keysym input events. */
8296 XSETFRAME (inev.ie.frame_or_window, f);
8297 inev.ie.modifiers
8298 = x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO (f), modifiers);
8299 inev.ie.timestamp = xkey.time;
8301 /* First deal with keysyms which have defined
8302 translations to characters. */
8303 if (keysym >= 32 && keysym < 128)
8304 /* Avoid explicitly decoding each ASCII character. */
8306 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
8307 inev.ie.code = keysym;
8308 goto done_keysym;
8311 /* Keysyms directly mapped to Unicode characters. */
8312 if (keysym >= 0x01000000 && keysym <= 0x0110FFFF)
8314 if (keysym < 0x01000080)
8315 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
8316 else
8317 inev.ie.kind = MULTIBYTE_CHAR_KEYSTROKE_EVENT;
8318 inev.ie.code = keysym & 0xFFFFFF;
8319 goto done_keysym;
8322 /* Now non-ASCII. */
8323 if (HASH_TABLE_P (Vx_keysym_table)
8324 && (c = Fgethash (make_number (keysym),
8325 Vx_keysym_table,
8326 Qnil),
8327 NATNUMP (c)))
8329 inev.ie.kind = (SINGLE_BYTE_CHAR_P (XFASTINT (c))
8330 ? ASCII_KEYSTROKE_EVENT
8331 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
8332 inev.ie.code = XFASTINT (c);
8333 goto done_keysym;
8336 /* Random non-modifier sorts of keysyms. */
8337 if (((keysym >= XK_BackSpace && keysym <= XK_Escape)
8338 || keysym == XK_Delete
8339 #ifdef XK_ISO_Left_Tab
8340 || (keysym >= XK_ISO_Left_Tab
8341 && keysym <= XK_ISO_Enter)
8342 #endif
8343 || IsCursorKey (keysym) /* 0xff50 <= x < 0xff60 */
8344 || IsMiscFunctionKey (keysym) /* 0xff60 <= x < VARIES */
8345 #ifdef HPUX
8346 /* This recognizes the "extended function
8347 keys". It seems there's no cleaner way.
8348 Test IsModifierKey to avoid handling
8349 mode_switch incorrectly. */
8350 || (XK_Select <= keysym && keysym < XK_KP_Space)
8351 #endif
8352 #ifdef XK_dead_circumflex
8353 || orig_keysym == XK_dead_circumflex
8354 #endif
8355 #ifdef XK_dead_grave
8356 || orig_keysym == XK_dead_grave
8357 #endif
8358 #ifdef XK_dead_tilde
8359 || orig_keysym == XK_dead_tilde
8360 #endif
8361 #ifdef XK_dead_diaeresis
8362 || orig_keysym == XK_dead_diaeresis
8363 #endif
8364 #ifdef XK_dead_macron
8365 || orig_keysym == XK_dead_macron
8366 #endif
8367 #ifdef XK_dead_degree
8368 || orig_keysym == XK_dead_degree
8369 #endif
8370 #ifdef XK_dead_acute
8371 || orig_keysym == XK_dead_acute
8372 #endif
8373 #ifdef XK_dead_cedilla
8374 || orig_keysym == XK_dead_cedilla
8375 #endif
8376 #ifdef XK_dead_breve
8377 || orig_keysym == XK_dead_breve
8378 #endif
8379 #ifdef XK_dead_ogonek
8380 || orig_keysym == XK_dead_ogonek
8381 #endif
8382 #ifdef XK_dead_caron
8383 || orig_keysym == XK_dead_caron
8384 #endif
8385 #ifdef XK_dead_doubleacute
8386 || orig_keysym == XK_dead_doubleacute
8387 #endif
8388 #ifdef XK_dead_abovedot
8389 || orig_keysym == XK_dead_abovedot
8390 #endif
8391 || IsKeypadKey (keysym) /* 0xff80 <= x < 0xffbe */
8392 || IsFunctionKey (keysym) /* 0xffbe <= x < 0xffe1 */
8393 /* Any "vendor-specific" key is ok. */
8394 || (orig_keysym & (1 << 28))
8395 || (keysym != NoSymbol && nbytes == 0))
8396 && ! (IsModifierKey (orig_keysym)
8397 /* The symbols from XK_ISO_Lock
8398 to XK_ISO_Last_Group_Lock
8399 don't have real modifiers but
8400 should be treated similarly to
8401 Mode_switch by Emacs. */
8402 #if defined XK_ISO_Lock && defined XK_ISO_Last_Group_Lock
8403 || (XK_ISO_Lock <= orig_keysym
8404 && orig_keysym <= XK_ISO_Last_Group_Lock)
8405 #endif
8408 STORE_KEYSYM_FOR_DEBUG (keysym);
8409 /* make_lispy_event will convert this to a symbolic
8410 key. */
8411 inev.ie.kind = NON_ASCII_KEYSTROKE_EVENT;
8412 inev.ie.code = keysym;
8413 goto done_keysym;
8416 { /* Raw bytes, not keysym. */
8417 ptrdiff_t i;
8418 int nchars, len;
8420 for (i = 0, nchars = 0; i < nbytes; i++)
8422 if (ASCII_CHAR_P (copy_bufptr[i]))
8423 nchars++;
8424 STORE_KEYSYM_FOR_DEBUG (copy_bufptr[i]);
8427 if (nchars < nbytes)
8429 /* Decode the input data. */
8431 /* The input should be decoded with `coding_system'
8432 which depends on which X*LookupString function
8433 we used just above and the locale. */
8434 setup_coding_system (coding_system, &coding);
8435 coding.src_multibyte = false;
8436 coding.dst_multibyte = true;
8437 /* The input is converted to events, thus we can't
8438 handle composition. Anyway, there's no XIM that
8439 gives us composition information. */
8440 coding.common_flags &= ~CODING_ANNOTATION_MASK;
8442 SAFE_NALLOCA (coding.destination, MAX_MULTIBYTE_LENGTH,
8443 nbytes);
8444 coding.dst_bytes = MAX_MULTIBYTE_LENGTH * nbytes;
8445 coding.mode |= CODING_MODE_LAST_BLOCK;
8446 decode_coding_c_string (&coding, copy_bufptr, nbytes, Qnil);
8447 nbytes = coding.produced;
8448 nchars = coding.produced_char;
8449 copy_bufptr = coding.destination;
8452 /* Convert the input data to a sequence of
8453 character events. */
8454 for (i = 0; i < nbytes; i += len)
8456 int ch;
8457 if (nchars == nbytes)
8458 ch = copy_bufptr[i], len = 1;
8459 else
8460 ch = STRING_CHAR_AND_LENGTH (copy_bufptr + i, len);
8461 inev.ie.kind = (SINGLE_BYTE_CHAR_P (ch)
8462 ? ASCII_KEYSTROKE_EVENT
8463 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
8464 inev.ie.code = ch;
8465 kbd_buffer_store_buffered_event (&inev, hold_quit);
8468 count += nchars;
8470 inev.ie.kind = NO_EVENT; /* Already stored above. */
8472 if (keysym == NoSymbol)
8473 break;
8475 /* FIXME: check side effects and remove this. */
8476 ((XEvent *) event)->xkey = xkey;
8478 done_keysym:
8479 #ifdef HAVE_X_I18N
8480 /* Don't dispatch this event since XtDispatchEvent calls
8481 XFilterEvent, and two calls in a row may freeze the
8482 client. */
8483 break;
8484 #else
8485 goto OTHER;
8486 #endif
8488 case KeyRelease:
8489 x_display_set_last_user_time (dpyinfo, event->xkey.time);
8490 #ifdef HAVE_X_I18N
8491 /* Don't dispatch this event since XtDispatchEvent calls
8492 XFilterEvent, and two calls in a row may freeze the
8493 client. */
8494 break;
8495 #else
8496 goto OTHER;
8497 #endif
8499 case EnterNotify:
8500 x_display_set_last_user_time (dpyinfo, event->xcrossing.time);
8501 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
8503 f = any;
8505 if (f && x_mouse_click_focus_ignore_position)
8506 ignore_next_mouse_click_timeout = event->xmotion.time + 200;
8508 /* EnterNotify counts as mouse movement,
8509 so update things that depend on mouse position. */
8510 if (f && !f->output_data.x->hourglass_p)
8511 note_mouse_movement (f, &event->xmotion);
8512 #ifdef USE_GTK
8513 /* We may get an EnterNotify on the buttons in the toolbar. In that
8514 case we moved out of any highlighted area and need to note this. */
8515 if (!f && dpyinfo->last_mouse_glyph_frame)
8516 note_mouse_movement (dpyinfo->last_mouse_glyph_frame, &event->xmotion);
8517 #endif
8518 goto OTHER;
8520 case FocusIn:
8521 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
8522 goto OTHER;
8524 case LeaveNotify:
8525 x_display_set_last_user_time (dpyinfo, event->xcrossing.time);
8526 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
8528 f = x_top_window_to_frame (dpyinfo, event->xcrossing.window);
8529 if (f)
8531 if (f == hlinfo->mouse_face_mouse_frame)
8533 /* If we move outside the frame, then we're
8534 certainly no longer on any text in the frame. */
8535 clear_mouse_face (hlinfo);
8536 hlinfo->mouse_face_mouse_frame = 0;
8539 /* Generate a nil HELP_EVENT to cancel a help-echo.
8540 Do it only if there's something to cancel.
8541 Otherwise, the startup message is cleared when
8542 the mouse leaves the frame. */
8543 if (any_help_event_p)
8544 do_help = -1;
8546 #ifdef USE_GTK
8547 /* See comment in EnterNotify above */
8548 else if (dpyinfo->last_mouse_glyph_frame)
8549 note_mouse_movement (dpyinfo->last_mouse_glyph_frame, &event->xmotion);
8550 #endif
8551 goto OTHER;
8553 case FocusOut:
8554 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
8555 goto OTHER;
8557 case MotionNotify:
8559 x_display_set_last_user_time (dpyinfo, event->xmotion.time);
8560 previous_help_echo_string = help_echo_string;
8561 help_echo_string = Qnil;
8563 f = (x_mouse_grabbed (dpyinfo) ? dpyinfo->last_mouse_frame
8564 : x_window_to_frame (dpyinfo, event->xmotion.window));
8566 if (hlinfo->mouse_face_hidden)
8568 hlinfo->mouse_face_hidden = false;
8569 clear_mouse_face (hlinfo);
8572 #ifdef USE_GTK
8573 if (f && xg_event_is_for_scrollbar (f, event))
8574 f = 0;
8575 #endif
8576 if (f)
8578 /* Maybe generate a SELECT_WINDOW_EVENT for
8579 `mouse-autoselect-window' but don't let popup menus
8580 interfere with this (Bug#1261). */
8581 if (!NILP (Vmouse_autoselect_window)
8582 && !popup_activated ()
8583 /* Don't switch if we're currently in the minibuffer.
8584 This tries to work around problems where the
8585 minibuffer gets unselected unexpectedly, and where
8586 you then have to move your mouse all the way down to
8587 the minibuffer to select it. */
8588 && !MINI_WINDOW_P (XWINDOW (selected_window))
8589 /* With `focus-follows-mouse' non-nil create an event
8590 also when the target window is on another frame. */
8591 && (f == XFRAME (selected_frame)
8592 || !NILP (focus_follows_mouse)))
8594 static Lisp_Object last_mouse_window;
8595 Lisp_Object window = window_from_coordinates
8596 (f, event->xmotion.x, event->xmotion.y, 0, false);
8598 /* A window will be autoselected only when it is not
8599 selected now and the last mouse movement event was
8600 not in it. The remainder of the code is a bit vague
8601 wrt what a "window" is. For immediate autoselection,
8602 the window is usually the entire window but for GTK
8603 where the scroll bars don't count. For delayed
8604 autoselection the window is usually the window's text
8605 area including the margins. */
8606 if (WINDOWP (window)
8607 && !EQ (window, last_mouse_window)
8608 && !EQ (window, selected_window))
8610 inev.ie.kind = SELECT_WINDOW_EVENT;
8611 inev.ie.frame_or_window = window;
8614 /* Remember the last window where we saw the mouse. */
8615 last_mouse_window = window;
8618 if (!note_mouse_movement (f, &event->xmotion))
8619 help_echo_string = previous_help_echo_string;
8621 else
8623 #ifndef USE_TOOLKIT_SCROLL_BARS
8624 struct scroll_bar *bar
8625 = x_window_to_scroll_bar (event->xmotion.display,
8626 event->xmotion.window, 2);
8628 if (bar)
8629 x_scroll_bar_note_movement (bar, &event->xmotion);
8630 #endif /* USE_TOOLKIT_SCROLL_BARS */
8632 /* If we move outside the frame, then we're
8633 certainly no longer on any text in the frame. */
8634 clear_mouse_face (hlinfo);
8637 /* If the contents of the global variable help_echo_string
8638 has changed, generate a HELP_EVENT. */
8639 if (!NILP (help_echo_string)
8640 || !NILP (previous_help_echo_string))
8641 do_help = 1;
8642 goto OTHER;
8645 case ConfigureNotify:
8646 /* An opaque move can generate a stream of events as the window
8647 is dragged around. If the connection round trip time isn't
8648 really short, they may come faster than we can respond to
8649 them, given the multiple queries we can do to check window
8650 manager state, translate coordinates, etc.
8652 So if this ConfigureNotify is immediately followed by another
8653 for the same window, use the info from the latest update, and
8654 consider the events all handled. */
8655 /* Opaque resize may be trickier; ConfigureNotify events are
8656 mixed with Expose events for multiple windows. */
8657 configureEvent = *event;
8658 while (XPending (dpyinfo->display))
8660 XNextEvent (dpyinfo->display, &next_event);
8661 if (next_event.type != ConfigureNotify
8662 || next_event.xconfigure.window != event->xconfigure.window
8663 /* Skipping events with different sizes can lead to a
8664 mispositioned mode line at initial window creation.
8665 Only drop window motion events for now. */
8666 || next_event.xconfigure.width != event->xconfigure.width
8667 || next_event.xconfigure.height != event->xconfigure.height)
8669 XPutBackEvent (dpyinfo->display, &next_event);
8670 break;
8672 else
8673 configureEvent = next_event;
8676 f = x_top_window_to_frame (dpyinfo, configureEvent.xconfigure.window);
8677 /* Unfortunately, we need to call font_drop_xrender_surfaces for
8678 _all_ ConfigureNotify events, otherwise we miss some and
8679 flicker. Don't try to optimize these calls by looking only
8680 for size changes: that's not sufficient. We miss some
8681 surface invalidations and flicker. */
8682 block_input ();
8683 if (f && FRAME_X_DOUBLE_BUFFERED_P (f))
8684 font_drop_xrender_surfaces (f);
8685 unblock_input ();
8686 #ifdef USE_CAIRO
8687 if (f) x_cr_destroy_surface (f);
8688 #endif
8689 #ifdef USE_GTK
8690 if (!f
8691 && (f = any)
8692 && configureEvent.xconfigure.window == FRAME_X_WINDOW (f))
8694 block_input ();
8695 if (FRAME_X_DOUBLE_BUFFERED_P (f))
8696 font_drop_xrender_surfaces (f);
8697 unblock_input ();
8698 xg_frame_resized (f, configureEvent.xconfigure.width,
8699 configureEvent.xconfigure.height);
8700 #ifdef USE_CAIRO
8701 x_cr_destroy_surface (f);
8702 #endif
8703 f = 0;
8705 #endif
8706 if (f)
8708 /* Don't call x_net_wm_state for the scroll bar window.
8709 (Bug#24963, Bug#25887) */
8710 if (configureEvent.xconfigure.window == FRAME_X_WINDOW (f))
8711 x_net_wm_state (f, configureEvent.xconfigure.window);
8713 #ifdef USE_X_TOOLKIT
8714 /* Tip frames are pure X window, set size for them. */
8715 if (! NILP (tip_frame) && XFRAME (tip_frame) == f)
8717 if (FRAME_PIXEL_HEIGHT (f) != configureEvent.xconfigure.height
8718 || FRAME_PIXEL_WIDTH (f) != configureEvent.xconfigure.width)
8720 SET_FRAME_GARBAGED (f);
8722 FRAME_PIXEL_HEIGHT (f) = configureEvent.xconfigure.height;
8723 FRAME_PIXEL_WIDTH (f) = configureEvent.xconfigure.width;
8725 #endif
8727 #ifndef USE_X_TOOLKIT
8728 #ifndef USE_GTK
8729 int width =
8730 FRAME_PIXEL_TO_TEXT_WIDTH (f, configureEvent.xconfigure.width);
8731 int height =
8732 FRAME_PIXEL_TO_TEXT_HEIGHT (f, configureEvent.xconfigure.height);
8734 /* In the toolkit version, change_frame_size
8735 is called by the code that handles resizing
8736 of the EmacsFrame widget. */
8738 /* Even if the number of character rows and columns has
8739 not changed, the font size may have changed, so we need
8740 to check the pixel dimensions as well. */
8741 if (width != FRAME_TEXT_WIDTH (f)
8742 || height != FRAME_TEXT_HEIGHT (f)
8743 || configureEvent.xconfigure.width != FRAME_PIXEL_WIDTH (f)
8744 || configureEvent.xconfigure.height != FRAME_PIXEL_HEIGHT (f))
8746 change_frame_size (f, width, height, false, true, false, true);
8747 x_clear_under_internal_border (f);
8748 SET_FRAME_GARBAGED (f);
8749 cancel_mouse_face (f);
8751 #endif /* not USE_GTK */
8752 #endif
8754 #ifdef USE_GTK
8755 /* GTK creates windows but doesn't map them.
8756 Only get real positions when mapped. */
8757 if (FRAME_GTK_OUTER_WIDGET (f)
8758 && gtk_widget_get_mapped (FRAME_GTK_OUTER_WIDGET (f)))
8759 #endif
8761 int old_left = f->left_pos;
8762 int old_top = f->top_pos;
8763 Lisp_Object frame = Qnil;
8765 XSETFRAME (frame, f);
8767 if (!FRAME_PARENT_FRAME (f))
8768 x_real_positions (f, &f->left_pos, &f->top_pos);
8769 else
8771 Window root;
8772 unsigned int dummy_uint;
8774 block_input ();
8775 XGetGeometry (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8776 &root, &f->left_pos, &f->top_pos,
8777 &dummy_uint, &dummy_uint, &dummy_uint, &dummy_uint);
8778 unblock_input ();
8781 if (old_left != f->left_pos || old_top != f->top_pos)
8783 inev.ie.kind = MOVE_FRAME_EVENT;
8784 XSETFRAME (inev.ie.frame_or_window, f);
8789 #ifdef HAVE_X_I18N
8790 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMStatusArea))
8791 xic_set_statusarea (f);
8792 #endif
8795 goto OTHER;
8797 case ButtonRelease:
8798 case ButtonPress:
8800 /* If we decide we want to generate an event to be seen
8801 by the rest of Emacs, we put it here. */
8802 bool tool_bar_p = false;
8804 memset (&compose_status, 0, sizeof (compose_status));
8805 dpyinfo->last_mouse_glyph_frame = NULL;
8806 x_display_set_last_user_time (dpyinfo, event->xbutton.time);
8808 if (x_mouse_grabbed (dpyinfo))
8809 f = dpyinfo->last_mouse_frame;
8810 else
8812 f = x_window_to_frame (dpyinfo, event->xbutton.window);
8814 if (f && event->xbutton.type == ButtonPress
8815 && !popup_activated ()
8816 && !x_window_to_scroll_bar (event->xbutton.display,
8817 event->xbutton.window, 2)
8818 && !FRAME_NO_ACCEPT_FOCUS (f))
8820 /* When clicking into a child frame or when clicking
8821 into a parent frame with the child frame selected and
8822 `no-accept-focus' is not set, select the clicked
8823 frame. */
8824 struct frame *hf = dpyinfo->x_highlight_frame;
8826 if (FRAME_PARENT_FRAME (f) || (hf && frame_ancestor_p (f, hf)))
8828 block_input ();
8829 XSetInputFocus (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8830 RevertToParent, CurrentTime);
8831 if (FRAME_PARENT_FRAME (f))
8832 XRaiseWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
8833 unblock_input ();
8838 #ifdef USE_GTK
8839 if (f && xg_event_is_for_scrollbar (f, event))
8840 f = 0;
8841 #endif
8842 if (f)
8844 #if ! defined (USE_GTK)
8845 /* Is this in the tool-bar? */
8846 if (WINDOWP (f->tool_bar_window)
8847 && WINDOW_TOTAL_LINES (XWINDOW (f->tool_bar_window)))
8849 Lisp_Object window;
8850 int x = event->xbutton.x;
8851 int y = event->xbutton.y;
8853 window = window_from_coordinates (f, x, y, 0, true);
8854 tool_bar_p = EQ (window, f->tool_bar_window);
8856 if (tool_bar_p && event->xbutton.button < 4)
8857 handle_tool_bar_click
8858 (f, x, y, event->xbutton.type == ButtonPress,
8859 x_x_to_emacs_modifiers (dpyinfo, event->xbutton.state));
8861 #endif /* !USE_GTK */
8863 if (!tool_bar_p)
8864 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
8865 if (! popup_activated ())
8866 #endif
8868 if (ignore_next_mouse_click_timeout)
8870 if (event->type == ButtonPress
8871 && event->xbutton.time > ignore_next_mouse_click_timeout)
8873 ignore_next_mouse_click_timeout = 0;
8874 construct_mouse_click (&inev.ie, &event->xbutton, f);
8876 if (event->type == ButtonRelease)
8877 ignore_next_mouse_click_timeout = 0;
8879 else
8880 construct_mouse_click (&inev.ie, &event->xbutton, f);
8882 if (FRAME_X_EMBEDDED_P (f))
8883 xembed_send_message (f, event->xbutton.time,
8884 XEMBED_REQUEST_FOCUS, 0, 0, 0);
8886 else
8888 struct scroll_bar *bar
8889 = x_window_to_scroll_bar (event->xbutton.display,
8890 event->xbutton.window, 2);
8892 #ifdef USE_TOOLKIT_SCROLL_BARS
8893 /* Make the "Ctrl-Mouse-2 splits window" work for toolkit
8894 scroll bars. */
8895 if (bar && event->xbutton.state & ControlMask)
8897 x_scroll_bar_handle_click (bar, event, &inev.ie);
8898 *finish = X_EVENT_DROP;
8900 #else /* not USE_TOOLKIT_SCROLL_BARS */
8901 if (bar)
8902 x_scroll_bar_handle_click (bar, event, &inev.ie);
8903 #endif /* not USE_TOOLKIT_SCROLL_BARS */
8906 if (event->type == ButtonPress)
8908 dpyinfo->grabbed |= (1 << event->xbutton.button);
8909 dpyinfo->last_mouse_frame = f;
8910 #if ! defined (USE_GTK)
8911 if (f && !tool_bar_p)
8912 f->last_tool_bar_item = -1;
8913 #endif /* not USE_GTK */
8915 else
8916 dpyinfo->grabbed &= ~(1 << event->xbutton.button);
8918 /* Ignore any mouse motion that happened before this event;
8919 any subsequent mouse-movement Emacs events should reflect
8920 only motion after the ButtonPress/Release. */
8921 if (f != 0)
8922 f->mouse_moved = false;
8924 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
8925 f = x_menubar_window_to_frame (dpyinfo, event);
8926 /* For a down-event in the menu bar,
8927 don't pass it to Xt right now.
8928 Instead, save it away
8929 and we will pass it to Xt from kbd_buffer_get_event.
8930 That way, we can run some Lisp code first. */
8931 if (! popup_activated ()
8932 #ifdef USE_GTK
8933 /* Gtk+ menus only react to the first three buttons. */
8934 && event->xbutton.button < 3
8935 #endif
8936 && f && event->type == ButtonPress
8937 /* Verify the event is really within the menu bar
8938 and not just sent to it due to grabbing. */
8939 && event->xbutton.x >= 0
8940 && event->xbutton.x < FRAME_PIXEL_WIDTH (f)
8941 && event->xbutton.y >= 0
8942 && event->xbutton.y < FRAME_MENUBAR_HEIGHT (f)
8943 && event->xbutton.same_screen)
8945 if (!f->output_data.x->saved_menu_event)
8946 f->output_data.x->saved_menu_event = xmalloc (sizeof *event);
8947 *f->output_data.x->saved_menu_event = *event;
8948 inev.ie.kind = MENU_BAR_ACTIVATE_EVENT;
8949 XSETFRAME (inev.ie.frame_or_window, f);
8950 *finish = X_EVENT_DROP;
8952 else
8953 goto OTHER;
8954 #endif /* USE_X_TOOLKIT || USE_GTK */
8956 break;
8958 case CirculateNotify:
8959 goto OTHER;
8961 case CirculateRequest:
8962 goto OTHER;
8964 case VisibilityNotify:
8965 goto OTHER;
8967 case MappingNotify:
8968 /* Someone has changed the keyboard mapping - update the
8969 local cache. */
8970 switch (event->xmapping.request)
8972 case MappingModifier:
8973 x_find_modifier_meanings (dpyinfo);
8974 FALLTHROUGH;
8975 case MappingKeyboard:
8976 XRefreshKeyboardMapping ((XMappingEvent *) &event->xmapping);
8978 goto OTHER;
8980 case DestroyNotify:
8981 xft_settings_event (dpyinfo, event);
8982 break;
8984 default:
8985 OTHER:
8986 #ifdef USE_X_TOOLKIT
8987 block_input ();
8988 if (*finish != X_EVENT_DROP)
8989 XtDispatchEvent ((XEvent *) event);
8990 unblock_input ();
8991 #endif /* USE_X_TOOLKIT */
8992 break;
8995 done:
8996 if (inev.ie.kind != NO_EVENT)
8998 kbd_buffer_store_buffered_event (&inev, hold_quit);
8999 count++;
9002 if (do_help
9003 && !(hold_quit && hold_quit->kind != NO_EVENT))
9005 Lisp_Object frame;
9007 if (f)
9008 XSETFRAME (frame, f);
9009 else
9010 frame = Qnil;
9012 if (do_help > 0)
9014 any_help_event_p = true;
9015 gen_help_event (help_echo_string, frame, help_echo_window,
9016 help_echo_object, help_echo_pos);
9018 else
9020 help_echo_string = Qnil;
9021 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
9023 count++;
9026 /* Sometimes event processing draws to the frame outside redisplay.
9027 To ensure that these changes become visible, draw them here. */
9028 flush_dirty_back_buffers ();
9029 SAFE_FREE ();
9030 return count;
9033 /* Handles the XEvent EVENT on display DISPLAY.
9034 This is used for event loops outside the normal event handling,
9035 i.e. looping while a popup menu or a dialog is posted.
9037 Returns the value handle_one_xevent sets in the finish argument. */
9039 x_dispatch_event (XEvent *event, Display *display)
9041 struct x_display_info *dpyinfo;
9042 int finish = X_EVENT_NORMAL;
9044 dpyinfo = x_display_info_for_display (display);
9046 if (dpyinfo)
9047 handle_one_xevent (dpyinfo, event, &finish, 0);
9049 return finish;
9052 /* Read events coming from the X server.
9053 Return as soon as there are no more events to be read.
9055 Return the number of characters stored into the buffer,
9056 thus pretending to be `read' (except the characters we store
9057 in the keyboard buffer can be multibyte, so are not necessarily
9058 C chars). */
9060 static int
9061 XTread_socket (struct terminal *terminal, struct input_event *hold_quit)
9063 int count = 0;
9064 bool event_found = false;
9065 struct x_display_info *dpyinfo = terminal->display_info.x;
9067 block_input ();
9069 /* For debugging, this gives a way to fake an I/O error. */
9070 if (dpyinfo == XTread_socket_fake_io_error)
9072 XTread_socket_fake_io_error = 0;
9073 x_io_error_quitter (dpyinfo->display);
9076 #ifndef USE_GTK
9077 while (XPending (dpyinfo->display))
9079 int finish;
9080 XEvent event;
9082 XNextEvent (dpyinfo->display, &event);
9084 #ifdef HAVE_X_I18N
9085 /* Filter events for the current X input method. */
9086 if (x_filter_event (dpyinfo, &event))
9087 continue;
9088 #endif
9089 event_found = true;
9091 count += handle_one_xevent (dpyinfo, &event, &finish, hold_quit);
9093 if (finish == X_EVENT_GOTO_OUT)
9094 break;
9097 #else /* USE_GTK */
9099 /* For GTK we must use the GTK event loop. But XEvents gets passed
9100 to our filter function above, and then to the big event switch.
9101 We use a bunch of globals to communicate with our filter function,
9102 that is kind of ugly, but it works.
9104 There is no way to do one display at the time, GTK just does events
9105 from all displays. */
9107 while (gtk_events_pending ())
9109 current_count = count;
9110 current_hold_quit = hold_quit;
9112 gtk_main_iteration ();
9114 count = current_count;
9115 current_count = -1;
9116 current_hold_quit = 0;
9118 if (current_finish == X_EVENT_GOTO_OUT)
9119 break;
9121 #endif /* USE_GTK */
9123 /* On some systems, an X bug causes Emacs to get no more events
9124 when the window is destroyed. Detect that. (1994.) */
9125 if (! event_found)
9127 /* Emacs and the X Server eats up CPU time if XNoOp is done every time.
9128 One XNOOP in 100 loops will make Emacs terminate.
9129 B. Bretthauer, 1994 */
9130 x_noop_count++;
9131 if (x_noop_count >= 100)
9133 x_noop_count=0;
9135 if (next_noop_dpyinfo == 0)
9136 next_noop_dpyinfo = x_display_list;
9138 XNoOp (next_noop_dpyinfo->display);
9140 /* Each time we get here, cycle through the displays now open. */
9141 next_noop_dpyinfo = next_noop_dpyinfo->next;
9145 /* If the focus was just given to an auto-raising frame,
9146 raise it now. FIXME: handle more than one such frame. */
9147 if (dpyinfo->x_pending_autoraise_frame)
9149 x_raise_frame (dpyinfo->x_pending_autoraise_frame);
9150 dpyinfo->x_pending_autoraise_frame = NULL;
9153 unblock_input ();
9155 return count;
9161 /***********************************************************************
9162 Text Cursor
9163 ***********************************************************************/
9165 /* Set clipping for output in glyph row ROW. W is the window in which
9166 we operate. GC is the graphics context to set clipping in.
9168 ROW may be a text row or, e.g., a mode line. Text rows must be
9169 clipped to the interior of the window dedicated to text display,
9170 mode lines must be clipped to the whole window. */
9172 static void
9173 x_clip_to_row (struct window *w, struct glyph_row *row,
9174 enum glyph_row_area area, GC gc)
9176 struct frame *f = XFRAME (WINDOW_FRAME (w));
9177 XRectangle clip_rect;
9178 int window_x, window_y, window_width;
9180 window_box (w, area, &window_x, &window_y, &window_width, 0);
9182 clip_rect.x = window_x;
9183 clip_rect.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
9184 clip_rect.y = max (clip_rect.y, window_y);
9185 clip_rect.width = window_width;
9186 clip_rect.height = row->visible_height;
9188 x_set_clip_rectangles (f, gc, &clip_rect, 1);
9192 /* Draw a hollow box cursor on window W in glyph row ROW. */
9194 static void
9195 x_draw_hollow_cursor (struct window *w, struct glyph_row *row)
9197 struct frame *f = XFRAME (WINDOW_FRAME (w));
9198 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
9199 Display *dpy = FRAME_X_DISPLAY (f);
9200 int x, y, wd, h;
9201 XGCValues xgcv;
9202 struct glyph *cursor_glyph;
9203 GC gc;
9205 /* Get the glyph the cursor is on. If we can't tell because
9206 the current matrix is invalid or such, give up. */
9207 cursor_glyph = get_phys_cursor_glyph (w);
9208 if (cursor_glyph == NULL)
9209 return;
9211 /* Compute frame-relative coordinates for phys cursor. */
9212 get_phys_cursor_geometry (w, row, cursor_glyph, &x, &y, &h);
9213 wd = w->phys_cursor_width - 1;
9215 /* The foreground of cursor_gc is typically the same as the normal
9216 background color, which can cause the cursor box to be invisible. */
9217 xgcv.foreground = f->output_data.x->cursor_pixel;
9218 if (dpyinfo->scratch_cursor_gc)
9219 XChangeGC (dpy, dpyinfo->scratch_cursor_gc, GCForeground, &xgcv);
9220 else
9221 dpyinfo->scratch_cursor_gc = XCreateGC (dpy, FRAME_X_DRAWABLE (f),
9222 GCForeground, &xgcv);
9223 gc = dpyinfo->scratch_cursor_gc;
9225 /* When on R2L character, show cursor at the right edge of the
9226 glyph, unless the cursor box is as wide as the glyph or wider
9227 (the latter happens when x-stretch-cursor is non-nil). */
9228 if ((cursor_glyph->resolved_level & 1) != 0
9229 && cursor_glyph->pixel_width > wd)
9231 x += cursor_glyph->pixel_width - wd;
9232 if (wd > 0)
9233 wd -= 1;
9235 /* Set clipping, draw the rectangle, and reset clipping again. */
9236 x_clip_to_row (w, row, TEXT_AREA, gc);
9237 x_draw_rectangle (f, gc, x, y, wd, h - 1);
9238 x_reset_clip_rectangles (f, gc);
9242 /* Draw a bar cursor on window W in glyph row ROW.
9244 Implementation note: One would like to draw a bar cursor with an
9245 angle equal to the one given by the font property XA_ITALIC_ANGLE.
9246 Unfortunately, I didn't find a font yet that has this property set.
9247 --gerd. */
9249 static void
9250 x_draw_bar_cursor (struct window *w, struct glyph_row *row, int width, enum text_cursor_kinds kind)
9252 struct frame *f = XFRAME (w->frame);
9253 struct glyph *cursor_glyph;
9255 /* If cursor is out of bounds, don't draw garbage. This can happen
9256 in mini-buffer windows when switching between echo area glyphs
9257 and mini-buffer. */
9258 cursor_glyph = get_phys_cursor_glyph (w);
9259 if (cursor_glyph == NULL)
9260 return;
9262 /* Experimental avoidance of cursor on xwidget. */
9263 if (cursor_glyph->type == XWIDGET_GLYPH)
9264 return;
9266 /* If on an image, draw like a normal cursor. That's usually better
9267 visible than drawing a bar, esp. if the image is large so that
9268 the bar might not be in the window. */
9269 if (cursor_glyph->type == IMAGE_GLYPH)
9271 struct glyph_row *r;
9272 r = MATRIX_ROW (w->current_matrix, w->phys_cursor.vpos);
9273 draw_phys_cursor_glyph (w, r, DRAW_CURSOR);
9275 else
9277 Display *dpy = FRAME_X_DISPLAY (f);
9278 Drawable drawable = FRAME_X_DRAWABLE (f);
9279 GC gc = FRAME_DISPLAY_INFO (f)->scratch_cursor_gc;
9280 unsigned long mask = GCForeground | GCBackground | GCGraphicsExposures;
9281 struct face *face = FACE_FROM_ID (f, cursor_glyph->face_id);
9282 XGCValues xgcv;
9284 /* If the glyph's background equals the color we normally draw
9285 the bars cursor in, the bar cursor in its normal color is
9286 invisible. Use the glyph's foreground color instead in this
9287 case, on the assumption that the glyph's colors are chosen so
9288 that the glyph is legible. */
9289 if (face->background == f->output_data.x->cursor_pixel)
9290 xgcv.background = xgcv.foreground = face->foreground;
9291 else
9292 xgcv.background = xgcv.foreground = f->output_data.x->cursor_pixel;
9293 xgcv.graphics_exposures = False;
9295 if (gc)
9296 XChangeGC (dpy, gc, mask, &xgcv);
9297 else
9299 gc = XCreateGC (dpy, drawable, mask, &xgcv);
9300 FRAME_DISPLAY_INFO (f)->scratch_cursor_gc = gc;
9303 x_clip_to_row (w, row, TEXT_AREA, gc);
9305 if (kind == BAR_CURSOR)
9307 int x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
9309 if (width < 0)
9310 width = FRAME_CURSOR_WIDTH (f);
9311 width = min (cursor_glyph->pixel_width, width);
9313 w->phys_cursor_width = width;
9315 /* If the character under cursor is R2L, draw the bar cursor
9316 on the right of its glyph, rather than on the left. */
9317 if ((cursor_glyph->resolved_level & 1) != 0)
9318 x += cursor_glyph->pixel_width - width;
9320 x_fill_rectangle (f, gc, x,
9321 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y),
9322 width, row->height);
9324 else /* HBAR_CURSOR */
9326 int dummy_x, dummy_y, dummy_h;
9327 int x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
9329 if (width < 0)
9330 width = row->height;
9332 width = min (row->height, width);
9334 get_phys_cursor_geometry (w, row, cursor_glyph, &dummy_x,
9335 &dummy_y, &dummy_h);
9337 if ((cursor_glyph->resolved_level & 1) != 0
9338 && cursor_glyph->pixel_width > w->phys_cursor_width - 1)
9339 x += cursor_glyph->pixel_width - w->phys_cursor_width + 1;
9340 x_fill_rectangle (f, gc, x,
9341 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y +
9342 row->height - width),
9343 w->phys_cursor_width - 1, width);
9346 x_reset_clip_rectangles (f, gc);
9351 /* RIF: Define cursor CURSOR on frame F. */
9353 static void
9354 x_define_frame_cursor (struct frame *f, Cursor cursor)
9356 if (!f->pointer_invisible
9357 && f->output_data.x->current_cursor != cursor)
9358 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), cursor);
9359 f->output_data.x->current_cursor = cursor;
9363 /* RIF: Clear area on frame F. */
9365 static void
9366 x_clear_frame_area (struct frame *f, int x, int y, int width, int height)
9368 x_clear_area (f, x, y, width, height);
9372 /* RIF: Draw cursor on window W. */
9374 static void
9375 x_draw_window_cursor (struct window *w, struct glyph_row *glyph_row, int x,
9376 int y, enum text_cursor_kinds cursor_type,
9377 int cursor_width, bool on_p, bool active_p)
9379 struct frame *f = XFRAME (WINDOW_FRAME (w));
9381 if (on_p)
9383 w->phys_cursor_type = cursor_type;
9384 w->phys_cursor_on_p = true;
9386 if (glyph_row->exact_window_width_line_p
9387 && (glyph_row->reversed_p
9388 ? (w->phys_cursor.hpos < 0)
9389 : (w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])))
9391 glyph_row->cursor_in_fringe_p = true;
9392 draw_fringe_bitmap (w, glyph_row, glyph_row->reversed_p);
9394 else
9396 switch (cursor_type)
9398 case HOLLOW_BOX_CURSOR:
9399 x_draw_hollow_cursor (w, glyph_row);
9400 break;
9402 case FILLED_BOX_CURSOR:
9403 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
9404 break;
9406 case BAR_CURSOR:
9407 x_draw_bar_cursor (w, glyph_row, cursor_width, BAR_CURSOR);
9408 break;
9410 case HBAR_CURSOR:
9411 x_draw_bar_cursor (w, glyph_row, cursor_width, HBAR_CURSOR);
9412 break;
9414 case NO_CURSOR:
9415 w->phys_cursor_width = 0;
9416 break;
9418 default:
9419 emacs_abort ();
9423 #ifdef HAVE_X_I18N
9424 if (w == XWINDOW (f->selected_window))
9425 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMPreeditPosition))
9426 xic_set_preeditarea (w, x, y);
9427 #endif
9430 XFlush (FRAME_X_DISPLAY (f));
9434 /* Icons. */
9436 /* Make the x-window of frame F use the gnu icon bitmap. */
9438 bool
9439 x_bitmap_icon (struct frame *f, Lisp_Object file)
9441 ptrdiff_t bitmap_id;
9443 if (FRAME_X_WINDOW (f) == 0)
9444 return true;
9446 /* Free up our existing icon bitmap and mask if any. */
9447 if (f->output_data.x->icon_bitmap > 0)
9448 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
9449 f->output_data.x->icon_bitmap = 0;
9451 if (STRINGP (file))
9453 #ifdef USE_GTK
9454 /* Use gtk_window_set_icon_from_file () if available,
9455 It's not restricted to bitmaps */
9456 if (xg_set_icon (f, file))
9457 return false;
9458 #endif /* USE_GTK */
9459 bitmap_id = x_create_bitmap_from_file (f, file);
9460 x_create_bitmap_mask (f, bitmap_id);
9462 else
9464 /* Create the GNU bitmap and mask if necessary. */
9465 if (FRAME_DISPLAY_INFO (f)->icon_bitmap_id < 0)
9467 ptrdiff_t rc = -1;
9469 #ifdef USE_GTK
9471 if (xg_set_icon (f, xg_default_icon_file)
9472 || xg_set_icon_from_xpm_data (f, gnu_xpm_bits))
9474 FRAME_DISPLAY_INFO (f)->icon_bitmap_id = -2;
9475 return false;
9478 #elif defined (HAVE_XPM) && defined (HAVE_X_WINDOWS)
9480 rc = x_create_bitmap_from_xpm_data (f, gnu_xpm_bits);
9481 if (rc != -1)
9482 FRAME_DISPLAY_INFO (f)->icon_bitmap_id = rc;
9484 #endif
9486 /* If all else fails, use the (black and white) xbm image. */
9487 if (rc == -1)
9489 rc = x_create_bitmap_from_data (f, (char *) gnu_xbm_bits,
9490 gnu_xbm_width, gnu_xbm_height);
9491 if (rc == -1)
9492 return true;
9494 FRAME_DISPLAY_INFO (f)->icon_bitmap_id = rc;
9495 x_create_bitmap_mask (f, FRAME_DISPLAY_INFO (f)->icon_bitmap_id);
9499 /* The first time we create the GNU bitmap and mask,
9500 this increments the ref-count one extra time.
9501 As a result, the GNU bitmap and mask are never freed.
9502 That way, we don't have to worry about allocating it again. */
9503 x_reference_bitmap (f, FRAME_DISPLAY_INFO (f)->icon_bitmap_id);
9505 bitmap_id = FRAME_DISPLAY_INFO (f)->icon_bitmap_id;
9508 x_wm_set_icon_pixmap (f, bitmap_id);
9509 f->output_data.x->icon_bitmap = bitmap_id;
9511 return false;
9515 /* Make the x-window of frame F use a rectangle with text.
9516 Use ICON_NAME as the text. */
9518 bool
9519 x_text_icon (struct frame *f, const char *icon_name)
9521 if (FRAME_X_WINDOW (f) == 0)
9522 return true;
9525 XTextProperty text;
9526 text.value = (unsigned char *) icon_name;
9527 text.encoding = XA_STRING;
9528 text.format = 8;
9529 text.nitems = strlen (icon_name);
9530 XSetWMIconName (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f), &text);
9533 if (f->output_data.x->icon_bitmap > 0)
9534 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
9535 f->output_data.x->icon_bitmap = 0;
9536 x_wm_set_icon_pixmap (f, 0);
9538 return false;
9541 #define X_ERROR_MESSAGE_SIZE 200
9543 /* If non-nil, this should be a string.
9544 It means catch X errors and store the error message in this string.
9546 The reason we use a stack is that x_catch_error/x_uncatch_error can
9547 be called from a signal handler.
9550 struct x_error_message_stack {
9551 char string[X_ERROR_MESSAGE_SIZE];
9552 Display *dpy;
9553 x_special_error_handler handler;
9554 void *handler_data;
9555 struct x_error_message_stack *prev;
9557 static struct x_error_message_stack *x_error_message;
9559 /* An X error handler which stores the error message in
9560 *x_error_message. This is called from x_error_handler if
9561 x_catch_errors is in effect. */
9563 static void
9564 x_error_catcher (Display *display, XErrorEvent *event)
9566 XGetErrorText (display, event->error_code,
9567 x_error_message->string,
9568 X_ERROR_MESSAGE_SIZE);
9569 if (x_error_message->handler)
9570 x_error_message->handler (display, event, x_error_message->string,
9571 x_error_message->handler_data);
9574 /* Begin trapping X errors for display DPY. Actually we trap X errors
9575 for all displays, but DPY should be the display you are actually
9576 operating on.
9578 After calling this function, X protocol errors no longer cause
9579 Emacs to exit; instead, they are recorded in the string
9580 stored in *x_error_message.
9582 Calling x_check_errors signals an Emacs error if an X error has
9583 occurred since the last call to x_catch_errors or x_check_errors.
9585 Calling x_uncatch_errors resumes the normal error handling.
9586 Calling x_uncatch_errors_after_check is similar, but skips an XSync
9587 to the server, and should be used only immediately after
9588 x_had_errors_p or x_check_errors. */
9590 void
9591 x_catch_errors_with_handler (Display *dpy, x_special_error_handler handler,
9592 void *handler_data)
9594 struct x_error_message_stack *data = xmalloc (sizeof *data);
9596 /* Make sure any errors from previous requests have been dealt with. */
9597 XSync (dpy, False);
9599 data->dpy = dpy;
9600 data->string[0] = 0;
9601 data->handler = handler;
9602 data->handler_data = handler_data;
9603 data->prev = x_error_message;
9604 x_error_message = data;
9607 void
9608 x_catch_errors (Display *dpy)
9610 x_catch_errors_with_handler (dpy, NULL, NULL);
9613 /* Undo the last x_catch_errors call.
9614 DPY should be the display that was passed to x_catch_errors.
9616 This version should be used only if the immediately preceding
9617 X-protocol-related thing was x_check_errors or x_had_error_p, both
9618 of which issue XSync calls, so we don't need to re-sync here. */
9620 void
9621 x_uncatch_errors_after_check (void)
9623 struct x_error_message_stack *tmp;
9625 block_input ();
9626 tmp = x_error_message;
9627 x_error_message = x_error_message->prev;
9628 xfree (tmp);
9629 unblock_input ();
9632 /* Undo the last x_catch_errors call.
9633 DPY should be the display that was passed to x_catch_errors. */
9635 void
9636 x_uncatch_errors (void)
9638 struct x_error_message_stack *tmp;
9640 block_input ();
9642 /* The display may have been closed before this function is called.
9643 Check if it is still open before calling XSync. */
9644 if (x_display_info_for_display (x_error_message->dpy) != 0)
9645 XSync (x_error_message->dpy, False);
9647 tmp = x_error_message;
9648 x_error_message = x_error_message->prev;
9649 xfree (tmp);
9650 unblock_input ();
9653 /* If any X protocol errors have arrived since the last call to
9654 x_catch_errors or x_check_errors, signal an Emacs error using
9655 sprintf (a buffer, FORMAT, the x error message text) as the text. */
9657 void
9658 x_check_errors (Display *dpy, const char *format)
9660 /* Make sure to catch any errors incurred so far. */
9661 XSync (dpy, False);
9663 if (x_error_message->string[0])
9665 char string[X_ERROR_MESSAGE_SIZE];
9666 memcpy (string, x_error_message->string, X_ERROR_MESSAGE_SIZE);
9667 x_uncatch_errors ();
9668 error (format, string);
9672 /* Nonzero if we had any X protocol errors
9673 since we did x_catch_errors on DPY. */
9675 bool
9676 x_had_errors_p (Display *dpy)
9678 /* Make sure to catch any errors incurred so far. */
9679 XSync (dpy, False);
9681 return x_error_message->string[0] != 0;
9684 /* Forget about any errors we have had, since we did x_catch_errors on DPY. */
9686 void
9687 x_clear_errors (Display *dpy)
9689 x_error_message->string[0] = 0;
9692 #if false
9693 /* See comment in unwind_to_catch why calling this is a bad
9694 * idea. --lorentey */
9695 /* Close off all unclosed x_catch_errors calls. */
9697 void
9698 x_fully_uncatch_errors (void)
9700 while (x_error_message)
9701 x_uncatch_errors ();
9703 #endif
9705 #if false
9706 static unsigned int x_wire_count;
9707 x_trace_wire (void)
9709 fprintf (stderr, "Lib call: %d\n", ++x_wire_count);
9711 #endif
9714 /************************************************************************
9715 Handling X errors
9716 ************************************************************************/
9718 /* Error message passed to x_connection_closed. */
9720 static char *error_msg;
9722 /* Handle the loss of connection to display DPY. ERROR_MESSAGE is
9723 the text of an error message that lead to the connection loss. */
9725 static _Noreturn void
9726 x_connection_closed (Display *dpy, const char *error_message, bool ioerror)
9728 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
9729 Lisp_Object frame, tail;
9730 ptrdiff_t idx = SPECPDL_INDEX ();
9732 error_msg = alloca (strlen (error_message) + 1);
9733 strcpy (error_msg, error_message);
9735 /* Inhibit redisplay while frames are being deleted. */
9736 specbind (Qinhibit_redisplay, Qt);
9738 if (dpyinfo)
9740 /* Protect display from being closed when we delete the last
9741 frame on it. */
9742 dpyinfo->reference_count++;
9743 dpyinfo->terminal->reference_count++;
9745 if (ioerror) dpyinfo->display = 0;
9747 /* First delete frames whose mini-buffers are on frames
9748 that are on the dead display. */
9749 FOR_EACH_FRAME (tail, frame)
9751 Lisp_Object minibuf_frame;
9752 minibuf_frame
9753 = WINDOW_FRAME (XWINDOW (FRAME_MINIBUF_WINDOW (XFRAME (frame))));
9754 if (FRAME_X_P (XFRAME (frame))
9755 && FRAME_X_P (XFRAME (minibuf_frame))
9756 && ! EQ (frame, minibuf_frame)
9757 && FRAME_DISPLAY_INFO (XFRAME (minibuf_frame)) == dpyinfo)
9758 delete_frame (frame, Qnoelisp);
9761 /* Now delete all remaining frames on the dead display.
9762 We are now sure none of these is used as the mini-buffer
9763 for another frame that we need to delete. */
9764 FOR_EACH_FRAME (tail, frame)
9765 if (FRAME_X_P (XFRAME (frame))
9766 && FRAME_DISPLAY_INFO (XFRAME (frame)) == dpyinfo)
9768 /* Set this to t so that delete_frame won't get confused
9769 trying to find a replacement. */
9770 kset_default_minibuffer_frame (FRAME_KBOARD (XFRAME (frame)), Qt);
9771 delete_frame (frame, Qnoelisp);
9774 /* If DPYINFO is null, this means we didn't open the display in the
9775 first place, so don't try to close it. */
9776 if (dpyinfo)
9778 /* We can not call XtCloseDisplay here because it calls XSync.
9779 XSync inside the error handler apparently hangs Emacs. On
9780 current Xt versions, this isn't needed either. */
9781 #ifdef USE_GTK
9782 /* A long-standing GTK bug prevents proper disconnect handling
9783 (https://bugzilla.gnome.org/show_bug.cgi?id=85715). Once,
9784 the resulting Glib error message loop filled a user's disk.
9785 To avoid this, kill Emacs unconditionally on disconnect. */
9786 shut_down_emacs (0, Qnil);
9787 fprintf (stderr, "%s\n\
9788 When compiled with GTK, Emacs cannot recover from X disconnects.\n\
9789 This is a GTK bug: https://bugzilla.gnome.org/show_bug.cgi?id=85715\n\
9790 For details, see etc/PROBLEMS.\n",
9791 error_msg);
9792 emacs_abort ();
9793 #endif /* USE_GTK */
9795 /* Indicate that this display is dead. */
9796 dpyinfo->display = 0;
9798 dpyinfo->reference_count--;
9799 dpyinfo->terminal->reference_count--;
9800 if (dpyinfo->reference_count != 0)
9801 /* We have just closed all frames on this display. */
9802 emacs_abort ();
9805 Lisp_Object tmp;
9806 XSETTERMINAL (tmp, dpyinfo->terminal);
9807 Fdelete_terminal (tmp, Qnoelisp);
9811 if (terminal_list == 0)
9813 fprintf (stderr, "%s\n", error_msg);
9814 Fkill_emacs (make_number (70));
9815 /* NOTREACHED */
9818 totally_unblock_input ();
9820 unbind_to (idx, Qnil);
9821 clear_waiting_for_input ();
9823 /* Here, we absolutely have to use a non-local exit (e.g. signal, throw,
9824 longjmp), because returning from this function would get us back into
9825 Xlib's code which will directly call `exit'. */
9826 error ("%s", error_msg);
9829 /* We specifically use it before defining it, so that gcc doesn't inline it,
9830 otherwise gdb doesn't know how to properly put a breakpoint on it. */
9831 static void x_error_quitter (Display *, XErrorEvent *);
9833 /* This is the first-level handler for X protocol errors.
9834 It calls x_error_quitter or x_error_catcher. */
9836 static int
9837 x_error_handler (Display *display, XErrorEvent *event)
9839 #if defined USE_GTK && defined HAVE_GTK3
9840 if ((event->error_code == BadMatch || event->error_code == BadWindow)
9841 && event->request_code == X_SetInputFocus)
9843 return 0;
9845 #endif
9847 if (x_error_message)
9848 x_error_catcher (display, event);
9849 else
9850 x_error_quitter (display, event);
9851 return 0;
9854 /* This is the usual handler for X protocol errors.
9855 It kills all frames on the display that we got the error for.
9856 If that was the only one, it prints an error message and kills Emacs. */
9858 /* .gdbinit puts a breakpoint here, so make sure it is not inlined. */
9860 /* On older GCC versions, just putting x_error_quitter
9861 after x_error_handler prevents inlining into the former. */
9863 static void NO_INLINE
9864 x_error_quitter (Display *display, XErrorEvent *event)
9866 char buf[256], buf1[356];
9868 /* Ignore BadName errors. They can happen because of fonts
9869 or colors that are not defined. */
9871 if (event->error_code == BadName)
9872 return;
9874 /* Note that there is no real way portable across R3/R4 to get the
9875 original error handler. */
9877 XGetErrorText (display, event->error_code, buf, sizeof (buf));
9878 sprintf (buf1, "X protocol error: %s on protocol request %d",
9879 buf, event->request_code);
9880 x_connection_closed (display, buf1, false);
9884 /* This is the handler for X IO errors, always.
9885 It kills all frames on the display that we lost touch with.
9886 If that was the only one, it prints an error message and kills Emacs. */
9888 static _Noreturn int
9889 x_io_error_quitter (Display *display)
9891 char buf[256];
9893 snprintf (buf, sizeof buf, "Connection lost to X server '%s'",
9894 DisplayString (display));
9895 x_connection_closed (display, buf, true);
9896 assume (false);
9899 /* Changing the font of the frame. */
9901 /* Give frame F the font FONT-OBJECT as its default font. The return
9902 value is FONT-OBJECT. FONTSET is an ID of the fontset for the
9903 frame. If it is negative, generate a new fontset from
9904 FONT-OBJECT. */
9906 Lisp_Object
9907 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
9909 struct font *font = XFONT_OBJECT (font_object);
9910 int unit, font_ascent, font_descent;
9911 #ifndef USE_X_TOOLKIT
9912 int old_menu_bar_height = FRAME_MENU_BAR_HEIGHT (f);
9913 Lisp_Object fullscreen;
9914 #endif
9916 if (fontset < 0)
9917 fontset = fontset_from_font (font_object);
9918 FRAME_FONTSET (f) = fontset;
9919 if (FRAME_FONT (f) == font)
9920 /* This font is already set in frame F. There's nothing more to
9921 do. */
9922 return font_object;
9924 FRAME_FONT (f) = font;
9925 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
9926 FRAME_COLUMN_WIDTH (f) = font->average_width;
9927 get_font_ascent_descent (font, &font_ascent, &font_descent);
9928 FRAME_LINE_HEIGHT (f) = font_ascent + font_descent;
9930 #ifndef USE_X_TOOLKIT
9931 FRAME_MENU_BAR_HEIGHT (f) = FRAME_MENU_BAR_LINES (f) * FRAME_LINE_HEIGHT (f);
9932 #endif
9934 /* Compute character columns occupied by scrollbar.
9936 Don't do things differently for non-toolkit scrollbars
9937 (Bug#17163). */
9938 unit = FRAME_COLUMN_WIDTH (f);
9939 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
9940 FRAME_CONFIG_SCROLL_BAR_COLS (f)
9941 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + unit - 1) / unit;
9942 else
9943 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + unit - 1) / unit;
9945 if (FRAME_X_WINDOW (f) != 0)
9947 /* Don't change the size of a tip frame; there's no point in
9948 doing it because it's done in Fx_show_tip, and it leads to
9949 problems because the tip frame has no widget. */
9950 if (NILP (tip_frame) || XFRAME (tip_frame) != f)
9952 adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
9953 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 3,
9954 false, Qfont);
9955 #ifndef USE_X_TOOLKIT
9956 if (FRAME_MENU_BAR_HEIGHT (f) != old_menu_bar_height
9957 && !f->after_make_frame
9958 && (EQ (frame_inhibit_implied_resize, Qt)
9959 || (CONSP (frame_inhibit_implied_resize)
9960 && NILP (Fmemq (Qfont, frame_inhibit_implied_resize))))
9961 && (NILP (fullscreen = get_frame_param (f, Qfullscreen))
9962 || EQ (fullscreen, Qfullwidth)))
9963 /* If the menu bar height changes, try to keep text height
9964 constant. */
9965 adjust_frame_size
9966 (f, -1, FRAME_TEXT_HEIGHT (f) + FRAME_MENU_BAR_HEIGHT (f)
9967 - old_menu_bar_height, 1, false, Qfont);
9968 #endif /* USE_X_TOOLKIT */
9972 #ifdef HAVE_X_I18N
9973 if (FRAME_XIC (f)
9974 && (FRAME_XIC_STYLE (f) & (XIMPreeditPosition | XIMStatusArea)))
9976 block_input ();
9977 xic_set_xfontset (f, SSDATA (fontset_ascii (fontset)));
9978 unblock_input ();
9980 #endif
9982 return font_object;
9986 /***********************************************************************
9987 X Input Methods
9988 ***********************************************************************/
9990 #ifdef HAVE_X_I18N
9992 #ifdef HAVE_X11R6
9994 /* XIM destroy callback function, which is called whenever the
9995 connection to input method XIM dies. CLIENT_DATA contains a
9996 pointer to the x_display_info structure corresponding to XIM. */
9998 static void
9999 xim_destroy_callback (XIM xim, XPointer client_data, XPointer call_data)
10001 struct x_display_info *dpyinfo = (struct x_display_info *) client_data;
10002 Lisp_Object frame, tail;
10004 block_input ();
10006 /* No need to call XDestroyIC.. */
10007 FOR_EACH_FRAME (tail, frame)
10009 struct frame *f = XFRAME (frame);
10010 if (FRAME_X_P (f) && FRAME_DISPLAY_INFO (f) == dpyinfo)
10012 FRAME_XIC (f) = NULL;
10013 xic_free_xfontset (f);
10017 /* No need to call XCloseIM. */
10018 dpyinfo->xim = NULL;
10019 XFree (dpyinfo->xim_styles);
10020 unblock_input ();
10023 #endif /* HAVE_X11R6 */
10025 /* Open the connection to the XIM server on display DPYINFO.
10026 RESOURCE_NAME is the resource name Emacs uses. */
10028 static void
10029 xim_open_dpy (struct x_display_info *dpyinfo, char *resource_name)
10031 XIM xim;
10033 #ifdef HAVE_XIM
10034 if (use_xim)
10036 if (dpyinfo->xim)
10037 XCloseIM (dpyinfo->xim);
10038 xim = XOpenIM (dpyinfo->display, dpyinfo->xrdb, resource_name,
10039 emacs_class);
10040 dpyinfo->xim = xim;
10042 if (xim)
10044 #ifdef HAVE_X11R6
10045 XIMCallback destroy;
10046 #endif
10048 /* Get supported styles and XIM values. */
10049 XGetIMValues (xim, XNQueryInputStyle, &dpyinfo->xim_styles, NULL);
10051 #ifdef HAVE_X11R6
10052 destroy.callback = xim_destroy_callback;
10053 destroy.client_data = (XPointer)dpyinfo;
10054 XSetIMValues (xim, XNDestroyCallback, &destroy, NULL);
10055 #endif
10059 else
10060 #endif /* HAVE_XIM */
10061 dpyinfo->xim = NULL;
10065 #ifdef HAVE_X11R6_XIM
10067 /* XIM instantiate callback function, which is called whenever an XIM
10068 server is available. DISPLAY is the display of the XIM.
10069 CLIENT_DATA contains a pointer to an xim_inst_t structure created
10070 when the callback was registered. */
10072 static void
10073 xim_instantiate_callback (Display *display, XPointer client_data, XPointer call_data)
10075 struct xim_inst_t *xim_inst = (struct xim_inst_t *) client_data;
10076 struct x_display_info *dpyinfo = xim_inst->dpyinfo;
10078 /* We don't support multiple XIM connections. */
10079 if (dpyinfo->xim)
10080 return;
10082 xim_open_dpy (dpyinfo, xim_inst->resource_name);
10084 /* Create XIC for the existing frames on the same display, as long
10085 as they have no XIC. */
10086 if (dpyinfo->xim && dpyinfo->reference_count > 0)
10088 Lisp_Object tail, frame;
10090 block_input ();
10091 FOR_EACH_FRAME (tail, frame)
10093 struct frame *f = XFRAME (frame);
10095 if (FRAME_X_P (f)
10096 && FRAME_DISPLAY_INFO (f) == xim_inst->dpyinfo)
10097 if (FRAME_XIC (f) == NULL)
10099 create_frame_xic (f);
10100 if (FRAME_XIC_STYLE (f) & XIMStatusArea)
10101 xic_set_statusarea (f);
10102 if (FRAME_XIC_STYLE (f) & XIMPreeditPosition)
10104 struct window *w = XWINDOW (f->selected_window);
10105 xic_set_preeditarea (w, w->cursor.x, w->cursor.y);
10110 unblock_input ();
10114 #endif /* HAVE_X11R6_XIM */
10117 /* Open a connection to the XIM server on display DPYINFO.
10118 RESOURCE_NAME is the resource name for Emacs. On X11R5, open the
10119 connection only at the first time. On X11R6, open the connection
10120 in the XIM instantiate callback function. */
10122 static void
10123 xim_initialize (struct x_display_info *dpyinfo, char *resource_name)
10125 dpyinfo->xim = NULL;
10126 #ifdef HAVE_XIM
10127 if (use_xim)
10129 #ifdef HAVE_X11R6_XIM
10130 struct xim_inst_t *xim_inst = xmalloc (sizeof *xim_inst);
10131 Bool ret;
10133 dpyinfo->xim_callback_data = xim_inst;
10134 xim_inst->dpyinfo = dpyinfo;
10135 xim_inst->resource_name = xstrdup (resource_name);
10136 ret = XRegisterIMInstantiateCallback
10137 (dpyinfo->display, dpyinfo->xrdb, xim_inst->resource_name,
10138 emacs_class, xim_instantiate_callback,
10139 /* This is XPointer in XFree86 but (XPointer *)
10140 on Tru64, at least, hence the configure test. */
10141 (XRegisterIMInstantiateCallback_arg6) xim_inst);
10142 eassert (ret == True);
10143 #else /* not HAVE_X11R6_XIM */
10144 xim_open_dpy (dpyinfo, resource_name);
10145 #endif /* not HAVE_X11R6_XIM */
10147 #endif /* HAVE_XIM */
10151 /* Close the connection to the XIM server on display DPYINFO. */
10153 static void
10154 xim_close_dpy (struct x_display_info *dpyinfo)
10156 #ifdef HAVE_XIM
10157 if (use_xim)
10159 #ifdef HAVE_X11R6_XIM
10160 struct xim_inst_t *xim_inst = dpyinfo->xim_callback_data;
10162 if (dpyinfo->display)
10164 Bool ret = XUnregisterIMInstantiateCallback
10165 (dpyinfo->display, dpyinfo->xrdb, xim_inst->resource_name,
10166 emacs_class, xim_instantiate_callback,
10167 (XRegisterIMInstantiateCallback_arg6) xim_inst);
10168 eassert (ret == True);
10170 xfree (xim_inst->resource_name);
10171 xfree (xim_inst);
10172 #endif /* HAVE_X11R6_XIM */
10173 if (dpyinfo->display)
10174 XCloseIM (dpyinfo->xim);
10175 dpyinfo->xim = NULL;
10176 XFree (dpyinfo->xim_styles);
10178 #endif /* HAVE_XIM */
10181 #endif /* not HAVE_X11R6_XIM */
10185 /* Calculate the absolute position in frame F
10186 from its current recorded position values and gravity. */
10188 static void
10189 x_calc_absolute_position (struct frame *f)
10191 int flags = f->size_hint_flags;
10192 struct frame *p = FRAME_PARENT_FRAME (f);
10194 /* We have nothing to do if the current position
10195 is already for the top-left corner. */
10196 if (! ((flags & XNegative) || (flags & YNegative)))
10197 return;
10199 /* Treat negative positions as relative to the leftmost bottommost
10200 position that fits on the screen. */
10201 if ((flags & XNegative) && (f->left_pos <= 0))
10203 int width = FRAME_PIXEL_WIDTH (f);
10205 /* A frame that has been visible at least once should have outer
10206 edges. */
10207 if (f->output_data.x->has_been_visible && !p)
10209 Lisp_Object frame;
10210 Lisp_Object edges = Qnil;
10212 XSETFRAME (frame, f);
10213 edges = Fx_frame_edges (frame, Qouter_edges);
10214 if (!NILP (edges))
10215 width = (XINT (Fnth (make_number (2), edges))
10216 - XINT (Fnth (make_number (0), edges)));
10219 if (p)
10220 f->left_pos = (FRAME_PIXEL_WIDTH (p) - width - 2 * f->border_width
10221 + f->left_pos);
10222 else
10223 f->left_pos = (x_display_pixel_width (FRAME_DISPLAY_INFO (f))
10224 - width + f->left_pos);
10228 if ((flags & YNegative) && (f->top_pos <= 0))
10230 int height = FRAME_PIXEL_HEIGHT (f);
10232 #if defined USE_X_TOOLKIT && defined USE_MOTIF
10233 /* Something is fishy here. When using Motif, starting Emacs with
10234 `-g -0-0', the frame appears too low by a few pixels.
10236 This seems to be so because initially, while Emacs is starting,
10237 the column widget's height and the frame's pixel height are
10238 different. The column widget's height is the right one. In
10239 later invocations, when Emacs is up, the frame's pixel height
10240 is right, though.
10242 It's not obvious where the initial small difference comes from.
10243 2000-12-01, gerd. */
10245 XtVaGetValues (f->output_data.x->column_widget, XtNheight, &height, NULL);
10246 #endif
10248 if (f->output_data.x->has_been_visible && !p)
10250 Lisp_Object frame;
10251 Lisp_Object edges = Qnil;
10253 XSETFRAME (frame, f);
10254 if (NILP (edges))
10255 edges = Fx_frame_edges (frame, Qouter_edges);
10256 if (!NILP (edges))
10257 height = (XINT (Fnth (make_number (3), edges))
10258 - XINT (Fnth (make_number (1), edges)));
10261 if (p)
10262 f->top_pos = (FRAME_PIXEL_HEIGHT (p) - height - 2 * f->border_width
10263 + f->top_pos);
10264 else
10265 f->top_pos = (x_display_pixel_height (FRAME_DISPLAY_INFO (f))
10266 - height + f->top_pos);
10269 /* The left_pos and top_pos
10270 are now relative to the top and left screen edges,
10271 so the flags should correspond. */
10272 f->size_hint_flags &= ~ (XNegative | YNegative);
10275 /* CHANGE_GRAVITY is 1 when calling from Fset_frame_position,
10276 to really change the position, and 0 when calling from
10277 x_make_frame_visible (in that case, XOFF and YOFF are the current
10278 position values). It is -1 when calling from x_set_frame_parameters,
10279 which means, do adjust for borders but don't change the gravity. */
10281 void
10282 x_set_offset (struct frame *f, register int xoff, register int yoff, int change_gravity)
10284 int modified_top, modified_left;
10286 if (change_gravity > 0)
10288 f->top_pos = yoff;
10289 f->left_pos = xoff;
10290 f->size_hint_flags &= ~ (XNegative | YNegative);
10291 if (xoff < 0)
10292 f->size_hint_flags |= XNegative;
10293 if (yoff < 0)
10294 f->size_hint_flags |= YNegative;
10295 f->win_gravity = NorthWestGravity;
10298 x_calc_absolute_position (f);
10300 block_input ();
10301 x_wm_set_size_hint (f, 0, false);
10303 #ifdef USE_GTK
10304 if (x_gtk_use_window_move)
10306 /* When a position change was requested and the outer GTK widget
10307 has been realized already, leave it to gtk_window_move to DTRT
10308 and return. Used for Bug#25851 and Bug#25943. */
10309 if (change_gravity != 0 && FRAME_GTK_OUTER_WIDGET (f))
10310 gtk_window_move (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)),
10311 f->left_pos, f->top_pos);
10312 unblock_input ();
10313 return;
10315 #endif /* USE_GTK */
10317 modified_left = f->left_pos;
10318 modified_top = f->top_pos;
10320 if (change_gravity != 0 && FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A)
10322 /* Some WMs (twm, wmaker at least) has an offset that is smaller
10323 than the WM decorations. So we use the calculated offset instead
10324 of the WM decoration sizes here (x/y_pixels_outer_diff). */
10325 modified_left += FRAME_X_OUTPUT (f)->move_offset_left;
10326 modified_top += FRAME_X_OUTPUT (f)->move_offset_top;
10329 #ifdef USE_GTK
10330 gtk_window_move (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)),
10331 modified_left, modified_top);
10332 #else
10333 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
10334 modified_left, modified_top);
10335 #endif
10337 x_sync_with_move (f, f->left_pos, f->top_pos,
10338 FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN);
10340 /* change_gravity is non-zero when this function is called from Lisp to
10341 programmatically move a frame. In that case, we call
10342 x_check_expected_move to discover if we have a "Type A" or "Type B"
10343 window manager, and, for a "Type A" window manager, adjust the position
10344 of the frame.
10346 We call x_check_expected_move if a programmatic move occurred, and
10347 either the window manager type (A/B) is unknown or it is Type A but we
10348 need to compute the top/left offset adjustment for this frame. */
10350 if (change_gravity != 0
10351 && !FRAME_PARENT_FRAME (f)
10352 && (FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN
10353 || (FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A
10354 && (FRAME_X_OUTPUT (f)->move_offset_left == 0
10355 && FRAME_X_OUTPUT (f)->move_offset_top == 0))))
10356 x_check_expected_move (f, modified_left, modified_top);
10358 unblock_input ();
10361 /* Return true if _NET_SUPPORTING_WM_CHECK window exists and _NET_SUPPORTED
10362 on the root window for frame F contains ATOMNAME.
10363 This is how a WM check shall be done according to the Window Manager
10364 Specification/Extended Window Manager Hints at
10365 http://freedesktop.org/wiki/Specifications/wm-spec. */
10367 bool
10368 x_wm_supports (struct frame *f, Atom want_atom)
10370 Atom actual_type;
10371 unsigned long actual_size, bytes_remaining;
10372 int i, rc, actual_format;
10373 bool ret;
10374 Window wmcheck_window;
10375 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10376 Window target_window = dpyinfo->root_window;
10377 int max_len = 65536;
10378 Display *dpy = FRAME_X_DISPLAY (f);
10379 unsigned char *tmp_data = NULL;
10380 Atom target_type = XA_WINDOW;
10382 block_input ();
10384 x_catch_errors (dpy);
10385 rc = XGetWindowProperty (dpy, target_window,
10386 dpyinfo->Xatom_net_supporting_wm_check,
10387 0, max_len, False, target_type,
10388 &actual_type, &actual_format, &actual_size,
10389 &bytes_remaining, &tmp_data);
10391 if (rc != Success || actual_type != XA_WINDOW || x_had_errors_p (dpy))
10393 if (tmp_data) XFree (tmp_data);
10394 x_uncatch_errors ();
10395 unblock_input ();
10396 return false;
10399 wmcheck_window = *(Window *) tmp_data;
10400 XFree (tmp_data);
10402 /* Check if window exists. */
10403 XSelectInput (dpy, wmcheck_window, StructureNotifyMask);
10404 if (x_had_errors_p (dpy))
10406 x_uncatch_errors_after_check ();
10407 unblock_input ();
10408 return false;
10411 if (dpyinfo->net_supported_window != wmcheck_window)
10413 /* Window changed, reload atoms */
10414 if (dpyinfo->net_supported_atoms != NULL)
10415 XFree (dpyinfo->net_supported_atoms);
10416 dpyinfo->net_supported_atoms = NULL;
10417 dpyinfo->nr_net_supported_atoms = 0;
10418 dpyinfo->net_supported_window = 0;
10420 target_type = XA_ATOM;
10421 tmp_data = NULL;
10422 rc = XGetWindowProperty (dpy, target_window,
10423 dpyinfo->Xatom_net_supported,
10424 0, max_len, False, target_type,
10425 &actual_type, &actual_format, &actual_size,
10426 &bytes_remaining, &tmp_data);
10428 if (rc != Success || actual_type != XA_ATOM || x_had_errors_p (dpy))
10430 if (tmp_data) XFree (tmp_data);
10431 x_uncatch_errors ();
10432 unblock_input ();
10433 return false;
10436 dpyinfo->net_supported_atoms = (Atom *)tmp_data;
10437 dpyinfo->nr_net_supported_atoms = actual_size;
10438 dpyinfo->net_supported_window = wmcheck_window;
10441 ret = false;
10443 for (i = 0; !ret && i < dpyinfo->nr_net_supported_atoms; ++i)
10444 ret = dpyinfo->net_supported_atoms[i] == want_atom;
10446 x_uncatch_errors ();
10447 unblock_input ();
10449 return ret;
10452 static void
10453 set_wm_state (Lisp_Object frame, bool add, Atom atom, Atom value)
10455 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (XFRAME (frame));
10457 x_send_client_event (frame, make_number (0), frame,
10458 dpyinfo->Xatom_net_wm_state,
10459 make_number (32),
10460 /* 1 = add, 0 = remove */
10461 Fcons
10462 (make_number (add),
10463 Fcons
10464 (make_fixnum_or_float (atom),
10465 (value != 0
10466 ? list1 (make_fixnum_or_float (value))
10467 : Qnil))));
10470 void
10471 x_set_sticky (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
10473 Lisp_Object frame;
10474 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10476 XSETFRAME (frame, f);
10478 set_wm_state (frame, !NILP (new_value),
10479 dpyinfo->Xatom_net_wm_state_sticky, None);
10483 * x_set_skip_taskbar:
10485 * Set frame F's `skip-taskbar' parameter. If non-nil, this should
10486 * remove F's icon from the taskbar associated with the display of F's
10487 * window-system window and inhibit switching to F's window via
10488 * <Alt>-<TAB>. If nil, lift these restrictions.
10490 * Some window managers may not honor this parameter.
10492 void
10493 x_set_skip_taskbar (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
10495 if (!EQ (new_value, old_value))
10497 #ifdef USE_GTK
10498 xg_set_skip_taskbar (f, new_value);
10499 #else
10500 Lisp_Object frame;
10501 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10503 XSETFRAME (frame, f);
10504 set_wm_state (frame, !NILP (new_value),
10505 dpyinfo->Xatom_net_wm_state_skip_taskbar, None);
10506 #endif /* USE_GTK */
10507 FRAME_SKIP_TASKBAR (f) = !NILP (new_value);
10512 * x_set_z_group:
10514 * Set frame F's `z-group' parameter. If `above', F's window-system
10515 * window is displayed above all windows that do not have the `above'
10516 * property set. If nil, F's window is shown below all windows that
10517 * have the `above' property set and above all windows that have the
10518 * `below' property set. If `below', F's window is displayed below all
10519 * windows that do not have the `below' property set.
10521 * Some window managers may not honor this parameter.
10523 void
10524 x_set_z_group (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
10526 /* We don't care about old_value. The window manager might have
10527 reset the value without telling us. */
10528 Lisp_Object frame;
10529 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10531 XSETFRAME (frame, f);
10533 if (NILP (new_value))
10535 set_wm_state (frame, false,
10536 dpyinfo->Xatom_net_wm_state_above, None);
10537 set_wm_state (frame, false,
10538 dpyinfo->Xatom_net_wm_state_below, None);
10539 FRAME_Z_GROUP (f) = z_group_none;
10541 else if (EQ (new_value, Qabove))
10543 set_wm_state (frame, true,
10544 dpyinfo->Xatom_net_wm_state_above, None);
10545 set_wm_state (frame, false,
10546 dpyinfo->Xatom_net_wm_state_below, None);
10547 FRAME_Z_GROUP (f) = z_group_above;
10549 else if (EQ (new_value, Qbelow))
10551 set_wm_state (frame, false,
10552 dpyinfo->Xatom_net_wm_state_above, None);
10553 set_wm_state (frame, true,
10554 dpyinfo->Xatom_net_wm_state_below, None);
10555 FRAME_Z_GROUP (f) = z_group_below;
10557 else if (EQ (new_value, Qabove_suspended))
10559 set_wm_state (frame, false,
10560 dpyinfo->Xatom_net_wm_state_above, None);
10561 FRAME_Z_GROUP (f) = z_group_above_suspended;
10563 else
10564 error ("Invalid z-group specification");
10568 /* Return the current _NET_WM_STATE.
10569 SIZE_STATE is set to one of the FULLSCREEN_* values.
10570 Set *STICKY to the sticky state.
10572 Return true iff we are not hidden. */
10574 static bool
10575 get_current_wm_state (struct frame *f,
10576 Window window,
10577 int *size_state,
10578 bool *sticky)
10580 unsigned long actual_size;
10581 int i;
10582 bool is_hidden = false;
10583 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10584 long max_len = 65536;
10585 Atom target_type = XA_ATOM;
10586 /* If XCB is available, we can avoid three XSync calls. */
10587 #ifdef USE_XCB
10588 xcb_get_property_cookie_t prop_cookie;
10589 xcb_get_property_reply_t *prop;
10590 xcb_atom_t *reply_data;
10591 #else
10592 Display *dpy = FRAME_X_DISPLAY (f);
10593 unsigned long bytes_remaining;
10594 int rc, actual_format;
10595 Atom actual_type;
10596 unsigned char *tmp_data = NULL;
10597 Atom *reply_data;
10598 #endif
10600 *sticky = false;
10601 *size_state = FULLSCREEN_NONE;
10603 block_input ();
10605 #ifdef USE_XCB
10606 prop_cookie = xcb_get_property (dpyinfo->xcb_connection, 0, window,
10607 dpyinfo->Xatom_net_wm_state,
10608 target_type, 0, max_len);
10609 prop = xcb_get_property_reply (dpyinfo->xcb_connection, prop_cookie, NULL);
10610 if (prop && prop->type == target_type)
10612 int actual_bytes = xcb_get_property_value_length (prop);
10613 eassume (0 <= actual_bytes);
10614 actual_size = actual_bytes / sizeof *reply_data;
10615 reply_data = xcb_get_property_value (prop);
10617 else
10619 actual_size = 0;
10620 is_hidden = FRAME_ICONIFIED_P (f);
10622 #else
10623 x_catch_errors (dpy);
10624 rc = XGetWindowProperty (dpy, window, dpyinfo->Xatom_net_wm_state,
10625 0, max_len, False, target_type,
10626 &actual_type, &actual_format, &actual_size,
10627 &bytes_remaining, &tmp_data);
10629 if (rc == Success && actual_type == target_type && ! x_had_errors_p (dpy))
10630 reply_data = (Atom *) tmp_data;
10631 else
10633 actual_size = 0;
10634 is_hidden = FRAME_ICONIFIED_P (f);
10637 x_uncatch_errors ();
10638 #endif
10640 for (i = 0; i < actual_size; ++i)
10642 Atom a = reply_data[i];
10643 if (a == dpyinfo->Xatom_net_wm_state_hidden)
10644 is_hidden = true;
10645 else if (a == dpyinfo->Xatom_net_wm_state_maximized_horz)
10647 if (*size_state == FULLSCREEN_HEIGHT)
10648 *size_state = FULLSCREEN_MAXIMIZED;
10649 else
10650 *size_state = FULLSCREEN_WIDTH;
10652 else if (a == dpyinfo->Xatom_net_wm_state_maximized_vert)
10654 if (*size_state == FULLSCREEN_WIDTH)
10655 *size_state = FULLSCREEN_MAXIMIZED;
10656 else
10657 *size_state = FULLSCREEN_HEIGHT;
10659 else if (a == dpyinfo->Xatom_net_wm_state_fullscreen)
10660 *size_state = FULLSCREEN_BOTH;
10661 else if (a == dpyinfo->Xatom_net_wm_state_sticky)
10662 *sticky = true;
10665 #ifdef USE_XCB
10666 free (prop);
10667 #else
10668 if (tmp_data) XFree (tmp_data);
10669 #endif
10671 unblock_input ();
10672 return ! is_hidden;
10675 /* Do fullscreen as specified in extended window manager hints */
10677 static bool
10678 do_ewmh_fullscreen (struct frame *f)
10680 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10681 bool have_net_atom = x_wm_supports (f, dpyinfo->Xatom_net_wm_state);
10682 int cur;
10683 bool dummy;
10685 get_current_wm_state (f, FRAME_OUTER_WINDOW (f), &cur, &dummy);
10687 /* Some window managers don't say they support _NET_WM_STATE, but they do say
10688 they support _NET_WM_STATE_FULLSCREEN. Try that also. */
10689 if (!have_net_atom)
10690 have_net_atom = x_wm_supports (f, dpyinfo->Xatom_net_wm_state_fullscreen);
10692 if (have_net_atom && cur != f->want_fullscreen)
10694 Lisp_Object frame;
10696 XSETFRAME (frame, f);
10698 /* Keep number of calls to set_wm_state as low as possible.
10699 Some window managers, or possible Gtk+, hangs when too many
10700 are sent at once. */
10701 switch (f->want_fullscreen)
10703 case FULLSCREEN_BOTH:
10704 if (cur != FULLSCREEN_BOTH)
10705 set_wm_state (frame, true, dpyinfo->Xatom_net_wm_state_fullscreen,
10706 None);
10707 break;
10708 case FULLSCREEN_WIDTH:
10709 if (x_frame_normalize_before_maximize && cur == FULLSCREEN_MAXIMIZED)
10711 set_wm_state (frame, false,
10712 dpyinfo->Xatom_net_wm_state_maximized_horz,
10713 dpyinfo->Xatom_net_wm_state_maximized_vert);
10714 set_wm_state (frame, true,
10715 dpyinfo->Xatom_net_wm_state_maximized_horz, None);
10717 else
10719 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_HEIGHT
10720 || cur == FULLSCREEN_MAXIMIZED)
10721 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
10722 dpyinfo->Xatom_net_wm_state_maximized_vert);
10723 if (cur != FULLSCREEN_MAXIMIZED || x_frame_normalize_before_maximize)
10724 set_wm_state (frame, true,
10725 dpyinfo->Xatom_net_wm_state_maximized_horz, None);
10727 break;
10728 case FULLSCREEN_HEIGHT:
10729 if (x_frame_normalize_before_maximize && cur == FULLSCREEN_MAXIMIZED)
10731 set_wm_state (frame, false,
10732 dpyinfo->Xatom_net_wm_state_maximized_horz,
10733 dpyinfo->Xatom_net_wm_state_maximized_vert);
10734 set_wm_state (frame, true,
10735 dpyinfo->Xatom_net_wm_state_maximized_vert, None);
10737 else
10739 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_WIDTH
10740 || cur == FULLSCREEN_MAXIMIZED)
10741 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
10742 dpyinfo->Xatom_net_wm_state_maximized_horz);
10743 if (cur != FULLSCREEN_MAXIMIZED || x_frame_normalize_before_maximize)
10744 set_wm_state (frame, true,
10745 dpyinfo->Xatom_net_wm_state_maximized_vert, None);
10747 break;
10748 case FULLSCREEN_MAXIMIZED:
10749 if (x_frame_normalize_before_maximize && cur == FULLSCREEN_BOTH)
10751 set_wm_state (frame, false,
10752 dpyinfo->Xatom_net_wm_state_fullscreen, None);
10753 set_wm_state (frame, true,
10754 dpyinfo->Xatom_net_wm_state_maximized_horz,
10755 dpyinfo->Xatom_net_wm_state_maximized_vert);
10757 else if (x_frame_normalize_before_maximize && cur == FULLSCREEN_WIDTH)
10759 set_wm_state (frame, false,
10760 dpyinfo->Xatom_net_wm_state_maximized_horz, None);
10761 set_wm_state (frame, true,
10762 dpyinfo->Xatom_net_wm_state_maximized_horz,
10763 dpyinfo->Xatom_net_wm_state_maximized_vert);
10765 else if (x_frame_normalize_before_maximize && cur == FULLSCREEN_HEIGHT)
10767 set_wm_state (frame, false,
10768 dpyinfo->Xatom_net_wm_state_maximized_vert, None);
10769 set_wm_state (frame, true,
10770 dpyinfo->Xatom_net_wm_state_maximized_horz,
10771 dpyinfo->Xatom_net_wm_state_maximized_vert);
10773 else
10775 if (cur == FULLSCREEN_BOTH)
10776 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
10777 None);
10778 else if (cur == FULLSCREEN_HEIGHT)
10779 set_wm_state (frame, true,
10780 dpyinfo->Xatom_net_wm_state_maximized_horz, None);
10781 else if (cur == FULLSCREEN_WIDTH)
10782 set_wm_state (frame, true, None,
10783 dpyinfo->Xatom_net_wm_state_maximized_vert);
10784 else
10785 set_wm_state (frame, true,
10786 dpyinfo->Xatom_net_wm_state_maximized_horz,
10787 dpyinfo->Xatom_net_wm_state_maximized_vert);
10789 break;
10790 case FULLSCREEN_NONE:
10791 if (cur == FULLSCREEN_BOTH)
10792 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
10793 None);
10794 else
10795 set_wm_state (frame, false,
10796 dpyinfo->Xatom_net_wm_state_maximized_horz,
10797 dpyinfo->Xatom_net_wm_state_maximized_vert);
10800 f->want_fullscreen = FULLSCREEN_NONE;
10804 return have_net_atom;
10807 static void
10808 XTfullscreen_hook (struct frame *f)
10810 if (FRAME_VISIBLE_P (f))
10812 block_input ();
10813 x_check_fullscreen (f);
10814 x_sync (f);
10815 unblock_input ();
10820 static bool
10821 x_handle_net_wm_state (struct frame *f, const XPropertyEvent *event)
10823 int value = FULLSCREEN_NONE;
10824 Lisp_Object lval;
10825 bool sticky = false;
10826 bool not_hidden = get_current_wm_state (f, event->window, &value, &sticky);
10828 lval = Qnil;
10829 switch (value)
10831 case FULLSCREEN_WIDTH:
10832 lval = Qfullwidth;
10833 break;
10834 case FULLSCREEN_HEIGHT:
10835 lval = Qfullheight;
10836 break;
10837 case FULLSCREEN_BOTH:
10838 lval = Qfullboth;
10839 break;
10840 case FULLSCREEN_MAXIMIZED:
10841 lval = Qmaximized;
10842 break;
10845 frame_size_history_add
10846 (f, Qx_handle_net_wm_state, 0, 0,
10847 list2 (get_frame_param (f, Qfullscreen), lval));
10849 store_frame_param (f, Qfullscreen, lval);
10850 store_frame_param (f, Qsticky, sticky ? Qt : Qnil);
10852 return not_hidden;
10855 /* Check if we need to resize the frame due to a fullscreen request.
10856 If so needed, resize the frame. */
10857 static void
10858 x_check_fullscreen (struct frame *f)
10860 Lisp_Object lval = Qnil;
10862 if (do_ewmh_fullscreen (f))
10863 return;
10865 if (f->output_data.x->parent_desc != FRAME_DISPLAY_INFO (f)->root_window)
10866 return; /* Only fullscreen without WM or with EWM hints (above). */
10868 /* Setting fullscreen to nil doesn't do anything. We could save the
10869 last non-fullscreen size and restore it, but it seems like a
10870 lot of work for this unusual case (no window manager running). */
10872 if (f->want_fullscreen != FULLSCREEN_NONE)
10874 int width = FRAME_PIXEL_WIDTH (f), height = FRAME_PIXEL_HEIGHT (f);
10875 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10877 switch (f->want_fullscreen)
10879 /* No difference between these two when there is no WM */
10880 case FULLSCREEN_MAXIMIZED:
10881 lval = Qmaximized;
10882 width = x_display_pixel_width (dpyinfo);
10883 height = x_display_pixel_height (dpyinfo);
10884 break;
10885 case FULLSCREEN_BOTH:
10886 lval = Qfullboth;
10887 width = x_display_pixel_width (dpyinfo);
10888 height = x_display_pixel_height (dpyinfo);
10889 break;
10890 case FULLSCREEN_WIDTH:
10891 lval = Qfullwidth;
10892 width = x_display_pixel_width (dpyinfo);
10893 height = height + FRAME_MENUBAR_HEIGHT (f);
10894 break;
10895 case FULLSCREEN_HEIGHT:
10896 lval = Qfullheight;
10897 height = x_display_pixel_height (dpyinfo);
10898 break;
10899 default:
10900 emacs_abort ();
10903 frame_size_history_add
10904 (f, Qx_check_fullscreen, width, height, Qnil);
10906 x_wm_set_size_hint (f, 0, false);
10908 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
10909 width, height);
10911 if (FRAME_VISIBLE_P (f))
10912 x_wait_for_event (f, ConfigureNotify);
10913 else
10915 change_frame_size (f, width, height - FRAME_MENUBAR_HEIGHT (f),
10916 false, true, false, true);
10917 x_sync (f);
10921 /* `x_net_wm_state' might have reset the fullscreen frame parameter,
10922 restore it. */
10923 store_frame_param (f, Qfullscreen, lval);
10926 /* This function is called by x_set_offset to determine whether the window
10927 manager interfered with the positioning of the frame. Type A window
10928 managers position the surrounding window manager decorations a small
10929 amount above and left of the user-supplied position. Type B window
10930 managers position the surrounding window manager decorations at the
10931 user-specified position. If we detect a Type A window manager, we
10932 compensate by moving the window right and down by the proper amount. */
10934 static void
10935 x_check_expected_move (struct frame *f, int expected_left, int expected_top)
10937 int current_left = 0, current_top = 0;
10939 /* x_real_positions returns the left and top offsets of the outermost
10940 window manager window around the frame. */
10942 x_real_positions (f, &current_left, &current_top);
10944 if (current_left != expected_left || current_top != expected_top)
10946 /* It's a "Type A" window manager. */
10948 int adjusted_left;
10949 int adjusted_top;
10951 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_A;
10952 FRAME_X_OUTPUT (f)->move_offset_left = expected_left - current_left;
10953 FRAME_X_OUTPUT (f)->move_offset_top = expected_top - current_top;
10955 /* Now fix the mispositioned frame's location. */
10957 adjusted_left = expected_left + FRAME_X_OUTPUT (f)->move_offset_left;
10958 adjusted_top = expected_top + FRAME_X_OUTPUT (f)->move_offset_top;
10960 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
10961 adjusted_left, adjusted_top);
10963 x_sync_with_move (f, expected_left, expected_top, false);
10965 else
10966 /* It's a "Type B" window manager. We don't have to adjust the
10967 frame's position. */
10969 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_B;
10973 /* Wait for XGetGeometry to return up-to-date position information for a
10974 recently-moved frame. Call this immediately after calling XMoveWindow.
10975 If FUZZY is non-zero, then LEFT and TOP are just estimates of where the
10976 frame has been moved to, so we use a fuzzy position comparison instead
10977 of an exact comparison. */
10979 static void
10980 x_sync_with_move (struct frame *f, int left, int top, bool fuzzy)
10982 int count = 0;
10984 while (count++ < 50)
10986 int current_left = 0, current_top = 0;
10988 /* In theory, this call to XSync only needs to happen once, but in
10989 practice, it doesn't seem to work, hence the need for the surrounding
10990 loop. */
10992 XSync (FRAME_X_DISPLAY (f), False);
10993 x_real_positions (f, &current_left, &current_top);
10995 if (fuzzy)
10997 /* The left fuzz-factor is 10 pixels. The top fuzz-factor is 40
10998 pixels. */
11000 if (eabs (current_left - left) <= 10
11001 && eabs (current_top - top) <= 40)
11002 return;
11004 else if (current_left == left && current_top == top)
11005 return;
11008 /* As a last resort, just wait 0.5 seconds and hope that XGetGeometry
11009 will then return up-to-date position info. */
11011 wait_reading_process_output (0, 500000000, 0, false, Qnil, NULL, 0);
11015 /* Wait for an event on frame F matching EVENTTYPE. */
11016 void
11017 x_wait_for_event (struct frame *f, int eventtype)
11019 int level = interrupt_input_blocked;
11021 fd_set fds;
11022 struct timespec tmo, tmo_at, time_now;
11023 int fd = ConnectionNumber (FRAME_X_DISPLAY (f));
11025 f->wait_event_type = eventtype;
11027 /* Set timeout to 0.1 second. Hopefully not noticeable.
11028 Maybe it should be configurable. */
11029 tmo = make_timespec (0, 100 * 1000 * 1000);
11030 tmo_at = timespec_add (current_timespec (), tmo);
11032 while (f->wait_event_type)
11034 pending_signals = true;
11035 totally_unblock_input ();
11036 /* XTread_socket is called after unblock. */
11037 block_input ();
11038 interrupt_input_blocked = level;
11040 FD_ZERO (&fds);
11041 FD_SET (fd, &fds);
11043 time_now = current_timespec ();
11044 if (timespec_cmp (tmo_at, time_now) < 0)
11045 break;
11047 tmo = timespec_sub (tmo_at, time_now);
11048 if (pselect (fd + 1, &fds, NULL, NULL, &tmo, NULL) == 0)
11049 break; /* Timeout */
11052 f->wait_event_type = 0;
11056 /* Change the size of frame F's X window to WIDTH/HEIGHT in the case F
11057 doesn't have a widget. If CHANGE_GRAVITY, change to
11058 top-left-corner window gravity for this size change and subsequent
11059 size changes. Otherwise leave the window gravity unchanged. */
11061 static void
11062 x_set_window_size_1 (struct frame *f, bool change_gravity,
11063 int width, int height)
11065 int pixelwidth = FRAME_TEXT_TO_PIXEL_WIDTH (f, width);
11066 int pixelheight = FRAME_TEXT_TO_PIXEL_HEIGHT (f, height);
11067 int old_width = FRAME_PIXEL_WIDTH (f);
11068 int old_height = FRAME_PIXEL_HEIGHT (f);
11069 Lisp_Object fullscreen = get_frame_param (f, Qfullscreen);
11071 if (change_gravity)
11072 f->win_gravity = NorthWestGravity;
11073 x_wm_set_size_hint (f, 0, false);
11075 /* When the frame is fullheight and we only want to change the width
11076 or it is fullwidth and we only want to change the height we should
11077 be able to preserve the fullscreen property. However, due to the
11078 fact that we have to send a resize request anyway, the window
11079 manager will abolish it. At least the respective size should
11080 remain unchanged but giving the frame back its normal size will
11081 be broken ... */
11082 if (EQ (fullscreen, Qfullwidth) && width == FRAME_TEXT_WIDTH (f))
11084 frame_size_history_add
11085 (f, Qx_set_window_size_1, width, height,
11086 list2 (make_number (old_height),
11087 make_number (pixelheight + FRAME_MENUBAR_HEIGHT (f))));
11089 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11090 old_width, pixelheight + FRAME_MENUBAR_HEIGHT (f));
11092 else if (EQ (fullscreen, Qfullheight) && height == FRAME_TEXT_HEIGHT (f))
11094 frame_size_history_add
11095 (f, Qx_set_window_size_2, width, height,
11096 list2 (make_number (old_width), make_number (pixelwidth)));
11098 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11099 pixelwidth, old_height);
11102 else
11104 frame_size_history_add
11105 (f, Qx_set_window_size_3, width, height,
11106 list3 (make_number (pixelwidth + FRAME_TOOLBAR_WIDTH (f)),
11107 make_number (pixelheight + FRAME_TOOLBAR_HEIGHT (f)
11108 + FRAME_MENUBAR_HEIGHT (f)),
11109 make_number (FRAME_MENUBAR_HEIGHT (f))));
11111 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11112 pixelwidth, pixelheight + FRAME_MENUBAR_HEIGHT (f));
11113 fullscreen = Qnil;
11118 /* We've set {FRAME,PIXEL}_{WIDTH,HEIGHT} to the values we hope to
11119 receive in the ConfigureNotify event; if we get what we asked
11120 for, then the event won't cause the screen to become garbaged, so
11121 we have to make sure to do it here. */
11122 SET_FRAME_GARBAGED (f);
11124 /* Now, strictly speaking, we can't be sure that this is accurate,
11125 but the window manager will get around to dealing with the size
11126 change request eventually, and we'll hear how it went when the
11127 ConfigureNotify event gets here.
11129 We could just not bother storing any of this information here,
11130 and let the ConfigureNotify event set everything up, but that
11131 might be kind of confusing to the Lisp code, since size changes
11132 wouldn't be reported in the frame parameters until some random
11133 point in the future when the ConfigureNotify event arrives.
11135 Pass true for DELAY since we can't run Lisp code inside of
11136 a BLOCK_INPUT. */
11138 /* But the ConfigureNotify may in fact never arrive, and then this is
11139 not right if the frame is visible. Instead wait (with timeout)
11140 for the ConfigureNotify. */
11141 if (FRAME_VISIBLE_P (f))
11143 x_wait_for_event (f, ConfigureNotify);
11145 if (!NILP (fullscreen))
11146 /* Try to restore fullscreen state. */
11148 store_frame_param (f, Qfullscreen, fullscreen);
11149 x_set_fullscreen (f, fullscreen, fullscreen);
11152 else
11154 change_frame_size (f, width, height, false, true, false, true);
11155 x_sync (f);
11160 /* Call this to change the size of frame F's x-window.
11161 If CHANGE_GRAVITY, change to top-left-corner window gravity
11162 for this size change and subsequent size changes.
11163 Otherwise we leave the window gravity unchanged. */
11165 void
11166 x_set_window_size (struct frame *f, bool change_gravity,
11167 int width, int height, bool pixelwise)
11169 block_input ();
11171 /* The following breaks our calculations. If it's really needed,
11172 think of something else. */
11173 #if false
11174 if (NILP (tip_frame) || XFRAME (tip_frame) != f)
11176 int text_width, text_height;
11178 /* When the frame is maximized/fullscreen or running under for
11179 example Xmonad, x_set_window_size_1 will be a no-op.
11180 In that case, the right thing to do is extend rows/width to
11181 the current frame size. We do that first if x_set_window_size_1
11182 turns out to not be a no-op (there is no way to know).
11183 The size will be adjusted again if the frame gets a
11184 ConfigureNotify event as a result of x_set_window_size. */
11185 int pixelh = FRAME_PIXEL_HEIGHT (f);
11186 #ifdef USE_X_TOOLKIT
11187 /* The menu bar is not part of text lines. The tool bar
11188 is however. */
11189 pixelh -= FRAME_MENUBAR_HEIGHT (f);
11190 #endif
11191 text_width = FRAME_PIXEL_TO_TEXT_WIDTH (f, FRAME_PIXEL_WIDTH (f));
11192 text_height = FRAME_PIXEL_TO_TEXT_HEIGHT (f, pixelh);
11194 change_frame_size (f, text_width, text_height, false, true, false, true);
11196 #endif
11198 /* Pixelize width and height, if necessary. */
11199 if (! pixelwise)
11201 width = width * FRAME_COLUMN_WIDTH (f);
11202 height = height * FRAME_LINE_HEIGHT (f);
11205 #ifdef USE_GTK
11206 if (FRAME_GTK_WIDGET (f))
11207 xg_frame_set_char_size (f, width, height);
11208 else
11209 x_set_window_size_1 (f, change_gravity, width, height);
11210 #else /* not USE_GTK */
11211 x_set_window_size_1 (f, change_gravity, width, height);
11212 x_clear_under_internal_border (f);
11213 #endif /* not USE_GTK */
11215 /* If cursor was outside the new size, mark it as off. */
11216 mark_window_cursors_off (XWINDOW (f->root_window));
11218 /* Clear out any recollection of where the mouse highlighting was,
11219 since it might be in a place that's outside the new frame size.
11220 Actually checking whether it is outside is a pain in the neck,
11221 so don't try--just let the highlighting be done afresh with new size. */
11222 cancel_mouse_face (f);
11224 unblock_input ();
11226 do_pending_window_change (false);
11229 /* Move the mouse to position pixel PIX_X, PIX_Y relative to frame F. */
11231 void
11232 frame_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
11234 block_input ();
11236 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
11237 0, 0, 0, 0, pix_x, pix_y);
11238 unblock_input ();
11241 /* Raise frame F. */
11243 void
11244 x_raise_frame (struct frame *f)
11246 block_input ();
11247 if (FRAME_VISIBLE_P (f))
11248 XRaiseWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
11249 XFlush (FRAME_X_DISPLAY (f));
11250 unblock_input ();
11253 /* Lower frame F. */
11255 static void
11256 x_lower_frame (struct frame *f)
11258 if (FRAME_VISIBLE_P (f))
11260 block_input ();
11261 XLowerWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
11262 XFlush (FRAME_X_DISPLAY (f));
11263 unblock_input ();
11267 /* Request focus with XEmbed */
11269 void
11270 xembed_request_focus (struct frame *f)
11272 /* See XEmbed Protocol Specification at
11273 http://freedesktop.org/wiki/Specifications/xembed-spec */
11274 if (FRAME_VISIBLE_P (f))
11275 xembed_send_message (f, CurrentTime,
11276 XEMBED_REQUEST_FOCUS, 0, 0, 0);
11279 /* Activate frame with Extended Window Manager Hints */
11281 void
11282 x_ewmh_activate_frame (struct frame *f)
11284 /* See Window Manager Specification/Extended Window Manager Hints at
11285 http://freedesktop.org/wiki/Specifications/wm-spec */
11287 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
11289 if (FRAME_VISIBLE_P (f) && x_wm_supports (f, dpyinfo->Xatom_net_active_window))
11291 Lisp_Object frame;
11292 XSETFRAME (frame, f);
11293 x_send_client_event (frame, make_number (0), frame,
11294 dpyinfo->Xatom_net_active_window,
11295 make_number (32),
11296 list2i (1, dpyinfo->last_user_time));
11300 static void
11301 XTframe_raise_lower (struct frame *f, bool raise_flag)
11303 if (raise_flag)
11304 x_raise_frame (f);
11305 else
11306 x_lower_frame (f);
11309 /* XEmbed implementation. */
11311 #if defined USE_X_TOOLKIT || ! defined USE_GTK
11313 /* XEmbed implementation. */
11315 #define XEMBED_VERSION 0
11317 static void
11318 xembed_set_info (struct frame *f, enum xembed_info flags)
11320 unsigned long data[2];
11321 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
11323 data[0] = XEMBED_VERSION;
11324 data[1] = flags;
11326 XChangeProperty (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11327 dpyinfo->Xatom_XEMBED_INFO, dpyinfo->Xatom_XEMBED_INFO,
11328 32, PropModeReplace, (unsigned char *) data, 2);
11330 #endif /* defined USE_X_TOOLKIT || ! defined USE_GTK */
11332 static void
11333 xembed_send_message (struct frame *f, Time t, enum xembed_message msg,
11334 long int detail, long int data1, long int data2)
11336 XEvent event;
11338 event.xclient.type = ClientMessage;
11339 event.xclient.window = FRAME_X_OUTPUT (f)->parent_desc;
11340 event.xclient.message_type = FRAME_DISPLAY_INFO (f)->Xatom_XEMBED;
11341 event.xclient.format = 32;
11342 event.xclient.data.l[0] = t;
11343 event.xclient.data.l[1] = msg;
11344 event.xclient.data.l[2] = detail;
11345 event.xclient.data.l[3] = data1;
11346 event.xclient.data.l[4] = data2;
11348 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_OUTPUT (f)->parent_desc,
11349 False, NoEventMask, &event);
11350 XSync (FRAME_X_DISPLAY (f), False);
11353 /* Change of visibility. */
11355 /* This function sends the request to make the frame visible, but may
11356 return before it the frame's visibility is changed. */
11358 void
11359 x_make_frame_visible (struct frame *f)
11361 if (FRAME_PARENT_FRAME (f))
11363 if (!FRAME_VISIBLE_P (f))
11365 block_input ();
11366 #ifdef USE_GTK
11367 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
11368 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11369 f->left_pos, f->top_pos);
11370 #else
11371 XMapRaised (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
11372 #endif
11373 unblock_input ();
11375 SET_FRAME_VISIBLE (f, true);
11376 SET_FRAME_ICONIFIED (f, false);
11378 return;
11381 block_input ();
11383 x_set_bitmap_icon (f);
11385 if (! FRAME_VISIBLE_P (f))
11387 /* We test asked_for_visible here to make sure we don't
11388 call x_set_offset a second time
11389 if we get to x_make_frame_visible a second time
11390 before the window gets really visible. */
11391 if (! FRAME_ICONIFIED_P (f)
11392 && ! FRAME_X_EMBEDDED_P (f)
11393 && ! f->output_data.x->asked_for_visible)
11394 x_set_offset (f, f->left_pos, f->top_pos, 0);
11396 f->output_data.x->asked_for_visible = true;
11398 if (! EQ (Vx_no_window_manager, Qt))
11399 x_wm_set_window_state (f, NormalState);
11400 #ifdef USE_X_TOOLKIT
11401 if (FRAME_X_EMBEDDED_P (f))
11402 xembed_set_info (f, XEMBED_MAPPED);
11403 else
11405 /* This was XtPopup, but that did nothing for an iconified frame. */
11406 XtMapWidget (f->output_data.x->widget);
11408 #else /* not USE_X_TOOLKIT */
11409 #ifdef USE_GTK
11410 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
11411 gtk_window_deiconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
11412 #else
11413 if (FRAME_X_EMBEDDED_P (f))
11414 xembed_set_info (f, XEMBED_MAPPED);
11415 else
11416 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11417 #endif /* not USE_GTK */
11418 #endif /* not USE_X_TOOLKIT */
11421 XFlush (FRAME_X_DISPLAY (f));
11423 /* Synchronize to ensure Emacs knows the frame is visible
11424 before we do anything else. We do this loop with input not blocked
11425 so that incoming events are handled. */
11427 /* This must be before UNBLOCK_INPUT
11428 since events that arrive in response to the actions above
11429 will set it when they are handled. */
11430 bool previously_visible = f->output_data.x->has_been_visible;
11432 int original_left = f->left_pos;
11433 int original_top = f->top_pos;
11435 /* This must come after we set COUNT. */
11436 unblock_input ();
11438 /* We unblock here so that arriving X events are processed. */
11440 /* Now move the window back to where it was "supposed to be".
11441 But don't do it if the gravity is negative.
11442 When the gravity is negative, this uses a position
11443 that is 3 pixels too low. Perhaps that's really the border width.
11445 Don't do this if the window has never been visible before,
11446 because the window manager may choose the position
11447 and we don't want to override it. */
11449 if (!FRAME_VISIBLE_P (f)
11450 && !FRAME_ICONIFIED_P (f)
11451 && !FRAME_X_EMBEDDED_P (f)
11452 && !FRAME_PARENT_FRAME (f)
11453 && f->win_gravity == NorthWestGravity
11454 && previously_visible)
11456 Drawable rootw;
11457 int x, y;
11458 unsigned int width, height, border, depth;
11460 block_input ();
11462 /* On some window managers (such as FVWM) moving an existing
11463 window, even to the same place, causes the window manager
11464 to introduce an offset. This can cause the window to move
11465 to an unexpected location. Check the geometry (a little
11466 slow here) and then verify that the window is in the right
11467 place. If the window is not in the right place, move it
11468 there, and take the potential window manager hit. */
11469 XGetGeometry (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11470 &rootw, &x, &y, &width, &height, &border, &depth);
11472 if (original_left != x || original_top != y)
11473 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
11474 original_left, original_top);
11476 unblock_input ();
11481 /* Change from mapped state to withdrawn state. */
11483 /* Make the frame visible (mapped and not iconified). */
11485 void
11486 x_make_frame_invisible (struct frame *f)
11488 Window window;
11490 /* Use the frame's outermost window, not the one we normally draw on. */
11491 window = FRAME_OUTER_WINDOW (f);
11493 /* Don't keep the highlight on an invisible frame. */
11494 if (FRAME_DISPLAY_INFO (f)->x_highlight_frame == f)
11495 FRAME_DISPLAY_INFO (f)->x_highlight_frame = 0;
11497 block_input ();
11499 /* Before unmapping the window, update the WM_SIZE_HINTS property to claim
11500 that the current position of the window is user-specified, rather than
11501 program-specified, so that when the window is mapped again, it will be
11502 placed at the same location, without forcing the user to position it
11503 by hand again (they have already done that once for this window.) */
11504 x_wm_set_size_hint (f, 0, true);
11506 #ifdef USE_GTK
11507 if (FRAME_GTK_OUTER_WIDGET (f))
11508 gtk_widget_hide (FRAME_GTK_OUTER_WIDGET (f));
11509 else
11510 #else
11511 if (FRAME_X_EMBEDDED_P (f))
11512 xembed_set_info (f, 0);
11513 else
11514 #endif
11516 if (! XWithdrawWindow (FRAME_X_DISPLAY (f), window,
11517 DefaultScreen (FRAME_X_DISPLAY (f))))
11519 unblock_input ();
11520 error ("Can't notify window manager of window withdrawal");
11523 x_sync (f);
11525 /* We can't distinguish this from iconification
11526 just by the event that we get from the server.
11527 So we can't win using the usual strategy of letting
11528 FRAME_SAMPLE_VISIBILITY set this. So do it by hand,
11529 and synchronize with the server to make sure we agree. */
11530 SET_FRAME_VISIBLE (f, 0);
11531 SET_FRAME_ICONIFIED (f, false);
11533 unblock_input ();
11536 /* Change window state from mapped to iconified. */
11538 void
11539 x_iconify_frame (struct frame *f)
11541 #ifdef USE_X_TOOLKIT
11542 int result;
11543 #endif
11545 /* Don't keep the highlight on an invisible frame. */
11546 if (FRAME_DISPLAY_INFO (f)->x_highlight_frame == f)
11547 FRAME_DISPLAY_INFO (f)->x_highlight_frame = 0;
11549 if (FRAME_ICONIFIED_P (f))
11550 return;
11552 block_input ();
11554 x_set_bitmap_icon (f);
11556 #if defined (USE_GTK)
11557 if (FRAME_GTK_OUTER_WIDGET (f))
11559 if (! FRAME_VISIBLE_P (f))
11560 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
11562 gtk_window_iconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
11563 SET_FRAME_VISIBLE (f, 0);
11564 SET_FRAME_ICONIFIED (f, true);
11565 unblock_input ();
11566 return;
11568 #endif
11570 #ifdef USE_X_TOOLKIT
11572 if (! FRAME_VISIBLE_P (f))
11574 if (! EQ (Vx_no_window_manager, Qt))
11575 x_wm_set_window_state (f, IconicState);
11576 /* This was XtPopup, but that did nothing for an iconified frame. */
11577 XtMapWidget (f->output_data.x->widget);
11578 /* The server won't give us any event to indicate
11579 that an invisible frame was changed to an icon,
11580 so we have to record it here. */
11581 SET_FRAME_VISIBLE (f, 0);
11582 SET_FRAME_ICONIFIED (f, true);
11583 unblock_input ();
11584 return;
11587 result = XIconifyWindow (FRAME_X_DISPLAY (f),
11588 XtWindow (f->output_data.x->widget),
11589 DefaultScreen (FRAME_X_DISPLAY (f)));
11590 unblock_input ();
11592 if (!result)
11593 error ("Can't notify window manager of iconification");
11595 SET_FRAME_ICONIFIED (f, true);
11596 SET_FRAME_VISIBLE (f, 0);
11598 block_input ();
11599 XFlush (FRAME_X_DISPLAY (f));
11600 unblock_input ();
11601 #else /* not USE_X_TOOLKIT */
11603 /* Make sure the X server knows where the window should be positioned,
11604 in case the user deiconifies with the window manager. */
11605 if (! FRAME_VISIBLE_P (f)
11606 && ! FRAME_ICONIFIED_P (f)
11607 && ! FRAME_X_EMBEDDED_P (f))
11608 x_set_offset (f, f->left_pos, f->top_pos, 0);
11610 /* Since we don't know which revision of X we're running, we'll use both
11611 the X11R3 and X11R4 techniques. I don't know if this is a good idea. */
11613 /* X11R4: send a ClientMessage to the window manager using the
11614 WM_CHANGE_STATE type. */
11616 XEvent msg;
11618 msg.xclient.window = FRAME_X_WINDOW (f);
11619 msg.xclient.type = ClientMessage;
11620 msg.xclient.message_type = FRAME_DISPLAY_INFO (f)->Xatom_wm_change_state;
11621 msg.xclient.format = 32;
11622 msg.xclient.data.l[0] = IconicState;
11624 if (! XSendEvent (FRAME_X_DISPLAY (f),
11625 DefaultRootWindow (FRAME_X_DISPLAY (f)),
11626 False,
11627 SubstructureRedirectMask | SubstructureNotifyMask,
11628 &msg))
11630 unblock_input ();
11631 error ("Can't notify window manager of iconification");
11635 /* X11R3: set the initial_state field of the window manager hints to
11636 IconicState. */
11637 x_wm_set_window_state (f, IconicState);
11639 if (!FRAME_VISIBLE_P (f))
11641 /* If the frame was withdrawn, before, we must map it. */
11642 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11645 SET_FRAME_ICONIFIED (f, true);
11646 SET_FRAME_VISIBLE (f, 0);
11648 XFlush (FRAME_X_DISPLAY (f));
11649 unblock_input ();
11650 #endif /* not USE_X_TOOLKIT */
11654 /* Free X resources of frame F. */
11656 void
11657 x_free_frame_resources (struct frame *f)
11659 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
11660 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
11661 #ifdef USE_X_TOOLKIT
11662 Lisp_Object bar;
11663 struct scroll_bar *b;
11664 #endif
11666 block_input ();
11668 /* If a display connection is dead, don't try sending more
11669 commands to the X server. */
11670 if (dpyinfo->display)
11672 /* Always exit with visible pointer to avoid weird issue
11673 with Xfixes (Bug#17609). */
11674 if (f->pointer_invisible)
11675 FRAME_DISPLAY_INFO (f)->toggle_visible_pointer (f, 0);
11677 /* We must free faces before destroying windows because some
11678 font-driver (e.g. xft) access a window while finishing a
11679 face. */
11680 free_frame_faces (f);
11681 tear_down_x_back_buffer (f);
11683 if (f->output_data.x->icon_desc)
11684 XDestroyWindow (FRAME_X_DISPLAY (f), f->output_data.x->icon_desc);
11686 #ifdef USE_X_TOOLKIT
11687 /* Explicitly destroy the scroll bars of the frame. Without
11688 this, we get "BadDrawable" errors from the toolkit later on,
11689 presumably from expose events generated for the disappearing
11690 toolkit scroll bars. */
11691 for (bar = FRAME_SCROLL_BARS (f); !NILP (bar); bar = b->next)
11693 b = XSCROLL_BAR (bar);
11694 x_scroll_bar_remove (b);
11696 #endif
11698 #ifdef HAVE_X_I18N
11699 if (FRAME_XIC (f))
11700 free_frame_xic (f);
11701 #endif
11703 x_free_cr_resources (f);
11704 #ifdef USE_X_TOOLKIT
11705 if (f->output_data.x->widget)
11707 XtDestroyWidget (f->output_data.x->widget);
11708 f->output_data.x->widget = NULL;
11710 /* Tooltips don't have widgets, only a simple X window, even if
11711 we are using a toolkit. */
11712 else if (FRAME_X_WINDOW (f))
11713 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11715 free_frame_menubar (f);
11717 if (f->shell_position)
11718 xfree (f->shell_position);
11719 #else /* !USE_X_TOOLKIT */
11721 #ifdef USE_GTK
11722 xg_free_frame_widgets (f);
11723 #endif /* USE_GTK */
11725 tear_down_x_back_buffer (f);
11726 if (FRAME_X_WINDOW (f))
11727 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11728 #endif /* !USE_X_TOOLKIT */
11730 unload_color (f, FRAME_FOREGROUND_PIXEL (f));
11731 unload_color (f, FRAME_BACKGROUND_PIXEL (f));
11732 unload_color (f, f->output_data.x->cursor_pixel);
11733 unload_color (f, f->output_data.x->cursor_foreground_pixel);
11734 unload_color (f, f->output_data.x->border_pixel);
11735 unload_color (f, f->output_data.x->mouse_pixel);
11737 if (f->output_data.x->scroll_bar_background_pixel != -1)
11738 unload_color (f, f->output_data.x->scroll_bar_background_pixel);
11739 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
11740 unload_color (f, f->output_data.x->scroll_bar_foreground_pixel);
11741 #if defined (USE_LUCID) && defined (USE_TOOLKIT_SCROLL_BARS)
11742 /* Scrollbar shadow colors. */
11743 if (f->output_data.x->scroll_bar_top_shadow_pixel != -1)
11744 unload_color (f, f->output_data.x->scroll_bar_top_shadow_pixel);
11745 if (f->output_data.x->scroll_bar_bottom_shadow_pixel != -1)
11746 unload_color (f, f->output_data.x->scroll_bar_bottom_shadow_pixel);
11747 #endif /* USE_LUCID && USE_TOOLKIT_SCROLL_BARS */
11748 if (f->output_data.x->white_relief.pixel != -1)
11749 unload_color (f, f->output_data.x->white_relief.pixel);
11750 if (f->output_data.x->black_relief.pixel != -1)
11751 unload_color (f, f->output_data.x->black_relief.pixel);
11753 x_free_gcs (f);
11755 /* Free extra GCs allocated by x_setup_relief_colors. */
11756 if (f->output_data.x->white_relief.gc)
11758 XFreeGC (dpyinfo->display, f->output_data.x->white_relief.gc);
11759 f->output_data.x->white_relief.gc = 0;
11761 if (f->output_data.x->black_relief.gc)
11763 XFreeGC (dpyinfo->display, f->output_data.x->black_relief.gc);
11764 f->output_data.x->black_relief.gc = 0;
11767 /* Free cursors. */
11768 if (f->output_data.x->text_cursor != 0)
11769 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->text_cursor);
11770 if (f->output_data.x->nontext_cursor != 0)
11771 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->nontext_cursor);
11772 if (f->output_data.x->modeline_cursor != 0)
11773 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->modeline_cursor);
11774 if (f->output_data.x->hand_cursor != 0)
11775 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->hand_cursor);
11776 if (f->output_data.x->hourglass_cursor != 0)
11777 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->hourglass_cursor);
11778 if (f->output_data.x->horizontal_drag_cursor != 0)
11779 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->horizontal_drag_cursor);
11780 if (f->output_data.x->vertical_drag_cursor != 0)
11781 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->vertical_drag_cursor);
11782 if (f->output_data.x->left_edge_cursor != 0)
11783 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->left_edge_cursor);
11784 if (f->output_data.x->top_left_corner_cursor != 0)
11785 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->top_left_corner_cursor);
11786 if (f->output_data.x->top_edge_cursor != 0)
11787 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->top_edge_cursor);
11788 if (f->output_data.x->top_right_corner_cursor != 0)
11789 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->top_right_corner_cursor);
11790 if (f->output_data.x->right_edge_cursor != 0)
11791 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->right_edge_cursor);
11792 if (f->output_data.x->bottom_right_corner_cursor != 0)
11793 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->bottom_right_corner_cursor);
11794 if (f->output_data.x->bottom_edge_cursor != 0)
11795 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->bottom_edge_cursor);
11796 if (f->output_data.x->bottom_left_corner_cursor != 0)
11797 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->bottom_left_corner_cursor);
11799 XFlush (FRAME_X_DISPLAY (f));
11802 xfree (f->output_data.x->saved_menu_event);
11803 xfree (f->output_data.x);
11804 f->output_data.x = NULL;
11806 if (f == dpyinfo->x_focus_frame)
11807 dpyinfo->x_focus_frame = 0;
11808 if (f == dpyinfo->x_focus_event_frame)
11809 dpyinfo->x_focus_event_frame = 0;
11810 if (f == dpyinfo->x_highlight_frame)
11811 dpyinfo->x_highlight_frame = 0;
11812 if (f == hlinfo->mouse_face_mouse_frame)
11813 reset_mouse_highlight (hlinfo);
11815 unblock_input ();
11819 /* Destroy the X window of frame F. */
11821 static void
11822 x_destroy_window (struct frame *f)
11824 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
11826 /* If a display connection is dead, don't try sending more
11827 commands to the X server. */
11828 if (dpyinfo->display != 0)
11829 x_free_frame_resources (f);
11831 dpyinfo->reference_count--;
11835 /* Setting window manager hints. */
11837 /* Set the normal size hints for the window manager, for frame F.
11838 FLAGS is the flags word to use--or 0 meaning preserve the flags
11839 that the window now has.
11840 If USER_POSITION, set the USPosition
11841 flag (this is useful when FLAGS is 0).
11842 The GTK version is in gtkutils.c. */
11844 #ifndef USE_GTK
11845 void
11846 x_wm_set_size_hint (struct frame *f, long flags, bool user_position)
11848 XSizeHints size_hints;
11849 Window window = FRAME_OUTER_WINDOW (f);
11851 if (!window)
11852 return;
11854 #ifdef USE_X_TOOLKIT
11855 if (f->output_data.x->widget)
11857 widget_update_wm_size_hints (f->output_data.x->widget);
11858 return;
11860 #endif
11862 /* Setting PMaxSize caused various problems. */
11863 size_hints.flags = PResizeInc | PMinSize /* | PMaxSize */;
11865 size_hints.x = f->left_pos;
11866 size_hints.y = f->top_pos;
11868 size_hints.width = FRAME_PIXEL_WIDTH (f);
11869 size_hints.height = FRAME_PIXEL_HEIGHT (f);
11871 size_hints.width_inc = frame_resize_pixelwise ? 1 : FRAME_COLUMN_WIDTH (f);
11872 size_hints.height_inc = frame_resize_pixelwise ? 1 : FRAME_LINE_HEIGHT (f);
11874 size_hints.max_width = x_display_pixel_width (FRAME_DISPLAY_INFO (f))
11875 - FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
11876 size_hints.max_height = x_display_pixel_height (FRAME_DISPLAY_INFO (f))
11877 - FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
11879 /* Calculate the base and minimum sizes. */
11881 int base_width, base_height;
11883 base_width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
11884 base_height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
11886 /* The window manager uses the base width hints to calculate the
11887 current number of rows and columns in the frame while
11888 resizing; min_width and min_height aren't useful for this
11889 purpose, since they might not give the dimensions for a
11890 zero-row, zero-column frame. */
11892 size_hints.flags |= PBaseSize;
11893 size_hints.base_width = base_width;
11894 size_hints.base_height = base_height + FRAME_MENUBAR_HEIGHT (f);
11895 size_hints.min_width = base_width;
11896 size_hints.min_height = base_height;
11899 /* If we don't need the old flags, we don't need the old hint at all. */
11900 if (flags)
11902 size_hints.flags |= flags;
11903 goto no_read;
11907 XSizeHints hints; /* Sometimes I hate X Windows... */
11908 long supplied_return;
11909 int value;
11911 value = XGetWMNormalHints (FRAME_X_DISPLAY (f), window, &hints,
11912 &supplied_return);
11914 if (flags)
11915 size_hints.flags |= flags;
11916 else
11918 if (value == 0)
11919 hints.flags = 0;
11920 if (hints.flags & PSize)
11921 size_hints.flags |= PSize;
11922 if (hints.flags & PPosition)
11923 size_hints.flags |= PPosition;
11924 if (hints.flags & USPosition)
11925 size_hints.flags |= USPosition;
11926 if (hints.flags & USSize)
11927 size_hints.flags |= USSize;
11931 no_read:
11933 #ifdef PWinGravity
11934 size_hints.win_gravity = f->win_gravity;
11935 size_hints.flags |= PWinGravity;
11937 if (user_position)
11939 size_hints.flags &= ~ PPosition;
11940 size_hints.flags |= USPosition;
11942 #endif /* PWinGravity */
11944 XSetWMNormalHints (FRAME_X_DISPLAY (f), window, &size_hints);
11946 #endif /* not USE_GTK */
11948 /* Used for IconicState or NormalState */
11950 static void
11951 x_wm_set_window_state (struct frame *f, int state)
11953 #ifdef USE_X_TOOLKIT
11954 Arg al[1];
11956 XtSetArg (al[0], XtNinitialState, state);
11957 XtSetValues (f->output_data.x->widget, al, 1);
11958 #else /* not USE_X_TOOLKIT */
11959 Window window = FRAME_X_WINDOW (f);
11961 f->output_data.x->wm_hints.flags |= StateHint;
11962 f->output_data.x->wm_hints.initial_state = state;
11964 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
11965 #endif /* not USE_X_TOOLKIT */
11968 static void
11969 x_wm_set_icon_pixmap (struct frame *f, ptrdiff_t pixmap_id)
11971 Pixmap icon_pixmap, icon_mask;
11973 #if !defined USE_X_TOOLKIT && !defined USE_GTK
11974 Window window = FRAME_OUTER_WINDOW (f);
11975 #endif
11977 if (pixmap_id > 0)
11979 icon_pixmap = x_bitmap_pixmap (f, pixmap_id);
11980 f->output_data.x->wm_hints.icon_pixmap = icon_pixmap;
11981 icon_mask = x_bitmap_mask (f, pixmap_id);
11982 f->output_data.x->wm_hints.icon_mask = icon_mask;
11984 else
11986 /* It seems there is no way to turn off use of an icon
11987 pixmap. */
11988 return;
11992 #ifdef USE_GTK
11994 xg_set_frame_icon (f, icon_pixmap, icon_mask);
11995 return;
11998 #elif defined (USE_X_TOOLKIT) /* same as in x_wm_set_window_state. */
12001 Arg al[1];
12002 XtSetArg (al[0], XtNiconPixmap, icon_pixmap);
12003 XtSetValues (f->output_data.x->widget, al, 1);
12004 XtSetArg (al[0], XtNiconMask, icon_mask);
12005 XtSetValues (f->output_data.x->widget, al, 1);
12008 #else /* not USE_X_TOOLKIT && not USE_GTK */
12010 f->output_data.x->wm_hints.flags |= (IconPixmapHint | IconMaskHint);
12011 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
12013 #endif /* not USE_X_TOOLKIT && not USE_GTK */
12016 void
12017 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
12019 Window window = FRAME_OUTER_WINDOW (f);
12021 f->output_data.x->wm_hints.flags |= IconPositionHint;
12022 f->output_data.x->wm_hints.icon_x = icon_x;
12023 f->output_data.x->wm_hints.icon_y = icon_y;
12025 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
12029 /***********************************************************************
12030 Fonts
12031 ***********************************************************************/
12033 #ifdef GLYPH_DEBUG
12035 /* Check that FONT is valid on frame F. It is if it can be found in F's
12036 font table. */
12038 static void
12039 x_check_font (struct frame *f, struct font *font)
12041 eassert (font != NULL && ! NILP (font->props[FONT_TYPE_INDEX]));
12042 if (font->driver->check)
12043 eassert (font->driver->check (f, font) == 0);
12046 #endif /* GLYPH_DEBUG */
12049 /***********************************************************************
12050 Initialization
12051 ***********************************************************************/
12053 #ifdef USE_X_TOOLKIT
12054 static XrmOptionDescRec emacs_options[] = {
12055 {(char *) "-geometry", (char *) ".geometry", XrmoptionSepArg, NULL},
12056 {(char *) "-iconic", (char *) ".iconic", XrmoptionNoArg, (XtPointer) "yes"},
12058 {(char *) "-internal-border-width",
12059 (char *) "*EmacsScreen.internalBorderWidth", XrmoptionSepArg, NULL},
12060 {(char *) "-ib", (char *) "*EmacsScreen.internalBorderWidth",
12061 XrmoptionSepArg, NULL},
12062 {(char *) "-T", (char *) "*EmacsShell.title", XrmoptionSepArg, NULL},
12063 {(char *) "-wn", (char *) "*EmacsShell.title", XrmoptionSepArg, NULL},
12064 {(char *) "-title", (char *) "*EmacsShell.title", XrmoptionSepArg, NULL},
12065 {(char *) "-iconname", (char *) "*EmacsShell.iconName",
12066 XrmoptionSepArg, NULL},
12067 {(char *) "-in", (char *) "*EmacsShell.iconName", XrmoptionSepArg, NULL},
12068 {(char *) "-mc", (char *) "*pointerColor", XrmoptionSepArg, NULL},
12069 {(char *) "-cr", (char *) "*cursorColor", XrmoptionSepArg, NULL}
12072 /* Whether atimer for Xt timeouts is activated or not. */
12074 static bool x_timeout_atimer_activated_flag;
12076 #endif /* USE_X_TOOLKIT */
12078 static int x_initialized;
12080 /* Test whether two display-name strings agree up to the dot that separates
12081 the screen number from the server number. */
12082 static bool
12083 same_x_server (const char *name1, const char *name2)
12085 bool seen_colon = false;
12086 Lisp_Object sysname = Fsystem_name ();
12087 const char *system_name = SSDATA (sysname);
12088 ptrdiff_t system_name_length = SBYTES (sysname);
12089 ptrdiff_t length_until_period = 0;
12091 while (system_name[length_until_period] != 0
12092 && system_name[length_until_period] != '.')
12093 length_until_period++;
12095 /* Treat `unix' like an empty host name. */
12096 if (! strncmp (name1, "unix:", 5))
12097 name1 += 4;
12098 if (! strncmp (name2, "unix:", 5))
12099 name2 += 4;
12100 /* Treat this host's name like an empty host name. */
12101 if (! strncmp (name1, system_name, system_name_length)
12102 && name1[system_name_length] == ':')
12103 name1 += system_name_length;
12104 if (! strncmp (name2, system_name, system_name_length)
12105 && name2[system_name_length] == ':')
12106 name2 += system_name_length;
12107 /* Treat this host's domainless name like an empty host name. */
12108 if (! strncmp (name1, system_name, length_until_period)
12109 && name1[length_until_period] == ':')
12110 name1 += length_until_period;
12111 if (! strncmp (name2, system_name, length_until_period)
12112 && name2[length_until_period] == ':')
12113 name2 += length_until_period;
12115 for (; *name1 != '\0' && *name1 == *name2; name1++, name2++)
12117 if (*name1 == ':')
12118 seen_colon = true;
12119 if (seen_colon && *name1 == '.')
12120 return true;
12122 return (seen_colon
12123 && (*name1 == '.' || *name1 == '\0')
12124 && (*name2 == '.' || *name2 == '\0'));
12127 /* Count number of set bits in mask and number of bits to shift to
12128 get to the first bit. With MASK 0x7e0, *BITS is set to 6, and *OFFSET
12129 to 5. */
12130 static void
12131 get_bits_and_offset (unsigned long mask, int *bits, int *offset)
12133 int nr = 0;
12134 int off = 0;
12136 while (!(mask & 1))
12138 off++;
12139 mask >>= 1;
12142 while (mask & 1)
12144 nr++;
12145 mask >>= 1;
12148 *offset = off;
12149 *bits = nr;
12152 /* Return true iff display DISPLAY is available for use.
12153 But don't permanently open it, just test its availability. */
12155 bool
12156 x_display_ok (const char *display)
12158 /* XOpenDisplay fails if it gets a signal. Block SIGIO which may arrive. */
12159 unrequest_sigio ();
12160 Display *dpy = XOpenDisplay (display);
12161 request_sigio ();
12162 if (!dpy)
12163 return false;
12164 XCloseDisplay (dpy);
12165 return true;
12168 #ifdef USE_GTK
12169 static void
12170 my_log_handler (const gchar *log_domain, GLogLevelFlags log_level,
12171 const gchar *msg, gpointer user_data)
12173 if (!strstr (msg, "g_set_prgname"))
12174 fprintf (stderr, "%s-WARNING **: %s\n", log_domain, msg);
12176 #endif
12178 /* Create invisible cursor on X display referred by DPYINFO. */
12180 static Cursor
12181 make_invisible_cursor (struct x_display_info *dpyinfo)
12183 Display *dpy = dpyinfo->display;
12184 static char const no_data[] = { 0 };
12185 Pixmap pix;
12186 XColor col;
12187 Cursor c = 0;
12189 x_catch_errors (dpy);
12190 pix = XCreateBitmapFromData (dpy, dpyinfo->root_window, no_data, 1, 1);
12191 if (! x_had_errors_p (dpy) && pix != None)
12193 Cursor pixc;
12194 col.pixel = 0;
12195 col.red = col.green = col.blue = 0;
12196 col.flags = DoRed | DoGreen | DoBlue;
12197 pixc = XCreatePixmapCursor (dpy, pix, pix, &col, &col, 0, 0);
12198 if (! x_had_errors_p (dpy) && pixc != None)
12199 c = pixc;
12200 XFreePixmap (dpy, pix);
12203 x_uncatch_errors ();
12205 return c;
12208 /* True if DPY supports Xfixes extension >= 4. */
12210 static bool
12211 x_probe_xfixes_extension (Display *dpy)
12213 #ifdef HAVE_XFIXES
12214 int major, minor;
12215 return XFixesQueryVersion (dpy, &major, &minor) && major >= 4;
12216 #else
12217 return false;
12218 #endif /* HAVE_XFIXES */
12221 /* Toggle mouse pointer visibility on frame F by using Xfixes functions. */
12223 static void
12224 xfixes_toggle_visible_pointer (struct frame *f, bool invisible)
12226 #ifdef HAVE_XFIXES
12227 if (invisible)
12228 XFixesHideCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
12229 else
12230 XFixesShowCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
12231 f->pointer_invisible = invisible;
12232 #else
12233 emacs_abort ();
12234 #endif /* HAVE_XFIXES */
12237 /* Toggle mouse pointer visibility on frame F by using invisible cursor. */
12239 static void
12240 x_toggle_visible_pointer (struct frame *f, bool invisible)
12242 eassert (FRAME_DISPLAY_INFO (f)->invisible_cursor != 0);
12243 if (invisible)
12244 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
12245 FRAME_DISPLAY_INFO (f)->invisible_cursor);
12246 else
12247 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
12248 f->output_data.x->current_cursor);
12249 f->pointer_invisible = invisible;
12252 /* Setup pointer blanking, prefer Xfixes if available. */
12254 static void
12255 x_setup_pointer_blanking (struct x_display_info *dpyinfo)
12257 /* FIXME: the brave tester should set EMACS_XFIXES because we're suspecting
12258 X server bug, see http://debbugs.gnu.org/cgi/bugreport.cgi?bug=17609. */
12259 if (egetenv ("EMACS_XFIXES") && x_probe_xfixes_extension (dpyinfo->display))
12260 dpyinfo->toggle_visible_pointer = xfixes_toggle_visible_pointer;
12261 else
12263 dpyinfo->toggle_visible_pointer = x_toggle_visible_pointer;
12264 dpyinfo->invisible_cursor = make_invisible_cursor (dpyinfo);
12268 /* Current X display connection identifier. Incremented for each next
12269 connection established. */
12270 static unsigned x_display_id;
12272 /* Open a connection to X display DISPLAY_NAME, and return
12273 the structure that describes the open display.
12274 If we cannot contact the display, return null. */
12276 struct x_display_info *
12277 x_term_init (Lisp_Object display_name, char *xrm_option, char *resource_name)
12279 Display *dpy;
12280 struct terminal *terminal;
12281 struct x_display_info *dpyinfo;
12282 XrmDatabase xrdb;
12283 #ifdef USE_XCB
12284 xcb_connection_t *xcb_conn;
12285 #endif
12287 block_input ();
12289 if (!x_initialized)
12291 x_initialize ();
12292 ++x_initialized;
12295 if (! x_display_ok (SSDATA (display_name)))
12296 error ("Display %s can't be opened", SSDATA (display_name));
12298 #ifdef USE_GTK
12300 #define NUM_ARGV 10
12301 int argc;
12302 char *argv[NUM_ARGV];
12303 char **argv2 = argv;
12304 guint id;
12306 if (x_initialized++ > 1)
12308 xg_display_open (SSDATA (display_name), &dpy);
12310 else
12312 static char display_opt[] = "--display";
12313 static char name_opt[] = "--name";
12315 for (argc = 0; argc < NUM_ARGV; ++argc)
12316 argv[argc] = 0;
12318 argc = 0;
12319 argv[argc++] = initial_argv[0];
12321 if (! NILP (display_name))
12323 argv[argc++] = display_opt;
12324 argv[argc++] = SSDATA (display_name);
12327 argv[argc++] = name_opt;
12328 argv[argc++] = resource_name;
12330 XSetLocaleModifiers ("");
12332 /* Work around GLib bug that outputs a faulty warning. See
12333 https://bugzilla.gnome.org/show_bug.cgi?id=563627. */
12334 id = g_log_set_handler ("GLib", G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
12335 | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
12337 /* NULL window -> events for all windows go to our function.
12338 Call before gtk_init so Gtk+ event filters comes after our. */
12339 gdk_window_add_filter (NULL, event_handler_gdk, NULL);
12341 /* gtk_init does set_locale. Fix locale before and after. */
12342 fixup_locale ();
12343 unrequest_sigio (); /* See comment in x_display_ok. */
12344 gtk_init (&argc, &argv2);
12345 request_sigio ();
12346 fixup_locale ();
12348 g_log_remove_handler ("GLib", id);
12350 xg_initialize ();
12352 dpy = DEFAULT_GDK_DISPLAY ();
12354 #if ! GTK_CHECK_VERSION (2, 90, 0)
12355 /* Load our own gtkrc if it exists. */
12357 const char *file = "~/.emacs.d/gtkrc";
12358 Lisp_Object s, abs_file;
12360 s = build_string (file);
12361 abs_file = Fexpand_file_name (s, Qnil);
12363 if (! NILP (abs_file) && !NILP (Ffile_readable_p (abs_file)))
12364 gtk_rc_parse (SSDATA (abs_file));
12366 #endif
12368 XSetErrorHandler (x_error_handler);
12369 XSetIOErrorHandler (x_io_error_quitter);
12372 #else /* not USE_GTK */
12373 #ifdef USE_X_TOOLKIT
12374 /* weiner@footloose.sps.mot.com reports that this causes
12375 errors with X11R5:
12376 X protocol error: BadAtom (invalid Atom parameter)
12377 on protocol request 18skiloaf.
12378 So let's not use it until R6. */
12379 #ifdef HAVE_X11XTR6
12380 XtSetLanguageProc (NULL, NULL, NULL);
12381 #endif
12384 int argc = 0;
12385 char *argv[3];
12387 argv[0] = (char *) "";
12388 argc = 1;
12389 if (xrm_option)
12391 argv[argc++] = (char *) "-xrm";
12392 argv[argc++] = xrm_option;
12394 turn_on_atimers (false);
12395 unrequest_sigio (); /* See comment in x_display_ok. */
12396 dpy = XtOpenDisplay (Xt_app_con, SSDATA (display_name),
12397 resource_name, EMACS_CLASS,
12398 emacs_options, XtNumber (emacs_options),
12399 &argc, argv);
12400 request_sigio ();
12401 turn_on_atimers (true);
12403 #ifdef HAVE_X11XTR6
12404 /* I think this is to compensate for XtSetLanguageProc. */
12405 fixup_locale ();
12406 #endif
12409 #else /* not USE_X_TOOLKIT */
12410 XSetLocaleModifiers ("");
12411 unrequest_sigio (); /* See comment in x_display_ok. */
12412 dpy = XOpenDisplay (SSDATA (display_name));
12413 request_sigio ();
12414 #endif /* not USE_X_TOOLKIT */
12415 #endif /* not USE_GTK*/
12417 /* Detect failure. */
12418 if (dpy == 0)
12420 unblock_input ();
12421 return 0;
12424 #ifdef USE_XCB
12425 xcb_conn = XGetXCBConnection (dpy);
12426 if (xcb_conn == 0)
12428 #ifdef USE_GTK
12429 xg_display_close (dpy);
12430 #else
12431 #ifdef USE_X_TOOLKIT
12432 XtCloseDisplay (dpy);
12433 #else
12434 XCloseDisplay (dpy);
12435 #endif
12436 #endif /* ! USE_GTK */
12438 unblock_input ();
12439 return 0;
12441 #endif
12443 /* We have definitely succeeded. Record the new connection. */
12445 dpyinfo = xzalloc (sizeof *dpyinfo);
12446 terminal = x_create_terminal (dpyinfo);
12449 struct x_display_info *share;
12451 for (share = x_display_list; share; share = share->next)
12452 if (same_x_server (SSDATA (XCAR (share->name_list_element)),
12453 SSDATA (display_name)))
12454 break;
12455 if (share)
12456 terminal->kboard = share->terminal->kboard;
12457 else
12459 terminal->kboard = allocate_kboard (Qx);
12461 if (!EQ (XSYMBOL (Qvendor_specific_keysyms)->function, Qunbound))
12463 char *vendor = ServerVendor (dpy);
12465 /* Temporarily hide the partially initialized terminal. */
12466 terminal_list = terminal->next_terminal;
12467 unblock_input ();
12468 kset_system_key_alist
12469 (terminal->kboard,
12470 call1 (Qvendor_specific_keysyms,
12471 vendor ? build_string (vendor) : empty_unibyte_string));
12472 block_input ();
12473 terminal->next_terminal = terminal_list;
12474 terminal_list = terminal;
12477 /* Don't let the initial kboard remain current longer than necessary.
12478 That would cause problems if a file loaded on startup tries to
12479 prompt in the mini-buffer. */
12480 if (current_kboard == initial_kboard)
12481 current_kboard = terminal->kboard;
12483 terminal->kboard->reference_count++;
12486 /* Put this display on the chain. */
12487 dpyinfo->next = x_display_list;
12488 x_display_list = dpyinfo;
12490 dpyinfo->name_list_element = Fcons (display_name, Qnil);
12491 dpyinfo->display = dpy;
12492 dpyinfo->connection = ConnectionNumber (dpyinfo->display);
12493 #ifdef USE_XCB
12494 dpyinfo->xcb_connection = xcb_conn;
12495 #endif
12497 /* http://lists.gnu.org/archive/html/emacs-devel/2015-11/msg00194.html */
12498 dpyinfo->smallest_font_height = 1;
12499 dpyinfo->smallest_char_width = 1;
12501 /* Set the name of the terminal. */
12502 terminal->name = xlispstrdup (display_name);
12504 #if false
12505 XSetAfterFunction (x_current_display, x_trace_wire);
12506 #endif
12508 Lisp_Object system_name = Fsystem_name ();
12509 ptrdiff_t nbytes;
12510 if (INT_ADD_WRAPV (SBYTES (Vinvocation_name), SBYTES (system_name) + 2,
12511 &nbytes))
12512 memory_full (SIZE_MAX);
12513 dpyinfo->x_id = ++x_display_id;
12514 dpyinfo->x_id_name = xmalloc (nbytes);
12515 char *nametail = lispstpcpy (dpyinfo->x_id_name, Vinvocation_name);
12516 *nametail++ = '@';
12517 lispstpcpy (nametail, system_name);
12519 /* Figure out which modifier bits mean what. */
12520 x_find_modifier_meanings (dpyinfo);
12522 /* Get the scroll bar cursor. */
12523 #ifdef USE_GTK
12524 /* We must create a GTK cursor, it is required for GTK widgets. */
12525 dpyinfo->xg_cursor = xg_create_default_cursor (dpyinfo->display);
12526 #endif /* USE_GTK */
12528 dpyinfo->vertical_scroll_bar_cursor
12529 = XCreateFontCursor (dpyinfo->display, XC_sb_v_double_arrow);
12531 dpyinfo->horizontal_scroll_bar_cursor
12532 = XCreateFontCursor (dpyinfo->display, XC_sb_h_double_arrow);
12534 xrdb = x_load_resources (dpyinfo->display, xrm_option,
12535 resource_name, EMACS_CLASS);
12536 #ifdef HAVE_XRMSETDATABASE
12537 XrmSetDatabase (dpyinfo->display, xrdb);
12538 #else
12539 dpyinfo->display->db = xrdb;
12540 #endif
12541 /* Put the rdb where we can find it in a way that works on
12542 all versions. */
12543 dpyinfo->xrdb = xrdb;
12545 dpyinfo->screen = ScreenOfDisplay (dpyinfo->display,
12546 DefaultScreen (dpyinfo->display));
12547 select_visual (dpyinfo);
12548 dpyinfo->cmap = DefaultColormapOfScreen (dpyinfo->screen);
12549 dpyinfo->root_window = RootWindowOfScreen (dpyinfo->screen);
12550 dpyinfo->icon_bitmap_id = -1;
12551 dpyinfo->wm_type = X_WMTYPE_UNKNOWN;
12553 reset_mouse_highlight (&dpyinfo->mouse_highlight);
12555 /* See if we can construct pixel values from RGB values. */
12556 if (dpyinfo->visual->class == TrueColor)
12558 get_bits_and_offset (dpyinfo->visual->red_mask,
12559 &dpyinfo->red_bits, &dpyinfo->red_offset);
12560 get_bits_and_offset (dpyinfo->visual->blue_mask,
12561 &dpyinfo->blue_bits, &dpyinfo->blue_offset);
12562 get_bits_and_offset (dpyinfo->visual->green_mask,
12563 &dpyinfo->green_bits, &dpyinfo->green_offset);
12566 /* See if a private colormap is requested. */
12567 if (dpyinfo->visual == DefaultVisualOfScreen (dpyinfo->screen))
12569 if (dpyinfo->visual->class == PseudoColor)
12571 AUTO_STRING (privateColormap, "privateColormap");
12572 AUTO_STRING (PrivateColormap, "PrivateColormap");
12573 Lisp_Object value
12574 = display_x_get_resource (dpyinfo, privateColormap,
12575 PrivateColormap, Qnil, Qnil);
12576 if (STRINGP (value)
12577 && (!strcmp (SSDATA (value), "true")
12578 || !strcmp (SSDATA (value), "on")))
12579 dpyinfo->cmap = XCopyColormapAndFree (dpyinfo->display, dpyinfo->cmap);
12582 else
12583 dpyinfo->cmap = XCreateColormap (dpyinfo->display, dpyinfo->root_window,
12584 dpyinfo->visual, AllocNone);
12586 #ifdef HAVE_XDBE
12587 dpyinfo->supports_xdbe = false;
12588 int xdbe_major;
12589 int xdbe_minor;
12590 if (XdbeQueryExtension (dpyinfo->display, &xdbe_major, &xdbe_minor))
12591 dpyinfo->supports_xdbe = true;
12592 #endif
12594 #ifdef HAVE_XFT
12596 /* If we are using Xft, the following precautions should be made:
12598 1. Make sure that the Xrender extension is added before the Xft one.
12599 Otherwise, the close-display hook set by Xft is called after the one
12600 for Xrender, and the former tries to re-add the latter. This results
12601 in inconsistency of internal states and leads to X protocol error when
12602 one reconnects to the same X server (Bug#1696).
12604 2. Check dpi value in X resources. It is better we use it as well,
12605 since Xft will use it, as will all Gnome applications. If our real DPI
12606 is smaller or larger than the one Xft uses, our font will look smaller
12607 or larger than other for other applications, even if it is the same
12608 font name (monospace-10 for example). */
12610 int event_base, error_base;
12611 char *v;
12612 double d;
12614 XRenderQueryExtension (dpyinfo->display, &event_base, &error_base);
12616 v = XGetDefault (dpyinfo->display, "Xft", "dpi");
12617 if (v != NULL && sscanf (v, "%lf", &d) == 1)
12618 dpyinfo->resy = dpyinfo->resx = d;
12620 #endif
12622 if (dpyinfo->resy < 1)
12624 int screen_number = XScreenNumberOfScreen (dpyinfo->screen);
12625 double pixels = DisplayHeight (dpyinfo->display, screen_number);
12626 double mm = DisplayHeightMM (dpyinfo->display, screen_number);
12627 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
12628 dpyinfo->resy = (mm < 1) ? 100 : pixels * 25.4 / mm;
12629 pixels = DisplayWidth (dpyinfo->display, screen_number);
12630 mm = DisplayWidthMM (dpyinfo->display, screen_number);
12631 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
12632 dpyinfo->resx = (mm < 1) ? 100 : pixels * 25.4 / mm;
12636 static const struct
12638 const char *name;
12639 int offset;
12640 } atom_refs[] = {
12641 #define ATOM_REFS_INIT(string, member) \
12642 { string, offsetof (struct x_display_info, member) },
12643 ATOM_REFS_INIT ("WM_PROTOCOLS", Xatom_wm_protocols)
12644 ATOM_REFS_INIT ("WM_TAKE_FOCUS", Xatom_wm_take_focus)
12645 ATOM_REFS_INIT ("WM_SAVE_YOURSELF", Xatom_wm_save_yourself)
12646 ATOM_REFS_INIT ("WM_DELETE_WINDOW", Xatom_wm_delete_window)
12647 ATOM_REFS_INIT ("WM_CHANGE_STATE", Xatom_wm_change_state)
12648 ATOM_REFS_INIT ("WM_CONFIGURE_DENIED", Xatom_wm_configure_denied)
12649 ATOM_REFS_INIT ("WM_MOVED", Xatom_wm_window_moved)
12650 ATOM_REFS_INIT ("WM_CLIENT_LEADER", Xatom_wm_client_leader)
12651 ATOM_REFS_INIT ("Editres", Xatom_editres)
12652 ATOM_REFS_INIT ("CLIPBOARD", Xatom_CLIPBOARD)
12653 ATOM_REFS_INIT ("TIMESTAMP", Xatom_TIMESTAMP)
12654 ATOM_REFS_INIT ("TEXT", Xatom_TEXT)
12655 ATOM_REFS_INIT ("COMPOUND_TEXT", Xatom_COMPOUND_TEXT)
12656 ATOM_REFS_INIT ("UTF8_STRING", Xatom_UTF8_STRING)
12657 ATOM_REFS_INIT ("DELETE", Xatom_DELETE)
12658 ATOM_REFS_INIT ("MULTIPLE", Xatom_MULTIPLE)
12659 ATOM_REFS_INIT ("INCR", Xatom_INCR)
12660 ATOM_REFS_INIT ("_EMACS_TMP_", Xatom_EMACS_TMP)
12661 ATOM_REFS_INIT ("TARGETS", Xatom_TARGETS)
12662 ATOM_REFS_INIT ("NULL", Xatom_NULL)
12663 ATOM_REFS_INIT ("ATOM", Xatom_ATOM)
12664 ATOM_REFS_INIT ("ATOM_PAIR", Xatom_ATOM_PAIR)
12665 ATOM_REFS_INIT ("CLIPBOARD_MANAGER", Xatom_CLIPBOARD_MANAGER)
12666 ATOM_REFS_INIT ("_XEMBED_INFO", Xatom_XEMBED_INFO)
12667 /* For properties of font. */
12668 ATOM_REFS_INIT ("PIXEL_SIZE", Xatom_PIXEL_SIZE)
12669 ATOM_REFS_INIT ("AVERAGE_WIDTH", Xatom_AVERAGE_WIDTH)
12670 ATOM_REFS_INIT ("_MULE_BASELINE_OFFSET", Xatom_MULE_BASELINE_OFFSET)
12671 ATOM_REFS_INIT ("_MULE_RELATIVE_COMPOSE", Xatom_MULE_RELATIVE_COMPOSE)
12672 ATOM_REFS_INIT ("_MULE_DEFAULT_ASCENT", Xatom_MULE_DEFAULT_ASCENT)
12673 /* Ghostscript support. */
12674 ATOM_REFS_INIT ("DONE", Xatom_DONE)
12675 ATOM_REFS_INIT ("PAGE", Xatom_PAGE)
12676 ATOM_REFS_INIT ("SCROLLBAR", Xatom_Scrollbar)
12677 ATOM_REFS_INIT ("HORIZONTAL_SCROLLBAR", Xatom_Horizontal_Scrollbar)
12678 ATOM_REFS_INIT ("_XEMBED", Xatom_XEMBED)
12679 /* EWMH */
12680 ATOM_REFS_INIT ("_NET_WM_STATE", Xatom_net_wm_state)
12681 ATOM_REFS_INIT ("_NET_WM_STATE_FULLSCREEN", Xatom_net_wm_state_fullscreen)
12682 ATOM_REFS_INIT ("_NET_WM_STATE_MAXIMIZED_HORZ",
12683 Xatom_net_wm_state_maximized_horz)
12684 ATOM_REFS_INIT ("_NET_WM_STATE_MAXIMIZED_VERT",
12685 Xatom_net_wm_state_maximized_vert)
12686 ATOM_REFS_INIT ("_NET_WM_STATE_STICKY", Xatom_net_wm_state_sticky)
12687 ATOM_REFS_INIT ("_NET_WM_STATE_HIDDEN", Xatom_net_wm_state_hidden)
12688 ATOM_REFS_INIT ("_NET_WM_WINDOW_TYPE", Xatom_net_window_type)
12689 ATOM_REFS_INIT ("_NET_WM_WINDOW_TYPE_TOOLTIP",
12690 Xatom_net_window_type_tooltip)
12691 ATOM_REFS_INIT ("_NET_WM_ICON_NAME", Xatom_net_wm_icon_name)
12692 ATOM_REFS_INIT ("_NET_WM_NAME", Xatom_net_wm_name)
12693 ATOM_REFS_INIT ("_NET_SUPPORTED", Xatom_net_supported)
12694 ATOM_REFS_INIT ("_NET_SUPPORTING_WM_CHECK", Xatom_net_supporting_wm_check)
12695 ATOM_REFS_INIT ("_NET_WM_WINDOW_OPACITY", Xatom_net_wm_window_opacity)
12696 ATOM_REFS_INIT ("_NET_ACTIVE_WINDOW", Xatom_net_active_window)
12697 ATOM_REFS_INIT ("_NET_FRAME_EXTENTS", Xatom_net_frame_extents)
12698 ATOM_REFS_INIT ("_NET_CURRENT_DESKTOP", Xatom_net_current_desktop)
12699 ATOM_REFS_INIT ("_NET_WORKAREA", Xatom_net_workarea)
12700 /* Session management */
12701 ATOM_REFS_INIT ("SM_CLIENT_ID", Xatom_SM_CLIENT_ID)
12702 ATOM_REFS_INIT ("_XSETTINGS_SETTINGS", Xatom_xsettings_prop)
12703 ATOM_REFS_INIT ("MANAGER", Xatom_xsettings_mgr)
12704 ATOM_REFS_INIT ("_NET_WM_STATE_SKIP_TASKBAR", Xatom_net_wm_state_skip_taskbar)
12705 ATOM_REFS_INIT ("_NET_WM_STATE_ABOVE", Xatom_net_wm_state_above)
12706 ATOM_REFS_INIT ("_NET_WM_STATE_BELOW", Xatom_net_wm_state_below)
12709 int i;
12710 enum { atom_count = ARRAYELTS (atom_refs) };
12711 /* 1 for _XSETTINGS_SN. */
12712 enum { total_atom_count = 1 + atom_count };
12713 Atom atoms_return[total_atom_count];
12714 char *atom_names[total_atom_count];
12715 static char const xsettings_fmt[] = "_XSETTINGS_S%d";
12716 char xsettings_atom_name[sizeof xsettings_fmt - 2
12717 + INT_STRLEN_BOUND (int)];
12719 for (i = 0; i < atom_count; i++)
12720 atom_names[i] = (char *) atom_refs[i].name;
12722 /* Build _XSETTINGS_SN atom name. */
12723 sprintf (xsettings_atom_name, xsettings_fmt,
12724 XScreenNumberOfScreen (dpyinfo->screen));
12725 atom_names[i] = xsettings_atom_name;
12727 XInternAtoms (dpyinfo->display, atom_names, total_atom_count,
12728 False, atoms_return);
12730 for (i = 0; i < atom_count; i++)
12731 *(Atom *) ((char *) dpyinfo + atom_refs[i].offset) = atoms_return[i];
12733 /* Manually copy last atom. */
12734 dpyinfo->Xatom_xsettings_sel = atoms_return[i];
12737 dpyinfo->x_dnd_atoms_size = 8;
12738 dpyinfo->x_dnd_atoms = xmalloc (sizeof *dpyinfo->x_dnd_atoms
12739 * dpyinfo->x_dnd_atoms_size);
12740 dpyinfo->gray
12741 = XCreatePixmapFromBitmapData (dpyinfo->display, dpyinfo->root_window,
12742 gray_bits, gray_width, gray_height,
12743 1, 0, 1);
12745 x_setup_pointer_blanking (dpyinfo);
12747 #ifdef HAVE_X_I18N
12748 xim_initialize (dpyinfo, resource_name);
12749 #endif
12751 xsettings_initialize (dpyinfo);
12753 /* This is only needed for distinguishing keyboard and process input. */
12754 if (dpyinfo->connection != 0)
12755 add_keyboard_wait_descriptor (dpyinfo->connection);
12757 #ifdef F_SETOWN
12758 fcntl (dpyinfo->connection, F_SETOWN, getpid ());
12759 #endif /* ! defined (F_SETOWN) */
12761 if (interrupt_input)
12762 init_sigio (dpyinfo->connection);
12764 #ifdef USE_LUCID
12766 XrmValue d, fr, to;
12767 Font font;
12769 dpy = dpyinfo->display;
12770 d.addr = (XPointer)&dpy;
12771 d.size = sizeof (Display *);
12772 fr.addr = (char *) XtDefaultFont;
12773 fr.size = sizeof (XtDefaultFont);
12774 to.size = sizeof (Font *);
12775 to.addr = (XPointer)&font;
12776 x_catch_errors (dpy);
12777 if (!XtCallConverter (dpy, XtCvtStringToFont, &d, 1, &fr, &to, NULL))
12778 emacs_abort ();
12779 if (x_had_errors_p (dpy) || !XQueryFont (dpy, font))
12780 XrmPutLineResource (&xrdb, "Emacs.dialog.*.font: 9x15");
12781 /* Do not free XFontStruct returned by the above call to XQueryFont.
12782 This leads to X protocol errors at XtCloseDisplay (Bug#18403). */
12783 x_uncatch_errors ();
12785 #endif
12787 /* See if we should run in synchronous mode. This is useful
12788 for debugging X code. */
12790 AUTO_STRING (synchronous, "synchronous");
12791 AUTO_STRING (Synchronous, "Synchronous");
12792 Lisp_Object value = display_x_get_resource (dpyinfo, synchronous,
12793 Synchronous, Qnil, Qnil);
12794 if (STRINGP (value)
12795 && (!strcmp (SSDATA (value), "true")
12796 || !strcmp (SSDATA (value), "on")))
12797 XSynchronize (dpyinfo->display, True);
12801 AUTO_STRING (useXIM, "useXIM");
12802 AUTO_STRING (UseXIM, "UseXIM");
12803 Lisp_Object value = display_x_get_resource (dpyinfo, useXIM, UseXIM,
12804 Qnil, Qnil);
12805 #ifdef USE_XIM
12806 if (STRINGP (value)
12807 && (!strcmp (SSDATA (value), "false")
12808 || !strcmp (SSDATA (value), "off")))
12809 use_xim = false;
12810 #else
12811 if (STRINGP (value)
12812 && (!strcmp (SSDATA (value), "true")
12813 || !strcmp (SSDATA (value), "on")))
12814 use_xim = true;
12815 #endif
12818 #ifdef HAVE_X_SM
12819 /* Only do this for the very first display in the Emacs session.
12820 Ignore X session management when Emacs was first started on a
12821 tty or started as a daemon. */
12822 if (terminal->id == 1 && ! IS_DAEMON)
12823 x_session_initialize (dpyinfo);
12824 #endif
12826 #ifdef USE_CAIRO
12827 x_extension_initialize (dpyinfo);
12828 #endif
12830 unblock_input ();
12832 return dpyinfo;
12835 /* Get rid of display DPYINFO, deleting all frames on it,
12836 and without sending any more commands to the X server. */
12838 static void
12839 x_delete_display (struct x_display_info *dpyinfo)
12841 struct terminal *t;
12842 struct color_name_cache_entry *color_entry, *next_color_entry;
12844 /* Close all frames and delete the generic struct terminal for this
12845 X display. */
12846 for (t = terminal_list; t; t = t->next_terminal)
12847 if (t->type == output_x_window && t->display_info.x == dpyinfo)
12849 #ifdef HAVE_X_SM
12850 /* Close X session management when we close its display. */
12851 if (t->id == 1 && x_session_have_connection ())
12852 x_session_close ();
12853 #endif
12854 delete_terminal (t);
12855 break;
12858 if (next_noop_dpyinfo == dpyinfo)
12859 next_noop_dpyinfo = dpyinfo->next;
12861 if (x_display_list == dpyinfo)
12862 x_display_list = dpyinfo->next;
12863 else
12865 struct x_display_info *tail;
12867 for (tail = x_display_list; tail; tail = tail->next)
12868 if (tail->next == dpyinfo)
12869 tail->next = tail->next->next;
12872 for (color_entry = dpyinfo->color_names;
12873 color_entry;
12874 color_entry = next_color_entry)
12876 next_color_entry = color_entry->next;
12877 xfree (color_entry->name);
12878 xfree (color_entry);
12881 xfree (dpyinfo->x_id_name);
12882 xfree (dpyinfo->x_dnd_atoms);
12883 xfree (dpyinfo->color_cells);
12884 xfree (dpyinfo);
12887 #ifdef USE_X_TOOLKIT
12889 /* Atimer callback function for TIMER. Called every 0.1s to process
12890 Xt timeouts, if needed. We must avoid calling XtAppPending as
12891 much as possible because that function does an implicit XFlush
12892 that slows us down. */
12894 static void
12895 x_process_timeouts (struct atimer *timer)
12897 block_input ();
12898 x_timeout_atimer_activated_flag = false;
12899 if (toolkit_scroll_bar_interaction || popup_activated ())
12901 while (XtAppPending (Xt_app_con) & XtIMTimer)
12902 XtAppProcessEvent (Xt_app_con, XtIMTimer);
12903 /* Reactivate the atimer for next time. */
12904 x_activate_timeout_atimer ();
12906 unblock_input ();
12909 /* Install an asynchronous timer that processes Xt timeout events
12910 every 0.1s as long as either `toolkit_scroll_bar_interaction' or
12911 `popup_activated_flag' (in xmenu.c) is set. Make sure to call this
12912 function whenever these variables are set. This is necessary
12913 because some widget sets use timeouts internally, for example the
12914 LessTif menu bar, or the Xaw3d scroll bar. When Xt timeouts aren't
12915 processed, these widgets don't behave normally. */
12917 void
12918 x_activate_timeout_atimer (void)
12920 block_input ();
12921 if (!x_timeout_atimer_activated_flag)
12923 struct timespec interval = make_timespec (0, 100 * 1000 * 1000);
12924 start_atimer (ATIMER_RELATIVE, interval, x_process_timeouts, 0);
12925 x_timeout_atimer_activated_flag = true;
12927 unblock_input ();
12930 #endif /* USE_X_TOOLKIT */
12933 /* Set up use of X before we make the first connection. */
12935 static struct redisplay_interface x_redisplay_interface =
12937 x_frame_parm_handlers,
12938 x_produce_glyphs,
12939 x_write_glyphs,
12940 x_insert_glyphs,
12941 x_clear_end_of_line,
12942 x_scroll_run,
12943 x_after_update_window_line,
12944 x_update_window_begin,
12945 x_update_window_end,
12946 x_flip_and_flush,
12947 x_clear_window_mouse_face,
12948 x_get_glyph_overhangs,
12949 x_fix_overlapping_area,
12950 x_draw_fringe_bitmap,
12951 #ifdef USE_CAIRO
12952 x_cr_define_fringe_bitmap,
12953 x_cr_destroy_fringe_bitmap,
12954 #else
12955 0, /* define_fringe_bitmap */
12956 0, /* destroy_fringe_bitmap */
12957 #endif
12958 x_compute_glyph_string_overhangs,
12959 x_draw_glyph_string,
12960 x_define_frame_cursor,
12961 x_clear_frame_area,
12962 x_draw_window_cursor,
12963 x_draw_vertical_window_border,
12964 x_draw_window_divider,
12965 x_shift_glyphs_for_insert, /* Never called; see comment in function. */
12966 x_show_hourglass,
12967 x_hide_hourglass
12971 /* This function is called when the last frame on a display is deleted. */
12972 void
12973 x_delete_terminal (struct terminal *terminal)
12975 struct x_display_info *dpyinfo = terminal->display_info.x;
12977 /* Protect against recursive calls. delete_frame in
12978 delete_terminal calls us back when it deletes our last frame. */
12979 if (!terminal->name)
12980 return;
12982 block_input ();
12983 #ifdef HAVE_X_I18N
12984 /* We must close our connection to the XIM server before closing the
12985 X display. */
12986 if (dpyinfo->xim)
12987 xim_close_dpy (dpyinfo);
12988 #endif
12990 /* Normally, the display is available... */
12991 if (dpyinfo->display)
12993 x_destroy_all_bitmaps (dpyinfo);
12994 XSetCloseDownMode (dpyinfo->display, DestroyAll);
12996 /* Whether or not XCloseDisplay destroys the associated resource
12997 database depends on the version of libX11. To avoid both
12998 crash and memory leak, we dissociate the database from the
12999 display and then destroy dpyinfo->xrdb ourselves.
13001 Unfortunately, the above strategy does not work in some
13002 situations due to a bug in newer versions of libX11: because
13003 XrmSetDatabase doesn't clear the flag XlibDisplayDfltRMDB if
13004 dpy->db is NULL, XCloseDisplay destroys the associated
13005 database whereas it has not been created by XGetDefault
13006 (Bug#21974 in freedesktop.org Bugzilla). As a workaround, we
13007 don't destroy the database here in order to avoid the crash
13008 in the above situations for now, though that may cause memory
13009 leaks in other situations. */
13010 #if false
13011 #ifdef HAVE_XRMSETDATABASE
13012 XrmSetDatabase (dpyinfo->display, NULL);
13013 #else
13014 dpyinfo->display->db = NULL;
13015 #endif
13016 /* We used to call XrmDestroyDatabase from x_delete_display, but
13017 some older versions of libX11 crash if we call it after
13018 closing all the displays. */
13019 XrmDestroyDatabase (dpyinfo->xrdb);
13020 #endif
13022 #ifdef USE_GTK
13023 xg_display_close (dpyinfo->display);
13024 #else
13025 #ifdef USE_X_TOOLKIT
13026 XtCloseDisplay (dpyinfo->display);
13027 #else
13028 XCloseDisplay (dpyinfo->display);
13029 #endif
13030 #endif /* ! USE_GTK */
13031 /* Do not close the connection here because it's already closed
13032 by X(t)CloseDisplay (Bug#18403). */
13033 dpyinfo->display = NULL;
13036 /* ...but if called from x_connection_closed, the display may already
13037 be closed and dpyinfo->display was set to 0 to indicate that. Since
13038 X server is most likely gone, explicit close is the only reliable
13039 way to continue and avoid Bug#19147. */
13040 else if (dpyinfo->connection >= 0)
13041 emacs_close (dpyinfo->connection);
13043 /* No more input on this descriptor. */
13044 delete_keyboard_wait_descriptor (dpyinfo->connection);
13045 /* Mark as dead. */
13046 dpyinfo->connection = -1;
13048 x_delete_display (dpyinfo);
13049 unblock_input ();
13052 /* Create a struct terminal, initialize it with the X11 specific
13053 functions and make DISPLAY->TERMINAL point to it. */
13055 static struct terminal *
13056 x_create_terminal (struct x_display_info *dpyinfo)
13058 struct terminal *terminal;
13060 terminal = create_terminal (output_x_window, &x_redisplay_interface);
13062 terminal->display_info.x = dpyinfo;
13063 dpyinfo->terminal = terminal;
13065 /* kboard is initialized in x_term_init. */
13067 terminal->clear_frame_hook = x_clear_frame;
13068 terminal->ins_del_lines_hook = x_ins_del_lines;
13069 terminal->delete_glyphs_hook = x_delete_glyphs;
13070 terminal->ring_bell_hook = XTring_bell;
13071 terminal->toggle_invisible_pointer_hook = XTtoggle_invisible_pointer;
13072 terminal->update_begin_hook = x_update_begin;
13073 terminal->update_end_hook = x_update_end;
13074 terminal->read_socket_hook = XTread_socket;
13075 terminal->frame_up_to_date_hook = XTframe_up_to_date;
13076 terminal->buffer_flipping_unblocked_hook = XTbuffer_flipping_unblocked_hook;
13077 terminal->mouse_position_hook = XTmouse_position;
13078 terminal->frame_rehighlight_hook = XTframe_rehighlight;
13079 terminal->frame_raise_lower_hook = XTframe_raise_lower;
13080 terminal->fullscreen_hook = XTfullscreen_hook;
13081 terminal->menu_show_hook = x_menu_show;
13082 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
13083 terminal->popup_dialog_hook = xw_popup_dialog;
13084 #endif
13085 terminal->set_vertical_scroll_bar_hook = XTset_vertical_scroll_bar;
13086 terminal->set_horizontal_scroll_bar_hook = XTset_horizontal_scroll_bar;
13087 terminal->condemn_scroll_bars_hook = XTcondemn_scroll_bars;
13088 terminal->redeem_scroll_bar_hook = XTredeem_scroll_bar;
13089 terminal->judge_scroll_bars_hook = XTjudge_scroll_bars;
13090 terminal->delete_frame_hook = x_destroy_window;
13091 terminal->delete_terminal_hook = x_delete_terminal;
13092 /* Other hooks are NULL by default. */
13094 return terminal;
13097 static void
13098 x_initialize (void)
13100 baud_rate = 19200;
13102 x_noop_count = 0;
13103 any_help_event_p = false;
13104 ignore_next_mouse_click_timeout = 0;
13106 #ifdef USE_GTK
13107 current_count = -1;
13108 #endif
13110 /* Try to use interrupt input; if we can't, then start polling. */
13111 Fset_input_interrupt_mode (Qt);
13113 #if THREADS_ENABLED
13114 /* This must be called before any other Xlib routines. */
13115 if (XInitThreads () == 0)
13116 fprintf (stderr,
13117 "Warning: An error occurred initializing X11 thread support!\n");
13118 #endif
13120 #ifdef USE_X_TOOLKIT
13121 XtToolkitInitialize ();
13123 Xt_app_con = XtCreateApplicationContext ();
13125 /* Register a converter from strings to pixels, which uses
13126 Emacs' color allocation infrastructure. */
13127 XtAppSetTypeConverter (Xt_app_con,
13128 XtRString, XtRPixel, cvt_string_to_pixel,
13129 cvt_string_to_pixel_args,
13130 XtNumber (cvt_string_to_pixel_args),
13131 XtCacheByDisplay, cvt_pixel_dtor);
13133 XtAppSetFallbackResources (Xt_app_con, Xt_default_resources);
13134 #endif
13136 #ifdef USE_TOOLKIT_SCROLL_BARS
13137 #ifndef USE_GTK
13138 xaw3d_arrow_scroll = False;
13139 xaw3d_pick_top = True;
13140 #endif
13141 #endif
13143 #ifdef USE_CAIRO
13144 x_cr_init_fringe (&x_redisplay_interface);
13145 #endif
13147 /* Note that there is no real way portable across R3/R4 to get the
13148 original error handler. */
13149 XSetErrorHandler (x_error_handler);
13150 XSetIOErrorHandler (x_io_error_quitter);
13153 #ifdef USE_GTK
13154 void
13155 init_xterm (void)
13157 /* Emacs can handle only core input events, so make sure
13158 Gtk doesn't use Xinput or Xinput2 extensions. */
13159 xputenv ("GDK_CORE_DEVICE_EVENTS=1");
13161 #endif
13163 void
13164 syms_of_xterm (void)
13166 x_error_message = NULL;
13168 DEFSYM (Qvendor_specific_keysyms, "vendor-specific-keysyms");
13169 DEFSYM (Qlatin_1, "latin-1");
13171 #ifdef USE_GTK
13172 xg_default_icon_file = build_pure_c_string ("icons/hicolor/scalable/apps/emacs.svg");
13173 staticpro (&xg_default_icon_file);
13175 DEFSYM (Qx_gtk_map_stock, "x-gtk-map-stock");
13176 #endif
13178 DEFVAR_BOOL ("x-use-underline-position-properties",
13179 x_use_underline_position_properties,
13180 doc: /* Non-nil means make use of UNDERLINE_POSITION font properties.
13181 A value of nil means ignore them. If you encounter fonts with bogus
13182 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
13183 to 4.1, set this to nil. You can also use `underline-minimum-offset'
13184 to override the font's UNDERLINE_POSITION for small font display
13185 sizes. */);
13186 x_use_underline_position_properties = true;
13188 DEFVAR_BOOL ("x-underline-at-descent-line",
13189 x_underline_at_descent_line,
13190 doc: /* Non-nil means to draw the underline at the same place as the descent line.
13191 A value of nil means to draw the underline according to the value of the
13192 variable `x-use-underline-position-properties', which is usually at the
13193 baseline level. The default value is nil. */);
13194 x_underline_at_descent_line = false;
13196 DEFVAR_BOOL ("x-mouse-click-focus-ignore-position",
13197 x_mouse_click_focus_ignore_position,
13198 doc: /* Non-nil means that a mouse click to focus a frame does not move point.
13199 This variable is only used when the window manager requires that you
13200 click on a frame to select it (give it focus). In that case, a value
13201 of nil, means that the selected window and cursor position changes to
13202 reflect the mouse click position, while a non-nil value means that the
13203 selected window or cursor position is preserved. */);
13204 x_mouse_click_focus_ignore_position = false;
13206 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
13207 doc: /* Which toolkit scroll bars Emacs uses, if any.
13208 A value of nil means Emacs doesn't use toolkit scroll bars.
13209 With the X Window system, the value is a symbol describing the
13210 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
13211 With MS Windows or Nextstep, the value is t. */);
13212 #ifdef USE_TOOLKIT_SCROLL_BARS
13213 #ifdef USE_MOTIF
13214 Vx_toolkit_scroll_bars = intern_c_string ("motif");
13215 #elif defined HAVE_XAW3D
13216 Vx_toolkit_scroll_bars = intern_c_string ("xaw3d");
13217 #elif USE_GTK
13218 Vx_toolkit_scroll_bars = intern_c_string ("gtk");
13219 #else
13220 Vx_toolkit_scroll_bars = intern_c_string ("xaw");
13221 #endif
13222 #else
13223 Vx_toolkit_scroll_bars = Qnil;
13224 #endif
13226 DEFSYM (Qmodifier_value, "modifier-value");
13227 DEFSYM (Qctrl, "ctrl");
13228 Fput (Qctrl, Qmodifier_value, make_number (ctrl_modifier));
13229 DEFSYM (Qalt, "alt");
13230 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
13231 DEFSYM (Qhyper, "hyper");
13232 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
13233 DEFSYM (Qmeta, "meta");
13234 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
13235 DEFSYM (Qsuper, "super");
13236 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
13238 DEFVAR_LISP ("x-ctrl-keysym", Vx_ctrl_keysym,
13239 doc: /* Which keys Emacs uses for the ctrl modifier.
13240 This should be one of the symbols `ctrl', `alt', `hyper', `meta',
13241 `super'. For example, `ctrl' means use the Ctrl_L and Ctrl_R keysyms.
13242 The default is nil, which is the same as `ctrl'. */);
13243 Vx_ctrl_keysym = Qnil;
13245 DEFVAR_LISP ("x-alt-keysym", Vx_alt_keysym,
13246 doc: /* Which keys Emacs uses for the alt modifier.
13247 This should be one of the symbols `ctrl', `alt', `hyper', `meta',
13248 `super'. For example, `alt' means use the Alt_L and Alt_R keysyms.
13249 The default is nil, which is the same as `alt'. */);
13250 Vx_alt_keysym = Qnil;
13252 DEFVAR_LISP ("x-hyper-keysym", Vx_hyper_keysym,
13253 doc: /* Which keys Emacs uses for the hyper modifier.
13254 This should be one of the symbols `ctrl', `alt', `hyper', `meta',
13255 `super'. For example, `hyper' means use the Hyper_L and Hyper_R
13256 keysyms. The default is nil, which is the same as `hyper'. */);
13257 Vx_hyper_keysym = Qnil;
13259 DEFVAR_LISP ("x-meta-keysym", Vx_meta_keysym,
13260 doc: /* Which keys Emacs uses for the meta modifier.
13261 This should be one of the symbols `ctrl', `alt', `hyper', `meta',
13262 `super'. For example, `meta' means use the Meta_L and Meta_R keysyms.
13263 The default is nil, which is the same as `meta'. */);
13264 Vx_meta_keysym = Qnil;
13266 DEFVAR_LISP ("x-super-keysym", Vx_super_keysym,
13267 doc: /* Which keys Emacs uses for the super modifier.
13268 This should be one of the symbols `ctrl', `alt', `hyper', `meta',
13269 `super'. For example, `super' means use the Super_L and Super_R
13270 keysyms. The default is nil, which is the same as `super'. */);
13271 Vx_super_keysym = Qnil;
13273 DEFVAR_LISP ("x-keysym-table", Vx_keysym_table,
13274 doc: /* Hash table of character codes indexed by X keysym codes. */);
13275 Vx_keysym_table = make_hash_table (hashtest_eql, 900,
13276 DEFAULT_REHASH_SIZE,
13277 DEFAULT_REHASH_THRESHOLD,
13278 Qnil, false);
13280 DEFVAR_BOOL ("x-frame-normalize-before-maximize",
13281 x_frame_normalize_before_maximize,
13282 doc: /* Non-nil means normalize frame before maximizing.
13283 If this variable is t, Emacs first asks the window manager to give the
13284 frame its normal size, and only then the final state, whenever changing
13285 from a full-height, full-width or full-both state to the maximized one
13286 or when changing from the maximized to the full-height or full-width
13287 state.
13289 Set this variable only if your window manager cannot handle the
13290 transition between the various maximization states. */);
13291 x_frame_normalize_before_maximize = false;
13293 DEFVAR_BOOL ("x-gtk-use-window-move", x_gtk_use_window_move,
13294 doc: /* Non-nil means rely on gtk_window_move to set frame positions.
13295 If this variable is t (the default), the GTK build uses the function
13296 gtk_window_move to set or store frame positions and disables some time
13297 consuming frame position adjustments. */);
13298 x_gtk_use_window_move = true;