Ensure hack-local-variables is run in a fundamental mode buffer.
[emacs.git] / src / xterm.c
blob9fb19a16f6011c67ea04caae9e5f4300503418a2
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_OPT_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_OPT_FROM_ID (f, WINDOW_DIVIDER_FACE_ID);
1085 struct face *face_first
1086 = FACE_OPT_FROM_ID (f, WINDOW_DIVIDER_FIRST_PIXEL_FACE_ID);
1087 struct face *face_last
1088 = FACE_OPT_FROM_ID (f, WINDOW_DIVIDER_LAST_PIXEL_FACE_ID);
1089 unsigned long color = face ? face->foreground : FRAME_FOREGROUND_PIXEL (f);
1090 unsigned long color_first = (face_first
1091 ? face_first->foreground
1092 : FRAME_FOREGROUND_PIXEL (f));
1093 unsigned long color_last = (face_last
1094 ? face_last->foreground
1095 : FRAME_FOREGROUND_PIXEL (f));
1096 Display *display = FRAME_X_DISPLAY (f);
1098 if (y1 - y0 > x1 - x0 && x1 - x0 > 2)
1099 /* Vertical. */
1101 XSetForeground (display, f->output_data.x->normal_gc, color_first);
1102 x_fill_rectangle (f, f->output_data.x->normal_gc,
1103 x0, y0, 1, y1 - y0);
1104 XSetForeground (display, f->output_data.x->normal_gc, color);
1105 x_fill_rectangle (f, f->output_data.x->normal_gc,
1106 x0 + 1, y0, x1 - x0 - 2, y1 - y0);
1107 XSetForeground (display, f->output_data.x->normal_gc, color_last);
1108 x_fill_rectangle (f, f->output_data.x->normal_gc,
1109 x1 - 1, y0, 1, y1 - y0);
1111 else if (x1 - x0 > y1 - y0 && y1 - y0 > 3)
1112 /* Horizontal. */
1114 XSetForeground (display, f->output_data.x->normal_gc, color_first);
1115 x_fill_rectangle (f, f->output_data.x->normal_gc,
1116 x0, y0, x1 - x0, 1);
1117 XSetForeground (display, f->output_data.x->normal_gc, color);
1118 x_fill_rectangle (f, f->output_data.x->normal_gc,
1119 x0, y0 + 1, x1 - x0, y1 - y0 - 2);
1120 XSetForeground (display, f->output_data.x->normal_gc, color_last);
1121 x_fill_rectangle (f, f->output_data.x->normal_gc,
1122 x0, y1 - 1, x1 - x0, 1);
1124 else
1126 XSetForeground (display, f->output_data.x->normal_gc, color);
1127 x_fill_rectangle (f, f->output_data.x->normal_gc,
1128 x0, y0, x1 - x0, y1 - y0);
1132 /* End update of window W.
1134 Draw vertical borders between horizontally adjacent windows, and
1135 display W's cursor if CURSOR_ON_P is non-zero.
1137 MOUSE_FACE_OVERWRITTEN_P non-zero means that some row containing
1138 glyphs in mouse-face were overwritten. In that case we have to
1139 make sure that the mouse-highlight is properly redrawn.
1141 W may be a menu bar pseudo-window in case we don't have X toolkit
1142 support. Such windows don't have a cursor, so don't display it
1143 here. */
1145 static void
1146 x_update_window_end (struct window *w, bool cursor_on_p,
1147 bool mouse_face_overwritten_p)
1149 if (!w->pseudo_window_p)
1151 block_input ();
1153 if (cursor_on_p)
1154 display_and_set_cursor (w, true,
1155 w->output_cursor.hpos, w->output_cursor.vpos,
1156 w->output_cursor.x, w->output_cursor.y);
1158 if (draw_window_fringes (w, true))
1160 if (WINDOW_RIGHT_DIVIDER_WIDTH (w))
1161 x_draw_right_divider (w);
1162 else
1163 x_draw_vertical_border (w);
1166 unblock_input ();
1169 /* If a row with mouse-face was overwritten, arrange for
1170 XTframe_up_to_date to redisplay the mouse highlight. */
1171 if (mouse_face_overwritten_p)
1173 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (XFRAME (w->frame));
1175 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
1176 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
1177 hlinfo->mouse_face_window = Qnil;
1182 /* End update of frame F. This function is installed as a hook in
1183 update_end. */
1185 static void
1186 x_update_end (struct frame *f)
1188 /* Mouse highlight may be displayed again. */
1189 MOUSE_HL_INFO (f)->mouse_face_defer = false;
1191 #ifdef USE_CAIRO
1192 if (FRAME_CR_SURFACE (f))
1194 cairo_t *cr = 0;
1195 block_input();
1196 #if defined (USE_GTK) && defined (HAVE_GTK3)
1197 if (FRAME_GTK_WIDGET (f))
1199 GdkWindow *w = gtk_widget_get_window (FRAME_GTK_WIDGET (f));
1200 cr = gdk_cairo_create (w);
1202 else
1203 #endif
1205 cairo_surface_t *surface;
1206 int width = FRAME_PIXEL_WIDTH (f);
1207 int height = FRAME_PIXEL_HEIGHT (f);
1208 if (! FRAME_EXTERNAL_TOOL_BAR (f))
1209 height += FRAME_TOOL_BAR_HEIGHT (f);
1210 if (! FRAME_EXTERNAL_MENU_BAR (f))
1211 height += FRAME_MENU_BAR_HEIGHT (f);
1212 surface = cairo_xlib_surface_create (FRAME_X_DISPLAY (f),
1213 FRAME_X_WINDOW (f),
1214 FRAME_DISPLAY_INFO (f)->visual,
1215 width,
1216 height);
1217 cr = cairo_create (surface);
1218 cairo_surface_destroy (surface);
1221 cairo_set_source_surface (cr, FRAME_CR_SURFACE (f), 0, 0);
1222 cairo_paint (cr);
1223 cairo_destroy (cr);
1224 unblock_input ();
1226 #endif /* USE_CAIRO */
1228 #ifndef XFlush
1229 block_input ();
1230 XFlush (FRAME_X_DISPLAY (f));
1231 unblock_input ();
1232 #endif
1236 /* This function is called from various places in xdisp.c
1237 whenever a complete update has been performed. */
1239 static void
1240 XTframe_up_to_date (struct frame *f)
1242 if (FRAME_X_P (f))
1243 FRAME_MOUSE_UPDATE (f);
1247 /* Clear under internal border if any (GTK has its own version). */
1248 #ifndef USE_GTK
1249 void
1250 x_clear_under_internal_border (struct frame *f)
1252 if (FRAME_INTERNAL_BORDER_WIDTH (f) > 0)
1254 int border = FRAME_INTERNAL_BORDER_WIDTH (f);
1255 int width = FRAME_PIXEL_WIDTH (f);
1256 int height = FRAME_PIXEL_HEIGHT (f);
1257 int margin = FRAME_TOP_MARGIN_HEIGHT (f);
1259 block_input ();
1260 x_clear_area (f, 0, 0, border, height);
1261 x_clear_area (f, 0, margin, width, border);
1262 x_clear_area (f, width - border, 0, border, height);
1263 x_clear_area (f, 0, height - border, width, border);
1264 unblock_input ();
1267 #endif
1269 /* Draw truncation mark bitmaps, continuation mark bitmaps, overlay
1270 arrow bitmaps, or clear the fringes if no bitmaps are required
1271 before DESIRED_ROW is made current. This function is called from
1272 update_window_line only if it is known that there are differences
1273 between bitmaps to be drawn between current row and DESIRED_ROW. */
1275 static void
1276 x_after_update_window_line (struct window *w, struct glyph_row *desired_row)
1278 eassert (w);
1280 if (!desired_row->mode_line_p && !w->pseudo_window_p)
1281 desired_row->redraw_fringe_bitmaps_p = true;
1283 #ifdef USE_X_TOOLKIT
1284 /* When a window has disappeared, make sure that no rest of
1285 full-width rows stays visible in the internal border. Could
1286 check here if updated window is the leftmost/rightmost window,
1287 but I guess it's not worth doing since vertically split windows
1288 are almost never used, internal border is rarely set, and the
1289 overhead is very small. */
1291 struct frame *f;
1292 int width, height;
1294 if (windows_or_buffers_changed
1295 && desired_row->full_width_p
1296 && (f = XFRAME (w->frame),
1297 width = FRAME_INTERNAL_BORDER_WIDTH (f),
1298 width != 0)
1299 && (height = desired_row->visible_height,
1300 height > 0))
1302 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
1304 block_input ();
1305 x_clear_area (f, 0, y, width, height);
1306 x_clear_area (f, FRAME_PIXEL_WIDTH (f) - width, y, width, height);
1307 unblock_input ();
1310 #endif
1313 static void
1314 x_draw_fringe_bitmap (struct window *w, struct glyph_row *row, struct draw_fringe_bitmap_params *p)
1316 struct frame *f = XFRAME (WINDOW_FRAME (w));
1317 Display *display = FRAME_X_DISPLAY (f);
1318 GC gc = f->output_data.x->normal_gc;
1319 struct face *face = p->face;
1321 /* Must clip because of partially visible lines. */
1322 x_clip_to_row (w, row, ANY_AREA, gc);
1324 if (p->bx >= 0 && !p->overlay_p)
1326 /* In case the same realized face is used for fringes and
1327 for something displayed in the text (e.g. face `region' on
1328 mono-displays, the fill style may have been changed to
1329 FillSolid in x_draw_glyph_string_background. */
1330 if (face->stipple)
1331 XSetFillStyle (display, face->gc, FillOpaqueStippled);
1332 else
1333 XSetForeground (display, face->gc, face->background);
1335 x_fill_rectangle (f, face->gc, p->bx, p->by, p->nx, p->ny);
1337 if (!face->stipple)
1338 XSetForeground (display, face->gc, face->foreground);
1341 #ifdef USE_CAIRO
1342 if (p->which && p->which < max_fringe_bmp)
1344 XGCValues gcv;
1346 XGetGCValues (display, gc, GCForeground | GCBackground, &gcv);
1347 XSetForeground (display, gc, (p->cursor_p
1348 ? (p->overlay_p ? face->background
1349 : f->output_data.x->cursor_pixel)
1350 : face->foreground));
1351 XSetBackground (display, gc, face->background);
1352 x_cr_draw_image (f, gc, fringe_bmp[p->which], 0, p->dh,
1353 p->wd, p->h, p->x, p->y, p->overlay_p);
1354 XSetForeground (display, gc, gcv.foreground);
1355 XSetBackground (display, gc, gcv.background);
1357 #else /* not USE_CAIRO */
1358 if (p->which)
1360 Window window = FRAME_X_WINDOW (f);
1361 char *bits;
1362 Pixmap pixmap, clipmask = (Pixmap) 0;
1363 int depth = DefaultDepthOfScreen (FRAME_X_SCREEN (f));
1364 XGCValues gcv;
1366 if (p->wd > 8)
1367 bits = (char *) (p->bits + p->dh);
1368 else
1369 bits = (char *) p->bits + p->dh;
1371 /* Draw the bitmap. I believe these small pixmaps can be cached
1372 by the server. */
1373 pixmap = XCreatePixmapFromBitmapData (display, window, bits, p->wd, p->h,
1374 (p->cursor_p
1375 ? (p->overlay_p ? face->background
1376 : f->output_data.x->cursor_pixel)
1377 : face->foreground),
1378 face->background, depth);
1380 if (p->overlay_p)
1382 clipmask = XCreatePixmapFromBitmapData (display,
1383 FRAME_DISPLAY_INFO (f)->root_window,
1384 bits, p->wd, p->h,
1385 1, 0, 1);
1386 gcv.clip_mask = clipmask;
1387 gcv.clip_x_origin = p->x;
1388 gcv.clip_y_origin = p->y;
1389 XChangeGC (display, gc, GCClipMask | GCClipXOrigin | GCClipYOrigin, &gcv);
1392 XCopyArea (display, pixmap, window, gc, 0, 0,
1393 p->wd, p->h, p->x, p->y);
1394 XFreePixmap (display, pixmap);
1396 if (p->overlay_p)
1398 gcv.clip_mask = (Pixmap) 0;
1399 XChangeGC (display, gc, GCClipMask, &gcv);
1400 XFreePixmap (display, clipmask);
1403 #endif /* not USE_CAIRO */
1405 x_reset_clip_rectangles (f, gc);
1408 /***********************************************************************
1409 Glyph display
1410 ***********************************************************************/
1414 static void x_set_glyph_string_clipping (struct glyph_string *);
1415 static void x_set_glyph_string_gc (struct glyph_string *);
1416 static void x_draw_glyph_string_foreground (struct glyph_string *);
1417 static void x_draw_composite_glyph_string_foreground (struct glyph_string *);
1418 static void x_draw_glyph_string_box (struct glyph_string *);
1419 static void x_draw_glyph_string (struct glyph_string *);
1420 static _Noreturn void x_delete_glyphs (struct frame *, int);
1421 static void x_compute_glyph_string_overhangs (struct glyph_string *);
1422 static void x_set_cursor_gc (struct glyph_string *);
1423 static void x_set_mode_line_face_gc (struct glyph_string *);
1424 static void x_set_mouse_face_gc (struct glyph_string *);
1425 static bool x_alloc_lighter_color (struct frame *, Display *, Colormap,
1426 unsigned long *, double, int);
1427 static void x_setup_relief_color (struct frame *, struct relief *,
1428 double, int, unsigned long);
1429 static void x_setup_relief_colors (struct glyph_string *);
1430 static void x_draw_image_glyph_string (struct glyph_string *);
1431 static void x_draw_image_relief (struct glyph_string *);
1432 static void x_draw_image_foreground (struct glyph_string *);
1433 static void x_draw_image_foreground_1 (struct glyph_string *, Pixmap);
1434 static void x_clear_glyph_string_rect (struct glyph_string *, int,
1435 int, int, int);
1436 static void x_draw_relief_rect (struct frame *, int, int, int, int,
1437 int, bool, bool, bool, bool, bool,
1438 XRectangle *);
1439 static void x_draw_box_rect (struct glyph_string *, int, int, int, int,
1440 int, bool, bool, XRectangle *);
1441 static void x_scroll_bar_clear (struct frame *);
1443 #ifdef GLYPH_DEBUG
1444 static void x_check_font (struct frame *, struct font *);
1445 #endif
1448 /* Set S->gc to a suitable GC for drawing glyph string S in cursor
1449 face. */
1451 static void
1452 x_set_cursor_gc (struct glyph_string *s)
1454 if (s->font == FRAME_FONT (s->f)
1455 && s->face->background == FRAME_BACKGROUND_PIXEL (s->f)
1456 && s->face->foreground == FRAME_FOREGROUND_PIXEL (s->f)
1457 && !s->cmp)
1458 s->gc = s->f->output_data.x->cursor_gc;
1459 else
1461 /* Cursor on non-default face: must merge. */
1462 XGCValues xgcv;
1463 unsigned long mask;
1465 xgcv.background = s->f->output_data.x->cursor_pixel;
1466 xgcv.foreground = s->face->background;
1468 /* If the glyph would be invisible, try a different foreground. */
1469 if (xgcv.foreground == xgcv.background)
1470 xgcv.foreground = s->face->foreground;
1471 if (xgcv.foreground == xgcv.background)
1472 xgcv.foreground = s->f->output_data.x->cursor_foreground_pixel;
1473 if (xgcv.foreground == xgcv.background)
1474 xgcv.foreground = s->face->foreground;
1476 /* Make sure the cursor is distinct from text in this face. */
1477 if (xgcv.background == s->face->background
1478 && xgcv.foreground == s->face->foreground)
1480 xgcv.background = s->face->foreground;
1481 xgcv.foreground = s->face->background;
1484 IF_DEBUG (x_check_font (s->f, s->font));
1485 xgcv.graphics_exposures = False;
1486 mask = GCForeground | GCBackground | GCGraphicsExposures;
1488 if (FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc)
1489 XChangeGC (s->display, FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc,
1490 mask, &xgcv);
1491 else
1492 FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc
1493 = XCreateGC (s->display, s->window, mask, &xgcv);
1495 s->gc = FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc;
1500 /* Set up S->gc of glyph string S for drawing text in mouse face. */
1502 static void
1503 x_set_mouse_face_gc (struct glyph_string *s)
1505 int face_id;
1506 struct face *face;
1508 /* What face has to be used last for the mouse face? */
1509 face_id = MOUSE_HL_INFO (s->f)->mouse_face_face_id;
1510 face = FACE_OPT_FROM_ID (s->f, face_id);
1511 if (face == NULL)
1512 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
1514 if (s->first_glyph->type == CHAR_GLYPH)
1515 face_id = FACE_FOR_CHAR (s->f, face, s->first_glyph->u.ch, -1, Qnil);
1516 else
1517 face_id = FACE_FOR_CHAR (s->f, face, 0, -1, Qnil);
1518 s->face = FACE_FROM_ID (s->f, face_id);
1519 prepare_face_for_display (s->f, s->face);
1521 if (s->font == s->face->font)
1522 s->gc = s->face->gc;
1523 else
1525 /* Otherwise construct scratch_cursor_gc with values from FACE
1526 except for FONT. */
1527 XGCValues xgcv;
1528 unsigned long mask;
1530 xgcv.background = s->face->background;
1531 xgcv.foreground = s->face->foreground;
1532 xgcv.graphics_exposures = False;
1533 mask = GCForeground | GCBackground | GCGraphicsExposures;
1535 if (FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc)
1536 XChangeGC (s->display, FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc,
1537 mask, &xgcv);
1538 else
1539 FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc
1540 = XCreateGC (s->display, s->window, mask, &xgcv);
1542 s->gc = FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc;
1545 eassert (s->gc != 0);
1549 /* Set S->gc of glyph string S to a GC suitable for drawing a mode line.
1550 Faces to use in the mode line have already been computed when the
1551 matrix was built, so there isn't much to do, here. */
1553 static void
1554 x_set_mode_line_face_gc (struct glyph_string *s)
1556 s->gc = s->face->gc;
1560 /* Set S->gc of glyph string S for drawing that glyph string. Set
1561 S->stippled_p to a non-zero value if the face of S has a stipple
1562 pattern. */
1564 static void
1565 x_set_glyph_string_gc (struct glyph_string *s)
1567 prepare_face_for_display (s->f, s->face);
1569 if (s->hl == DRAW_NORMAL_TEXT)
1571 s->gc = s->face->gc;
1572 s->stippled_p = s->face->stipple != 0;
1574 else if (s->hl == DRAW_INVERSE_VIDEO)
1576 x_set_mode_line_face_gc (s);
1577 s->stippled_p = s->face->stipple != 0;
1579 else if (s->hl == DRAW_CURSOR)
1581 x_set_cursor_gc (s);
1582 s->stippled_p = false;
1584 else if (s->hl == DRAW_MOUSE_FACE)
1586 x_set_mouse_face_gc (s);
1587 s->stippled_p = s->face->stipple != 0;
1589 else if (s->hl == DRAW_IMAGE_RAISED
1590 || s->hl == DRAW_IMAGE_SUNKEN)
1592 s->gc = s->face->gc;
1593 s->stippled_p = s->face->stipple != 0;
1595 else
1596 emacs_abort ();
1598 /* GC must have been set. */
1599 eassert (s->gc != 0);
1603 /* Set clipping for output of glyph string S. S may be part of a mode
1604 line or menu if we don't have X toolkit support. */
1606 static void
1607 x_set_glyph_string_clipping (struct glyph_string *s)
1609 XRectangle *r = s->clip;
1610 int n = get_glyph_string_clip_rects (s, r, 2);
1612 if (n > 0)
1613 x_set_clip_rectangles (s->f, s->gc, r, n);
1614 s->num_clips = n;
1618 /* Set SRC's clipping for output of glyph string DST. This is called
1619 when we are drawing DST's left_overhang or right_overhang only in
1620 the area of SRC. */
1622 static void
1623 x_set_glyph_string_clipping_exactly (struct glyph_string *src, struct glyph_string *dst)
1625 XRectangle r;
1627 r.x = src->x;
1628 r.width = src->width;
1629 r.y = src->y;
1630 r.height = src->height;
1631 dst->clip[0] = r;
1632 dst->num_clips = 1;
1633 x_set_clip_rectangles (dst->f, dst->gc, &r, 1);
1637 /* RIF:
1638 Compute left and right overhang of glyph string S. */
1640 static void
1641 x_compute_glyph_string_overhangs (struct glyph_string *s)
1643 if (s->cmp == NULL
1644 && (s->first_glyph->type == CHAR_GLYPH
1645 || s->first_glyph->type == COMPOSITE_GLYPH))
1647 struct font_metrics metrics;
1649 if (s->first_glyph->type == CHAR_GLYPH)
1651 unsigned *code = alloca (sizeof (unsigned) * s->nchars);
1652 struct font *font = s->font;
1653 int i;
1655 for (i = 0; i < s->nchars; i++)
1656 code[i] = (s->char2b[i].byte1 << 8) | s->char2b[i].byte2;
1657 font->driver->text_extents (font, code, s->nchars, &metrics);
1659 else
1661 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1663 composition_gstring_width (gstring, s->cmp_from, s->cmp_to, &metrics);
1665 s->right_overhang = (metrics.rbearing > metrics.width
1666 ? metrics.rbearing - metrics.width : 0);
1667 s->left_overhang = metrics.lbearing < 0 ? - metrics.lbearing : 0;
1669 else if (s->cmp)
1671 s->right_overhang = s->cmp->rbearing - s->cmp->pixel_width;
1672 s->left_overhang = - s->cmp->lbearing;
1677 /* Fill rectangle X, Y, W, H with background color of glyph string S. */
1679 static void
1680 x_clear_glyph_string_rect (struct glyph_string *s, int x, int y, int w, int h)
1682 XGCValues xgcv;
1683 XGetGCValues (s->display, s->gc, GCForeground | GCBackground, &xgcv);
1684 XSetForeground (s->display, s->gc, xgcv.background);
1685 x_fill_rectangle (s->f, s->gc, x, y, w, h);
1686 XSetForeground (s->display, s->gc, xgcv.foreground);
1690 /* Draw the background of glyph_string S. If S->background_filled_p
1691 is non-zero don't draw it. FORCE_P non-zero means draw the
1692 background even if it wouldn't be drawn normally. This is used
1693 when a string preceding S draws into the background of S, or S
1694 contains the first component of a composition. */
1696 static void
1697 x_draw_glyph_string_background (struct glyph_string *s, bool force_p)
1699 /* Nothing to do if background has already been drawn or if it
1700 shouldn't be drawn in the first place. */
1701 if (!s->background_filled_p)
1703 int box_line_width = max (s->face->box_line_width, 0);
1705 if (s->stippled_p)
1707 /* Fill background with a stipple pattern. */
1708 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
1709 x_fill_rectangle (s->f, s->gc, s->x,
1710 s->y + box_line_width,
1711 s->background_width,
1712 s->height - 2 * box_line_width);
1713 XSetFillStyle (s->display, s->gc, FillSolid);
1714 s->background_filled_p = true;
1716 else if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
1717 /* When xdisp.c ignores FONT_HEIGHT, we cannot trust
1718 font dimensions, since the actual glyphs might be
1719 much smaller. So in that case we always clear the
1720 rectangle with background color. */
1721 || FONT_TOO_HIGH (s->font)
1722 || s->font_not_found_p
1723 || s->extends_to_end_of_line_p
1724 || force_p)
1726 x_clear_glyph_string_rect (s, s->x, s->y + box_line_width,
1727 s->background_width,
1728 s->height - 2 * box_line_width);
1729 s->background_filled_p = true;
1735 /* Draw the foreground of glyph string S. */
1737 static void
1738 x_draw_glyph_string_foreground (struct glyph_string *s)
1740 int i, x;
1742 /* If first glyph of S has a left box line, start drawing the text
1743 of S to the right of that box line. */
1744 if (s->face->box != FACE_NO_BOX
1745 && s->first_glyph->left_box_line_p)
1746 x = s->x + eabs (s->face->box_line_width);
1747 else
1748 x = s->x;
1750 /* Draw characters of S as rectangles if S's font could not be
1751 loaded. */
1752 if (s->font_not_found_p)
1754 for (i = 0; i < s->nchars; ++i)
1756 struct glyph *g = s->first_glyph + i;
1757 x_draw_rectangle (s->f,
1758 s->gc, x, s->y, g->pixel_width - 1,
1759 s->height - 1);
1760 x += g->pixel_width;
1763 else
1765 struct font *font = s->font;
1766 int boff = font->baseline_offset;
1767 int y;
1769 if (font->vertical_centering)
1770 boff = VCENTER_BASELINE_OFFSET (font, s->f) - boff;
1772 y = s->ybase - boff;
1773 if (s->for_overlaps
1774 || (s->background_filled_p && s->hl != DRAW_CURSOR))
1775 font->driver->draw (s, 0, s->nchars, x, y, false);
1776 else
1777 font->driver->draw (s, 0, s->nchars, x, y, true);
1778 if (s->face->overstrike)
1779 font->driver->draw (s, 0, s->nchars, x + 1, y, false);
1783 /* Draw the foreground of composite glyph string S. */
1785 static void
1786 x_draw_composite_glyph_string_foreground (struct glyph_string *s)
1788 int i, j, x;
1789 struct font *font = s->font;
1791 /* If first glyph of S has a left box line, start drawing the text
1792 of S to the right of that box line. */
1793 if (s->face && s->face->box != FACE_NO_BOX
1794 && s->first_glyph->left_box_line_p)
1795 x = s->x + eabs (s->face->box_line_width);
1796 else
1797 x = s->x;
1799 /* S is a glyph string for a composition. S->cmp_from is the index
1800 of the first character drawn for glyphs of this composition.
1801 S->cmp_from == 0 means we are drawing the very first character of
1802 this composition. */
1804 /* Draw a rectangle for the composition if the font for the very
1805 first character of the composition could not be loaded. */
1806 if (s->font_not_found_p)
1808 if (s->cmp_from == 0)
1809 x_draw_rectangle (s->f, s->gc, x, s->y,
1810 s->width - 1, s->height - 1);
1812 else if (! s->first_glyph->u.cmp.automatic)
1814 int y = s->ybase;
1816 for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
1817 /* TAB in a composition means display glyphs with padding
1818 space on the left or right. */
1819 if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
1821 int xx = x + s->cmp->offsets[j * 2];
1822 int yy = y - s->cmp->offsets[j * 2 + 1];
1824 font->driver->draw (s, j, j + 1, xx, yy, false);
1825 if (s->face->overstrike)
1826 font->driver->draw (s, j, j + 1, xx + 1, yy, false);
1829 else
1831 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1832 Lisp_Object glyph;
1833 int y = s->ybase;
1834 int width = 0;
1836 for (i = j = s->cmp_from; i < s->cmp_to; i++)
1838 glyph = LGSTRING_GLYPH (gstring, i);
1839 if (NILP (LGLYPH_ADJUSTMENT (glyph)))
1840 width += LGLYPH_WIDTH (glyph);
1841 else
1843 int xoff, yoff, wadjust;
1845 if (j < i)
1847 font->driver->draw (s, j, i, x, y, false);
1848 if (s->face->overstrike)
1849 font->driver->draw (s, j, i, x + 1, y, false);
1850 x += width;
1852 xoff = LGLYPH_XOFF (glyph);
1853 yoff = LGLYPH_YOFF (glyph);
1854 wadjust = LGLYPH_WADJUST (glyph);
1855 font->driver->draw (s, i, i + 1, x + xoff, y + yoff, false);
1856 if (s->face->overstrike)
1857 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff,
1858 false);
1859 x += wadjust;
1860 j = i + 1;
1861 width = 0;
1864 if (j < i)
1866 font->driver->draw (s, j, i, x, y, false);
1867 if (s->face->overstrike)
1868 font->driver->draw (s, j, i, x + 1, y, false);
1874 /* Draw the foreground of glyph string S for glyphless characters. */
1876 static void
1877 x_draw_glyphless_glyph_string_foreground (struct glyph_string *s)
1879 struct glyph *glyph = s->first_glyph;
1880 XChar2b char2b[8];
1881 int x, i, j;
1883 /* If first glyph of S has a left box line, start drawing the text
1884 of S to the right of that box line. */
1885 if (s->face && s->face->box != FACE_NO_BOX
1886 && s->first_glyph->left_box_line_p)
1887 x = s->x + eabs (s->face->box_line_width);
1888 else
1889 x = s->x;
1891 s->char2b = char2b;
1893 for (i = 0; i < s->nchars; i++, glyph++)
1895 char buf[7], *str = NULL;
1896 int len = glyph->u.glyphless.len;
1898 if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_ACRONYM)
1900 if (len > 0
1901 && CHAR_TABLE_P (Vglyphless_char_display)
1902 && (CHAR_TABLE_EXTRA_SLOTS (XCHAR_TABLE (Vglyphless_char_display))
1903 >= 1))
1905 Lisp_Object acronym
1906 = (! glyph->u.glyphless.for_no_font
1907 ? CHAR_TABLE_REF (Vglyphless_char_display,
1908 glyph->u.glyphless.ch)
1909 : XCHAR_TABLE (Vglyphless_char_display)->extras[0]);
1910 if (STRINGP (acronym))
1911 str = SSDATA (acronym);
1914 else if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_HEX_CODE)
1916 sprintf (buf, "%0*X",
1917 glyph->u.glyphless.ch < 0x10000 ? 4 : 6,
1918 glyph->u.glyphless.ch + 0u);
1919 str = buf;
1922 if (str)
1924 int upper_len = (len + 1) / 2;
1925 unsigned code;
1927 /* It is assured that all LEN characters in STR is ASCII. */
1928 for (j = 0; j < len; j++)
1930 code = s->font->driver->encode_char (s->font, str[j]);
1931 STORE_XCHAR2B (char2b + j, code >> 8, code & 0xFF);
1933 s->font->driver->draw (s, 0, upper_len,
1934 x + glyph->slice.glyphless.upper_xoff,
1935 s->ybase + glyph->slice.glyphless.upper_yoff,
1936 false);
1937 s->font->driver->draw (s, upper_len, len,
1938 x + glyph->slice.glyphless.lower_xoff,
1939 s->ybase + glyph->slice.glyphless.lower_yoff,
1940 false);
1942 if (glyph->u.glyphless.method != GLYPHLESS_DISPLAY_THIN_SPACE)
1943 x_draw_rectangle (s->f, s->gc,
1944 x, s->ybase - glyph->ascent,
1945 glyph->pixel_width - 1,
1946 glyph->ascent + glyph->descent - 1);
1947 x += glyph->pixel_width;
1951 #ifdef USE_X_TOOLKIT
1953 #ifdef USE_LUCID
1955 /* Return the frame on which widget WIDGET is used.. Abort if frame
1956 cannot be determined. */
1958 static struct frame *
1959 x_frame_of_widget (Widget widget)
1961 struct x_display_info *dpyinfo;
1962 Lisp_Object tail, frame;
1963 struct frame *f;
1965 dpyinfo = x_display_info_for_display (XtDisplay (widget));
1967 /* Find the top-level shell of the widget. Note that this function
1968 can be called when the widget is not yet realized, so XtWindow
1969 (widget) == 0. That's the reason we can't simply use
1970 x_any_window_to_frame. */
1971 while (!XtIsTopLevelShell (widget))
1972 widget = XtParent (widget);
1974 /* Look for a frame with that top-level widget. Allocate the color
1975 on that frame to get the right gamma correction value. */
1976 FOR_EACH_FRAME (tail, frame)
1978 f = XFRAME (frame);
1979 if (FRAME_X_P (f)
1980 && f->output_data.nothing != 1
1981 && FRAME_DISPLAY_INFO (f) == dpyinfo
1982 && f->output_data.x->widget == widget)
1983 return f;
1985 emacs_abort ();
1988 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
1989 or DELTA. Try a color with RGB values multiplied by FACTOR first.
1990 If this produces the same color as PIXEL, try a color where all RGB
1991 values have DELTA added. Return the allocated color in *PIXEL.
1992 DISPLAY is the X display, CMAP is the colormap to operate on.
1993 Value is true if successful. */
1995 bool
1996 x_alloc_lighter_color_for_widget (Widget widget, Display *display, Colormap cmap,
1997 unsigned long *pixel, double factor, int delta)
1999 struct frame *f = x_frame_of_widget (widget);
2000 return x_alloc_lighter_color (f, display, cmap, pixel, factor, delta);
2003 #endif /* USE_LUCID */
2006 /* Structure specifying which arguments should be passed by Xt to
2007 cvt_string_to_pixel. We want the widget's screen and colormap. */
2009 static XtConvertArgRec cvt_string_to_pixel_args[] =
2011 {XtWidgetBaseOffset, (XtPointer) offsetof (WidgetRec, core.screen),
2012 sizeof (Screen *)},
2013 {XtWidgetBaseOffset, (XtPointer) offsetof (WidgetRec, core.colormap),
2014 sizeof (Colormap)}
2018 /* The address of this variable is returned by
2019 cvt_string_to_pixel. */
2021 static Pixel cvt_string_to_pixel_value;
2024 /* Convert a color name to a pixel color.
2026 DPY is the display we are working on.
2028 ARGS is an array of *NARGS XrmValue structures holding additional
2029 information about the widget for which the conversion takes place.
2030 The contents of this array are determined by the specification
2031 in cvt_string_to_pixel_args.
2033 FROM is a pointer to an XrmValue which points to the color name to
2034 convert. TO is an XrmValue in which to return the pixel color.
2036 CLOSURE_RET is a pointer to user-data, in which we record if
2037 we allocated the color or not.
2039 Value is True if successful, False otherwise. */
2041 static Boolean
2042 cvt_string_to_pixel (Display *dpy, XrmValue *args, Cardinal *nargs,
2043 XrmValue *from, XrmValue *to,
2044 XtPointer *closure_ret)
2046 Screen *screen;
2047 Colormap cmap;
2048 Pixel pixel;
2049 String color_name;
2050 XColor color;
2052 if (*nargs != 2)
2054 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
2055 "wrongParameters", "cvt_string_to_pixel",
2056 "XtToolkitError",
2057 "Screen and colormap args required", NULL, NULL);
2058 return False;
2061 screen = *(Screen **) args[0].addr;
2062 cmap = *(Colormap *) args[1].addr;
2063 color_name = (String) from->addr;
2065 if (strcmp (color_name, XtDefaultBackground) == 0)
2067 *closure_ret = (XtPointer) False;
2068 pixel = WhitePixelOfScreen (screen);
2070 else if (strcmp (color_name, XtDefaultForeground) == 0)
2072 *closure_ret = (XtPointer) False;
2073 pixel = BlackPixelOfScreen (screen);
2075 else if (XParseColor (dpy, cmap, color_name, &color)
2076 && x_alloc_nearest_color_1 (dpy, cmap, &color))
2078 pixel = color.pixel;
2079 *closure_ret = (XtPointer) True;
2081 else
2083 String params[1];
2084 Cardinal nparams = 1;
2086 params[0] = color_name;
2087 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
2088 "badValue", "cvt_string_to_pixel",
2089 "XtToolkitError", "Invalid color '%s'",
2090 params, &nparams);
2091 return False;
2094 if (to->addr != NULL)
2096 if (to->size < sizeof (Pixel))
2098 to->size = sizeof (Pixel);
2099 return False;
2102 *(Pixel *) to->addr = pixel;
2104 else
2106 cvt_string_to_pixel_value = pixel;
2107 to->addr = (XtPointer) &cvt_string_to_pixel_value;
2110 to->size = sizeof (Pixel);
2111 return True;
2115 /* Free a pixel color which was previously allocated via
2116 cvt_string_to_pixel. This is registered as the destructor
2117 for this type of resource via XtSetTypeConverter.
2119 APP is the application context in which we work.
2121 TO is a pointer to an XrmValue holding the color to free.
2122 CLOSURE is the value we stored in CLOSURE_RET for this color
2123 in cvt_string_to_pixel.
2125 ARGS and NARGS are like for cvt_string_to_pixel. */
2127 static void
2128 cvt_pixel_dtor (XtAppContext app, XrmValuePtr to, XtPointer closure, XrmValuePtr args,
2129 Cardinal *nargs)
2131 if (*nargs != 2)
2133 XtAppWarningMsg (app, "wrongParameters", "cvt_pixel_dtor",
2134 "XtToolkitError",
2135 "Screen and colormap arguments required",
2136 NULL, NULL);
2138 else if (closure != NULL)
2140 /* We did allocate the pixel, so free it. */
2141 Screen *screen = *(Screen **) args[0].addr;
2142 Colormap cmap = *(Colormap *) args[1].addr;
2143 x_free_dpy_colors (DisplayOfScreen (screen), screen, cmap,
2144 (Pixel *) to->addr, 1);
2149 #endif /* USE_X_TOOLKIT */
2152 /* Value is an array of XColor structures for the contents of the
2153 color map of display DPY. Set *NCELLS to the size of the array.
2154 Note that this probably shouldn't be called for large color maps,
2155 say a 24-bit TrueColor map. */
2157 static const XColor *
2158 x_color_cells (Display *dpy, int *ncells)
2160 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
2161 eassume (dpyinfo);
2163 if (dpyinfo->color_cells == NULL)
2165 Screen *screen = dpyinfo->screen;
2166 int ncolor_cells = XDisplayCells (dpy, XScreenNumberOfScreen (screen));
2167 int i;
2169 dpyinfo->color_cells = xnmalloc (ncolor_cells,
2170 sizeof *dpyinfo->color_cells);
2171 dpyinfo->ncolor_cells = ncolor_cells;
2173 for (i = 0; i < ncolor_cells; ++i)
2174 dpyinfo->color_cells[i].pixel = i;
2176 XQueryColors (dpy, dpyinfo->cmap,
2177 dpyinfo->color_cells, ncolor_cells);
2180 *ncells = dpyinfo->ncolor_cells;
2181 return dpyinfo->color_cells;
2185 /* On frame F, translate pixel colors to RGB values for the NCOLORS
2186 colors in COLORS. Use cached information, if available. */
2188 void
2189 x_query_colors (struct frame *f, XColor *colors, int ncolors)
2191 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2193 if (dpyinfo->red_bits > 0)
2195 /* For TrueColor displays, we can decompose the RGB value
2196 directly. */
2197 int i;
2198 unsigned int rmult, gmult, bmult;
2199 unsigned int rmask, gmask, bmask;
2201 rmask = (1 << dpyinfo->red_bits) - 1;
2202 gmask = (1 << dpyinfo->green_bits) - 1;
2203 bmask = (1 << dpyinfo->blue_bits) - 1;
2204 /* If we're widening, for example, 8 bits in the pixel value to
2205 16 bits for the separate-color representation, we want to
2206 extrapolate the lower bits based on those bits available --
2207 in other words, we'd like 0xff to become 0xffff instead of
2208 the 0xff00 we'd get by just zero-filling the lower bits.
2210 We generate a 32-bit scaled-up value and shift it, in case
2211 the bit count doesn't divide 16 evenly (e.g., when dealing
2212 with a 3-3-2 bit RGB display), to get more of the lower bits
2213 correct.
2215 Should we cache the multipliers in dpyinfo? Maybe
2216 special-case the 8-8-8 common case? */
2217 rmult = 0xffffffff / rmask;
2218 gmult = 0xffffffff / gmask;
2219 bmult = 0xffffffff / bmask;
2221 for (i = 0; i < ncolors; ++i)
2223 unsigned int r, g, b;
2224 unsigned long pixel = colors[i].pixel;
2226 r = (pixel >> dpyinfo->red_offset) & rmask;
2227 g = (pixel >> dpyinfo->green_offset) & gmask;
2228 b = (pixel >> dpyinfo->blue_offset) & bmask;
2230 colors[i].red = (r * rmult) >> 16;
2231 colors[i].green = (g * gmult) >> 16;
2232 colors[i].blue = (b * bmult) >> 16;
2234 return;
2237 if (dpyinfo->color_cells)
2239 int i;
2240 for (i = 0; i < ncolors; ++i)
2242 unsigned long pixel = colors[i].pixel;
2243 eassert (pixel < dpyinfo->ncolor_cells);
2244 eassert (dpyinfo->color_cells[pixel].pixel == pixel);
2245 colors[i] = dpyinfo->color_cells[pixel];
2247 return;
2250 XQueryColors (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), colors, ncolors);
2254 /* On frame F, translate pixel color to RGB values for the color in
2255 COLOR. Use cached information, if available. */
2257 void
2258 x_query_color (struct frame *f, XColor *color)
2260 x_query_colors (f, color, 1);
2264 /* On frame F, translate the color name to RGB values. Use cached
2265 information, if possible.
2267 Note that there is currently no way to clean old entries out of the
2268 cache. However, it is limited to names in the server's database,
2269 and names we've actually looked up; list-colors-display is probably
2270 the most color-intensive case we're likely to hit. */
2272 Status x_parse_color (struct frame *f, const char *color_name,
2273 XColor *color)
2275 Display *dpy = FRAME_X_DISPLAY (f);
2276 Colormap cmap = FRAME_X_COLORMAP (f);
2277 struct color_name_cache_entry *cache_entry;
2279 if (color_name[0] == '#')
2281 /* The hex form is parsed directly by XParseColor without
2282 talking to the X server. No need for caching. */
2283 return XParseColor (dpy, cmap, color_name, color);
2286 for (cache_entry = FRAME_DISPLAY_INFO (f)->color_names; cache_entry;
2287 cache_entry = cache_entry->next)
2289 if (!xstrcasecmp(cache_entry->name, color_name))
2291 *color = cache_entry->rgb;
2292 return 1;
2296 if (XParseColor (dpy, cmap, color_name, color) == 0)
2297 /* No caching of negative results, currently. */
2298 return 0;
2300 cache_entry = xzalloc (sizeof *cache_entry);
2301 cache_entry->rgb = *color;
2302 cache_entry->name = xstrdup (color_name);
2303 cache_entry->next = FRAME_DISPLAY_INFO (f)->color_names;
2304 FRAME_DISPLAY_INFO (f)->color_names = cache_entry;
2305 return 1;
2309 /* Allocate the color COLOR->pixel on DISPLAY, colormap CMAP. If an
2310 exact match can't be allocated, try the nearest color available.
2311 Value is true if successful. Set *COLOR to the color
2312 allocated. */
2314 static bool
2315 x_alloc_nearest_color_1 (Display *dpy, Colormap cmap, XColor *color)
2317 bool rc;
2319 rc = XAllocColor (dpy, cmap, color) != 0;
2320 if (rc == 0)
2322 /* If we got to this point, the colormap is full, so we're going
2323 to try to get the next closest color. The algorithm used is
2324 a least-squares matching, which is what X uses for closest
2325 color matching with StaticColor visuals. */
2326 int nearest, i;
2327 int max_color_delta = 255;
2328 int max_delta = 3 * max_color_delta;
2329 int nearest_delta = max_delta + 1;
2330 int ncells;
2331 const XColor *cells = x_color_cells (dpy, &ncells);
2333 for (nearest = i = 0; i < ncells; ++i)
2335 int dred = (color->red >> 8) - (cells[i].red >> 8);
2336 int dgreen = (color->green >> 8) - (cells[i].green >> 8);
2337 int dblue = (color->blue >> 8) - (cells[i].blue >> 8);
2338 int delta = dred * dred + dgreen * dgreen + dblue * dblue;
2340 if (delta < nearest_delta)
2342 nearest = i;
2343 nearest_delta = delta;
2347 color->red = cells[nearest].red;
2348 color->green = cells[nearest].green;
2349 color->blue = cells[nearest].blue;
2350 rc = XAllocColor (dpy, cmap, color) != 0;
2352 else
2354 /* If allocation succeeded, and the allocated pixel color is not
2355 equal to a cached pixel color recorded earlier, there was a
2356 change in the colormap, so clear the color cache. */
2357 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
2358 eassume (dpyinfo);
2360 if (dpyinfo->color_cells)
2362 XColor *cached_color = &dpyinfo->color_cells[color->pixel];
2363 if (cached_color->red != color->red
2364 || cached_color->blue != color->blue
2365 || cached_color->green != color->green)
2367 xfree (dpyinfo->color_cells);
2368 dpyinfo->color_cells = NULL;
2369 dpyinfo->ncolor_cells = 0;
2374 #ifdef DEBUG_X_COLORS
2375 if (rc)
2376 register_color (color->pixel);
2377 #endif /* DEBUG_X_COLORS */
2379 return rc;
2383 /* Allocate the color COLOR->pixel on frame F, colormap CMAP, after
2384 gamma correction. If an exact match can't be allocated, try the
2385 nearest color available. Value is true if successful. Set *COLOR
2386 to the color allocated. */
2388 bool
2389 x_alloc_nearest_color (struct frame *f, Colormap cmap, XColor *color)
2391 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2393 gamma_correct (f, color);
2395 if (dpyinfo->red_bits > 0)
2397 color->pixel = x_make_truecolor_pixel (dpyinfo,
2398 color->red,
2399 color->green,
2400 color->blue);
2401 return true;
2404 return x_alloc_nearest_color_1 (FRAME_X_DISPLAY (f), cmap, color);
2408 /* Allocate color PIXEL on frame F. PIXEL must already be allocated.
2409 It's necessary to do this instead of just using PIXEL directly to
2410 get color reference counts right. */
2412 unsigned long
2413 x_copy_color (struct frame *f, unsigned long pixel)
2415 XColor color;
2417 /* If display has an immutable color map, freeing colors is not
2418 necessary and some servers don't allow it. Since we won't free a
2419 color once we've allocated it, we don't need to re-allocate it to
2420 maintain the server's reference count. */
2421 if (!x_mutable_colormap (FRAME_X_VISUAL (f)))
2422 return pixel;
2424 color.pixel = pixel;
2425 block_input ();
2426 /* The color could still be found in the color_cells array. */
2427 x_query_color (f, &color);
2428 XAllocColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &color);
2429 unblock_input ();
2430 #ifdef DEBUG_X_COLORS
2431 register_color (pixel);
2432 #endif
2433 return color.pixel;
2437 /* Brightness beyond which a color won't have its highlight brightness
2438 boosted.
2440 Nominally, highlight colors for `3d' faces are calculated by
2441 brightening an object's color by a constant scale factor, but this
2442 doesn't yield good results for dark colors, so for colors who's
2443 brightness is less than this value (on a scale of 0-65535) have an
2444 use an additional additive factor.
2446 The value here is set so that the default menu-bar/mode-line color
2447 (grey75) will not have its highlights changed at all. */
2448 #define HIGHLIGHT_COLOR_DARK_BOOST_LIMIT 48000
2451 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
2452 or DELTA. Try a color with RGB values multiplied by FACTOR first.
2453 If this produces the same color as PIXEL, try a color where all RGB
2454 values have DELTA added. Return the allocated color in *PIXEL.
2455 DISPLAY is the X display, CMAP is the colormap to operate on.
2456 Value is non-zero if successful. */
2458 static bool
2459 x_alloc_lighter_color (struct frame *f, Display *display, Colormap cmap,
2460 unsigned long *pixel, double factor, int delta)
2462 XColor color, new;
2463 long bright;
2464 bool success_p;
2466 /* Get RGB color values. */
2467 color.pixel = *pixel;
2468 x_query_color (f, &color);
2470 /* Change RGB values by specified FACTOR. Avoid overflow! */
2471 eassert (factor >= 0);
2472 new.red = min (0xffff, factor * color.red);
2473 new.green = min (0xffff, factor * color.green);
2474 new.blue = min (0xffff, factor * color.blue);
2476 /* Calculate brightness of COLOR. */
2477 bright = (2 * color.red + 3 * color.green + color.blue) / 6;
2479 /* We only boost colors that are darker than
2480 HIGHLIGHT_COLOR_DARK_BOOST_LIMIT. */
2481 if (bright < HIGHLIGHT_COLOR_DARK_BOOST_LIMIT)
2482 /* Make an additive adjustment to NEW, because it's dark enough so
2483 that scaling by FACTOR alone isn't enough. */
2485 /* How far below the limit this color is (0 - 1, 1 being darker). */
2486 double dimness = 1 - (double)bright / HIGHLIGHT_COLOR_DARK_BOOST_LIMIT;
2487 /* The additive adjustment. */
2488 int min_delta = delta * dimness * factor / 2;
2490 if (factor < 1)
2492 new.red = max (0, new.red - min_delta);
2493 new.green = max (0, new.green - min_delta);
2494 new.blue = max (0, new.blue - min_delta);
2496 else
2498 new.red = min (0xffff, min_delta + new.red);
2499 new.green = min (0xffff, min_delta + new.green);
2500 new.blue = min (0xffff, min_delta + new.blue);
2504 /* Try to allocate the color. */
2505 success_p = x_alloc_nearest_color (f, cmap, &new);
2506 if (success_p)
2508 if (new.pixel == *pixel)
2510 /* If we end up with the same color as before, try adding
2511 delta to the RGB values. */
2512 x_free_colors (f, &new.pixel, 1);
2514 new.red = min (0xffff, delta + color.red);
2515 new.green = min (0xffff, delta + color.green);
2516 new.blue = min (0xffff, delta + color.blue);
2517 success_p = x_alloc_nearest_color (f, cmap, &new);
2519 else
2520 success_p = true;
2521 *pixel = new.pixel;
2524 return success_p;
2528 /* Set up the foreground color for drawing relief lines of glyph
2529 string S. RELIEF is a pointer to a struct relief containing the GC
2530 with which lines will be drawn. Use a color that is FACTOR or
2531 DELTA lighter or darker than the relief's background which is found
2532 in S->f->output_data.x->relief_background. If such a color cannot
2533 be allocated, use DEFAULT_PIXEL, instead. */
2535 static void
2536 x_setup_relief_color (struct frame *f, struct relief *relief, double factor,
2537 int delta, unsigned long default_pixel)
2539 XGCValues xgcv;
2540 struct x_output *di = f->output_data.x;
2541 unsigned long mask = GCForeground | GCLineWidth | GCGraphicsExposures;
2542 unsigned long pixel;
2543 unsigned long background = di->relief_background;
2544 Colormap cmap = FRAME_X_COLORMAP (f);
2545 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2546 Display *dpy = FRAME_X_DISPLAY (f);
2548 xgcv.graphics_exposures = False;
2549 xgcv.line_width = 1;
2551 /* Free previously allocated color. The color cell will be reused
2552 when it has been freed as many times as it was allocated, so this
2553 doesn't affect faces using the same colors. */
2554 if (relief->gc && relief->pixel != -1)
2556 x_free_colors (f, &relief->pixel, 1);
2557 relief->pixel = -1;
2560 /* Allocate new color. */
2561 xgcv.foreground = default_pixel;
2562 pixel = background;
2563 if (dpyinfo->n_planes != 1
2564 && x_alloc_lighter_color (f, dpy, cmap, &pixel, factor, delta))
2565 xgcv.foreground = relief->pixel = pixel;
2567 if (relief->gc == 0)
2569 xgcv.stipple = dpyinfo->gray;
2570 mask |= GCStipple;
2571 relief->gc = XCreateGC (dpy, FRAME_X_WINDOW (f), mask, &xgcv);
2573 else
2574 XChangeGC (dpy, relief->gc, mask, &xgcv);
2578 /* Set up colors for the relief lines around glyph string S. */
2580 static void
2581 x_setup_relief_colors (struct glyph_string *s)
2583 struct x_output *di = s->f->output_data.x;
2584 unsigned long color;
2586 if (s->face->use_box_color_for_shadows_p)
2587 color = s->face->box_color;
2588 else if (s->first_glyph->type == IMAGE_GLYPH
2589 && s->img->pixmap
2590 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2591 color = IMAGE_BACKGROUND (s->img, s->f, 0);
2592 else
2594 XGCValues xgcv;
2596 /* Get the background color of the face. */
2597 XGetGCValues (s->display, s->gc, GCBackground, &xgcv);
2598 color = xgcv.background;
2601 if (di->white_relief.gc == 0
2602 || color != di->relief_background)
2604 di->relief_background = color;
2605 x_setup_relief_color (s->f, &di->white_relief, 1.2, 0x8000,
2606 WHITE_PIX_DEFAULT (s->f));
2607 x_setup_relief_color (s->f, &di->black_relief, 0.6, 0x4000,
2608 BLACK_PIX_DEFAULT (s->f));
2613 /* Draw a relief on frame F inside the rectangle given by LEFT_X,
2614 TOP_Y, RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the relief
2615 to draw, it must be >= 0. RAISED_P means draw a raised
2616 relief. LEFT_P means draw a relief on the left side of
2617 the rectangle. RIGHT_P means draw a relief on the right
2618 side of the rectangle. CLIP_RECT is the clipping rectangle to use
2619 when drawing. */
2621 static void
2622 x_draw_relief_rect (struct frame *f,
2623 int left_x, int top_y, int right_x, int bottom_y,
2624 int width, bool raised_p, bool top_p, bool bot_p,
2625 bool left_p, bool right_p,
2626 XRectangle *clip_rect)
2628 #ifdef USE_CAIRO
2629 GC top_left_gc, bottom_right_gc;
2630 int corners = 0;
2632 if (raised_p)
2634 top_left_gc = f->output_data.x->white_relief.gc;
2635 bottom_right_gc = f->output_data.x->black_relief.gc;
2637 else
2639 top_left_gc = f->output_data.x->black_relief.gc;
2640 bottom_right_gc = f->output_data.x->white_relief.gc;
2643 x_set_clip_rectangles (f, top_left_gc, clip_rect, 1);
2644 x_set_clip_rectangles (f, bottom_right_gc, clip_rect, 1);
2646 if (left_p)
2648 x_fill_rectangle (f, top_left_gc, left_x, top_y,
2649 width, bottom_y + 1 - top_y);
2650 if (top_p)
2651 corners |= 1 << CORNER_TOP_LEFT;
2652 if (bot_p)
2653 corners |= 1 << CORNER_BOTTOM_LEFT;
2655 if (right_p)
2657 x_fill_rectangle (f, bottom_right_gc, right_x + 1 - width, top_y,
2658 width, bottom_y + 1 - top_y);
2659 if (top_p)
2660 corners |= 1 << CORNER_TOP_RIGHT;
2661 if (bot_p)
2662 corners |= 1 << CORNER_BOTTOM_RIGHT;
2664 if (top_p)
2666 if (!right_p)
2667 x_fill_rectangle (f, top_left_gc, left_x, top_y,
2668 right_x + 1 - left_x, width);
2669 else
2670 x_fill_trapezoid_for_relief (f, top_left_gc, left_x, top_y,
2671 right_x + 1 - left_x, width, 1);
2673 if (bot_p)
2675 if (!left_p)
2676 x_fill_rectangle (f, bottom_right_gc, left_x, bottom_y + 1 - width,
2677 right_x + 1 - left_x, width);
2678 else
2679 x_fill_trapezoid_for_relief (f, bottom_right_gc,
2680 left_x, bottom_y + 1 - width,
2681 right_x + 1 - left_x, width, 0);
2683 if (left_p && width != 1)
2684 x_fill_rectangle (f, bottom_right_gc, left_x, top_y,
2685 1, bottom_y + 1 - top_y);
2686 if (top_p && width != 1)
2687 x_fill_rectangle (f, bottom_right_gc, left_x, top_y,
2688 right_x + 1 - left_x, 1);
2689 if (corners)
2691 XSetBackground (FRAME_X_DISPLAY (f), top_left_gc,
2692 FRAME_BACKGROUND_PIXEL (f));
2693 x_erase_corners_for_relief (f, top_left_gc, left_x, top_y,
2694 right_x - left_x + 1, bottom_y - top_y + 1,
2695 6, 1, corners);
2698 x_reset_clip_rectangles (f, top_left_gc);
2699 x_reset_clip_rectangles (f, bottom_right_gc);
2700 #else
2701 Display *dpy = FRAME_X_DISPLAY (f);
2702 Window window = FRAME_X_WINDOW (f);
2703 int i;
2704 GC gc;
2706 if (raised_p)
2707 gc = f->output_data.x->white_relief.gc;
2708 else
2709 gc = f->output_data.x->black_relief.gc;
2710 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
2712 /* This code is more complicated than it has to be, because of two
2713 minor hacks to make the boxes look nicer: (i) if width > 1, draw
2714 the outermost line using the black relief. (ii) Omit the four
2715 corner pixels. */
2717 /* Top. */
2718 if (top_p)
2720 if (width == 1)
2721 XDrawLine (dpy, window, gc,
2722 left_x + left_p, top_y,
2723 right_x + !right_p, top_y);
2725 for (i = 1; i < width; ++i)
2726 XDrawLine (dpy, window, gc,
2727 left_x + i * left_p, top_y + i,
2728 right_x + 1 - i * right_p, top_y + i);
2731 /* Left. */
2732 if (left_p)
2734 if (width == 1)
2735 XDrawLine (dpy, window, gc, left_x, top_y + 1, left_x, bottom_y);
2737 XClearArea (dpy, window, left_x, top_y, 1, 1, False);
2738 XClearArea (dpy, window, left_x, bottom_y, 1, 1, False);
2740 for (i = (width > 1 ? 1 : 0); i < width; ++i)
2741 XDrawLine (dpy, window, gc,
2742 left_x + i, top_y + (i + 1) * top_p,
2743 left_x + i, bottom_y + 1 - (i + 1) * bot_p);
2746 XSetClipMask (dpy, gc, None);
2747 if (raised_p)
2748 gc = f->output_data.x->black_relief.gc;
2749 else
2750 gc = f->output_data.x->white_relief.gc;
2751 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
2753 if (width > 1)
2755 /* Outermost top line. */
2756 if (top_p)
2757 XDrawLine (dpy, window, gc,
2758 left_x + left_p, top_y,
2759 right_x + !right_p, top_y);
2761 /* Outermost left line. */
2762 if (left_p)
2763 XDrawLine (dpy, window, gc, left_x, top_y + 1, left_x, bottom_y);
2766 /* Bottom. */
2767 if (bot_p)
2769 XDrawLine (dpy, window, gc,
2770 left_x + left_p, bottom_y,
2771 right_x + !right_p, bottom_y);
2772 for (i = 1; i < width; ++i)
2773 XDrawLine (dpy, window, gc,
2774 left_x + i * left_p, bottom_y - i,
2775 right_x + 1 - i * right_p, bottom_y - i);
2778 /* Right. */
2779 if (right_p)
2781 XClearArea (dpy, window, right_x, top_y, 1, 1, False);
2782 XClearArea (dpy, window, right_x, bottom_y, 1, 1, False);
2783 for (i = 0; i < width; ++i)
2784 XDrawLine (dpy, window, gc,
2785 right_x - i, top_y + (i + 1) * top_p,
2786 right_x - i, bottom_y + 1 - (i + 1) * bot_p);
2789 x_reset_clip_rectangles (f, gc);
2791 #endif
2795 /* Draw a box on frame F inside the rectangle given by LEFT_X, TOP_Y,
2796 RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the lines to
2797 draw, it must be >= 0. LEFT_P means draw a line on the
2798 left side of the rectangle. RIGHT_P means draw a line
2799 on the right side of the rectangle. CLIP_RECT is the clipping
2800 rectangle to use when drawing. */
2802 static void
2803 x_draw_box_rect (struct glyph_string *s,
2804 int left_x, int top_y, int right_x, int bottom_y, int width,
2805 bool left_p, bool right_p, XRectangle *clip_rect)
2807 XGCValues xgcv;
2809 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2810 XSetForeground (s->display, s->gc, s->face->box_color);
2811 x_set_clip_rectangles (s->f, s->gc, clip_rect, 1);
2813 /* Top. */
2814 x_fill_rectangle (s->f, s->gc,
2815 left_x, top_y, right_x - left_x + 1, width);
2817 /* Left. */
2818 if (left_p)
2819 x_fill_rectangle (s->f, s->gc,
2820 left_x, top_y, width, bottom_y - top_y + 1);
2822 /* Bottom. */
2823 x_fill_rectangle (s->f, s->gc,
2824 left_x, bottom_y - width + 1, right_x - left_x + 1, width);
2826 /* Right. */
2827 if (right_p)
2828 x_fill_rectangle (s->f, s->gc,
2829 right_x - width + 1, top_y, width, bottom_y - top_y + 1);
2831 XSetForeground (s->display, s->gc, xgcv.foreground);
2832 x_reset_clip_rectangles (s->f, s->gc);
2836 /* Draw a box around glyph string S. */
2838 static void
2839 x_draw_glyph_string_box (struct glyph_string *s)
2841 int width, left_x, right_x, top_y, bottom_y, last_x;
2842 bool raised_p, left_p, right_p;
2843 struct glyph *last_glyph;
2844 XRectangle clip_rect;
2846 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2847 ? WINDOW_RIGHT_EDGE_X (s->w)
2848 : window_box_right (s->w, s->area));
2850 /* The glyph that may have a right box line. */
2851 last_glyph = (s->cmp || s->img
2852 ? s->first_glyph
2853 : s->first_glyph + s->nchars - 1);
2855 width = eabs (s->face->box_line_width);
2856 raised_p = s->face->box == FACE_RAISED_BOX;
2857 left_x = s->x;
2858 right_x = (s->row->full_width_p && s->extends_to_end_of_line_p
2859 ? last_x - 1
2860 : min (last_x, s->x + s->background_width) - 1);
2861 top_y = s->y;
2862 bottom_y = top_y + s->height - 1;
2864 left_p = (s->first_glyph->left_box_line_p
2865 || (s->hl == DRAW_MOUSE_FACE
2866 && (s->prev == NULL
2867 || s->prev->hl != s->hl)));
2868 right_p = (last_glyph->right_box_line_p
2869 || (s->hl == DRAW_MOUSE_FACE
2870 && (s->next == NULL
2871 || s->next->hl != s->hl)));
2873 get_glyph_string_clip_rect (s, &clip_rect);
2875 if (s->face->box == FACE_SIMPLE_BOX)
2876 x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
2877 left_p, right_p, &clip_rect);
2878 else
2880 x_setup_relief_colors (s);
2881 x_draw_relief_rect (s->f, left_x, top_y, right_x, bottom_y,
2882 width, raised_p, true, true, left_p, right_p,
2883 &clip_rect);
2888 /* Draw foreground of image glyph string S. */
2890 static void
2891 x_draw_image_foreground (struct glyph_string *s)
2893 int x = s->x;
2894 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2896 /* If first glyph of S has a left box line, start drawing it to the
2897 right of that line. */
2898 if (s->face->box != FACE_NO_BOX
2899 && s->first_glyph->left_box_line_p
2900 && s->slice.x == 0)
2901 x += eabs (s->face->box_line_width);
2903 /* If there is a margin around the image, adjust x- and y-position
2904 by that margin. */
2905 if (s->slice.x == 0)
2906 x += s->img->hmargin;
2907 if (s->slice.y == 0)
2908 y += s->img->vmargin;
2910 if (s->img->pixmap)
2912 if (s->img->mask)
2914 /* We can't set both a clip mask and use XSetClipRectangles
2915 because the latter also sets a clip mask. We also can't
2916 trust on the shape extension to be available
2917 (XShapeCombineRegion). So, compute the rectangle to draw
2918 manually. */
2919 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
2920 | GCFunction);
2921 XGCValues xgcv;
2922 XRectangle clip_rect, image_rect, r;
2924 xgcv.clip_mask = s->img->mask;
2925 xgcv.clip_x_origin = x;
2926 xgcv.clip_y_origin = y;
2927 xgcv.function = GXcopy;
2928 XChangeGC (s->display, s->gc, mask, &xgcv);
2930 get_glyph_string_clip_rect (s, &clip_rect);
2931 image_rect.x = x;
2932 image_rect.y = y;
2933 image_rect.width = s->slice.width;
2934 image_rect.height = s->slice.height;
2935 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
2936 XCopyArea (s->display, s->img->pixmap, s->window, s->gc,
2937 s->slice.x + r.x - x, s->slice.y + r.y - y,
2938 r.width, r.height, r.x, r.y);
2940 else
2942 XRectangle clip_rect, image_rect, r;
2944 get_glyph_string_clip_rect (s, &clip_rect);
2945 image_rect.x = x;
2946 image_rect.y = y;
2947 image_rect.width = s->slice.width;
2948 image_rect.height = s->slice.height;
2949 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
2950 XCopyArea (s->display, s->img->pixmap, s->window, s->gc,
2951 s->slice.x + r.x - x, s->slice.y + r.y - y,
2952 r.width, r.height, r.x, r.y);
2954 /* When the image has a mask, we can expect that at
2955 least part of a mouse highlight or a block cursor will
2956 be visible. If the image doesn't have a mask, make
2957 a block cursor visible by drawing a rectangle around
2958 the image. I believe it's looking better if we do
2959 nothing here for mouse-face. */
2960 if (s->hl == DRAW_CURSOR)
2962 int relief = eabs (s->img->relief);
2963 x_draw_rectangle (s->f, s->gc,
2964 x - relief, y - relief,
2965 s->slice.width + relief*2 - 1,
2966 s->slice.height + relief*2 - 1);
2970 else
2971 /* Draw a rectangle if image could not be loaded. */
2972 x_draw_rectangle (s->f, s->gc, x, y,
2973 s->slice.width - 1, s->slice.height - 1);
2977 /* Draw a relief around the image glyph string S. */
2979 static void
2980 x_draw_image_relief (struct glyph_string *s)
2982 int x1, y1, thick;
2983 bool raised_p, top_p, bot_p, left_p, right_p;
2984 int extra_x, extra_y;
2985 XRectangle r;
2986 int x = s->x;
2987 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2989 /* If first glyph of S has a left box line, start drawing it to the
2990 right of that line. */
2991 if (s->face->box != FACE_NO_BOX
2992 && s->first_glyph->left_box_line_p
2993 && s->slice.x == 0)
2994 x += eabs (s->face->box_line_width);
2996 /* If there is a margin around the image, adjust x- and y-position
2997 by that margin. */
2998 if (s->slice.x == 0)
2999 x += s->img->hmargin;
3000 if (s->slice.y == 0)
3001 y += s->img->vmargin;
3003 if (s->hl == DRAW_IMAGE_SUNKEN
3004 || s->hl == DRAW_IMAGE_RAISED)
3006 thick = tool_bar_button_relief >= 0 ? tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3007 raised_p = s->hl == DRAW_IMAGE_RAISED;
3009 else
3011 thick = eabs (s->img->relief);
3012 raised_p = s->img->relief > 0;
3015 x1 = x + s->slice.width - 1;
3016 y1 = y + s->slice.height - 1;
3018 extra_x = extra_y = 0;
3019 if (s->face->id == TOOL_BAR_FACE_ID)
3021 if (CONSP (Vtool_bar_button_margin)
3022 && INTEGERP (XCAR (Vtool_bar_button_margin))
3023 && INTEGERP (XCDR (Vtool_bar_button_margin)))
3025 extra_x = XINT (XCAR (Vtool_bar_button_margin));
3026 extra_y = XINT (XCDR (Vtool_bar_button_margin));
3028 else if (INTEGERP (Vtool_bar_button_margin))
3029 extra_x = extra_y = XINT (Vtool_bar_button_margin);
3032 top_p = bot_p = left_p = right_p = false;
3034 if (s->slice.x == 0)
3035 x -= thick + extra_x, left_p = true;
3036 if (s->slice.y == 0)
3037 y -= thick + extra_y, top_p = true;
3038 if (s->slice.x + s->slice.width == s->img->width)
3039 x1 += thick + extra_x, right_p = true;
3040 if (s->slice.y + s->slice.height == s->img->height)
3041 y1 += thick + extra_y, bot_p = true;
3043 x_setup_relief_colors (s);
3044 get_glyph_string_clip_rect (s, &r);
3045 x_draw_relief_rect (s->f, x, y, x1, y1, thick, raised_p,
3046 top_p, bot_p, left_p, right_p, &r);
3050 /* Draw the foreground of image glyph string S to PIXMAP. */
3052 static void
3053 x_draw_image_foreground_1 (struct glyph_string *s, Pixmap pixmap)
3055 int x = 0;
3056 int y = s->ybase - s->y - image_ascent (s->img, s->face, &s->slice);
3058 /* If first glyph of S has a left box line, start drawing it to the
3059 right of that line. */
3060 if (s->face->box != FACE_NO_BOX
3061 && s->first_glyph->left_box_line_p
3062 && s->slice.x == 0)
3063 x += eabs (s->face->box_line_width);
3065 /* If there is a margin around the image, adjust x- and y-position
3066 by that margin. */
3067 if (s->slice.x == 0)
3068 x += s->img->hmargin;
3069 if (s->slice.y == 0)
3070 y += s->img->vmargin;
3072 if (s->img->pixmap)
3074 if (s->img->mask)
3076 /* We can't set both a clip mask and use XSetClipRectangles
3077 because the latter also sets a clip mask. We also can't
3078 trust on the shape extension to be available
3079 (XShapeCombineRegion). So, compute the rectangle to draw
3080 manually. */
3081 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
3082 | GCFunction);
3083 XGCValues xgcv;
3085 xgcv.clip_mask = s->img->mask;
3086 xgcv.clip_x_origin = x - s->slice.x;
3087 xgcv.clip_y_origin = y - s->slice.y;
3088 xgcv.function = GXcopy;
3089 XChangeGC (s->display, s->gc, mask, &xgcv);
3091 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
3092 s->slice.x, s->slice.y,
3093 s->slice.width, s->slice.height, x, y);
3094 XSetClipMask (s->display, s->gc, None);
3096 else
3098 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
3099 s->slice.x, s->slice.y,
3100 s->slice.width, s->slice.height, x, y);
3102 /* When the image has a mask, we can expect that at
3103 least part of a mouse highlight or a block cursor will
3104 be visible. If the image doesn't have a mask, make
3105 a block cursor visible by drawing a rectangle around
3106 the image. I believe it's looking better if we do
3107 nothing here for mouse-face. */
3108 if (s->hl == DRAW_CURSOR)
3110 int r = eabs (s->img->relief);
3111 x_draw_rectangle (s->f, s->gc, x - r, y - r,
3112 s->slice.width + r*2 - 1,
3113 s->slice.height + r*2 - 1);
3117 else
3118 /* Draw a rectangle if image could not be loaded. */
3119 x_draw_rectangle (s->f, s->gc, x, y,
3120 s->slice.width - 1, s->slice.height - 1);
3124 /* Draw part of the background of glyph string S. X, Y, W, and H
3125 give the rectangle to draw. */
3127 static void
3128 x_draw_glyph_string_bg_rect (struct glyph_string *s, int x, int y, int w, int h)
3130 if (s->stippled_p)
3132 /* Fill background with a stipple pattern. */
3133 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
3134 x_fill_rectangle (s->f, s->gc, x, y, w, h);
3135 XSetFillStyle (s->display, s->gc, FillSolid);
3137 else
3138 x_clear_glyph_string_rect (s, x, y, w, h);
3142 /* Draw image glyph string S.
3144 s->y
3145 s->x +-------------------------
3146 | s->face->box
3148 | +-------------------------
3149 | | s->img->margin
3151 | | +-------------------
3152 | | | the image
3156 static void
3157 x_draw_image_glyph_string (struct glyph_string *s)
3159 int box_line_hwidth = eabs (s->face->box_line_width);
3160 int box_line_vwidth = max (s->face->box_line_width, 0);
3161 int height;
3162 Pixmap pixmap = None;
3164 height = s->height;
3165 if (s->slice.y == 0)
3166 height -= box_line_vwidth;
3167 if (s->slice.y + s->slice.height >= s->img->height)
3168 height -= box_line_vwidth;
3170 /* Fill background with face under the image. Do it only if row is
3171 taller than image or if image has a clip mask to reduce
3172 flickering. */
3173 s->stippled_p = s->face->stipple != 0;
3174 if (height > s->slice.height
3175 || s->img->hmargin
3176 || s->img->vmargin
3177 || s->img->mask
3178 || s->img->pixmap == 0
3179 || s->width != s->background_width)
3181 if (s->img->mask)
3183 /* Create a pixmap as large as the glyph string. Fill it
3184 with the background color. Copy the image to it, using
3185 its mask. Copy the temporary pixmap to the display. */
3186 Screen *screen = FRAME_X_SCREEN (s->f);
3187 int depth = DefaultDepthOfScreen (screen);
3189 /* Create a pixmap as large as the glyph string. */
3190 pixmap = XCreatePixmap (s->display, s->window,
3191 s->background_width,
3192 s->height, depth);
3194 /* Don't clip in the following because we're working on the
3195 pixmap. */
3196 XSetClipMask (s->display, s->gc, None);
3198 /* Fill the pixmap with the background color/stipple. */
3199 if (s->stippled_p)
3201 /* Fill background with a stipple pattern. */
3202 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
3203 XSetTSOrigin (s->display, s->gc, - s->x, - s->y);
3204 XFillRectangle (s->display, pixmap, s->gc,
3205 0, 0, s->background_width, s->height);
3206 XSetFillStyle (s->display, s->gc, FillSolid);
3207 XSetTSOrigin (s->display, s->gc, 0, 0);
3209 else
3211 XGCValues xgcv;
3212 XGetGCValues (s->display, s->gc, GCForeground | GCBackground,
3213 &xgcv);
3214 XSetForeground (s->display, s->gc, xgcv.background);
3215 XFillRectangle (s->display, pixmap, s->gc,
3216 0, 0, s->background_width, s->height);
3217 XSetForeground (s->display, s->gc, xgcv.foreground);
3220 else
3222 int x = s->x;
3223 int y = s->y;
3224 int width = s->background_width;
3226 if (s->first_glyph->left_box_line_p
3227 && s->slice.x == 0)
3229 x += box_line_hwidth;
3230 width -= box_line_hwidth;
3233 if (s->slice.y == 0)
3234 y += box_line_vwidth;
3236 x_draw_glyph_string_bg_rect (s, x, y, width, height);
3239 s->background_filled_p = true;
3242 /* Draw the foreground. */
3243 #ifdef USE_CAIRO
3244 if (s->img->cr_data)
3246 cairo_t *cr = x_begin_cr_clip (s->f, s->gc);
3248 int x = s->x + s->img->hmargin;
3249 int y = s->y + s->img->vmargin;
3250 int width = s->background_width;
3252 cairo_set_source_surface (cr, s->img->cr_data,
3253 x - s->slice.x,
3254 y - s->slice.y);
3255 cairo_rectangle (cr, x, y, width, height);
3256 cairo_fill (cr);
3257 x_end_cr_clip (s->f);
3259 else
3260 #endif
3261 if (pixmap != None)
3263 x_draw_image_foreground_1 (s, pixmap);
3264 x_set_glyph_string_clipping (s);
3265 XCopyArea (s->display, pixmap, s->window, s->gc,
3266 0, 0, s->background_width, s->height, s->x, s->y);
3267 XFreePixmap (s->display, pixmap);
3269 else
3270 x_draw_image_foreground (s);
3272 /* If we must draw a relief around the image, do it. */
3273 if (s->img->relief
3274 || s->hl == DRAW_IMAGE_RAISED
3275 || s->hl == DRAW_IMAGE_SUNKEN)
3276 x_draw_image_relief (s);
3280 /* Draw stretch glyph string S. */
3282 static void
3283 x_draw_stretch_glyph_string (struct glyph_string *s)
3285 eassert (s->first_glyph->type == STRETCH_GLYPH);
3287 if (s->hl == DRAW_CURSOR
3288 && !x_stretch_cursor_p)
3290 /* If `x-stretch-cursor' is nil, don't draw a block cursor as
3291 wide as the stretch glyph. */
3292 int width, background_width = s->background_width;
3293 int x = s->x;
3295 if (!s->row->reversed_p)
3297 int left_x = window_box_left_offset (s->w, TEXT_AREA);
3299 if (x < left_x)
3301 background_width -= left_x - x;
3302 x = left_x;
3305 else
3307 /* In R2L rows, draw the cursor on the right edge of the
3308 stretch glyph. */
3309 int right_x = window_box_right (s->w, TEXT_AREA);
3311 if (x + background_width > right_x)
3312 background_width -= x - right_x;
3313 x += background_width;
3315 width = min (FRAME_COLUMN_WIDTH (s->f), background_width);
3316 if (s->row->reversed_p)
3317 x -= width;
3319 /* Draw cursor. */
3320 x_draw_glyph_string_bg_rect (s, x, s->y, width, s->height);
3322 /* Clear rest using the GC of the original non-cursor face. */
3323 if (width < background_width)
3325 int y = s->y;
3326 int w = background_width - width, h = s->height;
3327 XRectangle r;
3328 GC gc;
3330 if (!s->row->reversed_p)
3331 x += width;
3332 else
3333 x = s->x;
3334 if (s->row->mouse_face_p
3335 && cursor_in_mouse_face_p (s->w))
3337 x_set_mouse_face_gc (s);
3338 gc = s->gc;
3340 else
3341 gc = s->face->gc;
3343 get_glyph_string_clip_rect (s, &r);
3344 x_set_clip_rectangles (s->f, gc, &r, 1);
3346 if (s->face->stipple)
3348 /* Fill background with a stipple pattern. */
3349 XSetFillStyle (s->display, gc, FillOpaqueStippled);
3350 x_fill_rectangle (s->f, gc, x, y, w, h);
3351 XSetFillStyle (s->display, gc, FillSolid);
3353 else
3355 XGCValues xgcv;
3356 XGetGCValues (s->display, gc, GCForeground | GCBackground, &xgcv);
3357 XSetForeground (s->display, gc, xgcv.background);
3358 x_fill_rectangle (s->f, gc, x, y, w, h);
3359 XSetForeground (s->display, gc, xgcv.foreground);
3362 x_reset_clip_rectangles (s->f, gc);
3365 else if (!s->background_filled_p)
3367 int background_width = s->background_width;
3368 int x = s->x, left_x = window_box_left_offset (s->w, TEXT_AREA);
3370 /* Don't draw into left margin, fringe or scrollbar area
3371 except for header line and mode line. */
3372 if (x < left_x && !s->row->mode_line_p)
3374 background_width -= left_x - x;
3375 x = left_x;
3377 if (background_width > 0)
3378 x_draw_glyph_string_bg_rect (s, x, s->y, background_width, s->height);
3381 s->background_filled_p = true;
3385 Draw a wavy line under S. The wave fills wave_height pixels from y0.
3387 x0 wave_length = 2
3389 y0 * * * * *
3390 |* * * * * * * * *
3391 wave_height = 3 | * * * *
3395 static void
3396 x_draw_underwave (struct glyph_string *s)
3398 int wave_height = 3, wave_length = 2;
3399 #ifdef USE_CAIRO
3400 x_draw_horizontal_wave (s->f, s->gc, s->x, s->ybase - wave_height + 3,
3401 s->width, wave_height, wave_length);
3402 #else /* not USE_CAIRO */
3403 int dx, dy, x0, y0, width, x1, y1, x2, y2, xmax;
3404 bool odd;
3405 XRectangle wave_clip, string_clip, final_clip;
3407 dx = wave_length;
3408 dy = wave_height - 1;
3409 x0 = s->x;
3410 y0 = s->ybase - wave_height + 3;
3411 width = s->width;
3412 xmax = x0 + width;
3414 /* Find and set clipping rectangle */
3416 wave_clip.x = x0;
3417 wave_clip.y = y0;
3418 wave_clip.width = width;
3419 wave_clip.height = wave_height;
3420 get_glyph_string_clip_rect (s, &string_clip);
3422 if (!x_intersect_rectangles (&wave_clip, &string_clip, &final_clip))
3423 return;
3425 XSetClipRectangles (s->display, s->gc, 0, 0, &final_clip, 1, Unsorted);
3427 /* Draw the waves */
3429 x1 = x0 - (x0 % dx);
3430 x2 = x1 + dx;
3431 odd = (x1 / dx) & 1;
3432 y1 = y2 = y0;
3434 if (odd)
3435 y1 += dy;
3436 else
3437 y2 += dy;
3439 if (INT_MAX - dx < xmax)
3440 emacs_abort ();
3442 while (x1 <= xmax)
3444 XDrawLine (s->display, s->window, s->gc, x1, y1, x2, y2);
3445 x1 = x2, y1 = y2;
3446 x2 += dx, y2 = y0 + odd*dy;
3447 odd = !odd;
3450 /* Restore previous clipping rectangle(s) */
3451 XSetClipRectangles (s->display, s->gc, 0, 0, s->clip, s->num_clips, Unsorted);
3452 #endif /* not USE_CAIRO */
3456 /* Draw glyph string S. */
3458 static void
3459 x_draw_glyph_string (struct glyph_string *s)
3461 bool relief_drawn_p = false;
3463 /* If S draws into the background of its successors, draw the
3464 background of the successors first so that S can draw into it.
3465 This makes S->next use XDrawString instead of XDrawImageString. */
3466 if (s->next && s->right_overhang && !s->for_overlaps)
3468 int width;
3469 struct glyph_string *next;
3471 for (width = 0, next = s->next;
3472 next && width < s->right_overhang;
3473 width += next->width, next = next->next)
3474 if (next->first_glyph->type != IMAGE_GLYPH)
3476 x_set_glyph_string_gc (next);
3477 x_set_glyph_string_clipping (next);
3478 if (next->first_glyph->type == STRETCH_GLYPH)
3479 x_draw_stretch_glyph_string (next);
3480 else
3481 x_draw_glyph_string_background (next, true);
3482 next->num_clips = 0;
3486 /* Set up S->gc, set clipping and draw S. */
3487 x_set_glyph_string_gc (s);
3489 /* Draw relief (if any) in advance for char/composition so that the
3490 glyph string can be drawn over it. */
3491 if (!s->for_overlaps
3492 && s->face->box != FACE_NO_BOX
3493 && (s->first_glyph->type == CHAR_GLYPH
3494 || s->first_glyph->type == COMPOSITE_GLYPH))
3497 x_set_glyph_string_clipping (s);
3498 x_draw_glyph_string_background (s, true);
3499 x_draw_glyph_string_box (s);
3500 x_set_glyph_string_clipping (s);
3501 relief_drawn_p = true;
3503 else if (!s->clip_head /* draw_glyphs didn't specify a clip mask. */
3504 && !s->clip_tail
3505 && ((s->prev && s->prev->hl != s->hl && s->left_overhang)
3506 || (s->next && s->next->hl != s->hl && s->right_overhang)))
3507 /* We must clip just this glyph. left_overhang part has already
3508 drawn when s->prev was drawn, and right_overhang part will be
3509 drawn later when s->next is drawn. */
3510 x_set_glyph_string_clipping_exactly (s, s);
3511 else
3512 x_set_glyph_string_clipping (s);
3514 switch (s->first_glyph->type)
3516 case IMAGE_GLYPH:
3517 x_draw_image_glyph_string (s);
3518 break;
3520 case XWIDGET_GLYPH:
3521 x_draw_xwidget_glyph_string (s);
3522 break;
3524 case STRETCH_GLYPH:
3525 x_draw_stretch_glyph_string (s);
3526 break;
3528 case CHAR_GLYPH:
3529 if (s->for_overlaps)
3530 s->background_filled_p = true;
3531 else
3532 x_draw_glyph_string_background (s, false);
3533 x_draw_glyph_string_foreground (s);
3534 break;
3536 case COMPOSITE_GLYPH:
3537 if (s->for_overlaps || (s->cmp_from > 0
3538 && ! s->first_glyph->u.cmp.automatic))
3539 s->background_filled_p = true;
3540 else
3541 x_draw_glyph_string_background (s, true);
3542 x_draw_composite_glyph_string_foreground (s);
3543 break;
3545 case GLYPHLESS_GLYPH:
3546 if (s->for_overlaps)
3547 s->background_filled_p = true;
3548 else
3549 x_draw_glyph_string_background (s, true);
3550 x_draw_glyphless_glyph_string_foreground (s);
3551 break;
3553 default:
3554 emacs_abort ();
3557 if (!s->for_overlaps)
3559 /* Draw underline. */
3560 if (s->face->underline_p)
3562 if (s->face->underline_type == FACE_UNDER_WAVE)
3564 if (s->face->underline_defaulted_p)
3565 x_draw_underwave (s);
3566 else
3568 XGCValues xgcv;
3569 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3570 XSetForeground (s->display, s->gc, s->face->underline_color);
3571 x_draw_underwave (s);
3572 XSetForeground (s->display, s->gc, xgcv.foreground);
3575 else if (s->face->underline_type == FACE_UNDER_LINE)
3577 unsigned long thickness, position;
3578 int y;
3580 if (s->prev && s->prev->face->underline_p
3581 && s->prev->face->underline_type == FACE_UNDER_LINE)
3583 /* We use the same underline style as the previous one. */
3584 thickness = s->prev->underline_thickness;
3585 position = s->prev->underline_position;
3587 else
3589 /* Get the underline thickness. Default is 1 pixel. */
3590 if (s->font && s->font->underline_thickness > 0)
3591 thickness = s->font->underline_thickness;
3592 else
3593 thickness = 1;
3594 if (x_underline_at_descent_line)
3595 position = (s->height - thickness) - (s->ybase - s->y);
3596 else
3598 /* Get the underline position. This is the recommended
3599 vertical offset in pixels from the baseline to the top of
3600 the underline. This is a signed value according to the
3601 specs, and its default is
3603 ROUND ((maximum descent) / 2), with
3604 ROUND(x) = floor (x + 0.5) */
3606 if (x_use_underline_position_properties
3607 && s->font && s->font->underline_position >= 0)
3608 position = s->font->underline_position;
3609 else if (s->font)
3610 position = (s->font->descent + 1) / 2;
3611 else
3612 position = underline_minimum_offset;
3614 position = max (position, underline_minimum_offset);
3616 /* Check the sanity of thickness and position. We should
3617 avoid drawing underline out of the current line area. */
3618 if (s->y + s->height <= s->ybase + position)
3619 position = (s->height - 1) - (s->ybase - s->y);
3620 if (s->y + s->height < s->ybase + position + thickness)
3621 thickness = (s->y + s->height) - (s->ybase + position);
3622 s->underline_thickness = thickness;
3623 s->underline_position = position;
3624 y = s->ybase + position;
3625 if (s->face->underline_defaulted_p)
3626 x_fill_rectangle (s->f, s->gc,
3627 s->x, y, s->width, thickness);
3628 else
3630 XGCValues xgcv;
3631 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3632 XSetForeground (s->display, s->gc, s->face->underline_color);
3633 x_fill_rectangle (s->f, s->gc,
3634 s->x, y, s->width, thickness);
3635 XSetForeground (s->display, s->gc, xgcv.foreground);
3639 /* Draw overline. */
3640 if (s->face->overline_p)
3642 unsigned long dy = 0, h = 1;
3644 if (s->face->overline_color_defaulted_p)
3645 x_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3646 s->width, h);
3647 else
3649 XGCValues xgcv;
3650 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3651 XSetForeground (s->display, s->gc, s->face->overline_color);
3652 x_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3653 s->width, h);
3654 XSetForeground (s->display, s->gc, xgcv.foreground);
3658 /* Draw strike-through. */
3659 if (s->face->strike_through_p)
3661 unsigned long h = 1;
3662 unsigned long dy = (s->height - h) / 2;
3664 if (s->face->strike_through_color_defaulted_p)
3665 x_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3666 s->width, h);
3667 else
3669 XGCValues xgcv;
3670 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3671 XSetForeground (s->display, s->gc, s->face->strike_through_color);
3672 x_fill_rectangle (s->f, s->gc, s->x, s->y + dy,
3673 s->width, h);
3674 XSetForeground (s->display, s->gc, xgcv.foreground);
3678 /* Draw relief if not yet drawn. */
3679 if (!relief_drawn_p && s->face->box != FACE_NO_BOX)
3680 x_draw_glyph_string_box (s);
3682 if (s->prev)
3684 struct glyph_string *prev;
3686 for (prev = s->prev; prev; prev = prev->prev)
3687 if (prev->hl != s->hl
3688 && prev->x + prev->width + prev->right_overhang > s->x)
3690 /* As prev was drawn while clipped to its own area, we
3691 must draw the right_overhang part using s->hl now. */
3692 enum draw_glyphs_face save = prev->hl;
3694 prev->hl = s->hl;
3695 x_set_glyph_string_gc (prev);
3696 x_set_glyph_string_clipping_exactly (s, prev);
3697 if (prev->first_glyph->type == CHAR_GLYPH)
3698 x_draw_glyph_string_foreground (prev);
3699 else
3700 x_draw_composite_glyph_string_foreground (prev);
3701 x_reset_clip_rectangles (prev->f, prev->gc);
3702 prev->hl = save;
3703 prev->num_clips = 0;
3707 if (s->next)
3709 struct glyph_string *next;
3711 for (next = s->next; next; next = next->next)
3712 if (next->hl != s->hl
3713 && next->x - next->left_overhang < s->x + s->width)
3715 /* As next will be drawn while clipped to its own area,
3716 we must draw the left_overhang part using s->hl now. */
3717 enum draw_glyphs_face save = next->hl;
3719 next->hl = s->hl;
3720 x_set_glyph_string_gc (next);
3721 x_set_glyph_string_clipping_exactly (s, next);
3722 if (next->first_glyph->type == CHAR_GLYPH)
3723 x_draw_glyph_string_foreground (next);
3724 else
3725 x_draw_composite_glyph_string_foreground (next);
3726 x_reset_clip_rectangles (next->f, next->gc);
3727 next->hl = save;
3728 next->num_clips = 0;
3729 next->clip_head = s->next;
3734 /* Reset clipping. */
3735 x_reset_clip_rectangles (s->f, s->gc);
3736 s->num_clips = 0;
3739 /* Shift display to make room for inserted glyphs. */
3741 static void
3742 x_shift_glyphs_for_insert (struct frame *f, int x, int y, int width, int height, int shift_by)
3744 /* Never called on a GUI frame, see
3745 http://lists.gnu.org/archive/html/emacs-devel/2015-05/msg00456.html
3747 XCopyArea (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), FRAME_X_WINDOW (f),
3748 f->output_data.x->normal_gc,
3749 x, y, width, height,
3750 x + shift_by, y);
3753 /* Delete N glyphs at the nominal cursor position. Not implemented
3754 for X frames. */
3756 static void
3757 x_delete_glyphs (struct frame *f, register int n)
3759 emacs_abort ();
3763 /* Like XClearArea, but check that WIDTH and HEIGHT are reasonable.
3764 If they are <= 0, this is probably an error. */
3766 static ATTRIBUTE_UNUSED void
3767 x_clear_area1 (Display *dpy, Window window,
3768 int x, int y, int width, int height, int exposures)
3770 eassert (width > 0 && height > 0);
3771 XClearArea (dpy, window, x, y, width, height, exposures);
3774 void
3775 x_clear_area (struct frame *f, int x, int y, int width, int height)
3777 #ifdef USE_CAIRO
3778 cairo_t *cr;
3780 eassert (width > 0 && height > 0);
3782 cr = x_begin_cr_clip (f, NULL);
3783 x_set_cr_source_with_gc_background (f, f->output_data.x->normal_gc);
3784 cairo_rectangle (cr, x, y, width, height);
3785 cairo_fill (cr);
3786 x_end_cr_clip (f);
3787 #else
3788 x_clear_area1 (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3789 x, y, width, height, False);
3790 #endif
3794 /* Clear an entire frame. */
3796 static void
3797 x_clear_frame (struct frame *f)
3799 /* Clearing the frame will erase any cursor, so mark them all as no
3800 longer visible. */
3801 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
3803 block_input ();
3805 x_clear_window (f);
3807 /* We have to clear the scroll bars. If we have changed colors or
3808 something like that, then they should be notified. */
3809 x_scroll_bar_clear (f);
3811 #if defined (USE_GTK) && defined (USE_TOOLKIT_SCROLL_BARS)
3812 /* Make sure scroll bars are redrawn. As they aren't redrawn by
3813 redisplay, do it here. */
3814 if (FRAME_GTK_WIDGET (f))
3815 gtk_widget_queue_draw (FRAME_GTK_WIDGET (f));
3816 #endif
3818 XFlush (FRAME_X_DISPLAY (f));
3820 unblock_input ();
3823 /* RIF: Show hourglass cursor on frame F. */
3825 static void
3826 x_show_hourglass (struct frame *f)
3828 Display *dpy = FRAME_X_DISPLAY (f);
3830 if (dpy)
3832 struct x_output *x = FRAME_X_OUTPUT (f);
3833 #ifdef USE_X_TOOLKIT
3834 if (x->widget)
3835 #else
3836 if (FRAME_OUTER_WINDOW (f))
3837 #endif
3839 x->hourglass_p = true;
3841 if (!x->hourglass_window)
3843 unsigned long mask = CWCursor;
3844 XSetWindowAttributes attrs;
3845 #ifdef USE_GTK
3846 Window parent = FRAME_X_WINDOW (f);
3847 #else
3848 Window parent = FRAME_OUTER_WINDOW (f);
3849 #endif
3850 attrs.cursor = x->hourglass_cursor;
3852 x->hourglass_window = XCreateWindow
3853 (dpy, parent, 0, 0, 32000, 32000, 0, 0,
3854 InputOnly, CopyFromParent, mask, &attrs);
3857 XMapRaised (dpy, x->hourglass_window);
3858 XFlush (dpy);
3863 /* RIF: Cancel hourglass cursor on frame F. */
3865 static void
3866 x_hide_hourglass (struct frame *f)
3868 struct x_output *x = FRAME_X_OUTPUT (f);
3870 /* Watch out for newly created frames. */
3871 if (x->hourglass_window)
3873 XUnmapWindow (FRAME_X_DISPLAY (f), x->hourglass_window);
3874 /* Sync here because XTread_socket looks at the
3875 hourglass_p flag that is reset to zero below. */
3876 XSync (FRAME_X_DISPLAY (f), False);
3877 x->hourglass_p = false;
3881 /* Invert the middle quarter of the frame for .15 sec. */
3883 static void
3884 XTflash (struct frame *f)
3886 block_input ();
3889 #ifdef USE_GTK
3890 /* Use Gdk routines to draw. This way, we won't draw over scroll bars
3891 when the scroll bars and the edit widget share the same X window. */
3892 GdkWindow *window = gtk_widget_get_window (FRAME_GTK_WIDGET (f));
3893 #ifdef HAVE_GTK3
3894 cairo_t *cr = gdk_cairo_create (window);
3895 cairo_set_source_rgb (cr, 1, 1, 1);
3896 cairo_set_operator (cr, CAIRO_OPERATOR_DIFFERENCE);
3897 #define XFillRectangle(d, win, gc, x, y, w, h) \
3898 do { \
3899 cairo_rectangle (cr, x, y, w, h); \
3900 cairo_fill (cr); \
3902 while (false)
3903 #else /* ! HAVE_GTK3 */
3904 GdkGCValues vals;
3905 GdkGC *gc;
3906 vals.foreground.pixel = (FRAME_FOREGROUND_PIXEL (f)
3907 ^ FRAME_BACKGROUND_PIXEL (f));
3908 vals.function = GDK_XOR;
3909 gc = gdk_gc_new_with_values (window,
3910 &vals, GDK_GC_FUNCTION | GDK_GC_FOREGROUND);
3911 #define XFillRectangle(d, win, gc, x, y, w, h) \
3912 gdk_draw_rectangle (window, gc, true, x, y, w, h)
3913 #endif /* ! HAVE_GTK3 */
3914 #else /* ! USE_GTK */
3915 GC gc;
3917 /* Create a GC that will use the GXxor function to flip foreground
3918 pixels into background pixels. */
3920 XGCValues values;
3922 values.function = GXxor;
3923 values.foreground = (FRAME_FOREGROUND_PIXEL (f)
3924 ^ FRAME_BACKGROUND_PIXEL (f));
3926 gc = XCreateGC (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3927 GCFunction | GCForeground, &values);
3929 #endif
3931 /* Get the height not including a menu bar widget. */
3932 int height = FRAME_PIXEL_HEIGHT (f);
3933 /* Height of each line to flash. */
3934 int flash_height = FRAME_LINE_HEIGHT (f);
3935 /* These will be the left and right margins of the rectangles. */
3936 int flash_left = FRAME_INTERNAL_BORDER_WIDTH (f);
3937 int flash_right = FRAME_PIXEL_WIDTH (f) - FRAME_INTERNAL_BORDER_WIDTH (f);
3938 int width = flash_right - flash_left;
3940 /* If window is tall, flash top and bottom line. */
3941 if (height > 3 * FRAME_LINE_HEIGHT (f))
3943 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3944 flash_left,
3945 (FRAME_INTERNAL_BORDER_WIDTH (f)
3946 + FRAME_TOP_MARGIN_HEIGHT (f)),
3947 width, flash_height);
3948 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3949 flash_left,
3950 (height - flash_height
3951 - FRAME_INTERNAL_BORDER_WIDTH (f)),
3952 width, flash_height);
3955 else
3956 /* If it is short, flash it all. */
3957 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3958 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
3959 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
3961 x_flush (f);
3964 struct timespec delay = make_timespec (0, 150 * 1000 * 1000);
3965 struct timespec wakeup = timespec_add (current_timespec (), delay);
3967 /* Keep waiting until past the time wakeup or any input gets
3968 available. */
3969 while (! detect_input_pending ())
3971 struct timespec current = current_timespec ();
3972 struct timespec timeout;
3974 /* Break if result would not be positive. */
3975 if (timespec_cmp (wakeup, current) <= 0)
3976 break;
3978 /* How long `select' should wait. */
3979 timeout = make_timespec (0, 10 * 1000 * 1000);
3981 /* Try to wait that long--but we might wake up sooner. */
3982 pselect (0, NULL, NULL, NULL, &timeout, NULL);
3986 /* If window is tall, flash top and bottom line. */
3987 if (height > 3 * FRAME_LINE_HEIGHT (f))
3989 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3990 flash_left,
3991 (FRAME_INTERNAL_BORDER_WIDTH (f)
3992 + FRAME_TOP_MARGIN_HEIGHT (f)),
3993 width, flash_height);
3994 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3995 flash_left,
3996 (height - flash_height
3997 - FRAME_INTERNAL_BORDER_WIDTH (f)),
3998 width, flash_height);
4000 else
4001 /* If it is short, flash it all. */
4002 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
4003 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
4004 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
4006 #ifdef USE_GTK
4007 #ifdef HAVE_GTK3
4008 cairo_destroy (cr);
4009 #else
4010 g_object_unref (G_OBJECT (gc));
4011 #endif
4012 #undef XFillRectangle
4013 #else
4014 XFreeGC (FRAME_X_DISPLAY (f), gc);
4015 #endif
4016 x_flush (f);
4020 unblock_input ();
4024 static void
4025 XTtoggle_invisible_pointer (struct frame *f, bool invisible)
4027 block_input ();
4028 FRAME_DISPLAY_INFO (f)->toggle_visible_pointer (f, invisible);
4029 unblock_input ();
4033 /* Make audible bell. */
4035 static void
4036 XTring_bell (struct frame *f)
4038 if (FRAME_X_DISPLAY (f))
4040 if (visible_bell)
4041 XTflash (f);
4042 else
4044 block_input ();
4045 #ifdef HAVE_XKB
4046 XkbBell (FRAME_X_DISPLAY (f), None, 0, None);
4047 #else
4048 XBell (FRAME_X_DISPLAY (f), 0);
4049 #endif
4050 XFlush (FRAME_X_DISPLAY (f));
4051 unblock_input ();
4056 /***********************************************************************
4057 Line Dance
4058 ***********************************************************************/
4060 /* Perform an insert-lines or delete-lines operation, inserting N
4061 lines or deleting -N lines at vertical position VPOS. */
4063 static void
4064 x_ins_del_lines (struct frame *f, int vpos, int n)
4066 emacs_abort ();
4070 /* Scroll part of the display as described by RUN. */
4072 static void
4073 x_scroll_run (struct window *w, struct run *run)
4075 struct frame *f = XFRAME (w->frame);
4076 int x, y, width, height, from_y, to_y, bottom_y;
4078 /* Get frame-relative bounding box of the text display area of W,
4079 without mode lines. Include in this box the left and right
4080 fringe of W. */
4081 window_box (w, ANY_AREA, &x, &y, &width, &height);
4083 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
4084 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
4085 bottom_y = y + height;
4087 if (to_y < from_y)
4089 /* Scrolling up. Make sure we don't copy part of the mode
4090 line at the bottom. */
4091 if (from_y + run->height > bottom_y)
4092 height = bottom_y - from_y;
4093 else
4094 height = run->height;
4096 else
4098 /* Scrolling down. Make sure we don't copy over the mode line.
4099 at the bottom. */
4100 if (to_y + run->height > bottom_y)
4101 height = bottom_y - to_y;
4102 else
4103 height = run->height;
4106 block_input ();
4108 /* Cursor off. Will be switched on again in x_update_window_end. */
4109 x_clear_cursor (w);
4111 #ifdef USE_CAIRO
4112 SET_FRAME_GARBAGED (f);
4113 #else
4114 XCopyArea (FRAME_X_DISPLAY (f),
4115 FRAME_X_WINDOW (f), FRAME_X_WINDOW (f),
4116 f->output_data.x->normal_gc,
4117 x, from_y,
4118 width, height,
4119 x, to_y);
4120 #endif
4122 unblock_input ();
4127 /***********************************************************************
4128 Exposure Events
4129 ***********************************************************************/
4132 static void
4133 frame_highlight (struct frame *f)
4135 /* We used to only do this if Vx_no_window_manager was non-nil, but
4136 the ICCCM (section 4.1.6) says that the window's border pixmap
4137 and border pixel are window attributes which are "private to the
4138 client", so we can always change it to whatever we want. */
4139 block_input ();
4140 /* I recently started to get errors in this XSetWindowBorder, depending on
4141 the window-manager in use, tho something more is at play since I've been
4142 using that same window-manager binary for ever. Let's not crash just
4143 because of this (bug#9310). */
4144 x_catch_errors (FRAME_X_DISPLAY (f));
4145 XSetWindowBorder (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4146 f->output_data.x->border_pixel);
4147 x_uncatch_errors ();
4148 unblock_input ();
4149 x_update_cursor (f, true);
4150 x_set_frame_alpha (f);
4153 static void
4154 frame_unhighlight (struct frame *f)
4156 /* We used to only do this if Vx_no_window_manager was non-nil, but
4157 the ICCCM (section 4.1.6) says that the window's border pixmap
4158 and border pixel are window attributes which are "private to the
4159 client", so we can always change it to whatever we want. */
4160 block_input ();
4161 /* Same as above for XSetWindowBorder (bug#9310). */
4162 x_catch_errors (FRAME_X_DISPLAY (f));
4163 XSetWindowBorderPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4164 f->output_data.x->border_tile);
4165 x_uncatch_errors ();
4166 unblock_input ();
4167 x_update_cursor (f, true);
4168 x_set_frame_alpha (f);
4171 /* The focus has changed. Update the frames as necessary to reflect
4172 the new situation. Note that we can't change the selected frame
4173 here, because the Lisp code we are interrupting might become confused.
4174 Each event gets marked with the frame in which it occurred, so the
4175 Lisp code can tell when the switch took place by examining the events. */
4177 static void
4178 x_new_focus_frame (struct x_display_info *dpyinfo, struct frame *frame)
4180 struct frame *old_focus = dpyinfo->x_focus_frame;
4182 if (frame != dpyinfo->x_focus_frame)
4184 /* Set this before calling other routines, so that they see
4185 the correct value of x_focus_frame. */
4186 dpyinfo->x_focus_frame = frame;
4188 if (old_focus && old_focus->auto_lower)
4189 x_lower_frame (old_focus);
4191 if (dpyinfo->x_focus_frame && dpyinfo->x_focus_frame->auto_raise)
4192 dpyinfo->x_pending_autoraise_frame = dpyinfo->x_focus_frame;
4193 else
4194 dpyinfo->x_pending_autoraise_frame = NULL;
4197 x_frame_rehighlight (dpyinfo);
4200 /* Handle FocusIn and FocusOut state changes for FRAME.
4201 If FRAME has focus and there exists more than one frame, puts
4202 a FOCUS_IN_EVENT into *BUFP. */
4204 static void
4205 x_focus_changed (int type, int state, struct x_display_info *dpyinfo, struct frame *frame, struct input_event *bufp)
4207 if (type == FocusIn)
4209 if (dpyinfo->x_focus_event_frame != frame)
4211 x_new_focus_frame (dpyinfo, frame);
4212 dpyinfo->x_focus_event_frame = frame;
4214 /* Don't stop displaying the initial startup message
4215 for a switch-frame event we don't need. */
4216 /* When run as a daemon, Vterminal_frame is always NIL. */
4217 bufp->arg = (((NILP (Vterminal_frame)
4218 || ! FRAME_X_P (XFRAME (Vterminal_frame))
4219 || EQ (Fdaemonp (), Qt))
4220 && CONSP (Vframe_list)
4221 && !NILP (XCDR (Vframe_list)))
4222 ? Qt : Qnil);
4223 bufp->kind = FOCUS_IN_EVENT;
4224 XSETFRAME (bufp->frame_or_window, frame);
4227 frame->output_data.x->focus_state |= state;
4229 #ifdef HAVE_X_I18N
4230 if (FRAME_XIC (frame))
4231 XSetICFocus (FRAME_XIC (frame));
4232 #endif
4234 else if (type == FocusOut)
4236 frame->output_data.x->focus_state &= ~state;
4238 if (dpyinfo->x_focus_event_frame == frame)
4240 dpyinfo->x_focus_event_frame = 0;
4241 x_new_focus_frame (dpyinfo, 0);
4243 bufp->kind = FOCUS_OUT_EVENT;
4244 XSETFRAME (bufp->frame_or_window, frame);
4247 #ifdef HAVE_X_I18N
4248 if (FRAME_XIC (frame))
4249 XUnsetICFocus (FRAME_XIC (frame));
4250 #endif
4251 if (frame->pointer_invisible)
4252 XTtoggle_invisible_pointer (frame, false);
4256 /* Return the Emacs frame-object corresponding to an X window.
4257 It could be the frame's main window or an icon window. */
4259 static struct frame *
4260 x_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
4262 Lisp_Object tail, frame;
4263 struct frame *f;
4265 if (wdesc == None)
4266 return NULL;
4268 FOR_EACH_FRAME (tail, frame)
4270 f = XFRAME (frame);
4271 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
4272 continue;
4273 if (f->output_data.x->hourglass_window == wdesc)
4274 return f;
4275 #ifdef USE_X_TOOLKIT
4276 if ((f->output_data.x->edit_widget
4277 && XtWindow (f->output_data.x->edit_widget) == wdesc)
4278 /* A tooltip frame? */
4279 || (!f->output_data.x->edit_widget
4280 && FRAME_X_WINDOW (f) == wdesc)
4281 || f->output_data.x->icon_desc == wdesc)
4282 return f;
4283 #else /* not USE_X_TOOLKIT */
4284 #ifdef USE_GTK
4285 if (f->output_data.x->edit_widget)
4287 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
4288 struct x_output *x = f->output_data.x;
4289 if (gwdesc != 0 && gwdesc == x->edit_widget)
4290 return f;
4292 #endif /* USE_GTK */
4293 if (FRAME_X_WINDOW (f) == wdesc
4294 || f->output_data.x->icon_desc == wdesc)
4295 return f;
4296 #endif /* not USE_X_TOOLKIT */
4298 return 0;
4301 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
4303 /* Like x_window_to_frame but also compares the window with the widget's
4304 windows. */
4306 static struct frame *
4307 x_any_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
4309 Lisp_Object tail, frame;
4310 struct frame *f, *found = NULL;
4311 struct x_output *x;
4313 if (wdesc == None)
4314 return NULL;
4316 FOR_EACH_FRAME (tail, frame)
4318 if (found)
4319 break;
4320 f = XFRAME (frame);
4321 if (FRAME_X_P (f) && FRAME_DISPLAY_INFO (f) == dpyinfo)
4323 /* This frame matches if the window is any of its widgets. */
4324 x = f->output_data.x;
4325 if (x->hourglass_window == wdesc)
4326 found = f;
4327 else if (x->widget)
4329 #ifdef USE_GTK
4330 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
4331 if (gwdesc != 0
4332 && gtk_widget_get_toplevel (gwdesc) == x->widget)
4333 found = f;
4334 #else
4335 if (wdesc == XtWindow (x->widget)
4336 || wdesc == XtWindow (x->column_widget)
4337 || wdesc == XtWindow (x->edit_widget))
4338 found = f;
4339 /* Match if the window is this frame's menubar. */
4340 else if (lw_window_is_in_menubar (wdesc, x->menubar_widget))
4341 found = f;
4342 #endif
4344 else if (FRAME_X_WINDOW (f) == wdesc)
4345 /* A tooltip frame. */
4346 found = f;
4350 return found;
4353 /* Likewise, but consider only the menu bar widget. */
4355 static struct frame *
4356 x_menubar_window_to_frame (struct x_display_info *dpyinfo,
4357 const XEvent *event)
4359 Window wdesc = event->xany.window;
4360 Lisp_Object tail, frame;
4361 struct frame *f;
4362 struct x_output *x;
4364 if (wdesc == None)
4365 return NULL;
4367 FOR_EACH_FRAME (tail, frame)
4369 f = XFRAME (frame);
4370 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
4371 continue;
4372 x = f->output_data.x;
4373 #ifdef USE_GTK
4374 if (x->menubar_widget && xg_event_is_for_menubar (f, event))
4375 return f;
4376 #else
4377 /* Match if the window is this frame's menubar. */
4378 if (x->menubar_widget
4379 && lw_window_is_in_menubar (wdesc, x->menubar_widget))
4380 return f;
4381 #endif
4383 return 0;
4386 /* Return the frame whose principal (outermost) window is WDESC.
4387 If WDESC is some other (smaller) window, we return 0. */
4389 struct frame *
4390 x_top_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
4392 Lisp_Object tail, frame;
4393 struct frame *f;
4394 struct x_output *x;
4396 if (wdesc == None)
4397 return NULL;
4399 FOR_EACH_FRAME (tail, frame)
4401 f = XFRAME (frame);
4402 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
4403 continue;
4404 x = f->output_data.x;
4406 if (x->widget)
4408 /* This frame matches if the window is its topmost widget. */
4409 #ifdef USE_GTK
4410 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
4411 if (gwdesc == x->widget)
4412 return f;
4413 #else
4414 if (wdesc == XtWindow (x->widget))
4415 return f;
4416 #endif
4418 else if (FRAME_X_WINDOW (f) == wdesc)
4419 /* Tooltip frame. */
4420 return f;
4422 return 0;
4425 #else /* !USE_X_TOOLKIT && !USE_GTK */
4427 #define x_any_window_to_frame(d, i) x_window_to_frame (d, i)
4428 #define x_top_window_to_frame(d, i) x_window_to_frame (d, i)
4430 #endif /* USE_X_TOOLKIT || USE_GTK */
4432 /* The focus may have changed. Figure out if it is a real focus change,
4433 by checking both FocusIn/Out and Enter/LeaveNotify events.
4435 Returns FOCUS_IN_EVENT event in *BUFP. */
4437 static void
4438 x_detect_focus_change (struct x_display_info *dpyinfo, struct frame *frame,
4439 const XEvent *event, struct input_event *bufp)
4441 if (!frame)
4442 return;
4444 switch (event->type)
4446 case EnterNotify:
4447 case LeaveNotify:
4449 struct frame *focus_frame = dpyinfo->x_focus_event_frame;
4450 int focus_state
4451 = focus_frame ? focus_frame->output_data.x->focus_state : 0;
4453 if (event->xcrossing.detail != NotifyInferior
4454 && event->xcrossing.focus
4455 && ! (focus_state & FOCUS_EXPLICIT))
4456 x_focus_changed ((event->type == EnterNotify ? FocusIn : FocusOut),
4457 FOCUS_IMPLICIT,
4458 dpyinfo, frame, bufp);
4460 break;
4462 case FocusIn:
4463 case FocusOut:
4464 x_focus_changed (event->type,
4465 (event->xfocus.detail == NotifyPointer ?
4466 FOCUS_IMPLICIT : FOCUS_EXPLICIT),
4467 dpyinfo, frame, bufp);
4468 break;
4470 case ClientMessage:
4471 if (event->xclient.message_type == dpyinfo->Xatom_XEMBED)
4473 enum xembed_message msg = event->xclient.data.l[1];
4474 x_focus_changed ((msg == XEMBED_FOCUS_IN ? FocusIn : FocusOut),
4475 FOCUS_EXPLICIT, dpyinfo, frame, bufp);
4477 break;
4482 #if !defined USE_X_TOOLKIT && !defined USE_GTK
4483 /* Handle an event saying the mouse has moved out of an Emacs frame. */
4485 void
4486 x_mouse_leave (struct x_display_info *dpyinfo)
4488 x_new_focus_frame (dpyinfo, dpyinfo->x_focus_event_frame);
4490 #endif
4492 /* The focus has changed, or we have redirected a frame's focus to
4493 another frame (this happens when a frame uses a surrogate
4494 mini-buffer frame). Shift the highlight as appropriate.
4496 The FRAME argument doesn't necessarily have anything to do with which
4497 frame is being highlighted or un-highlighted; we only use it to find
4498 the appropriate X display info. */
4500 static void
4501 XTframe_rehighlight (struct frame *frame)
4503 x_frame_rehighlight (FRAME_DISPLAY_INFO (frame));
4506 static void
4507 x_frame_rehighlight (struct x_display_info *dpyinfo)
4509 struct frame *old_highlight = dpyinfo->x_highlight_frame;
4511 if (dpyinfo->x_focus_frame)
4513 dpyinfo->x_highlight_frame
4514 = ((FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame)))
4515 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
4516 : dpyinfo->x_focus_frame);
4517 if (! FRAME_LIVE_P (dpyinfo->x_highlight_frame))
4519 fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
4520 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
4523 else
4524 dpyinfo->x_highlight_frame = 0;
4526 if (dpyinfo->x_highlight_frame != old_highlight)
4528 if (old_highlight)
4529 frame_unhighlight (old_highlight);
4530 if (dpyinfo->x_highlight_frame)
4531 frame_highlight (dpyinfo->x_highlight_frame);
4537 /* Keyboard processing - modifier keys, vendor-specific keysyms, etc. */
4539 /* Initialize mode_switch_bit and modifier_meaning. */
4540 static void
4541 x_find_modifier_meanings (struct x_display_info *dpyinfo)
4543 int min_code, max_code;
4544 KeySym *syms;
4545 int syms_per_code;
4546 XModifierKeymap *mods;
4548 dpyinfo->meta_mod_mask = 0;
4549 dpyinfo->shift_lock_mask = 0;
4550 dpyinfo->alt_mod_mask = 0;
4551 dpyinfo->super_mod_mask = 0;
4552 dpyinfo->hyper_mod_mask = 0;
4554 XDisplayKeycodes (dpyinfo->display, &min_code, &max_code);
4556 syms = XGetKeyboardMapping (dpyinfo->display,
4557 min_code, max_code - min_code + 1,
4558 &syms_per_code);
4559 mods = XGetModifierMapping (dpyinfo->display);
4561 /* Scan the modifier table to see which modifier bits the Meta and
4562 Alt keysyms are on. */
4564 int row, col; /* The row and column in the modifier table. */
4565 bool found_alt_or_meta;
4567 for (row = 3; row < 8; row++)
4569 found_alt_or_meta = false;
4570 for (col = 0; col < mods->max_keypermod; col++)
4572 KeyCode code = mods->modifiermap[(row * mods->max_keypermod) + col];
4574 /* Zeroes are used for filler. Skip them. */
4575 if (code == 0)
4576 continue;
4578 /* Are any of this keycode's keysyms a meta key? */
4580 int code_col;
4582 for (code_col = 0; code_col < syms_per_code; code_col++)
4584 int sym = syms[((code - min_code) * syms_per_code) + code_col];
4586 switch (sym)
4588 case XK_Meta_L:
4589 case XK_Meta_R:
4590 found_alt_or_meta = true;
4591 dpyinfo->meta_mod_mask |= (1 << row);
4592 break;
4594 case XK_Alt_L:
4595 case XK_Alt_R:
4596 found_alt_or_meta = true;
4597 dpyinfo->alt_mod_mask |= (1 << row);
4598 break;
4600 case XK_Hyper_L:
4601 case XK_Hyper_R:
4602 if (!found_alt_or_meta)
4603 dpyinfo->hyper_mod_mask |= (1 << row);
4604 code_col = syms_per_code;
4605 col = mods->max_keypermod;
4606 break;
4608 case XK_Super_L:
4609 case XK_Super_R:
4610 if (!found_alt_or_meta)
4611 dpyinfo->super_mod_mask |= (1 << row);
4612 code_col = syms_per_code;
4613 col = mods->max_keypermod;
4614 break;
4616 case XK_Shift_Lock:
4617 /* Ignore this if it's not on the lock modifier. */
4618 if (!found_alt_or_meta && ((1 << row) == LockMask))
4619 dpyinfo->shift_lock_mask = LockMask;
4620 code_col = syms_per_code;
4621 col = mods->max_keypermod;
4622 break;
4630 /* If we couldn't find any meta keys, accept any alt keys as meta keys. */
4631 if (! dpyinfo->meta_mod_mask)
4633 dpyinfo->meta_mod_mask = dpyinfo->alt_mod_mask;
4634 dpyinfo->alt_mod_mask = 0;
4637 /* If some keys are both alt and meta,
4638 make them just meta, not alt. */
4639 if (dpyinfo->alt_mod_mask & dpyinfo->meta_mod_mask)
4641 dpyinfo->alt_mod_mask &= ~dpyinfo->meta_mod_mask;
4644 XFree (syms);
4645 XFreeModifiermap (mods);
4648 /* Convert between the modifier bits X uses and the modifier bits
4649 Emacs uses. */
4652 x_x_to_emacs_modifiers (struct x_display_info *dpyinfo, int state)
4654 int mod_meta = meta_modifier;
4655 int mod_alt = alt_modifier;
4656 int mod_hyper = hyper_modifier;
4657 int mod_super = super_modifier;
4658 Lisp_Object tem;
4660 tem = Fget (Vx_alt_keysym, Qmodifier_value);
4661 if (INTEGERP (tem)) mod_alt = XINT (tem) & INT_MAX;
4662 tem = Fget (Vx_meta_keysym, Qmodifier_value);
4663 if (INTEGERP (tem)) mod_meta = XINT (tem) & INT_MAX;
4664 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
4665 if (INTEGERP (tem)) mod_hyper = XINT (tem) & INT_MAX;
4666 tem = Fget (Vx_super_keysym, Qmodifier_value);
4667 if (INTEGERP (tem)) mod_super = XINT (tem) & INT_MAX;
4669 return ( ((state & (ShiftMask | dpyinfo->shift_lock_mask)) ? shift_modifier : 0)
4670 | ((state & ControlMask) ? ctrl_modifier : 0)
4671 | ((state & dpyinfo->meta_mod_mask) ? mod_meta : 0)
4672 | ((state & dpyinfo->alt_mod_mask) ? mod_alt : 0)
4673 | ((state & dpyinfo->super_mod_mask) ? mod_super : 0)
4674 | ((state & dpyinfo->hyper_mod_mask) ? mod_hyper : 0));
4677 static int
4678 x_emacs_to_x_modifiers (struct x_display_info *dpyinfo, EMACS_INT state)
4680 EMACS_INT mod_meta = meta_modifier;
4681 EMACS_INT mod_alt = alt_modifier;
4682 EMACS_INT mod_hyper = hyper_modifier;
4683 EMACS_INT mod_super = super_modifier;
4685 Lisp_Object tem;
4687 tem = Fget (Vx_alt_keysym, Qmodifier_value);
4688 if (INTEGERP (tem)) mod_alt = XINT (tem);
4689 tem = Fget (Vx_meta_keysym, Qmodifier_value);
4690 if (INTEGERP (tem)) mod_meta = XINT (tem);
4691 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
4692 if (INTEGERP (tem)) mod_hyper = XINT (tem);
4693 tem = Fget (Vx_super_keysym, Qmodifier_value);
4694 if (INTEGERP (tem)) mod_super = XINT (tem);
4697 return ( ((state & mod_alt) ? dpyinfo->alt_mod_mask : 0)
4698 | ((state & mod_super) ? dpyinfo->super_mod_mask : 0)
4699 | ((state & mod_hyper) ? dpyinfo->hyper_mod_mask : 0)
4700 | ((state & shift_modifier) ? ShiftMask : 0)
4701 | ((state & ctrl_modifier) ? ControlMask : 0)
4702 | ((state & mod_meta) ? dpyinfo->meta_mod_mask : 0));
4705 /* Convert a keysym to its name. */
4707 char *
4708 x_get_keysym_name (int keysym)
4710 char *value;
4712 block_input ();
4713 value = XKeysymToString (keysym);
4714 unblock_input ();
4716 return value;
4719 /* Mouse clicks and mouse movement. Rah.
4721 Formerly, we used PointerMotionHintMask (in standard_event_mask)
4722 so that we would have to call XQueryPointer after each MotionNotify
4723 event to ask for another such event. However, this made mouse tracking
4724 slow, and there was a bug that made it eventually stop.
4726 Simply asking for MotionNotify all the time seems to work better.
4728 In order to avoid asking for motion events and then throwing most
4729 of them away or busy-polling the server for mouse positions, we ask
4730 the server for pointer motion hints. This means that we get only
4731 one event per group of mouse movements. "Groups" are delimited by
4732 other kinds of events (focus changes and button clicks, for
4733 example), or by XQueryPointer calls; when one of these happens, we
4734 get another MotionNotify event the next time the mouse moves. This
4735 is at least as efficient as getting motion events when mouse
4736 tracking is on, and I suspect only negligibly worse when tracking
4737 is off. */
4739 /* Prepare a mouse-event in *RESULT for placement in the input queue.
4741 If the event is a button press, then note that we have grabbed
4742 the mouse. */
4744 static Lisp_Object
4745 construct_mouse_click (struct input_event *result,
4746 const XButtonEvent *event,
4747 struct frame *f)
4749 /* Make the event type NO_EVENT; we'll change that when we decide
4750 otherwise. */
4751 result->kind = MOUSE_CLICK_EVENT;
4752 result->code = event->button - Button1;
4753 result->timestamp = event->time;
4754 result->modifiers = (x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO (f),
4755 event->state)
4756 | (event->type == ButtonRelease
4757 ? up_modifier
4758 : down_modifier));
4760 XSETINT (result->x, event->x);
4761 XSETINT (result->y, event->y);
4762 XSETFRAME (result->frame_or_window, f);
4763 result->arg = Qnil;
4764 return Qnil;
4767 /* Function to report a mouse movement to the mainstream Emacs code.
4768 The input handler calls this.
4770 We have received a mouse movement event, which is given in *event.
4771 If the mouse is over a different glyph than it was last time, tell
4772 the mainstream emacs code by setting mouse_moved. If not, ask for
4773 another motion event, so we can check again the next time it moves. */
4775 static bool
4776 note_mouse_movement (struct frame *frame, const XMotionEvent *event)
4778 XRectangle *r;
4779 struct x_display_info *dpyinfo;
4781 if (!FRAME_X_OUTPUT (frame))
4782 return false;
4784 dpyinfo = FRAME_DISPLAY_INFO (frame);
4785 dpyinfo->last_mouse_movement_time = event->time;
4786 dpyinfo->last_mouse_motion_frame = frame;
4787 dpyinfo->last_mouse_motion_x = event->x;
4788 dpyinfo->last_mouse_motion_y = event->y;
4790 if (event->window != FRAME_X_WINDOW (frame))
4792 frame->mouse_moved = true;
4793 dpyinfo->last_mouse_scroll_bar = NULL;
4794 note_mouse_highlight (frame, -1, -1);
4795 dpyinfo->last_mouse_glyph_frame = NULL;
4796 return true;
4800 /* Has the mouse moved off the glyph it was on at the last sighting? */
4801 r = &dpyinfo->last_mouse_glyph;
4802 if (frame != dpyinfo->last_mouse_glyph_frame
4803 || event->x < r->x || event->x >= r->x + r->width
4804 || event->y < r->y || event->y >= r->y + r->height)
4806 frame->mouse_moved = true;
4807 dpyinfo->last_mouse_scroll_bar = NULL;
4808 note_mouse_highlight (frame, event->x, event->y);
4809 /* Remember which glyph we're now on. */
4810 remember_mouse_glyph (frame, event->x, event->y, r);
4811 dpyinfo->last_mouse_glyph_frame = frame;
4812 return true;
4815 return false;
4818 /* Return the current position of the mouse.
4819 *FP should be a frame which indicates which display to ask about.
4821 If the mouse movement started in a scroll bar, set *FP, *BAR_WINDOW,
4822 and *PART to the frame, window, and scroll bar part that the mouse
4823 is over. Set *X and *Y to the portion and whole of the mouse's
4824 position on the scroll bar.
4826 If the mouse movement started elsewhere, set *FP to the frame the
4827 mouse is on, *BAR_WINDOW to nil, and *X and *Y to the character cell
4828 the mouse is over.
4830 Set *TIMESTAMP to the server time-stamp for the time at which the mouse
4831 was at this position.
4833 Don't store anything if we don't have a valid set of values to report.
4835 This clears the mouse_moved flag, so we can wait for the next mouse
4836 movement. */
4838 static void
4839 XTmouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
4840 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
4841 Time *timestamp)
4843 struct frame *f1;
4844 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (*fp);
4846 block_input ();
4848 if (dpyinfo->last_mouse_scroll_bar && insist == 0)
4850 struct scroll_bar *bar = dpyinfo->last_mouse_scroll_bar;
4852 if (bar->horizontal)
4853 x_horizontal_scroll_bar_report_motion (fp, bar_window, part, x, y, timestamp);
4854 else
4855 x_scroll_bar_report_motion (fp, bar_window, part, x, y, timestamp);
4857 else
4859 Window root;
4860 int root_x, root_y;
4862 Window dummy_window;
4863 int dummy;
4865 Lisp_Object frame, tail;
4867 /* Clear the mouse-moved flag for every frame on this display. */
4868 FOR_EACH_FRAME (tail, frame)
4869 if (FRAME_X_P (XFRAME (frame))
4870 && FRAME_X_DISPLAY (XFRAME (frame)) == FRAME_X_DISPLAY (*fp))
4871 XFRAME (frame)->mouse_moved = false;
4873 dpyinfo->last_mouse_scroll_bar = NULL;
4875 /* Figure out which root window we're on. */
4876 XQueryPointer (FRAME_X_DISPLAY (*fp),
4877 DefaultRootWindow (FRAME_X_DISPLAY (*fp)),
4879 /* The root window which contains the pointer. */
4880 &root,
4882 /* Trash which we can't trust if the pointer is on
4883 a different screen. */
4884 &dummy_window,
4886 /* The position on that root window. */
4887 &root_x, &root_y,
4889 /* More trash we can't trust. */
4890 &dummy, &dummy,
4892 /* Modifier keys and pointer buttons, about which
4893 we don't care. */
4894 (unsigned int *) &dummy);
4896 /* Now we have a position on the root; find the innermost window
4897 containing the pointer. */
4899 Window win, child;
4900 int win_x, win_y;
4901 int parent_x = 0, parent_y = 0;
4903 win = root;
4905 /* XTranslateCoordinates can get errors if the window
4906 structure is changing at the same time this function
4907 is running. So at least we must not crash from them. */
4909 x_catch_errors (FRAME_X_DISPLAY (*fp));
4911 if (x_mouse_grabbed (dpyinfo))
4913 /* If mouse was grabbed on a frame, give coords for that frame
4914 even if the mouse is now outside it. */
4915 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
4917 /* From-window. */
4918 root,
4920 /* To-window. */
4921 FRAME_X_WINDOW (dpyinfo->last_mouse_frame),
4923 /* From-position, to-position. */
4924 root_x, root_y, &win_x, &win_y,
4926 /* Child of win. */
4927 &child);
4928 f1 = dpyinfo->last_mouse_frame;
4930 else
4932 while (true)
4934 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
4936 /* From-window, to-window. */
4937 root, win,
4939 /* From-position, to-position. */
4940 root_x, root_y, &win_x, &win_y,
4942 /* Child of win. */
4943 &child);
4945 if (child == None || child == win)
4946 break;
4947 #ifdef USE_GTK
4948 /* We don't wan't to know the innermost window. We
4949 want the edit window. For non-Gtk+ the innermost
4950 window is the edit window. For Gtk+ it might not
4951 be. It might be the tool bar for example. */
4952 if (x_window_to_frame (dpyinfo, win))
4953 break;
4954 #endif
4955 win = child;
4956 parent_x = win_x;
4957 parent_y = win_y;
4960 /* Now we know that:
4961 win is the innermost window containing the pointer
4962 (XTC says it has no child containing the pointer),
4963 win_x and win_y are the pointer's position in it
4964 (XTC did this the last time through), and
4965 parent_x and parent_y are the pointer's position in win's parent.
4966 (They are what win_x and win_y were when win was child.
4967 If win is the root window, it has no parent, and
4968 parent_{x,y} are invalid, but that's okay, because we'll
4969 never use them in that case.) */
4971 #ifdef USE_GTK
4972 /* We don't wan't to know the innermost window. We
4973 want the edit window. */
4974 f1 = x_window_to_frame (dpyinfo, win);
4975 #else
4976 /* Is win one of our frames? */
4977 f1 = x_any_window_to_frame (dpyinfo, win);
4978 #endif
4980 #ifdef USE_X_TOOLKIT
4981 /* If we end up with the menu bar window, say it's not
4982 on the frame. */
4983 if (f1 != NULL
4984 && f1->output_data.x->menubar_widget
4985 && win == XtWindow (f1->output_data.x->menubar_widget))
4986 f1 = NULL;
4987 #endif /* USE_X_TOOLKIT */
4990 if (x_had_errors_p (FRAME_X_DISPLAY (*fp)))
4991 f1 = 0;
4993 x_uncatch_errors_after_check ();
4995 /* If not, is it one of our scroll bars? */
4996 if (! f1)
4998 struct scroll_bar *bar;
5000 bar = x_window_to_scroll_bar (FRAME_X_DISPLAY (*fp), win, 2);
5002 if (bar)
5004 f1 = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5005 win_x = parent_x;
5006 win_y = parent_y;
5010 if (f1 == 0 && insist > 0)
5011 f1 = SELECTED_FRAME ();
5013 if (f1)
5015 /* Ok, we found a frame. Store all the values.
5016 last_mouse_glyph is a rectangle used to reduce the
5017 generation of mouse events. To not miss any motion
5018 events, we must divide the frame into rectangles of the
5019 size of the smallest character that could be displayed
5020 on it, i.e. into the same rectangles that matrices on
5021 the frame are divided into. */
5023 /* FIXME: what if F1 is not an X frame? */
5024 dpyinfo = FRAME_DISPLAY_INFO (f1);
5025 remember_mouse_glyph (f1, win_x, win_y, &dpyinfo->last_mouse_glyph);
5026 dpyinfo->last_mouse_glyph_frame = f1;
5028 *bar_window = Qnil;
5029 *part = 0;
5030 *fp = f1;
5031 XSETINT (*x, win_x);
5032 XSETINT (*y, win_y);
5033 *timestamp = dpyinfo->last_mouse_movement_time;
5038 unblock_input ();
5043 /***********************************************************************
5044 Scroll bars
5045 ***********************************************************************/
5047 /* Scroll bar support. */
5049 /* Given an X window ID and a DISPLAY, find the struct scroll_bar which
5050 manages it.
5051 This can be called in GC, so we have to make sure to strip off mark
5052 bits. */
5054 static struct scroll_bar *
5055 x_window_to_scroll_bar (Display *display, Window window_id, int type)
5057 Lisp_Object tail, frame;
5059 #if defined (USE_GTK) && defined (USE_TOOLKIT_SCROLL_BARS)
5060 window_id = (Window) xg_get_scroll_id_for_window (display, window_id);
5061 #endif /* USE_GTK && USE_TOOLKIT_SCROLL_BARS */
5063 FOR_EACH_FRAME (tail, frame)
5065 Lisp_Object bar, condemned;
5067 if (! FRAME_X_P (XFRAME (frame)))
5068 continue;
5070 /* Scan this frame's scroll bar list for a scroll bar with the
5071 right window ID. */
5072 condemned = FRAME_CONDEMNED_SCROLL_BARS (XFRAME (frame));
5073 for (bar = FRAME_SCROLL_BARS (XFRAME (frame));
5074 /* This trick allows us to search both the ordinary and
5075 condemned scroll bar lists with one loop. */
5076 ! NILP (bar) || (bar = condemned,
5077 condemned = Qnil,
5078 ! NILP (bar));
5079 bar = XSCROLL_BAR (bar)->next)
5080 if (XSCROLL_BAR (bar)->x_window == window_id
5081 && FRAME_X_DISPLAY (XFRAME (frame)) == display
5082 && (type = 2
5083 || (type == 1 && XSCROLL_BAR (bar)->horizontal)
5084 || (type == 0 && !XSCROLL_BAR (bar)->horizontal)))
5085 return XSCROLL_BAR (bar);
5088 return NULL;
5092 #if defined USE_LUCID
5094 /* Return the Lucid menu bar WINDOW is part of. Return null
5095 if WINDOW is not part of a menu bar. */
5097 static Widget
5098 x_window_to_menu_bar (Window window)
5100 Lisp_Object tail, frame;
5102 FOR_EACH_FRAME (tail, frame)
5103 if (FRAME_X_P (XFRAME (frame)))
5105 Widget menu_bar = XFRAME (frame)->output_data.x->menubar_widget;
5107 if (menu_bar && xlwmenu_window_p (menu_bar, window))
5108 return menu_bar;
5110 return NULL;
5113 #endif /* USE_LUCID */
5116 /************************************************************************
5117 Toolkit scroll bars
5118 ************************************************************************/
5120 #ifdef USE_TOOLKIT_SCROLL_BARS
5122 static void x_send_scroll_bar_event (Lisp_Object, enum scroll_bar_part,
5123 int, int, bool);
5125 /* Lisp window being scrolled. Set when starting to interact with
5126 a toolkit scroll bar, reset to nil when ending the interaction. */
5128 static Lisp_Object window_being_scrolled;
5130 /* Whether this is an Xaw with arrow-scrollbars. This should imply
5131 that movements of 1/20 of the screen size are mapped to up/down. */
5133 #ifndef USE_GTK
5134 /* Id of action hook installed for scroll bars. */
5136 static XtActionHookId action_hook_id;
5137 static XtActionHookId horizontal_action_hook_id;
5139 static Boolean xaw3d_arrow_scroll;
5141 /* Whether the drag scrolling maintains the mouse at the top of the
5142 thumb. If not, resizing the thumb needs to be done more carefully
5143 to avoid jerkiness. */
5145 static Boolean xaw3d_pick_top;
5147 /* Action hook installed via XtAppAddActionHook when toolkit scroll
5148 bars are used.. The hook is responsible for detecting when
5149 the user ends an interaction with the scroll bar, and generates
5150 a `end-scroll' SCROLL_BAR_CLICK_EVENT' event if so. */
5152 static void
5153 xt_action_hook (Widget widget, XtPointer client_data, String action_name,
5154 XEvent *event, String *params, Cardinal *num_params)
5156 bool scroll_bar_p;
5157 const char *end_action;
5159 #ifdef USE_MOTIF
5160 scroll_bar_p = XmIsScrollBar (widget);
5161 end_action = "Release";
5162 #else /* !USE_MOTIF i.e. use Xaw */
5163 scroll_bar_p = XtIsSubclass (widget, scrollbarWidgetClass);
5164 end_action = "EndScroll";
5165 #endif /* USE_MOTIF */
5167 if (scroll_bar_p
5168 && strcmp (action_name, end_action) == 0
5169 && WINDOWP (window_being_scrolled))
5171 struct window *w;
5172 struct scroll_bar *bar;
5174 x_send_scroll_bar_event (window_being_scrolled,
5175 scroll_bar_end_scroll, 0, 0, false);
5176 w = XWINDOW (window_being_scrolled);
5177 bar = XSCROLL_BAR (w->vertical_scroll_bar);
5179 if (bar->dragging != -1)
5181 bar->dragging = -1;
5182 /* The thumb size is incorrect while dragging: fix it. */
5183 set_vertical_scroll_bar (w);
5185 window_being_scrolled = Qnil;
5186 #if defined (USE_LUCID)
5187 bar->last_seen_part = scroll_bar_nowhere;
5188 #endif
5189 /* Xt timeouts no longer needed. */
5190 toolkit_scroll_bar_interaction = false;
5195 static void
5196 xt_horizontal_action_hook (Widget widget, XtPointer client_data, String action_name,
5197 XEvent *event, String *params, Cardinal *num_params)
5199 bool scroll_bar_p;
5200 const char *end_action;
5202 #ifdef USE_MOTIF
5203 scroll_bar_p = XmIsScrollBar (widget);
5204 end_action = "Release";
5205 #else /* !USE_MOTIF i.e. use Xaw */
5206 scroll_bar_p = XtIsSubclass (widget, scrollbarWidgetClass);
5207 end_action = "EndScroll";
5208 #endif /* USE_MOTIF */
5210 if (scroll_bar_p
5211 && strcmp (action_name, end_action) == 0
5212 && WINDOWP (window_being_scrolled))
5214 struct window *w;
5215 struct scroll_bar *bar;
5217 x_send_scroll_bar_event (window_being_scrolled,
5218 scroll_bar_end_scroll, 0, 0, true);
5219 w = XWINDOW (window_being_scrolled);
5220 bar = XSCROLL_BAR (w->horizontal_scroll_bar);
5222 if (bar->dragging != -1)
5224 bar->dragging = -1;
5225 /* The thumb size is incorrect while dragging: fix it. */
5226 set_horizontal_scroll_bar (w);
5228 window_being_scrolled = Qnil;
5229 #if defined (USE_LUCID)
5230 bar->last_seen_part = scroll_bar_nowhere;
5231 #endif
5232 /* Xt timeouts no longer needed. */
5233 toolkit_scroll_bar_interaction = false;
5236 #endif /* not USE_GTK */
5238 /* Send a client message with message type Xatom_Scrollbar for a
5239 scroll action to the frame of WINDOW. PART is a value identifying
5240 the part of the scroll bar that was clicked on. PORTION is the
5241 amount to scroll of a whole of WHOLE. */
5243 static void
5244 x_send_scroll_bar_event (Lisp_Object window, enum scroll_bar_part part,
5245 int portion, int whole, bool horizontal)
5247 XEvent event;
5248 XClientMessageEvent *ev = &event.xclient;
5249 struct window *w = XWINDOW (window);
5250 struct frame *f = XFRAME (w->frame);
5251 intptr_t iw = (intptr_t) w;
5252 enum { BITS_PER_INTPTR = CHAR_BIT * sizeof iw };
5253 verify (BITS_PER_INTPTR <= 64);
5254 int sign_shift = BITS_PER_INTPTR - 32;
5256 block_input ();
5258 /* Construct a ClientMessage event to send to the frame. */
5259 ev->type = ClientMessage;
5260 ev->message_type = (horizontal
5261 ? FRAME_DISPLAY_INFO (f)->Xatom_Horizontal_Scrollbar
5262 : FRAME_DISPLAY_INFO (f)->Xatom_Scrollbar);
5263 ev->display = FRAME_X_DISPLAY (f);
5264 ev->window = FRAME_X_WINDOW (f);
5265 ev->format = 32;
5267 /* A 32-bit X client on a 64-bit X server can pass a window pointer
5268 as-is. A 64-bit client on a 32-bit X server is in trouble
5269 because a pointer does not fit and would be truncated while
5270 passing through the server. So use two slots and hope that X12
5271 will resolve such issues someday. */
5272 ev->data.l[0] = iw >> 31 >> 1;
5273 ev->data.l[1] = sign_shift <= 0 ? iw : iw << sign_shift >> sign_shift;
5274 ev->data.l[2] = part;
5275 ev->data.l[3] = portion;
5276 ev->data.l[4] = whole;
5278 /* Make Xt timeouts work while the scroll bar is active. */
5279 #ifdef USE_X_TOOLKIT
5280 toolkit_scroll_bar_interaction = true;
5281 x_activate_timeout_atimer ();
5282 #endif
5284 /* Setting the event mask to zero means that the message will
5285 be sent to the client that created the window, and if that
5286 window no longer exists, no event will be sent. */
5287 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), False, 0, &event);
5288 unblock_input ();
5292 /* Transform a scroll bar ClientMessage EVENT to an Emacs input event
5293 in *IEVENT. */
5295 static void
5296 x_scroll_bar_to_input_event (const XEvent *event,
5297 struct input_event *ievent)
5299 const XClientMessageEvent *ev = &event->xclient;
5300 Lisp_Object window;
5301 struct window *w;
5303 /* See the comment in the function above. */
5304 intptr_t iw0 = ev->data.l[0];
5305 intptr_t iw1 = ev->data.l[1];
5306 intptr_t iw = (iw0 << 31 << 1) + (iw1 & 0xffffffffu);
5307 w = (struct window *) iw;
5309 XSETWINDOW (window, w);
5311 ievent->kind = SCROLL_BAR_CLICK_EVENT;
5312 ievent->frame_or_window = window;
5313 ievent->arg = Qnil;
5314 #ifdef USE_GTK
5315 ievent->timestamp = CurrentTime;
5316 #else
5317 ievent->timestamp =
5318 XtLastTimestampProcessed (FRAME_X_DISPLAY (XFRAME (w->frame)));
5319 #endif
5320 ievent->code = 0;
5321 ievent->part = ev->data.l[2];
5322 ievent->x = make_number (ev->data.l[3]);
5323 ievent->y = make_number (ev->data.l[4]);
5324 ievent->modifiers = 0;
5327 /* Transform a horizontal scroll bar ClientMessage EVENT to an Emacs
5328 input event in *IEVENT. */
5330 static void
5331 x_horizontal_scroll_bar_to_input_event (const XEvent *event,
5332 struct input_event *ievent)
5334 const XClientMessageEvent *ev = &event->xclient;
5335 Lisp_Object window;
5336 struct window *w;
5338 /* See the comment in the function above. */
5339 intptr_t iw0 = ev->data.l[0];
5340 intptr_t iw1 = ev->data.l[1];
5341 intptr_t iw = (iw0 << 31 << 1) + (iw1 & 0xffffffffu);
5342 w = (struct window *) iw;
5344 XSETWINDOW (window, w);
5346 ievent->kind = HORIZONTAL_SCROLL_BAR_CLICK_EVENT;
5347 ievent->frame_or_window = window;
5348 ievent->arg = Qnil;
5349 #ifdef USE_GTK
5350 ievent->timestamp = CurrentTime;
5351 #else
5352 ievent->timestamp =
5353 XtLastTimestampProcessed (FRAME_X_DISPLAY (XFRAME (w->frame)));
5354 #endif
5355 ievent->code = 0;
5356 ievent->part = ev->data.l[2];
5357 ievent->x = make_number (ev->data.l[3]);
5358 ievent->y = make_number (ev->data.l[4]);
5359 ievent->modifiers = 0;
5363 #ifdef USE_MOTIF
5365 /* Minimum and maximum values used for Motif scroll bars. */
5367 #define XM_SB_MAX 10000000
5369 /* Scroll bar callback for Motif scroll bars. WIDGET is the scroll
5370 bar widget. CLIENT_DATA is a pointer to the scroll_bar structure.
5371 CALL_DATA is a pointer to a XmScrollBarCallbackStruct. */
5373 static void
5374 xm_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
5376 struct scroll_bar *bar = client_data;
5377 XmScrollBarCallbackStruct *cs = call_data;
5378 enum scroll_bar_part part = scroll_bar_nowhere;
5379 bool horizontal = bar->horizontal;
5380 int whole = 0, portion = 0;
5382 switch (cs->reason)
5384 case XmCR_DECREMENT:
5385 bar->dragging = -1;
5386 part = horizontal ? scroll_bar_left_arrow : scroll_bar_up_arrow;
5387 break;
5389 case XmCR_INCREMENT:
5390 bar->dragging = -1;
5391 part = horizontal ? scroll_bar_right_arrow : scroll_bar_down_arrow;
5392 break;
5394 case XmCR_PAGE_DECREMENT:
5395 bar->dragging = -1;
5396 part = horizontal ? scroll_bar_before_handle : scroll_bar_above_handle;
5397 break;
5399 case XmCR_PAGE_INCREMENT:
5400 bar->dragging = -1;
5401 part = horizontal ? scroll_bar_after_handle : scroll_bar_below_handle;
5402 break;
5404 case XmCR_TO_TOP:
5405 bar->dragging = -1;
5406 part = horizontal ? scroll_bar_to_leftmost : scroll_bar_to_top;
5407 break;
5409 case XmCR_TO_BOTTOM:
5410 bar->dragging = -1;
5411 part = horizontal ? scroll_bar_to_rightmost : scroll_bar_to_bottom;
5412 break;
5414 case XmCR_DRAG:
5416 int slider_size;
5418 block_input ();
5419 XtVaGetValues (widget, XmNsliderSize, &slider_size, NULL);
5420 unblock_input ();
5422 if (horizontal)
5424 portion = bar->whole * ((float)cs->value / XM_SB_MAX);
5425 whole = bar->whole * ((float)(XM_SB_MAX - slider_size) / XM_SB_MAX);
5426 portion = min (portion, whole);
5427 part = scroll_bar_horizontal_handle;
5429 else
5431 whole = XM_SB_MAX - slider_size;
5432 portion = min (cs->value, whole);
5433 part = scroll_bar_handle;
5436 bar->dragging = cs->value;
5438 break;
5440 case XmCR_VALUE_CHANGED:
5441 break;
5444 if (part != scroll_bar_nowhere)
5446 window_being_scrolled = bar->window;
5447 x_send_scroll_bar_event (bar->window, part, portion, whole,
5448 bar->horizontal);
5452 #elif defined USE_GTK
5454 /* Scroll bar callback for GTK scroll bars. WIDGET is the scroll
5455 bar widget. DATA is a pointer to the scroll_bar structure. */
5457 static gboolean
5458 xg_scroll_callback (GtkRange *range,
5459 GtkScrollType scroll,
5460 gdouble value,
5461 gpointer user_data)
5463 int whole = 0, portion = 0;
5464 struct scroll_bar *bar = user_data;
5465 enum scroll_bar_part part = scroll_bar_nowhere;
5466 GtkAdjustment *adj = GTK_ADJUSTMENT (gtk_range_get_adjustment (range));
5467 struct frame *f = g_object_get_data (G_OBJECT (range), XG_FRAME_DATA);
5469 if (xg_ignore_gtk_scrollbar) return false;
5471 switch (scroll)
5473 case GTK_SCROLL_JUMP:
5474 /* Buttons 1 2 or 3 must be grabbed. */
5475 if (FRAME_DISPLAY_INFO (f)->grabbed != 0
5476 && FRAME_DISPLAY_INFO (f)->grabbed < (1 << 4))
5478 if (bar->horizontal)
5480 part = scroll_bar_horizontal_handle;
5481 whole = (int)(gtk_adjustment_get_upper (adj) -
5482 gtk_adjustment_get_page_size (adj));
5483 portion = min ((int)value, whole);
5484 bar->dragging = portion;
5486 else
5488 part = scroll_bar_handle;
5489 whole = gtk_adjustment_get_upper (adj) -
5490 gtk_adjustment_get_page_size (adj);
5491 portion = min ((int)value, whole);
5492 bar->dragging = portion;
5495 break;
5496 case GTK_SCROLL_STEP_BACKWARD:
5497 part = (bar->horizontal
5498 ? scroll_bar_left_arrow : scroll_bar_up_arrow);
5499 bar->dragging = -1;
5500 break;
5501 case GTK_SCROLL_STEP_FORWARD:
5502 part = (bar->horizontal
5503 ? scroll_bar_right_arrow : scroll_bar_down_arrow);
5504 bar->dragging = -1;
5505 break;
5506 case GTK_SCROLL_PAGE_BACKWARD:
5507 part = (bar->horizontal
5508 ? scroll_bar_before_handle : scroll_bar_above_handle);
5509 bar->dragging = -1;
5510 break;
5511 case GTK_SCROLL_PAGE_FORWARD:
5512 part = (bar->horizontal
5513 ? scroll_bar_after_handle : scroll_bar_below_handle);
5514 bar->dragging = -1;
5515 break;
5516 default:
5517 break;
5520 if (part != scroll_bar_nowhere)
5522 window_being_scrolled = bar->window;
5523 x_send_scroll_bar_event (bar->window, part, portion, whole,
5524 bar->horizontal);
5527 return false;
5530 /* Callback for button release. Sets dragging to -1 when dragging is done. */
5532 static gboolean
5533 xg_end_scroll_callback (GtkWidget *widget,
5534 GdkEventButton *event,
5535 gpointer user_data)
5537 struct scroll_bar *bar = user_data;
5538 bar->dragging = -1;
5539 if (WINDOWP (window_being_scrolled))
5541 x_send_scroll_bar_event (window_being_scrolled,
5542 scroll_bar_end_scroll, 0, 0, bar->horizontal);
5543 window_being_scrolled = Qnil;
5546 return false;
5550 #else /* not USE_GTK and not USE_MOTIF */
5552 /* Xaw scroll bar callback. Invoked when the thumb is dragged.
5553 WIDGET is the scroll bar widget. CLIENT_DATA is a pointer to the
5554 scroll bar struct. CALL_DATA is a pointer to a float saying where
5555 the thumb is. */
5557 static void
5558 xaw_jump_callback (Widget widget, XtPointer client_data, XtPointer call_data)
5560 struct scroll_bar *bar = client_data;
5561 float *top_addr = call_data;
5562 float top = *top_addr;
5563 float shown;
5564 int whole, portion, height, width;
5565 enum scroll_bar_part part;
5566 bool horizontal = bar->horizontal;
5569 if (horizontal)
5571 /* Get the size of the thumb, a value between 0 and 1. */
5572 block_input ();
5573 XtVaGetValues (widget, XtNshown, &shown, XtNwidth, &width, NULL);
5574 unblock_input ();
5576 if (shown < 1)
5578 whole = bar->whole - (shown * bar->whole);
5579 portion = min (top * bar->whole, whole);
5581 else
5583 whole = bar->whole;
5584 portion = 0;
5587 part = scroll_bar_horizontal_handle;
5589 else
5591 /* Get the size of the thumb, a value between 0 and 1. */
5592 block_input ();
5593 XtVaGetValues (widget, XtNshown, &shown, XtNheight, &height, NULL);
5594 unblock_input ();
5596 whole = 10000000;
5597 portion = shown < 1 ? top * whole : 0;
5599 if (shown < 1 && (eabs (top + shown - 1) < 1.0f / height))
5600 /* Some derivatives of Xaw refuse to shrink the thumb when you reach
5601 the bottom, so we force the scrolling whenever we see that we're
5602 too close to the bottom (in x_set_toolkit_scroll_bar_thumb
5603 we try to ensure that we always stay two pixels away from the
5604 bottom). */
5605 part = scroll_bar_down_arrow;
5606 else
5607 part = scroll_bar_handle;
5610 window_being_scrolled = bar->window;
5611 bar->dragging = portion;
5612 bar->last_seen_part = part;
5613 x_send_scroll_bar_event (bar->window, part, portion, whole, bar->horizontal);
5617 /* Xaw scroll bar callback. Invoked for incremental scrolling.,
5618 i.e. line or page up or down. WIDGET is the Xaw scroll bar
5619 widget. CLIENT_DATA is a pointer to the scroll_bar structure for
5620 the scroll bar. CALL_DATA is an integer specifying the action that
5621 has taken place. Its magnitude is in the range 0..height of the
5622 scroll bar. Negative values mean scroll towards buffer start.
5623 Values < height of scroll bar mean line-wise movement. */
5625 static void
5626 xaw_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
5628 struct scroll_bar *bar = client_data;
5629 /* The position really is stored cast to a pointer. */
5630 int position = (intptr_t) call_data;
5631 Dimension height, width;
5632 enum scroll_bar_part part;
5634 if (bar->horizontal)
5636 /* Get the width of the scroll bar. */
5637 block_input ();
5638 XtVaGetValues (widget, XtNwidth, &width, NULL);
5639 unblock_input ();
5641 if (eabs (position) >= width)
5642 part = (position < 0) ? scroll_bar_before_handle : scroll_bar_after_handle;
5644 /* If Xaw3d was compiled with ARROW_SCROLLBAR,
5645 it maps line-movement to call_data = max(5, height/20). */
5646 else if (xaw3d_arrow_scroll && eabs (position) <= max (5, width / 20))
5647 part = (position < 0) ? scroll_bar_left_arrow : scroll_bar_right_arrow;
5648 else
5649 part = scroll_bar_move_ratio;
5651 window_being_scrolled = bar->window;
5652 bar->dragging = -1;
5653 bar->last_seen_part = part;
5654 x_send_scroll_bar_event (bar->window, part, position, width,
5655 bar->horizontal);
5657 else
5660 /* Get the height of the scroll bar. */
5661 block_input ();
5662 XtVaGetValues (widget, XtNheight, &height, NULL);
5663 unblock_input ();
5665 if (eabs (position) >= height)
5666 part = (position < 0) ? scroll_bar_above_handle : scroll_bar_below_handle;
5668 /* If Xaw3d was compiled with ARROW_SCROLLBAR,
5669 it maps line-movement to call_data = max(5, height/20). */
5670 else if (xaw3d_arrow_scroll && eabs (position) <= max (5, height / 20))
5671 part = (position < 0) ? scroll_bar_up_arrow : scroll_bar_down_arrow;
5672 else
5673 part = scroll_bar_move_ratio;
5675 window_being_scrolled = bar->window;
5676 bar->dragging = -1;
5677 bar->last_seen_part = part;
5678 x_send_scroll_bar_event (bar->window, part, position, height,
5679 bar->horizontal);
5683 #endif /* not USE_GTK and not USE_MOTIF */
5685 #define SCROLL_BAR_NAME "verticalScrollBar"
5686 #define SCROLL_BAR_HORIZONTAL_NAME "horizontalScrollBar"
5688 /* Create the widget for scroll bar BAR on frame F. Record the widget
5689 and X window of the scroll bar in BAR. */
5691 #ifdef USE_GTK
5692 static void
5693 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
5695 const char *scroll_bar_name = SCROLL_BAR_NAME;
5697 block_input ();
5698 xg_create_scroll_bar (f, bar, G_CALLBACK (xg_scroll_callback),
5699 G_CALLBACK (xg_end_scroll_callback),
5700 scroll_bar_name);
5701 unblock_input ();
5704 static void
5705 x_create_horizontal_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
5707 const char *scroll_bar_name = SCROLL_BAR_HORIZONTAL_NAME;
5709 block_input ();
5710 xg_create_horizontal_scroll_bar (f, bar, G_CALLBACK (xg_scroll_callback),
5711 G_CALLBACK (xg_end_scroll_callback),
5712 scroll_bar_name);
5713 unblock_input ();
5716 #else /* not USE_GTK */
5718 static void
5719 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
5721 Window xwindow;
5722 Widget widget;
5723 Arg av[20];
5724 int ac = 0;
5725 const char *scroll_bar_name = SCROLL_BAR_NAME;
5726 unsigned long pixel;
5728 block_input ();
5730 #ifdef USE_MOTIF
5731 /* Set resources. Create the widget. */
5732 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
5733 XtSetArg (av[ac], XmNminimum, 0); ++ac;
5734 XtSetArg (av[ac], XmNmaximum, XM_SB_MAX); ++ac;
5735 XtSetArg (av[ac], XmNorientation, XmVERTICAL); ++ac;
5736 XtSetArg (av[ac], XmNprocessingDirection, XmMAX_ON_BOTTOM), ++ac;
5737 XtSetArg (av[ac], XmNincrement, 1); ++ac;
5738 XtSetArg (av[ac], XmNpageIncrement, 1); ++ac;
5740 pixel = f->output_data.x->scroll_bar_foreground_pixel;
5741 if (pixel != -1)
5743 XtSetArg (av[ac], XmNforeground, pixel);
5744 ++ac;
5747 pixel = f->output_data.x->scroll_bar_background_pixel;
5748 if (pixel != -1)
5750 XtSetArg (av[ac], XmNbackground, pixel);
5751 ++ac;
5754 widget = XmCreateScrollBar (f->output_data.x->edit_widget,
5755 (char *) scroll_bar_name, av, ac);
5757 /* Add one callback for everything that can happen. */
5758 XtAddCallback (widget, XmNdecrementCallback, xm_scroll_callback,
5759 (XtPointer) bar);
5760 XtAddCallback (widget, XmNdragCallback, xm_scroll_callback,
5761 (XtPointer) bar);
5762 XtAddCallback (widget, XmNincrementCallback, xm_scroll_callback,
5763 (XtPointer) bar);
5764 XtAddCallback (widget, XmNpageDecrementCallback, xm_scroll_callback,
5765 (XtPointer) bar);
5766 XtAddCallback (widget, XmNpageIncrementCallback, xm_scroll_callback,
5767 (XtPointer) bar);
5768 XtAddCallback (widget, XmNtoBottomCallback, xm_scroll_callback,
5769 (XtPointer) bar);
5770 XtAddCallback (widget, XmNtoTopCallback, xm_scroll_callback,
5771 (XtPointer) bar);
5773 /* Realize the widget. Only after that is the X window created. */
5774 XtRealizeWidget (widget);
5776 /* Set the cursor to an arrow. I didn't find a resource to do that.
5777 And I'm wondering why it hasn't an arrow cursor by default. */
5778 XDefineCursor (XtDisplay (widget), XtWindow (widget),
5779 f->output_data.x->nontext_cursor);
5781 #else /* !USE_MOTIF i.e. use Xaw */
5783 /* Set resources. Create the widget. The background of the
5784 Xaw3d scroll bar widget is a little bit light for my taste.
5785 We don't alter it here to let users change it according
5786 to their taste with `emacs*verticalScrollBar.background: xxx'. */
5787 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
5788 XtSetArg (av[ac], XtNorientation, XtorientVertical); ++ac;
5789 /* For smoother scrolling with Xaw3d -sm */
5790 /* XtSetArg (av[ac], XtNpickTop, True); ++ac; */
5792 pixel = f->output_data.x->scroll_bar_foreground_pixel;
5793 if (pixel != -1)
5795 XtSetArg (av[ac], XtNforeground, pixel);
5796 ++ac;
5799 pixel = f->output_data.x->scroll_bar_background_pixel;
5800 if (pixel != -1)
5802 XtSetArg (av[ac], XtNbackground, pixel);
5803 ++ac;
5806 /* Top/bottom shadow colors. */
5808 /* Allocate them, if necessary. */
5809 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1)
5811 pixel = f->output_data.x->scroll_bar_background_pixel;
5812 if (pixel != -1)
5814 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
5815 FRAME_X_COLORMAP (f),
5816 &pixel, 1.2, 0x8000))
5817 pixel = -1;
5818 f->output_data.x->scroll_bar_top_shadow_pixel = pixel;
5821 if (f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
5823 pixel = f->output_data.x->scroll_bar_background_pixel;
5824 if (pixel != -1)
5826 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
5827 FRAME_X_COLORMAP (f),
5828 &pixel, 0.6, 0x4000))
5829 pixel = -1;
5830 f->output_data.x->scroll_bar_bottom_shadow_pixel = pixel;
5834 #ifdef XtNbeNiceToColormap
5835 /* Tell the toolkit about them. */
5836 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1
5837 || f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
5838 /* We tried to allocate a color for the top/bottom shadow, and
5839 failed, so tell Xaw3d to use dithering instead. */
5840 /* But only if we have a small colormap. Xaw3d can allocate nice
5841 colors itself. */
5843 XtSetArg (av[ac], XtNbeNiceToColormap,
5844 DefaultDepthOfScreen (FRAME_X_SCREEN (f)) < 16);
5845 ++ac;
5847 else
5848 /* Tell what colors Xaw3d should use for the top/bottom shadow, to
5849 be more consistent with other emacs 3d colors, and since Xaw3d is
5850 not good at dealing with allocation failure. */
5852 /* This tells Xaw3d to use real colors instead of dithering for
5853 the shadows. */
5854 XtSetArg (av[ac], XtNbeNiceToColormap, False);
5855 ++ac;
5857 /* Specify the colors. */
5858 pixel = f->output_data.x->scroll_bar_top_shadow_pixel;
5859 if (pixel != -1)
5861 XtSetArg (av[ac], XtNtopShadowPixel, pixel);
5862 ++ac;
5864 pixel = f->output_data.x->scroll_bar_bottom_shadow_pixel;
5865 if (pixel != -1)
5867 XtSetArg (av[ac], XtNbottomShadowPixel, pixel);
5868 ++ac;
5871 #endif
5873 widget = XtCreateWidget (scroll_bar_name, scrollbarWidgetClass,
5874 f->output_data.x->edit_widget, av, ac);
5877 char const *initial = "";
5878 char const *val = initial;
5879 XtVaGetValues (widget, XtNscrollVCursor, (XtPointer) &val,
5880 #ifdef XtNarrowScrollbars
5881 XtNarrowScrollbars, (XtPointer) &xaw3d_arrow_scroll,
5882 #endif
5883 XtNpickTop, (XtPointer) &xaw3d_pick_top, NULL);
5884 if (xaw3d_arrow_scroll || val == initial)
5885 { /* ARROW_SCROLL */
5886 xaw3d_arrow_scroll = True;
5887 /* Isn't that just a personal preference ? --Stef */
5888 XtVaSetValues (widget, XtNcursorName, "top_left_arrow", NULL);
5892 /* Define callbacks. */
5893 XtAddCallback (widget, XtNjumpProc, xaw_jump_callback, (XtPointer) bar);
5894 XtAddCallback (widget, XtNscrollProc, xaw_scroll_callback,
5895 (XtPointer) bar);
5897 /* Realize the widget. Only after that is the X window created. */
5898 XtRealizeWidget (widget);
5900 #endif /* !USE_MOTIF */
5902 /* Install an action hook that lets us detect when the user
5903 finishes interacting with a scroll bar. */
5904 if (action_hook_id == 0)
5905 action_hook_id = XtAppAddActionHook (Xt_app_con, xt_action_hook, 0);
5907 /* Remember X window and widget in the scroll bar vector. */
5908 SET_SCROLL_BAR_X_WIDGET (bar, widget);
5909 xwindow = XtWindow (widget);
5910 bar->x_window = xwindow;
5911 bar->whole = 1;
5912 bar->horizontal = false;
5914 unblock_input ();
5917 static void
5918 x_create_horizontal_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
5920 Window xwindow;
5921 Widget widget;
5922 Arg av[20];
5923 int ac = 0;
5924 const char *scroll_bar_name = SCROLL_BAR_HORIZONTAL_NAME;
5925 unsigned long pixel;
5927 block_input ();
5929 #ifdef USE_MOTIF
5930 /* Set resources. Create the widget. */
5931 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
5932 XtSetArg (av[ac], XmNminimum, 0); ++ac;
5933 XtSetArg (av[ac], XmNmaximum, XM_SB_MAX); ++ac;
5934 XtSetArg (av[ac], XmNorientation, XmHORIZONTAL); ++ac;
5935 XtSetArg (av[ac], XmNprocessingDirection, XmMAX_ON_RIGHT), ++ac;
5936 XtSetArg (av[ac], XmNincrement, 1); ++ac;
5937 XtSetArg (av[ac], XmNpageIncrement, 1); ++ac;
5939 pixel = f->output_data.x->scroll_bar_foreground_pixel;
5940 if (pixel != -1)
5942 XtSetArg (av[ac], XmNforeground, pixel);
5943 ++ac;
5946 pixel = f->output_data.x->scroll_bar_background_pixel;
5947 if (pixel != -1)
5949 XtSetArg (av[ac], XmNbackground, pixel);
5950 ++ac;
5953 widget = XmCreateScrollBar (f->output_data.x->edit_widget,
5954 (char *) scroll_bar_name, av, ac);
5956 /* Add one callback for everything that can happen. */
5957 XtAddCallback (widget, XmNdecrementCallback, xm_scroll_callback,
5958 (XtPointer) bar);
5959 XtAddCallback (widget, XmNdragCallback, xm_scroll_callback,
5960 (XtPointer) bar);
5961 XtAddCallback (widget, XmNincrementCallback, xm_scroll_callback,
5962 (XtPointer) bar);
5963 XtAddCallback (widget, XmNpageDecrementCallback, xm_scroll_callback,
5964 (XtPointer) bar);
5965 XtAddCallback (widget, XmNpageIncrementCallback, xm_scroll_callback,
5966 (XtPointer) bar);
5967 XtAddCallback (widget, XmNtoBottomCallback, xm_scroll_callback,
5968 (XtPointer) bar);
5969 XtAddCallback (widget, XmNtoTopCallback, xm_scroll_callback,
5970 (XtPointer) bar);
5972 /* Realize the widget. Only after that is the X window created. */
5973 XtRealizeWidget (widget);
5975 /* Set the cursor to an arrow. I didn't find a resource to do that.
5976 And I'm wondering why it hasn't an arrow cursor by default. */
5977 XDefineCursor (XtDisplay (widget), XtWindow (widget),
5978 f->output_data.x->nontext_cursor);
5980 #else /* !USE_MOTIF i.e. use Xaw */
5982 /* Set resources. Create the widget. The background of the
5983 Xaw3d scroll bar widget is a little bit light for my taste.
5984 We don't alter it here to let users change it according
5985 to their taste with `emacs*verticalScrollBar.background: xxx'. */
5986 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
5987 XtSetArg (av[ac], XtNorientation, XtorientHorizontal); ++ac;
5988 /* For smoother scrolling with Xaw3d -sm */
5989 /* XtSetArg (av[ac], XtNpickTop, True); ++ac; */
5991 pixel = f->output_data.x->scroll_bar_foreground_pixel;
5992 if (pixel != -1)
5994 XtSetArg (av[ac], XtNforeground, pixel);
5995 ++ac;
5998 pixel = f->output_data.x->scroll_bar_background_pixel;
5999 if (pixel != -1)
6001 XtSetArg (av[ac], XtNbackground, pixel);
6002 ++ac;
6005 /* Top/bottom shadow colors. */
6007 /* Allocate them, if necessary. */
6008 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1)
6010 pixel = f->output_data.x->scroll_bar_background_pixel;
6011 if (pixel != -1)
6013 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
6014 FRAME_X_COLORMAP (f),
6015 &pixel, 1.2, 0x8000))
6016 pixel = -1;
6017 f->output_data.x->scroll_bar_top_shadow_pixel = pixel;
6020 if (f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
6022 pixel = f->output_data.x->scroll_bar_background_pixel;
6023 if (pixel != -1)
6025 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
6026 FRAME_X_COLORMAP (f),
6027 &pixel, 0.6, 0x4000))
6028 pixel = -1;
6029 f->output_data.x->scroll_bar_bottom_shadow_pixel = pixel;
6033 #ifdef XtNbeNiceToColormap
6034 /* Tell the toolkit about them. */
6035 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1
6036 || f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
6037 /* We tried to allocate a color for the top/bottom shadow, and
6038 failed, so tell Xaw3d to use dithering instead. */
6039 /* But only if we have a small colormap. Xaw3d can allocate nice
6040 colors itself. */
6042 XtSetArg (av[ac], XtNbeNiceToColormap,
6043 DefaultDepthOfScreen (FRAME_X_SCREEN (f)) < 16);
6044 ++ac;
6046 else
6047 /* Tell what colors Xaw3d should use for the top/bottom shadow, to
6048 be more consistent with other emacs 3d colors, and since Xaw3d is
6049 not good at dealing with allocation failure. */
6051 /* This tells Xaw3d to use real colors instead of dithering for
6052 the shadows. */
6053 XtSetArg (av[ac], XtNbeNiceToColormap, False);
6054 ++ac;
6056 /* Specify the colors. */
6057 pixel = f->output_data.x->scroll_bar_top_shadow_pixel;
6058 if (pixel != -1)
6060 XtSetArg (av[ac], XtNtopShadowPixel, pixel);
6061 ++ac;
6063 pixel = f->output_data.x->scroll_bar_bottom_shadow_pixel;
6064 if (pixel != -1)
6066 XtSetArg (av[ac], XtNbottomShadowPixel, pixel);
6067 ++ac;
6070 #endif
6072 widget = XtCreateWidget (scroll_bar_name, scrollbarWidgetClass,
6073 f->output_data.x->edit_widget, av, ac);
6076 char const *initial = "";
6077 char const *val = initial;
6078 XtVaGetValues (widget, XtNscrollVCursor, (XtPointer) &val,
6079 #ifdef XtNarrowScrollbars
6080 XtNarrowScrollbars, (XtPointer) &xaw3d_arrow_scroll,
6081 #endif
6082 XtNpickTop, (XtPointer) &xaw3d_pick_top, NULL);
6083 if (xaw3d_arrow_scroll || val == initial)
6084 { /* ARROW_SCROLL */
6085 xaw3d_arrow_scroll = True;
6086 /* Isn't that just a personal preference ? --Stef */
6087 XtVaSetValues (widget, XtNcursorName, "top_left_arrow", NULL);
6091 /* Define callbacks. */
6092 XtAddCallback (widget, XtNjumpProc, xaw_jump_callback, (XtPointer) bar);
6093 XtAddCallback (widget, XtNscrollProc, xaw_scroll_callback,
6094 (XtPointer) bar);
6096 /* Realize the widget. Only after that is the X window created. */
6097 XtRealizeWidget (widget);
6099 #endif /* !USE_MOTIF */
6101 /* Install an action hook that lets us detect when the user
6102 finishes interacting with a scroll bar. */
6103 if (horizontal_action_hook_id == 0)
6104 horizontal_action_hook_id
6105 = XtAppAddActionHook (Xt_app_con, xt_horizontal_action_hook, 0);
6107 /* Remember X window and widget in the scroll bar vector. */
6108 SET_SCROLL_BAR_X_WIDGET (bar, widget);
6109 xwindow = XtWindow (widget);
6110 bar->x_window = xwindow;
6111 bar->whole = 1;
6112 bar->horizontal = true;
6114 unblock_input ();
6116 #endif /* not USE_GTK */
6119 /* Set the thumb size and position of scroll bar BAR. We are currently
6120 displaying PORTION out of a whole WHOLE, and our position POSITION. */
6122 #ifdef USE_GTK
6123 static void
6124 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position, int whole)
6126 xg_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
6129 static void
6130 x_set_toolkit_horizontal_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position, int whole)
6132 xg_set_toolkit_horizontal_scroll_bar_thumb (bar, portion, position, whole);
6135 #else /* not USE_GTK */
6136 static void
6137 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position,
6138 int whole)
6140 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6141 Widget widget = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
6142 float top, shown;
6144 block_input ();
6146 #ifdef USE_MOTIF
6148 if (scroll_bar_adjust_thumb_portion_p)
6150 /* We use an estimate of 30 chars per line rather than the real
6151 `portion' value. This has the disadvantage that the thumb size
6152 is not very representative, but it makes our life a lot easier.
6153 Otherwise, we have to constantly adjust the thumb size, which
6154 we can't always do quickly enough: while dragging, the size of
6155 the thumb might prevent the user from dragging the thumb all the
6156 way to the end. but Motif and some versions of Xaw3d don't allow
6157 updating the thumb size while dragging. Also, even if we can update
6158 its size, the update will often happen too late.
6159 If you don't believe it, check out revision 1.650 of xterm.c to see
6160 what hoops we were going through and the still poor behavior we got. */
6161 portion = WINDOW_TOTAL_LINES (XWINDOW (bar->window)) * 30;
6162 /* When the thumb is at the bottom, position == whole.
6163 So we need to increase `whole' to make space for the thumb. */
6164 whole += portion;
6167 if (whole <= 0)
6168 top = 0, shown = 1;
6169 else
6171 top = (float) position / whole;
6172 shown = (float) portion / whole;
6175 if (bar->dragging == -1)
6177 int size, value;
6179 /* Slider size. Must be in the range [1 .. MAX - MIN] where MAX
6180 is the scroll bar's maximum and MIN is the scroll bar's minimum
6181 value. */
6182 size = clip_to_bounds (1, shown * XM_SB_MAX, XM_SB_MAX);
6184 /* Position. Must be in the range [MIN .. MAX - SLIDER_SIZE]. */
6185 value = top * XM_SB_MAX;
6186 value = min (value, XM_SB_MAX - size);
6188 XmScrollBarSetValues (widget, value, size, 0, 0, False);
6190 #else /* !USE_MOTIF i.e. use Xaw */
6192 if (whole == 0)
6193 top = 0, shown = 1;
6194 else
6196 top = (float) position / whole;
6197 shown = (float) portion / whole;
6201 float old_top, old_shown;
6202 Dimension height;
6203 XtVaGetValues (widget,
6204 XtNtopOfThumb, &old_top,
6205 XtNshown, &old_shown,
6206 XtNheight, &height,
6207 NULL);
6209 /* Massage the top+shown values. */
6210 if (bar->dragging == -1 || bar->last_seen_part == scroll_bar_down_arrow)
6211 top = max (0, min (1, top));
6212 else
6213 top = old_top;
6214 #if ! defined (HAVE_XAW3D)
6215 /* With Xaw, 'top' values too closer to 1.0 may
6216 cause the thumb to disappear. Fix that. */
6217 top = min (top, 0.99f);
6218 #endif
6219 /* Keep two pixels available for moving the thumb down. */
6220 shown = max (0, min (1 - top - (2.0f / height), shown));
6221 #if ! defined (HAVE_XAW3D)
6222 /* Likewise with too small 'shown'. */
6223 shown = max (shown, 0.01f);
6224 #endif
6226 /* If the call to XawScrollbarSetThumb below doesn't seem to
6227 work, check that 'NARROWPROTO' is defined in src/config.h.
6228 If this is not so, most likely you need to fix configure. */
6229 if (top != old_top || shown != old_shown)
6231 if (bar->dragging == -1)
6232 XawScrollbarSetThumb (widget, top, shown);
6233 else
6235 /* Try to make the scrolling a tad smoother. */
6236 if (!xaw3d_pick_top)
6237 shown = min (shown, old_shown);
6239 XawScrollbarSetThumb (widget, top, shown);
6243 #endif /* !USE_MOTIF */
6245 unblock_input ();
6248 static void
6249 x_set_toolkit_horizontal_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position,
6250 int whole)
6252 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6253 Widget widget = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
6254 float top, shown;
6256 block_input ();
6258 #ifdef USE_MOTIF
6259 bar->whole = whole;
6260 shown = (float) portion / whole;
6261 top = (float) position / (whole - portion);
6263 int size = clip_to_bounds (1, shown * XM_SB_MAX, XM_SB_MAX);
6264 int value = clip_to_bounds (0, top * (XM_SB_MAX - size), XM_SB_MAX - size);
6266 XmScrollBarSetValues (widget, value, size, 0, 0, False);
6268 #else /* !USE_MOTIF i.e. use Xaw */
6269 bar->whole = whole;
6270 if (whole == 0)
6271 top = 0, shown = 1;
6272 else
6274 top = (float) position / whole;
6275 shown = (float) portion / whole;
6279 float old_top, old_shown;
6280 Dimension height;
6281 XtVaGetValues (widget,
6282 XtNtopOfThumb, &old_top,
6283 XtNshown, &old_shown,
6284 XtNheight, &height,
6285 NULL);
6287 #if false
6288 /* Massage the top+shown values. */
6289 if (bar->dragging == -1 || bar->last_seen_part == scroll_bar_down_arrow)
6290 top = max (0, min (1, top));
6291 else
6292 top = old_top;
6293 #if ! defined (HAVE_XAW3D)
6294 /* With Xaw, 'top' values too closer to 1.0 may
6295 cause the thumb to disappear. Fix that. */
6296 top = min (top, 0.99f);
6297 #endif
6298 /* Keep two pixels available for moving the thumb down. */
6299 shown = max (0, min (1 - top - (2.0f / height), shown));
6300 #if ! defined (HAVE_XAW3D)
6301 /* Likewise with too small 'shown'. */
6302 shown = max (shown, 0.01f);
6303 #endif
6304 #endif
6306 /* If the call to XawScrollbarSetThumb below doesn't seem to
6307 work, check that 'NARROWPROTO' is defined in src/config.h.
6308 If this is not so, most likely you need to fix configure. */
6309 XawScrollbarSetThumb (widget, top, shown);
6310 #if false
6311 if (top != old_top || shown != old_shown)
6313 if (bar->dragging == -1)
6314 XawScrollbarSetThumb (widget, top, shown);
6315 else
6317 /* Try to make the scrolling a tad smoother. */
6318 if (!xaw3d_pick_top)
6319 shown = min (shown, old_shown);
6321 XawScrollbarSetThumb (widget, top, shown);
6324 #endif
6326 #endif /* !USE_MOTIF */
6328 unblock_input ();
6330 #endif /* not USE_GTK */
6332 #endif /* USE_TOOLKIT_SCROLL_BARS */
6336 /************************************************************************
6337 Scroll bars, general
6338 ************************************************************************/
6340 /* Create a scroll bar and return the scroll bar vector for it. W is
6341 the Emacs window on which to create the scroll bar. TOP, LEFT,
6342 WIDTH and HEIGHT are the pixel coordinates and dimensions of the
6343 scroll bar. */
6345 static struct scroll_bar *
6346 x_scroll_bar_create (struct window *w, int top, int left,
6347 int width, int height, bool horizontal)
6349 struct frame *f = XFRAME (w->frame);
6350 struct scroll_bar *bar
6351 = ALLOCATE_PSEUDOVECTOR (struct scroll_bar, x_window, PVEC_OTHER);
6352 Lisp_Object barobj;
6354 block_input ();
6356 #ifdef USE_TOOLKIT_SCROLL_BARS
6357 if (horizontal)
6358 x_create_horizontal_toolkit_scroll_bar (f, bar);
6359 else
6360 x_create_toolkit_scroll_bar (f, bar);
6361 #else /* not USE_TOOLKIT_SCROLL_BARS */
6363 XSetWindowAttributes a;
6364 unsigned long mask;
6365 Window window;
6367 a.background_pixel = f->output_data.x->scroll_bar_background_pixel;
6368 if (a.background_pixel == -1)
6369 a.background_pixel = FRAME_BACKGROUND_PIXEL (f);
6371 a.event_mask = (ButtonPressMask | ButtonReleaseMask
6372 | ButtonMotionMask | PointerMotionHintMask
6373 | ExposureMask);
6374 a.cursor = FRAME_DISPLAY_INFO (f)->vertical_scroll_bar_cursor;
6376 mask = (CWBackPixel | CWEventMask | CWCursor);
6378 /* Clear the area of W that will serve as a scroll bar. This is
6379 for the case that a window has been split horizontally. In
6380 this case, no clear_frame is generated to reduce flickering. */
6381 if (width > 0 && window_box_height (w) > 0)
6382 x_clear_area (f, left, top, width, window_box_height (w));
6384 window = XCreateWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
6385 /* Position and size of scroll bar. */
6386 left, top, width, height,
6387 /* Border width, depth, class, and visual. */
6389 CopyFromParent,
6390 CopyFromParent,
6391 CopyFromParent,
6392 /* Attributes. */
6393 mask, &a);
6394 bar->x_window = window;
6396 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6398 XSETWINDOW (bar->window, w);
6399 bar->top = top;
6400 bar->left = left;
6401 bar->width = width;
6402 bar->height = height;
6403 bar->start = 0;
6404 bar->end = 0;
6405 bar->dragging = -1;
6406 bar->horizontal = horizontal;
6407 #if defined (USE_TOOLKIT_SCROLL_BARS) && defined (USE_LUCID)
6408 bar->last_seen_part = scroll_bar_nowhere;
6409 #endif
6411 /* Add bar to its frame's list of scroll bars. */
6412 bar->next = FRAME_SCROLL_BARS (f);
6413 bar->prev = Qnil;
6414 XSETVECTOR (barobj, bar);
6415 fset_scroll_bars (f, barobj);
6416 if (!NILP (bar->next))
6417 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
6419 /* Map the window/widget. */
6420 #ifdef USE_TOOLKIT_SCROLL_BARS
6422 #ifdef USE_GTK
6423 if (horizontal)
6424 xg_update_horizontal_scrollbar_pos (f, bar->x_window, top,
6425 left, width, max (height, 1));
6426 else
6427 xg_update_scrollbar_pos (f, bar->x_window, top,
6428 left, width, max (height, 1));
6429 #else /* not USE_GTK */
6430 Widget scroll_bar = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
6431 XtConfigureWidget (scroll_bar, left, top, width, max (height, 1), 0);
6432 XtMapWidget (scroll_bar);
6433 #endif /* not USE_GTK */
6435 #else /* not USE_TOOLKIT_SCROLL_BARS */
6436 XMapRaised (FRAME_X_DISPLAY (f), bar->x_window);
6437 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6439 unblock_input ();
6440 return bar;
6444 #ifndef USE_TOOLKIT_SCROLL_BARS
6446 /* Draw BAR's handle in the proper position.
6448 If the handle is already drawn from START to END, don't bother
6449 redrawing it, unless REBUILD; in that case, always
6450 redraw it. (REBUILD is handy for drawing the handle after expose
6451 events.)
6453 Normally, we want to constrain the start and end of the handle to
6454 fit inside its rectangle, but if the user is dragging the scroll
6455 bar handle, we want to let them drag it down all the way, so that
6456 the bar's top is as far down as it goes; otherwise, there's no way
6457 to move to the very end of the buffer. */
6459 static void
6460 x_scroll_bar_set_handle (struct scroll_bar *bar, int start, int end,
6461 bool rebuild)
6463 bool dragging = bar->dragging != -1;
6464 Window w = bar->x_window;
6465 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6466 GC gc = f->output_data.x->normal_gc;
6468 /* If the display is already accurate, do nothing. */
6469 if (! rebuild
6470 && start == bar->start
6471 && end == bar->end)
6472 return;
6474 block_input ();
6477 int inside_width = VERTICAL_SCROLL_BAR_INSIDE_WIDTH (f, bar->width);
6478 int inside_height = VERTICAL_SCROLL_BAR_INSIDE_HEIGHT (f, bar->height);
6479 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
6481 /* Make sure the values are reasonable, and try to preserve
6482 the distance between start and end. */
6484 int length = end - start;
6486 if (start < 0)
6487 start = 0;
6488 else if (start > top_range)
6489 start = top_range;
6490 end = start + length;
6492 if (end < start)
6493 end = start;
6494 else if (end > top_range && ! dragging)
6495 end = top_range;
6498 /* Store the adjusted setting in the scroll bar. */
6499 bar->start = start;
6500 bar->end = end;
6502 /* Clip the end position, just for display. */
6503 if (end > top_range)
6504 end = top_range;
6506 /* Draw bottom positions VERTICAL_SCROLL_BAR_MIN_HANDLE pixels
6507 below top positions, to make sure the handle is always at least
6508 that many pixels tall. */
6509 end += VERTICAL_SCROLL_BAR_MIN_HANDLE;
6511 /* Draw the empty space above the handle. Note that we can't clear
6512 zero-height areas; that means "clear to end of window." */
6513 if ((inside_width > 0) && (start > 0))
6514 x_clear_area1 (FRAME_X_DISPLAY (f), w,
6515 VERTICAL_SCROLL_BAR_LEFT_BORDER,
6516 VERTICAL_SCROLL_BAR_TOP_BORDER,
6517 inside_width, start, False);
6519 /* Change to proper foreground color if one is specified. */
6520 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
6521 XSetForeground (FRAME_X_DISPLAY (f), gc,
6522 f->output_data.x->scroll_bar_foreground_pixel);
6524 /* Draw the handle itself. */
6525 XFillRectangle (FRAME_X_DISPLAY (f), w, gc,
6526 /* x, y, width, height */
6527 VERTICAL_SCROLL_BAR_LEFT_BORDER,
6528 VERTICAL_SCROLL_BAR_TOP_BORDER + start,
6529 inside_width, end - start);
6531 /* Restore the foreground color of the GC if we changed it above. */
6532 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
6533 XSetForeground (FRAME_X_DISPLAY (f), gc,
6534 FRAME_FOREGROUND_PIXEL (f));
6536 /* Draw the empty space below the handle. Note that we can't
6537 clear zero-height areas; that means "clear to end of window." */
6538 if ((inside_width > 0) && (end < inside_height))
6539 x_clear_area1 (FRAME_X_DISPLAY (f), w,
6540 VERTICAL_SCROLL_BAR_LEFT_BORDER,
6541 VERTICAL_SCROLL_BAR_TOP_BORDER + end,
6542 inside_width, inside_height - end, False);
6545 unblock_input ();
6548 #endif /* !USE_TOOLKIT_SCROLL_BARS */
6550 /* Destroy scroll bar BAR, and set its Emacs window's scroll bar to
6551 nil. */
6553 static void
6554 x_scroll_bar_remove (struct scroll_bar *bar)
6556 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6557 block_input ();
6559 #ifdef USE_TOOLKIT_SCROLL_BARS
6560 #ifdef USE_GTK
6561 xg_remove_scroll_bar (f, bar->x_window);
6562 #else /* not USE_GTK */
6563 XtDestroyWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar));
6564 #endif /* not USE_GTK */
6565 #else
6566 XDestroyWindow (FRAME_X_DISPLAY (f), bar->x_window);
6567 #endif
6569 /* Dissociate this scroll bar from its window. */
6570 if (bar->horizontal)
6571 wset_horizontal_scroll_bar (XWINDOW (bar->window), Qnil);
6572 else
6573 wset_vertical_scroll_bar (XWINDOW (bar->window), Qnil);
6575 unblock_input ();
6579 /* Set the handle of the vertical scroll bar for WINDOW to indicate
6580 that we are displaying PORTION characters out of a total of WHOLE
6581 characters, starting at POSITION. If WINDOW has no scroll bar,
6582 create one. */
6584 static void
6585 XTset_vertical_scroll_bar (struct window *w, int portion, int whole, int position)
6587 struct frame *f = XFRAME (w->frame);
6588 Lisp_Object barobj;
6589 struct scroll_bar *bar;
6590 int top, height, left, width;
6591 int window_y, window_height;
6593 /* Get window dimensions. */
6594 window_box (w, ANY_AREA, 0, &window_y, 0, &window_height);
6595 top = window_y;
6596 height = window_height;
6597 left = WINDOW_SCROLL_BAR_AREA_X (w);
6598 width = WINDOW_SCROLL_BAR_AREA_WIDTH (w);
6600 /* Does the scroll bar exist yet? */
6601 if (NILP (w->vertical_scroll_bar))
6603 if (width > 0 && height > 0)
6605 block_input ();
6606 x_clear_area (f, left, top, width, height);
6607 unblock_input ();
6610 bar = x_scroll_bar_create (w, top, left, width, max (height, 1), false);
6612 else
6614 /* It may just need to be moved and resized. */
6615 unsigned int mask = 0;
6617 bar = XSCROLL_BAR (w->vertical_scroll_bar);
6619 block_input ();
6621 if (left != bar->left)
6622 mask |= CWX;
6623 if (top != bar->top)
6624 mask |= CWY;
6625 if (width != bar->width)
6626 mask |= CWWidth;
6627 if (height != bar->height)
6628 mask |= CWHeight;
6630 #ifdef USE_TOOLKIT_SCROLL_BARS
6632 /* Move/size the scroll bar widget. */
6633 if (mask)
6635 /* Since toolkit scroll bars are smaller than the space reserved
6636 for them on the frame, we have to clear "under" them. */
6637 if (width > 0 && height > 0)
6638 x_clear_area (f, left, top, width, height);
6639 #ifdef USE_GTK
6640 xg_update_scrollbar_pos (f, bar->x_window, top,
6641 left, width, max (height, 1));
6642 #else /* not USE_GTK */
6643 XtConfigureWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar),
6644 left, top, width, max (height, 1), 0);
6645 #endif /* not USE_GTK */
6647 #else /* not USE_TOOLKIT_SCROLL_BARS */
6649 /* Move/size the scroll bar window. */
6650 if (mask)
6652 XWindowChanges wc;
6654 wc.x = left;
6655 wc.y = top;
6656 wc.width = width;
6657 wc.height = height;
6658 XConfigureWindow (FRAME_X_DISPLAY (f), bar->x_window,
6659 mask, &wc);
6662 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6664 /* Remember new settings. */
6665 bar->left = left;
6666 bar->top = top;
6667 bar->width = width;
6668 bar->height = height;
6670 unblock_input ();
6673 #ifdef USE_TOOLKIT_SCROLL_BARS
6674 x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
6675 #else /* not USE_TOOLKIT_SCROLL_BARS */
6676 /* Set the scroll bar's current state, unless we're currently being
6677 dragged. */
6678 if (bar->dragging == -1)
6680 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, height);
6682 if (whole == 0)
6683 x_scroll_bar_set_handle (bar, 0, top_range, false);
6684 else
6686 int start = ((double) position * top_range) / whole;
6687 int end = ((double) (position + portion) * top_range) / whole;
6688 x_scroll_bar_set_handle (bar, start, end, false);
6691 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6693 XSETVECTOR (barobj, bar);
6694 wset_vertical_scroll_bar (w, barobj);
6698 static void
6699 XTset_horizontal_scroll_bar (struct window *w, int portion, int whole, int position)
6701 struct frame *f = XFRAME (w->frame);
6702 Lisp_Object barobj;
6703 struct scroll_bar *bar;
6704 int top, height, left, width;
6705 int window_x, window_width;
6706 int pixel_width = WINDOW_PIXEL_WIDTH (w);
6708 /* Get window dimensions. */
6709 window_box (w, ANY_AREA, &window_x, 0, &window_width, 0);
6710 left = window_x;
6711 width = window_width;
6712 top = WINDOW_SCROLL_BAR_AREA_Y (w);
6713 height = WINDOW_SCROLL_BAR_AREA_HEIGHT (w);
6715 /* Does the scroll bar exist yet? */
6716 if (NILP (w->horizontal_scroll_bar))
6718 if (width > 0 && height > 0)
6720 block_input ();
6722 /* Clear also part between window_width and
6723 WINDOW_PIXEL_WIDTH. */
6724 x_clear_area (f, left, top, pixel_width, height);
6725 unblock_input ();
6728 bar = x_scroll_bar_create (w, top, left, width, height, true);
6730 else
6732 /* It may just need to be moved and resized. */
6733 unsigned int mask = 0;
6735 bar = XSCROLL_BAR (w->horizontal_scroll_bar);
6737 block_input ();
6739 if (left != bar->left)
6740 mask |= CWX;
6741 if (top != bar->top)
6742 mask |= CWY;
6743 if (width != bar->width)
6744 mask |= CWWidth;
6745 if (height != bar->height)
6746 mask |= CWHeight;
6748 #ifdef USE_TOOLKIT_SCROLL_BARS
6749 /* Move/size the scroll bar widget. */
6750 if (mask)
6752 /* Since toolkit scroll bars are smaller than the space reserved
6753 for them on the frame, we have to clear "under" them. */
6754 if (width > 0 && height > 0)
6755 x_clear_area (f,
6756 WINDOW_LEFT_EDGE_X (w), top,
6757 pixel_width - WINDOW_RIGHT_DIVIDER_WIDTH (w), height);
6758 #ifdef USE_GTK
6759 xg_update_horizontal_scrollbar_pos (f, bar->x_window, top, left,
6760 width, height);
6761 #else /* not USE_GTK */
6762 XtConfigureWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar),
6763 left, top, width, height, 0);
6764 #endif /* not USE_GTK */
6766 #else /* not USE_TOOLKIT_SCROLL_BARS */
6768 /* Clear areas not covered by the scroll bar because it's not as
6769 wide as the area reserved for it. This makes sure a
6770 previous mode line display is cleared after C-x 2 C-x 1, for
6771 example. */
6773 int area_height = WINDOW_CONFIG_SCROLL_BAR_HEIGHT (w);
6774 int rest = area_height - height;
6775 if (rest > 0 && width > 0)
6776 x_clear_area (f, left, top, width, rest);
6779 /* Move/size the scroll bar window. */
6780 if (mask)
6782 XWindowChanges wc;
6784 wc.x = left;
6785 wc.y = top;
6786 wc.width = width;
6787 wc.height = height;
6788 XConfigureWindow (FRAME_X_DISPLAY (f), bar->x_window,
6789 mask, &wc);
6792 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6794 /* Remember new settings. */
6795 bar->left = left;
6796 bar->top = top;
6797 bar->width = width;
6798 bar->height = height;
6800 unblock_input ();
6803 #ifdef USE_TOOLKIT_SCROLL_BARS
6804 x_set_toolkit_horizontal_scroll_bar_thumb (bar, portion, position, whole);
6805 #else /* not USE_TOOLKIT_SCROLL_BARS */
6806 /* Set the scroll bar's current state, unless we're currently being
6807 dragged. */
6808 if (bar->dragging == -1)
6810 int left_range = HORIZONTAL_SCROLL_BAR_LEFT_RANGE (f, width);
6812 if (whole == 0)
6813 x_scroll_bar_set_handle (bar, 0, left_range, false);
6814 else
6816 int start = ((double) position * left_range) / whole;
6817 int end = ((double) (position + portion) * left_range) / whole;
6818 x_scroll_bar_set_handle (bar, start, end, false);
6821 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6823 XSETVECTOR (barobj, bar);
6824 wset_horizontal_scroll_bar (w, barobj);
6828 /* The following three hooks are used when we're doing a thorough
6829 redisplay of the frame. We don't explicitly know which scroll bars
6830 are going to be deleted, because keeping track of when windows go
6831 away is a real pain - "Can you say set-window-configuration, boys
6832 and girls?" Instead, we just assert at the beginning of redisplay
6833 that *all* scroll bars are to be removed, and then save a scroll bar
6834 from the fiery pit when we actually redisplay its window. */
6836 /* Arrange for all scroll bars on FRAME to be removed at the next call
6837 to `*judge_scroll_bars_hook'. A scroll bar may be spared if
6838 `*redeem_scroll_bar_hook' is applied to its window before the judgment. */
6840 static void
6841 XTcondemn_scroll_bars (struct frame *frame)
6843 if (!NILP (FRAME_SCROLL_BARS (frame)))
6845 if (!NILP (FRAME_CONDEMNED_SCROLL_BARS (frame)))
6847 /* Prepend scrollbars to already condemned ones. */
6848 Lisp_Object last = FRAME_SCROLL_BARS (frame);
6850 while (!NILP (XSCROLL_BAR (last)->next))
6851 last = XSCROLL_BAR (last)->next;
6853 XSCROLL_BAR (last)->next = FRAME_CONDEMNED_SCROLL_BARS (frame);
6854 XSCROLL_BAR (FRAME_CONDEMNED_SCROLL_BARS (frame))->prev = last;
6857 fset_condemned_scroll_bars (frame, FRAME_SCROLL_BARS (frame));
6858 fset_scroll_bars (frame, Qnil);
6863 /* Un-mark WINDOW's scroll bar for deletion in this judgment cycle.
6864 Note that WINDOW isn't necessarily condemned at all. */
6866 static void
6867 XTredeem_scroll_bar (struct window *w)
6869 struct scroll_bar *bar;
6870 Lisp_Object barobj;
6871 struct frame *f;
6873 /* We can't redeem this window's scroll bar if it doesn't have one. */
6874 if (NILP (w->vertical_scroll_bar) && NILP (w->horizontal_scroll_bar))
6875 emacs_abort ();
6877 if (!NILP (w->vertical_scroll_bar) && WINDOW_HAS_VERTICAL_SCROLL_BAR (w))
6879 bar = XSCROLL_BAR (w->vertical_scroll_bar);
6880 /* Unlink it from the condemned list. */
6881 f = XFRAME (WINDOW_FRAME (w));
6882 if (NILP (bar->prev))
6884 /* If the prev pointer is nil, it must be the first in one of
6885 the lists. */
6886 if (EQ (FRAME_SCROLL_BARS (f), w->vertical_scroll_bar))
6887 /* It's not condemned. Everything's fine. */
6888 goto horizontal;
6889 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
6890 w->vertical_scroll_bar))
6891 fset_condemned_scroll_bars (f, bar->next);
6892 else
6893 /* If its prev pointer is nil, it must be at the front of
6894 one or the other! */
6895 emacs_abort ();
6897 else
6898 XSCROLL_BAR (bar->prev)->next = bar->next;
6900 if (! NILP (bar->next))
6901 XSCROLL_BAR (bar->next)->prev = bar->prev;
6903 bar->next = FRAME_SCROLL_BARS (f);
6904 bar->prev = Qnil;
6905 XSETVECTOR (barobj, bar);
6906 fset_scroll_bars (f, barobj);
6907 if (! NILP (bar->next))
6908 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
6911 horizontal:
6912 if (!NILP (w->horizontal_scroll_bar) && WINDOW_HAS_HORIZONTAL_SCROLL_BAR (w))
6914 bar = XSCROLL_BAR (w->horizontal_scroll_bar);
6915 /* Unlink it from the condemned list. */
6916 f = XFRAME (WINDOW_FRAME (w));
6917 if (NILP (bar->prev))
6919 /* If the prev pointer is nil, it must be the first in one of
6920 the lists. */
6921 if (EQ (FRAME_SCROLL_BARS (f), w->horizontal_scroll_bar))
6922 /* It's not condemned. Everything's fine. */
6923 return;
6924 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
6925 w->horizontal_scroll_bar))
6926 fset_condemned_scroll_bars (f, bar->next);
6927 else
6928 /* If its prev pointer is nil, it must be at the front of
6929 one or the other! */
6930 emacs_abort ();
6932 else
6933 XSCROLL_BAR (bar->prev)->next = bar->next;
6935 if (! NILP (bar->next))
6936 XSCROLL_BAR (bar->next)->prev = bar->prev;
6938 bar->next = FRAME_SCROLL_BARS (f);
6939 bar->prev = Qnil;
6940 XSETVECTOR (barobj, bar);
6941 fset_scroll_bars (f, barobj);
6942 if (! NILP (bar->next))
6943 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
6947 /* Remove all scroll bars on FRAME that haven't been saved since the
6948 last call to `*condemn_scroll_bars_hook'. */
6950 static void
6951 XTjudge_scroll_bars (struct frame *f)
6953 Lisp_Object bar, next;
6955 bar = FRAME_CONDEMNED_SCROLL_BARS (f);
6957 /* Clear out the condemned list now so we won't try to process any
6958 more events on the hapless scroll bars. */
6959 fset_condemned_scroll_bars (f, Qnil);
6961 for (; ! NILP (bar); bar = next)
6963 struct scroll_bar *b = XSCROLL_BAR (bar);
6965 x_scroll_bar_remove (b);
6967 next = b->next;
6968 b->next = b->prev = Qnil;
6971 /* Now there should be no references to the condemned scroll bars,
6972 and they should get garbage-collected. */
6976 #ifndef USE_TOOLKIT_SCROLL_BARS
6977 /* Handle an Expose or GraphicsExpose event on a scroll bar. This
6978 is a no-op when using toolkit scroll bars.
6980 This may be called from a signal handler, so we have to ignore GC
6981 mark bits. */
6983 static void
6984 x_scroll_bar_expose (struct scroll_bar *bar, const XEvent *event)
6986 Window w = bar->x_window;
6987 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6988 GC gc = f->output_data.x->normal_gc;
6990 block_input ();
6992 x_scroll_bar_set_handle (bar, bar->start, bar->end, true);
6994 /* Switch to scroll bar foreground color. */
6995 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
6996 XSetForeground (FRAME_X_DISPLAY (f), gc,
6997 f->output_data.x->scroll_bar_foreground_pixel);
6999 /* Draw a one-pixel border just inside the edges of the scroll bar. */
7000 XDrawRectangle (FRAME_X_DISPLAY (f), w, gc,
7001 /* x, y, width, height */
7002 0, 0, bar->width - 1, bar->height - 1);
7004 /* Restore the foreground color of the GC if we changed it above. */
7005 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
7006 XSetForeground (FRAME_X_DISPLAY (f), gc,
7007 FRAME_FOREGROUND_PIXEL (f));
7009 unblock_input ();
7012 #endif /* not USE_TOOLKIT_SCROLL_BARS */
7014 /* Handle a mouse click on the scroll bar BAR. If *EMACS_EVENT's kind
7015 is set to something other than NO_EVENT, it is enqueued.
7017 This may be called from a signal handler, so we have to ignore GC
7018 mark bits. */
7021 static void
7022 x_scroll_bar_handle_click (struct scroll_bar *bar,
7023 const XEvent *event,
7024 struct input_event *emacs_event)
7026 if (! WINDOWP (bar->window))
7027 emacs_abort ();
7029 emacs_event->kind = (bar->horizontal
7030 ? HORIZONTAL_SCROLL_BAR_CLICK_EVENT
7031 : SCROLL_BAR_CLICK_EVENT);
7032 emacs_event->code = event->xbutton.button - Button1;
7033 emacs_event->modifiers
7034 = (x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO
7035 (XFRAME (WINDOW_FRAME (XWINDOW (bar->window)))),
7036 event->xbutton.state)
7037 | (event->type == ButtonRelease
7038 ? up_modifier
7039 : down_modifier));
7040 emacs_event->frame_or_window = bar->window;
7041 emacs_event->arg = Qnil;
7042 emacs_event->timestamp = event->xbutton.time;
7043 if (bar->horizontal)
7045 int left_range
7046 = HORIZONTAL_SCROLL_BAR_LEFT_RANGE (f, bar->width);
7047 int x = event->xbutton.x - HORIZONTAL_SCROLL_BAR_LEFT_BORDER;
7049 if (x < 0) x = 0;
7050 if (x > left_range) x = left_range;
7052 if (x < bar->start)
7053 emacs_event->part = scroll_bar_before_handle;
7054 else if (x < bar->end + HORIZONTAL_SCROLL_BAR_MIN_HANDLE)
7055 emacs_event->part = scroll_bar_horizontal_handle;
7056 else
7057 emacs_event->part = scroll_bar_after_handle;
7059 #ifndef USE_TOOLKIT_SCROLL_BARS
7060 /* If the user has released the handle, set it to its final position. */
7061 if (event->type == ButtonRelease && bar->dragging != -1)
7063 int new_start = - bar->dragging;
7064 int new_end = new_start + bar->end - bar->start;
7066 x_scroll_bar_set_handle (bar, new_start, new_end, false);
7067 bar->dragging = -1;
7069 #endif
7071 XSETINT (emacs_event->x, left_range);
7072 XSETINT (emacs_event->y, x);
7074 else
7076 int top_range
7077 = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
7078 int y = event->xbutton.y - VERTICAL_SCROLL_BAR_TOP_BORDER;
7080 if (y < 0) y = 0;
7081 if (y > top_range) y = top_range;
7083 if (y < bar->start)
7084 emacs_event->part = scroll_bar_above_handle;
7085 else if (y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
7086 emacs_event->part = scroll_bar_handle;
7087 else
7088 emacs_event->part = scroll_bar_below_handle;
7090 #ifndef USE_TOOLKIT_SCROLL_BARS
7091 /* If the user has released the handle, set it to its final position. */
7092 if (event->type == ButtonRelease && bar->dragging != -1)
7094 int new_start = y - bar->dragging;
7095 int new_end = new_start + bar->end - bar->start;
7097 x_scroll_bar_set_handle (bar, new_start, new_end, false);
7098 bar->dragging = -1;
7100 #endif
7102 XSETINT (emacs_event->x, y);
7103 XSETINT (emacs_event->y, top_range);
7107 #ifndef USE_TOOLKIT_SCROLL_BARS
7109 /* Handle some mouse motion while someone is dragging the scroll bar.
7111 This may be called from a signal handler, so we have to ignore GC
7112 mark bits. */
7114 static void
7115 x_scroll_bar_note_movement (struct scroll_bar *bar,
7116 const XMotionEvent *event)
7118 struct frame *f = XFRAME (XWINDOW (bar->window)->frame);
7119 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
7121 dpyinfo->last_mouse_movement_time = event->time;
7122 dpyinfo->last_mouse_scroll_bar = bar;
7123 f->mouse_moved = true;
7125 /* If we're dragging the bar, display it. */
7126 if (bar->dragging != -1)
7128 /* Where should the handle be now? */
7129 int new_start = event->y - bar->dragging;
7131 if (new_start != bar->start)
7133 int new_end = new_start + bar->end - bar->start;
7135 x_scroll_bar_set_handle (bar, new_start, new_end, false);
7140 #endif /* !USE_TOOLKIT_SCROLL_BARS */
7142 /* Return information to the user about the current position of the mouse
7143 on the scroll bar. */
7145 static void
7146 x_scroll_bar_report_motion (struct frame **fp, Lisp_Object *bar_window,
7147 enum scroll_bar_part *part, Lisp_Object *x,
7148 Lisp_Object *y, Time *timestamp)
7150 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (*fp);
7151 struct scroll_bar *bar = dpyinfo->last_mouse_scroll_bar;
7152 Window w = bar->x_window;
7153 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
7154 int win_x, win_y;
7155 Window dummy_window;
7156 int dummy_coord;
7157 unsigned int dummy_mask;
7159 block_input ();
7161 /* Get the mouse's position relative to the scroll bar window, and
7162 report that. */
7163 if (XQueryPointer (FRAME_X_DISPLAY (f), w,
7165 /* Root, child, root x and root y. */
7166 &dummy_window, &dummy_window,
7167 &dummy_coord, &dummy_coord,
7169 /* Position relative to scroll bar. */
7170 &win_x, &win_y,
7172 /* Mouse buttons and modifier keys. */
7173 &dummy_mask))
7175 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
7177 win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
7179 if (bar->dragging != -1)
7180 win_y -= bar->dragging;
7182 if (win_y < 0)
7183 win_y = 0;
7184 if (win_y > top_range)
7185 win_y = top_range;
7187 *fp = f;
7188 *bar_window = bar->window;
7190 if (bar->dragging != -1)
7191 *part = scroll_bar_handle;
7192 else if (win_y < bar->start)
7193 *part = scroll_bar_above_handle;
7194 else if (win_y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
7195 *part = scroll_bar_handle;
7196 else
7197 *part = scroll_bar_below_handle;
7199 XSETINT (*x, win_y);
7200 XSETINT (*y, top_range);
7202 f->mouse_moved = false;
7203 dpyinfo->last_mouse_scroll_bar = NULL;
7204 *timestamp = dpyinfo->last_mouse_movement_time;
7207 unblock_input ();
7211 /* Return information to the user about the current position of the mouse
7212 on the scroll bar. */
7214 static void
7215 x_horizontal_scroll_bar_report_motion (struct frame **fp, Lisp_Object *bar_window,
7216 enum scroll_bar_part *part, Lisp_Object *x,
7217 Lisp_Object *y, Time *timestamp)
7219 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (*fp);
7220 struct scroll_bar *bar = dpyinfo->last_mouse_scroll_bar;
7221 Window w = bar->x_window;
7222 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
7223 int win_x, win_y;
7224 Window dummy_window;
7225 int dummy_coord;
7226 unsigned int dummy_mask;
7228 block_input ();
7230 /* Get the mouse's position relative to the scroll bar window, and
7231 report that. */
7232 if (XQueryPointer (FRAME_X_DISPLAY (f), w,
7234 /* Root, child, root x and root y. */
7235 &dummy_window, &dummy_window,
7236 &dummy_coord, &dummy_coord,
7238 /* Position relative to scroll bar. */
7239 &win_x, &win_y,
7241 /* Mouse buttons and modifier keys. */
7242 &dummy_mask))
7244 int left_range = HORIZONTAL_SCROLL_BAR_LEFT_RANGE (f, bar->width);
7246 win_x -= HORIZONTAL_SCROLL_BAR_LEFT_BORDER;
7248 if (bar->dragging != -1)
7249 win_x -= bar->dragging;
7251 if (win_x < 0)
7252 win_x = 0;
7253 if (win_x > left_range)
7254 win_x = left_range;
7256 *fp = f;
7257 *bar_window = bar->window;
7259 if (bar->dragging != -1)
7260 *part = scroll_bar_horizontal_handle;
7261 else if (win_x < bar->start)
7262 *part = scroll_bar_before_handle;
7263 else if (win_x < bar->end + HORIZONTAL_SCROLL_BAR_MIN_HANDLE)
7264 *part = scroll_bar_handle;
7265 else
7266 *part = scroll_bar_after_handle;
7268 XSETINT (*y, win_x);
7269 XSETINT (*x, left_range);
7271 f->mouse_moved = false;
7272 dpyinfo->last_mouse_scroll_bar = NULL;
7273 *timestamp = dpyinfo->last_mouse_movement_time;
7276 unblock_input ();
7280 /* The screen has been cleared so we may have changed foreground or
7281 background colors, and the scroll bars may need to be redrawn.
7282 Clear out the scroll bars, and ask for expose events, so we can
7283 redraw them. */
7285 static void
7286 x_scroll_bar_clear (struct frame *f)
7288 #ifndef USE_TOOLKIT_SCROLL_BARS
7289 Lisp_Object bar;
7291 /* We can have scroll bars even if this is 0,
7292 if we just turned off scroll bar mode.
7293 But in that case we should not clear them. */
7294 if (FRAME_HAS_VERTICAL_SCROLL_BARS (f))
7295 for (bar = FRAME_SCROLL_BARS (f); VECTORP (bar);
7296 bar = XSCROLL_BAR (bar)->next)
7297 XClearArea (FRAME_X_DISPLAY (f),
7298 XSCROLL_BAR (bar)->x_window,
7299 0, 0, 0, 0, True);
7300 #endif /* not USE_TOOLKIT_SCROLL_BARS */
7303 #ifdef ENABLE_CHECKING
7305 /* Record the last 100 characters stored
7306 to help debug the loss-of-chars-during-GC problem. */
7308 static int temp_index;
7309 static short temp_buffer[100];
7311 #define STORE_KEYSYM_FOR_DEBUG(keysym) \
7312 if (temp_index == ARRAYELTS (temp_buffer)) \
7313 temp_index = 0; \
7314 temp_buffer[temp_index++] = (keysym)
7316 #else /* not ENABLE_CHECKING */
7318 #define STORE_KEYSYM_FOR_DEBUG(keysym) ((void)0)
7320 #endif /* ENABLE_CHECKING */
7322 /* Set this to nonzero to fake an "X I/O error"
7323 on a particular display. */
7325 static struct x_display_info *XTread_socket_fake_io_error;
7327 /* When we find no input here, we occasionally do a no-op command
7328 to verify that the X server is still running and we can still talk with it.
7329 We try all the open displays, one by one.
7330 This variable is used for cycling thru the displays. */
7332 static struct x_display_info *next_noop_dpyinfo;
7334 enum
7336 X_EVENT_NORMAL,
7337 X_EVENT_GOTO_OUT,
7338 X_EVENT_DROP
7341 /* Filter events for the current X input method.
7342 DPYINFO is the display this event is for.
7343 EVENT is the X event to filter.
7345 Returns non-zero if the event was filtered, caller shall not process
7346 this event further.
7347 Returns zero if event is wasn't filtered. */
7349 #ifdef HAVE_X_I18N
7350 static int
7351 x_filter_event (struct x_display_info *dpyinfo, XEvent *event)
7353 /* XFilterEvent returns non-zero if the input method has
7354 consumed the event. We pass the frame's X window to
7355 XFilterEvent because that's the one for which the IC
7356 was created. */
7358 struct frame *f1 = x_any_window_to_frame (dpyinfo,
7359 event->xclient.window);
7361 return XFilterEvent (event, f1 ? FRAME_X_WINDOW (f1) : None);
7363 #endif
7365 #ifdef USE_GTK
7366 static int current_count;
7367 static int current_finish;
7368 static struct input_event *current_hold_quit;
7370 /* This is the filter function invoked by the GTK event loop.
7371 It is invoked before the XEvent is translated to a GdkEvent,
7372 so we have a chance to act on the event before GTK. */
7373 static GdkFilterReturn
7374 event_handler_gdk (GdkXEvent *gxev, GdkEvent *ev, gpointer data)
7376 XEvent *xev = (XEvent *) gxev;
7378 block_input ();
7379 if (current_count >= 0)
7381 struct x_display_info *dpyinfo;
7383 dpyinfo = x_display_info_for_display (xev->xany.display);
7385 #ifdef HAVE_X_I18N
7386 /* Filter events for the current X input method.
7387 GTK calls XFilterEvent but not for key press and release,
7388 so we do it here. */
7389 if ((xev->type == KeyPress || xev->type == KeyRelease)
7390 && dpyinfo
7391 && x_filter_event (dpyinfo, xev))
7393 unblock_input ();
7394 return GDK_FILTER_REMOVE;
7396 #endif
7398 if (! dpyinfo)
7399 current_finish = X_EVENT_NORMAL;
7400 else
7401 current_count
7402 += handle_one_xevent (dpyinfo, xev, &current_finish,
7403 current_hold_quit);
7405 else
7406 current_finish = x_dispatch_event (xev, xev->xany.display);
7408 unblock_input ();
7410 if (current_finish == X_EVENT_GOTO_OUT || current_finish == X_EVENT_DROP)
7411 return GDK_FILTER_REMOVE;
7413 return GDK_FILTER_CONTINUE;
7415 #endif /* USE_GTK */
7418 static void xembed_send_message (struct frame *f, Time,
7419 enum xembed_message,
7420 long detail, long data1, long data2);
7422 static void
7423 x_net_wm_state (struct frame *f, Window window)
7425 int value = FULLSCREEN_NONE;
7426 Lisp_Object lval = Qnil;
7427 bool sticky = false;
7429 get_current_wm_state (f, window, &value, &sticky);
7431 switch (value)
7433 case FULLSCREEN_WIDTH:
7434 lval = Qfullwidth;
7435 break;
7436 case FULLSCREEN_HEIGHT:
7437 lval = Qfullheight;
7438 break;
7439 case FULLSCREEN_BOTH:
7440 lval = Qfullboth;
7441 break;
7442 case FULLSCREEN_MAXIMIZED:
7443 lval = Qmaximized;
7444 break;
7447 frame_size_history_add
7448 (f, Qx_net_wm_state, 0, 0,
7449 list2 (get_frame_param (f, Qfullscreen), lval));
7451 store_frame_param (f, Qfullscreen, lval);
7452 /** store_frame_param (f, Qsticky, sticky ? Qt : Qnil); **/
7455 /* Handles the XEvent EVENT on display DPYINFO.
7457 *FINISH is X_EVENT_GOTO_OUT if caller should stop reading events.
7458 *FINISH is zero if caller should continue reading events.
7459 *FINISH is X_EVENT_DROP if event should not be passed to the toolkit.
7460 *EVENT is unchanged unless we're processing KeyPress event.
7462 We return the number of characters stored into the buffer. */
7464 static int
7465 handle_one_xevent (struct x_display_info *dpyinfo,
7466 const XEvent *event,
7467 int *finish, struct input_event *hold_quit)
7469 union buffered_input_event inev;
7470 int count = 0;
7471 int do_help = 0;
7472 ptrdiff_t nbytes = 0;
7473 struct frame *any, *f = NULL;
7474 struct coding_system coding;
7475 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
7476 /* This holds the state XLookupString needs to implement dead keys
7477 and other tricks known as "compose processing". _X Window System_
7478 says that a portable program can't use this, but Stephen Gildea assures
7479 me that letting the compiler initialize it to zeros will work okay. */
7480 static XComposeStatus compose_status;
7481 XEvent configureEvent;
7482 XEvent next_event;
7484 USE_SAFE_ALLOCA;
7486 *finish = X_EVENT_NORMAL;
7488 EVENT_INIT (inev.ie);
7489 inev.ie.kind = NO_EVENT;
7490 inev.ie.arg = Qnil;
7492 any = x_any_window_to_frame (dpyinfo, event->xany.window);
7494 if (any && any->wait_event_type == event->type)
7495 any->wait_event_type = 0; /* Indicates we got it. */
7497 switch (event->type)
7499 case ClientMessage:
7501 if (event->xclient.message_type == dpyinfo->Xatom_wm_protocols
7502 && event->xclient.format == 32)
7504 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_take_focus)
7506 /* Use the value returned by x_any_window_to_frame
7507 because this could be the shell widget window
7508 if the frame has no title bar. */
7509 f = any;
7510 #ifdef HAVE_X_I18N
7511 /* Not quite sure this is needed -pd */
7512 if (f && FRAME_XIC (f))
7513 XSetICFocus (FRAME_XIC (f));
7514 #endif
7515 #if false
7516 /* Emacs sets WM hints whose `input' field is `true'. This
7517 instructs the WM to set the input focus automatically for
7518 Emacs with a call to XSetInputFocus. Setting WM_TAKE_FOCUS
7519 tells the WM to send us a ClientMessage WM_TAKE_FOCUS after
7520 it has set the focus. So, XSetInputFocus below is not
7521 needed.
7523 The call to XSetInputFocus below has also caused trouble. In
7524 cases where the XSetInputFocus done by the WM and the one
7525 below are temporally close (on a fast machine), the call
7526 below can generate additional FocusIn events which confuse
7527 Emacs. */
7529 /* Since we set WM_TAKE_FOCUS, we must call
7530 XSetInputFocus explicitly. But not if f is null,
7531 since that might be an event for a deleted frame. */
7532 if (f)
7534 Display *d = event->xclient.display;
7535 /* Catch and ignore errors, in case window has been
7536 iconified by a window manager such as GWM. */
7537 x_catch_errors (d);
7538 XSetInputFocus (d, event->xclient.window,
7539 /* The ICCCM says this is
7540 the only valid choice. */
7541 RevertToParent,
7542 event->xclient.data.l[1]);
7543 x_uncatch_errors ();
7545 /* Not certain about handling scroll bars here */
7546 #endif
7547 goto done;
7550 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_save_yourself)
7552 /* Save state modify the WM_COMMAND property to
7553 something which can reinstate us. This notifies
7554 the session manager, who's looking for such a
7555 PropertyNotify. Can restart processing when
7556 a keyboard or mouse event arrives. */
7557 /* If we have a session manager, don't set this.
7558 KDE will then start two Emacsen, one for the
7559 session manager and one for this. */
7560 #ifdef HAVE_X_SM
7561 if (! x_session_have_connection ())
7562 #endif
7564 f = x_top_window_to_frame (dpyinfo,
7565 event->xclient.window);
7566 /* This is just so we only give real data once
7567 for a single Emacs process. */
7568 if (f == SELECTED_FRAME ())
7569 XSetCommand (FRAME_X_DISPLAY (f),
7570 event->xclient.window,
7571 initial_argv, initial_argc);
7572 else if (f)
7573 XSetCommand (FRAME_X_DISPLAY (f),
7574 event->xclient.window,
7575 0, 0);
7577 goto done;
7580 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_delete_window)
7582 f = any;
7583 if (!f)
7584 goto OTHER; /* May be a dialog that is to be removed */
7586 inev.ie.kind = DELETE_WINDOW_EVENT;
7587 XSETFRAME (inev.ie.frame_or_window, f);
7588 goto done;
7591 goto done;
7594 if (event->xclient.message_type == dpyinfo->Xatom_wm_configure_denied)
7595 goto done;
7597 if (event->xclient.message_type == dpyinfo->Xatom_wm_window_moved)
7599 int new_x, new_y;
7600 f = x_window_to_frame (dpyinfo, event->xclient.window);
7602 new_x = event->xclient.data.s[0];
7603 new_y = event->xclient.data.s[1];
7605 if (f)
7607 f->left_pos = new_x;
7608 f->top_pos = new_y;
7610 goto done;
7613 #ifdef HACK_EDITRES
7614 if (event->xclient.message_type == dpyinfo->Xatom_editres)
7616 f = any;
7617 if (f)
7618 _XEditResCheckMessages (f->output_data.x->widget,
7619 NULL, (XEvent *) event, NULL);
7620 goto done;
7622 #endif /* HACK_EDITRES */
7624 if (event->xclient.message_type == dpyinfo->Xatom_DONE
7625 || event->xclient.message_type == dpyinfo->Xatom_PAGE)
7627 /* Ghostview job completed. Kill it. We could
7628 reply with "Next" if we received "Page", but we
7629 currently never do because we are interested in
7630 images, only, which should have 1 page. */
7631 Pixmap pixmap = (Pixmap) event->xclient.data.l[1];
7632 f = x_window_to_frame (dpyinfo, event->xclient.window);
7633 if (!f)
7634 goto OTHER;
7635 x_kill_gs_process (pixmap, f);
7636 expose_frame (f, 0, 0, 0, 0);
7637 goto done;
7640 #ifdef USE_TOOLKIT_SCROLL_BARS
7641 /* Scroll bar callbacks send a ClientMessage from which
7642 we construct an input_event. */
7643 if (event->xclient.message_type == dpyinfo->Xatom_Scrollbar)
7645 x_scroll_bar_to_input_event (event, &inev.ie);
7646 *finish = X_EVENT_GOTO_OUT;
7647 goto done;
7649 else if (event->xclient.message_type == dpyinfo->Xatom_Horizontal_Scrollbar)
7651 x_horizontal_scroll_bar_to_input_event (event, &inev.ie);
7652 *finish = X_EVENT_GOTO_OUT;
7653 goto done;
7655 #endif /* USE_TOOLKIT_SCROLL_BARS */
7657 /* XEmbed messages from the embedder (if any). */
7658 if (event->xclient.message_type == dpyinfo->Xatom_XEMBED)
7660 enum xembed_message msg = event->xclient.data.l[1];
7661 if (msg == XEMBED_FOCUS_IN || msg == XEMBED_FOCUS_OUT)
7662 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
7664 *finish = X_EVENT_GOTO_OUT;
7665 goto done;
7668 xft_settings_event (dpyinfo, event);
7670 f = any;
7671 if (!f)
7672 goto OTHER;
7673 if (x_handle_dnd_message (f, &event->xclient, dpyinfo, &inev.ie))
7674 *finish = X_EVENT_DROP;
7676 break;
7678 case SelectionNotify:
7679 x_display_set_last_user_time (dpyinfo, event->xselection.time);
7680 #ifdef USE_X_TOOLKIT
7681 if (! x_window_to_frame (dpyinfo, event->xselection.requestor))
7682 goto OTHER;
7683 #endif /* not USE_X_TOOLKIT */
7684 x_handle_selection_notify (&event->xselection);
7685 break;
7687 case SelectionClear: /* Someone has grabbed ownership. */
7688 x_display_set_last_user_time (dpyinfo, event->xselectionclear.time);
7689 #ifdef USE_X_TOOLKIT
7690 if (! x_window_to_frame (dpyinfo, event->xselectionclear.window))
7691 goto OTHER;
7692 #endif /* USE_X_TOOLKIT */
7694 const XSelectionClearEvent *eventp = &event->xselectionclear;
7696 inev.sie.kind = SELECTION_CLEAR_EVENT;
7697 SELECTION_EVENT_DPYINFO (&inev.sie) = dpyinfo;
7698 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
7699 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
7701 break;
7703 case SelectionRequest: /* Someone wants our selection. */
7704 x_display_set_last_user_time (dpyinfo, event->xselectionrequest.time);
7705 #ifdef USE_X_TOOLKIT
7706 if (!x_window_to_frame (dpyinfo, event->xselectionrequest.owner))
7707 goto OTHER;
7708 #endif /* USE_X_TOOLKIT */
7710 const XSelectionRequestEvent *eventp = &event->xselectionrequest;
7712 inev.sie.kind = SELECTION_REQUEST_EVENT;
7713 SELECTION_EVENT_DPYINFO (&inev.sie) = dpyinfo;
7714 SELECTION_EVENT_REQUESTOR (&inev.sie) = eventp->requestor;
7715 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
7716 SELECTION_EVENT_TARGET (&inev.sie) = eventp->target;
7717 SELECTION_EVENT_PROPERTY (&inev.sie) = eventp->property;
7718 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
7720 break;
7722 case PropertyNotify:
7723 x_display_set_last_user_time (dpyinfo, event->xproperty.time);
7724 f = x_top_window_to_frame (dpyinfo, event->xproperty.window);
7725 if (f && event->xproperty.atom == dpyinfo->Xatom_net_wm_state)
7727 bool not_hidden = x_handle_net_wm_state (f, &event->xproperty);
7728 if (not_hidden && FRAME_ICONIFIED_P (f))
7730 /* Gnome shell does not iconify us when C-z is pressed.
7731 It hides the frame. So if our state says we aren't
7732 hidden anymore, treat it as deiconified. */
7733 SET_FRAME_VISIBLE (f, 1);
7734 SET_FRAME_ICONIFIED (f, false);
7735 f->output_data.x->has_been_visible = true;
7736 inev.ie.kind = DEICONIFY_EVENT;
7737 XSETFRAME (inev.ie.frame_or_window, f);
7739 else if (! not_hidden && ! FRAME_ICONIFIED_P (f))
7741 SET_FRAME_VISIBLE (f, 0);
7742 SET_FRAME_ICONIFIED (f, true);
7743 inev.ie.kind = ICONIFY_EVENT;
7744 XSETFRAME (inev.ie.frame_or_window, f);
7748 x_handle_property_notify (&event->xproperty);
7749 xft_settings_event (dpyinfo, event);
7750 goto OTHER;
7752 case ReparentNotify:
7753 f = x_top_window_to_frame (dpyinfo, event->xreparent.window);
7754 if (f)
7756 f->output_data.x->parent_desc = event->xreparent.parent;
7757 x_real_positions (f, &f->left_pos, &f->top_pos);
7759 /* Perhaps reparented due to a WM restart. Reset this. */
7760 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_UNKNOWN;
7761 FRAME_DISPLAY_INFO (f)->net_supported_window = 0;
7763 x_set_frame_alpha (f);
7765 goto OTHER;
7767 case Expose:
7768 f = x_window_to_frame (dpyinfo, event->xexpose.window);
7769 if (f)
7771 if (!FRAME_VISIBLE_P (f))
7773 SET_FRAME_VISIBLE (f, 1);
7774 SET_FRAME_ICONIFIED (f, false);
7775 f->output_data.x->has_been_visible = true;
7776 SET_FRAME_GARBAGED (f);
7778 else
7780 #ifdef USE_GTK
7781 /* This seems to be needed for GTK 2.6 and later, see
7782 http://debbugs.gnu.org/cgi/bugreport.cgi?bug=15398. */
7783 x_clear_area (f,
7784 event->xexpose.x, event->xexpose.y,
7785 event->xexpose.width, event->xexpose.height);
7786 #endif
7787 expose_frame (f, event->xexpose.x, event->xexpose.y,
7788 event->xexpose.width, event->xexpose.height);
7791 else
7793 #ifndef USE_TOOLKIT_SCROLL_BARS
7794 struct scroll_bar *bar;
7795 #endif
7796 #if defined USE_LUCID
7797 /* Submenus of the Lucid menu bar aren't widgets
7798 themselves, so there's no way to dispatch events
7799 to them. Recognize this case separately. */
7801 Widget widget = x_window_to_menu_bar (event->xexpose.window);
7802 if (widget)
7803 xlwmenu_redisplay (widget);
7805 #endif /* USE_LUCID */
7807 #ifdef USE_TOOLKIT_SCROLL_BARS
7808 /* Dispatch event to the widget. */
7809 goto OTHER;
7810 #else /* not USE_TOOLKIT_SCROLL_BARS */
7811 bar = x_window_to_scroll_bar (event->xexpose.display,
7812 event->xexpose.window, 2);
7814 if (bar)
7815 x_scroll_bar_expose (bar, event);
7816 #ifdef USE_X_TOOLKIT
7817 else
7818 goto OTHER;
7819 #endif /* USE_X_TOOLKIT */
7820 #endif /* not USE_TOOLKIT_SCROLL_BARS */
7822 break;
7824 case GraphicsExpose: /* This occurs when an XCopyArea's
7825 source area was obscured or not
7826 available. */
7827 f = x_window_to_frame (dpyinfo, event->xgraphicsexpose.drawable);
7828 if (f)
7829 expose_frame (f, event->xgraphicsexpose.x,
7830 event->xgraphicsexpose.y,
7831 event->xgraphicsexpose.width,
7832 event->xgraphicsexpose.height);
7833 #ifdef USE_X_TOOLKIT
7834 else
7835 goto OTHER;
7836 #endif /* USE_X_TOOLKIT */
7837 break;
7839 case NoExpose: /* This occurs when an XCopyArea's
7840 source area was completely
7841 available. */
7842 break;
7844 case UnmapNotify:
7845 /* Redo the mouse-highlight after the tooltip has gone. */
7846 if (event->xunmap.window == tip_window)
7848 tip_window = 0;
7849 x_redo_mouse_highlight (dpyinfo);
7852 f = x_top_window_to_frame (dpyinfo, event->xunmap.window);
7853 if (f) /* F may no longer exist if
7854 the frame was deleted. */
7856 bool visible = FRAME_VISIBLE_P (f);
7857 /* While a frame is unmapped, display generation is
7858 disabled; you don't want to spend time updating a
7859 display that won't ever be seen. */
7860 SET_FRAME_VISIBLE (f, 0);
7861 /* We can't distinguish, from the event, whether the window
7862 has become iconified or invisible. So assume, if it
7863 was previously visible, than now it is iconified.
7864 But x_make_frame_invisible clears both
7865 the visible flag and the iconified flag;
7866 and that way, we know the window is not iconified now. */
7867 if (visible || FRAME_ICONIFIED_P (f))
7869 SET_FRAME_ICONIFIED (f, true);
7870 inev.ie.kind = ICONIFY_EVENT;
7871 XSETFRAME (inev.ie.frame_or_window, f);
7874 goto OTHER;
7876 case MapNotify:
7877 /* We use x_top_window_to_frame because map events can
7878 come for sub-windows and they don't mean that the
7879 frame is visible. */
7880 f = x_top_window_to_frame (dpyinfo, event->xmap.window);
7881 if (f)
7883 bool iconified = FRAME_ICONIFIED_P (f);
7885 /* Check if fullscreen was specified before we where mapped the
7886 first time, i.e. from the command line. */
7887 if (!f->output_data.x->has_been_visible)
7888 x_check_fullscreen (f);
7890 SET_FRAME_VISIBLE (f, 1);
7891 SET_FRAME_ICONIFIED (f, false);
7892 f->output_data.x->has_been_visible = true;
7894 if (iconified)
7896 inev.ie.kind = DEICONIFY_EVENT;
7897 XSETFRAME (inev.ie.frame_or_window, f);
7899 else if (! NILP (Vframe_list) && ! NILP (XCDR (Vframe_list)))
7900 /* Force a redisplay sooner or later to update the
7901 frame titles in case this is the second frame. */
7902 record_asynch_buffer_change ();
7904 goto OTHER;
7906 case KeyPress:
7908 x_display_set_last_user_time (dpyinfo, event->xkey.time);
7909 ignore_next_mouse_click_timeout = 0;
7911 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
7912 /* Dispatch KeyPress events when in menu. */
7913 if (popup_activated ())
7914 goto OTHER;
7915 #endif
7917 f = any;
7919 /* If mouse-highlight is an integer, input clears out
7920 mouse highlighting. */
7921 if (!hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight)
7922 #if ! defined (USE_GTK)
7923 && (f == 0
7924 || !EQ (f->tool_bar_window, hlinfo->mouse_face_window))
7925 #endif
7928 clear_mouse_face (hlinfo);
7929 hlinfo->mouse_face_hidden = true;
7932 #if defined USE_MOTIF && defined USE_TOOLKIT_SCROLL_BARS
7933 if (f == 0)
7935 /* Scroll bars consume key events, but we want
7936 the keys to go to the scroll bar's frame. */
7937 Widget widget = XtWindowToWidget (dpyinfo->display,
7938 event->xkey.window);
7939 if (widget && XmIsScrollBar (widget))
7941 widget = XtParent (widget);
7942 f = x_any_window_to_frame (dpyinfo, XtWindow (widget));
7945 #endif /* USE_MOTIF and USE_TOOLKIT_SCROLL_BARS */
7947 if (f != 0)
7949 KeySym keysym, orig_keysym;
7950 /* al%imercury@uunet.uu.net says that making this 81
7951 instead of 80 fixed a bug whereby meta chars made
7952 his Emacs hang.
7954 It seems that some version of XmbLookupString has
7955 a bug of not returning XBufferOverflow in
7956 status_return even if the input is too long to
7957 fit in 81 bytes. So, we must prepare sufficient
7958 bytes for copy_buffer. 513 bytes (256 chars for
7959 two-byte character set) seems to be a fairly good
7960 approximation. -- 2000.8.10 handa@etl.go.jp */
7961 unsigned char copy_buffer[513];
7962 unsigned char *copy_bufptr = copy_buffer;
7963 int copy_bufsiz = sizeof (copy_buffer);
7964 int modifiers;
7965 Lisp_Object coding_system = Qlatin_1;
7966 Lisp_Object c;
7967 /* Event will be modified. */
7968 XKeyEvent xkey = event->xkey;
7970 #ifdef USE_GTK
7971 /* Don't pass keys to GTK. A Tab will shift focus to the
7972 tool bar in GTK 2.4. Keys will still go to menus and
7973 dialogs because in that case popup_activated is nonzero
7974 (see above). */
7975 *finish = X_EVENT_DROP;
7976 #endif
7978 xkey.state |= x_emacs_to_x_modifiers (FRAME_DISPLAY_INFO (f),
7979 extra_keyboard_modifiers);
7980 modifiers = xkey.state;
7982 /* This will have to go some day... */
7984 /* make_lispy_event turns chars into control chars.
7985 Don't do it here because XLookupString is too eager. */
7986 xkey.state &= ~ControlMask;
7987 xkey.state &= ~(dpyinfo->meta_mod_mask
7988 | dpyinfo->super_mod_mask
7989 | dpyinfo->hyper_mod_mask
7990 | dpyinfo->alt_mod_mask);
7992 /* In case Meta is ComposeCharacter,
7993 clear its status. According to Markus Ehrnsperger
7994 Markus.Ehrnsperger@lehrstuhl-bross.physik.uni-muenchen.de
7995 this enables ComposeCharacter to work whether or
7996 not it is combined with Meta. */
7997 if (modifiers & dpyinfo->meta_mod_mask)
7998 memset (&compose_status, 0, sizeof (compose_status));
8000 #ifdef HAVE_X_I18N
8001 if (FRAME_XIC (f))
8003 Status status_return;
8005 coding_system = Vlocale_coding_system;
8006 nbytes = XmbLookupString (FRAME_XIC (f),
8007 &xkey, (char *) copy_bufptr,
8008 copy_bufsiz, &keysym,
8009 &status_return);
8010 if (status_return == XBufferOverflow)
8012 copy_bufsiz = nbytes + 1;
8013 copy_bufptr = alloca (copy_bufsiz);
8014 nbytes = XmbLookupString (FRAME_XIC (f),
8015 &xkey, (char *) copy_bufptr,
8016 copy_bufsiz, &keysym,
8017 &status_return);
8019 /* Xutf8LookupString is a new but already deprecated interface. -stef */
8020 if (status_return == XLookupNone)
8021 break;
8022 else if (status_return == XLookupChars)
8024 keysym = NoSymbol;
8025 modifiers = 0;
8027 else if (status_return != XLookupKeySym
8028 && status_return != XLookupBoth)
8029 emacs_abort ();
8031 else
8032 nbytes = XLookupString (&xkey, (char *) copy_bufptr,
8033 copy_bufsiz, &keysym,
8034 &compose_status);
8035 #else
8036 nbytes = XLookupString (&xkey, (char *) copy_bufptr,
8037 copy_bufsiz, &keysym,
8038 &compose_status);
8039 #endif
8041 /* If not using XIM/XIC, and a compose sequence is in progress,
8042 we break here. Otherwise, chars_matched is always 0. */
8043 if (compose_status.chars_matched > 0 && nbytes == 0)
8044 break;
8046 memset (&compose_status, 0, sizeof (compose_status));
8047 orig_keysym = keysym;
8049 /* Common for all keysym input events. */
8050 XSETFRAME (inev.ie.frame_or_window, f);
8051 inev.ie.modifiers
8052 = x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO (f), modifiers);
8053 inev.ie.timestamp = xkey.time;
8055 /* First deal with keysyms which have defined
8056 translations to characters. */
8057 if (keysym >= 32 && keysym < 128)
8058 /* Avoid explicitly decoding each ASCII character. */
8060 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
8061 inev.ie.code = keysym;
8062 goto done_keysym;
8065 /* Keysyms directly mapped to Unicode characters. */
8066 if (keysym >= 0x01000000 && keysym <= 0x0110FFFF)
8068 if (keysym < 0x01000080)
8069 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
8070 else
8071 inev.ie.kind = MULTIBYTE_CHAR_KEYSTROKE_EVENT;
8072 inev.ie.code = keysym & 0xFFFFFF;
8073 goto done_keysym;
8076 /* Now non-ASCII. */
8077 if (HASH_TABLE_P (Vx_keysym_table)
8078 && (c = Fgethash (make_number (keysym),
8079 Vx_keysym_table,
8080 Qnil),
8081 NATNUMP (c)))
8083 inev.ie.kind = (SINGLE_BYTE_CHAR_P (XFASTINT (c))
8084 ? ASCII_KEYSTROKE_EVENT
8085 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
8086 inev.ie.code = XFASTINT (c);
8087 goto done_keysym;
8090 /* Random non-modifier sorts of keysyms. */
8091 if (((keysym >= XK_BackSpace && keysym <= XK_Escape)
8092 || keysym == XK_Delete
8093 #ifdef XK_ISO_Left_Tab
8094 || (keysym >= XK_ISO_Left_Tab
8095 && keysym <= XK_ISO_Enter)
8096 #endif
8097 || IsCursorKey (keysym) /* 0xff50 <= x < 0xff60 */
8098 || IsMiscFunctionKey (keysym) /* 0xff60 <= x < VARIES */
8099 #ifdef HPUX
8100 /* This recognizes the "extended function
8101 keys". It seems there's no cleaner way.
8102 Test IsModifierKey to avoid handling
8103 mode_switch incorrectly. */
8104 || (XK_Select <= keysym && keysym < XK_KP_Space)
8105 #endif
8106 #ifdef XK_dead_circumflex
8107 || orig_keysym == XK_dead_circumflex
8108 #endif
8109 #ifdef XK_dead_grave
8110 || orig_keysym == XK_dead_grave
8111 #endif
8112 #ifdef XK_dead_tilde
8113 || orig_keysym == XK_dead_tilde
8114 #endif
8115 #ifdef XK_dead_diaeresis
8116 || orig_keysym == XK_dead_diaeresis
8117 #endif
8118 #ifdef XK_dead_macron
8119 || orig_keysym == XK_dead_macron
8120 #endif
8121 #ifdef XK_dead_degree
8122 || orig_keysym == XK_dead_degree
8123 #endif
8124 #ifdef XK_dead_acute
8125 || orig_keysym == XK_dead_acute
8126 #endif
8127 #ifdef XK_dead_cedilla
8128 || orig_keysym == XK_dead_cedilla
8129 #endif
8130 #ifdef XK_dead_breve
8131 || orig_keysym == XK_dead_breve
8132 #endif
8133 #ifdef XK_dead_ogonek
8134 || orig_keysym == XK_dead_ogonek
8135 #endif
8136 #ifdef XK_dead_caron
8137 || orig_keysym == XK_dead_caron
8138 #endif
8139 #ifdef XK_dead_doubleacute
8140 || orig_keysym == XK_dead_doubleacute
8141 #endif
8142 #ifdef XK_dead_abovedot
8143 || orig_keysym == XK_dead_abovedot
8144 #endif
8145 || IsKeypadKey (keysym) /* 0xff80 <= x < 0xffbe */
8146 || IsFunctionKey (keysym) /* 0xffbe <= x < 0xffe1 */
8147 /* Any "vendor-specific" key is ok. */
8148 || (orig_keysym & (1 << 28))
8149 || (keysym != NoSymbol && nbytes == 0))
8150 && ! (IsModifierKey (orig_keysym)
8151 /* The symbols from XK_ISO_Lock
8152 to XK_ISO_Last_Group_Lock
8153 don't have real modifiers but
8154 should be treated similarly to
8155 Mode_switch by Emacs. */
8156 #if defined XK_ISO_Lock && defined XK_ISO_Last_Group_Lock
8157 || (XK_ISO_Lock <= orig_keysym
8158 && orig_keysym <= XK_ISO_Last_Group_Lock)
8159 #endif
8162 STORE_KEYSYM_FOR_DEBUG (keysym);
8163 /* make_lispy_event will convert this to a symbolic
8164 key. */
8165 inev.ie.kind = NON_ASCII_KEYSTROKE_EVENT;
8166 inev.ie.code = keysym;
8167 goto done_keysym;
8170 { /* Raw bytes, not keysym. */
8171 ptrdiff_t i;
8172 int nchars, len;
8174 for (i = 0, nchars = 0; i < nbytes; i++)
8176 if (ASCII_CHAR_P (copy_bufptr[i]))
8177 nchars++;
8178 STORE_KEYSYM_FOR_DEBUG (copy_bufptr[i]);
8181 if (nchars < nbytes)
8183 /* Decode the input data. */
8185 /* The input should be decoded with `coding_system'
8186 which depends on which X*LookupString function
8187 we used just above and the locale. */
8188 setup_coding_system (coding_system, &coding);
8189 coding.src_multibyte = false;
8190 coding.dst_multibyte = true;
8191 /* The input is converted to events, thus we can't
8192 handle composition. Anyway, there's no XIM that
8193 gives us composition information. */
8194 coding.common_flags &= ~CODING_ANNOTATION_MASK;
8196 SAFE_NALLOCA (coding.destination, MAX_MULTIBYTE_LENGTH,
8197 nbytes);
8198 coding.dst_bytes = MAX_MULTIBYTE_LENGTH * nbytes;
8199 coding.mode |= CODING_MODE_LAST_BLOCK;
8200 decode_coding_c_string (&coding, copy_bufptr, nbytes, Qnil);
8201 nbytes = coding.produced;
8202 nchars = coding.produced_char;
8203 copy_bufptr = coding.destination;
8206 /* Convert the input data to a sequence of
8207 character events. */
8208 for (i = 0; i < nbytes; i += len)
8210 int ch;
8211 if (nchars == nbytes)
8212 ch = copy_bufptr[i], len = 1;
8213 else
8214 ch = STRING_CHAR_AND_LENGTH (copy_bufptr + i, len);
8215 inev.ie.kind = (SINGLE_BYTE_CHAR_P (ch)
8216 ? ASCII_KEYSTROKE_EVENT
8217 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
8218 inev.ie.code = ch;
8219 kbd_buffer_store_buffered_event (&inev, hold_quit);
8222 count += nchars;
8224 inev.ie.kind = NO_EVENT; /* Already stored above. */
8226 if (keysym == NoSymbol)
8227 break;
8229 /* FIXME: check side effects and remove this. */
8230 ((XEvent *) event)->xkey = xkey;
8232 done_keysym:
8233 #ifdef HAVE_X_I18N
8234 /* Don't dispatch this event since XtDispatchEvent calls
8235 XFilterEvent, and two calls in a row may freeze the
8236 client. */
8237 break;
8238 #else
8239 goto OTHER;
8240 #endif
8242 case KeyRelease:
8243 x_display_set_last_user_time (dpyinfo, event->xkey.time);
8244 #ifdef HAVE_X_I18N
8245 /* Don't dispatch this event since XtDispatchEvent calls
8246 XFilterEvent, and two calls in a row may freeze the
8247 client. */
8248 break;
8249 #else
8250 goto OTHER;
8251 #endif
8253 case EnterNotify:
8254 x_display_set_last_user_time (dpyinfo, event->xcrossing.time);
8255 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
8257 f = any;
8259 if (f && x_mouse_click_focus_ignore_position)
8260 ignore_next_mouse_click_timeout = event->xmotion.time + 200;
8262 /* EnterNotify counts as mouse movement,
8263 so update things that depend on mouse position. */
8264 if (f && !f->output_data.x->hourglass_p)
8265 note_mouse_movement (f, &event->xmotion);
8266 #ifdef USE_GTK
8267 /* We may get an EnterNotify on the buttons in the toolbar. In that
8268 case we moved out of any highlighted area and need to note this. */
8269 if (!f && dpyinfo->last_mouse_glyph_frame)
8270 note_mouse_movement (dpyinfo->last_mouse_glyph_frame, &event->xmotion);
8271 #endif
8272 goto OTHER;
8274 case FocusIn:
8275 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
8276 goto OTHER;
8278 case LeaveNotify:
8279 x_display_set_last_user_time (dpyinfo, event->xcrossing.time);
8280 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
8282 f = x_top_window_to_frame (dpyinfo, event->xcrossing.window);
8283 if (f)
8285 if (f == hlinfo->mouse_face_mouse_frame)
8287 /* If we move outside the frame, then we're
8288 certainly no longer on any text in the frame. */
8289 clear_mouse_face (hlinfo);
8290 hlinfo->mouse_face_mouse_frame = 0;
8293 /* Generate a nil HELP_EVENT to cancel a help-echo.
8294 Do it only if there's something to cancel.
8295 Otherwise, the startup message is cleared when
8296 the mouse leaves the frame. */
8297 if (any_help_event_p)
8298 do_help = -1;
8300 #ifdef USE_GTK
8301 /* See comment in EnterNotify above */
8302 else if (dpyinfo->last_mouse_glyph_frame)
8303 note_mouse_movement (dpyinfo->last_mouse_glyph_frame, &event->xmotion);
8304 #endif
8305 goto OTHER;
8307 case FocusOut:
8308 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
8309 goto OTHER;
8311 case MotionNotify:
8313 x_display_set_last_user_time (dpyinfo, event->xmotion.time);
8314 previous_help_echo_string = help_echo_string;
8315 help_echo_string = Qnil;
8317 f = (x_mouse_grabbed (dpyinfo) ? dpyinfo->last_mouse_frame
8318 : x_window_to_frame (dpyinfo, event->xmotion.window));
8320 if (hlinfo->mouse_face_hidden)
8322 hlinfo->mouse_face_hidden = false;
8323 clear_mouse_face (hlinfo);
8326 #ifdef USE_GTK
8327 if (f && xg_event_is_for_scrollbar (f, event))
8328 f = 0;
8329 #endif
8330 if (f)
8333 /* Generate SELECT_WINDOW_EVENTs when needed.
8334 Don't let popup menus influence things (bug#1261). */
8335 if (!NILP (Vmouse_autoselect_window) && !popup_activated ())
8337 static Lisp_Object last_mouse_window;
8338 Lisp_Object window = window_from_coordinates
8339 (f, event->xmotion.x, event->xmotion.y, 0, false);
8341 /* Window will be selected only when it is not selected now and
8342 last mouse movement event was not in it. Minibuffer window
8343 will be selected only when it is active. */
8344 if (WINDOWP (window)
8345 && !EQ (window, last_mouse_window)
8346 && !EQ (window, selected_window)
8347 /* For click-to-focus window managers
8348 create event iff we don't leave the
8349 selected frame. */
8350 && (focus_follows_mouse
8351 || (EQ (XWINDOW (window)->frame,
8352 XWINDOW (selected_window)->frame))))
8354 inev.ie.kind = SELECT_WINDOW_EVENT;
8355 inev.ie.frame_or_window = window;
8357 /* Remember the last window where we saw the mouse. */
8358 last_mouse_window = window;
8360 if (!note_mouse_movement (f, &event->xmotion))
8361 help_echo_string = previous_help_echo_string;
8363 else
8365 #ifndef USE_TOOLKIT_SCROLL_BARS
8366 struct scroll_bar *bar
8367 = x_window_to_scroll_bar (event->xmotion.display,
8368 event->xmotion.window, 2);
8370 if (bar)
8371 x_scroll_bar_note_movement (bar, &event->xmotion);
8372 #endif /* USE_TOOLKIT_SCROLL_BARS */
8374 /* If we move outside the frame, then we're
8375 certainly no longer on any text in the frame. */
8376 clear_mouse_face (hlinfo);
8379 /* If the contents of the global variable help_echo_string
8380 has changed, generate a HELP_EVENT. */
8381 if (!NILP (help_echo_string)
8382 || !NILP (previous_help_echo_string))
8383 do_help = 1;
8384 goto OTHER;
8387 case ConfigureNotify:
8388 /* An opaque move can generate a stream of events as the window
8389 is dragged around. If the connection round trip time isn't
8390 really short, they may come faster than we can respond to
8391 them, given the multiple queries we can do to check window
8392 manager state, translate coordinates, etc.
8394 So if this ConfigureNotify is immediately followed by another
8395 for the same window, use the info from the latest update, and
8396 consider the events all handled. */
8397 /* Opaque resize may be trickier; ConfigureNotify events are
8398 mixed with Expose events for multiple windows. */
8399 configureEvent = *event;
8400 while (XPending (dpyinfo->display))
8402 XNextEvent (dpyinfo->display, &next_event);
8403 if (next_event.type != ConfigureNotify
8404 || next_event.xconfigure.window != event->xconfigure.window
8405 /* Skipping events with different sizes can lead to a
8406 mispositioned mode line at initial window creation.
8407 Only drop window motion events for now. */
8408 || next_event.xconfigure.width != event->xconfigure.width
8409 || next_event.xconfigure.height != event->xconfigure.height)
8411 XPutBackEvent (dpyinfo->display, &next_event);
8412 break;
8414 else
8415 configureEvent = next_event;
8417 f = x_top_window_to_frame (dpyinfo, configureEvent.xconfigure.window);
8418 #ifdef USE_CAIRO
8419 if (f) x_cr_destroy_surface (f);
8420 #endif
8421 #ifdef USE_GTK
8422 if (!f
8423 && (f = any)
8424 && configureEvent.xconfigure.window == FRAME_X_WINDOW (f))
8426 xg_frame_resized (f, configureEvent.xconfigure.width,
8427 configureEvent.xconfigure.height);
8428 #ifdef USE_CAIRO
8429 x_cr_destroy_surface (f);
8430 #endif
8431 f = 0;
8433 #endif
8434 if (f)
8436 x_net_wm_state (f, configureEvent.xconfigure.window);
8438 #ifdef USE_X_TOOLKIT
8439 /* Tip frames are pure X window, set size for them. */
8440 if (! NILP (tip_frame) && XFRAME (tip_frame) == f)
8442 if (FRAME_PIXEL_HEIGHT (f) != configureEvent.xconfigure.height
8443 || FRAME_PIXEL_WIDTH (f) != configureEvent.xconfigure.width)
8444 SET_FRAME_GARBAGED (f);
8445 FRAME_PIXEL_HEIGHT (f) = configureEvent.xconfigure.height;
8446 FRAME_PIXEL_WIDTH (f) = configureEvent.xconfigure.width;
8448 #endif
8450 #ifndef USE_X_TOOLKIT
8451 #ifndef USE_GTK
8452 int width =
8453 FRAME_PIXEL_TO_TEXT_WIDTH (f, configureEvent.xconfigure.width);
8454 int height =
8455 FRAME_PIXEL_TO_TEXT_HEIGHT (f, configureEvent.xconfigure.height);
8457 /* In the toolkit version, change_frame_size
8458 is called by the code that handles resizing
8459 of the EmacsFrame widget. */
8461 /* Even if the number of character rows and columns has
8462 not changed, the font size may have changed, so we need
8463 to check the pixel dimensions as well. */
8464 if (width != FRAME_TEXT_WIDTH (f)
8465 || height != FRAME_TEXT_HEIGHT (f)
8466 || configureEvent.xconfigure.width != FRAME_PIXEL_WIDTH (f)
8467 || configureEvent.xconfigure.height != FRAME_PIXEL_HEIGHT (f))
8469 change_frame_size (f, width, height, false, true, false, true);
8470 x_clear_under_internal_border (f);
8471 SET_FRAME_GARBAGED (f);
8472 cancel_mouse_face (f);
8474 #endif /* not USE_GTK */
8475 #endif
8477 #ifdef USE_GTK
8478 /* GTK creates windows but doesn't map them.
8479 Only get real positions when mapped. */
8480 if (FRAME_GTK_OUTER_WIDGET (f)
8481 && gtk_widget_get_mapped (FRAME_GTK_OUTER_WIDGET (f)))
8482 #endif
8483 x_real_positions (f, &f->left_pos, &f->top_pos);
8485 #ifdef HAVE_X_I18N
8486 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMStatusArea))
8487 xic_set_statusarea (f);
8488 #endif
8491 goto OTHER;
8493 case ButtonRelease:
8494 case ButtonPress:
8496 /* If we decide we want to generate an event to be seen
8497 by the rest of Emacs, we put it here. */
8498 bool tool_bar_p = false;
8500 memset (&compose_status, 0, sizeof (compose_status));
8501 dpyinfo->last_mouse_glyph_frame = NULL;
8502 x_display_set_last_user_time (dpyinfo, event->xbutton.time);
8504 f = (x_mouse_grabbed (dpyinfo) ? dpyinfo->last_mouse_frame
8505 : x_window_to_frame (dpyinfo, event->xbutton.window));
8507 #ifdef USE_GTK
8508 if (f && xg_event_is_for_scrollbar (f, event))
8509 f = 0;
8510 #endif
8511 if (f)
8513 #if ! defined (USE_GTK)
8514 /* Is this in the tool-bar? */
8515 if (WINDOWP (f->tool_bar_window)
8516 && WINDOW_TOTAL_LINES (XWINDOW (f->tool_bar_window)))
8518 Lisp_Object window;
8519 int x = event->xbutton.x;
8520 int y = event->xbutton.y;
8522 window = window_from_coordinates (f, x, y, 0, true);
8523 tool_bar_p = EQ (window, f->tool_bar_window);
8525 if (tool_bar_p && event->xbutton.button < 4)
8526 handle_tool_bar_click
8527 (f, x, y, event->xbutton.type == ButtonPress,
8528 x_x_to_emacs_modifiers (dpyinfo, event->xbutton.state));
8530 #endif /* !USE_GTK */
8532 if (!tool_bar_p)
8533 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
8534 if (! popup_activated ())
8535 #endif
8537 if (ignore_next_mouse_click_timeout)
8539 if (event->type == ButtonPress
8540 && event->xbutton.time > ignore_next_mouse_click_timeout)
8542 ignore_next_mouse_click_timeout = 0;
8543 construct_mouse_click (&inev.ie, &event->xbutton, f);
8545 if (event->type == ButtonRelease)
8546 ignore_next_mouse_click_timeout = 0;
8548 else
8549 construct_mouse_click (&inev.ie, &event->xbutton, f);
8551 if (FRAME_X_EMBEDDED_P (f))
8552 xembed_send_message (f, event->xbutton.time,
8553 XEMBED_REQUEST_FOCUS, 0, 0, 0);
8555 else
8557 struct scroll_bar *bar
8558 = x_window_to_scroll_bar (event->xbutton.display,
8559 event->xbutton.window, 2);
8561 #ifdef USE_TOOLKIT_SCROLL_BARS
8562 /* Make the "Ctrl-Mouse-2 splits window" work for toolkit
8563 scroll bars. */
8564 if (bar && event->xbutton.state & ControlMask)
8566 x_scroll_bar_handle_click (bar, event, &inev.ie);
8567 *finish = X_EVENT_DROP;
8569 #else /* not USE_TOOLKIT_SCROLL_BARS */
8570 if (bar)
8571 x_scroll_bar_handle_click (bar, event, &inev.ie);
8572 #endif /* not USE_TOOLKIT_SCROLL_BARS */
8575 if (event->type == ButtonPress)
8577 dpyinfo->grabbed |= (1 << event->xbutton.button);
8578 dpyinfo->last_mouse_frame = f;
8579 #if ! defined (USE_GTK)
8580 if (f && !tool_bar_p)
8581 f->last_tool_bar_item = -1;
8582 #endif /* not USE_GTK */
8584 else
8585 dpyinfo->grabbed &= ~(1 << event->xbutton.button);
8587 /* Ignore any mouse motion that happened before this event;
8588 any subsequent mouse-movement Emacs events should reflect
8589 only motion after the ButtonPress/Release. */
8590 if (f != 0)
8591 f->mouse_moved = false;
8593 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
8594 f = x_menubar_window_to_frame (dpyinfo, event);
8595 /* For a down-event in the menu bar,
8596 don't pass it to Xt right now.
8597 Instead, save it away
8598 and we will pass it to Xt from kbd_buffer_get_event.
8599 That way, we can run some Lisp code first. */
8600 if (! popup_activated ()
8601 #ifdef USE_GTK
8602 /* Gtk+ menus only react to the first three buttons. */
8603 && event->xbutton.button < 3
8604 #endif
8605 && f && event->type == ButtonPress
8606 /* Verify the event is really within the menu bar
8607 and not just sent to it due to grabbing. */
8608 && event->xbutton.x >= 0
8609 && event->xbutton.x < FRAME_PIXEL_WIDTH (f)
8610 && event->xbutton.y >= 0
8611 && event->xbutton.y < FRAME_MENUBAR_HEIGHT (f)
8612 && event->xbutton.same_screen)
8614 if (!f->output_data.x->saved_menu_event)
8615 f->output_data.x->saved_menu_event = xmalloc (sizeof *event);
8616 *f->output_data.x->saved_menu_event = *event;
8617 inev.ie.kind = MENU_BAR_ACTIVATE_EVENT;
8618 XSETFRAME (inev.ie.frame_or_window, f);
8619 *finish = X_EVENT_DROP;
8621 else
8622 goto OTHER;
8623 #endif /* USE_X_TOOLKIT || USE_GTK */
8625 break;
8627 case CirculateNotify:
8628 goto OTHER;
8630 case CirculateRequest:
8631 goto OTHER;
8633 case VisibilityNotify:
8634 goto OTHER;
8636 case MappingNotify:
8637 /* Someone has changed the keyboard mapping - update the
8638 local cache. */
8639 switch (event->xmapping.request)
8641 case MappingModifier:
8642 x_find_modifier_meanings (dpyinfo);
8643 /* This is meant to fall through. */
8644 case MappingKeyboard:
8645 XRefreshKeyboardMapping ((XMappingEvent *) &event->xmapping);
8647 goto OTHER;
8649 case DestroyNotify:
8650 xft_settings_event (dpyinfo, event);
8651 break;
8653 default:
8654 OTHER:
8655 #ifdef USE_X_TOOLKIT
8656 block_input ();
8657 if (*finish != X_EVENT_DROP)
8658 XtDispatchEvent ((XEvent *) event);
8659 unblock_input ();
8660 #endif /* USE_X_TOOLKIT */
8661 break;
8664 done:
8665 if (inev.ie.kind != NO_EVENT)
8667 kbd_buffer_store_buffered_event (&inev, hold_quit);
8668 count++;
8671 if (do_help
8672 && !(hold_quit && hold_quit->kind != NO_EVENT))
8674 Lisp_Object frame;
8676 if (f)
8677 XSETFRAME (frame, f);
8678 else
8679 frame = Qnil;
8681 if (do_help > 0)
8683 any_help_event_p = true;
8684 gen_help_event (help_echo_string, frame, help_echo_window,
8685 help_echo_object, help_echo_pos);
8687 else
8689 help_echo_string = Qnil;
8690 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
8692 count++;
8695 SAFE_FREE ();
8696 return count;
8699 /* Handles the XEvent EVENT on display DISPLAY.
8700 This is used for event loops outside the normal event handling,
8701 i.e. looping while a popup menu or a dialog is posted.
8703 Returns the value handle_one_xevent sets in the finish argument. */
8705 x_dispatch_event (XEvent *event, Display *display)
8707 struct x_display_info *dpyinfo;
8708 int finish = X_EVENT_NORMAL;
8710 dpyinfo = x_display_info_for_display (display);
8712 if (dpyinfo)
8713 handle_one_xevent (dpyinfo, event, &finish, 0);
8715 return finish;
8718 /* Read events coming from the X server.
8719 Return as soon as there are no more events to be read.
8721 Return the number of characters stored into the buffer,
8722 thus pretending to be `read' (except the characters we store
8723 in the keyboard buffer can be multibyte, so are not necessarily
8724 C chars). */
8726 static int
8727 XTread_socket (struct terminal *terminal, struct input_event *hold_quit)
8729 int count = 0;
8730 bool event_found = false;
8731 struct x_display_info *dpyinfo = terminal->display_info.x;
8733 block_input ();
8735 /* For debugging, this gives a way to fake an I/O error. */
8736 if (dpyinfo == XTread_socket_fake_io_error)
8738 XTread_socket_fake_io_error = 0;
8739 x_io_error_quitter (dpyinfo->display);
8742 #ifndef USE_GTK
8743 while (XPending (dpyinfo->display))
8745 int finish;
8746 XEvent event;
8748 XNextEvent (dpyinfo->display, &event);
8750 #ifdef HAVE_X_I18N
8751 /* Filter events for the current X input method. */
8752 if (x_filter_event (dpyinfo, &event))
8753 continue;
8754 #endif
8755 event_found = true;
8757 count += handle_one_xevent (dpyinfo, &event, &finish, hold_quit);
8759 if (finish == X_EVENT_GOTO_OUT)
8760 break;
8763 #else /* USE_GTK */
8765 /* For GTK we must use the GTK event loop. But XEvents gets passed
8766 to our filter function above, and then to the big event switch.
8767 We use a bunch of globals to communicate with our filter function,
8768 that is kind of ugly, but it works.
8770 There is no way to do one display at the time, GTK just does events
8771 from all displays. */
8773 while (gtk_events_pending ())
8775 current_count = count;
8776 current_hold_quit = hold_quit;
8778 gtk_main_iteration ();
8780 count = current_count;
8781 current_count = -1;
8782 current_hold_quit = 0;
8784 if (current_finish == X_EVENT_GOTO_OUT)
8785 break;
8787 #endif /* USE_GTK */
8789 /* On some systems, an X bug causes Emacs to get no more events
8790 when the window is destroyed. Detect that. (1994.) */
8791 if (! event_found)
8793 /* Emacs and the X Server eats up CPU time if XNoOp is done every time.
8794 One XNOOP in 100 loops will make Emacs terminate.
8795 B. Bretthauer, 1994 */
8796 x_noop_count++;
8797 if (x_noop_count >= 100)
8799 x_noop_count=0;
8801 if (next_noop_dpyinfo == 0)
8802 next_noop_dpyinfo = x_display_list;
8804 XNoOp (next_noop_dpyinfo->display);
8806 /* Each time we get here, cycle through the displays now open. */
8807 next_noop_dpyinfo = next_noop_dpyinfo->next;
8811 /* If the focus was just given to an auto-raising frame,
8812 raise it now. FIXME: handle more than one such frame. */
8813 if (dpyinfo->x_pending_autoraise_frame)
8815 x_raise_frame (dpyinfo->x_pending_autoraise_frame);
8816 dpyinfo->x_pending_autoraise_frame = NULL;
8819 unblock_input ();
8821 return count;
8827 /***********************************************************************
8828 Text Cursor
8829 ***********************************************************************/
8831 /* Set clipping for output in glyph row ROW. W is the window in which
8832 we operate. GC is the graphics context to set clipping in.
8834 ROW may be a text row or, e.g., a mode line. Text rows must be
8835 clipped to the interior of the window dedicated to text display,
8836 mode lines must be clipped to the whole window. */
8838 static void
8839 x_clip_to_row (struct window *w, struct glyph_row *row,
8840 enum glyph_row_area area, GC gc)
8842 struct frame *f = XFRAME (WINDOW_FRAME (w));
8843 XRectangle clip_rect;
8844 int window_x, window_y, window_width;
8846 window_box (w, area, &window_x, &window_y, &window_width, 0);
8848 clip_rect.x = window_x;
8849 clip_rect.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
8850 clip_rect.y = max (clip_rect.y, window_y);
8851 clip_rect.width = window_width;
8852 clip_rect.height = row->visible_height;
8854 x_set_clip_rectangles (f, gc, &clip_rect, 1);
8858 /* Draw a hollow box cursor on window W in glyph row ROW. */
8860 static void
8861 x_draw_hollow_cursor (struct window *w, struct glyph_row *row)
8863 struct frame *f = XFRAME (WINDOW_FRAME (w));
8864 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
8865 Display *dpy = FRAME_X_DISPLAY (f);
8866 int x, y, wd, h;
8867 XGCValues xgcv;
8868 struct glyph *cursor_glyph;
8869 GC gc;
8871 /* Get the glyph the cursor is on. If we can't tell because
8872 the current matrix is invalid or such, give up. */
8873 cursor_glyph = get_phys_cursor_glyph (w);
8874 if (cursor_glyph == NULL)
8875 return;
8877 /* Compute frame-relative coordinates for phys cursor. */
8878 get_phys_cursor_geometry (w, row, cursor_glyph, &x, &y, &h);
8879 wd = w->phys_cursor_width - 1;
8881 /* The foreground of cursor_gc is typically the same as the normal
8882 background color, which can cause the cursor box to be invisible. */
8883 xgcv.foreground = f->output_data.x->cursor_pixel;
8884 if (dpyinfo->scratch_cursor_gc)
8885 XChangeGC (dpy, dpyinfo->scratch_cursor_gc, GCForeground, &xgcv);
8886 else
8887 dpyinfo->scratch_cursor_gc = XCreateGC (dpy, FRAME_X_WINDOW (f),
8888 GCForeground, &xgcv);
8889 gc = dpyinfo->scratch_cursor_gc;
8891 /* When on R2L character, show cursor at the right edge of the
8892 glyph, unless the cursor box is as wide as the glyph or wider
8893 (the latter happens when x-stretch-cursor is non-nil). */
8894 if ((cursor_glyph->resolved_level & 1) != 0
8895 && cursor_glyph->pixel_width > wd)
8897 x += cursor_glyph->pixel_width - wd;
8898 if (wd > 0)
8899 wd -= 1;
8901 /* Set clipping, draw the rectangle, and reset clipping again. */
8902 x_clip_to_row (w, row, TEXT_AREA, gc);
8903 x_draw_rectangle (f, gc, x, y, wd, h - 1);
8904 x_reset_clip_rectangles (f, gc);
8908 /* Draw a bar cursor on window W in glyph row ROW.
8910 Implementation note: One would like to draw a bar cursor with an
8911 angle equal to the one given by the font property XA_ITALIC_ANGLE.
8912 Unfortunately, I didn't find a font yet that has this property set.
8913 --gerd. */
8915 static void
8916 x_draw_bar_cursor (struct window *w, struct glyph_row *row, int width, enum text_cursor_kinds kind)
8918 struct frame *f = XFRAME (w->frame);
8919 struct glyph *cursor_glyph;
8921 /* If cursor is out of bounds, don't draw garbage. This can happen
8922 in mini-buffer windows when switching between echo area glyphs
8923 and mini-buffer. */
8924 cursor_glyph = get_phys_cursor_glyph (w);
8925 if (cursor_glyph == NULL)
8926 return;
8928 /* Experimental avoidance of cursor on xwidget. */
8929 if (cursor_glyph->type == XWIDGET_GLYPH)
8930 return;
8932 /* If on an image, draw like a normal cursor. That's usually better
8933 visible than drawing a bar, esp. if the image is large so that
8934 the bar might not be in the window. */
8935 if (cursor_glyph->type == IMAGE_GLYPH)
8937 struct glyph_row *r;
8938 r = MATRIX_ROW (w->current_matrix, w->phys_cursor.vpos);
8939 draw_phys_cursor_glyph (w, r, DRAW_CURSOR);
8941 else
8943 Display *dpy = FRAME_X_DISPLAY (f);
8944 Window window = FRAME_X_WINDOW (f);
8945 GC gc = FRAME_DISPLAY_INFO (f)->scratch_cursor_gc;
8946 unsigned long mask = GCForeground | GCBackground | GCGraphicsExposures;
8947 struct face *face = FACE_FROM_ID (f, cursor_glyph->face_id);
8948 XGCValues xgcv;
8950 /* If the glyph's background equals the color we normally draw
8951 the bars cursor in, the bar cursor in its normal color is
8952 invisible. Use the glyph's foreground color instead in this
8953 case, on the assumption that the glyph's colors are chosen so
8954 that the glyph is legible. */
8955 if (face->background == f->output_data.x->cursor_pixel)
8956 xgcv.background = xgcv.foreground = face->foreground;
8957 else
8958 xgcv.background = xgcv.foreground = f->output_data.x->cursor_pixel;
8959 xgcv.graphics_exposures = False;
8961 if (gc)
8962 XChangeGC (dpy, gc, mask, &xgcv);
8963 else
8965 gc = XCreateGC (dpy, window, mask, &xgcv);
8966 FRAME_DISPLAY_INFO (f)->scratch_cursor_gc = gc;
8969 x_clip_to_row (w, row, TEXT_AREA, gc);
8971 if (kind == BAR_CURSOR)
8973 int x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
8975 if (width < 0)
8976 width = FRAME_CURSOR_WIDTH (f);
8977 width = min (cursor_glyph->pixel_width, width);
8979 w->phys_cursor_width = width;
8981 /* If the character under cursor is R2L, draw the bar cursor
8982 on the right of its glyph, rather than on the left. */
8983 if ((cursor_glyph->resolved_level & 1) != 0)
8984 x += cursor_glyph->pixel_width - width;
8986 x_fill_rectangle (f, gc, x,
8987 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y),
8988 width, row->height);
8990 else /* HBAR_CURSOR */
8992 int dummy_x, dummy_y, dummy_h;
8993 int x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
8995 if (width < 0)
8996 width = row->height;
8998 width = min (row->height, width);
9000 get_phys_cursor_geometry (w, row, cursor_glyph, &dummy_x,
9001 &dummy_y, &dummy_h);
9003 if ((cursor_glyph->resolved_level & 1) != 0
9004 && cursor_glyph->pixel_width > w->phys_cursor_width - 1)
9005 x += cursor_glyph->pixel_width - w->phys_cursor_width + 1;
9006 x_fill_rectangle (f, gc, x,
9007 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y +
9008 row->height - width),
9009 w->phys_cursor_width - 1, width);
9012 x_reset_clip_rectangles (f, gc);
9017 /* RIF: Define cursor CURSOR on frame F. */
9019 static void
9020 x_define_frame_cursor (struct frame *f, Cursor cursor)
9022 if (!f->pointer_invisible
9023 && f->output_data.x->current_cursor != cursor)
9024 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), cursor);
9025 f->output_data.x->current_cursor = cursor;
9029 /* RIF: Clear area on frame F. */
9031 static void
9032 x_clear_frame_area (struct frame *f, int x, int y, int width, int height)
9034 x_clear_area (f, x, y, width, height);
9035 #ifdef USE_GTK
9036 /* Must queue a redraw, because scroll bars might have been cleared. */
9037 if (FRAME_GTK_WIDGET (f))
9038 gtk_widget_queue_draw (FRAME_GTK_WIDGET (f));
9039 #endif
9043 /* RIF: Draw cursor on window W. */
9045 static void
9046 x_draw_window_cursor (struct window *w, struct glyph_row *glyph_row, int x,
9047 int y, enum text_cursor_kinds cursor_type,
9048 int cursor_width, bool on_p, bool active_p)
9050 struct frame *f = XFRAME (WINDOW_FRAME (w));
9052 if (on_p)
9054 w->phys_cursor_type = cursor_type;
9055 w->phys_cursor_on_p = true;
9057 if (glyph_row->exact_window_width_line_p
9058 && (glyph_row->reversed_p
9059 ? (w->phys_cursor.hpos < 0)
9060 : (w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])))
9062 glyph_row->cursor_in_fringe_p = true;
9063 draw_fringe_bitmap (w, glyph_row, glyph_row->reversed_p);
9065 else
9067 switch (cursor_type)
9069 case HOLLOW_BOX_CURSOR:
9070 x_draw_hollow_cursor (w, glyph_row);
9071 break;
9073 case FILLED_BOX_CURSOR:
9074 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
9075 break;
9077 case BAR_CURSOR:
9078 x_draw_bar_cursor (w, glyph_row, cursor_width, BAR_CURSOR);
9079 break;
9081 case HBAR_CURSOR:
9082 x_draw_bar_cursor (w, glyph_row, cursor_width, HBAR_CURSOR);
9083 break;
9085 case NO_CURSOR:
9086 w->phys_cursor_width = 0;
9087 break;
9089 default:
9090 emacs_abort ();
9094 #ifdef HAVE_X_I18N
9095 if (w == XWINDOW (f->selected_window))
9096 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMPreeditPosition))
9097 xic_set_preeditarea (w, x, y);
9098 #endif
9101 XFlush (FRAME_X_DISPLAY (f));
9105 /* Icons. */
9107 /* Make the x-window of frame F use the gnu icon bitmap. */
9109 bool
9110 x_bitmap_icon (struct frame *f, Lisp_Object file)
9112 ptrdiff_t bitmap_id;
9114 if (FRAME_X_WINDOW (f) == 0)
9115 return true;
9117 /* Free up our existing icon bitmap and mask if any. */
9118 if (f->output_data.x->icon_bitmap > 0)
9119 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
9120 f->output_data.x->icon_bitmap = 0;
9122 if (STRINGP (file))
9124 #ifdef USE_GTK
9125 /* Use gtk_window_set_icon_from_file () if available,
9126 It's not restricted to bitmaps */
9127 if (xg_set_icon (f, file))
9128 return false;
9129 #endif /* USE_GTK */
9130 bitmap_id = x_create_bitmap_from_file (f, file);
9131 x_create_bitmap_mask (f, bitmap_id);
9133 else
9135 /* Create the GNU bitmap and mask if necessary. */
9136 if (FRAME_DISPLAY_INFO (f)->icon_bitmap_id < 0)
9138 ptrdiff_t rc = -1;
9140 #ifdef USE_GTK
9142 if (xg_set_icon (f, xg_default_icon_file)
9143 || xg_set_icon_from_xpm_data (f, gnu_xpm_bits))
9145 FRAME_DISPLAY_INFO (f)->icon_bitmap_id = -2;
9146 return false;
9149 #elif defined (HAVE_XPM) && defined (HAVE_X_WINDOWS)
9151 rc = x_create_bitmap_from_xpm_data (f, gnu_xpm_bits);
9152 if (rc != -1)
9153 FRAME_DISPLAY_INFO (f)->icon_bitmap_id = rc;
9155 #endif
9157 /* If all else fails, use the (black and white) xbm image. */
9158 if (rc == -1)
9160 rc = x_create_bitmap_from_data (f, (char *) gnu_xbm_bits,
9161 gnu_xbm_width, gnu_xbm_height);
9162 if (rc == -1)
9163 return true;
9165 FRAME_DISPLAY_INFO (f)->icon_bitmap_id = rc;
9166 x_create_bitmap_mask (f, FRAME_DISPLAY_INFO (f)->icon_bitmap_id);
9170 /* The first time we create the GNU bitmap and mask,
9171 this increments the ref-count one extra time.
9172 As a result, the GNU bitmap and mask are never freed.
9173 That way, we don't have to worry about allocating it again. */
9174 x_reference_bitmap (f, FRAME_DISPLAY_INFO (f)->icon_bitmap_id);
9176 bitmap_id = FRAME_DISPLAY_INFO (f)->icon_bitmap_id;
9179 x_wm_set_icon_pixmap (f, bitmap_id);
9180 f->output_data.x->icon_bitmap = bitmap_id;
9182 return false;
9186 /* Make the x-window of frame F use a rectangle with text.
9187 Use ICON_NAME as the text. */
9189 bool
9190 x_text_icon (struct frame *f, const char *icon_name)
9192 if (FRAME_X_WINDOW (f) == 0)
9193 return true;
9196 XTextProperty text;
9197 text.value = (unsigned char *) icon_name;
9198 text.encoding = XA_STRING;
9199 text.format = 8;
9200 text.nitems = strlen (icon_name);
9201 XSetWMIconName (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f), &text);
9204 if (f->output_data.x->icon_bitmap > 0)
9205 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
9206 f->output_data.x->icon_bitmap = 0;
9207 x_wm_set_icon_pixmap (f, 0);
9209 return false;
9212 #define X_ERROR_MESSAGE_SIZE 200
9214 /* If non-nil, this should be a string.
9215 It means catch X errors and store the error message in this string.
9217 The reason we use a stack is that x_catch_error/x_uncatch_error can
9218 be called from a signal handler.
9221 struct x_error_message_stack {
9222 char string[X_ERROR_MESSAGE_SIZE];
9223 Display *dpy;
9224 x_special_error_handler handler;
9225 void *handler_data;
9226 struct x_error_message_stack *prev;
9228 static struct x_error_message_stack *x_error_message;
9230 /* An X error handler which stores the error message in
9231 *x_error_message. This is called from x_error_handler if
9232 x_catch_errors is in effect. */
9234 static void
9235 x_error_catcher (Display *display, XErrorEvent *event)
9237 XGetErrorText (display, event->error_code,
9238 x_error_message->string,
9239 X_ERROR_MESSAGE_SIZE);
9240 if (x_error_message->handler)
9241 x_error_message->handler (display, event, x_error_message->string,
9242 x_error_message->handler_data);
9245 /* Begin trapping X errors for display DPY. Actually we trap X errors
9246 for all displays, but DPY should be the display you are actually
9247 operating on.
9249 After calling this function, X protocol errors no longer cause
9250 Emacs to exit; instead, they are recorded in the string
9251 stored in *x_error_message.
9253 Calling x_check_errors signals an Emacs error if an X error has
9254 occurred since the last call to x_catch_errors or x_check_errors.
9256 Calling x_uncatch_errors resumes the normal error handling.
9257 Calling x_uncatch_errors_after_check is similar, but skips an XSync
9258 to the server, and should be used only immediately after
9259 x_had_errors_p or x_check_errors. */
9261 void
9262 x_catch_errors_with_handler (Display *dpy, x_special_error_handler handler,
9263 void *handler_data)
9265 struct x_error_message_stack *data = xmalloc (sizeof *data);
9267 /* Make sure any errors from previous requests have been dealt with. */
9268 XSync (dpy, False);
9270 data->dpy = dpy;
9271 data->string[0] = 0;
9272 data->handler = handler;
9273 data->handler_data = handler_data;
9274 data->prev = x_error_message;
9275 x_error_message = data;
9278 void
9279 x_catch_errors (Display *dpy)
9281 x_catch_errors_with_handler (dpy, NULL, NULL);
9284 /* Undo the last x_catch_errors call.
9285 DPY should be the display that was passed to x_catch_errors.
9287 This version should be used only if the immediately preceding
9288 X-protocol-related thing was x_check_errors or x_had_error_p, both
9289 of which issue XSync calls, so we don't need to re-sync here. */
9291 void
9292 x_uncatch_errors_after_check (void)
9294 struct x_error_message_stack *tmp;
9296 block_input ();
9297 tmp = x_error_message;
9298 x_error_message = x_error_message->prev;
9299 xfree (tmp);
9300 unblock_input ();
9303 /* Undo the last x_catch_errors call.
9304 DPY should be the display that was passed to x_catch_errors. */
9306 void
9307 x_uncatch_errors (void)
9309 struct x_error_message_stack *tmp;
9311 block_input ();
9313 /* The display may have been closed before this function is called.
9314 Check if it is still open before calling XSync. */
9315 if (x_display_info_for_display (x_error_message->dpy) != 0)
9316 XSync (x_error_message->dpy, False);
9318 tmp = x_error_message;
9319 x_error_message = x_error_message->prev;
9320 xfree (tmp);
9321 unblock_input ();
9324 /* If any X protocol errors have arrived since the last call to
9325 x_catch_errors or x_check_errors, signal an Emacs error using
9326 sprintf (a buffer, FORMAT, the x error message text) as the text. */
9328 void
9329 x_check_errors (Display *dpy, const char *format)
9331 /* Make sure to catch any errors incurred so far. */
9332 XSync (dpy, False);
9334 if (x_error_message->string[0])
9336 char string[X_ERROR_MESSAGE_SIZE];
9337 memcpy (string, x_error_message->string, X_ERROR_MESSAGE_SIZE);
9338 x_uncatch_errors ();
9339 error (format, string);
9343 /* Nonzero if we had any X protocol errors
9344 since we did x_catch_errors on DPY. */
9346 bool
9347 x_had_errors_p (Display *dpy)
9349 /* Make sure to catch any errors incurred so far. */
9350 XSync (dpy, False);
9352 return x_error_message->string[0] != 0;
9355 /* Forget about any errors we have had, since we did x_catch_errors on DPY. */
9357 void
9358 x_clear_errors (Display *dpy)
9360 x_error_message->string[0] = 0;
9363 #if false
9364 /* See comment in unwind_to_catch why calling this is a bad
9365 * idea. --lorentey */
9366 /* Close off all unclosed x_catch_errors calls. */
9368 void
9369 x_fully_uncatch_errors (void)
9371 while (x_error_message)
9372 x_uncatch_errors ();
9374 #endif
9376 #if false
9377 static unsigned int x_wire_count;
9378 x_trace_wire (void)
9380 fprintf (stderr, "Lib call: %d\n", ++x_wire_count);
9382 #endif
9385 /************************************************************************
9386 Handling X errors
9387 ************************************************************************/
9389 /* Error message passed to x_connection_closed. */
9391 static char *error_msg;
9393 /* Handle the loss of connection to display DPY. ERROR_MESSAGE is
9394 the text of an error message that lead to the connection loss. */
9396 static _Noreturn void
9397 x_connection_closed (Display *dpy, const char *error_message, bool ioerror)
9399 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
9400 Lisp_Object frame, tail;
9401 ptrdiff_t idx = SPECPDL_INDEX ();
9403 error_msg = alloca (strlen (error_message) + 1);
9404 strcpy (error_msg, error_message);
9406 /* Inhibit redisplay while frames are being deleted. */
9407 specbind (Qinhibit_redisplay, Qt);
9409 if (dpyinfo)
9411 /* Protect display from being closed when we delete the last
9412 frame on it. */
9413 dpyinfo->reference_count++;
9414 dpyinfo->terminal->reference_count++;
9416 if (ioerror) dpyinfo->display = 0;
9418 /* First delete frames whose mini-buffers are on frames
9419 that are on the dead display. */
9420 FOR_EACH_FRAME (tail, frame)
9422 Lisp_Object minibuf_frame;
9423 minibuf_frame
9424 = WINDOW_FRAME (XWINDOW (FRAME_MINIBUF_WINDOW (XFRAME (frame))));
9425 if (FRAME_X_P (XFRAME (frame))
9426 && FRAME_X_P (XFRAME (minibuf_frame))
9427 && ! EQ (frame, minibuf_frame)
9428 && FRAME_DISPLAY_INFO (XFRAME (minibuf_frame)) == dpyinfo)
9429 delete_frame (frame, Qnoelisp);
9432 /* Now delete all remaining frames on the dead display.
9433 We are now sure none of these is used as the mini-buffer
9434 for another frame that we need to delete. */
9435 FOR_EACH_FRAME (tail, frame)
9436 if (FRAME_X_P (XFRAME (frame))
9437 && FRAME_DISPLAY_INFO (XFRAME (frame)) == dpyinfo)
9439 /* Set this to t so that delete_frame won't get confused
9440 trying to find a replacement. */
9441 kset_default_minibuffer_frame (FRAME_KBOARD (XFRAME (frame)), Qt);
9442 delete_frame (frame, Qnoelisp);
9445 /* If DPYINFO is null, this means we didn't open the display in the
9446 first place, so don't try to close it. */
9447 if (dpyinfo)
9449 /* We can not call XtCloseDisplay here because it calls XSync.
9450 XSync inside the error handler apparently hangs Emacs. On
9451 current Xt versions, this isn't needed either. */
9452 #ifdef USE_GTK
9453 /* A long-standing GTK bug prevents proper disconnect handling
9454 (https://bugzilla.gnome.org/show_bug.cgi?id=85715). Once,
9455 the resulting Glib error message loop filled a user's disk.
9456 To avoid this, kill Emacs unconditionally on disconnect. */
9457 shut_down_emacs (0, Qnil);
9458 fprintf (stderr, "%s\n\
9459 When compiled with GTK, Emacs cannot recover from X disconnects.\n\
9460 This is a GTK bug: https://bugzilla.gnome.org/show_bug.cgi?id=85715\n\
9461 For details, see etc/PROBLEMS.\n",
9462 error_msg);
9463 emacs_abort ();
9464 #endif /* USE_GTK */
9466 /* Indicate that this display is dead. */
9467 dpyinfo->display = 0;
9469 dpyinfo->reference_count--;
9470 dpyinfo->terminal->reference_count--;
9471 if (dpyinfo->reference_count != 0)
9472 /* We have just closed all frames on this display. */
9473 emacs_abort ();
9476 Lisp_Object tmp;
9477 XSETTERMINAL (tmp, dpyinfo->terminal);
9478 Fdelete_terminal (tmp, Qnoelisp);
9482 if (terminal_list == 0)
9484 fprintf (stderr, "%s\n", error_msg);
9485 Fkill_emacs (make_number (70));
9486 /* NOTREACHED */
9489 totally_unblock_input ();
9491 unbind_to (idx, Qnil);
9492 clear_waiting_for_input ();
9494 /* Here, we absolutely have to use a non-local exit (e.g. signal, throw,
9495 longjmp), because returning from this function would get us back into
9496 Xlib's code which will directly call `exit'. */
9497 error ("%s", error_msg);
9500 /* We specifically use it before defining it, so that gcc doesn't inline it,
9501 otherwise gdb doesn't know how to properly put a breakpoint on it. */
9502 static void x_error_quitter (Display *, XErrorEvent *);
9504 /* This is the first-level handler for X protocol errors.
9505 It calls x_error_quitter or x_error_catcher. */
9507 static int
9508 x_error_handler (Display *display, XErrorEvent *event)
9510 #if defined USE_GTK && defined HAVE_GTK3
9511 if ((event->error_code == BadMatch || event->error_code == BadWindow)
9512 && event->request_code == X_SetInputFocus)
9514 return 0;
9516 #endif
9518 if (x_error_message)
9519 x_error_catcher (display, event);
9520 else
9521 x_error_quitter (display, event);
9522 return 0;
9525 /* This is the usual handler for X protocol errors.
9526 It kills all frames on the display that we got the error for.
9527 If that was the only one, it prints an error message and kills Emacs. */
9529 /* .gdbinit puts a breakpoint here, so make sure it is not inlined. */
9531 /* On older GCC versions, just putting x_error_quitter
9532 after x_error_handler prevents inlining into the former. */
9534 static void NO_INLINE
9535 x_error_quitter (Display *display, XErrorEvent *event)
9537 char buf[256], buf1[356];
9539 /* Ignore BadName errors. They can happen because of fonts
9540 or colors that are not defined. */
9542 if (event->error_code == BadName)
9543 return;
9545 /* Note that there is no real way portable across R3/R4 to get the
9546 original error handler. */
9548 XGetErrorText (display, event->error_code, buf, sizeof (buf));
9549 sprintf (buf1, "X protocol error: %s on protocol request %d",
9550 buf, event->request_code);
9551 x_connection_closed (display, buf1, false);
9555 /* This is the handler for X IO errors, always.
9556 It kills all frames on the display that we lost touch with.
9557 If that was the only one, it prints an error message and kills Emacs. */
9559 static _Noreturn int
9560 x_io_error_quitter (Display *display)
9562 char buf[256];
9564 snprintf (buf, sizeof buf, "Connection lost to X server '%s'",
9565 DisplayString (display));
9566 x_connection_closed (display, buf, true);
9567 assume (false);
9570 /* Changing the font of the frame. */
9572 /* Give frame F the font FONT-OBJECT as its default font. The return
9573 value is FONT-OBJECT. FONTSET is an ID of the fontset for the
9574 frame. If it is negative, generate a new fontset from
9575 FONT-OBJECT. */
9577 Lisp_Object
9578 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
9580 struct font *font = XFONT_OBJECT (font_object);
9581 int unit, font_ascent, font_descent;
9582 #ifndef USE_X_TOOLKIT
9583 int old_menu_bar_height = FRAME_MENU_BAR_HEIGHT (f);
9584 Lisp_Object fullscreen;
9585 #endif
9587 if (fontset < 0)
9588 fontset = fontset_from_font (font_object);
9589 FRAME_FONTSET (f) = fontset;
9590 if (FRAME_FONT (f) == font)
9591 /* This font is already set in frame F. There's nothing more to
9592 do. */
9593 return font_object;
9595 FRAME_FONT (f) = font;
9596 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
9597 FRAME_COLUMN_WIDTH (f) = font->average_width;
9598 get_font_ascent_descent (font, &font_ascent, &font_descent);
9599 FRAME_LINE_HEIGHT (f) = font_ascent + font_descent;
9601 #ifndef USE_X_TOOLKIT
9602 FRAME_MENU_BAR_HEIGHT (f) = FRAME_MENU_BAR_LINES (f) * FRAME_LINE_HEIGHT (f);
9603 #endif
9605 /* Compute character columns occupied by scrollbar.
9607 Don't do things differently for non-toolkit scrollbars
9608 (Bug#17163). */
9609 unit = FRAME_COLUMN_WIDTH (f);
9610 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
9611 FRAME_CONFIG_SCROLL_BAR_COLS (f)
9612 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + unit - 1) / unit;
9613 else
9614 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + unit - 1) / unit;
9616 if (FRAME_X_WINDOW (f) != 0)
9618 /* Don't change the size of a tip frame; there's no point in
9619 doing it because it's done in Fx_show_tip, and it leads to
9620 problems because the tip frame has no widget. */
9621 if (NILP (tip_frame) || XFRAME (tip_frame) != f)
9623 adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
9624 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 3,
9625 false, Qfont);
9626 #ifndef USE_X_TOOLKIT
9627 if (FRAME_MENU_BAR_HEIGHT (f) != old_menu_bar_height
9628 && !f->after_make_frame
9629 && (EQ (frame_inhibit_implied_resize, Qt)
9630 || (CONSP (frame_inhibit_implied_resize)
9631 && NILP (Fmemq (Qfont, frame_inhibit_implied_resize))))
9632 && (NILP (fullscreen = get_frame_param (f, Qfullscreen))
9633 || EQ (fullscreen, Qfullwidth)))
9634 /* If the menu bar height changes, try to keep text height
9635 constant. */
9636 adjust_frame_size
9637 (f, -1, FRAME_TEXT_HEIGHT (f) + FRAME_MENU_BAR_HEIGHT (f)
9638 - old_menu_bar_height, 1, false, Qfont);
9639 #endif /* USE_X_TOOLKIT */
9643 #ifdef HAVE_X_I18N
9644 if (FRAME_XIC (f)
9645 && (FRAME_XIC_STYLE (f) & (XIMPreeditPosition | XIMStatusArea)))
9647 block_input ();
9648 xic_set_xfontset (f, SSDATA (fontset_ascii (fontset)));
9649 unblock_input ();
9651 #endif
9653 return font_object;
9657 /***********************************************************************
9658 X Input Methods
9659 ***********************************************************************/
9661 #ifdef HAVE_X_I18N
9663 #ifdef HAVE_X11R6
9665 /* XIM destroy callback function, which is called whenever the
9666 connection to input method XIM dies. CLIENT_DATA contains a
9667 pointer to the x_display_info structure corresponding to XIM. */
9669 static void
9670 xim_destroy_callback (XIM xim, XPointer client_data, XPointer call_data)
9672 struct x_display_info *dpyinfo = (struct x_display_info *) client_data;
9673 Lisp_Object frame, tail;
9675 block_input ();
9677 /* No need to call XDestroyIC.. */
9678 FOR_EACH_FRAME (tail, frame)
9680 struct frame *f = XFRAME (frame);
9681 if (FRAME_X_P (f) && FRAME_DISPLAY_INFO (f) == dpyinfo)
9683 FRAME_XIC (f) = NULL;
9684 xic_free_xfontset (f);
9688 /* No need to call XCloseIM. */
9689 dpyinfo->xim = NULL;
9690 XFree (dpyinfo->xim_styles);
9691 unblock_input ();
9694 #endif /* HAVE_X11R6 */
9696 /* Open the connection to the XIM server on display DPYINFO.
9697 RESOURCE_NAME is the resource name Emacs uses. */
9699 static void
9700 xim_open_dpy (struct x_display_info *dpyinfo, char *resource_name)
9702 XIM xim;
9704 #ifdef HAVE_XIM
9705 if (use_xim)
9707 if (dpyinfo->xim)
9708 XCloseIM (dpyinfo->xim);
9709 xim = XOpenIM (dpyinfo->display, dpyinfo->xrdb, resource_name,
9710 emacs_class);
9711 dpyinfo->xim = xim;
9713 if (xim)
9715 #ifdef HAVE_X11R6
9716 XIMCallback destroy;
9717 #endif
9719 /* Get supported styles and XIM values. */
9720 XGetIMValues (xim, XNQueryInputStyle, &dpyinfo->xim_styles, NULL);
9722 #ifdef HAVE_X11R6
9723 destroy.callback = xim_destroy_callback;
9724 destroy.client_data = (XPointer)dpyinfo;
9725 XSetIMValues (xim, XNDestroyCallback, &destroy, NULL);
9726 #endif
9730 else
9731 #endif /* HAVE_XIM */
9732 dpyinfo->xim = NULL;
9736 #ifdef HAVE_X11R6_XIM
9738 /* XIM instantiate callback function, which is called whenever an XIM
9739 server is available. DISPLAY is the display of the XIM.
9740 CLIENT_DATA contains a pointer to an xim_inst_t structure created
9741 when the callback was registered. */
9743 static void
9744 xim_instantiate_callback (Display *display, XPointer client_data, XPointer call_data)
9746 struct xim_inst_t *xim_inst = (struct xim_inst_t *) client_data;
9747 struct x_display_info *dpyinfo = xim_inst->dpyinfo;
9749 /* We don't support multiple XIM connections. */
9750 if (dpyinfo->xim)
9751 return;
9753 xim_open_dpy (dpyinfo, xim_inst->resource_name);
9755 /* Create XIC for the existing frames on the same display, as long
9756 as they have no XIC. */
9757 if (dpyinfo->xim && dpyinfo->reference_count > 0)
9759 Lisp_Object tail, frame;
9761 block_input ();
9762 FOR_EACH_FRAME (tail, frame)
9764 struct frame *f = XFRAME (frame);
9766 if (FRAME_X_P (f)
9767 && FRAME_DISPLAY_INFO (f) == xim_inst->dpyinfo)
9768 if (FRAME_XIC (f) == NULL)
9770 create_frame_xic (f);
9771 if (FRAME_XIC_STYLE (f) & XIMStatusArea)
9772 xic_set_statusarea (f);
9773 if (FRAME_XIC_STYLE (f) & XIMPreeditPosition)
9775 struct window *w = XWINDOW (f->selected_window);
9776 xic_set_preeditarea (w, w->cursor.x, w->cursor.y);
9781 unblock_input ();
9785 #endif /* HAVE_X11R6_XIM */
9788 /* Open a connection to the XIM server on display DPYINFO.
9789 RESOURCE_NAME is the resource name for Emacs. On X11R5, open the
9790 connection only at the first time. On X11R6, open the connection
9791 in the XIM instantiate callback function. */
9793 static void
9794 xim_initialize (struct x_display_info *dpyinfo, char *resource_name)
9796 dpyinfo->xim = NULL;
9797 #ifdef HAVE_XIM
9798 if (use_xim)
9800 #ifdef HAVE_X11R6_XIM
9801 struct xim_inst_t *xim_inst = xmalloc (sizeof *xim_inst);
9802 Bool ret;
9804 dpyinfo->xim_callback_data = xim_inst;
9805 xim_inst->dpyinfo = dpyinfo;
9806 xim_inst->resource_name = xstrdup (resource_name);
9807 ret = XRegisterIMInstantiateCallback
9808 (dpyinfo->display, dpyinfo->xrdb, xim_inst->resource_name,
9809 emacs_class, xim_instantiate_callback,
9810 /* This is XPointer in XFree86 but (XPointer *)
9811 on Tru64, at least, hence the configure test. */
9812 (XRegisterIMInstantiateCallback_arg6) xim_inst);
9813 eassert (ret == True);
9814 #else /* not HAVE_X11R6_XIM */
9815 xim_open_dpy (dpyinfo, resource_name);
9816 #endif /* not HAVE_X11R6_XIM */
9818 #endif /* HAVE_XIM */
9822 /* Close the connection to the XIM server on display DPYINFO. */
9824 static void
9825 xim_close_dpy (struct x_display_info *dpyinfo)
9827 #ifdef HAVE_XIM
9828 if (use_xim)
9830 #ifdef HAVE_X11R6_XIM
9831 struct xim_inst_t *xim_inst = dpyinfo->xim_callback_data;
9833 if (dpyinfo->display)
9835 Bool ret = XUnregisterIMInstantiateCallback
9836 (dpyinfo->display, dpyinfo->xrdb, xim_inst->resource_name,
9837 emacs_class, xim_instantiate_callback,
9838 (XRegisterIMInstantiateCallback_arg6) xim_inst);
9839 eassert (ret == True);
9841 xfree (xim_inst->resource_name);
9842 xfree (xim_inst);
9843 #endif /* HAVE_X11R6_XIM */
9844 if (dpyinfo->display)
9845 XCloseIM (dpyinfo->xim);
9846 dpyinfo->xim = NULL;
9847 XFree (dpyinfo->xim_styles);
9849 #endif /* HAVE_XIM */
9852 #endif /* not HAVE_X11R6_XIM */
9856 /* Calculate the absolute position in frame F
9857 from its current recorded position values and gravity. */
9859 static void
9860 x_calc_absolute_position (struct frame *f)
9862 int flags = f->size_hint_flags;
9864 /* We have nothing to do if the current position
9865 is already for the top-left corner. */
9866 if (! ((flags & XNegative) || (flags & YNegative)))
9867 return;
9869 /* Treat negative positions as relative to the leftmost bottommost
9870 position that fits on the screen. */
9871 if (flags & XNegative)
9872 f->left_pos = x_display_pixel_width (FRAME_DISPLAY_INFO (f))
9873 - FRAME_PIXEL_WIDTH (f) + f->left_pos;
9876 int height = FRAME_PIXEL_HEIGHT (f);
9878 #if defined USE_X_TOOLKIT && defined USE_MOTIF
9879 /* Something is fishy here. When using Motif, starting Emacs with
9880 `-g -0-0', the frame appears too low by a few pixels.
9882 This seems to be so because initially, while Emacs is starting,
9883 the column widget's height and the frame's pixel height are
9884 different. The column widget's height is the right one. In
9885 later invocations, when Emacs is up, the frame's pixel height
9886 is right, though.
9888 It's not obvious where the initial small difference comes from.
9889 2000-12-01, gerd. */
9891 XtVaGetValues (f->output_data.x->column_widget, XtNheight, &height, NULL);
9892 #endif
9894 if (flags & YNegative)
9895 f->top_pos = x_display_pixel_height (FRAME_DISPLAY_INFO (f))
9896 - height + f->top_pos;
9899 /* The left_pos and top_pos
9900 are now relative to the top and left screen edges,
9901 so the flags should correspond. */
9902 f->size_hint_flags &= ~ (XNegative | YNegative);
9905 /* CHANGE_GRAVITY is 1 when calling from Fset_frame_position,
9906 to really change the position, and 0 when calling from
9907 x_make_frame_visible (in that case, XOFF and YOFF are the current
9908 position values). It is -1 when calling from x_set_frame_parameters,
9909 which means, do adjust for borders but don't change the gravity. */
9911 void
9912 x_set_offset (struct frame *f, register int xoff, register int yoff, int change_gravity)
9914 int modified_top, modified_left;
9916 if (change_gravity > 0)
9918 f->top_pos = yoff;
9919 f->left_pos = xoff;
9920 f->size_hint_flags &= ~ (XNegative | YNegative);
9921 if (xoff < 0)
9922 f->size_hint_flags |= XNegative;
9923 if (yoff < 0)
9924 f->size_hint_flags |= YNegative;
9925 f->win_gravity = NorthWestGravity;
9927 x_calc_absolute_position (f);
9929 block_input ();
9930 x_wm_set_size_hint (f, 0, false);
9932 modified_left = f->left_pos;
9933 modified_top = f->top_pos;
9935 if (change_gravity != 0 && FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A)
9937 /* Some WMs (twm, wmaker at least) has an offset that is smaller
9938 than the WM decorations. So we use the calculated offset instead
9939 of the WM decoration sizes here (x/y_pixels_outer_diff). */
9940 modified_left += FRAME_X_OUTPUT (f)->move_offset_left;
9941 modified_top += FRAME_X_OUTPUT (f)->move_offset_top;
9944 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
9945 modified_left, modified_top);
9947 x_sync_with_move (f, f->left_pos, f->top_pos,
9948 FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN);
9950 /* change_gravity is non-zero when this function is called from Lisp to
9951 programmatically move a frame. In that case, we call
9952 x_check_expected_move to discover if we have a "Type A" or "Type B"
9953 window manager, and, for a "Type A" window manager, adjust the position
9954 of the frame.
9956 We call x_check_expected_move if a programmatic move occurred, and
9957 either the window manager type (A/B) is unknown or it is Type A but we
9958 need to compute the top/left offset adjustment for this frame. */
9960 if (change_gravity != 0
9961 && (FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN
9962 || (FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A
9963 && (FRAME_X_OUTPUT (f)->move_offset_left == 0
9964 && FRAME_X_OUTPUT (f)->move_offset_top == 0))))
9965 x_check_expected_move (f, modified_left, modified_top);
9967 unblock_input ();
9970 /* Return true if _NET_SUPPORTING_WM_CHECK window exists and _NET_SUPPORTED
9971 on the root window for frame F contains ATOMNAME.
9972 This is how a WM check shall be done according to the Window Manager
9973 Specification/Extended Window Manager Hints at
9974 http://freedesktop.org/wiki/Specifications/wm-spec. */
9976 bool
9977 x_wm_supports (struct frame *f, Atom want_atom)
9979 Atom actual_type;
9980 unsigned long actual_size, bytes_remaining;
9981 int i, rc, actual_format;
9982 bool ret;
9983 Window wmcheck_window;
9984 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
9985 Window target_window = dpyinfo->root_window;
9986 int max_len = 65536;
9987 Display *dpy = FRAME_X_DISPLAY (f);
9988 unsigned char *tmp_data = NULL;
9989 Atom target_type = XA_WINDOW;
9991 block_input ();
9993 x_catch_errors (dpy);
9994 rc = XGetWindowProperty (dpy, target_window,
9995 dpyinfo->Xatom_net_supporting_wm_check,
9996 0, max_len, False, target_type,
9997 &actual_type, &actual_format, &actual_size,
9998 &bytes_remaining, &tmp_data);
10000 if (rc != Success || actual_type != XA_WINDOW || x_had_errors_p (dpy))
10002 if (tmp_data) XFree (tmp_data);
10003 x_uncatch_errors ();
10004 unblock_input ();
10005 return false;
10008 wmcheck_window = *(Window *) tmp_data;
10009 XFree (tmp_data);
10011 /* Check if window exists. */
10012 XSelectInput (dpy, wmcheck_window, StructureNotifyMask);
10013 if (x_had_errors_p (dpy))
10015 x_uncatch_errors_after_check ();
10016 unblock_input ();
10017 return false;
10020 if (dpyinfo->net_supported_window != wmcheck_window)
10022 /* Window changed, reload atoms */
10023 if (dpyinfo->net_supported_atoms != NULL)
10024 XFree (dpyinfo->net_supported_atoms);
10025 dpyinfo->net_supported_atoms = NULL;
10026 dpyinfo->nr_net_supported_atoms = 0;
10027 dpyinfo->net_supported_window = 0;
10029 target_type = XA_ATOM;
10030 tmp_data = NULL;
10031 rc = XGetWindowProperty (dpy, target_window,
10032 dpyinfo->Xatom_net_supported,
10033 0, max_len, False, target_type,
10034 &actual_type, &actual_format, &actual_size,
10035 &bytes_remaining, &tmp_data);
10037 if (rc != Success || actual_type != XA_ATOM || x_had_errors_p (dpy))
10039 if (tmp_data) XFree (tmp_data);
10040 x_uncatch_errors ();
10041 unblock_input ();
10042 return false;
10045 dpyinfo->net_supported_atoms = (Atom *)tmp_data;
10046 dpyinfo->nr_net_supported_atoms = actual_size;
10047 dpyinfo->net_supported_window = wmcheck_window;
10050 ret = false;
10052 for (i = 0; !ret && i < dpyinfo->nr_net_supported_atoms; ++i)
10053 ret = dpyinfo->net_supported_atoms[i] == want_atom;
10055 x_uncatch_errors ();
10056 unblock_input ();
10058 return ret;
10061 static void
10062 set_wm_state (Lisp_Object frame, bool add, Atom atom, Atom value)
10064 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (XFRAME (frame));
10066 x_send_client_event (frame, make_number (0), frame,
10067 dpyinfo->Xatom_net_wm_state,
10068 make_number (32),
10069 /* 1 = add, 0 = remove */
10070 Fcons
10071 (make_number (add),
10072 Fcons
10073 (make_fixnum_or_float (atom),
10074 (value != 0
10075 ? list1 (make_fixnum_or_float (value))
10076 : Qnil))));
10079 void
10080 x_set_sticky (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
10082 Lisp_Object frame;
10083 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10085 XSETFRAME (frame, f);
10087 set_wm_state (frame, !NILP (new_value),
10088 dpyinfo->Xatom_net_wm_state_sticky, None);
10091 /* Return the current _NET_WM_STATE.
10092 SIZE_STATE is set to one of the FULLSCREEN_* values.
10093 Set *STICKY to the sticky state.
10095 Return true iff we are not hidden. */
10097 static bool
10098 get_current_wm_state (struct frame *f,
10099 Window window,
10100 int *size_state,
10101 bool *sticky)
10103 unsigned long actual_size;
10104 int i;
10105 bool is_hidden = false;
10106 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10107 long max_len = 65536;
10108 Atom target_type = XA_ATOM;
10109 /* If XCB is available, we can avoid three XSync calls. */
10110 #ifdef USE_XCB
10111 xcb_get_property_cookie_t prop_cookie;
10112 xcb_get_property_reply_t *prop;
10113 xcb_atom_t *reply_data;
10114 #else
10115 Display *dpy = FRAME_X_DISPLAY (f);
10116 unsigned long bytes_remaining;
10117 int rc, actual_format;
10118 Atom actual_type;
10119 unsigned char *tmp_data = NULL;
10120 Atom *reply_data;
10121 #endif
10123 *sticky = false;
10124 *size_state = FULLSCREEN_NONE;
10126 block_input ();
10128 #ifdef USE_XCB
10129 prop_cookie = xcb_get_property (dpyinfo->xcb_connection, 0, window,
10130 dpyinfo->Xatom_net_wm_state,
10131 target_type, 0, max_len);
10132 prop = xcb_get_property_reply (dpyinfo->xcb_connection, prop_cookie, NULL);
10133 if (prop && prop->type == target_type)
10135 int actual_bytes = xcb_get_property_value_length (prop);
10136 eassume (0 <= actual_bytes);
10137 actual_size = actual_bytes / sizeof *reply_data;
10138 reply_data = xcb_get_property_value (prop);
10140 else
10142 actual_size = 0;
10143 is_hidden = FRAME_ICONIFIED_P (f);
10145 #else
10146 x_catch_errors (dpy);
10147 rc = XGetWindowProperty (dpy, window, dpyinfo->Xatom_net_wm_state,
10148 0, max_len, False, target_type,
10149 &actual_type, &actual_format, &actual_size,
10150 &bytes_remaining, &tmp_data);
10152 if (rc == Success && actual_type == target_type && ! x_had_errors_p (dpy))
10153 reply_data = (Atom *) tmp_data;
10154 else
10156 actual_size = 0;
10157 is_hidden = FRAME_ICONIFIED_P (f);
10160 x_uncatch_errors ();
10161 #endif
10163 for (i = 0; i < actual_size; ++i)
10165 Atom a = reply_data[i];
10166 if (a == dpyinfo->Xatom_net_wm_state_hidden)
10167 is_hidden = true;
10168 else if (a == dpyinfo->Xatom_net_wm_state_maximized_horz)
10170 if (*size_state == FULLSCREEN_HEIGHT)
10171 *size_state = FULLSCREEN_MAXIMIZED;
10172 else
10173 *size_state = FULLSCREEN_WIDTH;
10175 else if (a == dpyinfo->Xatom_net_wm_state_maximized_vert)
10177 if (*size_state == FULLSCREEN_WIDTH)
10178 *size_state = FULLSCREEN_MAXIMIZED;
10179 else
10180 *size_state = FULLSCREEN_HEIGHT;
10182 else if (a == dpyinfo->Xatom_net_wm_state_fullscreen)
10183 *size_state = FULLSCREEN_BOTH;
10184 else if (a == dpyinfo->Xatom_net_wm_state_sticky)
10185 *sticky = true;
10188 #ifdef USE_XCB
10189 free (prop);
10190 #else
10191 if (tmp_data) XFree (tmp_data);
10192 #endif
10194 unblock_input ();
10195 return ! is_hidden;
10198 /* Do fullscreen as specified in extended window manager hints */
10200 static bool
10201 do_ewmh_fullscreen (struct frame *f)
10203 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10204 bool have_net_atom = x_wm_supports (f, dpyinfo->Xatom_net_wm_state);
10205 int cur;
10206 bool dummy;
10208 get_current_wm_state (f, FRAME_OUTER_WINDOW (f), &cur, &dummy);
10210 /* Some window managers don't say they support _NET_WM_STATE, but they do say
10211 they support _NET_WM_STATE_FULLSCREEN. Try that also. */
10212 if (!have_net_atom)
10213 have_net_atom = x_wm_supports (f, dpyinfo->Xatom_net_wm_state_fullscreen);
10215 if (have_net_atom && cur != f->want_fullscreen)
10217 Lisp_Object frame;
10219 XSETFRAME (frame, f);
10221 /* Keep number of calls to set_wm_state as low as possible.
10222 Some window managers, or possible Gtk+, hangs when too many
10223 are sent at once. */
10224 switch (f->want_fullscreen)
10226 case FULLSCREEN_BOTH:
10227 if (cur != FULLSCREEN_BOTH)
10228 set_wm_state (frame, true, dpyinfo->Xatom_net_wm_state_fullscreen,
10229 None);
10230 break;
10231 case FULLSCREEN_WIDTH:
10232 if (x_frame_normalize_before_maximize && cur == FULLSCREEN_MAXIMIZED)
10234 set_wm_state (frame, false,
10235 dpyinfo->Xatom_net_wm_state_maximized_horz,
10236 dpyinfo->Xatom_net_wm_state_maximized_vert);
10237 set_wm_state (frame, true,
10238 dpyinfo->Xatom_net_wm_state_maximized_horz, None);
10240 else
10242 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_HEIGHT
10243 || cur == FULLSCREEN_MAXIMIZED)
10244 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
10245 dpyinfo->Xatom_net_wm_state_maximized_vert);
10246 if (cur != FULLSCREEN_MAXIMIZED || x_frame_normalize_before_maximize)
10247 set_wm_state (frame, true,
10248 dpyinfo->Xatom_net_wm_state_maximized_horz, None);
10250 break;
10251 case FULLSCREEN_HEIGHT:
10252 if (x_frame_normalize_before_maximize && cur == FULLSCREEN_MAXIMIZED)
10254 set_wm_state (frame, false,
10255 dpyinfo->Xatom_net_wm_state_maximized_horz,
10256 dpyinfo->Xatom_net_wm_state_maximized_vert);
10257 set_wm_state (frame, true,
10258 dpyinfo->Xatom_net_wm_state_maximized_vert, None);
10260 else
10262 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_WIDTH
10263 || cur == FULLSCREEN_MAXIMIZED)
10264 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
10265 dpyinfo->Xatom_net_wm_state_maximized_horz);
10266 if (cur != FULLSCREEN_MAXIMIZED || x_frame_normalize_before_maximize)
10267 set_wm_state (frame, true,
10268 dpyinfo->Xatom_net_wm_state_maximized_vert, None);
10270 break;
10271 case FULLSCREEN_MAXIMIZED:
10272 if (x_frame_normalize_before_maximize && cur == FULLSCREEN_BOTH)
10274 set_wm_state (frame, false,
10275 dpyinfo->Xatom_net_wm_state_fullscreen, None);
10276 set_wm_state (frame, true,
10277 dpyinfo->Xatom_net_wm_state_maximized_horz,
10278 dpyinfo->Xatom_net_wm_state_maximized_vert);
10280 else if (x_frame_normalize_before_maximize && cur == FULLSCREEN_WIDTH)
10282 set_wm_state (frame, false,
10283 dpyinfo->Xatom_net_wm_state_maximized_horz, 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_HEIGHT)
10290 set_wm_state (frame, false,
10291 dpyinfo->Xatom_net_wm_state_maximized_vert, 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
10298 if (cur == FULLSCREEN_BOTH)
10299 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
10300 None);
10301 else if (cur == FULLSCREEN_HEIGHT)
10302 set_wm_state (frame, true,
10303 dpyinfo->Xatom_net_wm_state_maximized_horz, None);
10304 else if (cur == FULLSCREEN_WIDTH)
10305 set_wm_state (frame, true, None,
10306 dpyinfo->Xatom_net_wm_state_maximized_vert);
10307 else
10308 set_wm_state (frame, true,
10309 dpyinfo->Xatom_net_wm_state_maximized_horz,
10310 dpyinfo->Xatom_net_wm_state_maximized_vert);
10312 break;
10313 case FULLSCREEN_NONE:
10314 if (cur == FULLSCREEN_BOTH)
10315 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
10316 None);
10317 else
10318 set_wm_state (frame, false,
10319 dpyinfo->Xatom_net_wm_state_maximized_horz,
10320 dpyinfo->Xatom_net_wm_state_maximized_vert);
10323 f->want_fullscreen = FULLSCREEN_NONE;
10327 return have_net_atom;
10330 static void
10331 XTfullscreen_hook (struct frame *f)
10333 if (FRAME_VISIBLE_P (f))
10335 block_input ();
10336 x_check_fullscreen (f);
10337 x_sync (f);
10338 unblock_input ();
10343 static bool
10344 x_handle_net_wm_state (struct frame *f, const XPropertyEvent *event)
10346 int value = FULLSCREEN_NONE;
10347 Lisp_Object lval;
10348 bool sticky = false;
10349 bool not_hidden = get_current_wm_state (f, event->window, &value, &sticky);
10351 lval = Qnil;
10352 switch (value)
10354 case FULLSCREEN_WIDTH:
10355 lval = Qfullwidth;
10356 break;
10357 case FULLSCREEN_HEIGHT:
10358 lval = Qfullheight;
10359 break;
10360 case FULLSCREEN_BOTH:
10361 lval = Qfullboth;
10362 break;
10363 case FULLSCREEN_MAXIMIZED:
10364 lval = Qmaximized;
10365 break;
10368 frame_size_history_add
10369 (f, Qx_handle_net_wm_state, 0, 0,
10370 list2 (get_frame_param (f, Qfullscreen), lval));
10372 store_frame_param (f, Qfullscreen, lval);
10373 store_frame_param (f, Qsticky, sticky ? Qt : Qnil);
10375 return not_hidden;
10378 /* Check if we need to resize the frame due to a fullscreen request.
10379 If so needed, resize the frame. */
10380 static void
10381 x_check_fullscreen (struct frame *f)
10383 Lisp_Object lval = Qnil;
10385 if (do_ewmh_fullscreen (f))
10386 return;
10388 if (f->output_data.x->parent_desc != FRAME_DISPLAY_INFO (f)->root_window)
10389 return; /* Only fullscreen without WM or with EWM hints (above). */
10391 /* Setting fullscreen to nil doesn't do anything. We could save the
10392 last non-fullscreen size and restore it, but it seems like a
10393 lot of work for this unusual case (no window manager running). */
10395 if (f->want_fullscreen != FULLSCREEN_NONE)
10397 int width = FRAME_PIXEL_WIDTH (f), height = FRAME_PIXEL_HEIGHT (f);
10398 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10400 switch (f->want_fullscreen)
10402 /* No difference between these two when there is no WM */
10403 case FULLSCREEN_MAXIMIZED:
10404 lval = Qmaximized;
10405 width = x_display_pixel_width (dpyinfo);
10406 height = x_display_pixel_height (dpyinfo);
10407 break;
10408 case FULLSCREEN_BOTH:
10409 lval = Qfullboth;
10410 width = x_display_pixel_width (dpyinfo);
10411 height = x_display_pixel_height (dpyinfo);
10412 break;
10413 case FULLSCREEN_WIDTH:
10414 lval = Qfullwidth;
10415 width = x_display_pixel_width (dpyinfo);
10416 height = height + FRAME_MENUBAR_HEIGHT (f);
10417 break;
10418 case FULLSCREEN_HEIGHT:
10419 lval = Qfullheight;
10420 height = x_display_pixel_height (dpyinfo);
10421 break;
10422 default:
10423 emacs_abort ();
10426 frame_size_history_add
10427 (f, Qx_check_fullscreen, width, height, Qnil);
10429 x_wm_set_size_hint (f, 0, false);
10431 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
10432 width, height);
10434 if (FRAME_VISIBLE_P (f))
10435 x_wait_for_event (f, ConfigureNotify);
10436 else
10438 change_frame_size (f, width, height - FRAME_MENUBAR_HEIGHT (f),
10439 false, true, false, true);
10440 x_sync (f);
10444 /* `x_net_wm_state' might have reset the fullscreen frame parameter,
10445 restore it. */
10446 store_frame_param (f, Qfullscreen, lval);
10449 /* This function is called by x_set_offset to determine whether the window
10450 manager interfered with the positioning of the frame. Type A window
10451 managers position the surrounding window manager decorations a small
10452 amount above and left of the user-supplied position. Type B window
10453 managers position the surrounding window manager decorations at the
10454 user-specified position. If we detect a Type A window manager, we
10455 compensate by moving the window right and down by the proper amount. */
10457 static void
10458 x_check_expected_move (struct frame *f, int expected_left, int expected_top)
10460 int current_left = 0, current_top = 0;
10462 /* x_real_positions returns the left and top offsets of the outermost
10463 window manager window around the frame. */
10465 x_real_positions (f, &current_left, &current_top);
10467 if (current_left != expected_left || current_top != expected_top)
10469 /* It's a "Type A" window manager. */
10471 int adjusted_left;
10472 int adjusted_top;
10474 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_A;
10475 FRAME_X_OUTPUT (f)->move_offset_left = expected_left - current_left;
10476 FRAME_X_OUTPUT (f)->move_offset_top = expected_top - current_top;
10478 /* Now fix the mispositioned frame's location. */
10480 adjusted_left = expected_left + FRAME_X_OUTPUT (f)->move_offset_left;
10481 adjusted_top = expected_top + FRAME_X_OUTPUT (f)->move_offset_top;
10483 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
10484 adjusted_left, adjusted_top);
10486 x_sync_with_move (f, expected_left, expected_top, false);
10488 else
10489 /* It's a "Type B" window manager. We don't have to adjust the
10490 frame's position. */
10492 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_B;
10496 /* Wait for XGetGeometry to return up-to-date position information for a
10497 recently-moved frame. Call this immediately after calling XMoveWindow.
10498 If FUZZY is non-zero, then LEFT and TOP are just estimates of where the
10499 frame has been moved to, so we use a fuzzy position comparison instead
10500 of an exact comparison. */
10502 static void
10503 x_sync_with_move (struct frame *f, int left, int top, bool fuzzy)
10505 int count = 0;
10507 while (count++ < 50)
10509 int current_left = 0, current_top = 0;
10511 /* In theory, this call to XSync only needs to happen once, but in
10512 practice, it doesn't seem to work, hence the need for the surrounding
10513 loop. */
10515 XSync (FRAME_X_DISPLAY (f), False);
10516 x_real_positions (f, &current_left, &current_top);
10518 if (fuzzy)
10520 /* The left fuzz-factor is 10 pixels. The top fuzz-factor is 40
10521 pixels. */
10523 if (eabs (current_left - left) <= 10
10524 && eabs (current_top - top) <= 40)
10525 return;
10527 else if (current_left == left && current_top == top)
10528 return;
10531 /* As a last resort, just wait 0.5 seconds and hope that XGetGeometry
10532 will then return up-to-date position info. */
10534 wait_reading_process_output (0, 500000000, 0, false, Qnil, NULL, 0);
10538 /* Wait for an event on frame F matching EVENTTYPE. */
10539 void
10540 x_wait_for_event (struct frame *f, int eventtype)
10542 int level = interrupt_input_blocked;
10544 fd_set fds;
10545 struct timespec tmo, tmo_at, time_now;
10546 int fd = ConnectionNumber (FRAME_X_DISPLAY (f));
10548 f->wait_event_type = eventtype;
10550 /* Set timeout to 0.1 second. Hopefully not noticeable.
10551 Maybe it should be configurable. */
10552 tmo = make_timespec (0, 100 * 1000 * 1000);
10553 tmo_at = timespec_add (current_timespec (), tmo);
10555 while (f->wait_event_type)
10557 pending_signals = true;
10558 totally_unblock_input ();
10559 /* XTread_socket is called after unblock. */
10560 block_input ();
10561 interrupt_input_blocked = level;
10563 FD_ZERO (&fds);
10564 FD_SET (fd, &fds);
10566 time_now = current_timespec ();
10567 if (timespec_cmp (tmo_at, time_now) < 0)
10568 break;
10570 tmo = timespec_sub (tmo_at, time_now);
10571 if (pselect (fd + 1, &fds, NULL, NULL, &tmo, NULL) == 0)
10572 break; /* Timeout */
10575 f->wait_event_type = 0;
10579 /* Change the size of frame F's X window to WIDTH/HEIGHT in the case F
10580 doesn't have a widget. If CHANGE_GRAVITY, change to
10581 top-left-corner window gravity for this size change and subsequent
10582 size changes. Otherwise leave the window gravity unchanged. */
10584 static void
10585 x_set_window_size_1 (struct frame *f, bool change_gravity,
10586 int width, int height)
10588 int pixelwidth = FRAME_TEXT_TO_PIXEL_WIDTH (f, width);
10589 int pixelheight = FRAME_TEXT_TO_PIXEL_HEIGHT (f, height);
10590 int old_width = FRAME_PIXEL_WIDTH (f);
10591 int old_height = FRAME_PIXEL_HEIGHT (f);
10592 Lisp_Object fullscreen = get_frame_param (f, Qfullscreen);
10594 if (change_gravity) f->win_gravity = NorthWestGravity;
10595 x_wm_set_size_hint (f, 0, false);
10597 /* When the frame is fullheight and we only want to change the width
10598 or it is fullwidth and we only want to change the height we should
10599 be able to preserve the fullscreen property. However, due to the
10600 fact that we have to send a resize request anyway, the window
10601 manager will abolish it. At least the respective size should
10602 remain unchanged but giving the frame back its normal size will
10603 be broken ... */
10604 if (EQ (fullscreen, Qfullwidth) && width == FRAME_TEXT_WIDTH (f))
10606 frame_size_history_add
10607 (f, Qx_set_window_size_1, width, height,
10608 list2 (make_number (old_height),
10609 make_number (pixelheight + FRAME_MENUBAR_HEIGHT (f))));
10611 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
10612 old_width, pixelheight + FRAME_MENUBAR_HEIGHT (f));
10614 else if (EQ (fullscreen, Qfullheight) && height == FRAME_TEXT_HEIGHT (f))
10616 frame_size_history_add
10617 (f, Qx_set_window_size_2, width, height,
10618 list2 (make_number (old_width), make_number (pixelwidth)));
10620 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
10621 pixelwidth, old_height);
10624 else
10626 frame_size_history_add
10627 (f, Qx_set_window_size_3, width, height,
10628 list3 (make_number (pixelwidth + FRAME_TOOLBAR_WIDTH (f)),
10629 make_number (pixelheight + FRAME_TOOLBAR_HEIGHT (f)
10630 + FRAME_MENUBAR_HEIGHT (f)),
10631 make_number (FRAME_MENUBAR_HEIGHT (f))));
10633 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
10634 pixelwidth, pixelheight + FRAME_MENUBAR_HEIGHT (f));
10635 fullscreen = Qnil;
10640 /* We've set {FRAME,PIXEL}_{WIDTH,HEIGHT} to the values we hope to
10641 receive in the ConfigureNotify event; if we get what we asked
10642 for, then the event won't cause the screen to become garbaged, so
10643 we have to make sure to do it here. */
10644 SET_FRAME_GARBAGED (f);
10646 /* Now, strictly speaking, we can't be sure that this is accurate,
10647 but the window manager will get around to dealing with the size
10648 change request eventually, and we'll hear how it went when the
10649 ConfigureNotify event gets here.
10651 We could just not bother storing any of this information here,
10652 and let the ConfigureNotify event set everything up, but that
10653 might be kind of confusing to the Lisp code, since size changes
10654 wouldn't be reported in the frame parameters until some random
10655 point in the future when the ConfigureNotify event arrives.
10657 Pass true for DELAY since we can't run Lisp code inside of
10658 a BLOCK_INPUT. */
10660 /* But the ConfigureNotify may in fact never arrive, and then this is
10661 not right if the frame is visible. Instead wait (with timeout)
10662 for the ConfigureNotify. */
10663 if (FRAME_VISIBLE_P (f))
10665 x_wait_for_event (f, ConfigureNotify);
10667 if (!NILP (fullscreen))
10668 /* Try to restore fullscreen state. */
10670 store_frame_param (f, Qfullscreen, fullscreen);
10671 x_set_fullscreen (f, fullscreen, fullscreen);
10674 else
10676 change_frame_size (f, width, height, false, true, false, true);
10677 x_sync (f);
10682 /* Call this to change the size of frame F's x-window.
10683 If CHANGE_GRAVITY, change to top-left-corner window gravity
10684 for this size change and subsequent size changes.
10685 Otherwise we leave the window gravity unchanged. */
10687 void
10688 x_set_window_size (struct frame *f, bool change_gravity,
10689 int width, int height, bool pixelwise)
10691 block_input ();
10693 /* The following breaks our calculations. If it's really needed,
10694 think of something else. */
10695 #if false
10696 if (NILP (tip_frame) || XFRAME (tip_frame) != f)
10698 int text_width, text_height;
10700 /* When the frame is maximized/fullscreen or running under for
10701 example Xmonad, x_set_window_size_1 will be a no-op.
10702 In that case, the right thing to do is extend rows/width to
10703 the current frame size. We do that first if x_set_window_size_1
10704 turns out to not be a no-op (there is no way to know).
10705 The size will be adjusted again if the frame gets a
10706 ConfigureNotify event as a result of x_set_window_size. */
10707 int pixelh = FRAME_PIXEL_HEIGHT (f);
10708 #ifdef USE_X_TOOLKIT
10709 /* The menu bar is not part of text lines. The tool bar
10710 is however. */
10711 pixelh -= FRAME_MENUBAR_HEIGHT (f);
10712 #endif
10713 text_width = FRAME_PIXEL_TO_TEXT_WIDTH (f, FRAME_PIXEL_WIDTH (f));
10714 text_height = FRAME_PIXEL_TO_TEXT_HEIGHT (f, pixelh);
10716 change_frame_size (f, text_width, text_height, false, true, false, true);
10718 #endif
10720 /* Pixelize width and height, if necessary. */
10721 if (! pixelwise)
10723 width = width * FRAME_COLUMN_WIDTH (f);
10724 height = height * FRAME_LINE_HEIGHT (f);
10727 #ifdef USE_GTK
10728 if (FRAME_GTK_WIDGET (f))
10729 xg_frame_set_char_size (f, width, height);
10730 else
10731 x_set_window_size_1 (f, change_gravity, width, height);
10732 #else /* not USE_GTK */
10733 x_set_window_size_1 (f, change_gravity, width, height);
10734 x_clear_under_internal_border (f);
10735 #endif /* not USE_GTK */
10737 /* If cursor was outside the new size, mark it as off. */
10738 mark_window_cursors_off (XWINDOW (f->root_window));
10740 /* Clear out any recollection of where the mouse highlighting was,
10741 since it might be in a place that's outside the new frame size.
10742 Actually checking whether it is outside is a pain in the neck,
10743 so don't try--just let the highlighting be done afresh with new size. */
10744 cancel_mouse_face (f);
10746 unblock_input ();
10748 do_pending_window_change (false);
10751 /* Move the mouse to position pixel PIX_X, PIX_Y relative to frame F. */
10753 void
10754 frame_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
10756 block_input ();
10758 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
10759 0, 0, 0, 0, pix_x, pix_y);
10760 unblock_input ();
10763 /* Raise frame F. */
10765 void
10766 x_raise_frame (struct frame *f)
10768 block_input ();
10769 if (FRAME_VISIBLE_P (f))
10770 XRaiseWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
10771 XFlush (FRAME_X_DISPLAY (f));
10772 unblock_input ();
10775 /* Lower frame F. */
10777 static void
10778 x_lower_frame (struct frame *f)
10780 if (FRAME_VISIBLE_P (f))
10782 block_input ();
10783 XLowerWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
10784 XFlush (FRAME_X_DISPLAY (f));
10785 unblock_input ();
10789 /* Request focus with XEmbed */
10791 void
10792 xembed_request_focus (struct frame *f)
10794 /* See XEmbed Protocol Specification at
10795 http://freedesktop.org/wiki/Specifications/xembed-spec */
10796 if (FRAME_VISIBLE_P (f))
10797 xembed_send_message (f, CurrentTime,
10798 XEMBED_REQUEST_FOCUS, 0, 0, 0);
10801 /* Activate frame with Extended Window Manager Hints */
10803 void
10804 x_ewmh_activate_frame (struct frame *f)
10806 /* See Window Manager Specification/Extended Window Manager Hints at
10807 http://freedesktop.org/wiki/Specifications/wm-spec */
10809 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10811 if (FRAME_VISIBLE_P (f) && x_wm_supports (f, dpyinfo->Xatom_net_active_window))
10813 Lisp_Object frame;
10814 XSETFRAME (frame, f);
10815 x_send_client_event (frame, make_number (0), frame,
10816 dpyinfo->Xatom_net_active_window,
10817 make_number (32),
10818 list2i (1, dpyinfo->last_user_time));
10822 static void
10823 XTframe_raise_lower (struct frame *f, bool raise_flag)
10825 if (raise_flag)
10826 x_raise_frame (f);
10827 else
10828 x_lower_frame (f);
10831 /* XEmbed implementation. */
10833 #if defined USE_X_TOOLKIT || ! defined USE_GTK
10835 /* XEmbed implementation. */
10837 #define XEMBED_VERSION 0
10839 static void
10840 xembed_set_info (struct frame *f, enum xembed_info flags)
10842 unsigned long data[2];
10843 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10845 data[0] = XEMBED_VERSION;
10846 data[1] = flags;
10848 XChangeProperty (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
10849 dpyinfo->Xatom_XEMBED_INFO, dpyinfo->Xatom_XEMBED_INFO,
10850 32, PropModeReplace, (unsigned char *) data, 2);
10852 #endif /* defined USE_X_TOOLKIT || ! defined USE_GTK */
10854 static void
10855 xembed_send_message (struct frame *f, Time t, enum xembed_message msg,
10856 long int detail, long int data1, long int data2)
10858 XEvent event;
10860 event.xclient.type = ClientMessage;
10861 event.xclient.window = FRAME_X_OUTPUT (f)->parent_desc;
10862 event.xclient.message_type = FRAME_DISPLAY_INFO (f)->Xatom_XEMBED;
10863 event.xclient.format = 32;
10864 event.xclient.data.l[0] = t;
10865 event.xclient.data.l[1] = msg;
10866 event.xclient.data.l[2] = detail;
10867 event.xclient.data.l[3] = data1;
10868 event.xclient.data.l[4] = data2;
10870 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_OUTPUT (f)->parent_desc,
10871 False, NoEventMask, &event);
10872 XSync (FRAME_X_DISPLAY (f), False);
10875 /* Change of visibility. */
10877 /* This tries to wait until the frame is really visible.
10878 However, if the window manager asks the user where to position
10879 the frame, this will return before the user finishes doing that.
10880 The frame will not actually be visible at that time,
10881 but it will become visible later when the window manager
10882 finishes with it. */
10884 void
10885 x_make_frame_visible (struct frame *f)
10887 int original_top, original_left;
10888 int tries = 0;
10890 block_input ();
10892 x_set_bitmap_icon (f);
10894 if (! FRAME_VISIBLE_P (f))
10896 /* We test FRAME_GARBAGED_P here to make sure we don't
10897 call x_set_offset a second time
10898 if we get to x_make_frame_visible a second time
10899 before the window gets really visible. */
10900 if (! FRAME_ICONIFIED_P (f)
10901 && ! FRAME_X_EMBEDDED_P (f)
10902 && ! f->output_data.x->asked_for_visible)
10903 x_set_offset (f, f->left_pos, f->top_pos, 0);
10905 f->output_data.x->asked_for_visible = true;
10907 if (! EQ (Vx_no_window_manager, Qt))
10908 x_wm_set_window_state (f, NormalState);
10909 #ifdef USE_X_TOOLKIT
10910 if (FRAME_X_EMBEDDED_P (f))
10911 xembed_set_info (f, XEMBED_MAPPED);
10912 else
10914 /* This was XtPopup, but that did nothing for an iconified frame. */
10915 XtMapWidget (f->output_data.x->widget);
10917 #else /* not USE_X_TOOLKIT */
10918 #ifdef USE_GTK
10919 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
10920 gtk_window_deiconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
10921 #else
10922 if (FRAME_X_EMBEDDED_P (f))
10923 xembed_set_info (f, XEMBED_MAPPED);
10924 else
10925 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
10926 #endif /* not USE_GTK */
10927 #endif /* not USE_X_TOOLKIT */
10930 XFlush (FRAME_X_DISPLAY (f));
10932 /* Synchronize to ensure Emacs knows the frame is visible
10933 before we do anything else. We do this loop with input not blocked
10934 so that incoming events are handled. */
10936 Lisp_Object frame;
10937 /* This must be before UNBLOCK_INPUT
10938 since events that arrive in response to the actions above
10939 will set it when they are handled. */
10940 bool previously_visible = f->output_data.x->has_been_visible;
10942 original_left = f->left_pos;
10943 original_top = f->top_pos;
10945 /* This must come after we set COUNT. */
10946 unblock_input ();
10948 /* We unblock here so that arriving X events are processed. */
10950 /* Now move the window back to where it was "supposed to be".
10951 But don't do it if the gravity is negative.
10952 When the gravity is negative, this uses a position
10953 that is 3 pixels too low. Perhaps that's really the border width.
10955 Don't do this if the window has never been visible before,
10956 because the window manager may choose the position
10957 and we don't want to override it. */
10959 if (! FRAME_VISIBLE_P (f)
10960 && ! FRAME_ICONIFIED_P (f)
10961 && ! FRAME_X_EMBEDDED_P (f)
10962 && f->win_gravity == NorthWestGravity
10963 && previously_visible)
10965 Drawable rootw;
10966 int x, y;
10967 unsigned int width, height, border, depth;
10969 block_input ();
10971 /* On some window managers (such as FVWM) moving an existing
10972 window, even to the same place, causes the window manager
10973 to introduce an offset. This can cause the window to move
10974 to an unexpected location. Check the geometry (a little
10975 slow here) and then verify that the window is in the right
10976 place. If the window is not in the right place, move it
10977 there, and take the potential window manager hit. */
10978 XGetGeometry (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
10979 &rootw, &x, &y, &width, &height, &border, &depth);
10981 if (original_left != x || original_top != y)
10982 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
10983 original_left, original_top);
10985 unblock_input ();
10988 XSETFRAME (frame, f);
10990 /* Process X events until a MapNotify event has been seen. */
10991 while (!FRAME_VISIBLE_P (f))
10993 /* Force processing of queued events. */
10994 x_sync (f);
10996 /* If on another desktop, the deiconify/map may be ignored and the
10997 frame never becomes visible. XMonad does this.
10998 Prevent an endless loop. */
10999 if (FRAME_ICONIFIED_P (f) && ++tries > 100)
11000 break;
11002 /* This hack is still in use at least for Cygwin. See
11003 http://lists.gnu.org/archive/html/emacs-devel/2013-12/msg00351.html.
11005 Machines that do polling rather than SIGIO have been
11006 observed to go into a busy-wait here. So we'll fake an
11007 alarm signal to let the handler know that there's something
11008 to be read. We used to raise a real alarm, but it seems
11009 that the handler isn't always enabled here. This is
11010 probably a bug. */
11011 if (input_polling_used ())
11013 /* It could be confusing if a real alarm arrives while
11014 processing the fake one. Turn it off and let the
11015 handler reset it. */
11016 int old_poll_suppress_count = poll_suppress_count;
11017 poll_suppress_count = 1;
11018 poll_for_input_1 ();
11019 poll_suppress_count = old_poll_suppress_count;
11022 if (XPending (FRAME_X_DISPLAY (f)))
11024 XEvent xev;
11025 XNextEvent (FRAME_X_DISPLAY (f), &xev);
11026 x_dispatch_event (&xev, FRAME_X_DISPLAY (f));
11032 /* Change from mapped state to withdrawn state. */
11034 /* Make the frame visible (mapped and not iconified). */
11036 void
11037 x_make_frame_invisible (struct frame *f)
11039 Window window;
11041 /* Use the frame's outermost window, not the one we normally draw on. */
11042 window = FRAME_OUTER_WINDOW (f);
11044 /* Don't keep the highlight on an invisible frame. */
11045 if (FRAME_DISPLAY_INFO (f)->x_highlight_frame == f)
11046 FRAME_DISPLAY_INFO (f)->x_highlight_frame = 0;
11048 block_input ();
11050 /* Before unmapping the window, update the WM_SIZE_HINTS property to claim
11051 that the current position of the window is user-specified, rather than
11052 program-specified, so that when the window is mapped again, it will be
11053 placed at the same location, without forcing the user to position it
11054 by hand again (they have already done that once for this window.) */
11055 x_wm_set_size_hint (f, 0, true);
11057 #ifdef USE_GTK
11058 if (FRAME_GTK_OUTER_WIDGET (f))
11059 gtk_widget_hide (FRAME_GTK_OUTER_WIDGET (f));
11060 else
11061 #else
11062 if (FRAME_X_EMBEDDED_P (f))
11063 xembed_set_info (f, 0);
11064 else
11065 #endif
11068 if (! XWithdrawWindow (FRAME_X_DISPLAY (f), window,
11069 DefaultScreen (FRAME_X_DISPLAY (f))))
11071 unblock_input ();
11072 error ("Can't notify window manager of window withdrawal");
11076 /* We can't distinguish this from iconification
11077 just by the event that we get from the server.
11078 So we can't win using the usual strategy of letting
11079 FRAME_SAMPLE_VISIBILITY set this. So do it by hand,
11080 and synchronize with the server to make sure we agree. */
11081 SET_FRAME_VISIBLE (f, 0);
11082 SET_FRAME_ICONIFIED (f, false);
11084 x_sync (f);
11086 unblock_input ();
11089 /* Change window state from mapped to iconified. */
11091 void
11092 x_iconify_frame (struct frame *f)
11094 #ifdef USE_X_TOOLKIT
11095 int result;
11096 #endif
11098 /* Don't keep the highlight on an invisible frame. */
11099 if (FRAME_DISPLAY_INFO (f)->x_highlight_frame == f)
11100 FRAME_DISPLAY_INFO (f)->x_highlight_frame = 0;
11102 if (FRAME_ICONIFIED_P (f))
11103 return;
11105 block_input ();
11107 x_set_bitmap_icon (f);
11109 #if defined (USE_GTK)
11110 if (FRAME_GTK_OUTER_WIDGET (f))
11112 if (! FRAME_VISIBLE_P (f))
11113 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
11115 gtk_window_iconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
11116 SET_FRAME_VISIBLE (f, 0);
11117 SET_FRAME_ICONIFIED (f, true);
11118 unblock_input ();
11119 return;
11121 #endif
11123 #ifdef USE_X_TOOLKIT
11125 if (! FRAME_VISIBLE_P (f))
11127 if (! EQ (Vx_no_window_manager, Qt))
11128 x_wm_set_window_state (f, IconicState);
11129 /* This was XtPopup, but that did nothing for an iconified frame. */
11130 XtMapWidget (f->output_data.x->widget);
11131 /* The server won't give us any event to indicate
11132 that an invisible frame was changed to an icon,
11133 so we have to record it here. */
11134 SET_FRAME_VISIBLE (f, 0);
11135 SET_FRAME_ICONIFIED (f, true);
11136 unblock_input ();
11137 return;
11140 result = XIconifyWindow (FRAME_X_DISPLAY (f),
11141 XtWindow (f->output_data.x->widget),
11142 DefaultScreen (FRAME_X_DISPLAY (f)));
11143 unblock_input ();
11145 if (!result)
11146 error ("Can't notify window manager of iconification");
11148 SET_FRAME_ICONIFIED (f, true);
11149 SET_FRAME_VISIBLE (f, 0);
11151 block_input ();
11152 XFlush (FRAME_X_DISPLAY (f));
11153 unblock_input ();
11154 #else /* not USE_X_TOOLKIT */
11156 /* Make sure the X server knows where the window should be positioned,
11157 in case the user deiconifies with the window manager. */
11158 if (! FRAME_VISIBLE_P (f)
11159 && ! FRAME_ICONIFIED_P (f)
11160 && ! FRAME_X_EMBEDDED_P (f))
11161 x_set_offset (f, f->left_pos, f->top_pos, 0);
11163 /* Since we don't know which revision of X we're running, we'll use both
11164 the X11R3 and X11R4 techniques. I don't know if this is a good idea. */
11166 /* X11R4: send a ClientMessage to the window manager using the
11167 WM_CHANGE_STATE type. */
11169 XEvent msg;
11171 msg.xclient.window = FRAME_X_WINDOW (f);
11172 msg.xclient.type = ClientMessage;
11173 msg.xclient.message_type = FRAME_DISPLAY_INFO (f)->Xatom_wm_change_state;
11174 msg.xclient.format = 32;
11175 msg.xclient.data.l[0] = IconicState;
11177 if (! XSendEvent (FRAME_X_DISPLAY (f),
11178 DefaultRootWindow (FRAME_X_DISPLAY (f)),
11179 False,
11180 SubstructureRedirectMask | SubstructureNotifyMask,
11181 &msg))
11183 unblock_input ();
11184 error ("Can't notify window manager of iconification");
11188 /* X11R3: set the initial_state field of the window manager hints to
11189 IconicState. */
11190 x_wm_set_window_state (f, IconicState);
11192 if (!FRAME_VISIBLE_P (f))
11194 /* If the frame was withdrawn, before, we must map it. */
11195 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11198 SET_FRAME_ICONIFIED (f, true);
11199 SET_FRAME_VISIBLE (f, 0);
11201 XFlush (FRAME_X_DISPLAY (f));
11202 unblock_input ();
11203 #endif /* not USE_X_TOOLKIT */
11207 /* Free X resources of frame F. */
11209 void
11210 x_free_frame_resources (struct frame *f)
11212 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
11213 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
11214 #ifdef USE_X_TOOLKIT
11215 Lisp_Object bar;
11216 struct scroll_bar *b;
11217 #endif
11219 block_input ();
11221 /* If a display connection is dead, don't try sending more
11222 commands to the X server. */
11223 if (dpyinfo->display)
11225 /* Always exit with visible pointer to avoid weird issue
11226 with Xfixes (Bug#17609). */
11227 if (f->pointer_invisible)
11228 FRAME_DISPLAY_INFO (f)->toggle_visible_pointer (f, 0);
11230 /* We must free faces before destroying windows because some
11231 font-driver (e.g. xft) access a window while finishing a
11232 face. */
11233 free_frame_faces (f);
11235 if (f->output_data.x->icon_desc)
11236 XDestroyWindow (FRAME_X_DISPLAY (f), f->output_data.x->icon_desc);
11238 #ifdef USE_X_TOOLKIT
11239 /* Explicitly destroy the scroll bars of the frame. Without
11240 this, we get "BadDrawable" errors from the toolkit later on,
11241 presumably from expose events generated for the disappearing
11242 toolkit scroll bars. */
11243 for (bar = FRAME_SCROLL_BARS (f); !NILP (bar); bar = b->next)
11245 b = XSCROLL_BAR (bar);
11246 x_scroll_bar_remove (b);
11248 #endif
11250 #ifdef HAVE_X_I18N
11251 if (FRAME_XIC (f))
11252 free_frame_xic (f);
11253 #endif
11255 x_free_cr_resources (f);
11256 #ifdef USE_X_TOOLKIT
11257 if (f->output_data.x->widget)
11259 XtDestroyWidget (f->output_data.x->widget);
11260 f->output_data.x->widget = NULL;
11262 /* Tooltips don't have widgets, only a simple X window, even if
11263 we are using a toolkit. */
11264 else if (FRAME_X_WINDOW (f))
11265 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11267 free_frame_menubar (f);
11269 if (f->shell_position)
11270 xfree (f->shell_position);
11271 #else /* !USE_X_TOOLKIT */
11273 #ifdef USE_GTK
11274 xg_free_frame_widgets (f);
11275 #endif /* USE_GTK */
11277 if (FRAME_X_WINDOW (f))
11278 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11279 #endif /* !USE_X_TOOLKIT */
11281 unload_color (f, FRAME_FOREGROUND_PIXEL (f));
11282 unload_color (f, FRAME_BACKGROUND_PIXEL (f));
11283 unload_color (f, f->output_data.x->cursor_pixel);
11284 unload_color (f, f->output_data.x->cursor_foreground_pixel);
11285 unload_color (f, f->output_data.x->border_pixel);
11286 unload_color (f, f->output_data.x->mouse_pixel);
11288 if (f->output_data.x->scroll_bar_background_pixel != -1)
11289 unload_color (f, f->output_data.x->scroll_bar_background_pixel);
11290 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
11291 unload_color (f, f->output_data.x->scroll_bar_foreground_pixel);
11292 #if defined (USE_LUCID) && defined (USE_TOOLKIT_SCROLL_BARS)
11293 /* Scrollbar shadow colors. */
11294 if (f->output_data.x->scroll_bar_top_shadow_pixel != -1)
11295 unload_color (f, f->output_data.x->scroll_bar_top_shadow_pixel);
11296 if (f->output_data.x->scroll_bar_bottom_shadow_pixel != -1)
11297 unload_color (f, f->output_data.x->scroll_bar_bottom_shadow_pixel);
11298 #endif /* USE_LUCID && USE_TOOLKIT_SCROLL_BARS */
11299 if (f->output_data.x->white_relief.pixel != -1)
11300 unload_color (f, f->output_data.x->white_relief.pixel);
11301 if (f->output_data.x->black_relief.pixel != -1)
11302 unload_color (f, f->output_data.x->black_relief.pixel);
11304 x_free_gcs (f);
11306 /* Free extra GCs allocated by x_setup_relief_colors. */
11307 if (f->output_data.x->white_relief.gc)
11309 XFreeGC (dpyinfo->display, f->output_data.x->white_relief.gc);
11310 f->output_data.x->white_relief.gc = 0;
11312 if (f->output_data.x->black_relief.gc)
11314 XFreeGC (dpyinfo->display, f->output_data.x->black_relief.gc);
11315 f->output_data.x->black_relief.gc = 0;
11318 /* Free cursors. */
11319 if (f->output_data.x->text_cursor != 0)
11320 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->text_cursor);
11321 if (f->output_data.x->nontext_cursor != 0)
11322 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->nontext_cursor);
11323 if (f->output_data.x->modeline_cursor != 0)
11324 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->modeline_cursor);
11325 if (f->output_data.x->hand_cursor != 0)
11326 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->hand_cursor);
11327 if (f->output_data.x->hourglass_cursor != 0)
11328 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->hourglass_cursor);
11329 if (f->output_data.x->horizontal_drag_cursor != 0)
11330 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->horizontal_drag_cursor);
11331 if (f->output_data.x->vertical_drag_cursor != 0)
11332 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->vertical_drag_cursor);
11334 XFlush (FRAME_X_DISPLAY (f));
11337 xfree (f->output_data.x->saved_menu_event);
11338 xfree (f->output_data.x);
11339 f->output_data.x = NULL;
11341 if (f == dpyinfo->x_focus_frame)
11342 dpyinfo->x_focus_frame = 0;
11343 if (f == dpyinfo->x_focus_event_frame)
11344 dpyinfo->x_focus_event_frame = 0;
11345 if (f == dpyinfo->x_highlight_frame)
11346 dpyinfo->x_highlight_frame = 0;
11347 if (f == hlinfo->mouse_face_mouse_frame)
11348 reset_mouse_highlight (hlinfo);
11350 unblock_input ();
11354 /* Destroy the X window of frame F. */
11356 static void
11357 x_destroy_window (struct frame *f)
11359 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
11361 /* If a display connection is dead, don't try sending more
11362 commands to the X server. */
11363 if (dpyinfo->display != 0)
11364 x_free_frame_resources (f);
11366 dpyinfo->reference_count--;
11370 /* Setting window manager hints. */
11372 /* Set the normal size hints for the window manager, for frame F.
11373 FLAGS is the flags word to use--or 0 meaning preserve the flags
11374 that the window now has.
11375 If USER_POSITION, set the USPosition
11376 flag (this is useful when FLAGS is 0).
11377 The GTK version is in gtkutils.c. */
11379 #ifndef USE_GTK
11380 void
11381 x_wm_set_size_hint (struct frame *f, long flags, bool user_position)
11383 XSizeHints size_hints;
11384 Window window = FRAME_OUTER_WINDOW (f);
11386 if (!window)
11387 return;
11389 #ifdef USE_X_TOOLKIT
11390 if (f->output_data.x->widget)
11392 widget_update_wm_size_hints (f->output_data.x->widget);
11393 return;
11395 #endif
11397 /* Setting PMaxSize caused various problems. */
11398 size_hints.flags = PResizeInc | PMinSize /* | PMaxSize */;
11400 size_hints.x = f->left_pos;
11401 size_hints.y = f->top_pos;
11403 size_hints.width = FRAME_PIXEL_WIDTH (f);
11404 size_hints.height = FRAME_PIXEL_HEIGHT (f);
11406 size_hints.width_inc = frame_resize_pixelwise ? 1 : FRAME_COLUMN_WIDTH (f);
11407 size_hints.height_inc = frame_resize_pixelwise ? 1 : FRAME_LINE_HEIGHT (f);
11409 size_hints.max_width = x_display_pixel_width (FRAME_DISPLAY_INFO (f))
11410 - FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
11411 size_hints.max_height = x_display_pixel_height (FRAME_DISPLAY_INFO (f))
11412 - FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
11414 /* Calculate the base and minimum sizes. */
11416 int base_width, base_height;
11418 base_width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
11419 base_height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
11421 /* The window manager uses the base width hints to calculate the
11422 current number of rows and columns in the frame while
11423 resizing; min_width and min_height aren't useful for this
11424 purpose, since they might not give the dimensions for a
11425 zero-row, zero-column frame. */
11427 size_hints.flags |= PBaseSize;
11428 size_hints.base_width = base_width;
11429 size_hints.base_height = base_height + FRAME_MENUBAR_HEIGHT (f);
11430 size_hints.min_width = base_width;
11431 size_hints.min_height = base_height;
11434 /* If we don't need the old flags, we don't need the old hint at all. */
11435 if (flags)
11437 size_hints.flags |= flags;
11438 goto no_read;
11442 XSizeHints hints; /* Sometimes I hate X Windows... */
11443 long supplied_return;
11444 int value;
11446 value = XGetWMNormalHints (FRAME_X_DISPLAY (f), window, &hints,
11447 &supplied_return);
11449 if (flags)
11450 size_hints.flags |= flags;
11451 else
11453 if (value == 0)
11454 hints.flags = 0;
11455 if (hints.flags & PSize)
11456 size_hints.flags |= PSize;
11457 if (hints.flags & PPosition)
11458 size_hints.flags |= PPosition;
11459 if (hints.flags & USPosition)
11460 size_hints.flags |= USPosition;
11461 if (hints.flags & USSize)
11462 size_hints.flags |= USSize;
11466 no_read:
11468 #ifdef PWinGravity
11469 size_hints.win_gravity = f->win_gravity;
11470 size_hints.flags |= PWinGravity;
11472 if (user_position)
11474 size_hints.flags &= ~ PPosition;
11475 size_hints.flags |= USPosition;
11477 #endif /* PWinGravity */
11479 XSetWMNormalHints (FRAME_X_DISPLAY (f), window, &size_hints);
11481 #endif /* not USE_GTK */
11483 /* Used for IconicState or NormalState */
11485 static void
11486 x_wm_set_window_state (struct frame *f, int state)
11488 #ifdef USE_X_TOOLKIT
11489 Arg al[1];
11491 XtSetArg (al[0], XtNinitialState, state);
11492 XtSetValues (f->output_data.x->widget, al, 1);
11493 #else /* not USE_X_TOOLKIT */
11494 Window window = FRAME_X_WINDOW (f);
11496 f->output_data.x->wm_hints.flags |= StateHint;
11497 f->output_data.x->wm_hints.initial_state = state;
11499 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
11500 #endif /* not USE_X_TOOLKIT */
11503 static void
11504 x_wm_set_icon_pixmap (struct frame *f, ptrdiff_t pixmap_id)
11506 Pixmap icon_pixmap, icon_mask;
11508 #if !defined USE_X_TOOLKIT && !defined USE_GTK
11509 Window window = FRAME_OUTER_WINDOW (f);
11510 #endif
11512 if (pixmap_id > 0)
11514 icon_pixmap = x_bitmap_pixmap (f, pixmap_id);
11515 f->output_data.x->wm_hints.icon_pixmap = icon_pixmap;
11516 icon_mask = x_bitmap_mask (f, pixmap_id);
11517 f->output_data.x->wm_hints.icon_mask = icon_mask;
11519 else
11521 /* It seems there is no way to turn off use of an icon
11522 pixmap. */
11523 return;
11527 #ifdef USE_GTK
11529 xg_set_frame_icon (f, icon_pixmap, icon_mask);
11530 return;
11533 #elif defined (USE_X_TOOLKIT) /* same as in x_wm_set_window_state. */
11536 Arg al[1];
11537 XtSetArg (al[0], XtNiconPixmap, icon_pixmap);
11538 XtSetValues (f->output_data.x->widget, al, 1);
11539 XtSetArg (al[0], XtNiconMask, icon_mask);
11540 XtSetValues (f->output_data.x->widget, al, 1);
11543 #else /* not USE_X_TOOLKIT && not USE_GTK */
11545 f->output_data.x->wm_hints.flags |= (IconPixmapHint | IconMaskHint);
11546 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
11548 #endif /* not USE_X_TOOLKIT && not USE_GTK */
11551 void
11552 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
11554 Window window = FRAME_OUTER_WINDOW (f);
11556 f->output_data.x->wm_hints.flags |= IconPositionHint;
11557 f->output_data.x->wm_hints.icon_x = icon_x;
11558 f->output_data.x->wm_hints.icon_y = icon_y;
11560 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
11564 /***********************************************************************
11565 Fonts
11566 ***********************************************************************/
11568 #ifdef GLYPH_DEBUG
11570 /* Check that FONT is valid on frame F. It is if it can be found in F's
11571 font table. */
11573 static void
11574 x_check_font (struct frame *f, struct font *font)
11576 eassert (font != NULL && ! NILP (font->props[FONT_TYPE_INDEX]));
11577 if (font->driver->check)
11578 eassert (font->driver->check (f, font) == 0);
11581 #endif /* GLYPH_DEBUG */
11584 /***********************************************************************
11585 Initialization
11586 ***********************************************************************/
11588 #ifdef USE_X_TOOLKIT
11589 static XrmOptionDescRec emacs_options[] = {
11590 {"-geometry", ".geometry", XrmoptionSepArg, NULL},
11591 {"-iconic", ".iconic", XrmoptionNoArg, (XtPointer) "yes"},
11593 {"-internal-border-width", "*EmacsScreen.internalBorderWidth",
11594 XrmoptionSepArg, NULL},
11595 {"-ib", "*EmacsScreen.internalBorderWidth", XrmoptionSepArg, NULL},
11597 {"-T", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
11598 {"-wn", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
11599 {"-title", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
11600 {"-iconname", "*EmacsShell.iconName", XrmoptionSepArg, (XtPointer) NULL},
11601 {"-in", "*EmacsShell.iconName", XrmoptionSepArg, (XtPointer) NULL},
11602 {"-mc", "*pointerColor", XrmoptionSepArg, (XtPointer) NULL},
11603 {"-cr", "*cursorColor", XrmoptionSepArg, (XtPointer) NULL}
11606 /* Whether atimer for Xt timeouts is activated or not. */
11608 static bool x_timeout_atimer_activated_flag;
11610 #endif /* USE_X_TOOLKIT */
11612 static int x_initialized;
11614 /* Test whether two display-name strings agree up to the dot that separates
11615 the screen number from the server number. */
11616 static bool
11617 same_x_server (const char *name1, const char *name2)
11619 bool seen_colon = false;
11620 Lisp_Object sysname = Fsystem_name ();
11621 const char *system_name = SSDATA (sysname);
11622 ptrdiff_t system_name_length = SBYTES (sysname);
11623 ptrdiff_t length_until_period = 0;
11625 while (system_name[length_until_period] != 0
11626 && system_name[length_until_period] != '.')
11627 length_until_period++;
11629 /* Treat `unix' like an empty host name. */
11630 if (! strncmp (name1, "unix:", 5))
11631 name1 += 4;
11632 if (! strncmp (name2, "unix:", 5))
11633 name2 += 4;
11634 /* Treat this host's name like an empty host name. */
11635 if (! strncmp (name1, system_name, system_name_length)
11636 && name1[system_name_length] == ':')
11637 name1 += system_name_length;
11638 if (! strncmp (name2, system_name, system_name_length)
11639 && name2[system_name_length] == ':')
11640 name2 += system_name_length;
11641 /* Treat this host's domainless name like an empty host name. */
11642 if (! strncmp (name1, system_name, length_until_period)
11643 && name1[length_until_period] == ':')
11644 name1 += length_until_period;
11645 if (! strncmp (name2, system_name, length_until_period)
11646 && name2[length_until_period] == ':')
11647 name2 += length_until_period;
11649 for (; *name1 != '\0' && *name1 == *name2; name1++, name2++)
11651 if (*name1 == ':')
11652 seen_colon = true;
11653 if (seen_colon && *name1 == '.')
11654 return true;
11656 return (seen_colon
11657 && (*name1 == '.' || *name1 == '\0')
11658 && (*name2 == '.' || *name2 == '\0'));
11661 /* Count number of set bits in mask and number of bits to shift to
11662 get to the first bit. With MASK 0x7e0, *BITS is set to 6, and *OFFSET
11663 to 5. */
11664 static void
11665 get_bits_and_offset (unsigned long mask, int *bits, int *offset)
11667 int nr = 0;
11668 int off = 0;
11670 while (!(mask & 1))
11672 off++;
11673 mask >>= 1;
11676 while (mask & 1)
11678 nr++;
11679 mask >>= 1;
11682 *offset = off;
11683 *bits = nr;
11686 /* Return true iff display DISPLAY is available for use.
11687 But don't permanently open it, just test its availability. */
11689 bool
11690 x_display_ok (const char *display)
11692 /* XOpenDisplay fails if it gets a signal. Block SIGIO which may arrive. */
11693 unrequest_sigio ();
11694 Display *dpy = XOpenDisplay (display);
11695 request_sigio ();
11696 if (!dpy)
11697 return false;
11698 XCloseDisplay (dpy);
11699 return true;
11702 #ifdef USE_GTK
11703 static void
11704 my_log_handler (const gchar *log_domain, GLogLevelFlags log_level,
11705 const gchar *msg, gpointer user_data)
11707 if (!strstr (msg, "g_set_prgname"))
11708 fprintf (stderr, "%s-WARNING **: %s\n", log_domain, msg);
11710 #endif
11712 /* Create invisible cursor on X display referred by DPYINFO. */
11714 static Cursor
11715 make_invisible_cursor (struct x_display_info *dpyinfo)
11717 Display *dpy = dpyinfo->display;
11718 static char const no_data[] = { 0 };
11719 Pixmap pix;
11720 XColor col;
11721 Cursor c = 0;
11723 x_catch_errors (dpy);
11724 pix = XCreateBitmapFromData (dpy, dpyinfo->root_window, no_data, 1, 1);
11725 if (! x_had_errors_p (dpy) && pix != None)
11727 Cursor pixc;
11728 col.pixel = 0;
11729 col.red = col.green = col.blue = 0;
11730 col.flags = DoRed | DoGreen | DoBlue;
11731 pixc = XCreatePixmapCursor (dpy, pix, pix, &col, &col, 0, 0);
11732 if (! x_had_errors_p (dpy) && pixc != None)
11733 c = pixc;
11734 XFreePixmap (dpy, pix);
11737 x_uncatch_errors ();
11739 return c;
11742 /* True if DPY supports Xfixes extension >= 4. */
11744 static bool
11745 x_probe_xfixes_extension (Display *dpy)
11747 #ifdef HAVE_XFIXES
11748 int major, minor;
11749 return XFixesQueryVersion (dpy, &major, &minor) && major >= 4;
11750 #else
11751 return false;
11752 #endif /* HAVE_XFIXES */
11755 /* Toggle mouse pointer visibility on frame F by using Xfixes functions. */
11757 static void
11758 xfixes_toggle_visible_pointer (struct frame *f, bool invisible)
11760 #ifdef HAVE_XFIXES
11761 if (invisible)
11762 XFixesHideCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11763 else
11764 XFixesShowCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
11765 f->pointer_invisible = invisible;
11766 #else
11767 emacs_abort ();
11768 #endif /* HAVE_XFIXES */
11771 /* Toggle mouse pointer visibility on frame F by using invisible cursor. */
11773 static void
11774 x_toggle_visible_pointer (struct frame *f, bool invisible)
11776 eassert (FRAME_DISPLAY_INFO (f)->invisible_cursor != 0);
11777 if (invisible)
11778 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
11779 FRAME_DISPLAY_INFO (f)->invisible_cursor);
11780 else
11781 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
11782 f->output_data.x->current_cursor);
11783 f->pointer_invisible = invisible;
11786 /* Setup pointer blanking, prefer Xfixes if available. */
11788 static void
11789 x_setup_pointer_blanking (struct x_display_info *dpyinfo)
11791 /* FIXME: the brave tester should set EMACS_XFIXES because we're suspecting
11792 X server bug, see http://debbugs.gnu.org/cgi/bugreport.cgi?bug=17609. */
11793 if (egetenv ("EMACS_XFIXES") && x_probe_xfixes_extension (dpyinfo->display))
11794 dpyinfo->toggle_visible_pointer = xfixes_toggle_visible_pointer;
11795 else
11797 dpyinfo->toggle_visible_pointer = x_toggle_visible_pointer;
11798 dpyinfo->invisible_cursor = make_invisible_cursor (dpyinfo);
11802 /* Current X display connection identifier. Incremented for each next
11803 connection established. */
11804 static unsigned x_display_id;
11806 /* Open a connection to X display DISPLAY_NAME, and return
11807 the structure that describes the open display.
11808 If we cannot contact the display, return null. */
11810 struct x_display_info *
11811 x_term_init (Lisp_Object display_name, char *xrm_option, char *resource_name)
11813 Display *dpy;
11814 struct terminal *terminal;
11815 struct x_display_info *dpyinfo;
11816 XrmDatabase xrdb;
11817 #ifdef USE_XCB
11818 xcb_connection_t *xcb_conn;
11819 #endif
11821 block_input ();
11823 if (!x_initialized)
11825 x_initialize ();
11826 ++x_initialized;
11829 if (! x_display_ok (SSDATA (display_name)))
11830 error ("Display %s can't be opened", SSDATA (display_name));
11832 #ifdef USE_GTK
11834 #define NUM_ARGV 10
11835 int argc;
11836 char *argv[NUM_ARGV];
11837 char **argv2 = argv;
11838 guint id;
11840 if (x_initialized++ > 1)
11842 xg_display_open (SSDATA (display_name), &dpy);
11844 else
11846 static char display_opt[] = "--display";
11847 static char name_opt[] = "--name";
11849 for (argc = 0; argc < NUM_ARGV; ++argc)
11850 argv[argc] = 0;
11852 argc = 0;
11853 argv[argc++] = initial_argv[0];
11855 if (! NILP (display_name))
11857 argv[argc++] = display_opt;
11858 argv[argc++] = SSDATA (display_name);
11861 argv[argc++] = name_opt;
11862 argv[argc++] = resource_name;
11864 XSetLocaleModifiers ("");
11866 /* Work around GLib bug that outputs a faulty warning. See
11867 https://bugzilla.gnome.org/show_bug.cgi?id=563627. */
11868 id = g_log_set_handler ("GLib", G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
11869 | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
11871 /* NULL window -> events for all windows go to our function.
11872 Call before gtk_init so Gtk+ event filters comes after our. */
11873 gdk_window_add_filter (NULL, event_handler_gdk, NULL);
11875 /* gtk_init does set_locale. Fix locale before and after. */
11876 fixup_locale ();
11877 unrequest_sigio (); /* See comment in x_display_ok. */
11878 gtk_init (&argc, &argv2);
11879 request_sigio ();
11880 fixup_locale ();
11882 g_log_remove_handler ("GLib", id);
11884 xg_initialize ();
11886 dpy = DEFAULT_GDK_DISPLAY ();
11888 #if ! GTK_CHECK_VERSION (2, 90, 0)
11889 /* Load our own gtkrc if it exists. */
11891 const char *file = "~/.emacs.d/gtkrc";
11892 Lisp_Object s, abs_file;
11894 s = build_string (file);
11895 abs_file = Fexpand_file_name (s, Qnil);
11897 if (! NILP (abs_file) && !NILP (Ffile_readable_p (abs_file)))
11898 gtk_rc_parse (SSDATA (abs_file));
11900 #endif
11902 XSetErrorHandler (x_error_handler);
11903 XSetIOErrorHandler (x_io_error_quitter);
11906 #else /* not USE_GTK */
11907 #ifdef USE_X_TOOLKIT
11908 /* weiner@footloose.sps.mot.com reports that this causes
11909 errors with X11R5:
11910 X protocol error: BadAtom (invalid Atom parameter)
11911 on protocol request 18skiloaf.
11912 So let's not use it until R6. */
11913 #ifdef HAVE_X11XTR6
11914 XtSetLanguageProc (NULL, NULL, NULL);
11915 #endif
11918 int argc = 0;
11919 char *argv[3];
11921 argv[0] = "";
11922 argc = 1;
11923 if (xrm_option)
11925 argv[argc++] = "-xrm";
11926 argv[argc++] = xrm_option;
11928 turn_on_atimers (false);
11929 unrequest_sigio (); /* See comment in x_display_ok. */
11930 dpy = XtOpenDisplay (Xt_app_con, SSDATA (display_name),
11931 resource_name, EMACS_CLASS,
11932 emacs_options, XtNumber (emacs_options),
11933 &argc, argv);
11934 request_sigio ();
11935 turn_on_atimers (true);
11937 #ifdef HAVE_X11XTR6
11938 /* I think this is to compensate for XtSetLanguageProc. */
11939 fixup_locale ();
11940 #endif
11943 #else /* not USE_X_TOOLKIT */
11944 XSetLocaleModifiers ("");
11945 unrequest_sigio (); // See comment in x_display_ok.
11946 dpy = XOpenDisplay (SSDATA (display_name));
11947 request_sigio ();
11948 #endif /* not USE_X_TOOLKIT */
11949 #endif /* not USE_GTK*/
11951 /* Detect failure. */
11952 if (dpy == 0)
11954 unblock_input ();
11955 return 0;
11958 #ifdef USE_XCB
11959 xcb_conn = XGetXCBConnection (dpy);
11960 if (xcb_conn == 0)
11962 #ifdef USE_GTK
11963 xg_display_close (dpy);
11964 #else
11965 #ifdef USE_X_TOOLKIT
11966 XtCloseDisplay (dpy);
11967 #else
11968 XCloseDisplay (dpy);
11969 #endif
11970 #endif /* ! USE_GTK */
11972 unblock_input ();
11973 return 0;
11975 #endif
11977 /* We have definitely succeeded. Record the new connection. */
11979 dpyinfo = xzalloc (sizeof *dpyinfo);
11980 terminal = x_create_terminal (dpyinfo);
11983 struct x_display_info *share;
11985 for (share = x_display_list; share; share = share->next)
11986 if (same_x_server (SSDATA (XCAR (share->name_list_element)),
11987 SSDATA (display_name)))
11988 break;
11989 if (share)
11990 terminal->kboard = share->terminal->kboard;
11991 else
11993 terminal->kboard = allocate_kboard (Qx);
11995 if (!EQ (XSYMBOL (Qvendor_specific_keysyms)->function, Qunbound))
11997 char *vendor = ServerVendor (dpy);
11999 /* Temporarily hide the partially initialized terminal. */
12000 terminal_list = terminal->next_terminal;
12001 unblock_input ();
12002 kset_system_key_alist
12003 (terminal->kboard,
12004 call1 (Qvendor_specific_keysyms,
12005 vendor ? build_string (vendor) : empty_unibyte_string));
12006 block_input ();
12007 terminal->next_terminal = terminal_list;
12008 terminal_list = terminal;
12011 /* Don't let the initial kboard remain current longer than necessary.
12012 That would cause problems if a file loaded on startup tries to
12013 prompt in the mini-buffer. */
12014 if (current_kboard == initial_kboard)
12015 current_kboard = terminal->kboard;
12017 terminal->kboard->reference_count++;
12020 /* Put this display on the chain. */
12021 dpyinfo->next = x_display_list;
12022 x_display_list = dpyinfo;
12024 dpyinfo->name_list_element = Fcons (display_name, Qnil);
12025 dpyinfo->display = dpy;
12026 dpyinfo->connection = ConnectionNumber (dpyinfo->display);
12027 #ifdef USE_XCB
12028 dpyinfo->xcb_connection = xcb_conn;
12029 #endif
12031 /* http://lists.gnu.org/archive/html/emacs-devel/2015-11/msg00194.html */
12032 dpyinfo->smallest_font_height = 1;
12033 dpyinfo->smallest_char_width = 1;
12035 /* Set the name of the terminal. */
12036 terminal->name = xlispstrdup (display_name);
12038 #if false
12039 XSetAfterFunction (x_current_display, x_trace_wire);
12040 #endif
12042 Lisp_Object system_name = Fsystem_name ();
12043 ptrdiff_t nbytes;
12044 if (INT_ADD_WRAPV (SBYTES (Vinvocation_name), SBYTES (system_name) + 2,
12045 &nbytes))
12046 memory_full (SIZE_MAX);
12047 dpyinfo->x_id = ++x_display_id;
12048 dpyinfo->x_id_name = xmalloc (nbytes);
12049 char *nametail = lispstpcpy (dpyinfo->x_id_name, Vinvocation_name);
12050 *nametail++ = '@';
12051 lispstpcpy (nametail, system_name);
12053 /* Figure out which modifier bits mean what. */
12054 x_find_modifier_meanings (dpyinfo);
12056 /* Get the scroll bar cursor. */
12057 #ifdef USE_GTK
12058 /* We must create a GTK cursor, it is required for GTK widgets. */
12059 dpyinfo->xg_cursor = xg_create_default_cursor (dpyinfo->display);
12060 #endif /* USE_GTK */
12062 dpyinfo->vertical_scroll_bar_cursor
12063 = XCreateFontCursor (dpyinfo->display, XC_sb_v_double_arrow);
12065 dpyinfo->horizontal_scroll_bar_cursor
12066 = XCreateFontCursor (dpyinfo->display, XC_sb_h_double_arrow);
12068 xrdb = x_load_resources (dpyinfo->display, xrm_option,
12069 resource_name, EMACS_CLASS);
12070 #ifdef HAVE_XRMSETDATABASE
12071 XrmSetDatabase (dpyinfo->display, xrdb);
12072 #else
12073 dpyinfo->display->db = xrdb;
12074 #endif
12075 /* Put the rdb where we can find it in a way that works on
12076 all versions. */
12077 dpyinfo->xrdb = xrdb;
12079 dpyinfo->screen = ScreenOfDisplay (dpyinfo->display,
12080 DefaultScreen (dpyinfo->display));
12081 select_visual (dpyinfo);
12082 dpyinfo->cmap = DefaultColormapOfScreen (dpyinfo->screen);
12083 dpyinfo->root_window = RootWindowOfScreen (dpyinfo->screen);
12084 dpyinfo->icon_bitmap_id = -1;
12085 dpyinfo->wm_type = X_WMTYPE_UNKNOWN;
12087 reset_mouse_highlight (&dpyinfo->mouse_highlight);
12089 /* See if we can construct pixel values from RGB values. */
12090 if (dpyinfo->visual->class == TrueColor)
12092 get_bits_and_offset (dpyinfo->visual->red_mask,
12093 &dpyinfo->red_bits, &dpyinfo->red_offset);
12094 get_bits_and_offset (dpyinfo->visual->blue_mask,
12095 &dpyinfo->blue_bits, &dpyinfo->blue_offset);
12096 get_bits_and_offset (dpyinfo->visual->green_mask,
12097 &dpyinfo->green_bits, &dpyinfo->green_offset);
12100 /* See if a private colormap is requested. */
12101 if (dpyinfo->visual == DefaultVisualOfScreen (dpyinfo->screen))
12103 if (dpyinfo->visual->class == PseudoColor)
12105 AUTO_STRING (privateColormap, "privateColormap");
12106 AUTO_STRING (PrivateColormap, "PrivateColormap");
12107 Lisp_Object value
12108 = display_x_get_resource (dpyinfo, privateColormap,
12109 PrivateColormap, Qnil, Qnil);
12110 if (STRINGP (value)
12111 && (!strcmp (SSDATA (value), "true")
12112 || !strcmp (SSDATA (value), "on")))
12113 dpyinfo->cmap = XCopyColormapAndFree (dpyinfo->display, dpyinfo->cmap);
12116 else
12117 dpyinfo->cmap = XCreateColormap (dpyinfo->display, dpyinfo->root_window,
12118 dpyinfo->visual, AllocNone);
12120 #ifdef HAVE_XFT
12122 /* If we are using Xft, the following precautions should be made:
12124 1. Make sure that the Xrender extension is added before the Xft one.
12125 Otherwise, the close-display hook set by Xft is called after the one
12126 for Xrender, and the former tries to re-add the latter. This results
12127 in inconsistency of internal states and leads to X protocol error when
12128 one reconnects to the same X server (Bug#1696).
12130 2. Check dpi value in X resources. It is better we use it as well,
12131 since Xft will use it, as will all Gnome applications. If our real DPI
12132 is smaller or larger than the one Xft uses, our font will look smaller
12133 or larger than other for other applications, even if it is the same
12134 font name (monospace-10 for example). */
12136 int event_base, error_base;
12137 char *v;
12138 double d;
12140 XRenderQueryExtension (dpyinfo->display, &event_base, &error_base);
12142 v = XGetDefault (dpyinfo->display, "Xft", "dpi");
12143 if (v != NULL && sscanf (v, "%lf", &d) == 1)
12144 dpyinfo->resy = dpyinfo->resx = d;
12146 #endif
12148 if (dpyinfo->resy < 1)
12150 int screen_number = XScreenNumberOfScreen (dpyinfo->screen);
12151 double pixels = DisplayHeight (dpyinfo->display, screen_number);
12152 double mm = DisplayHeightMM (dpyinfo->display, screen_number);
12153 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
12154 dpyinfo->resy = (mm < 1) ? 100 : pixels * 25.4 / mm;
12155 pixels = DisplayWidth (dpyinfo->display, screen_number);
12156 mm = DisplayWidthMM (dpyinfo->display, screen_number);
12157 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
12158 dpyinfo->resx = (mm < 1) ? 100 : pixels * 25.4 / mm;
12162 static const struct
12164 const char *name;
12165 int offset;
12166 } atom_refs[] = {
12167 #define ATOM_REFS_INIT(string, member) \
12168 { string, offsetof (struct x_display_info, member) },
12169 ATOM_REFS_INIT ("WM_PROTOCOLS", Xatom_wm_protocols)
12170 ATOM_REFS_INIT ("WM_TAKE_FOCUS", Xatom_wm_take_focus)
12171 ATOM_REFS_INIT ("WM_SAVE_YOURSELF", Xatom_wm_save_yourself)
12172 ATOM_REFS_INIT ("WM_DELETE_WINDOW", Xatom_wm_delete_window)
12173 ATOM_REFS_INIT ("WM_CHANGE_STATE", Xatom_wm_change_state)
12174 ATOM_REFS_INIT ("WM_CONFIGURE_DENIED", Xatom_wm_configure_denied)
12175 ATOM_REFS_INIT ("WM_MOVED", Xatom_wm_window_moved)
12176 ATOM_REFS_INIT ("WM_CLIENT_LEADER", Xatom_wm_client_leader)
12177 ATOM_REFS_INIT ("Editres", Xatom_editres)
12178 ATOM_REFS_INIT ("CLIPBOARD", Xatom_CLIPBOARD)
12179 ATOM_REFS_INIT ("TIMESTAMP", Xatom_TIMESTAMP)
12180 ATOM_REFS_INIT ("TEXT", Xatom_TEXT)
12181 ATOM_REFS_INIT ("COMPOUND_TEXT", Xatom_COMPOUND_TEXT)
12182 ATOM_REFS_INIT ("UTF8_STRING", Xatom_UTF8_STRING)
12183 ATOM_REFS_INIT ("DELETE", Xatom_DELETE)
12184 ATOM_REFS_INIT ("MULTIPLE", Xatom_MULTIPLE)
12185 ATOM_REFS_INIT ("INCR", Xatom_INCR)
12186 ATOM_REFS_INIT ("_EMACS_TMP_", Xatom_EMACS_TMP)
12187 ATOM_REFS_INIT ("TARGETS", Xatom_TARGETS)
12188 ATOM_REFS_INIT ("NULL", Xatom_NULL)
12189 ATOM_REFS_INIT ("ATOM", Xatom_ATOM)
12190 ATOM_REFS_INIT ("ATOM_PAIR", Xatom_ATOM_PAIR)
12191 ATOM_REFS_INIT ("CLIPBOARD_MANAGER", Xatom_CLIPBOARD_MANAGER)
12192 ATOM_REFS_INIT ("_XEMBED_INFO", Xatom_XEMBED_INFO)
12193 /* For properties of font. */
12194 ATOM_REFS_INIT ("PIXEL_SIZE", Xatom_PIXEL_SIZE)
12195 ATOM_REFS_INIT ("AVERAGE_WIDTH", Xatom_AVERAGE_WIDTH)
12196 ATOM_REFS_INIT ("_MULE_BASELINE_OFFSET", Xatom_MULE_BASELINE_OFFSET)
12197 ATOM_REFS_INIT ("_MULE_RELATIVE_COMPOSE", Xatom_MULE_RELATIVE_COMPOSE)
12198 ATOM_REFS_INIT ("_MULE_DEFAULT_ASCENT", Xatom_MULE_DEFAULT_ASCENT)
12199 /* Ghostscript support. */
12200 ATOM_REFS_INIT ("DONE", Xatom_DONE)
12201 ATOM_REFS_INIT ("PAGE", Xatom_PAGE)
12202 ATOM_REFS_INIT ("SCROLLBAR", Xatom_Scrollbar)
12203 ATOM_REFS_INIT ("HORIZONTAL_SCROLLBAR", Xatom_Horizontal_Scrollbar)
12204 ATOM_REFS_INIT ("_XEMBED", Xatom_XEMBED)
12205 /* EWMH */
12206 ATOM_REFS_INIT ("_NET_WM_STATE", Xatom_net_wm_state)
12207 ATOM_REFS_INIT ("_NET_WM_STATE_FULLSCREEN", Xatom_net_wm_state_fullscreen)
12208 ATOM_REFS_INIT ("_NET_WM_STATE_MAXIMIZED_HORZ",
12209 Xatom_net_wm_state_maximized_horz)
12210 ATOM_REFS_INIT ("_NET_WM_STATE_MAXIMIZED_VERT",
12211 Xatom_net_wm_state_maximized_vert)
12212 ATOM_REFS_INIT ("_NET_WM_STATE_STICKY", Xatom_net_wm_state_sticky)
12213 ATOM_REFS_INIT ("_NET_WM_STATE_HIDDEN", Xatom_net_wm_state_hidden)
12214 ATOM_REFS_INIT ("_NET_WM_WINDOW_TYPE", Xatom_net_window_type)
12215 ATOM_REFS_INIT ("_NET_WM_WINDOW_TYPE_TOOLTIP",
12216 Xatom_net_window_type_tooltip)
12217 ATOM_REFS_INIT ("_NET_WM_ICON_NAME", Xatom_net_wm_icon_name)
12218 ATOM_REFS_INIT ("_NET_WM_NAME", Xatom_net_wm_name)
12219 ATOM_REFS_INIT ("_NET_SUPPORTED", Xatom_net_supported)
12220 ATOM_REFS_INIT ("_NET_SUPPORTING_WM_CHECK", Xatom_net_supporting_wm_check)
12221 ATOM_REFS_INIT ("_NET_WM_WINDOW_OPACITY", Xatom_net_wm_window_opacity)
12222 ATOM_REFS_INIT ("_NET_ACTIVE_WINDOW", Xatom_net_active_window)
12223 ATOM_REFS_INIT ("_NET_FRAME_EXTENTS", Xatom_net_frame_extents)
12224 ATOM_REFS_INIT ("_NET_CURRENT_DESKTOP", Xatom_net_current_desktop)
12225 ATOM_REFS_INIT ("_NET_WORKAREA", Xatom_net_workarea)
12226 /* Session management */
12227 ATOM_REFS_INIT ("SM_CLIENT_ID", Xatom_SM_CLIENT_ID)
12228 ATOM_REFS_INIT ("_XSETTINGS_SETTINGS", Xatom_xsettings_prop)
12229 ATOM_REFS_INIT ("MANAGER", Xatom_xsettings_mgr)
12232 int i;
12233 enum { atom_count = ARRAYELTS (atom_refs) };
12234 /* 1 for _XSETTINGS_SN. */
12235 enum { total_atom_count = 1 + atom_count };
12236 Atom atoms_return[total_atom_count];
12237 char *atom_names[total_atom_count];
12238 static char const xsettings_fmt[] = "_XSETTINGS_S%d";
12239 char xsettings_atom_name[sizeof xsettings_fmt - 2
12240 + INT_STRLEN_BOUND (int)];
12242 for (i = 0; i < atom_count; i++)
12243 atom_names[i] = (char *) atom_refs[i].name;
12245 /* Build _XSETTINGS_SN atom name. */
12246 sprintf (xsettings_atom_name, xsettings_fmt,
12247 XScreenNumberOfScreen (dpyinfo->screen));
12248 atom_names[i] = xsettings_atom_name;
12250 XInternAtoms (dpyinfo->display, atom_names, total_atom_count,
12251 False, atoms_return);
12253 for (i = 0; i < atom_count; i++)
12254 *(Atom *) ((char *) dpyinfo + atom_refs[i].offset) = atoms_return[i];
12256 /* Manually copy last atom. */
12257 dpyinfo->Xatom_xsettings_sel = atoms_return[i];
12260 dpyinfo->x_dnd_atoms_size = 8;
12261 dpyinfo->x_dnd_atoms = xmalloc (sizeof *dpyinfo->x_dnd_atoms
12262 * dpyinfo->x_dnd_atoms_size);
12263 dpyinfo->gray
12264 = XCreatePixmapFromBitmapData (dpyinfo->display, dpyinfo->root_window,
12265 gray_bits, gray_width, gray_height,
12266 1, 0, 1);
12268 x_setup_pointer_blanking (dpyinfo);
12270 #ifdef HAVE_X_I18N
12271 xim_initialize (dpyinfo, resource_name);
12272 #endif
12274 xsettings_initialize (dpyinfo);
12276 /* This is only needed for distinguishing keyboard and process input. */
12277 if (dpyinfo->connection != 0)
12278 add_keyboard_wait_descriptor (dpyinfo->connection);
12280 #ifdef F_SETOWN
12281 fcntl (dpyinfo->connection, F_SETOWN, getpid ());
12282 #endif /* ! defined (F_SETOWN) */
12284 if (interrupt_input)
12285 init_sigio (dpyinfo->connection);
12287 #ifdef USE_LUCID
12289 XrmValue d, fr, to;
12290 Font font;
12292 dpy = dpyinfo->display;
12293 d.addr = (XPointer)&dpy;
12294 d.size = sizeof (Display *);
12295 fr.addr = XtDefaultFont;
12296 fr.size = sizeof (XtDefaultFont);
12297 to.size = sizeof (Font *);
12298 to.addr = (XPointer)&font;
12299 x_catch_errors (dpy);
12300 if (!XtCallConverter (dpy, XtCvtStringToFont, &d, 1, &fr, &to, NULL))
12301 emacs_abort ();
12302 if (x_had_errors_p (dpy) || !XQueryFont (dpy, font))
12303 XrmPutLineResource (&xrdb, "Emacs.dialog.*.font: 9x15");
12304 /* Do not free XFontStruct returned by the above call to XQueryFont.
12305 This leads to X protocol errors at XtCloseDisplay (Bug#18403). */
12306 x_uncatch_errors ();
12308 #endif
12310 /* See if we should run in synchronous mode. This is useful
12311 for debugging X code. */
12313 AUTO_STRING (synchronous, "synchronous");
12314 AUTO_STRING (Synchronous, "Synchronous");
12315 Lisp_Object value = display_x_get_resource (dpyinfo, synchronous,
12316 Synchronous, Qnil, Qnil);
12317 if (STRINGP (value)
12318 && (!strcmp (SSDATA (value), "true")
12319 || !strcmp (SSDATA (value), "on")))
12320 XSynchronize (dpyinfo->display, True);
12324 AUTO_STRING (useXIM, "useXIM");
12325 AUTO_STRING (UseXIM, "UseXIM");
12326 Lisp_Object value = display_x_get_resource (dpyinfo, useXIM, UseXIM,
12327 Qnil, Qnil);
12328 #ifdef USE_XIM
12329 if (STRINGP (value)
12330 && (!strcmp (SSDATA (value), "false")
12331 || !strcmp (SSDATA (value), "off")))
12332 use_xim = false;
12333 #else
12334 if (STRINGP (value)
12335 && (!strcmp (SSDATA (value), "true")
12336 || !strcmp (SSDATA (value), "on")))
12337 use_xim = true;
12338 #endif
12341 #ifdef HAVE_X_SM
12342 /* Only do this for the very first display in the Emacs session.
12343 Ignore X session management when Emacs was first started on a
12344 tty or started as a daemon. */
12345 if (terminal->id == 1 && ! IS_DAEMON)
12346 x_session_initialize (dpyinfo);
12347 #endif
12349 #ifdef USE_CAIRO
12350 x_extension_initialize (dpyinfo);
12351 #endif
12353 unblock_input ();
12355 return dpyinfo;
12358 /* Get rid of display DPYINFO, deleting all frames on it,
12359 and without sending any more commands to the X server. */
12361 static void
12362 x_delete_display (struct x_display_info *dpyinfo)
12364 struct terminal *t;
12365 struct color_name_cache_entry *color_entry, *next_color_entry;
12367 /* Close all frames and delete the generic struct terminal for this
12368 X display. */
12369 for (t = terminal_list; t; t = t->next_terminal)
12370 if (t->type == output_x_window && t->display_info.x == dpyinfo)
12372 #ifdef HAVE_X_SM
12373 /* Close X session management when we close its display. */
12374 if (t->id == 1 && x_session_have_connection ())
12375 x_session_close ();
12376 #endif
12377 delete_terminal (t);
12378 break;
12381 if (next_noop_dpyinfo == dpyinfo)
12382 next_noop_dpyinfo = dpyinfo->next;
12384 if (x_display_list == dpyinfo)
12385 x_display_list = dpyinfo->next;
12386 else
12388 struct x_display_info *tail;
12390 for (tail = x_display_list; tail; tail = tail->next)
12391 if (tail->next == dpyinfo)
12392 tail->next = tail->next->next;
12395 for (color_entry = dpyinfo->color_names;
12396 color_entry;
12397 color_entry = next_color_entry)
12399 next_color_entry = color_entry->next;
12400 xfree (color_entry->name);
12401 xfree (color_entry);
12404 xfree (dpyinfo->x_id_name);
12405 xfree (dpyinfo->x_dnd_atoms);
12406 xfree (dpyinfo->color_cells);
12407 xfree (dpyinfo);
12410 #ifdef USE_X_TOOLKIT
12412 /* Atimer callback function for TIMER. Called every 0.1s to process
12413 Xt timeouts, if needed. We must avoid calling XtAppPending as
12414 much as possible because that function does an implicit XFlush
12415 that slows us down. */
12417 static void
12418 x_process_timeouts (struct atimer *timer)
12420 block_input ();
12421 x_timeout_atimer_activated_flag = false;
12422 if (toolkit_scroll_bar_interaction || popup_activated ())
12424 while (XtAppPending (Xt_app_con) & XtIMTimer)
12425 XtAppProcessEvent (Xt_app_con, XtIMTimer);
12426 /* Reactivate the atimer for next time. */
12427 x_activate_timeout_atimer ();
12429 unblock_input ();
12432 /* Install an asynchronous timer that processes Xt timeout events
12433 every 0.1s as long as either `toolkit_scroll_bar_interaction' or
12434 `popup_activated_flag' (in xmenu.c) is set. Make sure to call this
12435 function whenever these variables are set. This is necessary
12436 because some widget sets use timeouts internally, for example the
12437 LessTif menu bar, or the Xaw3d scroll bar. When Xt timeouts aren't
12438 processed, these widgets don't behave normally. */
12440 void
12441 x_activate_timeout_atimer (void)
12443 block_input ();
12444 if (!x_timeout_atimer_activated_flag)
12446 struct timespec interval = make_timespec (0, 100 * 1000 * 1000);
12447 start_atimer (ATIMER_RELATIVE, interval, x_process_timeouts, 0);
12448 x_timeout_atimer_activated_flag = true;
12450 unblock_input ();
12453 #endif /* USE_X_TOOLKIT */
12456 /* Set up use of X before we make the first connection. */
12458 static struct redisplay_interface x_redisplay_interface =
12460 x_frame_parm_handlers,
12461 x_produce_glyphs,
12462 x_write_glyphs,
12463 x_insert_glyphs,
12464 x_clear_end_of_line,
12465 x_scroll_run,
12466 x_after_update_window_line,
12467 x_update_window_begin,
12468 x_update_window_end,
12469 x_flush,
12470 x_clear_window_mouse_face,
12471 x_get_glyph_overhangs,
12472 x_fix_overlapping_area,
12473 x_draw_fringe_bitmap,
12474 #ifdef USE_CAIRO
12475 x_cr_define_fringe_bitmap,
12476 x_cr_destroy_fringe_bitmap,
12477 #else
12478 0, /* define_fringe_bitmap */
12479 0, /* destroy_fringe_bitmap */
12480 #endif
12481 x_compute_glyph_string_overhangs,
12482 x_draw_glyph_string,
12483 x_define_frame_cursor,
12484 x_clear_frame_area,
12485 x_draw_window_cursor,
12486 x_draw_vertical_window_border,
12487 x_draw_window_divider,
12488 x_shift_glyphs_for_insert, /* Never called; see comment in function. */
12489 x_show_hourglass,
12490 x_hide_hourglass
12494 /* This function is called when the last frame on a display is deleted. */
12495 void
12496 x_delete_terminal (struct terminal *terminal)
12498 struct x_display_info *dpyinfo = terminal->display_info.x;
12500 /* Protect against recursive calls. delete_frame in
12501 delete_terminal calls us back when it deletes our last frame. */
12502 if (!terminal->name)
12503 return;
12505 block_input ();
12506 #ifdef HAVE_X_I18N
12507 /* We must close our connection to the XIM server before closing the
12508 X display. */
12509 if (dpyinfo->xim)
12510 xim_close_dpy (dpyinfo);
12511 #endif
12513 /* Normally, the display is available... */
12514 if (dpyinfo->display)
12516 x_destroy_all_bitmaps (dpyinfo);
12517 XSetCloseDownMode (dpyinfo->display, DestroyAll);
12519 /* Whether or not XCloseDisplay destroys the associated resource
12520 database depends on the version of libX11. To avoid both
12521 crash and memory leak, we dissociate the database from the
12522 display and then destroy dpyinfo->xrdb ourselves.
12524 Unfortunately, the above strategy does not work in some
12525 situations due to a bug in newer versions of libX11: because
12526 XrmSetDatabase doesn't clear the flag XlibDisplayDfltRMDB if
12527 dpy->db is NULL, XCloseDisplay destroys the associated
12528 database whereas it has not been created by XGetDefault
12529 (Bug#21974 in freedesktop.org Bugzilla). As a workaround, we
12530 don't destroy the database here in order to avoid the crash
12531 in the above situations for now, though that may cause memory
12532 leaks in other situations. */
12533 #if false
12534 #ifdef HAVE_XRMSETDATABASE
12535 XrmSetDatabase (dpyinfo->display, NULL);
12536 #else
12537 dpyinfo->display->db = NULL;
12538 #endif
12539 /* We used to call XrmDestroyDatabase from x_delete_display, but
12540 some older versions of libX11 crash if we call it after
12541 closing all the displays. */
12542 XrmDestroyDatabase (dpyinfo->xrdb);
12543 #endif
12545 #ifdef USE_GTK
12546 xg_display_close (dpyinfo->display);
12547 #else
12548 #ifdef USE_X_TOOLKIT
12549 XtCloseDisplay (dpyinfo->display);
12550 #else
12551 XCloseDisplay (dpyinfo->display);
12552 #endif
12553 #endif /* ! USE_GTK */
12554 /* Do not close the connection here because it's already closed
12555 by X(t)CloseDisplay (Bug#18403). */
12556 dpyinfo->display = NULL;
12559 /* ...but if called from x_connection_closed, the display may already
12560 be closed and dpyinfo->display was set to 0 to indicate that. Since
12561 X server is most likely gone, explicit close is the only reliable
12562 way to continue and avoid Bug#19147. */
12563 else if (dpyinfo->connection >= 0)
12564 emacs_close (dpyinfo->connection);
12566 /* No more input on this descriptor. */
12567 delete_keyboard_wait_descriptor (dpyinfo->connection);
12568 /* Mark as dead. */
12569 dpyinfo->connection = -1;
12571 x_delete_display (dpyinfo);
12572 unblock_input ();
12575 /* Create a struct terminal, initialize it with the X11 specific
12576 functions and make DISPLAY->TERMINAL point to it. */
12578 static struct terminal *
12579 x_create_terminal (struct x_display_info *dpyinfo)
12581 struct terminal *terminal;
12583 terminal = create_terminal (output_x_window, &x_redisplay_interface);
12585 terminal->display_info.x = dpyinfo;
12586 dpyinfo->terminal = terminal;
12588 /* kboard is initialized in x_term_init. */
12590 terminal->clear_frame_hook = x_clear_frame;
12591 terminal->ins_del_lines_hook = x_ins_del_lines;
12592 terminal->delete_glyphs_hook = x_delete_glyphs;
12593 terminal->ring_bell_hook = XTring_bell;
12594 terminal->toggle_invisible_pointer_hook = XTtoggle_invisible_pointer;
12595 terminal->update_begin_hook = x_update_begin;
12596 terminal->update_end_hook = x_update_end;
12597 terminal->read_socket_hook = XTread_socket;
12598 terminal->frame_up_to_date_hook = XTframe_up_to_date;
12599 terminal->mouse_position_hook = XTmouse_position;
12600 terminal->frame_rehighlight_hook = XTframe_rehighlight;
12601 terminal->frame_raise_lower_hook = XTframe_raise_lower;
12602 terminal->fullscreen_hook = XTfullscreen_hook;
12603 terminal->menu_show_hook = x_menu_show;
12604 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
12605 terminal->popup_dialog_hook = xw_popup_dialog;
12606 #endif
12607 terminal->set_vertical_scroll_bar_hook = XTset_vertical_scroll_bar;
12608 terminal->set_horizontal_scroll_bar_hook = XTset_horizontal_scroll_bar;
12609 terminal->condemn_scroll_bars_hook = XTcondemn_scroll_bars;
12610 terminal->redeem_scroll_bar_hook = XTredeem_scroll_bar;
12611 terminal->judge_scroll_bars_hook = XTjudge_scroll_bars;
12612 terminal->delete_frame_hook = x_destroy_window;
12613 terminal->delete_terminal_hook = x_delete_terminal;
12614 /* Other hooks are NULL by default. */
12616 return terminal;
12619 static void
12620 x_initialize (void)
12622 baud_rate = 19200;
12624 x_noop_count = 0;
12625 any_help_event_p = false;
12626 ignore_next_mouse_click_timeout = 0;
12628 #ifdef USE_GTK
12629 current_count = -1;
12630 #endif
12632 /* Try to use interrupt input; if we can't, then start polling. */
12633 Fset_input_interrupt_mode (Qt);
12635 #ifdef USE_X_TOOLKIT
12636 XtToolkitInitialize ();
12638 Xt_app_con = XtCreateApplicationContext ();
12640 /* Register a converter from strings to pixels, which uses
12641 Emacs' color allocation infrastructure. */
12642 XtAppSetTypeConverter (Xt_app_con,
12643 XtRString, XtRPixel, cvt_string_to_pixel,
12644 cvt_string_to_pixel_args,
12645 XtNumber (cvt_string_to_pixel_args),
12646 XtCacheByDisplay, cvt_pixel_dtor);
12648 XtAppSetFallbackResources (Xt_app_con, Xt_default_resources);
12649 #endif
12651 #ifdef USE_TOOLKIT_SCROLL_BARS
12652 #ifndef USE_GTK
12653 xaw3d_arrow_scroll = False;
12654 xaw3d_pick_top = True;
12655 #endif
12656 #endif
12658 #ifdef USE_CAIRO
12659 x_cr_init_fringe (&x_redisplay_interface);
12660 #endif
12662 /* Note that there is no real way portable across R3/R4 to get the
12663 original error handler. */
12664 XSetErrorHandler (x_error_handler);
12665 XSetIOErrorHandler (x_io_error_quitter);
12668 #ifdef USE_GTK
12669 void
12670 init_xterm (void)
12672 /* Emacs can handle only core input events, so make sure
12673 Gtk doesn't use Xinput or Xinput2 extensions. */
12674 xputenv ("GDK_CORE_DEVICE_EVENTS=1");
12676 #endif
12678 void
12679 syms_of_xterm (void)
12681 x_error_message = NULL;
12683 DEFSYM (Qvendor_specific_keysyms, "vendor-specific-keysyms");
12684 DEFSYM (Qlatin_1, "latin-1");
12686 #ifdef USE_GTK
12687 xg_default_icon_file = build_pure_c_string ("icons/hicolor/scalable/apps/emacs.svg");
12688 staticpro (&xg_default_icon_file);
12690 DEFSYM (Qx_gtk_map_stock, "x-gtk-map-stock");
12691 #endif
12693 DEFVAR_BOOL ("x-use-underline-position-properties",
12694 x_use_underline_position_properties,
12695 doc: /* Non-nil means make use of UNDERLINE_POSITION font properties.
12696 A value of nil means ignore them. If you encounter fonts with bogus
12697 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
12698 to 4.1, set this to nil. You can also use `underline-minimum-offset'
12699 to override the font's UNDERLINE_POSITION for small font display
12700 sizes. */);
12701 x_use_underline_position_properties = true;
12703 DEFVAR_BOOL ("x-underline-at-descent-line",
12704 x_underline_at_descent_line,
12705 doc: /* Non-nil means to draw the underline at the same place as the descent line.
12706 A value of nil means to draw the underline according to the value of the
12707 variable `x-use-underline-position-properties', which is usually at the
12708 baseline level. The default value is nil. */);
12709 x_underline_at_descent_line = false;
12711 DEFVAR_BOOL ("x-mouse-click-focus-ignore-position",
12712 x_mouse_click_focus_ignore_position,
12713 doc: /* Non-nil means that a mouse click to focus a frame does not move point.
12714 This variable is only used when the window manager requires that you
12715 click on a frame to select it (give it focus). In that case, a value
12716 of nil, means that the selected window and cursor position changes to
12717 reflect the mouse click position, while a non-nil value means that the
12718 selected window or cursor position is preserved. */);
12719 x_mouse_click_focus_ignore_position = false;
12721 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
12722 doc: /* Which toolkit scroll bars Emacs uses, if any.
12723 A value of nil means Emacs doesn't use toolkit scroll bars.
12724 With the X Window system, the value is a symbol describing the
12725 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
12726 With MS Windows or Nextstep, the value is t. */);
12727 #ifdef USE_TOOLKIT_SCROLL_BARS
12728 #ifdef USE_MOTIF
12729 Vx_toolkit_scroll_bars = intern_c_string ("motif");
12730 #elif defined HAVE_XAW3D
12731 Vx_toolkit_scroll_bars = intern_c_string ("xaw3d");
12732 #elif USE_GTK
12733 Vx_toolkit_scroll_bars = intern_c_string ("gtk");
12734 #else
12735 Vx_toolkit_scroll_bars = intern_c_string ("xaw");
12736 #endif
12737 #else
12738 Vx_toolkit_scroll_bars = Qnil;
12739 #endif
12741 DEFSYM (Qmodifier_value, "modifier-value");
12742 DEFSYM (Qalt, "alt");
12743 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
12744 DEFSYM (Qhyper, "hyper");
12745 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
12746 DEFSYM (Qmeta, "meta");
12747 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
12748 DEFSYM (Qsuper, "super");
12749 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
12751 DEFVAR_LISP ("x-alt-keysym", Vx_alt_keysym,
12752 doc: /* Which keys Emacs uses for the alt modifier.
12753 This should be one of the symbols `alt', `hyper', `meta', `super'.
12754 For example, `alt' means use the Alt_L and Alt_R keysyms. The default
12755 is nil, which is the same as `alt'. */);
12756 Vx_alt_keysym = Qnil;
12758 DEFVAR_LISP ("x-hyper-keysym", Vx_hyper_keysym,
12759 doc: /* Which keys Emacs uses for the hyper modifier.
12760 This should be one of the symbols `alt', `hyper', `meta', `super'.
12761 For example, `hyper' means use the Hyper_L and Hyper_R keysyms. The
12762 default is nil, which is the same as `hyper'. */);
12763 Vx_hyper_keysym = Qnil;
12765 DEFVAR_LISP ("x-meta-keysym", Vx_meta_keysym,
12766 doc: /* Which keys Emacs uses for the meta modifier.
12767 This should be one of the symbols `alt', `hyper', `meta', `super'.
12768 For example, `meta' means use the Meta_L and Meta_R keysyms. The
12769 default is nil, which is the same as `meta'. */);
12770 Vx_meta_keysym = Qnil;
12772 DEFVAR_LISP ("x-super-keysym", Vx_super_keysym,
12773 doc: /* Which keys Emacs uses for the super modifier.
12774 This should be one of the symbols `alt', `hyper', `meta', `super'.
12775 For example, `super' means use the Super_L and Super_R keysyms. The
12776 default is nil, which is the same as `super'. */);
12777 Vx_super_keysym = Qnil;
12779 DEFVAR_LISP ("x-keysym-table", Vx_keysym_table,
12780 doc: /* Hash table of character codes indexed by X keysym codes. */);
12781 Vx_keysym_table = make_hash_table (hashtest_eql, make_number (900),
12782 make_float (DEFAULT_REHASH_SIZE),
12783 make_float (DEFAULT_REHASH_THRESHOLD),
12784 Qnil);
12786 DEFVAR_BOOL ("x-frame-normalize-before-maximize",
12787 x_frame_normalize_before_maximize,
12788 doc: /* Non-nil means normalize frame before maximizing.
12789 If this variable is t, Emacs first asks the window manager to give the
12790 frame its normal size, and only then the final state, whenever changing
12791 from a full-height, full-width or full-both state to the maximized one
12792 or when changing from the maximized to the full-height or full-width
12793 state.
12795 Set this variable only if your window manager cannot handle the
12796 transition between the various maximization states. */);
12797 x_frame_normalize_before_maximize = false;