Fix char-width-table values for some Emoji
[emacs.git] / src / xterm.c
blobc64c17463cf001039609c691759c45a5c74fb06b
1 /* X Communication module for terminals which understand the X protocol.
3 Copyright (C) 1989, 1993-2016 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 #ifdef USE_CAIRO
26 #include <math.h>
27 #endif
29 #include "lisp.h"
30 #include "blockinput.h"
32 /* This may include sys/types.h, and that somehow loses
33 if this is not done before the other system files. */
34 #include "xterm.h"
35 #include <X11/cursorfont.h>
37 /* If we have Xfixes extension, use it for pointer blanking. */
38 #ifdef HAVE_XFIXES
39 #include <X11/extensions/Xfixes.h>
40 #endif
42 /* Using Xft implies that XRender is available. */
43 #ifdef HAVE_XFT
44 #include <X11/extensions/Xrender.h>
45 #endif
47 /* Load sys/types.h if not already loaded.
48 In some systems loading it twice is suicidal. */
49 #ifndef makedev
50 #include <sys/types.h>
51 #endif /* makedev */
53 #include <sys/ioctl.h>
55 #include "systime.h"
57 #include <fcntl.h>
58 #include <errno.h>
59 #include <sys/stat.h>
60 #include "character.h"
61 #include "coding.h"
62 #include "composite.h"
63 #include "frame.h"
64 #include "dispextern.h"
65 #include "xwidget.h"
66 #include "fontset.h"
67 #include "termhooks.h"
68 #include "termopts.h"
69 #include "termchar.h"
70 #include "emacs-icon.h"
71 #include "buffer.h"
72 #include "window.h"
73 #include "keyboard.h"
74 #include "atimer.h"
75 #include "font.h"
76 #include "xsettings.h"
77 #include "sysselect.h"
78 #include "menu.h"
80 #ifdef USE_X_TOOLKIT
81 #include <X11/Shell.h>
82 #endif
84 #include <unistd.h>
86 #ifdef USE_GTK
87 #include "gtkutil.h"
88 #ifdef HAVE_GTK3
89 #include <X11/Xproto.h>
90 #endif
91 #endif
93 #if defined (USE_LUCID) || defined (USE_MOTIF)
94 #include "../lwlib/xlwmenu.h"
95 #endif
97 #ifdef USE_X_TOOLKIT
98 #if !defined (NO_EDITRES)
99 #define HACK_EDITRES
100 extern void _XEditResCheckMessages (Widget, XtPointer, XEvent *, Boolean *);
101 #endif /* not NO_EDITRES */
103 /* Include toolkit specific headers for the scroll bar widget. */
105 #ifdef USE_TOOLKIT_SCROLL_BARS
106 #if defined USE_MOTIF
107 #include <Xm/Xm.h> /* For LESSTIF_VERSION */
108 #include <Xm/ScrollBar.h>
109 #else /* !USE_MOTIF i.e. use Xaw */
111 #ifdef HAVE_XAW3D
112 #include <X11/Xaw3d/Simple.h>
113 #include <X11/Xaw3d/Scrollbar.h>
114 #include <X11/Xaw3d/ThreeD.h>
115 #else /* !HAVE_XAW3D */
116 #include <X11/Xaw/Simple.h>
117 #include <X11/Xaw/Scrollbar.h>
118 #endif /* !HAVE_XAW3D */
119 #ifndef XtNpickTop
120 #define XtNpickTop "pickTop"
121 #endif /* !XtNpickTop */
122 #endif /* !USE_MOTIF */
123 #endif /* USE_TOOLKIT_SCROLL_BARS */
125 #endif /* USE_X_TOOLKIT */
127 #ifdef USE_X_TOOLKIT
128 #include "widget.h"
129 #ifndef XtNinitialState
130 #define XtNinitialState "initialState"
131 #endif
132 #endif
134 #include "bitmaps/gray.xbm"
136 #ifdef HAVE_XKB
137 #include <X11/XKBlib.h>
138 #endif
140 /* Default to using XIM if available. */
141 #ifdef USE_XIM
142 bool use_xim = true;
143 #else
144 bool use_xim = false; /* configure --without-xim */
145 #endif
147 /* Non-zero means that a HELP_EVENT has been generated since Emacs
148 start. */
150 static bool any_help_event_p;
152 /* This is a chain of structures for all the X displays currently in
153 use. */
155 struct x_display_info *x_display_list;
157 #ifdef USE_X_TOOLKIT
159 /* The application context for Xt use. */
160 XtAppContext Xt_app_con;
161 static String Xt_default_resources[] = {0};
163 /* Non-zero means user is interacting with a toolkit scroll bar. */
164 static bool toolkit_scroll_bar_interaction;
166 #endif /* USE_X_TOOLKIT */
168 /* Non-zero timeout value means ignore next mouse click if it arrives
169 before that timeout elapses (i.e. as part of the same sequence of
170 events resulting from clicking on a frame to select it). */
172 static Time ignore_next_mouse_click_timeout;
174 /* Used locally within XTread_socket. */
176 static int x_noop_count;
178 #ifdef USE_GTK
179 /* The name of the Emacs icon file. */
180 static Lisp_Object xg_default_icon_file;
181 #endif
183 /* Some functions take this as char *, not const char *. */
184 static char emacs_class[] = EMACS_CLASS;
186 enum xembed_info
188 XEMBED_MAPPED = 1 << 0
191 enum xembed_message
193 XEMBED_EMBEDDED_NOTIFY = 0,
194 XEMBED_WINDOW_ACTIVATE = 1,
195 XEMBED_WINDOW_DEACTIVATE = 2,
196 XEMBED_REQUEST_FOCUS = 3,
197 XEMBED_FOCUS_IN = 4,
198 XEMBED_FOCUS_OUT = 5,
199 XEMBED_FOCUS_NEXT = 6,
200 XEMBED_FOCUS_PREV = 7,
202 XEMBED_MODALITY_ON = 10,
203 XEMBED_MODALITY_OFF = 11,
204 XEMBED_REGISTER_ACCELERATOR = 12,
205 XEMBED_UNREGISTER_ACCELERATOR = 13,
206 XEMBED_ACTIVATE_ACCELERATOR = 14
209 static void x_free_cr_resources (struct frame *);
210 static bool x_alloc_nearest_color_1 (Display *, Colormap, XColor *);
211 static void x_raise_frame (struct frame *);
212 static void x_lower_frame (struct frame *);
213 static int x_io_error_quitter (Display *);
214 static struct terminal *x_create_terminal (struct x_display_info *);
215 static void x_frame_rehighlight (struct x_display_info *);
217 static void x_clip_to_row (struct window *, struct glyph_row *,
218 enum glyph_row_area, GC);
219 static struct scroll_bar *x_window_to_scroll_bar (Display *, Window, int);
220 static void x_scroll_bar_report_motion (struct frame **, Lisp_Object *,
221 enum scroll_bar_part *,
222 Lisp_Object *, Lisp_Object *,
223 Time *);
224 static void x_horizontal_scroll_bar_report_motion (struct frame **, Lisp_Object *,
225 enum scroll_bar_part *,
226 Lisp_Object *, Lisp_Object *,
227 Time *);
228 static bool x_handle_net_wm_state (struct frame *, const XPropertyEvent *);
229 static void x_check_fullscreen (struct frame *);
230 static void x_check_expected_move (struct frame *, int, int);
231 static void x_sync_with_move (struct frame *, int, int, bool);
232 static int handle_one_xevent (struct x_display_info *,
233 const XEvent *, int *,
234 struct input_event *);
235 #if ! (defined USE_X_TOOLKIT || defined USE_MOTIF)
236 static int x_dispatch_event (XEvent *, Display *);
237 #endif
238 static void x_wm_set_window_state (struct frame *, int);
239 static void x_wm_set_icon_pixmap (struct frame *, ptrdiff_t);
240 static void x_initialize (void);
242 static bool get_current_wm_state (struct frame *, Window, int *, bool *);
244 /* Flush display of frame F. */
246 static void
247 x_flush (struct frame *f)
249 eassert (f && FRAME_X_P (f));
250 /* Don't call XFlush when it is not safe to redisplay; the X
251 connection may be broken. */
252 if (!NILP (Vinhibit_redisplay))
253 return;
255 block_input ();
256 XFlush (FRAME_X_DISPLAY (f));
257 unblock_input ();
261 /* Remove calls to XFlush by defining XFlush to an empty replacement.
262 Calls to XFlush should be unnecessary because the X output buffer
263 is flushed automatically as needed by calls to XPending,
264 XNextEvent, or XWindowEvent according to the XFlush man page.
265 XTread_socket calls XPending. Removing XFlush improves
266 performance. */
268 #define XFlush(DISPLAY) (void) 0
271 /***********************************************************************
272 Debugging
273 ***********************************************************************/
275 #if false
277 /* This is a function useful for recording debugging information about
278 the sequence of occurrences in this file. */
280 struct record
282 char *locus;
283 int type;
286 struct record event_record[100];
288 int event_record_index;
290 void
291 record_event (char *locus, int type)
293 if (event_record_index == ARRAYELTS (event_record))
294 event_record_index = 0;
296 event_record[event_record_index].locus = locus;
297 event_record[event_record_index].type = type;
298 event_record_index++;
301 #endif
303 #ifdef USE_CAIRO
305 #define FRAME_CR_CONTEXT(f) ((f)->output_data.x->cr_context)
306 #define FRAME_CR_SURFACE(f) ((f)->output_data.x->cr_surface)
308 static struct x_gc_ext_data *
309 x_gc_get_ext_data (struct frame *f, GC gc, int create_if_not_found_p)
311 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
312 XEDataObject object;
313 XExtData **head, *ext_data;
315 object.gc = gc;
316 head = XEHeadOfExtensionList (object);
317 ext_data = XFindOnExtensionList (head, dpyinfo->ext_codes->extension);
318 if (ext_data == NULL)
320 if (!create_if_not_found_p)
321 return NULL;
322 else
324 ext_data = xzalloc (sizeof (*ext_data));
325 ext_data->number = dpyinfo->ext_codes->extension;
326 ext_data->private_data = xzalloc (sizeof (struct x_gc_ext_data));
327 XAddToExtensionList (head, ext_data);
330 return (struct x_gc_ext_data *) ext_data->private_data;
333 static void
334 x_extension_initialize (struct x_display_info *dpyinfo)
336 XExtCodes *ext_codes = XAddExtension (dpyinfo->display);
338 dpyinfo->ext_codes = ext_codes;
341 static void
342 x_cr_destroy_surface (struct frame *f)
344 if (FRAME_CR_SURFACE (f))
346 cairo_t *cr = FRAME_CR_CONTEXT (f);
347 cairo_surface_destroy (FRAME_CR_SURFACE (f));
348 FRAME_CR_SURFACE (f) = 0;
349 if (cr) cairo_destroy (cr);
350 FRAME_CR_CONTEXT (f) = NULL;
354 cairo_t *
355 x_begin_cr_clip (struct frame *f, GC gc)
357 cairo_t *cr = FRAME_CR_CONTEXT (f);
359 if (!cr)
362 if (! FRAME_CR_SURFACE (f))
364 cairo_surface_t *surface;
365 surface = cairo_xlib_surface_create (FRAME_X_DISPLAY (f),
366 FRAME_X_WINDOW (f),
367 FRAME_DISPLAY_INFO (f)->visual,
368 FRAME_PIXEL_WIDTH (f),
369 FRAME_PIXEL_HEIGHT (f));
370 cr = cairo_create (surface);
371 cairo_surface_destroy (surface);
373 else
374 cr = cairo_create (FRAME_CR_SURFACE (f));
375 FRAME_CR_CONTEXT (f) = cr;
377 cairo_save (cr);
379 if (gc)
381 struct x_gc_ext_data *gc_ext = x_gc_get_ext_data (f, gc, 0);
383 if (gc_ext && gc_ext->n_clip_rects)
385 int i;
387 for (i = 0; i < gc_ext->n_clip_rects; i++)
388 cairo_rectangle (cr, gc_ext->clip_rects[i].x,
389 gc_ext->clip_rects[i].y,
390 gc_ext->clip_rects[i].width,
391 gc_ext->clip_rects[i].height);
392 cairo_clip (cr);
396 return cr;
399 void
400 x_end_cr_clip (struct frame *f)
402 cairo_restore (FRAME_CR_CONTEXT (f));
405 void
406 x_set_cr_source_with_gc_foreground (struct frame *f, GC gc)
408 XGCValues xgcv;
409 XColor color;
411 XGetGCValues (FRAME_X_DISPLAY (f), gc, GCForeground, &xgcv);
412 color.pixel = xgcv.foreground;
413 x_query_color (f, &color);
414 cairo_set_source_rgb (FRAME_CR_CONTEXT (f), color.red / 65535.0,
415 color.green / 65535.0, color.blue / 65535.0);
418 void
419 x_set_cr_source_with_gc_background (struct frame *f, GC gc)
421 XGCValues xgcv;
422 XColor color;
424 XGetGCValues (FRAME_X_DISPLAY (f), gc, GCBackground, &xgcv);
425 color.pixel = xgcv.background;
426 x_query_color (f, &color);
427 cairo_set_source_rgb (FRAME_CR_CONTEXT (f), color.red / 65535.0,
428 color.green / 65535.0, color.blue / 65535.0);
431 /* Fringe bitmaps. */
433 static int max_fringe_bmp = 0;
434 static cairo_pattern_t **fringe_bmp = 0;
436 static void
437 x_cr_define_fringe_bitmap (int which, unsigned short *bits, int h, int wd)
439 int i, stride;
440 cairo_surface_t *surface;
441 unsigned char *data;
442 cairo_pattern_t *pattern;
444 if (which >= max_fringe_bmp)
446 i = max_fringe_bmp;
447 max_fringe_bmp = which + 20;
448 fringe_bmp = (cairo_pattern_t **) xrealloc (fringe_bmp, max_fringe_bmp * sizeof (cairo_pattern_t *));
449 while (i < max_fringe_bmp)
450 fringe_bmp[i++] = 0;
453 block_input ();
455 surface = cairo_image_surface_create (CAIRO_FORMAT_A1, wd, h);
456 stride = cairo_image_surface_get_stride (surface);
457 data = cairo_image_surface_get_data (surface);
459 for (i = 0; i < h; i++)
461 *((unsigned short *) data) = bits[i];
462 data += stride;
465 cairo_surface_mark_dirty (surface);
466 pattern = cairo_pattern_create_for_surface (surface);
467 cairo_surface_destroy (surface);
469 unblock_input ();
471 fringe_bmp[which] = pattern;
474 static void
475 x_cr_destroy_fringe_bitmap (int which)
477 if (which >= max_fringe_bmp)
478 return;
480 if (fringe_bmp[which])
482 block_input ();
483 cairo_pattern_destroy (fringe_bmp[which]);
484 unblock_input ();
486 fringe_bmp[which] = 0;
489 static void
490 x_cr_draw_image (struct frame *f, GC gc, cairo_pattern_t *image,
491 int src_x, int src_y, int width, int height,
492 int dest_x, int dest_y, bool overlay_p)
494 cairo_t *cr;
495 cairo_matrix_t matrix;
496 cairo_surface_t *surface;
497 cairo_format_t format;
499 cr = x_begin_cr_clip (f, gc);
500 if (overlay_p)
501 cairo_rectangle (cr, dest_x, dest_y, width, height);
502 else
504 x_set_cr_source_with_gc_background (f, gc);
505 cairo_rectangle (cr, dest_x, dest_y, width, height);
506 cairo_fill_preserve (cr);
508 cairo_clip (cr);
509 cairo_matrix_init_translate (&matrix, src_x - dest_x, src_y - dest_y);
510 cairo_pattern_set_matrix (image, &matrix);
511 cairo_pattern_get_surface (image, &surface);
512 format = cairo_image_surface_get_format (surface);
513 if (format != CAIRO_FORMAT_A8 && format != CAIRO_FORMAT_A1)
515 cairo_set_source (cr, image);
516 cairo_fill (cr);
518 else
520 x_set_cr_source_with_gc_foreground (f, gc);
521 cairo_mask (cr, image);
523 x_end_cr_clip (f);
526 void
527 x_cr_draw_frame (cairo_t *cr, struct frame *f)
529 int width, height;
531 width = FRAME_PIXEL_WIDTH (f);
532 height = FRAME_PIXEL_HEIGHT (f);
534 x_free_cr_resources (f);
535 FRAME_CR_CONTEXT (f) = cr;
536 x_clear_area (f, 0, 0, width, height);
537 expose_frame (f, 0, 0, width, height);
538 FRAME_CR_CONTEXT (f) = NULL;
541 static cairo_status_t
542 x_cr_accumulate_data (void *closure, const unsigned char *data,
543 unsigned int length)
545 Lisp_Object *acc = (Lisp_Object *) closure;
547 *acc = Fcons (make_unibyte_string ((char const *) data, length), *acc);
549 return CAIRO_STATUS_SUCCESS;
552 static void
553 x_cr_destroy (Lisp_Object arg)
555 cairo_t *cr = (cairo_t *) XSAVE_POINTER (arg, 0);
557 block_input ();
558 cairo_destroy (cr);
559 unblock_input ();
562 Lisp_Object
563 x_cr_export_frames (Lisp_Object frames, cairo_surface_type_t surface_type)
565 struct frame *f;
566 cairo_surface_t *surface;
567 cairo_t *cr;
568 int width, height;
569 void (*surface_set_size_func) (cairo_surface_t *, double, double) = NULL;
570 Lisp_Object acc = Qnil;
571 int count = SPECPDL_INDEX ();
573 specbind (Qredisplay_dont_pause, Qt);
574 redisplay_preserve_echo_area (31);
576 f = XFRAME (XCAR (frames));
577 frames = XCDR (frames);
578 width = FRAME_PIXEL_WIDTH (f);
579 height = FRAME_PIXEL_HEIGHT (f);
581 block_input ();
582 #ifdef CAIRO_HAS_PDF_SURFACE
583 if (surface_type == CAIRO_SURFACE_TYPE_PDF)
585 surface = cairo_pdf_surface_create_for_stream (x_cr_accumulate_data, &acc,
586 width, height);
587 surface_set_size_func = cairo_pdf_surface_set_size;
589 else
590 #endif
591 #ifdef CAIRO_HAS_PNG_FUNCTIONS
592 if (surface_type == CAIRO_SURFACE_TYPE_IMAGE)
593 surface = cairo_image_surface_create (CAIRO_FORMAT_RGB24, width, height);
594 else
595 #endif
596 #ifdef CAIRO_HAS_PS_SURFACE
597 if (surface_type == CAIRO_SURFACE_TYPE_PS)
599 surface = cairo_ps_surface_create_for_stream (x_cr_accumulate_data, &acc,
600 width, height);
601 surface_set_size_func = cairo_ps_surface_set_size;
603 else
604 #endif
605 #ifdef CAIRO_HAS_SVG_SURFACE
606 if (surface_type == CAIRO_SURFACE_TYPE_SVG)
607 surface = cairo_svg_surface_create_for_stream (x_cr_accumulate_data, &acc,
608 width, height);
609 else
610 #endif
611 abort ();
613 cr = cairo_create (surface);
614 cairo_surface_destroy (surface);
615 record_unwind_protect (x_cr_destroy, make_save_ptr (cr));
617 while (1)
619 x_free_cr_resources (f);
620 FRAME_CR_CONTEXT (f) = cr;
621 x_clear_area (f, 0, 0, width, height);
622 expose_frame (f, 0, 0, width, height);
623 FRAME_CR_CONTEXT (f) = NULL;
625 if (NILP (frames))
626 break;
628 cairo_surface_show_page (surface);
629 f = XFRAME (XCAR (frames));
630 frames = XCDR (frames);
631 width = FRAME_PIXEL_WIDTH (f);
632 height = FRAME_PIXEL_HEIGHT (f);
633 if (surface_set_size_func)
634 (*surface_set_size_func) (surface, width, height);
636 unblock_input ();
637 QUIT;
638 block_input ();
641 #ifdef CAIRO_HAS_PNG_FUNCTIONS
642 if (surface_type == CAIRO_SURFACE_TYPE_IMAGE)
644 cairo_surface_flush (surface);
645 cairo_surface_write_to_png_stream (surface, x_cr_accumulate_data, &acc);
647 #endif
648 unblock_input ();
650 unbind_to (count, Qnil);
652 return CALLN (Fapply, intern ("concat"), Fnreverse (acc));
655 #endif /* USE_CAIRO */
657 static void
658 x_free_cr_resources (struct frame *f)
660 #ifdef USE_CAIRO
661 if (f == NULL)
663 Lisp_Object rest, frame;
664 FOR_EACH_FRAME (rest, frame)
665 if (FRAME_X_P (XFRAME (frame)))
666 x_free_cr_resources (XFRAME (frame));
668 else
670 cairo_t *cr = FRAME_CR_CONTEXT (f);
672 if (cr)
674 cairo_surface_t *surface = cairo_get_target (cr);
676 if (cairo_surface_get_type (surface) == CAIRO_SURFACE_TYPE_XLIB)
678 cairo_destroy (cr);
679 FRAME_CR_CONTEXT (f) = NULL;
683 #endif
686 static void
687 x_set_clip_rectangles (struct frame *f, GC gc, XRectangle *rectangles, int n)
689 XSetClipRectangles (FRAME_X_DISPLAY (f), gc, 0, 0, rectangles, n, Unsorted);
690 #ifdef USE_CAIRO
691 eassert (n >= 0 && n <= MAX_CLIP_RECTS);
694 struct x_gc_ext_data *gc_ext = x_gc_get_ext_data (f, gc, 1);
696 gc_ext->n_clip_rects = n;
697 memcpy (gc_ext->clip_rects, rectangles, sizeof (XRectangle) * n);
699 #endif
702 static void
703 x_reset_clip_rectangles (struct frame *f, GC gc)
705 XSetClipMask (FRAME_X_DISPLAY (f), gc, None);
706 #ifdef USE_CAIRO
708 struct x_gc_ext_data *gc_ext = x_gc_get_ext_data (f, gc, 0);
710 if (gc_ext)
711 gc_ext->n_clip_rects = 0;
713 #endif
716 static void
717 x_fill_rectangle (struct frame *f, GC gc, int x, int y, int width, int height)
719 #ifdef USE_CAIRO
720 cairo_t *cr;
722 cr = x_begin_cr_clip (f, gc);
723 x_set_cr_source_with_gc_foreground (f, gc);
724 cairo_rectangle (cr, x, y, width, height);
725 cairo_fill (cr);
726 x_end_cr_clip (f);
727 #else
728 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
729 gc, x, y, width, height);
730 #endif
733 static void
734 x_draw_rectangle (struct frame *f, GC gc, int x, int y, int width, int height)
736 #ifdef USE_CAIRO
737 cairo_t *cr;
739 cr = x_begin_cr_clip (f, gc);
740 x_set_cr_source_with_gc_foreground (f, gc);
741 cairo_rectangle (cr, x + 0.5, y + 0.5, width, height);
742 cairo_set_line_width (cr, 1);
743 cairo_stroke (cr);
744 x_end_cr_clip (f);
745 #else
746 XDrawRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
747 gc, x, y, width, height);
748 #endif
751 static void
752 x_clear_window (struct frame *f)
754 #ifdef USE_CAIRO
755 cairo_t *cr;
757 cr = x_begin_cr_clip (f, NULL);
758 x_set_cr_source_with_gc_background (f, f->output_data.x->normal_gc);
759 cairo_paint (cr);
760 x_end_cr_clip (f);
761 #else
762 XClearWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
763 #endif
766 #ifdef USE_CAIRO
767 static void
768 x_fill_trapezoid_for_relief (struct frame *f, GC gc, int x, int y,
769 int width, int height, int top_p)
771 cairo_t *cr;
773 cr = x_begin_cr_clip (f, gc);
774 x_set_cr_source_with_gc_foreground (f, gc);
775 cairo_move_to (cr, top_p ? x : x + height, y);
776 cairo_line_to (cr, x, y + height);
777 cairo_line_to (cr, top_p ? x + width - height : x + width, y + height);
778 cairo_line_to (cr, x + width, y);
779 cairo_fill (cr);
780 x_end_cr_clip (f);
783 enum corners
785 CORNER_BOTTOM_RIGHT, /* 0 -> pi/2 */
786 CORNER_BOTTOM_LEFT, /* pi/2 -> pi */
787 CORNER_TOP_LEFT, /* pi -> 3pi/2 */
788 CORNER_TOP_RIGHT, /* 3pi/2 -> 2pi */
789 CORNER_LAST
792 static void
793 x_erase_corners_for_relief (struct frame *f, GC gc, int x, int y,
794 int width, int height,
795 double radius, double margin, int corners)
797 cairo_t *cr;
798 int i;
800 cr = x_begin_cr_clip (f, gc);
801 x_set_cr_source_with_gc_background (f, gc);
802 for (i = 0; i < CORNER_LAST; i++)
803 if (corners & (1 << i))
805 double xm, ym, xc, yc;
807 if (i == CORNER_TOP_LEFT || i == CORNER_BOTTOM_LEFT)
808 xm = x - margin, xc = xm + radius;
809 else
810 xm = x + width + margin, xc = xm - radius;
811 if (i == CORNER_TOP_LEFT || i == CORNER_TOP_RIGHT)
812 ym = y - margin, yc = ym + radius;
813 else
814 ym = y + height + margin, yc = ym - radius;
816 cairo_move_to (cr, xm, ym);
817 cairo_arc (cr, xc, yc, radius, i * M_PI_2, (i + 1) * M_PI_2);
819 cairo_clip (cr);
820 cairo_rectangle (cr, x, y, width, height);
821 cairo_fill (cr);
822 x_end_cr_clip (f);
825 static void
826 x_draw_horizontal_wave (struct frame *f, GC gc, int x, int y,
827 int width, int height, int wave_length)
829 cairo_t *cr;
830 double dx = wave_length, dy = height - 1;
831 int xoffset, n;
833 cr = x_begin_cr_clip (f, gc);
834 x_set_cr_source_with_gc_foreground (f, gc);
835 cairo_rectangle (cr, x, y, width, height);
836 cairo_clip (cr);
838 if (x >= 0)
840 xoffset = x % (wave_length * 2);
841 if (xoffset == 0)
842 xoffset = wave_length * 2;
844 else
845 xoffset = x % (wave_length * 2) + wave_length * 2;
846 n = (width + xoffset) / wave_length + 1;
847 if (xoffset > wave_length)
849 xoffset -= wave_length;
850 --n;
851 y += height - 1;
852 dy = -dy;
855 cairo_move_to (cr, x - xoffset + 0.5, y + 0.5);
856 while (--n >= 0)
858 cairo_rel_line_to (cr, dx, dy);
859 dy = -dy;
861 cairo_set_line_width (cr, 1);
862 cairo_stroke (cr);
863 x_end_cr_clip (f);
865 #endif
868 /* Return the struct x_display_info corresponding to DPY. */
870 struct x_display_info *
871 x_display_info_for_display (Display *dpy)
873 struct x_display_info *dpyinfo;
875 for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
876 if (dpyinfo->display == dpy)
877 return dpyinfo;
879 return 0;
882 static Window
883 x_find_topmost_parent (struct frame *f)
885 struct x_output *x = f->output_data.x;
886 Window win = None, wi = x->parent_desc;
887 Display *dpy = FRAME_X_DISPLAY (f);
889 while (wi != FRAME_DISPLAY_INFO (f)->root_window)
891 Window root;
892 Window *children;
893 unsigned int nchildren;
895 win = wi;
896 if (XQueryTree (dpy, win, &root, &wi, &children, &nchildren))
897 XFree (children);
898 else
899 break;
902 return win;
905 #define OPAQUE 0xffffffff
907 void
908 x_set_frame_alpha (struct frame *f)
910 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
911 Display *dpy = FRAME_X_DISPLAY (f);
912 Window win = FRAME_OUTER_WINDOW (f);
913 double alpha = 1.0;
914 double alpha_min = 1.0;
915 unsigned long opac;
916 Window parent;
918 if (dpyinfo->x_highlight_frame == f)
919 alpha = f->alpha[0];
920 else
921 alpha = f->alpha[1];
923 if (FLOATP (Vframe_alpha_lower_limit))
924 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
925 else if (INTEGERP (Vframe_alpha_lower_limit))
926 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
928 if (alpha < 0.0)
929 return;
930 else if (alpha > 1.0)
931 alpha = 1.0;
932 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
933 alpha = alpha_min;
935 opac = alpha * OPAQUE;
937 x_catch_errors (dpy);
939 /* If there is a parent from the window manager, put the property there
940 also, to work around broken window managers that fail to do that.
941 Do this unconditionally as this function is called on reparent when
942 alpha has not changed on the frame. */
944 parent = x_find_topmost_parent (f);
945 if (parent != None)
946 XChangeProperty (dpy, parent, dpyinfo->Xatom_net_wm_window_opacity,
947 XA_CARDINAL, 32, PropModeReplace,
948 (unsigned char *) &opac, 1);
950 /* return unless necessary */
952 unsigned char *data;
953 Atom actual;
954 int rc, format;
955 unsigned long n, left;
957 rc = XGetWindowProperty (dpy, win, dpyinfo->Xatom_net_wm_window_opacity,
958 0, 1, False, XA_CARDINAL,
959 &actual, &format, &n, &left,
960 &data);
962 if (rc == Success && actual != None)
964 unsigned long value = *(unsigned long *)data;
965 XFree (data);
966 if (value == opac)
968 x_uncatch_errors ();
969 return;
974 XChangeProperty (dpy, win, dpyinfo->Xatom_net_wm_window_opacity,
975 XA_CARDINAL, 32, PropModeReplace,
976 (unsigned char *) &opac, 1);
977 x_uncatch_errors ();
980 /***********************************************************************
981 Starting and ending an update
982 ***********************************************************************/
984 /* Start an update of frame F. This function is installed as a hook
985 for update_begin, i.e. it is called when update_begin is called.
986 This function is called prior to calls to x_update_window_begin for
987 each window being updated. Currently, there is nothing to do here
988 because all interesting stuff is done on a window basis. */
990 static void
991 x_update_begin (struct frame *f)
993 #ifdef USE_CAIRO
994 if (! NILP (tip_frame) && XFRAME (tip_frame) == f
995 && ! FRAME_VISIBLE_P (f))
996 return;
998 if (! FRAME_CR_SURFACE (f))
1000 int width, height;
1001 #ifdef USE_GTK
1002 if (FRAME_GTK_WIDGET (f))
1004 GdkWindow *w = gtk_widget_get_window (FRAME_GTK_WIDGET (f));
1005 width = gdk_window_get_width (w);
1006 height = gdk_window_get_height (w);
1008 else
1009 #endif
1011 width = FRAME_PIXEL_WIDTH (f);
1012 height = FRAME_PIXEL_HEIGHT (f);
1013 if (! FRAME_EXTERNAL_TOOL_BAR (f))
1014 height += FRAME_TOOL_BAR_HEIGHT (f);
1015 if (! FRAME_EXTERNAL_MENU_BAR (f))
1016 height += FRAME_MENU_BAR_HEIGHT (f);
1019 if (width > 0 && height > 0)
1021 block_input();
1022 FRAME_CR_SURFACE (f) = cairo_image_surface_create
1023 (CAIRO_FORMAT_ARGB32, width, height);
1024 unblock_input();
1027 #endif /* USE_CAIRO */
1030 /* Start update of window W. */
1032 static void
1033 x_update_window_begin (struct window *w)
1035 struct frame *f = XFRAME (WINDOW_FRAME (w));
1036 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1038 w->output_cursor = w->cursor;
1040 block_input ();
1042 if (f == hlinfo->mouse_face_mouse_frame)
1044 /* Don't do highlighting for mouse motion during the update. */
1045 hlinfo->mouse_face_defer = true;
1047 /* If F needs to be redrawn, simply forget about any prior mouse
1048 highlighting. */
1049 if (FRAME_GARBAGED_P (f))
1050 hlinfo->mouse_face_window = Qnil;
1053 unblock_input ();
1057 /* Draw a vertical window border from (x,y0) to (x,y1) */
1059 static void
1060 x_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
1062 struct frame *f = XFRAME (WINDOW_FRAME (w));
1063 struct face *face;
1065 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
1066 if (face)
1067 XSetForeground (FRAME_X_DISPLAY (f), f->output_data.x->normal_gc,
1068 face->foreground);
1070 #ifdef USE_CAIRO
1071 x_fill_rectangle (f, f->output_data.x->normal_gc, x, y0, 1, y1 - y0);
1072 #else
1073 XDrawLine (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
1074 f->output_data.x->normal_gc, x, y0, x, y1);
1075 #endif
1078 /* Draw a window divider from (x0,y0) to (x1,y1) */
1080 static void
1081 x_draw_window_divider (struct window *w, int x0, int x1, int y0, int y1)
1083 struct frame *f = XFRAME (WINDOW_FRAME (w));
1084 struct face *face = FACE_FROM_ID (f, WINDOW_DIVIDER_FACE_ID);
1085 struct face *face_first = FACE_FROM_ID (f, WINDOW_DIVIDER_FIRST_PIXEL_FACE_ID);
1086 struct face *face_last = FACE_FROM_ID (f, WINDOW_DIVIDER_LAST_PIXEL_FACE_ID);
1087 unsigned long color = face ? face->foreground : FRAME_FOREGROUND_PIXEL (f);
1088 unsigned long color_first = (face_first
1089 ? face_first->foreground
1090 : FRAME_FOREGROUND_PIXEL (f));
1091 unsigned long color_last = (face_last
1092 ? face_last->foreground
1093 : FRAME_FOREGROUND_PIXEL (f));
1094 Display *display = FRAME_X_DISPLAY (f);
1096 if (y1 - y0 > x1 - x0 && x1 - x0 > 2)
1097 /* Vertical. */
1099 XSetForeground (display, f->output_data.x->normal_gc, color_first);
1100 x_fill_rectangle (f, f->output_data.x->normal_gc,
1101 x0, y0, 1, y1 - y0);
1102 XSetForeground (display, f->output_data.x->normal_gc, color);
1103 x_fill_rectangle (f, f->output_data.x->normal_gc,
1104 x0 + 1, y0, x1 - x0 - 2, y1 - y0);
1105 XSetForeground (display, f->output_data.x->normal_gc, color_last);
1106 x_fill_rectangle (f, f->output_data.x->normal_gc,
1107 x1 - 1, y0, 1, y1 - y0);
1109 else if (x1 - x0 > y1 - y0 && y1 - y0 > 3)
1110 /* Horizontal. */
1112 XSetForeground (display, f->output_data.x->normal_gc, color_first);
1113 x_fill_rectangle (f, f->output_data.x->normal_gc,
1114 x0, y0, x1 - x0, 1);
1115 XSetForeground (display, f->output_data.x->normal_gc, color);
1116 x_fill_rectangle (f, f->output_data.x->normal_gc,
1117 x0, y0 + 1, x1 - x0, y1 - y0 - 2);
1118 XSetForeground (display, f->output_data.x->normal_gc, color_last);
1119 x_fill_rectangle (f, f->output_data.x->normal_gc,
1120 x0, y1 - 1, x1 - x0, 1);
1122 else
1124 XSetForeground (display, f->output_data.x->normal_gc, color);
1125 x_fill_rectangle (f, f->output_data.x->normal_gc,
1126 x0, y0, x1 - x0, y1 - y0);
1130 /* End update of window W.
1132 Draw vertical borders between horizontally adjacent windows, and
1133 display W's cursor if CURSOR_ON_P is non-zero.
1135 MOUSE_FACE_OVERWRITTEN_P non-zero means that some row containing
1136 glyphs in mouse-face were overwritten. In that case we have to
1137 make sure that the mouse-highlight is properly redrawn.
1139 W may be a menu bar pseudo-window in case we don't have X toolkit
1140 support. Such windows don't have a cursor, so don't display it
1141 here. */
1143 static void
1144 x_update_window_end (struct window *w, bool cursor_on_p,
1145 bool mouse_face_overwritten_p)
1147 if (!w->pseudo_window_p)
1149 block_input ();
1151 if (cursor_on_p)
1152 display_and_set_cursor (w, true,
1153 w->output_cursor.hpos, w->output_cursor.vpos,
1154 w->output_cursor.x, w->output_cursor.y);
1156 if (draw_window_fringes (w, true))
1158 if (WINDOW_RIGHT_DIVIDER_WIDTH (w))
1159 x_draw_right_divider (w);
1160 else
1161 x_draw_vertical_border (w);
1164 unblock_input ();
1167 /* If a row with mouse-face was overwritten, arrange for
1168 XTframe_up_to_date to redisplay the mouse highlight. */
1169 if (mouse_face_overwritten_p)
1171 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (XFRAME (w->frame));
1173 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
1174 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
1175 hlinfo->mouse_face_window = Qnil;
1180 /* End update of frame F. This function is installed as a hook in
1181 update_end. */
1183 static void
1184 x_update_end (struct frame *f)
1186 /* Mouse highlight may be displayed again. */
1187 MOUSE_HL_INFO (f)->mouse_face_defer = false;
1189 #ifdef USE_CAIRO
1190 if (FRAME_CR_SURFACE (f))
1192 cairo_t *cr = 0;
1193 block_input();
1194 #if defined (USE_GTK) && defined (HAVE_GTK3)
1195 if (FRAME_GTK_WIDGET (f))
1197 GdkWindow *w = gtk_widget_get_window (FRAME_GTK_WIDGET (f));
1198 cr = gdk_cairo_create (w);
1200 else
1201 #endif
1203 cairo_surface_t *surface;
1204 int width = FRAME_PIXEL_WIDTH (f);
1205 int height = FRAME_PIXEL_HEIGHT (f);
1206 if (! FRAME_EXTERNAL_TOOL_BAR (f))
1207 height += FRAME_TOOL_BAR_HEIGHT (f);
1208 if (! FRAME_EXTERNAL_MENU_BAR (f))
1209 height += FRAME_MENU_BAR_HEIGHT (f);
1210 surface = cairo_xlib_surface_create (FRAME_X_DISPLAY (f),
1211 FRAME_X_WINDOW (f),
1212 FRAME_DISPLAY_INFO (f)->visual,
1213 width,
1214 height);
1215 cr = cairo_create (surface);
1216 cairo_surface_destroy (surface);
1219 cairo_set_source_surface (cr, FRAME_CR_SURFACE (f), 0, 0);
1220 cairo_paint (cr);
1221 cairo_destroy (cr);
1222 unblock_input ();
1224 #endif /* USE_CAIRO */
1226 #ifndef XFlush
1227 block_input ();
1228 XFlush (FRAME_X_DISPLAY (f));
1229 unblock_input ();
1230 #endif
1234 /* This function is called from various places in xdisp.c
1235 whenever a complete update has been performed. */
1237 static void
1238 XTframe_up_to_date (struct frame *f)
1240 if (FRAME_X_P (f))
1241 FRAME_MOUSE_UPDATE (f);
1245 /* Clear under internal border if any (GTK has its own version). */
1246 #ifndef USE_GTK
1247 void
1248 x_clear_under_internal_border (struct frame *f)
1250 if (FRAME_INTERNAL_BORDER_WIDTH (f) > 0)
1252 int border = FRAME_INTERNAL_BORDER_WIDTH (f);
1253 int width = FRAME_PIXEL_WIDTH (f);
1254 int height = FRAME_PIXEL_HEIGHT (f);
1255 int margin = FRAME_TOP_MARGIN_HEIGHT (f);
1257 block_input ();
1258 x_clear_area (f, 0, 0, border, height);
1259 x_clear_area (f, 0, margin, width, border);
1260 x_clear_area (f, width - border, 0, border, height);
1261 x_clear_area (f, 0, height - border, width, border);
1262 unblock_input ();
1265 #endif
1267 /* Draw truncation mark bitmaps, continuation mark bitmaps, overlay
1268 arrow bitmaps, or clear the fringes if no bitmaps are required
1269 before DESIRED_ROW is made current. This function is called from
1270 update_window_line only if it is known that there are differences
1271 between bitmaps to be drawn between current row and DESIRED_ROW. */
1273 static void
1274 x_after_update_window_line (struct window *w, struct glyph_row *desired_row)
1276 eassert (w);
1278 if (!desired_row->mode_line_p && !w->pseudo_window_p)
1279 desired_row->redraw_fringe_bitmaps_p = true;
1281 #ifdef USE_X_TOOLKIT
1282 /* When a window has disappeared, make sure that no rest of
1283 full-width rows stays visible in the internal border. Could
1284 check here if updated window is the leftmost/rightmost window,
1285 but I guess it's not worth doing since vertically split windows
1286 are almost never used, internal border is rarely set, and the
1287 overhead is very small. */
1289 struct frame *f;
1290 int width, height;
1292 if (windows_or_buffers_changed
1293 && desired_row->full_width_p
1294 && (f = XFRAME (w->frame),
1295 width = FRAME_INTERNAL_BORDER_WIDTH (f),
1296 width != 0)
1297 && (height = desired_row->visible_height,
1298 height > 0))
1300 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
1302 block_input ();
1303 x_clear_area (f, 0, y, width, height);
1304 x_clear_area (f, FRAME_PIXEL_WIDTH (f) - width, y, width, height);
1305 unblock_input ();
1308 #endif
1311 static void
1312 x_draw_fringe_bitmap (struct window *w, struct glyph_row *row, struct draw_fringe_bitmap_params *p)
1314 struct frame *f = XFRAME (WINDOW_FRAME (w));
1315 Display *display = FRAME_X_DISPLAY (f);
1316 GC gc = f->output_data.x->normal_gc;
1317 struct face *face = p->face;
1319 /* Must clip because of partially visible lines. */
1320 x_clip_to_row (w, row, ANY_AREA, gc);
1322 if (p->bx >= 0 && !p->overlay_p)
1324 /* In case the same realized face is used for fringes and
1325 for something displayed in the text (e.g. face `region' on
1326 mono-displays, the fill style may have been changed to
1327 FillSolid in x_draw_glyph_string_background. */
1328 if (face->stipple)
1329 XSetFillStyle (display, face->gc, FillOpaqueStippled);
1330 else
1331 XSetForeground (display, face->gc, face->background);
1333 x_fill_rectangle (f, face->gc, p->bx, p->by, p->nx, p->ny);
1335 if (!face->stipple)
1336 XSetForeground (display, face->gc, face->foreground);
1339 #ifdef USE_CAIRO
1340 if (p->which && p->which < max_fringe_bmp)
1342 XGCValues gcv;
1344 XGetGCValues (display, gc, GCForeground | GCBackground, &gcv);
1345 XSetForeground (display, gc, (p->cursor_p
1346 ? (p->overlay_p ? face->background
1347 : f->output_data.x->cursor_pixel)
1348 : face->foreground));
1349 XSetBackground (display, gc, face->background);
1350 x_cr_draw_image (f, gc, fringe_bmp[p->which], 0, p->dh,
1351 p->wd, p->h, p->x, p->y, p->overlay_p);
1352 XSetForeground (display, gc, gcv.foreground);
1353 XSetBackground (display, gc, gcv.background);
1355 #else /* not USE_CAIRO */
1356 if (p->which)
1358 Window window = FRAME_X_WINDOW (f);
1359 char *bits;
1360 Pixmap pixmap, clipmask = (Pixmap) 0;
1361 int depth = DefaultDepthOfScreen (FRAME_X_SCREEN (f));
1362 XGCValues gcv;
1364 if (p->wd > 8)
1365 bits = (char *) (p->bits + p->dh);
1366 else
1367 bits = (char *) p->bits + p->dh;
1369 /* Draw the bitmap. I believe these small pixmaps can be cached
1370 by the server. */
1371 pixmap = XCreatePixmapFromBitmapData (display, window, bits, p->wd, p->h,
1372 (p->cursor_p
1373 ? (p->overlay_p ? face->background
1374 : f->output_data.x->cursor_pixel)
1375 : face->foreground),
1376 face->background, depth);
1378 if (p->overlay_p)
1380 clipmask = XCreatePixmapFromBitmapData (display,
1381 FRAME_DISPLAY_INFO (f)->root_window,
1382 bits, p->wd, p->h,
1383 1, 0, 1);
1384 gcv.clip_mask = clipmask;
1385 gcv.clip_x_origin = p->x;
1386 gcv.clip_y_origin = p->y;
1387 XChangeGC (display, gc, GCClipMask | GCClipXOrigin | GCClipYOrigin, &gcv);
1390 XCopyArea (display, pixmap, window, gc, 0, 0,
1391 p->wd, p->h, p->x, p->y);
1392 XFreePixmap (display, pixmap);
1394 if (p->overlay_p)
1396 gcv.clip_mask = (Pixmap) 0;
1397 XChangeGC (display, gc, GCClipMask, &gcv);
1398 XFreePixmap (display, clipmask);
1401 #endif /* not USE_CAIRO */
1403 x_reset_clip_rectangles (f, gc);
1406 /***********************************************************************
1407 Glyph display
1408 ***********************************************************************/
1412 static void x_set_glyph_string_clipping (struct glyph_string *);
1413 static void x_set_glyph_string_gc (struct glyph_string *);
1414 static void x_draw_glyph_string_foreground (struct glyph_string *);
1415 static void x_draw_composite_glyph_string_foreground (struct glyph_string *);
1416 static void x_draw_glyph_string_box (struct glyph_string *);
1417 static void x_draw_glyph_string (struct glyph_string *);
1418 static _Noreturn void x_delete_glyphs (struct frame *, int);
1419 static void x_compute_glyph_string_overhangs (struct glyph_string *);
1420 static void x_set_cursor_gc (struct glyph_string *);
1421 static void x_set_mode_line_face_gc (struct glyph_string *);
1422 static void x_set_mouse_face_gc (struct glyph_string *);
1423 static bool x_alloc_lighter_color (struct frame *, Display *, Colormap,
1424 unsigned long *, double, int);
1425 static void x_setup_relief_color (struct frame *, struct relief *,
1426 double, int, unsigned long);
1427 static void x_setup_relief_colors (struct glyph_string *);
1428 static void x_draw_image_glyph_string (struct glyph_string *);
1429 static void x_draw_image_relief (struct glyph_string *);
1430 static void x_draw_image_foreground (struct glyph_string *);
1431 static void x_draw_image_foreground_1 (struct glyph_string *, Pixmap);
1432 static void x_clear_glyph_string_rect (struct glyph_string *, int,
1433 int, int, int);
1434 static void x_draw_relief_rect (struct frame *, int, int, int, int,
1435 int, bool, bool, bool, bool, bool,
1436 XRectangle *);
1437 static void x_draw_box_rect (struct glyph_string *, int, int, int, int,
1438 int, bool, bool, XRectangle *);
1439 static void x_scroll_bar_clear (struct frame *);
1441 #ifdef GLYPH_DEBUG
1442 static void x_check_font (struct frame *, struct font *);
1443 #endif
1446 /* Set S->gc to a suitable GC for drawing glyph string S in cursor
1447 face. */
1449 static void
1450 x_set_cursor_gc (struct glyph_string *s)
1452 if (s->font == FRAME_FONT (s->f)
1453 && s->face->background == FRAME_BACKGROUND_PIXEL (s->f)
1454 && s->face->foreground == FRAME_FOREGROUND_PIXEL (s->f)
1455 && !s->cmp)
1456 s->gc = s->f->output_data.x->cursor_gc;
1457 else
1459 /* Cursor on non-default face: must merge. */
1460 XGCValues xgcv;
1461 unsigned long mask;
1463 xgcv.background = s->f->output_data.x->cursor_pixel;
1464 xgcv.foreground = s->face->background;
1466 /* If the glyph would be invisible, try a different foreground. */
1467 if (xgcv.foreground == xgcv.background)
1468 xgcv.foreground = s->face->foreground;
1469 if (xgcv.foreground == xgcv.background)
1470 xgcv.foreground = s->f->output_data.x->cursor_foreground_pixel;
1471 if (xgcv.foreground == xgcv.background)
1472 xgcv.foreground = s->face->foreground;
1474 /* Make sure the cursor is distinct from text in this face. */
1475 if (xgcv.background == s->face->background
1476 && xgcv.foreground == s->face->foreground)
1478 xgcv.background = s->face->foreground;
1479 xgcv.foreground = s->face->background;
1482 IF_DEBUG (x_check_font (s->f, s->font));
1483 xgcv.graphics_exposures = False;
1484 mask = GCForeground | GCBackground | GCGraphicsExposures;
1486 if (FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc)
1487 XChangeGC (s->display, FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc,
1488 mask, &xgcv);
1489 else
1490 FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc
1491 = XCreateGC (s->display, s->window, mask, &xgcv);
1493 s->gc = FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc;
1498 /* Set up S->gc of glyph string S for drawing text in mouse face. */
1500 static void
1501 x_set_mouse_face_gc (struct glyph_string *s)
1503 int face_id;
1504 struct face *face;
1506 /* What face has to be used last for the mouse face? */
1507 face_id = MOUSE_HL_INFO (s->f)->mouse_face_face_id;
1508 face = FACE_FROM_ID (s->f, face_id);
1509 if (face == NULL)
1510 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
1512 if (s->first_glyph->type == CHAR_GLYPH)
1513 face_id = FACE_FOR_CHAR (s->f, face, s->first_glyph->u.ch, -1, Qnil);
1514 else
1515 face_id = FACE_FOR_CHAR (s->f, face, 0, -1, Qnil);
1516 s->face = FACE_FROM_ID (s->f, face_id);
1517 prepare_face_for_display (s->f, s->face);
1519 if (s->font == s->face->font)
1520 s->gc = s->face->gc;
1521 else
1523 /* Otherwise construct scratch_cursor_gc with values from FACE
1524 except for FONT. */
1525 XGCValues xgcv;
1526 unsigned long mask;
1528 xgcv.background = s->face->background;
1529 xgcv.foreground = s->face->foreground;
1530 xgcv.graphics_exposures = False;
1531 mask = GCForeground | GCBackground | GCGraphicsExposures;
1533 if (FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc)
1534 XChangeGC (s->display, FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc,
1535 mask, &xgcv);
1536 else
1537 FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc
1538 = XCreateGC (s->display, s->window, mask, &xgcv);
1540 s->gc = FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc;
1543 eassert (s->gc != 0);
1547 /* Set S->gc of glyph string S to a GC suitable for drawing a mode line.
1548 Faces to use in the mode line have already been computed when the
1549 matrix was built, so there isn't much to do, here. */
1551 static void
1552 x_set_mode_line_face_gc (struct glyph_string *s)
1554 s->gc = s->face->gc;
1558 /* Set S->gc of glyph string S for drawing that glyph string. Set
1559 S->stippled_p to a non-zero value if the face of S has a stipple
1560 pattern. */
1562 static void
1563 x_set_glyph_string_gc (struct glyph_string *s)
1565 prepare_face_for_display (s->f, s->face);
1567 if (s->hl == DRAW_NORMAL_TEXT)
1569 s->gc = s->face->gc;
1570 s->stippled_p = s->face->stipple != 0;
1572 else if (s->hl == DRAW_INVERSE_VIDEO)
1574 x_set_mode_line_face_gc (s);
1575 s->stippled_p = s->face->stipple != 0;
1577 else if (s->hl == DRAW_CURSOR)
1579 x_set_cursor_gc (s);
1580 s->stippled_p = false;
1582 else if (s->hl == DRAW_MOUSE_FACE)
1584 x_set_mouse_face_gc (s);
1585 s->stippled_p = s->face->stipple != 0;
1587 else if (s->hl == DRAW_IMAGE_RAISED
1588 || s->hl == DRAW_IMAGE_SUNKEN)
1590 s->gc = s->face->gc;
1591 s->stippled_p = s->face->stipple != 0;
1593 else
1594 emacs_abort ();
1596 /* GC must have been set. */
1597 eassert (s->gc != 0);
1601 /* Set clipping for output of glyph string S. S may be part of a mode
1602 line or menu if we don't have X toolkit support. */
1604 static void
1605 x_set_glyph_string_clipping (struct glyph_string *s)
1607 XRectangle *r = s->clip;
1608 int n = get_glyph_string_clip_rects (s, r, 2);
1610 if (n > 0)
1611 x_set_clip_rectangles (s->f, s->gc, r, n);
1612 s->num_clips = n;
1616 /* Set SRC's clipping for output of glyph string DST. This is called
1617 when we are drawing DST's left_overhang or right_overhang only in
1618 the area of SRC. */
1620 static void
1621 x_set_glyph_string_clipping_exactly (struct glyph_string *src, struct glyph_string *dst)
1623 XRectangle r;
1625 r.x = src->x;
1626 r.width = src->width;
1627 r.y = src->y;
1628 r.height = src->height;
1629 dst->clip[0] = r;
1630 dst->num_clips = 1;
1631 x_set_clip_rectangles (dst->f, dst->gc, &r, 1);
1635 /* RIF:
1636 Compute left and right overhang of glyph string S. */
1638 static void
1639 x_compute_glyph_string_overhangs (struct glyph_string *s)
1641 if (s->cmp == NULL
1642 && (s->first_glyph->type == CHAR_GLYPH
1643 || s->first_glyph->type == COMPOSITE_GLYPH))
1645 struct font_metrics metrics;
1647 if (s->first_glyph->type == CHAR_GLYPH)
1649 unsigned *code = alloca (sizeof (unsigned) * s->nchars);
1650 struct font *font = s->font;
1651 int i;
1653 for (i = 0; i < s->nchars; i++)
1654 code[i] = (s->char2b[i].byte1 << 8) | s->char2b[i].byte2;
1655 font->driver->text_extents (font, code, s->nchars, &metrics);
1657 else
1659 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1661 composition_gstring_width (gstring, s->cmp_from, s->cmp_to, &metrics);
1663 s->right_overhang = (metrics.rbearing > metrics.width
1664 ? metrics.rbearing - metrics.width : 0);
1665 s->left_overhang = metrics.lbearing < 0 ? - metrics.lbearing : 0;
1667 else if (s->cmp)
1669 s->right_overhang = s->cmp->rbearing - s->cmp->pixel_width;
1670 s->left_overhang = - s->cmp->lbearing;
1675 /* Fill rectangle X, Y, W, H with background color of glyph string S. */
1677 static void
1678 x_clear_glyph_string_rect (struct glyph_string *s, int x, int y, int w, int h)
1680 XGCValues xgcv;
1681 XGetGCValues (s->display, s->gc, GCForeground | GCBackground, &xgcv);
1682 XSetForeground (s->display, s->gc, xgcv.background);
1683 x_fill_rectangle (s->f, s->gc, x, y, w, h);
1684 XSetForeground (s->display, s->gc, xgcv.foreground);
1688 /* Draw the background of glyph_string S. If S->background_filled_p
1689 is non-zero don't draw it. FORCE_P non-zero means draw the
1690 background even if it wouldn't be drawn normally. This is used
1691 when a string preceding S draws into the background of S, or S
1692 contains the first component of a composition. */
1694 static void
1695 x_draw_glyph_string_background (struct glyph_string *s, bool force_p)
1697 /* Nothing to do if background has already been drawn or if it
1698 shouldn't be drawn in the first place. */
1699 if (!s->background_filled_p)
1701 int box_line_width = max (s->face->box_line_width, 0);
1703 if (s->stippled_p)
1705 /* Fill background with a stipple pattern. */
1706 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
1707 x_fill_rectangle (s->f, s->gc, s->x,
1708 s->y + box_line_width,
1709 s->background_width,
1710 s->height - 2 * box_line_width);
1711 XSetFillStyle (s->display, s->gc, FillSolid);
1712 s->background_filled_p = true;
1714 else if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
1715 /* When xdisp.c ignores FONT_HEIGHT, we cannot trust
1716 font dimensions, since the actual glyphs might be
1717 much smaller. So in that case we always clear the
1718 rectangle with background color. */
1719 || FONT_TOO_HIGH (s->font)
1720 || s->font_not_found_p
1721 || s->extends_to_end_of_line_p
1722 || force_p)
1724 x_clear_glyph_string_rect (s, s->x, s->y + box_line_width,
1725 s->background_width,
1726 s->height - 2 * box_line_width);
1727 s->background_filled_p = true;
1733 /* Draw the foreground of glyph string S. */
1735 static void
1736 x_draw_glyph_string_foreground (struct glyph_string *s)
1738 int i, x;
1740 /* If first glyph of S has a left box line, start drawing the text
1741 of S to the right of that box line. */
1742 if (s->face->box != FACE_NO_BOX
1743 && s->first_glyph->left_box_line_p)
1744 x = s->x + eabs (s->face->box_line_width);
1745 else
1746 x = s->x;
1748 /* Draw characters of S as rectangles if S's font could not be
1749 loaded. */
1750 if (s->font_not_found_p)
1752 for (i = 0; i < s->nchars; ++i)
1754 struct glyph *g = s->first_glyph + i;
1755 x_draw_rectangle (s->f,
1756 s->gc, x, s->y, g->pixel_width - 1,
1757 s->height - 1);
1758 x += g->pixel_width;
1761 else
1763 struct font *font = s->font;
1764 int boff = font->baseline_offset;
1765 int y;
1767 if (font->vertical_centering)
1768 boff = VCENTER_BASELINE_OFFSET (font, s->f) - boff;
1770 y = s->ybase - boff;
1771 if (s->for_overlaps
1772 || (s->background_filled_p && s->hl != DRAW_CURSOR))
1773 font->driver->draw (s, 0, s->nchars, x, y, false);
1774 else
1775 font->driver->draw (s, 0, s->nchars, x, y, true);
1776 if (s->face->overstrike)
1777 font->driver->draw (s, 0, s->nchars, x + 1, y, false);
1781 /* Draw the foreground of composite glyph string S. */
1783 static void
1784 x_draw_composite_glyph_string_foreground (struct glyph_string *s)
1786 int i, j, x;
1787 struct font *font = s->font;
1789 /* If first glyph of S has a left box line, start drawing the text
1790 of S to the right of that box line. */
1791 if (s->face && s->face->box != FACE_NO_BOX
1792 && s->first_glyph->left_box_line_p)
1793 x = s->x + eabs (s->face->box_line_width);
1794 else
1795 x = s->x;
1797 /* S is a glyph string for a composition. S->cmp_from is the index
1798 of the first character drawn for glyphs of this composition.
1799 S->cmp_from == 0 means we are drawing the very first character of
1800 this composition. */
1802 /* Draw a rectangle for the composition if the font for the very
1803 first character of the composition could not be loaded. */
1804 if (s->font_not_found_p)
1806 if (s->cmp_from == 0)
1807 x_draw_rectangle (s->f, s->gc, x, s->y,
1808 s->width - 1, s->height - 1);
1810 else if (! s->first_glyph->u.cmp.automatic)
1812 int y = s->ybase;
1814 for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
1815 /* TAB in a composition means display glyphs with padding
1816 space on the left or right. */
1817 if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
1819 int xx = x + s->cmp->offsets[j * 2];
1820 int yy = y - s->cmp->offsets[j * 2 + 1];
1822 font->driver->draw (s, j, j + 1, xx, yy, false);
1823 if (s->face->overstrike)
1824 font->driver->draw (s, j, j + 1, xx + 1, yy, false);
1827 else
1829 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1830 Lisp_Object glyph;
1831 int y = s->ybase;
1832 int width = 0;
1834 for (i = j = s->cmp_from; i < s->cmp_to; i++)
1836 glyph = LGSTRING_GLYPH (gstring, i);
1837 if (NILP (LGLYPH_ADJUSTMENT (glyph)))
1838 width += LGLYPH_WIDTH (glyph);
1839 else
1841 int xoff, yoff, wadjust;
1843 if (j < i)
1845 font->driver->draw (s, j, i, x, y, false);
1846 if (s->face->overstrike)
1847 font->driver->draw (s, j, i, x + 1, y, false);
1848 x += width;
1850 xoff = LGLYPH_XOFF (glyph);
1851 yoff = LGLYPH_YOFF (glyph);
1852 wadjust = LGLYPH_WADJUST (glyph);
1853 font->driver->draw (s, i, i + 1, x + xoff, y + yoff, false);
1854 if (s->face->overstrike)
1855 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff,
1856 false);
1857 x += wadjust;
1858 j = i + 1;
1859 width = 0;
1862 if (j < i)
1864 font->driver->draw (s, j, i, x, y, false);
1865 if (s->face->overstrike)
1866 font->driver->draw (s, j, i, x + 1, y, false);
1872 /* Draw the foreground of glyph string S for glyphless characters. */
1874 static void
1875 x_draw_glyphless_glyph_string_foreground (struct glyph_string *s)
1877 struct glyph *glyph = s->first_glyph;
1878 XChar2b char2b[8];
1879 int x, i, j;
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->char2b = char2b;
1891 for (i = 0; i < s->nchars; i++, glyph++)
1893 char buf[7], *str = NULL;
1894 int len = glyph->u.glyphless.len;
1896 if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_ACRONYM)
1898 if (len > 0
1899 && CHAR_TABLE_P (Vglyphless_char_display)
1900 && (CHAR_TABLE_EXTRA_SLOTS (XCHAR_TABLE (Vglyphless_char_display))
1901 >= 1))
1903 Lisp_Object acronym
1904 = (! glyph->u.glyphless.for_no_font
1905 ? CHAR_TABLE_REF (Vglyphless_char_display,
1906 glyph->u.glyphless.ch)
1907 : XCHAR_TABLE (Vglyphless_char_display)->extras[0]);
1908 if (STRINGP (acronym))
1909 str = SSDATA (acronym);
1912 else if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_HEX_CODE)
1914 sprintf (buf, "%0*X",
1915 glyph->u.glyphless.ch < 0x10000 ? 4 : 6,
1916 glyph->u.glyphless.ch + 0u);
1917 str = buf;
1920 if (str)
1922 int upper_len = (len + 1) / 2;
1923 unsigned code;
1925 /* It is assured that all LEN characters in STR is ASCII. */
1926 for (j = 0; j < len; j++)
1928 code = s->font->driver->encode_char (s->font, str[j]);
1929 STORE_XCHAR2B (char2b + j, code >> 8, code & 0xFF);
1931 s->font->driver->draw (s, 0, upper_len,
1932 x + glyph->slice.glyphless.upper_xoff,
1933 s->ybase + glyph->slice.glyphless.upper_yoff,
1934 false);
1935 s->font->driver->draw (s, upper_len, len,
1936 x + glyph->slice.glyphless.lower_xoff,
1937 s->ybase + glyph->slice.glyphless.lower_yoff,
1938 false);
1940 if (glyph->u.glyphless.method != GLYPHLESS_DISPLAY_THIN_SPACE)
1941 x_draw_rectangle (s->f, s->gc,
1942 x, s->ybase - glyph->ascent,
1943 glyph->pixel_width - 1,
1944 glyph->ascent + glyph->descent - 1);
1945 x += glyph->pixel_width;
1949 #ifdef USE_X_TOOLKIT
1951 #ifdef USE_LUCID
1953 /* Return the frame on which widget WIDGET is used.. Abort if frame
1954 cannot be determined. */
1956 static struct frame *
1957 x_frame_of_widget (Widget widget)
1959 struct x_display_info *dpyinfo;
1960 Lisp_Object tail, frame;
1961 struct frame *f;
1963 dpyinfo = x_display_info_for_display (XtDisplay (widget));
1965 /* Find the top-level shell of the widget. Note that this function
1966 can be called when the widget is not yet realized, so XtWindow
1967 (widget) == 0. That's the reason we can't simply use
1968 x_any_window_to_frame. */
1969 while (!XtIsTopLevelShell (widget))
1970 widget = XtParent (widget);
1972 /* Look for a frame with that top-level widget. Allocate the color
1973 on that frame to get the right gamma correction value. */
1974 FOR_EACH_FRAME (tail, frame)
1976 f = XFRAME (frame);
1977 if (FRAME_X_P (f)
1978 && f->output_data.nothing != 1
1979 && FRAME_DISPLAY_INFO (f) == dpyinfo
1980 && f->output_data.x->widget == widget)
1981 return f;
1983 emacs_abort ();
1986 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
1987 or DELTA. Try a color with RGB values multiplied by FACTOR first.
1988 If this produces the same color as PIXEL, try a color where all RGB
1989 values have DELTA added. Return the allocated color in *PIXEL.
1990 DISPLAY is the X display, CMAP is the colormap to operate on.
1991 Value is true if successful. */
1993 bool
1994 x_alloc_lighter_color_for_widget (Widget widget, Display *display, Colormap cmap,
1995 unsigned long *pixel, double factor, int delta)
1997 struct frame *f = x_frame_of_widget (widget);
1998 return x_alloc_lighter_color (f, display, cmap, pixel, factor, delta);
2001 #endif /* USE_LUCID */
2004 /* Structure specifying which arguments should be passed by Xt to
2005 cvt_string_to_pixel. We want the widget's screen and colormap. */
2007 static XtConvertArgRec cvt_string_to_pixel_args[] =
2009 {XtWidgetBaseOffset, (XtPointer) offsetof (WidgetRec, core.screen),
2010 sizeof (Screen *)},
2011 {XtWidgetBaseOffset, (XtPointer) offsetof (WidgetRec, core.colormap),
2012 sizeof (Colormap)}
2016 /* The address of this variable is returned by
2017 cvt_string_to_pixel. */
2019 static Pixel cvt_string_to_pixel_value;
2022 /* Convert a color name to a pixel color.
2024 DPY is the display we are working on.
2026 ARGS is an array of *NARGS XrmValue structures holding additional
2027 information about the widget for which the conversion takes place.
2028 The contents of this array are determined by the specification
2029 in cvt_string_to_pixel_args.
2031 FROM is a pointer to an XrmValue which points to the color name to
2032 convert. TO is an XrmValue in which to return the pixel color.
2034 CLOSURE_RET is a pointer to user-data, in which we record if
2035 we allocated the color or not.
2037 Value is True if successful, False otherwise. */
2039 static Boolean
2040 cvt_string_to_pixel (Display *dpy, XrmValue *args, Cardinal *nargs,
2041 XrmValue *from, XrmValue *to,
2042 XtPointer *closure_ret)
2044 Screen *screen;
2045 Colormap cmap;
2046 Pixel pixel;
2047 String color_name;
2048 XColor color;
2050 if (*nargs != 2)
2052 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
2053 "wrongParameters", "cvt_string_to_pixel",
2054 "XtToolkitError",
2055 "Screen and colormap args required", NULL, NULL);
2056 return False;
2059 screen = *(Screen **) args[0].addr;
2060 cmap = *(Colormap *) args[1].addr;
2061 color_name = (String) from->addr;
2063 if (strcmp (color_name, XtDefaultBackground) == 0)
2065 *closure_ret = (XtPointer) False;
2066 pixel = WhitePixelOfScreen (screen);
2068 else if (strcmp (color_name, XtDefaultForeground) == 0)
2070 *closure_ret = (XtPointer) False;
2071 pixel = BlackPixelOfScreen (screen);
2073 else if (XParseColor (dpy, cmap, color_name, &color)
2074 && x_alloc_nearest_color_1 (dpy, cmap, &color))
2076 pixel = color.pixel;
2077 *closure_ret = (XtPointer) True;
2079 else
2081 String params[1];
2082 Cardinal nparams = 1;
2084 params[0] = color_name;
2085 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
2086 "badValue", "cvt_string_to_pixel",
2087 "XtToolkitError", "Invalid color '%s'",
2088 params, &nparams);
2089 return False;
2092 if (to->addr != NULL)
2094 if (to->size < sizeof (Pixel))
2096 to->size = sizeof (Pixel);
2097 return False;
2100 *(Pixel *) to->addr = pixel;
2102 else
2104 cvt_string_to_pixel_value = pixel;
2105 to->addr = (XtPointer) &cvt_string_to_pixel_value;
2108 to->size = sizeof (Pixel);
2109 return True;
2113 /* Free a pixel color which was previously allocated via
2114 cvt_string_to_pixel. This is registered as the destructor
2115 for this type of resource via XtSetTypeConverter.
2117 APP is the application context in which we work.
2119 TO is a pointer to an XrmValue holding the color to free.
2120 CLOSURE is the value we stored in CLOSURE_RET for this color
2121 in cvt_string_to_pixel.
2123 ARGS and NARGS are like for cvt_string_to_pixel. */
2125 static void
2126 cvt_pixel_dtor (XtAppContext app, XrmValuePtr to, XtPointer closure, XrmValuePtr args,
2127 Cardinal *nargs)
2129 if (*nargs != 2)
2131 XtAppWarningMsg (app, "wrongParameters", "cvt_pixel_dtor",
2132 "XtToolkitError",
2133 "Screen and colormap arguments required",
2134 NULL, NULL);
2136 else if (closure != NULL)
2138 /* We did allocate the pixel, so free it. */
2139 Screen *screen = *(Screen **) args[0].addr;
2140 Colormap cmap = *(Colormap *) args[1].addr;
2141 x_free_dpy_colors (DisplayOfScreen (screen), screen, cmap,
2142 (Pixel *) to->addr, 1);
2147 #endif /* USE_X_TOOLKIT */
2150 /* Value is an array of XColor structures for the contents of the
2151 color map of display DPY. Set *NCELLS to the size of the array.
2152 Note that this probably shouldn't be called for large color maps,
2153 say a 24-bit TrueColor map. */
2155 static const XColor *
2156 x_color_cells (Display *dpy, int *ncells)
2158 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
2160 if (dpyinfo->color_cells == NULL)
2162 Screen *screen = dpyinfo->screen;
2163 int ncolor_cells = XDisplayCells (dpy, XScreenNumberOfScreen (screen));
2164 int i;
2166 dpyinfo->color_cells = xnmalloc (ncolor_cells,
2167 sizeof *dpyinfo->color_cells);
2168 dpyinfo->ncolor_cells = ncolor_cells;
2170 for (i = 0; i < ncolor_cells; ++i)
2171 dpyinfo->color_cells[i].pixel = i;
2173 XQueryColors (dpy, dpyinfo->cmap,
2174 dpyinfo->color_cells, ncolor_cells);
2177 *ncells = dpyinfo->ncolor_cells;
2178 return dpyinfo->color_cells;
2182 /* On frame F, translate pixel colors to RGB values for the NCOLORS
2183 colors in COLORS. Use cached information, if available. */
2185 void
2186 x_query_colors (struct frame *f, XColor *colors, int ncolors)
2188 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2190 if (dpyinfo->red_bits > 0)
2192 /* For TrueColor displays, we can decompose the RGB value
2193 directly. */
2194 int i;
2195 unsigned int rmult, gmult, bmult;
2196 unsigned int rmask, gmask, bmask;
2198 rmask = (1 << dpyinfo->red_bits) - 1;
2199 gmask = (1 << dpyinfo->green_bits) - 1;
2200 bmask = (1 << dpyinfo->blue_bits) - 1;
2201 /* If we're widening, for example, 8 bits in the pixel value to
2202 16 bits for the separate-color representation, we want to
2203 extrapolate the lower bits based on those bits available --
2204 in other words, we'd like 0xff to become 0xffff instead of
2205 the 0xff00 we'd get by just zero-filling the lower bits.
2207 We generate a 32-bit scaled-up value and shift it, in case
2208 the bit count doesn't divide 16 evenly (e.g., when dealing
2209 with a 3-3-2 bit RGB display), to get more of the lower bits
2210 correct.
2212 Should we cache the multipliers in dpyinfo? Maybe
2213 special-case the 8-8-8 common case? */
2214 rmult = 0xffffffff / rmask;
2215 gmult = 0xffffffff / gmask;
2216 bmult = 0xffffffff / bmask;
2218 for (i = 0; i < ncolors; ++i)
2220 unsigned int r, g, b;
2221 unsigned long pixel = colors[i].pixel;
2223 r = (pixel >> dpyinfo->red_offset) & rmask;
2224 g = (pixel >> dpyinfo->green_offset) & gmask;
2225 b = (pixel >> dpyinfo->blue_offset) & bmask;
2227 colors[i].red = (r * rmult) >> 16;
2228 colors[i].green = (g * gmult) >> 16;
2229 colors[i].blue = (b * bmult) >> 16;
2231 return;
2234 if (dpyinfo->color_cells)
2236 int i;
2237 for (i = 0; i < ncolors; ++i)
2239 unsigned long pixel = colors[i].pixel;
2240 eassert (pixel < dpyinfo->ncolor_cells);
2241 eassert (dpyinfo->color_cells[pixel].pixel == pixel);
2242 colors[i] = dpyinfo->color_cells[pixel];
2244 return;
2247 XQueryColors (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), colors, ncolors);
2251 /* On frame F, translate pixel color to RGB values for the color in
2252 COLOR. Use cached information, if available. */
2254 void
2255 x_query_color (struct frame *f, XColor *color)
2257 x_query_colors (f, color, 1);
2261 /* On frame F, translate the color name to RGB values. Use cached
2262 information, if possible.
2264 Note that there is currently no way to clean old entries out of the
2265 cache. However, it is limited to names in the server's database,
2266 and names we've actually looked up; list-colors-display is probably
2267 the most color-intensive case we're likely to hit. */
2269 Status x_parse_color (struct frame *f, const char *color_name,
2270 XColor *color)
2272 Display *dpy = FRAME_X_DISPLAY (f);
2273 Colormap cmap = FRAME_X_COLORMAP (f);
2274 struct color_name_cache_entry *cache_entry;
2276 if (color_name[0] == '#')
2278 /* The hex form is parsed directly by XParseColor without
2279 talking to the X server. No need for caching. */
2280 return XParseColor (dpy, cmap, color_name, color);
2283 for (cache_entry = FRAME_DISPLAY_INFO (f)->color_names; cache_entry;
2284 cache_entry = cache_entry->next)
2286 if (!xstrcasecmp(cache_entry->name, color_name))
2288 *color = cache_entry->rgb;
2289 return 1;
2293 if (XParseColor (dpy, cmap, color_name, color) == 0)
2294 /* No caching of negative results, currently. */
2295 return 0;
2297 cache_entry = xzalloc (sizeof *cache_entry);
2298 cache_entry->rgb = *color;
2299 cache_entry->name = xstrdup (color_name);
2300 cache_entry->next = FRAME_DISPLAY_INFO (f)->color_names;
2301 FRAME_DISPLAY_INFO (f)->color_names = cache_entry;
2302 return 1;
2306 /* Allocate the color COLOR->pixel on DISPLAY, colormap CMAP. If an
2307 exact match can't be allocated, try the nearest color available.
2308 Value is true if successful. Set *COLOR to the color
2309 allocated. */
2311 static bool
2312 x_alloc_nearest_color_1 (Display *dpy, Colormap cmap, XColor *color)
2314 bool rc;
2316 rc = XAllocColor (dpy, cmap, color) != 0;
2317 if (rc == 0)
2319 /* If we got to this point, the colormap is full, so we're going
2320 to try to get the next closest color. The algorithm used is
2321 a least-squares matching, which is what X uses for closest
2322 color matching with StaticColor visuals. */
2323 int nearest, i;
2324 int max_color_delta = 255;
2325 int max_delta = 3 * max_color_delta;
2326 int nearest_delta = max_delta + 1;
2327 int ncells;
2328 const XColor *cells = x_color_cells (dpy, &ncells);
2330 for (nearest = i = 0; i < ncells; ++i)
2332 int dred = (color->red >> 8) - (cells[i].red >> 8);
2333 int dgreen = (color->green >> 8) - (cells[i].green >> 8);
2334 int dblue = (color->blue >> 8) - (cells[i].blue >> 8);
2335 int delta = dred * dred + dgreen * dgreen + dblue * dblue;
2337 if (delta < nearest_delta)
2339 nearest = i;
2340 nearest_delta = delta;
2344 color->red = cells[nearest].red;
2345 color->green = cells[nearest].green;
2346 color->blue = cells[nearest].blue;
2347 rc = XAllocColor (dpy, cmap, color) != 0;
2349 else
2351 /* If allocation succeeded, and the allocated pixel color is not
2352 equal to a cached pixel color recorded earlier, there was a
2353 change in the colormap, so clear the color cache. */
2354 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
2355 XColor *cached_color;
2357 if (dpyinfo->color_cells
2358 && (cached_color = &dpyinfo->color_cells[color->pixel],
2359 (cached_color->red != color->red
2360 || cached_color->blue != color->blue
2361 || cached_color->green != color->green)))
2363 xfree (dpyinfo->color_cells);
2364 dpyinfo->color_cells = NULL;
2365 dpyinfo->ncolor_cells = 0;
2369 #ifdef DEBUG_X_COLORS
2370 if (rc)
2371 register_color (color->pixel);
2372 #endif /* DEBUG_X_COLORS */
2374 return rc;
2378 /* Allocate the color COLOR->pixel on frame F, colormap CMAP, after
2379 gamma correction. If an exact match can't be allocated, try the
2380 nearest color available. Value is true if successful. Set *COLOR
2381 to the color allocated. */
2383 bool
2384 x_alloc_nearest_color (struct frame *f, Colormap cmap, XColor *color)
2386 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2388 gamma_correct (f, color);
2390 if (dpyinfo->red_bits > 0)
2392 color->pixel = x_make_truecolor_pixel (dpyinfo,
2393 color->red,
2394 color->green,
2395 color->blue);
2396 return true;
2399 return x_alloc_nearest_color_1 (FRAME_X_DISPLAY (f), cmap, color);
2403 /* Allocate color PIXEL on frame F. PIXEL must already be allocated.
2404 It's necessary to do this instead of just using PIXEL directly to
2405 get color reference counts right. */
2407 unsigned long
2408 x_copy_color (struct frame *f, unsigned long pixel)
2410 XColor color;
2412 /* If display has an immutable color map, freeing colors is not
2413 necessary and some servers don't allow it. Since we won't free a
2414 color once we've allocated it, we don't need to re-allocate it to
2415 maintain the server's reference count. */
2416 if (!x_mutable_colormap (FRAME_X_VISUAL (f)))
2417 return pixel;
2419 color.pixel = pixel;
2420 block_input ();
2421 /* The color could still be found in the color_cells array. */
2422 x_query_color (f, &color);
2423 XAllocColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &color);
2424 unblock_input ();
2425 #ifdef DEBUG_X_COLORS
2426 register_color (pixel);
2427 #endif
2428 return color.pixel;
2432 /* Brightness beyond which a color won't have its highlight brightness
2433 boosted.
2435 Nominally, highlight colors for `3d' faces are calculated by
2436 brightening an object's color by a constant scale factor, but this
2437 doesn't yield good results for dark colors, so for colors who's
2438 brightness is less than this value (on a scale of 0-65535) have an
2439 use an additional additive factor.
2441 The value here is set so that the default menu-bar/mode-line color
2442 (grey75) will not have its highlights changed at all. */
2443 #define HIGHLIGHT_COLOR_DARK_BOOST_LIMIT 48000
2446 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
2447 or DELTA. Try a color with RGB values multiplied by FACTOR first.
2448 If this produces the same color as PIXEL, try a color where all RGB
2449 values have DELTA added. Return the allocated color in *PIXEL.
2450 DISPLAY is the X display, CMAP is the colormap to operate on.
2451 Value is non-zero if successful. */
2453 static bool
2454 x_alloc_lighter_color (struct frame *f, Display *display, Colormap cmap,
2455 unsigned long *pixel, double factor, int delta)
2457 XColor color, new;
2458 long bright;
2459 bool success_p;
2461 /* Get RGB color values. */
2462 color.pixel = *pixel;
2463 x_query_color (f, &color);
2465 /* Change RGB values by specified FACTOR. Avoid overflow! */
2466 eassert (factor >= 0);
2467 new.red = min (0xffff, factor * color.red);
2468 new.green = min (0xffff, factor * color.green);
2469 new.blue = min (0xffff, factor * color.blue);
2471 /* Calculate brightness of COLOR. */
2472 bright = (2 * color.red + 3 * color.green + color.blue) / 6;
2474 /* We only boost colors that are darker than
2475 HIGHLIGHT_COLOR_DARK_BOOST_LIMIT. */
2476 if (bright < HIGHLIGHT_COLOR_DARK_BOOST_LIMIT)
2477 /* Make an additive adjustment to NEW, because it's dark enough so
2478 that scaling by FACTOR alone isn't enough. */
2480 /* How far below the limit this color is (0 - 1, 1 being darker). */
2481 double dimness = 1 - (double)bright / HIGHLIGHT_COLOR_DARK_BOOST_LIMIT;
2482 /* The additive adjustment. */
2483 int min_delta = delta * dimness * factor / 2;
2485 if (factor < 1)
2487 new.red = max (0, new.red - min_delta);
2488 new.green = max (0, new.green - min_delta);
2489 new.blue = max (0, new.blue - min_delta);
2491 else
2493 new.red = min (0xffff, min_delta + new.red);
2494 new.green = min (0xffff, min_delta + new.green);
2495 new.blue = min (0xffff, min_delta + new.blue);
2499 /* Try to allocate the color. */
2500 success_p = x_alloc_nearest_color (f, cmap, &new);
2501 if (success_p)
2503 if (new.pixel == *pixel)
2505 /* If we end up with the same color as before, try adding
2506 delta to the RGB values. */
2507 x_free_colors (f, &new.pixel, 1);
2509 new.red = min (0xffff, delta + color.red);
2510 new.green = min (0xffff, delta + color.green);
2511 new.blue = min (0xffff, delta + color.blue);
2512 success_p = x_alloc_nearest_color (f, cmap, &new);
2514 else
2515 success_p = true;
2516 *pixel = new.pixel;
2519 return success_p;
2523 /* Set up the foreground color for drawing relief lines of glyph
2524 string S. RELIEF is a pointer to a struct relief containing the GC
2525 with which lines will be drawn. Use a color that is FACTOR or
2526 DELTA lighter or darker than the relief's background which is found
2527 in S->f->output_data.x->relief_background. If such a color cannot
2528 be allocated, use DEFAULT_PIXEL, instead. */
2530 static void
2531 x_setup_relief_color (struct frame *f, struct relief *relief, double factor,
2532 int delta, unsigned long default_pixel)
2534 XGCValues xgcv;
2535 struct x_output *di = f->output_data.x;
2536 unsigned long mask = GCForeground | GCLineWidth | GCGraphicsExposures;
2537 unsigned long pixel;
2538 unsigned long background = di->relief_background;
2539 Colormap cmap = FRAME_X_COLORMAP (f);
2540 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2541 Display *dpy = FRAME_X_DISPLAY (f);
2543 xgcv.graphics_exposures = False;
2544 xgcv.line_width = 1;
2546 /* Free previously allocated color. The color cell will be reused
2547 when it has been freed as many times as it was allocated, so this
2548 doesn't affect faces using the same colors. */
2549 if (relief->gc && relief->pixel != -1)
2551 x_free_colors (f, &relief->pixel, 1);
2552 relief->pixel = -1;
2555 /* Allocate new color. */
2556 xgcv.foreground = default_pixel;
2557 pixel = background;
2558 if (dpyinfo->n_planes != 1
2559 && x_alloc_lighter_color (f, dpy, cmap, &pixel, factor, delta))
2560 xgcv.foreground = relief->pixel = pixel;
2562 if (relief->gc == 0)
2564 xgcv.stipple = dpyinfo->gray;
2565 mask |= GCStipple;
2566 relief->gc = XCreateGC (dpy, FRAME_X_WINDOW (f), mask, &xgcv);
2568 else
2569 XChangeGC (dpy, relief->gc, mask, &xgcv);
2573 /* Set up colors for the relief lines around glyph string S. */
2575 static void
2576 x_setup_relief_colors (struct glyph_string *s)
2578 struct x_output *di = s->f->output_data.x;
2579 unsigned long color;
2581 if (s->face->use_box_color_for_shadows_p)
2582 color = s->face->box_color;
2583 else if (s->first_glyph->type == IMAGE_GLYPH
2584 && s->img->pixmap
2585 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2586 color = IMAGE_BACKGROUND (s->img, s->f, 0);
2587 else
2589 XGCValues xgcv;
2591 /* Get the background color of the face. */
2592 XGetGCValues (s->display, s->gc, GCBackground, &xgcv);
2593 color = xgcv.background;
2596 if (di->white_relief.gc == 0
2597 || color != di->relief_background)
2599 di->relief_background = color;
2600 x_setup_relief_color (s->f, &di->white_relief, 1.2, 0x8000,
2601 WHITE_PIX_DEFAULT (s->f));
2602 x_setup_relief_color (s->f, &di->black_relief, 0.6, 0x4000,
2603 BLACK_PIX_DEFAULT (s->f));
2608 /* Draw a relief on frame F inside the rectangle given by LEFT_X,
2609 TOP_Y, RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the relief
2610 to draw, it must be >= 0. RAISED_P means draw a raised
2611 relief. LEFT_P means draw a relief on the left side of
2612 the rectangle. RIGHT_P means draw a relief on the right
2613 side of the rectangle. CLIP_RECT is the clipping rectangle to use
2614 when drawing. */
2616 static void
2617 x_draw_relief_rect (struct frame *f,
2618 int left_x, int top_y, int right_x, int bottom_y,
2619 int width, bool raised_p, bool top_p, bool bot_p,
2620 bool left_p, bool right_p,
2621 XRectangle *clip_rect)
2623 #ifdef USE_CAIRO
2624 GC top_left_gc, bottom_right_gc;
2625 int corners = 0;
2627 if (raised_p)
2629 top_left_gc = f->output_data.x->white_relief.gc;
2630 bottom_right_gc = f->output_data.x->black_relief.gc;
2632 else
2634 top_left_gc = f->output_data.x->black_relief.gc;
2635 bottom_right_gc = f->output_data.x->white_relief.gc;
2638 x_set_clip_rectangles (f, top_left_gc, clip_rect, 1);
2639 x_set_clip_rectangles (f, bottom_right_gc, clip_rect, 1);
2641 if (left_p)
2643 x_fill_rectangle (f, top_left_gc, left_x, top_y,
2644 width, bottom_y + 1 - top_y);
2645 if (top_p)
2646 corners |= 1 << CORNER_TOP_LEFT;
2647 if (bot_p)
2648 corners |= 1 << CORNER_BOTTOM_LEFT;
2650 if (right_p)
2652 x_fill_rectangle (f, bottom_right_gc, right_x + 1 - width, top_y,
2653 width, bottom_y + 1 - top_y);
2654 if (top_p)
2655 corners |= 1 << CORNER_TOP_RIGHT;
2656 if (bot_p)
2657 corners |= 1 << CORNER_BOTTOM_RIGHT;
2659 if (top_p)
2661 if (!right_p)
2662 x_fill_rectangle (f, top_left_gc, left_x, top_y,
2663 right_x + 1 - left_x, width);
2664 else
2665 x_fill_trapezoid_for_relief (f, top_left_gc, left_x, top_y,
2666 right_x + 1 - left_x, width, 1);
2668 if (bot_p)
2670 if (!left_p)
2671 x_fill_rectangle (f, bottom_right_gc, left_x, bottom_y + 1 - width,
2672 right_x + 1 - left_x, width);
2673 else
2674 x_fill_trapezoid_for_relief (f, bottom_right_gc,
2675 left_x, bottom_y + 1 - width,
2676 right_x + 1 - left_x, width, 0);
2678 if (left_p && width != 1)
2679 x_fill_rectangle (f, bottom_right_gc, left_x, top_y,
2680 1, bottom_y + 1 - top_y);
2681 if (top_p && width != 1)
2682 x_fill_rectangle (f, bottom_right_gc, left_x, top_y,
2683 right_x + 1 - left_x, 1);
2684 if (corners)
2686 XSetBackground (FRAME_X_DISPLAY (f), top_left_gc,
2687 FRAME_BACKGROUND_PIXEL (f));
2688 x_erase_corners_for_relief (f, top_left_gc, left_x, top_y,
2689 right_x - left_x + 1, bottom_y - top_y + 1,
2690 6, 1, corners);
2693 x_reset_clip_rectangles (f, top_left_gc);
2694 x_reset_clip_rectangles (f, bottom_right_gc);
2695 #else
2696 Display *dpy = FRAME_X_DISPLAY (f);
2697 Window window = FRAME_X_WINDOW (f);
2698 int i;
2699 GC gc;
2701 if (raised_p)
2702 gc = f->output_data.x->white_relief.gc;
2703 else
2704 gc = f->output_data.x->black_relief.gc;
2705 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
2707 /* This code is more complicated than it has to be, because of two
2708 minor hacks to make the boxes look nicer: (i) if width > 1, draw
2709 the outermost line using the black relief. (ii) Omit the four
2710 corner pixels. */
2712 /* Top. */
2713 if (top_p)
2715 if (width == 1)
2716 XDrawLine (dpy, window, gc,
2717 left_x + left_p, top_y,
2718 right_x + !right_p, top_y);
2720 for (i = 1; i < width; ++i)
2721 XDrawLine (dpy, window, gc,
2722 left_x + i * left_p, top_y + i,
2723 right_x + 1 - i * right_p, top_y + i);
2726 /* Left. */
2727 if (left_p)
2729 if (width == 1)
2730 XDrawLine (dpy, window, gc, left_x, top_y + 1, left_x, bottom_y);
2732 XClearArea (dpy, window, left_x, top_y, 1, 1, False);
2733 XClearArea (dpy, window, left_x, bottom_y, 1, 1, False);
2735 for (i = (width > 1 ? 1 : 0); i < width; ++i)
2736 XDrawLine (dpy, window, gc,
2737 left_x + i, top_y + (i + 1) * top_p,
2738 left_x + i, bottom_y + 1 - (i + 1) * bot_p);
2741 XSetClipMask (dpy, gc, None);
2742 if (raised_p)
2743 gc = f->output_data.x->black_relief.gc;
2744 else
2745 gc = f->output_data.x->white_relief.gc;
2746 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
2748 if (width > 1)
2750 /* Outermost top line. */
2751 if (top_p)
2752 XDrawLine (dpy, window, gc,
2753 left_x + left_p, top_y,
2754 right_x + !right_p, top_y);
2756 /* Outermost left line. */
2757 if (left_p)
2758 XDrawLine (dpy, window, gc, left_x, top_y + 1, left_x, bottom_y);
2761 /* Bottom. */
2762 if (bot_p)
2764 XDrawLine (dpy, window, gc,
2765 left_x + left_p, bottom_y,
2766 right_x + !right_p, bottom_y);
2767 for (i = 1; i < width; ++i)
2768 XDrawLine (dpy, window, gc,
2769 left_x + i * left_p, bottom_y - i,
2770 right_x + 1 - i * right_p, bottom_y - i);
2773 /* Right. */
2774 if (right_p)
2776 XClearArea (dpy, window, right_x, top_y, 1, 1, False);
2777 XClearArea (dpy, window, right_x, bottom_y, 1, 1, False);
2778 for (i = 0; i < width; ++i)
2779 XDrawLine (dpy, window, gc,
2780 right_x - i, top_y + (i + 1) * top_p,
2781 right_x - i, bottom_y + 1 - (i + 1) * bot_p);
2784 x_reset_clip_rectangles (f, gc);
2786 #endif
2790 /* Draw a box on frame F inside the rectangle given by LEFT_X, TOP_Y,
2791 RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the lines to
2792 draw, it must be >= 0. LEFT_P means draw a line on the
2793 left side of the rectangle. RIGHT_P means draw a line
2794 on the right side of the rectangle. CLIP_RECT is the clipping
2795 rectangle to use when drawing. */
2797 static void
2798 x_draw_box_rect (struct glyph_string *s,
2799 int left_x, int top_y, int right_x, int bottom_y, int width,
2800 bool left_p, bool right_p, XRectangle *clip_rect)
2802 XGCValues xgcv;
2804 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2805 XSetForeground (s->display, s->gc, s->face->box_color);
2806 x_set_clip_rectangles (s->f, s->gc, clip_rect, 1);
2808 /* Top. */
2809 x_fill_rectangle (s->f, s->gc,
2810 left_x, top_y, right_x - left_x + 1, width);
2812 /* Left. */
2813 if (left_p)
2814 x_fill_rectangle (s->f, s->gc,
2815 left_x, top_y, width, bottom_y - top_y + 1);
2817 /* Bottom. */
2818 x_fill_rectangle (s->f, s->gc,
2819 left_x, bottom_y - width + 1, right_x - left_x + 1, width);
2821 /* Right. */
2822 if (right_p)
2823 x_fill_rectangle (s->f, s->gc,
2824 right_x - width + 1, top_y, width, bottom_y - top_y + 1);
2826 XSetForeground (s->display, s->gc, xgcv.foreground);
2827 x_reset_clip_rectangles (s->f, s->gc);
2831 /* Draw a box around glyph string S. */
2833 static void
2834 x_draw_glyph_string_box (struct glyph_string *s)
2836 int width, left_x, right_x, top_y, bottom_y, last_x;
2837 bool raised_p, left_p, right_p;
2838 struct glyph *last_glyph;
2839 XRectangle clip_rect;
2841 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2842 ? WINDOW_RIGHT_EDGE_X (s->w)
2843 : window_box_right (s->w, s->area));
2845 /* The glyph that may have a right box line. */
2846 last_glyph = (s->cmp || s->img
2847 ? s->first_glyph
2848 : s->first_glyph + s->nchars - 1);
2850 width = eabs (s->face->box_line_width);
2851 raised_p = s->face->box == FACE_RAISED_BOX;
2852 left_x = s->x;
2853 right_x = (s->row->full_width_p && s->extends_to_end_of_line_p
2854 ? last_x - 1
2855 : min (last_x, s->x + s->background_width) - 1);
2856 top_y = s->y;
2857 bottom_y = top_y + s->height - 1;
2859 left_p = (s->first_glyph->left_box_line_p
2860 || (s->hl == DRAW_MOUSE_FACE
2861 && (s->prev == NULL
2862 || s->prev->hl != s->hl)));
2863 right_p = (last_glyph->right_box_line_p
2864 || (s->hl == DRAW_MOUSE_FACE
2865 && (s->next == NULL
2866 || s->next->hl != s->hl)));
2868 get_glyph_string_clip_rect (s, &clip_rect);
2870 if (s->face->box == FACE_SIMPLE_BOX)
2871 x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
2872 left_p, right_p, &clip_rect);
2873 else
2875 x_setup_relief_colors (s);
2876 x_draw_relief_rect (s->f, left_x, top_y, right_x, bottom_y,
2877 width, raised_p, true, true, left_p, right_p,
2878 &clip_rect);
2883 /* Draw foreground of image glyph string S. */
2885 static void
2886 x_draw_image_foreground (struct glyph_string *s)
2888 int x = s->x;
2889 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2891 /* If first glyph of S has a left box line, start drawing it to the
2892 right of that line. */
2893 if (s->face->box != FACE_NO_BOX
2894 && s->first_glyph->left_box_line_p
2895 && s->slice.x == 0)
2896 x += eabs (s->face->box_line_width);
2898 /* If there is a margin around the image, adjust x- and y-position
2899 by that margin. */
2900 if (s->slice.x == 0)
2901 x += s->img->hmargin;
2902 if (s->slice.y == 0)
2903 y += s->img->vmargin;
2905 if (s->img->pixmap)
2907 if (s->img->mask)
2909 /* We can't set both a clip mask and use XSetClipRectangles
2910 because the latter also sets a clip mask. We also can't
2911 trust on the shape extension to be available
2912 (XShapeCombineRegion). So, compute the rectangle to draw
2913 manually. */
2914 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
2915 | GCFunction);
2916 XGCValues xgcv;
2917 XRectangle clip_rect, image_rect, r;
2919 xgcv.clip_mask = s->img->mask;
2920 xgcv.clip_x_origin = x;
2921 xgcv.clip_y_origin = y;
2922 xgcv.function = GXcopy;
2923 XChangeGC (s->display, s->gc, mask, &xgcv);
2925 get_glyph_string_clip_rect (s, &clip_rect);
2926 image_rect.x = x;
2927 image_rect.y = y;
2928 image_rect.width = s->slice.width;
2929 image_rect.height = s->slice.height;
2930 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
2931 XCopyArea (s->display, s->img->pixmap, s->window, s->gc,
2932 s->slice.x + r.x - x, s->slice.y + r.y - y,
2933 r.width, r.height, r.x, r.y);
2935 else
2937 XRectangle clip_rect, image_rect, r;
2939 get_glyph_string_clip_rect (s, &clip_rect);
2940 image_rect.x = x;
2941 image_rect.y = y;
2942 image_rect.width = s->slice.width;
2943 image_rect.height = s->slice.height;
2944 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
2945 XCopyArea (s->display, s->img->pixmap, s->window, s->gc,
2946 s->slice.x + r.x - x, s->slice.y + r.y - y,
2947 r.width, r.height, r.x, r.y);
2949 /* When the image has a mask, we can expect that at
2950 least part of a mouse highlight or a block cursor will
2951 be visible. If the image doesn't have a mask, make
2952 a block cursor visible by drawing a rectangle around
2953 the image. I believe it's looking better if we do
2954 nothing here for mouse-face. */
2955 if (s->hl == DRAW_CURSOR)
2957 int relief = eabs (s->img->relief);
2958 x_draw_rectangle (s->f, s->gc,
2959 x - relief, y - relief,
2960 s->slice.width + relief*2 - 1,
2961 s->slice.height + relief*2 - 1);
2965 else
2966 /* Draw a rectangle if image could not be loaded. */
2967 x_draw_rectangle (s->f, s->gc, x, y,
2968 s->slice.width - 1, s->slice.height - 1);
2972 /* Draw a relief around the image glyph string S. */
2974 static void
2975 x_draw_image_relief (struct glyph_string *s)
2977 int x1, y1, thick;
2978 bool raised_p, top_p, bot_p, left_p, right_p;
2979 int extra_x, extra_y;
2980 XRectangle r;
2981 int x = s->x;
2982 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2984 /* If first glyph of S has a left box line, start drawing it to the
2985 right of that line. */
2986 if (s->face->box != FACE_NO_BOX
2987 && s->first_glyph->left_box_line_p
2988 && s->slice.x == 0)
2989 x += eabs (s->face->box_line_width);
2991 /* If there is a margin around the image, adjust x- and y-position
2992 by that margin. */
2993 if (s->slice.x == 0)
2994 x += s->img->hmargin;
2995 if (s->slice.y == 0)
2996 y += s->img->vmargin;
2998 if (s->hl == DRAW_IMAGE_SUNKEN
2999 || s->hl == DRAW_IMAGE_RAISED)
3001 thick = tool_bar_button_relief >= 0 ? tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3002 raised_p = s->hl == DRAW_IMAGE_RAISED;
3004 else
3006 thick = eabs (s->img->relief);
3007 raised_p = s->img->relief > 0;
3010 x1 = x + s->slice.width - 1;
3011 y1 = y + s->slice.height - 1;
3013 extra_x = extra_y = 0;
3014 if (s->face->id == TOOL_BAR_FACE_ID)
3016 if (CONSP (Vtool_bar_button_margin)
3017 && INTEGERP (XCAR (Vtool_bar_button_margin))
3018 && INTEGERP (XCDR (Vtool_bar_button_margin)))
3020 extra_x = XINT (XCAR (Vtool_bar_button_margin));
3021 extra_y = XINT (XCDR (Vtool_bar_button_margin));
3023 else if (INTEGERP (Vtool_bar_button_margin))
3024 extra_x = extra_y = XINT (Vtool_bar_button_margin);
3027 top_p = bot_p = left_p = right_p = false;
3029 if (s->slice.x == 0)
3030 x -= thick + extra_x, left_p = true;
3031 if (s->slice.y == 0)
3032 y -= thick + extra_y, top_p = true;
3033 if (s->slice.x + s->slice.width == s->img->width)
3034 x1 += thick + extra_x, right_p = true;
3035 if (s->slice.y + s->slice.height == s->img->height)
3036 y1 += thick + extra_y, bot_p = true;
3038 x_setup_relief_colors (s);
3039 get_glyph_string_clip_rect (s, &r);
3040 x_draw_relief_rect (s->f, x, y, x1, y1, thick, raised_p,
3041 top_p, bot_p, left_p, right_p, &r);
3045 /* Draw the foreground of image glyph string S to PIXMAP. */
3047 static void
3048 x_draw_image_foreground_1 (struct glyph_string *s, Pixmap pixmap)
3050 int x = 0;
3051 int y = s->ybase - s->y - image_ascent (s->img, s->face, &s->slice);
3053 /* If first glyph of S has a left box line, start drawing it to the
3054 right of that line. */
3055 if (s->face->box != FACE_NO_BOX
3056 && s->first_glyph->left_box_line_p
3057 && s->slice.x == 0)
3058 x += eabs (s->face->box_line_width);
3060 /* If there is a margin around the image, adjust x- and y-position
3061 by that margin. */
3062 if (s->slice.x == 0)
3063 x += s->img->hmargin;
3064 if (s->slice.y == 0)
3065 y += s->img->vmargin;
3067 if (s->img->pixmap)
3069 if (s->img->mask)
3071 /* We can't set both a clip mask and use XSetClipRectangles
3072 because the latter also sets a clip mask. We also can't
3073 trust on the shape extension to be available
3074 (XShapeCombineRegion). So, compute the rectangle to draw
3075 manually. */
3076 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
3077 | GCFunction);
3078 XGCValues xgcv;
3080 xgcv.clip_mask = s->img->mask;
3081 xgcv.clip_x_origin = x - s->slice.x;
3082 xgcv.clip_y_origin = y - s->slice.y;
3083 xgcv.function = GXcopy;
3084 XChangeGC (s->display, s->gc, mask, &xgcv);
3086 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
3087 s->slice.x, s->slice.y,
3088 s->slice.width, s->slice.height, x, y);
3089 XSetClipMask (s->display, s->gc, None);
3091 else
3093 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
3094 s->slice.x, s->slice.y,
3095 s->slice.width, s->slice.height, x, y);
3097 /* When the image has a mask, we can expect that at
3098 least part of a mouse highlight or a block cursor will
3099 be visible. If the image doesn't have a mask, make
3100 a block cursor visible by drawing a rectangle around
3101 the image. I believe it's looking better if we do
3102 nothing here for mouse-face. */
3103 if (s->hl == DRAW_CURSOR)
3105 int r = eabs (s->img->relief);
3106 x_draw_rectangle (s->f, s->gc, x - r, y - r,
3107 s->slice.width + r*2 - 1,
3108 s->slice.height + r*2 - 1);
3112 else
3113 /* Draw a rectangle if image could not be loaded. */
3114 x_draw_rectangle (s->f, s->gc, x, y,
3115 s->slice.width - 1, s->slice.height - 1);
3119 /* Draw part of the background of glyph string S. X, Y, W, and H
3120 give the rectangle to draw. */
3122 static void
3123 x_draw_glyph_string_bg_rect (struct glyph_string *s, int x, int y, int w, int h)
3125 if (s->stippled_p)
3127 /* Fill background with a stipple pattern. */
3128 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
3129 x_fill_rectangle (s->f, s->gc, x, y, w, h);
3130 XSetFillStyle (s->display, s->gc, FillSolid);
3132 else
3133 x_clear_glyph_string_rect (s, x, y, w, h);
3137 /* Draw image glyph string S.
3139 s->y
3140 s->x +-------------------------
3141 | s->face->box
3143 | +-------------------------
3144 | | s->img->margin
3146 | | +-------------------
3147 | | | the image
3151 static void
3152 x_draw_image_glyph_string (struct glyph_string *s)
3154 int box_line_hwidth = eabs (s->face->box_line_width);
3155 int box_line_vwidth = max (s->face->box_line_width, 0);
3156 int height;
3157 Pixmap pixmap = None;
3159 height = s->height;
3160 if (s->slice.y == 0)
3161 height -= box_line_vwidth;
3162 if (s->slice.y + s->slice.height >= s->img->height)
3163 height -= box_line_vwidth;
3165 /* Fill background with face under the image. Do it only if row is
3166 taller than image or if image has a clip mask to reduce
3167 flickering. */
3168 s->stippled_p = s->face->stipple != 0;
3169 if (height > s->slice.height
3170 || s->img->hmargin
3171 || s->img->vmargin
3172 || s->img->mask
3173 || s->img->pixmap == 0
3174 || s->width != s->background_width)
3176 if (s->img->mask)
3178 /* Create a pixmap as large as the glyph string. Fill it
3179 with the background color. Copy the image to it, using
3180 its mask. Copy the temporary pixmap to the display. */
3181 Screen *screen = FRAME_X_SCREEN (s->f);
3182 int depth = DefaultDepthOfScreen (screen);
3184 /* Create a pixmap as large as the glyph string. */
3185 pixmap = XCreatePixmap (s->display, s->window,
3186 s->background_width,
3187 s->height, depth);
3189 /* Don't clip in the following because we're working on the
3190 pixmap. */
3191 XSetClipMask (s->display, s->gc, None);
3193 /* Fill the pixmap with the background color/stipple. */
3194 if (s->stippled_p)
3196 /* Fill background with a stipple pattern. */
3197 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
3198 XSetTSOrigin (s->display, s->gc, - s->x, - s->y);
3199 XFillRectangle (s->display, pixmap, s->gc,
3200 0, 0, s->background_width, s->height);
3201 XSetFillStyle (s->display, s->gc, FillSolid);
3202 XSetTSOrigin (s->display, s->gc, 0, 0);
3204 else
3206 XGCValues xgcv;
3207 XGetGCValues (s->display, s->gc, GCForeground | GCBackground,
3208 &xgcv);
3209 XSetForeground (s->display, s->gc, xgcv.background);
3210 XFillRectangle (s->display, pixmap, s->gc,
3211 0, 0, s->background_width, s->height);
3212 XSetForeground (s->display, s->gc, xgcv.foreground);
3215 else
3217 int x = s->x;
3218 int y = s->y;
3219 int width = s->background_width;
3221 if (s->first_glyph->left_box_line_p
3222 && s->slice.x == 0)
3224 x += box_line_hwidth;
3225 width -= box_line_hwidth;
3228 if (s->slice.y == 0)
3229 y += box_line_vwidth;
3231 x_draw_glyph_string_bg_rect (s, x, y, width, height);
3234 s->background_filled_p = true;
3237 /* Draw the foreground. */
3238 #ifdef USE_CAIRO
3239 if (s->img->cr_data)
3241 cairo_t *cr = x_begin_cr_clip (s->f, s->gc);
3243 int x = s->x + s->img->hmargin;
3244 int y = s->y + s->img->vmargin;
3245 int width = s->background_width;
3247 cairo_set_source_surface (cr, s->img->cr_data,
3248 x - s->slice.x,
3249 y - s->slice.y);
3250 cairo_rectangle (cr, x, y, width, height);
3251 cairo_fill (cr);
3252 x_end_cr_clip (s->f);
3254 else
3255 #endif
3256 if (pixmap != None)
3258 x_draw_image_foreground_1 (s, pixmap);
3259 x_set_glyph_string_clipping (s);
3260 XCopyArea (s->display, pixmap, s->window, s->gc,
3261 0, 0, s->background_width, s->height, s->x, s->y);
3262 XFreePixmap (s->display, pixmap);
3264 else
3265 x_draw_image_foreground (s);
3267 /* If we must draw a relief around the image, do it. */
3268 if (s->img->relief
3269 || s->hl == DRAW_IMAGE_RAISED
3270 || s->hl == DRAW_IMAGE_SUNKEN)
3271 x_draw_image_relief (s);
3275 /* Draw stretch glyph string S. */
3277 static void
3278 x_draw_stretch_glyph_string (struct glyph_string *s)
3280 eassert (s->first_glyph->type == STRETCH_GLYPH);
3282 if (s->hl == DRAW_CURSOR
3283 && !x_stretch_cursor_p)
3285 /* If `x-stretch-cursor' is nil, don't draw a block cursor as
3286 wide as the stretch glyph. */
3287 int width, background_width = s->background_width;
3288 int x = s->x;
3290 if (!s->row->reversed_p)
3292 int left_x = window_box_left_offset (s->w, TEXT_AREA);
3294 if (x < left_x)
3296 background_width -= left_x - x;
3297 x = left_x;
3300 else
3302 /* In R2L rows, draw the cursor on the right edge of the
3303 stretch glyph. */
3304 int right_x = window_box_right (s->w, TEXT_AREA);
3306 if (x + background_width > right_x)
3307 background_width -= x - right_x;
3308 x += background_width;
3310 width = min (FRAME_COLUMN_WIDTH (s->f), background_width);
3311 if (s->row->reversed_p)
3312 x -= width;
3314 /* Draw cursor. */
3315 x_draw_glyph_string_bg_rect (s, x, s->y, width, s->height);
3317 /* Clear rest using the GC of the original non-cursor face. */
3318 if (width < background_width)
3320 int y = s->y;
3321 int w = background_width - width, h = s->height;
3322 XRectangle r;
3323 GC gc;
3325 if (!s->row->reversed_p)
3326 x += width;
3327 else
3328 x = s->x;
3329 if (s->row->mouse_face_p
3330 && cursor_in_mouse_face_p (s->w))
3332 x_set_mouse_face_gc (s);
3333 gc = s->gc;
3335 else
3336 gc = s->face->gc;
3338 get_glyph_string_clip_rect (s, &r);
3339 x_set_clip_rectangles (s->f, gc, &r, 1);
3341 if (s->face->stipple)
3343 /* Fill background with a stipple pattern. */
3344 XSetFillStyle (s->display, gc, FillOpaqueStippled);
3345 x_fill_rectangle (s->f, gc, x, y, w, h);
3346 XSetFillStyle (s->display, gc, FillSolid);
3348 else
3350 XGCValues xgcv;
3351 XGetGCValues (s->display, gc, GCForeground | GCBackground, &xgcv);
3352 XSetForeground (s->display, gc, xgcv.background);
3353 x_fill_rectangle (s->f, gc, x, y, w, h);
3354 XSetForeground (s->display, gc, xgcv.foreground);
3357 x_reset_clip_rectangles (s->f, gc);
3360 else if (!s->background_filled_p)
3362 int background_width = s->background_width;
3363 int x = s->x, left_x = window_box_left_offset (s->w, TEXT_AREA);
3365 /* Don't draw into left margin, fringe or scrollbar area
3366 except for header line and mode line. */
3367 if (x < left_x && !s->row->mode_line_p)
3369 background_width -= left_x - x;
3370 x = left_x;
3372 if (background_width > 0)
3373 x_draw_glyph_string_bg_rect (s, x, s->y, background_width, s->height);
3376 s->background_filled_p = true;
3380 Draw a wavy line under S. The wave fills wave_height pixels from y0.
3382 x0 wave_length = 2
3384 y0 * * * * *
3385 |* * * * * * * * *
3386 wave_height = 3 | * * * *
3390 static void
3391 x_draw_underwave (struct glyph_string *s)
3393 int wave_height = 3, wave_length = 2;
3394 #ifdef USE_CAIRO
3395 x_draw_horizontal_wave (s->f, s->gc, s->x, s->ybase - wave_height + 3,
3396 s->width, wave_height, wave_length);
3397 #else /* not USE_CAIRO */
3398 int dx, dy, x0, y0, width, x1, y1, x2, y2, xmax;
3399 bool odd;
3400 XRectangle wave_clip, string_clip, final_clip;
3402 dx = wave_length;
3403 dy = wave_height - 1;
3404 x0 = s->x;
3405 y0 = s->ybase - wave_height + 3;
3406 width = s->width;
3407 xmax = x0 + width;
3409 /* Find and set clipping rectangle */
3411 wave_clip.x = x0;
3412 wave_clip.y = y0;
3413 wave_clip.width = width;
3414 wave_clip.height = wave_height;
3415 get_glyph_string_clip_rect (s, &string_clip);
3417 if (!x_intersect_rectangles (&wave_clip, &string_clip, &final_clip))
3418 return;
3420 XSetClipRectangles (s->display, s->gc, 0, 0, &final_clip, 1, Unsorted);
3422 /* Draw the waves */
3424 x1 = x0 - (x0 % dx);
3425 x2 = x1 + dx;
3426 odd = (x1 / dx) & 1;
3427 y1 = y2 = y0;
3429 if (odd)
3430 y1 += dy;
3431 else
3432 y2 += dy;
3434 if (INT_MAX - dx < xmax)
3435 emacs_abort ();
3437 while (x1 <= xmax)
3439 XDrawLine (s->display, s->window, s->gc, x1, y1, x2, y2);
3440 x1 = x2, y1 = y2;
3441 x2 += dx, y2 = y0 + odd*dy;
3442 odd = !odd;
3445 /* Restore previous clipping rectangle(s) */
3446 XSetClipRectangles (s->display, s->gc, 0, 0, s->clip, s->num_clips, Unsorted);
3447 #endif /* not USE_CAIRO */
3451 /* Draw glyph string S. */
3453 static void
3454 x_draw_glyph_string (struct glyph_string *s)
3456 bool relief_drawn_p = false;
3458 /* If S draws into the background of its successors, draw the
3459 background of the successors first so that S can draw into it.
3460 This makes S->next use XDrawString instead of XDrawImageString. */
3461 if (s->next && s->right_overhang && !s->for_overlaps)
3463 int width;
3464 struct glyph_string *next;
3466 for (width = 0, next = s->next;
3467 next && width < s->right_overhang;
3468 width += next->width, next = next->next)
3469 if (next->first_glyph->type != IMAGE_GLYPH)
3471 x_set_glyph_string_gc (next);
3472 x_set_glyph_string_clipping (next);
3473 if (next->first_glyph->type == STRETCH_GLYPH)
3474 x_draw_stretch_glyph_string (next);
3475 else
3476 x_draw_glyph_string_background (next, true);
3477 next->num_clips = 0;
3481 /* Set up S->gc, set clipping and draw S. */
3482 x_set_glyph_string_gc (s);
3484 /* Draw relief (if any) in advance for char/composition so that the
3485 glyph string can be drawn over it. */
3486 if (!s->for_overlaps
3487 && s->face->box != FACE_NO_BOX
3488 && (s->first_glyph->type == CHAR_GLYPH
3489 || s->first_glyph->type == COMPOSITE_GLYPH))
3492 x_set_glyph_string_clipping (s);
3493 x_draw_glyph_string_background (s, true);
3494 x_draw_glyph_string_box (s);
3495 x_set_glyph_string_clipping (s);
3496 relief_drawn_p = true;
3498 else if (!s->clip_head /* draw_glyphs didn't specify a clip mask. */
3499 && !s->clip_tail
3500 && ((s->prev && s->prev->hl != s->hl && s->left_overhang)
3501 || (s->next && s->next->hl != s->hl && s->right_overhang)))
3502 /* We must clip just this glyph. left_overhang part has already
3503 drawn when s->prev was drawn, and right_overhang part will be
3504 drawn later when s->next is drawn. */
3505 x_set_glyph_string_clipping_exactly (s, s);
3506 else
3507 x_set_glyph_string_clipping (s);
3509 switch (s->first_glyph->type)
3511 case IMAGE_GLYPH:
3512 x_draw_image_glyph_string (s);
3513 break;
3515 case XWIDGET_GLYPH:
3516 x_draw_xwidget_glyph_string (s);
3517 break;
3519 case STRETCH_GLYPH:
3520 x_draw_stretch_glyph_string (s);
3521 break;
3523 case CHAR_GLYPH:
3524 if (s->for_overlaps)
3525 s->background_filled_p = true;
3526 else
3527 x_draw_glyph_string_background (s, false);
3528 x_draw_glyph_string_foreground (s);
3529 break;
3531 case COMPOSITE_GLYPH:
3532 if (s->for_overlaps || (s->cmp_from > 0
3533 && ! s->first_glyph->u.cmp.automatic))
3534 s->background_filled_p = true;
3535 else
3536 x_draw_glyph_string_background (s, true);
3537 x_draw_composite_glyph_string_foreground (s);
3538 break;
3540 case GLYPHLESS_GLYPH:
3541 if (s->for_overlaps)
3542 s->background_filled_p = true;
3543 else
3544 x_draw_glyph_string_background (s, true);
3545 x_draw_glyphless_glyph_string_foreground (s);
3546 break;
3548 default:
3549 emacs_abort ();
3552 if (!s->for_overlaps)
3554 /* Draw underline. */
3555 if (s->face->underline_p)
3557 if (s->face->underline_type == FACE_UNDER_WAVE)
3559 if (s->face->underline_defaulted_p)
3560 x_draw_underwave (s);
3561 else
3563 XGCValues xgcv;
3564 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3565 XSetForeground (s->display, s->gc, s->face->underline_color);
3566 x_draw_underwave (s);
3567 XSetForeground (s->display, s->gc, xgcv.foreground);
3570 else if (s->face->underline_type == FACE_UNDER_LINE)
3572 unsigned long thickness, position;
3573 int y;
3575 if (s->prev && s->prev->face->underline_p
3576 && s->prev->face->underline_type == FACE_UNDER_LINE)
3578 /* We use the same underline style as the previous one. */
3579 thickness = s->prev->underline_thickness;
3580 position = s->prev->underline_position;
3582 else
3584 /* Get the underline thickness. Default is 1 pixel. */
3585 if (s->font && s->font->underline_thickness > 0)
3586 thickness = s->font->underline_thickness;
3587 else
3588 thickness = 1;
3589 if (x_underline_at_descent_line)
3590 position = (s->height - thickness) - (s->ybase - s->y);
3591 else
3593 /* Get the underline position. This is the recommended
3594 vertical offset in pixels from the baseline to the top of
3595 the underline. This is a signed value according to the
3596 specs, and its default is
3598 ROUND ((maximum descent) / 2), with
3599 ROUND(x) = floor (x + 0.5) */
3601 if (x_use_underline_position_properties
3602 && s->font && s->font->underline_position >= 0)
3603 position = s->font->underline_position;
3604 else if (s->font)
3605 position = (s->font->descent + 1) / 2;
3606 else
3607 position = underline_minimum_offset;
3609 position = max (position, underline_minimum_offset);
3611 /* Check the sanity of thickness and position. We should
3612 avoid drawing underline out of the current line area. */
3613 if (s->y + s->height <= s->ybase + position)
3614 position = (s->height - 1) - (s->ybase - s->y);
3615 if (s->y + s->height < s->ybase + position + thickness)
3616 thickness = (s->y + s->height) - (s->ybase + position);
3617 s->underline_thickness = thickness;
3618 s->underline_position = position;
3619 y = s->ybase + position;
3620 if (s->face->underline_defaulted_p)
3621 x_fill_rectangle (s->f, s->gc,
3622 s->x, y, s->width, thickness);
3623 else
3625 XGCValues xgcv;
3626 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3627 XSetForeground (s->display, s->gc, s->face->underline_color);
3628 x_fill_rectangle (s->f, s->gc,
3629 s->x, y, s->width, thickness);
3630 XSetForeground (s->display, s->gc, xgcv.foreground);
3634 /* Draw overline. */
3635 if (s->face->overline_p)
3637 unsigned long dy = 0, h = 1;
3639 if (s->face->overline_color_defaulted_p)
3640 x_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3641 s->width, h);
3642 else
3644 XGCValues xgcv;
3645 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3646 XSetForeground (s->display, s->gc, s->face->overline_color);
3647 x_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3648 s->width, h);
3649 XSetForeground (s->display, s->gc, xgcv.foreground);
3653 /* Draw strike-through. */
3654 if (s->face->strike_through_p)
3656 unsigned long h = 1;
3657 unsigned long dy = (s->height - h) / 2;
3659 if (s->face->strike_through_color_defaulted_p)
3660 x_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3661 s->width, h);
3662 else
3664 XGCValues xgcv;
3665 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3666 XSetForeground (s->display, s->gc, s->face->strike_through_color);
3667 x_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3668 s->width, h);
3669 XSetForeground (s->display, s->gc, xgcv.foreground);
3673 /* Draw relief if not yet drawn. */
3674 if (!relief_drawn_p && s->face->box != FACE_NO_BOX)
3675 x_draw_glyph_string_box (s);
3677 if (s->prev)
3679 struct glyph_string *prev;
3681 for (prev = s->prev; prev; prev = prev->prev)
3682 if (prev->hl != s->hl
3683 && prev->x + prev->width + prev->right_overhang > s->x)
3685 /* As prev was drawn while clipped to its own area, we
3686 must draw the right_overhang part using s->hl now. */
3687 enum draw_glyphs_face save = prev->hl;
3689 prev->hl = s->hl;
3690 x_set_glyph_string_gc (prev);
3691 x_set_glyph_string_clipping_exactly (s, prev);
3692 if (prev->first_glyph->type == CHAR_GLYPH)
3693 x_draw_glyph_string_foreground (prev);
3694 else
3695 x_draw_composite_glyph_string_foreground (prev);
3696 x_reset_clip_rectangles (prev->f, prev->gc);
3697 prev->hl = save;
3698 prev->num_clips = 0;
3702 if (s->next)
3704 struct glyph_string *next;
3706 for (next = s->next; next; next = next->next)
3707 if (next->hl != s->hl
3708 && next->x - next->left_overhang < s->x + s->width)
3710 /* As next will be drawn while clipped to its own area,
3711 we must draw the left_overhang part using s->hl now. */
3712 enum draw_glyphs_face save = next->hl;
3714 next->hl = s->hl;
3715 x_set_glyph_string_gc (next);
3716 x_set_glyph_string_clipping_exactly (s, next);
3717 if (next->first_glyph->type == CHAR_GLYPH)
3718 x_draw_glyph_string_foreground (next);
3719 else
3720 x_draw_composite_glyph_string_foreground (next);
3721 x_reset_clip_rectangles (next->f, next->gc);
3722 next->hl = save;
3723 next->num_clips = 0;
3724 next->clip_head = s->next;
3729 /* Reset clipping. */
3730 x_reset_clip_rectangles (s->f, s->gc);
3731 s->num_clips = 0;
3734 /* Shift display to make room for inserted glyphs. */
3736 static void
3737 x_shift_glyphs_for_insert (struct frame *f, int x, int y, int width, int height, int shift_by)
3739 /* Never called on a GUI frame, see
3740 http://lists.gnu.org/archive/html/emacs-devel/2015-05/msg00456.html
3742 XCopyArea (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), FRAME_X_WINDOW (f),
3743 f->output_data.x->normal_gc,
3744 x, y, width, height,
3745 x + shift_by, y);
3748 /* Delete N glyphs at the nominal cursor position. Not implemented
3749 for X frames. */
3751 static void
3752 x_delete_glyphs (struct frame *f, register int n)
3754 emacs_abort ();
3758 /* Like XClearArea, but check that WIDTH and HEIGHT are reasonable.
3759 If they are <= 0, this is probably an error. */
3761 static ATTRIBUTE_UNUSED void
3762 x_clear_area1 (Display *dpy, Window window,
3763 int x, int y, int width, int height, int exposures)
3765 eassert (width > 0 && height > 0);
3766 XClearArea (dpy, window, x, y, width, height, exposures);
3769 void
3770 x_clear_area (struct frame *f, int x, int y, int width, int height)
3772 #ifdef USE_CAIRO
3773 cairo_t *cr;
3775 eassert (width > 0 && height > 0);
3777 cr = x_begin_cr_clip (f, NULL);
3778 x_set_cr_source_with_gc_background (f, f->output_data.x->normal_gc);
3779 cairo_rectangle (cr, x, y, width, height);
3780 cairo_fill (cr);
3781 x_end_cr_clip (f);
3782 #else
3783 x_clear_area1 (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3784 x, y, width, height, False);
3785 #endif
3789 /* Clear an entire frame. */
3791 static void
3792 x_clear_frame (struct frame *f)
3794 /* Clearing the frame will erase any cursor, so mark them all as no
3795 longer visible. */
3796 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
3798 block_input ();
3800 x_clear_window (f);
3802 /* We have to clear the scroll bars. If we have changed colors or
3803 something like that, then they should be notified. */
3804 x_scroll_bar_clear (f);
3806 #if defined (USE_GTK) && defined (USE_TOOLKIT_SCROLL_BARS)
3807 /* Make sure scroll bars are redrawn. As they aren't redrawn by
3808 redisplay, do it here. */
3809 if (FRAME_GTK_WIDGET (f))
3810 gtk_widget_queue_draw (FRAME_GTK_WIDGET (f));
3811 #endif
3813 XFlush (FRAME_X_DISPLAY (f));
3815 unblock_input ();
3818 /* RIF: Show hourglass cursor on frame F. */
3820 static void
3821 x_show_hourglass (struct frame *f)
3823 Display *dpy = FRAME_X_DISPLAY (f);
3825 if (dpy)
3827 struct x_output *x = FRAME_X_OUTPUT (f);
3828 #ifdef USE_X_TOOLKIT
3829 if (x->widget)
3830 #else
3831 if (FRAME_OUTER_WINDOW (f))
3832 #endif
3834 x->hourglass_p = true;
3836 if (!x->hourglass_window)
3838 unsigned long mask = CWCursor;
3839 XSetWindowAttributes attrs;
3840 #ifdef USE_GTK
3841 Window parent = FRAME_X_WINDOW (f);
3842 #else
3843 Window parent = FRAME_OUTER_WINDOW (f);
3844 #endif
3845 attrs.cursor = x->hourglass_cursor;
3847 x->hourglass_window = XCreateWindow
3848 (dpy, parent, 0, 0, 32000, 32000, 0, 0,
3849 InputOnly, CopyFromParent, mask, &attrs);
3852 XMapRaised (dpy, x->hourglass_window);
3853 XFlush (dpy);
3858 /* RIF: Cancel hourglass cursor on frame F. */
3860 static void
3861 x_hide_hourglass (struct frame *f)
3863 struct x_output *x = FRAME_X_OUTPUT (f);
3865 /* Watch out for newly created frames. */
3866 if (x->hourglass_window)
3868 XUnmapWindow (FRAME_X_DISPLAY (f), x->hourglass_window);
3869 /* Sync here because XTread_socket looks at the
3870 hourglass_p flag that is reset to zero below. */
3871 XSync (FRAME_X_DISPLAY (f), False);
3872 x->hourglass_p = false;
3876 /* Invert the middle quarter of the frame for .15 sec. */
3878 static void
3879 XTflash (struct frame *f)
3881 block_input ();
3884 #ifdef USE_GTK
3885 /* Use Gdk routines to draw. This way, we won't draw over scroll bars
3886 when the scroll bars and the edit widget share the same X window. */
3887 GdkWindow *window = gtk_widget_get_window (FRAME_GTK_WIDGET (f));
3888 #ifdef HAVE_GTK3
3889 cairo_t *cr = gdk_cairo_create (window);
3890 cairo_set_source_rgb (cr, 1, 1, 1);
3891 cairo_set_operator (cr, CAIRO_OPERATOR_DIFFERENCE);
3892 #define XFillRectangle(d, win, gc, x, y, w, h) \
3893 do { \
3894 cairo_rectangle (cr, x, y, w, h); \
3895 cairo_fill (cr); \
3897 while (false)
3898 #else /* ! HAVE_GTK3 */
3899 GdkGCValues vals;
3900 GdkGC *gc;
3901 vals.foreground.pixel = (FRAME_FOREGROUND_PIXEL (f)
3902 ^ FRAME_BACKGROUND_PIXEL (f));
3903 vals.function = GDK_XOR;
3904 gc = gdk_gc_new_with_values (window,
3905 &vals, GDK_GC_FUNCTION | GDK_GC_FOREGROUND);
3906 #define XFillRectangle(d, win, gc, x, y, w, h) \
3907 gdk_draw_rectangle (window, gc, true, x, y, w, h)
3908 #endif /* ! HAVE_GTK3 */
3909 #else /* ! USE_GTK */
3910 GC gc;
3912 /* Create a GC that will use the GXxor function to flip foreground
3913 pixels into background pixels. */
3915 XGCValues values;
3917 values.function = GXxor;
3918 values.foreground = (FRAME_FOREGROUND_PIXEL (f)
3919 ^ FRAME_BACKGROUND_PIXEL (f));
3921 gc = XCreateGC (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3922 GCFunction | GCForeground, &values);
3924 #endif
3926 /* Get the height not including a menu bar widget. */
3927 int height = FRAME_PIXEL_HEIGHT (f);
3928 /* Height of each line to flash. */
3929 int flash_height = FRAME_LINE_HEIGHT (f);
3930 /* These will be the left and right margins of the rectangles. */
3931 int flash_left = FRAME_INTERNAL_BORDER_WIDTH (f);
3932 int flash_right = FRAME_PIXEL_WIDTH (f) - FRAME_INTERNAL_BORDER_WIDTH (f);
3933 int width = flash_right - flash_left;
3935 /* If window is tall, flash top and bottom line. */
3936 if (height > 3 * FRAME_LINE_HEIGHT (f))
3938 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3939 flash_left,
3940 (FRAME_INTERNAL_BORDER_WIDTH (f)
3941 + FRAME_TOP_MARGIN_HEIGHT (f)),
3942 width, flash_height);
3943 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3944 flash_left,
3945 (height - flash_height
3946 - FRAME_INTERNAL_BORDER_WIDTH (f)),
3947 width, flash_height);
3950 else
3951 /* If it is short, flash it all. */
3952 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3953 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
3954 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
3956 x_flush (f);
3959 struct timespec delay = make_timespec (0, 150 * 1000 * 1000);
3960 struct timespec wakeup = timespec_add (current_timespec (), delay);
3962 /* Keep waiting until past the time wakeup or any input gets
3963 available. */
3964 while (! detect_input_pending ())
3966 struct timespec current = current_timespec ();
3967 struct timespec timeout;
3969 /* Break if result would not be positive. */
3970 if (timespec_cmp (wakeup, current) <= 0)
3971 break;
3973 /* How long `select' should wait. */
3974 timeout = make_timespec (0, 10 * 1000 * 1000);
3976 /* Try to wait that long--but we might wake up sooner. */
3977 pselect (0, NULL, NULL, NULL, &timeout, NULL);
3981 /* If window is tall, flash top and bottom line. */
3982 if (height > 3 * FRAME_LINE_HEIGHT (f))
3984 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3985 flash_left,
3986 (FRAME_INTERNAL_BORDER_WIDTH (f)
3987 + FRAME_TOP_MARGIN_HEIGHT (f)),
3988 width, flash_height);
3989 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3990 flash_left,
3991 (height - flash_height
3992 - FRAME_INTERNAL_BORDER_WIDTH (f)),
3993 width, flash_height);
3995 else
3996 /* If it is short, flash it all. */
3997 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3998 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
3999 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
4001 #ifdef USE_GTK
4002 #ifdef HAVE_GTK3
4003 cairo_destroy (cr);
4004 #else
4005 g_object_unref (G_OBJECT (gc));
4006 #endif
4007 #undef XFillRectangle
4008 #else
4009 XFreeGC (FRAME_X_DISPLAY (f), gc);
4010 #endif
4011 x_flush (f);
4015 unblock_input ();
4019 static void
4020 XTtoggle_invisible_pointer (struct frame *f, bool invisible)
4022 block_input ();
4023 FRAME_DISPLAY_INFO (f)->toggle_visible_pointer (f, invisible);
4024 unblock_input ();
4028 /* Make audible bell. */
4030 static void
4031 XTring_bell (struct frame *f)
4033 if (FRAME_X_DISPLAY (f))
4035 if (visible_bell)
4036 XTflash (f);
4037 else
4039 block_input ();
4040 #ifdef HAVE_XKB
4041 XkbBell (FRAME_X_DISPLAY (f), None, 0, None);
4042 #else
4043 XBell (FRAME_X_DISPLAY (f), 0);
4044 #endif
4045 XFlush (FRAME_X_DISPLAY (f));
4046 unblock_input ();
4051 /***********************************************************************
4052 Line Dance
4053 ***********************************************************************/
4055 /* Perform an insert-lines or delete-lines operation, inserting N
4056 lines or deleting -N lines at vertical position VPOS. */
4058 static void
4059 x_ins_del_lines (struct frame *f, int vpos, int n)
4061 emacs_abort ();
4065 /* Scroll part of the display as described by RUN. */
4067 static void
4068 x_scroll_run (struct window *w, struct run *run)
4070 struct frame *f = XFRAME (w->frame);
4071 int x, y, width, height, from_y, to_y, bottom_y;
4073 /* Get frame-relative bounding box of the text display area of W,
4074 without mode lines. Include in this box the left and right
4075 fringe of W. */
4076 window_box (w, ANY_AREA, &x, &y, &width, &height);
4078 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
4079 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
4080 bottom_y = y + height;
4082 if (to_y < from_y)
4084 /* Scrolling up. Make sure we don't copy part of the mode
4085 line at the bottom. */
4086 if (from_y + run->height > bottom_y)
4087 height = bottom_y - from_y;
4088 else
4089 height = run->height;
4091 else
4093 /* Scrolling down. Make sure we don't copy over the mode line.
4094 at the bottom. */
4095 if (to_y + run->height > bottom_y)
4096 height = bottom_y - to_y;
4097 else
4098 height = run->height;
4101 block_input ();
4103 /* Cursor off. Will be switched on again in x_update_window_end. */
4104 x_clear_cursor (w);
4106 #ifdef USE_CAIRO
4107 SET_FRAME_GARBAGED (f);
4108 #else
4109 XCopyArea (FRAME_X_DISPLAY (f),
4110 FRAME_X_WINDOW (f), FRAME_X_WINDOW (f),
4111 f->output_data.x->normal_gc,
4112 x, from_y,
4113 width, height,
4114 x, to_y);
4115 #endif
4117 unblock_input ();
4122 /***********************************************************************
4123 Exposure Events
4124 ***********************************************************************/
4127 static void
4128 frame_highlight (struct frame *f)
4130 /* We used to only do this if Vx_no_window_manager was non-nil, but
4131 the ICCCM (section 4.1.6) says that the window's border pixmap
4132 and border pixel are window attributes which are "private to the
4133 client", so we can always change it to whatever we want. */
4134 block_input ();
4135 /* I recently started to get errors in this XSetWindowBorder, depending on
4136 the window-manager in use, tho something more is at play since I've been
4137 using that same window-manager binary for ever. Let's not crash just
4138 because of this (bug#9310). */
4139 x_catch_errors (FRAME_X_DISPLAY (f));
4140 XSetWindowBorder (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4141 f->output_data.x->border_pixel);
4142 x_uncatch_errors ();
4143 unblock_input ();
4144 x_update_cursor (f, true);
4145 x_set_frame_alpha (f);
4148 static void
4149 frame_unhighlight (struct frame *f)
4151 /* We used to only do this if Vx_no_window_manager was non-nil, but
4152 the ICCCM (section 4.1.6) says that the window's border pixmap
4153 and border pixel are window attributes which are "private to the
4154 client", so we can always change it to whatever we want. */
4155 block_input ();
4156 /* Same as above for XSetWindowBorder (bug#9310). */
4157 x_catch_errors (FRAME_X_DISPLAY (f));
4158 XSetWindowBorderPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4159 f->output_data.x->border_tile);
4160 x_uncatch_errors ();
4161 unblock_input ();
4162 x_update_cursor (f, true);
4163 x_set_frame_alpha (f);
4166 /* The focus has changed. Update the frames as necessary to reflect
4167 the new situation. Note that we can't change the selected frame
4168 here, because the Lisp code we are interrupting might become confused.
4169 Each event gets marked with the frame in which it occurred, so the
4170 Lisp code can tell when the switch took place by examining the events. */
4172 static void
4173 x_new_focus_frame (struct x_display_info *dpyinfo, struct frame *frame)
4175 struct frame *old_focus = dpyinfo->x_focus_frame;
4177 if (frame != dpyinfo->x_focus_frame)
4179 /* Set this before calling other routines, so that they see
4180 the correct value of x_focus_frame. */
4181 dpyinfo->x_focus_frame = frame;
4183 if (old_focus && old_focus->auto_lower)
4184 x_lower_frame (old_focus);
4186 if (dpyinfo->x_focus_frame && dpyinfo->x_focus_frame->auto_raise)
4187 dpyinfo->x_pending_autoraise_frame = dpyinfo->x_focus_frame;
4188 else
4189 dpyinfo->x_pending_autoraise_frame = NULL;
4192 x_frame_rehighlight (dpyinfo);
4195 /* Handle FocusIn and FocusOut state changes for FRAME.
4196 If FRAME has focus and there exists more than one frame, puts
4197 a FOCUS_IN_EVENT into *BUFP. */
4199 static void
4200 x_focus_changed (int type, int state, struct x_display_info *dpyinfo, struct frame *frame, struct input_event *bufp)
4202 if (type == FocusIn)
4204 if (dpyinfo->x_focus_event_frame != frame)
4206 x_new_focus_frame (dpyinfo, frame);
4207 dpyinfo->x_focus_event_frame = frame;
4209 /* Don't stop displaying the initial startup message
4210 for a switch-frame event we don't need. */
4211 /* When run as a daemon, Vterminal_frame is always NIL. */
4212 bufp->arg = (((NILP (Vterminal_frame)
4213 || ! FRAME_X_P (XFRAME (Vterminal_frame))
4214 || EQ (Fdaemonp (), Qt))
4215 && CONSP (Vframe_list)
4216 && !NILP (XCDR (Vframe_list)))
4217 ? Qt : Qnil);
4218 bufp->kind = FOCUS_IN_EVENT;
4219 XSETFRAME (bufp->frame_or_window, frame);
4222 frame->output_data.x->focus_state |= state;
4224 #ifdef HAVE_X_I18N
4225 if (FRAME_XIC (frame))
4226 XSetICFocus (FRAME_XIC (frame));
4227 #endif
4229 else if (type == FocusOut)
4231 frame->output_data.x->focus_state &= ~state;
4233 if (dpyinfo->x_focus_event_frame == frame)
4235 dpyinfo->x_focus_event_frame = 0;
4236 x_new_focus_frame (dpyinfo, 0);
4238 bufp->kind = FOCUS_OUT_EVENT;
4239 XSETFRAME (bufp->frame_or_window, frame);
4242 #ifdef HAVE_X_I18N
4243 if (FRAME_XIC (frame))
4244 XUnsetICFocus (FRAME_XIC (frame));
4245 #endif
4246 if (frame->pointer_invisible)
4247 XTtoggle_invisible_pointer (frame, false);
4251 /* Return the Emacs frame-object corresponding to an X window.
4252 It could be the frame's main window or an icon window. */
4254 static struct frame *
4255 x_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
4257 Lisp_Object tail, frame;
4258 struct frame *f;
4260 if (wdesc == None)
4261 return NULL;
4263 FOR_EACH_FRAME (tail, frame)
4265 f = XFRAME (frame);
4266 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
4267 continue;
4268 if (f->output_data.x->hourglass_window == wdesc)
4269 return f;
4270 #ifdef USE_X_TOOLKIT
4271 if ((f->output_data.x->edit_widget
4272 && XtWindow (f->output_data.x->edit_widget) == wdesc)
4273 /* A tooltip frame? */
4274 || (!f->output_data.x->edit_widget
4275 && FRAME_X_WINDOW (f) == wdesc)
4276 || f->output_data.x->icon_desc == wdesc)
4277 return f;
4278 #else /* not USE_X_TOOLKIT */
4279 #ifdef USE_GTK
4280 if (f->output_data.x->edit_widget)
4282 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
4283 struct x_output *x = f->output_data.x;
4284 if (gwdesc != 0 && gwdesc == x->edit_widget)
4285 return f;
4287 #endif /* USE_GTK */
4288 if (FRAME_X_WINDOW (f) == wdesc
4289 || f->output_data.x->icon_desc == wdesc)
4290 return f;
4291 #endif /* not USE_X_TOOLKIT */
4293 return 0;
4296 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
4298 /* Like x_window_to_frame but also compares the window with the widget's
4299 windows. */
4301 static struct frame *
4302 x_any_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
4304 Lisp_Object tail, frame;
4305 struct frame *f, *found = NULL;
4306 struct x_output *x;
4308 if (wdesc == None)
4309 return NULL;
4311 FOR_EACH_FRAME (tail, frame)
4313 if (found)
4314 break;
4315 f = XFRAME (frame);
4316 if (FRAME_X_P (f) && FRAME_DISPLAY_INFO (f) == dpyinfo)
4318 /* This frame matches if the window is any of its widgets. */
4319 x = f->output_data.x;
4320 if (x->hourglass_window == wdesc)
4321 found = f;
4322 else if (x->widget)
4324 #ifdef USE_GTK
4325 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
4326 if (gwdesc != 0
4327 && gtk_widget_get_toplevel (gwdesc) == x->widget)
4328 found = f;
4329 #else
4330 if (wdesc == XtWindow (x->widget)
4331 || wdesc == XtWindow (x->column_widget)
4332 || wdesc == XtWindow (x->edit_widget))
4333 found = f;
4334 /* Match if the window is this frame's menubar. */
4335 else if (lw_window_is_in_menubar (wdesc, x->menubar_widget))
4336 found = f;
4337 #endif
4339 else if (FRAME_X_WINDOW (f) == wdesc)
4340 /* A tooltip frame. */
4341 found = f;
4345 return found;
4348 /* Likewise, but consider only the menu bar widget. */
4350 static struct frame *
4351 x_menubar_window_to_frame (struct x_display_info *dpyinfo,
4352 const XEvent *event)
4354 Window wdesc = event->xany.window;
4355 Lisp_Object tail, frame;
4356 struct frame *f;
4357 struct x_output *x;
4359 if (wdesc == None)
4360 return NULL;
4362 FOR_EACH_FRAME (tail, frame)
4364 f = XFRAME (frame);
4365 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
4366 continue;
4367 x = f->output_data.x;
4368 #ifdef USE_GTK
4369 if (x->menubar_widget && xg_event_is_for_menubar (f, event))
4370 return f;
4371 #else
4372 /* Match if the window is this frame's menubar. */
4373 if (x->menubar_widget
4374 && lw_window_is_in_menubar (wdesc, x->menubar_widget))
4375 return f;
4376 #endif
4378 return 0;
4381 /* Return the frame whose principal (outermost) window is WDESC.
4382 If WDESC is some other (smaller) window, we return 0. */
4384 struct frame *
4385 x_top_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
4387 Lisp_Object tail, frame;
4388 struct frame *f;
4389 struct x_output *x;
4391 if (wdesc == None)
4392 return NULL;
4394 FOR_EACH_FRAME (tail, frame)
4396 f = XFRAME (frame);
4397 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
4398 continue;
4399 x = f->output_data.x;
4401 if (x->widget)
4403 /* This frame matches if the window is its topmost widget. */
4404 #ifdef USE_GTK
4405 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
4406 if (gwdesc == x->widget)
4407 return f;
4408 #else
4409 if (wdesc == XtWindow (x->widget))
4410 return f;
4411 #endif
4413 else if (FRAME_X_WINDOW (f) == wdesc)
4414 /* Tooltip frame. */
4415 return f;
4417 return 0;
4420 #else /* !USE_X_TOOLKIT && !USE_GTK */
4422 #define x_any_window_to_frame(d, i) x_window_to_frame (d, i)
4423 #define x_top_window_to_frame(d, i) x_window_to_frame (d, i)
4425 #endif /* USE_X_TOOLKIT || USE_GTK */
4427 /* The focus may have changed. Figure out if it is a real focus change,
4428 by checking both FocusIn/Out and Enter/LeaveNotify events.
4430 Returns FOCUS_IN_EVENT event in *BUFP. */
4432 static void
4433 x_detect_focus_change (struct x_display_info *dpyinfo, struct frame *frame,
4434 const XEvent *event, struct input_event *bufp)
4436 if (!frame)
4437 return;
4439 switch (event->type)
4441 case EnterNotify:
4442 case LeaveNotify:
4444 struct frame *focus_frame = dpyinfo->x_focus_event_frame;
4445 int focus_state
4446 = focus_frame ? focus_frame->output_data.x->focus_state : 0;
4448 if (event->xcrossing.detail != NotifyInferior
4449 && event->xcrossing.focus
4450 && ! (focus_state & FOCUS_EXPLICIT))
4451 x_focus_changed ((event->type == EnterNotify ? FocusIn : FocusOut),
4452 FOCUS_IMPLICIT,
4453 dpyinfo, frame, bufp);
4455 break;
4457 case FocusIn:
4458 case FocusOut:
4459 x_focus_changed (event->type,
4460 (event->xfocus.detail == NotifyPointer ?
4461 FOCUS_IMPLICIT : FOCUS_EXPLICIT),
4462 dpyinfo, frame, bufp);
4463 break;
4465 case ClientMessage:
4466 if (event->xclient.message_type == dpyinfo->Xatom_XEMBED)
4468 enum xembed_message msg = event->xclient.data.l[1];
4469 x_focus_changed ((msg == XEMBED_FOCUS_IN ? FocusIn : FocusOut),
4470 FOCUS_EXPLICIT, dpyinfo, frame, bufp);
4472 break;
4477 #if !defined USE_X_TOOLKIT && !defined USE_GTK
4478 /* Handle an event saying the mouse has moved out of an Emacs frame. */
4480 void
4481 x_mouse_leave (struct x_display_info *dpyinfo)
4483 x_new_focus_frame (dpyinfo, dpyinfo->x_focus_event_frame);
4485 #endif
4487 /* The focus has changed, or we have redirected a frame's focus to
4488 another frame (this happens when a frame uses a surrogate
4489 mini-buffer frame). Shift the highlight as appropriate.
4491 The FRAME argument doesn't necessarily have anything to do with which
4492 frame is being highlighted or un-highlighted; we only use it to find
4493 the appropriate X display info. */
4495 static void
4496 XTframe_rehighlight (struct frame *frame)
4498 x_frame_rehighlight (FRAME_DISPLAY_INFO (frame));
4501 static void
4502 x_frame_rehighlight (struct x_display_info *dpyinfo)
4504 struct frame *old_highlight = dpyinfo->x_highlight_frame;
4506 if (dpyinfo->x_focus_frame)
4508 dpyinfo->x_highlight_frame
4509 = ((FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame)))
4510 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
4511 : dpyinfo->x_focus_frame);
4512 if (! FRAME_LIVE_P (dpyinfo->x_highlight_frame))
4514 fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
4515 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
4518 else
4519 dpyinfo->x_highlight_frame = 0;
4521 if (dpyinfo->x_highlight_frame != old_highlight)
4523 if (old_highlight)
4524 frame_unhighlight (old_highlight);
4525 if (dpyinfo->x_highlight_frame)
4526 frame_highlight (dpyinfo->x_highlight_frame);
4532 /* Keyboard processing - modifier keys, vendor-specific keysyms, etc. */
4534 /* Initialize mode_switch_bit and modifier_meaning. */
4535 static void
4536 x_find_modifier_meanings (struct x_display_info *dpyinfo)
4538 int min_code, max_code;
4539 KeySym *syms;
4540 int syms_per_code;
4541 XModifierKeymap *mods;
4543 dpyinfo->meta_mod_mask = 0;
4544 dpyinfo->shift_lock_mask = 0;
4545 dpyinfo->alt_mod_mask = 0;
4546 dpyinfo->super_mod_mask = 0;
4547 dpyinfo->hyper_mod_mask = 0;
4549 XDisplayKeycodes (dpyinfo->display, &min_code, &max_code);
4551 syms = XGetKeyboardMapping (dpyinfo->display,
4552 min_code, max_code - min_code + 1,
4553 &syms_per_code);
4554 mods = XGetModifierMapping (dpyinfo->display);
4556 /* Scan the modifier table to see which modifier bits the Meta and
4557 Alt keysyms are on. */
4559 int row, col; /* The row and column in the modifier table. */
4560 bool found_alt_or_meta;
4562 for (row = 3; row < 8; row++)
4564 found_alt_or_meta = false;
4565 for (col = 0; col < mods->max_keypermod; col++)
4567 KeyCode code = mods->modifiermap[(row * mods->max_keypermod) + col];
4569 /* Zeroes are used for filler. Skip them. */
4570 if (code == 0)
4571 continue;
4573 /* Are any of this keycode's keysyms a meta key? */
4575 int code_col;
4577 for (code_col = 0; code_col < syms_per_code; code_col++)
4579 int sym = syms[((code - min_code) * syms_per_code) + code_col];
4581 switch (sym)
4583 case XK_Meta_L:
4584 case XK_Meta_R:
4585 found_alt_or_meta = true;
4586 dpyinfo->meta_mod_mask |= (1 << row);
4587 break;
4589 case XK_Alt_L:
4590 case XK_Alt_R:
4591 found_alt_or_meta = true;
4592 dpyinfo->alt_mod_mask |= (1 << row);
4593 break;
4595 case XK_Hyper_L:
4596 case XK_Hyper_R:
4597 if (!found_alt_or_meta)
4598 dpyinfo->hyper_mod_mask |= (1 << row);
4599 code_col = syms_per_code;
4600 col = mods->max_keypermod;
4601 break;
4603 case XK_Super_L:
4604 case XK_Super_R:
4605 if (!found_alt_or_meta)
4606 dpyinfo->super_mod_mask |= (1 << row);
4607 code_col = syms_per_code;
4608 col = mods->max_keypermod;
4609 break;
4611 case XK_Shift_Lock:
4612 /* Ignore this if it's not on the lock modifier. */
4613 if (!found_alt_or_meta && ((1 << row) == LockMask))
4614 dpyinfo->shift_lock_mask = LockMask;
4615 code_col = syms_per_code;
4616 col = mods->max_keypermod;
4617 break;
4625 /* If we couldn't find any meta keys, accept any alt keys as meta keys. */
4626 if (! dpyinfo->meta_mod_mask)
4628 dpyinfo->meta_mod_mask = dpyinfo->alt_mod_mask;
4629 dpyinfo->alt_mod_mask = 0;
4632 /* If some keys are both alt and meta,
4633 make them just meta, not alt. */
4634 if (dpyinfo->alt_mod_mask & dpyinfo->meta_mod_mask)
4636 dpyinfo->alt_mod_mask &= ~dpyinfo->meta_mod_mask;
4639 XFree (syms);
4640 XFreeModifiermap (mods);
4643 /* Convert between the modifier bits X uses and the modifier bits
4644 Emacs uses. */
4647 x_x_to_emacs_modifiers (struct x_display_info *dpyinfo, int state)
4649 int mod_meta = meta_modifier;
4650 int mod_alt = alt_modifier;
4651 int mod_hyper = hyper_modifier;
4652 int mod_super = super_modifier;
4653 Lisp_Object tem;
4655 tem = Fget (Vx_alt_keysym, Qmodifier_value);
4656 if (INTEGERP (tem)) mod_alt = XINT (tem) & INT_MAX;
4657 tem = Fget (Vx_meta_keysym, Qmodifier_value);
4658 if (INTEGERP (tem)) mod_meta = XINT (tem) & INT_MAX;
4659 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
4660 if (INTEGERP (tem)) mod_hyper = XINT (tem) & INT_MAX;
4661 tem = Fget (Vx_super_keysym, Qmodifier_value);
4662 if (INTEGERP (tem)) mod_super = XINT (tem) & INT_MAX;
4664 return ( ((state & (ShiftMask | dpyinfo->shift_lock_mask)) ? shift_modifier : 0)
4665 | ((state & ControlMask) ? ctrl_modifier : 0)
4666 | ((state & dpyinfo->meta_mod_mask) ? mod_meta : 0)
4667 | ((state & dpyinfo->alt_mod_mask) ? mod_alt : 0)
4668 | ((state & dpyinfo->super_mod_mask) ? mod_super : 0)
4669 | ((state & dpyinfo->hyper_mod_mask) ? mod_hyper : 0));
4672 static int
4673 x_emacs_to_x_modifiers (struct x_display_info *dpyinfo, EMACS_INT state)
4675 EMACS_INT mod_meta = meta_modifier;
4676 EMACS_INT mod_alt = alt_modifier;
4677 EMACS_INT mod_hyper = hyper_modifier;
4678 EMACS_INT mod_super = super_modifier;
4680 Lisp_Object tem;
4682 tem = Fget (Vx_alt_keysym, Qmodifier_value);
4683 if (INTEGERP (tem)) mod_alt = XINT (tem);
4684 tem = Fget (Vx_meta_keysym, Qmodifier_value);
4685 if (INTEGERP (tem)) mod_meta = XINT (tem);
4686 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
4687 if (INTEGERP (tem)) mod_hyper = XINT (tem);
4688 tem = Fget (Vx_super_keysym, Qmodifier_value);
4689 if (INTEGERP (tem)) mod_super = XINT (tem);
4692 return ( ((state & mod_alt) ? dpyinfo->alt_mod_mask : 0)
4693 | ((state & mod_super) ? dpyinfo->super_mod_mask : 0)
4694 | ((state & mod_hyper) ? dpyinfo->hyper_mod_mask : 0)
4695 | ((state & shift_modifier) ? ShiftMask : 0)
4696 | ((state & ctrl_modifier) ? ControlMask : 0)
4697 | ((state & mod_meta) ? dpyinfo->meta_mod_mask : 0));
4700 /* Convert a keysym to its name. */
4702 char *
4703 x_get_keysym_name (int keysym)
4705 char *value;
4707 block_input ();
4708 value = XKeysymToString (keysym);
4709 unblock_input ();
4711 return value;
4714 /* Mouse clicks and mouse movement. Rah.
4716 Formerly, we used PointerMotionHintMask (in standard_event_mask)
4717 so that we would have to call XQueryPointer after each MotionNotify
4718 event to ask for another such event. However, this made mouse tracking
4719 slow, and there was a bug that made it eventually stop.
4721 Simply asking for MotionNotify all the time seems to work better.
4723 In order to avoid asking for motion events and then throwing most
4724 of them away or busy-polling the server for mouse positions, we ask
4725 the server for pointer motion hints. This means that we get only
4726 one event per group of mouse movements. "Groups" are delimited by
4727 other kinds of events (focus changes and button clicks, for
4728 example), or by XQueryPointer calls; when one of these happens, we
4729 get another MotionNotify event the next time the mouse moves. This
4730 is at least as efficient as getting motion events when mouse
4731 tracking is on, and I suspect only negligibly worse when tracking
4732 is off. */
4734 /* Prepare a mouse-event in *RESULT for placement in the input queue.
4736 If the event is a button press, then note that we have grabbed
4737 the mouse. */
4739 static Lisp_Object
4740 construct_mouse_click (struct input_event *result,
4741 const XButtonEvent *event,
4742 struct frame *f)
4744 /* Make the event type NO_EVENT; we'll change that when we decide
4745 otherwise. */
4746 result->kind = MOUSE_CLICK_EVENT;
4747 result->code = event->button - Button1;
4748 result->timestamp = event->time;
4749 result->modifiers = (x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO (f),
4750 event->state)
4751 | (event->type == ButtonRelease
4752 ? up_modifier
4753 : down_modifier));
4755 XSETINT (result->x, event->x);
4756 XSETINT (result->y, event->y);
4757 XSETFRAME (result->frame_or_window, f);
4758 result->arg = Qnil;
4759 return Qnil;
4762 /* Function to report a mouse movement to the mainstream Emacs code.
4763 The input handler calls this.
4765 We have received a mouse movement event, which is given in *event.
4766 If the mouse is over a different glyph than it was last time, tell
4767 the mainstream emacs code by setting mouse_moved. If not, ask for
4768 another motion event, so we can check again the next time it moves. */
4770 static bool
4771 note_mouse_movement (struct frame *frame, const XMotionEvent *event)
4773 XRectangle *r;
4774 struct x_display_info *dpyinfo;
4776 if (!FRAME_X_OUTPUT (frame))
4777 return false;
4779 dpyinfo = FRAME_DISPLAY_INFO (frame);
4780 dpyinfo->last_mouse_movement_time = event->time;
4781 dpyinfo->last_mouse_motion_frame = frame;
4782 dpyinfo->last_mouse_motion_x = event->x;
4783 dpyinfo->last_mouse_motion_y = event->y;
4785 if (event->window != FRAME_X_WINDOW (frame))
4787 frame->mouse_moved = true;
4788 dpyinfo->last_mouse_scroll_bar = NULL;
4789 note_mouse_highlight (frame, -1, -1);
4790 dpyinfo->last_mouse_glyph_frame = NULL;
4791 return true;
4795 /* Has the mouse moved off the glyph it was on at the last sighting? */
4796 r = &dpyinfo->last_mouse_glyph;
4797 if (frame != dpyinfo->last_mouse_glyph_frame
4798 || event->x < r->x || event->x >= r->x + r->width
4799 || event->y < r->y || event->y >= r->y + r->height)
4801 frame->mouse_moved = true;
4802 dpyinfo->last_mouse_scroll_bar = NULL;
4803 note_mouse_highlight (frame, event->x, event->y);
4804 /* Remember which glyph we're now on. */
4805 remember_mouse_glyph (frame, event->x, event->y, r);
4806 dpyinfo->last_mouse_glyph_frame = frame;
4807 return true;
4810 return false;
4813 /* Return the current position of the mouse.
4814 *FP should be a frame which indicates which display to ask about.
4816 If the mouse movement started in a scroll bar, set *FP, *BAR_WINDOW,
4817 and *PART to the frame, window, and scroll bar part that the mouse
4818 is over. Set *X and *Y to the portion and whole of the mouse's
4819 position on the scroll bar.
4821 If the mouse movement started elsewhere, set *FP to the frame the
4822 mouse is on, *BAR_WINDOW to nil, and *X and *Y to the character cell
4823 the mouse is over.
4825 Set *TIMESTAMP to the server time-stamp for the time at which the mouse
4826 was at this position.
4828 Don't store anything if we don't have a valid set of values to report.
4830 This clears the mouse_moved flag, so we can wait for the next mouse
4831 movement. */
4833 static void
4834 XTmouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
4835 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
4836 Time *timestamp)
4838 struct frame *f1;
4839 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (*fp);
4841 block_input ();
4843 if (dpyinfo->last_mouse_scroll_bar && insist == 0)
4845 struct scroll_bar *bar = dpyinfo->last_mouse_scroll_bar;
4847 if (bar->horizontal)
4848 x_horizontal_scroll_bar_report_motion (fp, bar_window, part, x, y, timestamp);
4849 else
4850 x_scroll_bar_report_motion (fp, bar_window, part, x, y, timestamp);
4852 else
4854 Window root;
4855 int root_x, root_y;
4857 Window dummy_window;
4858 int dummy;
4860 Lisp_Object frame, tail;
4862 /* Clear the mouse-moved flag for every frame on this display. */
4863 FOR_EACH_FRAME (tail, frame)
4864 if (FRAME_X_P (XFRAME (frame))
4865 && FRAME_X_DISPLAY (XFRAME (frame)) == FRAME_X_DISPLAY (*fp))
4866 XFRAME (frame)->mouse_moved = false;
4868 dpyinfo->last_mouse_scroll_bar = NULL;
4870 /* Figure out which root window we're on. */
4871 XQueryPointer (FRAME_X_DISPLAY (*fp),
4872 DefaultRootWindow (FRAME_X_DISPLAY (*fp)),
4874 /* The root window which contains the pointer. */
4875 &root,
4877 /* Trash which we can't trust if the pointer is on
4878 a different screen. */
4879 &dummy_window,
4881 /* The position on that root window. */
4882 &root_x, &root_y,
4884 /* More trash we can't trust. */
4885 &dummy, &dummy,
4887 /* Modifier keys and pointer buttons, about which
4888 we don't care. */
4889 (unsigned int *) &dummy);
4891 /* Now we have a position on the root; find the innermost window
4892 containing the pointer. */
4894 Window win, child;
4895 int win_x, win_y;
4896 int parent_x = 0, parent_y = 0;
4898 win = root;
4900 /* XTranslateCoordinates can get errors if the window
4901 structure is changing at the same time this function
4902 is running. So at least we must not crash from them. */
4904 x_catch_errors (FRAME_X_DISPLAY (*fp));
4906 if (x_mouse_grabbed (dpyinfo))
4908 /* If mouse was grabbed on a frame, give coords for that frame
4909 even if the mouse is now outside it. */
4910 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
4912 /* From-window. */
4913 root,
4915 /* To-window. */
4916 FRAME_X_WINDOW (dpyinfo->last_mouse_frame),
4918 /* From-position, to-position. */
4919 root_x, root_y, &win_x, &win_y,
4921 /* Child of win. */
4922 &child);
4923 f1 = dpyinfo->last_mouse_frame;
4925 else
4927 while (true)
4929 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
4931 /* From-window, to-window. */
4932 root, win,
4934 /* From-position, to-position. */
4935 root_x, root_y, &win_x, &win_y,
4937 /* Child of win. */
4938 &child);
4940 if (child == None || child == win)
4941 break;
4942 #ifdef USE_GTK
4943 /* We don't wan't to know the innermost window. We
4944 want the edit window. For non-Gtk+ the innermost
4945 window is the edit window. For Gtk+ it might not
4946 be. It might be the tool bar for example. */
4947 if (x_window_to_frame (dpyinfo, win))
4948 break;
4949 #endif
4950 win = child;
4951 parent_x = win_x;
4952 parent_y = win_y;
4955 /* Now we know that:
4956 win is the innermost window containing the pointer
4957 (XTC says it has no child containing the pointer),
4958 win_x and win_y are the pointer's position in it
4959 (XTC did this the last time through), and
4960 parent_x and parent_y are the pointer's position in win's parent.
4961 (They are what win_x and win_y were when win was child.
4962 If win is the root window, it has no parent, and
4963 parent_{x,y} are invalid, but that's okay, because we'll
4964 never use them in that case.) */
4966 #ifdef USE_GTK
4967 /* We don't wan't to know the innermost window. We
4968 want the edit window. */
4969 f1 = x_window_to_frame (dpyinfo, win);
4970 #else
4971 /* Is win one of our frames? */
4972 f1 = x_any_window_to_frame (dpyinfo, win);
4973 #endif
4975 #ifdef USE_X_TOOLKIT
4976 /* If we end up with the menu bar window, say it's not
4977 on the frame. */
4978 if (f1 != NULL
4979 && f1->output_data.x->menubar_widget
4980 && win == XtWindow (f1->output_data.x->menubar_widget))
4981 f1 = NULL;
4982 #endif /* USE_X_TOOLKIT */
4985 if (x_had_errors_p (FRAME_X_DISPLAY (*fp)))
4986 f1 = 0;
4988 x_uncatch_errors_after_check ();
4990 /* If not, is it one of our scroll bars? */
4991 if (! f1)
4993 struct scroll_bar *bar;
4995 bar = x_window_to_scroll_bar (FRAME_X_DISPLAY (*fp), win, 2);
4997 if (bar)
4999 f1 = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5000 win_x = parent_x;
5001 win_y = parent_y;
5005 if (f1 == 0 && insist > 0)
5006 f1 = SELECTED_FRAME ();
5008 if (f1)
5010 /* Ok, we found a frame. Store all the values.
5011 last_mouse_glyph is a rectangle used to reduce the
5012 generation of mouse events. To not miss any motion
5013 events, we must divide the frame into rectangles of the
5014 size of the smallest character that could be displayed
5015 on it, i.e. into the same rectangles that matrices on
5016 the frame are divided into. */
5018 /* FIXME: what if F1 is not an X frame? */
5019 dpyinfo = FRAME_DISPLAY_INFO (f1);
5020 remember_mouse_glyph (f1, win_x, win_y, &dpyinfo->last_mouse_glyph);
5021 dpyinfo->last_mouse_glyph_frame = f1;
5023 *bar_window = Qnil;
5024 *part = 0;
5025 *fp = f1;
5026 XSETINT (*x, win_x);
5027 XSETINT (*y, win_y);
5028 *timestamp = dpyinfo->last_mouse_movement_time;
5033 unblock_input ();
5038 /***********************************************************************
5039 Scroll bars
5040 ***********************************************************************/
5042 /* Scroll bar support. */
5044 /* Given an X window ID and a DISPLAY, find the struct scroll_bar which
5045 manages it.
5046 This can be called in GC, so we have to make sure to strip off mark
5047 bits. */
5049 static struct scroll_bar *
5050 x_window_to_scroll_bar (Display *display, Window window_id, int type)
5052 Lisp_Object tail, frame;
5054 #if defined (USE_GTK) && defined (USE_TOOLKIT_SCROLL_BARS)
5055 window_id = (Window) xg_get_scroll_id_for_window (display, window_id);
5056 #endif /* USE_GTK && USE_TOOLKIT_SCROLL_BARS */
5058 FOR_EACH_FRAME (tail, frame)
5060 Lisp_Object bar, condemned;
5062 if (! FRAME_X_P (XFRAME (frame)))
5063 continue;
5065 /* Scan this frame's scroll bar list for a scroll bar with the
5066 right window ID. */
5067 condemned = FRAME_CONDEMNED_SCROLL_BARS (XFRAME (frame));
5068 for (bar = FRAME_SCROLL_BARS (XFRAME (frame));
5069 /* This trick allows us to search both the ordinary and
5070 condemned scroll bar lists with one loop. */
5071 ! NILP (bar) || (bar = condemned,
5072 condemned = Qnil,
5073 ! NILP (bar));
5074 bar = XSCROLL_BAR (bar)->next)
5075 if (XSCROLL_BAR (bar)->x_window == window_id
5076 && FRAME_X_DISPLAY (XFRAME (frame)) == display
5077 && (type = 2
5078 || (type == 1 && XSCROLL_BAR (bar)->horizontal)
5079 || (type == 0 && !XSCROLL_BAR (bar)->horizontal)))
5080 return XSCROLL_BAR (bar);
5083 return NULL;
5087 #if defined USE_LUCID
5089 /* Return the Lucid menu bar WINDOW is part of. Return null
5090 if WINDOW is not part of a menu bar. */
5092 static Widget
5093 x_window_to_menu_bar (Window window)
5095 Lisp_Object tail, frame;
5097 FOR_EACH_FRAME (tail, frame)
5098 if (FRAME_X_P (XFRAME (frame)))
5100 Widget menu_bar = XFRAME (frame)->output_data.x->menubar_widget;
5102 if (menu_bar && xlwmenu_window_p (menu_bar, window))
5103 return menu_bar;
5105 return NULL;
5108 #endif /* USE_LUCID */
5111 /************************************************************************
5112 Toolkit scroll bars
5113 ************************************************************************/
5115 #ifdef USE_TOOLKIT_SCROLL_BARS
5117 static void x_send_scroll_bar_event (Lisp_Object, enum scroll_bar_part,
5118 int, int, bool);
5120 /* Lisp window being scrolled. Set when starting to interact with
5121 a toolkit scroll bar, reset to nil when ending the interaction. */
5123 static Lisp_Object window_being_scrolled;
5125 /* Whether this is an Xaw with arrow-scrollbars. This should imply
5126 that movements of 1/20 of the screen size are mapped to up/down. */
5128 #ifndef USE_GTK
5129 /* Id of action hook installed for scroll bars. */
5131 static XtActionHookId action_hook_id;
5132 static XtActionHookId horizontal_action_hook_id;
5134 static Boolean xaw3d_arrow_scroll;
5136 /* Whether the drag scrolling maintains the mouse at the top of the
5137 thumb. If not, resizing the thumb needs to be done more carefully
5138 to avoid jerkiness. */
5140 static Boolean xaw3d_pick_top;
5142 /* Action hook installed via XtAppAddActionHook when toolkit scroll
5143 bars are used.. The hook is responsible for detecting when
5144 the user ends an interaction with the scroll bar, and generates
5145 a `end-scroll' SCROLL_BAR_CLICK_EVENT' event if so. */
5147 static void
5148 xt_action_hook (Widget widget, XtPointer client_data, String action_name,
5149 XEvent *event, String *params, Cardinal *num_params)
5151 bool scroll_bar_p;
5152 const char *end_action;
5154 #ifdef USE_MOTIF
5155 scroll_bar_p = XmIsScrollBar (widget);
5156 end_action = "Release";
5157 #else /* !USE_MOTIF i.e. use Xaw */
5158 scroll_bar_p = XtIsSubclass (widget, scrollbarWidgetClass);
5159 end_action = "EndScroll";
5160 #endif /* USE_MOTIF */
5162 if (scroll_bar_p
5163 && strcmp (action_name, end_action) == 0
5164 && WINDOWP (window_being_scrolled))
5166 struct window *w;
5167 struct scroll_bar *bar;
5169 x_send_scroll_bar_event (window_being_scrolled,
5170 scroll_bar_end_scroll, 0, 0, false);
5171 w = XWINDOW (window_being_scrolled);
5172 bar = XSCROLL_BAR (w->vertical_scroll_bar);
5174 if (bar->dragging != -1)
5176 bar->dragging = -1;
5177 /* The thumb size is incorrect while dragging: fix it. */
5178 set_vertical_scroll_bar (w);
5180 window_being_scrolled = Qnil;
5181 #if defined (USE_LUCID)
5182 bar->last_seen_part = scroll_bar_nowhere;
5183 #endif
5184 /* Xt timeouts no longer needed. */
5185 toolkit_scroll_bar_interaction = false;
5190 static void
5191 xt_horizontal_action_hook (Widget widget, XtPointer client_data, String action_name,
5192 XEvent *event, String *params, Cardinal *num_params)
5194 bool scroll_bar_p;
5195 const char *end_action;
5197 #ifdef USE_MOTIF
5198 scroll_bar_p = XmIsScrollBar (widget);
5199 end_action = "Release";
5200 #else /* !USE_MOTIF i.e. use Xaw */
5201 scroll_bar_p = XtIsSubclass (widget, scrollbarWidgetClass);
5202 end_action = "EndScroll";
5203 #endif /* USE_MOTIF */
5205 if (scroll_bar_p
5206 && strcmp (action_name, end_action) == 0
5207 && WINDOWP (window_being_scrolled))
5209 struct window *w;
5210 struct scroll_bar *bar;
5212 x_send_scroll_bar_event (window_being_scrolled,
5213 scroll_bar_end_scroll, 0, 0, true);
5214 w = XWINDOW (window_being_scrolled);
5215 bar = XSCROLL_BAR (w->horizontal_scroll_bar);
5217 if (bar->dragging != -1)
5219 bar->dragging = -1;
5220 /* The thumb size is incorrect while dragging: fix it. */
5221 set_horizontal_scroll_bar (w);
5223 window_being_scrolled = Qnil;
5224 #if defined (USE_LUCID)
5225 bar->last_seen_part = scroll_bar_nowhere;
5226 #endif
5227 /* Xt timeouts no longer needed. */
5228 toolkit_scroll_bar_interaction = false;
5231 #endif /* not USE_GTK */
5233 /* Send a client message with message type Xatom_Scrollbar for a
5234 scroll action to the frame of WINDOW. PART is a value identifying
5235 the part of the scroll bar that was clicked on. PORTION is the
5236 amount to scroll of a whole of WHOLE. */
5238 static void
5239 x_send_scroll_bar_event (Lisp_Object window, enum scroll_bar_part part,
5240 int portion, int whole, bool horizontal)
5242 XEvent event;
5243 XClientMessageEvent *ev = &event.xclient;
5244 struct window *w = XWINDOW (window);
5245 struct frame *f = XFRAME (w->frame);
5246 intptr_t iw = (intptr_t) w;
5247 enum { BITS_PER_INTPTR = CHAR_BIT * sizeof iw };
5248 verify (BITS_PER_INTPTR <= 64);
5249 int sign_shift = BITS_PER_INTPTR - 32;
5251 block_input ();
5253 /* Construct a ClientMessage event to send to the frame. */
5254 ev->type = ClientMessage;
5255 ev->message_type = (horizontal
5256 ? FRAME_DISPLAY_INFO (f)->Xatom_Horizontal_Scrollbar
5257 : FRAME_DISPLAY_INFO (f)->Xatom_Scrollbar);
5258 ev->display = FRAME_X_DISPLAY (f);
5259 ev->window = FRAME_X_WINDOW (f);
5260 ev->format = 32;
5262 /* A 32-bit X client on a 64-bit X server can pass a window pointer
5263 as-is. A 64-bit client on a 32-bit X server is in trouble
5264 because a pointer does not fit and would be truncated while
5265 passing through the server. So use two slots and hope that X12
5266 will resolve such issues someday. */
5267 ev->data.l[0] = iw >> 31 >> 1;
5268 ev->data.l[1] = sign_shift <= 0 ? iw : iw << sign_shift >> sign_shift;
5269 ev->data.l[2] = part;
5270 ev->data.l[3] = portion;
5271 ev->data.l[4] = whole;
5273 /* Make Xt timeouts work while the scroll bar is active. */
5274 #ifdef USE_X_TOOLKIT
5275 toolkit_scroll_bar_interaction = true;
5276 x_activate_timeout_atimer ();
5277 #endif
5279 /* Setting the event mask to zero means that the message will
5280 be sent to the client that created the window, and if that
5281 window no longer exists, no event will be sent. */
5282 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), False, 0, &event);
5283 unblock_input ();
5287 /* Transform a scroll bar ClientMessage EVENT to an Emacs input event
5288 in *IEVENT. */
5290 static void
5291 x_scroll_bar_to_input_event (const XEvent *event,
5292 struct input_event *ievent)
5294 const XClientMessageEvent *ev = &event->xclient;
5295 Lisp_Object window;
5296 struct window *w;
5298 /* See the comment in the function above. */
5299 intptr_t iw0 = ev->data.l[0];
5300 intptr_t iw1 = ev->data.l[1];
5301 intptr_t iw = (iw0 << 31 << 1) + (iw1 & 0xffffffffu);
5302 w = (struct window *) iw;
5304 XSETWINDOW (window, w);
5306 ievent->kind = SCROLL_BAR_CLICK_EVENT;
5307 ievent->frame_or_window = window;
5308 ievent->arg = Qnil;
5309 #ifdef USE_GTK
5310 ievent->timestamp = CurrentTime;
5311 #else
5312 ievent->timestamp =
5313 XtLastTimestampProcessed (FRAME_X_DISPLAY (XFRAME (w->frame)));
5314 #endif
5315 ievent->code = 0;
5316 ievent->part = ev->data.l[2];
5317 ievent->x = make_number (ev->data.l[3]);
5318 ievent->y = make_number (ev->data.l[4]);
5319 ievent->modifiers = 0;
5322 /* Transform a horizontal scroll bar ClientMessage EVENT to an Emacs
5323 input event in *IEVENT. */
5325 static void
5326 x_horizontal_scroll_bar_to_input_event (const XEvent *event,
5327 struct input_event *ievent)
5329 const XClientMessageEvent *ev = &event->xclient;
5330 Lisp_Object window;
5331 struct window *w;
5333 /* See the comment in the function above. */
5334 intptr_t iw0 = ev->data.l[0];
5335 intptr_t iw1 = ev->data.l[1];
5336 intptr_t iw = (iw0 << 31 << 1) + (iw1 & 0xffffffffu);
5337 w = (struct window *) iw;
5339 XSETWINDOW (window, w);
5341 ievent->kind = HORIZONTAL_SCROLL_BAR_CLICK_EVENT;
5342 ievent->frame_or_window = window;
5343 ievent->arg = Qnil;
5344 #ifdef USE_GTK
5345 ievent->timestamp = CurrentTime;
5346 #else
5347 ievent->timestamp =
5348 XtLastTimestampProcessed (FRAME_X_DISPLAY (XFRAME (w->frame)));
5349 #endif
5350 ievent->code = 0;
5351 ievent->part = ev->data.l[2];
5352 ievent->x = make_number (ev->data.l[3]);
5353 ievent->y = make_number (ev->data.l[4]);
5354 ievent->modifiers = 0;
5358 #ifdef USE_MOTIF
5360 /* Minimum and maximum values used for Motif scroll bars. */
5362 #define XM_SB_MAX 10000000
5364 /* Scroll bar callback for Motif scroll bars. WIDGET is the scroll
5365 bar widget. CLIENT_DATA is a pointer to the scroll_bar structure.
5366 CALL_DATA is a pointer to a XmScrollBarCallbackStruct. */
5368 static void
5369 xm_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
5371 struct scroll_bar *bar = client_data;
5372 XmScrollBarCallbackStruct *cs = call_data;
5373 enum scroll_bar_part part = scroll_bar_nowhere;
5374 bool horizontal = bar->horizontal;
5375 int whole = 0, portion = 0;
5377 switch (cs->reason)
5379 case XmCR_DECREMENT:
5380 bar->dragging = -1;
5381 part = horizontal ? scroll_bar_left_arrow : scroll_bar_up_arrow;
5382 break;
5384 case XmCR_INCREMENT:
5385 bar->dragging = -1;
5386 part = horizontal ? scroll_bar_right_arrow : scroll_bar_down_arrow;
5387 break;
5389 case XmCR_PAGE_DECREMENT:
5390 bar->dragging = -1;
5391 part = horizontal ? scroll_bar_before_handle : scroll_bar_above_handle;
5392 break;
5394 case XmCR_PAGE_INCREMENT:
5395 bar->dragging = -1;
5396 part = horizontal ? scroll_bar_after_handle : scroll_bar_below_handle;
5397 break;
5399 case XmCR_TO_TOP:
5400 bar->dragging = -1;
5401 part = horizontal ? scroll_bar_to_leftmost : scroll_bar_to_top;
5402 break;
5404 case XmCR_TO_BOTTOM:
5405 bar->dragging = -1;
5406 part = horizontal ? scroll_bar_to_rightmost : scroll_bar_to_bottom;
5407 break;
5409 case XmCR_DRAG:
5411 int slider_size;
5413 block_input ();
5414 XtVaGetValues (widget, XmNsliderSize, &slider_size, NULL);
5415 unblock_input ();
5417 if (horizontal)
5419 portion = bar->whole * ((float)cs->value / XM_SB_MAX);
5420 whole = bar->whole * ((float)(XM_SB_MAX - slider_size) / XM_SB_MAX);
5421 portion = min (portion, whole);
5422 part = scroll_bar_horizontal_handle;
5424 else
5426 whole = XM_SB_MAX - slider_size;
5427 portion = min (cs->value, whole);
5428 part = scroll_bar_handle;
5431 bar->dragging = cs->value;
5433 break;
5435 case XmCR_VALUE_CHANGED:
5436 break;
5439 if (part != scroll_bar_nowhere)
5441 window_being_scrolled = bar->window;
5442 x_send_scroll_bar_event (bar->window, part, portion, whole,
5443 bar->horizontal);
5447 #elif defined USE_GTK
5449 /* Scroll bar callback for GTK scroll bars. WIDGET is the scroll
5450 bar widget. DATA is a pointer to the scroll_bar structure. */
5452 static gboolean
5453 xg_scroll_callback (GtkRange *range,
5454 GtkScrollType scroll,
5455 gdouble value,
5456 gpointer user_data)
5458 int whole = 0, portion = 0;
5459 struct scroll_bar *bar = user_data;
5460 enum scroll_bar_part part = scroll_bar_nowhere;
5461 GtkAdjustment *adj = GTK_ADJUSTMENT (gtk_range_get_adjustment (range));
5462 struct frame *f = g_object_get_data (G_OBJECT (range), XG_FRAME_DATA);
5464 if (xg_ignore_gtk_scrollbar) return false;
5466 switch (scroll)
5468 case GTK_SCROLL_JUMP:
5469 /* Buttons 1 2 or 3 must be grabbed. */
5470 if (FRAME_DISPLAY_INFO (f)->grabbed != 0
5471 && FRAME_DISPLAY_INFO (f)->grabbed < (1 << 4))
5473 if (bar->horizontal)
5475 part = scroll_bar_horizontal_handle;
5476 whole = (int)(gtk_adjustment_get_upper (adj) -
5477 gtk_adjustment_get_page_size (adj));
5478 portion = min ((int)value, whole);
5479 bar->dragging = portion;
5481 else
5483 part = scroll_bar_handle;
5484 whole = gtk_adjustment_get_upper (adj) -
5485 gtk_adjustment_get_page_size (adj);
5486 portion = min ((int)value, whole);
5487 bar->dragging = portion;
5490 break;
5491 case GTK_SCROLL_STEP_BACKWARD:
5492 part = (bar->horizontal
5493 ? scroll_bar_left_arrow : scroll_bar_up_arrow);
5494 bar->dragging = -1;
5495 break;
5496 case GTK_SCROLL_STEP_FORWARD:
5497 part = (bar->horizontal
5498 ? scroll_bar_right_arrow : scroll_bar_down_arrow);
5499 bar->dragging = -1;
5500 break;
5501 case GTK_SCROLL_PAGE_BACKWARD:
5502 part = (bar->horizontal
5503 ? scroll_bar_before_handle : scroll_bar_above_handle);
5504 bar->dragging = -1;
5505 break;
5506 case GTK_SCROLL_PAGE_FORWARD:
5507 part = (bar->horizontal
5508 ? scroll_bar_after_handle : scroll_bar_below_handle);
5509 bar->dragging = -1;
5510 break;
5511 default:
5512 break;
5515 if (part != scroll_bar_nowhere)
5517 window_being_scrolled = bar->window;
5518 x_send_scroll_bar_event (bar->window, part, portion, whole,
5519 bar->horizontal);
5522 return false;
5525 /* Callback for button release. Sets dragging to -1 when dragging is done. */
5527 static gboolean
5528 xg_end_scroll_callback (GtkWidget *widget,
5529 GdkEventButton *event,
5530 gpointer user_data)
5532 struct scroll_bar *bar = user_data;
5533 bar->dragging = -1;
5534 if (WINDOWP (window_being_scrolled))
5536 x_send_scroll_bar_event (window_being_scrolled,
5537 scroll_bar_end_scroll, 0, 0, bar->horizontal);
5538 window_being_scrolled = Qnil;
5541 return false;
5545 #else /* not USE_GTK and not USE_MOTIF */
5547 /* Xaw scroll bar callback. Invoked when the thumb is dragged.
5548 WIDGET is the scroll bar widget. CLIENT_DATA is a pointer to the
5549 scroll bar struct. CALL_DATA is a pointer to a float saying where
5550 the thumb is. */
5552 static void
5553 xaw_jump_callback (Widget widget, XtPointer client_data, XtPointer call_data)
5555 struct scroll_bar *bar = client_data;
5556 float *top_addr = call_data;
5557 float top = *top_addr;
5558 float shown;
5559 int whole, portion, height, width;
5560 enum scroll_bar_part part;
5561 bool horizontal = bar->horizontal;
5564 if (horizontal)
5566 /* Get the size of the thumb, a value between 0 and 1. */
5567 block_input ();
5568 XtVaGetValues (widget, XtNshown, &shown, XtNwidth, &width, NULL);
5569 unblock_input ();
5571 if (shown < 1)
5573 whole = bar->whole - (shown * bar->whole);
5574 portion = min (top * bar->whole, whole);
5576 else
5578 whole = bar->whole;
5579 portion = 0;
5582 part = scroll_bar_horizontal_handle;
5584 else
5586 /* Get the size of the thumb, a value between 0 and 1. */
5587 block_input ();
5588 XtVaGetValues (widget, XtNshown, &shown, XtNheight, &height, NULL);
5589 unblock_input ();
5591 whole = 10000000;
5592 portion = shown < 1 ? top * whole : 0;
5594 if (shown < 1 && (eabs (top + shown - 1) < 1.0f / height))
5595 /* Some derivatives of Xaw refuse to shrink the thumb when you reach
5596 the bottom, so we force the scrolling whenever we see that we're
5597 too close to the bottom (in x_set_toolkit_scroll_bar_thumb
5598 we try to ensure that we always stay two pixels away from the
5599 bottom). */
5600 part = scroll_bar_down_arrow;
5601 else
5602 part = scroll_bar_handle;
5605 window_being_scrolled = bar->window;
5606 bar->dragging = portion;
5607 bar->last_seen_part = part;
5608 x_send_scroll_bar_event (bar->window, part, portion, whole, bar->horizontal);
5612 /* Xaw scroll bar callback. Invoked for incremental scrolling.,
5613 i.e. line or page up or down. WIDGET is the Xaw scroll bar
5614 widget. CLIENT_DATA is a pointer to the scroll_bar structure for
5615 the scroll bar. CALL_DATA is an integer specifying the action that
5616 has taken place. Its magnitude is in the range 0..height of the
5617 scroll bar. Negative values mean scroll towards buffer start.
5618 Values < height of scroll bar mean line-wise movement. */
5620 static void
5621 xaw_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
5623 struct scroll_bar *bar = client_data;
5624 /* The position really is stored cast to a pointer. */
5625 int position = (intptr_t) call_data;
5626 Dimension height, width;
5627 enum scroll_bar_part part;
5629 if (bar->horizontal)
5631 /* Get the width of the scroll bar. */
5632 block_input ();
5633 XtVaGetValues (widget, XtNwidth, &width, NULL);
5634 unblock_input ();
5636 if (eabs (position) >= width)
5637 part = (position < 0) ? scroll_bar_before_handle : scroll_bar_after_handle;
5639 /* If Xaw3d was compiled with ARROW_SCROLLBAR,
5640 it maps line-movement to call_data = max(5, height/20). */
5641 else if (xaw3d_arrow_scroll && eabs (position) <= max (5, width / 20))
5642 part = (position < 0) ? scroll_bar_left_arrow : scroll_bar_right_arrow;
5643 else
5644 part = scroll_bar_move_ratio;
5646 window_being_scrolled = bar->window;
5647 bar->dragging = -1;
5648 bar->last_seen_part = part;
5649 x_send_scroll_bar_event (bar->window, part, position, width,
5650 bar->horizontal);
5652 else
5655 /* Get the height of the scroll bar. */
5656 block_input ();
5657 XtVaGetValues (widget, XtNheight, &height, NULL);
5658 unblock_input ();
5660 if (eabs (position) >= height)
5661 part = (position < 0) ? scroll_bar_above_handle : scroll_bar_below_handle;
5663 /* If Xaw3d was compiled with ARROW_SCROLLBAR,
5664 it maps line-movement to call_data = max(5, height/20). */
5665 else if (xaw3d_arrow_scroll && eabs (position) <= max (5, height / 20))
5666 part = (position < 0) ? scroll_bar_up_arrow : scroll_bar_down_arrow;
5667 else
5668 part = scroll_bar_move_ratio;
5670 window_being_scrolled = bar->window;
5671 bar->dragging = -1;
5672 bar->last_seen_part = part;
5673 x_send_scroll_bar_event (bar->window, part, position, height,
5674 bar->horizontal);
5678 #endif /* not USE_GTK and not USE_MOTIF */
5680 #define SCROLL_BAR_NAME "verticalScrollBar"
5681 #define SCROLL_BAR_HORIZONTAL_NAME "horizontalScrollBar"
5683 /* Create the widget for scroll bar BAR on frame F. Record the widget
5684 and X window of the scroll bar in BAR. */
5686 #ifdef USE_GTK
5687 static void
5688 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
5690 const char *scroll_bar_name = SCROLL_BAR_NAME;
5692 block_input ();
5693 xg_create_scroll_bar (f, bar, G_CALLBACK (xg_scroll_callback),
5694 G_CALLBACK (xg_end_scroll_callback),
5695 scroll_bar_name);
5696 unblock_input ();
5699 static void
5700 x_create_horizontal_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
5702 const char *scroll_bar_name = SCROLL_BAR_HORIZONTAL_NAME;
5704 block_input ();
5705 xg_create_horizontal_scroll_bar (f, bar, G_CALLBACK (xg_scroll_callback),
5706 G_CALLBACK (xg_end_scroll_callback),
5707 scroll_bar_name);
5708 unblock_input ();
5711 #else /* not USE_GTK */
5713 static void
5714 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
5716 Window xwindow;
5717 Widget widget;
5718 Arg av[20];
5719 int ac = 0;
5720 const char *scroll_bar_name = SCROLL_BAR_NAME;
5721 unsigned long pixel;
5723 block_input ();
5725 #ifdef USE_MOTIF
5726 /* Set resources. Create the widget. */
5727 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
5728 XtSetArg (av[ac], XmNminimum, 0); ++ac;
5729 XtSetArg (av[ac], XmNmaximum, XM_SB_MAX); ++ac;
5730 XtSetArg (av[ac], XmNorientation, XmVERTICAL); ++ac;
5731 XtSetArg (av[ac], XmNprocessingDirection, XmMAX_ON_BOTTOM), ++ac;
5732 XtSetArg (av[ac], XmNincrement, 1); ++ac;
5733 XtSetArg (av[ac], XmNpageIncrement, 1); ++ac;
5735 pixel = f->output_data.x->scroll_bar_foreground_pixel;
5736 if (pixel != -1)
5738 XtSetArg (av[ac], XmNforeground, pixel);
5739 ++ac;
5742 pixel = f->output_data.x->scroll_bar_background_pixel;
5743 if (pixel != -1)
5745 XtSetArg (av[ac], XmNbackground, pixel);
5746 ++ac;
5749 widget = XmCreateScrollBar (f->output_data.x->edit_widget,
5750 (char *) scroll_bar_name, av, ac);
5752 /* Add one callback for everything that can happen. */
5753 XtAddCallback (widget, XmNdecrementCallback, xm_scroll_callback,
5754 (XtPointer) bar);
5755 XtAddCallback (widget, XmNdragCallback, xm_scroll_callback,
5756 (XtPointer) bar);
5757 XtAddCallback (widget, XmNincrementCallback, xm_scroll_callback,
5758 (XtPointer) bar);
5759 XtAddCallback (widget, XmNpageDecrementCallback, xm_scroll_callback,
5760 (XtPointer) bar);
5761 XtAddCallback (widget, XmNpageIncrementCallback, xm_scroll_callback,
5762 (XtPointer) bar);
5763 XtAddCallback (widget, XmNtoBottomCallback, xm_scroll_callback,
5764 (XtPointer) bar);
5765 XtAddCallback (widget, XmNtoTopCallback, xm_scroll_callback,
5766 (XtPointer) bar);
5768 /* Realize the widget. Only after that is the X window created. */
5769 XtRealizeWidget (widget);
5771 /* Set the cursor to an arrow. I didn't find a resource to do that.
5772 And I'm wondering why it hasn't an arrow cursor by default. */
5773 XDefineCursor (XtDisplay (widget), XtWindow (widget),
5774 f->output_data.x->nontext_cursor);
5776 #else /* !USE_MOTIF i.e. use Xaw */
5778 /* Set resources. Create the widget. The background of the
5779 Xaw3d scroll bar widget is a little bit light for my taste.
5780 We don't alter it here to let users change it according
5781 to their taste with `emacs*verticalScrollBar.background: xxx'. */
5782 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
5783 XtSetArg (av[ac], XtNorientation, XtorientVertical); ++ac;
5784 /* For smoother scrolling with Xaw3d -sm */
5785 /* XtSetArg (av[ac], XtNpickTop, True); ++ac; */
5787 pixel = f->output_data.x->scroll_bar_foreground_pixel;
5788 if (pixel != -1)
5790 XtSetArg (av[ac], XtNforeground, pixel);
5791 ++ac;
5794 pixel = f->output_data.x->scroll_bar_background_pixel;
5795 if (pixel != -1)
5797 XtSetArg (av[ac], XtNbackground, pixel);
5798 ++ac;
5801 /* Top/bottom shadow colors. */
5803 /* Allocate them, if necessary. */
5804 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1)
5806 pixel = f->output_data.x->scroll_bar_background_pixel;
5807 if (pixel != -1)
5809 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
5810 FRAME_X_COLORMAP (f),
5811 &pixel, 1.2, 0x8000))
5812 pixel = -1;
5813 f->output_data.x->scroll_bar_top_shadow_pixel = pixel;
5816 if (f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
5818 pixel = f->output_data.x->scroll_bar_background_pixel;
5819 if (pixel != -1)
5821 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
5822 FRAME_X_COLORMAP (f),
5823 &pixel, 0.6, 0x4000))
5824 pixel = -1;
5825 f->output_data.x->scroll_bar_bottom_shadow_pixel = pixel;
5829 #ifdef XtNbeNiceToColormap
5830 /* Tell the toolkit about them. */
5831 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1
5832 || f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
5833 /* We tried to allocate a color for the top/bottom shadow, and
5834 failed, so tell Xaw3d to use dithering instead. */
5835 /* But only if we have a small colormap. Xaw3d can allocate nice
5836 colors itself. */
5838 XtSetArg (av[ac], XtNbeNiceToColormap,
5839 DefaultDepthOfScreen (FRAME_X_SCREEN (f)) < 16);
5840 ++ac;
5842 else
5843 /* Tell what colors Xaw3d should use for the top/bottom shadow, to
5844 be more consistent with other emacs 3d colors, and since Xaw3d is
5845 not good at dealing with allocation failure. */
5847 /* This tells Xaw3d to use real colors instead of dithering for
5848 the shadows. */
5849 XtSetArg (av[ac], XtNbeNiceToColormap, False);
5850 ++ac;
5852 /* Specify the colors. */
5853 pixel = f->output_data.x->scroll_bar_top_shadow_pixel;
5854 if (pixel != -1)
5856 XtSetArg (av[ac], XtNtopShadowPixel, pixel);
5857 ++ac;
5859 pixel = f->output_data.x->scroll_bar_bottom_shadow_pixel;
5860 if (pixel != -1)
5862 XtSetArg (av[ac], XtNbottomShadowPixel, pixel);
5863 ++ac;
5866 #endif
5868 widget = XtCreateWidget (scroll_bar_name, scrollbarWidgetClass,
5869 f->output_data.x->edit_widget, av, ac);
5872 char const *initial = "";
5873 char const *val = initial;
5874 XtVaGetValues (widget, XtNscrollVCursor, (XtPointer) &val,
5875 #ifdef XtNarrowScrollbars
5876 XtNarrowScrollbars, (XtPointer) &xaw3d_arrow_scroll,
5877 #endif
5878 XtNpickTop, (XtPointer) &xaw3d_pick_top, NULL);
5879 if (xaw3d_arrow_scroll || val == initial)
5880 { /* ARROW_SCROLL */
5881 xaw3d_arrow_scroll = True;
5882 /* Isn't that just a personal preference ? --Stef */
5883 XtVaSetValues (widget, XtNcursorName, "top_left_arrow", NULL);
5887 /* Define callbacks. */
5888 XtAddCallback (widget, XtNjumpProc, xaw_jump_callback, (XtPointer) bar);
5889 XtAddCallback (widget, XtNscrollProc, xaw_scroll_callback,
5890 (XtPointer) bar);
5892 /* Realize the widget. Only after that is the X window created. */
5893 XtRealizeWidget (widget);
5895 #endif /* !USE_MOTIF */
5897 /* Install an action hook that lets us detect when the user
5898 finishes interacting with a scroll bar. */
5899 if (action_hook_id == 0)
5900 action_hook_id = XtAppAddActionHook (Xt_app_con, xt_action_hook, 0);
5902 /* Remember X window and widget in the scroll bar vector. */
5903 SET_SCROLL_BAR_X_WIDGET (bar, widget);
5904 xwindow = XtWindow (widget);
5905 bar->x_window = xwindow;
5906 bar->whole = 1;
5907 bar->horizontal = false;
5909 unblock_input ();
5912 static void
5913 x_create_horizontal_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
5915 Window xwindow;
5916 Widget widget;
5917 Arg av[20];
5918 int ac = 0;
5919 const char *scroll_bar_name = SCROLL_BAR_HORIZONTAL_NAME;
5920 unsigned long pixel;
5922 block_input ();
5924 #ifdef USE_MOTIF
5925 /* Set resources. Create the widget. */
5926 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
5927 XtSetArg (av[ac], XmNminimum, 0); ++ac;
5928 XtSetArg (av[ac], XmNmaximum, XM_SB_MAX); ++ac;
5929 XtSetArg (av[ac], XmNorientation, XmHORIZONTAL); ++ac;
5930 XtSetArg (av[ac], XmNprocessingDirection, XmMAX_ON_RIGHT), ++ac;
5931 XtSetArg (av[ac], XmNincrement, 1); ++ac;
5932 XtSetArg (av[ac], XmNpageIncrement, 1); ++ac;
5934 pixel = f->output_data.x->scroll_bar_foreground_pixel;
5935 if (pixel != -1)
5937 XtSetArg (av[ac], XmNforeground, pixel);
5938 ++ac;
5941 pixel = f->output_data.x->scroll_bar_background_pixel;
5942 if (pixel != -1)
5944 XtSetArg (av[ac], XmNbackground, pixel);
5945 ++ac;
5948 widget = XmCreateScrollBar (f->output_data.x->edit_widget,
5949 (char *) scroll_bar_name, av, ac);
5951 /* Add one callback for everything that can happen. */
5952 XtAddCallback (widget, XmNdecrementCallback, xm_scroll_callback,
5953 (XtPointer) bar);
5954 XtAddCallback (widget, XmNdragCallback, xm_scroll_callback,
5955 (XtPointer) bar);
5956 XtAddCallback (widget, XmNincrementCallback, xm_scroll_callback,
5957 (XtPointer) bar);
5958 XtAddCallback (widget, XmNpageDecrementCallback, xm_scroll_callback,
5959 (XtPointer) bar);
5960 XtAddCallback (widget, XmNpageIncrementCallback, xm_scroll_callback,
5961 (XtPointer) bar);
5962 XtAddCallback (widget, XmNtoBottomCallback, xm_scroll_callback,
5963 (XtPointer) bar);
5964 XtAddCallback (widget, XmNtoTopCallback, xm_scroll_callback,
5965 (XtPointer) bar);
5967 /* Realize the widget. Only after that is the X window created. */
5968 XtRealizeWidget (widget);
5970 /* Set the cursor to an arrow. I didn't find a resource to do that.
5971 And I'm wondering why it hasn't an arrow cursor by default. */
5972 XDefineCursor (XtDisplay (widget), XtWindow (widget),
5973 f->output_data.x->nontext_cursor);
5975 #else /* !USE_MOTIF i.e. use Xaw */
5977 /* Set resources. Create the widget. The background of the
5978 Xaw3d scroll bar widget is a little bit light for my taste.
5979 We don't alter it here to let users change it according
5980 to their taste with `emacs*verticalScrollBar.background: xxx'. */
5981 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
5982 XtSetArg (av[ac], XtNorientation, XtorientHorizontal); ++ac;
5983 /* For smoother scrolling with Xaw3d -sm */
5984 /* XtSetArg (av[ac], XtNpickTop, True); ++ac; */
5986 pixel = f->output_data.x->scroll_bar_foreground_pixel;
5987 if (pixel != -1)
5989 XtSetArg (av[ac], XtNforeground, pixel);
5990 ++ac;
5993 pixel = f->output_data.x->scroll_bar_background_pixel;
5994 if (pixel != -1)
5996 XtSetArg (av[ac], XtNbackground, pixel);
5997 ++ac;
6000 /* Top/bottom shadow colors. */
6002 /* Allocate them, if necessary. */
6003 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1)
6005 pixel = f->output_data.x->scroll_bar_background_pixel;
6006 if (pixel != -1)
6008 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
6009 FRAME_X_COLORMAP (f),
6010 &pixel, 1.2, 0x8000))
6011 pixel = -1;
6012 f->output_data.x->scroll_bar_top_shadow_pixel = pixel;
6015 if (f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
6017 pixel = f->output_data.x->scroll_bar_background_pixel;
6018 if (pixel != -1)
6020 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
6021 FRAME_X_COLORMAP (f),
6022 &pixel, 0.6, 0x4000))
6023 pixel = -1;
6024 f->output_data.x->scroll_bar_bottom_shadow_pixel = pixel;
6028 #ifdef XtNbeNiceToColormap
6029 /* Tell the toolkit about them. */
6030 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1
6031 || f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
6032 /* We tried to allocate a color for the top/bottom shadow, and
6033 failed, so tell Xaw3d to use dithering instead. */
6034 /* But only if we have a small colormap. Xaw3d can allocate nice
6035 colors itself. */
6037 XtSetArg (av[ac], XtNbeNiceToColormap,
6038 DefaultDepthOfScreen (FRAME_X_SCREEN (f)) < 16);
6039 ++ac;
6041 else
6042 /* Tell what colors Xaw3d should use for the top/bottom shadow, to
6043 be more consistent with other emacs 3d colors, and since Xaw3d is
6044 not good at dealing with allocation failure. */
6046 /* This tells Xaw3d to use real colors instead of dithering for
6047 the shadows. */
6048 XtSetArg (av[ac], XtNbeNiceToColormap, False);
6049 ++ac;
6051 /* Specify the colors. */
6052 pixel = f->output_data.x->scroll_bar_top_shadow_pixel;
6053 if (pixel != -1)
6055 XtSetArg (av[ac], XtNtopShadowPixel, pixel);
6056 ++ac;
6058 pixel = f->output_data.x->scroll_bar_bottom_shadow_pixel;
6059 if (pixel != -1)
6061 XtSetArg (av[ac], XtNbottomShadowPixel, pixel);
6062 ++ac;
6065 #endif
6067 widget = XtCreateWidget (scroll_bar_name, scrollbarWidgetClass,
6068 f->output_data.x->edit_widget, av, ac);
6071 char const *initial = "";
6072 char const *val = initial;
6073 XtVaGetValues (widget, XtNscrollVCursor, (XtPointer) &val,
6074 #ifdef XtNarrowScrollbars
6075 XtNarrowScrollbars, (XtPointer) &xaw3d_arrow_scroll,
6076 #endif
6077 XtNpickTop, (XtPointer) &xaw3d_pick_top, NULL);
6078 if (xaw3d_arrow_scroll || val == initial)
6079 { /* ARROW_SCROLL */
6080 xaw3d_arrow_scroll = True;
6081 /* Isn't that just a personal preference ? --Stef */
6082 XtVaSetValues (widget, XtNcursorName, "top_left_arrow", NULL);
6086 /* Define callbacks. */
6087 XtAddCallback (widget, XtNjumpProc, xaw_jump_callback, (XtPointer) bar);
6088 XtAddCallback (widget, XtNscrollProc, xaw_scroll_callback,
6089 (XtPointer) bar);
6091 /* Realize the widget. Only after that is the X window created. */
6092 XtRealizeWidget (widget);
6094 #endif /* !USE_MOTIF */
6096 /* Install an action hook that lets us detect when the user
6097 finishes interacting with a scroll bar. */
6098 if (horizontal_action_hook_id == 0)
6099 horizontal_action_hook_id
6100 = XtAppAddActionHook (Xt_app_con, xt_horizontal_action_hook, 0);
6102 /* Remember X window and widget in the scroll bar vector. */
6103 SET_SCROLL_BAR_X_WIDGET (bar, widget);
6104 xwindow = XtWindow (widget);
6105 bar->x_window = xwindow;
6106 bar->whole = 1;
6107 bar->horizontal = true;
6109 unblock_input ();
6111 #endif /* not USE_GTK */
6114 /* Set the thumb size and position of scroll bar BAR. We are currently
6115 displaying PORTION out of a whole WHOLE, and our position POSITION. */
6117 #ifdef USE_GTK
6118 static void
6119 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position, int whole)
6121 xg_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
6124 static void
6125 x_set_toolkit_horizontal_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position, int whole)
6127 xg_set_toolkit_horizontal_scroll_bar_thumb (bar, portion, position, whole);
6130 #else /* not USE_GTK */
6131 static void
6132 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position,
6133 int whole)
6135 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6136 Widget widget = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
6137 float top, shown;
6139 block_input ();
6141 #ifdef USE_MOTIF
6143 if (scroll_bar_adjust_thumb_portion_p)
6145 /* We use an estimate of 30 chars per line rather than the real
6146 `portion' value. This has the disadvantage that the thumb size
6147 is not very representative, but it makes our life a lot easier.
6148 Otherwise, we have to constantly adjust the thumb size, which
6149 we can't always do quickly enough: while dragging, the size of
6150 the thumb might prevent the user from dragging the thumb all the
6151 way to the end. but Motif and some versions of Xaw3d don't allow
6152 updating the thumb size while dragging. Also, even if we can update
6153 its size, the update will often happen too late.
6154 If you don't believe it, check out revision 1.650 of xterm.c to see
6155 what hoops we were going through and the still poor behavior we got. */
6156 portion = WINDOW_TOTAL_LINES (XWINDOW (bar->window)) * 30;
6157 /* When the thumb is at the bottom, position == whole.
6158 So we need to increase `whole' to make space for the thumb. */
6159 whole += portion;
6162 if (whole <= 0)
6163 top = 0, shown = 1;
6164 else
6166 top = (float) position / whole;
6167 shown = (float) portion / whole;
6170 if (bar->dragging == -1)
6172 int size, value;
6174 /* Slider size. Must be in the range [1 .. MAX - MIN] where MAX
6175 is the scroll bar's maximum and MIN is the scroll bar's minimum
6176 value. */
6177 size = clip_to_bounds (1, shown * XM_SB_MAX, XM_SB_MAX);
6179 /* Position. Must be in the range [MIN .. MAX - SLIDER_SIZE]. */
6180 value = top * XM_SB_MAX;
6181 value = min (value, XM_SB_MAX - size);
6183 XmScrollBarSetValues (widget, value, size, 0, 0, False);
6185 #else /* !USE_MOTIF i.e. use Xaw */
6187 if (whole == 0)
6188 top = 0, shown = 1;
6189 else
6191 top = (float) position / whole;
6192 shown = (float) portion / whole;
6196 float old_top, old_shown;
6197 Dimension height;
6198 XtVaGetValues (widget,
6199 XtNtopOfThumb, &old_top,
6200 XtNshown, &old_shown,
6201 XtNheight, &height,
6202 NULL);
6204 /* Massage the top+shown values. */
6205 if (bar->dragging == -1 || bar->last_seen_part == scroll_bar_down_arrow)
6206 top = max (0, min (1, top));
6207 else
6208 top = old_top;
6209 #if ! defined (HAVE_XAW3D)
6210 /* With Xaw, 'top' values too closer to 1.0 may
6211 cause the thumb to disappear. Fix that. */
6212 top = min (top, 0.99f);
6213 #endif
6214 /* Keep two pixels available for moving the thumb down. */
6215 shown = max (0, min (1 - top - (2.0f / height), shown));
6216 #if ! defined (HAVE_XAW3D)
6217 /* Likewise with too small 'shown'. */
6218 shown = max (shown, 0.01f);
6219 #endif
6221 /* If the call to XawScrollbarSetThumb below doesn't seem to
6222 work, check that 'NARROWPROTO' is defined in src/config.h.
6223 If this is not so, most likely you need to fix configure. */
6224 if (top != old_top || shown != old_shown)
6226 if (bar->dragging == -1)
6227 XawScrollbarSetThumb (widget, top, shown);
6228 else
6230 /* Try to make the scrolling a tad smoother. */
6231 if (!xaw3d_pick_top)
6232 shown = min (shown, old_shown);
6234 XawScrollbarSetThumb (widget, top, shown);
6238 #endif /* !USE_MOTIF */
6240 unblock_input ();
6243 static void
6244 x_set_toolkit_horizontal_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position,
6245 int whole)
6247 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6248 Widget widget = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
6249 float top, shown;
6251 block_input ();
6253 #ifdef USE_MOTIF
6254 bar->whole = whole;
6255 shown = (float) portion / whole;
6256 top = (float) position / (whole - portion);
6258 int size = clip_to_bounds (1, shown * XM_SB_MAX, XM_SB_MAX);
6259 int value = clip_to_bounds (0, top * (XM_SB_MAX - size), XM_SB_MAX - size);
6261 XmScrollBarSetValues (widget, value, size, 0, 0, False);
6263 #else /* !USE_MOTIF i.e. use Xaw */
6264 bar->whole = whole;
6265 if (whole == 0)
6266 top = 0, shown = 1;
6267 else
6269 top = (float) position / whole;
6270 shown = (float) portion / whole;
6274 float old_top, old_shown;
6275 Dimension height;
6276 XtVaGetValues (widget,
6277 XtNtopOfThumb, &old_top,
6278 XtNshown, &old_shown,
6279 XtNheight, &height,
6280 NULL);
6282 #if false
6283 /* Massage the top+shown values. */
6284 if (bar->dragging == -1 || bar->last_seen_part == scroll_bar_down_arrow)
6285 top = max (0, min (1, top));
6286 else
6287 top = old_top;
6288 #if ! defined (HAVE_XAW3D)
6289 /* With Xaw, 'top' values too closer to 1.0 may
6290 cause the thumb to disappear. Fix that. */
6291 top = min (top, 0.99f);
6292 #endif
6293 /* Keep two pixels available for moving the thumb down. */
6294 shown = max (0, min (1 - top - (2.0f / height), shown));
6295 #if ! defined (HAVE_XAW3D)
6296 /* Likewise with too small 'shown'. */
6297 shown = max (shown, 0.01f);
6298 #endif
6299 #endif
6301 /* If the call to XawScrollbarSetThumb below doesn't seem to
6302 work, check that 'NARROWPROTO' is defined in src/config.h.
6303 If this is not so, most likely you need to fix configure. */
6304 XawScrollbarSetThumb (widget, top, shown);
6305 #if false
6306 if (top != old_top || shown != old_shown)
6308 if (bar->dragging == -1)
6309 XawScrollbarSetThumb (widget, top, shown);
6310 else
6312 /* Try to make the scrolling a tad smoother. */
6313 if (!xaw3d_pick_top)
6314 shown = min (shown, old_shown);
6316 XawScrollbarSetThumb (widget, top, shown);
6319 #endif
6321 #endif /* !USE_MOTIF */
6323 unblock_input ();
6325 #endif /* not USE_GTK */
6327 #endif /* USE_TOOLKIT_SCROLL_BARS */
6331 /************************************************************************
6332 Scroll bars, general
6333 ************************************************************************/
6335 /* Create a scroll bar and return the scroll bar vector for it. W is
6336 the Emacs window on which to create the scroll bar. TOP, LEFT,
6337 WIDTH and HEIGHT are the pixel coordinates and dimensions of the
6338 scroll bar. */
6340 static struct scroll_bar *
6341 x_scroll_bar_create (struct window *w, int top, int left,
6342 int width, int height, bool horizontal)
6344 struct frame *f = XFRAME (w->frame);
6345 struct scroll_bar *bar
6346 = ALLOCATE_PSEUDOVECTOR (struct scroll_bar, x_window, PVEC_OTHER);
6347 Lisp_Object barobj;
6349 block_input ();
6351 #ifdef USE_TOOLKIT_SCROLL_BARS
6352 if (horizontal)
6353 x_create_horizontal_toolkit_scroll_bar (f, bar);
6354 else
6355 x_create_toolkit_scroll_bar (f, bar);
6356 #else /* not USE_TOOLKIT_SCROLL_BARS */
6358 XSetWindowAttributes a;
6359 unsigned long mask;
6360 Window window;
6362 a.background_pixel = f->output_data.x->scroll_bar_background_pixel;
6363 if (a.background_pixel == -1)
6364 a.background_pixel = FRAME_BACKGROUND_PIXEL (f);
6366 a.event_mask = (ButtonPressMask | ButtonReleaseMask
6367 | ButtonMotionMask | PointerMotionHintMask
6368 | ExposureMask);
6369 a.cursor = FRAME_DISPLAY_INFO (f)->vertical_scroll_bar_cursor;
6371 mask = (CWBackPixel | CWEventMask | CWCursor);
6373 /* Clear the area of W that will serve as a scroll bar. This is
6374 for the case that a window has been split horizontally. In
6375 this case, no clear_frame is generated to reduce flickering. */
6376 if (width > 0 && window_box_height (w) > 0)
6377 x_clear_area (f, left, top, width, window_box_height (w));
6379 window = XCreateWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
6380 /* Position and size of scroll bar. */
6381 left, top, width, height,
6382 /* Border width, depth, class, and visual. */
6384 CopyFromParent,
6385 CopyFromParent,
6386 CopyFromParent,
6387 /* Attributes. */
6388 mask, &a);
6389 bar->x_window = window;
6391 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6393 XSETWINDOW (bar->window, w);
6394 bar->top = top;
6395 bar->left = left;
6396 bar->width = width;
6397 bar->height = height;
6398 bar->start = 0;
6399 bar->end = 0;
6400 bar->dragging = -1;
6401 bar->horizontal = horizontal;
6402 #if defined (USE_TOOLKIT_SCROLL_BARS) && defined (USE_LUCID)
6403 bar->last_seen_part = scroll_bar_nowhere;
6404 #endif
6406 /* Add bar to its frame's list of scroll bars. */
6407 bar->next = FRAME_SCROLL_BARS (f);
6408 bar->prev = Qnil;
6409 XSETVECTOR (barobj, bar);
6410 fset_scroll_bars (f, barobj);
6411 if (!NILP (bar->next))
6412 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
6414 /* Map the window/widget. */
6415 #ifdef USE_TOOLKIT_SCROLL_BARS
6417 #ifdef USE_GTK
6418 if (horizontal)
6419 xg_update_horizontal_scrollbar_pos (f, bar->x_window, top,
6420 left, width, max (height, 1));
6421 else
6422 xg_update_scrollbar_pos (f, bar->x_window, top,
6423 left, width, max (height, 1));
6424 #else /* not USE_GTK */
6425 Widget scroll_bar = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
6426 XtConfigureWidget (scroll_bar, left, top, width, max (height, 1), 0);
6427 XtMapWidget (scroll_bar);
6428 #endif /* not USE_GTK */
6430 #else /* not USE_TOOLKIT_SCROLL_BARS */
6431 XMapRaised (FRAME_X_DISPLAY (f), bar->x_window);
6432 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6434 unblock_input ();
6435 return bar;
6439 #ifndef USE_TOOLKIT_SCROLL_BARS
6441 /* Draw BAR's handle in the proper position.
6443 If the handle is already drawn from START to END, don't bother
6444 redrawing it, unless REBUILD; in that case, always
6445 redraw it. (REBUILD is handy for drawing the handle after expose
6446 events.)
6448 Normally, we want to constrain the start and end of the handle to
6449 fit inside its rectangle, but if the user is dragging the scroll
6450 bar handle, we want to let them drag it down all the way, so that
6451 the bar's top is as far down as it goes; otherwise, there's no way
6452 to move to the very end of the buffer. */
6454 static void
6455 x_scroll_bar_set_handle (struct scroll_bar *bar, int start, int end,
6456 bool rebuild)
6458 bool dragging = bar->dragging != -1;
6459 Window w = bar->x_window;
6460 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6461 GC gc = f->output_data.x->normal_gc;
6463 /* If the display is already accurate, do nothing. */
6464 if (! rebuild
6465 && start == bar->start
6466 && end == bar->end)
6467 return;
6469 block_input ();
6472 int inside_width = VERTICAL_SCROLL_BAR_INSIDE_WIDTH (f, bar->width);
6473 int inside_height = VERTICAL_SCROLL_BAR_INSIDE_HEIGHT (f, bar->height);
6474 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
6476 /* Make sure the values are reasonable, and try to preserve
6477 the distance between start and end. */
6479 int length = end - start;
6481 if (start < 0)
6482 start = 0;
6483 else if (start > top_range)
6484 start = top_range;
6485 end = start + length;
6487 if (end < start)
6488 end = start;
6489 else if (end > top_range && ! dragging)
6490 end = top_range;
6493 /* Store the adjusted setting in the scroll bar. */
6494 bar->start = start;
6495 bar->end = end;
6497 /* Clip the end position, just for display. */
6498 if (end > top_range)
6499 end = top_range;
6501 /* Draw bottom positions VERTICAL_SCROLL_BAR_MIN_HANDLE pixels
6502 below top positions, to make sure the handle is always at least
6503 that many pixels tall. */
6504 end += VERTICAL_SCROLL_BAR_MIN_HANDLE;
6506 /* Draw the empty space above the handle. Note that we can't clear
6507 zero-height areas; that means "clear to end of window." */
6508 if ((inside_width > 0) && (start > 0))
6509 x_clear_area1 (FRAME_X_DISPLAY (f), w,
6510 VERTICAL_SCROLL_BAR_LEFT_BORDER,
6511 VERTICAL_SCROLL_BAR_TOP_BORDER,
6512 inside_width, start, False);
6514 /* Change to proper foreground color if one is specified. */
6515 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
6516 XSetForeground (FRAME_X_DISPLAY (f), gc,
6517 f->output_data.x->scroll_bar_foreground_pixel);
6519 /* Draw the handle itself. */
6520 XFillRectangle (FRAME_X_DISPLAY (f), w, gc,
6521 /* x, y, width, height */
6522 VERTICAL_SCROLL_BAR_LEFT_BORDER,
6523 VERTICAL_SCROLL_BAR_TOP_BORDER + start,
6524 inside_width, end - start);
6526 /* Restore the foreground color of the GC if we changed it above. */
6527 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
6528 XSetForeground (FRAME_X_DISPLAY (f), gc,
6529 FRAME_FOREGROUND_PIXEL (f));
6531 /* Draw the empty space below the handle. Note that we can't
6532 clear zero-height areas; that means "clear to end of window." */
6533 if ((inside_width > 0) && (end < inside_height))
6534 x_clear_area1 (FRAME_X_DISPLAY (f), w,
6535 VERTICAL_SCROLL_BAR_LEFT_BORDER,
6536 VERTICAL_SCROLL_BAR_TOP_BORDER + end,
6537 inside_width, inside_height - end, False);
6540 unblock_input ();
6543 #endif /* !USE_TOOLKIT_SCROLL_BARS */
6545 /* Destroy scroll bar BAR, and set its Emacs window's scroll bar to
6546 nil. */
6548 static void
6549 x_scroll_bar_remove (struct scroll_bar *bar)
6551 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6552 block_input ();
6554 #ifdef USE_TOOLKIT_SCROLL_BARS
6555 #ifdef USE_GTK
6556 xg_remove_scroll_bar (f, bar->x_window);
6557 #else /* not USE_GTK */
6558 XtDestroyWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar));
6559 #endif /* not USE_GTK */
6560 #else
6561 XDestroyWindow (FRAME_X_DISPLAY (f), bar->x_window);
6562 #endif
6564 /* Dissociate this scroll bar from its window. */
6565 if (bar->horizontal)
6566 wset_horizontal_scroll_bar (XWINDOW (bar->window), Qnil);
6567 else
6568 wset_vertical_scroll_bar (XWINDOW (bar->window), Qnil);
6570 unblock_input ();
6574 /* Set the handle of the vertical scroll bar for WINDOW to indicate
6575 that we are displaying PORTION characters out of a total of WHOLE
6576 characters, starting at POSITION. If WINDOW has no scroll bar,
6577 create one. */
6579 static void
6580 XTset_vertical_scroll_bar (struct window *w, int portion, int whole, int position)
6582 struct frame *f = XFRAME (w->frame);
6583 Lisp_Object barobj;
6584 struct scroll_bar *bar;
6585 int top, height, left, width;
6586 int window_y, window_height;
6588 /* Get window dimensions. */
6589 window_box (w, ANY_AREA, 0, &window_y, 0, &window_height);
6590 top = window_y;
6591 height = window_height;
6592 left = WINDOW_SCROLL_BAR_AREA_X (w);
6593 width = WINDOW_SCROLL_BAR_AREA_WIDTH (w);
6595 /* Does the scroll bar exist yet? */
6596 if (NILP (w->vertical_scroll_bar))
6598 if (width > 0 && height > 0)
6600 block_input ();
6601 x_clear_area (f, left, top, width, height);
6602 unblock_input ();
6605 bar = x_scroll_bar_create (w, top, left, width, max (height, 1), false);
6607 else
6609 /* It may just need to be moved and resized. */
6610 unsigned int mask = 0;
6612 bar = XSCROLL_BAR (w->vertical_scroll_bar);
6614 block_input ();
6616 if (left != bar->left)
6617 mask |= CWX;
6618 if (top != bar->top)
6619 mask |= CWY;
6620 if (width != bar->width)
6621 mask |= CWWidth;
6622 if (height != bar->height)
6623 mask |= CWHeight;
6625 #ifdef USE_TOOLKIT_SCROLL_BARS
6627 /* Move/size the scroll bar widget. */
6628 if (mask)
6630 /* Since toolkit scroll bars are smaller than the space reserved
6631 for them on the frame, we have to clear "under" them. */
6632 if (width > 0 && height > 0)
6633 x_clear_area (f, left, top, width, height);
6634 #ifdef USE_GTK
6635 xg_update_scrollbar_pos (f, bar->x_window, top,
6636 left, width, max (height, 1));
6637 #else /* not USE_GTK */
6638 XtConfigureWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar),
6639 left, top, width, max (height, 1), 0);
6640 #endif /* not USE_GTK */
6642 #else /* not USE_TOOLKIT_SCROLL_BARS */
6644 /* Move/size the scroll bar window. */
6645 if (mask)
6647 XWindowChanges wc;
6649 wc.x = left;
6650 wc.y = top;
6651 wc.width = width;
6652 wc.height = height;
6653 XConfigureWindow (FRAME_X_DISPLAY (f), bar->x_window,
6654 mask, &wc);
6657 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6659 /* Remember new settings. */
6660 bar->left = left;
6661 bar->top = top;
6662 bar->width = width;
6663 bar->height = height;
6665 unblock_input ();
6668 #ifdef USE_TOOLKIT_SCROLL_BARS
6669 x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
6670 #else /* not USE_TOOLKIT_SCROLL_BARS */
6671 /* Set the scroll bar's current state, unless we're currently being
6672 dragged. */
6673 if (bar->dragging == -1)
6675 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, height);
6677 if (whole == 0)
6678 x_scroll_bar_set_handle (bar, 0, top_range, false);
6679 else
6681 int start = ((double) position * top_range) / whole;
6682 int end = ((double) (position + portion) * top_range) / whole;
6683 x_scroll_bar_set_handle (bar, start, end, false);
6686 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6688 XSETVECTOR (barobj, bar);
6689 wset_vertical_scroll_bar (w, barobj);
6693 static void
6694 XTset_horizontal_scroll_bar (struct window *w, int portion, int whole, int position)
6696 struct frame *f = XFRAME (w->frame);
6697 Lisp_Object barobj;
6698 struct scroll_bar *bar;
6699 int top, height, left, width;
6700 int window_x, window_width;
6701 int pixel_width = WINDOW_PIXEL_WIDTH (w);
6703 /* Get window dimensions. */
6704 window_box (w, ANY_AREA, &window_x, 0, &window_width, 0);
6705 left = window_x;
6706 width = window_width;
6707 top = WINDOW_SCROLL_BAR_AREA_Y (w);
6708 height = WINDOW_SCROLL_BAR_AREA_HEIGHT (w);
6710 /* Does the scroll bar exist yet? */
6711 if (NILP (w->horizontal_scroll_bar))
6713 if (width > 0 && height > 0)
6715 block_input ();
6717 /* Clear also part between window_width and
6718 WINDOW_PIXEL_WIDTH. */
6719 x_clear_area (f, left, top, pixel_width, height);
6720 unblock_input ();
6723 bar = x_scroll_bar_create (w, top, left, width, height, true);
6725 else
6727 /* It may just need to be moved and resized. */
6728 unsigned int mask = 0;
6730 bar = XSCROLL_BAR (w->horizontal_scroll_bar);
6732 block_input ();
6734 if (left != bar->left)
6735 mask |= CWX;
6736 if (top != bar->top)
6737 mask |= CWY;
6738 if (width != bar->width)
6739 mask |= CWWidth;
6740 if (height != bar->height)
6741 mask |= CWHeight;
6743 #ifdef USE_TOOLKIT_SCROLL_BARS
6744 /* Move/size the scroll bar widget. */
6745 if (mask)
6747 /* Since toolkit scroll bars are smaller than the space reserved
6748 for them on the frame, we have to clear "under" them. */
6749 if (width > 0 && height > 0)
6750 x_clear_area (f,
6751 WINDOW_LEFT_EDGE_X (w), top,
6752 pixel_width - WINDOW_RIGHT_DIVIDER_WIDTH (w), height);
6753 #ifdef USE_GTK
6754 xg_update_horizontal_scrollbar_pos (f, bar->x_window, top, left,
6755 width, height);
6756 #else /* not USE_GTK */
6757 XtConfigureWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar),
6758 left, top, width, height, 0);
6759 #endif /* not USE_GTK */
6761 #else /* not USE_TOOLKIT_SCROLL_BARS */
6763 /* Clear areas not covered by the scroll bar because it's not as
6764 wide as the area reserved for it. This makes sure a
6765 previous mode line display is cleared after C-x 2 C-x 1, for
6766 example. */
6768 int area_height = WINDOW_CONFIG_SCROLL_BAR_HEIGHT (w);
6769 int rest = area_height - height;
6770 if (rest > 0 && width > 0)
6771 x_clear_area (f, left, top, width, rest);
6774 /* Move/size the scroll bar window. */
6775 if (mask)
6777 XWindowChanges wc;
6779 wc.x = left;
6780 wc.y = top;
6781 wc.width = width;
6782 wc.height = height;
6783 XConfigureWindow (FRAME_X_DISPLAY (f), bar->x_window,
6784 mask, &wc);
6787 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6789 /* Remember new settings. */
6790 bar->left = left;
6791 bar->top = top;
6792 bar->width = width;
6793 bar->height = height;
6795 unblock_input ();
6798 #ifdef USE_TOOLKIT_SCROLL_BARS
6799 x_set_toolkit_horizontal_scroll_bar_thumb (bar, portion, position, whole);
6800 #else /* not USE_TOOLKIT_SCROLL_BARS */
6801 /* Set the scroll bar's current state, unless we're currently being
6802 dragged. */
6803 if (bar->dragging == -1)
6805 int left_range = HORIZONTAL_SCROLL_BAR_LEFT_RANGE (f, width);
6807 if (whole == 0)
6808 x_scroll_bar_set_handle (bar, 0, left_range, false);
6809 else
6811 int start = ((double) position * left_range) / whole;
6812 int end = ((double) (position + portion) * left_range) / whole;
6813 x_scroll_bar_set_handle (bar, start, end, false);
6816 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6818 XSETVECTOR (barobj, bar);
6819 wset_horizontal_scroll_bar (w, barobj);
6823 /* The following three hooks are used when we're doing a thorough
6824 redisplay of the frame. We don't explicitly know which scroll bars
6825 are going to be deleted, because keeping track of when windows go
6826 away is a real pain - "Can you say set-window-configuration, boys
6827 and girls?" Instead, we just assert at the beginning of redisplay
6828 that *all* scroll bars are to be removed, and then save a scroll bar
6829 from the fiery pit when we actually redisplay its window. */
6831 /* Arrange for all scroll bars on FRAME to be removed at the next call
6832 to `*judge_scroll_bars_hook'. A scroll bar may be spared if
6833 `*redeem_scroll_bar_hook' is applied to its window before the judgment. */
6835 static void
6836 XTcondemn_scroll_bars (struct frame *frame)
6838 if (!NILP (FRAME_SCROLL_BARS (frame)))
6840 if (!NILP (FRAME_CONDEMNED_SCROLL_BARS (frame)))
6842 /* Prepend scrollbars to already condemned ones. */
6843 Lisp_Object last = FRAME_SCROLL_BARS (frame);
6845 while (!NILP (XSCROLL_BAR (last)->next))
6846 last = XSCROLL_BAR (last)->next;
6848 XSCROLL_BAR (last)->next = FRAME_CONDEMNED_SCROLL_BARS (frame);
6849 XSCROLL_BAR (FRAME_CONDEMNED_SCROLL_BARS (frame))->prev = last;
6852 fset_condemned_scroll_bars (frame, FRAME_SCROLL_BARS (frame));
6853 fset_scroll_bars (frame, Qnil);
6858 /* Un-mark WINDOW's scroll bar for deletion in this judgment cycle.
6859 Note that WINDOW isn't necessarily condemned at all. */
6861 static void
6862 XTredeem_scroll_bar (struct window *w)
6864 struct scroll_bar *bar;
6865 Lisp_Object barobj;
6866 struct frame *f;
6868 /* We can't redeem this window's scroll bar if it doesn't have one. */
6869 if (NILP (w->vertical_scroll_bar) && NILP (w->horizontal_scroll_bar))
6870 emacs_abort ();
6872 if (!NILP (w->vertical_scroll_bar) && WINDOW_HAS_VERTICAL_SCROLL_BAR (w))
6874 bar = XSCROLL_BAR (w->vertical_scroll_bar);
6875 /* Unlink it from the condemned list. */
6876 f = XFRAME (WINDOW_FRAME (w));
6877 if (NILP (bar->prev))
6879 /* If the prev pointer is nil, it must be the first in one of
6880 the lists. */
6881 if (EQ (FRAME_SCROLL_BARS (f), w->vertical_scroll_bar))
6882 /* It's not condemned. Everything's fine. */
6883 goto horizontal;
6884 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
6885 w->vertical_scroll_bar))
6886 fset_condemned_scroll_bars (f, bar->next);
6887 else
6888 /* If its prev pointer is nil, it must be at the front of
6889 one or the other! */
6890 emacs_abort ();
6892 else
6893 XSCROLL_BAR (bar->prev)->next = bar->next;
6895 if (! NILP (bar->next))
6896 XSCROLL_BAR (bar->next)->prev = bar->prev;
6898 bar->next = FRAME_SCROLL_BARS (f);
6899 bar->prev = Qnil;
6900 XSETVECTOR (barobj, bar);
6901 fset_scroll_bars (f, barobj);
6902 if (! NILP (bar->next))
6903 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
6906 horizontal:
6907 if (!NILP (w->horizontal_scroll_bar) && WINDOW_HAS_HORIZONTAL_SCROLL_BAR (w))
6909 bar = XSCROLL_BAR (w->horizontal_scroll_bar);
6910 /* Unlink it from the condemned list. */
6911 f = XFRAME (WINDOW_FRAME (w));
6912 if (NILP (bar->prev))
6914 /* If the prev pointer is nil, it must be the first in one of
6915 the lists. */
6916 if (EQ (FRAME_SCROLL_BARS (f), w->horizontal_scroll_bar))
6917 /* It's not condemned. Everything's fine. */
6918 return;
6919 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
6920 w->horizontal_scroll_bar))
6921 fset_condemned_scroll_bars (f, bar->next);
6922 else
6923 /* If its prev pointer is nil, it must be at the front of
6924 one or the other! */
6925 emacs_abort ();
6927 else
6928 XSCROLL_BAR (bar->prev)->next = bar->next;
6930 if (! NILP (bar->next))
6931 XSCROLL_BAR (bar->next)->prev = bar->prev;
6933 bar->next = FRAME_SCROLL_BARS (f);
6934 bar->prev = Qnil;
6935 XSETVECTOR (barobj, bar);
6936 fset_scroll_bars (f, barobj);
6937 if (! NILP (bar->next))
6938 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
6942 /* Remove all scroll bars on FRAME that haven't been saved since the
6943 last call to `*condemn_scroll_bars_hook'. */
6945 static void
6946 XTjudge_scroll_bars (struct frame *f)
6948 Lisp_Object bar, next;
6950 bar = FRAME_CONDEMNED_SCROLL_BARS (f);
6952 /* Clear out the condemned list now so we won't try to process any
6953 more events on the hapless scroll bars. */
6954 fset_condemned_scroll_bars (f, Qnil);
6956 for (; ! NILP (bar); bar = next)
6958 struct scroll_bar *b = XSCROLL_BAR (bar);
6960 x_scroll_bar_remove (b);
6962 next = b->next;
6963 b->next = b->prev = Qnil;
6966 /* Now there should be no references to the condemned scroll bars,
6967 and they should get garbage-collected. */
6971 #ifndef USE_TOOLKIT_SCROLL_BARS
6972 /* Handle an Expose or GraphicsExpose event on a scroll bar. This
6973 is a no-op when using toolkit scroll bars.
6975 This may be called from a signal handler, so we have to ignore GC
6976 mark bits. */
6978 static void
6979 x_scroll_bar_expose (struct scroll_bar *bar, const XEvent *event)
6981 Window w = bar->x_window;
6982 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6983 GC gc = f->output_data.x->normal_gc;
6985 block_input ();
6987 x_scroll_bar_set_handle (bar, bar->start, bar->end, true);
6989 /* Switch to scroll bar foreground color. */
6990 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
6991 XSetForeground (FRAME_X_DISPLAY (f), gc,
6992 f->output_data.x->scroll_bar_foreground_pixel);
6994 /* Draw a one-pixel border just inside the edges of the scroll bar. */
6995 XDrawRectangle (FRAME_X_DISPLAY (f), w, gc,
6996 /* x, y, width, height */
6997 0, 0, bar->width - 1, bar->height - 1);
6999 /* Restore the foreground color of the GC if we changed it above. */
7000 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
7001 XSetForeground (FRAME_X_DISPLAY (f), gc,
7002 FRAME_FOREGROUND_PIXEL (f));
7004 unblock_input ();
7007 #endif /* not USE_TOOLKIT_SCROLL_BARS */
7009 /* Handle a mouse click on the scroll bar BAR. If *EMACS_EVENT's kind
7010 is set to something other than NO_EVENT, it is enqueued.
7012 This may be called from a signal handler, so we have to ignore GC
7013 mark bits. */
7016 static void
7017 x_scroll_bar_handle_click (struct scroll_bar *bar,
7018 const XEvent *event,
7019 struct input_event *emacs_event)
7021 if (! WINDOWP (bar->window))
7022 emacs_abort ();
7024 emacs_event->kind = (bar->horizontal
7025 ? HORIZONTAL_SCROLL_BAR_CLICK_EVENT
7026 : SCROLL_BAR_CLICK_EVENT);
7027 emacs_event->code = event->xbutton.button - Button1;
7028 emacs_event->modifiers
7029 = (x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO
7030 (XFRAME (WINDOW_FRAME (XWINDOW (bar->window)))),
7031 event->xbutton.state)
7032 | (event->type == ButtonRelease
7033 ? up_modifier
7034 : down_modifier));
7035 emacs_event->frame_or_window = bar->window;
7036 emacs_event->arg = Qnil;
7037 emacs_event->timestamp = event->xbutton.time;
7038 if (bar->horizontal)
7040 int left_range
7041 = HORIZONTAL_SCROLL_BAR_LEFT_RANGE (f, bar->width);
7042 int x = event->xbutton.x - HORIZONTAL_SCROLL_BAR_LEFT_BORDER;
7044 if (x < 0) x = 0;
7045 if (x > left_range) x = left_range;
7047 if (x < bar->start)
7048 emacs_event->part = scroll_bar_before_handle;
7049 else if (x < bar->end + HORIZONTAL_SCROLL_BAR_MIN_HANDLE)
7050 emacs_event->part = scroll_bar_horizontal_handle;
7051 else
7052 emacs_event->part = scroll_bar_after_handle;
7054 #ifndef USE_TOOLKIT_SCROLL_BARS
7055 /* If the user has released the handle, set it to its final position. */
7056 if (event->type == ButtonRelease && bar->dragging != -1)
7058 int new_start = - bar->dragging;
7059 int new_end = new_start + bar->end - bar->start;
7061 x_scroll_bar_set_handle (bar, new_start, new_end, false);
7062 bar->dragging = -1;
7064 #endif
7066 XSETINT (emacs_event->x, left_range);
7067 XSETINT (emacs_event->y, x);
7069 else
7071 int top_range
7072 = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
7073 int y = event->xbutton.y - VERTICAL_SCROLL_BAR_TOP_BORDER;
7075 if (y < 0) y = 0;
7076 if (y > top_range) y = top_range;
7078 if (y < bar->start)
7079 emacs_event->part = scroll_bar_above_handle;
7080 else if (y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
7081 emacs_event->part = scroll_bar_handle;
7082 else
7083 emacs_event->part = scroll_bar_below_handle;
7085 #ifndef USE_TOOLKIT_SCROLL_BARS
7086 /* If the user has released the handle, set it to its final position. */
7087 if (event->type == ButtonRelease && bar->dragging != -1)
7089 int new_start = y - bar->dragging;
7090 int new_end = new_start + bar->end - bar->start;
7092 x_scroll_bar_set_handle (bar, new_start, new_end, false);
7093 bar->dragging = -1;
7095 #endif
7097 XSETINT (emacs_event->x, y);
7098 XSETINT (emacs_event->y, top_range);
7102 #ifndef USE_TOOLKIT_SCROLL_BARS
7104 /* Handle some mouse motion while someone is dragging the scroll bar.
7106 This may be called from a signal handler, so we have to ignore GC
7107 mark bits. */
7109 static void
7110 x_scroll_bar_note_movement (struct scroll_bar *bar,
7111 const XMotionEvent *event)
7113 struct frame *f = XFRAME (XWINDOW (bar->window)->frame);
7114 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
7116 dpyinfo->last_mouse_movement_time = event->time;
7117 dpyinfo->last_mouse_scroll_bar = bar;
7118 f->mouse_moved = true;
7120 /* If we're dragging the bar, display it. */
7121 if (bar->dragging != -1)
7123 /* Where should the handle be now? */
7124 int new_start = event->y - bar->dragging;
7126 if (new_start != bar->start)
7128 int new_end = new_start + bar->end - bar->start;
7130 x_scroll_bar_set_handle (bar, new_start, new_end, false);
7135 #endif /* !USE_TOOLKIT_SCROLL_BARS */
7137 /* Return information to the user about the current position of the mouse
7138 on the scroll bar. */
7140 static void
7141 x_scroll_bar_report_motion (struct frame **fp, Lisp_Object *bar_window,
7142 enum scroll_bar_part *part, Lisp_Object *x,
7143 Lisp_Object *y, Time *timestamp)
7145 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (*fp);
7146 struct scroll_bar *bar = dpyinfo->last_mouse_scroll_bar;
7147 Window w = bar->x_window;
7148 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
7149 int win_x, win_y;
7150 Window dummy_window;
7151 int dummy_coord;
7152 unsigned int dummy_mask;
7154 block_input ();
7156 /* Get the mouse's position relative to the scroll bar window, and
7157 report that. */
7158 if (XQueryPointer (FRAME_X_DISPLAY (f), w,
7160 /* Root, child, root x and root y. */
7161 &dummy_window, &dummy_window,
7162 &dummy_coord, &dummy_coord,
7164 /* Position relative to scroll bar. */
7165 &win_x, &win_y,
7167 /* Mouse buttons and modifier keys. */
7168 &dummy_mask))
7170 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
7172 win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
7174 if (bar->dragging != -1)
7175 win_y -= bar->dragging;
7177 if (win_y < 0)
7178 win_y = 0;
7179 if (win_y > top_range)
7180 win_y = top_range;
7182 *fp = f;
7183 *bar_window = bar->window;
7185 if (bar->dragging != -1)
7186 *part = scroll_bar_handle;
7187 else if (win_y < bar->start)
7188 *part = scroll_bar_above_handle;
7189 else if (win_y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
7190 *part = scroll_bar_handle;
7191 else
7192 *part = scroll_bar_below_handle;
7194 XSETINT (*x, win_y);
7195 XSETINT (*y, top_range);
7197 f->mouse_moved = false;
7198 dpyinfo->last_mouse_scroll_bar = NULL;
7199 *timestamp = dpyinfo->last_mouse_movement_time;
7202 unblock_input ();
7206 /* Return information to the user about the current position of the mouse
7207 on the scroll bar. */
7209 static void
7210 x_horizontal_scroll_bar_report_motion (struct frame **fp, Lisp_Object *bar_window,
7211 enum scroll_bar_part *part, Lisp_Object *x,
7212 Lisp_Object *y, Time *timestamp)
7214 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (*fp);
7215 struct scroll_bar *bar = dpyinfo->last_mouse_scroll_bar;
7216 Window w = bar->x_window;
7217 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
7218 int win_x, win_y;
7219 Window dummy_window;
7220 int dummy_coord;
7221 unsigned int dummy_mask;
7223 block_input ();
7225 /* Get the mouse's position relative to the scroll bar window, and
7226 report that. */
7227 if (XQueryPointer (FRAME_X_DISPLAY (f), w,
7229 /* Root, child, root x and root y. */
7230 &dummy_window, &dummy_window,
7231 &dummy_coord, &dummy_coord,
7233 /* Position relative to scroll bar. */
7234 &win_x, &win_y,
7236 /* Mouse buttons and modifier keys. */
7237 &dummy_mask))
7239 int left_range = HORIZONTAL_SCROLL_BAR_LEFT_RANGE (f, bar->width);
7241 win_x -= HORIZONTAL_SCROLL_BAR_LEFT_BORDER;
7243 if (bar->dragging != -1)
7244 win_x -= bar->dragging;
7246 if (win_x < 0)
7247 win_x = 0;
7248 if (win_x > left_range)
7249 win_x = left_range;
7251 *fp = f;
7252 *bar_window = bar->window;
7254 if (bar->dragging != -1)
7255 *part = scroll_bar_horizontal_handle;
7256 else if (win_x < bar->start)
7257 *part = scroll_bar_before_handle;
7258 else if (win_x < bar->end + HORIZONTAL_SCROLL_BAR_MIN_HANDLE)
7259 *part = scroll_bar_handle;
7260 else
7261 *part = scroll_bar_after_handle;
7263 XSETINT (*y, win_x);
7264 XSETINT (*x, left_range);
7266 f->mouse_moved = false;
7267 dpyinfo->last_mouse_scroll_bar = NULL;
7268 *timestamp = dpyinfo->last_mouse_movement_time;
7271 unblock_input ();
7275 /* The screen has been cleared so we may have changed foreground or
7276 background colors, and the scroll bars may need to be redrawn.
7277 Clear out the scroll bars, and ask for expose events, so we can
7278 redraw them. */
7280 static void
7281 x_scroll_bar_clear (struct frame *f)
7283 #ifndef USE_TOOLKIT_SCROLL_BARS
7284 Lisp_Object bar;
7286 /* We can have scroll bars even if this is 0,
7287 if we just turned off scroll bar mode.
7288 But in that case we should not clear them. */
7289 if (FRAME_HAS_VERTICAL_SCROLL_BARS (f))
7290 for (bar = FRAME_SCROLL_BARS (f); VECTORP (bar);
7291 bar = XSCROLL_BAR (bar)->next)
7292 XClearArea (FRAME_X_DISPLAY (f),
7293 XSCROLL_BAR (bar)->x_window,
7294 0, 0, 0, 0, True);
7295 #endif /* not USE_TOOLKIT_SCROLL_BARS */
7298 #ifdef ENABLE_CHECKING
7300 /* Record the last 100 characters stored
7301 to help debug the loss-of-chars-during-GC problem. */
7303 static int temp_index;
7304 static short temp_buffer[100];
7306 #define STORE_KEYSYM_FOR_DEBUG(keysym) \
7307 if (temp_index == ARRAYELTS (temp_buffer)) \
7308 temp_index = 0; \
7309 temp_buffer[temp_index++] = (keysym)
7311 #else /* not ENABLE_CHECKING */
7313 #define STORE_KEYSYM_FOR_DEBUG(keysym) ((void)0)
7315 #endif /* ENABLE_CHECKING */
7317 /* Set this to nonzero to fake an "X I/O error"
7318 on a particular display. */
7320 static struct x_display_info *XTread_socket_fake_io_error;
7322 /* When we find no input here, we occasionally do a no-op command
7323 to verify that the X server is still running and we can still talk with it.
7324 We try all the open displays, one by one.
7325 This variable is used for cycling thru the displays. */
7327 static struct x_display_info *next_noop_dpyinfo;
7329 enum
7331 X_EVENT_NORMAL,
7332 X_EVENT_GOTO_OUT,
7333 X_EVENT_DROP
7336 /* Filter events for the current X input method.
7337 DPYINFO is the display this event is for.
7338 EVENT is the X event to filter.
7340 Returns non-zero if the event was filtered, caller shall not process
7341 this event further.
7342 Returns zero if event is wasn't filtered. */
7344 #ifdef HAVE_X_I18N
7345 static int
7346 x_filter_event (struct x_display_info *dpyinfo, XEvent *event)
7348 /* XFilterEvent returns non-zero if the input method has
7349 consumed the event. We pass the frame's X window to
7350 XFilterEvent because that's the one for which the IC
7351 was created. */
7353 struct frame *f1 = x_any_window_to_frame (dpyinfo,
7354 event->xclient.window);
7356 return XFilterEvent (event, f1 ? FRAME_X_WINDOW (f1) : None);
7358 #endif
7360 #ifdef USE_GTK
7361 static int current_count;
7362 static int current_finish;
7363 static struct input_event *current_hold_quit;
7365 /* This is the filter function invoked by the GTK event loop.
7366 It is invoked before the XEvent is translated to a GdkEvent,
7367 so we have a chance to act on the event before GTK. */
7368 static GdkFilterReturn
7369 event_handler_gdk (GdkXEvent *gxev, GdkEvent *ev, gpointer data)
7371 XEvent *xev = (XEvent *) gxev;
7373 block_input ();
7374 if (current_count >= 0)
7376 struct x_display_info *dpyinfo;
7378 dpyinfo = x_display_info_for_display (xev->xany.display);
7380 #ifdef HAVE_X_I18N
7381 /* Filter events for the current X input method.
7382 GTK calls XFilterEvent but not for key press and release,
7383 so we do it here. */
7384 if ((xev->type == KeyPress || xev->type == KeyRelease)
7385 && dpyinfo
7386 && x_filter_event (dpyinfo, xev))
7388 unblock_input ();
7389 return GDK_FILTER_REMOVE;
7391 #endif
7393 if (! dpyinfo)
7394 current_finish = X_EVENT_NORMAL;
7395 else
7396 current_count
7397 += handle_one_xevent (dpyinfo, xev, &current_finish,
7398 current_hold_quit);
7400 else
7401 current_finish = x_dispatch_event (xev, xev->xany.display);
7403 unblock_input ();
7405 if (current_finish == X_EVENT_GOTO_OUT || current_finish == X_EVENT_DROP)
7406 return GDK_FILTER_REMOVE;
7408 return GDK_FILTER_CONTINUE;
7410 #endif /* USE_GTK */
7413 static void xembed_send_message (struct frame *f, Time,
7414 enum xembed_message,
7415 long detail, long data1, long data2);
7417 static void
7418 x_net_wm_state (struct frame *f, Window window)
7420 int value = FULLSCREEN_NONE;
7421 Lisp_Object lval = Qnil;
7422 bool sticky = false;
7424 get_current_wm_state (f, window, &value, &sticky);
7426 switch (value)
7428 case FULLSCREEN_WIDTH:
7429 lval = Qfullwidth;
7430 break;
7431 case FULLSCREEN_HEIGHT:
7432 lval = Qfullheight;
7433 break;
7434 case FULLSCREEN_BOTH:
7435 lval = Qfullboth;
7436 break;
7437 case FULLSCREEN_MAXIMIZED:
7438 lval = Qmaximized;
7439 break;
7442 frame_size_history_add
7443 (f, Qx_net_wm_state, 0, 0,
7444 list2 (get_frame_param (f, Qfullscreen), lval));
7446 store_frame_param (f, Qfullscreen, lval);
7447 /** store_frame_param (f, Qsticky, sticky ? Qt : Qnil); **/
7450 /* Handles the XEvent EVENT on display DPYINFO.
7452 *FINISH is X_EVENT_GOTO_OUT if caller should stop reading events.
7453 *FINISH is zero if caller should continue reading events.
7454 *FINISH is X_EVENT_DROP if event should not be passed to the toolkit.
7455 *EVENT is unchanged unless we're processing KeyPress event.
7457 We return the number of characters stored into the buffer. */
7459 static int
7460 handle_one_xevent (struct x_display_info *dpyinfo,
7461 const XEvent *event,
7462 int *finish, struct input_event *hold_quit)
7464 union buffered_input_event inev;
7465 int count = 0;
7466 int do_help = 0;
7467 ptrdiff_t nbytes = 0;
7468 struct frame *any, *f = NULL;
7469 struct coding_system coding;
7470 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
7471 /* This holds the state XLookupString needs to implement dead keys
7472 and other tricks known as "compose processing". _X Window System_
7473 says that a portable program can't use this, but Stephen Gildea assures
7474 me that letting the compiler initialize it to zeros will work okay. */
7475 static XComposeStatus compose_status;
7476 XEvent configureEvent;
7477 XEvent next_event;
7479 USE_SAFE_ALLOCA;
7481 *finish = X_EVENT_NORMAL;
7483 EVENT_INIT (inev.ie);
7484 inev.ie.kind = NO_EVENT;
7485 inev.ie.arg = Qnil;
7487 any = x_any_window_to_frame (dpyinfo, event->xany.window);
7489 if (any && any->wait_event_type == event->type)
7490 any->wait_event_type = 0; /* Indicates we got it. */
7492 switch (event->type)
7494 case ClientMessage:
7496 if (event->xclient.message_type == dpyinfo->Xatom_wm_protocols
7497 && event->xclient.format == 32)
7499 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_take_focus)
7501 /* Use the value returned by x_any_window_to_frame
7502 because this could be the shell widget window
7503 if the frame has no title bar. */
7504 f = any;
7505 #ifdef HAVE_X_I18N
7506 /* Not quite sure this is needed -pd */
7507 if (f && FRAME_XIC (f))
7508 XSetICFocus (FRAME_XIC (f));
7509 #endif
7510 #if false
7511 /* Emacs sets WM hints whose `input' field is `true'. This
7512 instructs the WM to set the input focus automatically for
7513 Emacs with a call to XSetInputFocus. Setting WM_TAKE_FOCUS
7514 tells the WM to send us a ClientMessage WM_TAKE_FOCUS after
7515 it has set the focus. So, XSetInputFocus below is not
7516 needed.
7518 The call to XSetInputFocus below has also caused trouble. In
7519 cases where the XSetInputFocus done by the WM and the one
7520 below are temporally close (on a fast machine), the call
7521 below can generate additional FocusIn events which confuse
7522 Emacs. */
7524 /* Since we set WM_TAKE_FOCUS, we must call
7525 XSetInputFocus explicitly. But not if f is null,
7526 since that might be an event for a deleted frame. */
7527 if (f)
7529 Display *d = event->xclient.display;
7530 /* Catch and ignore errors, in case window has been
7531 iconified by a window manager such as GWM. */
7532 x_catch_errors (d);
7533 XSetInputFocus (d, event->xclient.window,
7534 /* The ICCCM says this is
7535 the only valid choice. */
7536 RevertToParent,
7537 event->xclient.data.l[1]);
7538 x_uncatch_errors ();
7540 /* Not certain about handling scroll bars here */
7541 #endif
7542 goto done;
7545 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_save_yourself)
7547 /* Save state modify the WM_COMMAND property to
7548 something which can reinstate us. This notifies
7549 the session manager, who's looking for such a
7550 PropertyNotify. Can restart processing when
7551 a keyboard or mouse event arrives. */
7552 /* If we have a session manager, don't set this.
7553 KDE will then start two Emacsen, one for the
7554 session manager and one for this. */
7555 #ifdef HAVE_X_SM
7556 if (! x_session_have_connection ())
7557 #endif
7559 f = x_top_window_to_frame (dpyinfo,
7560 event->xclient.window);
7561 /* This is just so we only give real data once
7562 for a single Emacs process. */
7563 if (f == SELECTED_FRAME ())
7564 XSetCommand (FRAME_X_DISPLAY (f),
7565 event->xclient.window,
7566 initial_argv, initial_argc);
7567 else if (f)
7568 XSetCommand (FRAME_X_DISPLAY (f),
7569 event->xclient.window,
7570 0, 0);
7572 goto done;
7575 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_delete_window)
7577 f = any;
7578 if (!f)
7579 goto OTHER; /* May be a dialog that is to be removed */
7581 inev.ie.kind = DELETE_WINDOW_EVENT;
7582 XSETFRAME (inev.ie.frame_or_window, f);
7583 goto done;
7586 goto done;
7589 if (event->xclient.message_type == dpyinfo->Xatom_wm_configure_denied)
7590 goto done;
7592 if (event->xclient.message_type == dpyinfo->Xatom_wm_window_moved)
7594 int new_x, new_y;
7595 f = x_window_to_frame (dpyinfo, event->xclient.window);
7597 new_x = event->xclient.data.s[0];
7598 new_y = event->xclient.data.s[1];
7600 if (f)
7602 f->left_pos = new_x;
7603 f->top_pos = new_y;
7605 goto done;
7608 #ifdef HACK_EDITRES
7609 if (event->xclient.message_type == dpyinfo->Xatom_editres)
7611 f = any;
7612 if (f)
7613 _XEditResCheckMessages (f->output_data.x->widget,
7614 NULL, (XEvent *) event, NULL);
7615 goto done;
7617 #endif /* HACK_EDITRES */
7619 if (event->xclient.message_type == dpyinfo->Xatom_DONE
7620 || event->xclient.message_type == dpyinfo->Xatom_PAGE)
7622 /* Ghostview job completed. Kill it. We could
7623 reply with "Next" if we received "Page", but we
7624 currently never do because we are interested in
7625 images, only, which should have 1 page. */
7626 Pixmap pixmap = (Pixmap) event->xclient.data.l[1];
7627 f = x_window_to_frame (dpyinfo, event->xclient.window);
7628 if (!f)
7629 goto OTHER;
7630 x_kill_gs_process (pixmap, f);
7631 expose_frame (f, 0, 0, 0, 0);
7632 goto done;
7635 #ifdef USE_TOOLKIT_SCROLL_BARS
7636 /* Scroll bar callbacks send a ClientMessage from which
7637 we construct an input_event. */
7638 if (event->xclient.message_type == dpyinfo->Xatom_Scrollbar)
7640 x_scroll_bar_to_input_event (event, &inev.ie);
7641 *finish = X_EVENT_GOTO_OUT;
7642 goto done;
7644 else if (event->xclient.message_type == dpyinfo->Xatom_Horizontal_Scrollbar)
7646 x_horizontal_scroll_bar_to_input_event (event, &inev.ie);
7647 *finish = X_EVENT_GOTO_OUT;
7648 goto done;
7650 #endif /* USE_TOOLKIT_SCROLL_BARS */
7652 /* XEmbed messages from the embedder (if any). */
7653 if (event->xclient.message_type == dpyinfo->Xatom_XEMBED)
7655 enum xembed_message msg = event->xclient.data.l[1];
7656 if (msg == XEMBED_FOCUS_IN || msg == XEMBED_FOCUS_OUT)
7657 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
7659 *finish = X_EVENT_GOTO_OUT;
7660 goto done;
7663 xft_settings_event (dpyinfo, event);
7665 f = any;
7666 if (!f)
7667 goto OTHER;
7668 if (x_handle_dnd_message (f, &event->xclient, dpyinfo, &inev.ie))
7669 *finish = X_EVENT_DROP;
7671 break;
7673 case SelectionNotify:
7674 x_display_set_last_user_time (dpyinfo, event->xselection.time);
7675 #ifdef USE_X_TOOLKIT
7676 if (! x_window_to_frame (dpyinfo, event->xselection.requestor))
7677 goto OTHER;
7678 #endif /* not USE_X_TOOLKIT */
7679 x_handle_selection_notify (&event->xselection);
7680 break;
7682 case SelectionClear: /* Someone has grabbed ownership. */
7683 x_display_set_last_user_time (dpyinfo, event->xselectionclear.time);
7684 #ifdef USE_X_TOOLKIT
7685 if (! x_window_to_frame (dpyinfo, event->xselectionclear.window))
7686 goto OTHER;
7687 #endif /* USE_X_TOOLKIT */
7689 const XSelectionClearEvent *eventp = &event->xselectionclear;
7691 inev.sie.kind = SELECTION_CLEAR_EVENT;
7692 SELECTION_EVENT_DPYINFO (&inev.sie) = dpyinfo;
7693 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
7694 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
7696 break;
7698 case SelectionRequest: /* Someone wants our selection. */
7699 x_display_set_last_user_time (dpyinfo, event->xselectionrequest.time);
7700 #ifdef USE_X_TOOLKIT
7701 if (!x_window_to_frame (dpyinfo, event->xselectionrequest.owner))
7702 goto OTHER;
7703 #endif /* USE_X_TOOLKIT */
7705 const XSelectionRequestEvent *eventp = &event->xselectionrequest;
7707 inev.sie.kind = SELECTION_REQUEST_EVENT;
7708 SELECTION_EVENT_DPYINFO (&inev.sie) = dpyinfo;
7709 SELECTION_EVENT_REQUESTOR (&inev.sie) = eventp->requestor;
7710 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
7711 SELECTION_EVENT_TARGET (&inev.sie) = eventp->target;
7712 SELECTION_EVENT_PROPERTY (&inev.sie) = eventp->property;
7713 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
7715 break;
7717 case PropertyNotify:
7718 x_display_set_last_user_time (dpyinfo, event->xproperty.time);
7719 f = x_top_window_to_frame (dpyinfo, event->xproperty.window);
7720 if (f && event->xproperty.atom == dpyinfo->Xatom_net_wm_state)
7722 bool not_hidden = x_handle_net_wm_state (f, &event->xproperty);
7723 if (not_hidden && FRAME_ICONIFIED_P (f))
7725 /* Gnome shell does not iconify us when C-z is pressed.
7726 It hides the frame. So if our state says we aren't
7727 hidden anymore, treat it as deiconified. */
7728 SET_FRAME_VISIBLE (f, 1);
7729 SET_FRAME_ICONIFIED (f, false);
7730 f->output_data.x->has_been_visible = true;
7731 inev.ie.kind = DEICONIFY_EVENT;
7732 XSETFRAME (inev.ie.frame_or_window, f);
7734 else if (! not_hidden && ! FRAME_ICONIFIED_P (f))
7736 SET_FRAME_VISIBLE (f, 0);
7737 SET_FRAME_ICONIFIED (f, true);
7738 inev.ie.kind = ICONIFY_EVENT;
7739 XSETFRAME (inev.ie.frame_or_window, f);
7743 x_handle_property_notify (&event->xproperty);
7744 xft_settings_event (dpyinfo, event);
7745 goto OTHER;
7747 case ReparentNotify:
7748 f = x_top_window_to_frame (dpyinfo, event->xreparent.window);
7749 if (f)
7751 f->output_data.x->parent_desc = event->xreparent.parent;
7752 x_real_positions (f, &f->left_pos, &f->top_pos);
7754 /* Perhaps reparented due to a WM restart. Reset this. */
7755 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_UNKNOWN;
7756 FRAME_DISPLAY_INFO (f)->net_supported_window = 0;
7758 x_set_frame_alpha (f);
7760 goto OTHER;
7762 case Expose:
7763 f = x_window_to_frame (dpyinfo, event->xexpose.window);
7764 if (f)
7766 if (!FRAME_VISIBLE_P (f))
7768 SET_FRAME_VISIBLE (f, 1);
7769 SET_FRAME_ICONIFIED (f, false);
7770 f->output_data.x->has_been_visible = true;
7771 SET_FRAME_GARBAGED (f);
7773 else
7775 #ifdef USE_GTK
7776 /* This seems to be needed for GTK 2.6 and later, see
7777 http://debbugs.gnu.org/cgi/bugreport.cgi?bug=15398. */
7778 x_clear_area (f,
7779 event->xexpose.x, event->xexpose.y,
7780 event->xexpose.width, event->xexpose.height);
7781 #endif
7782 expose_frame (f, event->xexpose.x, event->xexpose.y,
7783 event->xexpose.width, event->xexpose.height);
7786 else
7788 #ifndef USE_TOOLKIT_SCROLL_BARS
7789 struct scroll_bar *bar;
7790 #endif
7791 #if defined USE_LUCID
7792 /* Submenus of the Lucid menu bar aren't widgets
7793 themselves, so there's no way to dispatch events
7794 to them. Recognize this case separately. */
7796 Widget widget = x_window_to_menu_bar (event->xexpose.window);
7797 if (widget)
7798 xlwmenu_redisplay (widget);
7800 #endif /* USE_LUCID */
7802 #ifdef USE_TOOLKIT_SCROLL_BARS
7803 /* Dispatch event to the widget. */
7804 goto OTHER;
7805 #else /* not USE_TOOLKIT_SCROLL_BARS */
7806 bar = x_window_to_scroll_bar (event->xexpose.display,
7807 event->xexpose.window, 2);
7809 if (bar)
7810 x_scroll_bar_expose (bar, event);
7811 #ifdef USE_X_TOOLKIT
7812 else
7813 goto OTHER;
7814 #endif /* USE_X_TOOLKIT */
7815 #endif /* not USE_TOOLKIT_SCROLL_BARS */
7817 break;
7819 case GraphicsExpose: /* This occurs when an XCopyArea's
7820 source area was obscured or not
7821 available. */
7822 f = x_window_to_frame (dpyinfo, event->xgraphicsexpose.drawable);
7823 if (f)
7824 expose_frame (f, event->xgraphicsexpose.x,
7825 event->xgraphicsexpose.y,
7826 event->xgraphicsexpose.width,
7827 event->xgraphicsexpose.height);
7828 #ifdef USE_X_TOOLKIT
7829 else
7830 goto OTHER;
7831 #endif /* USE_X_TOOLKIT */
7832 break;
7834 case NoExpose: /* This occurs when an XCopyArea's
7835 source area was completely
7836 available. */
7837 break;
7839 case UnmapNotify:
7840 /* Redo the mouse-highlight after the tooltip has gone. */
7841 if (event->xunmap.window == tip_window)
7843 tip_window = 0;
7844 x_redo_mouse_highlight (dpyinfo);
7847 f = x_top_window_to_frame (dpyinfo, event->xunmap.window);
7848 if (f) /* F may no longer exist if
7849 the frame was deleted. */
7851 bool visible = FRAME_VISIBLE_P (f);
7852 /* While a frame is unmapped, display generation is
7853 disabled; you don't want to spend time updating a
7854 display that won't ever be seen. */
7855 SET_FRAME_VISIBLE (f, 0);
7856 /* We can't distinguish, from the event, whether the window
7857 has become iconified or invisible. So assume, if it
7858 was previously visible, than now it is iconified.
7859 But x_make_frame_invisible clears both
7860 the visible flag and the iconified flag;
7861 and that way, we know the window is not iconified now. */
7862 if (visible || FRAME_ICONIFIED_P (f))
7864 SET_FRAME_ICONIFIED (f, true);
7865 inev.ie.kind = ICONIFY_EVENT;
7866 XSETFRAME (inev.ie.frame_or_window, f);
7869 goto OTHER;
7871 case MapNotify:
7872 /* We use x_top_window_to_frame because map events can
7873 come for sub-windows and they don't mean that the
7874 frame is visible. */
7875 f = x_top_window_to_frame (dpyinfo, event->xmap.window);
7876 if (f)
7878 bool iconified = FRAME_ICONIFIED_P (f);
7880 /* Check if fullscreen was specified before we where mapped the
7881 first time, i.e. from the command line. */
7882 if (!f->output_data.x->has_been_visible)
7883 x_check_fullscreen (f);
7885 SET_FRAME_VISIBLE (f, 1);
7886 SET_FRAME_ICONIFIED (f, false);
7887 f->output_data.x->has_been_visible = true;
7889 if (iconified)
7891 inev.ie.kind = DEICONIFY_EVENT;
7892 XSETFRAME (inev.ie.frame_or_window, f);
7894 else if (! NILP (Vframe_list) && ! NILP (XCDR (Vframe_list)))
7895 /* Force a redisplay sooner or later to update the
7896 frame titles in case this is the second frame. */
7897 record_asynch_buffer_change ();
7899 #ifdef USE_GTK
7900 /* xg_frame_resized does the wrong thing with Gtk+ 3.20.3 or later.
7901 For earlier Gtk+ versions it is unclear whether
7902 xg_frame_resized is useful, so leave it in for now.
7903 See Bug#23144. */
7904 # if ! GTK_CHECK_VERSION (3, 20, 3)
7905 xg_frame_resized (f, -1, -1);
7906 # endif
7907 #endif
7909 goto OTHER;
7911 case KeyPress:
7913 x_display_set_last_user_time (dpyinfo, event->xkey.time);
7914 ignore_next_mouse_click_timeout = 0;
7916 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
7917 /* Dispatch KeyPress events when in menu. */
7918 if (popup_activated ())
7919 goto OTHER;
7920 #endif
7922 f = any;
7924 /* If mouse-highlight is an integer, input clears out
7925 mouse highlighting. */
7926 if (!hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight)
7927 #if ! defined (USE_GTK)
7928 && (f == 0
7929 || !EQ (f->tool_bar_window, hlinfo->mouse_face_window))
7930 #endif
7933 clear_mouse_face (hlinfo);
7934 hlinfo->mouse_face_hidden = true;
7937 #if defined USE_MOTIF && defined USE_TOOLKIT_SCROLL_BARS
7938 if (f == 0)
7940 /* Scroll bars consume key events, but we want
7941 the keys to go to the scroll bar's frame. */
7942 Widget widget = XtWindowToWidget (dpyinfo->display,
7943 event->xkey.window);
7944 if (widget && XmIsScrollBar (widget))
7946 widget = XtParent (widget);
7947 f = x_any_window_to_frame (dpyinfo, XtWindow (widget));
7950 #endif /* USE_MOTIF and USE_TOOLKIT_SCROLL_BARS */
7952 if (f != 0)
7954 KeySym keysym, orig_keysym;
7955 /* al%imercury@uunet.uu.net says that making this 81
7956 instead of 80 fixed a bug whereby meta chars made
7957 his Emacs hang.
7959 It seems that some version of XmbLookupString has
7960 a bug of not returning XBufferOverflow in
7961 status_return even if the input is too long to
7962 fit in 81 bytes. So, we must prepare sufficient
7963 bytes for copy_buffer. 513 bytes (256 chars for
7964 two-byte character set) seems to be a fairly good
7965 approximation. -- 2000.8.10 handa@etl.go.jp */
7966 unsigned char copy_buffer[513];
7967 unsigned char *copy_bufptr = copy_buffer;
7968 int copy_bufsiz = sizeof (copy_buffer);
7969 int modifiers;
7970 Lisp_Object coding_system = Qlatin_1;
7971 Lisp_Object c;
7972 /* Event will be modified. */
7973 XKeyEvent xkey = event->xkey;
7975 #ifdef USE_GTK
7976 /* Don't pass keys to GTK. A Tab will shift focus to the
7977 tool bar in GTK 2.4. Keys will still go to menus and
7978 dialogs because in that case popup_activated is nonzero
7979 (see above). */
7980 *finish = X_EVENT_DROP;
7981 #endif
7983 xkey.state |= x_emacs_to_x_modifiers (FRAME_DISPLAY_INFO (f),
7984 extra_keyboard_modifiers);
7985 modifiers = xkey.state;
7987 /* This will have to go some day... */
7989 /* make_lispy_event turns chars into control chars.
7990 Don't do it here because XLookupString is too eager. */
7991 xkey.state &= ~ControlMask;
7992 xkey.state &= ~(dpyinfo->meta_mod_mask
7993 | dpyinfo->super_mod_mask
7994 | dpyinfo->hyper_mod_mask
7995 | dpyinfo->alt_mod_mask);
7997 /* In case Meta is ComposeCharacter,
7998 clear its status. According to Markus Ehrnsperger
7999 Markus.Ehrnsperger@lehrstuhl-bross.physik.uni-muenchen.de
8000 this enables ComposeCharacter to work whether or
8001 not it is combined with Meta. */
8002 if (modifiers & dpyinfo->meta_mod_mask)
8003 memset (&compose_status, 0, sizeof (compose_status));
8005 #ifdef HAVE_X_I18N
8006 if (FRAME_XIC (f))
8008 Status status_return;
8010 coding_system = Vlocale_coding_system;
8011 nbytes = XmbLookupString (FRAME_XIC (f),
8012 &xkey, (char *) copy_bufptr,
8013 copy_bufsiz, &keysym,
8014 &status_return);
8015 if (status_return == XBufferOverflow)
8017 copy_bufsiz = nbytes + 1;
8018 copy_bufptr = alloca (copy_bufsiz);
8019 nbytes = XmbLookupString (FRAME_XIC (f),
8020 &xkey, (char *) copy_bufptr,
8021 copy_bufsiz, &keysym,
8022 &status_return);
8024 /* Xutf8LookupString is a new but already deprecated interface. -stef */
8025 if (status_return == XLookupNone)
8026 break;
8027 else if (status_return == XLookupChars)
8029 keysym = NoSymbol;
8030 modifiers = 0;
8032 else if (status_return != XLookupKeySym
8033 && status_return != XLookupBoth)
8034 emacs_abort ();
8036 else
8037 nbytes = XLookupString (&xkey, (char *) copy_bufptr,
8038 copy_bufsiz, &keysym,
8039 &compose_status);
8040 #else
8041 nbytes = XLookupString (&xkey, (char *) copy_bufptr,
8042 copy_bufsiz, &keysym,
8043 &compose_status);
8044 #endif
8046 /* If not using XIM/XIC, and a compose sequence is in progress,
8047 we break here. Otherwise, chars_matched is always 0. */
8048 if (compose_status.chars_matched > 0 && nbytes == 0)
8049 break;
8051 memset (&compose_status, 0, sizeof (compose_status));
8052 orig_keysym = keysym;
8054 /* Common for all keysym input events. */
8055 XSETFRAME (inev.ie.frame_or_window, f);
8056 inev.ie.modifiers
8057 = x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO (f), modifiers);
8058 inev.ie.timestamp = xkey.time;
8060 /* First deal with keysyms which have defined
8061 translations to characters. */
8062 if (keysym >= 32 && keysym < 128)
8063 /* Avoid explicitly decoding each ASCII character. */
8065 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
8066 inev.ie.code = keysym;
8067 goto done_keysym;
8070 /* Keysyms directly mapped to Unicode characters. */
8071 if (keysym >= 0x01000000 && keysym <= 0x0110FFFF)
8073 if (keysym < 0x01000080)
8074 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
8075 else
8076 inev.ie.kind = MULTIBYTE_CHAR_KEYSTROKE_EVENT;
8077 inev.ie.code = keysym & 0xFFFFFF;
8078 goto done_keysym;
8081 /* Now non-ASCII. */
8082 if (HASH_TABLE_P (Vx_keysym_table)
8083 && (c = Fgethash (make_number (keysym),
8084 Vx_keysym_table,
8085 Qnil),
8086 NATNUMP (c)))
8088 inev.ie.kind = (SINGLE_BYTE_CHAR_P (XFASTINT (c))
8089 ? ASCII_KEYSTROKE_EVENT
8090 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
8091 inev.ie.code = XFASTINT (c);
8092 goto done_keysym;
8095 /* Random non-modifier sorts of keysyms. */
8096 if (((keysym >= XK_BackSpace && keysym <= XK_Escape)
8097 || keysym == XK_Delete
8098 #ifdef XK_ISO_Left_Tab
8099 || (keysym >= XK_ISO_Left_Tab
8100 && keysym <= XK_ISO_Enter)
8101 #endif
8102 || IsCursorKey (keysym) /* 0xff50 <= x < 0xff60 */
8103 || IsMiscFunctionKey (keysym) /* 0xff60 <= x < VARIES */
8104 #ifdef HPUX
8105 /* This recognizes the "extended function
8106 keys". It seems there's no cleaner way.
8107 Test IsModifierKey to avoid handling
8108 mode_switch incorrectly. */
8109 || (XK_Select <= keysym && keysym < XK_KP_Space)
8110 #endif
8111 #ifdef XK_dead_circumflex
8112 || orig_keysym == XK_dead_circumflex
8113 #endif
8114 #ifdef XK_dead_grave
8115 || orig_keysym == XK_dead_grave
8116 #endif
8117 #ifdef XK_dead_tilde
8118 || orig_keysym == XK_dead_tilde
8119 #endif
8120 #ifdef XK_dead_diaeresis
8121 || orig_keysym == XK_dead_diaeresis
8122 #endif
8123 #ifdef XK_dead_macron
8124 || orig_keysym == XK_dead_macron
8125 #endif
8126 #ifdef XK_dead_degree
8127 || orig_keysym == XK_dead_degree
8128 #endif
8129 #ifdef XK_dead_acute
8130 || orig_keysym == XK_dead_acute
8131 #endif
8132 #ifdef XK_dead_cedilla
8133 || orig_keysym == XK_dead_cedilla
8134 #endif
8135 #ifdef XK_dead_breve
8136 || orig_keysym == XK_dead_breve
8137 #endif
8138 #ifdef XK_dead_ogonek
8139 || orig_keysym == XK_dead_ogonek
8140 #endif
8141 #ifdef XK_dead_caron
8142 || orig_keysym == XK_dead_caron
8143 #endif
8144 #ifdef XK_dead_doubleacute
8145 || orig_keysym == XK_dead_doubleacute
8146 #endif
8147 #ifdef XK_dead_abovedot
8148 || orig_keysym == XK_dead_abovedot
8149 #endif
8150 || IsKeypadKey (keysym) /* 0xff80 <= x < 0xffbe */
8151 || IsFunctionKey (keysym) /* 0xffbe <= x < 0xffe1 */
8152 /* Any "vendor-specific" key is ok. */
8153 || (orig_keysym & (1 << 28))
8154 || (keysym != NoSymbol && nbytes == 0))
8155 && ! (IsModifierKey (orig_keysym)
8156 /* The symbols from XK_ISO_Lock
8157 to XK_ISO_Last_Group_Lock
8158 don't have real modifiers but
8159 should be treated similarly to
8160 Mode_switch by Emacs. */
8161 #if defined XK_ISO_Lock && defined XK_ISO_Last_Group_Lock
8162 || (XK_ISO_Lock <= orig_keysym
8163 && orig_keysym <= XK_ISO_Last_Group_Lock)
8164 #endif
8167 STORE_KEYSYM_FOR_DEBUG (keysym);
8168 /* make_lispy_event will convert this to a symbolic
8169 key. */
8170 inev.ie.kind = NON_ASCII_KEYSTROKE_EVENT;
8171 inev.ie.code = keysym;
8172 goto done_keysym;
8175 { /* Raw bytes, not keysym. */
8176 ptrdiff_t i;
8177 int nchars, len;
8179 for (i = 0, nchars = 0; i < nbytes; i++)
8181 if (ASCII_CHAR_P (copy_bufptr[i]))
8182 nchars++;
8183 STORE_KEYSYM_FOR_DEBUG (copy_bufptr[i]);
8186 if (nchars < nbytes)
8188 /* Decode the input data. */
8190 /* The input should be decoded with `coding_system'
8191 which depends on which X*LookupString function
8192 we used just above and the locale. */
8193 setup_coding_system (coding_system, &coding);
8194 coding.src_multibyte = false;
8195 coding.dst_multibyte = true;
8196 /* The input is converted to events, thus we can't
8197 handle composition. Anyway, there's no XIM that
8198 gives us composition information. */
8199 coding.common_flags &= ~CODING_ANNOTATION_MASK;
8201 SAFE_NALLOCA (coding.destination, MAX_MULTIBYTE_LENGTH,
8202 nbytes);
8203 coding.dst_bytes = MAX_MULTIBYTE_LENGTH * nbytes;
8204 coding.mode |= CODING_MODE_LAST_BLOCK;
8205 decode_coding_c_string (&coding, copy_bufptr, nbytes, Qnil);
8206 nbytes = coding.produced;
8207 nchars = coding.produced_char;
8208 copy_bufptr = coding.destination;
8211 /* Convert the input data to a sequence of
8212 character events. */
8213 for (i = 0; i < nbytes; i += len)
8215 int ch;
8216 if (nchars == nbytes)
8217 ch = copy_bufptr[i], len = 1;
8218 else
8219 ch = STRING_CHAR_AND_LENGTH (copy_bufptr + i, len);
8220 inev.ie.kind = (SINGLE_BYTE_CHAR_P (ch)
8221 ? ASCII_KEYSTROKE_EVENT
8222 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
8223 inev.ie.code = ch;
8224 kbd_buffer_store_buffered_event (&inev, hold_quit);
8227 count += nchars;
8229 inev.ie.kind = NO_EVENT; /* Already stored above. */
8231 if (keysym == NoSymbol)
8232 break;
8234 /* FIXME: check side effects and remove this. */
8235 ((XEvent *) event)->xkey = xkey;
8237 done_keysym:
8238 #ifdef HAVE_X_I18N
8239 /* Don't dispatch this event since XtDispatchEvent calls
8240 XFilterEvent, and two calls in a row may freeze the
8241 client. */
8242 break;
8243 #else
8244 goto OTHER;
8245 #endif
8247 case KeyRelease:
8248 x_display_set_last_user_time (dpyinfo, event->xkey.time);
8249 #ifdef HAVE_X_I18N
8250 /* Don't dispatch this event since XtDispatchEvent calls
8251 XFilterEvent, and two calls in a row may freeze the
8252 client. */
8253 break;
8254 #else
8255 goto OTHER;
8256 #endif
8258 case EnterNotify:
8259 x_display_set_last_user_time (dpyinfo, event->xcrossing.time);
8260 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
8262 f = any;
8264 if (f && x_mouse_click_focus_ignore_position)
8265 ignore_next_mouse_click_timeout = event->xmotion.time + 200;
8267 /* EnterNotify counts as mouse movement,
8268 so update things that depend on mouse position. */
8269 if (f && !f->output_data.x->hourglass_p)
8270 note_mouse_movement (f, &event->xmotion);
8271 #ifdef USE_GTK
8272 /* We may get an EnterNotify on the buttons in the toolbar. In that
8273 case we moved out of any highlighted area and need to note this. */
8274 if (!f && dpyinfo->last_mouse_glyph_frame)
8275 note_mouse_movement (dpyinfo->last_mouse_glyph_frame, &event->xmotion);
8276 #endif
8277 goto OTHER;
8279 case FocusIn:
8280 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
8281 goto OTHER;
8283 case LeaveNotify:
8284 x_display_set_last_user_time (dpyinfo, event->xcrossing.time);
8285 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
8287 f = x_top_window_to_frame (dpyinfo, event->xcrossing.window);
8288 if (f)
8290 if (f == hlinfo->mouse_face_mouse_frame)
8292 /* If we move outside the frame, then we're
8293 certainly no longer on any text in the frame. */
8294 clear_mouse_face (hlinfo);
8295 hlinfo->mouse_face_mouse_frame = 0;
8298 /* Generate a nil HELP_EVENT to cancel a help-echo.
8299 Do it only if there's something to cancel.
8300 Otherwise, the startup message is cleared when
8301 the mouse leaves the frame. */
8302 if (any_help_event_p)
8303 do_help = -1;
8305 #ifdef USE_GTK
8306 /* See comment in EnterNotify above */
8307 else if (dpyinfo->last_mouse_glyph_frame)
8308 note_mouse_movement (dpyinfo->last_mouse_glyph_frame, &event->xmotion);
8309 #endif
8310 goto OTHER;
8312 case FocusOut:
8313 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
8314 goto OTHER;
8316 case MotionNotify:
8318 x_display_set_last_user_time (dpyinfo, event->xmotion.time);
8319 previous_help_echo_string = help_echo_string;
8320 help_echo_string = Qnil;
8322 f = (x_mouse_grabbed (dpyinfo) ? dpyinfo->last_mouse_frame
8323 : x_window_to_frame (dpyinfo, event->xmotion.window));
8325 if (hlinfo->mouse_face_hidden)
8327 hlinfo->mouse_face_hidden = false;
8328 clear_mouse_face (hlinfo);
8331 #ifdef USE_GTK
8332 if (f && xg_event_is_for_scrollbar (f, event))
8333 f = 0;
8334 #endif
8335 if (f)
8338 /* Generate SELECT_WINDOW_EVENTs when needed.
8339 Don't let popup menus influence things (bug#1261). */
8340 if (!NILP (Vmouse_autoselect_window) && !popup_activated ())
8342 static Lisp_Object last_mouse_window;
8343 Lisp_Object window = window_from_coordinates
8344 (f, event->xmotion.x, event->xmotion.y, 0, false);
8346 /* Window will be selected only when it is not selected now and
8347 last mouse movement event was not in it. Minibuffer window
8348 will be selected only when it is active. */
8349 if (WINDOWP (window)
8350 && !EQ (window, last_mouse_window)
8351 && !EQ (window, selected_window)
8352 /* For click-to-focus window managers
8353 create event iff we don't leave the
8354 selected frame. */
8355 && (focus_follows_mouse
8356 || (EQ (XWINDOW (window)->frame,
8357 XWINDOW (selected_window)->frame))))
8359 inev.ie.kind = SELECT_WINDOW_EVENT;
8360 inev.ie.frame_or_window = window;
8362 /* Remember the last window where we saw the mouse. */
8363 last_mouse_window = window;
8365 if (!note_mouse_movement (f, &event->xmotion))
8366 help_echo_string = previous_help_echo_string;
8368 else
8370 #ifndef USE_TOOLKIT_SCROLL_BARS
8371 struct scroll_bar *bar
8372 = x_window_to_scroll_bar (event->xmotion.display,
8373 event->xmotion.window, 2);
8375 if (bar)
8376 x_scroll_bar_note_movement (bar, &event->xmotion);
8377 #endif /* USE_TOOLKIT_SCROLL_BARS */
8379 /* If we move outside the frame, then we're
8380 certainly no longer on any text in the frame. */
8381 clear_mouse_face (hlinfo);
8384 /* If the contents of the global variable help_echo_string
8385 has changed, generate a HELP_EVENT. */
8386 if (!NILP (help_echo_string)
8387 || !NILP (previous_help_echo_string))
8388 do_help = 1;
8389 goto OTHER;
8392 case ConfigureNotify:
8393 /* An opaque move can generate a stream of events as the window
8394 is dragged around. If the connection round trip time isn't
8395 really short, they may come faster than we can respond to
8396 them, given the multiple queries we can do to check window
8397 manager state, translate coordinates, etc.
8399 So if this ConfigureNotify is immediately followed by another
8400 for the same window, use the info from the latest update, and
8401 consider the events all handled. */
8402 /* Opaque resize may be trickier; ConfigureNotify events are
8403 mixed with Expose events for multiple windows. */
8404 configureEvent = *event;
8405 while (XPending (dpyinfo->display))
8407 XNextEvent (dpyinfo->display, &next_event);
8408 if (next_event.type != ConfigureNotify
8409 || next_event.xconfigure.window != event->xconfigure.window
8410 /* Skipping events with different sizes can lead to a
8411 mispositioned mode line at initial window creation.
8412 Only drop window motion events for now. */
8413 || next_event.xconfigure.width != event->xconfigure.width
8414 || next_event.xconfigure.height != event->xconfigure.height)
8416 XPutBackEvent (dpyinfo->display, &next_event);
8417 break;
8419 else
8420 configureEvent = next_event;
8422 f = x_top_window_to_frame (dpyinfo, configureEvent.xconfigure.window);
8423 #ifdef USE_CAIRO
8424 if (f) x_cr_destroy_surface (f);
8425 #endif
8426 #ifdef USE_GTK
8427 if (!f
8428 && (f = any)
8429 && configureEvent.xconfigure.window == FRAME_X_WINDOW (f))
8431 xg_frame_resized (f, configureEvent.xconfigure.width,
8432 configureEvent.xconfigure.height);
8433 #ifdef USE_CAIRO
8434 x_cr_destroy_surface (f);
8435 #endif
8436 f = 0;
8438 #endif
8439 if (f)
8441 x_net_wm_state (f, configureEvent.xconfigure.window);
8443 #ifdef USE_X_TOOLKIT
8444 /* Tip frames are pure X window, set size for them. */
8445 if (! NILP (tip_frame) && XFRAME (tip_frame) == f)
8447 if (FRAME_PIXEL_HEIGHT (f) != configureEvent.xconfigure.height
8448 || FRAME_PIXEL_WIDTH (f) != configureEvent.xconfigure.width)
8449 SET_FRAME_GARBAGED (f);
8450 FRAME_PIXEL_HEIGHT (f) = configureEvent.xconfigure.height;
8451 FRAME_PIXEL_WIDTH (f) = configureEvent.xconfigure.width;
8453 #endif
8455 #ifndef USE_X_TOOLKIT
8456 #ifndef USE_GTK
8457 int width =
8458 FRAME_PIXEL_TO_TEXT_WIDTH (f, configureEvent.xconfigure.width);
8459 int height =
8460 FRAME_PIXEL_TO_TEXT_HEIGHT (f, configureEvent.xconfigure.height);
8462 /* In the toolkit version, change_frame_size
8463 is called by the code that handles resizing
8464 of the EmacsFrame widget. */
8466 /* Even if the number of character rows and columns has
8467 not changed, the font size may have changed, so we need
8468 to check the pixel dimensions as well. */
8469 if (width != FRAME_TEXT_WIDTH (f)
8470 || height != FRAME_TEXT_HEIGHT (f)
8471 || configureEvent.xconfigure.width != FRAME_PIXEL_WIDTH (f)
8472 || configureEvent.xconfigure.height != FRAME_PIXEL_HEIGHT (f))
8474 change_frame_size (f, width, height, false, true, false, true);
8475 x_clear_under_internal_border (f);
8476 SET_FRAME_GARBAGED (f);
8477 cancel_mouse_face (f);
8479 #endif /* not USE_GTK */
8480 #endif
8482 #ifdef USE_GTK
8483 /* GTK creates windows but doesn't map them.
8484 Only get real positions when mapped. */
8485 if (FRAME_GTK_OUTER_WIDGET (f)
8486 && gtk_widget_get_mapped (FRAME_GTK_OUTER_WIDGET (f)))
8487 #endif
8488 x_real_positions (f, &f->left_pos, &f->top_pos);
8490 #ifdef HAVE_X_I18N
8491 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMStatusArea))
8492 xic_set_statusarea (f);
8493 #endif
8496 goto OTHER;
8498 case ButtonRelease:
8499 case ButtonPress:
8501 /* If we decide we want to generate an event to be seen
8502 by the rest of Emacs, we put it here. */
8503 bool tool_bar_p = false;
8505 memset (&compose_status, 0, sizeof (compose_status));
8506 dpyinfo->last_mouse_glyph_frame = NULL;
8507 x_display_set_last_user_time (dpyinfo, event->xbutton.time);
8509 f = (x_mouse_grabbed (dpyinfo) ? dpyinfo->last_mouse_frame
8510 : x_window_to_frame (dpyinfo, event->xbutton.window));
8512 #ifdef USE_GTK
8513 if (f && xg_event_is_for_scrollbar (f, event))
8514 f = 0;
8515 #endif
8516 if (f)
8518 #if ! defined (USE_GTK)
8519 /* Is this in the tool-bar? */
8520 if (WINDOWP (f->tool_bar_window)
8521 && WINDOW_TOTAL_LINES (XWINDOW (f->tool_bar_window)))
8523 Lisp_Object window;
8524 int x = event->xbutton.x;
8525 int y = event->xbutton.y;
8527 window = window_from_coordinates (f, x, y, 0, true);
8528 tool_bar_p = EQ (window, f->tool_bar_window);
8530 if (tool_bar_p && event->xbutton.button < 4)
8531 handle_tool_bar_click
8532 (f, x, y, event->xbutton.type == ButtonPress,
8533 x_x_to_emacs_modifiers (dpyinfo, event->xbutton.state));
8535 #endif /* !USE_GTK */
8537 if (!tool_bar_p)
8538 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
8539 if (! popup_activated ())
8540 #endif
8542 if (ignore_next_mouse_click_timeout)
8544 if (event->type == ButtonPress
8545 && event->xbutton.time > ignore_next_mouse_click_timeout)
8547 ignore_next_mouse_click_timeout = 0;
8548 construct_mouse_click (&inev.ie, &event->xbutton, f);
8550 if (event->type == ButtonRelease)
8551 ignore_next_mouse_click_timeout = 0;
8553 else
8554 construct_mouse_click (&inev.ie, &event->xbutton, f);
8556 if (FRAME_X_EMBEDDED_P (f))
8557 xembed_send_message (f, event->xbutton.time,
8558 XEMBED_REQUEST_FOCUS, 0, 0, 0);
8560 else
8562 struct scroll_bar *bar
8563 = x_window_to_scroll_bar (event->xbutton.display,
8564 event->xbutton.window, 2);
8566 #ifdef USE_TOOLKIT_SCROLL_BARS
8567 /* Make the "Ctrl-Mouse-2 splits window" work for toolkit
8568 scroll bars. */
8569 if (bar && event->xbutton.state & ControlMask)
8571 x_scroll_bar_handle_click (bar, event, &inev.ie);
8572 *finish = X_EVENT_DROP;
8574 #else /* not USE_TOOLKIT_SCROLL_BARS */
8575 if (bar)
8576 x_scroll_bar_handle_click (bar, event, &inev.ie);
8577 #endif /* not USE_TOOLKIT_SCROLL_BARS */
8580 if (event->type == ButtonPress)
8582 dpyinfo->grabbed |= (1 << event->xbutton.button);
8583 dpyinfo->last_mouse_frame = f;
8584 #if ! defined (USE_GTK)
8585 if (f && !tool_bar_p)
8586 f->last_tool_bar_item = -1;
8587 #endif /* not USE_GTK */
8589 else
8590 dpyinfo->grabbed &= ~(1 << event->xbutton.button);
8592 /* Ignore any mouse motion that happened before this event;
8593 any subsequent mouse-movement Emacs events should reflect
8594 only motion after the ButtonPress/Release. */
8595 if (f != 0)
8596 f->mouse_moved = false;
8598 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
8599 f = x_menubar_window_to_frame (dpyinfo, event);
8600 /* For a down-event in the menu bar,
8601 don't pass it to Xt right now.
8602 Instead, save it away
8603 and we will pass it to Xt from kbd_buffer_get_event.
8604 That way, we can run some Lisp code first. */
8605 if (! popup_activated ()
8606 #ifdef USE_GTK
8607 /* Gtk+ menus only react to the first three buttons. */
8608 && event->xbutton.button < 3
8609 #endif
8610 && f && event->type == ButtonPress
8611 /* Verify the event is really within the menu bar
8612 and not just sent to it due to grabbing. */
8613 && event->xbutton.x >= 0
8614 && event->xbutton.x < FRAME_PIXEL_WIDTH (f)
8615 && event->xbutton.y >= 0
8616 && event->xbutton.y < FRAME_MENUBAR_HEIGHT (f)
8617 && event->xbutton.same_screen)
8619 if (!f->output_data.x->saved_menu_event)
8620 f->output_data.x->saved_menu_event = xmalloc (sizeof *event);
8621 *f->output_data.x->saved_menu_event = *event;
8622 inev.ie.kind = MENU_BAR_ACTIVATE_EVENT;
8623 XSETFRAME (inev.ie.frame_or_window, f);
8624 *finish = X_EVENT_DROP;
8626 else
8627 goto OTHER;
8628 #endif /* USE_X_TOOLKIT || USE_GTK */
8630 break;
8632 case CirculateNotify:
8633 goto OTHER;
8635 case CirculateRequest:
8636 goto OTHER;
8638 case VisibilityNotify:
8639 goto OTHER;
8641 case MappingNotify:
8642 /* Someone has changed the keyboard mapping - update the
8643 local cache. */
8644 switch (event->xmapping.request)
8646 case MappingModifier:
8647 x_find_modifier_meanings (dpyinfo);
8648 /* This is meant to fall through. */
8649 case MappingKeyboard:
8650 XRefreshKeyboardMapping ((XMappingEvent *) &event->xmapping);
8652 goto OTHER;
8654 case DestroyNotify:
8655 xft_settings_event (dpyinfo, event);
8656 break;
8658 default:
8659 OTHER:
8660 #ifdef USE_X_TOOLKIT
8661 block_input ();
8662 if (*finish != X_EVENT_DROP)
8663 XtDispatchEvent ((XEvent *) event);
8664 unblock_input ();
8665 #endif /* USE_X_TOOLKIT */
8666 break;
8669 done:
8670 if (inev.ie.kind != NO_EVENT)
8672 kbd_buffer_store_buffered_event (&inev, hold_quit);
8673 count++;
8676 if (do_help
8677 && !(hold_quit && hold_quit->kind != NO_EVENT))
8679 Lisp_Object frame;
8681 if (f)
8682 XSETFRAME (frame, f);
8683 else
8684 frame = Qnil;
8686 if (do_help > 0)
8688 any_help_event_p = true;
8689 gen_help_event (help_echo_string, frame, help_echo_window,
8690 help_echo_object, help_echo_pos);
8692 else
8694 help_echo_string = Qnil;
8695 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
8697 count++;
8700 SAFE_FREE ();
8701 return count;
8704 /* Handles the XEvent EVENT on display DISPLAY.
8705 This is used for event loops outside the normal event handling,
8706 i.e. looping while a popup menu or a dialog is posted.
8708 Returns the value handle_one_xevent sets in the finish argument. */
8710 x_dispatch_event (XEvent *event, Display *display)
8712 struct x_display_info *dpyinfo;
8713 int finish = X_EVENT_NORMAL;
8715 dpyinfo = x_display_info_for_display (display);
8717 if (dpyinfo)
8718 handle_one_xevent (dpyinfo, event, &finish, 0);
8720 return finish;
8723 /* Read events coming from the X server.
8724 Return as soon as there are no more events to be read.
8726 Return the number of characters stored into the buffer,
8727 thus pretending to be `read' (except the characters we store
8728 in the keyboard buffer can be multibyte, so are not necessarily
8729 C chars). */
8731 static int
8732 XTread_socket (struct terminal *terminal, struct input_event *hold_quit)
8734 int count = 0;
8735 bool event_found = false;
8736 struct x_display_info *dpyinfo = terminal->display_info.x;
8738 block_input ();
8740 /* For debugging, this gives a way to fake an I/O error. */
8741 if (dpyinfo == XTread_socket_fake_io_error)
8743 XTread_socket_fake_io_error = 0;
8744 x_io_error_quitter (dpyinfo->display);
8747 #ifndef USE_GTK
8748 while (XPending (dpyinfo->display))
8750 int finish;
8751 XEvent event;
8753 XNextEvent (dpyinfo->display, &event);
8755 #ifdef HAVE_X_I18N
8756 /* Filter events for the current X input method. */
8757 if (x_filter_event (dpyinfo, &event))
8758 continue;
8759 #endif
8760 event_found = true;
8762 count += handle_one_xevent (dpyinfo, &event, &finish, hold_quit);
8764 if (finish == X_EVENT_GOTO_OUT)
8765 break;
8768 #else /* USE_GTK */
8770 /* For GTK we must use the GTK event loop. But XEvents gets passed
8771 to our filter function above, and then to the big event switch.
8772 We use a bunch of globals to communicate with our filter function,
8773 that is kind of ugly, but it works.
8775 There is no way to do one display at the time, GTK just does events
8776 from all displays. */
8778 while (gtk_events_pending ())
8780 current_count = count;
8781 current_hold_quit = hold_quit;
8783 gtk_main_iteration ();
8785 count = current_count;
8786 current_count = -1;
8787 current_hold_quit = 0;
8789 if (current_finish == X_EVENT_GOTO_OUT)
8790 break;
8792 #endif /* USE_GTK */
8794 /* On some systems, an X bug causes Emacs to get no more events
8795 when the window is destroyed. Detect that. (1994.) */
8796 if (! event_found)
8798 /* Emacs and the X Server eats up CPU time if XNoOp is done every time.
8799 One XNOOP in 100 loops will make Emacs terminate.
8800 B. Bretthauer, 1994 */
8801 x_noop_count++;
8802 if (x_noop_count >= 100)
8804 x_noop_count=0;
8806 if (next_noop_dpyinfo == 0)
8807 next_noop_dpyinfo = x_display_list;
8809 XNoOp (next_noop_dpyinfo->display);
8811 /* Each time we get here, cycle through the displays now open. */
8812 next_noop_dpyinfo = next_noop_dpyinfo->next;
8816 /* If the focus was just given to an auto-raising frame,
8817 raise it now. FIXME: handle more than one such frame. */
8818 if (dpyinfo->x_pending_autoraise_frame)
8820 x_raise_frame (dpyinfo->x_pending_autoraise_frame);
8821 dpyinfo->x_pending_autoraise_frame = NULL;
8824 unblock_input ();
8826 return count;
8832 /***********************************************************************
8833 Text Cursor
8834 ***********************************************************************/
8836 /* Set clipping for output in glyph row ROW. W is the window in which
8837 we operate. GC is the graphics context to set clipping in.
8839 ROW may be a text row or, e.g., a mode line. Text rows must be
8840 clipped to the interior of the window dedicated to text display,
8841 mode lines must be clipped to the whole window. */
8843 static void
8844 x_clip_to_row (struct window *w, struct glyph_row *row,
8845 enum glyph_row_area area, GC gc)
8847 struct frame *f = XFRAME (WINDOW_FRAME (w));
8848 XRectangle clip_rect;
8849 int window_x, window_y, window_width;
8851 window_box (w, area, &window_x, &window_y, &window_width, 0);
8853 clip_rect.x = window_x;
8854 clip_rect.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
8855 clip_rect.y = max (clip_rect.y, window_y);
8856 clip_rect.width = window_width;
8857 clip_rect.height = row->visible_height;
8859 x_set_clip_rectangles (f, gc, &clip_rect, 1);
8863 /* Draw a hollow box cursor on window W in glyph row ROW. */
8865 static void
8866 x_draw_hollow_cursor (struct window *w, struct glyph_row *row)
8868 struct frame *f = XFRAME (WINDOW_FRAME (w));
8869 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
8870 Display *dpy = FRAME_X_DISPLAY (f);
8871 int x, y, wd, h;
8872 XGCValues xgcv;
8873 struct glyph *cursor_glyph;
8874 GC gc;
8876 /* Get the glyph the cursor is on. If we can't tell because
8877 the current matrix is invalid or such, give up. */
8878 cursor_glyph = get_phys_cursor_glyph (w);
8879 if (cursor_glyph == NULL)
8880 return;
8882 /* Compute frame-relative coordinates for phys cursor. */
8883 get_phys_cursor_geometry (w, row, cursor_glyph, &x, &y, &h);
8884 wd = w->phys_cursor_width - 1;
8886 /* The foreground of cursor_gc is typically the same as the normal
8887 background color, which can cause the cursor box to be invisible. */
8888 xgcv.foreground = f->output_data.x->cursor_pixel;
8889 if (dpyinfo->scratch_cursor_gc)
8890 XChangeGC (dpy, dpyinfo->scratch_cursor_gc, GCForeground, &xgcv);
8891 else
8892 dpyinfo->scratch_cursor_gc = XCreateGC (dpy, FRAME_X_WINDOW (f),
8893 GCForeground, &xgcv);
8894 gc = dpyinfo->scratch_cursor_gc;
8896 /* When on R2L character, show cursor at the right edge of the
8897 glyph, unless the cursor box is as wide as the glyph or wider
8898 (the latter happens when x-stretch-cursor is non-nil). */
8899 if ((cursor_glyph->resolved_level & 1) != 0
8900 && cursor_glyph->pixel_width > wd)
8902 x += cursor_glyph->pixel_width - wd;
8903 if (wd > 0)
8904 wd -= 1;
8906 /* Set clipping, draw the rectangle, and reset clipping again. */
8907 x_clip_to_row (w, row, TEXT_AREA, gc);
8908 x_draw_rectangle (f, gc, x, y, wd, h - 1);
8909 x_reset_clip_rectangles (f, gc);
8913 /* Draw a bar cursor on window W in glyph row ROW.
8915 Implementation note: One would like to draw a bar cursor with an
8916 angle equal to the one given by the font property XA_ITALIC_ANGLE.
8917 Unfortunately, I didn't find a font yet that has this property set.
8918 --gerd. */
8920 static void
8921 x_draw_bar_cursor (struct window *w, struct glyph_row *row, int width, enum text_cursor_kinds kind)
8923 struct frame *f = XFRAME (w->frame);
8924 struct glyph *cursor_glyph;
8926 /* If cursor is out of bounds, don't draw garbage. This can happen
8927 in mini-buffer windows when switching between echo area glyphs
8928 and mini-buffer. */
8929 cursor_glyph = get_phys_cursor_glyph (w);
8930 if (cursor_glyph == NULL)
8931 return;
8933 /* Experimental avoidance of cursor on xwidget. */
8934 if (cursor_glyph->type == XWIDGET_GLYPH)
8935 return;
8937 /* If on an image, draw like a normal cursor. That's usually better
8938 visible than drawing a bar, esp. if the image is large so that
8939 the bar might not be in the window. */
8940 if (cursor_glyph->type == IMAGE_GLYPH)
8942 struct glyph_row *r;
8943 r = MATRIX_ROW (w->current_matrix, w->phys_cursor.vpos);
8944 draw_phys_cursor_glyph (w, r, DRAW_CURSOR);
8946 else
8948 Display *dpy = FRAME_X_DISPLAY (f);
8949 Window window = FRAME_X_WINDOW (f);
8950 GC gc = FRAME_DISPLAY_INFO (f)->scratch_cursor_gc;
8951 unsigned long mask = GCForeground | GCBackground | GCGraphicsExposures;
8952 struct face *face = FACE_FROM_ID (f, cursor_glyph->face_id);
8953 XGCValues xgcv;
8955 /* If the glyph's background equals the color we normally draw
8956 the bars cursor in, the bar cursor in its normal color is
8957 invisible. Use the glyph's foreground color instead in this
8958 case, on the assumption that the glyph's colors are chosen so
8959 that the glyph is legible. */
8960 if (face->background == f->output_data.x->cursor_pixel)
8961 xgcv.background = xgcv.foreground = face->foreground;
8962 else
8963 xgcv.background = xgcv.foreground = f->output_data.x->cursor_pixel;
8964 xgcv.graphics_exposures = False;
8966 if (gc)
8967 XChangeGC (dpy, gc, mask, &xgcv);
8968 else
8970 gc = XCreateGC (dpy, window, mask, &xgcv);
8971 FRAME_DISPLAY_INFO (f)->scratch_cursor_gc = gc;
8974 x_clip_to_row (w, row, TEXT_AREA, gc);
8976 if (kind == BAR_CURSOR)
8978 int x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
8980 if (width < 0)
8981 width = FRAME_CURSOR_WIDTH (f);
8982 width = min (cursor_glyph->pixel_width, width);
8984 w->phys_cursor_width = width;
8986 /* If the character under cursor is R2L, draw the bar cursor
8987 on the right of its glyph, rather than on the left. */
8988 if ((cursor_glyph->resolved_level & 1) != 0)
8989 x += cursor_glyph->pixel_width - width;
8991 x_fill_rectangle (f, gc, x,
8992 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y),
8993 width, row->height);
8995 else /* HBAR_CURSOR */
8997 int dummy_x, dummy_y, dummy_h;
8998 int x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
9000 if (width < 0)
9001 width = row->height;
9003 width = min (row->height, width);
9005 get_phys_cursor_geometry (w, row, cursor_glyph, &dummy_x,
9006 &dummy_y, &dummy_h);
9008 if ((cursor_glyph->resolved_level & 1) != 0
9009 && cursor_glyph->pixel_width > w->phys_cursor_width - 1)
9010 x += cursor_glyph->pixel_width - w->phys_cursor_width + 1;
9011 x_fill_rectangle (f, gc, x,
9012 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y +
9013 row->height - width),
9014 w->phys_cursor_width - 1, width);
9017 x_reset_clip_rectangles (f, gc);
9022 /* RIF: Define cursor CURSOR on frame F. */
9024 static void
9025 x_define_frame_cursor (struct frame *f, Cursor cursor)
9027 if (!f->pointer_invisible
9028 && f->output_data.x->current_cursor != cursor)
9029 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), cursor);
9030 f->output_data.x->current_cursor = cursor;
9034 /* RIF: Clear area on frame F. */
9036 static void
9037 x_clear_frame_area (struct frame *f, int x, int y, int width, int height)
9039 x_clear_area (f, x, y, width, height);
9040 #ifdef USE_GTK
9041 /* Must queue a redraw, because scroll bars might have been cleared. */
9042 if (FRAME_GTK_WIDGET (f))
9043 gtk_widget_queue_draw (FRAME_GTK_WIDGET (f));
9044 #endif
9048 /* RIF: Draw cursor on window W. */
9050 static void
9051 x_draw_window_cursor (struct window *w, struct glyph_row *glyph_row, int x,
9052 int y, enum text_cursor_kinds cursor_type,
9053 int cursor_width, bool on_p, bool active_p)
9055 struct frame *f = XFRAME (WINDOW_FRAME (w));
9057 if (on_p)
9059 w->phys_cursor_type = cursor_type;
9060 w->phys_cursor_on_p = true;
9062 if (glyph_row->exact_window_width_line_p
9063 && (glyph_row->reversed_p
9064 ? (w->phys_cursor.hpos < 0)
9065 : (w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])))
9067 glyph_row->cursor_in_fringe_p = true;
9068 draw_fringe_bitmap (w, glyph_row, glyph_row->reversed_p);
9070 else
9072 switch (cursor_type)
9074 case HOLLOW_BOX_CURSOR:
9075 x_draw_hollow_cursor (w, glyph_row);
9076 break;
9078 case FILLED_BOX_CURSOR:
9079 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
9080 break;
9082 case BAR_CURSOR:
9083 x_draw_bar_cursor (w, glyph_row, cursor_width, BAR_CURSOR);
9084 break;
9086 case HBAR_CURSOR:
9087 x_draw_bar_cursor (w, glyph_row, cursor_width, HBAR_CURSOR);
9088 break;
9090 case NO_CURSOR:
9091 w->phys_cursor_width = 0;
9092 break;
9094 default:
9095 emacs_abort ();
9099 #ifdef HAVE_X_I18N
9100 if (w == XWINDOW (f->selected_window))
9101 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMPreeditPosition))
9102 xic_set_preeditarea (w, x, y);
9103 #endif
9106 XFlush (FRAME_X_DISPLAY (f));
9110 /* Icons. */
9112 /* Make the x-window of frame F use the gnu icon bitmap. */
9114 bool
9115 x_bitmap_icon (struct frame *f, Lisp_Object file)
9117 ptrdiff_t bitmap_id;
9119 if (FRAME_X_WINDOW (f) == 0)
9120 return true;
9122 /* Free up our existing icon bitmap and mask if any. */
9123 if (f->output_data.x->icon_bitmap > 0)
9124 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
9125 f->output_data.x->icon_bitmap = 0;
9127 if (STRINGP (file))
9129 #ifdef USE_GTK
9130 /* Use gtk_window_set_icon_from_file () if available,
9131 It's not restricted to bitmaps */
9132 if (xg_set_icon (f, file))
9133 return false;
9134 #endif /* USE_GTK */
9135 bitmap_id = x_create_bitmap_from_file (f, file);
9136 x_create_bitmap_mask (f, bitmap_id);
9138 else
9140 /* Create the GNU bitmap and mask if necessary. */
9141 if (FRAME_DISPLAY_INFO (f)->icon_bitmap_id < 0)
9143 ptrdiff_t rc = -1;
9145 #ifdef USE_GTK
9147 if (xg_set_icon (f, xg_default_icon_file)
9148 || xg_set_icon_from_xpm_data (f, gnu_xpm_bits))
9150 FRAME_DISPLAY_INFO (f)->icon_bitmap_id = -2;
9151 return false;
9154 #elif defined (HAVE_XPM) && defined (HAVE_X_WINDOWS)
9156 rc = x_create_bitmap_from_xpm_data (f, gnu_xpm_bits);
9157 if (rc != -1)
9158 FRAME_DISPLAY_INFO (f)->icon_bitmap_id = rc;
9160 #endif
9162 /* If all else fails, use the (black and white) xbm image. */
9163 if (rc == -1)
9165 rc = x_create_bitmap_from_data (f, (char *) gnu_xbm_bits,
9166 gnu_xbm_width, gnu_xbm_height);
9167 if (rc == -1)
9168 return true;
9170 FRAME_DISPLAY_INFO (f)->icon_bitmap_id = rc;
9171 x_create_bitmap_mask (f, FRAME_DISPLAY_INFO (f)->icon_bitmap_id);
9175 /* The first time we create the GNU bitmap and mask,
9176 this increments the ref-count one extra time.
9177 As a result, the GNU bitmap and mask are never freed.
9178 That way, we don't have to worry about allocating it again. */
9179 x_reference_bitmap (f, FRAME_DISPLAY_INFO (f)->icon_bitmap_id);
9181 bitmap_id = FRAME_DISPLAY_INFO (f)->icon_bitmap_id;
9184 x_wm_set_icon_pixmap (f, bitmap_id);
9185 f->output_data.x->icon_bitmap = bitmap_id;
9187 return false;
9191 /* Make the x-window of frame F use a rectangle with text.
9192 Use ICON_NAME as the text. */
9194 bool
9195 x_text_icon (struct frame *f, const char *icon_name)
9197 if (FRAME_X_WINDOW (f) == 0)
9198 return true;
9201 XTextProperty text;
9202 text.value = (unsigned char *) icon_name;
9203 text.encoding = XA_STRING;
9204 text.format = 8;
9205 text.nitems = strlen (icon_name);
9206 XSetWMIconName (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f), &text);
9209 if (f->output_data.x->icon_bitmap > 0)
9210 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
9211 f->output_data.x->icon_bitmap = 0;
9212 x_wm_set_icon_pixmap (f, 0);
9214 return false;
9217 #define X_ERROR_MESSAGE_SIZE 200
9219 /* If non-nil, this should be a string.
9220 It means catch X errors and store the error message in this string.
9222 The reason we use a stack is that x_catch_error/x_uncatch_error can
9223 be called from a signal handler.
9226 struct x_error_message_stack {
9227 char string[X_ERROR_MESSAGE_SIZE];
9228 Display *dpy;
9229 x_special_error_handler handler;
9230 void *handler_data;
9231 struct x_error_message_stack *prev;
9233 static struct x_error_message_stack *x_error_message;
9235 /* An X error handler which stores the error message in
9236 *x_error_message. This is called from x_error_handler if
9237 x_catch_errors is in effect. */
9239 static void
9240 x_error_catcher (Display *display, XErrorEvent *event)
9242 XGetErrorText (display, event->error_code,
9243 x_error_message->string,
9244 X_ERROR_MESSAGE_SIZE);
9245 if (x_error_message->handler)
9246 x_error_message->handler (display, event, x_error_message->string,
9247 x_error_message->handler_data);
9250 /* Begin trapping X errors for display DPY. Actually we trap X errors
9251 for all displays, but DPY should be the display you are actually
9252 operating on.
9254 After calling this function, X protocol errors no longer cause
9255 Emacs to exit; instead, they are recorded in the string
9256 stored in *x_error_message.
9258 Calling x_check_errors signals an Emacs error if an X error has
9259 occurred since the last call to x_catch_errors or x_check_errors.
9261 Calling x_uncatch_errors resumes the normal error handling.
9262 Calling x_uncatch_errors_after_check is similar, but skips an XSync
9263 to the server, and should be used only immediately after
9264 x_had_errors_p or x_check_errors. */
9266 void
9267 x_catch_errors_with_handler (Display *dpy, x_special_error_handler handler,
9268 void *handler_data)
9270 struct x_error_message_stack *data = xmalloc (sizeof *data);
9272 /* Make sure any errors from previous requests have been dealt with. */
9273 XSync (dpy, False);
9275 data->dpy = dpy;
9276 data->string[0] = 0;
9277 data->handler = handler;
9278 data->handler_data = handler_data;
9279 data->prev = x_error_message;
9280 x_error_message = data;
9283 void
9284 x_catch_errors (Display *dpy)
9286 x_catch_errors_with_handler (dpy, NULL, NULL);
9289 /* Undo the last x_catch_errors call.
9290 DPY should be the display that was passed to x_catch_errors.
9292 This version should be used only if the immediately preceding
9293 X-protocol-related thing was x_check_errors or x_had_error_p, both
9294 of which issue XSync calls, so we don't need to re-sync here. */
9296 void
9297 x_uncatch_errors_after_check (void)
9299 struct x_error_message_stack *tmp;
9301 block_input ();
9302 tmp = x_error_message;
9303 x_error_message = x_error_message->prev;
9304 xfree (tmp);
9305 unblock_input ();
9308 /* Undo the last x_catch_errors call.
9309 DPY should be the display that was passed to x_catch_errors. */
9311 void
9312 x_uncatch_errors (void)
9314 struct x_error_message_stack *tmp;
9316 block_input ();
9318 /* The display may have been closed before this function is called.
9319 Check if it is still open before calling XSync. */
9320 if (x_display_info_for_display (x_error_message->dpy) != 0)
9321 XSync (x_error_message->dpy, False);
9323 tmp = x_error_message;
9324 x_error_message = x_error_message->prev;
9325 xfree (tmp);
9326 unblock_input ();
9329 /* If any X protocol errors have arrived since the last call to
9330 x_catch_errors or x_check_errors, signal an Emacs error using
9331 sprintf (a buffer, FORMAT, the x error message text) as the text. */
9333 void
9334 x_check_errors (Display *dpy, const char *format)
9336 /* Make sure to catch any errors incurred so far. */
9337 XSync (dpy, False);
9339 if (x_error_message->string[0])
9341 char string[X_ERROR_MESSAGE_SIZE];
9342 memcpy (string, x_error_message->string, X_ERROR_MESSAGE_SIZE);
9343 x_uncatch_errors ();
9344 error (format, string);
9348 /* Nonzero if we had any X protocol errors
9349 since we did x_catch_errors on DPY. */
9351 bool
9352 x_had_errors_p (Display *dpy)
9354 /* Make sure to catch any errors incurred so far. */
9355 XSync (dpy, False);
9357 return x_error_message->string[0] != 0;
9360 /* Forget about any errors we have had, since we did x_catch_errors on DPY. */
9362 void
9363 x_clear_errors (Display *dpy)
9365 x_error_message->string[0] = 0;
9368 #if false
9369 /* See comment in unwind_to_catch why calling this is a bad
9370 * idea. --lorentey */
9371 /* Close off all unclosed x_catch_errors calls. */
9373 void
9374 x_fully_uncatch_errors (void)
9376 while (x_error_message)
9377 x_uncatch_errors ();
9379 #endif
9381 #if false
9382 static unsigned int x_wire_count;
9383 x_trace_wire (void)
9385 fprintf (stderr, "Lib call: %d\n", ++x_wire_count);
9387 #endif
9390 /************************************************************************
9391 Handling X errors
9392 ************************************************************************/
9394 /* Error message passed to x_connection_closed. */
9396 static char *error_msg;
9398 /* Handle the loss of connection to display DPY. ERROR_MESSAGE is
9399 the text of an error message that lead to the connection loss. */
9401 static void
9402 x_connection_closed (Display *dpy, const char *error_message, bool ioerror)
9404 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
9405 Lisp_Object frame, tail;
9406 ptrdiff_t idx = SPECPDL_INDEX ();
9408 error_msg = alloca (strlen (error_message) + 1);
9409 strcpy (error_msg, error_message);
9411 /* Inhibit redisplay while frames are being deleted. */
9412 specbind (Qinhibit_redisplay, Qt);
9414 if (dpyinfo)
9416 /* Protect display from being closed when we delete the last
9417 frame on it. */
9418 dpyinfo->reference_count++;
9419 dpyinfo->terminal->reference_count++;
9421 if (ioerror) dpyinfo->display = 0;
9423 /* First delete frames whose mini-buffers are on frames
9424 that are on the dead display. */
9425 FOR_EACH_FRAME (tail, frame)
9427 Lisp_Object minibuf_frame;
9428 minibuf_frame
9429 = WINDOW_FRAME (XWINDOW (FRAME_MINIBUF_WINDOW (XFRAME (frame))));
9430 if (FRAME_X_P (XFRAME (frame))
9431 && FRAME_X_P (XFRAME (minibuf_frame))
9432 && ! EQ (frame, minibuf_frame)
9433 && FRAME_DISPLAY_INFO (XFRAME (minibuf_frame)) == dpyinfo)
9434 delete_frame (frame, Qnoelisp);
9437 /* Now delete all remaining frames on the dead display.
9438 We are now sure none of these is used as the mini-buffer
9439 for another frame that we need to delete. */
9440 FOR_EACH_FRAME (tail, frame)
9441 if (FRAME_X_P (XFRAME (frame))
9442 && FRAME_DISPLAY_INFO (XFRAME (frame)) == dpyinfo)
9444 /* Set this to t so that delete_frame won't get confused
9445 trying to find a replacement. */
9446 kset_default_minibuffer_frame (FRAME_KBOARD (XFRAME (frame)), Qt);
9447 delete_frame (frame, Qnoelisp);
9450 /* If DPYINFO is null, this means we didn't open the display in the
9451 first place, so don't try to close it. */
9452 if (dpyinfo)
9454 /* We can not call XtCloseDisplay here because it calls XSync.
9455 XSync inside the error handler apparently hangs Emacs. On
9456 current Xt versions, this isn't needed either. */
9457 #ifdef USE_GTK
9458 /* A long-standing GTK bug prevents proper disconnect handling
9459 (https://bugzilla.gnome.org/show_bug.cgi?id=85715). Once,
9460 the resulting Glib error message loop filled a user's disk.
9461 To avoid this, kill Emacs unconditionally on disconnect. */
9462 shut_down_emacs (0, Qnil);
9463 fprintf (stderr, "%s\n\
9464 When compiled with GTK, Emacs cannot recover from X disconnects.\n\
9465 This is a GTK bug: https://bugzilla.gnome.org/show_bug.cgi?id=85715\n\
9466 For details, see etc/PROBLEMS.\n",
9467 error_msg);
9468 emacs_abort ();
9469 #endif /* USE_GTK */
9471 /* Indicate that this display is dead. */
9472 dpyinfo->display = 0;
9474 dpyinfo->reference_count--;
9475 dpyinfo->terminal->reference_count--;
9476 if (dpyinfo->reference_count != 0)
9477 /* We have just closed all frames on this display. */
9478 emacs_abort ();
9481 Lisp_Object tmp;
9482 XSETTERMINAL (tmp, dpyinfo->terminal);
9483 Fdelete_terminal (tmp, Qnoelisp);
9487 if (terminal_list == 0)
9489 fprintf (stderr, "%s\n", error_msg);
9490 Fkill_emacs (make_number (70));
9491 /* NOTREACHED */
9494 totally_unblock_input ();
9496 unbind_to (idx, Qnil);
9497 clear_waiting_for_input ();
9499 /* Tell GCC not to suggest attribute 'noreturn' for this function. */
9500 IF_LINT (if (! terminal_list) return; )
9502 /* Here, we absolutely have to use a non-local exit (e.g. signal, throw,
9503 longjmp), because returning from this function would get us back into
9504 Xlib's code which will directly call `exit'. */
9505 error ("%s", error_msg);
9508 /* We specifically use it before defining it, so that gcc doesn't inline it,
9509 otherwise gdb doesn't know how to properly put a breakpoint on it. */
9510 static void x_error_quitter (Display *, XErrorEvent *);
9512 /* This is the first-level handler for X protocol errors.
9513 It calls x_error_quitter or x_error_catcher. */
9515 static int
9516 x_error_handler (Display *display, XErrorEvent *event)
9518 #if defined USE_GTK && defined HAVE_GTK3
9519 if ((event->error_code == BadMatch || event->error_code == BadWindow)
9520 && event->request_code == X_SetInputFocus)
9522 return 0;
9524 #endif
9526 if (x_error_message)
9527 x_error_catcher (display, event);
9528 else
9529 x_error_quitter (display, event);
9530 return 0;
9533 /* This is the usual handler for X protocol errors.
9534 It kills all frames on the display that we got the error for.
9535 If that was the only one, it prints an error message and kills Emacs. */
9537 /* .gdbinit puts a breakpoint here, so make sure it is not inlined. */
9539 /* On older GCC versions, just putting x_error_quitter
9540 after x_error_handler prevents inlining into the former. */
9542 static void NO_INLINE
9543 x_error_quitter (Display *display, XErrorEvent *event)
9545 char buf[256], buf1[356];
9547 /* Ignore BadName errors. They can happen because of fonts
9548 or colors that are not defined. */
9550 if (event->error_code == BadName)
9551 return;
9553 /* Note that there is no real way portable across R3/R4 to get the
9554 original error handler. */
9556 XGetErrorText (display, event->error_code, buf, sizeof (buf));
9557 sprintf (buf1, "X protocol error: %s on protocol request %d",
9558 buf, event->request_code);
9559 x_connection_closed (display, buf1, false);
9563 /* This is the handler for X IO errors, always.
9564 It kills all frames on the display that we lost touch with.
9565 If that was the only one, it prints an error message and kills Emacs. */
9567 static int
9568 x_io_error_quitter (Display *display)
9570 char buf[256];
9572 snprintf (buf, sizeof buf, "Connection lost to X server '%s'",
9573 DisplayString (display));
9574 x_connection_closed (display, buf, true);
9575 return 0;
9578 /* Changing the font of the frame. */
9580 /* Give frame F the font FONT-OBJECT as its default font. The return
9581 value is FONT-OBJECT. FONTSET is an ID of the fontset for the
9582 frame. If it is negative, generate a new fontset from
9583 FONT-OBJECT. */
9585 Lisp_Object
9586 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
9588 struct font *font = XFONT_OBJECT (font_object);
9589 int unit, font_ascent, font_descent;
9590 #ifndef USE_X_TOOLKIT
9591 int old_menu_bar_height = FRAME_MENU_BAR_HEIGHT (f);
9592 Lisp_Object fullscreen;
9593 #endif
9595 if (fontset < 0)
9596 fontset = fontset_from_font (font_object);
9597 FRAME_FONTSET (f) = fontset;
9598 if (FRAME_FONT (f) == font)
9599 /* This font is already set in frame F. There's nothing more to
9600 do. */
9601 return font_object;
9603 FRAME_FONT (f) = font;
9604 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
9605 FRAME_COLUMN_WIDTH (f) = font->average_width;
9606 get_font_ascent_descent (font, &font_ascent, &font_descent);
9607 FRAME_LINE_HEIGHT (f) = font_ascent + font_descent;
9609 #ifndef USE_X_TOOLKIT
9610 FRAME_MENU_BAR_HEIGHT (f) = FRAME_MENU_BAR_LINES (f) * FRAME_LINE_HEIGHT (f);
9611 #endif
9613 /* Compute character columns occupied by scrollbar.
9615 Don't do things differently for non-toolkit scrollbars
9616 (Bug#17163). */
9617 unit = FRAME_COLUMN_WIDTH (f);
9618 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
9619 FRAME_CONFIG_SCROLL_BAR_COLS (f)
9620 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + unit - 1) / unit;
9621 else
9622 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + unit - 1) / unit;
9624 if (FRAME_X_WINDOW (f) != 0)
9626 /* Don't change the size of a tip frame; there's no point in
9627 doing it because it's done in Fx_show_tip, and it leads to
9628 problems because the tip frame has no widget. */
9629 if (NILP (tip_frame) || XFRAME (tip_frame) != f)
9631 adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
9632 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 3,
9633 false, Qfont);
9634 #ifndef USE_X_TOOLKIT
9635 if (FRAME_MENU_BAR_HEIGHT (f) != old_menu_bar_height
9636 && !f->after_make_frame
9637 && (EQ (frame_inhibit_implied_resize, Qt)
9638 || (CONSP (frame_inhibit_implied_resize)
9639 && NILP (Fmemq (Qfont, frame_inhibit_implied_resize))))
9640 && (NILP (fullscreen = get_frame_param (f, Qfullscreen))
9641 || EQ (fullscreen, Qfullwidth)))
9642 /* If the menu bar height changes, try to keep text height
9643 constant. */
9644 adjust_frame_size
9645 (f, -1, FRAME_TEXT_HEIGHT (f) + FRAME_MENU_BAR_HEIGHT (f)
9646 - old_menu_bar_height, 1, false, Qfont);
9647 #endif /* USE_X_TOOLKIT */
9651 #ifdef HAVE_X_I18N
9652 if (FRAME_XIC (f)
9653 && (FRAME_XIC_STYLE (f) & (XIMPreeditPosition | XIMStatusArea)))
9655 block_input ();
9656 xic_set_xfontset (f, SSDATA (fontset_ascii (fontset)));
9657 unblock_input ();
9659 #endif
9661 return font_object;
9665 /***********************************************************************
9666 X Input Methods
9667 ***********************************************************************/
9669 #ifdef HAVE_X_I18N
9671 #ifdef HAVE_X11R6
9673 /* XIM destroy callback function, which is called whenever the
9674 connection to input method XIM dies. CLIENT_DATA contains a
9675 pointer to the x_display_info structure corresponding to XIM. */
9677 static void
9678 xim_destroy_callback (XIM xim, XPointer client_data, XPointer call_data)
9680 struct x_display_info *dpyinfo = (struct x_display_info *) client_data;
9681 Lisp_Object frame, tail;
9683 block_input ();
9685 /* No need to call XDestroyIC.. */
9686 FOR_EACH_FRAME (tail, frame)
9688 struct frame *f = XFRAME (frame);
9689 if (FRAME_X_P (f) && FRAME_DISPLAY_INFO (f) == dpyinfo)
9691 FRAME_XIC (f) = NULL;
9692 xic_free_xfontset (f);
9696 /* No need to call XCloseIM. */
9697 dpyinfo->xim = NULL;
9698 XFree (dpyinfo->xim_styles);
9699 unblock_input ();
9702 #endif /* HAVE_X11R6 */
9704 /* Open the connection to the XIM server on display DPYINFO.
9705 RESOURCE_NAME is the resource name Emacs uses. */
9707 static void
9708 xim_open_dpy (struct x_display_info *dpyinfo, char *resource_name)
9710 XIM xim;
9712 #ifdef HAVE_XIM
9713 if (use_xim)
9715 if (dpyinfo->xim)
9716 XCloseIM (dpyinfo->xim);
9717 xim = XOpenIM (dpyinfo->display, dpyinfo->xrdb, resource_name,
9718 emacs_class);
9719 dpyinfo->xim = xim;
9721 if (xim)
9723 #ifdef HAVE_X11R6
9724 XIMCallback destroy;
9725 #endif
9727 /* Get supported styles and XIM values. */
9728 XGetIMValues (xim, XNQueryInputStyle, &dpyinfo->xim_styles, NULL);
9730 #ifdef HAVE_X11R6
9731 destroy.callback = xim_destroy_callback;
9732 destroy.client_data = (XPointer)dpyinfo;
9733 XSetIMValues (xim, XNDestroyCallback, &destroy, NULL);
9734 #endif
9738 else
9739 #endif /* HAVE_XIM */
9740 dpyinfo->xim = NULL;
9744 #ifdef HAVE_X11R6_XIM
9746 /* XIM instantiate callback function, which is called whenever an XIM
9747 server is available. DISPLAY is the display of the XIM.
9748 CLIENT_DATA contains a pointer to an xim_inst_t structure created
9749 when the callback was registered. */
9751 static void
9752 xim_instantiate_callback (Display *display, XPointer client_data, XPointer call_data)
9754 struct xim_inst_t *xim_inst = (struct xim_inst_t *) client_data;
9755 struct x_display_info *dpyinfo = xim_inst->dpyinfo;
9757 /* We don't support multiple XIM connections. */
9758 if (dpyinfo->xim)
9759 return;
9761 xim_open_dpy (dpyinfo, xim_inst->resource_name);
9763 /* Create XIC for the existing frames on the same display, as long
9764 as they have no XIC. */
9765 if (dpyinfo->xim && dpyinfo->reference_count > 0)
9767 Lisp_Object tail, frame;
9769 block_input ();
9770 FOR_EACH_FRAME (tail, frame)
9772 struct frame *f = XFRAME (frame);
9774 if (FRAME_X_P (f)
9775 && FRAME_DISPLAY_INFO (f) == xim_inst->dpyinfo)
9776 if (FRAME_XIC (f) == NULL)
9778 create_frame_xic (f);
9779 if (FRAME_XIC_STYLE (f) & XIMStatusArea)
9780 xic_set_statusarea (f);
9781 if (FRAME_XIC_STYLE (f) & XIMPreeditPosition)
9783 struct window *w = XWINDOW (f->selected_window);
9784 xic_set_preeditarea (w, w->cursor.x, w->cursor.y);
9789 unblock_input ();
9793 #endif /* HAVE_X11R6_XIM */
9796 /* Open a connection to the XIM server on display DPYINFO.
9797 RESOURCE_NAME is the resource name for Emacs. On X11R5, open the
9798 connection only at the first time. On X11R6, open the connection
9799 in the XIM instantiate callback function. */
9801 static void
9802 xim_initialize (struct x_display_info *dpyinfo, char *resource_name)
9804 dpyinfo->xim = NULL;
9805 #ifdef HAVE_XIM
9806 if (use_xim)
9808 #ifdef HAVE_X11R6_XIM
9809 struct xim_inst_t *xim_inst = xmalloc (sizeof *xim_inst);
9810 Bool ret;
9812 dpyinfo->xim_callback_data = xim_inst;
9813 xim_inst->dpyinfo = dpyinfo;
9814 xim_inst->resource_name = xstrdup (resource_name);
9815 ret = XRegisterIMInstantiateCallback
9816 (dpyinfo->display, dpyinfo->xrdb, xim_inst->resource_name,
9817 emacs_class, xim_instantiate_callback,
9818 /* This is XPointer in XFree86 but (XPointer *)
9819 on Tru64, at least, hence the configure test. */
9820 (XRegisterIMInstantiateCallback_arg6) xim_inst);
9821 eassert (ret == True);
9822 #else /* not HAVE_X11R6_XIM */
9823 xim_open_dpy (dpyinfo, resource_name);
9824 #endif /* not HAVE_X11R6_XIM */
9826 #endif /* HAVE_XIM */
9830 /* Close the connection to the XIM server on display DPYINFO. */
9832 static void
9833 xim_close_dpy (struct x_display_info *dpyinfo)
9835 #ifdef HAVE_XIM
9836 if (use_xim)
9838 #ifdef HAVE_X11R6_XIM
9839 struct xim_inst_t *xim_inst = dpyinfo->xim_callback_data;
9841 if (dpyinfo->display)
9843 Bool ret = XUnregisterIMInstantiateCallback
9844 (dpyinfo->display, dpyinfo->xrdb, xim_inst->resource_name,
9845 emacs_class, xim_instantiate_callback,
9846 (XRegisterIMInstantiateCallback_arg6) xim_inst);
9847 eassert (ret == True);
9849 xfree (xim_inst->resource_name);
9850 xfree (xim_inst);
9851 #endif /* HAVE_X11R6_XIM */
9852 if (dpyinfo->display)
9853 XCloseIM (dpyinfo->xim);
9854 dpyinfo->xim = NULL;
9855 XFree (dpyinfo->xim_styles);
9857 #endif /* HAVE_XIM */
9860 #endif /* not HAVE_X11R6_XIM */
9864 /* Calculate the absolute position in frame F
9865 from its current recorded position values and gravity. */
9867 static void
9868 x_calc_absolute_position (struct frame *f)
9870 int flags = f->size_hint_flags;
9872 /* We have nothing to do if the current position
9873 is already for the top-left corner. */
9874 if (! ((flags & XNegative) || (flags & YNegative)))
9875 return;
9877 /* Treat negative positions as relative to the leftmost bottommost
9878 position that fits on the screen. */
9879 if (flags & XNegative)
9880 f->left_pos = x_display_pixel_width (FRAME_DISPLAY_INFO (f))
9881 - FRAME_PIXEL_WIDTH (f) + f->left_pos;
9884 int height = FRAME_PIXEL_HEIGHT (f);
9886 #if defined USE_X_TOOLKIT && defined USE_MOTIF
9887 /* Something is fishy here. When using Motif, starting Emacs with
9888 `-g -0-0', the frame appears too low by a few pixels.
9890 This seems to be so because initially, while Emacs is starting,
9891 the column widget's height and the frame's pixel height are
9892 different. The column widget's height is the right one. In
9893 later invocations, when Emacs is up, the frame's pixel height
9894 is right, though.
9896 It's not obvious where the initial small difference comes from.
9897 2000-12-01, gerd. */
9899 XtVaGetValues (f->output_data.x->column_widget, XtNheight, &height, NULL);
9900 #endif
9902 if (flags & YNegative)
9903 f->top_pos = x_display_pixel_height (FRAME_DISPLAY_INFO (f))
9904 - height + f->top_pos;
9907 /* The left_pos and top_pos
9908 are now relative to the top and left screen edges,
9909 so the flags should correspond. */
9910 f->size_hint_flags &= ~ (XNegative | YNegative);
9913 /* CHANGE_GRAVITY is 1 when calling from Fset_frame_position,
9914 to really change the position, and 0 when calling from
9915 x_make_frame_visible (in that case, XOFF and YOFF are the current
9916 position values). It is -1 when calling from x_set_frame_parameters,
9917 which means, do adjust for borders but don't change the gravity. */
9919 void
9920 x_set_offset (struct frame *f, register int xoff, register int yoff, int change_gravity)
9922 int modified_top, modified_left;
9924 if (change_gravity > 0)
9926 f->top_pos = yoff;
9927 f->left_pos = xoff;
9928 f->size_hint_flags &= ~ (XNegative | YNegative);
9929 if (xoff < 0)
9930 f->size_hint_flags |= XNegative;
9931 if (yoff < 0)
9932 f->size_hint_flags |= YNegative;
9933 f->win_gravity = NorthWestGravity;
9935 x_calc_absolute_position (f);
9937 block_input ();
9938 x_wm_set_size_hint (f, 0, false);
9940 modified_left = f->left_pos;
9941 modified_top = f->top_pos;
9943 if (change_gravity != 0 && FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A)
9945 /* Some WMs (twm, wmaker at least) has an offset that is smaller
9946 than the WM decorations. So we use the calculated offset instead
9947 of the WM decoration sizes here (x/y_pixels_outer_diff). */
9948 modified_left += FRAME_X_OUTPUT (f)->move_offset_left;
9949 modified_top += FRAME_X_OUTPUT (f)->move_offset_top;
9952 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
9953 modified_left, modified_top);
9955 x_sync_with_move (f, f->left_pos, f->top_pos,
9956 FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN);
9958 /* change_gravity is non-zero when this function is called from Lisp to
9959 programmatically move a frame. In that case, we call
9960 x_check_expected_move to discover if we have a "Type A" or "Type B"
9961 window manager, and, for a "Type A" window manager, adjust the position
9962 of the frame.
9964 We call x_check_expected_move if a programmatic move occurred, and
9965 either the window manager type (A/B) is unknown or it is Type A but we
9966 need to compute the top/left offset adjustment for this frame. */
9968 if (change_gravity != 0
9969 && (FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN
9970 || (FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A
9971 && (FRAME_X_OUTPUT (f)->move_offset_left == 0
9972 && FRAME_X_OUTPUT (f)->move_offset_top == 0))))
9973 x_check_expected_move (f, modified_left, modified_top);
9975 unblock_input ();
9978 /* Return true if _NET_SUPPORTING_WM_CHECK window exists and _NET_SUPPORTED
9979 on the root window for frame F contains ATOMNAME.
9980 This is how a WM check shall be done according to the Window Manager
9981 Specification/Extended Window Manager Hints at
9982 http://freedesktop.org/wiki/Specifications/wm-spec. */
9984 bool
9985 x_wm_supports (struct frame *f, Atom want_atom)
9987 Atom actual_type;
9988 unsigned long actual_size, bytes_remaining;
9989 int i, rc, actual_format;
9990 bool ret;
9991 Window wmcheck_window;
9992 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
9993 Window target_window = dpyinfo->root_window;
9994 int max_len = 65536;
9995 Display *dpy = FRAME_X_DISPLAY (f);
9996 unsigned char *tmp_data = NULL;
9997 Atom target_type = XA_WINDOW;
9999 block_input ();
10001 x_catch_errors (dpy);
10002 rc = XGetWindowProperty (dpy, target_window,
10003 dpyinfo->Xatom_net_supporting_wm_check,
10004 0, max_len, False, target_type,
10005 &actual_type, &actual_format, &actual_size,
10006 &bytes_remaining, &tmp_data);
10008 if (rc != Success || actual_type != XA_WINDOW || x_had_errors_p (dpy))
10010 if (tmp_data) XFree (tmp_data);
10011 x_uncatch_errors ();
10012 unblock_input ();
10013 return false;
10016 wmcheck_window = *(Window *) tmp_data;
10017 XFree (tmp_data);
10019 /* Check if window exists. */
10020 XSelectInput (dpy, wmcheck_window, StructureNotifyMask);
10021 if (x_had_errors_p (dpy))
10023 x_uncatch_errors_after_check ();
10024 unblock_input ();
10025 return false;
10028 if (dpyinfo->net_supported_window != wmcheck_window)
10030 /* Window changed, reload atoms */
10031 if (dpyinfo->net_supported_atoms != NULL)
10032 XFree (dpyinfo->net_supported_atoms);
10033 dpyinfo->net_supported_atoms = NULL;
10034 dpyinfo->nr_net_supported_atoms = 0;
10035 dpyinfo->net_supported_window = 0;
10037 target_type = XA_ATOM;
10038 tmp_data = NULL;
10039 rc = XGetWindowProperty (dpy, target_window,
10040 dpyinfo->Xatom_net_supported,
10041 0, max_len, False, target_type,
10042 &actual_type, &actual_format, &actual_size,
10043 &bytes_remaining, &tmp_data);
10045 if (rc != Success || actual_type != XA_ATOM || x_had_errors_p (dpy))
10047 if (tmp_data) XFree (tmp_data);
10048 x_uncatch_errors ();
10049 unblock_input ();
10050 return false;
10053 dpyinfo->net_supported_atoms = (Atom *)tmp_data;
10054 dpyinfo->nr_net_supported_atoms = actual_size;
10055 dpyinfo->net_supported_window = wmcheck_window;
10058 ret = false;
10060 for (i = 0; !ret && i < dpyinfo->nr_net_supported_atoms; ++i)
10061 ret = dpyinfo->net_supported_atoms[i] == want_atom;
10063 x_uncatch_errors ();
10064 unblock_input ();
10066 return ret;
10069 static void
10070 set_wm_state (Lisp_Object frame, bool add, Atom atom, Atom value)
10072 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (XFRAME (frame));
10074 x_send_client_event (frame, make_number (0), frame,
10075 dpyinfo->Xatom_net_wm_state,
10076 make_number (32),
10077 /* 1 = add, 0 = remove */
10078 Fcons
10079 (make_number (add),
10080 Fcons
10081 (make_fixnum_or_float (atom),
10082 (value != 0
10083 ? list1 (make_fixnum_or_float (value))
10084 : Qnil))));
10087 void
10088 x_set_sticky (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
10090 Lisp_Object frame;
10091 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10093 XSETFRAME (frame, f);
10095 set_wm_state (frame, !NILP (new_value),
10096 dpyinfo->Xatom_net_wm_state_sticky, None);
10099 /* Return the current _NET_WM_STATE.
10100 SIZE_STATE is set to one of the FULLSCREEN_* values.
10101 Set *STICKY to the sticky state.
10103 Return true iff we are not hidden. */
10105 static bool
10106 get_current_wm_state (struct frame *f,
10107 Window window,
10108 int *size_state,
10109 bool *sticky)
10111 unsigned long actual_size;
10112 int i;
10113 bool is_hidden = false;
10114 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10115 long max_len = 65536;
10116 Atom target_type = XA_ATOM;
10117 /* If XCB is available, we can avoid three XSync calls. */
10118 #ifdef USE_XCB
10119 xcb_get_property_cookie_t prop_cookie;
10120 xcb_get_property_reply_t *prop;
10121 xcb_atom_t *reply_data;
10122 #else
10123 Display *dpy = FRAME_X_DISPLAY (f);
10124 unsigned long bytes_remaining;
10125 int rc, actual_format;
10126 Atom actual_type;
10127 unsigned char *tmp_data = NULL;
10128 Atom *reply_data;
10129 #endif
10131 *sticky = false;
10132 *size_state = FULLSCREEN_NONE;
10134 block_input ();
10136 #ifdef USE_XCB
10137 prop_cookie = xcb_get_property (dpyinfo->xcb_connection, 0, window,
10138 dpyinfo->Xatom_net_wm_state,
10139 target_type, 0, max_len);
10140 prop = xcb_get_property_reply (dpyinfo->xcb_connection, prop_cookie, NULL);
10141 if (prop && prop->type == target_type)
10143 int actual_bytes = xcb_get_property_value_length (prop);
10144 eassume (0 <= actual_bytes);
10145 actual_size = actual_bytes / sizeof *reply_data;
10146 reply_data = xcb_get_property_value (prop);
10148 else
10150 actual_size = 0;
10151 is_hidden = FRAME_ICONIFIED_P (f);
10153 #else
10154 x_catch_errors (dpy);
10155 rc = XGetWindowProperty (dpy, window, dpyinfo->Xatom_net_wm_state,
10156 0, max_len, False, target_type,
10157 &actual_type, &actual_format, &actual_size,
10158 &bytes_remaining, &tmp_data);
10160 if (rc == Success && actual_type == target_type && ! x_had_errors_p (dpy))
10161 reply_data = (Atom *) tmp_data;
10162 else
10164 actual_size = 0;
10165 is_hidden = FRAME_ICONIFIED_P (f);
10168 x_uncatch_errors ();
10169 #endif
10171 for (i = 0; i < actual_size; ++i)
10173 Atom a = reply_data[i];
10174 if (a == dpyinfo->Xatom_net_wm_state_hidden)
10175 is_hidden = true;
10176 else if (a == dpyinfo->Xatom_net_wm_state_maximized_horz)
10178 if (*size_state == FULLSCREEN_HEIGHT)
10179 *size_state = FULLSCREEN_MAXIMIZED;
10180 else
10181 *size_state = FULLSCREEN_WIDTH;
10183 else if (a == dpyinfo->Xatom_net_wm_state_maximized_vert)
10185 if (*size_state == FULLSCREEN_WIDTH)
10186 *size_state = FULLSCREEN_MAXIMIZED;
10187 else
10188 *size_state = FULLSCREEN_HEIGHT;
10190 else if (a == dpyinfo->Xatom_net_wm_state_fullscreen)
10191 *size_state = FULLSCREEN_BOTH;
10192 else if (a == dpyinfo->Xatom_net_wm_state_sticky)
10193 *sticky = true;
10196 #ifdef USE_XCB
10197 free (prop);
10198 #else
10199 if (tmp_data) XFree (tmp_data);
10200 #endif
10202 unblock_input ();
10203 return ! is_hidden;
10206 /* Do fullscreen as specified in extended window manager hints */
10208 static bool
10209 do_ewmh_fullscreen (struct frame *f)
10211 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10212 bool have_net_atom = x_wm_supports (f, dpyinfo->Xatom_net_wm_state);
10213 int cur;
10214 bool dummy;
10216 get_current_wm_state (f, FRAME_OUTER_WINDOW (f), &cur, &dummy);
10218 /* Some window managers don't say they support _NET_WM_STATE, but they do say
10219 they support _NET_WM_STATE_FULLSCREEN. Try that also. */
10220 if (!have_net_atom)
10221 have_net_atom = x_wm_supports (f, dpyinfo->Xatom_net_wm_state_fullscreen);
10223 if (have_net_atom && cur != f->want_fullscreen)
10225 Lisp_Object frame;
10227 XSETFRAME (frame, f);
10229 /* Keep number of calls to set_wm_state as low as possible.
10230 Some window managers, or possible Gtk+, hangs when too many
10231 are sent at once. */
10232 switch (f->want_fullscreen)
10234 case FULLSCREEN_BOTH:
10235 if (cur != FULLSCREEN_BOTH)
10236 set_wm_state (frame, true, dpyinfo->Xatom_net_wm_state_fullscreen,
10237 None);
10238 break;
10239 case FULLSCREEN_WIDTH:
10240 if (x_frame_normalize_before_maximize && cur == FULLSCREEN_MAXIMIZED)
10242 set_wm_state (frame, false,
10243 dpyinfo->Xatom_net_wm_state_maximized_horz,
10244 dpyinfo->Xatom_net_wm_state_maximized_vert);
10245 set_wm_state (frame, true,
10246 dpyinfo->Xatom_net_wm_state_maximized_horz, None);
10248 else
10250 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_HEIGHT
10251 || cur == FULLSCREEN_MAXIMIZED)
10252 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
10253 dpyinfo->Xatom_net_wm_state_maximized_vert);
10254 if (cur != FULLSCREEN_MAXIMIZED || x_frame_normalize_before_maximize)
10255 set_wm_state (frame, true,
10256 dpyinfo->Xatom_net_wm_state_maximized_horz, None);
10258 break;
10259 case FULLSCREEN_HEIGHT:
10260 if (x_frame_normalize_before_maximize && cur == FULLSCREEN_MAXIMIZED)
10262 set_wm_state (frame, false,
10263 dpyinfo->Xatom_net_wm_state_maximized_horz,
10264 dpyinfo->Xatom_net_wm_state_maximized_vert);
10265 set_wm_state (frame, true,
10266 dpyinfo->Xatom_net_wm_state_maximized_vert, None);
10268 else
10270 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_WIDTH
10271 || cur == FULLSCREEN_MAXIMIZED)
10272 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
10273 dpyinfo->Xatom_net_wm_state_maximized_horz);
10274 if (cur != FULLSCREEN_MAXIMIZED || x_frame_normalize_before_maximize)
10275 set_wm_state (frame, true,
10276 dpyinfo->Xatom_net_wm_state_maximized_vert, None);
10278 break;
10279 case FULLSCREEN_MAXIMIZED:
10280 if (x_frame_normalize_before_maximize && cur == FULLSCREEN_BOTH)
10282 set_wm_state (frame, false,
10283 dpyinfo->Xatom_net_wm_state_fullscreen, None);
10284 set_wm_state (frame, true,
10285 dpyinfo->Xatom_net_wm_state_maximized_horz,
10286 dpyinfo->Xatom_net_wm_state_maximized_vert);
10288 else if (x_frame_normalize_before_maximize && cur == FULLSCREEN_WIDTH)
10290 set_wm_state (frame, false,
10291 dpyinfo->Xatom_net_wm_state_maximized_horz, None);
10292 set_wm_state (frame, true,
10293 dpyinfo->Xatom_net_wm_state_maximized_horz,
10294 dpyinfo->Xatom_net_wm_state_maximized_vert);
10296 else if (x_frame_normalize_before_maximize && cur == FULLSCREEN_HEIGHT)
10298 set_wm_state (frame, false,
10299 dpyinfo->Xatom_net_wm_state_maximized_vert, None);
10300 set_wm_state (frame, true,
10301 dpyinfo->Xatom_net_wm_state_maximized_horz,
10302 dpyinfo->Xatom_net_wm_state_maximized_vert);
10304 else
10306 if (cur == FULLSCREEN_BOTH)
10307 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
10308 None);
10309 else if (cur == FULLSCREEN_HEIGHT)
10310 set_wm_state (frame, true,
10311 dpyinfo->Xatom_net_wm_state_maximized_horz, None);
10312 else if (cur == FULLSCREEN_WIDTH)
10313 set_wm_state (frame, true, None,
10314 dpyinfo->Xatom_net_wm_state_maximized_vert);
10315 else
10316 set_wm_state (frame, true,
10317 dpyinfo->Xatom_net_wm_state_maximized_horz,
10318 dpyinfo->Xatom_net_wm_state_maximized_vert);
10320 break;
10321 case FULLSCREEN_NONE:
10322 if (cur == FULLSCREEN_BOTH)
10323 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
10324 None);
10325 else
10326 set_wm_state (frame, false,
10327 dpyinfo->Xatom_net_wm_state_maximized_horz,
10328 dpyinfo->Xatom_net_wm_state_maximized_vert);
10331 f->want_fullscreen = FULLSCREEN_NONE;
10335 return have_net_atom;
10338 static void
10339 XTfullscreen_hook (struct frame *f)
10341 if (FRAME_VISIBLE_P (f))
10343 block_input ();
10344 x_check_fullscreen (f);
10345 x_sync (f);
10346 unblock_input ();
10351 static bool
10352 x_handle_net_wm_state (struct frame *f, const XPropertyEvent *event)
10354 int value = FULLSCREEN_NONE;
10355 Lisp_Object lval;
10356 bool sticky = false;
10357 bool not_hidden = get_current_wm_state (f, event->window, &value, &sticky);
10359 lval = Qnil;
10360 switch (value)
10362 case FULLSCREEN_WIDTH:
10363 lval = Qfullwidth;
10364 break;
10365 case FULLSCREEN_HEIGHT:
10366 lval = Qfullheight;
10367 break;
10368 case FULLSCREEN_BOTH:
10369 lval = Qfullboth;
10370 break;
10371 case FULLSCREEN_MAXIMIZED:
10372 lval = Qmaximized;
10373 break;
10376 frame_size_history_add
10377 (f, Qx_handle_net_wm_state, 0, 0,
10378 list2 (get_frame_param (f, Qfullscreen), lval));
10380 store_frame_param (f, Qfullscreen, lval);
10381 store_frame_param (f, Qsticky, sticky ? Qt : Qnil);
10383 return not_hidden;
10386 /* Check if we need to resize the frame due to a fullscreen request.
10387 If so needed, resize the frame. */
10388 static void
10389 x_check_fullscreen (struct frame *f)
10391 Lisp_Object lval = Qnil;
10393 if (do_ewmh_fullscreen (f))
10394 return;
10396 if (f->output_data.x->parent_desc != FRAME_DISPLAY_INFO (f)->root_window)
10397 return; /* Only fullscreen without WM or with EWM hints (above). */
10399 /* Setting fullscreen to nil doesn't do anything. We could save the
10400 last non-fullscreen size and restore it, but it seems like a
10401 lot of work for this unusual case (no window manager running). */
10403 if (f->want_fullscreen != FULLSCREEN_NONE)
10405 int width = FRAME_PIXEL_WIDTH (f), height = FRAME_PIXEL_HEIGHT (f);
10406 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10408 switch (f->want_fullscreen)
10410 /* No difference between these two when there is no WM */
10411 case FULLSCREEN_MAXIMIZED:
10412 lval = Qmaximized;
10413 width = x_display_pixel_width (dpyinfo);
10414 height = x_display_pixel_height (dpyinfo);
10415 break;
10416 case FULLSCREEN_BOTH:
10417 lval = Qfullboth;
10418 width = x_display_pixel_width (dpyinfo);
10419 height = x_display_pixel_height (dpyinfo);
10420 break;
10421 case FULLSCREEN_WIDTH:
10422 lval = Qfullwidth;
10423 width = x_display_pixel_width (dpyinfo);
10424 height = height + FRAME_MENUBAR_HEIGHT (f);
10425 break;
10426 case FULLSCREEN_HEIGHT:
10427 lval = Qfullheight;
10428 height = x_display_pixel_height (dpyinfo);
10429 break;
10430 default:
10431 emacs_abort ();
10434 frame_size_history_add
10435 (f, Qx_check_fullscreen, width, height, Qnil);
10437 x_wm_set_size_hint (f, 0, false);
10439 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
10440 width, height);
10442 if (FRAME_VISIBLE_P (f))
10443 x_wait_for_event (f, ConfigureNotify);
10444 else
10446 change_frame_size (f, width, height - FRAME_MENUBAR_HEIGHT (f),
10447 false, true, false, true);
10448 x_sync (f);
10452 /* `x_net_wm_state' might have reset the fullscreen frame parameter,
10453 restore it. */
10454 store_frame_param (f, Qfullscreen, lval);
10457 /* This function is called by x_set_offset to determine whether the window
10458 manager interfered with the positioning of the frame. Type A window
10459 managers position the surrounding window manager decorations a small
10460 amount above and left of the user-supplied position. Type B window
10461 managers position the surrounding window manager decorations at the
10462 user-specified position. If we detect a Type A window manager, we
10463 compensate by moving the window right and down by the proper amount. */
10465 static void
10466 x_check_expected_move (struct frame *f, int expected_left, int expected_top)
10468 int current_left = 0, current_top = 0;
10470 /* x_real_positions returns the left and top offsets of the outermost
10471 window manager window around the frame. */
10473 x_real_positions (f, &current_left, &current_top);
10475 if (current_left != expected_left || current_top != expected_top)
10477 /* It's a "Type A" window manager. */
10479 int adjusted_left;
10480 int adjusted_top;
10482 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_A;
10483 FRAME_X_OUTPUT (f)->move_offset_left = expected_left - current_left;
10484 FRAME_X_OUTPUT (f)->move_offset_top = expected_top - current_top;
10486 /* Now fix the mispositioned frame's location. */
10488 adjusted_left = expected_left + FRAME_X_OUTPUT (f)->move_offset_left;
10489 adjusted_top = expected_top + FRAME_X_OUTPUT (f)->move_offset_top;
10491 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
10492 adjusted_left, adjusted_top);
10494 x_sync_with_move (f, expected_left, expected_top, false);
10496 else
10497 /* It's a "Type B" window manager. We don't have to adjust the
10498 frame's position. */
10500 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_B;
10504 /* Wait for XGetGeometry to return up-to-date position information for a
10505 recently-moved frame. Call this immediately after calling XMoveWindow.
10506 If FUZZY is non-zero, then LEFT and TOP are just estimates of where the
10507 frame has been moved to, so we use a fuzzy position comparison instead
10508 of an exact comparison. */
10510 static void
10511 x_sync_with_move (struct frame *f, int left, int top, bool fuzzy)
10513 int count = 0;
10515 while (count++ < 50)
10517 int current_left = 0, current_top = 0;
10519 /* In theory, this call to XSync only needs to happen once, but in
10520 practice, it doesn't seem to work, hence the need for the surrounding
10521 loop. */
10523 XSync (FRAME_X_DISPLAY (f), False);
10524 x_real_positions (f, &current_left, &current_top);
10526 if (fuzzy)
10528 /* The left fuzz-factor is 10 pixels. The top fuzz-factor is 40
10529 pixels. */
10531 if (eabs (current_left - left) <= 10
10532 && eabs (current_top - top) <= 40)
10533 return;
10535 else if (current_left == left && current_top == top)
10536 return;
10539 /* As a last resort, just wait 0.5 seconds and hope that XGetGeometry
10540 will then return up-to-date position info. */
10542 wait_reading_process_output (0, 500000000, 0, false, Qnil, NULL, 0);
10546 /* Wait for an event on frame F matching EVENTTYPE. */
10547 void
10548 x_wait_for_event (struct frame *f, int eventtype)
10550 int level = interrupt_input_blocked;
10552 fd_set fds;
10553 struct timespec tmo, tmo_at, time_now;
10554 int fd = ConnectionNumber (FRAME_X_DISPLAY (f));
10556 f->wait_event_type = eventtype;
10558 /* Set timeout to 0.1 second. Hopefully not noticeable.
10559 Maybe it should be configurable. */
10560 tmo = make_timespec (0, 100 * 1000 * 1000);
10561 tmo_at = timespec_add (current_timespec (), tmo);
10563 while (f->wait_event_type)
10565 pending_signals = true;
10566 totally_unblock_input ();
10567 /* XTread_socket is called after unblock. */
10568 block_input ();
10569 interrupt_input_blocked = level;
10571 FD_ZERO (&fds);
10572 FD_SET (fd, &fds);
10574 time_now = current_timespec ();
10575 if (timespec_cmp (tmo_at, time_now) < 0)
10576 break;
10578 tmo = timespec_sub (tmo_at, time_now);
10579 if (pselect (fd + 1, &fds, NULL, NULL, &tmo, NULL) == 0)
10580 break; /* Timeout */
10583 f->wait_event_type = 0;
10587 /* Change the size of frame F's X window to WIDTH/HEIGHT in the case F
10588 doesn't have a widget. If CHANGE_GRAVITY, change to
10589 top-left-corner window gravity for this size change and subsequent
10590 size changes. Otherwise leave the window gravity unchanged. */
10592 static void
10593 x_set_window_size_1 (struct frame *f, bool change_gravity,
10594 int width, int height)
10596 int pixelwidth = FRAME_TEXT_TO_PIXEL_WIDTH (f, width);
10597 int pixelheight = FRAME_TEXT_TO_PIXEL_HEIGHT (f, height);
10598 int old_width = FRAME_PIXEL_WIDTH (f);
10599 int old_height = FRAME_PIXEL_HEIGHT (f);
10600 Lisp_Object fullscreen = get_frame_param (f, Qfullscreen);
10602 if (change_gravity) f->win_gravity = NorthWestGravity;
10603 x_wm_set_size_hint (f, 0, false);
10605 /* When the frame is fullheight and we only want to change the width
10606 or it is fullwidth and we only want to change the height we should
10607 be able to preserve the fullscreen property. However, due to the
10608 fact that we have to send a resize request anyway, the window
10609 manager will abolish it. At least the respective size should
10610 remain unchanged but giving the frame back its normal size will
10611 be broken ... */
10612 if (EQ (fullscreen, Qfullwidth) && width == FRAME_TEXT_WIDTH (f))
10614 frame_size_history_add
10615 (f, Qx_set_window_size_1, width, height,
10616 list2 (make_number (old_height),
10617 make_number (pixelheight + FRAME_MENUBAR_HEIGHT (f))));
10619 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
10620 old_width, pixelheight + FRAME_MENUBAR_HEIGHT (f));
10622 else if (EQ (fullscreen, Qfullheight) && height == FRAME_TEXT_HEIGHT (f))
10624 frame_size_history_add
10625 (f, Qx_set_window_size_2, width, height,
10626 list2 (make_number (old_width), make_number (pixelwidth)));
10628 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
10629 pixelwidth, old_height);
10632 else
10634 frame_size_history_add
10635 (f, Qx_set_window_size_3, width, height,
10636 list3 (make_number (pixelwidth + FRAME_TOOLBAR_WIDTH (f)),
10637 make_number (pixelheight + FRAME_TOOLBAR_HEIGHT (f)
10638 + FRAME_MENUBAR_HEIGHT (f)),
10639 make_number (FRAME_MENUBAR_HEIGHT (f))));
10641 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
10642 pixelwidth, pixelheight + FRAME_MENUBAR_HEIGHT (f));
10643 fullscreen = Qnil;
10648 /* We've set {FRAME,PIXEL}_{WIDTH,HEIGHT} to the values we hope to
10649 receive in the ConfigureNotify event; if we get what we asked
10650 for, then the event won't cause the screen to become garbaged, so
10651 we have to make sure to do it here. */
10652 SET_FRAME_GARBAGED (f);
10654 /* Now, strictly speaking, we can't be sure that this is accurate,
10655 but the window manager will get around to dealing with the size
10656 change request eventually, and we'll hear how it went when the
10657 ConfigureNotify event gets here.
10659 We could just not bother storing any of this information here,
10660 and let the ConfigureNotify event set everything up, but that
10661 might be kind of confusing to the Lisp code, since size changes
10662 wouldn't be reported in the frame parameters until some random
10663 point in the future when the ConfigureNotify event arrives.
10665 Pass true for DELAY since we can't run Lisp code inside of
10666 a BLOCK_INPUT. */
10668 /* But the ConfigureNotify may in fact never arrive, and then this is
10669 not right if the frame is visible. Instead wait (with timeout)
10670 for the ConfigureNotify. */
10671 if (FRAME_VISIBLE_P (f))
10673 x_wait_for_event (f, ConfigureNotify);
10675 if (!NILP (fullscreen))
10676 /* Try to restore fullscreen state. */
10678 store_frame_param (f, Qfullscreen, fullscreen);
10679 x_set_fullscreen (f, fullscreen, fullscreen);
10682 else
10684 change_frame_size (f, width, height, false, true, false, true);
10685 x_sync (f);
10690 /* Call this to change the size of frame F's x-window.
10691 If CHANGE_GRAVITY, change to top-left-corner window gravity
10692 for this size change and subsequent size changes.
10693 Otherwise we leave the window gravity unchanged. */
10695 void
10696 x_set_window_size (struct frame *f, bool change_gravity,
10697 int width, int height, bool pixelwise)
10699 block_input ();
10701 /* The following breaks our calculations. If it's really needed,
10702 think of something else. */
10703 #if false
10704 if (NILP (tip_frame) || XFRAME (tip_frame) != f)
10706 int text_width, text_height;
10708 /* When the frame is maximized/fullscreen or running under for
10709 example Xmonad, x_set_window_size_1 will be a no-op.
10710 In that case, the right thing to do is extend rows/width to
10711 the current frame size. We do that first if x_set_window_size_1
10712 turns out to not be a no-op (there is no way to know).
10713 The size will be adjusted again if the frame gets a
10714 ConfigureNotify event as a result of x_set_window_size. */
10715 int pixelh = FRAME_PIXEL_HEIGHT (f);
10716 #ifdef USE_X_TOOLKIT
10717 /* The menu bar is not part of text lines. The tool bar
10718 is however. */
10719 pixelh -= FRAME_MENUBAR_HEIGHT (f);
10720 #endif
10721 text_width = FRAME_PIXEL_TO_TEXT_WIDTH (f, FRAME_PIXEL_WIDTH (f));
10722 text_height = FRAME_PIXEL_TO_TEXT_HEIGHT (f, pixelh);
10724 change_frame_size (f, text_width, text_height, false, true, false, true);
10726 #endif
10728 /* Pixelize width and height, if necessary. */
10729 if (! pixelwise)
10731 width = width * FRAME_COLUMN_WIDTH (f);
10732 height = height * FRAME_LINE_HEIGHT (f);
10735 #ifdef USE_GTK
10736 if (FRAME_GTK_WIDGET (f))
10737 xg_frame_set_char_size (f, width, height);
10738 else
10739 x_set_window_size_1 (f, change_gravity, width, height);
10740 #else /* not USE_GTK */
10741 x_set_window_size_1 (f, change_gravity, width, height);
10742 x_clear_under_internal_border (f);
10743 #endif /* not USE_GTK */
10745 /* If cursor was outside the new size, mark it as off. */
10746 mark_window_cursors_off (XWINDOW (f->root_window));
10748 /* Clear out any recollection of where the mouse highlighting was,
10749 since it might be in a place that's outside the new frame size.
10750 Actually checking whether it is outside is a pain in the neck,
10751 so don't try--just let the highlighting be done afresh with new size. */
10752 cancel_mouse_face (f);
10754 unblock_input ();
10756 do_pending_window_change (false);
10759 /* Move the mouse to position pixel PIX_X, PIX_Y relative to frame F. */
10761 void
10762 frame_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
10764 block_input ();
10766 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
10767 0, 0, 0, 0, pix_x, pix_y);
10768 unblock_input ();
10771 /* Raise frame F. */
10773 void
10774 x_raise_frame (struct frame *f)
10776 block_input ();
10777 if (FRAME_VISIBLE_P (f))
10778 XRaiseWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
10779 XFlush (FRAME_X_DISPLAY (f));
10780 unblock_input ();
10783 /* Lower frame F. */
10785 static void
10786 x_lower_frame (struct frame *f)
10788 if (FRAME_VISIBLE_P (f))
10790 block_input ();
10791 XLowerWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
10792 XFlush (FRAME_X_DISPLAY (f));
10793 unblock_input ();
10797 /* Request focus with XEmbed */
10799 void
10800 xembed_request_focus (struct frame *f)
10802 /* See XEmbed Protocol Specification at
10803 http://freedesktop.org/wiki/Specifications/xembed-spec */
10804 if (FRAME_VISIBLE_P (f))
10805 xembed_send_message (f, CurrentTime,
10806 XEMBED_REQUEST_FOCUS, 0, 0, 0);
10809 /* Activate frame with Extended Window Manager Hints */
10811 void
10812 x_ewmh_activate_frame (struct frame *f)
10814 /* See Window Manager Specification/Extended Window Manager Hints at
10815 http://freedesktop.org/wiki/Specifications/wm-spec */
10817 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10819 if (FRAME_VISIBLE_P (f) && x_wm_supports (f, dpyinfo->Xatom_net_active_window))
10821 Lisp_Object frame;
10822 XSETFRAME (frame, f);
10823 x_send_client_event (frame, make_number (0), frame,
10824 dpyinfo->Xatom_net_active_window,
10825 make_number (32),
10826 list2i (1, dpyinfo->last_user_time));
10830 static void
10831 XTframe_raise_lower (struct frame *f, bool raise_flag)
10833 if (raise_flag)
10834 x_raise_frame (f);
10835 else
10836 x_lower_frame (f);
10839 /* XEmbed implementation. */
10841 #if defined USE_X_TOOLKIT || ! defined USE_GTK
10843 /* XEmbed implementation. */
10845 #define XEMBED_VERSION 0
10847 static void
10848 xembed_set_info (struct frame *f, enum xembed_info flags)
10850 unsigned long data[2];
10851 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10853 data[0] = XEMBED_VERSION;
10854 data[1] = flags;
10856 XChangeProperty (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
10857 dpyinfo->Xatom_XEMBED_INFO, dpyinfo->Xatom_XEMBED_INFO,
10858 32, PropModeReplace, (unsigned char *) data, 2);
10860 #endif /* defined USE_X_TOOLKIT || ! defined USE_GTK */
10862 static void
10863 xembed_send_message (struct frame *f, Time t, enum xembed_message msg,
10864 long int detail, long int data1, long int data2)
10866 XEvent event;
10868 event.xclient.type = ClientMessage;
10869 event.xclient.window = FRAME_X_OUTPUT (f)->parent_desc;
10870 event.xclient.message_type = FRAME_DISPLAY_INFO (f)->Xatom_XEMBED;
10871 event.xclient.format = 32;
10872 event.xclient.data.l[0] = t;
10873 event.xclient.data.l[1] = msg;
10874 event.xclient.data.l[2] = detail;
10875 event.xclient.data.l[3] = data1;
10876 event.xclient.data.l[4] = data2;
10878 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_OUTPUT (f)->parent_desc,
10879 False, NoEventMask, &event);
10880 XSync (FRAME_X_DISPLAY (f), False);
10883 /* Change of visibility. */
10885 /* This tries to wait until the frame is really visible.
10886 However, if the window manager asks the user where to position
10887 the frame, this will return before the user finishes doing that.
10888 The frame will not actually be visible at that time,
10889 but it will become visible later when the window manager
10890 finishes with it. */
10892 void
10893 x_make_frame_visible (struct frame *f)
10895 int original_top, original_left;
10896 int tries = 0;
10898 block_input ();
10900 x_set_bitmap_icon (f);
10902 if (! FRAME_VISIBLE_P (f))
10904 /* We test FRAME_GARBAGED_P here to make sure we don't
10905 call x_set_offset a second time
10906 if we get to x_make_frame_visible a second time
10907 before the window gets really visible. */
10908 if (! FRAME_ICONIFIED_P (f)
10909 && ! FRAME_X_EMBEDDED_P (f)
10910 && ! f->output_data.x->asked_for_visible)
10911 x_set_offset (f, f->left_pos, f->top_pos, 0);
10913 f->output_data.x->asked_for_visible = true;
10915 if (! EQ (Vx_no_window_manager, Qt))
10916 x_wm_set_window_state (f, NormalState);
10917 #ifdef USE_X_TOOLKIT
10918 if (FRAME_X_EMBEDDED_P (f))
10919 xembed_set_info (f, XEMBED_MAPPED);
10920 else
10922 /* This was XtPopup, but that did nothing for an iconified frame. */
10923 XtMapWidget (f->output_data.x->widget);
10925 #else /* not USE_X_TOOLKIT */
10926 #ifdef USE_GTK
10927 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
10928 gtk_window_deiconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
10929 #else
10930 if (FRAME_X_EMBEDDED_P (f))
10931 xembed_set_info (f, XEMBED_MAPPED);
10932 else
10933 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
10934 #endif /* not USE_GTK */
10935 #endif /* not USE_X_TOOLKIT */
10938 XFlush (FRAME_X_DISPLAY (f));
10940 /* Synchronize to ensure Emacs knows the frame is visible
10941 before we do anything else. We do this loop with input not blocked
10942 so that incoming events are handled. */
10944 Lisp_Object frame;
10945 /* This must be before UNBLOCK_INPUT
10946 since events that arrive in response to the actions above
10947 will set it when they are handled. */
10948 bool previously_visible = f->output_data.x->has_been_visible;
10950 original_left = f->left_pos;
10951 original_top = f->top_pos;
10953 /* This must come after we set COUNT. */
10954 unblock_input ();
10956 /* We unblock here so that arriving X events are processed. */
10958 /* Now move the window back to where it was "supposed to be".
10959 But don't do it if the gravity is negative.
10960 When the gravity is negative, this uses a position
10961 that is 3 pixels too low. Perhaps that's really the border width.
10963 Don't do this if the window has never been visible before,
10964 because the window manager may choose the position
10965 and we don't want to override it. */
10967 if (! FRAME_VISIBLE_P (f)
10968 && ! FRAME_ICONIFIED_P (f)
10969 && ! FRAME_X_EMBEDDED_P (f)
10970 && f->win_gravity == NorthWestGravity
10971 && previously_visible)
10973 Drawable rootw;
10974 int x, y;
10975 unsigned int width, height, border, depth;
10977 block_input ();
10979 /* On some window managers (such as FVWM) moving an existing
10980 window, even to the same place, causes the window manager
10981 to introduce an offset. This can cause the window to move
10982 to an unexpected location. Check the geometry (a little
10983 slow here) and then verify that the window is in the right
10984 place. If the window is not in the right place, move it
10985 there, and take the potential window manager hit. */
10986 XGetGeometry (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
10987 &rootw, &x, &y, &width, &height, &border, &depth);
10989 if (original_left != x || original_top != y)
10990 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
10991 original_left, original_top);
10993 unblock_input ();
10996 XSETFRAME (frame, f);
10998 /* Process X events until a MapNotify event has been seen. */
10999 while (!FRAME_VISIBLE_P (f))
11001 /* Force processing of queued events. */
11002 x_sync (f);
11004 /* If on another desktop, the deiconify/map may be ignored and the
11005 frame never becomes visible. XMonad does this.
11006 Prevent an endless loop. */
11007 if (FRAME_ICONIFIED_P (f) && ++tries > 100)
11008 break;
11010 /* This hack is still in use at least for Cygwin. See
11011 http://lists.gnu.org/archive/html/emacs-devel/2013-12/msg00351.html.
11013 Machines that do polling rather than SIGIO have been
11014 observed to go into a busy-wait here. So we'll fake an
11015 alarm signal to let the handler know that there's something
11016 to be read. We used to raise a real alarm, but it seems
11017 that the handler isn't always enabled here. This is
11018 probably a bug. */
11019 if (input_polling_used ())
11021 /* It could be confusing if a real alarm arrives while
11022 processing the fake one. Turn it off and let the
11023 handler reset it. */
11024 int old_poll_suppress_count = poll_suppress_count;
11025 poll_suppress_count = 1;
11026 poll_for_input_1 ();
11027 poll_suppress_count = old_poll_suppress_count;
11030 if (XPending (FRAME_X_DISPLAY (f)))
11032 XEvent xev;
11033 XNextEvent (FRAME_X_DISPLAY (f), &xev);
11034 x_dispatch_event (&xev, FRAME_X_DISPLAY (f));
11040 /* Change from mapped state to withdrawn state. */
11042 /* Make the frame visible (mapped and not iconified). */
11044 void
11045 x_make_frame_invisible (struct frame *f)
11047 Window window;
11049 /* Use the frame's outermost window, not the one we normally draw on. */
11050 window = FRAME_OUTER_WINDOW (f);
11052 /* Don't keep the highlight on an invisible frame. */
11053 if (FRAME_DISPLAY_INFO (f)->x_highlight_frame == f)
11054 FRAME_DISPLAY_INFO (f)->x_highlight_frame = 0;
11056 block_input ();
11058 /* Before unmapping the window, update the WM_SIZE_HINTS property to claim
11059 that the current position of the window is user-specified, rather than
11060 program-specified, so that when the window is mapped again, it will be
11061 placed at the same location, without forcing the user to position it
11062 by hand again (they have already done that once for this window.) */
11063 x_wm_set_size_hint (f, 0, true);
11065 #ifdef USE_GTK
11066 if (FRAME_GTK_OUTER_WIDGET (f))
11067 gtk_widget_hide (FRAME_GTK_OUTER_WIDGET (f));
11068 else
11069 #else
11070 if (FRAME_X_EMBEDDED_P (f))
11071 xembed_set_info (f, 0);
11072 else
11073 #endif
11076 if (! XWithdrawWindow (FRAME_X_DISPLAY (f), window,
11077 DefaultScreen (FRAME_X_DISPLAY (f))))
11079 unblock_input ();
11080 error ("Can't notify window manager of window withdrawal");
11084 /* We can't distinguish this from iconification
11085 just by the event that we get from the server.
11086 So we can't win using the usual strategy of letting
11087 FRAME_SAMPLE_VISIBILITY set this. So do it by hand,
11088 and synchronize with the server to make sure we agree. */
11089 SET_FRAME_VISIBLE (f, 0);
11090 SET_FRAME_ICONIFIED (f, false);
11092 x_sync (f);
11094 unblock_input ();
11097 /* Change window state from mapped to iconified. */
11099 void
11100 x_iconify_frame (struct frame *f)
11102 #ifdef USE_X_TOOLKIT
11103 int result;
11104 #endif
11106 /* Don't keep the highlight on an invisible frame. */
11107 if (FRAME_DISPLAY_INFO (f)->x_highlight_frame == f)
11108 FRAME_DISPLAY_INFO (f)->x_highlight_frame = 0;
11110 if (FRAME_ICONIFIED_P (f))
11111 return;
11113 block_input ();
11115 x_set_bitmap_icon (f);
11117 #if defined (USE_GTK)
11118 if (FRAME_GTK_OUTER_WIDGET (f))
11120 if (! FRAME_VISIBLE_P (f))
11121 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
11123 gtk_window_iconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
11124 SET_FRAME_VISIBLE (f, 0);
11125 SET_FRAME_ICONIFIED (f, true);
11126 unblock_input ();
11127 return;
11129 #endif
11131 #ifdef USE_X_TOOLKIT
11133 if (! FRAME_VISIBLE_P (f))
11135 if (! EQ (Vx_no_window_manager, Qt))
11136 x_wm_set_window_state (f, IconicState);
11137 /* This was XtPopup, but that did nothing for an iconified frame. */
11138 XtMapWidget (f->output_data.x->widget);
11139 /* The server won't give us any event to indicate
11140 that an invisible frame was changed to an icon,
11141 so we have to record it here. */
11142 SET_FRAME_VISIBLE (f, 0);
11143 SET_FRAME_ICONIFIED (f, true);
11144 unblock_input ();
11145 return;
11148 result = XIconifyWindow (FRAME_X_DISPLAY (f),
11149 XtWindow (f->output_data.x->widget),
11150 DefaultScreen (FRAME_X_DISPLAY (f)));
11151 unblock_input ();
11153 if (!result)
11154 error ("Can't notify window manager of iconification");
11156 SET_FRAME_ICONIFIED (f, true);
11157 SET_FRAME_VISIBLE (f, 0);
11159 block_input ();
11160 XFlush (FRAME_X_DISPLAY (f));
11161 unblock_input ();
11162 #else /* not USE_X_TOOLKIT */
11164 /* Make sure the X server knows where the window should be positioned,
11165 in case the user deiconifies with the window manager. */
11166 if (! FRAME_VISIBLE_P (f)
11167 && ! FRAME_ICONIFIED_P (f)
11168 && ! FRAME_X_EMBEDDED_P (f))
11169 x_set_offset (f, f->left_pos, f->top_pos, 0);
11171 /* Since we don't know which revision of X we're running, we'll use both
11172 the X11R3 and X11R4 techniques. I don't know if this is a good idea. */
11174 /* X11R4: send a ClientMessage to the window manager using the
11175 WM_CHANGE_STATE type. */
11177 XEvent msg;
11179 msg.xclient.window = FRAME_X_WINDOW (f);
11180 msg.xclient.type = ClientMessage;
11181 msg.xclient.message_type = FRAME_DISPLAY_INFO (f)->Xatom_wm_change_state;
11182 msg.xclient.format = 32;
11183 msg.xclient.data.l[0] = IconicState;
11185 if (! XSendEvent (FRAME_X_DISPLAY (f),
11186 DefaultRootWindow (FRAME_X_DISPLAY (f)),
11187 False,
11188 SubstructureRedirectMask | SubstructureNotifyMask,
11189 &msg))
11191 unblock_input ();
11192 error ("Can't notify window manager of iconification");
11196 /* X11R3: set the initial_state field of the window manager hints to
11197 IconicState. */
11198 x_wm_set_window_state (f, IconicState);
11200 if (!FRAME_VISIBLE_P (f))
11202 /* If the frame was withdrawn, before, we must map it. */
11203 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11206 SET_FRAME_ICONIFIED (f, true);
11207 SET_FRAME_VISIBLE (f, 0);
11209 XFlush (FRAME_X_DISPLAY (f));
11210 unblock_input ();
11211 #endif /* not USE_X_TOOLKIT */
11215 /* Free X resources of frame F. */
11217 void
11218 x_free_frame_resources (struct frame *f)
11220 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
11221 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
11222 #ifdef USE_X_TOOLKIT
11223 Lisp_Object bar;
11224 struct scroll_bar *b;
11225 #endif
11227 block_input ();
11229 /* If a display connection is dead, don't try sending more
11230 commands to the X server. */
11231 if (dpyinfo->display)
11233 /* Always exit with visible pointer to avoid weird issue
11234 with Xfixes (Bug#17609). */
11235 if (f->pointer_invisible)
11236 FRAME_DISPLAY_INFO (f)->toggle_visible_pointer (f, 0);
11238 /* We must free faces before destroying windows because some
11239 font-driver (e.g. xft) access a window while finishing a
11240 face. */
11241 free_frame_faces (f);
11243 if (f->output_data.x->icon_desc)
11244 XDestroyWindow (FRAME_X_DISPLAY (f), f->output_data.x->icon_desc);
11246 #ifdef USE_X_TOOLKIT
11247 /* Explicitly destroy the scroll bars of the frame. Without
11248 this, we get "BadDrawable" errors from the toolkit later on,
11249 presumably from expose events generated for the disappearing
11250 toolkit scroll bars. */
11251 for (bar = FRAME_SCROLL_BARS (f); !NILP (bar); bar = b->next)
11253 b = XSCROLL_BAR (bar);
11254 x_scroll_bar_remove (b);
11256 #endif
11258 #ifdef HAVE_X_I18N
11259 if (FRAME_XIC (f))
11260 free_frame_xic (f);
11261 #endif
11263 x_free_cr_resources (f);
11264 #ifdef USE_X_TOOLKIT
11265 if (f->output_data.x->widget)
11267 XtDestroyWidget (f->output_data.x->widget);
11268 f->output_data.x->widget = NULL;
11270 /* Tooltips don't have widgets, only a simple X window, even if
11271 we are using a toolkit. */
11272 else if (FRAME_X_WINDOW (f))
11273 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11275 free_frame_menubar (f);
11277 if (f->shell_position)
11278 xfree (f->shell_position);
11279 #else /* !USE_X_TOOLKIT */
11281 #ifdef USE_GTK
11282 xg_free_frame_widgets (f);
11283 #endif /* USE_GTK */
11285 if (FRAME_X_WINDOW (f))
11286 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11287 #endif /* !USE_X_TOOLKIT */
11289 unload_color (f, FRAME_FOREGROUND_PIXEL (f));
11290 unload_color (f, FRAME_BACKGROUND_PIXEL (f));
11291 unload_color (f, f->output_data.x->cursor_pixel);
11292 unload_color (f, f->output_data.x->cursor_foreground_pixel);
11293 unload_color (f, f->output_data.x->border_pixel);
11294 unload_color (f, f->output_data.x->mouse_pixel);
11296 if (f->output_data.x->scroll_bar_background_pixel != -1)
11297 unload_color (f, f->output_data.x->scroll_bar_background_pixel);
11298 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
11299 unload_color (f, f->output_data.x->scroll_bar_foreground_pixel);
11300 #if defined (USE_LUCID) && defined (USE_TOOLKIT_SCROLL_BARS)
11301 /* Scrollbar shadow colors. */
11302 if (f->output_data.x->scroll_bar_top_shadow_pixel != -1)
11303 unload_color (f, f->output_data.x->scroll_bar_top_shadow_pixel);
11304 if (f->output_data.x->scroll_bar_bottom_shadow_pixel != -1)
11305 unload_color (f, f->output_data.x->scroll_bar_bottom_shadow_pixel);
11306 #endif /* USE_LUCID && USE_TOOLKIT_SCROLL_BARS */
11307 if (f->output_data.x->white_relief.pixel != -1)
11308 unload_color (f, f->output_data.x->white_relief.pixel);
11309 if (f->output_data.x->black_relief.pixel != -1)
11310 unload_color (f, f->output_data.x->black_relief.pixel);
11312 x_free_gcs (f);
11314 /* Free extra GCs allocated by x_setup_relief_colors. */
11315 if (f->output_data.x->white_relief.gc)
11317 XFreeGC (dpyinfo->display, f->output_data.x->white_relief.gc);
11318 f->output_data.x->white_relief.gc = 0;
11320 if (f->output_data.x->black_relief.gc)
11322 XFreeGC (dpyinfo->display, f->output_data.x->black_relief.gc);
11323 f->output_data.x->black_relief.gc = 0;
11326 /* Free cursors. */
11327 if (f->output_data.x->text_cursor != 0)
11328 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->text_cursor);
11329 if (f->output_data.x->nontext_cursor != 0)
11330 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->nontext_cursor);
11331 if (f->output_data.x->modeline_cursor != 0)
11332 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->modeline_cursor);
11333 if (f->output_data.x->hand_cursor != 0)
11334 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->hand_cursor);
11335 if (f->output_data.x->hourglass_cursor != 0)
11336 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->hourglass_cursor);
11337 if (f->output_data.x->horizontal_drag_cursor != 0)
11338 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->horizontal_drag_cursor);
11339 if (f->output_data.x->vertical_drag_cursor != 0)
11340 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->vertical_drag_cursor);
11342 XFlush (FRAME_X_DISPLAY (f));
11345 xfree (f->output_data.x->saved_menu_event);
11346 xfree (f->output_data.x);
11347 f->output_data.x = NULL;
11349 if (f == dpyinfo->x_focus_frame)
11350 dpyinfo->x_focus_frame = 0;
11351 if (f == dpyinfo->x_focus_event_frame)
11352 dpyinfo->x_focus_event_frame = 0;
11353 if (f == dpyinfo->x_highlight_frame)
11354 dpyinfo->x_highlight_frame = 0;
11355 if (f == hlinfo->mouse_face_mouse_frame)
11356 reset_mouse_highlight (hlinfo);
11358 unblock_input ();
11362 /* Destroy the X window of frame F. */
11364 static void
11365 x_destroy_window (struct frame *f)
11367 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
11369 /* If a display connection is dead, don't try sending more
11370 commands to the X server. */
11371 if (dpyinfo->display != 0)
11372 x_free_frame_resources (f);
11374 dpyinfo->reference_count--;
11378 /* Setting window manager hints. */
11380 /* Set the normal size hints for the window manager, for frame F.
11381 FLAGS is the flags word to use--or 0 meaning preserve the flags
11382 that the window now has.
11383 If USER_POSITION, set the USPosition
11384 flag (this is useful when FLAGS is 0).
11385 The GTK version is in gtkutils.c. */
11387 #ifndef USE_GTK
11388 void
11389 x_wm_set_size_hint (struct frame *f, long flags, bool user_position)
11391 XSizeHints size_hints;
11392 Window window = FRAME_OUTER_WINDOW (f);
11394 if (!window)
11395 return;
11397 #ifdef USE_X_TOOLKIT
11398 if (f->output_data.x->widget)
11400 widget_update_wm_size_hints (f->output_data.x->widget);
11401 return;
11403 #endif
11405 /* Setting PMaxSize caused various problems. */
11406 size_hints.flags = PResizeInc | PMinSize /* | PMaxSize */;
11408 size_hints.x = f->left_pos;
11409 size_hints.y = f->top_pos;
11411 size_hints.width = FRAME_PIXEL_WIDTH (f);
11412 size_hints.height = FRAME_PIXEL_HEIGHT (f);
11414 size_hints.width_inc = frame_resize_pixelwise ? 1 : FRAME_COLUMN_WIDTH (f);
11415 size_hints.height_inc = frame_resize_pixelwise ? 1 : FRAME_LINE_HEIGHT (f);
11417 size_hints.max_width = x_display_pixel_width (FRAME_DISPLAY_INFO (f))
11418 - FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
11419 size_hints.max_height = x_display_pixel_height (FRAME_DISPLAY_INFO (f))
11420 - FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
11422 /* Calculate the base and minimum sizes. */
11424 int base_width, base_height;
11426 base_width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
11427 base_height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
11429 /* The window manager uses the base width hints to calculate the
11430 current number of rows and columns in the frame while
11431 resizing; min_width and min_height aren't useful for this
11432 purpose, since they might not give the dimensions for a
11433 zero-row, zero-column frame. */
11435 size_hints.flags |= PBaseSize;
11436 size_hints.base_width = base_width;
11437 size_hints.base_height = base_height + FRAME_MENUBAR_HEIGHT (f);
11438 size_hints.min_width = base_width;
11439 size_hints.min_height = base_height;
11442 /* If we don't need the old flags, we don't need the old hint at all. */
11443 if (flags)
11445 size_hints.flags |= flags;
11446 goto no_read;
11450 XSizeHints hints; /* Sometimes I hate X Windows... */
11451 long supplied_return;
11452 int value;
11454 value = XGetWMNormalHints (FRAME_X_DISPLAY (f), window, &hints,
11455 &supplied_return);
11457 if (flags)
11458 size_hints.flags |= flags;
11459 else
11461 if (value == 0)
11462 hints.flags = 0;
11463 if (hints.flags & PSize)
11464 size_hints.flags |= PSize;
11465 if (hints.flags & PPosition)
11466 size_hints.flags |= PPosition;
11467 if (hints.flags & USPosition)
11468 size_hints.flags |= USPosition;
11469 if (hints.flags & USSize)
11470 size_hints.flags |= USSize;
11474 no_read:
11476 #ifdef PWinGravity
11477 size_hints.win_gravity = f->win_gravity;
11478 size_hints.flags |= PWinGravity;
11480 if (user_position)
11482 size_hints.flags &= ~ PPosition;
11483 size_hints.flags |= USPosition;
11485 #endif /* PWinGravity */
11487 XSetWMNormalHints (FRAME_X_DISPLAY (f), window, &size_hints);
11489 #endif /* not USE_GTK */
11491 /* Used for IconicState or NormalState */
11493 static void
11494 x_wm_set_window_state (struct frame *f, int state)
11496 #ifdef USE_X_TOOLKIT
11497 Arg al[1];
11499 XtSetArg (al[0], XtNinitialState, state);
11500 XtSetValues (f->output_data.x->widget, al, 1);
11501 #else /* not USE_X_TOOLKIT */
11502 Window window = FRAME_X_WINDOW (f);
11504 f->output_data.x->wm_hints.flags |= StateHint;
11505 f->output_data.x->wm_hints.initial_state = state;
11507 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
11508 #endif /* not USE_X_TOOLKIT */
11511 static void
11512 x_wm_set_icon_pixmap (struct frame *f, ptrdiff_t pixmap_id)
11514 Pixmap icon_pixmap, icon_mask;
11516 #if !defined USE_X_TOOLKIT && !defined USE_GTK
11517 Window window = FRAME_OUTER_WINDOW (f);
11518 #endif
11520 if (pixmap_id > 0)
11522 icon_pixmap = x_bitmap_pixmap (f, pixmap_id);
11523 f->output_data.x->wm_hints.icon_pixmap = icon_pixmap;
11524 icon_mask = x_bitmap_mask (f, pixmap_id);
11525 f->output_data.x->wm_hints.icon_mask = icon_mask;
11527 else
11529 /* It seems there is no way to turn off use of an icon
11530 pixmap. */
11531 return;
11535 #ifdef USE_GTK
11537 xg_set_frame_icon (f, icon_pixmap, icon_mask);
11538 return;
11541 #elif defined (USE_X_TOOLKIT) /* same as in x_wm_set_window_state. */
11544 Arg al[1];
11545 XtSetArg (al[0], XtNiconPixmap, icon_pixmap);
11546 XtSetValues (f->output_data.x->widget, al, 1);
11547 XtSetArg (al[0], XtNiconMask, icon_mask);
11548 XtSetValues (f->output_data.x->widget, al, 1);
11551 #else /* not USE_X_TOOLKIT && not USE_GTK */
11553 f->output_data.x->wm_hints.flags |= (IconPixmapHint | IconMaskHint);
11554 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
11556 #endif /* not USE_X_TOOLKIT && not USE_GTK */
11559 void
11560 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
11562 Window window = FRAME_OUTER_WINDOW (f);
11564 f->output_data.x->wm_hints.flags |= IconPositionHint;
11565 f->output_data.x->wm_hints.icon_x = icon_x;
11566 f->output_data.x->wm_hints.icon_y = icon_y;
11568 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
11572 /***********************************************************************
11573 Fonts
11574 ***********************************************************************/
11576 #ifdef GLYPH_DEBUG
11578 /* Check that FONT is valid on frame F. It is if it can be found in F's
11579 font table. */
11581 static void
11582 x_check_font (struct frame *f, struct font *font)
11584 eassert (font != NULL && ! NILP (font->props[FONT_TYPE_INDEX]));
11585 if (font->driver->check)
11586 eassert (font->driver->check (f, font) == 0);
11589 #endif /* GLYPH_DEBUG */
11592 /***********************************************************************
11593 Initialization
11594 ***********************************************************************/
11596 #ifdef USE_X_TOOLKIT
11597 static XrmOptionDescRec emacs_options[] = {
11598 {"-geometry", ".geometry", XrmoptionSepArg, NULL},
11599 {"-iconic", ".iconic", XrmoptionNoArg, (XtPointer) "yes"},
11601 {"-internal-border-width", "*EmacsScreen.internalBorderWidth",
11602 XrmoptionSepArg, NULL},
11603 {"-ib", "*EmacsScreen.internalBorderWidth", XrmoptionSepArg, NULL},
11605 {"-T", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
11606 {"-wn", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
11607 {"-title", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
11608 {"-iconname", "*EmacsShell.iconName", XrmoptionSepArg, (XtPointer) NULL},
11609 {"-in", "*EmacsShell.iconName", XrmoptionSepArg, (XtPointer) NULL},
11610 {"-mc", "*pointerColor", XrmoptionSepArg, (XtPointer) NULL},
11611 {"-cr", "*cursorColor", XrmoptionSepArg, (XtPointer) NULL}
11614 /* Whether atimer for Xt timeouts is activated or not. */
11616 static bool x_timeout_atimer_activated_flag;
11618 #endif /* USE_X_TOOLKIT */
11620 static int x_initialized;
11622 /* Test whether two display-name strings agree up to the dot that separates
11623 the screen number from the server number. */
11624 static bool
11625 same_x_server (const char *name1, const char *name2)
11627 bool seen_colon = false;
11628 Lisp_Object sysname = Fsystem_name ();
11629 const char *system_name = SSDATA (sysname);
11630 ptrdiff_t system_name_length = SBYTES (sysname);
11631 ptrdiff_t length_until_period = 0;
11633 while (system_name[length_until_period] != 0
11634 && system_name[length_until_period] != '.')
11635 length_until_period++;
11637 /* Treat `unix' like an empty host name. */
11638 if (! strncmp (name1, "unix:", 5))
11639 name1 += 4;
11640 if (! strncmp (name2, "unix:", 5))
11641 name2 += 4;
11642 /* Treat this host's name like an empty host name. */
11643 if (! strncmp (name1, system_name, system_name_length)
11644 && name1[system_name_length] == ':')
11645 name1 += system_name_length;
11646 if (! strncmp (name2, system_name, system_name_length)
11647 && name2[system_name_length] == ':')
11648 name2 += system_name_length;
11649 /* Treat this host's domainless name like an empty host name. */
11650 if (! strncmp (name1, system_name, length_until_period)
11651 && name1[length_until_period] == ':')
11652 name1 += length_until_period;
11653 if (! strncmp (name2, system_name, length_until_period)
11654 && name2[length_until_period] == ':')
11655 name2 += length_until_period;
11657 for (; *name1 != '\0' && *name1 == *name2; name1++, name2++)
11659 if (*name1 == ':')
11660 seen_colon = true;
11661 if (seen_colon && *name1 == '.')
11662 return true;
11664 return (seen_colon
11665 && (*name1 == '.' || *name1 == '\0')
11666 && (*name2 == '.' || *name2 == '\0'));
11669 /* Count number of set bits in mask and number of bits to shift to
11670 get to the first bit. With MASK 0x7e0, *BITS is set to 6, and *OFFSET
11671 to 5. */
11672 static void
11673 get_bits_and_offset (unsigned long mask, int *bits, int *offset)
11675 int nr = 0;
11676 int off = 0;
11678 while (!(mask & 1))
11680 off++;
11681 mask >>= 1;
11684 while (mask & 1)
11686 nr++;
11687 mask >>= 1;
11690 *offset = off;
11691 *bits = nr;
11694 /* Return true iff display DISPLAY is available for use.
11695 But don't permanently open it, just test its availability. */
11697 bool
11698 x_display_ok (const char *display)
11700 /* XOpenDisplay fails if it gets a signal. Block SIGIO which may arrive. */
11701 unrequest_sigio ();
11702 Display *dpy = XOpenDisplay (display);
11703 request_sigio ();
11704 if (!dpy)
11705 return false;
11706 XCloseDisplay (dpy);
11707 return true;
11710 #ifdef USE_GTK
11711 static void
11712 my_log_handler (const gchar *log_domain, GLogLevelFlags log_level,
11713 const gchar *msg, gpointer user_data)
11715 if (!strstr (msg, "g_set_prgname"))
11716 fprintf (stderr, "%s-WARNING **: %s\n", log_domain, msg);
11718 #endif
11720 /* Create invisible cursor on X display referred by DPYINFO. */
11722 static Cursor
11723 make_invisible_cursor (struct x_display_info *dpyinfo)
11725 Display *dpy = dpyinfo->display;
11726 static char const no_data[] = { 0 };
11727 Pixmap pix;
11728 XColor col;
11729 Cursor c = 0;
11731 x_catch_errors (dpy);
11732 pix = XCreateBitmapFromData (dpy, dpyinfo->root_window, no_data, 1, 1);
11733 if (! x_had_errors_p (dpy) && pix != None)
11735 Cursor pixc;
11736 col.pixel = 0;
11737 col.red = col.green = col.blue = 0;
11738 col.flags = DoRed | DoGreen | DoBlue;
11739 pixc = XCreatePixmapCursor (dpy, pix, pix, &col, &col, 0, 0);
11740 if (! x_had_errors_p (dpy) && pixc != None)
11741 c = pixc;
11742 XFreePixmap (dpy, pix);
11745 x_uncatch_errors ();
11747 return c;
11750 /* True if DPY supports Xfixes extension >= 4. */
11752 static bool
11753 x_probe_xfixes_extension (Display *dpy)
11755 #ifdef HAVE_XFIXES
11756 int major, minor;
11757 return XFixesQueryVersion (dpy, &major, &minor) && major >= 4;
11758 #else
11759 return false;
11760 #endif /* HAVE_XFIXES */
11763 /* Toggle mouse pointer visibility on frame F by using Xfixes functions. */
11765 static void
11766 xfixes_toggle_visible_pointer (struct frame *f, bool invisible)
11768 #ifdef HAVE_XFIXES
11769 if (invisible)
11770 XFixesHideCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11771 else
11772 XFixesShowCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11773 f->pointer_invisible = invisible;
11774 #else
11775 emacs_abort ();
11776 #endif /* HAVE_XFIXES */
11779 /* Toggle mouse pointer visibility on frame F by using invisible cursor. */
11781 static void
11782 x_toggle_visible_pointer (struct frame *f, bool invisible)
11784 eassert (FRAME_DISPLAY_INFO (f)->invisible_cursor != 0);
11785 if (invisible)
11786 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
11787 FRAME_DISPLAY_INFO (f)->invisible_cursor);
11788 else
11789 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
11790 f->output_data.x->current_cursor);
11791 f->pointer_invisible = invisible;
11794 /* Setup pointer blanking, prefer Xfixes if available. */
11796 static void
11797 x_setup_pointer_blanking (struct x_display_info *dpyinfo)
11799 /* FIXME: the brave tester should set EMACS_XFIXES because we're suspecting
11800 X server bug, see http://debbugs.gnu.org/cgi/bugreport.cgi?bug=17609. */
11801 if (egetenv ("EMACS_XFIXES") && x_probe_xfixes_extension (dpyinfo->display))
11802 dpyinfo->toggle_visible_pointer = xfixes_toggle_visible_pointer;
11803 else
11805 dpyinfo->toggle_visible_pointer = x_toggle_visible_pointer;
11806 dpyinfo->invisible_cursor = make_invisible_cursor (dpyinfo);
11810 /* Current X display connection identifier. Incremented for each next
11811 connection established. */
11812 static unsigned x_display_id;
11814 /* Open a connection to X display DISPLAY_NAME, and return
11815 the structure that describes the open display.
11816 If we cannot contact the display, return null. */
11818 struct x_display_info *
11819 x_term_init (Lisp_Object display_name, char *xrm_option, char *resource_name)
11821 Display *dpy;
11822 struct terminal *terminal;
11823 struct x_display_info *dpyinfo;
11824 XrmDatabase xrdb;
11825 #ifdef USE_XCB
11826 xcb_connection_t *xcb_conn;
11827 #endif
11829 block_input ();
11831 if (!x_initialized)
11833 x_initialize ();
11834 ++x_initialized;
11837 if (! x_display_ok (SSDATA (display_name)))
11838 error ("Display %s can't be opened", SSDATA (display_name));
11840 #ifdef USE_GTK
11842 #define NUM_ARGV 10
11843 int argc;
11844 char *argv[NUM_ARGV];
11845 char **argv2 = argv;
11846 guint id;
11848 if (x_initialized++ > 1)
11850 xg_display_open (SSDATA (display_name), &dpy);
11852 else
11854 static char display_opt[] = "--display";
11855 static char name_opt[] = "--name";
11857 for (argc = 0; argc < NUM_ARGV; ++argc)
11858 argv[argc] = 0;
11860 argc = 0;
11861 argv[argc++] = initial_argv[0];
11863 if (! NILP (display_name))
11865 argv[argc++] = display_opt;
11866 argv[argc++] = SSDATA (display_name);
11869 argv[argc++] = name_opt;
11870 argv[argc++] = resource_name;
11872 XSetLocaleModifiers ("");
11874 /* Work around GLib bug that outputs a faulty warning. See
11875 https://bugzilla.gnome.org/show_bug.cgi?id=563627. */
11876 id = g_log_set_handler ("GLib", G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
11877 | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
11879 /* NULL window -> events for all windows go to our function.
11880 Call before gtk_init so Gtk+ event filters comes after our. */
11881 gdk_window_add_filter (NULL, event_handler_gdk, NULL);
11883 /* gtk_init does set_locale. Fix locale before and after. */
11884 fixup_locale ();
11885 unrequest_sigio (); /* See comment in x_display_ok. */
11886 gtk_init (&argc, &argv2);
11887 request_sigio ();
11888 fixup_locale ();
11890 g_log_remove_handler ("GLib", id);
11892 xg_initialize ();
11894 dpy = DEFAULT_GDK_DISPLAY ();
11896 #if ! GTK_CHECK_VERSION (2, 90, 0)
11897 /* Load our own gtkrc if it exists. */
11899 const char *file = "~/.emacs.d/gtkrc";
11900 Lisp_Object s, abs_file;
11902 s = build_string (file);
11903 abs_file = Fexpand_file_name (s, Qnil);
11905 if (! NILP (abs_file) && !NILP (Ffile_readable_p (abs_file)))
11906 gtk_rc_parse (SSDATA (abs_file));
11908 #endif
11910 XSetErrorHandler (x_error_handler);
11911 XSetIOErrorHandler (x_io_error_quitter);
11914 #else /* not USE_GTK */
11915 #ifdef USE_X_TOOLKIT
11916 /* weiner@footloose.sps.mot.com reports that this causes
11917 errors with X11R5:
11918 X protocol error: BadAtom (invalid Atom parameter)
11919 on protocol request 18skiloaf.
11920 So let's not use it until R6. */
11921 #ifdef HAVE_X11XTR6
11922 XtSetLanguageProc (NULL, NULL, NULL);
11923 #endif
11926 int argc = 0;
11927 char *argv[3];
11929 argv[0] = "";
11930 argc = 1;
11931 if (xrm_option)
11933 argv[argc++] = "-xrm";
11934 argv[argc++] = xrm_option;
11936 turn_on_atimers (false);
11937 unrequest_sigio (); /* See comment in x_display_ok. */
11938 dpy = XtOpenDisplay (Xt_app_con, SSDATA (display_name),
11939 resource_name, EMACS_CLASS,
11940 emacs_options, XtNumber (emacs_options),
11941 &argc, argv);
11942 request_sigio ();
11943 turn_on_atimers (true);
11945 #ifdef HAVE_X11XTR6
11946 /* I think this is to compensate for XtSetLanguageProc. */
11947 fixup_locale ();
11948 #endif
11951 #else /* not USE_X_TOOLKIT */
11952 XSetLocaleModifiers ("");
11953 unrequest_sigio (); // See comment in x_display_ok.
11954 dpy = XOpenDisplay (SSDATA (display_name));
11955 request_sigio ();
11956 #endif /* not USE_X_TOOLKIT */
11957 #endif /* not USE_GTK*/
11959 /* Detect failure. */
11960 if (dpy == 0)
11962 unblock_input ();
11963 return 0;
11966 #ifdef USE_XCB
11967 xcb_conn = XGetXCBConnection (dpy);
11968 if (xcb_conn == 0)
11970 #ifdef USE_GTK
11971 xg_display_close (dpy);
11972 #else
11973 #ifdef USE_X_TOOLKIT
11974 XtCloseDisplay (dpy);
11975 #else
11976 XCloseDisplay (dpy);
11977 #endif
11978 #endif /* ! USE_GTK */
11980 unblock_input ();
11981 return 0;
11983 #endif
11985 /* We have definitely succeeded. Record the new connection. */
11987 dpyinfo = xzalloc (sizeof *dpyinfo);
11988 terminal = x_create_terminal (dpyinfo);
11991 struct x_display_info *share;
11993 for (share = x_display_list; share; share = share->next)
11994 if (same_x_server (SSDATA (XCAR (share->name_list_element)),
11995 SSDATA (display_name)))
11996 break;
11997 if (share)
11998 terminal->kboard = share->terminal->kboard;
11999 else
12001 terminal->kboard = allocate_kboard (Qx);
12003 if (!EQ (XSYMBOL (Qvendor_specific_keysyms)->function, Qunbound))
12005 char *vendor = ServerVendor (dpy);
12007 /* Temporarily hide the partially initialized terminal. */
12008 terminal_list = terminal->next_terminal;
12009 unblock_input ();
12010 kset_system_key_alist
12011 (terminal->kboard,
12012 call1 (Qvendor_specific_keysyms,
12013 vendor ? build_string (vendor) : empty_unibyte_string));
12014 block_input ();
12015 terminal->next_terminal = terminal_list;
12016 terminal_list = terminal;
12019 /* Don't let the initial kboard remain current longer than necessary.
12020 That would cause problems if a file loaded on startup tries to
12021 prompt in the mini-buffer. */
12022 if (current_kboard == initial_kboard)
12023 current_kboard = terminal->kboard;
12025 terminal->kboard->reference_count++;
12028 /* Put this display on the chain. */
12029 dpyinfo->next = x_display_list;
12030 x_display_list = dpyinfo;
12032 dpyinfo->name_list_element = Fcons (display_name, Qnil);
12033 dpyinfo->display = dpy;
12034 dpyinfo->connection = ConnectionNumber (dpyinfo->display);
12035 #ifdef USE_XCB
12036 dpyinfo->xcb_connection = xcb_conn;
12037 #endif
12039 /* http://lists.gnu.org/archive/html/emacs-devel/2015-11/msg00194.html */
12040 dpyinfo->smallest_font_height = 1;
12041 dpyinfo->smallest_char_width = 1;
12043 /* Set the name of the terminal. */
12044 terminal->name = xlispstrdup (display_name);
12046 #if false
12047 XSetAfterFunction (x_current_display, x_trace_wire);
12048 #endif
12050 Lisp_Object system_name = Fsystem_name ();
12051 ptrdiff_t nbytes;
12052 if (INT_ADD_WRAPV (SBYTES (Vinvocation_name), SBYTES (system_name) + 2,
12053 &nbytes))
12054 memory_full (SIZE_MAX);
12055 dpyinfo->x_id = ++x_display_id;
12056 dpyinfo->x_id_name = xmalloc (nbytes);
12057 char *nametail = lispstpcpy (dpyinfo->x_id_name, Vinvocation_name);
12058 *nametail++ = '@';
12059 lispstpcpy (nametail, system_name);
12061 /* Figure out which modifier bits mean what. */
12062 x_find_modifier_meanings (dpyinfo);
12064 /* Get the scroll bar cursor. */
12065 #ifdef USE_GTK
12066 /* We must create a GTK cursor, it is required for GTK widgets. */
12067 dpyinfo->xg_cursor = xg_create_default_cursor (dpyinfo->display);
12068 #endif /* USE_GTK */
12070 dpyinfo->vertical_scroll_bar_cursor
12071 = XCreateFontCursor (dpyinfo->display, XC_sb_v_double_arrow);
12073 dpyinfo->horizontal_scroll_bar_cursor
12074 = XCreateFontCursor (dpyinfo->display, XC_sb_h_double_arrow);
12076 xrdb = x_load_resources (dpyinfo->display, xrm_option,
12077 resource_name, EMACS_CLASS);
12078 #ifdef HAVE_XRMSETDATABASE
12079 XrmSetDatabase (dpyinfo->display, xrdb);
12080 #else
12081 dpyinfo->display->db = xrdb;
12082 #endif
12083 /* Put the rdb where we can find it in a way that works on
12084 all versions. */
12085 dpyinfo->xrdb = xrdb;
12087 dpyinfo->screen = ScreenOfDisplay (dpyinfo->display,
12088 DefaultScreen (dpyinfo->display));
12089 select_visual (dpyinfo);
12090 dpyinfo->cmap = DefaultColormapOfScreen (dpyinfo->screen);
12091 dpyinfo->root_window = RootWindowOfScreen (dpyinfo->screen);
12092 dpyinfo->icon_bitmap_id = -1;
12093 dpyinfo->wm_type = X_WMTYPE_UNKNOWN;
12095 reset_mouse_highlight (&dpyinfo->mouse_highlight);
12097 /* See if we can construct pixel values from RGB values. */
12098 if (dpyinfo->visual->class == TrueColor)
12100 get_bits_and_offset (dpyinfo->visual->red_mask,
12101 &dpyinfo->red_bits, &dpyinfo->red_offset);
12102 get_bits_and_offset (dpyinfo->visual->blue_mask,
12103 &dpyinfo->blue_bits, &dpyinfo->blue_offset);
12104 get_bits_and_offset (dpyinfo->visual->green_mask,
12105 &dpyinfo->green_bits, &dpyinfo->green_offset);
12108 /* See if a private colormap is requested. */
12109 if (dpyinfo->visual == DefaultVisualOfScreen (dpyinfo->screen))
12111 if (dpyinfo->visual->class == PseudoColor)
12113 AUTO_STRING (privateColormap, "privateColormap");
12114 AUTO_STRING (PrivateColormap, "PrivateColormap");
12115 Lisp_Object value
12116 = display_x_get_resource (dpyinfo, privateColormap,
12117 PrivateColormap, Qnil, Qnil);
12118 if (STRINGP (value)
12119 && (!strcmp (SSDATA (value), "true")
12120 || !strcmp (SSDATA (value), "on")))
12121 dpyinfo->cmap = XCopyColormapAndFree (dpyinfo->display, dpyinfo->cmap);
12124 else
12125 dpyinfo->cmap = XCreateColormap (dpyinfo->display, dpyinfo->root_window,
12126 dpyinfo->visual, AllocNone);
12128 #ifdef HAVE_XFT
12130 /* If we are using Xft, the following precautions should be made:
12132 1. Make sure that the Xrender extension is added before the Xft one.
12133 Otherwise, the close-display hook set by Xft is called after the one
12134 for Xrender, and the former tries to re-add the latter. This results
12135 in inconsistency of internal states and leads to X protocol error when
12136 one reconnects to the same X server (Bug#1696).
12138 2. Check dpi value in X resources. It is better we use it as well,
12139 since Xft will use it, as will all Gnome applications. If our real DPI
12140 is smaller or larger than the one Xft uses, our font will look smaller
12141 or larger than other for other applications, even if it is the same
12142 font name (monospace-10 for example). */
12144 int event_base, error_base;
12145 char *v;
12146 double d;
12148 XRenderQueryExtension (dpyinfo->display, &event_base, &error_base);
12150 v = XGetDefault (dpyinfo->display, "Xft", "dpi");
12151 if (v != NULL && sscanf (v, "%lf", &d) == 1)
12152 dpyinfo->resy = dpyinfo->resx = d;
12154 #endif
12156 if (dpyinfo->resy < 1)
12158 int screen_number = XScreenNumberOfScreen (dpyinfo->screen);
12159 double pixels = DisplayHeight (dpyinfo->display, screen_number);
12160 double mm = DisplayHeightMM (dpyinfo->display, screen_number);
12161 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
12162 dpyinfo->resy = (mm < 1) ? 100 : pixels * 25.4 / mm;
12163 pixels = DisplayWidth (dpyinfo->display, screen_number);
12164 mm = DisplayWidthMM (dpyinfo->display, screen_number);
12165 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
12166 dpyinfo->resx = (mm < 1) ? 100 : pixels * 25.4 / mm;
12170 static const struct
12172 const char *name;
12173 int offset;
12174 } atom_refs[] = {
12175 #define ATOM_REFS_INIT(string, member) \
12176 { string, offsetof (struct x_display_info, member) },
12177 ATOM_REFS_INIT ("WM_PROTOCOLS", Xatom_wm_protocols)
12178 ATOM_REFS_INIT ("WM_TAKE_FOCUS", Xatom_wm_take_focus)
12179 ATOM_REFS_INIT ("WM_SAVE_YOURSELF", Xatom_wm_save_yourself)
12180 ATOM_REFS_INIT ("WM_DELETE_WINDOW", Xatom_wm_delete_window)
12181 ATOM_REFS_INIT ("WM_CHANGE_STATE", Xatom_wm_change_state)
12182 ATOM_REFS_INIT ("WM_CONFIGURE_DENIED", Xatom_wm_configure_denied)
12183 ATOM_REFS_INIT ("WM_MOVED", Xatom_wm_window_moved)
12184 ATOM_REFS_INIT ("WM_CLIENT_LEADER", Xatom_wm_client_leader)
12185 ATOM_REFS_INIT ("Editres", Xatom_editres)
12186 ATOM_REFS_INIT ("CLIPBOARD", Xatom_CLIPBOARD)
12187 ATOM_REFS_INIT ("TIMESTAMP", Xatom_TIMESTAMP)
12188 ATOM_REFS_INIT ("TEXT", Xatom_TEXT)
12189 ATOM_REFS_INIT ("COMPOUND_TEXT", Xatom_COMPOUND_TEXT)
12190 ATOM_REFS_INIT ("UTF8_STRING", Xatom_UTF8_STRING)
12191 ATOM_REFS_INIT ("DELETE", Xatom_DELETE)
12192 ATOM_REFS_INIT ("MULTIPLE", Xatom_MULTIPLE)
12193 ATOM_REFS_INIT ("INCR", Xatom_INCR)
12194 ATOM_REFS_INIT ("_EMACS_TMP_", Xatom_EMACS_TMP)
12195 ATOM_REFS_INIT ("TARGETS", Xatom_TARGETS)
12196 ATOM_REFS_INIT ("NULL", Xatom_NULL)
12197 ATOM_REFS_INIT ("ATOM", Xatom_ATOM)
12198 ATOM_REFS_INIT ("ATOM_PAIR", Xatom_ATOM_PAIR)
12199 ATOM_REFS_INIT ("CLIPBOARD_MANAGER", Xatom_CLIPBOARD_MANAGER)
12200 ATOM_REFS_INIT ("_XEMBED_INFO", Xatom_XEMBED_INFO)
12201 /* For properties of font. */
12202 ATOM_REFS_INIT ("PIXEL_SIZE", Xatom_PIXEL_SIZE)
12203 ATOM_REFS_INIT ("AVERAGE_WIDTH", Xatom_AVERAGE_WIDTH)
12204 ATOM_REFS_INIT ("_MULE_BASELINE_OFFSET", Xatom_MULE_BASELINE_OFFSET)
12205 ATOM_REFS_INIT ("_MULE_RELATIVE_COMPOSE", Xatom_MULE_RELATIVE_COMPOSE)
12206 ATOM_REFS_INIT ("_MULE_DEFAULT_ASCENT", Xatom_MULE_DEFAULT_ASCENT)
12207 /* Ghostscript support. */
12208 ATOM_REFS_INIT ("DONE", Xatom_DONE)
12209 ATOM_REFS_INIT ("PAGE", Xatom_PAGE)
12210 ATOM_REFS_INIT ("SCROLLBAR", Xatom_Scrollbar)
12211 ATOM_REFS_INIT ("HORIZONTAL_SCROLLBAR", Xatom_Horizontal_Scrollbar)
12212 ATOM_REFS_INIT ("_XEMBED", Xatom_XEMBED)
12213 /* EWMH */
12214 ATOM_REFS_INIT ("_NET_WM_STATE", Xatom_net_wm_state)
12215 ATOM_REFS_INIT ("_NET_WM_STATE_FULLSCREEN", Xatom_net_wm_state_fullscreen)
12216 ATOM_REFS_INIT ("_NET_WM_STATE_MAXIMIZED_HORZ",
12217 Xatom_net_wm_state_maximized_horz)
12218 ATOM_REFS_INIT ("_NET_WM_STATE_MAXIMIZED_VERT",
12219 Xatom_net_wm_state_maximized_vert)
12220 ATOM_REFS_INIT ("_NET_WM_STATE_STICKY", Xatom_net_wm_state_sticky)
12221 ATOM_REFS_INIT ("_NET_WM_STATE_HIDDEN", Xatom_net_wm_state_hidden)
12222 ATOM_REFS_INIT ("_NET_WM_WINDOW_TYPE", Xatom_net_window_type)
12223 ATOM_REFS_INIT ("_NET_WM_WINDOW_TYPE_TOOLTIP",
12224 Xatom_net_window_type_tooltip)
12225 ATOM_REFS_INIT ("_NET_WM_ICON_NAME", Xatom_net_wm_icon_name)
12226 ATOM_REFS_INIT ("_NET_WM_NAME", Xatom_net_wm_name)
12227 ATOM_REFS_INIT ("_NET_SUPPORTED", Xatom_net_supported)
12228 ATOM_REFS_INIT ("_NET_SUPPORTING_WM_CHECK", Xatom_net_supporting_wm_check)
12229 ATOM_REFS_INIT ("_NET_WM_WINDOW_OPACITY", Xatom_net_wm_window_opacity)
12230 ATOM_REFS_INIT ("_NET_ACTIVE_WINDOW", Xatom_net_active_window)
12231 ATOM_REFS_INIT ("_NET_FRAME_EXTENTS", Xatom_net_frame_extents)
12232 ATOM_REFS_INIT ("_NET_CURRENT_DESKTOP", Xatom_net_current_desktop)
12233 ATOM_REFS_INIT ("_NET_WORKAREA", Xatom_net_workarea)
12234 /* Session management */
12235 ATOM_REFS_INIT ("SM_CLIENT_ID", Xatom_SM_CLIENT_ID)
12236 ATOM_REFS_INIT ("_XSETTINGS_SETTINGS", Xatom_xsettings_prop)
12237 ATOM_REFS_INIT ("MANAGER", Xatom_xsettings_mgr)
12240 int i;
12241 enum { atom_count = ARRAYELTS (atom_refs) };
12242 /* 1 for _XSETTINGS_SN. */
12243 enum { total_atom_count = 1 + atom_count };
12244 Atom atoms_return[total_atom_count];
12245 char *atom_names[total_atom_count];
12246 static char const xsettings_fmt[] = "_XSETTINGS_S%d";
12247 char xsettings_atom_name[sizeof xsettings_fmt - 2
12248 + INT_STRLEN_BOUND (int)];
12250 for (i = 0; i < atom_count; i++)
12251 atom_names[i] = (char *) atom_refs[i].name;
12253 /* Build _XSETTINGS_SN atom name. */
12254 sprintf (xsettings_atom_name, xsettings_fmt,
12255 XScreenNumberOfScreen (dpyinfo->screen));
12256 atom_names[i] = xsettings_atom_name;
12258 XInternAtoms (dpyinfo->display, atom_names, total_atom_count,
12259 False, atoms_return);
12261 for (i = 0; i < atom_count; i++)
12262 *(Atom *) ((char *) dpyinfo + atom_refs[i].offset) = atoms_return[i];
12264 /* Manually copy last atom. */
12265 dpyinfo->Xatom_xsettings_sel = atoms_return[i];
12268 dpyinfo->x_dnd_atoms_size = 8;
12269 dpyinfo->x_dnd_atoms = xmalloc (sizeof *dpyinfo->x_dnd_atoms
12270 * dpyinfo->x_dnd_atoms_size);
12271 dpyinfo->gray
12272 = XCreatePixmapFromBitmapData (dpyinfo->display, dpyinfo->root_window,
12273 gray_bits, gray_width, gray_height,
12274 1, 0, 1);
12276 x_setup_pointer_blanking (dpyinfo);
12278 #ifdef HAVE_X_I18N
12279 xim_initialize (dpyinfo, resource_name);
12280 #endif
12282 xsettings_initialize (dpyinfo);
12284 /* This is only needed for distinguishing keyboard and process input. */
12285 if (dpyinfo->connection != 0)
12286 add_keyboard_wait_descriptor (dpyinfo->connection);
12288 #ifdef F_SETOWN
12289 fcntl (dpyinfo->connection, F_SETOWN, getpid ());
12290 #endif /* ! defined (F_SETOWN) */
12292 if (interrupt_input)
12293 init_sigio (dpyinfo->connection);
12295 #ifdef USE_LUCID
12297 XrmValue d, fr, to;
12298 Font font;
12300 dpy = dpyinfo->display;
12301 d.addr = (XPointer)&dpy;
12302 d.size = sizeof (Display *);
12303 fr.addr = XtDefaultFont;
12304 fr.size = sizeof (XtDefaultFont);
12305 to.size = sizeof (Font *);
12306 to.addr = (XPointer)&font;
12307 x_catch_errors (dpy);
12308 if (!XtCallConverter (dpy, XtCvtStringToFont, &d, 1, &fr, &to, NULL))
12309 emacs_abort ();
12310 if (x_had_errors_p (dpy) || !XQueryFont (dpy, font))
12311 XrmPutLineResource (&xrdb, "Emacs.dialog.*.font: 9x15");
12312 /* Do not free XFontStruct returned by the above call to XQueryFont.
12313 This leads to X protocol errors at XtCloseDisplay (Bug#18403). */
12314 x_uncatch_errors ();
12316 #endif
12318 /* See if we should run in synchronous mode. This is useful
12319 for debugging X code. */
12321 AUTO_STRING (synchronous, "synchronous");
12322 AUTO_STRING (Synchronous, "Synchronous");
12323 Lisp_Object value = display_x_get_resource (dpyinfo, synchronous,
12324 Synchronous, Qnil, Qnil);
12325 if (STRINGP (value)
12326 && (!strcmp (SSDATA (value), "true")
12327 || !strcmp (SSDATA (value), "on")))
12328 XSynchronize (dpyinfo->display, True);
12332 AUTO_STRING (useXIM, "useXIM");
12333 AUTO_STRING (UseXIM, "UseXIM");
12334 Lisp_Object value = display_x_get_resource (dpyinfo, useXIM, UseXIM,
12335 Qnil, Qnil);
12336 #ifdef USE_XIM
12337 if (STRINGP (value)
12338 && (!strcmp (SSDATA (value), "false")
12339 || !strcmp (SSDATA (value), "off")))
12340 use_xim = false;
12341 #else
12342 if (STRINGP (value)
12343 && (!strcmp (SSDATA (value), "true")
12344 || !strcmp (SSDATA (value), "on")))
12345 use_xim = true;
12346 #endif
12349 #ifdef HAVE_X_SM
12350 /* Only do this for the very first display in the Emacs session.
12351 Ignore X session management when Emacs was first started on a
12352 tty or started as a daemon. */
12353 if (terminal->id == 1 && ! IS_DAEMON)
12354 x_session_initialize (dpyinfo);
12355 #endif
12357 #ifdef USE_CAIRO
12358 x_extension_initialize (dpyinfo);
12359 #endif
12361 unblock_input ();
12363 return dpyinfo;
12366 /* Get rid of display DPYINFO, deleting all frames on it,
12367 and without sending any more commands to the X server. */
12369 static void
12370 x_delete_display (struct x_display_info *dpyinfo)
12372 struct terminal *t;
12373 struct color_name_cache_entry *color_entry, *next_color_entry;
12375 /* Close all frames and delete the generic struct terminal for this
12376 X display. */
12377 for (t = terminal_list; t; t = t->next_terminal)
12378 if (t->type == output_x_window && t->display_info.x == dpyinfo)
12380 #ifdef HAVE_X_SM
12381 /* Close X session management when we close its display. */
12382 if (t->id == 1 && x_session_have_connection ())
12383 x_session_close ();
12384 #endif
12385 delete_terminal (t);
12386 break;
12389 if (next_noop_dpyinfo == dpyinfo)
12390 next_noop_dpyinfo = dpyinfo->next;
12392 if (x_display_list == dpyinfo)
12393 x_display_list = dpyinfo->next;
12394 else
12396 struct x_display_info *tail;
12398 for (tail = x_display_list; tail; tail = tail->next)
12399 if (tail->next == dpyinfo)
12400 tail->next = tail->next->next;
12403 for (color_entry = dpyinfo->color_names;
12404 color_entry;
12405 color_entry = next_color_entry)
12407 next_color_entry = color_entry->next;
12408 xfree (color_entry->name);
12409 xfree (color_entry);
12412 xfree (dpyinfo->x_id_name);
12413 xfree (dpyinfo->x_dnd_atoms);
12414 xfree (dpyinfo->color_cells);
12415 xfree (dpyinfo);
12418 #ifdef USE_X_TOOLKIT
12420 /* Atimer callback function for TIMER. Called every 0.1s to process
12421 Xt timeouts, if needed. We must avoid calling XtAppPending as
12422 much as possible because that function does an implicit XFlush
12423 that slows us down. */
12425 static void
12426 x_process_timeouts (struct atimer *timer)
12428 block_input ();
12429 x_timeout_atimer_activated_flag = false;
12430 if (toolkit_scroll_bar_interaction || popup_activated ())
12432 while (XtAppPending (Xt_app_con) & XtIMTimer)
12433 XtAppProcessEvent (Xt_app_con, XtIMTimer);
12434 /* Reactivate the atimer for next time. */
12435 x_activate_timeout_atimer ();
12437 unblock_input ();
12440 /* Install an asynchronous timer that processes Xt timeout events
12441 every 0.1s as long as either `toolkit_scroll_bar_interaction' or
12442 `popup_activated_flag' (in xmenu.c) is set. Make sure to call this
12443 function whenever these variables are set. This is necessary
12444 because some widget sets use timeouts internally, for example the
12445 LessTif menu bar, or the Xaw3d scroll bar. When Xt timeouts aren't
12446 processed, these widgets don't behave normally. */
12448 void
12449 x_activate_timeout_atimer (void)
12451 block_input ();
12452 if (!x_timeout_atimer_activated_flag)
12454 struct timespec interval = make_timespec (0, 100 * 1000 * 1000);
12455 start_atimer (ATIMER_RELATIVE, interval, x_process_timeouts, 0);
12456 x_timeout_atimer_activated_flag = true;
12458 unblock_input ();
12461 #endif /* USE_X_TOOLKIT */
12464 /* Set up use of X before we make the first connection. */
12466 static struct redisplay_interface x_redisplay_interface =
12468 x_frame_parm_handlers,
12469 x_produce_glyphs,
12470 x_write_glyphs,
12471 x_insert_glyphs,
12472 x_clear_end_of_line,
12473 x_scroll_run,
12474 x_after_update_window_line,
12475 x_update_window_begin,
12476 x_update_window_end,
12477 x_flush,
12478 x_clear_window_mouse_face,
12479 x_get_glyph_overhangs,
12480 x_fix_overlapping_area,
12481 x_draw_fringe_bitmap,
12482 #ifdef USE_CAIRO
12483 x_cr_define_fringe_bitmap,
12484 x_cr_destroy_fringe_bitmap,
12485 #else
12486 0, /* define_fringe_bitmap */
12487 0, /* destroy_fringe_bitmap */
12488 #endif
12489 x_compute_glyph_string_overhangs,
12490 x_draw_glyph_string,
12491 x_define_frame_cursor,
12492 x_clear_frame_area,
12493 x_draw_window_cursor,
12494 x_draw_vertical_window_border,
12495 x_draw_window_divider,
12496 x_shift_glyphs_for_insert, /* Never called; see comment in function. */
12497 x_show_hourglass,
12498 x_hide_hourglass
12502 /* This function is called when the last frame on a display is deleted. */
12503 void
12504 x_delete_terminal (struct terminal *terminal)
12506 struct x_display_info *dpyinfo = terminal->display_info.x;
12508 /* Protect against recursive calls. delete_frame in
12509 delete_terminal calls us back when it deletes our last frame. */
12510 if (!terminal->name)
12511 return;
12513 block_input ();
12514 #ifdef HAVE_X_I18N
12515 /* We must close our connection to the XIM server before closing the
12516 X display. */
12517 if (dpyinfo->xim)
12518 xim_close_dpy (dpyinfo);
12519 #endif
12521 /* Normally, the display is available... */
12522 if (dpyinfo->display)
12524 x_destroy_all_bitmaps (dpyinfo);
12525 XSetCloseDownMode (dpyinfo->display, DestroyAll);
12527 /* Whether or not XCloseDisplay destroys the associated resource
12528 database depends on the version of libX11. To avoid both
12529 crash and memory leak, we dissociate the database from the
12530 display and then destroy dpyinfo->xrdb ourselves.
12532 Unfortunately, the above strategy does not work in some
12533 situations due to a bug in newer versions of libX11: because
12534 XrmSetDatabase doesn't clear the flag XlibDisplayDfltRMDB if
12535 dpy->db is NULL, XCloseDisplay destroys the associated
12536 database whereas it has not been created by XGetDefault
12537 (Bug#21974 in freedesktop.org Bugzilla). As a workaround, we
12538 don't destroy the database here in order to avoid the crash
12539 in the above situations for now, though that may cause memory
12540 leaks in other situations. */
12541 #if false
12542 #ifdef HAVE_XRMSETDATABASE
12543 XrmSetDatabase (dpyinfo->display, NULL);
12544 #else
12545 dpyinfo->display->db = NULL;
12546 #endif
12547 /* We used to call XrmDestroyDatabase from x_delete_display, but
12548 some older versions of libX11 crash if we call it after
12549 closing all the displays. */
12550 XrmDestroyDatabase (dpyinfo->xrdb);
12551 #endif
12553 #ifdef USE_GTK
12554 xg_display_close (dpyinfo->display);
12555 #else
12556 #ifdef USE_X_TOOLKIT
12557 XtCloseDisplay (dpyinfo->display);
12558 #else
12559 XCloseDisplay (dpyinfo->display);
12560 #endif
12561 #endif /* ! USE_GTK */
12562 /* Do not close the connection here because it's already closed
12563 by X(t)CloseDisplay (Bug#18403). */
12564 dpyinfo->display = NULL;
12567 /* ...but if called from x_connection_closed, the display may already
12568 be closed and dpyinfo->display was set to 0 to indicate that. Since
12569 X server is most likely gone, explicit close is the only reliable
12570 way to continue and avoid Bug#19147. */
12571 else if (dpyinfo->connection >= 0)
12572 emacs_close (dpyinfo->connection);
12574 /* No more input on this descriptor. */
12575 delete_keyboard_wait_descriptor (dpyinfo->connection);
12576 /* Mark as dead. */
12577 dpyinfo->connection = -1;
12579 x_delete_display (dpyinfo);
12580 unblock_input ();
12583 /* Create a struct terminal, initialize it with the X11 specific
12584 functions and make DISPLAY->TERMINAL point to it. */
12586 static struct terminal *
12587 x_create_terminal (struct x_display_info *dpyinfo)
12589 struct terminal *terminal;
12591 terminal = create_terminal (output_x_window, &x_redisplay_interface);
12593 terminal->display_info.x = dpyinfo;
12594 dpyinfo->terminal = terminal;
12596 /* kboard is initialized in x_term_init. */
12598 terminal->clear_frame_hook = x_clear_frame;
12599 terminal->ins_del_lines_hook = x_ins_del_lines;
12600 terminal->delete_glyphs_hook = x_delete_glyphs;
12601 terminal->ring_bell_hook = XTring_bell;
12602 terminal->toggle_invisible_pointer_hook = XTtoggle_invisible_pointer;
12603 terminal->update_begin_hook = x_update_begin;
12604 terminal->update_end_hook = x_update_end;
12605 terminal->read_socket_hook = XTread_socket;
12606 terminal->frame_up_to_date_hook = XTframe_up_to_date;
12607 terminal->mouse_position_hook = XTmouse_position;
12608 terminal->frame_rehighlight_hook = XTframe_rehighlight;
12609 terminal->frame_raise_lower_hook = XTframe_raise_lower;
12610 terminal->fullscreen_hook = XTfullscreen_hook;
12611 terminal->menu_show_hook = x_menu_show;
12612 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
12613 terminal->popup_dialog_hook = xw_popup_dialog;
12614 #endif
12615 terminal->set_vertical_scroll_bar_hook = XTset_vertical_scroll_bar;
12616 terminal->set_horizontal_scroll_bar_hook = XTset_horizontal_scroll_bar;
12617 terminal->condemn_scroll_bars_hook = XTcondemn_scroll_bars;
12618 terminal->redeem_scroll_bar_hook = XTredeem_scroll_bar;
12619 terminal->judge_scroll_bars_hook = XTjudge_scroll_bars;
12620 terminal->delete_frame_hook = x_destroy_window;
12621 terminal->delete_terminal_hook = x_delete_terminal;
12622 /* Other hooks are NULL by default. */
12624 return terminal;
12627 static void
12628 x_initialize (void)
12630 baud_rate = 19200;
12632 x_noop_count = 0;
12633 any_help_event_p = false;
12634 ignore_next_mouse_click_timeout = 0;
12636 #ifdef USE_GTK
12637 current_count = -1;
12638 #endif
12640 /* Try to use interrupt input; if we can't, then start polling. */
12641 Fset_input_interrupt_mode (Qt);
12643 #ifdef USE_X_TOOLKIT
12644 XtToolkitInitialize ();
12646 Xt_app_con = XtCreateApplicationContext ();
12648 /* Register a converter from strings to pixels, which uses
12649 Emacs' color allocation infrastructure. */
12650 XtAppSetTypeConverter (Xt_app_con,
12651 XtRString, XtRPixel, cvt_string_to_pixel,
12652 cvt_string_to_pixel_args,
12653 XtNumber (cvt_string_to_pixel_args),
12654 XtCacheByDisplay, cvt_pixel_dtor);
12656 XtAppSetFallbackResources (Xt_app_con, Xt_default_resources);
12657 #endif
12659 #ifdef USE_TOOLKIT_SCROLL_BARS
12660 #ifndef USE_GTK
12661 xaw3d_arrow_scroll = False;
12662 xaw3d_pick_top = True;
12663 #endif
12664 #endif
12666 #ifdef USE_CAIRO
12667 x_cr_init_fringe (&x_redisplay_interface);
12668 #endif
12670 /* Note that there is no real way portable across R3/R4 to get the
12671 original error handler. */
12672 XSetErrorHandler (x_error_handler);
12673 XSetIOErrorHandler (x_io_error_quitter);
12676 #ifdef USE_GTK
12677 void
12678 init_xterm (void)
12680 /* Emacs can handle only core input events, so make sure
12681 Gtk doesn't use Xinput or Xinput2 extensions. */
12682 xputenv ("GDK_CORE_DEVICE_EVENTS=1");
12684 #endif
12686 void
12687 syms_of_xterm (void)
12689 x_error_message = NULL;
12691 DEFSYM (Qvendor_specific_keysyms, "vendor-specific-keysyms");
12692 DEFSYM (Qlatin_1, "latin-1");
12694 #ifdef USE_GTK
12695 xg_default_icon_file = build_pure_c_string ("icons/hicolor/scalable/apps/emacs.svg");
12696 staticpro (&xg_default_icon_file);
12698 DEFSYM (Qx_gtk_map_stock, "x-gtk-map-stock");
12699 #endif
12701 DEFVAR_BOOL ("x-use-underline-position-properties",
12702 x_use_underline_position_properties,
12703 doc: /* Non-nil means make use of UNDERLINE_POSITION font properties.
12704 A value of nil means ignore them. If you encounter fonts with bogus
12705 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
12706 to 4.1, set this to nil. You can also use `underline-minimum-offset'
12707 to override the font's UNDERLINE_POSITION for small font display
12708 sizes. */);
12709 x_use_underline_position_properties = true;
12711 DEFVAR_BOOL ("x-underline-at-descent-line",
12712 x_underline_at_descent_line,
12713 doc: /* Non-nil means to draw the underline at the same place as the descent line.
12714 A value of nil means to draw the underline according to the value of the
12715 variable `x-use-underline-position-properties', which is usually at the
12716 baseline level. The default value is nil. */);
12717 x_underline_at_descent_line = false;
12719 DEFVAR_BOOL ("x-mouse-click-focus-ignore-position",
12720 x_mouse_click_focus_ignore_position,
12721 doc: /* Non-nil means that a mouse click to focus a frame does not move point.
12722 This variable is only used when the window manager requires that you
12723 click on a frame to select it (give it focus). In that case, a value
12724 of nil, means that the selected window and cursor position changes to
12725 reflect the mouse click position, while a non-nil value means that the
12726 selected window or cursor position is preserved. */);
12727 x_mouse_click_focus_ignore_position = false;
12729 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
12730 doc: /* Which toolkit scroll bars Emacs uses, if any.
12731 A value of nil means Emacs doesn't use toolkit scroll bars.
12732 With the X Window system, the value is a symbol describing the
12733 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
12734 With MS Windows or Nextstep, the value is t. */);
12735 #ifdef USE_TOOLKIT_SCROLL_BARS
12736 #ifdef USE_MOTIF
12737 Vx_toolkit_scroll_bars = intern_c_string ("motif");
12738 #elif defined HAVE_XAW3D
12739 Vx_toolkit_scroll_bars = intern_c_string ("xaw3d");
12740 #elif USE_GTK
12741 Vx_toolkit_scroll_bars = intern_c_string ("gtk");
12742 #else
12743 Vx_toolkit_scroll_bars = intern_c_string ("xaw");
12744 #endif
12745 #else
12746 Vx_toolkit_scroll_bars = Qnil;
12747 #endif
12749 DEFSYM (Qmodifier_value, "modifier-value");
12750 DEFSYM (Qalt, "alt");
12751 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
12752 DEFSYM (Qhyper, "hyper");
12753 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
12754 DEFSYM (Qmeta, "meta");
12755 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
12756 DEFSYM (Qsuper, "super");
12757 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
12759 DEFVAR_LISP ("x-alt-keysym", Vx_alt_keysym,
12760 doc: /* Which keys Emacs uses for the alt modifier.
12761 This should be one of the symbols `alt', `hyper', `meta', `super'.
12762 For example, `alt' means use the Alt_L and Alt_R keysyms. The default
12763 is nil, which is the same as `alt'. */);
12764 Vx_alt_keysym = Qnil;
12766 DEFVAR_LISP ("x-hyper-keysym", Vx_hyper_keysym,
12767 doc: /* Which keys Emacs uses for the hyper modifier.
12768 This should be one of the symbols `alt', `hyper', `meta', `super'.
12769 For example, `hyper' means use the Hyper_L and Hyper_R keysyms. The
12770 default is nil, which is the same as `hyper'. */);
12771 Vx_hyper_keysym = Qnil;
12773 DEFVAR_LISP ("x-meta-keysym", Vx_meta_keysym,
12774 doc: /* Which keys Emacs uses for the meta modifier.
12775 This should be one of the symbols `alt', `hyper', `meta', `super'.
12776 For example, `meta' means use the Meta_L and Meta_R keysyms. The
12777 default is nil, which is the same as `meta'. */);
12778 Vx_meta_keysym = Qnil;
12780 DEFVAR_LISP ("x-super-keysym", Vx_super_keysym,
12781 doc: /* Which keys Emacs uses for the super modifier.
12782 This should be one of the symbols `alt', `hyper', `meta', `super'.
12783 For example, `super' means use the Super_L and Super_R keysyms. The
12784 default is nil, which is the same as `super'. */);
12785 Vx_super_keysym = Qnil;
12787 DEFVAR_LISP ("x-keysym-table", Vx_keysym_table,
12788 doc: /* Hash table of character codes indexed by X keysym codes. */);
12789 Vx_keysym_table = make_hash_table (hashtest_eql, make_number (900),
12790 make_float (DEFAULT_REHASH_SIZE),
12791 make_float (DEFAULT_REHASH_THRESHOLD),
12792 Qnil);
12794 DEFVAR_BOOL ("x-frame-normalize-before-maximize",
12795 x_frame_normalize_before_maximize,
12796 doc: /* Non-nil means normalize frame before maximizing.
12797 If this variable is t, Emacs first asks the window manager to give the
12798 frame its normal size, and only then the final state, whenever changing
12799 from a full-height, full-width or full-both state to the maximized one
12800 or when changing from the maximized to the full-height or full-width
12801 state.
12803 Set this variable only if your window manager cannot handle the
12804 transition between the various maximization states. */);
12805 x_frame_normalize_before_maximize = false;