cleanup
[emacs.git] / src / xterm.c
blobabceefb1b0e887667071e146c909f4e399719e23
1 /* X Communication module for terminals which understand the X protocol.
3 Copyright (C) 1989, 1993-2015 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
10 (at 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>
26 #include "lisp.h"
27 #include "blockinput.h"
28 #include "syssignal.h"
30 /* This may include sys/types.h, and that somehow loses
31 if this is not done before the other system files. */
32 #include "xterm.h"
33 #include <X11/cursorfont.h>
35 /* If we have Xfixes extension, use it for pointer blanking. */
36 #ifdef HAVE_XFIXES
37 #include <X11/extensions/Xfixes.h>
38 #endif
40 /* Using Xft implies that XRender is available. */
41 #ifdef HAVE_XFT
42 #include <X11/extensions/Xrender.h>
43 #endif
45 /* Load sys/types.h if not already loaded.
46 In some systems loading it twice is suicidal. */
47 #ifndef makedev
48 #include <sys/types.h>
49 #endif /* makedev */
51 #include <sys/ioctl.h>
53 #include "systime.h"
55 #include <fcntl.h>
56 #include <errno.h>
57 #include <sys/stat.h>
58 /* Caused redefinition of DBL_DIG on Netbsd; seems not to be needed. */
59 /* #include <sys/param.h> */
61 #include "charset.h"
62 #include "character.h"
63 #include "coding.h"
64 #include "frame.h"
65 #include "dispextern.h"
66 #ifdef HAVE_XWIDGETS
67 #include "xwidget.h"
68 #endif
69 #include "fontset.h"
70 #include "termhooks.h"
71 #include "termopts.h"
72 #include "termchar.h"
73 #include "emacs-icon.h"
74 #include "disptab.h"
75 #include "buffer.h"
76 #include "window.h"
77 #include "keyboard.h"
78 #include "intervals.h"
79 #include "process.h"
80 #include "atimer.h"
81 #include "keymap.h"
82 #include "font.h"
83 #include "xsettings.h"
84 #include "xgselect.h"
85 #include "sysselect.h"
86 #include "menu.h"
88 #ifdef USE_X_TOOLKIT
89 #include <X11/Shell.h>
90 #endif
92 #include <unistd.h>
94 #ifdef USE_GTK
95 #include "gtkutil.h"
96 #ifdef HAVE_GTK3
97 #include <X11/Xproto.h>
98 #endif
99 #endif
101 #if defined (USE_LUCID) || defined (USE_MOTIF)
102 #include "../lwlib/xlwmenu.h"
103 #endif
105 #ifdef USE_X_TOOLKIT
106 #if !defined (NO_EDITRES)
107 #define HACK_EDITRES
108 extern void _XEditResCheckMessages (Widget, XtPointer, XEvent *, Boolean *);
109 #endif /* not NO_EDITRES */
111 /* Include toolkit specific headers for the scroll bar widget. */
113 #ifdef USE_TOOLKIT_SCROLL_BARS
114 #if defined USE_MOTIF
115 #include <Xm/Xm.h> /* For LESSTIF_VERSION */
116 #include <Xm/ScrollBar.h>
117 #else /* !USE_MOTIF i.e. use Xaw */
119 #ifdef HAVE_XAW3D
120 #include <X11/Xaw3d/Simple.h>
121 #include <X11/Xaw3d/Scrollbar.h>
122 #include <X11/Xaw3d/ThreeD.h>
123 #else /* !HAVE_XAW3D */
124 #include <X11/Xaw/Simple.h>
125 #include <X11/Xaw/Scrollbar.h>
126 #endif /* !HAVE_XAW3D */
127 #ifndef XtNpickTop
128 #define XtNpickTop "pickTop"
129 #endif /* !XtNpickTop */
130 #endif /* !USE_MOTIF */
131 #endif /* USE_TOOLKIT_SCROLL_BARS */
133 #endif /* USE_X_TOOLKIT */
135 #ifdef USE_X_TOOLKIT
136 #include "widget.h"
137 #ifndef XtNinitialState
138 #define XtNinitialState "initialState"
139 #endif
140 #endif
142 #include "bitmaps/gray.xbm"
144 #ifdef HAVE_XKB
145 #include <X11/XKBlib.h>
146 #endif
148 /* Default to using XIM if available. */
149 #ifdef USE_XIM
150 bool use_xim = true;
151 #else
152 bool use_xim = false; /* configure --without-xim */
153 #endif
155 /* Non-zero means that a HELP_EVENT has been generated since Emacs
156 start. */
158 static bool any_help_event_p;
160 /* This is a chain of structures for all the X displays currently in
161 use. */
163 struct x_display_info *x_display_list;
165 #ifdef USE_X_TOOLKIT
167 /* The application context for Xt use. */
168 XtAppContext Xt_app_con;
169 static String Xt_default_resources[] = {0};
171 /* Non-zero means user is interacting with a toolkit scroll bar. */
172 static bool toolkit_scroll_bar_interaction;
174 #endif /* USE_X_TOOLKIT */
176 /* Non-zero timeout value means ignore next mouse click if it arrives
177 before that timeout elapses (i.e. as part of the same sequence of
178 events resulting from clicking on a frame to select it). */
180 static Time ignore_next_mouse_click_timeout;
182 /* Used locally within XTread_socket. */
184 static int x_noop_count;
186 #ifdef USE_GTK
187 /* The name of the Emacs icon file. */
188 static Lisp_Object xg_default_icon_file;
189 #endif
191 /* Some functions take this as char *, not const char *. */
192 static char emacs_class[] = EMACS_CLASS;
194 enum xembed_info
196 XEMBED_MAPPED = 1 << 0
199 enum xembed_message
201 XEMBED_EMBEDDED_NOTIFY = 0,
202 XEMBED_WINDOW_ACTIVATE = 1,
203 XEMBED_WINDOW_DEACTIVATE = 2,
204 XEMBED_REQUEST_FOCUS = 3,
205 XEMBED_FOCUS_IN = 4,
206 XEMBED_FOCUS_OUT = 5,
207 XEMBED_FOCUS_NEXT = 6,
208 XEMBED_FOCUS_PREV = 7,
210 XEMBED_MODALITY_ON = 10,
211 XEMBED_MODALITY_OFF = 11,
212 XEMBED_REGISTER_ACCELERATOR = 12,
213 XEMBED_UNREGISTER_ACCELERATOR = 13,
214 XEMBED_ACTIVATE_ACCELERATOR = 14
217 static bool x_alloc_nearest_color_1 (Display *, Colormap, XColor *);
218 static void x_set_window_size_1 (struct frame *, bool, int, int, bool);
219 static void x_raise_frame (struct frame *);
220 static void x_lower_frame (struct frame *);
221 static const XColor *x_color_cells (Display *, int *);
222 static int x_io_error_quitter (Display *);
223 static struct terminal *x_create_terminal (struct x_display_info *);
224 static void x_update_end (struct frame *);
225 static void XTframe_up_to_date (struct frame *);
226 static void x_clear_frame (struct frame *);
227 static _Noreturn void x_ins_del_lines (struct frame *, int, int);
228 static void frame_highlight (struct frame *);
229 static void frame_unhighlight (struct frame *);
230 static void x_new_focus_frame (struct x_display_info *, struct frame *);
231 static void x_focus_changed (int, int, struct x_display_info *,
232 struct frame *, struct input_event *);
233 static void XTframe_rehighlight (struct frame *);
234 static void x_frame_rehighlight (struct x_display_info *);
235 static void x_draw_hollow_cursor (struct window *, struct glyph_row *);
236 static void x_draw_bar_cursor (struct window *, struct glyph_row *, int,
237 enum text_cursor_kinds);
239 static void x_clip_to_row (struct window *, struct glyph_row *,
240 enum glyph_row_area, GC);
241 static void x_flush (struct frame *f);
242 static void x_update_begin (struct frame *);
243 static void x_update_window_begin (struct window *);
244 static struct scroll_bar *x_window_to_scroll_bar (Display *, Window, int);
245 static void x_scroll_bar_report_motion (struct frame **, Lisp_Object *,
246 enum scroll_bar_part *,
247 Lisp_Object *, Lisp_Object *,
248 Time *);
249 static void x_horizontal_scroll_bar_report_motion (struct frame **, Lisp_Object *,
250 enum scroll_bar_part *,
251 Lisp_Object *, Lisp_Object *,
252 Time *);
253 static bool x_handle_net_wm_state (struct frame *, const XPropertyEvent *);
254 static void x_check_fullscreen (struct frame *);
255 static void x_check_expected_move (struct frame *, int, int);
256 static void x_sync_with_move (struct frame *, int, int, bool);
257 static int handle_one_xevent (struct x_display_info *,
258 const XEvent *, int *,
259 struct input_event *);
260 #if ! (defined USE_X_TOOLKIT || defined USE_MOTIF)
261 static int x_dispatch_event (XEvent *, Display *);
262 #endif
263 /* Don't declare this _Noreturn because we want no
264 interference with debugging failing X calls. */
265 static void x_connection_closed (Display *, const char *);
266 static void x_wm_set_window_state (struct frame *, int);
267 static void x_wm_set_icon_pixmap (struct frame *, ptrdiff_t);
268 static void x_initialize (void);
270 static bool get_current_wm_state (struct frame *, Window, int *, bool *);
272 /* Flush display of frame F. */
274 static void
275 x_flush (struct frame *f)
277 eassert (f && FRAME_X_P (f));
278 /* Don't call XFlush when it is not safe to redisplay; the X
279 connection may be broken. */
280 if (!NILP (Vinhibit_redisplay))
281 return;
283 block_input ();
284 XFlush (FRAME_X_DISPLAY (f));
285 unblock_input ();
289 /* Remove calls to XFlush by defining XFlush to an empty replacement.
290 Calls to XFlush should be unnecessary because the X output buffer
291 is flushed automatically as needed by calls to XPending,
292 XNextEvent, or XWindowEvent according to the XFlush man page.
293 XTread_socket calls XPending. Removing XFlush improves
294 performance. */
296 #define XFlush(DISPLAY) (void) 0
299 /***********************************************************************
300 Debugging
301 ***********************************************************************/
303 #if false
305 /* This is a function useful for recording debugging information about
306 the sequence of occurrences in this file. */
308 struct record
310 char *locus;
311 int type;
314 struct record event_record[100];
316 int event_record_index;
318 void
319 record_event (char *locus, int type)
321 if (event_record_index == ARRAYELTS (event_record))
322 event_record_index = 0;
324 event_record[event_record_index].locus = locus;
325 event_record[event_record_index].type = type;
326 event_record_index++;
329 #endif
333 /* Return the struct x_display_info corresponding to DPY. */
335 struct x_display_info *
336 x_display_info_for_display (Display *dpy)
338 struct x_display_info *dpyinfo;
340 for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
341 if (dpyinfo->display == dpy)
342 return dpyinfo;
344 return 0;
347 static Window
348 x_find_topmost_parent (struct frame *f)
350 struct x_output *x = f->output_data.x;
351 Window win = None, wi = x->parent_desc;
352 Display *dpy = FRAME_X_DISPLAY (f);
354 while (wi != FRAME_DISPLAY_INFO (f)->root_window)
356 Window root;
357 Window *children;
358 unsigned int nchildren;
360 win = wi;
361 if (XQueryTree (dpy, win, &root, &wi, &children, &nchildren))
362 XFree (children);
363 else
364 break;
367 return win;
370 #define OPAQUE 0xffffffff
372 void
373 x_set_frame_alpha (struct frame *f)
375 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
376 Display *dpy = FRAME_X_DISPLAY (f);
377 Window win = FRAME_OUTER_WINDOW (f);
378 double alpha = 1.0;
379 double alpha_min = 1.0;
380 unsigned long opac;
381 Window parent;
383 if (dpyinfo->x_highlight_frame == f)
384 alpha = f->alpha[0];
385 else
386 alpha = f->alpha[1];
388 if (FLOATP (Vframe_alpha_lower_limit))
389 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
390 else if (INTEGERP (Vframe_alpha_lower_limit))
391 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
393 if (alpha < 0.0)
394 return;
395 else if (alpha > 1.0)
396 alpha = 1.0;
397 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
398 alpha = alpha_min;
400 opac = alpha * OPAQUE;
402 x_catch_errors (dpy);
404 /* If there is a parent from the window manager, put the property there
405 also, to work around broken window managers that fail to do that.
406 Do this unconditionally as this function is called on reparent when
407 alpha has not changed on the frame. */
409 parent = x_find_topmost_parent (f);
410 if (parent != None)
411 XChangeProperty (dpy, parent, dpyinfo->Xatom_net_wm_window_opacity,
412 XA_CARDINAL, 32, PropModeReplace,
413 (unsigned char *) &opac, 1);
415 /* return unless necessary */
417 unsigned char *data;
418 Atom actual;
419 int rc, format;
420 unsigned long n, left;
422 rc = XGetWindowProperty (dpy, win, dpyinfo->Xatom_net_wm_window_opacity,
423 0, 1, False, XA_CARDINAL,
424 &actual, &format, &n, &left,
425 &data);
427 if (rc == Success && actual != None)
429 unsigned long value = *(unsigned long *)data;
430 XFree (data);
431 if (value == opac)
433 x_uncatch_errors ();
434 return;
439 XChangeProperty (dpy, win, dpyinfo->Xatom_net_wm_window_opacity,
440 XA_CARDINAL, 32, PropModeReplace,
441 (unsigned char *) &opac, 1);
442 x_uncatch_errors ();
445 /***********************************************************************
446 Starting and ending an update
447 ***********************************************************************/
449 /* Start an update of frame F. This function is installed as a hook
450 for update_begin, i.e. it is called when update_begin is called.
451 This function is called prior to calls to x_update_window_begin for
452 each window being updated. Currently, there is nothing to do here
453 because all interesting stuff is done on a window basis. */
455 static void
456 x_update_begin (struct frame *f)
458 /* Nothing to do. */
462 /* Start update of window W. */
464 static void
465 x_update_window_begin (struct window *w)
467 struct frame *f = XFRAME (WINDOW_FRAME (w));
468 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
470 w->output_cursor = w->cursor;
472 block_input ();
474 if (f == hlinfo->mouse_face_mouse_frame)
476 /* Don't do highlighting for mouse motion during the update. */
477 hlinfo->mouse_face_defer = true;
479 /* If F needs to be redrawn, simply forget about any prior mouse
480 highlighting. */
481 if (FRAME_GARBAGED_P (f))
482 hlinfo->mouse_face_window = Qnil;
485 unblock_input ();
489 /* Draw a vertical window border from (x,y0) to (x,y1) */
491 static void
492 x_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
494 struct frame *f = XFRAME (WINDOW_FRAME (w));
495 struct face *face;
497 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
498 if (face)
499 XSetForeground (FRAME_X_DISPLAY (f), f->output_data.x->normal_gc,
500 face->foreground);
502 XDrawLine (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
503 f->output_data.x->normal_gc, x, y0, x, y1);
506 /* Draw a window divider from (x0,y0) to (x1,y1) */
508 static void
509 x_draw_window_divider (struct window *w, int x0, int x1, int y0, int y1)
511 struct frame *f = XFRAME (WINDOW_FRAME (w));
512 struct face *face = FACE_FROM_ID (f, WINDOW_DIVIDER_FACE_ID);
513 struct face *face_first = FACE_FROM_ID (f, WINDOW_DIVIDER_FIRST_PIXEL_FACE_ID);
514 struct face *face_last = FACE_FROM_ID (f, WINDOW_DIVIDER_LAST_PIXEL_FACE_ID);
515 unsigned long color = face ? face->foreground : FRAME_FOREGROUND_PIXEL (f);
516 unsigned long color_first = (face_first
517 ? face_first->foreground
518 : FRAME_FOREGROUND_PIXEL (f));
519 unsigned long color_last = (face_last
520 ? face_last->foreground
521 : FRAME_FOREGROUND_PIXEL (f));
522 Display *display = FRAME_X_DISPLAY (f);
523 Window window = FRAME_X_WINDOW (f);
525 if (y1 - y0 > x1 - x0 && x1 - x0 > 2)
526 /* Vertical. */
528 XSetForeground (display, f->output_data.x->normal_gc, color_first);
529 XFillRectangle (display, window, f->output_data.x->normal_gc,
530 x0, y0, 1, y1 - y0);
531 XSetForeground (display, f->output_data.x->normal_gc, color);
532 XFillRectangle (display, window, f->output_data.x->normal_gc,
533 x0 + 1, y0, x1 - x0 - 2, y1 - y0);
534 XSetForeground (display, f->output_data.x->normal_gc, color_last);
535 XFillRectangle (display, window, f->output_data.x->normal_gc,
536 x1 - 1, y0, 1, y1 - y0);
538 else if (x1 - x0 > y1 - y0 && y1 - y0 > 3)
539 /* Horizontal. */
541 XSetForeground (display, f->output_data.x->normal_gc, color_first);
542 XFillRectangle (display, window, f->output_data.x->normal_gc,
543 x0, y0, x1 - x0, 1);
544 XSetForeground (display, f->output_data.x->normal_gc, color);
545 XFillRectangle (display, window, f->output_data.x->normal_gc,
546 x0, y0 + 1, x1 - x0, y1 - y0 - 2);
547 XSetForeground (display, f->output_data.x->normal_gc, color_last);
548 XFillRectangle (display, window, f->output_data.x->normal_gc,
549 x0, y1 - 1, x1 - x0, 1);
551 else
553 XSetForeground (display, f->output_data.x->normal_gc, color);
554 XFillRectangle (display, window, f->output_data.x->normal_gc,
555 x0, y0, x1 - x0, y1 - y0);
559 /* End update of window W.
561 Draw vertical borders between horizontally adjacent windows, and
562 display W's cursor if CURSOR_ON_P is non-zero.
564 MOUSE_FACE_OVERWRITTEN_P non-zero means that some row containing
565 glyphs in mouse-face were overwritten. In that case we have to
566 make sure that the mouse-highlight is properly redrawn.
568 W may be a menu bar pseudo-window in case we don't have X toolkit
569 support. Such windows don't have a cursor, so don't display it
570 here. */
572 static void
573 x_update_window_end (struct window *w, bool cursor_on_p,
574 bool mouse_face_overwritten_p)
576 if (!w->pseudo_window_p)
578 block_input ();
580 if (cursor_on_p)
581 display_and_set_cursor (w, true,
582 w->output_cursor.hpos, w->output_cursor.vpos,
583 w->output_cursor.x, w->output_cursor.y);
585 if (draw_window_fringes (w, true))
587 if (WINDOW_RIGHT_DIVIDER_WIDTH (w))
588 x_draw_right_divider (w);
589 else
590 x_draw_vertical_border (w);
593 unblock_input ();
596 /* If a row with mouse-face was overwritten, arrange for
597 XTframe_up_to_date to redisplay the mouse highlight. */
598 if (mouse_face_overwritten_p)
600 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (XFRAME (w->frame));
602 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
603 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
604 hlinfo->mouse_face_window = Qnil;
609 /* End update of frame F. This function is installed as a hook in
610 update_end. */
612 static void
613 x_update_end (struct frame *f)
615 /* Mouse highlight may be displayed again. */
616 MOUSE_HL_INFO (f)->mouse_face_defer = false;
618 #ifndef XFlush
619 block_input ();
620 XFlush (FRAME_X_DISPLAY (f));
621 unblock_input ();
622 #endif
626 /* This function is called from various places in xdisp.c
627 whenever a complete update has been performed. */
629 static void
630 XTframe_up_to_date (struct frame *f)
632 if (FRAME_X_P (f))
633 FRAME_MOUSE_UPDATE (f);
637 /* Clear under internal border if any (GTK has its own version). */
638 #ifndef USE_GTK
639 void
640 x_clear_under_internal_border (struct frame *f)
642 if (FRAME_INTERNAL_BORDER_WIDTH (f) > 0)
644 Display *display = FRAME_X_DISPLAY (f);
645 Window window = FRAME_X_WINDOW (f);
646 int border = FRAME_INTERNAL_BORDER_WIDTH (f);
647 int width = FRAME_PIXEL_WIDTH (f);
648 int height = FRAME_PIXEL_HEIGHT (f);
649 int margin = FRAME_TOP_MARGIN_HEIGHT (f);
651 block_input ();
652 x_clear_area (display, window, 0, 0, border, height);
653 x_clear_area (display, window, 0, margin, width, border);
654 x_clear_area (display, window, width - border, 0, border, height);
655 x_clear_area (display, window, 0, height - border, width, border);
656 unblock_input ();
659 #endif
661 /* Draw truncation mark bitmaps, continuation mark bitmaps, overlay
662 arrow bitmaps, or clear the fringes if no bitmaps are required
663 before DESIRED_ROW is made current. This function is called from
664 update_window_line only if it is known that there are differences
665 between bitmaps to be drawn between current row and DESIRED_ROW. */
667 static void
668 x_after_update_window_line (struct window *w, struct glyph_row *desired_row)
670 eassert (w);
672 if (!desired_row->mode_line_p && !w->pseudo_window_p)
673 desired_row->redraw_fringe_bitmaps_p = true;
675 #ifdef USE_X_TOOLKIT
676 /* When a window has disappeared, make sure that no rest of
677 full-width rows stays visible in the internal border. Could
678 check here if updated window is the leftmost/rightmost window,
679 but I guess it's not worth doing since vertically split windows
680 are almost never used, internal border is rarely set, and the
681 overhead is very small. */
683 struct frame *f;
684 int width, height;
686 if (windows_or_buffers_changed
687 && desired_row->full_width_p
688 && (f = XFRAME (w->frame),
689 width = FRAME_INTERNAL_BORDER_WIDTH (f),
690 width != 0)
691 && (height = desired_row->visible_height,
692 height > 0))
694 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
696 block_input ();
697 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
698 0, y, width, height);
699 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
700 FRAME_PIXEL_WIDTH (f) - width,
701 y, width, height);
702 unblock_input ();
705 #endif
708 static void
709 x_draw_fringe_bitmap (struct window *w, struct glyph_row *row, struct draw_fringe_bitmap_params *p)
711 struct frame *f = XFRAME (WINDOW_FRAME (w));
712 Display *display = FRAME_X_DISPLAY (f);
713 Window window = FRAME_X_WINDOW (f);
714 GC gc = f->output_data.x->normal_gc;
715 struct face *face = p->face;
717 /* Must clip because of partially visible lines. */
718 x_clip_to_row (w, row, ANY_AREA, gc);
720 if (p->bx >= 0 && !p->overlay_p)
722 /* In case the same realized face is used for fringes and
723 for something displayed in the text (e.g. face `region' on
724 mono-displays, the fill style may have been changed to
725 FillSolid in x_draw_glyph_string_background. */
726 if (face->stipple)
727 XSetFillStyle (display, face->gc, FillOpaqueStippled);
728 else
729 XSetForeground (display, face->gc, face->background);
731 XFillRectangle (display, window, face->gc,
732 p->bx, p->by, p->nx, p->ny);
734 if (!face->stipple)
735 XSetForeground (display, face->gc, face->foreground);
738 if (p->which)
740 char *bits;
741 Pixmap pixmap, clipmask = (Pixmap) 0;
742 int depth = DefaultDepthOfScreen (FRAME_X_SCREEN (f));
743 XGCValues gcv;
745 if (p->wd > 8)
746 bits = (char *) (p->bits + p->dh);
747 else
748 bits = (char *) p->bits + p->dh;
750 /* Draw the bitmap. I believe these small pixmaps can be cached
751 by the server. */
752 pixmap = XCreatePixmapFromBitmapData (display, window, bits, p->wd, p->h,
753 (p->cursor_p
754 ? (p->overlay_p ? face->background
755 : f->output_data.x->cursor_pixel)
756 : face->foreground),
757 face->background, depth);
759 if (p->overlay_p)
761 clipmask = XCreatePixmapFromBitmapData (display,
762 FRAME_DISPLAY_INFO (f)->root_window,
763 bits, p->wd, p->h,
764 1, 0, 1);
765 gcv.clip_mask = clipmask;
766 gcv.clip_x_origin = p->x;
767 gcv.clip_y_origin = p->y;
768 XChangeGC (display, gc, GCClipMask | GCClipXOrigin | GCClipYOrigin, &gcv);
771 XCopyArea (display, pixmap, window, gc, 0, 0,
772 p->wd, p->h, p->x, p->y);
773 XFreePixmap (display, pixmap);
775 if (p->overlay_p)
777 gcv.clip_mask = (Pixmap) 0;
778 XChangeGC (display, gc, GCClipMask, &gcv);
779 XFreePixmap (display, clipmask);
783 XSetClipMask (display, gc, None);
786 /***********************************************************************
787 Glyph display
788 ***********************************************************************/
792 static void x_set_glyph_string_clipping (struct glyph_string *);
793 static void x_set_glyph_string_gc (struct glyph_string *);
794 static void x_draw_glyph_string_foreground (struct glyph_string *);
795 static void x_draw_composite_glyph_string_foreground (struct glyph_string *);
796 static void x_draw_glyph_string_box (struct glyph_string *);
797 static void x_draw_glyph_string (struct glyph_string *);
798 static _Noreturn void x_delete_glyphs (struct frame *, int);
799 static void x_compute_glyph_string_overhangs (struct glyph_string *);
800 static void x_set_cursor_gc (struct glyph_string *);
801 static void x_set_mode_line_face_gc (struct glyph_string *);
802 static void x_set_mouse_face_gc (struct glyph_string *);
803 static bool x_alloc_lighter_color (struct frame *, Display *, Colormap,
804 unsigned long *, double, int);
805 static void x_setup_relief_color (struct frame *, struct relief *,
806 double, int, unsigned long);
807 static void x_setup_relief_colors (struct glyph_string *);
808 static void x_draw_image_glyph_string (struct glyph_string *);
809 static void x_draw_image_relief (struct glyph_string *);
810 static void x_draw_image_foreground (struct glyph_string *);
811 static void x_draw_image_foreground_1 (struct glyph_string *, Pixmap);
812 static void x_clear_glyph_string_rect (struct glyph_string *, int,
813 int, int, int);
814 static void x_draw_relief_rect (struct frame *, int, int, int, int,
815 int, bool, bool, bool, bool, bool,
816 XRectangle *);
817 static void x_draw_box_rect (struct glyph_string *, int, int, int, int,
818 int, bool, bool, XRectangle *);
819 static void x_scroll_bar_clear (struct frame *);
821 #ifdef GLYPH_DEBUG
822 static void x_check_font (struct frame *, struct font *);
823 #endif
826 /* Set S->gc to a suitable GC for drawing glyph string S in cursor
827 face. */
829 static void
830 x_set_cursor_gc (struct glyph_string *s)
832 if (s->font == FRAME_FONT (s->f)
833 && s->face->background == FRAME_BACKGROUND_PIXEL (s->f)
834 && s->face->foreground == FRAME_FOREGROUND_PIXEL (s->f)
835 && !s->cmp)
836 s->gc = s->f->output_data.x->cursor_gc;
837 else
839 /* Cursor on non-default face: must merge. */
840 XGCValues xgcv;
841 unsigned long mask;
843 xgcv.background = s->f->output_data.x->cursor_pixel;
844 xgcv.foreground = s->face->background;
846 /* If the glyph would be invisible, try a different foreground. */
847 if (xgcv.foreground == xgcv.background)
848 xgcv.foreground = s->face->foreground;
849 if (xgcv.foreground == xgcv.background)
850 xgcv.foreground = s->f->output_data.x->cursor_foreground_pixel;
851 if (xgcv.foreground == xgcv.background)
852 xgcv.foreground = s->face->foreground;
854 /* Make sure the cursor is distinct from text in this face. */
855 if (xgcv.background == s->face->background
856 && xgcv.foreground == s->face->foreground)
858 xgcv.background = s->face->foreground;
859 xgcv.foreground = s->face->background;
862 IF_DEBUG (x_check_font (s->f, s->font));
863 xgcv.graphics_exposures = False;
864 mask = GCForeground | GCBackground | GCGraphicsExposures;
866 if (FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc)
867 XChangeGC (s->display, FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc,
868 mask, &xgcv);
869 else
870 FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc
871 = XCreateGC (s->display, s->window, mask, &xgcv);
873 s->gc = FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc;
878 /* Set up S->gc of glyph string S for drawing text in mouse face. */
880 static void
881 x_set_mouse_face_gc (struct glyph_string *s)
883 int face_id;
884 struct face *face;
886 /* What face has to be used last for the mouse face? */
887 face_id = MOUSE_HL_INFO (s->f)->mouse_face_face_id;
888 face = FACE_FROM_ID (s->f, face_id);
889 if (face == NULL)
890 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
892 if (s->first_glyph->type == CHAR_GLYPH)
893 face_id = FACE_FOR_CHAR (s->f, face, s->first_glyph->u.ch, -1, Qnil);
894 else
895 face_id = FACE_FOR_CHAR (s->f, face, 0, -1, Qnil);
896 s->face = FACE_FROM_ID (s->f, face_id);
897 prepare_face_for_display (s->f, s->face);
899 if (s->font == s->face->font)
900 s->gc = s->face->gc;
901 else
903 /* Otherwise construct scratch_cursor_gc with values from FACE
904 except for FONT. */
905 XGCValues xgcv;
906 unsigned long mask;
908 xgcv.background = s->face->background;
909 xgcv.foreground = s->face->foreground;
910 xgcv.graphics_exposures = False;
911 mask = GCForeground | GCBackground | GCGraphicsExposures;
913 if (FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc)
914 XChangeGC (s->display, FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc,
915 mask, &xgcv);
916 else
917 FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc
918 = XCreateGC (s->display, s->window, mask, &xgcv);
920 s->gc = FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc;
923 eassert (s->gc != 0);
927 /* Set S->gc of glyph string S to a GC suitable for drawing a mode line.
928 Faces to use in the mode line have already been computed when the
929 matrix was built, so there isn't much to do, here. */
931 static void
932 x_set_mode_line_face_gc (struct glyph_string *s)
934 s->gc = s->face->gc;
938 /* Set S->gc of glyph string S for drawing that glyph string. Set
939 S->stippled_p to a non-zero value if the face of S has a stipple
940 pattern. */
942 static void
943 x_set_glyph_string_gc (struct glyph_string *s)
945 prepare_face_for_display (s->f, s->face);
947 if (s->hl == DRAW_NORMAL_TEXT)
949 s->gc = s->face->gc;
950 s->stippled_p = s->face->stipple != 0;
952 else if (s->hl == DRAW_INVERSE_VIDEO)
954 x_set_mode_line_face_gc (s);
955 s->stippled_p = s->face->stipple != 0;
957 else if (s->hl == DRAW_CURSOR)
959 x_set_cursor_gc (s);
960 s->stippled_p = false;
962 else if (s->hl == DRAW_MOUSE_FACE)
964 x_set_mouse_face_gc (s);
965 s->stippled_p = s->face->stipple != 0;
967 else if (s->hl == DRAW_IMAGE_RAISED
968 || s->hl == DRAW_IMAGE_SUNKEN)
970 s->gc = s->face->gc;
971 s->stippled_p = s->face->stipple != 0;
973 else
974 emacs_abort ();
976 /* GC must have been set. */
977 eassert (s->gc != 0);
981 /* Set clipping for output of glyph string S. S may be part of a mode
982 line or menu if we don't have X toolkit support. */
984 static void
985 x_set_glyph_string_clipping (struct glyph_string *s)
987 XRectangle *r = s->clip;
988 int n = get_glyph_string_clip_rects (s, r, 2);
990 if (n > 0)
991 XSetClipRectangles (s->display, s->gc, 0, 0, r, n, Unsorted);
992 s->num_clips = n;
996 /* Set SRC's clipping for output of glyph string DST. This is called
997 when we are drawing DST's left_overhang or right_overhang only in
998 the area of SRC. */
1000 static void
1001 x_set_glyph_string_clipping_exactly (struct glyph_string *src, struct glyph_string *dst)
1003 XRectangle r;
1005 r.x = src->x;
1006 r.width = src->width;
1007 r.y = src->y;
1008 r.height = src->height;
1009 dst->clip[0] = r;
1010 dst->num_clips = 1;
1011 XSetClipRectangles (dst->display, dst->gc, 0, 0, &r, 1, Unsorted);
1015 /* RIF:
1016 Compute left and right overhang of glyph string S. */
1018 static void
1019 x_compute_glyph_string_overhangs (struct glyph_string *s)
1021 if (s->cmp == NULL
1022 && (s->first_glyph->type == CHAR_GLYPH
1023 || s->first_glyph->type == COMPOSITE_GLYPH))
1025 struct font_metrics metrics;
1027 if (s->first_glyph->type == CHAR_GLYPH)
1029 unsigned *code = alloca (sizeof (unsigned) * s->nchars);
1030 struct font *font = s->font;
1031 int i;
1033 for (i = 0; i < s->nchars; i++)
1034 code[i] = (s->char2b[i].byte1 << 8) | s->char2b[i].byte2;
1035 font->driver->text_extents (font, code, s->nchars, &metrics);
1037 else
1039 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1041 composition_gstring_width (gstring, s->cmp_from, s->cmp_to, &metrics);
1043 s->right_overhang = (metrics.rbearing > metrics.width
1044 ? metrics.rbearing - metrics.width : 0);
1045 s->left_overhang = metrics.lbearing < 0 ? - metrics.lbearing : 0;
1047 else if (s->cmp)
1049 s->right_overhang = s->cmp->rbearing - s->cmp->pixel_width;
1050 s->left_overhang = - s->cmp->lbearing;
1055 /* Fill rectangle X, Y, W, H with background color of glyph string S. */
1057 static void
1058 x_clear_glyph_string_rect (struct glyph_string *s, int x, int y, int w, int h)
1060 XGCValues xgcv;
1061 XGetGCValues (s->display, s->gc, GCForeground | GCBackground, &xgcv);
1062 XSetForeground (s->display, s->gc, xgcv.background);
1063 XFillRectangle (s->display, s->window, s->gc, x, y, w, h);
1064 XSetForeground (s->display, s->gc, xgcv.foreground);
1068 /* Draw the background of glyph_string S. If S->background_filled_p
1069 is non-zero don't draw it. FORCE_P non-zero means draw the
1070 background even if it wouldn't be drawn normally. This is used
1071 when a string preceding S draws into the background of S, or S
1072 contains the first component of a composition. */
1074 static void
1075 x_draw_glyph_string_background (struct glyph_string *s, bool force_p)
1077 /* Nothing to do if background has already been drawn or if it
1078 shouldn't be drawn in the first place. */
1079 if (!s->background_filled_p)
1081 int box_line_width = max (s->face->box_line_width, 0);
1083 if (s->stippled_p)
1085 /* Fill background with a stipple pattern. */
1086 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
1087 XFillRectangle (s->display, s->window, s->gc, s->x,
1088 s->y + box_line_width,
1089 s->background_width,
1090 s->height - 2 * box_line_width);
1091 XSetFillStyle (s->display, s->gc, FillSolid);
1092 s->background_filled_p = true;
1094 else if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
1095 || s->font_not_found_p
1096 || s->extends_to_end_of_line_p
1097 || force_p)
1099 x_clear_glyph_string_rect (s, s->x, s->y + box_line_width,
1100 s->background_width,
1101 s->height - 2 * box_line_width);
1102 s->background_filled_p = true;
1108 /* Draw the foreground of glyph string S. */
1110 static void
1111 x_draw_glyph_string_foreground (struct glyph_string *s)
1113 int i, x;
1115 /* If first glyph of S has a left box line, start drawing the text
1116 of S to the right of that box line. */
1117 if (s->face->box != FACE_NO_BOX
1118 && s->first_glyph->left_box_line_p)
1119 x = s->x + eabs (s->face->box_line_width);
1120 else
1121 x = s->x;
1123 /* Draw characters of S as rectangles if S's font could not be
1124 loaded. */
1125 if (s->font_not_found_p)
1127 for (i = 0; i < s->nchars; ++i)
1129 struct glyph *g = s->first_glyph + i;
1130 XDrawRectangle (s->display, s->window,
1131 s->gc, x, s->y, g->pixel_width - 1,
1132 s->height - 1);
1133 x += g->pixel_width;
1136 else
1138 struct font *font = s->font;
1139 int boff = font->baseline_offset;
1140 int y;
1142 if (font->vertical_centering)
1143 boff = VCENTER_BASELINE_OFFSET (font, s->f) - boff;
1145 y = s->ybase - boff;
1146 if (s->for_overlaps
1147 || (s->background_filled_p && s->hl != DRAW_CURSOR))
1148 font->driver->draw (s, 0, s->nchars, x, y, false);
1149 else
1150 font->driver->draw (s, 0, s->nchars, x, y, true);
1151 if (s->face->overstrike)
1152 font->driver->draw (s, 0, s->nchars, x + 1, y, false);
1156 /* Draw the foreground of composite glyph string S. */
1158 static void
1159 x_draw_composite_glyph_string_foreground (struct glyph_string *s)
1161 int i, j, x;
1162 struct font *font = s->font;
1164 /* If first glyph of S has a left box line, start drawing the text
1165 of S to the right of that box line. */
1166 if (s->face && s->face->box != FACE_NO_BOX
1167 && s->first_glyph->left_box_line_p)
1168 x = s->x + eabs (s->face->box_line_width);
1169 else
1170 x = s->x;
1172 /* S is a glyph string for a composition. S->cmp_from is the index
1173 of the first character drawn for glyphs of this composition.
1174 S->cmp_from == 0 means we are drawing the very first character of
1175 this composition. */
1177 /* Draw a rectangle for the composition if the font for the very
1178 first character of the composition could not be loaded. */
1179 if (s->font_not_found_p)
1181 if (s->cmp_from == 0)
1182 XDrawRectangle (s->display, s->window, s->gc, x, s->y,
1183 s->width - 1, s->height - 1);
1185 else if (! s->first_glyph->u.cmp.automatic)
1187 int y = s->ybase;
1189 for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
1190 /* TAB in a composition means display glyphs with padding
1191 space on the left or right. */
1192 if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
1194 int xx = x + s->cmp->offsets[j * 2];
1195 int yy = y - s->cmp->offsets[j * 2 + 1];
1197 font->driver->draw (s, j, j + 1, xx, yy, false);
1198 if (s->face->overstrike)
1199 font->driver->draw (s, j, j + 1, xx + 1, yy, false);
1202 else
1204 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1205 Lisp_Object glyph;
1206 int y = s->ybase;
1207 int width = 0;
1209 for (i = j = s->cmp_from; i < s->cmp_to; i++)
1211 glyph = LGSTRING_GLYPH (gstring, i);
1212 if (NILP (LGLYPH_ADJUSTMENT (glyph)))
1213 width += LGLYPH_WIDTH (glyph);
1214 else
1216 int xoff, yoff, wadjust;
1218 if (j < i)
1220 font->driver->draw (s, j, i, x, y, false);
1221 if (s->face->overstrike)
1222 font->driver->draw (s, j, i, x + 1, y, false);
1223 x += width;
1225 xoff = LGLYPH_XOFF (glyph);
1226 yoff = LGLYPH_YOFF (glyph);
1227 wadjust = LGLYPH_WADJUST (glyph);
1228 font->driver->draw (s, i, i + 1, x + xoff, y + yoff, false);
1229 if (s->face->overstrike)
1230 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff,
1231 false);
1232 x += wadjust;
1233 j = i + 1;
1234 width = 0;
1237 if (j < i)
1239 font->driver->draw (s, j, i, x, y, false);
1240 if (s->face->overstrike)
1241 font->driver->draw (s, j, i, x + 1, y, false);
1247 /* Draw the foreground of glyph string S for glyphless characters. */
1249 static void
1250 x_draw_glyphless_glyph_string_foreground (struct glyph_string *s)
1252 struct glyph *glyph = s->first_glyph;
1253 XChar2b char2b[8];
1254 int x, i, j;
1256 /* If first glyph of S has a left box line, start drawing the text
1257 of S to the right of that box line. */
1258 if (s->face && s->face->box != FACE_NO_BOX
1259 && s->first_glyph->left_box_line_p)
1260 x = s->x + eabs (s->face->box_line_width);
1261 else
1262 x = s->x;
1264 s->char2b = char2b;
1266 for (i = 0; i < s->nchars; i++, glyph++)
1268 char buf[7], *str = NULL;
1269 int len = glyph->u.glyphless.len;
1271 if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_ACRONYM)
1273 if (len > 0
1274 && CHAR_TABLE_P (Vglyphless_char_display)
1275 && (CHAR_TABLE_EXTRA_SLOTS (XCHAR_TABLE (Vglyphless_char_display))
1276 >= 1))
1278 Lisp_Object acronym
1279 = (! glyph->u.glyphless.for_no_font
1280 ? CHAR_TABLE_REF (Vglyphless_char_display,
1281 glyph->u.glyphless.ch)
1282 : XCHAR_TABLE (Vglyphless_char_display)->extras[0]);
1283 if (STRINGP (acronym))
1284 str = SSDATA (acronym);
1287 else if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_HEX_CODE)
1289 sprintf (buf, "%0*X",
1290 glyph->u.glyphless.ch < 0x10000 ? 4 : 6,
1291 glyph->u.glyphless.ch);
1292 str = buf;
1295 if (str)
1297 int upper_len = (len + 1) / 2;
1298 unsigned code;
1300 /* It is assured that all LEN characters in STR is ASCII. */
1301 for (j = 0; j < len; j++)
1303 code = s->font->driver->encode_char (s->font, str[j]);
1304 STORE_XCHAR2B (char2b + j, code >> 8, code & 0xFF);
1306 s->font->driver->draw (s, 0, upper_len,
1307 x + glyph->slice.glyphless.upper_xoff,
1308 s->ybase + glyph->slice.glyphless.upper_yoff,
1309 false);
1310 s->font->driver->draw (s, upper_len, len,
1311 x + glyph->slice.glyphless.lower_xoff,
1312 s->ybase + glyph->slice.glyphless.lower_yoff,
1313 false);
1315 if (glyph->u.glyphless.method != GLYPHLESS_DISPLAY_THIN_SPACE)
1316 XDrawRectangle (s->display, s->window, s->gc,
1317 x, s->ybase - glyph->ascent,
1318 glyph->pixel_width - 1,
1319 glyph->ascent + glyph->descent - 1);
1320 x += glyph->pixel_width;
1324 #ifdef USE_X_TOOLKIT
1326 #ifdef USE_LUCID
1328 /* Return the frame on which widget WIDGET is used.. Abort if frame
1329 cannot be determined. */
1331 static struct frame *
1332 x_frame_of_widget (Widget widget)
1334 struct x_display_info *dpyinfo;
1335 Lisp_Object tail, frame;
1336 struct frame *f;
1338 dpyinfo = x_display_info_for_display (XtDisplay (widget));
1340 /* Find the top-level shell of the widget. Note that this function
1341 can be called when the widget is not yet realized, so XtWindow
1342 (widget) == 0. That's the reason we can't simply use
1343 x_any_window_to_frame. */
1344 while (!XtIsTopLevelShell (widget))
1345 widget = XtParent (widget);
1347 /* Look for a frame with that top-level widget. Allocate the color
1348 on that frame to get the right gamma correction value. */
1349 FOR_EACH_FRAME (tail, frame)
1351 f = XFRAME (frame);
1352 if (FRAME_X_P (f)
1353 && f->output_data.nothing != 1
1354 && FRAME_DISPLAY_INFO (f) == dpyinfo
1355 && f->output_data.x->widget == widget)
1356 return f;
1358 emacs_abort ();
1361 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
1362 or DELTA. Try a color with RGB values multiplied by FACTOR first.
1363 If this produces the same color as PIXEL, try a color where all RGB
1364 values have DELTA added. Return the allocated color in *PIXEL.
1365 DISPLAY is the X display, CMAP is the colormap to operate on.
1366 Value is true if successful. */
1368 bool
1369 x_alloc_lighter_color_for_widget (Widget widget, Display *display, Colormap cmap,
1370 unsigned long *pixel, double factor, int delta)
1372 struct frame *f = x_frame_of_widget (widget);
1373 return x_alloc_lighter_color (f, display, cmap, pixel, factor, delta);
1376 #endif /* USE_LUCID */
1379 /* Structure specifying which arguments should be passed by Xt to
1380 cvt_string_to_pixel. We want the widget's screen and colormap. */
1382 static XtConvertArgRec cvt_string_to_pixel_args[] =
1384 {XtWidgetBaseOffset, (XtPointer) XtOffset (Widget, core.screen),
1385 sizeof (Screen *)},
1386 {XtWidgetBaseOffset, (XtPointer) XtOffset (Widget, core.colormap),
1387 sizeof (Colormap)}
1391 /* The address of this variable is returned by
1392 cvt_string_to_pixel. */
1394 static Pixel cvt_string_to_pixel_value;
1397 /* Convert a color name to a pixel color.
1399 DPY is the display we are working on.
1401 ARGS is an array of *NARGS XrmValue structures holding additional
1402 information about the widget for which the conversion takes place.
1403 The contents of this array are determined by the specification
1404 in cvt_string_to_pixel_args.
1406 FROM is a pointer to an XrmValue which points to the color name to
1407 convert. TO is an XrmValue in which to return the pixel color.
1409 CLOSURE_RET is a pointer to user-data, in which we record if
1410 we allocated the color or not.
1412 Value is True if successful, False otherwise. */
1414 static Boolean
1415 cvt_string_to_pixel (Display *dpy, XrmValue *args, Cardinal *nargs,
1416 XrmValue *from, XrmValue *to,
1417 XtPointer *closure_ret)
1419 Screen *screen;
1420 Colormap cmap;
1421 Pixel pixel;
1422 String color_name;
1423 XColor color;
1425 if (*nargs != 2)
1427 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
1428 "wrongParameters", "cvt_string_to_pixel",
1429 "XtToolkitError",
1430 "Screen and colormap args required", NULL, NULL);
1431 return False;
1434 screen = *(Screen **) args[0].addr;
1435 cmap = *(Colormap *) args[1].addr;
1436 color_name = (String) from->addr;
1438 if (strcmp (color_name, XtDefaultBackground) == 0)
1440 *closure_ret = (XtPointer) False;
1441 pixel = WhitePixelOfScreen (screen);
1443 else if (strcmp (color_name, XtDefaultForeground) == 0)
1445 *closure_ret = (XtPointer) False;
1446 pixel = BlackPixelOfScreen (screen);
1448 else if (XParseColor (dpy, cmap, color_name, &color)
1449 && x_alloc_nearest_color_1 (dpy, cmap, &color))
1451 pixel = color.pixel;
1452 *closure_ret = (XtPointer) True;
1454 else
1456 String params[1];
1457 Cardinal nparams = 1;
1459 params[0] = color_name;
1460 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
1461 "badValue", "cvt_string_to_pixel",
1462 "XtToolkitError", "Invalid color `%s'",
1463 params, &nparams);
1464 return False;
1467 if (to->addr != NULL)
1469 if (to->size < sizeof (Pixel))
1471 to->size = sizeof (Pixel);
1472 return False;
1475 *(Pixel *) to->addr = pixel;
1477 else
1479 cvt_string_to_pixel_value = pixel;
1480 to->addr = (XtPointer) &cvt_string_to_pixel_value;
1483 to->size = sizeof (Pixel);
1484 return True;
1488 /* Free a pixel color which was previously allocated via
1489 cvt_string_to_pixel. This is registered as the destructor
1490 for this type of resource via XtSetTypeConverter.
1492 APP is the application context in which we work.
1494 TO is a pointer to an XrmValue holding the color to free.
1495 CLOSURE is the value we stored in CLOSURE_RET for this color
1496 in cvt_string_to_pixel.
1498 ARGS and NARGS are like for cvt_string_to_pixel. */
1500 static void
1501 cvt_pixel_dtor (XtAppContext app, XrmValuePtr to, XtPointer closure, XrmValuePtr args,
1502 Cardinal *nargs)
1504 if (*nargs != 2)
1506 XtAppWarningMsg (app, "wrongParameters", "cvt_pixel_dtor",
1507 "XtToolkitError",
1508 "Screen and colormap arguments required",
1509 NULL, NULL);
1511 else if (closure != NULL)
1513 /* We did allocate the pixel, so free it. */
1514 Screen *screen = *(Screen **) args[0].addr;
1515 Colormap cmap = *(Colormap *) args[1].addr;
1516 x_free_dpy_colors (DisplayOfScreen (screen), screen, cmap,
1517 (Pixel *) to->addr, 1);
1522 #endif /* USE_X_TOOLKIT */
1525 /* Value is an array of XColor structures for the contents of the
1526 color map of display DPY. Set *NCELLS to the size of the array.
1527 Note that this probably shouldn't be called for large color maps,
1528 say a 24-bit TrueColor map. */
1530 static const XColor *
1531 x_color_cells (Display *dpy, int *ncells)
1533 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
1535 if (dpyinfo->color_cells == NULL)
1537 Screen *screen = dpyinfo->screen;
1538 int ncolor_cells = XDisplayCells (dpy, XScreenNumberOfScreen (screen));
1539 int i;
1541 dpyinfo->color_cells = xnmalloc (ncolor_cells,
1542 sizeof *dpyinfo->color_cells);
1543 dpyinfo->ncolor_cells = ncolor_cells;
1545 for (i = 0; i < ncolor_cells; ++i)
1546 dpyinfo->color_cells[i].pixel = i;
1548 XQueryColors (dpy, dpyinfo->cmap,
1549 dpyinfo->color_cells, ncolor_cells);
1552 *ncells = dpyinfo->ncolor_cells;
1553 return dpyinfo->color_cells;
1557 /* On frame F, translate pixel colors to RGB values for the NCOLORS
1558 colors in COLORS. Use cached information, if available. */
1560 void
1561 x_query_colors (struct frame *f, XColor *colors, int ncolors)
1563 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1565 if (dpyinfo->color_cells)
1567 int i;
1568 for (i = 0; i < ncolors; ++i)
1570 unsigned long pixel = colors[i].pixel;
1571 eassert (pixel < dpyinfo->ncolor_cells);
1572 eassert (dpyinfo->color_cells[pixel].pixel == pixel);
1573 colors[i] = dpyinfo->color_cells[pixel];
1576 else
1577 XQueryColors (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), colors, ncolors);
1581 /* On frame F, translate pixel color to RGB values for the color in
1582 COLOR. Use cached information, if available. */
1584 void
1585 x_query_color (struct frame *f, XColor *color)
1587 x_query_colors (f, color, 1);
1591 /* Allocate the color COLOR->pixel on DISPLAY, colormap CMAP. If an
1592 exact match can't be allocated, try the nearest color available.
1593 Value is true if successful. Set *COLOR to the color
1594 allocated. */
1596 static bool
1597 x_alloc_nearest_color_1 (Display *dpy, Colormap cmap, XColor *color)
1599 bool rc;
1601 rc = XAllocColor (dpy, cmap, color) != 0;
1602 if (rc == 0)
1604 /* If we got to this point, the colormap is full, so we're going
1605 to try to get the next closest color. The algorithm used is
1606 a least-squares matching, which is what X uses for closest
1607 color matching with StaticColor visuals. */
1608 int nearest, i;
1609 int max_color_delta = 255;
1610 int max_delta = 3 * max_color_delta;
1611 int nearest_delta = max_delta + 1;
1612 int ncells;
1613 const XColor *cells = x_color_cells (dpy, &ncells);
1615 for (nearest = i = 0; i < ncells; ++i)
1617 int dred = (color->red >> 8) - (cells[i].red >> 8);
1618 int dgreen = (color->green >> 8) - (cells[i].green >> 8);
1619 int dblue = (color->blue >> 8) - (cells[i].blue >> 8);
1620 int delta = dred * dred + dgreen * dgreen + dblue * dblue;
1622 if (delta < nearest_delta)
1624 nearest = i;
1625 nearest_delta = delta;
1629 color->red = cells[nearest].red;
1630 color->green = cells[nearest].green;
1631 color->blue = cells[nearest].blue;
1632 rc = XAllocColor (dpy, cmap, color) != 0;
1634 else
1636 /* If allocation succeeded, and the allocated pixel color is not
1637 equal to a cached pixel color recorded earlier, there was a
1638 change in the colormap, so clear the color cache. */
1639 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
1640 XColor *cached_color;
1642 if (dpyinfo->color_cells
1643 && (cached_color = &dpyinfo->color_cells[color->pixel],
1644 (cached_color->red != color->red
1645 || cached_color->blue != color->blue
1646 || cached_color->green != color->green)))
1648 xfree (dpyinfo->color_cells);
1649 dpyinfo->color_cells = NULL;
1650 dpyinfo->ncolor_cells = 0;
1654 #ifdef DEBUG_X_COLORS
1655 if (rc)
1656 register_color (color->pixel);
1657 #endif /* DEBUG_X_COLORS */
1659 return rc;
1663 /* Allocate the color COLOR->pixel on frame F, colormap CMAP. If an
1664 exact match can't be allocated, try the nearest color available.
1665 Value is true if successful. Set *COLOR to the color
1666 allocated. */
1668 bool
1669 x_alloc_nearest_color (struct frame *f, Colormap cmap, XColor *color)
1671 gamma_correct (f, color);
1672 return x_alloc_nearest_color_1 (FRAME_X_DISPLAY (f), cmap, color);
1676 /* Allocate color PIXEL on frame F. PIXEL must already be allocated.
1677 It's necessary to do this instead of just using PIXEL directly to
1678 get color reference counts right. */
1680 unsigned long
1681 x_copy_color (struct frame *f, unsigned long pixel)
1683 XColor color;
1685 color.pixel = pixel;
1686 block_input ();
1687 x_query_color (f, &color);
1688 XAllocColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &color);
1689 unblock_input ();
1690 #ifdef DEBUG_X_COLORS
1691 register_color (pixel);
1692 #endif
1693 return color.pixel;
1697 /* Brightness beyond which a color won't have its highlight brightness
1698 boosted.
1700 Nominally, highlight colors for `3d' faces are calculated by
1701 brightening an object's color by a constant scale factor, but this
1702 doesn't yield good results for dark colors, so for colors who's
1703 brightness is less than this value (on a scale of 0-65535) have an
1704 use an additional additive factor.
1706 The value here is set so that the default menu-bar/mode-line color
1707 (grey75) will not have its highlights changed at all. */
1708 #define HIGHLIGHT_COLOR_DARK_BOOST_LIMIT 48000
1711 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
1712 or DELTA. Try a color with RGB values multiplied by FACTOR first.
1713 If this produces the same color as PIXEL, try a color where all RGB
1714 values have DELTA added. Return the allocated color in *PIXEL.
1715 DISPLAY is the X display, CMAP is the colormap to operate on.
1716 Value is non-zero if successful. */
1718 static bool
1719 x_alloc_lighter_color (struct frame *f, Display *display, Colormap cmap,
1720 unsigned long *pixel, double factor, int delta)
1722 XColor color, new;
1723 long bright;
1724 bool success_p;
1726 /* Get RGB color values. */
1727 color.pixel = *pixel;
1728 x_query_color (f, &color);
1730 /* Change RGB values by specified FACTOR. Avoid overflow! */
1731 eassert (factor >= 0);
1732 new.red = min (0xffff, factor * color.red);
1733 new.green = min (0xffff, factor * color.green);
1734 new.blue = min (0xffff, factor * color.blue);
1736 /* Calculate brightness of COLOR. */
1737 bright = (2 * color.red + 3 * color.green + color.blue) / 6;
1739 /* We only boost colors that are darker than
1740 HIGHLIGHT_COLOR_DARK_BOOST_LIMIT. */
1741 if (bright < HIGHLIGHT_COLOR_DARK_BOOST_LIMIT)
1742 /* Make an additive adjustment to NEW, because it's dark enough so
1743 that scaling by FACTOR alone isn't enough. */
1745 /* How far below the limit this color is (0 - 1, 1 being darker). */
1746 double dimness = 1 - (double)bright / HIGHLIGHT_COLOR_DARK_BOOST_LIMIT;
1747 /* The additive adjustment. */
1748 int min_delta = delta * dimness * factor / 2;
1750 if (factor < 1)
1752 new.red = max (0, new.red - min_delta);
1753 new.green = max (0, new.green - min_delta);
1754 new.blue = max (0, new.blue - min_delta);
1756 else
1758 new.red = min (0xffff, min_delta + new.red);
1759 new.green = min (0xffff, min_delta + new.green);
1760 new.blue = min (0xffff, min_delta + new.blue);
1764 /* Try to allocate the color. */
1765 success_p = x_alloc_nearest_color (f, cmap, &new);
1766 if (success_p)
1768 if (new.pixel == *pixel)
1770 /* If we end up with the same color as before, try adding
1771 delta to the RGB values. */
1772 x_free_colors (f, &new.pixel, 1);
1774 new.red = min (0xffff, delta + color.red);
1775 new.green = min (0xffff, delta + color.green);
1776 new.blue = min (0xffff, delta + color.blue);
1777 success_p = x_alloc_nearest_color (f, cmap, &new);
1779 else
1780 success_p = true;
1781 *pixel = new.pixel;
1784 return success_p;
1788 /* Set up the foreground color for drawing relief lines of glyph
1789 string S. RELIEF is a pointer to a struct relief containing the GC
1790 with which lines will be drawn. Use a color that is FACTOR or
1791 DELTA lighter or darker than the relief's background which is found
1792 in S->f->output_data.x->relief_background. If such a color cannot
1793 be allocated, use DEFAULT_PIXEL, instead. */
1795 static void
1796 x_setup_relief_color (struct frame *f, struct relief *relief, double factor,
1797 int delta, unsigned long default_pixel)
1799 XGCValues xgcv;
1800 struct x_output *di = f->output_data.x;
1801 unsigned long mask = GCForeground | GCLineWidth | GCGraphicsExposures;
1802 unsigned long pixel;
1803 unsigned long background = di->relief_background;
1804 Colormap cmap = FRAME_X_COLORMAP (f);
1805 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1806 Display *dpy = FRAME_X_DISPLAY (f);
1808 xgcv.graphics_exposures = False;
1809 xgcv.line_width = 1;
1811 /* Free previously allocated color. The color cell will be reused
1812 when it has been freed as many times as it was allocated, so this
1813 doesn't affect faces using the same colors. */
1814 if (relief->gc && relief->pixel != -1)
1816 x_free_colors (f, &relief->pixel, 1);
1817 relief->pixel = -1;
1820 /* Allocate new color. */
1821 xgcv.foreground = default_pixel;
1822 pixel = background;
1823 if (dpyinfo->n_planes != 1
1824 && x_alloc_lighter_color (f, dpy, cmap, &pixel, factor, delta))
1825 xgcv.foreground = relief->pixel = pixel;
1827 if (relief->gc == 0)
1829 xgcv.stipple = dpyinfo->gray;
1830 mask |= GCStipple;
1831 relief->gc = XCreateGC (dpy, FRAME_X_WINDOW (f), mask, &xgcv);
1833 else
1834 XChangeGC (dpy, relief->gc, mask, &xgcv);
1838 /* Set up colors for the relief lines around glyph string S. */
1840 static void
1841 x_setup_relief_colors (struct glyph_string *s)
1843 struct x_output *di = s->f->output_data.x;
1844 unsigned long color;
1846 if (s->face->use_box_color_for_shadows_p)
1847 color = s->face->box_color;
1848 else if (s->first_glyph->type == IMAGE_GLYPH
1849 && s->img->pixmap
1850 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
1851 color = IMAGE_BACKGROUND (s->img, s->f, 0);
1852 else
1854 XGCValues xgcv;
1856 /* Get the background color of the face. */
1857 XGetGCValues (s->display, s->gc, GCBackground, &xgcv);
1858 color = xgcv.background;
1861 if (di->white_relief.gc == 0
1862 || color != di->relief_background)
1864 di->relief_background = color;
1865 x_setup_relief_color (s->f, &di->white_relief, 1.2, 0x8000,
1866 WHITE_PIX_DEFAULT (s->f));
1867 x_setup_relief_color (s->f, &di->black_relief, 0.6, 0x4000,
1868 BLACK_PIX_DEFAULT (s->f));
1873 /* Draw a relief on frame F inside the rectangle given by LEFT_X,
1874 TOP_Y, RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the relief
1875 to draw, it must be >= 0. RAISED_P means draw a raised
1876 relief. LEFT_P means draw a relief on the left side of
1877 the rectangle. RIGHT_P means draw a relief on the right
1878 side of the rectangle. CLIP_RECT is the clipping rectangle to use
1879 when drawing. */
1881 static void
1882 x_draw_relief_rect (struct frame *f,
1883 int left_x, int top_y, int right_x, int bottom_y,
1884 int width, bool raised_p, bool top_p, bool bot_p,
1885 bool left_p, bool right_p,
1886 XRectangle *clip_rect)
1888 Display *dpy = FRAME_X_DISPLAY (f);
1889 Window window = FRAME_X_WINDOW (f);
1890 int i;
1891 GC gc;
1893 if (raised_p)
1894 gc = f->output_data.x->white_relief.gc;
1895 else
1896 gc = f->output_data.x->black_relief.gc;
1897 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
1899 /* This code is more complicated than it has to be, because of two
1900 minor hacks to make the boxes look nicer: (i) if width > 1, draw
1901 the outermost line using the black relief. (ii) Omit the four
1902 corner pixels. */
1904 /* Top. */
1905 if (top_p)
1907 if (width == 1)
1908 XDrawLine (dpy, window, gc,
1909 left_x + left_p, top_y,
1910 right_x + !right_p, top_y);
1912 for (i = 1; i < width; ++i)
1913 XDrawLine (dpy, window, gc,
1914 left_x + i * left_p, top_y + i,
1915 right_x + 1 - i * right_p, top_y + i);
1918 /* Left. */
1919 if (left_p)
1921 if (width == 1)
1922 XDrawLine (dpy, window, gc, left_x, top_y + 1, left_x, bottom_y);
1924 XClearArea (dpy, window, left_x, top_y, 1, 1, False);
1925 XClearArea (dpy, window, left_x, bottom_y, 1, 1, False);
1927 for (i = (width > 1 ? 1 : 0); i < width; ++i)
1928 XDrawLine (dpy, window, gc,
1929 left_x + i, top_y + (i + 1) * top_p,
1930 left_x + i, bottom_y + 1 - (i + 1) * bot_p);
1933 XSetClipMask (dpy, gc, None);
1934 if (raised_p)
1935 gc = f->output_data.x->black_relief.gc;
1936 else
1937 gc = f->output_data.x->white_relief.gc;
1938 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
1940 if (width > 1)
1942 /* Outermost top line. */
1943 if (top_p)
1944 XDrawLine (dpy, window, gc,
1945 left_x + left_p, top_y,
1946 right_x + !right_p, top_y);
1948 /* Outermost left line. */
1949 if (left_p)
1950 XDrawLine (dpy, window, gc, left_x, top_y + 1, left_x, bottom_y);
1953 /* Bottom. */
1954 if (bot_p)
1956 XDrawLine (dpy, window, gc,
1957 left_x + left_p, bottom_y,
1958 right_x + !right_p, bottom_y);
1959 for (i = 1; i < width; ++i)
1960 XDrawLine (dpy, window, gc,
1961 left_x + i * left_p, bottom_y - i,
1962 right_x + 1 - i * right_p, bottom_y - i);
1965 /* Right. */
1966 if (right_p)
1968 XClearArea (dpy, window, right_x, top_y, 1, 1, False);
1969 XClearArea (dpy, window, right_x, bottom_y, 1, 1, False);
1970 for (i = 0; i < width; ++i)
1971 XDrawLine (dpy, window, gc,
1972 right_x - i, top_y + (i + 1) * top_p,
1973 right_x - i, bottom_y + 1 - (i + 1) * bot_p);
1976 XSetClipMask (dpy, gc, None);
1980 /* Draw a box on frame F inside the rectangle given by LEFT_X, TOP_Y,
1981 RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the lines to
1982 draw, it must be >= 0. LEFT_P means draw a line on the
1983 left side of the rectangle. RIGHT_P means draw a line
1984 on the right side of the rectangle. CLIP_RECT is the clipping
1985 rectangle to use when drawing. */
1987 static void
1988 x_draw_box_rect (struct glyph_string *s,
1989 int left_x, int top_y, int right_x, int bottom_y, int width,
1990 bool left_p, bool right_p, XRectangle *clip_rect)
1992 XGCValues xgcv;
1994 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
1995 XSetForeground (s->display, s->gc, s->face->box_color);
1996 XSetClipRectangles (s->display, s->gc, 0, 0, clip_rect, 1, Unsorted);
1998 /* Top. */
1999 XFillRectangle (s->display, s->window, s->gc,
2000 left_x, top_y, right_x - left_x + 1, width);
2002 /* Left. */
2003 if (left_p)
2004 XFillRectangle (s->display, s->window, s->gc,
2005 left_x, top_y, width, bottom_y - top_y + 1);
2007 /* Bottom. */
2008 XFillRectangle (s->display, s->window, s->gc,
2009 left_x, bottom_y - width + 1, right_x - left_x + 1, width);
2011 /* Right. */
2012 if (right_p)
2013 XFillRectangle (s->display, s->window, s->gc,
2014 right_x - width + 1, top_y, width, bottom_y - top_y + 1);
2016 XSetForeground (s->display, s->gc, xgcv.foreground);
2017 XSetClipMask (s->display, s->gc, None);
2021 /* Draw a box around glyph string S. */
2023 static void
2024 x_draw_glyph_string_box (struct glyph_string *s)
2026 int width, left_x, right_x, top_y, bottom_y, last_x;
2027 bool raised_p, left_p, right_p;
2028 struct glyph *last_glyph;
2029 XRectangle clip_rect;
2031 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2032 ? WINDOW_RIGHT_EDGE_X (s->w)
2033 : window_box_right (s->w, s->area));
2035 /* The glyph that may have a right box line. */
2036 last_glyph = (s->cmp || s->img
2037 ? s->first_glyph
2038 : s->first_glyph + s->nchars - 1);
2040 width = eabs (s->face->box_line_width);
2041 raised_p = s->face->box == FACE_RAISED_BOX;
2042 left_x = s->x;
2043 right_x = (s->row->full_width_p && s->extends_to_end_of_line_p
2044 ? last_x - 1
2045 : min (last_x, s->x + s->background_width) - 1);
2046 top_y = s->y;
2047 bottom_y = top_y + s->height - 1;
2049 left_p = (s->first_glyph->left_box_line_p
2050 || (s->hl == DRAW_MOUSE_FACE
2051 && (s->prev == NULL
2052 || s->prev->hl != s->hl)));
2053 right_p = (last_glyph->right_box_line_p
2054 || (s->hl == DRAW_MOUSE_FACE
2055 && (s->next == NULL
2056 || s->next->hl != s->hl)));
2058 get_glyph_string_clip_rect (s, &clip_rect);
2060 if (s->face->box == FACE_SIMPLE_BOX)
2061 x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
2062 left_p, right_p, &clip_rect);
2063 else
2065 x_setup_relief_colors (s);
2066 x_draw_relief_rect (s->f, left_x, top_y, right_x, bottom_y,
2067 width, raised_p, true, true, left_p, right_p,
2068 &clip_rect);
2073 /* Draw foreground of image glyph string S. */
2075 static void
2076 x_draw_image_foreground (struct glyph_string *s)
2078 int x = s->x;
2079 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2081 /* If first glyph of S has a left box line, start drawing it to the
2082 right of that line. */
2083 if (s->face->box != FACE_NO_BOX
2084 && s->first_glyph->left_box_line_p
2085 && s->slice.x == 0)
2086 x += eabs (s->face->box_line_width);
2088 /* If there is a margin around the image, adjust x- and y-position
2089 by that margin. */
2090 if (s->slice.x == 0)
2091 x += s->img->hmargin;
2092 if (s->slice.y == 0)
2093 y += s->img->vmargin;
2095 if (s->img->pixmap)
2097 if (s->img->mask)
2099 /* We can't set both a clip mask and use XSetClipRectangles
2100 because the latter also sets a clip mask. We also can't
2101 trust on the shape extension to be available
2102 (XShapeCombineRegion). So, compute the rectangle to draw
2103 manually. */
2104 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
2105 | GCFunction);
2106 XGCValues xgcv;
2107 XRectangle clip_rect, image_rect, r;
2109 xgcv.clip_mask = s->img->mask;
2110 xgcv.clip_x_origin = x;
2111 xgcv.clip_y_origin = y;
2112 xgcv.function = GXcopy;
2113 XChangeGC (s->display, s->gc, mask, &xgcv);
2115 get_glyph_string_clip_rect (s, &clip_rect);
2116 image_rect.x = x;
2117 image_rect.y = y;
2118 image_rect.width = s->slice.width;
2119 image_rect.height = s->slice.height;
2120 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
2121 XCopyArea (s->display, s->img->pixmap, s->window, s->gc,
2122 s->slice.x + r.x - x, s->slice.y + r.y - y,
2123 r.width, r.height, r.x, r.y);
2125 else
2127 XRectangle clip_rect, image_rect, r;
2129 get_glyph_string_clip_rect (s, &clip_rect);
2130 image_rect.x = x;
2131 image_rect.y = y;
2132 image_rect.width = s->slice.width;
2133 image_rect.height = s->slice.height;
2134 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
2135 XCopyArea (s->display, s->img->pixmap, s->window, s->gc,
2136 s->slice.x + r.x - x, s->slice.y + r.y - y,
2137 r.width, r.height, r.x, r.y);
2139 /* When the image has a mask, we can expect that at
2140 least part of a mouse highlight or a block cursor will
2141 be visible. If the image doesn't have a mask, make
2142 a block cursor visible by drawing a rectangle around
2143 the image. I believe it's looking better if we do
2144 nothing here for mouse-face. */
2145 if (s->hl == DRAW_CURSOR)
2147 int relief = eabs (s->img->relief);
2148 XDrawRectangle (s->display, s->window, s->gc,
2149 x - relief, y - relief,
2150 s->slice.width + relief*2 - 1,
2151 s->slice.height + relief*2 - 1);
2155 else
2156 /* Draw a rectangle if image could not be loaded. */
2157 XDrawRectangle (s->display, s->window, s->gc, x, y,
2158 s->slice.width - 1, s->slice.height - 1);
2162 /* Draw a relief around the image glyph string S. */
2164 static void
2165 x_draw_image_relief (struct glyph_string *s)
2167 int x1, y1, thick;
2168 bool raised_p, top_p, bot_p, left_p, right_p;
2169 int extra_x, extra_y;
2170 XRectangle r;
2171 int x = s->x;
2172 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2174 /* If first glyph of S has a left box line, start drawing it to the
2175 right of that line. */
2176 if (s->face->box != FACE_NO_BOX
2177 && s->first_glyph->left_box_line_p
2178 && s->slice.x == 0)
2179 x += eabs (s->face->box_line_width);
2181 /* If there is a margin around the image, adjust x- and y-position
2182 by that margin. */
2183 if (s->slice.x == 0)
2184 x += s->img->hmargin;
2185 if (s->slice.y == 0)
2186 y += s->img->vmargin;
2188 if (s->hl == DRAW_IMAGE_SUNKEN
2189 || s->hl == DRAW_IMAGE_RAISED)
2191 thick = tool_bar_button_relief >= 0 ? tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
2192 raised_p = s->hl == DRAW_IMAGE_RAISED;
2194 else
2196 thick = eabs (s->img->relief);
2197 raised_p = s->img->relief > 0;
2200 x1 = x + s->slice.width - 1;
2201 y1 = y + s->slice.height - 1;
2203 extra_x = extra_y = 0;
2204 if (s->face->id == TOOL_BAR_FACE_ID)
2206 if (CONSP (Vtool_bar_button_margin)
2207 && INTEGERP (XCAR (Vtool_bar_button_margin))
2208 && INTEGERP (XCDR (Vtool_bar_button_margin)))
2210 extra_x = XINT (XCAR (Vtool_bar_button_margin));
2211 extra_y = XINT (XCDR (Vtool_bar_button_margin));
2213 else if (INTEGERP (Vtool_bar_button_margin))
2214 extra_x = extra_y = XINT (Vtool_bar_button_margin);
2217 top_p = bot_p = left_p = right_p = false;
2219 if (s->slice.x == 0)
2220 x -= thick + extra_x, left_p = true;
2221 if (s->slice.y == 0)
2222 y -= thick + extra_y, top_p = true;
2223 if (s->slice.x + s->slice.width == s->img->width)
2224 x1 += thick + extra_x, right_p = true;
2225 if (s->slice.y + s->slice.height == s->img->height)
2226 y1 += thick + extra_y, bot_p = true;
2228 x_setup_relief_colors (s);
2229 get_glyph_string_clip_rect (s, &r);
2230 x_draw_relief_rect (s->f, x, y, x1, y1, thick, raised_p,
2231 top_p, bot_p, left_p, right_p, &r);
2235 /* Draw the foreground of image glyph string S to PIXMAP. */
2237 static void
2238 x_draw_image_foreground_1 (struct glyph_string *s, Pixmap pixmap)
2240 int x = 0;
2241 int y = s->ybase - s->y - image_ascent (s->img, s->face, &s->slice);
2243 /* If first glyph of S has a left box line, start drawing it to the
2244 right of that line. */
2245 if (s->face->box != FACE_NO_BOX
2246 && s->first_glyph->left_box_line_p
2247 && s->slice.x == 0)
2248 x += eabs (s->face->box_line_width);
2250 /* If there is a margin around the image, adjust x- and y-position
2251 by that margin. */
2252 if (s->slice.x == 0)
2253 x += s->img->hmargin;
2254 if (s->slice.y == 0)
2255 y += s->img->vmargin;
2257 if (s->img->pixmap)
2259 if (s->img->mask)
2261 /* We can't set both a clip mask and use XSetClipRectangles
2262 because the latter also sets a clip mask. We also can't
2263 trust on the shape extension to be available
2264 (XShapeCombineRegion). So, compute the rectangle to draw
2265 manually. */
2266 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
2267 | GCFunction);
2268 XGCValues xgcv;
2270 xgcv.clip_mask = s->img->mask;
2271 xgcv.clip_x_origin = x - s->slice.x;
2272 xgcv.clip_y_origin = y - s->slice.y;
2273 xgcv.function = GXcopy;
2274 XChangeGC (s->display, s->gc, mask, &xgcv);
2276 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
2277 s->slice.x, s->slice.y,
2278 s->slice.width, s->slice.height, x, y);
2279 XSetClipMask (s->display, s->gc, None);
2281 else
2283 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
2284 s->slice.x, s->slice.y,
2285 s->slice.width, s->slice.height, x, y);
2287 /* When the image has a mask, we can expect that at
2288 least part of a mouse highlight or a block cursor will
2289 be visible. If the image doesn't have a mask, make
2290 a block cursor visible by drawing a rectangle around
2291 the image. I believe it's looking better if we do
2292 nothing here for mouse-face. */
2293 if (s->hl == DRAW_CURSOR)
2295 int r = eabs (s->img->relief);
2296 XDrawRectangle (s->display, s->window, s->gc, x - r, y - r,
2297 s->slice.width + r*2 - 1,
2298 s->slice.height + r*2 - 1);
2302 else
2303 /* Draw a rectangle if image could not be loaded. */
2304 XDrawRectangle (s->display, pixmap, s->gc, x, y,
2305 s->slice.width - 1, s->slice.height - 1);
2309 /* Draw part of the background of glyph string S. X, Y, W, and H
2310 give the rectangle to draw. */
2312 static void
2313 x_draw_glyph_string_bg_rect (struct glyph_string *s, int x, int y, int w, int h)
2315 if (s->stippled_p)
2317 /* Fill background with a stipple pattern. */
2318 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
2319 XFillRectangle (s->display, s->window, s->gc, x, y, w, h);
2320 XSetFillStyle (s->display, s->gc, FillSolid);
2322 else
2323 x_clear_glyph_string_rect (s, x, y, w, h);
2327 /* Draw image glyph string S.
2329 s->y
2330 s->x +-------------------------
2331 | s->face->box
2333 | +-------------------------
2334 | | s->img->margin
2336 | | +-------------------
2337 | | | the image
2341 static void
2342 x_draw_image_glyph_string (struct glyph_string *s)
2344 int box_line_hwidth = eabs (s->face->box_line_width);
2345 int box_line_vwidth = max (s->face->box_line_width, 0);
2346 int height;
2347 Pixmap pixmap = None;
2349 height = s->height;
2350 if (s->slice.y == 0)
2351 height -= box_line_vwidth;
2352 if (s->slice.y + s->slice.height >= s->img->height)
2353 height -= box_line_vwidth;
2355 /* Fill background with face under the image. Do it only if row is
2356 taller than image or if image has a clip mask to reduce
2357 flickering. */
2358 s->stippled_p = s->face->stipple != 0;
2359 if (height > s->slice.height
2360 || s->img->hmargin
2361 || s->img->vmargin
2362 || s->img->mask
2363 || s->img->pixmap == 0
2364 || s->width != s->background_width)
2366 if (s->img->mask)
2368 /* Create a pixmap as large as the glyph string. Fill it
2369 with the background color. Copy the image to it, using
2370 its mask. Copy the temporary pixmap to the display. */
2371 Screen *screen = FRAME_X_SCREEN (s->f);
2372 int depth = DefaultDepthOfScreen (screen);
2374 /* Create a pixmap as large as the glyph string. */
2375 pixmap = XCreatePixmap (s->display, s->window,
2376 s->background_width,
2377 s->height, depth);
2379 /* Don't clip in the following because we're working on the
2380 pixmap. */
2381 XSetClipMask (s->display, s->gc, None);
2383 /* Fill the pixmap with the background color/stipple. */
2384 if (s->stippled_p)
2386 /* Fill background with a stipple pattern. */
2387 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
2388 XSetTSOrigin (s->display, s->gc, - s->x, - s->y);
2389 XFillRectangle (s->display, pixmap, s->gc,
2390 0, 0, s->background_width, s->height);
2391 XSetFillStyle (s->display, s->gc, FillSolid);
2392 XSetTSOrigin (s->display, s->gc, 0, 0);
2394 else
2396 XGCValues xgcv;
2397 XGetGCValues (s->display, s->gc, GCForeground | GCBackground,
2398 &xgcv);
2399 XSetForeground (s->display, s->gc, xgcv.background);
2400 XFillRectangle (s->display, pixmap, s->gc,
2401 0, 0, s->background_width, s->height);
2402 XSetForeground (s->display, s->gc, xgcv.foreground);
2405 else
2407 int x = s->x;
2408 int y = s->y;
2409 int width = s->background_width;
2411 if (s->first_glyph->left_box_line_p
2412 && s->slice.x == 0)
2414 x += box_line_hwidth;
2415 width -= box_line_hwidth;
2418 if (s->slice.y == 0)
2419 y += box_line_vwidth;
2421 x_draw_glyph_string_bg_rect (s, x, y, width, height);
2424 s->background_filled_p = true;
2427 /* Draw the foreground. */
2428 if (pixmap != None)
2430 x_draw_image_foreground_1 (s, pixmap);
2431 x_set_glyph_string_clipping (s);
2432 XCopyArea (s->display, pixmap, s->window, s->gc,
2433 0, 0, s->background_width, s->height, s->x, s->y);
2434 XFreePixmap (s->display, pixmap);
2436 else
2437 x_draw_image_foreground (s);
2439 /* If we must draw a relief around the image, do it. */
2440 if (s->img->relief
2441 || s->hl == DRAW_IMAGE_RAISED
2442 || s->hl == DRAW_IMAGE_SUNKEN)
2443 x_draw_image_relief (s);
2447 /* Draw stretch glyph string S. */
2449 static void
2450 x_draw_stretch_glyph_string (struct glyph_string *s)
2452 eassert (s->first_glyph->type == STRETCH_GLYPH);
2454 if (s->hl == DRAW_CURSOR
2455 && !x_stretch_cursor_p)
2457 /* If `x-stretch-cursor' is nil, don't draw a block cursor as
2458 wide as the stretch glyph. */
2459 int width, background_width = s->background_width;
2460 int x = s->x;
2462 if (!s->row->reversed_p)
2464 int left_x = window_box_left_offset (s->w, TEXT_AREA);
2466 if (x < left_x)
2468 background_width -= left_x - x;
2469 x = left_x;
2472 else
2474 /* In R2L rows, draw the cursor on the right edge of the
2475 stretch glyph. */
2476 int right_x = window_box_right (s->w, TEXT_AREA);
2478 if (x + background_width > right_x)
2479 background_width -= x - right_x;
2480 x += background_width;
2482 width = min (FRAME_COLUMN_WIDTH (s->f), background_width);
2483 if (s->row->reversed_p)
2484 x -= width;
2486 /* Draw cursor. */
2487 x_draw_glyph_string_bg_rect (s, x, s->y, width, s->height);
2489 /* Clear rest using the GC of the original non-cursor face. */
2490 if (width < background_width)
2492 int y = s->y;
2493 int w = background_width - width, h = s->height;
2494 XRectangle r;
2495 GC gc;
2497 if (!s->row->reversed_p)
2498 x += width;
2499 else
2500 x = s->x;
2501 if (s->row->mouse_face_p
2502 && cursor_in_mouse_face_p (s->w))
2504 x_set_mouse_face_gc (s);
2505 gc = s->gc;
2507 else
2508 gc = s->face->gc;
2510 get_glyph_string_clip_rect (s, &r);
2511 XSetClipRectangles (s->display, gc, 0, 0, &r, 1, Unsorted);
2513 if (s->face->stipple)
2515 /* Fill background with a stipple pattern. */
2516 XSetFillStyle (s->display, gc, FillOpaqueStippled);
2517 XFillRectangle (s->display, s->window, gc, x, y, w, h);
2518 XSetFillStyle (s->display, gc, FillSolid);
2520 else
2522 XGCValues xgcv;
2523 XGetGCValues (s->display, gc, GCForeground | GCBackground, &xgcv);
2524 XSetForeground (s->display, gc, xgcv.background);
2525 XFillRectangle (s->display, s->window, gc, x, y, w, h);
2526 XSetForeground (s->display, gc, xgcv.foreground);
2529 XSetClipMask (s->display, gc, None);
2532 else if (!s->background_filled_p)
2534 int background_width = s->background_width;
2535 int x = s->x, left_x = window_box_left_offset (s->w, TEXT_AREA);
2537 /* Don't draw into left margin, fringe or scrollbar area
2538 except for header line and mode line. */
2539 if (x < left_x && !s->row->mode_line_p)
2541 background_width -= left_x - x;
2542 x = left_x;
2544 if (background_width > 0)
2545 x_draw_glyph_string_bg_rect (s, x, s->y, background_width, s->height);
2548 s->background_filled_p = true;
2552 Draw a wavy line under S. The wave fills wave_height pixels from y0.
2554 x0 wave_length = 2
2556 y0 * * * * *
2557 |* * * * * * * * *
2558 wave_height = 3 | * * * *
2562 static void
2563 x_draw_underwave (struct glyph_string *s)
2565 int wave_height = 3, wave_length = 2;
2566 int dx, dy, x0, y0, width, x1, y1, x2, y2, xmax;
2567 bool odd;
2568 XRectangle wave_clip, string_clip, final_clip;
2570 dx = wave_length;
2571 dy = wave_height - 1;
2572 x0 = s->x;
2573 y0 = s->ybase - wave_height + 3;
2574 width = s->width;
2575 xmax = x0 + width;
2577 /* Find and set clipping rectangle */
2579 wave_clip.x = x0;
2580 wave_clip.y = y0;
2581 wave_clip.width = width;
2582 wave_clip.height = wave_height;
2583 get_glyph_string_clip_rect (s, &string_clip);
2585 if (!x_intersect_rectangles (&wave_clip, &string_clip, &final_clip))
2586 return;
2588 XSetClipRectangles (s->display, s->gc, 0, 0, &final_clip, 1, Unsorted);
2590 /* Draw the waves */
2592 x1 = x0 - (x0 % dx);
2593 x2 = x1 + dx;
2594 odd = (x1 / dx) & 1;
2595 y1 = y2 = y0;
2597 if (odd)
2598 y1 += dy;
2599 else
2600 y2 += dy;
2602 if (INT_MAX - dx < xmax)
2603 emacs_abort ();
2605 while (x1 <= xmax)
2607 XDrawLine (s->display, s->window, s->gc, x1, y1, x2, y2);
2608 x1 = x2, y1 = y2;
2609 x2 += dx, y2 = y0 + odd*dy;
2610 odd = !odd;
2613 /* Restore previous clipping rectangle(s) */
2614 XSetClipRectangles (s->display, s->gc, 0, 0, s->clip, s->num_clips, Unsorted);
2618 /* Draw glyph string S. */
2620 static void
2621 x_draw_glyph_string (struct glyph_string *s)
2623 bool relief_drawn_p = false;
2625 /* If S draws into the background of its successors, draw the
2626 background of the successors first so that S can draw into it.
2627 This makes S->next use XDrawString instead of XDrawImageString. */
2628 if (s->next && s->right_overhang && !s->for_overlaps)
2630 int width;
2631 struct glyph_string *next;
2633 for (width = 0, next = s->next;
2634 next && width < s->right_overhang;
2635 width += next->width, next = next->next)
2636 if (next->first_glyph->type != IMAGE_GLYPH)
2638 x_set_glyph_string_gc (next);
2639 x_set_glyph_string_clipping (next);
2640 if (next->first_glyph->type == STRETCH_GLYPH)
2641 x_draw_stretch_glyph_string (next);
2642 else
2643 x_draw_glyph_string_background (next, true);
2644 next->num_clips = 0;
2648 /* Set up S->gc, set clipping and draw S. */
2649 x_set_glyph_string_gc (s);
2651 /* Draw relief (if any) in advance for char/composition so that the
2652 glyph string can be drawn over it. */
2653 if (!s->for_overlaps
2654 && s->face->box != FACE_NO_BOX
2655 && (s->first_glyph->type == CHAR_GLYPH
2656 || s->first_glyph->type == COMPOSITE_GLYPH))
2659 x_set_glyph_string_clipping (s);
2660 x_draw_glyph_string_background (s, true);
2661 x_draw_glyph_string_box (s);
2662 x_set_glyph_string_clipping (s);
2663 relief_drawn_p = true;
2665 else if (!s->clip_head /* draw_glyphs didn't specify a clip mask. */
2666 && !s->clip_tail
2667 && ((s->prev && s->prev->hl != s->hl && s->left_overhang)
2668 || (s->next && s->next->hl != s->hl && s->right_overhang)))
2669 /* We must clip just this glyph. left_overhang part has already
2670 drawn when s->prev was drawn, and right_overhang part will be
2671 drawn later when s->next is drawn. */
2672 x_set_glyph_string_clipping_exactly (s, s);
2673 else
2674 x_set_glyph_string_clipping (s);
2676 switch (s->first_glyph->type)
2678 case IMAGE_GLYPH:
2679 x_draw_image_glyph_string (s);
2680 break;
2682 #ifdef HAVE_XWIDGETS
2683 case XWIDGET_GLYPH:
2684 //erase xwidget background
2685 //x_draw_glyph_string_background (s, 0);
2686 x_draw_xwidget_glyph_string (s);
2687 break;
2688 #endif
2689 case STRETCH_GLYPH:
2690 x_draw_stretch_glyph_string (s);
2691 break;
2693 case CHAR_GLYPH:
2694 if (s->for_overlaps)
2695 s->background_filled_p = true;
2696 else
2697 x_draw_glyph_string_background (s, false);
2698 x_draw_glyph_string_foreground (s);
2699 break;
2701 case COMPOSITE_GLYPH:
2702 if (s->for_overlaps || (s->cmp_from > 0
2703 && ! s->first_glyph->u.cmp.automatic))
2704 s->background_filled_p = true;
2705 else
2706 x_draw_glyph_string_background (s, true);
2707 x_draw_composite_glyph_string_foreground (s);
2708 break;
2710 case GLYPHLESS_GLYPH:
2711 if (s->for_overlaps)
2712 s->background_filled_p = true;
2713 else
2714 x_draw_glyph_string_background (s, true);
2715 x_draw_glyphless_glyph_string_foreground (s);
2716 break;
2718 default:
2719 emacs_abort ();
2722 if (!s->for_overlaps)
2724 /* Draw underline. */
2725 if (s->face->underline_p)
2727 if (s->face->underline_type == FACE_UNDER_WAVE)
2729 if (s->face->underline_defaulted_p)
2730 x_draw_underwave (s);
2731 else
2733 XGCValues xgcv;
2734 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2735 XSetForeground (s->display, s->gc, s->face->underline_color);
2736 x_draw_underwave (s);
2737 XSetForeground (s->display, s->gc, xgcv.foreground);
2740 else if (s->face->underline_type == FACE_UNDER_LINE)
2742 unsigned long thickness, position;
2743 int y;
2745 if (s->prev && s->prev->face->underline_p
2746 && s->prev->face->underline_type == FACE_UNDER_LINE)
2748 /* We use the same underline style as the previous one. */
2749 thickness = s->prev->underline_thickness;
2750 position = s->prev->underline_position;
2752 else
2754 /* Get the underline thickness. Default is 1 pixel. */
2755 if (s->font && s->font->underline_thickness > 0)
2756 thickness = s->font->underline_thickness;
2757 else
2758 thickness = 1;
2759 if (x_underline_at_descent_line)
2760 position = (s->height - thickness) - (s->ybase - s->y);
2761 else
2763 /* Get the underline position. This is the recommended
2764 vertical offset in pixels from the baseline to the top of
2765 the underline. This is a signed value according to the
2766 specs, and its default is
2768 ROUND ((maximum descent) / 2), with
2769 ROUND(x) = floor (x + 0.5) */
2771 if (x_use_underline_position_properties
2772 && s->font && s->font->underline_position >= 0)
2773 position = s->font->underline_position;
2774 else if (s->font)
2775 position = (s->font->descent + 1) / 2;
2776 else
2777 position = underline_minimum_offset;
2779 position = max (position, underline_minimum_offset);
2781 /* Check the sanity of thickness and position. We should
2782 avoid drawing underline out of the current line area. */
2783 if (s->y + s->height <= s->ybase + position)
2784 position = (s->height - 1) - (s->ybase - s->y);
2785 if (s->y + s->height < s->ybase + position + thickness)
2786 thickness = (s->y + s->height) - (s->ybase + position);
2787 s->underline_thickness = thickness;
2788 s->underline_position = position;
2789 y = s->ybase + position;
2790 if (s->face->underline_defaulted_p)
2791 XFillRectangle (s->display, s->window, s->gc,
2792 s->x, y, s->width, thickness);
2793 else
2795 XGCValues xgcv;
2796 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2797 XSetForeground (s->display, s->gc, s->face->underline_color);
2798 XFillRectangle (s->display, s->window, s->gc,
2799 s->x, y, s->width, thickness);
2800 XSetForeground (s->display, s->gc, xgcv.foreground);
2804 /* Draw overline. */
2805 if (s->face->overline_p)
2807 unsigned long dy = 0, h = 1;
2809 if (s->face->overline_color_defaulted_p)
2810 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2811 s->width, h);
2812 else
2814 XGCValues xgcv;
2815 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2816 XSetForeground (s->display, s->gc, s->face->overline_color);
2817 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2818 s->width, h);
2819 XSetForeground (s->display, s->gc, xgcv.foreground);
2823 /* Draw strike-through. */
2824 if (s->face->strike_through_p)
2826 unsigned long h = 1;
2827 unsigned long dy = (s->height - h) / 2;
2829 if (s->face->strike_through_color_defaulted_p)
2830 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2831 s->width, h);
2832 else
2834 XGCValues xgcv;
2835 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2836 XSetForeground (s->display, s->gc, s->face->strike_through_color);
2837 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2838 s->width, h);
2839 XSetForeground (s->display, s->gc, xgcv.foreground);
2843 /* Draw relief if not yet drawn. */
2844 if (!relief_drawn_p && s->face->box != FACE_NO_BOX)
2845 x_draw_glyph_string_box (s);
2847 if (s->prev)
2849 struct glyph_string *prev;
2851 for (prev = s->prev; prev; prev = prev->prev)
2852 if (prev->hl != s->hl
2853 && prev->x + prev->width + prev->right_overhang > s->x)
2855 /* As prev was drawn while clipped to its own area, we
2856 must draw the right_overhang part using s->hl now. */
2857 enum draw_glyphs_face save = prev->hl;
2859 prev->hl = s->hl;
2860 x_set_glyph_string_gc (prev);
2861 x_set_glyph_string_clipping_exactly (s, prev);
2862 if (prev->first_glyph->type == CHAR_GLYPH)
2863 x_draw_glyph_string_foreground (prev);
2864 else
2865 x_draw_composite_glyph_string_foreground (prev);
2866 XSetClipMask (prev->display, prev->gc, None);
2867 prev->hl = save;
2868 prev->num_clips = 0;
2872 if (s->next)
2874 struct glyph_string *next;
2876 for (next = s->next; next; next = next->next)
2877 if (next->hl != s->hl
2878 && next->x - next->left_overhang < s->x + s->width)
2880 /* As next will be drawn while clipped to its own area,
2881 we must draw the left_overhang part using s->hl now. */
2882 enum draw_glyphs_face save = next->hl;
2884 next->hl = s->hl;
2885 x_set_glyph_string_gc (next);
2886 x_set_glyph_string_clipping_exactly (s, next);
2887 if (next->first_glyph->type == CHAR_GLYPH)
2888 x_draw_glyph_string_foreground (next);
2889 else
2890 x_draw_composite_glyph_string_foreground (next);
2891 XSetClipMask (next->display, next->gc, None);
2892 next->hl = save;
2893 next->num_clips = 0;
2894 next->clip_head = s->next;
2899 /* Reset clipping. */
2900 XSetClipMask (s->display, s->gc, None);
2901 s->num_clips = 0;
2904 /* Shift display to make room for inserted glyphs. */
2906 static void
2907 x_shift_glyphs_for_insert (struct frame *f, int x, int y, int width, int height, int shift_by)
2909 XCopyArea (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), FRAME_X_WINDOW (f),
2910 f->output_data.x->normal_gc,
2911 x, y, width, height,
2912 x + shift_by, y);
2915 /* Delete N glyphs at the nominal cursor position. Not implemented
2916 for X frames. */
2918 static void
2919 x_delete_glyphs (struct frame *f, register int n)
2921 emacs_abort ();
2925 /* Like XClearArea, but check that WIDTH and HEIGHT are reasonable.
2926 If they are <= 0, this is probably an error. */
2928 void
2929 x_clear_area (Display *dpy, Window window, int x, int y, int width, int height)
2931 eassert (width > 0 && height > 0);
2932 XClearArea (dpy, window, x, y, width, height, False);
2936 /* Clear an entire frame. */
2938 static void
2939 x_clear_frame (struct frame *f)
2941 /* Clearing the frame will erase any cursor, so mark them all as no
2942 longer visible. */
2943 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2945 block_input ();
2947 XClearWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
2949 /* We have to clear the scroll bars. If we have changed colors or
2950 something like that, then they should be notified. */
2951 x_scroll_bar_clear (f);
2953 #if defined (USE_GTK) && defined (USE_TOOLKIT_SCROLL_BARS)
2954 /* Make sure scroll bars are redrawn. As they aren't redrawn by
2955 redisplay, do it here. */
2956 if (FRAME_GTK_WIDGET (f))
2957 gtk_widget_queue_draw (FRAME_GTK_WIDGET (f));
2958 #endif
2960 XFlush (FRAME_X_DISPLAY (f));
2962 unblock_input ();
2965 /* RIF: Show hourglass cursor on frame F. */
2967 static void
2968 x_show_hourglass (struct frame *f)
2970 Display *dpy = FRAME_X_DISPLAY (f);
2972 if (dpy)
2974 struct x_output *x = FRAME_X_OUTPUT (f);
2975 #ifdef USE_X_TOOLKIT
2976 if (x->widget)
2977 #else
2978 if (FRAME_OUTER_WINDOW (f))
2979 #endif
2981 x->hourglass_p = true;
2983 if (!x->hourglass_window)
2985 unsigned long mask = CWCursor;
2986 XSetWindowAttributes attrs;
2987 #ifdef USE_GTK
2988 Window parent = FRAME_X_WINDOW (f);
2989 #else
2990 Window parent = FRAME_OUTER_WINDOW (f);
2991 #endif
2992 attrs.cursor = x->hourglass_cursor;
2994 x->hourglass_window = XCreateWindow
2995 (dpy, parent, 0, 0, 32000, 32000, 0, 0,
2996 InputOnly, CopyFromParent, mask, &attrs);
2999 XMapRaised (dpy, x->hourglass_window);
3000 XFlush (dpy);
3005 /* RIF: Cancel hourglass cursor on frame F. */
3007 static void
3008 x_hide_hourglass (struct frame *f)
3010 struct x_output *x = FRAME_X_OUTPUT (f);
3012 /* Watch out for newly created frames. */
3013 if (x->hourglass_window)
3015 XUnmapWindow (FRAME_X_DISPLAY (f), x->hourglass_window);
3016 /* Sync here because XTread_socket looks at the
3017 hourglass_p flag that is reset to zero below. */
3018 XSync (FRAME_X_DISPLAY (f), False);
3019 x->hourglass_p = false;
3023 /* Invert the middle quarter of the frame for .15 sec. */
3025 static void
3026 XTflash (struct frame *f)
3028 block_input ();
3031 #ifdef USE_GTK
3032 /* Use Gdk routines to draw. This way, we won't draw over scroll bars
3033 when the scroll bars and the edit widget share the same X window. */
3034 GdkWindow *window = gtk_widget_get_window (FRAME_GTK_WIDGET (f));
3035 #ifdef HAVE_GTK3
3036 cairo_t *cr = gdk_cairo_create (window);
3037 cairo_set_source_rgb (cr, 1, 1, 1);
3038 cairo_set_operator (cr, CAIRO_OPERATOR_DIFFERENCE);
3039 #define XFillRectangle(d, win, gc, x, y, w, h) \
3040 do { \
3041 cairo_rectangle (cr, x, y, w, h); \
3042 cairo_fill (cr); \
3044 while (false)
3045 #else /* ! HAVE_GTK3 */
3046 GdkGCValues vals;
3047 GdkGC *gc;
3048 vals.foreground.pixel = (FRAME_FOREGROUND_PIXEL (f)
3049 ^ FRAME_BACKGROUND_PIXEL (f));
3050 vals.function = GDK_XOR;
3051 gc = gdk_gc_new_with_values (window,
3052 &vals, GDK_GC_FUNCTION | GDK_GC_FOREGROUND);
3053 #define XFillRectangle(d, win, gc, x, y, w, h) \
3054 gdk_draw_rectangle (window, gc, true, x, y, w, h)
3055 #endif /* ! HAVE_GTK3 */
3056 #else /* ! USE_GTK */
3057 GC gc;
3059 /* Create a GC that will use the GXxor function to flip foreground
3060 pixels into background pixels. */
3062 XGCValues values;
3064 values.function = GXxor;
3065 values.foreground = (FRAME_FOREGROUND_PIXEL (f)
3066 ^ FRAME_BACKGROUND_PIXEL (f));
3068 gc = XCreateGC (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3069 GCFunction | GCForeground, &values);
3071 #endif
3073 /* Get the height not including a menu bar widget. */
3074 int height = FRAME_PIXEL_HEIGHT (f);
3075 /* Height of each line to flash. */
3076 int flash_height = FRAME_LINE_HEIGHT (f);
3077 /* These will be the left and right margins of the rectangles. */
3078 int flash_left = FRAME_INTERNAL_BORDER_WIDTH (f);
3079 int flash_right = FRAME_PIXEL_WIDTH (f) - FRAME_INTERNAL_BORDER_WIDTH (f);
3080 int width = flash_right - flash_left;
3082 /* If window is tall, flash top and bottom line. */
3083 if (height > 3 * FRAME_LINE_HEIGHT (f))
3085 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3086 flash_left,
3087 (FRAME_INTERNAL_BORDER_WIDTH (f)
3088 + FRAME_TOP_MARGIN_HEIGHT (f)),
3089 width, flash_height);
3090 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3091 flash_left,
3092 (height - flash_height
3093 - FRAME_INTERNAL_BORDER_WIDTH (f)),
3094 width, flash_height);
3097 else
3098 /* If it is short, flash it all. */
3099 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3100 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
3101 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
3103 x_flush (f);
3106 struct timespec delay = make_timespec (0, 150 * 1000 * 1000);
3107 struct timespec wakeup = timespec_add (current_timespec (), delay);
3109 /* Keep waiting until past the time wakeup or any input gets
3110 available. */
3111 while (! detect_input_pending ())
3113 struct timespec current = current_timespec ();
3114 struct timespec timeout;
3116 /* Break if result would not be positive. */
3117 if (timespec_cmp (wakeup, current) <= 0)
3118 break;
3120 /* How long `select' should wait. */
3121 timeout = make_timespec (0, 10 * 1000 * 1000);
3123 /* Try to wait that long--but we might wake up sooner. */
3124 pselect (0, NULL, NULL, NULL, &timeout, NULL);
3128 /* If window is tall, flash top and bottom line. */
3129 if (height > 3 * FRAME_LINE_HEIGHT (f))
3131 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3132 flash_left,
3133 (FRAME_INTERNAL_BORDER_WIDTH (f)
3134 + FRAME_TOP_MARGIN_HEIGHT (f)),
3135 width, flash_height);
3136 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3137 flash_left,
3138 (height - flash_height
3139 - FRAME_INTERNAL_BORDER_WIDTH (f)),
3140 width, flash_height);
3142 else
3143 /* If it is short, flash it all. */
3144 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3145 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
3146 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
3148 #ifdef USE_GTK
3149 #ifdef HAVE_GTK3
3150 cairo_destroy (cr);
3151 #else
3152 g_object_unref (G_OBJECT (gc));
3153 #endif
3154 #undef XFillRectangle
3155 #else
3156 XFreeGC (FRAME_X_DISPLAY (f), gc);
3157 #endif
3158 x_flush (f);
3162 unblock_input ();
3166 static void
3167 XTtoggle_invisible_pointer (struct frame *f, bool invisible)
3169 block_input ();
3170 FRAME_DISPLAY_INFO (f)->toggle_visible_pointer (f, invisible);
3171 unblock_input ();
3175 /* Make audible bell. */
3177 static void
3178 XTring_bell (struct frame *f)
3180 if (FRAME_X_DISPLAY (f))
3182 if (visible_bell)
3183 XTflash (f);
3184 else
3186 block_input ();
3187 #ifdef HAVE_XKB
3188 XkbBell (FRAME_X_DISPLAY (f), None, 0, None);
3189 #else
3190 XBell (FRAME_X_DISPLAY (f), 0);
3191 #endif
3192 XFlush (FRAME_X_DISPLAY (f));
3193 unblock_input ();
3198 /***********************************************************************
3199 Line Dance
3200 ***********************************************************************/
3202 /* Perform an insert-lines or delete-lines operation, inserting N
3203 lines or deleting -N lines at vertical position VPOS. */
3205 static void
3206 x_ins_del_lines (struct frame *f, int vpos, int n)
3208 emacs_abort ();
3212 /* Scroll part of the display as described by RUN. */
3214 static void
3215 x_scroll_run (struct window *w, struct run *run)
3217 struct frame *f = XFRAME (w->frame);
3218 int x, y, width, height, from_y, to_y, bottom_y;
3220 /* Get frame-relative bounding box of the text display area of W,
3221 without mode lines. Include in this box the left and right
3222 fringe of W. */
3223 window_box (w, ANY_AREA, &x, &y, &width, &height);
3225 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
3226 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
3227 bottom_y = y + height;
3229 if (to_y < from_y)
3231 /* Scrolling up. Make sure we don't copy part of the mode
3232 line at the bottom. */
3233 if (from_y + run->height > bottom_y)
3234 height = bottom_y - from_y;
3235 else
3236 height = run->height;
3238 else
3240 /* Scrolling down. Make sure we don't copy over the mode line.
3241 at the bottom. */
3242 if (to_y + run->height > bottom_y)
3243 height = bottom_y - to_y;
3244 else
3245 height = run->height;
3248 block_input ();
3250 /* Cursor off. Will be switched on again in x_update_window_end. */
3251 x_clear_cursor (w);
3253 XCopyArea (FRAME_X_DISPLAY (f),
3254 FRAME_X_WINDOW (f), FRAME_X_WINDOW (f),
3255 f->output_data.x->normal_gc,
3256 x, from_y,
3257 width, height,
3258 x, to_y);
3260 unblock_input ();
3265 /***********************************************************************
3266 Exposure Events
3267 ***********************************************************************/
3270 static void
3271 frame_highlight (struct frame *f)
3273 /* We used to only do this if Vx_no_window_manager was non-nil, but
3274 the ICCCM (section 4.1.6) says that the window's border pixmap
3275 and border pixel are window attributes which are "private to the
3276 client", so we can always change it to whatever we want. */
3277 block_input ();
3278 /* I recently started to get errors in this XSetWindowBorder, depending on
3279 the window-manager in use, tho something more is at play since I've been
3280 using that same window-manager binary for ever. Let's not crash just
3281 because of this (bug#9310). */
3282 x_catch_errors (FRAME_X_DISPLAY (f));
3283 XSetWindowBorder (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3284 f->output_data.x->border_pixel);
3285 x_uncatch_errors ();
3286 unblock_input ();
3287 x_update_cursor (f, true);
3288 x_set_frame_alpha (f);
3291 static void
3292 frame_unhighlight (struct frame *f)
3294 /* We used to only do this if Vx_no_window_manager was non-nil, but
3295 the ICCCM (section 4.1.6) says that the window's border pixmap
3296 and border pixel are window attributes which are "private to the
3297 client", so we can always change it to whatever we want. */
3298 block_input ();
3299 /* Same as above for XSetWindowBorder (bug#9310). */
3300 x_catch_errors (FRAME_X_DISPLAY (f));
3301 XSetWindowBorderPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3302 f->output_data.x->border_tile);
3303 x_uncatch_errors ();
3304 unblock_input ();
3305 x_update_cursor (f, true);
3306 x_set_frame_alpha (f);
3309 /* The focus has changed. Update the frames as necessary to reflect
3310 the new situation. Note that we can't change the selected frame
3311 here, because the Lisp code we are interrupting might become confused.
3312 Each event gets marked with the frame in which it occurred, so the
3313 Lisp code can tell when the switch took place by examining the events. */
3315 static void
3316 x_new_focus_frame (struct x_display_info *dpyinfo, struct frame *frame)
3318 struct frame *old_focus = dpyinfo->x_focus_frame;
3320 if (frame != dpyinfo->x_focus_frame)
3322 /* Set this before calling other routines, so that they see
3323 the correct value of x_focus_frame. */
3324 dpyinfo->x_focus_frame = frame;
3326 if (old_focus && old_focus->auto_lower)
3327 x_lower_frame (old_focus);
3329 if (dpyinfo->x_focus_frame && dpyinfo->x_focus_frame->auto_raise)
3330 dpyinfo->x_pending_autoraise_frame = dpyinfo->x_focus_frame;
3331 else
3332 dpyinfo->x_pending_autoraise_frame = NULL;
3335 x_frame_rehighlight (dpyinfo);
3338 /* Handle FocusIn and FocusOut state changes for FRAME.
3339 If FRAME has focus and there exists more than one frame, puts
3340 a FOCUS_IN_EVENT into *BUFP. */
3342 static void
3343 x_focus_changed (int type, int state, struct x_display_info *dpyinfo, struct frame *frame, struct input_event *bufp)
3345 if (type == FocusIn)
3347 if (dpyinfo->x_focus_event_frame != frame)
3349 x_new_focus_frame (dpyinfo, frame);
3350 dpyinfo->x_focus_event_frame = frame;
3352 /* Don't stop displaying the initial startup message
3353 for a switch-frame event we don't need. */
3354 /* When run as a daemon, Vterminal_frame is always NIL. */
3355 bufp->arg = (((NILP (Vterminal_frame)
3356 || ! FRAME_X_P (XFRAME (Vterminal_frame))
3357 || EQ (Fdaemonp (), Qt))
3358 && CONSP (Vframe_list)
3359 && !NILP (XCDR (Vframe_list)))
3360 ? Qt : Qnil);
3361 bufp->kind = FOCUS_IN_EVENT;
3362 XSETFRAME (bufp->frame_or_window, frame);
3365 frame->output_data.x->focus_state |= state;
3367 #ifdef HAVE_X_I18N
3368 if (FRAME_XIC (frame))
3369 XSetICFocus (FRAME_XIC (frame));
3370 #endif
3372 else if (type == FocusOut)
3374 frame->output_data.x->focus_state &= ~state;
3376 if (dpyinfo->x_focus_event_frame == frame)
3378 dpyinfo->x_focus_event_frame = 0;
3379 x_new_focus_frame (dpyinfo, 0);
3381 bufp->kind = FOCUS_OUT_EVENT;
3382 XSETFRAME (bufp->frame_or_window, frame);
3385 #ifdef HAVE_X_I18N
3386 if (FRAME_XIC (frame))
3387 XUnsetICFocus (FRAME_XIC (frame));
3388 #endif
3389 if (frame->pointer_invisible)
3390 XTtoggle_invisible_pointer (frame, false);
3394 /* Return the Emacs frame-object corresponding to an X window.
3395 It could be the frame's main window or an icon window. */
3397 static struct frame *
3398 x_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
3400 Lisp_Object tail, frame;
3401 struct frame *f;
3403 if (wdesc == None)
3404 return NULL;
3406 FOR_EACH_FRAME (tail, frame)
3408 f = XFRAME (frame);
3409 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
3410 continue;
3411 if (f->output_data.x->hourglass_window == wdesc)
3412 return f;
3413 #ifdef USE_X_TOOLKIT
3414 if ((f->output_data.x->edit_widget
3415 && XtWindow (f->output_data.x->edit_widget) == wdesc)
3416 /* A tooltip frame? */
3417 || (!f->output_data.x->edit_widget
3418 && FRAME_X_WINDOW (f) == wdesc)
3419 || f->output_data.x->icon_desc == wdesc)
3420 return f;
3421 #else /* not USE_X_TOOLKIT */
3422 #ifdef USE_GTK
3423 if (f->output_data.x->edit_widget)
3425 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
3426 struct x_output *x = f->output_data.x;
3427 if (gwdesc != 0 && gwdesc == x->edit_widget)
3428 return f;
3430 #endif /* USE_GTK */
3431 if (FRAME_X_WINDOW (f) == wdesc
3432 || f->output_data.x->icon_desc == wdesc)
3433 return f;
3434 #endif /* not USE_X_TOOLKIT */
3436 return 0;
3439 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
3441 /* Like x_window_to_frame but also compares the window with the widget's
3442 windows. */
3444 static struct frame *
3445 x_any_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
3447 Lisp_Object tail, frame;
3448 struct frame *f, *found = NULL;
3449 struct x_output *x;
3451 if (wdesc == None)
3452 return NULL;
3454 FOR_EACH_FRAME (tail, frame)
3456 if (found)
3457 break;
3458 f = XFRAME (frame);
3459 if (FRAME_X_P (f) && FRAME_DISPLAY_INFO (f) == dpyinfo)
3461 /* This frame matches if the window is any of its widgets. */
3462 x = f->output_data.x;
3463 if (x->hourglass_window == wdesc)
3464 found = f;
3465 else if (x->widget)
3467 #ifdef USE_GTK
3468 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
3469 if (gwdesc != 0
3470 && gtk_widget_get_toplevel (gwdesc) == x->widget)
3471 found = f;
3472 #else
3473 if (wdesc == XtWindow (x->widget)
3474 || wdesc == XtWindow (x->column_widget)
3475 || wdesc == XtWindow (x->edit_widget))
3476 found = f;
3477 /* Match if the window is this frame's menubar. */
3478 else if (lw_window_is_in_menubar (wdesc, x->menubar_widget))
3479 found = f;
3480 #endif
3482 else if (FRAME_X_WINDOW (f) == wdesc)
3483 /* A tooltip frame. */
3484 found = f;
3488 return found;
3491 /* Likewise, but consider only the menu bar widget. */
3493 static struct frame *
3494 x_menubar_window_to_frame (struct x_display_info *dpyinfo,
3495 const XEvent *event)
3497 Window wdesc = event->xany.window;
3498 Lisp_Object tail, frame;
3499 struct frame *f;
3500 struct x_output *x;
3502 if (wdesc == None)
3503 return NULL;
3505 FOR_EACH_FRAME (tail, frame)
3507 f = XFRAME (frame);
3508 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
3509 continue;
3510 x = f->output_data.x;
3511 #ifdef USE_GTK
3512 if (x->menubar_widget && xg_event_is_for_menubar (f, event))
3513 return f;
3514 #else
3515 /* Match if the window is this frame's menubar. */
3516 if (x->menubar_widget
3517 && lw_window_is_in_menubar (wdesc, x->menubar_widget))
3518 return f;
3519 #endif
3521 return 0;
3524 /* Return the frame whose principal (outermost) window is WDESC.
3525 If WDESC is some other (smaller) window, we return 0. */
3527 struct frame *
3528 x_top_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
3530 Lisp_Object tail, frame;
3531 struct frame *f;
3532 struct x_output *x;
3534 if (wdesc == None)
3535 return NULL;
3537 FOR_EACH_FRAME (tail, frame)
3539 f = XFRAME (frame);
3540 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
3541 continue;
3542 x = f->output_data.x;
3544 if (x->widget)
3546 /* This frame matches if the window is its topmost widget. */
3547 #ifdef USE_GTK
3548 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
3549 if (gwdesc == x->widget)
3550 return f;
3551 #else
3552 if (wdesc == XtWindow (x->widget))
3553 return f;
3554 #endif
3556 else if (FRAME_X_WINDOW (f) == wdesc)
3557 /* Tooltip frame. */
3558 return f;
3560 return 0;
3563 #else /* !USE_X_TOOLKIT && !USE_GTK */
3565 #define x_any_window_to_frame(d, i) x_window_to_frame (d, i)
3566 #define x_top_window_to_frame(d, i) x_window_to_frame (d, i)
3568 #endif /* USE_X_TOOLKIT || USE_GTK */
3570 /* The focus may have changed. Figure out if it is a real focus change,
3571 by checking both FocusIn/Out and Enter/LeaveNotify events.
3573 Returns FOCUS_IN_EVENT event in *BUFP. */
3575 static void
3576 x_detect_focus_change (struct x_display_info *dpyinfo, struct frame *frame,
3577 const XEvent *event, struct input_event *bufp)
3579 if (!frame)
3580 return;
3582 switch (event->type)
3584 case EnterNotify:
3585 case LeaveNotify:
3587 struct frame *focus_frame = dpyinfo->x_focus_event_frame;
3588 int focus_state
3589 = focus_frame ? focus_frame->output_data.x->focus_state : 0;
3591 if (event->xcrossing.detail != NotifyInferior
3592 && event->xcrossing.focus
3593 && ! (focus_state & FOCUS_EXPLICIT))
3594 x_focus_changed ((event->type == EnterNotify ? FocusIn : FocusOut),
3595 FOCUS_IMPLICIT,
3596 dpyinfo, frame, bufp);
3598 break;
3600 case FocusIn:
3601 case FocusOut:
3602 x_focus_changed (event->type,
3603 (event->xfocus.detail == NotifyPointer ?
3604 FOCUS_IMPLICIT : FOCUS_EXPLICIT),
3605 dpyinfo, frame, bufp);
3606 break;
3608 case ClientMessage:
3609 if (event->xclient.message_type == dpyinfo->Xatom_XEMBED)
3611 enum xembed_message msg = event->xclient.data.l[1];
3612 x_focus_changed ((msg == XEMBED_FOCUS_IN ? FocusIn : FocusOut),
3613 FOCUS_EXPLICIT, dpyinfo, frame, bufp);
3615 break;
3620 #if !defined USE_X_TOOLKIT && !defined USE_GTK
3621 /* Handle an event saying the mouse has moved out of an Emacs frame. */
3623 void
3624 x_mouse_leave (struct x_display_info *dpyinfo)
3626 x_new_focus_frame (dpyinfo, dpyinfo->x_focus_event_frame);
3628 #endif
3630 /* The focus has changed, or we have redirected a frame's focus to
3631 another frame (this happens when a frame uses a surrogate
3632 mini-buffer frame). Shift the highlight as appropriate.
3634 The FRAME argument doesn't necessarily have anything to do with which
3635 frame is being highlighted or un-highlighted; we only use it to find
3636 the appropriate X display info. */
3638 static void
3639 XTframe_rehighlight (struct frame *frame)
3641 x_frame_rehighlight (FRAME_DISPLAY_INFO (frame));
3644 static void
3645 x_frame_rehighlight (struct x_display_info *dpyinfo)
3647 struct frame *old_highlight = dpyinfo->x_highlight_frame;
3649 if (dpyinfo->x_focus_frame)
3651 dpyinfo->x_highlight_frame
3652 = ((FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame)))
3653 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
3654 : dpyinfo->x_focus_frame);
3655 if (! FRAME_LIVE_P (dpyinfo->x_highlight_frame))
3657 fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
3658 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
3661 else
3662 dpyinfo->x_highlight_frame = 0;
3664 if (dpyinfo->x_highlight_frame != old_highlight)
3666 if (old_highlight)
3667 frame_unhighlight (old_highlight);
3668 if (dpyinfo->x_highlight_frame)
3669 frame_highlight (dpyinfo->x_highlight_frame);
3675 /* Keyboard processing - modifier keys, vendor-specific keysyms, etc. */
3677 /* Initialize mode_switch_bit and modifier_meaning. */
3678 static void
3679 x_find_modifier_meanings (struct x_display_info *dpyinfo)
3681 int min_code, max_code;
3682 KeySym *syms;
3683 int syms_per_code;
3684 XModifierKeymap *mods;
3686 dpyinfo->meta_mod_mask = 0;
3687 dpyinfo->shift_lock_mask = 0;
3688 dpyinfo->alt_mod_mask = 0;
3689 dpyinfo->super_mod_mask = 0;
3690 dpyinfo->hyper_mod_mask = 0;
3692 XDisplayKeycodes (dpyinfo->display, &min_code, &max_code);
3694 syms = XGetKeyboardMapping (dpyinfo->display,
3695 min_code, max_code - min_code + 1,
3696 &syms_per_code);
3697 mods = XGetModifierMapping (dpyinfo->display);
3699 /* Scan the modifier table to see which modifier bits the Meta and
3700 Alt keysyms are on. */
3702 int row, col; /* The row and column in the modifier table. */
3703 bool found_alt_or_meta;
3705 for (row = 3; row < 8; row++)
3707 found_alt_or_meta = false;
3708 for (col = 0; col < mods->max_keypermod; col++)
3710 KeyCode code = mods->modifiermap[(row * mods->max_keypermod) + col];
3712 /* Zeroes are used for filler. Skip them. */
3713 if (code == 0)
3714 continue;
3716 /* Are any of this keycode's keysyms a meta key? */
3718 int code_col;
3720 for (code_col = 0; code_col < syms_per_code; code_col++)
3722 int sym = syms[((code - min_code) * syms_per_code) + code_col];
3724 switch (sym)
3726 case XK_Meta_L:
3727 case XK_Meta_R:
3728 found_alt_or_meta = true;
3729 dpyinfo->meta_mod_mask |= (1 << row);
3730 break;
3732 case XK_Alt_L:
3733 case XK_Alt_R:
3734 found_alt_or_meta = true;
3735 dpyinfo->alt_mod_mask |= (1 << row);
3736 break;
3738 case XK_Hyper_L:
3739 case XK_Hyper_R:
3740 if (!found_alt_or_meta)
3741 dpyinfo->hyper_mod_mask |= (1 << row);
3742 code_col = syms_per_code;
3743 col = mods->max_keypermod;
3744 break;
3746 case XK_Super_L:
3747 case XK_Super_R:
3748 if (!found_alt_or_meta)
3749 dpyinfo->super_mod_mask |= (1 << row);
3750 code_col = syms_per_code;
3751 col = mods->max_keypermod;
3752 break;
3754 case XK_Shift_Lock:
3755 /* Ignore this if it's not on the lock modifier. */
3756 if (!found_alt_or_meta && ((1 << row) == LockMask))
3757 dpyinfo->shift_lock_mask = LockMask;
3758 code_col = syms_per_code;
3759 col = mods->max_keypermod;
3760 break;
3768 /* If we couldn't find any meta keys, accept any alt keys as meta keys. */
3769 if (! dpyinfo->meta_mod_mask)
3771 dpyinfo->meta_mod_mask = dpyinfo->alt_mod_mask;
3772 dpyinfo->alt_mod_mask = 0;
3775 /* If some keys are both alt and meta,
3776 make them just meta, not alt. */
3777 if (dpyinfo->alt_mod_mask & dpyinfo->meta_mod_mask)
3779 dpyinfo->alt_mod_mask &= ~dpyinfo->meta_mod_mask;
3782 XFree (syms);
3783 XFreeModifiermap (mods);
3786 /* Convert between the modifier bits X uses and the modifier bits
3787 Emacs uses. */
3790 x_x_to_emacs_modifiers (struct x_display_info *dpyinfo, int state)
3792 int mod_meta = meta_modifier;
3793 int mod_alt = alt_modifier;
3794 int mod_hyper = hyper_modifier;
3795 int mod_super = super_modifier;
3796 Lisp_Object tem;
3798 tem = Fget (Vx_alt_keysym, Qmodifier_value);
3799 if (INTEGERP (tem)) mod_alt = XINT (tem) & INT_MAX;
3800 tem = Fget (Vx_meta_keysym, Qmodifier_value);
3801 if (INTEGERP (tem)) mod_meta = XINT (tem) & INT_MAX;
3802 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
3803 if (INTEGERP (tem)) mod_hyper = XINT (tem) & INT_MAX;
3804 tem = Fget (Vx_super_keysym, Qmodifier_value);
3805 if (INTEGERP (tem)) mod_super = XINT (tem) & INT_MAX;
3807 return ( ((state & (ShiftMask | dpyinfo->shift_lock_mask)) ? shift_modifier : 0)
3808 | ((state & ControlMask) ? ctrl_modifier : 0)
3809 | ((state & dpyinfo->meta_mod_mask) ? mod_meta : 0)
3810 | ((state & dpyinfo->alt_mod_mask) ? mod_alt : 0)
3811 | ((state & dpyinfo->super_mod_mask) ? mod_super : 0)
3812 | ((state & dpyinfo->hyper_mod_mask) ? mod_hyper : 0));
3815 static int
3816 x_emacs_to_x_modifiers (struct x_display_info *dpyinfo, EMACS_INT state)
3818 EMACS_INT mod_meta = meta_modifier;
3819 EMACS_INT mod_alt = alt_modifier;
3820 EMACS_INT mod_hyper = hyper_modifier;
3821 EMACS_INT mod_super = super_modifier;
3823 Lisp_Object tem;
3825 tem = Fget (Vx_alt_keysym, Qmodifier_value);
3826 if (INTEGERP (tem)) mod_alt = XINT (tem);
3827 tem = Fget (Vx_meta_keysym, Qmodifier_value);
3828 if (INTEGERP (tem)) mod_meta = XINT (tem);
3829 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
3830 if (INTEGERP (tem)) mod_hyper = XINT (tem);
3831 tem = Fget (Vx_super_keysym, Qmodifier_value);
3832 if (INTEGERP (tem)) mod_super = XINT (tem);
3835 return ( ((state & mod_alt) ? dpyinfo->alt_mod_mask : 0)
3836 | ((state & mod_super) ? dpyinfo->super_mod_mask : 0)
3837 | ((state & mod_hyper) ? dpyinfo->hyper_mod_mask : 0)
3838 | ((state & shift_modifier) ? ShiftMask : 0)
3839 | ((state & ctrl_modifier) ? ControlMask : 0)
3840 | ((state & mod_meta) ? dpyinfo->meta_mod_mask : 0));
3843 /* Convert a keysym to its name. */
3845 char *
3846 x_get_keysym_name (int keysym)
3848 char *value;
3850 block_input ();
3851 value = XKeysymToString (keysym);
3852 unblock_input ();
3854 return value;
3857 /* Mouse clicks and mouse movement. Rah.
3859 Formerly, we used PointerMotionHintMask (in standard_event_mask)
3860 so that we would have to call XQueryPointer after each MotionNotify
3861 event to ask for another such event. However, this made mouse tracking
3862 slow, and there was a bug that made it eventually stop.
3864 Simply asking for MotionNotify all the time seems to work better.
3866 In order to avoid asking for motion events and then throwing most
3867 of them away or busy-polling the server for mouse positions, we ask
3868 the server for pointer motion hints. This means that we get only
3869 one event per group of mouse movements. "Groups" are delimited by
3870 other kinds of events (focus changes and button clicks, for
3871 example), or by XQueryPointer calls; when one of these happens, we
3872 get another MotionNotify event the next time the mouse moves. This
3873 is at least as efficient as getting motion events when mouse
3874 tracking is on, and I suspect only negligibly worse when tracking
3875 is off. */
3877 /* Prepare a mouse-event in *RESULT for placement in the input queue.
3879 If the event is a button press, then note that we have grabbed
3880 the mouse. */
3882 static Lisp_Object
3883 construct_mouse_click (struct input_event *result,
3884 const XButtonEvent *event,
3885 struct frame *f)
3887 /* Make the event type NO_EVENT; we'll change that when we decide
3888 otherwise. */
3889 result->kind = MOUSE_CLICK_EVENT;
3890 result->code = event->button - Button1;
3891 result->timestamp = event->time;
3892 result->modifiers = (x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO (f),
3893 event->state)
3894 | (event->type == ButtonRelease
3895 ? up_modifier
3896 : down_modifier));
3898 XSETINT (result->x, event->x);
3899 XSETINT (result->y, event->y);
3900 XSETFRAME (result->frame_or_window, f);
3901 result->arg = Qnil;
3902 return Qnil;
3905 /* Function to report a mouse movement to the mainstream Emacs code.
3906 The input handler calls this.
3908 We have received a mouse movement event, which is given in *event.
3909 If the mouse is over a different glyph than it was last time, tell
3910 the mainstream emacs code by setting mouse_moved. If not, ask for
3911 another motion event, so we can check again the next time it moves. */
3913 static bool
3914 note_mouse_movement (struct frame *frame, const XMotionEvent *event)
3916 XRectangle *r;
3917 struct x_display_info *dpyinfo;
3919 if (!FRAME_X_OUTPUT (frame))
3920 return false;
3922 dpyinfo = FRAME_DISPLAY_INFO (frame);
3923 dpyinfo->last_mouse_movement_time = event->time;
3924 dpyinfo->last_mouse_motion_frame = frame;
3925 dpyinfo->last_mouse_motion_x = event->x;
3926 dpyinfo->last_mouse_motion_y = event->y;
3928 if (event->window != FRAME_X_WINDOW (frame))
3930 frame->mouse_moved = true;
3931 dpyinfo->last_mouse_scroll_bar = NULL;
3932 note_mouse_highlight (frame, -1, -1);
3933 dpyinfo->last_mouse_glyph_frame = NULL;
3934 return true;
3938 /* Has the mouse moved off the glyph it was on at the last sighting? */
3939 r = &dpyinfo->last_mouse_glyph;
3940 if (frame != dpyinfo->last_mouse_glyph_frame
3941 || event->x < r->x || event->x >= r->x + r->width
3942 || event->y < r->y || event->y >= r->y + r->height)
3944 frame->mouse_moved = true;
3945 dpyinfo->last_mouse_scroll_bar = NULL;
3946 note_mouse_highlight (frame, event->x, event->y);
3947 /* Remember which glyph we're now on. */
3948 remember_mouse_glyph (frame, event->x, event->y, r);
3949 dpyinfo->last_mouse_glyph_frame = frame;
3950 return true;
3953 return false;
3956 /* Return the current position of the mouse.
3957 *FP should be a frame which indicates which display to ask about.
3959 If the mouse movement started in a scroll bar, set *FP, *BAR_WINDOW,
3960 and *PART to the frame, window, and scroll bar part that the mouse
3961 is over. Set *X and *Y to the portion and whole of the mouse's
3962 position on the scroll bar.
3964 If the mouse movement started elsewhere, set *FP to the frame the
3965 mouse is on, *BAR_WINDOW to nil, and *X and *Y to the character cell
3966 the mouse is over.
3968 Set *TIMESTAMP to the server time-stamp for the time at which the mouse
3969 was at this position.
3971 Don't store anything if we don't have a valid set of values to report.
3973 This clears the mouse_moved flag, so we can wait for the next mouse
3974 movement. */
3976 static void
3977 XTmouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
3978 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
3979 Time *timestamp)
3981 struct frame *f1;
3982 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (*fp);
3984 block_input ();
3986 if (dpyinfo->last_mouse_scroll_bar && insist == 0)
3988 struct scroll_bar *bar = dpyinfo->last_mouse_scroll_bar;
3990 if (bar->horizontal)
3991 x_horizontal_scroll_bar_report_motion (fp, bar_window, part, x, y, timestamp);
3992 else
3993 x_scroll_bar_report_motion (fp, bar_window, part, x, y, timestamp);
3995 else
3997 Window root;
3998 int root_x, root_y;
4000 Window dummy_window;
4001 int dummy;
4003 Lisp_Object frame, tail;
4005 /* Clear the mouse-moved flag for every frame on this display. */
4006 FOR_EACH_FRAME (tail, frame)
4007 if (FRAME_X_P (XFRAME (frame))
4008 && FRAME_X_DISPLAY (XFRAME (frame)) == FRAME_X_DISPLAY (*fp))
4009 XFRAME (frame)->mouse_moved = false;
4011 dpyinfo->last_mouse_scroll_bar = NULL;
4013 /* Figure out which root window we're on. */
4014 XQueryPointer (FRAME_X_DISPLAY (*fp),
4015 DefaultRootWindow (FRAME_X_DISPLAY (*fp)),
4017 /* The root window which contains the pointer. */
4018 &root,
4020 /* Trash which we can't trust if the pointer is on
4021 a different screen. */
4022 &dummy_window,
4024 /* The position on that root window. */
4025 &root_x, &root_y,
4027 /* More trash we can't trust. */
4028 &dummy, &dummy,
4030 /* Modifier keys and pointer buttons, about which
4031 we don't care. */
4032 (unsigned int *) &dummy);
4034 /* Now we have a position on the root; find the innermost window
4035 containing the pointer. */
4037 Window win, child;
4038 int win_x, win_y;
4039 int parent_x = 0, parent_y = 0;
4041 win = root;
4043 /* XTranslateCoordinates can get errors if the window
4044 structure is changing at the same time this function
4045 is running. So at least we must not crash from them. */
4047 x_catch_errors (FRAME_X_DISPLAY (*fp));
4049 if (x_mouse_grabbed (dpyinfo))
4051 /* If mouse was grabbed on a frame, give coords for that frame
4052 even if the mouse is now outside it. */
4053 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
4055 /* From-window. */
4056 root,
4058 /* To-window. */
4059 FRAME_X_WINDOW (dpyinfo->last_mouse_frame),
4061 /* From-position, to-position. */
4062 root_x, root_y, &win_x, &win_y,
4064 /* Child of win. */
4065 &child);
4066 f1 = dpyinfo->last_mouse_frame;
4068 else
4070 while (true)
4072 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
4074 /* From-window, to-window. */
4075 root, win,
4077 /* From-position, to-position. */
4078 root_x, root_y, &win_x, &win_y,
4080 /* Child of win. */
4081 &child);
4083 if (child == None || child == win)
4084 break;
4085 #ifdef USE_GTK
4086 /* We don't wan't to know the innermost window. We
4087 want the edit window. For non-Gtk+ the innermost
4088 window is the edit window. For Gtk+ it might not
4089 be. It might be the tool bar for example. */
4090 if (x_window_to_frame (dpyinfo, win))
4091 break;
4092 #endif
4093 win = child;
4094 parent_x = win_x;
4095 parent_y = win_y;
4098 /* Now we know that:
4099 win is the innermost window containing the pointer
4100 (XTC says it has no child containing the pointer),
4101 win_x and win_y are the pointer's position in it
4102 (XTC did this the last time through), and
4103 parent_x and parent_y are the pointer's position in win's parent.
4104 (They are what win_x and win_y were when win was child.
4105 If win is the root window, it has no parent, and
4106 parent_{x,y} are invalid, but that's okay, because we'll
4107 never use them in that case.) */
4109 #ifdef USE_GTK
4110 /* We don't wan't to know the innermost window. We
4111 want the edit window. */
4112 f1 = x_window_to_frame (dpyinfo, win);
4113 #else
4114 /* Is win one of our frames? */
4115 f1 = x_any_window_to_frame (dpyinfo, win);
4116 #endif
4118 #ifdef USE_X_TOOLKIT
4119 /* If we end up with the menu bar window, say it's not
4120 on the frame. */
4121 if (f1 != NULL
4122 && f1->output_data.x->menubar_widget
4123 && win == XtWindow (f1->output_data.x->menubar_widget))
4124 f1 = NULL;
4125 #endif /* USE_X_TOOLKIT */
4128 if (x_had_errors_p (FRAME_X_DISPLAY (*fp)))
4129 f1 = 0;
4131 x_uncatch_errors ();
4133 /* If not, is it one of our scroll bars? */
4134 if (! f1)
4136 struct scroll_bar *bar;
4138 bar = x_window_to_scroll_bar (FRAME_X_DISPLAY (*fp), win, 2);
4140 if (bar)
4142 f1 = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
4143 win_x = parent_x;
4144 win_y = parent_y;
4148 if (f1 == 0 && insist > 0)
4149 f1 = SELECTED_FRAME ();
4151 if (f1)
4153 /* Ok, we found a frame. Store all the values.
4154 last_mouse_glyph is a rectangle used to reduce the
4155 generation of mouse events. To not miss any motion
4156 events, we must divide the frame into rectangles of the
4157 size of the smallest character that could be displayed
4158 on it, i.e. into the same rectangles that matrices on
4159 the frame are divided into. */
4161 /* FIXME: what if F1 is not an X frame? */
4162 dpyinfo = FRAME_DISPLAY_INFO (f1);
4163 remember_mouse_glyph (f1, win_x, win_y, &dpyinfo->last_mouse_glyph);
4164 dpyinfo->last_mouse_glyph_frame = f1;
4166 *bar_window = Qnil;
4167 *part = scroll_bar_above_handle;
4168 *fp = f1;
4169 XSETINT (*x, win_x);
4170 XSETINT (*y, win_y);
4171 *timestamp = dpyinfo->last_mouse_movement_time;
4176 unblock_input ();
4181 /***********************************************************************
4182 Scroll bars
4183 ***********************************************************************/
4185 /* Scroll bar support. */
4187 /* Given an X window ID and a DISPLAY, find the struct scroll_bar which
4188 manages it.
4189 This can be called in GC, so we have to make sure to strip off mark
4190 bits. */
4192 static struct scroll_bar *
4193 x_window_to_scroll_bar (Display *display, Window window_id, int type)
4195 Lisp_Object tail, frame;
4197 #if defined (USE_GTK) && defined (USE_TOOLKIT_SCROLL_BARS)
4198 window_id = (Window) xg_get_scroll_id_for_window (display, window_id);
4199 #endif /* USE_GTK && USE_TOOLKIT_SCROLL_BARS */
4201 FOR_EACH_FRAME (tail, frame)
4203 Lisp_Object bar, condemned;
4205 if (! FRAME_X_P (XFRAME (frame)))
4206 continue;
4208 /* Scan this frame's scroll bar list for a scroll bar with the
4209 right window ID. */
4210 condemned = FRAME_CONDEMNED_SCROLL_BARS (XFRAME (frame));
4211 for (bar = FRAME_SCROLL_BARS (XFRAME (frame));
4212 /* This trick allows us to search both the ordinary and
4213 condemned scroll bar lists with one loop. */
4214 ! NILP (bar) || (bar = condemned,
4215 condemned = Qnil,
4216 ! NILP (bar));
4217 bar = XSCROLL_BAR (bar)->next)
4218 if (XSCROLL_BAR (bar)->x_window == window_id
4219 && FRAME_X_DISPLAY (XFRAME (frame)) == display
4220 && (type = 2
4221 || (type == 1 && XSCROLL_BAR (bar)->horizontal)
4222 || (type == 0 && !XSCROLL_BAR (bar)->horizontal)))
4223 return XSCROLL_BAR (bar);
4226 return NULL;
4230 #if defined USE_LUCID
4232 /* Return the Lucid menu bar WINDOW is part of. Return null
4233 if WINDOW is not part of a menu bar. */
4235 static Widget
4236 x_window_to_menu_bar (Window window)
4238 Lisp_Object tail, frame;
4240 FOR_EACH_FRAME (tail, frame)
4241 if (FRAME_X_P (XFRAME (frame)))
4243 Widget menu_bar = XFRAME (frame)->output_data.x->menubar_widget;
4245 if (menu_bar && xlwmenu_window_p (menu_bar, window))
4246 return menu_bar;
4248 return NULL;
4251 #endif /* USE_LUCID */
4254 /************************************************************************
4255 Toolkit scroll bars
4256 ************************************************************************/
4258 #ifdef USE_TOOLKIT_SCROLL_BARS
4260 static void x_send_scroll_bar_event (Lisp_Object, enum scroll_bar_part,
4261 int, int, bool);
4263 /* Lisp window being scrolled. Set when starting to interact with
4264 a toolkit scroll bar, reset to nil when ending the interaction. */
4266 static Lisp_Object window_being_scrolled;
4268 /* Whether this is an Xaw with arrow-scrollbars. This should imply
4269 that movements of 1/20 of the screen size are mapped to up/down. */
4271 #ifndef USE_GTK
4272 /* Id of action hook installed for scroll bars. */
4274 static XtActionHookId action_hook_id;
4275 static XtActionHookId horizontal_action_hook_id;
4277 static Boolean xaw3d_arrow_scroll;
4279 /* Whether the drag scrolling maintains the mouse at the top of the
4280 thumb. If not, resizing the thumb needs to be done more carefully
4281 to avoid jerkiness. */
4283 static Boolean xaw3d_pick_top;
4285 /* Action hook installed via XtAppAddActionHook when toolkit scroll
4286 bars are used.. The hook is responsible for detecting when
4287 the user ends an interaction with the scroll bar, and generates
4288 a `end-scroll' SCROLL_BAR_CLICK_EVENT' event if so. */
4290 static void
4291 xt_action_hook (Widget widget, XtPointer client_data, String action_name,
4292 XEvent *event, String *params, Cardinal *num_params)
4294 bool scroll_bar_p;
4295 const char *end_action;
4297 #ifdef USE_MOTIF
4298 scroll_bar_p = XmIsScrollBar (widget);
4299 end_action = "Release";
4300 #else /* !USE_MOTIF i.e. use Xaw */
4301 scroll_bar_p = XtIsSubclass (widget, scrollbarWidgetClass);
4302 end_action = "EndScroll";
4303 #endif /* USE_MOTIF */
4305 if (scroll_bar_p
4306 && strcmp (action_name, end_action) == 0
4307 && WINDOWP (window_being_scrolled))
4309 struct window *w;
4310 struct scroll_bar *bar;
4312 x_send_scroll_bar_event (window_being_scrolled,
4313 scroll_bar_end_scroll, 0, 0, false);
4314 w = XWINDOW (window_being_scrolled);
4315 bar = XSCROLL_BAR (w->vertical_scroll_bar);
4317 if (bar->dragging != -1)
4319 bar->dragging = -1;
4320 /* The thumb size is incorrect while dragging: fix it. */
4321 set_vertical_scroll_bar (w);
4323 window_being_scrolled = Qnil;
4324 #if defined (USE_LUCID)
4325 bar->last_seen_part = scroll_bar_nowhere;
4326 #endif
4327 /* Xt timeouts no longer needed. */
4328 toolkit_scroll_bar_interaction = false;
4333 static void
4334 xt_horizontal_action_hook (Widget widget, XtPointer client_data, String action_name,
4335 XEvent *event, String *params, Cardinal *num_params)
4337 bool scroll_bar_p;
4338 const char *end_action;
4340 #ifdef USE_MOTIF
4341 scroll_bar_p = XmIsScrollBar (widget);
4342 end_action = "Release";
4343 #else /* !USE_MOTIF i.e. use Xaw */
4344 scroll_bar_p = XtIsSubclass (widget, scrollbarWidgetClass);
4345 end_action = "EndScroll";
4346 #endif /* USE_MOTIF */
4348 if (scroll_bar_p
4349 && strcmp (action_name, end_action) == 0
4350 && WINDOWP (window_being_scrolled))
4352 struct window *w;
4353 struct scroll_bar *bar;
4355 x_send_scroll_bar_event (window_being_scrolled,
4356 scroll_bar_end_scroll, 0, 0, true);
4357 w = XWINDOW (window_being_scrolled);
4358 bar = XSCROLL_BAR (w->horizontal_scroll_bar);
4360 if (bar->dragging != -1)
4362 bar->dragging = -1;
4363 /* The thumb size is incorrect while dragging: fix it. */
4364 set_horizontal_scroll_bar (w);
4366 window_being_scrolled = Qnil;
4367 #if defined (USE_LUCID)
4368 bar->last_seen_part = scroll_bar_nowhere;
4369 #endif
4370 /* Xt timeouts no longer needed. */
4371 toolkit_scroll_bar_interaction = false;
4374 #endif /* not USE_GTK */
4376 /* Send a client message with message type Xatom_Scrollbar for a
4377 scroll action to the frame of WINDOW. PART is a value identifying
4378 the part of the scroll bar that was clicked on. PORTION is the
4379 amount to scroll of a whole of WHOLE. */
4381 static void
4382 x_send_scroll_bar_event (Lisp_Object window, enum scroll_bar_part part,
4383 int portion, int whole, bool horizontal)
4385 XEvent event;
4386 XClientMessageEvent *ev = &event.xclient;
4387 struct window *w = XWINDOW (window);
4388 struct frame *f = XFRAME (w->frame);
4389 intptr_t iw = (intptr_t) w;
4390 enum { BITS_PER_INTPTR = CHAR_BIT * sizeof iw };
4391 verify (BITS_PER_INTPTR <= 64);
4392 int sign_shift = BITS_PER_INTPTR - 32;
4394 block_input ();
4396 /* Construct a ClientMessage event to send to the frame. */
4397 ev->type = ClientMessage;
4398 ev->message_type = (horizontal
4399 ? FRAME_DISPLAY_INFO (f)->Xatom_Horizontal_Scrollbar
4400 : FRAME_DISPLAY_INFO (f)->Xatom_Scrollbar);
4401 ev->display = FRAME_X_DISPLAY (f);
4402 ev->window = FRAME_X_WINDOW (f);
4403 ev->format = 32;
4405 /* A 32-bit X client on a 64-bit X server can pass a window pointer
4406 as-is. A 64-bit client on a 32-bit X server is in trouble
4407 because a pointer does not fit and would be truncated while
4408 passing through the server. So use two slots and hope that X12
4409 will resolve such issues someday. */
4410 ev->data.l[0] = iw >> 31 >> 1;
4411 ev->data.l[1] = sign_shift <= 0 ? iw : iw << sign_shift >> sign_shift;
4412 ev->data.l[2] = part;
4413 ev->data.l[3] = portion;
4414 ev->data.l[4] = whole;
4416 /* Make Xt timeouts work while the scroll bar is active. */
4417 #ifdef USE_X_TOOLKIT
4418 toolkit_scroll_bar_interaction = true;
4419 x_activate_timeout_atimer ();
4420 #endif
4422 /* Setting the event mask to zero means that the message will
4423 be sent to the client that created the window, and if that
4424 window no longer exists, no event will be sent. */
4425 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), False, 0, &event);
4426 unblock_input ();
4430 /* Transform a scroll bar ClientMessage EVENT to an Emacs input event
4431 in *IEVENT. */
4433 static void
4434 x_scroll_bar_to_input_event (const XEvent *event,
4435 struct input_event *ievent)
4437 const XClientMessageEvent *ev = &event->xclient;
4438 Lisp_Object window;
4439 struct window *w;
4441 /* See the comment in the function above. */
4442 intptr_t iw0 = ev->data.l[0];
4443 intptr_t iw1 = ev->data.l[1];
4444 intptr_t iw = (iw0 << 31 << 1) + (iw1 & 0xffffffffu);
4445 w = (struct window *) iw;
4447 XSETWINDOW (window, w);
4449 ievent->kind = SCROLL_BAR_CLICK_EVENT;
4450 ievent->frame_or_window = window;
4451 ievent->arg = Qnil;
4452 #ifdef USE_GTK
4453 ievent->timestamp = CurrentTime;
4454 #else
4455 ievent->timestamp =
4456 XtLastTimestampProcessed (FRAME_X_DISPLAY (XFRAME (w->frame)));
4457 #endif
4458 ievent->code = 0;
4459 ievent->part = ev->data.l[2];
4460 ievent->x = make_number (ev->data.l[3]);
4461 ievent->y = make_number (ev->data.l[4]);
4462 ievent->modifiers = 0;
4465 /* Transform a horizontal scroll bar ClientMessage EVENT to an Emacs
4466 input event in *IEVENT. */
4468 static void
4469 x_horizontal_scroll_bar_to_input_event (const XEvent *event,
4470 struct input_event *ievent)
4472 const XClientMessageEvent *ev = &event->xclient;
4473 Lisp_Object window;
4474 struct window *w;
4476 /* See the comment in the function above. */
4477 intptr_t iw0 = ev->data.l[0];
4478 intptr_t iw1 = ev->data.l[1];
4479 intptr_t iw = (iw0 << 31 << 1) + (iw1 & 0xffffffffu);
4480 w = (struct window *) iw;
4482 XSETWINDOW (window, w);
4484 ievent->kind = HORIZONTAL_SCROLL_BAR_CLICK_EVENT;
4485 ievent->frame_or_window = window;
4486 ievent->arg = Qnil;
4487 #ifdef USE_GTK
4488 ievent->timestamp = CurrentTime;
4489 #else
4490 ievent->timestamp =
4491 XtLastTimestampProcessed (FRAME_X_DISPLAY (XFRAME (w->frame)));
4492 #endif
4493 ievent->code = 0;
4494 ievent->part = ev->data.l[2];
4495 ievent->x = make_number (ev->data.l[3]);
4496 ievent->y = make_number (ev->data.l[4]);
4497 ievent->modifiers = 0;
4501 #ifdef USE_MOTIF
4503 /* Minimum and maximum values used for Motif scroll bars. */
4505 #define XM_SB_MAX 10000000
4507 /* Scroll bar callback for Motif scroll bars. WIDGET is the scroll
4508 bar widget. CLIENT_DATA is a pointer to the scroll_bar structure.
4509 CALL_DATA is a pointer to a XmScrollBarCallbackStruct. */
4511 static void
4512 xm_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
4514 struct scroll_bar *bar = client_data;
4515 XmScrollBarCallbackStruct *cs = call_data;
4516 enum scroll_bar_part part = scroll_bar_nowhere;
4517 bool horizontal = bar->horizontal;
4518 int whole = 0, portion = 0;
4520 switch (cs->reason)
4522 case XmCR_DECREMENT:
4523 bar->dragging = -1;
4524 part = horizontal ? scroll_bar_left_arrow : scroll_bar_up_arrow;
4525 break;
4527 case XmCR_INCREMENT:
4528 bar->dragging = -1;
4529 part = horizontal ? scroll_bar_right_arrow : scroll_bar_down_arrow;
4530 break;
4532 case XmCR_PAGE_DECREMENT:
4533 bar->dragging = -1;
4534 part = horizontal ? scroll_bar_before_handle : scroll_bar_above_handle;
4535 break;
4537 case XmCR_PAGE_INCREMENT:
4538 bar->dragging = -1;
4539 part = horizontal ? scroll_bar_after_handle : scroll_bar_below_handle;
4540 break;
4542 case XmCR_TO_TOP:
4543 bar->dragging = -1;
4544 part = horizontal ? scroll_bar_to_leftmost : scroll_bar_to_top;
4545 break;
4547 case XmCR_TO_BOTTOM:
4548 bar->dragging = -1;
4549 part = horizontal ? scroll_bar_to_rightmost : scroll_bar_to_bottom;
4550 break;
4552 case XmCR_DRAG:
4554 int slider_size;
4556 block_input ();
4557 XtVaGetValues (widget, XmNsliderSize, &slider_size, NULL);
4558 unblock_input ();
4560 if (horizontal)
4562 portion = bar->whole * ((float)cs->value / XM_SB_MAX);
4563 whole = bar->whole * ((float)(XM_SB_MAX - slider_size) / XM_SB_MAX);
4564 portion = min (portion, whole);
4565 part = scroll_bar_horizontal_handle;
4567 else
4569 whole = XM_SB_MAX - slider_size;
4570 portion = min (cs->value, whole);
4571 part = scroll_bar_handle;
4574 bar->dragging = cs->value;
4576 break;
4578 case XmCR_VALUE_CHANGED:
4579 break;
4582 if (part != scroll_bar_nowhere)
4584 window_being_scrolled = bar->window;
4585 x_send_scroll_bar_event (bar->window, part, portion, whole,
4586 bar->horizontal);
4590 #elif defined USE_GTK
4592 /* Scroll bar callback for GTK scroll bars. WIDGET is the scroll
4593 bar widget. DATA is a pointer to the scroll_bar structure. */
4595 static gboolean
4596 xg_scroll_callback (GtkRange *range,
4597 GtkScrollType scroll,
4598 gdouble value,
4599 gpointer user_data)
4601 int whole = 0, portion = 0;
4602 struct scroll_bar *bar = user_data;
4603 enum scroll_bar_part part = scroll_bar_nowhere;
4604 GtkAdjustment *adj = GTK_ADJUSTMENT (gtk_range_get_adjustment (range));
4605 struct frame *f = g_object_get_data (G_OBJECT (range), XG_FRAME_DATA);
4607 if (xg_ignore_gtk_scrollbar) return false;
4609 switch (scroll)
4611 case GTK_SCROLL_JUMP:
4612 /* Buttons 1 2 or 3 must be grabbed. */
4613 if (FRAME_DISPLAY_INFO (f)->grabbed != 0
4614 && FRAME_DISPLAY_INFO (f)->grabbed < (1 << 4))
4616 if (bar->horizontal)
4618 part = scroll_bar_horizontal_handle;
4619 whole = (int)(gtk_adjustment_get_upper (adj) -
4620 gtk_adjustment_get_page_size (adj));
4621 portion = min ((int)value, whole);
4622 bar->dragging = portion;
4624 else
4626 part = scroll_bar_handle;
4627 whole = gtk_adjustment_get_upper (adj) -
4628 gtk_adjustment_get_page_size (adj);
4629 portion = min ((int)value, whole);
4630 bar->dragging = portion;
4633 break;
4634 case GTK_SCROLL_STEP_BACKWARD:
4635 part = (bar->horizontal
4636 ? scroll_bar_left_arrow : scroll_bar_up_arrow);
4637 bar->dragging = -1;
4638 break;
4639 case GTK_SCROLL_STEP_FORWARD:
4640 part = (bar->horizontal
4641 ? scroll_bar_right_arrow : scroll_bar_down_arrow);
4642 bar->dragging = -1;
4643 break;
4644 case GTK_SCROLL_PAGE_BACKWARD:
4645 part = (bar->horizontal
4646 ? scroll_bar_before_handle : scroll_bar_above_handle);
4647 bar->dragging = -1;
4648 break;
4649 case GTK_SCROLL_PAGE_FORWARD:
4650 part = (bar->horizontal
4651 ? scroll_bar_after_handle : scroll_bar_below_handle);
4652 bar->dragging = -1;
4653 break;
4656 if (part != scroll_bar_nowhere)
4658 window_being_scrolled = bar->window;
4659 x_send_scroll_bar_event (bar->window, part, portion, whole,
4660 bar->horizontal);
4663 return false;
4666 /* Callback for button release. Sets dragging to -1 when dragging is done. */
4668 static gboolean
4669 xg_end_scroll_callback (GtkWidget *widget,
4670 GdkEventButton *event,
4671 gpointer user_data)
4673 struct scroll_bar *bar = user_data;
4674 bar->dragging = -1;
4675 if (WINDOWP (window_being_scrolled))
4677 x_send_scroll_bar_event (window_being_scrolled,
4678 scroll_bar_end_scroll, 0, 0, bar->horizontal);
4679 window_being_scrolled = Qnil;
4682 return false;
4686 #else /* not USE_GTK and not USE_MOTIF */
4688 /* Xaw scroll bar callback. Invoked when the thumb is dragged.
4689 WIDGET is the scroll bar widget. CLIENT_DATA is a pointer to the
4690 scroll bar struct. CALL_DATA is a pointer to a float saying where
4691 the thumb is. */
4693 static void
4694 xaw_jump_callback (Widget widget, XtPointer client_data, XtPointer call_data)
4696 struct scroll_bar *bar = client_data;
4697 float *top_addr = call_data;
4698 float top = *top_addr;
4699 float shown;
4700 int whole, portion, height, width;
4701 enum scroll_bar_part part;
4702 bool horizontal = bar->horizontal;
4705 if (horizontal)
4707 /* Get the size of the thumb, a value between 0 and 1. */
4708 block_input ();
4709 XtVaGetValues (widget, XtNshown, &shown, XtNwidth, &width, NULL);
4710 unblock_input ();
4712 if (shown < 1)
4714 whole = bar->whole - (shown * bar->whole);
4715 portion = min (top * bar->whole, whole);
4717 else
4719 whole = bar->whole;
4720 portion = 0;
4723 part = scroll_bar_horizontal_handle;
4725 else
4727 /* Get the size of the thumb, a value between 0 and 1. */
4728 block_input ();
4729 XtVaGetValues (widget, XtNshown, &shown, XtNheight, &height, NULL);
4730 unblock_input ();
4732 whole = 10000000;
4733 portion = shown < 1 ? top * whole : 0;
4735 if (shown < 1 && (eabs (top + shown - 1) < 1.0f / height))
4736 /* Some derivatives of Xaw refuse to shrink the thumb when you reach
4737 the bottom, so we force the scrolling whenever we see that we're
4738 too close to the bottom (in x_set_toolkit_scroll_bar_thumb
4739 we try to ensure that we always stay two pixels away from the
4740 bottom). */
4741 part = scroll_bar_down_arrow;
4742 else
4743 part = scroll_bar_handle;
4746 window_being_scrolled = bar->window;
4747 bar->dragging = portion;
4748 bar->last_seen_part = part;
4749 x_send_scroll_bar_event (bar->window, part, portion, whole, bar->horizontal);
4753 /* Xaw scroll bar callback. Invoked for incremental scrolling.,
4754 i.e. line or page up or down. WIDGET is the Xaw scroll bar
4755 widget. CLIENT_DATA is a pointer to the scroll_bar structure for
4756 the scroll bar. CALL_DATA is an integer specifying the action that
4757 has taken place. Its magnitude is in the range 0..height of the
4758 scroll bar. Negative values mean scroll towards buffer start.
4759 Values < height of scroll bar mean line-wise movement. */
4761 static void
4762 xaw_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
4764 struct scroll_bar *bar = client_data;
4765 /* The position really is stored cast to a pointer. */
4766 int position = (intptr_t) call_data;
4767 Dimension height, width;
4768 enum scroll_bar_part part;
4770 if (bar->horizontal)
4772 /* Get the width of the scroll bar. */
4773 block_input ();
4774 XtVaGetValues (widget, XtNwidth, &width, NULL);
4775 unblock_input ();
4777 if (eabs (position) >= width)
4778 part = (position < 0) ? scroll_bar_before_handle : scroll_bar_after_handle;
4780 /* If Xaw3d was compiled with ARROW_SCROLLBAR,
4781 it maps line-movement to call_data = max(5, height/20). */
4782 else if (xaw3d_arrow_scroll && eabs (position) <= max (5, width / 20))
4783 part = (position < 0) ? scroll_bar_left_arrow : scroll_bar_right_arrow;
4784 else
4785 part = scroll_bar_move_ratio;
4787 window_being_scrolled = bar->window;
4788 bar->dragging = -1;
4789 bar->last_seen_part = part;
4790 x_send_scroll_bar_event (bar->window, part, position, width,
4791 bar->horizontal);
4793 else
4796 /* Get the height of the scroll bar. */
4797 block_input ();
4798 XtVaGetValues (widget, XtNheight, &height, NULL);
4799 unblock_input ();
4801 if (eabs (position) >= height)
4802 part = (position < 0) ? scroll_bar_above_handle : scroll_bar_below_handle;
4804 /* If Xaw3d was compiled with ARROW_SCROLLBAR,
4805 it maps line-movement to call_data = max(5, height/20). */
4806 else if (xaw3d_arrow_scroll && eabs (position) <= max (5, height / 20))
4807 part = (position < 0) ? scroll_bar_up_arrow : scroll_bar_down_arrow;
4808 else
4809 part = scroll_bar_move_ratio;
4811 window_being_scrolled = bar->window;
4812 bar->dragging = -1;
4813 bar->last_seen_part = part;
4814 x_send_scroll_bar_event (bar->window, part, position, height,
4815 bar->horizontal);
4819 #endif /* not USE_GTK and not USE_MOTIF */
4821 #define SCROLL_BAR_NAME "verticalScrollBar"
4822 #define SCROLL_BAR_HORIZONTAL_NAME "horizontalScrollBar"
4824 /* Create the widget for scroll bar BAR on frame F. Record the widget
4825 and X window of the scroll bar in BAR. */
4827 #ifdef USE_GTK
4828 static void
4829 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
4831 const char *scroll_bar_name = SCROLL_BAR_NAME;
4833 block_input ();
4834 xg_create_scroll_bar (f, bar, G_CALLBACK (xg_scroll_callback),
4835 G_CALLBACK (xg_end_scroll_callback),
4836 scroll_bar_name);
4837 unblock_input ();
4840 static void
4841 x_create_horizontal_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
4843 const char *scroll_bar_name = SCROLL_BAR_HORIZONTAL_NAME;
4845 block_input ();
4846 xg_create_horizontal_scroll_bar (f, bar, G_CALLBACK (xg_scroll_callback),
4847 G_CALLBACK (xg_end_scroll_callback),
4848 scroll_bar_name);
4849 unblock_input ();
4852 #else /* not USE_GTK */
4854 static void
4855 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
4857 Window xwindow;
4858 Widget widget;
4859 Arg av[20];
4860 int ac = 0;
4861 const char *scroll_bar_name = SCROLL_BAR_NAME;
4862 unsigned long pixel;
4864 block_input ();
4866 #ifdef USE_MOTIF
4867 /* Set resources. Create the widget. */
4868 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
4869 XtSetArg (av[ac], XmNminimum, 0); ++ac;
4870 XtSetArg (av[ac], XmNmaximum, XM_SB_MAX); ++ac;
4871 XtSetArg (av[ac], XmNorientation, XmVERTICAL); ++ac;
4872 XtSetArg (av[ac], XmNprocessingDirection, XmMAX_ON_BOTTOM), ++ac;
4873 XtSetArg (av[ac], XmNincrement, 1); ++ac;
4874 XtSetArg (av[ac], XmNpageIncrement, 1); ++ac;
4876 pixel = f->output_data.x->scroll_bar_foreground_pixel;
4877 if (pixel != -1)
4879 XtSetArg (av[ac], XmNforeground, pixel);
4880 ++ac;
4883 pixel = f->output_data.x->scroll_bar_background_pixel;
4884 if (pixel != -1)
4886 XtSetArg (av[ac], XmNbackground, pixel);
4887 ++ac;
4890 widget = XmCreateScrollBar (f->output_data.x->edit_widget,
4891 (char *) scroll_bar_name, av, ac);
4893 /* Add one callback for everything that can happen. */
4894 XtAddCallback (widget, XmNdecrementCallback, xm_scroll_callback,
4895 (XtPointer) bar);
4896 XtAddCallback (widget, XmNdragCallback, xm_scroll_callback,
4897 (XtPointer) bar);
4898 XtAddCallback (widget, XmNincrementCallback, xm_scroll_callback,
4899 (XtPointer) bar);
4900 XtAddCallback (widget, XmNpageDecrementCallback, xm_scroll_callback,
4901 (XtPointer) bar);
4902 XtAddCallback (widget, XmNpageIncrementCallback, xm_scroll_callback,
4903 (XtPointer) bar);
4904 XtAddCallback (widget, XmNtoBottomCallback, xm_scroll_callback,
4905 (XtPointer) bar);
4906 XtAddCallback (widget, XmNtoTopCallback, xm_scroll_callback,
4907 (XtPointer) bar);
4909 /* Realize the widget. Only after that is the X window created. */
4910 XtRealizeWidget (widget);
4912 /* Set the cursor to an arrow. I didn't find a resource to do that.
4913 And I'm wondering why it hasn't an arrow cursor by default. */
4914 XDefineCursor (XtDisplay (widget), XtWindow (widget),
4915 f->output_data.x->nontext_cursor);
4917 #else /* !USE_MOTIF i.e. use Xaw */
4919 /* Set resources. Create the widget. The background of the
4920 Xaw3d scroll bar widget is a little bit light for my taste.
4921 We don't alter it here to let users change it according
4922 to their taste with `emacs*verticalScrollBar.background: xxx'. */
4923 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
4924 XtSetArg (av[ac], XtNorientation, XtorientVertical); ++ac;
4925 /* For smoother scrolling with Xaw3d -sm */
4926 /* XtSetArg (av[ac], XtNpickTop, True); ++ac; */
4928 pixel = f->output_data.x->scroll_bar_foreground_pixel;
4929 if (pixel != -1)
4931 XtSetArg (av[ac], XtNforeground, pixel);
4932 ++ac;
4935 pixel = f->output_data.x->scroll_bar_background_pixel;
4936 if (pixel != -1)
4938 XtSetArg (av[ac], XtNbackground, pixel);
4939 ++ac;
4942 /* Top/bottom shadow colors. */
4944 /* Allocate them, if necessary. */
4945 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1)
4947 pixel = f->output_data.x->scroll_bar_background_pixel;
4948 if (pixel != -1)
4950 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
4951 FRAME_X_COLORMAP (f),
4952 &pixel, 1.2, 0x8000))
4953 pixel = -1;
4954 f->output_data.x->scroll_bar_top_shadow_pixel = pixel;
4957 if (f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
4959 pixel = f->output_data.x->scroll_bar_background_pixel;
4960 if (pixel != -1)
4962 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
4963 FRAME_X_COLORMAP (f),
4964 &pixel, 0.6, 0x4000))
4965 pixel = -1;
4966 f->output_data.x->scroll_bar_bottom_shadow_pixel = pixel;
4970 #ifdef XtNbeNiceToColormap
4971 /* Tell the toolkit about them. */
4972 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1
4973 || f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
4974 /* We tried to allocate a color for the top/bottom shadow, and
4975 failed, so tell Xaw3d to use dithering instead. */
4976 /* But only if we have a small colormap. Xaw3d can allocate nice
4977 colors itself. */
4979 XtSetArg (av[ac], XtNbeNiceToColormap,
4980 DefaultDepthOfScreen (FRAME_X_SCREEN (f)) < 16);
4981 ++ac;
4983 else
4984 /* Tell what colors Xaw3d should use for the top/bottom shadow, to
4985 be more consistent with other emacs 3d colors, and since Xaw3d is
4986 not good at dealing with allocation failure. */
4988 /* This tells Xaw3d to use real colors instead of dithering for
4989 the shadows. */
4990 XtSetArg (av[ac], XtNbeNiceToColormap, False);
4991 ++ac;
4993 /* Specify the colors. */
4994 pixel = f->output_data.x->scroll_bar_top_shadow_pixel;
4995 if (pixel != -1)
4997 XtSetArg (av[ac], XtNtopShadowPixel, pixel);
4998 ++ac;
5000 pixel = f->output_data.x->scroll_bar_bottom_shadow_pixel;
5001 if (pixel != -1)
5003 XtSetArg (av[ac], XtNbottomShadowPixel, pixel);
5004 ++ac;
5007 #endif
5009 widget = XtCreateWidget (scroll_bar_name, scrollbarWidgetClass,
5010 f->output_data.x->edit_widget, av, ac);
5013 char const *initial = "";
5014 char const *val = initial;
5015 XtVaGetValues (widget, XtNscrollVCursor, (XtPointer) &val,
5016 #ifdef XtNarrowScrollbars
5017 XtNarrowScrollbars, (XtPointer) &xaw3d_arrow_scroll,
5018 #endif
5019 XtNpickTop, (XtPointer) &xaw3d_pick_top, NULL);
5020 if (xaw3d_arrow_scroll || val == initial)
5021 { /* ARROW_SCROLL */
5022 xaw3d_arrow_scroll = True;
5023 /* Isn't that just a personal preference ? --Stef */
5024 XtVaSetValues (widget, XtNcursorName, "top_left_arrow", NULL);
5028 /* Define callbacks. */
5029 XtAddCallback (widget, XtNjumpProc, xaw_jump_callback, (XtPointer) bar);
5030 XtAddCallback (widget, XtNscrollProc, xaw_scroll_callback,
5031 (XtPointer) bar);
5033 /* Realize the widget. Only after that is the X window created. */
5034 XtRealizeWidget (widget);
5036 #endif /* !USE_MOTIF */
5038 /* Install an action hook that lets us detect when the user
5039 finishes interacting with a scroll bar. */
5040 if (action_hook_id == 0)
5041 action_hook_id = XtAppAddActionHook (Xt_app_con, xt_action_hook, 0);
5043 /* Remember X window and widget in the scroll bar vector. */
5044 SET_SCROLL_BAR_X_WIDGET (bar, widget);
5045 xwindow = XtWindow (widget);
5046 bar->x_window = xwindow;
5047 bar->whole = 1;
5048 bar->horizontal = false;
5050 unblock_input ();
5053 static void
5054 x_create_horizontal_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
5056 Window xwindow;
5057 Widget widget;
5058 Arg av[20];
5059 int ac = 0;
5060 const char *scroll_bar_name = SCROLL_BAR_HORIZONTAL_NAME;
5061 unsigned long pixel;
5063 block_input ();
5065 #ifdef USE_MOTIF
5066 /* Set resources. Create the widget. */
5067 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
5068 XtSetArg (av[ac], XmNminimum, 0); ++ac;
5069 XtSetArg (av[ac], XmNmaximum, XM_SB_MAX); ++ac;
5070 XtSetArg (av[ac], XmNorientation, XmHORIZONTAL); ++ac;
5071 XtSetArg (av[ac], XmNprocessingDirection, XmMAX_ON_RIGHT), ++ac;
5072 XtSetArg (av[ac], XmNincrement, 1); ++ac;
5073 XtSetArg (av[ac], XmNpageIncrement, 1); ++ac;
5075 pixel = f->output_data.x->scroll_bar_foreground_pixel;
5076 if (pixel != -1)
5078 XtSetArg (av[ac], XmNforeground, pixel);
5079 ++ac;
5082 pixel = f->output_data.x->scroll_bar_background_pixel;
5083 if (pixel != -1)
5085 XtSetArg (av[ac], XmNbackground, pixel);
5086 ++ac;
5089 widget = XmCreateScrollBar (f->output_data.x->edit_widget,
5090 (char *) scroll_bar_name, av, ac);
5092 /* Add one callback for everything that can happen. */
5093 XtAddCallback (widget, XmNdecrementCallback, xm_scroll_callback,
5094 (XtPointer) bar);
5095 XtAddCallback (widget, XmNdragCallback, xm_scroll_callback,
5096 (XtPointer) bar);
5097 XtAddCallback (widget, XmNincrementCallback, xm_scroll_callback,
5098 (XtPointer) bar);
5099 XtAddCallback (widget, XmNpageDecrementCallback, xm_scroll_callback,
5100 (XtPointer) bar);
5101 XtAddCallback (widget, XmNpageIncrementCallback, xm_scroll_callback,
5102 (XtPointer) bar);
5103 XtAddCallback (widget, XmNtoBottomCallback, xm_scroll_callback,
5104 (XtPointer) bar);
5105 XtAddCallback (widget, XmNtoTopCallback, xm_scroll_callback,
5106 (XtPointer) bar);
5108 /* Realize the widget. Only after that is the X window created. */
5109 XtRealizeWidget (widget);
5111 /* Set the cursor to an arrow. I didn't find a resource to do that.
5112 And I'm wondering why it hasn't an arrow cursor by default. */
5113 XDefineCursor (XtDisplay (widget), XtWindow (widget),
5114 f->output_data.x->nontext_cursor);
5116 #else /* !USE_MOTIF i.e. use Xaw */
5118 /* Set resources. Create the widget. The background of the
5119 Xaw3d scroll bar widget is a little bit light for my taste.
5120 We don't alter it here to let users change it according
5121 to their taste with `emacs*verticalScrollBar.background: xxx'. */
5122 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
5123 XtSetArg (av[ac], XtNorientation, XtorientHorizontal); ++ac;
5124 /* For smoother scrolling with Xaw3d -sm */
5125 /* XtSetArg (av[ac], XtNpickTop, True); ++ac; */
5127 pixel = f->output_data.x->scroll_bar_foreground_pixel;
5128 if (pixel != -1)
5130 XtSetArg (av[ac], XtNforeground, pixel);
5131 ++ac;
5134 pixel = f->output_data.x->scroll_bar_background_pixel;
5135 if (pixel != -1)
5137 XtSetArg (av[ac], XtNbackground, pixel);
5138 ++ac;
5141 /* Top/bottom shadow colors. */
5143 /* Allocate them, if necessary. */
5144 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1)
5146 pixel = f->output_data.x->scroll_bar_background_pixel;
5147 if (pixel != -1)
5149 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
5150 FRAME_X_COLORMAP (f),
5151 &pixel, 1.2, 0x8000))
5152 pixel = -1;
5153 f->output_data.x->scroll_bar_top_shadow_pixel = pixel;
5156 if (f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
5158 pixel = f->output_data.x->scroll_bar_background_pixel;
5159 if (pixel != -1)
5161 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
5162 FRAME_X_COLORMAP (f),
5163 &pixel, 0.6, 0x4000))
5164 pixel = -1;
5165 f->output_data.x->scroll_bar_bottom_shadow_pixel = pixel;
5169 #ifdef XtNbeNiceToColormap
5170 /* Tell the toolkit about them. */
5171 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1
5172 || f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
5173 /* We tried to allocate a color for the top/bottom shadow, and
5174 failed, so tell Xaw3d to use dithering instead. */
5175 /* But only if we have a small colormap. Xaw3d can allocate nice
5176 colors itself. */
5178 XtSetArg (av[ac], XtNbeNiceToColormap,
5179 DefaultDepthOfScreen (FRAME_X_SCREEN (f)) < 16);
5180 ++ac;
5182 else
5183 /* Tell what colors Xaw3d should use for the top/bottom shadow, to
5184 be more consistent with other emacs 3d colors, and since Xaw3d is
5185 not good at dealing with allocation failure. */
5187 /* This tells Xaw3d to use real colors instead of dithering for
5188 the shadows. */
5189 XtSetArg (av[ac], XtNbeNiceToColormap, False);
5190 ++ac;
5192 /* Specify the colors. */
5193 pixel = f->output_data.x->scroll_bar_top_shadow_pixel;
5194 if (pixel != -1)
5196 XtSetArg (av[ac], XtNtopShadowPixel, pixel);
5197 ++ac;
5199 pixel = f->output_data.x->scroll_bar_bottom_shadow_pixel;
5200 if (pixel != -1)
5202 XtSetArg (av[ac], XtNbottomShadowPixel, pixel);
5203 ++ac;
5206 #endif
5208 widget = XtCreateWidget (scroll_bar_name, scrollbarWidgetClass,
5209 f->output_data.x->edit_widget, av, ac);
5212 char const *initial = "";
5213 char const *val = initial;
5214 XtVaGetValues (widget, XtNscrollVCursor, (XtPointer) &val,
5215 #ifdef XtNarrowScrollbars
5216 XtNarrowScrollbars, (XtPointer) &xaw3d_arrow_scroll,
5217 #endif
5218 XtNpickTop, (XtPointer) &xaw3d_pick_top, NULL);
5219 if (xaw3d_arrow_scroll || val == initial)
5220 { /* ARROW_SCROLL */
5221 xaw3d_arrow_scroll = True;
5222 /* Isn't that just a personal preference ? --Stef */
5223 XtVaSetValues (widget, XtNcursorName, "top_left_arrow", NULL);
5227 /* Define callbacks. */
5228 XtAddCallback (widget, XtNjumpProc, xaw_jump_callback, (XtPointer) bar);
5229 XtAddCallback (widget, XtNscrollProc, xaw_scroll_callback,
5230 (XtPointer) bar);
5232 /* Realize the widget. Only after that is the X window created. */
5233 XtRealizeWidget (widget);
5235 #endif /* !USE_MOTIF */
5237 /* Install an action hook that lets us detect when the user
5238 finishes interacting with a scroll bar. */
5239 if (horizontal_action_hook_id == 0)
5240 horizontal_action_hook_id
5241 = XtAppAddActionHook (Xt_app_con, xt_horizontal_action_hook, 0);
5243 /* Remember X window and widget in the scroll bar vector. */
5244 SET_SCROLL_BAR_X_WIDGET (bar, widget);
5245 xwindow = XtWindow (widget);
5246 bar->x_window = xwindow;
5247 bar->whole = 1;
5248 bar->horizontal = true;
5250 unblock_input ();
5252 #endif /* not USE_GTK */
5255 /* Set the thumb size and position of scroll bar BAR. We are currently
5256 displaying PORTION out of a whole WHOLE, and our position POSITION. */
5258 #ifdef USE_GTK
5259 static void
5260 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position, int whole)
5262 xg_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
5265 static void
5266 x_set_toolkit_horizontal_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position, int whole)
5268 xg_set_toolkit_horizontal_scroll_bar_thumb (bar, portion, position, whole);
5271 #else /* not USE_GTK */
5272 static void
5273 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position,
5274 int whole)
5276 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5277 Widget widget = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
5278 float top, shown;
5280 block_input ();
5282 #ifdef USE_MOTIF
5284 if (scroll_bar_adjust_thumb_portion_p)
5286 /* We use an estimate of 30 chars per line rather than the real
5287 `portion' value. This has the disadvantage that the thumb size
5288 is not very representative, but it makes our life a lot easier.
5289 Otherwise, we have to constantly adjust the thumb size, which
5290 we can't always do quickly enough: while dragging, the size of
5291 the thumb might prevent the user from dragging the thumb all the
5292 way to the end. but Motif and some versions of Xaw3d don't allow
5293 updating the thumb size while dragging. Also, even if we can update
5294 its size, the update will often happen too late.
5295 If you don't believe it, check out revision 1.650 of xterm.c to see
5296 what hoops we were going through and the still poor behavior we got. */
5297 portion = WINDOW_TOTAL_LINES (XWINDOW (bar->window)) * 30;
5298 /* When the thumb is at the bottom, position == whole.
5299 So we need to increase `whole' to make space for the thumb. */
5300 whole += portion;
5303 if (whole <= 0)
5304 top = 0, shown = 1;
5305 else
5307 top = (float) position / whole;
5308 shown = (float) portion / whole;
5311 if (bar->dragging == -1)
5313 int size, value;
5315 /* Slider size. Must be in the range [1 .. MAX - MIN] where MAX
5316 is the scroll bar's maximum and MIN is the scroll bar's minimum
5317 value. */
5318 size = clip_to_bounds (1, shown * XM_SB_MAX, XM_SB_MAX);
5320 /* Position. Must be in the range [MIN .. MAX - SLIDER_SIZE]. */
5321 value = top * XM_SB_MAX;
5322 value = min (value, XM_SB_MAX - size);
5324 XmScrollBarSetValues (widget, value, size, 0, 0, False);
5326 #else /* !USE_MOTIF i.e. use Xaw */
5328 if (whole == 0)
5329 top = 0, shown = 1;
5330 else
5332 top = (float) position / whole;
5333 shown = (float) portion / whole;
5337 float old_top, old_shown;
5338 Dimension height;
5339 XtVaGetValues (widget,
5340 XtNtopOfThumb, &old_top,
5341 XtNshown, &old_shown,
5342 XtNheight, &height,
5343 NULL);
5345 /* Massage the top+shown values. */
5346 if (bar->dragging == -1 || bar->last_seen_part == scroll_bar_down_arrow)
5347 top = max (0, min (1, top));
5348 else
5349 top = old_top;
5350 #if ! defined (HAVE_XAW3D)
5351 /* With Xaw, 'top' values too closer to 1.0 may
5352 cause the thumb to disappear. Fix that. */
5353 top = min (top, 0.99f);
5354 #endif
5355 /* Keep two pixels available for moving the thumb down. */
5356 shown = max (0, min (1 - top - (2.0f / height), shown));
5357 #if ! defined (HAVE_XAW3D)
5358 /* Likewise with too small 'shown'. */
5359 shown = max (shown, 0.01f);
5360 #endif
5362 /* If the call to XawScrollbarSetThumb below doesn't seem to
5363 work, check that 'NARROWPROTO' is defined in src/config.h.
5364 If this is not so, most likely you need to fix configure. */
5365 if (top != old_top || shown != old_shown)
5367 if (bar->dragging == -1)
5368 XawScrollbarSetThumb (widget, top, shown);
5369 else
5371 /* Try to make the scrolling a tad smoother. */
5372 if (!xaw3d_pick_top)
5373 shown = min (shown, old_shown);
5375 XawScrollbarSetThumb (widget, top, shown);
5379 #endif /* !USE_MOTIF */
5381 unblock_input ();
5384 static void
5385 x_set_toolkit_horizontal_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position,
5386 int whole)
5388 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5389 Widget widget = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
5390 float top, shown;
5392 block_input ();
5394 #ifdef USE_MOTIF
5395 bar->whole = whole;
5396 shown = (float) portion / whole;
5397 top = (float) position / (whole - portion);
5399 int size = clip_to_bounds (1, shown * XM_SB_MAX, XM_SB_MAX);
5400 int value = clip_to_bounds (0, top * (XM_SB_MAX - size), XM_SB_MAX - size);
5402 XmScrollBarSetValues (widget, value, size, 0, 0, False);
5404 #else /* !USE_MOTIF i.e. use Xaw */
5405 bar->whole = whole;
5406 if (whole == 0)
5407 top = 0, shown = 1;
5408 else
5410 top = (float) position / whole;
5411 shown = (float) portion / whole;
5415 float old_top, old_shown;
5416 Dimension height;
5417 XtVaGetValues (widget,
5418 XtNtopOfThumb, &old_top,
5419 XtNshown, &old_shown,
5420 XtNheight, &height,
5421 NULL);
5423 #if false
5424 /* Massage the top+shown values. */
5425 if (bar->dragging == -1 || bar->last_seen_part == scroll_bar_down_arrow)
5426 top = max (0, min (1, top));
5427 else
5428 top = old_top;
5429 #if ! defined (HAVE_XAW3D)
5430 /* With Xaw, 'top' values too closer to 1.0 may
5431 cause the thumb to disappear. Fix that. */
5432 top = min (top, 0.99f);
5433 #endif
5434 /* Keep two pixels available for moving the thumb down. */
5435 shown = max (0, min (1 - top - (2.0f / height), shown));
5436 #if ! defined (HAVE_XAW3D)
5437 /* Likewise with too small 'shown'. */
5438 shown = max (shown, 0.01f);
5439 #endif
5440 #endif
5442 /* If the call to XawScrollbarSetThumb below doesn't seem to
5443 work, check that 'NARROWPROTO' is defined in src/config.h.
5444 If this is not so, most likely you need to fix configure. */
5445 XawScrollbarSetThumb (widget, top, shown);
5446 #if false
5447 if (top != old_top || shown != old_shown)
5449 if (bar->dragging == -1)
5450 XawScrollbarSetThumb (widget, top, shown);
5451 else
5453 /* Try to make the scrolling a tad smoother. */
5454 if (!xaw3d_pick_top)
5455 shown = min (shown, old_shown);
5457 XawScrollbarSetThumb (widget, top, shown);
5460 #endif
5462 #endif /* !USE_MOTIF */
5464 unblock_input ();
5466 #endif /* not USE_GTK */
5468 #endif /* USE_TOOLKIT_SCROLL_BARS */
5472 /************************************************************************
5473 Scroll bars, general
5474 ************************************************************************/
5476 /* Create a scroll bar and return the scroll bar vector for it. W is
5477 the Emacs window on which to create the scroll bar. TOP, LEFT,
5478 WIDTH and HEIGHT are the pixel coordinates and dimensions of the
5479 scroll bar. */
5481 static struct scroll_bar *
5482 x_scroll_bar_create (struct window *w, int top, int left,
5483 int width, int height, bool horizontal)
5485 struct frame *f = XFRAME (w->frame);
5486 struct scroll_bar *bar
5487 = ALLOCATE_PSEUDOVECTOR (struct scroll_bar, x_window, PVEC_OTHER);
5488 Lisp_Object barobj;
5490 block_input ();
5492 #ifdef USE_TOOLKIT_SCROLL_BARS
5493 if (horizontal)
5494 x_create_horizontal_toolkit_scroll_bar (f, bar);
5495 else
5496 x_create_toolkit_scroll_bar (f, bar);
5497 #else /* not USE_TOOLKIT_SCROLL_BARS */
5499 XSetWindowAttributes a;
5500 unsigned long mask;
5501 Window window;
5503 a.background_pixel = f->output_data.x->scroll_bar_background_pixel;
5504 if (a.background_pixel == -1)
5505 a.background_pixel = FRAME_BACKGROUND_PIXEL (f);
5507 a.event_mask = (ButtonPressMask | ButtonReleaseMask
5508 | ButtonMotionMask | PointerMotionHintMask
5509 | ExposureMask);
5510 a.cursor = FRAME_DISPLAY_INFO (f)->vertical_scroll_bar_cursor;
5512 mask = (CWBackPixel | CWEventMask | CWCursor);
5514 /* Clear the area of W that will serve as a scroll bar. This is
5515 for the case that a window has been split horizontally. In
5516 this case, no clear_frame is generated to reduce flickering. */
5517 if (width > 0 && window_box_height (w) > 0)
5518 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5519 left, top, width, window_box_height (w));
5521 window = XCreateWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5522 /* Position and size of scroll bar. */
5523 left, top, width, height,
5524 /* Border width, depth, class, and visual. */
5526 CopyFromParent,
5527 CopyFromParent,
5528 CopyFromParent,
5529 /* Attributes. */
5530 mask, &a);
5531 bar->x_window = window;
5533 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5535 XSETWINDOW (bar->window, w);
5536 bar->top = top;
5537 bar->left = left;
5538 bar->width = width;
5539 bar->height = height;
5540 bar->start = 0;
5541 bar->end = 0;
5542 bar->dragging = -1;
5543 bar->horizontal = horizontal;
5544 #if defined (USE_TOOLKIT_SCROLL_BARS) && defined (USE_LUCID)
5545 bar->last_seen_part = scroll_bar_nowhere;
5546 #endif
5548 /* Add bar to its frame's list of scroll bars. */
5549 bar->next = FRAME_SCROLL_BARS (f);
5550 bar->prev = Qnil;
5551 XSETVECTOR (barobj, bar);
5552 fset_scroll_bars (f, barobj);
5553 if (!NILP (bar->next))
5554 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
5556 /* Map the window/widget. */
5557 #ifdef USE_TOOLKIT_SCROLL_BARS
5559 #ifdef USE_GTK
5560 if (horizontal)
5561 xg_update_horizontal_scrollbar_pos (f, bar->x_window, top,
5562 left, width, max (height, 1));
5563 else
5564 xg_update_scrollbar_pos (f, bar->x_window, top,
5565 left, width, max (height, 1));
5566 #else /* not USE_GTK */
5567 Widget scroll_bar = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
5568 XtConfigureWidget (scroll_bar, left, top, width, max (height, 1), 0);
5569 XtMapWidget (scroll_bar);
5570 #endif /* not USE_GTK */
5572 #else /* not USE_TOOLKIT_SCROLL_BARS */
5573 XMapRaised (FRAME_X_DISPLAY (f), bar->x_window);
5574 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5576 unblock_input ();
5577 return bar;
5581 #ifndef USE_TOOLKIT_SCROLL_BARS
5583 /* Draw BAR's handle in the proper position.
5585 If the handle is already drawn from START to END, don't bother
5586 redrawing it, unless REBUILD; in that case, always
5587 redraw it. (REBUILD is handy for drawing the handle after expose
5588 events.)
5590 Normally, we want to constrain the start and end of the handle to
5591 fit inside its rectangle, but if the user is dragging the scroll
5592 bar handle, we want to let them drag it down all the way, so that
5593 the bar's top is as far down as it goes; otherwise, there's no way
5594 to move to the very end of the buffer. */
5596 static void
5597 x_scroll_bar_set_handle (struct scroll_bar *bar, int start, int end,
5598 bool rebuild)
5600 bool dragging = bar->dragging != -1;
5601 Window w = bar->x_window;
5602 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5603 GC gc = f->output_data.x->normal_gc;
5605 /* If the display is already accurate, do nothing. */
5606 if (! rebuild
5607 && start == bar->start
5608 && end == bar->end)
5609 return;
5611 block_input ();
5614 int inside_width = VERTICAL_SCROLL_BAR_INSIDE_WIDTH (f, bar->width);
5615 int inside_height = VERTICAL_SCROLL_BAR_INSIDE_HEIGHT (f, bar->height);
5616 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
5618 /* Make sure the values are reasonable, and try to preserve
5619 the distance between start and end. */
5621 int length = end - start;
5623 if (start < 0)
5624 start = 0;
5625 else if (start > top_range)
5626 start = top_range;
5627 end = start + length;
5629 if (end < start)
5630 end = start;
5631 else if (end > top_range && ! dragging)
5632 end = top_range;
5635 /* Store the adjusted setting in the scroll bar. */
5636 bar->start = start;
5637 bar->end = end;
5639 /* Clip the end position, just for display. */
5640 if (end > top_range)
5641 end = top_range;
5643 /* Draw bottom positions VERTICAL_SCROLL_BAR_MIN_HANDLE pixels
5644 below top positions, to make sure the handle is always at least
5645 that many pixels tall. */
5646 end += VERTICAL_SCROLL_BAR_MIN_HANDLE;
5648 /* Draw the empty space above the handle. Note that we can't clear
5649 zero-height areas; that means "clear to end of window." */
5650 if ((inside_width > 0) && (start > 0))
5651 x_clear_area (FRAME_X_DISPLAY (f), w,
5652 VERTICAL_SCROLL_BAR_LEFT_BORDER,
5653 VERTICAL_SCROLL_BAR_TOP_BORDER,
5654 inside_width, start);
5656 /* Change to proper foreground color if one is specified. */
5657 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5658 XSetForeground (FRAME_X_DISPLAY (f), gc,
5659 f->output_data.x->scroll_bar_foreground_pixel);
5661 /* Draw the handle itself. */
5662 XFillRectangle (FRAME_X_DISPLAY (f), w, gc,
5663 /* x, y, width, height */
5664 VERTICAL_SCROLL_BAR_LEFT_BORDER,
5665 VERTICAL_SCROLL_BAR_TOP_BORDER + start,
5666 inside_width, end - start);
5668 /* Restore the foreground color of the GC if we changed it above. */
5669 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5670 XSetForeground (FRAME_X_DISPLAY (f), gc,
5671 FRAME_FOREGROUND_PIXEL (f));
5673 /* Draw the empty space below the handle. Note that we can't
5674 clear zero-height areas; that means "clear to end of window." */
5675 if ((inside_width > 0) && (end < inside_height))
5676 x_clear_area (FRAME_X_DISPLAY (f), w,
5677 VERTICAL_SCROLL_BAR_LEFT_BORDER,
5678 VERTICAL_SCROLL_BAR_TOP_BORDER + end,
5679 inside_width, inside_height - end);
5682 unblock_input ();
5685 #endif /* !USE_TOOLKIT_SCROLL_BARS */
5687 /* Destroy scroll bar BAR, and set its Emacs window's scroll bar to
5688 nil. */
5690 static void
5691 x_scroll_bar_remove (struct scroll_bar *bar)
5693 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5694 block_input ();
5696 #ifdef USE_TOOLKIT_SCROLL_BARS
5697 #ifdef USE_GTK
5698 xg_remove_scroll_bar (f, bar->x_window);
5699 #else /* not USE_GTK */
5700 XtDestroyWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar));
5701 #endif /* not USE_GTK */
5702 #else
5703 XDestroyWindow (FRAME_X_DISPLAY (f), bar->x_window);
5704 #endif
5706 /* Dissociate this scroll bar from its window. */
5707 if (bar->horizontal)
5708 wset_horizontal_scroll_bar (XWINDOW (bar->window), Qnil);
5709 else
5710 wset_vertical_scroll_bar (XWINDOW (bar->window), Qnil);
5712 unblock_input ();
5716 /* Set the handle of the vertical scroll bar for WINDOW to indicate
5717 that we are displaying PORTION characters out of a total of WHOLE
5718 characters, starting at POSITION. If WINDOW has no scroll bar,
5719 create one. */
5721 static void
5722 XTset_vertical_scroll_bar (struct window *w, int portion, int whole, int position)
5724 struct frame *f = XFRAME (w->frame);
5725 Lisp_Object barobj;
5726 struct scroll_bar *bar;
5727 int top, height, left, width;
5728 int window_y, window_height;
5730 /* Get window dimensions. */
5731 window_box (w, ANY_AREA, 0, &window_y, 0, &window_height);
5732 top = window_y;
5733 height = window_height;
5734 left = WINDOW_SCROLL_BAR_AREA_X (w);
5735 width = WINDOW_SCROLL_BAR_AREA_WIDTH (w);
5737 /* Does the scroll bar exist yet? */
5738 if (NILP (w->vertical_scroll_bar))
5740 if (width > 0 && height > 0)
5742 block_input ();
5743 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5744 left, top, width, height);
5745 unblock_input ();
5748 bar = x_scroll_bar_create (w, top, left, width, max (height, 1), false);
5750 else
5752 /* It may just need to be moved and resized. */
5753 unsigned int mask = 0;
5755 bar = XSCROLL_BAR (w->vertical_scroll_bar);
5757 block_input ();
5759 if (left != bar->left)
5760 mask |= CWX;
5761 if (top != bar->top)
5762 mask |= CWY;
5763 if (width != bar->width)
5764 mask |= CWWidth;
5765 if (height != bar->height)
5766 mask |= CWHeight;
5768 #ifdef USE_TOOLKIT_SCROLL_BARS
5770 /* Move/size the scroll bar widget. */
5771 if (mask)
5773 /* Since toolkit scroll bars are smaller than the space reserved
5774 for them on the frame, we have to clear "under" them. */
5775 if (width > 0 && height > 0)
5776 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5777 left, top, width, height);
5778 #ifdef USE_GTK
5779 xg_update_scrollbar_pos (f, bar->x_window, top,
5780 left, width, max (height, 1));
5781 #else /* not USE_GTK */
5782 XtConfigureWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar),
5783 left, top, width, max (height, 1), 0);
5784 #endif /* not USE_GTK */
5786 #else /* not USE_TOOLKIT_SCROLL_BARS */
5788 /* Move/size the scroll bar window. */
5789 if (mask)
5791 XWindowChanges wc;
5793 wc.x = left;
5794 wc.y = top;
5795 wc.width = width;
5796 wc.height = height;
5797 XConfigureWindow (FRAME_X_DISPLAY (f), bar->x_window,
5798 mask, &wc);
5801 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5803 /* Remember new settings. */
5804 bar->left = left;
5805 bar->top = top;
5806 bar->width = width;
5807 bar->height = height;
5809 unblock_input ();
5812 #ifdef USE_TOOLKIT_SCROLL_BARS
5813 x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
5814 #else /* not USE_TOOLKIT_SCROLL_BARS */
5815 /* Set the scroll bar's current state, unless we're currently being
5816 dragged. */
5817 if (bar->dragging == -1)
5819 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, height);
5821 if (whole == 0)
5822 x_scroll_bar_set_handle (bar, 0, top_range, false);
5823 else
5825 int start = ((double) position * top_range) / whole;
5826 int end = ((double) (position + portion) * top_range) / whole;
5827 x_scroll_bar_set_handle (bar, start, end, false);
5830 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5832 XSETVECTOR (barobj, bar);
5833 wset_vertical_scroll_bar (w, barobj);
5837 static void
5838 XTset_horizontal_scroll_bar (struct window *w, int portion, int whole, int position)
5840 struct frame *f = XFRAME (w->frame);
5841 Lisp_Object barobj;
5842 struct scroll_bar *bar;
5843 int top, height, left, width;
5844 int window_x, window_width;
5845 int pixel_width = WINDOW_PIXEL_WIDTH (w);
5847 /* Get window dimensions. */
5848 window_box (w, ANY_AREA, &window_x, 0, &window_width, 0);
5849 left = window_x;
5850 width = window_width;
5851 top = WINDOW_SCROLL_BAR_AREA_Y (w);
5852 height = WINDOW_SCROLL_BAR_AREA_HEIGHT (w);
5854 /* Does the scroll bar exist yet? */
5855 if (NILP (w->horizontal_scroll_bar))
5857 if (width > 0 && height > 0)
5859 block_input ();
5861 /* Clear also part between window_width and
5862 WINDOW_PIXEL_WIDTH. */
5863 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5864 left, top, pixel_width, height);
5865 unblock_input ();
5868 bar = x_scroll_bar_create (w, top, left, width, height, true);
5870 else
5872 /* It may just need to be moved and resized. */
5873 unsigned int mask = 0;
5875 bar = XSCROLL_BAR (w->horizontal_scroll_bar);
5877 block_input ();
5879 if (left != bar->left)
5880 mask |= CWX;
5881 if (top != bar->top)
5882 mask |= CWY;
5883 if (width != bar->width)
5884 mask |= CWWidth;
5885 if (height != bar->height)
5886 mask |= CWHeight;
5888 #ifdef USE_TOOLKIT_SCROLL_BARS
5889 /* Move/size the scroll bar widget. */
5890 if (mask)
5892 /* Since toolkit scroll bars are smaller than the space reserved
5893 for them on the frame, we have to clear "under" them. */
5894 if (width > 0 && height > 0)
5895 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5896 WINDOW_LEFT_EDGE_X (w), top,
5897 pixel_width - WINDOW_RIGHT_DIVIDER_WIDTH (w), height);
5898 #ifdef USE_GTK
5899 xg_update_horizontal_scrollbar_pos (f, bar->x_window, top, left,
5900 width, height);
5901 #else /* not USE_GTK */
5902 XtConfigureWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar),
5903 left, top, width, height, 0);
5904 #endif /* not USE_GTK */
5906 #else /* not USE_TOOLKIT_SCROLL_BARS */
5908 /* Clear areas not covered by the scroll bar because it's not as
5909 wide as the area reserved for it. This makes sure a
5910 previous mode line display is cleared after C-x 2 C-x 1, for
5911 example. */
5913 int area_height = WINDOW_CONFIG_SCROLL_BAR_HEIGHT (w);
5914 int rest = area_height - height;
5915 if (rest > 0 && width > 0)
5916 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5917 left, top, width, rest);
5920 /* Move/size the scroll bar window. */
5921 if (mask)
5923 XWindowChanges wc;
5925 wc.x = left;
5926 wc.y = top;
5927 wc.width = width;
5928 wc.height = height;
5929 XConfigureWindow (FRAME_X_DISPLAY (f), bar->x_window,
5930 mask, &wc);
5933 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5935 /* Remember new settings. */
5936 bar->left = left;
5937 bar->top = top;
5938 bar->width = width;
5939 bar->height = height;
5941 unblock_input ();
5944 #ifdef USE_TOOLKIT_SCROLL_BARS
5945 x_set_toolkit_horizontal_scroll_bar_thumb (bar, portion, position, whole);
5946 #else /* not USE_TOOLKIT_SCROLL_BARS */
5947 /* Set the scroll bar's current state, unless we're currently being
5948 dragged. */
5949 if (bar->dragging == -1)
5951 int left_range = HORIZONTAL_SCROLL_BAR_LEFT_RANGE (f, width);
5953 if (whole == 0)
5954 x_scroll_bar_set_handle (bar, 0, left_range, false);
5955 else
5957 int start = ((double) position * left_range) / whole;
5958 int end = ((double) (position + portion) * left_range) / whole;
5959 x_scroll_bar_set_handle (bar, start, end, false);
5962 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5964 XSETVECTOR (barobj, bar);
5965 wset_horizontal_scroll_bar (w, barobj);
5969 /* The following three hooks are used when we're doing a thorough
5970 redisplay of the frame. We don't explicitly know which scroll bars
5971 are going to be deleted, because keeping track of when windows go
5972 away is a real pain - "Can you say set-window-configuration, boys
5973 and girls?" Instead, we just assert at the beginning of redisplay
5974 that *all* scroll bars are to be removed, and then save a scroll bar
5975 from the fiery pit when we actually redisplay its window. */
5977 /* Arrange for all scroll bars on FRAME to be removed at the next call
5978 to `*judge_scroll_bars_hook'. A scroll bar may be spared if
5979 `*redeem_scroll_bar_hook' is applied to its window before the judgment. */
5981 static void
5982 XTcondemn_scroll_bars (struct frame *frame)
5984 if (!NILP (FRAME_SCROLL_BARS (frame)))
5986 if (!NILP (FRAME_CONDEMNED_SCROLL_BARS (frame)))
5988 /* Prepend scrollbars to already condemned ones. */
5989 Lisp_Object last = FRAME_SCROLL_BARS (frame);
5991 while (!NILP (XSCROLL_BAR (last)->next))
5992 last = XSCROLL_BAR (last)->next;
5994 XSCROLL_BAR (last)->next = FRAME_CONDEMNED_SCROLL_BARS (frame);
5995 XSCROLL_BAR (FRAME_CONDEMNED_SCROLL_BARS (frame))->prev = last;
5998 fset_condemned_scroll_bars (frame, FRAME_SCROLL_BARS (frame));
5999 fset_scroll_bars (frame, Qnil);
6004 /* Un-mark WINDOW's scroll bar for deletion in this judgment cycle.
6005 Note that WINDOW isn't necessarily condemned at all. */
6007 static void
6008 XTredeem_scroll_bar (struct window *w)
6010 struct scroll_bar *bar;
6011 Lisp_Object barobj;
6012 struct frame *f;
6014 /* We can't redeem this window's scroll bar if it doesn't have one. */
6015 if (NILP (w->vertical_scroll_bar) && NILP (w->horizontal_scroll_bar))
6016 emacs_abort ();
6018 if (!NILP (w->vertical_scroll_bar) && WINDOW_HAS_VERTICAL_SCROLL_BAR (w))
6020 bar = XSCROLL_BAR (w->vertical_scroll_bar);
6021 /* Unlink it from the condemned list. */
6022 f = XFRAME (WINDOW_FRAME (w));
6023 if (NILP (bar->prev))
6025 /* If the prev pointer is nil, it must be the first in one of
6026 the lists. */
6027 if (EQ (FRAME_SCROLL_BARS (f), w->vertical_scroll_bar))
6028 /* It's not condemned. Everything's fine. */
6029 goto horizontal;
6030 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
6031 w->vertical_scroll_bar))
6032 fset_condemned_scroll_bars (f, bar->next);
6033 else
6034 /* If its prev pointer is nil, it must be at the front of
6035 one or the other! */
6036 emacs_abort ();
6038 else
6039 XSCROLL_BAR (bar->prev)->next = bar->next;
6041 if (! NILP (bar->next))
6042 XSCROLL_BAR (bar->next)->prev = bar->prev;
6044 bar->next = FRAME_SCROLL_BARS (f);
6045 bar->prev = Qnil;
6046 XSETVECTOR (barobj, bar);
6047 fset_scroll_bars (f, barobj);
6048 if (! NILP (bar->next))
6049 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
6052 horizontal:
6053 if (!NILP (w->horizontal_scroll_bar) && WINDOW_HAS_HORIZONTAL_SCROLL_BAR (w))
6055 bar = XSCROLL_BAR (w->horizontal_scroll_bar);
6056 /* Unlink it from the condemned list. */
6057 f = XFRAME (WINDOW_FRAME (w));
6058 if (NILP (bar->prev))
6060 /* If the prev pointer is nil, it must be the first in one of
6061 the lists. */
6062 if (EQ (FRAME_SCROLL_BARS (f), w->horizontal_scroll_bar))
6063 /* It's not condemned. Everything's fine. */
6064 return;
6065 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
6066 w->horizontal_scroll_bar))
6067 fset_condemned_scroll_bars (f, bar->next);
6068 else
6069 /* If its prev pointer is nil, it must be at the front of
6070 one or the other! */
6071 emacs_abort ();
6073 else
6074 XSCROLL_BAR (bar->prev)->next = bar->next;
6076 if (! NILP (bar->next))
6077 XSCROLL_BAR (bar->next)->prev = bar->prev;
6079 bar->next = FRAME_SCROLL_BARS (f);
6080 bar->prev = Qnil;
6081 XSETVECTOR (barobj, bar);
6082 fset_scroll_bars (f, barobj);
6083 if (! NILP (bar->next))
6084 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
6088 /* Remove all scroll bars on FRAME that haven't been saved since the
6089 last call to `*condemn_scroll_bars_hook'. */
6091 static void
6092 XTjudge_scroll_bars (struct frame *f)
6094 Lisp_Object bar, next;
6096 bar = FRAME_CONDEMNED_SCROLL_BARS (f);
6098 /* Clear out the condemned list now so we won't try to process any
6099 more events on the hapless scroll bars. */
6100 fset_condemned_scroll_bars (f, Qnil);
6102 for (; ! NILP (bar); bar = next)
6104 struct scroll_bar *b = XSCROLL_BAR (bar);
6106 x_scroll_bar_remove (b);
6108 next = b->next;
6109 b->next = b->prev = Qnil;
6112 /* Now there should be no references to the condemned scroll bars,
6113 and they should get garbage-collected. */
6117 #ifndef USE_TOOLKIT_SCROLL_BARS
6118 /* Handle an Expose or GraphicsExpose event on a scroll bar. This
6119 is a no-op when using toolkit scroll bars.
6121 This may be called from a signal handler, so we have to ignore GC
6122 mark bits. */
6124 static void
6125 x_scroll_bar_expose (struct scroll_bar *bar, const XEvent *event)
6127 Window w = bar->x_window;
6128 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6129 GC gc = f->output_data.x->normal_gc;
6131 block_input ();
6133 x_scroll_bar_set_handle (bar, bar->start, bar->end, true);
6135 /* Switch to scroll bar foreground color. */
6136 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
6137 XSetForeground (FRAME_X_DISPLAY (f), gc,
6138 f->output_data.x->scroll_bar_foreground_pixel);
6140 /* Draw a one-pixel border just inside the edges of the scroll bar. */
6141 XDrawRectangle (FRAME_X_DISPLAY (f), w, gc,
6142 /* x, y, width, height */
6143 0, 0, bar->width - 1, bar->height - 1);
6145 /* Restore the foreground color of the GC if we changed it above. */
6146 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
6147 XSetForeground (FRAME_X_DISPLAY (f), gc,
6148 FRAME_FOREGROUND_PIXEL (f));
6150 unblock_input ();
6153 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6155 /* Handle a mouse click on the scroll bar BAR. If *EMACS_EVENT's kind
6156 is set to something other than NO_EVENT, it is enqueued.
6158 This may be called from a signal handler, so we have to ignore GC
6159 mark bits. */
6162 static void
6163 x_scroll_bar_handle_click (struct scroll_bar *bar,
6164 const XEvent *event,
6165 struct input_event *emacs_event)
6167 if (! WINDOWP (bar->window))
6168 emacs_abort ();
6170 emacs_event->kind = (bar->horizontal
6171 ? HORIZONTAL_SCROLL_BAR_CLICK_EVENT
6172 : SCROLL_BAR_CLICK_EVENT);
6173 emacs_event->code = event->xbutton.button - Button1;
6174 emacs_event->modifiers
6175 = (x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO
6176 (XFRAME (WINDOW_FRAME (XWINDOW (bar->window)))),
6177 event->xbutton.state)
6178 | (event->type == ButtonRelease
6179 ? up_modifier
6180 : down_modifier));
6181 emacs_event->frame_or_window = bar->window;
6182 emacs_event->arg = Qnil;
6183 emacs_event->timestamp = event->xbutton.time;
6184 if (bar->horizontal)
6186 int left_range
6187 = HORIZONTAL_SCROLL_BAR_LEFT_RANGE (f, bar->width);
6188 int x = event->xbutton.x - HORIZONTAL_SCROLL_BAR_LEFT_BORDER;
6190 if (x < 0) x = 0;
6191 if (x > left_range) x = left_range;
6193 if (x < bar->start)
6194 emacs_event->part = scroll_bar_before_handle;
6195 else if (x < bar->end + HORIZONTAL_SCROLL_BAR_MIN_HANDLE)
6196 emacs_event->part = scroll_bar_horizontal_handle;
6197 else
6198 emacs_event->part = scroll_bar_after_handle;
6200 #ifndef USE_TOOLKIT_SCROLL_BARS
6201 /* If the user has released the handle, set it to its final position. */
6202 if (event->type == ButtonRelease && bar->dragging != -1)
6204 int new_start = - bar->dragging;
6205 int new_end = new_start + bar->end - bar->start;
6207 x_scroll_bar_set_handle (bar, new_start, new_end, false);
6208 bar->dragging = -1;
6210 #endif
6212 XSETINT (emacs_event->x, left_range);
6213 XSETINT (emacs_event->y, x);
6215 else
6217 int top_range
6218 = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
6219 int y = event->xbutton.y - VERTICAL_SCROLL_BAR_TOP_BORDER;
6221 if (y < 0) y = 0;
6222 if (y > top_range) y = top_range;
6224 if (y < bar->start)
6225 emacs_event->part = scroll_bar_above_handle;
6226 else if (y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
6227 emacs_event->part = scroll_bar_handle;
6228 else
6229 emacs_event->part = scroll_bar_below_handle;
6231 #ifndef USE_TOOLKIT_SCROLL_BARS
6232 /* If the user has released the handle, set it to its final position. */
6233 if (event->type == ButtonRelease && bar->dragging != -1)
6235 int new_start = y - bar->dragging;
6236 int new_end = new_start + bar->end - bar->start;
6238 x_scroll_bar_set_handle (bar, new_start, new_end, false);
6239 bar->dragging = -1;
6241 #endif
6243 XSETINT (emacs_event->x, y);
6244 XSETINT (emacs_event->y, top_range);
6248 #ifndef USE_TOOLKIT_SCROLL_BARS
6250 /* Handle some mouse motion while someone is dragging the scroll bar.
6252 This may be called from a signal handler, so we have to ignore GC
6253 mark bits. */
6255 static void
6256 x_scroll_bar_note_movement (struct scroll_bar *bar,
6257 const XMotionEvent *event)
6259 struct frame *f = XFRAME (XWINDOW (bar->window)->frame);
6260 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
6262 dpyinfo->last_mouse_movement_time = event->time;
6263 dpyinfo->last_mouse_scroll_bar = bar;
6264 f->mouse_moved = true;
6266 /* If we're dragging the bar, display it. */
6267 if (bar->dragging != -1)
6269 /* Where should the handle be now? */
6270 int new_start = event->y - bar->dragging;
6272 if (new_start != bar->start)
6274 int new_end = new_start + bar->end - bar->start;
6276 x_scroll_bar_set_handle (bar, new_start, new_end, false);
6281 #endif /* !USE_TOOLKIT_SCROLL_BARS */
6283 /* Return information to the user about the current position of the mouse
6284 on the scroll bar. */
6286 static void
6287 x_scroll_bar_report_motion (struct frame **fp, Lisp_Object *bar_window,
6288 enum scroll_bar_part *part, Lisp_Object *x,
6289 Lisp_Object *y, Time *timestamp)
6291 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (*fp);
6292 struct scroll_bar *bar = dpyinfo->last_mouse_scroll_bar;
6293 Window w = bar->x_window;
6294 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6295 int win_x, win_y;
6296 Window dummy_window;
6297 int dummy_coord;
6298 unsigned int dummy_mask;
6300 block_input ();
6302 /* Get the mouse's position relative to the scroll bar window, and
6303 report that. */
6304 if (XQueryPointer (FRAME_X_DISPLAY (f), w,
6306 /* Root, child, root x and root y. */
6307 &dummy_window, &dummy_window,
6308 &dummy_coord, &dummy_coord,
6310 /* Position relative to scroll bar. */
6311 &win_x, &win_y,
6313 /* Mouse buttons and modifier keys. */
6314 &dummy_mask))
6316 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
6318 win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
6320 if (bar->dragging != -1)
6321 win_y -= bar->dragging;
6323 if (win_y < 0)
6324 win_y = 0;
6325 if (win_y > top_range)
6326 win_y = top_range;
6328 *fp = f;
6329 *bar_window = bar->window;
6331 if (bar->dragging != -1)
6332 *part = scroll_bar_handle;
6333 else if (win_y < bar->start)
6334 *part = scroll_bar_above_handle;
6335 else if (win_y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
6336 *part = scroll_bar_handle;
6337 else
6338 *part = scroll_bar_below_handle;
6340 XSETINT (*x, win_y);
6341 XSETINT (*y, top_range);
6343 f->mouse_moved = false;
6344 dpyinfo->last_mouse_scroll_bar = NULL;
6345 *timestamp = dpyinfo->last_mouse_movement_time;
6348 unblock_input ();
6352 /* Return information to the user about the current position of the mouse
6353 on the scroll bar. */
6355 static void
6356 x_horizontal_scroll_bar_report_motion (struct frame **fp, Lisp_Object *bar_window,
6357 enum scroll_bar_part *part, Lisp_Object *x,
6358 Lisp_Object *y, Time *timestamp)
6360 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (*fp);
6361 struct scroll_bar *bar = dpyinfo->last_mouse_scroll_bar;
6362 Window w = bar->x_window;
6363 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
6364 int win_x, win_y;
6365 Window dummy_window;
6366 int dummy_coord;
6367 unsigned int dummy_mask;
6369 block_input ();
6371 /* Get the mouse's position relative to the scroll bar window, and
6372 report that. */
6373 if (XQueryPointer (FRAME_X_DISPLAY (f), w,
6375 /* Root, child, root x and root y. */
6376 &dummy_window, &dummy_window,
6377 &dummy_coord, &dummy_coord,
6379 /* Position relative to scroll bar. */
6380 &win_x, &win_y,
6382 /* Mouse buttons and modifier keys. */
6383 &dummy_mask))
6385 int left_range = HORIZONTAL_SCROLL_BAR_LEFT_RANGE (f, bar->width);
6387 win_x -= HORIZONTAL_SCROLL_BAR_LEFT_BORDER;
6389 if (bar->dragging != -1)
6390 win_x -= bar->dragging;
6392 if (win_x < 0)
6393 win_x = 0;
6394 if (win_x > left_range)
6395 win_x = left_range;
6397 *fp = f;
6398 *bar_window = bar->window;
6400 if (bar->dragging != -1)
6401 *part = scroll_bar_horizontal_handle;
6402 else if (win_x < bar->start)
6403 *part = scroll_bar_before_handle;
6404 else if (win_x < bar->end + HORIZONTAL_SCROLL_BAR_MIN_HANDLE)
6405 *part = scroll_bar_handle;
6406 else
6407 *part = scroll_bar_after_handle;
6409 XSETINT (*y, win_x);
6410 XSETINT (*x, left_range);
6412 f->mouse_moved = false;
6413 dpyinfo->last_mouse_scroll_bar = NULL;
6414 *timestamp = dpyinfo->last_mouse_movement_time;
6417 unblock_input ();
6421 /* The screen has been cleared so we may have changed foreground or
6422 background colors, and the scroll bars may need to be redrawn.
6423 Clear out the scroll bars, and ask for expose events, so we can
6424 redraw them. */
6426 static void
6427 x_scroll_bar_clear (struct frame *f)
6429 #ifndef USE_TOOLKIT_SCROLL_BARS
6430 Lisp_Object bar;
6432 /* We can have scroll bars even if this is 0,
6433 if we just turned off scroll bar mode.
6434 But in that case we should not clear them. */
6435 if (FRAME_HAS_VERTICAL_SCROLL_BARS (f))
6436 for (bar = FRAME_SCROLL_BARS (f); VECTORP (bar);
6437 bar = XSCROLL_BAR (bar)->next)
6438 XClearArea (FRAME_X_DISPLAY (f),
6439 XSCROLL_BAR (bar)->x_window,
6440 0, 0, 0, 0, True);
6441 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6444 #ifdef ENABLE_CHECKING
6446 /* Record the last 100 characters stored
6447 to help debug the loss-of-chars-during-GC problem. */
6449 static int temp_index;
6450 static short temp_buffer[100];
6452 #define STORE_KEYSYM_FOR_DEBUG(keysym) \
6453 if (temp_index == ARRAYELTS (temp_buffer)) \
6454 temp_index = 0; \
6455 temp_buffer[temp_index++] = (keysym)
6457 #else /* not ENABLE_CHECKING */
6459 #define STORE_KEYSYM_FOR_DEBUG(keysym) ((void)0)
6461 #endif /* ENABLE_CHECKING */
6463 /* Set this to nonzero to fake an "X I/O error"
6464 on a particular display. */
6466 static struct x_display_info *XTread_socket_fake_io_error;
6468 /* When we find no input here, we occasionally do a no-op command
6469 to verify that the X server is still running and we can still talk with it.
6470 We try all the open displays, one by one.
6471 This variable is used for cycling thru the displays. */
6473 static struct x_display_info *next_noop_dpyinfo;
6475 enum
6477 X_EVENT_NORMAL,
6478 X_EVENT_GOTO_OUT,
6479 X_EVENT_DROP
6482 /* Filter events for the current X input method.
6483 DPYINFO is the display this event is for.
6484 EVENT is the X event to filter.
6486 Returns non-zero if the event was filtered, caller shall not process
6487 this event further.
6488 Returns zero if event is wasn't filtered. */
6490 #ifdef HAVE_X_I18N
6491 static int
6492 x_filter_event (struct x_display_info *dpyinfo, XEvent *event)
6494 /* XFilterEvent returns non-zero if the input method has
6495 consumed the event. We pass the frame's X window to
6496 XFilterEvent because that's the one for which the IC
6497 was created. */
6499 struct frame *f1 = x_any_window_to_frame (dpyinfo,
6500 event->xclient.window);
6502 return XFilterEvent (event, f1 ? FRAME_X_WINDOW (f1) : None);
6504 #endif
6506 #ifdef USE_GTK
6507 static int current_count;
6508 static int current_finish;
6509 static struct input_event *current_hold_quit;
6511 /* This is the filter function invoked by the GTK event loop.
6512 It is invoked before the XEvent is translated to a GdkEvent,
6513 so we have a chance to act on the event before GTK. */
6514 static GdkFilterReturn
6515 event_handler_gdk (GdkXEvent *gxev, GdkEvent *ev, gpointer data)
6517 XEvent *xev = (XEvent *) gxev;
6519 block_input ();
6520 if (current_count >= 0)
6522 struct x_display_info *dpyinfo;
6524 dpyinfo = x_display_info_for_display (xev->xany.display);
6526 #ifdef HAVE_X_I18N
6527 /* Filter events for the current X input method.
6528 GTK calls XFilterEvent but not for key press and release,
6529 so we do it here. */
6530 if ((xev->type == KeyPress || xev->type == KeyRelease)
6531 && dpyinfo
6532 && x_filter_event (dpyinfo, xev))
6534 unblock_input ();
6535 return GDK_FILTER_REMOVE;
6537 #endif
6539 if (! dpyinfo)
6540 current_finish = X_EVENT_NORMAL;
6541 else
6542 current_count
6543 += handle_one_xevent (dpyinfo, xev, &current_finish,
6544 current_hold_quit);
6546 else
6547 current_finish = x_dispatch_event (xev, xev->xany.display);
6549 unblock_input ();
6551 if (current_finish == X_EVENT_GOTO_OUT || current_finish == X_EVENT_DROP)
6552 return GDK_FILTER_REMOVE;
6554 return GDK_FILTER_CONTINUE;
6556 #endif /* USE_GTK */
6559 static void xembed_send_message (struct frame *f, Time,
6560 enum xembed_message,
6561 long detail, long data1, long data2);
6563 static void
6564 x_net_wm_state (struct frame *f, Window window)
6566 int value = FULLSCREEN_NONE;
6567 Lisp_Object lval = Qnil;
6568 bool sticky = false;
6570 get_current_wm_state (f, window, &value, &sticky);
6572 switch (value)
6574 case FULLSCREEN_WIDTH:
6575 lval = Qfullwidth;
6576 break;
6577 case FULLSCREEN_HEIGHT:
6578 lval = Qfullheight;
6579 break;
6580 case FULLSCREEN_BOTH:
6581 lval = Qfullboth;
6582 break;
6583 case FULLSCREEN_MAXIMIZED:
6584 lval = Qmaximized;
6585 break;
6588 store_frame_param (f, Qfullscreen, lval);
6589 /** store_frame_param (f, Qsticky, sticky ? Qt : Qnil); **/
6592 /* Handles the XEvent EVENT on display DPYINFO.
6594 *FINISH is X_EVENT_GOTO_OUT if caller should stop reading events.
6595 *FINISH is zero if caller should continue reading events.
6596 *FINISH is X_EVENT_DROP if event should not be passed to the toolkit.
6597 *EVENT is unchanged unless we're processing KeyPress event.
6599 We return the number of characters stored into the buffer. */
6601 static int
6602 handle_one_xevent (struct x_display_info *dpyinfo,
6603 const XEvent *event,
6604 int *finish, struct input_event *hold_quit)
6606 union {
6607 struct input_event ie;
6608 struct selection_input_event sie;
6609 } inev;
6610 int count = 0;
6611 int do_help = 0;
6612 ptrdiff_t nbytes = 0;
6613 struct frame *any, *f = NULL;
6614 struct coding_system coding;
6615 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
6616 /* This holds the state XLookupString needs to implement dead keys
6617 and other tricks known as "compose processing". _X Window System_
6618 says that a portable program can't use this, but Stephen Gildea assures
6619 me that letting the compiler initialize it to zeros will work okay. */
6620 static XComposeStatus compose_status;
6622 USE_SAFE_ALLOCA;
6624 *finish = X_EVENT_NORMAL;
6626 EVENT_INIT (inev.ie);
6627 inev.ie.kind = NO_EVENT;
6628 inev.ie.arg = Qnil;
6630 any = x_any_window_to_frame (dpyinfo, event->xany.window);
6632 if (any && any->wait_event_type == event->type)
6633 any->wait_event_type = 0; /* Indicates we got it. */
6635 switch (event->type)
6637 case ClientMessage:
6639 if (event->xclient.message_type == dpyinfo->Xatom_wm_protocols
6640 && event->xclient.format == 32)
6642 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_take_focus)
6644 /* Use the value returned by x_any_window_to_frame
6645 because this could be the shell widget window
6646 if the frame has no title bar. */
6647 f = any;
6648 #ifdef HAVE_X_I18N
6649 /* Not quite sure this is needed -pd */
6650 if (f && FRAME_XIC (f))
6651 XSetICFocus (FRAME_XIC (f));
6652 #endif
6653 #if false
6654 /* Emacs sets WM hints whose `input' field is `true'. This
6655 instructs the WM to set the input focus automatically for
6656 Emacs with a call to XSetInputFocus. Setting WM_TAKE_FOCUS
6657 tells the WM to send us a ClientMessage WM_TAKE_FOCUS after
6658 it has set the focus. So, XSetInputFocus below is not
6659 needed.
6661 The call to XSetInputFocus below has also caused trouble. In
6662 cases where the XSetInputFocus done by the WM and the one
6663 below are temporally close (on a fast machine), the call
6664 below can generate additional FocusIn events which confuse
6665 Emacs. */
6667 /* Since we set WM_TAKE_FOCUS, we must call
6668 XSetInputFocus explicitly. But not if f is null,
6669 since that might be an event for a deleted frame. */
6670 if (f)
6672 Display *d = event->xclient.display;
6673 /* Catch and ignore errors, in case window has been
6674 iconified by a window manager such as GWM. */
6675 x_catch_errors (d);
6676 XSetInputFocus (d, event->xclient.window,
6677 /* The ICCCM says this is
6678 the only valid choice. */
6679 RevertToParent,
6680 event->xclient.data.l[1]);
6681 /* This is needed to detect the error
6682 if there is an error. */
6683 XSync (d, False);
6684 x_uncatch_errors ();
6686 /* Not certain about handling scroll bars here */
6687 #endif
6688 goto done;
6691 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_save_yourself)
6693 /* Save state modify the WM_COMMAND property to
6694 something which can reinstate us. This notifies
6695 the session manager, who's looking for such a
6696 PropertyNotify. Can restart processing when
6697 a keyboard or mouse event arrives. */
6698 /* If we have a session manager, don't set this.
6699 KDE will then start two Emacsen, one for the
6700 session manager and one for this. */
6701 #ifdef HAVE_X_SM
6702 if (! x_session_have_connection ())
6703 #endif
6705 f = x_top_window_to_frame (dpyinfo,
6706 event->xclient.window);
6707 /* This is just so we only give real data once
6708 for a single Emacs process. */
6709 if (f == SELECTED_FRAME ())
6710 XSetCommand (FRAME_X_DISPLAY (f),
6711 event->xclient.window,
6712 initial_argv, initial_argc);
6713 else if (f)
6714 XSetCommand (FRAME_X_DISPLAY (f),
6715 event->xclient.window,
6716 0, 0);
6718 goto done;
6721 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_delete_window)
6723 f = any;
6724 if (!f)
6725 goto OTHER; /* May be a dialog that is to be removed */
6727 inev.ie.kind = DELETE_WINDOW_EVENT;
6728 XSETFRAME (inev.ie.frame_or_window, f);
6729 goto done;
6732 goto done;
6735 if (event->xclient.message_type == dpyinfo->Xatom_wm_configure_denied)
6736 goto done;
6738 if (event->xclient.message_type == dpyinfo->Xatom_wm_window_moved)
6740 int new_x, new_y;
6741 f = x_window_to_frame (dpyinfo, event->xclient.window);
6743 new_x = event->xclient.data.s[0];
6744 new_y = event->xclient.data.s[1];
6746 if (f)
6748 f->left_pos = new_x;
6749 f->top_pos = new_y;
6751 goto done;
6754 #ifdef HACK_EDITRES
6755 if (event->xclient.message_type == dpyinfo->Xatom_editres)
6757 f = any;
6758 if (f)
6759 _XEditResCheckMessages (f->output_data.x->widget,
6760 NULL, (XEvent *) event, NULL);
6761 goto done;
6763 #endif /* HACK_EDITRES */
6765 if (event->xclient.message_type == dpyinfo->Xatom_DONE
6766 || event->xclient.message_type == dpyinfo->Xatom_PAGE)
6768 /* Ghostview job completed. Kill it. We could
6769 reply with "Next" if we received "Page", but we
6770 currently never do because we are interested in
6771 images, only, which should have 1 page. */
6772 Pixmap pixmap = (Pixmap) event->xclient.data.l[1];
6773 f = x_window_to_frame (dpyinfo, event->xclient.window);
6774 if (!f)
6775 goto OTHER;
6776 x_kill_gs_process (pixmap, f);
6777 expose_frame (f, 0, 0, 0, 0);
6778 goto done;
6781 #ifdef USE_TOOLKIT_SCROLL_BARS
6782 /* Scroll bar callbacks send a ClientMessage from which
6783 we construct an input_event. */
6784 if (event->xclient.message_type == dpyinfo->Xatom_Scrollbar)
6786 x_scroll_bar_to_input_event (event, &inev.ie);
6787 *finish = X_EVENT_GOTO_OUT;
6788 goto done;
6790 else if (event->xclient.message_type == dpyinfo->Xatom_Horizontal_Scrollbar)
6792 x_horizontal_scroll_bar_to_input_event (event, &inev.ie);
6793 *finish = X_EVENT_GOTO_OUT;
6794 goto done;
6796 #endif /* USE_TOOLKIT_SCROLL_BARS */
6798 /* XEmbed messages from the embedder (if any). */
6799 if (event->xclient.message_type == dpyinfo->Xatom_XEMBED)
6801 enum xembed_message msg = event->xclient.data.l[1];
6802 if (msg == XEMBED_FOCUS_IN || msg == XEMBED_FOCUS_OUT)
6803 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
6805 *finish = X_EVENT_GOTO_OUT;
6806 goto done;
6809 xft_settings_event (dpyinfo, event);
6811 f = any;
6812 if (!f)
6813 goto OTHER;
6814 if (x_handle_dnd_message (f, &event->xclient, dpyinfo, &inev.ie))
6815 *finish = X_EVENT_DROP;
6817 break;
6819 case SelectionNotify:
6820 x_display_set_last_user_time (dpyinfo, event->xselection.time);
6821 #ifdef USE_X_TOOLKIT
6822 if (! x_window_to_frame (dpyinfo, event->xselection.requestor))
6823 goto OTHER;
6824 #endif /* not USE_X_TOOLKIT */
6825 x_handle_selection_notify (&event->xselection);
6826 break;
6828 case SelectionClear: /* Someone has grabbed ownership. */
6829 x_display_set_last_user_time (dpyinfo, event->xselectionclear.time);
6830 #ifdef USE_X_TOOLKIT
6831 if (! x_window_to_frame (dpyinfo, event->xselectionclear.window))
6832 goto OTHER;
6833 #endif /* USE_X_TOOLKIT */
6835 const XSelectionClearEvent *eventp = &event->xselectionclear;
6837 inev.ie.kind = SELECTION_CLEAR_EVENT;
6838 SELECTION_EVENT_DPYINFO (&inev.sie) = dpyinfo;
6839 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
6840 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
6842 break;
6844 case SelectionRequest: /* Someone wants our selection. */
6845 x_display_set_last_user_time (dpyinfo, event->xselectionrequest.time);
6846 #ifdef USE_X_TOOLKIT
6847 if (!x_window_to_frame (dpyinfo, event->xselectionrequest.owner))
6848 goto OTHER;
6849 #endif /* USE_X_TOOLKIT */
6851 const XSelectionRequestEvent *eventp = &event->xselectionrequest;
6853 inev.ie.kind = SELECTION_REQUEST_EVENT;
6854 SELECTION_EVENT_DPYINFO (&inev.sie) = dpyinfo;
6855 SELECTION_EVENT_REQUESTOR (&inev.sie) = eventp->requestor;
6856 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
6857 SELECTION_EVENT_TARGET (&inev.sie) = eventp->target;
6858 SELECTION_EVENT_PROPERTY (&inev.sie) = eventp->property;
6859 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
6861 break;
6863 case PropertyNotify:
6864 x_display_set_last_user_time (dpyinfo, event->xproperty.time);
6865 f = x_top_window_to_frame (dpyinfo, event->xproperty.window);
6866 if (f && event->xproperty.atom == dpyinfo->Xatom_net_wm_state)
6868 bool not_hidden = x_handle_net_wm_state (f, &event->xproperty);
6869 if (not_hidden && FRAME_ICONIFIED_P (f))
6871 /* Gnome shell does not iconify us when C-z is pressed.
6872 It hides the frame. So if our state says we aren't
6873 hidden anymore, treat it as deiconified. */
6874 SET_FRAME_VISIBLE (f, 1);
6875 SET_FRAME_ICONIFIED (f, false);
6876 f->output_data.x->has_been_visible = true;
6877 inev.ie.kind = DEICONIFY_EVENT;
6878 XSETFRAME (inev.ie.frame_or_window, f);
6880 else if (! not_hidden && ! FRAME_ICONIFIED_P (f))
6882 SET_FRAME_VISIBLE (f, 0);
6883 SET_FRAME_ICONIFIED (f, true);
6884 inev.ie.kind = ICONIFY_EVENT;
6885 XSETFRAME (inev.ie.frame_or_window, f);
6889 x_handle_property_notify (&event->xproperty);
6890 xft_settings_event (dpyinfo, event);
6891 goto OTHER;
6893 case ReparentNotify:
6894 f = x_top_window_to_frame (dpyinfo, event->xreparent.window);
6895 if (f)
6897 f->output_data.x->parent_desc = event->xreparent.parent;
6898 x_real_positions (f, &f->left_pos, &f->top_pos);
6900 /* Perhaps reparented due to a WM restart. Reset this. */
6901 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_UNKNOWN;
6902 FRAME_DISPLAY_INFO (f)->net_supported_window = 0;
6904 x_set_frame_alpha (f);
6906 goto OTHER;
6908 case Expose:
6909 f = x_window_to_frame (dpyinfo, event->xexpose.window);
6910 if (f)
6912 if (!FRAME_VISIBLE_P (f))
6914 SET_FRAME_VISIBLE (f, 1);
6915 SET_FRAME_ICONIFIED (f, false);
6916 f->output_data.x->has_been_visible = true;
6917 SET_FRAME_GARBAGED (f);
6919 else
6921 #ifdef USE_GTK
6922 /* This seems to be needed for GTK 2.6 and later, see
6923 http://debbugs.gnu.org/cgi/bugreport.cgi?bug=15398. */
6924 x_clear_area (event->xexpose.display,
6925 event->xexpose.window,
6926 event->xexpose.x, event->xexpose.y,
6927 event->xexpose.width, event->xexpose.height);
6928 #endif
6929 expose_frame (f, event->xexpose.x, event->xexpose.y,
6930 event->xexpose.width, event->xexpose.height);
6933 else
6935 #ifndef USE_TOOLKIT_SCROLL_BARS
6936 struct scroll_bar *bar;
6937 #endif
6938 #if defined USE_LUCID
6939 /* Submenus of the Lucid menu bar aren't widgets
6940 themselves, so there's no way to dispatch events
6941 to them. Recognize this case separately. */
6943 Widget widget = x_window_to_menu_bar (event->xexpose.window);
6944 if (widget)
6945 xlwmenu_redisplay (widget);
6947 #endif /* USE_LUCID */
6949 #ifdef USE_TOOLKIT_SCROLL_BARS
6950 /* Dispatch event to the widget. */
6951 goto OTHER;
6952 #else /* not USE_TOOLKIT_SCROLL_BARS */
6953 bar = x_window_to_scroll_bar (event->xexpose.display,
6954 event->xexpose.window, 2);
6956 if (bar)
6957 x_scroll_bar_expose (bar, event);
6958 #ifdef USE_X_TOOLKIT
6959 else
6960 goto OTHER;
6961 #endif /* USE_X_TOOLKIT */
6962 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6964 break;
6966 case GraphicsExpose: /* This occurs when an XCopyArea's
6967 source area was obscured or not
6968 available. */
6969 f = x_window_to_frame (dpyinfo, event->xgraphicsexpose.drawable);
6970 if (f)
6971 expose_frame (f, event->xgraphicsexpose.x,
6972 event->xgraphicsexpose.y,
6973 event->xgraphicsexpose.width,
6974 event->xgraphicsexpose.height);
6975 #ifdef USE_X_TOOLKIT
6976 else
6977 goto OTHER;
6978 #endif /* USE_X_TOOLKIT */
6979 break;
6981 case NoExpose: /* This occurs when an XCopyArea's
6982 source area was completely
6983 available. */
6984 break;
6986 case UnmapNotify:
6987 /* Redo the mouse-highlight after the tooltip has gone. */
6988 if (event->xunmap.window == tip_window)
6990 tip_window = 0;
6991 x_redo_mouse_highlight (dpyinfo);
6994 f = x_top_window_to_frame (dpyinfo, event->xunmap.window);
6995 if (f) /* F may no longer exist if
6996 the frame was deleted. */
6998 bool visible = FRAME_VISIBLE_P (f);
6999 /* While a frame is unmapped, display generation is
7000 disabled; you don't want to spend time updating a
7001 display that won't ever be seen. */
7002 SET_FRAME_VISIBLE (f, 0);
7003 /* We can't distinguish, from the event, whether the window
7004 has become iconified or invisible. So assume, if it
7005 was previously visible, than now it is iconified.
7006 But x_make_frame_invisible clears both
7007 the visible flag and the iconified flag;
7008 and that way, we know the window is not iconified now. */
7009 if (visible || FRAME_ICONIFIED_P (f))
7011 SET_FRAME_ICONIFIED (f, true);
7012 inev.ie.kind = ICONIFY_EVENT;
7013 XSETFRAME (inev.ie.frame_or_window, f);
7016 goto OTHER;
7018 case MapNotify:
7019 if (event->xmap.window == tip_window)
7020 /* The tooltip has been drawn already. Avoid
7021 the SET_FRAME_GARBAGED below. */
7022 goto OTHER;
7024 /* We use x_top_window_to_frame because map events can
7025 come for sub-windows and they don't mean that the
7026 frame is visible. */
7027 f = x_top_window_to_frame (dpyinfo, event->xmap.window);
7028 if (f)
7030 bool iconified = FRAME_ICONIFIED_P (f);
7032 /* Check if fullscreen was specified before we where mapped the
7033 first time, i.e. from the command line. */
7034 if (!f->output_data.x->has_been_visible)
7035 x_check_fullscreen (f);
7037 SET_FRAME_VISIBLE (f, 1);
7038 SET_FRAME_ICONIFIED (f, false);
7039 f->output_data.x->has_been_visible = true;
7041 if (iconified)
7043 inev.ie.kind = DEICONIFY_EVENT;
7044 XSETFRAME (inev.ie.frame_or_window, f);
7046 else if (! NILP (Vframe_list) && ! NILP (XCDR (Vframe_list)))
7047 /* Force a redisplay sooner or later to update the
7048 frame titles in case this is the second frame. */
7049 record_asynch_buffer_change ();
7051 #ifdef USE_GTK
7052 xg_frame_resized (f, -1, -1);
7053 #endif
7055 goto OTHER;
7057 case KeyPress:
7059 x_display_set_last_user_time (dpyinfo, event->xkey.time);
7060 ignore_next_mouse_click_timeout = 0;
7062 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
7063 /* Dispatch KeyPress events when in menu. */
7064 if (popup_activated ())
7065 goto OTHER;
7066 #endif
7068 f = any;
7070 #if ! defined (USE_GTK)
7071 /* If mouse-highlight is an integer, input clears out
7072 mouse highlighting. */
7073 if (!hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight)
7074 && (f == 0
7075 || !EQ (f->tool_bar_window, hlinfo->mouse_face_window)))
7077 clear_mouse_face (hlinfo);
7078 hlinfo->mouse_face_hidden = true;
7080 #endif
7082 #if defined USE_MOTIF && defined USE_TOOLKIT_SCROLL_BARS
7083 if (f == 0)
7085 /* Scroll bars consume key events, but we want
7086 the keys to go to the scroll bar's frame. */
7087 Widget widget = XtWindowToWidget (dpyinfo->display,
7088 event->xkey.window);
7089 if (widget && XmIsScrollBar (widget))
7091 widget = XtParent (widget);
7092 f = x_any_window_to_frame (dpyinfo, XtWindow (widget));
7095 #endif /* USE_MOTIF and USE_TOOLKIT_SCROLL_BARS */
7097 if (f != 0)
7099 KeySym keysym, orig_keysym;
7100 /* al%imercury@uunet.uu.net says that making this 81
7101 instead of 80 fixed a bug whereby meta chars made
7102 his Emacs hang.
7104 It seems that some version of XmbLookupString has
7105 a bug of not returning XBufferOverflow in
7106 status_return even if the input is too long to
7107 fit in 81 bytes. So, we must prepare sufficient
7108 bytes for copy_buffer. 513 bytes (256 chars for
7109 two-byte character set) seems to be a fairly good
7110 approximation. -- 2000.8.10 handa@etl.go.jp */
7111 unsigned char copy_buffer[513];
7112 unsigned char *copy_bufptr = copy_buffer;
7113 int copy_bufsiz = sizeof (copy_buffer);
7114 int modifiers;
7115 Lisp_Object coding_system = Qlatin_1;
7116 Lisp_Object c;
7117 /* Event will be modified. */
7118 XKeyEvent xkey = event->xkey;
7120 #ifdef USE_GTK
7121 /* Don't pass keys to GTK. A Tab will shift focus to the
7122 tool bar in GTK 2.4. Keys will still go to menus and
7123 dialogs because in that case popup_activated is nonzero
7124 (see above). */
7125 *finish = X_EVENT_DROP;
7126 #endif
7128 xkey.state |= x_emacs_to_x_modifiers (FRAME_DISPLAY_INFO (f),
7129 extra_keyboard_modifiers);
7130 modifiers = xkey.state;
7132 /* This will have to go some day... */
7134 /* make_lispy_event turns chars into control chars.
7135 Don't do it here because XLookupString is too eager. */
7136 xkey.state &= ~ControlMask;
7137 xkey.state &= ~(dpyinfo->meta_mod_mask
7138 | dpyinfo->super_mod_mask
7139 | dpyinfo->hyper_mod_mask
7140 | dpyinfo->alt_mod_mask);
7142 /* In case Meta is ComposeCharacter,
7143 clear its status. According to Markus Ehrnsperger
7144 Markus.Ehrnsperger@lehrstuhl-bross.physik.uni-muenchen.de
7145 this enables ComposeCharacter to work whether or
7146 not it is combined with Meta. */
7147 if (modifiers & dpyinfo->meta_mod_mask)
7148 memset (&compose_status, 0, sizeof (compose_status));
7150 #ifdef HAVE_X_I18N
7151 if (FRAME_XIC (f))
7153 Status status_return;
7155 coding_system = Vlocale_coding_system;
7156 nbytes = XmbLookupString (FRAME_XIC (f),
7157 &xkey, (char *) copy_bufptr,
7158 copy_bufsiz, &keysym,
7159 &status_return);
7160 if (status_return == XBufferOverflow)
7162 copy_bufsiz = nbytes + 1;
7163 copy_bufptr = alloca (copy_bufsiz);
7164 nbytes = XmbLookupString (FRAME_XIC (f),
7165 &xkey, (char *) copy_bufptr,
7166 copy_bufsiz, &keysym,
7167 &status_return);
7169 /* Xutf8LookupString is a new but already deprecated interface. -stef */
7170 if (status_return == XLookupNone)
7171 break;
7172 else if (status_return == XLookupChars)
7174 keysym = NoSymbol;
7175 modifiers = 0;
7177 else if (status_return != XLookupKeySym
7178 && status_return != XLookupBoth)
7179 emacs_abort ();
7181 else
7182 nbytes = XLookupString (&xkey, (char *) copy_bufptr,
7183 copy_bufsiz, &keysym,
7184 &compose_status);
7185 #else
7186 nbytes = XLookupString (&xkey, (char *) copy_bufptr,
7187 copy_bufsiz, &keysym,
7188 &compose_status);
7189 #endif
7191 /* If not using XIM/XIC, and a compose sequence is in progress,
7192 we break here. Otherwise, chars_matched is always 0. */
7193 if (compose_status.chars_matched > 0 && nbytes == 0)
7194 break;
7196 memset (&compose_status, 0, sizeof (compose_status));
7197 orig_keysym = keysym;
7199 /* Common for all keysym input events. */
7200 XSETFRAME (inev.ie.frame_or_window, f);
7201 inev.ie.modifiers
7202 = x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO (f), modifiers);
7203 inev.ie.timestamp = xkey.time;
7205 /* First deal with keysyms which have defined
7206 translations to characters. */
7207 if (keysym >= 32 && keysym < 128)
7208 /* Avoid explicitly decoding each ASCII character. */
7210 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
7211 inev.ie.code = keysym;
7212 goto done_keysym;
7215 /* Keysyms directly mapped to Unicode characters. */
7216 if (keysym >= 0x01000000 && keysym <= 0x0110FFFF)
7218 if (keysym < 0x01000080)
7219 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
7220 else
7221 inev.ie.kind = MULTIBYTE_CHAR_KEYSTROKE_EVENT;
7222 inev.ie.code = keysym & 0xFFFFFF;
7223 goto done_keysym;
7226 /* Now non-ASCII. */
7227 if (HASH_TABLE_P (Vx_keysym_table)
7228 && (c = Fgethash (make_number (keysym),
7229 Vx_keysym_table,
7230 Qnil),
7231 NATNUMP (c)))
7233 inev.ie.kind = (SINGLE_BYTE_CHAR_P (XFASTINT (c))
7234 ? ASCII_KEYSTROKE_EVENT
7235 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
7236 inev.ie.code = XFASTINT (c);
7237 goto done_keysym;
7240 /* Random non-modifier sorts of keysyms. */
7241 if (((keysym >= XK_BackSpace && keysym <= XK_Escape)
7242 || keysym == XK_Delete
7243 #ifdef XK_ISO_Left_Tab
7244 || (keysym >= XK_ISO_Left_Tab
7245 && keysym <= XK_ISO_Enter)
7246 #endif
7247 || IsCursorKey (keysym) /* 0xff50 <= x < 0xff60 */
7248 || IsMiscFunctionKey (keysym) /* 0xff60 <= x < VARIES */
7249 #ifdef HPUX
7250 /* This recognizes the "extended function
7251 keys". It seems there's no cleaner way.
7252 Test IsModifierKey to avoid handling
7253 mode_switch incorrectly. */
7254 || (XK_Select <= keysym && keysym < XK_KP_Space)
7255 #endif
7256 #ifdef XK_dead_circumflex
7257 || orig_keysym == XK_dead_circumflex
7258 #endif
7259 #ifdef XK_dead_grave
7260 || orig_keysym == XK_dead_grave
7261 #endif
7262 #ifdef XK_dead_tilde
7263 || orig_keysym == XK_dead_tilde
7264 #endif
7265 #ifdef XK_dead_diaeresis
7266 || orig_keysym == XK_dead_diaeresis
7267 #endif
7268 #ifdef XK_dead_macron
7269 || orig_keysym == XK_dead_macron
7270 #endif
7271 #ifdef XK_dead_degree
7272 || orig_keysym == XK_dead_degree
7273 #endif
7274 #ifdef XK_dead_acute
7275 || orig_keysym == XK_dead_acute
7276 #endif
7277 #ifdef XK_dead_cedilla
7278 || orig_keysym == XK_dead_cedilla
7279 #endif
7280 #ifdef XK_dead_breve
7281 || orig_keysym == XK_dead_breve
7282 #endif
7283 #ifdef XK_dead_ogonek
7284 || orig_keysym == XK_dead_ogonek
7285 #endif
7286 #ifdef XK_dead_caron
7287 || orig_keysym == XK_dead_caron
7288 #endif
7289 #ifdef XK_dead_doubleacute
7290 || orig_keysym == XK_dead_doubleacute
7291 #endif
7292 #ifdef XK_dead_abovedot
7293 || orig_keysym == XK_dead_abovedot
7294 #endif
7295 || IsKeypadKey (keysym) /* 0xff80 <= x < 0xffbe */
7296 || IsFunctionKey (keysym) /* 0xffbe <= x < 0xffe1 */
7297 /* Any "vendor-specific" key is ok. */
7298 || (orig_keysym & (1 << 28))
7299 || (keysym != NoSymbol && nbytes == 0))
7300 && ! (IsModifierKey (orig_keysym)
7301 /* The symbols from XK_ISO_Lock
7302 to XK_ISO_Last_Group_Lock
7303 don't have real modifiers but
7304 should be treated similarly to
7305 Mode_switch by Emacs. */
7306 #if defined XK_ISO_Lock && defined XK_ISO_Last_Group_Lock
7307 || (XK_ISO_Lock <= orig_keysym
7308 && orig_keysym <= XK_ISO_Last_Group_Lock)
7309 #endif
7312 STORE_KEYSYM_FOR_DEBUG (keysym);
7313 /* make_lispy_event will convert this to a symbolic
7314 key. */
7315 inev.ie.kind = NON_ASCII_KEYSTROKE_EVENT;
7316 inev.ie.code = keysym;
7317 goto done_keysym;
7320 { /* Raw bytes, not keysym. */
7321 ptrdiff_t i;
7322 int nchars, len;
7324 for (i = 0, nchars = 0; i < nbytes; i++)
7326 if (ASCII_CHAR_P (copy_bufptr[i]))
7327 nchars++;
7328 STORE_KEYSYM_FOR_DEBUG (copy_bufptr[i]);
7331 if (nchars < nbytes)
7333 /* Decode the input data. */
7335 /* The input should be decoded with `coding_system'
7336 which depends on which X*LookupString function
7337 we used just above and the locale. */
7338 setup_coding_system (coding_system, &coding);
7339 coding.src_multibyte = false;
7340 coding.dst_multibyte = true;
7341 /* The input is converted to events, thus we can't
7342 handle composition. Anyway, there's no XIM that
7343 gives us composition information. */
7344 coding.common_flags &= ~CODING_ANNOTATION_MASK;
7346 SAFE_NALLOCA (coding.destination, MAX_MULTIBYTE_LENGTH,
7347 nbytes);
7348 coding.dst_bytes = MAX_MULTIBYTE_LENGTH * nbytes;
7349 coding.mode |= CODING_MODE_LAST_BLOCK;
7350 decode_coding_c_string (&coding, copy_bufptr, nbytes, Qnil);
7351 nbytes = coding.produced;
7352 nchars = coding.produced_char;
7353 copy_bufptr = coding.destination;
7356 /* Convert the input data to a sequence of
7357 character events. */
7358 for (i = 0; i < nbytes; i += len)
7360 int ch;
7361 if (nchars == nbytes)
7362 ch = copy_bufptr[i], len = 1;
7363 else
7364 ch = STRING_CHAR_AND_LENGTH (copy_bufptr + i, len);
7365 inev.ie.kind = (SINGLE_BYTE_CHAR_P (ch)
7366 ? ASCII_KEYSTROKE_EVENT
7367 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
7368 inev.ie.code = ch;
7369 kbd_buffer_store_event_hold (&inev.ie, hold_quit);
7372 count += nchars;
7374 inev.ie.kind = NO_EVENT; /* Already stored above. */
7376 if (keysym == NoSymbol)
7377 break;
7379 /* FIXME: check side effects and remove this. */
7380 ((XEvent *) event)->xkey = xkey;
7382 done_keysym:
7383 #ifdef HAVE_X_I18N
7384 /* Don't dispatch this event since XtDispatchEvent calls
7385 XFilterEvent, and two calls in a row may freeze the
7386 client. */
7387 break;
7388 #else
7389 goto OTHER;
7390 #endif
7392 case KeyRelease:
7393 x_display_set_last_user_time (dpyinfo, event->xkey.time);
7394 #ifdef HAVE_X_I18N
7395 /* Don't dispatch this event since XtDispatchEvent calls
7396 XFilterEvent, and two calls in a row may freeze the
7397 client. */
7398 break;
7399 #else
7400 goto OTHER;
7401 #endif
7403 case EnterNotify:
7404 x_display_set_last_user_time (dpyinfo, event->xcrossing.time);
7405 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
7407 f = any;
7409 if (f && x_mouse_click_focus_ignore_position)
7410 ignore_next_mouse_click_timeout = event->xmotion.time + 200;
7412 /* EnterNotify counts as mouse movement,
7413 so update things that depend on mouse position. */
7414 if (f && !f->output_data.x->hourglass_p)
7415 note_mouse_movement (f, &event->xmotion);
7416 #ifdef USE_GTK
7417 /* We may get an EnterNotify on the buttons in the toolbar. In that
7418 case we moved out of any highlighted area and need to note this. */
7419 if (!f && dpyinfo->last_mouse_glyph_frame)
7420 note_mouse_movement (dpyinfo->last_mouse_glyph_frame, &event->xmotion);
7421 #endif
7422 goto OTHER;
7424 case FocusIn:
7425 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
7426 goto OTHER;
7428 case LeaveNotify:
7429 x_display_set_last_user_time (dpyinfo, event->xcrossing.time);
7430 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
7432 f = x_top_window_to_frame (dpyinfo, event->xcrossing.window);
7433 if (f)
7435 if (f == hlinfo->mouse_face_mouse_frame)
7437 /* If we move outside the frame, then we're
7438 certainly no longer on any text in the frame. */
7439 clear_mouse_face (hlinfo);
7440 hlinfo->mouse_face_mouse_frame = 0;
7443 /* Generate a nil HELP_EVENT to cancel a help-echo.
7444 Do it only if there's something to cancel.
7445 Otherwise, the startup message is cleared when
7446 the mouse leaves the frame. */
7447 if (any_help_event_p)
7448 do_help = -1;
7450 #ifdef USE_GTK
7451 /* See comment in EnterNotify above */
7452 else if (dpyinfo->last_mouse_glyph_frame)
7453 note_mouse_movement (dpyinfo->last_mouse_glyph_frame, &event->xmotion);
7454 #endif
7455 goto OTHER;
7457 case FocusOut:
7458 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
7459 goto OTHER;
7461 case MotionNotify:
7463 x_display_set_last_user_time (dpyinfo, event->xmotion.time);
7464 previous_help_echo_string = help_echo_string;
7465 help_echo_string = Qnil;
7467 f = (x_mouse_grabbed (dpyinfo) ? dpyinfo->last_mouse_frame
7468 : x_window_to_frame (dpyinfo, event->xmotion.window));
7470 if (hlinfo->mouse_face_hidden)
7472 hlinfo->mouse_face_hidden = false;
7473 clear_mouse_face (hlinfo);
7476 #ifdef USE_GTK
7477 if (f && xg_event_is_for_scrollbar (f, event))
7478 f = 0;
7479 #endif
7480 if (f)
7483 /* Generate SELECT_WINDOW_EVENTs when needed.
7484 Don't let popup menus influence things (bug#1261). */
7485 if (!NILP (Vmouse_autoselect_window) && !popup_activated ())
7487 static Lisp_Object last_mouse_window;
7488 Lisp_Object window = window_from_coordinates
7489 (f, event->xmotion.x, event->xmotion.y, 0, false);
7491 /* Window will be selected only when it is not selected now and
7492 last mouse movement event was not in it. Minibuffer window
7493 will be selected only when it is active. */
7494 if (WINDOWP (window)
7495 && !EQ (window, last_mouse_window)
7496 && !EQ (window, selected_window)
7497 /* For click-to-focus window managers
7498 create event iff we don't leave the
7499 selected frame. */
7500 && (focus_follows_mouse
7501 || (EQ (XWINDOW (window)->frame,
7502 XWINDOW (selected_window)->frame))))
7504 inev.ie.kind = SELECT_WINDOW_EVENT;
7505 inev.ie.frame_or_window = window;
7507 /* Remember the last window where we saw the mouse. */
7508 last_mouse_window = window;
7510 if (!note_mouse_movement (f, &event->xmotion))
7511 help_echo_string = previous_help_echo_string;
7513 else
7515 #ifndef USE_TOOLKIT_SCROLL_BARS
7516 struct scroll_bar *bar
7517 = x_window_to_scroll_bar (event->xmotion.display,
7518 event->xmotion.window, 2);
7520 if (bar)
7521 x_scroll_bar_note_movement (bar, &event->xmotion);
7522 #endif /* USE_TOOLKIT_SCROLL_BARS */
7524 /* If we move outside the frame, then we're
7525 certainly no longer on any text in the frame. */
7526 clear_mouse_face (hlinfo);
7529 /* If the contents of the global variable help_echo_string
7530 has changed, generate a HELP_EVENT. */
7531 if (!NILP (help_echo_string)
7532 || !NILP (previous_help_echo_string))
7533 do_help = 1;
7534 goto OTHER;
7537 case ConfigureNotify:
7538 f = x_top_window_to_frame (dpyinfo, event->xconfigure.window);
7539 #ifdef USE_GTK
7540 if (!f
7541 && (f = any)
7542 && event->xconfigure.window == FRAME_X_WINDOW (f))
7544 xg_frame_resized (f, event->xconfigure.width,
7545 event->xconfigure.height);
7546 f = 0;
7548 #endif
7549 if (f)
7551 x_net_wm_state (f, event->xconfigure.window);
7553 #ifndef USE_X_TOOLKIT
7554 #ifndef USE_GTK
7555 int width = FRAME_PIXEL_TO_TEXT_WIDTH (f, event->xconfigure.width);
7556 int height = FRAME_PIXEL_TO_TEXT_HEIGHT (f, event->xconfigure.height);
7558 /* In the toolkit version, change_frame_size
7559 is called by the code that handles resizing
7560 of the EmacsFrame widget. */
7562 /* Even if the number of character rows and columns has
7563 not changed, the font size may have changed, so we need
7564 to check the pixel dimensions as well. */
7565 if (width != FRAME_TEXT_WIDTH (f)
7566 || height != FRAME_TEXT_HEIGHT (f)
7567 || event->xconfigure.width != FRAME_PIXEL_WIDTH (f)
7568 || event->xconfigure.height != FRAME_PIXEL_HEIGHT (f))
7570 change_frame_size (f, width, height, false, true, false, true);
7571 x_clear_under_internal_border (f);
7572 SET_FRAME_GARBAGED (f);
7573 cancel_mouse_face (f);
7575 #endif /* not USE_GTK */
7576 #endif
7578 #ifdef USE_GTK
7579 /* GTK creates windows but doesn't map them.
7580 Only get real positions when mapped. */
7581 if (FRAME_GTK_OUTER_WIDGET (f)
7582 && gtk_widget_get_mapped (FRAME_GTK_OUTER_WIDGET (f)))
7583 #endif
7584 x_real_positions (f, &f->left_pos, &f->top_pos);
7586 #ifdef HAVE_X_I18N
7587 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMStatusArea))
7588 xic_set_statusarea (f);
7589 #endif
7592 goto OTHER;
7594 case ButtonRelease:
7595 case ButtonPress:
7597 /* If we decide we want to generate an event to be seen
7598 by the rest of Emacs, we put it here. */
7599 bool tool_bar_p = false;
7601 memset (&compose_status, 0, sizeof (compose_status));
7602 dpyinfo->last_mouse_glyph_frame = NULL;
7603 x_display_set_last_user_time (dpyinfo, event->xbutton.time);
7605 f = (x_mouse_grabbed (dpyinfo) ? dpyinfo->last_mouse_frame
7606 : x_window_to_frame (dpyinfo, event->xbutton.window));
7608 #ifdef USE_GTK
7609 if (f && xg_event_is_for_scrollbar (f, event))
7610 f = 0;
7611 #endif
7612 if (f)
7614 #if ! defined (USE_GTK)
7615 /* Is this in the tool-bar? */
7616 if (WINDOWP (f->tool_bar_window)
7617 && WINDOW_TOTAL_LINES (XWINDOW (f->tool_bar_window)))
7619 Lisp_Object window;
7620 int x = event->xbutton.x;
7621 int y = event->xbutton.y;
7623 window = window_from_coordinates (f, x, y, 0, true);
7624 tool_bar_p = EQ (window, f->tool_bar_window);
7626 if (tool_bar_p && event->xbutton.button < 4)
7627 handle_tool_bar_click
7628 (f, x, y, event->xbutton.type == ButtonPress,
7629 x_x_to_emacs_modifiers (dpyinfo, event->xbutton.state));
7631 #endif /* !USE_GTK */
7633 if (!tool_bar_p)
7634 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
7635 if (! popup_activated ())
7636 #endif
7638 if (ignore_next_mouse_click_timeout)
7640 if (event->type == ButtonPress
7641 && event->xbutton.time > ignore_next_mouse_click_timeout)
7643 ignore_next_mouse_click_timeout = 0;
7644 construct_mouse_click (&inev.ie, &event->xbutton, f);
7646 if (event->type == ButtonRelease)
7647 ignore_next_mouse_click_timeout = 0;
7649 else
7650 construct_mouse_click (&inev.ie, &event->xbutton, f);
7652 if (FRAME_X_EMBEDDED_P (f))
7653 xembed_send_message (f, event->xbutton.time,
7654 XEMBED_REQUEST_FOCUS, 0, 0, 0);
7656 else
7658 struct scroll_bar *bar
7659 = x_window_to_scroll_bar (event->xbutton.display,
7660 event->xbutton.window, 2);
7662 #ifdef USE_TOOLKIT_SCROLL_BARS
7663 /* Make the "Ctrl-Mouse-2 splits window" work for toolkit
7664 scroll bars. */
7665 if (bar && event->xbutton.state & ControlMask)
7667 x_scroll_bar_handle_click (bar, event, &inev.ie);
7668 *finish = X_EVENT_DROP;
7670 #else /* not USE_TOOLKIT_SCROLL_BARS */
7671 if (bar)
7672 x_scroll_bar_handle_click (bar, event, &inev.ie);
7673 #endif /* not USE_TOOLKIT_SCROLL_BARS */
7676 if (event->type == ButtonPress)
7678 dpyinfo->grabbed |= (1 << event->xbutton.button);
7679 dpyinfo->last_mouse_frame = f;
7680 #if ! defined (USE_GTK)
7681 if (f && !tool_bar_p)
7682 f->last_tool_bar_item = -1;
7683 #endif /* not USE_GTK */
7685 else
7686 dpyinfo->grabbed &= ~(1 << event->xbutton.button);
7688 /* Ignore any mouse motion that happened before this event;
7689 any subsequent mouse-movement Emacs events should reflect
7690 only motion after the ButtonPress/Release. */
7691 if (f != 0)
7692 f->mouse_moved = false;
7694 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
7695 f = x_menubar_window_to_frame (dpyinfo, event);
7696 /* For a down-event in the menu bar,
7697 don't pass it to Xt right now.
7698 Instead, save it away
7699 and we will pass it to Xt from kbd_buffer_get_event.
7700 That way, we can run some Lisp code first. */
7701 if (! popup_activated ()
7702 #ifdef USE_GTK
7703 /* Gtk+ menus only react to the first three buttons. */
7704 && event->xbutton.button < 3
7705 #endif
7706 && f && event->type == ButtonPress
7707 /* Verify the event is really within the menu bar
7708 and not just sent to it due to grabbing. */
7709 && event->xbutton.x >= 0
7710 && event->xbutton.x < FRAME_PIXEL_WIDTH (f)
7711 && event->xbutton.y >= 0
7712 && event->xbutton.y < FRAME_MENUBAR_HEIGHT (f)
7713 && event->xbutton.same_screen)
7715 if (!f->output_data.x->saved_menu_event)
7716 f->output_data.x->saved_menu_event = xmalloc (sizeof *event);
7717 *f->output_data.x->saved_menu_event = *event;
7718 inev.ie.kind = MENU_BAR_ACTIVATE_EVENT;
7719 XSETFRAME (inev.ie.frame_or_window, f);
7720 *finish = X_EVENT_DROP;
7722 else
7723 goto OTHER;
7724 #endif /* USE_X_TOOLKIT || USE_GTK */
7726 break;
7728 case CirculateNotify:
7729 goto OTHER;
7731 case CirculateRequest:
7732 goto OTHER;
7734 case VisibilityNotify:
7735 goto OTHER;
7737 case MappingNotify:
7738 /* Someone has changed the keyboard mapping - update the
7739 local cache. */
7740 switch (event->xmapping.request)
7742 case MappingModifier:
7743 x_find_modifier_meanings (dpyinfo);
7744 /* This is meant to fall through. */
7745 case MappingKeyboard:
7746 XRefreshKeyboardMapping ((XMappingEvent *) &event->xmapping);
7748 goto OTHER;
7750 case DestroyNotify:
7751 xft_settings_event (dpyinfo, event);
7752 break;
7754 default:
7755 OTHER:
7756 #ifdef USE_X_TOOLKIT
7757 block_input ();
7758 if (*finish != X_EVENT_DROP)
7759 XtDispatchEvent ((XEvent *) event);
7760 unblock_input ();
7761 #endif /* USE_X_TOOLKIT */
7762 break;
7765 done:
7766 if (inev.ie.kind != NO_EVENT)
7768 kbd_buffer_store_event_hold (&inev.ie, hold_quit);
7769 count++;
7772 if (do_help
7773 && !(hold_quit && hold_quit->kind != NO_EVENT))
7775 Lisp_Object frame;
7777 if (f)
7778 XSETFRAME (frame, f);
7779 else
7780 frame = Qnil;
7782 if (do_help > 0)
7784 any_help_event_p = true;
7785 gen_help_event (help_echo_string, frame, help_echo_window,
7786 help_echo_object, help_echo_pos);
7788 else
7790 help_echo_string = Qnil;
7791 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
7793 count++;
7796 SAFE_FREE ();
7797 return count;
7800 /* Handles the XEvent EVENT on display DISPLAY.
7801 This is used for event loops outside the normal event handling,
7802 i.e. looping while a popup menu or a dialog is posted.
7804 Returns the value handle_one_xevent sets in the finish argument. */
7806 x_dispatch_event (XEvent *event, Display *display)
7808 struct x_display_info *dpyinfo;
7809 int finish = X_EVENT_NORMAL;
7811 dpyinfo = x_display_info_for_display (display);
7813 if (dpyinfo)
7814 handle_one_xevent (dpyinfo, event, &finish, 0);
7816 return finish;
7819 /* Read events coming from the X server.
7820 Return as soon as there are no more events to be read.
7822 Return the number of characters stored into the buffer,
7823 thus pretending to be `read' (except the characters we store
7824 in the keyboard buffer can be multibyte, so are not necessarily
7825 C chars). */
7827 static int
7828 XTread_socket (struct terminal *terminal, struct input_event *hold_quit)
7830 int count = 0;
7831 bool event_found = false;
7832 struct x_display_info *dpyinfo = terminal->display_info.x;
7834 block_input ();
7836 /* For debugging, this gives a way to fake an I/O error. */
7837 if (dpyinfo == XTread_socket_fake_io_error)
7839 XTread_socket_fake_io_error = 0;
7840 x_io_error_quitter (dpyinfo->display);
7843 #ifndef USE_GTK
7844 while (XPending (dpyinfo->display))
7846 int finish;
7847 XEvent event;
7849 XNextEvent (dpyinfo->display, &event);
7851 #ifdef HAVE_X_I18N
7852 /* Filter events for the current X input method. */
7853 if (x_filter_event (dpyinfo, &event))
7854 continue;
7855 #endif
7856 event_found = true;
7858 count += handle_one_xevent (dpyinfo, &event, &finish, hold_quit);
7860 if (finish == X_EVENT_GOTO_OUT)
7861 break;
7864 #else /* USE_GTK */
7866 /* For GTK we must use the GTK event loop. But XEvents gets passed
7867 to our filter function above, and then to the big event switch.
7868 We use a bunch of globals to communicate with our filter function,
7869 that is kind of ugly, but it works.
7871 There is no way to do one display at the time, GTK just does events
7872 from all displays. */
7874 while (gtk_events_pending ())
7876 current_count = count;
7877 current_hold_quit = hold_quit;
7879 gtk_main_iteration ();
7881 count = current_count;
7882 current_count = -1;
7883 current_hold_quit = 0;
7885 if (current_finish == X_EVENT_GOTO_OUT)
7886 break;
7888 #endif /* USE_GTK */
7890 /* On some systems, an X bug causes Emacs to get no more events
7891 when the window is destroyed. Detect that. (1994.) */
7892 if (! event_found)
7894 /* Emacs and the X Server eats up CPU time if XNoOp is done every time.
7895 One XNOOP in 100 loops will make Emacs terminate.
7896 B. Bretthauer, 1994 */
7897 x_noop_count++;
7898 if (x_noop_count >= 100)
7900 x_noop_count=0;
7902 if (next_noop_dpyinfo == 0)
7903 next_noop_dpyinfo = x_display_list;
7905 XNoOp (next_noop_dpyinfo->display);
7907 /* Each time we get here, cycle through the displays now open. */
7908 next_noop_dpyinfo = next_noop_dpyinfo->next;
7912 /* If the focus was just given to an auto-raising frame,
7913 raise it now. FIXME: handle more than one such frame. */
7914 if (dpyinfo->x_pending_autoraise_frame)
7916 x_raise_frame (dpyinfo->x_pending_autoraise_frame);
7917 dpyinfo->x_pending_autoraise_frame = NULL;
7920 unblock_input ();
7922 return count;
7928 /***********************************************************************
7929 Text Cursor
7930 ***********************************************************************/
7932 /* Set clipping for output in glyph row ROW. W is the window in which
7933 we operate. GC is the graphics context to set clipping in.
7935 ROW may be a text row or, e.g., a mode line. Text rows must be
7936 clipped to the interior of the window dedicated to text display,
7937 mode lines must be clipped to the whole window. */
7939 static void
7940 x_clip_to_row (struct window *w, struct glyph_row *row,
7941 enum glyph_row_area area, GC gc)
7943 struct frame *f = XFRAME (WINDOW_FRAME (w));
7944 XRectangle clip_rect;
7945 int window_x, window_y, window_width;
7947 window_box (w, area, &window_x, &window_y, &window_width, 0);
7949 clip_rect.x = window_x;
7950 clip_rect.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
7951 clip_rect.y = max (clip_rect.y, window_y);
7952 clip_rect.width = window_width;
7953 clip_rect.height = row->visible_height;
7955 XSetClipRectangles (FRAME_X_DISPLAY (f), gc, 0, 0, &clip_rect, 1, Unsorted);
7959 /* Draw a hollow box cursor on window W in glyph row ROW. */
7961 static void
7962 x_draw_hollow_cursor (struct window *w, struct glyph_row *row)
7964 struct frame *f = XFRAME (WINDOW_FRAME (w));
7965 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
7966 Display *dpy = FRAME_X_DISPLAY (f);
7967 int x, y, wd, h;
7968 XGCValues xgcv;
7969 struct glyph *cursor_glyph;
7970 GC gc;
7972 /* Get the glyph the cursor is on. If we can't tell because
7973 the current matrix is invalid or such, give up. */
7974 cursor_glyph = get_phys_cursor_glyph (w);
7975 if (cursor_glyph == NULL)
7976 return;
7978 /* Compute frame-relative coordinates for phys cursor. */
7979 get_phys_cursor_geometry (w, row, cursor_glyph, &x, &y, &h);
7980 wd = w->phys_cursor_width - 1;
7982 /* The foreground of cursor_gc is typically the same as the normal
7983 background color, which can cause the cursor box to be invisible. */
7984 xgcv.foreground = f->output_data.x->cursor_pixel;
7985 if (dpyinfo->scratch_cursor_gc)
7986 XChangeGC (dpy, dpyinfo->scratch_cursor_gc, GCForeground, &xgcv);
7987 else
7988 dpyinfo->scratch_cursor_gc = XCreateGC (dpy, FRAME_X_WINDOW (f),
7989 GCForeground, &xgcv);
7990 gc = dpyinfo->scratch_cursor_gc;
7992 /* When on R2L character, show cursor at the right edge of the
7993 glyph, unless the cursor box is as wide as the glyph or wider
7994 (the latter happens when x-stretch-cursor is non-nil). */
7995 if ((cursor_glyph->resolved_level & 1) != 0
7996 && cursor_glyph->pixel_width > wd)
7998 x += cursor_glyph->pixel_width - wd;
7999 if (wd > 0)
8000 wd -= 1;
8002 /* Set clipping, draw the rectangle, and reset clipping again. */
8003 x_clip_to_row (w, row, TEXT_AREA, gc);
8004 XDrawRectangle (dpy, FRAME_X_WINDOW (f), gc, x, y, wd, h - 1);
8005 XSetClipMask (dpy, gc, None);
8009 /* Draw a bar cursor on window W in glyph row ROW.
8011 Implementation note: One would like to draw a bar cursor with an
8012 angle equal to the one given by the font property XA_ITALIC_ANGLE.
8013 Unfortunately, I didn't find a font yet that has this property set.
8014 --gerd. */
8016 static void
8017 x_draw_bar_cursor (struct window *w, struct glyph_row *row, int width, enum text_cursor_kinds kind)
8019 struct frame *f = XFRAME (w->frame);
8020 struct glyph *cursor_glyph;
8022 /* If cursor is out of bounds, don't draw garbage. This can happen
8023 in mini-buffer windows when switching between echo area glyphs
8024 and mini-buffer. */
8025 cursor_glyph = get_phys_cursor_glyph (w);
8026 if (cursor_glyph == NULL)
8027 return;
8029 #ifdef HAVE_XWIDGETS
8030 if (cursor_glyph->type == XWIDGET_GLYPH){
8031 return; //experimental avoidance of cursor on xwidget
8033 #endif
8034 /* If on an image, draw like a normal cursor. That's usually better
8035 visible than drawing a bar, esp. if the image is large so that
8036 the bar might not be in the window. */
8037 if (cursor_glyph->type == IMAGE_GLYPH)
8039 struct glyph_row *r;
8040 r = MATRIX_ROW (w->current_matrix, w->phys_cursor.vpos);
8041 draw_phys_cursor_glyph (w, r, DRAW_CURSOR);
8043 else
8045 Display *dpy = FRAME_X_DISPLAY (f);
8046 Window window = FRAME_X_WINDOW (f);
8047 GC gc = FRAME_DISPLAY_INFO (f)->scratch_cursor_gc;
8048 unsigned long mask = GCForeground | GCBackground | GCGraphicsExposures;
8049 struct face *face = FACE_FROM_ID (f, cursor_glyph->face_id);
8050 XGCValues xgcv;
8052 /* If the glyph's background equals the color we normally draw
8053 the bars cursor in, the bar cursor in its normal color is
8054 invisible. Use the glyph's foreground color instead in this
8055 case, on the assumption that the glyph's colors are chosen so
8056 that the glyph is legible. */
8057 if (face->background == f->output_data.x->cursor_pixel)
8058 xgcv.background = xgcv.foreground = face->foreground;
8059 else
8060 xgcv.background = xgcv.foreground = f->output_data.x->cursor_pixel;
8061 xgcv.graphics_exposures = False;
8063 if (gc)
8064 XChangeGC (dpy, gc, mask, &xgcv);
8065 else
8067 gc = XCreateGC (dpy, window, mask, &xgcv);
8068 FRAME_DISPLAY_INFO (f)->scratch_cursor_gc = gc;
8071 x_clip_to_row (w, row, TEXT_AREA, gc);
8073 if (kind == BAR_CURSOR)
8075 int x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
8077 if (width < 0)
8078 width = FRAME_CURSOR_WIDTH (f);
8079 width = min (cursor_glyph->pixel_width, width);
8081 w->phys_cursor_width = width;
8083 /* If the character under cursor is R2L, draw the bar cursor
8084 on the right of its glyph, rather than on the left. */
8085 if ((cursor_glyph->resolved_level & 1) != 0)
8086 x += cursor_glyph->pixel_width - width;
8088 XFillRectangle (dpy, window, gc, x,
8089 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y),
8090 width, row->height);
8092 else /* HBAR_CURSOR */
8094 int dummy_x, dummy_y, dummy_h;
8095 int x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
8097 if (width < 0)
8098 width = row->height;
8100 width = min (row->height, width);
8102 get_phys_cursor_geometry (w, row, cursor_glyph, &dummy_x,
8103 &dummy_y, &dummy_h);
8105 if ((cursor_glyph->resolved_level & 1) != 0
8106 && cursor_glyph->pixel_width > w->phys_cursor_width - 1)
8107 x += cursor_glyph->pixel_width - w->phys_cursor_width + 1;
8108 XFillRectangle (dpy, window, gc, x,
8109 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y +
8110 row->height - width),
8111 w->phys_cursor_width - 1, width);
8114 XSetClipMask (dpy, gc, None);
8119 /* RIF: Define cursor CURSOR on frame F. */
8121 static void
8122 x_define_frame_cursor (struct frame *f, Cursor cursor)
8124 if (!f->pointer_invisible
8125 && f->output_data.x->current_cursor != cursor)
8126 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), cursor);
8127 f->output_data.x->current_cursor = cursor;
8131 /* RIF: Clear area on frame F. */
8133 static void
8134 x_clear_frame_area (struct frame *f, int x, int y, int width, int height)
8136 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), x, y, width, height);
8137 #ifdef USE_GTK
8138 /* Must queue a redraw, because scroll bars might have been cleared. */
8139 if (FRAME_GTK_WIDGET (f))
8140 gtk_widget_queue_draw (FRAME_GTK_WIDGET (f));
8141 #endif
8145 /* RIF: Draw cursor on window W. */
8147 static void
8148 x_draw_window_cursor (struct window *w, struct glyph_row *glyph_row, int x,
8149 int y, enum text_cursor_kinds cursor_type,
8150 int cursor_width, bool on_p, bool active_p)
8152 struct frame *f = XFRAME (WINDOW_FRAME (w));
8154 if (on_p)
8156 w->phys_cursor_type = cursor_type;
8157 w->phys_cursor_on_p = true;
8159 if (glyph_row->exact_window_width_line_p
8160 && (glyph_row->reversed_p
8161 ? (w->phys_cursor.hpos < 0)
8162 : (w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])))
8164 glyph_row->cursor_in_fringe_p = true;
8165 draw_fringe_bitmap (w, glyph_row, glyph_row->reversed_p);
8167 else
8169 switch (cursor_type)
8171 case HOLLOW_BOX_CURSOR:
8172 x_draw_hollow_cursor (w, glyph_row);
8173 break;
8175 case FILLED_BOX_CURSOR:
8176 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
8177 break;
8179 case BAR_CURSOR:
8180 x_draw_bar_cursor (w, glyph_row, cursor_width, BAR_CURSOR);
8181 break;
8183 case HBAR_CURSOR:
8184 x_draw_bar_cursor (w, glyph_row, cursor_width, HBAR_CURSOR);
8185 break;
8187 case NO_CURSOR:
8188 w->phys_cursor_width = 0;
8189 break;
8191 default:
8192 emacs_abort ();
8196 #ifdef HAVE_X_I18N
8197 if (w == XWINDOW (f->selected_window))
8198 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMPreeditPosition))
8199 xic_set_preeditarea (w, x, y);
8200 #endif
8203 XFlush (FRAME_X_DISPLAY (f));
8207 /* Icons. */
8209 /* Make the x-window of frame F use the gnu icon bitmap. */
8211 bool
8212 x_bitmap_icon (struct frame *f, Lisp_Object file)
8214 ptrdiff_t bitmap_id;
8216 if (FRAME_X_WINDOW (f) == 0)
8217 return true;
8219 /* Free up our existing icon bitmap and mask if any. */
8220 if (f->output_data.x->icon_bitmap > 0)
8221 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
8222 f->output_data.x->icon_bitmap = 0;
8224 if (STRINGP (file))
8226 #ifdef USE_GTK
8227 /* Use gtk_window_set_icon_from_file () if available,
8228 It's not restricted to bitmaps */
8229 if (xg_set_icon (f, file))
8230 return false;
8231 #endif /* USE_GTK */
8232 bitmap_id = x_create_bitmap_from_file (f, file);
8233 x_create_bitmap_mask (f, bitmap_id);
8235 else
8237 /* Create the GNU bitmap and mask if necessary. */
8238 if (FRAME_DISPLAY_INFO (f)->icon_bitmap_id < 0)
8240 ptrdiff_t rc = -1;
8242 #ifdef USE_GTK
8244 if (xg_set_icon (f, xg_default_icon_file)
8245 || xg_set_icon_from_xpm_data (f, gnu_xpm_bits))
8247 FRAME_DISPLAY_INFO (f)->icon_bitmap_id = -2;
8248 return false;
8251 #elif defined (HAVE_XPM) && defined (HAVE_X_WINDOWS)
8253 rc = x_create_bitmap_from_xpm_data (f, gnu_xpm_bits);
8254 if (rc != -1)
8255 FRAME_DISPLAY_INFO (f)->icon_bitmap_id = rc;
8257 #endif
8259 /* If all else fails, use the (black and white) xbm image. */
8260 if (rc == -1)
8262 rc = x_create_bitmap_from_data (f, (char *) gnu_xbm_bits,
8263 gnu_xbm_width, gnu_xbm_height);
8264 if (rc == -1)
8265 return true;
8267 FRAME_DISPLAY_INFO (f)->icon_bitmap_id = rc;
8268 x_create_bitmap_mask (f, FRAME_DISPLAY_INFO (f)->icon_bitmap_id);
8272 /* The first time we create the GNU bitmap and mask,
8273 this increments the ref-count one extra time.
8274 As a result, the GNU bitmap and mask are never freed.
8275 That way, we don't have to worry about allocating it again. */
8276 x_reference_bitmap (f, FRAME_DISPLAY_INFO (f)->icon_bitmap_id);
8278 bitmap_id = FRAME_DISPLAY_INFO (f)->icon_bitmap_id;
8281 x_wm_set_icon_pixmap (f, bitmap_id);
8282 f->output_data.x->icon_bitmap = bitmap_id;
8284 return false;
8288 /* Make the x-window of frame F use a rectangle with text.
8289 Use ICON_NAME as the text. */
8291 bool
8292 x_text_icon (struct frame *f, const char *icon_name)
8294 if (FRAME_X_WINDOW (f) == 0)
8295 return true;
8298 XTextProperty text;
8299 text.value = (unsigned char *) icon_name;
8300 text.encoding = XA_STRING;
8301 text.format = 8;
8302 text.nitems = strlen (icon_name);
8303 XSetWMIconName (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f), &text);
8306 if (f->output_data.x->icon_bitmap > 0)
8307 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
8308 f->output_data.x->icon_bitmap = 0;
8309 x_wm_set_icon_pixmap (f, 0);
8311 return false;
8314 #define X_ERROR_MESSAGE_SIZE 200
8316 /* If non-nil, this should be a string.
8317 It means catch X errors and store the error message in this string.
8319 The reason we use a stack is that x_catch_error/x_uncatch_error can
8320 be called from a signal handler.
8323 struct x_error_message_stack {
8324 char string[X_ERROR_MESSAGE_SIZE];
8325 Display *dpy;
8326 struct x_error_message_stack *prev;
8328 static struct x_error_message_stack *x_error_message;
8330 /* An X error handler which stores the error message in
8331 *x_error_message. This is called from x_error_handler if
8332 x_catch_errors is in effect. */
8334 static void
8335 x_error_catcher (Display *display, XErrorEvent *event)
8337 XGetErrorText (display, event->error_code,
8338 x_error_message->string,
8339 X_ERROR_MESSAGE_SIZE);
8342 /* Begin trapping X errors for display DPY. Actually we trap X errors
8343 for all displays, but DPY should be the display you are actually
8344 operating on.
8346 After calling this function, X protocol errors no longer cause
8347 Emacs to exit; instead, they are recorded in the string
8348 stored in *x_error_message.
8350 Calling x_check_errors signals an Emacs error if an X error has
8351 occurred since the last call to x_catch_errors or x_check_errors.
8353 Calling x_uncatch_errors resumes the normal error handling. */
8355 void
8356 x_catch_errors (Display *dpy)
8358 struct x_error_message_stack *data = xmalloc (sizeof *data);
8360 /* Make sure any errors from previous requests have been dealt with. */
8361 XSync (dpy, False);
8363 data->dpy = dpy;
8364 data->string[0] = 0;
8365 data->prev = x_error_message;
8366 x_error_message = data;
8369 /* Undo the last x_catch_errors call.
8370 DPY should be the display that was passed to x_catch_errors. */
8372 void
8373 x_uncatch_errors (void)
8375 struct x_error_message_stack *tmp;
8377 block_input ();
8379 /* The display may have been closed before this function is called.
8380 Check if it is still open before calling XSync. */
8381 if (x_display_info_for_display (x_error_message->dpy) != 0)
8382 XSync (x_error_message->dpy, False);
8384 tmp = x_error_message;
8385 x_error_message = x_error_message->prev;
8386 xfree (tmp);
8387 unblock_input ();
8390 /* If any X protocol errors have arrived since the last call to
8391 x_catch_errors or x_check_errors, signal an Emacs error using
8392 sprintf (a buffer, FORMAT, the x error message text) as the text. */
8394 void
8395 x_check_errors (Display *dpy, const char *format)
8397 /* Make sure to catch any errors incurred so far. */
8398 XSync (dpy, False);
8400 if (x_error_message->string[0])
8402 char string[X_ERROR_MESSAGE_SIZE];
8403 memcpy (string, x_error_message->string, X_ERROR_MESSAGE_SIZE);
8404 x_uncatch_errors ();
8405 error (format, string);
8409 /* Nonzero if we had any X protocol errors
8410 since we did x_catch_errors on DPY. */
8412 bool
8413 x_had_errors_p (Display *dpy)
8415 /* Make sure to catch any errors incurred so far. */
8416 XSync (dpy, False);
8418 return x_error_message->string[0] != 0;
8421 /* Forget about any errors we have had, since we did x_catch_errors on DPY. */
8423 void
8424 x_clear_errors (Display *dpy)
8426 x_error_message->string[0] = 0;
8429 #if false
8430 /* See comment in unwind_to_catch why calling this is a bad
8431 * idea. --lorentey */
8432 /* Close off all unclosed x_catch_errors calls. */
8434 void
8435 x_fully_uncatch_errors (void)
8437 while (x_error_message)
8438 x_uncatch_errors ();
8440 #endif
8442 #if false
8443 static unsigned int x_wire_count;
8444 x_trace_wire (void)
8446 fprintf (stderr, "Lib call: %d\n", ++x_wire_count);
8448 #endif
8451 /************************************************************************
8452 Handling X errors
8453 ************************************************************************/
8455 /* Error message passed to x_connection_closed. */
8457 static char *error_msg;
8459 /* Handle the loss of connection to display DPY. ERROR_MESSAGE is
8460 the text of an error message that lead to the connection loss. */
8462 static void
8463 x_connection_closed (Display *dpy, const char *error_message)
8465 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
8466 Lisp_Object frame, tail;
8467 ptrdiff_t idx = SPECPDL_INDEX ();
8469 error_msg = alloca (strlen (error_message) + 1);
8470 strcpy (error_msg, error_message);
8472 /* Inhibit redisplay while frames are being deleted. */
8473 specbind (Qinhibit_redisplay, Qt);
8475 if (dpyinfo)
8477 /* Protect display from being closed when we delete the last
8478 frame on it. */
8479 dpyinfo->reference_count++;
8480 dpyinfo->terminal->reference_count++;
8483 /* First delete frames whose mini-buffers are on frames
8484 that are on the dead display. */
8485 FOR_EACH_FRAME (tail, frame)
8487 Lisp_Object minibuf_frame;
8488 minibuf_frame
8489 = WINDOW_FRAME (XWINDOW (FRAME_MINIBUF_WINDOW (XFRAME (frame))));
8490 if (FRAME_X_P (XFRAME (frame))
8491 && FRAME_X_P (XFRAME (minibuf_frame))
8492 && ! EQ (frame, minibuf_frame)
8493 && FRAME_DISPLAY_INFO (XFRAME (minibuf_frame)) == dpyinfo)
8494 delete_frame (frame, Qnoelisp);
8497 /* Now delete all remaining frames on the dead display.
8498 We are now sure none of these is used as the mini-buffer
8499 for another frame that we need to delete. */
8500 FOR_EACH_FRAME (tail, frame)
8501 if (FRAME_X_P (XFRAME (frame))
8502 && FRAME_DISPLAY_INFO (XFRAME (frame)) == dpyinfo)
8504 /* Set this to t so that delete_frame won't get confused
8505 trying to find a replacement. */
8506 kset_default_minibuffer_frame (FRAME_KBOARD (XFRAME (frame)), Qt);
8507 delete_frame (frame, Qnoelisp);
8510 /* If DPYINFO is null, this means we didn't open the display in the
8511 first place, so don't try to close it. */
8512 if (dpyinfo)
8514 /* We can not call XtCloseDisplay here because it calls XSync.
8515 XSync inside the error handler apparently hangs Emacs. On
8516 current Xt versions, this isn't needed either. */
8517 #ifdef USE_GTK
8518 /* A long-standing GTK bug prevents proper disconnect handling
8519 (https://bugzilla.gnome.org/show_bug.cgi?id=85715). Once,
8520 the resulting Glib error message loop filled a user's disk.
8521 To avoid this, kill Emacs unconditionally on disconnect. */
8522 shut_down_emacs (0, Qnil);
8523 fprintf (stderr, "%s\n\
8524 When compiled with GTK, Emacs cannot recover from X disconnects.\n\
8525 This is a GTK bug: https://bugzilla.gnome.org/show_bug.cgi?id=85715\n\
8526 For details, see etc/PROBLEMS.\n",
8527 error_msg);
8528 emacs_abort ();
8529 #endif /* USE_GTK */
8531 /* Indicate that this display is dead. */
8532 dpyinfo->display = 0;
8534 dpyinfo->reference_count--;
8535 dpyinfo->terminal->reference_count--;
8536 if (dpyinfo->reference_count != 0)
8537 /* We have just closed all frames on this display. */
8538 emacs_abort ();
8541 Lisp_Object tmp;
8542 XSETTERMINAL (tmp, dpyinfo->terminal);
8543 Fdelete_terminal (tmp, Qnoelisp);
8547 if (terminal_list == 0)
8549 fprintf (stderr, "%s\n", error_msg);
8550 Fkill_emacs (make_number (70));
8551 /* NOTREACHED */
8554 totally_unblock_input ();
8556 unbind_to (idx, Qnil);
8557 clear_waiting_for_input ();
8559 /* Tell GCC not to suggest attribute 'noreturn' for this function. */
8560 IF_LINT (if (! terminal_list) return; )
8562 /* Here, we absolutely have to use a non-local exit (e.g. signal, throw,
8563 longjmp), because returning from this function would get us back into
8564 Xlib's code which will directly call `exit'. */
8565 error ("%s", error_msg);
8568 /* We specifically use it before defining it, so that gcc doesn't inline it,
8569 otherwise gdb doesn't know how to properly put a breakpoint on it. */
8570 static void x_error_quitter (Display *, XErrorEvent *);
8572 /* This is the first-level handler for X protocol errors.
8573 It calls x_error_quitter or x_error_catcher. */
8575 static int
8576 x_error_handler (Display *display, XErrorEvent *event)
8578 #if defined USE_GTK && defined HAVE_GTK3
8579 if ((event->error_code == BadMatch || event->error_code == BadWindow)
8580 && event->request_code == X_SetInputFocus)
8582 return 0;
8584 #endif
8586 if (x_error_message)
8587 x_error_catcher (display, event);
8588 else
8589 x_error_quitter (display, event);
8590 return 0;
8593 /* This is the usual handler for X protocol errors.
8594 It kills all frames on the display that we got the error for.
8595 If that was the only one, it prints an error message and kills Emacs. */
8597 /* .gdbinit puts a breakpoint here, so make sure it is not inlined. */
8599 /* On older GCC versions, just putting x_error_quitter
8600 after x_error_handler prevents inlining into the former. */
8602 static void NO_INLINE
8603 x_error_quitter (Display *display, XErrorEvent *event)
8605 char buf[256], buf1[356];
8607 /* Ignore BadName errors. They can happen because of fonts
8608 or colors that are not defined. */
8610 if (event->error_code == BadName)
8611 return;
8613 /* Note that there is no real way portable across R3/R4 to get the
8614 original error handler. */
8616 XGetErrorText (display, event->error_code, buf, sizeof (buf));
8617 sprintf (buf1, "X protocol error: %s on protocol request %d",
8618 buf, event->request_code);
8619 x_connection_closed (display, buf1);
8623 /* This is the handler for X IO errors, always.
8624 It kills all frames on the display that we lost touch with.
8625 If that was the only one, it prints an error message and kills Emacs. */
8627 static int
8628 x_io_error_quitter (Display *display)
8630 char buf[256];
8632 snprintf (buf, sizeof buf, "Connection lost to X server `%s'",
8633 DisplayString (display));
8634 x_connection_closed (display, buf);
8635 return 0;
8638 /* Changing the font of the frame. */
8640 /* Give frame F the font FONT-OBJECT as its default font. The return
8641 value is FONT-OBJECT. FONTSET is an ID of the fontset for the
8642 frame. If it is negative, generate a new fontset from
8643 FONT-OBJECT. */
8645 Lisp_Object
8646 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
8648 struct font *font = XFONT_OBJECT (font_object);
8649 int unit;
8651 if (fontset < 0)
8652 fontset = fontset_from_font (font_object);
8653 FRAME_FONTSET (f) = fontset;
8654 if (FRAME_FONT (f) == font)
8655 /* This font is already set in frame F. There's nothing more to
8656 do. */
8657 return font_object;
8659 FRAME_FONT (f) = font;
8660 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
8661 FRAME_COLUMN_WIDTH (f) = font->average_width;
8662 FRAME_LINE_HEIGHT (f) = FONT_HEIGHT (font);
8664 #ifndef USE_X_TOOLKIT
8665 FRAME_MENU_BAR_HEIGHT (f) = FRAME_MENU_BAR_LINES (f) * FRAME_LINE_HEIGHT (f);
8666 #endif
8668 /* Compute character columns occupied by scrollbar.
8670 Don't do things differently for non-toolkit scrollbars
8671 (Bug#17163). */
8672 unit = FRAME_COLUMN_WIDTH (f);
8673 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
8674 FRAME_CONFIG_SCROLL_BAR_COLS (f)
8675 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + unit - 1) / unit;
8676 else
8677 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + unit - 1) / unit;
8679 if (FRAME_X_WINDOW (f) != 0)
8681 /* Don't change the size of a tip frame; there's no point in
8682 doing it because it's done in Fx_show_tip, and it leads to
8683 problems because the tip frame has no widget. */
8684 if (NILP (tip_frame) || XFRAME (tip_frame) != f)
8685 adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
8686 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 3,
8687 false, Qfont);
8690 #ifdef HAVE_X_I18N
8691 if (FRAME_XIC (f)
8692 && (FRAME_XIC_STYLE (f) & (XIMPreeditPosition | XIMStatusArea)))
8694 block_input ();
8695 xic_set_xfontset (f, SSDATA (fontset_ascii (fontset)));
8696 unblock_input ();
8698 #endif
8700 return font_object;
8704 /***********************************************************************
8705 X Input Methods
8706 ***********************************************************************/
8708 #ifdef HAVE_X_I18N
8710 #ifdef HAVE_X11R6
8712 /* XIM destroy callback function, which is called whenever the
8713 connection to input method XIM dies. CLIENT_DATA contains a
8714 pointer to the x_display_info structure corresponding to XIM. */
8716 static void
8717 xim_destroy_callback (XIM xim, XPointer client_data, XPointer call_data)
8719 struct x_display_info *dpyinfo = (struct x_display_info *) client_data;
8720 Lisp_Object frame, tail;
8722 block_input ();
8724 /* No need to call XDestroyIC.. */
8725 FOR_EACH_FRAME (tail, frame)
8727 struct frame *f = XFRAME (frame);
8728 if (FRAME_X_P (f) && FRAME_DISPLAY_INFO (f) == dpyinfo)
8730 FRAME_XIC (f) = NULL;
8731 xic_free_xfontset (f);
8735 /* No need to call XCloseIM. */
8736 dpyinfo->xim = NULL;
8737 XFree (dpyinfo->xim_styles);
8738 unblock_input ();
8741 #endif /* HAVE_X11R6 */
8743 /* Open the connection to the XIM server on display DPYINFO.
8744 RESOURCE_NAME is the resource name Emacs uses. */
8746 static void
8747 xim_open_dpy (struct x_display_info *dpyinfo, char *resource_name)
8749 XIM xim;
8751 #ifdef HAVE_XIM
8752 if (use_xim)
8754 if (dpyinfo->xim)
8755 XCloseIM (dpyinfo->xim);
8756 xim = XOpenIM (dpyinfo->display, dpyinfo->xrdb, resource_name,
8757 emacs_class);
8758 dpyinfo->xim = xim;
8760 if (xim)
8762 #ifdef HAVE_X11R6
8763 XIMCallback destroy;
8764 #endif
8766 /* Get supported styles and XIM values. */
8767 XGetIMValues (xim, XNQueryInputStyle, &dpyinfo->xim_styles, NULL);
8769 #ifdef HAVE_X11R6
8770 destroy.callback = xim_destroy_callback;
8771 destroy.client_data = (XPointer)dpyinfo;
8772 XSetIMValues (xim, XNDestroyCallback, &destroy, NULL);
8773 #endif
8777 else
8778 #endif /* HAVE_XIM */
8779 dpyinfo->xim = NULL;
8783 #ifdef HAVE_X11R6_XIM
8785 /* XIM instantiate callback function, which is called whenever an XIM
8786 server is available. DISPLAY is the display of the XIM.
8787 CLIENT_DATA contains a pointer to an xim_inst_t structure created
8788 when the callback was registered. */
8790 static void
8791 xim_instantiate_callback (Display *display, XPointer client_data, XPointer call_data)
8793 struct xim_inst_t *xim_inst = (struct xim_inst_t *) client_data;
8794 struct x_display_info *dpyinfo = xim_inst->dpyinfo;
8796 /* We don't support multiple XIM connections. */
8797 if (dpyinfo->xim)
8798 return;
8800 xim_open_dpy (dpyinfo, xim_inst->resource_name);
8802 /* Create XIC for the existing frames on the same display, as long
8803 as they have no XIC. */
8804 if (dpyinfo->xim && dpyinfo->reference_count > 0)
8806 Lisp_Object tail, frame;
8808 block_input ();
8809 FOR_EACH_FRAME (tail, frame)
8811 struct frame *f = XFRAME (frame);
8813 if (FRAME_X_P (f)
8814 && FRAME_DISPLAY_INFO (f) == xim_inst->dpyinfo)
8815 if (FRAME_XIC (f) == NULL)
8817 create_frame_xic (f);
8818 if (FRAME_XIC_STYLE (f) & XIMStatusArea)
8819 xic_set_statusarea (f);
8820 if (FRAME_XIC_STYLE (f) & XIMPreeditPosition)
8822 struct window *w = XWINDOW (f->selected_window);
8823 xic_set_preeditarea (w, w->cursor.x, w->cursor.y);
8828 unblock_input ();
8832 #endif /* HAVE_X11R6_XIM */
8835 /* Open a connection to the XIM server on display DPYINFO.
8836 RESOURCE_NAME is the resource name for Emacs. On X11R5, open the
8837 connection only at the first time. On X11R6, open the connection
8838 in the XIM instantiate callback function. */
8840 static void
8841 xim_initialize (struct x_display_info *dpyinfo, char *resource_name)
8843 dpyinfo->xim = NULL;
8844 #ifdef HAVE_XIM
8845 if (use_xim)
8847 #ifdef HAVE_X11R6_XIM
8848 struct xim_inst_t *xim_inst = xmalloc (sizeof *xim_inst);
8849 Bool ret;
8851 dpyinfo->xim_callback_data = xim_inst;
8852 xim_inst->dpyinfo = dpyinfo;
8853 xim_inst->resource_name = xstrdup (resource_name);
8854 ret = XRegisterIMInstantiateCallback
8855 (dpyinfo->display, dpyinfo->xrdb, xim_inst->resource_name,
8856 emacs_class, xim_instantiate_callback,
8857 /* This is XPointer in XFree86 but (XPointer *)
8858 on Tru64, at least, hence the configure test. */
8859 (XRegisterIMInstantiateCallback_arg6) xim_inst);
8860 eassert (ret == True);
8861 #else /* not HAVE_X11R6_XIM */
8862 xim_open_dpy (dpyinfo, resource_name);
8863 #endif /* not HAVE_X11R6_XIM */
8865 #endif /* HAVE_XIM */
8869 /* Close the connection to the XIM server on display DPYINFO. */
8871 static void
8872 xim_close_dpy (struct x_display_info *dpyinfo)
8874 #ifdef HAVE_XIM
8875 if (use_xim)
8877 #ifdef HAVE_X11R6_XIM
8878 struct xim_inst_t *xim_inst = dpyinfo->xim_callback_data;
8880 if (dpyinfo->display)
8882 Bool ret = XUnregisterIMInstantiateCallback
8883 (dpyinfo->display, dpyinfo->xrdb, xim_inst->resource_name,
8884 emacs_class, xim_instantiate_callback,
8885 (XRegisterIMInstantiateCallback_arg6) xim_inst);
8886 eassert (ret == True);
8888 xfree (xim_inst->resource_name);
8889 xfree (xim_inst);
8890 #endif /* HAVE_X11R6_XIM */
8891 if (dpyinfo->display)
8892 XCloseIM (dpyinfo->xim);
8893 dpyinfo->xim = NULL;
8894 XFree (dpyinfo->xim_styles);
8896 #endif /* HAVE_XIM */
8899 #endif /* not HAVE_X11R6_XIM */
8903 /* Calculate the absolute position in frame F
8904 from its current recorded position values and gravity. */
8906 static void
8907 x_calc_absolute_position (struct frame *f)
8909 int flags = f->size_hint_flags;
8911 /* We have nothing to do if the current position
8912 is already for the top-left corner. */
8913 if (! ((flags & XNegative) || (flags & YNegative)))
8914 return;
8916 /* Treat negative positions as relative to the leftmost bottommost
8917 position that fits on the screen. */
8918 if (flags & XNegative)
8919 f->left_pos = x_display_pixel_width (FRAME_DISPLAY_INFO (f))
8920 - FRAME_PIXEL_WIDTH (f) + f->left_pos;
8923 int height = FRAME_PIXEL_HEIGHT (f);
8925 #if defined USE_X_TOOLKIT && defined USE_MOTIF
8926 /* Something is fishy here. When using Motif, starting Emacs with
8927 `-g -0-0', the frame appears too low by a few pixels.
8929 This seems to be so because initially, while Emacs is starting,
8930 the column widget's height and the frame's pixel height are
8931 different. The column widget's height is the right one. In
8932 later invocations, when Emacs is up, the frame's pixel height
8933 is right, though.
8935 It's not obvious where the initial small difference comes from.
8936 2000-12-01, gerd. */
8938 XtVaGetValues (f->output_data.x->column_widget, XtNheight, &height, NULL);
8939 #endif
8941 if (flags & YNegative)
8942 f->top_pos = x_display_pixel_height (FRAME_DISPLAY_INFO (f))
8943 - height + f->top_pos;
8946 /* The left_pos and top_pos
8947 are now relative to the top and left screen edges,
8948 so the flags should correspond. */
8949 f->size_hint_flags &= ~ (XNegative | YNegative);
8952 /* CHANGE_GRAVITY is 1 when calling from Fset_frame_position,
8953 to really change the position, and 0 when calling from
8954 x_make_frame_visible (in that case, XOFF and YOFF are the current
8955 position values). It is -1 when calling from x_set_frame_parameters,
8956 which means, do adjust for borders but don't change the gravity. */
8958 void
8959 x_set_offset (struct frame *f, register int xoff, register int yoff, int change_gravity)
8961 int modified_top, modified_left;
8963 if (change_gravity > 0)
8965 f->top_pos = yoff;
8966 f->left_pos = xoff;
8967 f->size_hint_flags &= ~ (XNegative | YNegative);
8968 if (xoff < 0)
8969 f->size_hint_flags |= XNegative;
8970 if (yoff < 0)
8971 f->size_hint_flags |= YNegative;
8972 f->win_gravity = NorthWestGravity;
8974 x_calc_absolute_position (f);
8976 block_input ();
8977 x_wm_set_size_hint (f, 0, false);
8979 modified_left = f->left_pos;
8980 modified_top = f->top_pos;
8982 if (change_gravity != 0 && FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A)
8984 /* Some WMs (twm, wmaker at least) has an offset that is smaller
8985 than the WM decorations. So we use the calculated offset instead
8986 of the WM decoration sizes here (x/y_pixels_outer_diff). */
8987 modified_left += FRAME_X_OUTPUT (f)->move_offset_left;
8988 modified_top += FRAME_X_OUTPUT (f)->move_offset_top;
8991 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8992 modified_left, modified_top);
8994 x_sync_with_move (f, f->left_pos, f->top_pos,
8995 FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN);
8997 /* change_gravity is non-zero when this function is called from Lisp to
8998 programmatically move a frame. In that case, we call
8999 x_check_expected_move to discover if we have a "Type A" or "Type B"
9000 window manager, and, for a "Type A" window manager, adjust the position
9001 of the frame.
9003 We call x_check_expected_move if a programmatic move occurred, and
9004 either the window manager type (A/B) is unknown or it is Type A but we
9005 need to compute the top/left offset adjustment for this frame. */
9007 if (change_gravity != 0
9008 && (FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN
9009 || (FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A
9010 && (FRAME_X_OUTPUT (f)->move_offset_left == 0
9011 && FRAME_X_OUTPUT (f)->move_offset_top == 0))))
9012 x_check_expected_move (f, modified_left, modified_top);
9014 unblock_input ();
9017 /* Return true if _NET_SUPPORTING_WM_CHECK window exists and _NET_SUPPORTED
9018 on the root window for frame F contains ATOMNAME.
9019 This is how a WM check shall be done according to the Window Manager
9020 Specification/Extended Window Manager Hints at
9021 http://freedesktop.org/wiki/Specifications/wm-spec. */
9023 static bool
9024 wm_supports (struct frame *f, Atom want_atom)
9026 Atom actual_type;
9027 unsigned long actual_size, bytes_remaining;
9028 int i, rc, actual_format;
9029 bool ret;
9030 Window wmcheck_window;
9031 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
9032 Window target_window = dpyinfo->root_window;
9033 int max_len = 65536;
9034 Display *dpy = FRAME_X_DISPLAY (f);
9035 unsigned char *tmp_data = NULL;
9036 Atom target_type = XA_WINDOW;
9038 block_input ();
9040 x_catch_errors (dpy);
9041 rc = XGetWindowProperty (dpy, target_window,
9042 dpyinfo->Xatom_net_supporting_wm_check,
9043 0, max_len, False, target_type,
9044 &actual_type, &actual_format, &actual_size,
9045 &bytes_remaining, &tmp_data);
9047 if (rc != Success || actual_type != XA_WINDOW || x_had_errors_p (dpy))
9049 if (tmp_data) XFree (tmp_data);
9050 x_uncatch_errors ();
9051 unblock_input ();
9052 return false;
9055 wmcheck_window = *(Window *) tmp_data;
9056 XFree (tmp_data);
9058 /* Check if window exists. */
9059 XSelectInput (dpy, wmcheck_window, StructureNotifyMask);
9060 x_sync (f);
9061 if (x_had_errors_p (dpy))
9063 x_uncatch_errors ();
9064 unblock_input ();
9065 return false;
9068 if (dpyinfo->net_supported_window != wmcheck_window)
9070 /* Window changed, reload atoms */
9071 if (dpyinfo->net_supported_atoms != NULL)
9072 XFree (dpyinfo->net_supported_atoms);
9073 dpyinfo->net_supported_atoms = NULL;
9074 dpyinfo->nr_net_supported_atoms = 0;
9075 dpyinfo->net_supported_window = 0;
9077 target_type = XA_ATOM;
9078 tmp_data = NULL;
9079 rc = XGetWindowProperty (dpy, target_window,
9080 dpyinfo->Xatom_net_supported,
9081 0, max_len, False, target_type,
9082 &actual_type, &actual_format, &actual_size,
9083 &bytes_remaining, &tmp_data);
9085 if (rc != Success || actual_type != XA_ATOM || x_had_errors_p (dpy))
9087 if (tmp_data) XFree (tmp_data);
9088 x_uncatch_errors ();
9089 unblock_input ();
9090 return false;
9093 dpyinfo->net_supported_atoms = (Atom *)tmp_data;
9094 dpyinfo->nr_net_supported_atoms = actual_size;
9095 dpyinfo->net_supported_window = wmcheck_window;
9098 ret = false;
9100 for (i = 0; !ret && i < dpyinfo->nr_net_supported_atoms; ++i)
9101 ret = dpyinfo->net_supported_atoms[i] == want_atom;
9103 x_uncatch_errors ();
9104 unblock_input ();
9106 return ret;
9109 static void
9110 set_wm_state (Lisp_Object frame, bool add, Atom atom, Atom value)
9112 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (XFRAME (frame));
9114 x_send_client_event (frame, make_number (0), frame,
9115 dpyinfo->Xatom_net_wm_state,
9116 make_number (32),
9117 /* 1 = add, 0 = remove */
9118 Fcons
9119 (make_number (add),
9120 Fcons
9121 (make_fixnum_or_float (atom),
9122 (value != 0
9123 ? list1 (make_fixnum_or_float (value))
9124 : Qnil))));
9127 void
9128 x_set_sticky (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
9130 Lisp_Object frame;
9131 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
9133 XSETFRAME (frame, f);
9135 set_wm_state (frame, !NILP (new_value),
9136 dpyinfo->Xatom_net_wm_state_sticky, None);
9139 /* Return the current _NET_WM_STATE.
9140 SIZE_STATE is set to one of the FULLSCREEN_* values.
9141 Set *STICKY to the sticky state.
9143 Return true iff we are not hidden. */
9145 static bool
9146 get_current_wm_state (struct frame *f,
9147 Window window,
9148 int *size_state,
9149 bool *sticky)
9151 Atom actual_type;
9152 unsigned long actual_size, bytes_remaining;
9153 int i, rc, actual_format;
9154 bool is_hidden = false;
9155 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
9156 long max_len = 65536;
9157 Display *dpy = FRAME_X_DISPLAY (f);
9158 unsigned char *tmp_data = NULL;
9159 Atom target_type = XA_ATOM;
9161 *sticky = false;
9162 *size_state = FULLSCREEN_NONE;
9164 block_input ();
9165 x_catch_errors (dpy);
9166 rc = XGetWindowProperty (dpy, window, dpyinfo->Xatom_net_wm_state,
9167 0, max_len, False, target_type,
9168 &actual_type, &actual_format, &actual_size,
9169 &bytes_remaining, &tmp_data);
9171 if (rc != Success || actual_type != target_type || x_had_errors_p (dpy))
9173 if (tmp_data) XFree (tmp_data);
9174 x_uncatch_errors ();
9175 unblock_input ();
9176 return !FRAME_ICONIFIED_P (f);
9179 x_uncatch_errors ();
9181 for (i = 0; i < actual_size; ++i)
9183 Atom a = ((Atom*)tmp_data)[i];
9184 if (a == dpyinfo->Xatom_net_wm_state_hidden)
9185 is_hidden = true;
9186 else if (a == dpyinfo->Xatom_net_wm_state_maximized_horz)
9188 if (*size_state == FULLSCREEN_HEIGHT)
9189 *size_state = FULLSCREEN_MAXIMIZED;
9190 else
9191 *size_state = FULLSCREEN_WIDTH;
9193 else if (a == dpyinfo->Xatom_net_wm_state_maximized_vert)
9195 if (*size_state == FULLSCREEN_WIDTH)
9196 *size_state = FULLSCREEN_MAXIMIZED;
9197 else
9198 *size_state = FULLSCREEN_HEIGHT;
9200 else if (a == dpyinfo->Xatom_net_wm_state_fullscreen)
9201 *size_state = FULLSCREEN_BOTH;
9202 else if (a == dpyinfo->Xatom_net_wm_state_sticky)
9203 *sticky = true;
9206 if (tmp_data) XFree (tmp_data);
9207 unblock_input ();
9208 return ! is_hidden;
9211 /* Do fullscreen as specified in extended window manager hints */
9213 static bool
9214 do_ewmh_fullscreen (struct frame *f)
9216 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
9217 bool have_net_atom = wm_supports (f, dpyinfo->Xatom_net_wm_state);
9218 int cur;
9219 bool dummy;
9221 get_current_wm_state (f, FRAME_OUTER_WINDOW (f), &cur, &dummy);
9223 /* Some window managers don't say they support _NET_WM_STATE, but they do say
9224 they support _NET_WM_STATE_FULLSCREEN. Try that also. */
9225 if (!have_net_atom)
9226 have_net_atom = wm_supports (f, dpyinfo->Xatom_net_wm_state_fullscreen);
9228 if (have_net_atom && cur != f->want_fullscreen)
9230 Lisp_Object frame;
9232 XSETFRAME (frame, f);
9234 /* Keep number of calls to set_wm_state as low as possible.
9235 Some window managers, or possible Gtk+, hangs when too many
9236 are sent at once. */
9237 switch (f->want_fullscreen)
9239 case FULLSCREEN_BOTH:
9240 if (cur != FULLSCREEN_BOTH)
9241 set_wm_state (frame, true, dpyinfo->Xatom_net_wm_state_fullscreen,
9242 None);
9243 break;
9244 case FULLSCREEN_WIDTH:
9245 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_HEIGHT
9246 || cur == FULLSCREEN_MAXIMIZED)
9247 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
9248 dpyinfo->Xatom_net_wm_state_maximized_vert);
9249 if (cur != FULLSCREEN_MAXIMIZED)
9250 set_wm_state (frame, true,
9251 dpyinfo->Xatom_net_wm_state_maximized_horz, None);
9252 break;
9253 case FULLSCREEN_HEIGHT:
9254 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_WIDTH
9255 || cur == FULLSCREEN_MAXIMIZED)
9256 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
9257 dpyinfo->Xatom_net_wm_state_maximized_horz);
9258 if (cur != FULLSCREEN_MAXIMIZED)
9259 set_wm_state (frame, true,
9260 dpyinfo->Xatom_net_wm_state_maximized_vert, None);
9261 break;
9262 case FULLSCREEN_MAXIMIZED:
9263 if (cur == FULLSCREEN_BOTH)
9264 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
9265 None);
9266 set_wm_state (frame, true,
9267 dpyinfo->Xatom_net_wm_state_maximized_horz,
9268 dpyinfo->Xatom_net_wm_state_maximized_vert);
9269 break;
9270 case FULLSCREEN_NONE:
9271 if (cur == FULLSCREEN_BOTH)
9272 set_wm_state (frame, false, dpyinfo->Xatom_net_wm_state_fullscreen,
9273 None);
9274 else
9275 set_wm_state (frame, false,
9276 dpyinfo->Xatom_net_wm_state_maximized_horz,
9277 dpyinfo->Xatom_net_wm_state_maximized_vert);
9280 f->want_fullscreen = FULLSCREEN_NONE;
9284 return have_net_atom;
9287 static void
9288 XTfullscreen_hook (struct frame *f)
9290 if (FRAME_VISIBLE_P (f))
9292 block_input ();
9293 x_check_fullscreen (f);
9294 x_sync (f);
9295 unblock_input ();
9300 static bool
9301 x_handle_net_wm_state (struct frame *f, const XPropertyEvent *event)
9303 int value = FULLSCREEN_NONE;
9304 Lisp_Object lval;
9305 bool sticky = false;
9306 bool not_hidden = get_current_wm_state (f, event->window, &value, &sticky);
9308 lval = Qnil;
9309 switch (value)
9311 case FULLSCREEN_WIDTH:
9312 lval = Qfullwidth;
9313 break;
9314 case FULLSCREEN_HEIGHT:
9315 lval = Qfullheight;
9316 break;
9317 case FULLSCREEN_BOTH:
9318 lval = Qfullboth;
9319 break;
9320 case FULLSCREEN_MAXIMIZED:
9321 lval = Qmaximized;
9322 break;
9325 store_frame_param (f, Qfullscreen, lval);
9326 store_frame_param (f, Qsticky, sticky ? Qt : Qnil);
9328 return not_hidden;
9331 /* Check if we need to resize the frame due to a fullscreen request.
9332 If so needed, resize the frame. */
9333 static void
9334 x_check_fullscreen (struct frame *f)
9336 if (do_ewmh_fullscreen (f))
9337 return;
9339 if (f->output_data.x->parent_desc != FRAME_DISPLAY_INFO (f)->root_window)
9340 return; /* Only fullscreen without WM or with EWM hints (above). */
9342 /* Setting fullscreen to nil doesn't do anything. We could save the
9343 last non-fullscreen size and restore it, but it seems like a
9344 lot of work for this unusual case (no window manager running). */
9346 if (f->want_fullscreen != FULLSCREEN_NONE)
9348 int width = FRAME_PIXEL_WIDTH (f), height = FRAME_PIXEL_HEIGHT (f);
9349 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
9351 switch (f->want_fullscreen)
9353 /* No difference between these two when there is no WM */
9354 case FULLSCREEN_BOTH:
9355 case FULLSCREEN_MAXIMIZED:
9356 width = x_display_pixel_width (dpyinfo);
9357 height = x_display_pixel_height (dpyinfo);
9358 break;
9359 case FULLSCREEN_WIDTH:
9360 width = x_display_pixel_width (dpyinfo);
9361 break;
9362 case FULLSCREEN_HEIGHT:
9363 height = x_display_pixel_height (dpyinfo);
9366 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
9367 width, height);
9371 /* This function is called by x_set_offset to determine whether the window
9372 manager interfered with the positioning of the frame. Type A window
9373 managers position the surrounding window manager decorations a small
9374 amount above and left of the user-supplied position. Type B window
9375 managers position the surrounding window manager decorations at the
9376 user-specified position. If we detect a Type A window manager, we
9377 compensate by moving the window right and down by the proper amount. */
9379 static void
9380 x_check_expected_move (struct frame *f, int expected_left, int expected_top)
9382 int current_left = 0, current_top = 0;
9384 /* x_real_positions returns the left and top offsets of the outermost
9385 window manager window around the frame. */
9387 x_real_positions (f, &current_left, &current_top);
9389 if (current_left != expected_left || current_top != expected_top)
9391 /* It's a "Type A" window manager. */
9393 int adjusted_left;
9394 int adjusted_top;
9396 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_A;
9397 FRAME_X_OUTPUT (f)->move_offset_left = expected_left - current_left;
9398 FRAME_X_OUTPUT (f)->move_offset_top = expected_top - current_top;
9400 /* Now fix the mispositioned frame's location. */
9402 adjusted_left = expected_left + FRAME_X_OUTPUT (f)->move_offset_left;
9403 adjusted_top = expected_top + FRAME_X_OUTPUT (f)->move_offset_top;
9405 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
9406 adjusted_left, adjusted_top);
9408 x_sync_with_move (f, expected_left, expected_top, false);
9410 else
9411 /* It's a "Type B" window manager. We don't have to adjust the
9412 frame's position. */
9414 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_B;
9418 /* Wait for XGetGeometry to return up-to-date position information for a
9419 recently-moved frame. Call this immediately after calling XMoveWindow.
9420 If FUZZY is non-zero, then LEFT and TOP are just estimates of where the
9421 frame has been moved to, so we use a fuzzy position comparison instead
9422 of an exact comparison. */
9424 static void
9425 x_sync_with_move (struct frame *f, int left, int top, bool fuzzy)
9427 int count = 0;
9429 while (count++ < 50)
9431 int current_left = 0, current_top = 0;
9433 /* In theory, this call to XSync only needs to happen once, but in
9434 practice, it doesn't seem to work, hence the need for the surrounding
9435 loop. */
9437 XSync (FRAME_X_DISPLAY (f), False);
9438 x_real_positions (f, &current_left, &current_top);
9440 if (fuzzy)
9442 /* The left fuzz-factor is 10 pixels. The top fuzz-factor is 40
9443 pixels. */
9445 if (eabs (current_left - left) <= 10
9446 && eabs (current_top - top) <= 40)
9447 return;
9449 else if (current_left == left && current_top == top)
9450 return;
9453 /* As a last resort, just wait 0.5 seconds and hope that XGetGeometry
9454 will then return up-to-date position info. */
9456 wait_reading_process_output (0, 500000000, 0, false, Qnil, NULL, 0);
9460 /* Wait for an event on frame F matching EVENTTYPE. */
9461 void
9462 x_wait_for_event (struct frame *f, int eventtype)
9464 int level = interrupt_input_blocked;
9466 fd_set fds;
9467 struct timespec tmo, tmo_at, time_now;
9468 int fd = ConnectionNumber (FRAME_X_DISPLAY (f));
9470 f->wait_event_type = eventtype;
9472 /* Set timeout to 0.1 second. Hopefully not noticeable.
9473 Maybe it should be configurable. */
9474 tmo = make_timespec (0, 100 * 1000 * 1000);
9475 tmo_at = timespec_add (current_timespec (), tmo);
9477 while (f->wait_event_type)
9479 pending_signals = true;
9480 totally_unblock_input ();
9481 /* XTread_socket is called after unblock. */
9482 block_input ();
9483 interrupt_input_blocked = level;
9485 FD_ZERO (&fds);
9486 FD_SET (fd, &fds);
9488 time_now = current_timespec ();
9489 if (timespec_cmp (tmo_at, time_now) < 0)
9490 break;
9492 tmo = timespec_sub (tmo_at, time_now);
9493 if (pselect (fd + 1, &fds, NULL, NULL, &tmo, NULL) == 0)
9494 break; /* Timeout */
9497 f->wait_event_type = 0;
9501 /* Change the size of frame F's X window to WIDTH/HEIGHT in the case F
9502 doesn't have a widget. If CHANGE_GRAVITY, change to
9503 top-left-corner window gravity for this size change and subsequent
9504 size changes. Otherwise leave the window gravity unchanged. */
9506 static void
9507 x_set_window_size_1 (struct frame *f, bool change_gravity,
9508 int width, int height, bool pixelwise)
9510 int pixelwidth, pixelheight;
9512 pixelwidth = (pixelwise
9513 ? FRAME_TEXT_TO_PIXEL_WIDTH (f, width)
9514 : FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, width));
9515 pixelheight = ((pixelwise
9516 ? FRAME_TEXT_TO_PIXEL_HEIGHT (f, height)
9517 : FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, height)));
9519 if (change_gravity) f->win_gravity = NorthWestGravity;
9520 x_wm_set_size_hint (f, 0, false);
9521 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
9522 pixelwidth, pixelheight + FRAME_MENUBAR_HEIGHT (f));
9525 /* We've set {FRAME,PIXEL}_{WIDTH,HEIGHT} to the values we hope to
9526 receive in the ConfigureNotify event; if we get what we asked
9527 for, then the event won't cause the screen to become garbaged, so
9528 we have to make sure to do it here. */
9529 SET_FRAME_GARBAGED (f);
9531 /* Now, strictly speaking, we can't be sure that this is accurate,
9532 but the window manager will get around to dealing with the size
9533 change request eventually, and we'll hear how it went when the
9534 ConfigureNotify event gets here.
9536 We could just not bother storing any of this information here,
9537 and let the ConfigureNotify event set everything up, but that
9538 might be kind of confusing to the Lisp code, since size changes
9539 wouldn't be reported in the frame parameters until some random
9540 point in the future when the ConfigureNotify event arrives.
9542 Pass true for DELAY since we can't run Lisp code inside of
9543 a BLOCK_INPUT. */
9545 /* But the ConfigureNotify may in fact never arrive, and then this is
9546 not right if the frame is visible. Instead wait (with timeout)
9547 for the ConfigureNotify. */
9548 if (FRAME_VISIBLE_P (f))
9549 x_wait_for_event (f, ConfigureNotify);
9550 else
9552 change_frame_size (f, width, height, false, true, false, true);
9553 x_sync (f);
9558 /* Call this to change the size of frame F's x-window.
9559 If CHANGE_GRAVITY, change to top-left-corner window gravity
9560 for this size change and subsequent size changes.
9561 Otherwise we leave the window gravity unchanged. */
9563 void
9564 x_set_window_size (struct frame *f, bool change_gravity,
9565 int width, int height, bool pixelwise)
9567 block_input ();
9569 /* The following breaks our calculations. If it's really needed,
9570 think of something else. */
9571 #if false
9572 if (NILP (tip_frame) || XFRAME (tip_frame) != f)
9574 int text_width, text_height;
9576 /* When the frame is maximized/fullscreen or running under for
9577 example Xmonad, x_set_window_size_1 will be a no-op.
9578 In that case, the right thing to do is extend rows/width to
9579 the current frame size. We do that first if x_set_window_size_1
9580 turns out to not be a no-op (there is no way to know).
9581 The size will be adjusted again if the frame gets a
9582 ConfigureNotify event as a result of x_set_window_size. */
9583 int pixelh = FRAME_PIXEL_HEIGHT (f);
9584 #ifdef USE_X_TOOLKIT
9585 /* The menu bar is not part of text lines. The tool bar
9586 is however. */
9587 pixelh -= FRAME_MENUBAR_HEIGHT (f);
9588 #endif
9589 text_width = FRAME_PIXEL_TO_TEXT_WIDTH (f, FRAME_PIXEL_WIDTH (f));
9590 text_height = FRAME_PIXEL_TO_TEXT_HEIGHT (f, pixelh);
9592 change_frame_size (f, text_width, text_height, false, true, false, true);
9594 #endif
9596 #ifdef USE_GTK
9597 if (FRAME_GTK_WIDGET (f))
9598 if (! pixelwise)
9599 xg_frame_set_char_size (f, width * FRAME_COLUMN_WIDTH (f),
9600 height * FRAME_LINE_HEIGHT (f));
9601 else
9602 xg_frame_set_char_size (f, width, height);
9603 else
9604 x_set_window_size_1 (f, change_gravity, width, height, pixelwise);
9605 #else /* not USE_GTK */
9607 x_set_window_size_1 (f, change_gravity, width, height, pixelwise);
9608 x_clear_under_internal_border (f);
9610 #endif /* not USE_GTK */
9612 /* If cursor was outside the new size, mark it as off. */
9613 mark_window_cursors_off (XWINDOW (f->root_window));
9615 /* Clear out any recollection of where the mouse highlighting was,
9616 since it might be in a place that's outside the new frame size.
9617 Actually checking whether it is outside is a pain in the neck,
9618 so don't try--just let the highlighting be done afresh with new size. */
9619 cancel_mouse_face (f);
9621 unblock_input ();
9623 do_pending_window_change (false);
9626 /* Move the mouse to position pixel PIX_X, PIX_Y relative to frame F. */
9628 void
9629 frame_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
9631 block_input ();
9633 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
9634 0, 0, 0, 0, pix_x, pix_y);
9635 unblock_input ();
9638 /* Raise frame F. */
9640 void
9641 x_raise_frame (struct frame *f)
9643 block_input ();
9644 if (FRAME_VISIBLE_P (f))
9645 XRaiseWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
9646 XFlush (FRAME_X_DISPLAY (f));
9647 unblock_input ();
9650 /* Lower frame F. */
9652 static void
9653 x_lower_frame (struct frame *f)
9655 if (FRAME_VISIBLE_P (f))
9657 block_input ();
9658 XLowerWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
9659 XFlush (FRAME_X_DISPLAY (f));
9660 unblock_input ();
9664 /* Request focus with XEmbed */
9666 void
9667 xembed_request_focus (struct frame *f)
9669 /* See XEmbed Protocol Specification at
9670 http://freedesktop.org/wiki/Specifications/xembed-spec */
9671 if (FRAME_VISIBLE_P (f))
9672 xembed_send_message (f, CurrentTime,
9673 XEMBED_REQUEST_FOCUS, 0, 0, 0);
9676 /* Activate frame with Extended Window Manager Hints */
9678 void
9679 x_ewmh_activate_frame (struct frame *f)
9681 /* See Window Manager Specification/Extended Window Manager Hints at
9682 http://freedesktop.org/wiki/Specifications/wm-spec */
9684 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
9686 if (FRAME_VISIBLE_P (f) && wm_supports (f, dpyinfo->Xatom_net_active_window))
9688 Lisp_Object frame;
9689 XSETFRAME (frame, f);
9690 x_send_client_event (frame, make_number (0), frame,
9691 dpyinfo->Xatom_net_active_window,
9692 make_number (32),
9693 list2i (1, dpyinfo->last_user_time));
9697 static void
9698 XTframe_raise_lower (struct frame *f, bool raise_flag)
9700 if (raise_flag)
9701 x_raise_frame (f);
9702 else
9703 x_lower_frame (f);
9706 /* XEmbed implementation. */
9708 #if defined USE_X_TOOLKIT || ! defined USE_GTK
9710 /* XEmbed implementation. */
9712 #define XEMBED_VERSION 0
9714 static void
9715 xembed_set_info (struct frame *f, enum xembed_info flags)
9717 unsigned long data[2];
9718 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
9720 data[0] = XEMBED_VERSION;
9721 data[1] = flags;
9723 XChangeProperty (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
9724 dpyinfo->Xatom_XEMBED_INFO, dpyinfo->Xatom_XEMBED_INFO,
9725 32, PropModeReplace, (unsigned char *) data, 2);
9727 #endif /* defined USE_X_TOOLKIT || ! defined USE_GTK */
9729 static void
9730 xembed_send_message (struct frame *f, Time t, enum xembed_message msg,
9731 long int detail, long int data1, long int data2)
9733 XEvent event;
9735 event.xclient.type = ClientMessage;
9736 event.xclient.window = FRAME_X_OUTPUT (f)->parent_desc;
9737 event.xclient.message_type = FRAME_DISPLAY_INFO (f)->Xatom_XEMBED;
9738 event.xclient.format = 32;
9739 event.xclient.data.l[0] = t;
9740 event.xclient.data.l[1] = msg;
9741 event.xclient.data.l[2] = detail;
9742 event.xclient.data.l[3] = data1;
9743 event.xclient.data.l[4] = data2;
9745 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_OUTPUT (f)->parent_desc,
9746 False, NoEventMask, &event);
9747 XSync (FRAME_X_DISPLAY (f), False);
9750 /* Change of visibility. */
9752 /* This tries to wait until the frame is really visible.
9753 However, if the window manager asks the user where to position
9754 the frame, this will return before the user finishes doing that.
9755 The frame will not actually be visible at that time,
9756 but it will become visible later when the window manager
9757 finishes with it. */
9759 void
9760 x_make_frame_visible (struct frame *f)
9762 int original_top, original_left;
9763 int tries = 0;
9765 block_input ();
9767 x_set_bitmap_icon (f);
9769 if (! FRAME_VISIBLE_P (f))
9771 /* We test FRAME_GARBAGED_P here to make sure we don't
9772 call x_set_offset a second time
9773 if we get to x_make_frame_visible a second time
9774 before the window gets really visible. */
9775 if (! FRAME_ICONIFIED_P (f)
9776 && ! FRAME_X_EMBEDDED_P (f)
9777 && ! f->output_data.x->asked_for_visible)
9778 x_set_offset (f, f->left_pos, f->top_pos, 0);
9780 f->output_data.x->asked_for_visible = true;
9782 if (! EQ (Vx_no_window_manager, Qt))
9783 x_wm_set_window_state (f, NormalState);
9784 #ifdef USE_X_TOOLKIT
9785 if (FRAME_X_EMBEDDED_P (f))
9786 xembed_set_info (f, XEMBED_MAPPED);
9787 else
9789 /* This was XtPopup, but that did nothing for an iconified frame. */
9790 XtMapWidget (f->output_data.x->widget);
9792 #else /* not USE_X_TOOLKIT */
9793 #ifdef USE_GTK
9794 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
9795 gtk_window_deiconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
9796 #else
9797 if (FRAME_X_EMBEDDED_P (f))
9798 xembed_set_info (f, XEMBED_MAPPED);
9799 else
9800 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9801 #endif /* not USE_GTK */
9802 #endif /* not USE_X_TOOLKIT */
9805 XFlush (FRAME_X_DISPLAY (f));
9807 /* Synchronize to ensure Emacs knows the frame is visible
9808 before we do anything else. We do this loop with input not blocked
9809 so that incoming events are handled. */
9811 Lisp_Object frame;
9812 /* This must be before UNBLOCK_INPUT
9813 since events that arrive in response to the actions above
9814 will set it when they are handled. */
9815 bool previously_visible = f->output_data.x->has_been_visible;
9817 original_left = f->left_pos;
9818 original_top = f->top_pos;
9820 /* This must come after we set COUNT. */
9821 unblock_input ();
9823 /* We unblock here so that arriving X events are processed. */
9825 /* Now move the window back to where it was "supposed to be".
9826 But don't do it if the gravity is negative.
9827 When the gravity is negative, this uses a position
9828 that is 3 pixels too low. Perhaps that's really the border width.
9830 Don't do this if the window has never been visible before,
9831 because the window manager may choose the position
9832 and we don't want to override it. */
9834 if (! FRAME_VISIBLE_P (f)
9835 && ! FRAME_ICONIFIED_P (f)
9836 && ! FRAME_X_EMBEDDED_P (f)
9837 && f->win_gravity == NorthWestGravity
9838 && previously_visible)
9840 Drawable rootw;
9841 int x, y;
9842 unsigned int width, height, border, depth;
9844 block_input ();
9846 /* On some window managers (such as FVWM) moving an existing
9847 window, even to the same place, causes the window manager
9848 to introduce an offset. This can cause the window to move
9849 to an unexpected location. Check the geometry (a little
9850 slow here) and then verify that the window is in the right
9851 place. If the window is not in the right place, move it
9852 there, and take the potential window manager hit. */
9853 XGetGeometry (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
9854 &rootw, &x, &y, &width, &height, &border, &depth);
9856 if (original_left != x || original_top != y)
9857 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
9858 original_left, original_top);
9860 unblock_input ();
9863 XSETFRAME (frame, f);
9865 /* Process X events until a MapNotify event has been seen. */
9866 while (!FRAME_VISIBLE_P (f))
9868 /* Force processing of queued events. */
9869 x_sync (f);
9871 /* If on another desktop, the deiconify/map may be ignored and the
9872 frame never becomes visible. XMonad does this.
9873 Prevent an endless loop. */
9874 if (FRAME_ICONIFIED_P (f) && ++tries > 100)
9875 break;
9877 /* This hack is still in use at least for Cygwin. See
9878 http://lists.gnu.org/archive/html/emacs-devel/2013-12/msg00351.html.
9880 Machines that do polling rather than SIGIO have been
9881 observed to go into a busy-wait here. So we'll fake an
9882 alarm signal to let the handler know that there's something
9883 to be read. We used to raise a real alarm, but it seems
9884 that the handler isn't always enabled here. This is
9885 probably a bug. */
9886 if (input_polling_used ())
9888 /* It could be confusing if a real alarm arrives while
9889 processing the fake one. Turn it off and let the
9890 handler reset it. */
9891 int old_poll_suppress_count = poll_suppress_count;
9892 poll_suppress_count = 1;
9893 poll_for_input_1 ();
9894 poll_suppress_count = old_poll_suppress_count;
9897 if (XPending (FRAME_X_DISPLAY (f)))
9899 XEvent xev;
9900 XNextEvent (FRAME_X_DISPLAY (f), &xev);
9901 x_dispatch_event (&xev, FRAME_X_DISPLAY (f));
9907 /* Change from mapped state to withdrawn state. */
9909 /* Make the frame visible (mapped and not iconified). */
9911 void
9912 x_make_frame_invisible (struct frame *f)
9914 Window window;
9916 /* Use the frame's outermost window, not the one we normally draw on. */
9917 window = FRAME_OUTER_WINDOW (f);
9919 /* Don't keep the highlight on an invisible frame. */
9920 if (FRAME_DISPLAY_INFO (f)->x_highlight_frame == f)
9921 FRAME_DISPLAY_INFO (f)->x_highlight_frame = 0;
9923 block_input ();
9925 /* Before unmapping the window, update the WM_SIZE_HINTS property to claim
9926 that the current position of the window is user-specified, rather than
9927 program-specified, so that when the window is mapped again, it will be
9928 placed at the same location, without forcing the user to position it
9929 by hand again (they have already done that once for this window.) */
9930 x_wm_set_size_hint (f, 0, true);
9932 #ifdef USE_GTK
9933 if (FRAME_GTK_OUTER_WIDGET (f))
9934 gtk_widget_hide (FRAME_GTK_OUTER_WIDGET (f));
9935 else
9936 #else
9937 if (FRAME_X_EMBEDDED_P (f))
9938 xembed_set_info (f, 0);
9939 else
9940 #endif
9943 if (! XWithdrawWindow (FRAME_X_DISPLAY (f), window,
9944 DefaultScreen (FRAME_X_DISPLAY (f))))
9946 unblock_input ();
9947 error ("Can't notify window manager of window withdrawal");
9951 /* We can't distinguish this from iconification
9952 just by the event that we get from the server.
9953 So we can't win using the usual strategy of letting
9954 FRAME_SAMPLE_VISIBILITY set this. So do it by hand,
9955 and synchronize with the server to make sure we agree. */
9956 SET_FRAME_VISIBLE (f, 0);
9957 SET_FRAME_ICONIFIED (f, false);
9959 x_sync (f);
9961 unblock_input ();
9964 /* Change window state from mapped to iconified. */
9966 void
9967 x_iconify_frame (struct frame *f)
9969 #ifdef USE_X_TOOLKIT
9970 int result;
9971 #endif
9973 /* Don't keep the highlight on an invisible frame. */
9974 if (FRAME_DISPLAY_INFO (f)->x_highlight_frame == f)
9975 FRAME_DISPLAY_INFO (f)->x_highlight_frame = 0;
9977 if (FRAME_ICONIFIED_P (f))
9978 return;
9980 block_input ();
9982 x_set_bitmap_icon (f);
9984 #if defined (USE_GTK)
9985 if (FRAME_GTK_OUTER_WIDGET (f))
9987 if (! FRAME_VISIBLE_P (f))
9988 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
9990 gtk_window_iconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
9991 SET_FRAME_VISIBLE (f, 0);
9992 SET_FRAME_ICONIFIED (f, true);
9993 unblock_input ();
9994 return;
9996 #endif
9998 #ifdef USE_X_TOOLKIT
10000 if (! FRAME_VISIBLE_P (f))
10002 if (! EQ (Vx_no_window_manager, Qt))
10003 x_wm_set_window_state (f, IconicState);
10004 /* This was XtPopup, but that did nothing for an iconified frame. */
10005 XtMapWidget (f->output_data.x->widget);
10006 /* The server won't give us any event to indicate
10007 that an invisible frame was changed to an icon,
10008 so we have to record it here. */
10009 SET_FRAME_VISIBLE (f, 0);
10010 SET_FRAME_ICONIFIED (f, true);
10011 unblock_input ();
10012 return;
10015 result = XIconifyWindow (FRAME_X_DISPLAY (f),
10016 XtWindow (f->output_data.x->widget),
10017 DefaultScreen (FRAME_X_DISPLAY (f)));
10018 unblock_input ();
10020 if (!result)
10021 error ("Can't notify window manager of iconification");
10023 SET_FRAME_ICONIFIED (f, true);
10024 SET_FRAME_VISIBLE (f, 0);
10026 block_input ();
10027 XFlush (FRAME_X_DISPLAY (f));
10028 unblock_input ();
10029 #else /* not USE_X_TOOLKIT */
10031 /* Make sure the X server knows where the window should be positioned,
10032 in case the user deiconifies with the window manager. */
10033 if (! FRAME_VISIBLE_P (f)
10034 && ! FRAME_ICONIFIED_P (f)
10035 && ! FRAME_X_EMBEDDED_P (f))
10036 x_set_offset (f, f->left_pos, f->top_pos, 0);
10038 /* Since we don't know which revision of X we're running, we'll use both
10039 the X11R3 and X11R4 techniques. I don't know if this is a good idea. */
10041 /* X11R4: send a ClientMessage to the window manager using the
10042 WM_CHANGE_STATE type. */
10044 XEvent msg;
10046 msg.xclient.window = FRAME_X_WINDOW (f);
10047 msg.xclient.type = ClientMessage;
10048 msg.xclient.message_type = FRAME_DISPLAY_INFO (f)->Xatom_wm_change_state;
10049 msg.xclient.format = 32;
10050 msg.xclient.data.l[0] = IconicState;
10052 if (! XSendEvent (FRAME_X_DISPLAY (f),
10053 DefaultRootWindow (FRAME_X_DISPLAY (f)),
10054 False,
10055 SubstructureRedirectMask | SubstructureNotifyMask,
10056 &msg))
10058 unblock_input ();
10059 error ("Can't notify window manager of iconification");
10063 /* X11R3: set the initial_state field of the window manager hints to
10064 IconicState. */
10065 x_wm_set_window_state (f, IconicState);
10067 if (!FRAME_VISIBLE_P (f))
10069 /* If the frame was withdrawn, before, we must map it. */
10070 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
10073 SET_FRAME_ICONIFIED (f, true);
10074 SET_FRAME_VISIBLE (f, 0);
10076 XFlush (FRAME_X_DISPLAY (f));
10077 unblock_input ();
10078 #endif /* not USE_X_TOOLKIT */
10082 /* Free X resources of frame F. */
10084 void
10085 x_free_frame_resources (struct frame *f)
10087 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10088 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
10089 #ifdef USE_X_TOOLKIT
10090 Lisp_Object bar;
10091 struct scroll_bar *b;
10092 #endif
10094 block_input ();
10096 /* If a display connection is dead, don't try sending more
10097 commands to the X server. */
10098 if (dpyinfo->display)
10100 /* Always exit with visible pointer to avoid weird issue
10101 with Xfixes (Bug#17609). */
10102 if (f->pointer_invisible)
10103 FRAME_DISPLAY_INFO (f)->toggle_visible_pointer (f, 0);
10105 /* We must free faces before destroying windows because some
10106 font-driver (e.g. xft) access a window while finishing a
10107 face. */
10108 free_frame_faces (f);
10110 if (f->output_data.x->icon_desc)
10111 XDestroyWindow (FRAME_X_DISPLAY (f), f->output_data.x->icon_desc);
10113 #ifdef USE_X_TOOLKIT
10114 /* Explicitly destroy the scroll bars of the frame. Without
10115 this, we get "BadDrawable" errors from the toolkit later on,
10116 presumably from expose events generated for the disappearing
10117 toolkit scroll bars. */
10118 for (bar = FRAME_SCROLL_BARS (f); !NILP (bar); bar = b->next)
10120 b = XSCROLL_BAR (bar);
10121 x_scroll_bar_remove (b);
10123 #endif
10125 #ifdef HAVE_X_I18N
10126 if (FRAME_XIC (f))
10127 free_frame_xic (f);
10128 #endif
10130 #ifdef USE_X_TOOLKIT
10131 if (f->output_data.x->widget)
10133 XtDestroyWidget (f->output_data.x->widget);
10134 f->output_data.x->widget = NULL;
10136 /* Tooltips don't have widgets, only a simple X window, even if
10137 we are using a toolkit. */
10138 else if (FRAME_X_WINDOW (f))
10139 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
10141 free_frame_menubar (f);
10143 if (f->shell_position)
10144 xfree (f->shell_position);
10145 #else /* !USE_X_TOOLKIT */
10147 #ifdef USE_GTK
10148 xg_free_frame_widgets (f);
10149 #endif /* USE_GTK */
10151 if (FRAME_X_WINDOW (f))
10152 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
10153 #endif /* !USE_X_TOOLKIT */
10155 unload_color (f, FRAME_FOREGROUND_PIXEL (f));
10156 unload_color (f, FRAME_BACKGROUND_PIXEL (f));
10157 unload_color (f, f->output_data.x->cursor_pixel);
10158 unload_color (f, f->output_data.x->cursor_foreground_pixel);
10159 unload_color (f, f->output_data.x->border_pixel);
10160 unload_color (f, f->output_data.x->mouse_pixel);
10162 if (f->output_data.x->scroll_bar_background_pixel != -1)
10163 unload_color (f, f->output_data.x->scroll_bar_background_pixel);
10164 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
10165 unload_color (f, f->output_data.x->scroll_bar_foreground_pixel);
10166 #if defined (USE_LUCID) && defined (USE_TOOLKIT_SCROLL_BARS)
10167 /* Scrollbar shadow colors. */
10168 if (f->output_data.x->scroll_bar_top_shadow_pixel != -1)
10169 unload_color (f, f->output_data.x->scroll_bar_top_shadow_pixel);
10170 if (f->output_data.x->scroll_bar_bottom_shadow_pixel != -1)
10171 unload_color (f, f->output_data.x->scroll_bar_bottom_shadow_pixel);
10172 #endif /* USE_LUCID && USE_TOOLKIT_SCROLL_BARS */
10173 if (f->output_data.x->white_relief.pixel != -1)
10174 unload_color (f, f->output_data.x->white_relief.pixel);
10175 if (f->output_data.x->black_relief.pixel != -1)
10176 unload_color (f, f->output_data.x->black_relief.pixel);
10178 x_free_gcs (f);
10180 /* Free extra GCs allocated by x_setup_relief_colors. */
10181 if (f->output_data.x->white_relief.gc)
10183 XFreeGC (dpyinfo->display, f->output_data.x->white_relief.gc);
10184 f->output_data.x->white_relief.gc = 0;
10186 if (f->output_data.x->black_relief.gc)
10188 XFreeGC (dpyinfo->display, f->output_data.x->black_relief.gc);
10189 f->output_data.x->black_relief.gc = 0;
10192 /* Free cursors. */
10193 if (f->output_data.x->text_cursor != 0)
10194 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->text_cursor);
10195 if (f->output_data.x->nontext_cursor != 0)
10196 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->nontext_cursor);
10197 if (f->output_data.x->modeline_cursor != 0)
10198 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->modeline_cursor);
10199 if (f->output_data.x->hand_cursor != 0)
10200 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->hand_cursor);
10201 if (f->output_data.x->hourglass_cursor != 0)
10202 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->hourglass_cursor);
10203 if (f->output_data.x->horizontal_drag_cursor != 0)
10204 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->horizontal_drag_cursor);
10205 if (f->output_data.x->vertical_drag_cursor != 0)
10206 XFreeCursor (FRAME_X_DISPLAY (f), f->output_data.x->vertical_drag_cursor);
10208 XFlush (FRAME_X_DISPLAY (f));
10211 xfree (f->output_data.x->saved_menu_event);
10212 xfree (f->output_data.x);
10213 f->output_data.x = NULL;
10215 if (f == dpyinfo->x_focus_frame)
10216 dpyinfo->x_focus_frame = 0;
10217 if (f == dpyinfo->x_focus_event_frame)
10218 dpyinfo->x_focus_event_frame = 0;
10219 if (f == dpyinfo->x_highlight_frame)
10220 dpyinfo->x_highlight_frame = 0;
10221 if (f == hlinfo->mouse_face_mouse_frame)
10222 reset_mouse_highlight (hlinfo);
10224 unblock_input ();
10228 /* Destroy the X window of frame F. */
10230 static void
10231 x_destroy_window (struct frame *f)
10233 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
10235 /* If a display connection is dead, don't try sending more
10236 commands to the X server. */
10237 if (dpyinfo->display != 0)
10238 x_free_frame_resources (f);
10240 dpyinfo->reference_count--;
10244 /* Setting window manager hints. */
10246 /* Set the normal size hints for the window manager, for frame F.
10247 FLAGS is the flags word to use--or 0 meaning preserve the flags
10248 that the window now has.
10249 If USER_POSITION, set the USPosition
10250 flag (this is useful when FLAGS is 0).
10251 The GTK version is in gtkutils.c. */
10253 #ifndef USE_GTK
10254 void
10255 x_wm_set_size_hint (struct frame *f, long flags, bool user_position)
10257 XSizeHints size_hints;
10258 Window window = FRAME_OUTER_WINDOW (f);
10260 if (!window)
10261 return;
10263 #ifdef USE_X_TOOLKIT
10264 if (f->output_data.x->widget)
10266 widget_update_wm_size_hints (f->output_data.x->widget);
10267 return;
10269 #endif
10271 /* Setting PMaxSize caused various problems. */
10272 size_hints.flags = PResizeInc | PMinSize /* | PMaxSize */;
10274 size_hints.x = f->left_pos;
10275 size_hints.y = f->top_pos;
10277 size_hints.height = FRAME_PIXEL_HEIGHT (f);
10278 size_hints.width = FRAME_PIXEL_WIDTH (f);
10280 size_hints.width_inc = frame_resize_pixelwise ? 1 : FRAME_COLUMN_WIDTH (f);
10281 size_hints.height_inc = frame_resize_pixelwise ? 1 : FRAME_LINE_HEIGHT (f);
10283 size_hints.max_width = x_display_pixel_width (FRAME_DISPLAY_INFO (f))
10284 - FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
10285 size_hints.max_height = x_display_pixel_height (FRAME_DISPLAY_INFO (f))
10286 - FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
10288 /* Calculate the base and minimum sizes. */
10290 int base_width, base_height;
10291 int min_rows = 0, min_cols = 0;
10293 base_width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
10294 base_height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
10296 if (frame_resize_pixelwise)
10297 /* Needed to prevent a bad protocol error crash when making the
10298 frame size very small. */
10300 min_cols = 2 * min_cols;
10301 min_rows = 2 * min_rows;
10304 /* The window manager uses the base width hints to calculate the
10305 current number of rows and columns in the frame while
10306 resizing; min_width and min_height aren't useful for this
10307 purpose, since they might not give the dimensions for a
10308 zero-row, zero-column frame.
10310 We use the base_width and base_height members if we have
10311 them; otherwise, we set the min_width and min_height members
10312 to the size for a zero x zero frame. */
10314 size_hints.flags |= PBaseSize;
10315 size_hints.base_width = base_width;
10316 size_hints.base_height = base_height + FRAME_MENUBAR_HEIGHT (f);
10317 size_hints.min_width = base_width + min_cols * FRAME_COLUMN_WIDTH (f);
10318 size_hints.min_height = base_height + min_rows * FRAME_LINE_HEIGHT (f);
10321 /* If we don't need the old flags, we don't need the old hint at all. */
10322 if (flags)
10324 size_hints.flags |= flags;
10325 goto no_read;
10329 XSizeHints hints; /* Sometimes I hate X Windows... */
10330 long supplied_return;
10331 int value;
10333 value = XGetWMNormalHints (FRAME_X_DISPLAY (f), window, &hints,
10334 &supplied_return);
10336 if (flags)
10337 size_hints.flags |= flags;
10338 else
10340 if (value == 0)
10341 hints.flags = 0;
10342 if (hints.flags & PSize)
10343 size_hints.flags |= PSize;
10344 if (hints.flags & PPosition)
10345 size_hints.flags |= PPosition;
10346 if (hints.flags & USPosition)
10347 size_hints.flags |= USPosition;
10348 if (hints.flags & USSize)
10349 size_hints.flags |= USSize;
10353 no_read:
10355 #ifdef PWinGravity
10356 size_hints.win_gravity = f->win_gravity;
10357 size_hints.flags |= PWinGravity;
10359 if (user_position)
10361 size_hints.flags &= ~ PPosition;
10362 size_hints.flags |= USPosition;
10364 #endif /* PWinGravity */
10366 XSetWMNormalHints (FRAME_X_DISPLAY (f), window, &size_hints);
10368 #endif /* not USE_GTK */
10370 /* Used for IconicState or NormalState */
10372 static void
10373 x_wm_set_window_state (struct frame *f, int state)
10375 #ifdef USE_X_TOOLKIT
10376 Arg al[1];
10378 XtSetArg (al[0], XtNinitialState, state);
10379 XtSetValues (f->output_data.x->widget, al, 1);
10380 #else /* not USE_X_TOOLKIT */
10381 Window window = FRAME_X_WINDOW (f);
10383 f->output_data.x->wm_hints.flags |= StateHint;
10384 f->output_data.x->wm_hints.initial_state = state;
10386 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
10387 #endif /* not USE_X_TOOLKIT */
10390 static void
10391 x_wm_set_icon_pixmap (struct frame *f, ptrdiff_t pixmap_id)
10393 Pixmap icon_pixmap, icon_mask;
10395 #if !defined USE_X_TOOLKIT && !defined USE_GTK
10396 Window window = FRAME_OUTER_WINDOW (f);
10397 #endif
10399 if (pixmap_id > 0)
10401 icon_pixmap = x_bitmap_pixmap (f, pixmap_id);
10402 f->output_data.x->wm_hints.icon_pixmap = icon_pixmap;
10403 icon_mask = x_bitmap_mask (f, pixmap_id);
10404 f->output_data.x->wm_hints.icon_mask = icon_mask;
10406 else
10408 /* It seems there is no way to turn off use of an icon
10409 pixmap. */
10410 return;
10414 #ifdef USE_GTK
10416 xg_set_frame_icon (f, icon_pixmap, icon_mask);
10417 return;
10420 #elif defined (USE_X_TOOLKIT) /* same as in x_wm_set_window_state. */
10423 Arg al[1];
10424 XtSetArg (al[0], XtNiconPixmap, icon_pixmap);
10425 XtSetValues (f->output_data.x->widget, al, 1);
10426 XtSetArg (al[0], XtNiconMask, icon_mask);
10427 XtSetValues (f->output_data.x->widget, al, 1);
10430 #else /* not USE_X_TOOLKIT && not USE_GTK */
10432 f->output_data.x->wm_hints.flags |= (IconPixmapHint | IconMaskHint);
10433 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
10435 #endif /* not USE_X_TOOLKIT && not USE_GTK */
10438 void
10439 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
10441 Window window = FRAME_OUTER_WINDOW (f);
10443 f->output_data.x->wm_hints.flags |= IconPositionHint;
10444 f->output_data.x->wm_hints.icon_x = icon_x;
10445 f->output_data.x->wm_hints.icon_y = icon_y;
10447 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
10451 /***********************************************************************
10452 Fonts
10453 ***********************************************************************/
10455 #ifdef GLYPH_DEBUG
10457 /* Check that FONT is valid on frame F. It is if it can be found in F's
10458 font table. */
10460 static void
10461 x_check_font (struct frame *f, struct font *font)
10463 eassert (font != NULL && ! NILP (font->props[FONT_TYPE_INDEX]));
10464 if (font->driver->check)
10465 eassert (font->driver->check (f, font) == 0);
10468 #endif /* GLYPH_DEBUG */
10471 /***********************************************************************
10472 Initialization
10473 ***********************************************************************/
10475 #ifdef USE_X_TOOLKIT
10476 static XrmOptionDescRec emacs_options[] = {
10477 {"-geometry", ".geometry", XrmoptionSepArg, NULL},
10478 {"-iconic", ".iconic", XrmoptionNoArg, (XtPointer) "yes"},
10480 {"-internal-border-width", "*EmacsScreen.internalBorderWidth",
10481 XrmoptionSepArg, NULL},
10482 {"-ib", "*EmacsScreen.internalBorderWidth", XrmoptionSepArg, NULL},
10484 {"-T", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
10485 {"-wn", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
10486 {"-title", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
10487 {"-iconname", "*EmacsShell.iconName", XrmoptionSepArg, (XtPointer) NULL},
10488 {"-in", "*EmacsShell.iconName", XrmoptionSepArg, (XtPointer) NULL},
10489 {"-mc", "*pointerColor", XrmoptionSepArg, (XtPointer) NULL},
10490 {"-cr", "*cursorColor", XrmoptionSepArg, (XtPointer) NULL}
10493 /* Whether atimer for Xt timeouts is activated or not. */
10495 static bool x_timeout_atimer_activated_flag;
10497 #endif /* USE_X_TOOLKIT */
10499 static int x_initialized;
10501 /* Test whether two display-name strings agree up to the dot that separates
10502 the screen number from the server number. */
10503 static bool
10504 same_x_server (const char *name1, const char *name2)
10506 bool seen_colon = false;
10507 Lisp_Object sysname = Fsystem_name ();
10508 const char *system_name = SSDATA (sysname);
10509 ptrdiff_t system_name_length = SBYTES (sysname);
10510 ptrdiff_t length_until_period = 0;
10512 while (system_name[length_until_period] != 0
10513 && system_name[length_until_period] != '.')
10514 length_until_period++;
10516 /* Treat `unix' like an empty host name. */
10517 if (! strncmp (name1, "unix:", 5))
10518 name1 += 4;
10519 if (! strncmp (name2, "unix:", 5))
10520 name2 += 4;
10521 /* Treat this host's name like an empty host name. */
10522 if (! strncmp (name1, system_name, system_name_length)
10523 && name1[system_name_length] == ':')
10524 name1 += system_name_length;
10525 if (! strncmp (name2, system_name, system_name_length)
10526 && name2[system_name_length] == ':')
10527 name2 += system_name_length;
10528 /* Treat this host's domainless name like an empty host name. */
10529 if (! strncmp (name1, system_name, length_until_period)
10530 && name1[length_until_period] == ':')
10531 name1 += length_until_period;
10532 if (! strncmp (name2, system_name, length_until_period)
10533 && name2[length_until_period] == ':')
10534 name2 += length_until_period;
10536 for (; *name1 != '\0' && *name1 == *name2; name1++, name2++)
10538 if (*name1 == ':')
10539 seen_colon = true;
10540 if (seen_colon && *name1 == '.')
10541 return true;
10543 return (seen_colon
10544 && (*name1 == '.' || *name1 == '\0')
10545 && (*name2 == '.' || *name2 == '\0'));
10548 /* Count number of set bits in mask and number of bits to shift to
10549 get to the first bit. With MASK 0x7e0, *BITS is set to 6, and *OFFSET
10550 to 5. */
10551 static void
10552 get_bits_and_offset (unsigned long mask, int *bits, int *offset)
10554 int nr = 0;
10555 int off = 0;
10557 while (!(mask & 1))
10559 off++;
10560 mask >>= 1;
10563 while (mask & 1)
10565 nr++;
10566 mask >>= 1;
10569 *offset = off;
10570 *bits = nr;
10573 /* Return true iff display DISPLAY is available for use.
10574 But don't permanently open it, just test its availability. */
10576 bool
10577 x_display_ok (const char *display)
10579 Display *dpy = XOpenDisplay (display);
10580 if (!dpy)
10581 return false;
10582 XCloseDisplay (dpy);
10583 return true;
10586 #ifdef USE_GTK
10587 static void
10588 my_log_handler (const gchar *log_domain, GLogLevelFlags log_level,
10589 const gchar *msg, gpointer user_data)
10591 if (!strstr (msg, "g_set_prgname"))
10592 fprintf (stderr, "%s-WARNING **: %s\n", log_domain, msg);
10594 #endif
10596 /* Create invisible cursor on X display referred by DPYINFO. */
10598 static Cursor
10599 make_invisible_cursor (struct x_display_info *dpyinfo)
10601 Display *dpy = dpyinfo->display;
10602 static char const no_data[] = { 0 };
10603 Pixmap pix;
10604 XColor col;
10605 Cursor c = 0;
10607 x_catch_errors (dpy);
10608 pix = XCreateBitmapFromData (dpy, dpyinfo->root_window, no_data, 1, 1);
10609 if (! x_had_errors_p (dpy) && pix != None)
10611 Cursor pixc;
10612 col.pixel = 0;
10613 col.red = col.green = col.blue = 0;
10614 col.flags = DoRed | DoGreen | DoBlue;
10615 pixc = XCreatePixmapCursor (dpy, pix, pix, &col, &col, 0, 0);
10616 if (! x_had_errors_p (dpy) && pixc != None)
10617 c = pixc;
10618 XFreePixmap (dpy, pix);
10621 x_uncatch_errors ();
10623 return c;
10626 /* True if DPY supports Xfixes extension >= 4. */
10628 static bool
10629 x_probe_xfixes_extension (Display *dpy)
10631 #ifdef HAVE_XFIXES
10632 int major, minor;
10633 return XFixesQueryVersion (dpy, &major, &minor) && major >= 4;
10634 #else
10635 return false;
10636 #endif /* HAVE_XFIXES */
10639 /* Toggle mouse pointer visibility on frame F by using Xfixes functions. */
10641 static void
10642 xfixes_toggle_visible_pointer (struct frame *f, bool invisible)
10644 #ifdef HAVE_XFIXES
10645 if (invisible)
10646 XFixesHideCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
10647 else
10648 XFixesShowCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
10649 f->pointer_invisible = invisible;
10650 #else
10651 emacs_abort ();
10652 #endif /* HAVE_XFIXES */
10655 /* Toggle mouse pointer visibility on frame F by using invisible cursor. */
10657 static void
10658 x_toggle_visible_pointer (struct frame *f, bool invisible)
10660 eassert (FRAME_DISPLAY_INFO (f)->invisible_cursor != 0);
10661 if (invisible)
10662 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
10663 FRAME_DISPLAY_INFO (f)->invisible_cursor);
10664 else
10665 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
10666 f->output_data.x->current_cursor);
10667 f->pointer_invisible = invisible;
10670 /* Setup pointer blanking, prefer Xfixes if available. */
10672 static void
10673 x_setup_pointer_blanking (struct x_display_info *dpyinfo)
10675 /* FIXME: the brave tester should set EMACS_XFIXES because we're suspecting
10676 X server bug, see http://debbugs.gnu.org/cgi/bugreport.cgi?bug=17609. */
10677 if (egetenv ("EMACS_XFIXES") && x_probe_xfixes_extension (dpyinfo->display))
10678 dpyinfo->toggle_visible_pointer = xfixes_toggle_visible_pointer;
10679 else
10681 dpyinfo->toggle_visible_pointer = x_toggle_visible_pointer;
10682 dpyinfo->invisible_cursor = make_invisible_cursor (dpyinfo);
10686 /* Current X display connection identifier. Incremented for each next
10687 connection established. */
10688 static unsigned x_display_id;
10690 /* Open a connection to X display DISPLAY_NAME, and return
10691 the structure that describes the open display.
10692 If we cannot contact the display, return null. */
10694 struct x_display_info *
10695 x_term_init (Lisp_Object display_name, char *xrm_option, char *resource_name)
10697 Display *dpy;
10698 struct terminal *terminal;
10699 struct x_display_info *dpyinfo;
10700 XrmDatabase xrdb;
10701 ptrdiff_t lim;
10703 block_input ();
10705 if (!x_initialized)
10707 x_initialize ();
10708 ++x_initialized;
10711 if (! x_display_ok (SSDATA (display_name)))
10712 error ("Display %s can't be opened", SSDATA (display_name));
10714 #ifdef USE_GTK
10716 #define NUM_ARGV 10
10717 int argc;
10718 char *argv[NUM_ARGV];
10719 char **argv2 = argv;
10720 guint id;
10722 if (x_initialized++ > 1)
10724 xg_display_open (SSDATA (display_name), &dpy);
10726 else
10728 static char display_opt[] = "--display";
10729 static char name_opt[] = "--name";
10731 for (argc = 0; argc < NUM_ARGV; ++argc)
10732 argv[argc] = 0;
10734 argc = 0;
10735 argv[argc++] = initial_argv[0];
10737 if (! NILP (display_name))
10739 argv[argc++] = display_opt;
10740 argv[argc++] = SSDATA (display_name);
10743 argv[argc++] = name_opt;
10744 argv[argc++] = resource_name;
10746 XSetLocaleModifiers ("");
10748 /* Work around GLib bug that outputs a faulty warning. See
10749 https://bugzilla.gnome.org/show_bug.cgi?id=563627. */
10750 id = g_log_set_handler ("GLib", G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
10751 | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
10753 /* NULL window -> events for all windows go to our function.
10754 Call before gtk_init so Gtk+ event filters comes after our. */
10755 gdk_window_add_filter (NULL, event_handler_gdk, NULL);
10757 /* gtk_init does set_locale. Fix locale before and after. */
10758 fixup_locale ();
10759 gtk_init (&argc, &argv2);
10760 fixup_locale ();
10762 g_log_remove_handler ("GLib", id);
10764 xg_initialize ();
10766 dpy = DEFAULT_GDK_DISPLAY ();
10768 #if ! GTK_CHECK_VERSION (2, 90, 0)
10769 /* Load our own gtkrc if it exists. */
10771 const char *file = "~/.emacs.d/gtkrc";
10772 Lisp_Object s, abs_file;
10774 s = build_string (file);
10775 abs_file = Fexpand_file_name (s, Qnil);
10777 if (! NILP (abs_file) && !NILP (Ffile_readable_p (abs_file)))
10778 gtk_rc_parse (SSDATA (abs_file));
10780 #endif
10782 XSetErrorHandler (x_error_handler);
10783 XSetIOErrorHandler (x_io_error_quitter);
10786 #else /* not USE_GTK */
10787 #ifdef USE_X_TOOLKIT
10788 /* weiner@footloose.sps.mot.com reports that this causes
10789 errors with X11R5:
10790 X protocol error: BadAtom (invalid Atom parameter)
10791 on protocol request 18skiloaf.
10792 So let's not use it until R6. */
10793 #ifdef HAVE_X11XTR6
10794 XtSetLanguageProc (NULL, NULL, NULL);
10795 #endif
10798 int argc = 0;
10799 char *argv[3];
10801 argv[0] = "";
10802 argc = 1;
10803 if (xrm_option)
10805 argv[argc++] = "-xrm";
10806 argv[argc++] = xrm_option;
10808 turn_on_atimers (false);
10809 dpy = XtOpenDisplay (Xt_app_con, SSDATA (display_name),
10810 resource_name, EMACS_CLASS,
10811 emacs_options, XtNumber (emacs_options),
10812 &argc, argv);
10813 turn_on_atimers (true);
10815 #ifdef HAVE_X11XTR6
10816 /* I think this is to compensate for XtSetLanguageProc. */
10817 fixup_locale ();
10818 #endif
10821 #else /* not USE_X_TOOLKIT */
10822 XSetLocaleModifiers ("");
10823 dpy = XOpenDisplay (SSDATA (display_name));
10824 #endif /* not USE_X_TOOLKIT */
10825 #endif /* not USE_GTK*/
10827 /* Detect failure. */
10828 if (dpy == 0)
10830 unblock_input ();
10831 return 0;
10834 /* We have definitely succeeded. Record the new connection. */
10836 dpyinfo = xzalloc (sizeof *dpyinfo);
10837 terminal = x_create_terminal (dpyinfo);
10840 struct x_display_info *share;
10842 for (share = x_display_list; share; share = share->next)
10843 if (same_x_server (SSDATA (XCAR (share->name_list_element)),
10844 SSDATA (display_name)))
10845 break;
10846 if (share)
10847 terminal->kboard = share->terminal->kboard;
10848 else
10850 terminal->kboard = allocate_kboard (Qx);
10852 if (!EQ (XSYMBOL (Qvendor_specific_keysyms)->function, Qunbound))
10854 char *vendor = ServerVendor (dpy);
10856 /* Protect terminal from GC before removing it from the
10857 list of terminals. */
10858 struct gcpro gcpro1;
10859 Lisp_Object gcpro_term;
10860 XSETTERMINAL (gcpro_term, terminal);
10861 GCPRO1 (gcpro_term);
10863 /* Temporarily hide the partially initialized terminal. */
10864 terminal_list = terminal->next_terminal;
10865 unblock_input ();
10866 kset_system_key_alist
10867 (terminal->kboard,
10868 call1 (Qvendor_specific_keysyms,
10869 vendor ? build_string (vendor) : empty_unibyte_string));
10870 block_input ();
10871 terminal->next_terminal = terminal_list;
10872 terminal_list = terminal;
10873 UNGCPRO;
10876 /* Don't let the initial kboard remain current longer than necessary.
10877 That would cause problems if a file loaded on startup tries to
10878 prompt in the mini-buffer. */
10879 if (current_kboard == initial_kboard)
10880 current_kboard = terminal->kboard;
10882 terminal->kboard->reference_count++;
10885 /* Put this display on the chain. */
10886 dpyinfo->next = x_display_list;
10887 x_display_list = dpyinfo;
10889 dpyinfo->name_list_element = Fcons (display_name, Qnil);
10890 dpyinfo->display = dpy;
10891 dpyinfo->connection = ConnectionNumber (dpyinfo->display);
10893 /* Set the name of the terminal. */
10894 terminal->name = xlispstrdup (display_name);
10896 #if false
10897 XSetAfterFunction (x_current_display, x_trace_wire);
10898 #endif
10900 lim = min (PTRDIFF_MAX, SIZE_MAX) - sizeof "@";
10901 Lisp_Object system_name = Fsystem_name ();
10902 if (lim - SBYTES (Vinvocation_name) < SBYTES (system_name))
10903 memory_full (SIZE_MAX);
10904 dpyinfo->x_id = ++x_display_id;
10905 dpyinfo->x_id_name = xmalloc (SBYTES (Vinvocation_name)
10906 + SBYTES (system_name) + 2);
10907 char *nametail = lispstpcpy (dpyinfo->x_id_name, Vinvocation_name);
10908 *nametail++ = '@';
10909 lispstpcpy (nametail, system_name);
10911 /* Figure out which modifier bits mean what. */
10912 x_find_modifier_meanings (dpyinfo);
10914 /* Get the scroll bar cursor. */
10915 #ifdef USE_GTK
10916 /* We must create a GTK cursor, it is required for GTK widgets. */
10917 dpyinfo->xg_cursor = xg_create_default_cursor (dpyinfo->display);
10918 #endif /* USE_GTK */
10920 dpyinfo->vertical_scroll_bar_cursor
10921 = XCreateFontCursor (dpyinfo->display, XC_sb_v_double_arrow);
10923 dpyinfo->horizontal_scroll_bar_cursor
10924 = XCreateFontCursor (dpyinfo->display, XC_sb_h_double_arrow);
10926 xrdb = x_load_resources (dpyinfo->display, xrm_option,
10927 resource_name, EMACS_CLASS);
10928 #ifdef HAVE_XRMSETDATABASE
10929 XrmSetDatabase (dpyinfo->display, xrdb);
10930 #else
10931 dpyinfo->display->db = xrdb;
10932 #endif
10933 /* Put the rdb where we can find it in a way that works on
10934 all versions. */
10935 dpyinfo->xrdb = xrdb;
10937 dpyinfo->screen = ScreenOfDisplay (dpyinfo->display,
10938 DefaultScreen (dpyinfo->display));
10939 select_visual (dpyinfo);
10940 dpyinfo->cmap = DefaultColormapOfScreen (dpyinfo->screen);
10941 dpyinfo->root_window = RootWindowOfScreen (dpyinfo->screen);
10942 dpyinfo->icon_bitmap_id = -1;
10943 dpyinfo->wm_type = X_WMTYPE_UNKNOWN;
10945 reset_mouse_highlight (&dpyinfo->mouse_highlight);
10947 /* See if we can construct pixel values from RGB values. */
10948 if (dpyinfo->visual->class == TrueColor)
10950 get_bits_and_offset (dpyinfo->visual->red_mask,
10951 &dpyinfo->red_bits, &dpyinfo->red_offset);
10952 get_bits_and_offset (dpyinfo->visual->blue_mask,
10953 &dpyinfo->blue_bits, &dpyinfo->blue_offset);
10954 get_bits_and_offset (dpyinfo->visual->green_mask,
10955 &dpyinfo->green_bits, &dpyinfo->green_offset);
10958 /* See if a private colormap is requested. */
10959 if (dpyinfo->visual == DefaultVisualOfScreen (dpyinfo->screen))
10961 if (dpyinfo->visual->class == PseudoColor)
10963 AUTO_STRING (privateColormap, "privateColormap");
10964 AUTO_STRING (PrivateColormap, "PrivateColormap");
10965 Lisp_Object value
10966 = display_x_get_resource (dpyinfo, privateColormap,
10967 PrivateColormap, Qnil, Qnil);
10968 if (STRINGP (value)
10969 && (!strcmp (SSDATA (value), "true")
10970 || !strcmp (SSDATA (value), "on")))
10971 dpyinfo->cmap = XCopyColormapAndFree (dpyinfo->display, dpyinfo->cmap);
10974 else
10975 dpyinfo->cmap = XCreateColormap (dpyinfo->display, dpyinfo->root_window,
10976 dpyinfo->visual, AllocNone);
10978 #ifdef HAVE_XFT
10980 /* If we are using Xft, the following precautions should be made:
10982 1. Make sure that the Xrender extension is added before the Xft one.
10983 Otherwise, the close-display hook set by Xft is called after the one
10984 for Xrender, and the former tries to re-add the latter. This results
10985 in inconsistency of internal states and leads to X protocol error when
10986 one reconnects to the same X server (Bug#1696).
10988 2. Check dpi value in X resources. It is better we use it as well,
10989 since Xft will use it, as will all Gnome applications. If our real DPI
10990 is smaller or larger than the one Xft uses, our font will look smaller
10991 or larger than other for other applications, even if it is the same
10992 font name (monospace-10 for example). */
10994 int event_base, error_base;
10995 char *v;
10996 double d;
10998 XRenderQueryExtension (dpyinfo->display, &event_base, &error_base);
11000 v = XGetDefault (dpyinfo->display, "Xft", "dpi");
11001 if (v != NULL && sscanf (v, "%lf", &d) == 1)
11002 dpyinfo->resy = dpyinfo->resx = d;
11004 #endif
11006 if (dpyinfo->resy < 1)
11008 int screen_number = XScreenNumberOfScreen (dpyinfo->screen);
11009 double pixels = DisplayHeight (dpyinfo->display, screen_number);
11010 double mm = DisplayHeightMM (dpyinfo->display, screen_number);
11011 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
11012 dpyinfo->resy = (mm < 1) ? 100 : pixels * 25.4 / mm;
11013 pixels = DisplayWidth (dpyinfo->display, screen_number);
11014 mm = DisplayWidthMM (dpyinfo->display, screen_number);
11015 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
11016 dpyinfo->resx = (mm < 1) ? 100 : pixels * 25.4 / mm;
11020 static const struct
11022 const char *name;
11023 int offset;
11024 } atom_refs[] = {
11025 #define ATOM_REFS_INIT(string, member) \
11026 { string, offsetof (struct x_display_info, member) },
11027 ATOM_REFS_INIT ("WM_PROTOCOLS", Xatom_wm_protocols)
11028 ATOM_REFS_INIT ("WM_TAKE_FOCUS", Xatom_wm_take_focus)
11029 ATOM_REFS_INIT ("WM_SAVE_YOURSELF", Xatom_wm_save_yourself)
11030 ATOM_REFS_INIT ("WM_DELETE_WINDOW", Xatom_wm_delete_window)
11031 ATOM_REFS_INIT ("WM_CHANGE_STATE", Xatom_wm_change_state)
11032 ATOM_REFS_INIT ("WM_CONFIGURE_DENIED", Xatom_wm_configure_denied)
11033 ATOM_REFS_INIT ("WM_MOVED", Xatom_wm_window_moved)
11034 ATOM_REFS_INIT ("WM_CLIENT_LEADER", Xatom_wm_client_leader)
11035 ATOM_REFS_INIT ("Editres", Xatom_editres)
11036 ATOM_REFS_INIT ("CLIPBOARD", Xatom_CLIPBOARD)
11037 ATOM_REFS_INIT ("TIMESTAMP", Xatom_TIMESTAMP)
11038 ATOM_REFS_INIT ("TEXT", Xatom_TEXT)
11039 ATOM_REFS_INIT ("COMPOUND_TEXT", Xatom_COMPOUND_TEXT)
11040 ATOM_REFS_INIT ("UTF8_STRING", Xatom_UTF8_STRING)
11041 ATOM_REFS_INIT ("DELETE", Xatom_DELETE)
11042 ATOM_REFS_INIT ("MULTIPLE", Xatom_MULTIPLE)
11043 ATOM_REFS_INIT ("INCR", Xatom_INCR)
11044 ATOM_REFS_INIT ("_EMACS_TMP_", Xatom_EMACS_TMP)
11045 ATOM_REFS_INIT ("TARGETS", Xatom_TARGETS)
11046 ATOM_REFS_INIT ("NULL", Xatom_NULL)
11047 ATOM_REFS_INIT ("ATOM", Xatom_ATOM)
11048 ATOM_REFS_INIT ("ATOM_PAIR", Xatom_ATOM_PAIR)
11049 ATOM_REFS_INIT ("CLIPBOARD_MANAGER", Xatom_CLIPBOARD_MANAGER)
11050 ATOM_REFS_INIT ("_XEMBED_INFO", Xatom_XEMBED_INFO)
11051 /* For properties of font. */
11052 ATOM_REFS_INIT ("PIXEL_SIZE", Xatom_PIXEL_SIZE)
11053 ATOM_REFS_INIT ("AVERAGE_WIDTH", Xatom_AVERAGE_WIDTH)
11054 ATOM_REFS_INIT ("_MULE_BASELINE_OFFSET", Xatom_MULE_BASELINE_OFFSET)
11055 ATOM_REFS_INIT ("_MULE_RELATIVE_COMPOSE", Xatom_MULE_RELATIVE_COMPOSE)
11056 ATOM_REFS_INIT ("_MULE_DEFAULT_ASCENT", Xatom_MULE_DEFAULT_ASCENT)
11057 /* Ghostscript support. */
11058 ATOM_REFS_INIT ("DONE", Xatom_DONE)
11059 ATOM_REFS_INIT ("PAGE", Xatom_PAGE)
11060 ATOM_REFS_INIT ("SCROLLBAR", Xatom_Scrollbar)
11061 ATOM_REFS_INIT ("HORIZONTAL_SCROLLBAR", Xatom_Horizontal_Scrollbar)
11062 ATOM_REFS_INIT ("_XEMBED", Xatom_XEMBED)
11063 /* EWMH */
11064 ATOM_REFS_INIT ("_NET_WM_STATE", Xatom_net_wm_state)
11065 ATOM_REFS_INIT ("_NET_WM_STATE_FULLSCREEN", Xatom_net_wm_state_fullscreen)
11066 ATOM_REFS_INIT ("_NET_WM_STATE_MAXIMIZED_HORZ",
11067 Xatom_net_wm_state_maximized_horz)
11068 ATOM_REFS_INIT ("_NET_WM_STATE_MAXIMIZED_VERT",
11069 Xatom_net_wm_state_maximized_vert)
11070 ATOM_REFS_INIT ("_NET_WM_STATE_STICKY", Xatom_net_wm_state_sticky)
11071 ATOM_REFS_INIT ("_NET_WM_STATE_HIDDEN", Xatom_net_wm_state_hidden)
11072 ATOM_REFS_INIT ("_NET_WM_WINDOW_TYPE", Xatom_net_window_type)
11073 ATOM_REFS_INIT ("_NET_WM_WINDOW_TYPE_TOOLTIP",
11074 Xatom_net_window_type_tooltip)
11075 ATOM_REFS_INIT ("_NET_WM_ICON_NAME", Xatom_net_wm_icon_name)
11076 ATOM_REFS_INIT ("_NET_WM_NAME", Xatom_net_wm_name)
11077 ATOM_REFS_INIT ("_NET_SUPPORTED", Xatom_net_supported)
11078 ATOM_REFS_INIT ("_NET_SUPPORTING_WM_CHECK", Xatom_net_supporting_wm_check)
11079 ATOM_REFS_INIT ("_NET_WM_WINDOW_OPACITY", Xatom_net_wm_window_opacity)
11080 ATOM_REFS_INIT ("_NET_ACTIVE_WINDOW", Xatom_net_active_window)
11081 ATOM_REFS_INIT ("_NET_FRAME_EXTENTS", Xatom_net_frame_extents)
11082 ATOM_REFS_INIT ("_NET_CURRENT_DESKTOP", Xatom_net_current_desktop)
11083 ATOM_REFS_INIT ("_NET_WORKAREA", Xatom_net_workarea)
11084 /* Session management */
11085 ATOM_REFS_INIT ("SM_CLIENT_ID", Xatom_SM_CLIENT_ID)
11086 ATOM_REFS_INIT ("_XSETTINGS_SETTINGS", Xatom_xsettings_prop)
11087 ATOM_REFS_INIT ("MANAGER", Xatom_xsettings_mgr)
11090 int i;
11091 enum { atom_count = ARRAYELTS (atom_refs) };
11092 /* 1 for _XSETTINGS_SN. */
11093 enum { total_atom_count = 1 + atom_count };
11094 Atom atoms_return[total_atom_count];
11095 char *atom_names[total_atom_count];
11096 static char const xsettings_fmt[] = "_XSETTINGS_S%d";
11097 char xsettings_atom_name[sizeof xsettings_fmt - 2
11098 + INT_STRLEN_BOUND (int)];
11100 for (i = 0; i < atom_count; i++)
11101 atom_names[i] = (char *) atom_refs[i].name;
11103 /* Build _XSETTINGS_SN atom name. */
11104 sprintf (xsettings_atom_name, xsettings_fmt,
11105 XScreenNumberOfScreen (dpyinfo->screen));
11106 atom_names[i] = xsettings_atom_name;
11108 XInternAtoms (dpyinfo->display, atom_names, total_atom_count,
11109 False, atoms_return);
11111 for (i = 0; i < atom_count; i++)
11112 *(Atom *) ((char *) dpyinfo + atom_refs[i].offset) = atoms_return[i];
11114 /* Manually copy last atom. */
11115 dpyinfo->Xatom_xsettings_sel = atoms_return[i];
11118 dpyinfo->x_dnd_atoms_size = 8;
11119 dpyinfo->x_dnd_atoms = xmalloc (sizeof *dpyinfo->x_dnd_atoms
11120 * dpyinfo->x_dnd_atoms_size);
11121 dpyinfo->gray
11122 = XCreatePixmapFromBitmapData (dpyinfo->display, dpyinfo->root_window,
11123 gray_bits, gray_width, gray_height,
11124 1, 0, 1);
11126 x_setup_pointer_blanking (dpyinfo);
11128 #ifdef HAVE_X_I18N
11129 xim_initialize (dpyinfo, resource_name);
11130 #endif
11132 xsettings_initialize (dpyinfo);
11134 /* This is only needed for distinguishing keyboard and process input. */
11135 if (dpyinfo->connection != 0)
11136 add_keyboard_wait_descriptor (dpyinfo->connection);
11138 #ifdef F_SETOWN
11139 fcntl (dpyinfo->connection, F_SETOWN, getpid ());
11140 #endif /* ! defined (F_SETOWN) */
11142 if (interrupt_input)
11143 init_sigio (dpyinfo->connection);
11145 #ifdef USE_LUCID
11147 XrmValue d, fr, to;
11148 Font font;
11150 dpy = dpyinfo->display;
11151 d.addr = (XPointer)&dpy;
11152 d.size = sizeof (Display *);
11153 fr.addr = XtDefaultFont;
11154 fr.size = sizeof (XtDefaultFont);
11155 to.size = sizeof (Font *);
11156 to.addr = (XPointer)&font;
11157 x_catch_errors (dpy);
11158 if (!XtCallConverter (dpy, XtCvtStringToFont, &d, 1, &fr, &to, NULL))
11159 emacs_abort ();
11160 if (x_had_errors_p (dpy) || !XQueryFont (dpy, font))
11161 XrmPutLineResource (&xrdb, "Emacs.dialog.*.font: 9x15");
11162 /* Do not free XFontStruct returned by the above call to XQueryFont.
11163 This leads to X protocol errors at XtCloseDisplay (Bug#18403). */
11164 x_uncatch_errors ();
11166 #endif
11168 /* See if we should run in synchronous mode. This is useful
11169 for debugging X code. */
11171 AUTO_STRING (synchronous, "synchronous");
11172 AUTO_STRING (Synchronous, "Synchronous");
11173 Lisp_Object value = display_x_get_resource (dpyinfo, synchronous,
11174 Synchronous, Qnil, Qnil);
11175 if (STRINGP (value)
11176 && (!strcmp (SSDATA (value), "true")
11177 || !strcmp (SSDATA (value), "on")))
11178 XSynchronize (dpyinfo->display, True);
11182 AUTO_STRING (useXIM, "useXIM");
11183 AUTO_STRING (UseXIM, "UseXIM");
11184 Lisp_Object value = display_x_get_resource (dpyinfo, useXIM, UseXIM,
11185 Qnil, Qnil);
11186 #ifdef USE_XIM
11187 if (STRINGP (value)
11188 && (!strcmp (SSDATA (value), "false")
11189 || !strcmp (SSDATA (value), "off")))
11190 use_xim = false;
11191 #else
11192 if (STRINGP (value)
11193 && (!strcmp (SSDATA (value), "true")
11194 || !strcmp (SSDATA (value), "on")))
11195 use_xim = true;
11196 #endif
11199 #ifdef HAVE_X_SM
11200 /* Only do this for the very first display in the Emacs session.
11201 Ignore X session management when Emacs was first started on a
11202 tty or started as a daemon. */
11203 if (terminal->id == 1 && ! IS_DAEMON)
11204 x_session_initialize (dpyinfo);
11205 #endif
11207 unblock_input ();
11209 return dpyinfo;
11212 /* Get rid of display DPYINFO, deleting all frames on it,
11213 and without sending any more commands to the X server. */
11215 static void
11216 x_delete_display (struct x_display_info *dpyinfo)
11218 struct terminal *t;
11220 /* Close all frames and delete the generic struct terminal for this
11221 X display. */
11222 for (t = terminal_list; t; t = t->next_terminal)
11223 if (t->type == output_x_window && t->display_info.x == dpyinfo)
11225 #ifdef HAVE_X_SM
11226 /* Close X session management when we close its display. */
11227 if (t->id == 1 && x_session_have_connection ())
11228 x_session_close ();
11229 #endif
11230 delete_terminal (t);
11231 break;
11234 if (next_noop_dpyinfo == dpyinfo)
11235 next_noop_dpyinfo = dpyinfo->next;
11237 if (x_display_list == dpyinfo)
11238 x_display_list = dpyinfo->next;
11239 else
11241 struct x_display_info *tail;
11243 for (tail = x_display_list; tail; tail = tail->next)
11244 if (tail->next == dpyinfo)
11245 tail->next = tail->next->next;
11248 xfree (dpyinfo->x_id_name);
11249 xfree (dpyinfo->x_dnd_atoms);
11250 xfree (dpyinfo->color_cells);
11251 xfree (dpyinfo);
11254 #ifdef USE_X_TOOLKIT
11256 /* Atimer callback function for TIMER. Called every 0.1s to process
11257 Xt timeouts, if needed. We must avoid calling XtAppPending as
11258 much as possible because that function does an implicit XFlush
11259 that slows us down. */
11261 static void
11262 x_process_timeouts (struct atimer *timer)
11264 block_input ();
11265 x_timeout_atimer_activated_flag = false;
11266 if (toolkit_scroll_bar_interaction || popup_activated ())
11268 while (XtAppPending (Xt_app_con) & XtIMTimer)
11269 XtAppProcessEvent (Xt_app_con, XtIMTimer);
11270 /* Reactivate the atimer for next time. */
11271 x_activate_timeout_atimer ();
11273 unblock_input ();
11276 /* Install an asynchronous timer that processes Xt timeout events
11277 every 0.1s as long as either `toolkit_scroll_bar_interaction' or
11278 `popup_activated_flag' (in xmenu.c) is set. Make sure to call this
11279 function whenever these variables are set. This is necessary
11280 because some widget sets use timeouts internally, for example the
11281 LessTif menu bar, or the Xaw3d scroll bar. When Xt timeouts aren't
11282 processed, these widgets don't behave normally. */
11284 void
11285 x_activate_timeout_atimer (void)
11287 block_input ();
11288 if (!x_timeout_atimer_activated_flag)
11290 struct timespec interval = make_timespec (0, 100 * 1000 * 1000);
11291 start_atimer (ATIMER_RELATIVE, interval, x_process_timeouts, 0);
11292 x_timeout_atimer_activated_flag = true;
11294 unblock_input ();
11297 #endif /* USE_X_TOOLKIT */
11300 /* Set up use of X before we make the first connection. */
11302 static struct redisplay_interface x_redisplay_interface =
11304 x_frame_parm_handlers,
11305 x_produce_glyphs,
11306 x_write_glyphs,
11307 x_insert_glyphs,
11308 x_clear_end_of_line,
11309 x_scroll_run,
11310 x_after_update_window_line,
11311 x_update_window_begin,
11312 x_update_window_end,
11313 x_flush,
11314 x_clear_window_mouse_face,
11315 x_get_glyph_overhangs,
11316 x_fix_overlapping_area,
11317 x_draw_fringe_bitmap,
11318 0, /* define_fringe_bitmap */
11319 0, /* destroy_fringe_bitmap */
11320 x_compute_glyph_string_overhangs,
11321 x_draw_glyph_string,
11322 x_define_frame_cursor,
11323 x_clear_frame_area,
11324 x_draw_window_cursor,
11325 x_draw_vertical_window_border,
11326 x_draw_window_divider,
11327 x_shift_glyphs_for_insert,
11328 x_show_hourglass,
11329 x_hide_hourglass
11333 /* This function is called when the last frame on a display is deleted. */
11334 void
11335 x_delete_terminal (struct terminal *terminal)
11337 struct x_display_info *dpyinfo = terminal->display_info.x;
11339 /* Protect against recursive calls. delete_frame in
11340 delete_terminal calls us back when it deletes our last frame. */
11341 if (!terminal->name)
11342 return;
11344 block_input ();
11345 #ifdef HAVE_X_I18N
11346 /* We must close our connection to the XIM server before closing the
11347 X display. */
11348 if (dpyinfo->xim)
11349 xim_close_dpy (dpyinfo);
11350 #endif
11352 /* Normally, the display is available... */
11353 if (dpyinfo->display)
11355 x_destroy_all_bitmaps (dpyinfo);
11356 XSetCloseDownMode (dpyinfo->display, DestroyAll);
11358 /* Whether or not XCloseDisplay destroys the associated resource
11359 database depends on the version of libX11. To avoid both
11360 crash and memory leak, we dissociate the database from the
11361 display and then destroy dpyinfo->xrdb ourselves.
11363 Unfortunately, the above strategy does not work in some
11364 situations due to a bug in newer versions of libX11: because
11365 XrmSetDatabase doesn't clear the flag XlibDisplayDfltRMDB if
11366 dpy->db is NULL, XCloseDisplay destroys the associated
11367 database whereas it has not been created by XGetDefault
11368 (Bug#21974 in freedesktop.org Bugzilla). As a workaround, we
11369 don't destroy the database here in order to avoid the crash
11370 in the above situations for now, though that may cause memory
11371 leaks in other situations. */
11372 #if false
11373 #ifdef HAVE_XRMSETDATABASE
11374 XrmSetDatabase (dpyinfo->display, NULL);
11375 #else
11376 dpyinfo->display->db = NULL;
11377 #endif
11378 /* We used to call XrmDestroyDatabase from x_delete_display, but
11379 some older versions of libX11 crash if we call it after
11380 closing all the displays. */
11381 XrmDestroyDatabase (dpyinfo->xrdb);
11382 #endif
11384 #ifdef USE_GTK
11385 xg_display_close (dpyinfo->display);
11386 #else
11387 #ifdef USE_X_TOOLKIT
11388 XtCloseDisplay (dpyinfo->display);
11389 #else
11390 XCloseDisplay (dpyinfo->display);
11391 #endif
11392 #endif /* ! USE_GTK */
11393 /* Do not close the connection here because it's already closed
11394 by X(t)CloseDisplay (Bug#18403). */
11395 dpyinfo->display = NULL;
11398 /* ...but if called from x_connection_closed, the display may already
11399 be closed and dpyinfo->display was set to 0 to indicate that. Since
11400 X server is most likely gone, explicit close is the only reliable
11401 way to continue and avoid Bug#19147. */
11402 else if (dpyinfo->connection >= 0)
11403 emacs_close (dpyinfo->connection);
11405 /* No more input on this descriptor. */
11406 delete_keyboard_wait_descriptor (dpyinfo->connection);
11407 /* Mark as dead. */
11408 dpyinfo->connection = -1;
11410 x_delete_display (dpyinfo);
11411 unblock_input ();
11414 /* Create a struct terminal, initialize it with the X11 specific
11415 functions and make DISPLAY->TERMINAL point to it. */
11417 static struct terminal *
11418 x_create_terminal (struct x_display_info *dpyinfo)
11420 struct terminal *terminal;
11422 terminal = create_terminal (output_x_window, &x_redisplay_interface);
11424 terminal->display_info.x = dpyinfo;
11425 dpyinfo->terminal = terminal;
11427 /* kboard is initialized in x_term_init. */
11429 terminal->clear_frame_hook = x_clear_frame;
11430 terminal->ins_del_lines_hook = x_ins_del_lines;
11431 terminal->delete_glyphs_hook = x_delete_glyphs;
11432 terminal->ring_bell_hook = XTring_bell;
11433 terminal->toggle_invisible_pointer_hook = XTtoggle_invisible_pointer;
11434 terminal->update_begin_hook = x_update_begin;
11435 terminal->update_end_hook = x_update_end;
11436 terminal->read_socket_hook = XTread_socket;
11437 terminal->frame_up_to_date_hook = XTframe_up_to_date;
11438 terminal->mouse_position_hook = XTmouse_position;
11439 terminal->frame_rehighlight_hook = XTframe_rehighlight;
11440 terminal->frame_raise_lower_hook = XTframe_raise_lower;
11441 terminal->fullscreen_hook = XTfullscreen_hook;
11442 terminal->menu_show_hook = x_menu_show;
11443 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
11444 terminal->popup_dialog_hook = xw_popup_dialog;
11445 #endif
11446 terminal->set_vertical_scroll_bar_hook = XTset_vertical_scroll_bar;
11447 terminal->set_horizontal_scroll_bar_hook = XTset_horizontal_scroll_bar;
11448 terminal->condemn_scroll_bars_hook = XTcondemn_scroll_bars;
11449 terminal->redeem_scroll_bar_hook = XTredeem_scroll_bar;
11450 terminal->judge_scroll_bars_hook = XTjudge_scroll_bars;
11451 terminal->delete_frame_hook = x_destroy_window;
11452 terminal->delete_terminal_hook = x_delete_terminal;
11453 /* Other hooks are NULL by default. */
11455 return terminal;
11458 static void
11459 x_initialize (void)
11461 baud_rate = 19200;
11463 x_noop_count = 0;
11464 any_help_event_p = false;
11465 ignore_next_mouse_click_timeout = 0;
11467 #ifdef USE_GTK
11468 current_count = -1;
11469 #endif
11471 /* Try to use interrupt input; if we can't, then start polling. */
11472 Fset_input_interrupt_mode (Qt);
11474 #ifdef USE_X_TOOLKIT
11475 XtToolkitInitialize ();
11477 Xt_app_con = XtCreateApplicationContext ();
11479 /* Register a converter from strings to pixels, which uses
11480 Emacs' color allocation infrastructure. */
11481 XtAppSetTypeConverter (Xt_app_con,
11482 XtRString, XtRPixel, cvt_string_to_pixel,
11483 cvt_string_to_pixel_args,
11484 XtNumber (cvt_string_to_pixel_args),
11485 XtCacheByDisplay, cvt_pixel_dtor);
11487 XtAppSetFallbackResources (Xt_app_con, Xt_default_resources);
11488 #endif
11490 #ifdef USE_TOOLKIT_SCROLL_BARS
11491 #ifndef USE_GTK
11492 xaw3d_arrow_scroll = False;
11493 xaw3d_pick_top = True;
11494 #endif
11495 #endif
11497 /* Note that there is no real way portable across R3/R4 to get the
11498 original error handler. */
11499 XSetErrorHandler (x_error_handler);
11500 XSetIOErrorHandler (x_io_error_quitter);
11503 #ifdef USE_GTK
11504 void
11505 init_xterm (void)
11507 /* Emacs can handle only core input events, so make sure
11508 Gtk doesn't use Xinput or Xinput2 extensions. */
11509 xputenv ("GDK_CORE_DEVICE_EVENTS=1");
11511 #endif
11513 void
11514 syms_of_xterm (void)
11516 x_error_message = NULL;
11518 DEFSYM (Qvendor_specific_keysyms, "vendor-specific-keysyms");
11519 DEFSYM (Qlatin_1, "latin-1");
11521 #ifdef USE_GTK
11522 xg_default_icon_file = build_pure_c_string ("icons/hicolor/scalable/apps/emacs.svg");
11523 staticpro (&xg_default_icon_file);
11525 DEFSYM (Qx_gtk_map_stock, "x-gtk-map-stock");
11526 #endif
11528 DEFVAR_BOOL ("x-use-underline-position-properties",
11529 x_use_underline_position_properties,
11530 doc: /* Non-nil means make use of UNDERLINE_POSITION font properties.
11531 A value of nil means ignore them. If you encounter fonts with bogus
11532 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
11533 to 4.1, set this to nil. You can also use `underline-minimum-offset'
11534 to override the font's UNDERLINE_POSITION for small font display
11535 sizes. */);
11536 x_use_underline_position_properties = true;
11538 DEFVAR_BOOL ("x-underline-at-descent-line",
11539 x_underline_at_descent_line,
11540 doc: /* Non-nil means to draw the underline at the same place as the descent line.
11541 A value of nil means to draw the underline according to the value of the
11542 variable `x-use-underline-position-properties', which is usually at the
11543 baseline level. The default value is nil. */);
11544 x_underline_at_descent_line = false;
11546 DEFVAR_BOOL ("x-mouse-click-focus-ignore-position",
11547 x_mouse_click_focus_ignore_position,
11548 doc: /* Non-nil means that a mouse click to focus a frame does not move point.
11549 This variable is only used when the window manager requires that you
11550 click on a frame to select it (give it focus). In that case, a value
11551 of nil, means that the selected window and cursor position changes to
11552 reflect the mouse click position, while a non-nil value means that the
11553 selected window or cursor position is preserved. */);
11554 x_mouse_click_focus_ignore_position = false;
11556 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
11557 doc: /* Which toolkit scroll bars Emacs uses, if any.
11558 A value of nil means Emacs doesn't use toolkit scroll bars.
11559 With the X Window system, the value is a symbol describing the
11560 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
11561 With MS Windows or Nextstep, the value is t. */);
11562 #ifdef USE_TOOLKIT_SCROLL_BARS
11563 #ifdef USE_MOTIF
11564 Vx_toolkit_scroll_bars = intern_c_string ("motif");
11565 #elif defined HAVE_XAW3D
11566 Vx_toolkit_scroll_bars = intern_c_string ("xaw3d");
11567 #elif USE_GTK
11568 Vx_toolkit_scroll_bars = intern_c_string ("gtk");
11569 #else
11570 Vx_toolkit_scroll_bars = intern_c_string ("xaw");
11571 #endif
11572 #else
11573 Vx_toolkit_scroll_bars = Qnil;
11574 #endif
11576 DEFSYM (Qmodifier_value, "modifier-value");
11577 DEFSYM (Qalt, "alt");
11578 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
11579 DEFSYM (Qhyper, "hyper");
11580 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
11581 DEFSYM (Qmeta, "meta");
11582 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
11583 DEFSYM (Qsuper, "super");
11584 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
11586 DEFVAR_LISP ("x-alt-keysym", Vx_alt_keysym,
11587 doc: /* Which keys Emacs uses for the alt modifier.
11588 This should be one of the symbols `alt', `hyper', `meta', `super'.
11589 For example, `alt' means use the Alt_L and Alt_R keysyms. The default
11590 is nil, which is the same as `alt'. */);
11591 Vx_alt_keysym = Qnil;
11593 DEFVAR_LISP ("x-hyper-keysym", Vx_hyper_keysym,
11594 doc: /* Which keys Emacs uses for the hyper modifier.
11595 This should be one of the symbols `alt', `hyper', `meta', `super'.
11596 For example, `hyper' means use the Hyper_L and Hyper_R keysyms. The
11597 default is nil, which is the same as `hyper'. */);
11598 Vx_hyper_keysym = Qnil;
11600 DEFVAR_LISP ("x-meta-keysym", Vx_meta_keysym,
11601 doc: /* Which keys Emacs uses for the meta modifier.
11602 This should be one of the symbols `alt', `hyper', `meta', `super'.
11603 For example, `meta' means use the Meta_L and Meta_R keysyms. The
11604 default is nil, which is the same as `meta'. */);
11605 Vx_meta_keysym = Qnil;
11607 DEFVAR_LISP ("x-super-keysym", Vx_super_keysym,
11608 doc: /* Which keys Emacs uses for the super modifier.
11609 This should be one of the symbols `alt', `hyper', `meta', `super'.
11610 For example, `super' means use the Super_L and Super_R keysyms. The
11611 default is nil, which is the same as `super'. */);
11612 Vx_super_keysym = Qnil;
11614 DEFVAR_LISP ("x-keysym-table", Vx_keysym_table,
11615 doc: /* Hash table of character codes indexed by X keysym codes. */);
11616 Vx_keysym_table = make_hash_table (hashtest_eql, make_number (900),
11617 make_float (DEFAULT_REHASH_SIZE),
11618 make_float (DEFAULT_REHASH_THRESHOLD),
11619 Qnil);