Support resizing frames and windows pixelwise.
[emacs.git] / src / xterm.c
blob46419aed154d1505a1b968003a23d2ef35c3a097
1 /* X Communication module for terminals which understand the X protocol.
3 Copyright (C) 1989, 1993-2013 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 /* Load sys/types.h if not already loaded.
36 In some systems loading it twice is suicidal. */
37 #ifndef makedev
38 #include <sys/types.h>
39 #endif /* makedev */
41 #include <sys/ioctl.h>
43 #include "systime.h"
45 #include <fcntl.h>
46 #include <errno.h>
47 #include <sys/stat.h>
48 /* Caused redefinition of DBL_DIG on Netbsd; seems not to be needed. */
49 /* #include <sys/param.h> */
51 #include "charset.h"
52 #include "character.h"
53 #include "coding.h"
54 #include "frame.h"
55 #include "dispextern.h"
56 #include "fontset.h"
57 #include "termhooks.h"
58 #include "termopts.h"
59 #include "termchar.h"
60 #include "emacs-icon.h"
61 #include "disptab.h"
62 #include "buffer.h"
63 #include "window.h"
64 #include "keyboard.h"
65 #include "intervals.h"
66 #include "process.h"
67 #include "atimer.h"
68 #include "keymap.h"
69 #include "font.h"
70 #include "xsettings.h"
71 #include "xgselect.h"
72 #include "sysselect.h"
74 #ifdef USE_X_TOOLKIT
75 #include <X11/Shell.h>
76 #endif
78 #include <unistd.h>
80 #ifdef USE_GTK
81 #include "gtkutil.h"
82 #ifdef HAVE_GTK3
83 #include <X11/Xproto.h>
84 #endif
85 #endif
87 #if defined (USE_LUCID) || defined (USE_MOTIF)
88 #include "../lwlib/xlwmenu.h"
89 #endif
91 #ifdef USE_X_TOOLKIT
92 #if !defined (NO_EDITRES)
93 #define HACK_EDITRES
94 extern void _XEditResCheckMessages (Widget, XtPointer, XEvent *, Boolean *);
95 #endif /* not NO_EDITRES */
97 /* Include toolkit specific headers for the scroll bar widget. */
99 #ifdef USE_TOOLKIT_SCROLL_BARS
100 #if defined USE_MOTIF
101 #include <Xm/Xm.h> /* For LESSTIF_VERSION */
102 #include <Xm/ScrollBar.h>
103 #else /* !USE_MOTIF i.e. use Xaw */
105 #ifdef HAVE_XAW3D
106 #include <X11/Xaw3d/Simple.h>
107 #include <X11/Xaw3d/Scrollbar.h>
108 #include <X11/Xaw3d/ThreeD.h>
109 #else /* !HAVE_XAW3D */
110 #include <X11/Xaw/Simple.h>
111 #include <X11/Xaw/Scrollbar.h>
112 #endif /* !HAVE_XAW3D */
113 #ifndef XtNpickTop
114 #define XtNpickTop "pickTop"
115 #endif /* !XtNpickTop */
116 #endif /* !USE_MOTIF */
117 #endif /* USE_TOOLKIT_SCROLL_BARS */
119 #endif /* USE_X_TOOLKIT */
121 #ifdef USE_X_TOOLKIT
122 #include "widget.h"
123 #ifndef XtNinitialState
124 #define XtNinitialState "initialState"
125 #endif
126 #endif
128 #include "bitmaps/gray.xbm"
130 #ifdef HAVE_XKB
131 #include <X11/XKBlib.h>
132 #endif
134 /* Default to using XIM if available. */
135 #ifdef USE_XIM
136 int use_xim = 1;
137 #else
138 int use_xim = 0; /* configure --without-xim */
139 #endif
141 /* Non-zero means that a HELP_EVENT has been generated since Emacs
142 start. */
144 static bool any_help_event_p;
146 /* This is a chain of structures for all the X displays currently in
147 use. */
149 struct x_display_info *x_display_list;
151 #ifdef USE_X_TOOLKIT
153 /* The application context for Xt use. */
154 XtAppContext Xt_app_con;
155 static String Xt_default_resources[] = {0};
157 /* Non-zero means user is interacting with a toolkit scroll bar. */
158 static bool toolkit_scroll_bar_interaction;
160 #endif /* USE_X_TOOLKIT */
162 /* Non-zero timeout value means ignore next mouse click if it arrives
163 before that timeout elapses (i.e. as part of the same sequence of
164 events resulting from clicking on a frame to select it). */
166 static Time ignore_next_mouse_click_timeout;
168 /* Incremented by XTread_socket whenever it really tries to read
169 events. */
171 static int volatile input_signal_count;
173 /* Used locally within XTread_socket. */
175 static int x_noop_count;
177 static Lisp_Object Qalt, Qhyper, Qmeta, Qsuper, Qmodifier_value;
179 static Lisp_Object Qvendor_specific_keysyms;
180 static Lisp_Object Qlatin_1;
182 #ifdef USE_GTK
183 /* The name of the Emacs icon file. */
184 static Lisp_Object xg_default_icon_file;
186 /* Used in gtkutil.c. */
187 Lisp_Object Qx_gtk_map_stock;
188 #endif
190 /* Some functions take this as char *, not const char *. */
191 static char emacs_class[] = EMACS_CLASS;
193 enum xembed_info
195 XEMBED_MAPPED = 1 << 0
198 enum xembed_message
200 XEMBED_EMBEDDED_NOTIFY = 0,
201 XEMBED_WINDOW_ACTIVATE = 1,
202 XEMBED_WINDOW_DEACTIVATE = 2,
203 XEMBED_REQUEST_FOCUS = 3,
204 XEMBED_FOCUS_IN = 4,
205 XEMBED_FOCUS_OUT = 5,
206 XEMBED_FOCUS_NEXT = 6,
207 XEMBED_FOCUS_PREV = 7,
209 XEMBED_MODALITY_ON = 10,
210 XEMBED_MODALITY_OFF = 11,
211 XEMBED_REGISTER_ACCELERATOR = 12,
212 XEMBED_UNREGISTER_ACCELERATOR = 13,
213 XEMBED_ACTIVATE_ACCELERATOR = 14
216 static bool x_alloc_nearest_color_1 (Display *, Colormap, XColor *);
217 static void x_set_window_size_1 (struct frame *, int, int, int, bool);
218 static void x_raise_frame (struct frame *);
219 static void x_lower_frame (struct frame *);
220 static const XColor *x_color_cells (Display *, int *);
221 static int x_io_error_quitter (Display *);
222 static struct terminal *x_create_terminal (struct x_display_info *);
223 void x_delete_terminal (struct terminal *);
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);
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 int x_handle_net_wm_state (struct frame *, const XPropertyEvent *);
250 static void x_check_fullscreen (struct frame *);
251 static void x_check_expected_move (struct frame *, int, int);
252 static void x_sync_with_move (struct frame *, int, int, int);
253 static int handle_one_xevent (struct x_display_info *,
254 const XEvent *, int *,
255 struct input_event *);
256 #ifdef USE_GTK
257 static int x_dispatch_event (XEvent *, Display *);
258 #endif
259 /* Don't declare this _Noreturn because we want no
260 interference with debugging failing X calls. */
261 static void x_connection_closed (Display *, const char *);
262 static void x_wm_set_window_state (struct frame *, int);
263 static void x_wm_set_icon_pixmap (struct frame *, ptrdiff_t);
264 static void x_initialize (void);
267 /* Flush display of frame F. */
269 static void
270 x_flush (struct frame *f)
272 eassert (f && FRAME_X_P (f));
273 /* Don't call XFlush when it is not safe to redisplay; the X
274 connection may be broken. */
275 if (!NILP (Vinhibit_redisplay))
276 return;
278 block_input ();
279 XFlush (FRAME_X_DISPLAY (f));
280 unblock_input ();
284 /* Remove calls to XFlush by defining XFlush to an empty replacement.
285 Calls to XFlush should be unnecessary because the X output buffer
286 is flushed automatically as needed by calls to XPending,
287 XNextEvent, or XWindowEvent according to the XFlush man page.
288 XTread_socket calls XPending. Removing XFlush improves
289 performance. */
291 #define XFlush(DISPLAY) (void) 0
294 /***********************************************************************
295 Debugging
296 ***********************************************************************/
298 #if 0
300 /* This is a function useful for recording debugging information about
301 the sequence of occurrences in this file. */
303 struct record
305 char *locus;
306 int type;
309 struct record event_record[100];
311 int event_record_index;
313 void
314 record_event (char *locus, int type)
316 if (event_record_index == sizeof (event_record) / sizeof (struct record))
317 event_record_index = 0;
319 event_record[event_record_index].locus = locus;
320 event_record[event_record_index].type = type;
321 event_record_index++;
324 #endif /* 0 */
328 /* Return the struct x_display_info corresponding to DPY. */
330 struct x_display_info *
331 x_display_info_for_display (Display *dpy)
333 struct x_display_info *dpyinfo;
335 for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
336 if (dpyinfo->display == dpy)
337 return dpyinfo;
339 return 0;
342 static Window
343 x_find_topmost_parent (struct frame *f)
345 struct x_output *x = f->output_data.x;
346 Window win = None, wi = x->parent_desc;
347 Display *dpy = FRAME_X_DISPLAY (f);
349 while (wi != FRAME_DISPLAY_INFO (f)->root_window)
351 Window root;
352 Window *children;
353 unsigned int nchildren;
355 win = wi;
356 XQueryTree (dpy, win, &root, &wi, &children, &nchildren);
357 XFree (children);
360 return win;
363 #define OPAQUE 0xffffffff
365 void
366 x_set_frame_alpha (struct frame *f)
368 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
369 Display *dpy = FRAME_X_DISPLAY (f);
370 Window win = FRAME_OUTER_WINDOW (f);
371 double alpha = 1.0;
372 double alpha_min = 1.0;
373 unsigned long opac;
374 Window parent;
376 if (dpyinfo->x_highlight_frame == f)
377 alpha = f->alpha[0];
378 else
379 alpha = f->alpha[1];
381 if (FLOATP (Vframe_alpha_lower_limit))
382 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
383 else if (INTEGERP (Vframe_alpha_lower_limit))
384 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
386 if (alpha < 0.0)
387 return;
388 else if (alpha > 1.0)
389 alpha = 1.0;
390 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
391 alpha = alpha_min;
393 opac = alpha * OPAQUE;
395 x_catch_errors (dpy);
397 /* If there is a parent from the window manager, put the property there
398 also, to work around broken window managers that fail to do that.
399 Do this unconditionally as this function is called on reparent when
400 alpha has not changed on the frame. */
402 parent = x_find_topmost_parent (f);
403 if (parent != None)
404 XChangeProperty (dpy, parent, dpyinfo->Xatom_net_wm_window_opacity,
405 XA_CARDINAL, 32, PropModeReplace,
406 (unsigned char *) &opac, 1L);
408 /* return unless necessary */
410 unsigned char *data;
411 Atom actual;
412 int rc, format;
413 unsigned long n, left;
415 rc = XGetWindowProperty (dpy, win, dpyinfo->Xatom_net_wm_window_opacity,
416 0L, 1L, False, XA_CARDINAL,
417 &actual, &format, &n, &left,
418 &data);
420 if (rc == Success && actual != None)
422 unsigned long value = *(unsigned long *)data;
423 XFree (data);
424 if (value == opac)
426 x_uncatch_errors ();
427 return;
432 XChangeProperty (dpy, win, dpyinfo->Xatom_net_wm_window_opacity,
433 XA_CARDINAL, 32, PropModeReplace,
434 (unsigned char *) &opac, 1L);
435 x_uncatch_errors ();
439 x_display_pixel_height (struct x_display_info *dpyinfo)
441 return HeightOfScreen (dpyinfo->screen);
445 x_display_pixel_width (struct x_display_info *dpyinfo)
447 return WidthOfScreen (dpyinfo->screen);
451 /***********************************************************************
452 Starting and ending an update
453 ***********************************************************************/
455 /* Start an update of frame F. This function is installed as a hook
456 for update_begin, i.e. it is called when update_begin is called.
457 This function is called prior to calls to x_update_window_begin for
458 each window being updated. Currently, there is nothing to do here
459 because all interesting stuff is done on a window basis. */
461 static void
462 x_update_begin (struct frame *f)
464 /* Nothing to do. */
468 /* Start update of window W. */
470 static void
471 x_update_window_begin (struct window *w)
473 struct frame *f = XFRAME (WINDOW_FRAME (w));
474 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
476 w->output_cursor = w->cursor;
478 block_input ();
480 if (f == hlinfo->mouse_face_mouse_frame)
482 /* Don't do highlighting for mouse motion during the update. */
483 hlinfo->mouse_face_defer = 1;
485 /* If F needs to be redrawn, simply forget about any prior mouse
486 highlighting. */
487 if (FRAME_GARBAGED_P (f))
488 hlinfo->mouse_face_window = Qnil;
491 unblock_input ();
495 /* Draw a vertical window border from (x,y0) to (x,y1) */
497 static void
498 x_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
500 struct frame *f = XFRAME (WINDOW_FRAME (w));
501 struct face *face;
503 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
504 if (face)
505 XSetForeground (FRAME_X_DISPLAY (f), f->output_data.x->normal_gc,
506 face->foreground);
508 XDrawLine (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
509 f->output_data.x->normal_gc, x, y0, x, y1);
512 /* Draw a window divider from (x0,y0) to (x1,y1) */
514 static void
515 x_draw_window_divider (struct window *w, int x0, int x1, int y0, int y1)
517 struct frame *f = XFRAME (WINDOW_FRAME (w));
518 struct face *face;
520 face = FACE_FROM_ID (f, WINDOW_DIVIDER_FACE_ID);
521 if (face)
522 XSetForeground (FRAME_X_DISPLAY (f), f->output_data.x->normal_gc,
523 face->foreground);
525 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
526 f->output_data.x->normal_gc, x0, y0, x1 - x0, y1 - y0);
529 /* End update of window W.
531 Draw vertical borders between horizontally adjacent windows, and
532 display W's cursor if CURSOR_ON_P is non-zero.
534 MOUSE_FACE_OVERWRITTEN_P non-zero means that some row containing
535 glyphs in mouse-face were overwritten. In that case we have to
536 make sure that the mouse-highlight is properly redrawn.
538 W may be a menu bar pseudo-window in case we don't have X toolkit
539 support. Such windows don't have a cursor, so don't display it
540 here. */
542 static void
543 x_update_window_end (struct window *w, bool cursor_on_p,
544 bool mouse_face_overwritten_p)
546 if (!w->pseudo_window_p)
548 block_input ();
550 if (cursor_on_p)
551 display_and_set_cursor (w, 1,
552 w->output_cursor.hpos, w->output_cursor.vpos,
553 w->output_cursor.x, w->output_cursor.y);
555 if (draw_window_fringes (w, 1))
557 if (WINDOW_RIGHT_DIVIDER_WIDTH (w))
558 x_draw_right_divider (w);
559 else
560 x_draw_vertical_border (w);
563 unblock_input ();
566 /* If a row with mouse-face was overwritten, arrange for
567 XTframe_up_to_date to redisplay the mouse highlight. */
568 if (mouse_face_overwritten_p)
569 reset_mouse_highlight (MOUSE_HL_INFO (XFRAME (w->frame)));
573 /* End update of frame F. This function is installed as a hook in
574 update_end. */
576 static void
577 x_update_end (struct frame *f)
579 /* Mouse highlight may be displayed again. */
580 MOUSE_HL_INFO (f)->mouse_face_defer = 0;
582 #ifndef XFlush
583 block_input ();
584 XFlush (FRAME_X_DISPLAY (f));
585 unblock_input ();
586 #endif
590 /* This function is called from various places in xdisp.c
591 whenever a complete update has been performed. */
593 static void
594 XTframe_up_to_date (struct frame *f)
596 if (FRAME_X_P (f))
597 FRAME_MOUSE_UPDATE (f);
601 /* Draw truncation mark bitmaps, continuation mark bitmaps, overlay
602 arrow bitmaps, or clear the fringes if no bitmaps are required
603 before DESIRED_ROW is made current. This function is called from
604 update_window_line only if it is known that there are differences
605 between bitmaps to be drawn between current row and DESIRED_ROW. */
607 static void
608 x_after_update_window_line (struct window *w, struct glyph_row *desired_row)
610 struct frame *f;
611 int width, height;
613 eassert (w);
615 if (!desired_row->mode_line_p && !w->pseudo_window_p)
616 desired_row->redraw_fringe_bitmaps_p = 1;
618 /* When a window has disappeared, make sure that no rest of
619 full-width rows stays visible in the internal border. Could
620 check here if updated window is the leftmost/rightmost window,
621 but I guess it's not worth doing since vertically split windows
622 are almost never used, internal border is rarely set, and the
623 overhead is very small. */
624 if (windows_or_buffers_changed
625 && desired_row->full_width_p
626 && (f = XFRAME (w->frame),
627 width = FRAME_INTERNAL_BORDER_WIDTH (f),
628 width != 0)
629 && (height = desired_row->visible_height,
630 height > 0))
632 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
634 block_input ();
635 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
636 0, y, width, height);
637 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
638 FRAME_PIXEL_WIDTH (f) - width,
639 y, width, height);
640 unblock_input ();
644 static void
645 x_draw_fringe_bitmap (struct window *w, struct glyph_row *row, struct draw_fringe_bitmap_params *p)
647 struct frame *f = XFRAME (WINDOW_FRAME (w));
648 Display *display = FRAME_X_DISPLAY (f);
649 Window window = FRAME_X_WINDOW (f);
650 GC gc = f->output_data.x->normal_gc;
651 struct face *face = p->face;
653 /* Must clip because of partially visible lines. */
654 x_clip_to_row (w, row, ANY_AREA, gc);
656 if (!p->overlay_p)
658 int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
660 /* In case the same realized face is used for fringes and
661 for something displayed in the text (e.g. face `region' on
662 mono-displays, the fill style may have been changed to
663 FillSolid in x_draw_glyph_string_background. */
664 if (face->stipple)
665 XSetFillStyle (display, face->gc, FillOpaqueStippled);
666 else
667 XSetForeground (display, face->gc, face->background);
669 #ifdef USE_TOOLKIT_SCROLL_BARS
670 /* If the fringe is adjacent to the left (right) scroll bar of a
671 leftmost (rightmost, respectively) window, then extend its
672 background to the gap between the fringe and the bar. */
673 if ((WINDOW_LEFTMOST_P (w)
674 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
675 || (WINDOW_RIGHTMOST_P (w)
676 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w)))
678 int sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
680 if (sb_width > 0)
682 int bar_area_x = WINDOW_SCROLL_BAR_AREA_X (w);
683 int bar_area_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
685 if (bx < 0)
687 /* Bitmap fills the fringe. */
688 if (bar_area_x + bar_area_width == p->x)
689 bx = bar_area_x + sb_width;
690 else if (p->x + p->wd == bar_area_x)
691 bx = bar_area_x;
692 if (bx >= 0)
694 int header_line_height = WINDOW_HEADER_LINE_HEIGHT (w);
696 nx = bar_area_width - sb_width;
697 by = WINDOW_TO_FRAME_PIXEL_Y (w, max (header_line_height,
698 row->y));
699 ny = row->visible_height;
702 else
704 if (bar_area_x + bar_area_width == bx)
706 bx = bar_area_x + sb_width;
707 nx += bar_area_width - sb_width;
709 else if (bx + nx == bar_area_x)
710 nx += bar_area_width - sb_width;
714 #endif
715 if (bx >= 0 && nx > 0)
716 XFillRectangle (display, window, face->gc, bx, by, nx, ny);
718 if (!face->stipple)
719 XSetForeground (display, face->gc, face->foreground);
722 if (p->which)
724 char *bits;
725 Pixmap pixmap, clipmask = (Pixmap) 0;
726 int depth = DefaultDepthOfScreen (FRAME_X_SCREEN (f));
727 XGCValues gcv;
729 if (p->wd > 8)
730 bits = (char *) (p->bits + p->dh);
731 else
732 bits = (char *) p->bits + p->dh;
734 /* Draw the bitmap. I believe these small pixmaps can be cached
735 by the server. */
736 pixmap = XCreatePixmapFromBitmapData (display, window, bits, p->wd, p->h,
737 (p->cursor_p
738 ? (p->overlay_p ? face->background
739 : f->output_data.x->cursor_pixel)
740 : face->foreground),
741 face->background, depth);
743 if (p->overlay_p)
745 clipmask = XCreatePixmapFromBitmapData (display,
746 FRAME_DISPLAY_INFO (f)->root_window,
747 bits, p->wd, p->h,
748 1, 0, 1);
749 gcv.clip_mask = clipmask;
750 gcv.clip_x_origin = p->x;
751 gcv.clip_y_origin = p->y;
752 XChangeGC (display, gc, GCClipMask | GCClipXOrigin | GCClipYOrigin, &gcv);
755 XCopyArea (display, pixmap, window, gc, 0, 0,
756 p->wd, p->h, p->x, p->y);
757 XFreePixmap (display, pixmap);
759 if (p->overlay_p)
761 gcv.clip_mask = (Pixmap) 0;
762 XChangeGC (display, gc, GCClipMask, &gcv);
763 XFreePixmap (display, clipmask);
767 XSetClipMask (display, gc, None);
770 /***********************************************************************
771 Glyph display
772 ***********************************************************************/
776 static void x_set_glyph_string_clipping (struct glyph_string *);
777 static void x_set_glyph_string_gc (struct glyph_string *);
778 static void x_draw_glyph_string_foreground (struct glyph_string *);
779 static void x_draw_composite_glyph_string_foreground (struct glyph_string *);
780 static void x_draw_glyph_string_box (struct glyph_string *);
781 static void x_draw_glyph_string (struct glyph_string *);
782 static _Noreturn void x_delete_glyphs (struct frame *, int);
783 static void x_compute_glyph_string_overhangs (struct glyph_string *);
784 static void x_set_cursor_gc (struct glyph_string *);
785 static void x_set_mode_line_face_gc (struct glyph_string *);
786 static void x_set_mouse_face_gc (struct glyph_string *);
787 static bool x_alloc_lighter_color (struct frame *, Display *, Colormap,
788 unsigned long *, double, int);
789 static void x_setup_relief_color (struct frame *, struct relief *,
790 double, int, unsigned long);
791 static void x_setup_relief_colors (struct glyph_string *);
792 static void x_draw_image_glyph_string (struct glyph_string *);
793 static void x_draw_image_relief (struct glyph_string *);
794 static void x_draw_image_foreground (struct glyph_string *);
795 static void x_draw_image_foreground_1 (struct glyph_string *, Pixmap);
796 static void x_clear_glyph_string_rect (struct glyph_string *, int,
797 int, int, int);
798 static void x_draw_relief_rect (struct frame *, int, int, int, int,
799 int, int, int, int, int, int,
800 XRectangle *);
801 static void x_draw_box_rect (struct glyph_string *, int, int, int, int,
802 int, int, int, XRectangle *);
803 static void x_scroll_bar_clear (struct frame *);
805 #ifdef GLYPH_DEBUG
806 static void x_check_font (struct frame *, struct font *);
807 #endif
810 /* Set S->gc to a suitable GC for drawing glyph string S in cursor
811 face. */
813 static void
814 x_set_cursor_gc (struct glyph_string *s)
816 if (s->font == FRAME_FONT (s->f)
817 && s->face->background == FRAME_BACKGROUND_PIXEL (s->f)
818 && s->face->foreground == FRAME_FOREGROUND_PIXEL (s->f)
819 && !s->cmp)
820 s->gc = s->f->output_data.x->cursor_gc;
821 else
823 /* Cursor on non-default face: must merge. */
824 XGCValues xgcv;
825 unsigned long mask;
827 xgcv.background = s->f->output_data.x->cursor_pixel;
828 xgcv.foreground = s->face->background;
830 /* If the glyph would be invisible, try a different foreground. */
831 if (xgcv.foreground == xgcv.background)
832 xgcv.foreground = s->face->foreground;
833 if (xgcv.foreground == xgcv.background)
834 xgcv.foreground = s->f->output_data.x->cursor_foreground_pixel;
835 if (xgcv.foreground == xgcv.background)
836 xgcv.foreground = s->face->foreground;
838 /* Make sure the cursor is distinct from text in this face. */
839 if (xgcv.background == s->face->background
840 && xgcv.foreground == s->face->foreground)
842 xgcv.background = s->face->foreground;
843 xgcv.foreground = s->face->background;
846 IF_DEBUG (x_check_font (s->f, s->font));
847 xgcv.graphics_exposures = False;
848 mask = GCForeground | GCBackground | GCGraphicsExposures;
850 if (FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc)
851 XChangeGC (s->display, FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc,
852 mask, &xgcv);
853 else
854 FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc
855 = XCreateGC (s->display, s->window, mask, &xgcv);
857 s->gc = FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc;
862 /* Set up S->gc of glyph string S for drawing text in mouse face. */
864 static void
865 x_set_mouse_face_gc (struct glyph_string *s)
867 int face_id;
868 struct face *face;
870 /* What face has to be used last for the mouse face? */
871 face_id = MOUSE_HL_INFO (s->f)->mouse_face_face_id;
872 face = FACE_FROM_ID (s->f, face_id);
873 if (face == NULL)
874 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
876 if (s->first_glyph->type == CHAR_GLYPH)
877 face_id = FACE_FOR_CHAR (s->f, face, s->first_glyph->u.ch, -1, Qnil);
878 else
879 face_id = FACE_FOR_CHAR (s->f, face, 0, -1, Qnil);
880 s->face = FACE_FROM_ID (s->f, face_id);
881 PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
883 if (s->font == s->face->font)
884 s->gc = s->face->gc;
885 else
887 /* Otherwise construct scratch_cursor_gc with values from FACE
888 except for FONT. */
889 XGCValues xgcv;
890 unsigned long mask;
892 xgcv.background = s->face->background;
893 xgcv.foreground = s->face->foreground;
894 xgcv.graphics_exposures = False;
895 mask = GCForeground | GCBackground | GCGraphicsExposures;
897 if (FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc)
898 XChangeGC (s->display, FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc,
899 mask, &xgcv);
900 else
901 FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc
902 = XCreateGC (s->display, s->window, mask, &xgcv);
904 s->gc = FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc;
907 eassert (s->gc != 0);
911 /* Set S->gc of glyph string S to a GC suitable for drawing a mode line.
912 Faces to use in the mode line have already been computed when the
913 matrix was built, so there isn't much to do, here. */
915 static void
916 x_set_mode_line_face_gc (struct glyph_string *s)
918 s->gc = s->face->gc;
922 /* Set S->gc of glyph string S for drawing that glyph string. Set
923 S->stippled_p to a non-zero value if the face of S has a stipple
924 pattern. */
926 static void
927 x_set_glyph_string_gc (struct glyph_string *s)
929 PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
931 if (s->hl == DRAW_NORMAL_TEXT)
933 s->gc = s->face->gc;
934 s->stippled_p = s->face->stipple != 0;
936 else if (s->hl == DRAW_INVERSE_VIDEO)
938 x_set_mode_line_face_gc (s);
939 s->stippled_p = s->face->stipple != 0;
941 else if (s->hl == DRAW_CURSOR)
943 x_set_cursor_gc (s);
944 s->stippled_p = 0;
946 else if (s->hl == DRAW_MOUSE_FACE)
948 x_set_mouse_face_gc (s);
949 s->stippled_p = s->face->stipple != 0;
951 else if (s->hl == DRAW_IMAGE_RAISED
952 || s->hl == DRAW_IMAGE_SUNKEN)
954 s->gc = s->face->gc;
955 s->stippled_p = s->face->stipple != 0;
957 else
959 s->gc = s->face->gc;
960 s->stippled_p = s->face->stipple != 0;
963 /* GC must have been set. */
964 eassert (s->gc != 0);
968 /* Set clipping for output of glyph string S. S may be part of a mode
969 line or menu if we don't have X toolkit support. */
971 static void
972 x_set_glyph_string_clipping (struct glyph_string *s)
974 XRectangle *r = s->clip;
975 int n = get_glyph_string_clip_rects (s, r, 2);
977 if (n > 0)
978 XSetClipRectangles (s->display, s->gc, 0, 0, r, n, Unsorted);
979 s->num_clips = n;
983 /* Set SRC's clipping for output of glyph string DST. This is called
984 when we are drawing DST's left_overhang or right_overhang only in
985 the area of SRC. */
987 static void
988 x_set_glyph_string_clipping_exactly (struct glyph_string *src, struct glyph_string *dst)
990 XRectangle r;
992 r.x = src->x;
993 r.width = src->width;
994 r.y = src->y;
995 r.height = src->height;
996 dst->clip[0] = r;
997 dst->num_clips = 1;
998 XSetClipRectangles (dst->display, dst->gc, 0, 0, &r, 1, Unsorted);
1002 /* RIF:
1003 Compute left and right overhang of glyph string S. */
1005 static void
1006 x_compute_glyph_string_overhangs (struct glyph_string *s)
1008 if (s->cmp == NULL
1009 && (s->first_glyph->type == CHAR_GLYPH
1010 || s->first_glyph->type == COMPOSITE_GLYPH))
1012 struct font_metrics metrics;
1014 if (s->first_glyph->type == CHAR_GLYPH)
1016 unsigned *code = alloca (sizeof (unsigned) * s->nchars);
1017 struct font *font = s->font;
1018 int i;
1020 for (i = 0; i < s->nchars; i++)
1021 code[i] = (s->char2b[i].byte1 << 8) | s->char2b[i].byte2;
1022 font->driver->text_extents (font, code, s->nchars, &metrics);
1024 else
1026 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1028 composition_gstring_width (gstring, s->cmp_from, s->cmp_to, &metrics);
1030 s->right_overhang = (metrics.rbearing > metrics.width
1031 ? metrics.rbearing - metrics.width : 0);
1032 s->left_overhang = metrics.lbearing < 0 ? - metrics.lbearing : 0;
1034 else if (s->cmp)
1036 s->right_overhang = s->cmp->rbearing - s->cmp->pixel_width;
1037 s->left_overhang = - s->cmp->lbearing;
1042 /* Fill rectangle X, Y, W, H with background color of glyph string S. */
1044 static void
1045 x_clear_glyph_string_rect (struct glyph_string *s, int x, int y, int w, int h)
1047 XGCValues xgcv;
1048 XGetGCValues (s->display, s->gc, GCForeground | GCBackground, &xgcv);
1049 XSetForeground (s->display, s->gc, xgcv.background);
1050 XFillRectangle (s->display, s->window, s->gc, x, y, w, h);
1051 XSetForeground (s->display, s->gc, xgcv.foreground);
1055 /* Draw the background of glyph_string S. If S->background_filled_p
1056 is non-zero don't draw it. FORCE_P non-zero means draw the
1057 background even if it wouldn't be drawn normally. This is used
1058 when a string preceding S draws into the background of S, or S
1059 contains the first component of a composition. */
1061 static void
1062 x_draw_glyph_string_background (struct glyph_string *s, bool force_p)
1064 /* Nothing to do if background has already been drawn or if it
1065 shouldn't be drawn in the first place. */
1066 if (!s->background_filled_p)
1068 int box_line_width = max (s->face->box_line_width, 0);
1070 if (s->stippled_p)
1072 /* Fill background with a stipple pattern. */
1073 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
1074 XFillRectangle (s->display, s->window, s->gc, s->x,
1075 s->y + box_line_width,
1076 s->background_width,
1077 s->height - 2 * box_line_width);
1078 XSetFillStyle (s->display, s->gc, FillSolid);
1079 s->background_filled_p = 1;
1081 else if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
1082 || s->font_not_found_p
1083 || s->extends_to_end_of_line_p
1084 || force_p)
1086 x_clear_glyph_string_rect (s, s->x, s->y + box_line_width,
1087 s->background_width,
1088 s->height - 2 * box_line_width);
1089 s->background_filled_p = 1;
1095 /* Draw the foreground of glyph string S. */
1097 static void
1098 x_draw_glyph_string_foreground (struct glyph_string *s)
1100 int i, x;
1102 /* If first glyph of S has a left box line, start drawing the text
1103 of S to the right of that box line. */
1104 if (s->face->box != FACE_NO_BOX
1105 && s->first_glyph->left_box_line_p)
1106 x = s->x + eabs (s->face->box_line_width);
1107 else
1108 x = s->x;
1110 /* Draw characters of S as rectangles if S's font could not be
1111 loaded. */
1112 if (s->font_not_found_p)
1114 for (i = 0; i < s->nchars; ++i)
1116 struct glyph *g = s->first_glyph + i;
1117 XDrawRectangle (s->display, s->window,
1118 s->gc, x, s->y, g->pixel_width - 1,
1119 s->height - 1);
1120 x += g->pixel_width;
1123 else
1125 struct font *font = s->font;
1126 int boff = font->baseline_offset;
1127 int y;
1129 if (font->vertical_centering)
1130 boff = VCENTER_BASELINE_OFFSET (font, s->f) - boff;
1132 y = s->ybase - boff;
1133 if (s->for_overlaps
1134 || (s->background_filled_p && s->hl != DRAW_CURSOR))
1135 font->driver->draw (s, 0, s->nchars, x, y, 0);
1136 else
1137 font->driver->draw (s, 0, s->nchars, x, y, 1);
1138 if (s->face->overstrike)
1139 font->driver->draw (s, 0, s->nchars, x + 1, y, 0);
1143 /* Draw the foreground of composite glyph string S. */
1145 static void
1146 x_draw_composite_glyph_string_foreground (struct glyph_string *s)
1148 int i, j, x;
1149 struct font *font = s->font;
1151 /* If first glyph of S has a left box line, start drawing the text
1152 of S to the right of that box line. */
1153 if (s->face && s->face->box != FACE_NO_BOX
1154 && s->first_glyph->left_box_line_p)
1155 x = s->x + eabs (s->face->box_line_width);
1156 else
1157 x = s->x;
1159 /* S is a glyph string for a composition. S->cmp_from is the index
1160 of the first character drawn for glyphs of this composition.
1161 S->cmp_from == 0 means we are drawing the very first character of
1162 this composition. */
1164 /* Draw a rectangle for the composition if the font for the very
1165 first character of the composition could not be loaded. */
1166 if (s->font_not_found_p)
1168 if (s->cmp_from == 0)
1169 XDrawRectangle (s->display, s->window, s->gc, x, s->y,
1170 s->width - 1, s->height - 1);
1172 else if (! s->first_glyph->u.cmp.automatic)
1174 int y = s->ybase;
1176 for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
1177 /* TAB in a composition means display glyphs with padding
1178 space on the left or right. */
1179 if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
1181 int xx = x + s->cmp->offsets[j * 2];
1182 int yy = y - s->cmp->offsets[j * 2 + 1];
1184 font->driver->draw (s, j, j + 1, xx, yy, 0);
1185 if (s->face->overstrike)
1186 font->driver->draw (s, j, j + 1, xx + 1, yy, 0);
1189 else
1191 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1192 Lisp_Object glyph;
1193 int y = s->ybase;
1194 int width = 0;
1196 for (i = j = s->cmp_from; i < s->cmp_to; i++)
1198 glyph = LGSTRING_GLYPH (gstring, i);
1199 if (NILP (LGLYPH_ADJUSTMENT (glyph)))
1200 width += LGLYPH_WIDTH (glyph);
1201 else
1203 int xoff, yoff, wadjust;
1205 if (j < i)
1207 font->driver->draw (s, j, i, x, y, 0);
1208 if (s->face->overstrike)
1209 font->driver->draw (s, j, i, x + 1, y, 0);
1210 x += width;
1212 xoff = LGLYPH_XOFF (glyph);
1213 yoff = LGLYPH_YOFF (glyph);
1214 wadjust = LGLYPH_WADJUST (glyph);
1215 font->driver->draw (s, i, i + 1, x + xoff, y + yoff, 0);
1216 if (s->face->overstrike)
1217 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff, 0);
1218 x += wadjust;
1219 j = i + 1;
1220 width = 0;
1223 if (j < i)
1225 font->driver->draw (s, j, i, x, y, 0);
1226 if (s->face->overstrike)
1227 font->driver->draw (s, j, i, x + 1, y, 0);
1233 /* Draw the foreground of glyph string S for glyphless characters. */
1235 static void
1236 x_draw_glyphless_glyph_string_foreground (struct glyph_string *s)
1238 struct glyph *glyph = s->first_glyph;
1239 XChar2b char2b[8];
1240 int x, i, j;
1242 /* If first glyph of S has a left box line, start drawing the text
1243 of S to the right of that box line. */
1244 if (s->face && s->face->box != FACE_NO_BOX
1245 && s->first_glyph->left_box_line_p)
1246 x = s->x + eabs (s->face->box_line_width);
1247 else
1248 x = s->x;
1250 s->char2b = char2b;
1252 for (i = 0; i < s->nchars; i++, glyph++)
1254 char buf[7], *str = NULL;
1255 int len = glyph->u.glyphless.len;
1257 if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_ACRONYM)
1259 if (len > 0
1260 && CHAR_TABLE_P (Vglyphless_char_display)
1261 && (CHAR_TABLE_EXTRA_SLOTS (XCHAR_TABLE (Vglyphless_char_display))
1262 >= 1))
1264 Lisp_Object acronym
1265 = (! glyph->u.glyphless.for_no_font
1266 ? CHAR_TABLE_REF (Vglyphless_char_display,
1267 glyph->u.glyphless.ch)
1268 : XCHAR_TABLE (Vglyphless_char_display)->extras[0]);
1269 if (STRINGP (acronym))
1270 str = SSDATA (acronym);
1273 else if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_HEX_CODE)
1275 sprintf (buf, "%0*X",
1276 glyph->u.glyphless.ch < 0x10000 ? 4 : 6,
1277 glyph->u.glyphless.ch);
1278 str = buf;
1281 if (str)
1283 int upper_len = (len + 1) / 2;
1284 unsigned code;
1286 /* It is assured that all LEN characters in STR is ASCII. */
1287 for (j = 0; j < len; j++)
1289 code = s->font->driver->encode_char (s->font, str[j]);
1290 STORE_XCHAR2B (char2b + j, code >> 8, code & 0xFF);
1292 s->font->driver->draw (s, 0, upper_len,
1293 x + glyph->slice.glyphless.upper_xoff,
1294 s->ybase + glyph->slice.glyphless.upper_yoff,
1296 s->font->driver->draw (s, upper_len, len,
1297 x + glyph->slice.glyphless.lower_xoff,
1298 s->ybase + glyph->slice.glyphless.lower_yoff,
1301 if (glyph->u.glyphless.method != GLYPHLESS_DISPLAY_THIN_SPACE)
1302 XDrawRectangle (s->display, s->window, s->gc,
1303 x, s->ybase - glyph->ascent,
1304 glyph->pixel_width - 1,
1305 glyph->ascent + glyph->descent - 1);
1306 x += glyph->pixel_width;
1310 #ifdef USE_X_TOOLKIT
1312 #ifdef USE_LUCID
1314 /* Return the frame on which widget WIDGET is used.. Abort if frame
1315 cannot be determined. */
1317 static struct frame *
1318 x_frame_of_widget (Widget widget)
1320 struct x_display_info *dpyinfo;
1321 Lisp_Object tail, frame;
1322 struct frame *f;
1324 dpyinfo = x_display_info_for_display (XtDisplay (widget));
1326 /* Find the top-level shell of the widget. Note that this function
1327 can be called when the widget is not yet realized, so XtWindow
1328 (widget) == 0. That's the reason we can't simply use
1329 x_any_window_to_frame. */
1330 while (!XtIsTopLevelShell (widget))
1331 widget = XtParent (widget);
1333 /* Look for a frame with that top-level widget. Allocate the color
1334 on that frame to get the right gamma correction value. */
1335 FOR_EACH_FRAME (tail, frame)
1337 f = XFRAME (frame);
1338 if (FRAME_X_P (f)
1339 && f->output_data.nothing != 1
1340 && FRAME_DISPLAY_INFO (f) == dpyinfo
1341 && f->output_data.x->widget == widget)
1342 return f;
1344 emacs_abort ();
1347 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
1348 or DELTA. Try a color with RGB values multiplied by FACTOR first.
1349 If this produces the same color as PIXEL, try a color where all RGB
1350 values have DELTA added. Return the allocated color in *PIXEL.
1351 DISPLAY is the X display, CMAP is the colormap to operate on.
1352 Value is true if successful. */
1354 bool
1355 x_alloc_lighter_color_for_widget (Widget widget, Display *display, Colormap cmap,
1356 unsigned long *pixel, double factor, int delta)
1358 struct frame *f = x_frame_of_widget (widget);
1359 return x_alloc_lighter_color (f, display, cmap, pixel, factor, delta);
1362 #endif /* USE_LUCID */
1365 /* Structure specifying which arguments should be passed by Xt to
1366 cvt_string_to_pixel. We want the widget's screen and colormap. */
1368 static XtConvertArgRec cvt_string_to_pixel_args[] =
1370 {XtWidgetBaseOffset, (XtPointer) XtOffset (Widget, core.screen),
1371 sizeof (Screen *)},
1372 {XtWidgetBaseOffset, (XtPointer) XtOffset (Widget, core.colormap),
1373 sizeof (Colormap)}
1377 /* The address of this variable is returned by
1378 cvt_string_to_pixel. */
1380 static Pixel cvt_string_to_pixel_value;
1383 /* Convert a color name to a pixel color.
1385 DPY is the display we are working on.
1387 ARGS is an array of *NARGS XrmValue structures holding additional
1388 information about the widget for which the conversion takes place.
1389 The contents of this array are determined by the specification
1390 in cvt_string_to_pixel_args.
1392 FROM is a pointer to an XrmValue which points to the color name to
1393 convert. TO is an XrmValue in which to return the pixel color.
1395 CLOSURE_RET is a pointer to user-data, in which we record if
1396 we allocated the color or not.
1398 Value is True if successful, False otherwise. */
1400 static Boolean
1401 cvt_string_to_pixel (Display *dpy, XrmValue *args, Cardinal *nargs,
1402 XrmValue *from, XrmValue *to,
1403 XtPointer *closure_ret)
1405 Screen *screen;
1406 Colormap cmap;
1407 Pixel pixel;
1408 String color_name;
1409 XColor color;
1411 if (*nargs != 2)
1413 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
1414 "wrongParameters", "cvt_string_to_pixel",
1415 "XtToolkitError",
1416 "Screen and colormap args required", NULL, NULL);
1417 return False;
1420 screen = *(Screen **) args[0].addr;
1421 cmap = *(Colormap *) args[1].addr;
1422 color_name = (String) from->addr;
1424 if (strcmp (color_name, XtDefaultBackground) == 0)
1426 *closure_ret = (XtPointer) False;
1427 pixel = WhitePixelOfScreen (screen);
1429 else if (strcmp (color_name, XtDefaultForeground) == 0)
1431 *closure_ret = (XtPointer) False;
1432 pixel = BlackPixelOfScreen (screen);
1434 else if (XParseColor (dpy, cmap, color_name, &color)
1435 && x_alloc_nearest_color_1 (dpy, cmap, &color))
1437 pixel = color.pixel;
1438 *closure_ret = (XtPointer) True;
1440 else
1442 String params[1];
1443 Cardinal nparams = 1;
1445 params[0] = color_name;
1446 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
1447 "badValue", "cvt_string_to_pixel",
1448 "XtToolkitError", "Invalid color `%s'",
1449 params, &nparams);
1450 return False;
1453 if (to->addr != NULL)
1455 if (to->size < sizeof (Pixel))
1457 to->size = sizeof (Pixel);
1458 return False;
1461 *(Pixel *) to->addr = pixel;
1463 else
1465 cvt_string_to_pixel_value = pixel;
1466 to->addr = (XtPointer) &cvt_string_to_pixel_value;
1469 to->size = sizeof (Pixel);
1470 return True;
1474 /* Free a pixel color which was previously allocated via
1475 cvt_string_to_pixel. This is registered as the destructor
1476 for this type of resource via XtSetTypeConverter.
1478 APP is the application context in which we work.
1480 TO is a pointer to an XrmValue holding the color to free.
1481 CLOSURE is the value we stored in CLOSURE_RET for this color
1482 in cvt_string_to_pixel.
1484 ARGS and NARGS are like for cvt_string_to_pixel. */
1486 static void
1487 cvt_pixel_dtor (XtAppContext app, XrmValuePtr to, XtPointer closure, XrmValuePtr args,
1488 Cardinal *nargs)
1490 if (*nargs != 2)
1492 XtAppWarningMsg (app, "wrongParameters", "cvt_pixel_dtor",
1493 "XtToolkitError",
1494 "Screen and colormap arguments required",
1495 NULL, NULL);
1497 else if (closure != NULL)
1499 /* We did allocate the pixel, so free it. */
1500 Screen *screen = *(Screen **) args[0].addr;
1501 Colormap cmap = *(Colormap *) args[1].addr;
1502 x_free_dpy_colors (DisplayOfScreen (screen), screen, cmap,
1503 (Pixel *) to->addr, 1);
1508 #endif /* USE_X_TOOLKIT */
1511 /* Value is an array of XColor structures for the contents of the
1512 color map of display DPY. Set *NCELLS to the size of the array.
1513 Note that this probably shouldn't be called for large color maps,
1514 say a 24-bit TrueColor map. */
1516 static const XColor *
1517 x_color_cells (Display *dpy, int *ncells)
1519 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
1521 if (dpyinfo->color_cells == NULL)
1523 Screen *screen = dpyinfo->screen;
1524 int ncolor_cells = XDisplayCells (dpy, XScreenNumberOfScreen (screen));
1525 int i;
1527 dpyinfo->color_cells = xnmalloc (ncolor_cells,
1528 sizeof *dpyinfo->color_cells);
1529 dpyinfo->ncolor_cells = ncolor_cells;
1531 for (i = 0; i < ncolor_cells; ++i)
1532 dpyinfo->color_cells[i].pixel = i;
1534 XQueryColors (dpy, dpyinfo->cmap,
1535 dpyinfo->color_cells, ncolor_cells);
1538 *ncells = dpyinfo->ncolor_cells;
1539 return dpyinfo->color_cells;
1543 /* On frame F, translate pixel colors to RGB values for the NCOLORS
1544 colors in COLORS. Use cached information, if available. */
1546 void
1547 x_query_colors (struct frame *f, XColor *colors, int ncolors)
1549 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1551 if (dpyinfo->color_cells)
1553 int i;
1554 for (i = 0; i < ncolors; ++i)
1556 unsigned long pixel = colors[i].pixel;
1557 eassert (pixel < dpyinfo->ncolor_cells);
1558 eassert (dpyinfo->color_cells[pixel].pixel == pixel);
1559 colors[i] = dpyinfo->color_cells[pixel];
1562 else
1563 XQueryColors (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), colors, ncolors);
1567 /* On frame F, translate pixel color to RGB values for the color in
1568 COLOR. Use cached information, if available. */
1570 void
1571 x_query_color (struct frame *f, XColor *color)
1573 x_query_colors (f, color, 1);
1577 /* Allocate the color COLOR->pixel on DISPLAY, colormap CMAP. If an
1578 exact match can't be allocated, try the nearest color available.
1579 Value is true if successful. Set *COLOR to the color
1580 allocated. */
1582 static bool
1583 x_alloc_nearest_color_1 (Display *dpy, Colormap cmap, XColor *color)
1585 bool rc;
1587 rc = XAllocColor (dpy, cmap, color) != 0;
1588 if (rc == 0)
1590 /* If we got to this point, the colormap is full, so we're going
1591 to try to get the next closest color. The algorithm used is
1592 a least-squares matching, which is what X uses for closest
1593 color matching with StaticColor visuals. */
1594 int nearest, i;
1595 int max_color_delta = 255;
1596 int max_delta = 3 * max_color_delta;
1597 int nearest_delta = max_delta + 1;
1598 int ncells;
1599 const XColor *cells = x_color_cells (dpy, &ncells);
1601 for (nearest = i = 0; i < ncells; ++i)
1603 int dred = (color->red >> 8) - (cells[i].red >> 8);
1604 int dgreen = (color->green >> 8) - (cells[i].green >> 8);
1605 int dblue = (color->blue >> 8) - (cells[i].blue >> 8);
1606 int delta = dred * dred + dgreen * dgreen + dblue * dblue;
1608 if (delta < nearest_delta)
1610 nearest = i;
1611 nearest_delta = delta;
1615 color->red = cells[nearest].red;
1616 color->green = cells[nearest].green;
1617 color->blue = cells[nearest].blue;
1618 rc = XAllocColor (dpy, cmap, color) != 0;
1620 else
1622 /* If allocation succeeded, and the allocated pixel color is not
1623 equal to a cached pixel color recorded earlier, there was a
1624 change in the colormap, so clear the color cache. */
1625 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
1626 XColor *cached_color;
1628 if (dpyinfo->color_cells
1629 && (cached_color = &dpyinfo->color_cells[color->pixel],
1630 (cached_color->red != color->red
1631 || cached_color->blue != color->blue
1632 || cached_color->green != color->green)))
1634 xfree (dpyinfo->color_cells);
1635 dpyinfo->color_cells = NULL;
1636 dpyinfo->ncolor_cells = 0;
1640 #ifdef DEBUG_X_COLORS
1641 if (rc)
1642 register_color (color->pixel);
1643 #endif /* DEBUG_X_COLORS */
1645 return rc;
1649 /* Allocate the color COLOR->pixel on frame F, colormap CMAP. If an
1650 exact match can't be allocated, try the nearest color available.
1651 Value is true if successful. Set *COLOR to the color
1652 allocated. */
1654 bool
1655 x_alloc_nearest_color (struct frame *f, Colormap cmap, XColor *color)
1657 gamma_correct (f, color);
1658 return x_alloc_nearest_color_1 (FRAME_X_DISPLAY (f), cmap, color);
1662 /* Allocate color PIXEL on frame F. PIXEL must already be allocated.
1663 It's necessary to do this instead of just using PIXEL directly to
1664 get color reference counts right. */
1666 unsigned long
1667 x_copy_color (struct frame *f, unsigned long pixel)
1669 XColor color;
1671 color.pixel = pixel;
1672 block_input ();
1673 x_query_color (f, &color);
1674 XAllocColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &color);
1675 unblock_input ();
1676 #ifdef DEBUG_X_COLORS
1677 register_color (pixel);
1678 #endif
1679 return color.pixel;
1683 /* Brightness beyond which a color won't have its highlight brightness
1684 boosted.
1686 Nominally, highlight colors for `3d' faces are calculated by
1687 brightening an object's color by a constant scale factor, but this
1688 doesn't yield good results for dark colors, so for colors who's
1689 brightness is less than this value (on a scale of 0-65535) have an
1690 use an additional additive factor.
1692 The value here is set so that the default menu-bar/mode-line color
1693 (grey75) will not have its highlights changed at all. */
1694 #define HIGHLIGHT_COLOR_DARK_BOOST_LIMIT 48000
1697 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
1698 or DELTA. Try a color with RGB values multiplied by FACTOR first.
1699 If this produces the same color as PIXEL, try a color where all RGB
1700 values have DELTA added. Return the allocated color in *PIXEL.
1701 DISPLAY is the X display, CMAP is the colormap to operate on.
1702 Value is non-zero if successful. */
1704 static bool
1705 x_alloc_lighter_color (struct frame *f, Display *display, Colormap cmap,
1706 unsigned long *pixel, double factor, int delta)
1708 XColor color, new;
1709 long bright;
1710 bool success_p;
1712 /* Get RGB color values. */
1713 color.pixel = *pixel;
1714 x_query_color (f, &color);
1716 /* Change RGB values by specified FACTOR. Avoid overflow! */
1717 eassert (factor >= 0);
1718 new.red = min (0xffff, factor * color.red);
1719 new.green = min (0xffff, factor * color.green);
1720 new.blue = min (0xffff, factor * color.blue);
1722 /* Calculate brightness of COLOR. */
1723 bright = (2 * color.red + 3 * color.green + color.blue) / 6;
1725 /* We only boost colors that are darker than
1726 HIGHLIGHT_COLOR_DARK_BOOST_LIMIT. */
1727 if (bright < HIGHLIGHT_COLOR_DARK_BOOST_LIMIT)
1728 /* Make an additive adjustment to NEW, because it's dark enough so
1729 that scaling by FACTOR alone isn't enough. */
1731 /* How far below the limit this color is (0 - 1, 1 being darker). */
1732 double dimness = 1 - (double)bright / HIGHLIGHT_COLOR_DARK_BOOST_LIMIT;
1733 /* The additive adjustment. */
1734 int min_delta = delta * dimness * factor / 2;
1736 if (factor < 1)
1738 new.red = max (0, new.red - min_delta);
1739 new.green = max (0, new.green - min_delta);
1740 new.blue = max (0, new.blue - min_delta);
1742 else
1744 new.red = min (0xffff, min_delta + new.red);
1745 new.green = min (0xffff, min_delta + new.green);
1746 new.blue = min (0xffff, min_delta + new.blue);
1750 /* Try to allocate the color. */
1751 success_p = x_alloc_nearest_color (f, cmap, &new);
1752 if (success_p)
1754 if (new.pixel == *pixel)
1756 /* If we end up with the same color as before, try adding
1757 delta to the RGB values. */
1758 x_free_colors (f, &new.pixel, 1);
1760 new.red = min (0xffff, delta + color.red);
1761 new.green = min (0xffff, delta + color.green);
1762 new.blue = min (0xffff, delta + color.blue);
1763 success_p = x_alloc_nearest_color (f, cmap, &new);
1765 else
1766 success_p = 1;
1767 *pixel = new.pixel;
1770 return success_p;
1774 /* Set up the foreground color for drawing relief lines of glyph
1775 string S. RELIEF is a pointer to a struct relief containing the GC
1776 with which lines will be drawn. Use a color that is FACTOR or
1777 DELTA lighter or darker than the relief's background which is found
1778 in S->f->output_data.x->relief_background. If such a color cannot
1779 be allocated, use DEFAULT_PIXEL, instead. */
1781 static void
1782 x_setup_relief_color (struct frame *f, struct relief *relief, double factor,
1783 int delta, unsigned long default_pixel)
1785 XGCValues xgcv;
1786 struct x_output *di = f->output_data.x;
1787 unsigned long mask = GCForeground | GCLineWidth | GCGraphicsExposures;
1788 unsigned long pixel;
1789 unsigned long background = di->relief_background;
1790 Colormap cmap = FRAME_X_COLORMAP (f);
1791 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1792 Display *dpy = FRAME_X_DISPLAY (f);
1794 xgcv.graphics_exposures = False;
1795 xgcv.line_width = 1;
1797 /* Free previously allocated color. The color cell will be reused
1798 when it has been freed as many times as it was allocated, so this
1799 doesn't affect faces using the same colors. */
1800 if (relief->gc && relief->pixel != -1)
1802 x_free_colors (f, &relief->pixel, 1);
1803 relief->pixel = -1;
1806 /* Allocate new color. */
1807 xgcv.foreground = default_pixel;
1808 pixel = background;
1809 if (dpyinfo->n_planes != 1
1810 && x_alloc_lighter_color (f, dpy, cmap, &pixel, factor, delta))
1811 xgcv.foreground = relief->pixel = pixel;
1813 if (relief->gc == 0)
1815 xgcv.stipple = dpyinfo->gray;
1816 mask |= GCStipple;
1817 relief->gc = XCreateGC (dpy, FRAME_X_WINDOW (f), mask, &xgcv);
1819 else
1820 XChangeGC (dpy, relief->gc, mask, &xgcv);
1824 /* Set up colors for the relief lines around glyph string S. */
1826 static void
1827 x_setup_relief_colors (struct glyph_string *s)
1829 struct x_output *di = s->f->output_data.x;
1830 unsigned long color;
1832 if (s->face->use_box_color_for_shadows_p)
1833 color = s->face->box_color;
1834 else if (s->first_glyph->type == IMAGE_GLYPH
1835 && s->img->pixmap
1836 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
1837 color = IMAGE_BACKGROUND (s->img, s->f, 0);
1838 else
1840 XGCValues xgcv;
1842 /* Get the background color of the face. */
1843 XGetGCValues (s->display, s->gc, GCBackground, &xgcv);
1844 color = xgcv.background;
1847 if (di->white_relief.gc == 0
1848 || color != di->relief_background)
1850 di->relief_background = color;
1851 x_setup_relief_color (s->f, &di->white_relief, 1.2, 0x8000,
1852 WHITE_PIX_DEFAULT (s->f));
1853 x_setup_relief_color (s->f, &di->black_relief, 0.6, 0x4000,
1854 BLACK_PIX_DEFAULT (s->f));
1859 /* Draw a relief on frame F inside the rectangle given by LEFT_X,
1860 TOP_Y, RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the relief
1861 to draw, it must be >= 0. RAISED_P non-zero means draw a raised
1862 relief. LEFT_P non-zero means draw a relief on the left side of
1863 the rectangle. RIGHT_P non-zero means draw a relief on the right
1864 side of the rectangle. CLIP_RECT is the clipping rectangle to use
1865 when drawing. */
1867 static void
1868 x_draw_relief_rect (struct frame *f,
1869 int left_x, int top_y, int right_x, int bottom_y, int width,
1870 int raised_p, int top_p, int bot_p, int left_p, int right_p,
1871 XRectangle *clip_rect)
1873 Display *dpy = FRAME_X_DISPLAY (f);
1874 Window window = FRAME_X_WINDOW (f);
1875 int i;
1876 GC gc;
1878 if (raised_p)
1879 gc = f->output_data.x->white_relief.gc;
1880 else
1881 gc = f->output_data.x->black_relief.gc;
1882 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
1884 /* This code is more complicated than it has to be, because of two
1885 minor hacks to make the boxes look nicer: (i) if width > 1, draw
1886 the outermost line using the black relief. (ii) Omit the four
1887 corner pixels. */
1889 /* Top. */
1890 if (top_p)
1892 if (width == 1)
1893 XDrawLine (dpy, window, gc,
1894 left_x + (left_p ? 1 : 0), top_y,
1895 right_x + (right_p ? 0 : 1), top_y);
1897 for (i = 1; i < width; ++i)
1898 XDrawLine (dpy, window, gc,
1899 left_x + i * left_p, top_y + i,
1900 right_x + 1 - i * right_p, top_y + i);
1903 /* Left. */
1904 if (left_p)
1906 if (width == 1)
1907 XDrawLine (dpy, window, gc, left_x, top_y + 1, left_x, bottom_y);
1909 XClearArea (dpy, window, left_x, top_y, 1, 1, False);
1910 XClearArea (dpy, window, left_x, bottom_y, 1, 1, False);
1912 for (i = (width > 1 ? 1 : 0); i < width; ++i)
1913 XDrawLine (dpy, window, gc,
1914 left_x + i, top_y + (i + 1) * top_p,
1915 left_x + i, bottom_y + 1 - (i + 1) * bot_p);
1918 XSetClipMask (dpy, gc, None);
1919 if (raised_p)
1920 gc = f->output_data.x->black_relief.gc;
1921 else
1922 gc = f->output_data.x->white_relief.gc;
1923 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
1925 if (width > 1)
1927 /* Outermost top line. */
1928 if (top_p)
1929 XDrawLine (dpy, window, gc,
1930 left_x + (left_p ? 1 : 0), top_y,
1931 right_x + (right_p ? 0 : 1), top_y);
1933 /* Outermost left line. */
1934 if (left_p)
1935 XDrawLine (dpy, window, gc, left_x, top_y + 1, left_x, bottom_y);
1938 /* Bottom. */
1939 if (bot_p)
1941 XDrawLine (dpy, window, gc,
1942 left_x + (left_p ? 1 : 0), bottom_y,
1943 right_x + (right_p ? 0 : 1), bottom_y);
1944 for (i = 1; i < width; ++i)
1945 XDrawLine (dpy, window, gc,
1946 left_x + i * left_p, bottom_y - i,
1947 right_x + 1 - i * right_p, bottom_y - i);
1950 /* Right. */
1951 if (right_p)
1953 XClearArea (dpy, window, right_x, top_y, 1, 1, False);
1954 XClearArea (dpy, window, right_x, bottom_y, 1, 1, False);
1955 for (i = 0; i < width; ++i)
1956 XDrawLine (dpy, window, gc,
1957 right_x - i, top_y + (i + 1) * top_p,
1958 right_x - i, bottom_y + 1 - (i + 1) * bot_p);
1961 XSetClipMask (dpy, gc, None);
1965 /* Draw a box on frame F inside the rectangle given by LEFT_X, TOP_Y,
1966 RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the lines to
1967 draw, it must be >= 0. LEFT_P non-zero means draw a line on the
1968 left side of the rectangle. RIGHT_P non-zero means draw a line
1969 on the right side of the rectangle. CLIP_RECT is the clipping
1970 rectangle to use when drawing. */
1972 static void
1973 x_draw_box_rect (struct glyph_string *s,
1974 int left_x, int top_y, int right_x, int bottom_y, int width,
1975 int left_p, int right_p, XRectangle *clip_rect)
1977 XGCValues xgcv;
1979 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
1980 XSetForeground (s->display, s->gc, s->face->box_color);
1981 XSetClipRectangles (s->display, s->gc, 0, 0, clip_rect, 1, Unsorted);
1983 /* Top. */
1984 XFillRectangle (s->display, s->window, s->gc,
1985 left_x, top_y, right_x - left_x + 1, width);
1987 /* Left. */
1988 if (left_p)
1989 XFillRectangle (s->display, s->window, s->gc,
1990 left_x, top_y, width, bottom_y - top_y + 1);
1992 /* Bottom. */
1993 XFillRectangle (s->display, s->window, s->gc,
1994 left_x, bottom_y - width + 1, right_x - left_x + 1, width);
1996 /* Right. */
1997 if (right_p)
1998 XFillRectangle (s->display, s->window, s->gc,
1999 right_x - width + 1, top_y, width, bottom_y - top_y + 1);
2001 XSetForeground (s->display, s->gc, xgcv.foreground);
2002 XSetClipMask (s->display, s->gc, None);
2006 /* Draw a box around glyph string S. */
2008 static void
2009 x_draw_glyph_string_box (struct glyph_string *s)
2011 int width, left_x, right_x, top_y, bottom_y, last_x, raised_p;
2012 int left_p, right_p;
2013 struct glyph *last_glyph;
2014 XRectangle clip_rect;
2016 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2017 ? WINDOW_RIGHT_EDGE_X (s->w)
2018 : window_box_right (s->w, s->area));
2020 /* The glyph that may have a right box line. */
2021 last_glyph = (s->cmp || s->img
2022 ? s->first_glyph
2023 : s->first_glyph + s->nchars - 1);
2025 width = eabs (s->face->box_line_width);
2026 raised_p = s->face->box == FACE_RAISED_BOX;
2027 left_x = s->x;
2028 right_x = (s->row->full_width_p && s->extends_to_end_of_line_p
2029 ? last_x - 1
2030 : min (last_x, s->x + s->background_width) - 1);
2031 top_y = s->y;
2032 bottom_y = top_y + s->height - 1;
2034 left_p = (s->first_glyph->left_box_line_p
2035 || (s->hl == DRAW_MOUSE_FACE
2036 && (s->prev == NULL
2037 || s->prev->hl != s->hl)));
2038 right_p = (last_glyph->right_box_line_p
2039 || (s->hl == DRAW_MOUSE_FACE
2040 && (s->next == NULL
2041 || s->next->hl != s->hl)));
2043 get_glyph_string_clip_rect (s, &clip_rect);
2045 if (s->face->box == FACE_SIMPLE_BOX)
2046 x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
2047 left_p, right_p, &clip_rect);
2048 else
2050 x_setup_relief_colors (s);
2051 x_draw_relief_rect (s->f, left_x, top_y, right_x, bottom_y,
2052 width, raised_p, 1, 1, left_p, right_p, &clip_rect);
2057 /* Draw foreground of image glyph string S. */
2059 static void
2060 x_draw_image_foreground (struct glyph_string *s)
2062 int x = s->x;
2063 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2065 /* If first glyph of S has a left box line, start drawing it to the
2066 right of that line. */
2067 if (s->face->box != FACE_NO_BOX
2068 && s->first_glyph->left_box_line_p
2069 && s->slice.x == 0)
2070 x += eabs (s->face->box_line_width);
2072 /* If there is a margin around the image, adjust x- and y-position
2073 by that margin. */
2074 if (s->slice.x == 0)
2075 x += s->img->hmargin;
2076 if (s->slice.y == 0)
2077 y += s->img->vmargin;
2079 if (s->img->pixmap)
2081 if (s->img->mask)
2083 /* We can't set both a clip mask and use XSetClipRectangles
2084 because the latter also sets a clip mask. We also can't
2085 trust on the shape extension to be available
2086 (XShapeCombineRegion). So, compute the rectangle to draw
2087 manually. */
2088 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
2089 | GCFunction);
2090 XGCValues xgcv;
2091 XRectangle clip_rect, image_rect, r;
2093 xgcv.clip_mask = s->img->mask;
2094 xgcv.clip_x_origin = x;
2095 xgcv.clip_y_origin = y;
2096 xgcv.function = GXcopy;
2097 XChangeGC (s->display, s->gc, mask, &xgcv);
2099 get_glyph_string_clip_rect (s, &clip_rect);
2100 image_rect.x = x;
2101 image_rect.y = y;
2102 image_rect.width = s->slice.width;
2103 image_rect.height = s->slice.height;
2104 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
2105 XCopyArea (s->display, s->img->pixmap, s->window, s->gc,
2106 s->slice.x + r.x - x, s->slice.y + r.y - y,
2107 r.width, r.height, r.x, r.y);
2109 else
2111 XRectangle clip_rect, image_rect, r;
2113 get_glyph_string_clip_rect (s, &clip_rect);
2114 image_rect.x = x;
2115 image_rect.y = y;
2116 image_rect.width = s->slice.width;
2117 image_rect.height = s->slice.height;
2118 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
2119 XCopyArea (s->display, s->img->pixmap, s->window, s->gc,
2120 s->slice.x + r.x - x, s->slice.y + r.y - y,
2121 r.width, r.height, r.x, r.y);
2123 /* When the image has a mask, we can expect that at
2124 least part of a mouse highlight or a block cursor will
2125 be visible. If the image doesn't have a mask, make
2126 a block cursor visible by drawing a rectangle around
2127 the image. I believe it's looking better if we do
2128 nothing here for mouse-face. */
2129 if (s->hl == DRAW_CURSOR)
2131 int relief = eabs (s->img->relief);
2132 XDrawRectangle (s->display, s->window, s->gc,
2133 x - relief, y - relief,
2134 s->slice.width + relief*2 - 1,
2135 s->slice.height + relief*2 - 1);
2139 else
2140 /* Draw a rectangle if image could not be loaded. */
2141 XDrawRectangle (s->display, s->window, s->gc, x, y,
2142 s->slice.width - 1, s->slice.height - 1);
2146 /* Draw a relief around the image glyph string S. */
2148 static void
2149 x_draw_image_relief (struct glyph_string *s)
2151 int x1, y1, thick, raised_p, top_p, bot_p, left_p, right_p;
2152 XRectangle r;
2153 int x = s->x;
2154 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2156 /* If first glyph of S has a left box line, start drawing it to the
2157 right of that line. */
2158 if (s->face->box != FACE_NO_BOX
2159 && s->first_glyph->left_box_line_p
2160 && s->slice.x == 0)
2161 x += eabs (s->face->box_line_width);
2163 /* If there is a margin around the image, adjust x- and y-position
2164 by that margin. */
2165 if (s->slice.x == 0)
2166 x += s->img->hmargin;
2167 if (s->slice.y == 0)
2168 y += s->img->vmargin;
2170 if (s->hl == DRAW_IMAGE_SUNKEN
2171 || s->hl == DRAW_IMAGE_RAISED)
2173 thick = tool_bar_button_relief >= 0 ? tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
2174 raised_p = s->hl == DRAW_IMAGE_RAISED;
2176 else
2178 thick = eabs (s->img->relief);
2179 raised_p = s->img->relief > 0;
2182 x1 = x + s->slice.width - 1;
2183 y1 = y + s->slice.height - 1;
2184 top_p = bot_p = left_p = right_p = 0;
2186 if (s->slice.x == 0)
2187 x -= thick, left_p = 1;
2188 if (s->slice.y == 0)
2189 y -= thick, top_p = 1;
2190 if (s->slice.x + s->slice.width == s->img->width)
2191 x1 += thick, right_p = 1;
2192 if (s->slice.y + s->slice.height == s->img->height)
2193 y1 += thick, bot_p = 1;
2195 x_setup_relief_colors (s);
2196 get_glyph_string_clip_rect (s, &r);
2197 x_draw_relief_rect (s->f, x, y, x1, y1, thick, raised_p,
2198 top_p, bot_p, left_p, right_p, &r);
2202 /* Draw the foreground of image glyph string S to PIXMAP. */
2204 static void
2205 x_draw_image_foreground_1 (struct glyph_string *s, Pixmap pixmap)
2207 int x = 0;
2208 int y = s->ybase - s->y - image_ascent (s->img, s->face, &s->slice);
2210 /* If first glyph of S has a left box line, start drawing it to the
2211 right of that line. */
2212 if (s->face->box != FACE_NO_BOX
2213 && s->first_glyph->left_box_line_p
2214 && s->slice.x == 0)
2215 x += eabs (s->face->box_line_width);
2217 /* If there is a margin around the image, adjust x- and y-position
2218 by that margin. */
2219 if (s->slice.x == 0)
2220 x += s->img->hmargin;
2221 if (s->slice.y == 0)
2222 y += s->img->vmargin;
2224 if (s->img->pixmap)
2226 if (s->img->mask)
2228 /* We can't set both a clip mask and use XSetClipRectangles
2229 because the latter also sets a clip mask. We also can't
2230 trust on the shape extension to be available
2231 (XShapeCombineRegion). So, compute the rectangle to draw
2232 manually. */
2233 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
2234 | GCFunction);
2235 XGCValues xgcv;
2237 xgcv.clip_mask = s->img->mask;
2238 xgcv.clip_x_origin = x - s->slice.x;
2239 xgcv.clip_y_origin = y - s->slice.y;
2240 xgcv.function = GXcopy;
2241 XChangeGC (s->display, s->gc, mask, &xgcv);
2243 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
2244 s->slice.x, s->slice.y,
2245 s->slice.width, s->slice.height, x, y);
2246 XSetClipMask (s->display, s->gc, None);
2248 else
2250 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
2251 s->slice.x, s->slice.y,
2252 s->slice.width, s->slice.height, x, y);
2254 /* When the image has a mask, we can expect that at
2255 least part of a mouse highlight or a block cursor will
2256 be visible. If the image doesn't have a mask, make
2257 a block cursor visible by drawing a rectangle around
2258 the image. I believe it's looking better if we do
2259 nothing here for mouse-face. */
2260 if (s->hl == DRAW_CURSOR)
2262 int r = eabs (s->img->relief);
2263 XDrawRectangle (s->display, s->window, s->gc, x - r, y - r,
2264 s->slice.width + r*2 - 1,
2265 s->slice.height + r*2 - 1);
2269 else
2270 /* Draw a rectangle if image could not be loaded. */
2271 XDrawRectangle (s->display, pixmap, s->gc, x, y,
2272 s->slice.width - 1, s->slice.height - 1);
2276 /* Draw part of the background of glyph string S. X, Y, W, and H
2277 give the rectangle to draw. */
2279 static void
2280 x_draw_glyph_string_bg_rect (struct glyph_string *s, int x, int y, int w, int h)
2282 if (s->stippled_p)
2284 /* Fill background with a stipple pattern. */
2285 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
2286 XFillRectangle (s->display, s->window, s->gc, x, y, w, h);
2287 XSetFillStyle (s->display, s->gc, FillSolid);
2289 else
2290 x_clear_glyph_string_rect (s, x, y, w, h);
2294 /* Draw image glyph string S.
2296 s->y
2297 s->x +-------------------------
2298 | s->face->box
2300 | +-------------------------
2301 | | s->img->margin
2303 | | +-------------------
2304 | | | the image
2308 static void
2309 x_draw_image_glyph_string (struct glyph_string *s)
2311 int box_line_hwidth = eabs (s->face->box_line_width);
2312 int box_line_vwidth = max (s->face->box_line_width, 0);
2313 int height;
2314 Pixmap pixmap = None;
2316 height = s->height;
2317 if (s->slice.y == 0)
2318 height -= box_line_vwidth;
2319 if (s->slice.y + s->slice.height >= s->img->height)
2320 height -= box_line_vwidth;
2322 /* Fill background with face under the image. Do it only if row is
2323 taller than image or if image has a clip mask to reduce
2324 flickering. */
2325 s->stippled_p = s->face->stipple != 0;
2326 if (height > s->slice.height
2327 || s->img->hmargin
2328 || s->img->vmargin
2329 || s->img->mask
2330 || s->img->pixmap == 0
2331 || s->width != s->background_width)
2333 if (s->img->mask)
2335 /* Create a pixmap as large as the glyph string. Fill it
2336 with the background color. Copy the image to it, using
2337 its mask. Copy the temporary pixmap to the display. */
2338 Screen *screen = FRAME_X_SCREEN (s->f);
2339 int depth = DefaultDepthOfScreen (screen);
2341 /* Create a pixmap as large as the glyph string. */
2342 pixmap = XCreatePixmap (s->display, s->window,
2343 s->background_width,
2344 s->height, depth);
2346 /* Don't clip in the following because we're working on the
2347 pixmap. */
2348 XSetClipMask (s->display, s->gc, None);
2350 /* Fill the pixmap with the background color/stipple. */
2351 if (s->stippled_p)
2353 /* Fill background with a stipple pattern. */
2354 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
2355 XSetTSOrigin (s->display, s->gc, - s->x, - s->y);
2356 XFillRectangle (s->display, pixmap, s->gc,
2357 0, 0, s->background_width, s->height);
2358 XSetFillStyle (s->display, s->gc, FillSolid);
2359 XSetTSOrigin (s->display, s->gc, 0, 0);
2361 else
2363 XGCValues xgcv;
2364 XGetGCValues (s->display, s->gc, GCForeground | GCBackground,
2365 &xgcv);
2366 XSetForeground (s->display, s->gc, xgcv.background);
2367 XFillRectangle (s->display, pixmap, s->gc,
2368 0, 0, s->background_width, s->height);
2369 XSetForeground (s->display, s->gc, xgcv.foreground);
2372 else
2374 int x = s->x;
2375 int y = s->y;
2377 if (s->first_glyph->left_box_line_p
2378 && s->slice.x == 0)
2379 x += box_line_hwidth;
2381 if (s->slice.y == 0)
2382 y += box_line_vwidth;
2384 x_draw_glyph_string_bg_rect (s, x, y, s->background_width, height);
2387 s->background_filled_p = 1;
2390 /* Draw the foreground. */
2391 if (pixmap != None)
2393 x_draw_image_foreground_1 (s, pixmap);
2394 x_set_glyph_string_clipping (s);
2395 XCopyArea (s->display, pixmap, s->window, s->gc,
2396 0, 0, s->background_width, s->height, s->x, s->y);
2397 XFreePixmap (s->display, pixmap);
2399 else
2400 x_draw_image_foreground (s);
2402 /* If we must draw a relief around the image, do it. */
2403 if (s->img->relief
2404 || s->hl == DRAW_IMAGE_RAISED
2405 || s->hl == DRAW_IMAGE_SUNKEN)
2406 x_draw_image_relief (s);
2410 /* Draw stretch glyph string S. */
2412 static void
2413 x_draw_stretch_glyph_string (struct glyph_string *s)
2415 eassert (s->first_glyph->type == STRETCH_GLYPH);
2417 if (s->hl == DRAW_CURSOR
2418 && !x_stretch_cursor_p)
2420 /* If `x-stretch-cursor' is nil, don't draw a block cursor as
2421 wide as the stretch glyph. */
2422 int width, background_width = s->background_width;
2423 int x = s->x;
2425 if (!s->row->reversed_p)
2427 int left_x = window_box_left_offset (s->w, TEXT_AREA);
2429 if (x < left_x)
2431 background_width -= left_x - x;
2432 x = left_x;
2435 else
2437 /* In R2L rows, draw the cursor on the right edge of the
2438 stretch glyph. */
2439 int right_x = window_box_right_offset (s->w, TEXT_AREA);
2441 if (x + background_width > right_x)
2442 background_width -= x - right_x;
2443 x += background_width;
2445 width = min (FRAME_COLUMN_WIDTH (s->f), background_width);
2446 if (s->row->reversed_p)
2447 x -= width;
2449 /* Draw cursor. */
2450 x_draw_glyph_string_bg_rect (s, x, s->y, width, s->height);
2452 /* Clear rest using the GC of the original non-cursor face. */
2453 if (width < background_width)
2455 int y = s->y;
2456 int w = background_width - width, h = s->height;
2457 XRectangle r;
2458 GC gc;
2460 if (!s->row->reversed_p)
2461 x += width;
2462 else
2463 x = s->x;
2464 if (s->row->mouse_face_p
2465 && cursor_in_mouse_face_p (s->w))
2467 x_set_mouse_face_gc (s);
2468 gc = s->gc;
2470 else
2471 gc = s->face->gc;
2473 get_glyph_string_clip_rect (s, &r);
2474 XSetClipRectangles (s->display, gc, 0, 0, &r, 1, Unsorted);
2476 if (s->face->stipple)
2478 /* Fill background with a stipple pattern. */
2479 XSetFillStyle (s->display, gc, FillOpaqueStippled);
2480 XFillRectangle (s->display, s->window, gc, x, y, w, h);
2481 XSetFillStyle (s->display, gc, FillSolid);
2483 else
2485 XGCValues xgcv;
2486 XGetGCValues (s->display, gc, GCForeground | GCBackground, &xgcv);
2487 XSetForeground (s->display, gc, xgcv.background);
2488 XFillRectangle (s->display, s->window, gc, x, y, w, h);
2489 XSetForeground (s->display, gc, xgcv.foreground);
2493 else if (!s->background_filled_p)
2495 int background_width = s->background_width;
2496 int x = s->x, left_x = window_box_left_offset (s->w, TEXT_AREA);
2498 /* Don't draw into left margin, fringe or scrollbar area
2499 except for header line and mode line. */
2500 if (x < left_x && !s->row->mode_line_p)
2502 background_width -= left_x - x;
2503 x = left_x;
2505 if (background_width > 0)
2506 x_draw_glyph_string_bg_rect (s, x, s->y, background_width, s->height);
2509 s->background_filled_p = 1;
2513 Draw a wavy line under S. The wave fills wave_height pixels from y0.
2515 x0 wave_length = 2
2517 y0 * * * * *
2518 |* * * * * * * * *
2519 wave_height = 3 | * * * *
2523 static void
2524 x_draw_underwave (struct glyph_string *s)
2526 int wave_height = 3, wave_length = 2;
2527 int dx, dy, x0, y0, width, x1, y1, x2, y2, odd, xmax;
2528 XRectangle wave_clip, string_clip, final_clip;
2530 dx = wave_length;
2531 dy = wave_height - 1;
2532 x0 = s->x;
2533 y0 = s->ybase - wave_height + 3;
2534 width = s->width;
2535 xmax = x0 + width;
2537 /* Find and set clipping rectangle */
2539 wave_clip.x = x0;
2540 wave_clip.y = y0;
2541 wave_clip.width = width;
2542 wave_clip.height = wave_height;
2543 get_glyph_string_clip_rect (s, &string_clip);
2545 if (!x_intersect_rectangles (&wave_clip, &string_clip, &final_clip))
2546 return;
2548 XSetClipRectangles (s->display, s->gc, 0, 0, &final_clip, 1, Unsorted);
2550 /* Draw the waves */
2552 x1 = x0 - (x0 % dx);
2553 x2 = x1 + dx;
2554 odd = (x1/dx) % 2;
2555 y1 = y2 = y0;
2557 if (odd)
2558 y1 += dy;
2559 else
2560 y2 += dy;
2562 if (INT_MAX - dx < xmax)
2563 emacs_abort ();
2565 while (x1 <= xmax)
2567 XDrawLine (s->display, s->window, s->gc, x1, y1, x2, y2);
2568 x1 = x2, y1 = y2;
2569 x2 += dx, y2 = y0 + odd*dy;
2570 odd = !odd;
2573 /* Restore previous clipping rectangle(s) */
2574 XSetClipRectangles (s->display, s->gc, 0, 0, s->clip, s->num_clips, Unsorted);
2578 /* Draw glyph string S. */
2580 static void
2581 x_draw_glyph_string (struct glyph_string *s)
2583 bool relief_drawn_p = 0;
2585 /* If S draws into the background of its successors, draw the
2586 background of the successors first so that S can draw into it.
2587 This makes S->next use XDrawString instead of XDrawImageString. */
2588 if (s->next && s->right_overhang && !s->for_overlaps)
2590 int width;
2591 struct glyph_string *next;
2593 for (width = 0, next = s->next;
2594 next && width < s->right_overhang;
2595 width += next->width, next = next->next)
2596 if (next->first_glyph->type != IMAGE_GLYPH)
2598 x_set_glyph_string_gc (next);
2599 x_set_glyph_string_clipping (next);
2600 if (next->first_glyph->type == STRETCH_GLYPH)
2601 x_draw_stretch_glyph_string (next);
2602 else
2603 x_draw_glyph_string_background (next, 1);
2604 next->num_clips = 0;
2608 /* Set up S->gc, set clipping and draw S. */
2609 x_set_glyph_string_gc (s);
2611 /* Draw relief (if any) in advance for char/composition so that the
2612 glyph string can be drawn over it. */
2613 if (!s->for_overlaps
2614 && s->face->box != FACE_NO_BOX
2615 && (s->first_glyph->type == CHAR_GLYPH
2616 || s->first_glyph->type == COMPOSITE_GLYPH))
2619 x_set_glyph_string_clipping (s);
2620 x_draw_glyph_string_background (s, 1);
2621 x_draw_glyph_string_box (s);
2622 x_set_glyph_string_clipping (s);
2623 relief_drawn_p = 1;
2625 else if (!s->clip_head /* draw_glyphs didn't specify a clip mask. */
2626 && !s->clip_tail
2627 && ((s->prev && s->prev->hl != s->hl && s->left_overhang)
2628 || (s->next && s->next->hl != s->hl && s->right_overhang)))
2629 /* We must clip just this glyph. left_overhang part has already
2630 drawn when s->prev was drawn, and right_overhang part will be
2631 drawn later when s->next is drawn. */
2632 x_set_glyph_string_clipping_exactly (s, s);
2633 else
2634 x_set_glyph_string_clipping (s);
2636 switch (s->first_glyph->type)
2638 case IMAGE_GLYPH:
2639 x_draw_image_glyph_string (s);
2640 break;
2642 case STRETCH_GLYPH:
2643 x_draw_stretch_glyph_string (s);
2644 break;
2646 case CHAR_GLYPH:
2647 if (s->for_overlaps)
2648 s->background_filled_p = 1;
2649 else
2650 x_draw_glyph_string_background (s, 0);
2651 x_draw_glyph_string_foreground (s);
2652 break;
2654 case COMPOSITE_GLYPH:
2655 if (s->for_overlaps || (s->cmp_from > 0
2656 && ! s->first_glyph->u.cmp.automatic))
2657 s->background_filled_p = 1;
2658 else
2659 x_draw_glyph_string_background (s, 1);
2660 x_draw_composite_glyph_string_foreground (s);
2661 break;
2663 case GLYPHLESS_GLYPH:
2664 if (s->for_overlaps)
2665 s->background_filled_p = 1;
2666 else
2667 x_draw_glyph_string_background (s, 1);
2668 x_draw_glyphless_glyph_string_foreground (s);
2669 break;
2671 default:
2672 emacs_abort ();
2675 if (!s->for_overlaps)
2677 /* Draw underline. */
2678 if (s->face->underline_p)
2680 if (s->face->underline_type == FACE_UNDER_WAVE)
2682 if (s->face->underline_defaulted_p)
2683 x_draw_underwave (s);
2684 else
2686 XGCValues xgcv;
2687 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2688 XSetForeground (s->display, s->gc, s->face->underline_color);
2689 x_draw_underwave (s);
2690 XSetForeground (s->display, s->gc, xgcv.foreground);
2693 else if (s->face->underline_type == FACE_UNDER_LINE)
2695 unsigned long thickness, position;
2696 int y;
2698 if (s->prev && s->prev->face->underline_p
2699 && s->prev->face->underline_type == FACE_UNDER_LINE)
2701 /* We use the same underline style as the previous one. */
2702 thickness = s->prev->underline_thickness;
2703 position = s->prev->underline_position;
2705 else
2707 /* Get the underline thickness. Default is 1 pixel. */
2708 if (s->font && s->font->underline_thickness > 0)
2709 thickness = s->font->underline_thickness;
2710 else
2711 thickness = 1;
2712 if (x_underline_at_descent_line)
2713 position = (s->height - thickness) - (s->ybase - s->y);
2714 else
2716 /* Get the underline position. This is the recommended
2717 vertical offset in pixels from the baseline to the top of
2718 the underline. This is a signed value according to the
2719 specs, and its default is
2721 ROUND ((maximum descent) / 2), with
2722 ROUND(x) = floor (x + 0.5) */
2724 if (x_use_underline_position_properties
2725 && s->font && s->font->underline_position >= 0)
2726 position = s->font->underline_position;
2727 else if (s->font)
2728 position = (s->font->descent + 1) / 2;
2729 else
2730 position = underline_minimum_offset;
2732 position = max (position, underline_minimum_offset);
2734 /* Check the sanity of thickness and position. We should
2735 avoid drawing underline out of the current line area. */
2736 if (s->y + s->height <= s->ybase + position)
2737 position = (s->height - 1) - (s->ybase - s->y);
2738 if (s->y + s->height < s->ybase + position + thickness)
2739 thickness = (s->y + s->height) - (s->ybase + position);
2740 s->underline_thickness = thickness;
2741 s->underline_position = position;
2742 y = s->ybase + position;
2743 if (s->face->underline_defaulted_p)
2744 XFillRectangle (s->display, s->window, s->gc,
2745 s->x, y, s->width, thickness);
2746 else
2748 XGCValues xgcv;
2749 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2750 XSetForeground (s->display, s->gc, s->face->underline_color);
2751 XFillRectangle (s->display, s->window, s->gc,
2752 s->x, y, s->width, thickness);
2753 XSetForeground (s->display, s->gc, xgcv.foreground);
2757 /* Draw overline. */
2758 if (s->face->overline_p)
2760 unsigned long dy = 0, h = 1;
2762 if (s->face->overline_color_defaulted_p)
2763 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2764 s->width, h);
2765 else
2767 XGCValues xgcv;
2768 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2769 XSetForeground (s->display, s->gc, s->face->overline_color);
2770 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2771 s->width, h);
2772 XSetForeground (s->display, s->gc, xgcv.foreground);
2776 /* Draw strike-through. */
2777 if (s->face->strike_through_p)
2779 unsigned long h = 1;
2780 unsigned long dy = (s->height - h) / 2;
2782 if (s->face->strike_through_color_defaulted_p)
2783 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2784 s->width, h);
2785 else
2787 XGCValues xgcv;
2788 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2789 XSetForeground (s->display, s->gc, s->face->strike_through_color);
2790 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2791 s->width, h);
2792 XSetForeground (s->display, s->gc, xgcv.foreground);
2796 /* Draw relief if not yet drawn. */
2797 if (!relief_drawn_p && s->face->box != FACE_NO_BOX)
2798 x_draw_glyph_string_box (s);
2800 if (s->prev)
2802 struct glyph_string *prev;
2804 for (prev = s->prev; prev; prev = prev->prev)
2805 if (prev->hl != s->hl
2806 && prev->x + prev->width + prev->right_overhang > s->x)
2808 /* As prev was drawn while clipped to its own area, we
2809 must draw the right_overhang part using s->hl now. */
2810 enum draw_glyphs_face save = prev->hl;
2812 prev->hl = s->hl;
2813 x_set_glyph_string_gc (prev);
2814 x_set_glyph_string_clipping_exactly (s, prev);
2815 if (prev->first_glyph->type == CHAR_GLYPH)
2816 x_draw_glyph_string_foreground (prev);
2817 else
2818 x_draw_composite_glyph_string_foreground (prev);
2819 XSetClipMask (prev->display, prev->gc, None);
2820 prev->hl = save;
2821 prev->num_clips = 0;
2825 if (s->next)
2827 struct glyph_string *next;
2829 for (next = s->next; next; next = next->next)
2830 if (next->hl != s->hl
2831 && next->x - next->left_overhang < s->x + s->width)
2833 /* As next will be drawn while clipped to its own area,
2834 we must draw the left_overhang part using s->hl now. */
2835 enum draw_glyphs_face save = next->hl;
2837 next->hl = s->hl;
2838 x_set_glyph_string_gc (next);
2839 x_set_glyph_string_clipping_exactly (s, next);
2840 if (next->first_glyph->type == CHAR_GLYPH)
2841 x_draw_glyph_string_foreground (next);
2842 else
2843 x_draw_composite_glyph_string_foreground (next);
2844 XSetClipMask (next->display, next->gc, None);
2845 next->hl = save;
2846 next->num_clips = 0;
2847 next->clip_head = s->next;
2852 /* Reset clipping. */
2853 XSetClipMask (s->display, s->gc, None);
2854 s->num_clips = 0;
2857 /* Shift display to make room for inserted glyphs. */
2859 static void
2860 x_shift_glyphs_for_insert (struct frame *f, int x, int y, int width, int height, int shift_by)
2862 XCopyArea (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), FRAME_X_WINDOW (f),
2863 f->output_data.x->normal_gc,
2864 x, y, width, height,
2865 x + shift_by, y);
2868 /* Delete N glyphs at the nominal cursor position. Not implemented
2869 for X frames. */
2871 static void
2872 x_delete_glyphs (struct frame *f, register int n)
2874 emacs_abort ();
2878 /* Like XClearArea, but check that WIDTH and HEIGHT are reasonable.
2879 If they are <= 0, this is probably an error. */
2881 void
2882 x_clear_area (Display *dpy, Window window, int x, int y, int width, int height)
2884 eassert (width > 0 && height > 0);
2885 XClearArea (dpy, window, x, y, width, height, False);
2889 /* Clear an entire frame. */
2891 static void
2892 x_clear_frame (struct frame *f)
2894 /* Clearing the frame will erase any cursor, so mark them all as no
2895 longer visible. */
2896 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2898 block_input ();
2900 XClearWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
2902 /* We have to clear the scroll bars. If we have changed colors or
2903 something like that, then they should be notified. */
2904 x_scroll_bar_clear (f);
2906 #if defined (USE_GTK) && defined (USE_TOOLKIT_SCROLL_BARS)
2907 /* Make sure scroll bars are redrawn. As they aren't redrawn by
2908 redisplay, do it here. */
2909 if (FRAME_GTK_WIDGET (f))
2910 gtk_widget_queue_draw (FRAME_GTK_WIDGET (f));
2911 #endif
2913 XFlush (FRAME_X_DISPLAY (f));
2915 unblock_input ();
2920 /* Invert the middle quarter of the frame for .15 sec. */
2922 static void
2923 XTflash (struct frame *f)
2925 block_input ();
2928 #ifdef USE_GTK
2929 /* Use Gdk routines to draw. This way, we won't draw over scroll bars
2930 when the scroll bars and the edit widget share the same X window. */
2931 GdkWindow *window = gtk_widget_get_window (FRAME_GTK_WIDGET (f));
2932 #ifdef HAVE_GTK3
2933 cairo_t *cr = gdk_cairo_create (window);
2934 cairo_set_source_rgb (cr, 1, 1, 1);
2935 cairo_set_operator (cr, CAIRO_OPERATOR_DIFFERENCE);
2936 #define XFillRectangle(d, win, gc, x, y, w, h) \
2937 do { \
2938 cairo_rectangle (cr, x, y, w, h); \
2939 cairo_fill (cr); \
2941 while (0)
2942 #else /* ! HAVE_GTK3 */
2943 GdkGCValues vals;
2944 GdkGC *gc;
2945 vals.foreground.pixel = (FRAME_FOREGROUND_PIXEL (f)
2946 ^ FRAME_BACKGROUND_PIXEL (f));
2947 vals.function = GDK_XOR;
2948 gc = gdk_gc_new_with_values (window,
2949 &vals, GDK_GC_FUNCTION | GDK_GC_FOREGROUND);
2950 #define XFillRectangle(d, win, gc, x, y, w, h) \
2951 gdk_draw_rectangle (window, gc, TRUE, x, y, w, h)
2952 #endif /* ! HAVE_GTK3 */
2953 #else /* ! USE_GTK */
2954 GC gc;
2956 /* Create a GC that will use the GXxor function to flip foreground
2957 pixels into background pixels. */
2959 XGCValues values;
2961 values.function = GXxor;
2962 values.foreground = (FRAME_FOREGROUND_PIXEL (f)
2963 ^ FRAME_BACKGROUND_PIXEL (f));
2965 gc = XCreateGC (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
2966 GCFunction | GCForeground, &values);
2968 #endif
2970 /* Get the height not including a menu bar widget. */
2971 int height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, FRAME_LINES (f));
2972 /* Height of each line to flash. */
2973 int flash_height = FRAME_LINE_HEIGHT (f);
2974 /* These will be the left and right margins of the rectangles. */
2975 int flash_left = FRAME_INTERNAL_BORDER_WIDTH (f);
2976 int flash_right = FRAME_PIXEL_WIDTH (f) - FRAME_INTERNAL_BORDER_WIDTH (f);
2977 int width = flash_right - flash_left;
2979 /* If window is tall, flash top and bottom line. */
2980 if (height > 3 * FRAME_LINE_HEIGHT (f))
2982 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
2983 flash_left,
2984 (FRAME_INTERNAL_BORDER_WIDTH (f)
2985 + FRAME_TOP_MARGIN_HEIGHT (f)),
2986 width, flash_height);
2987 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
2988 flash_left,
2989 (height - flash_height
2990 - FRAME_INTERNAL_BORDER_WIDTH (f)),
2991 width, flash_height);
2994 else
2995 /* If it is short, flash it all. */
2996 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
2997 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
2998 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
3000 x_flush (f);
3003 struct timespec delay = make_timespec (0, 150 * 1000 * 1000);
3004 struct timespec wakeup = timespec_add (current_timespec (), delay);
3006 /* Keep waiting until past the time wakeup or any input gets
3007 available. */
3008 while (! detect_input_pending ())
3010 struct timespec current = current_timespec ();
3011 struct timespec timeout;
3013 /* Break if result would not be positive. */
3014 if (timespec_cmp (wakeup, current) <= 0)
3015 break;
3017 /* How long `select' should wait. */
3018 timeout = make_timespec (0, 10 * 1000 * 1000);
3020 /* Try to wait that long--but we might wake up sooner. */
3021 pselect (0, NULL, NULL, NULL, &timeout, NULL);
3025 /* If window is tall, flash top and bottom line. */
3026 if (height > 3 * FRAME_LINE_HEIGHT (f))
3028 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3029 flash_left,
3030 (FRAME_INTERNAL_BORDER_WIDTH (f)
3031 + FRAME_TOP_MARGIN_HEIGHT (f)),
3032 width, flash_height);
3033 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3034 flash_left,
3035 (height - flash_height
3036 - FRAME_INTERNAL_BORDER_WIDTH (f)),
3037 width, flash_height);
3039 else
3040 /* If it is short, flash it all. */
3041 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3042 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
3043 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
3045 #ifdef USE_GTK
3046 #ifdef HAVE_GTK3
3047 cairo_destroy (cr);
3048 #else
3049 g_object_unref (G_OBJECT (gc));
3050 #endif
3051 #undef XFillRectangle
3052 #else
3053 XFreeGC (FRAME_X_DISPLAY (f), gc);
3054 #endif
3055 x_flush (f);
3059 unblock_input ();
3063 static void
3064 XTtoggle_invisible_pointer (struct frame *f, int invisible)
3066 block_input ();
3067 if (invisible)
3069 if (FRAME_DISPLAY_INFO (f)->invisible_cursor != 0)
3070 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3071 FRAME_DISPLAY_INFO (f)->invisible_cursor);
3073 else
3074 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3075 f->output_data.x->current_cursor);
3076 f->pointer_invisible = invisible;
3077 unblock_input ();
3081 /* Make audible bell. */
3083 static void
3084 XTring_bell (struct frame *f)
3086 if (FRAME_X_DISPLAY (f))
3088 if (visible_bell)
3089 XTflash (f);
3090 else
3092 block_input ();
3093 #ifdef HAVE_XKB
3094 XkbBell (FRAME_X_DISPLAY (f), None, 0, None);
3095 #else
3096 XBell (FRAME_X_DISPLAY (f), 0);
3097 #endif
3098 XFlush (FRAME_X_DISPLAY (f));
3099 unblock_input ();
3104 /***********************************************************************
3105 Line Dance
3106 ***********************************************************************/
3108 /* Perform an insert-lines or delete-lines operation, inserting N
3109 lines or deleting -N lines at vertical position VPOS. */
3111 static void
3112 x_ins_del_lines (struct frame *f, int vpos, int n)
3114 emacs_abort ();
3118 /* Scroll part of the display as described by RUN. */
3120 static void
3121 x_scroll_run (struct window *w, struct run *run)
3123 struct frame *f = XFRAME (w->frame);
3124 int x, y, width, height, from_y, to_y, bottom_y;
3126 /* Get frame-relative bounding box of the text display area of W,
3127 without mode lines. Include in this box the left and right
3128 fringe of W. */
3129 window_box (w, ANY_AREA, &x, &y, &width, &height);
3131 #ifdef USE_TOOLKIT_SCROLL_BARS
3132 /* If the fringe is adjacent to the left (right) scroll bar of a
3133 leftmost (rightmost, respectively) window, then extend its
3134 background to the gap between the fringe and the bar. */
3135 if ((WINDOW_LEFTMOST_P (w)
3136 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
3137 || (WINDOW_RIGHTMOST_P (w)
3138 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w)))
3140 int sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
3142 if (sb_width > 0)
3144 int bar_area_x = WINDOW_SCROLL_BAR_AREA_X (w);
3145 int bar_area_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
3147 if (bar_area_x + bar_area_width == x)
3149 x = bar_area_x + sb_width;
3150 width += bar_area_width - sb_width;
3152 else if (x + width == bar_area_x)
3153 width += bar_area_width - sb_width;
3156 #endif
3158 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
3159 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
3160 bottom_y = y + height;
3162 if (to_y < from_y)
3164 /* Scrolling up. Make sure we don't copy part of the mode
3165 line at the bottom. */
3166 if (from_y + run->height > bottom_y)
3167 height = bottom_y - from_y;
3168 else
3169 height = run->height;
3171 else
3173 /* Scrolling down. Make sure we don't copy over the mode line.
3174 at the bottom. */
3175 if (to_y + run->height > bottom_y)
3176 height = bottom_y - to_y;
3177 else
3178 height = run->height;
3181 block_input ();
3183 /* Cursor off. Will be switched on again in x_update_window_end. */
3184 x_clear_cursor (w);
3186 XCopyArea (FRAME_X_DISPLAY (f),
3187 FRAME_X_WINDOW (f), FRAME_X_WINDOW (f),
3188 f->output_data.x->normal_gc,
3189 x, from_y,
3190 width, height,
3191 x, to_y);
3193 unblock_input ();
3198 /***********************************************************************
3199 Exposure Events
3200 ***********************************************************************/
3203 static void
3204 frame_highlight (struct frame *f)
3206 /* We used to only do this if Vx_no_window_manager was non-nil, but
3207 the ICCCM (section 4.1.6) says that the window's border pixmap
3208 and border pixel are window attributes which are "private to the
3209 client", so we can always change it to whatever we want. */
3210 block_input ();
3211 /* I recently started to get errors in this XSetWindowBorder, depending on
3212 the window-manager in use, tho something more is at play since I've been
3213 using that same window-manager binary for ever. Let's not crash just
3214 because of this (bug#9310). */
3215 x_catch_errors (FRAME_X_DISPLAY (f));
3216 XSetWindowBorder (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3217 f->output_data.x->border_pixel);
3218 x_uncatch_errors ();
3219 unblock_input ();
3220 x_update_cursor (f, 1);
3221 x_set_frame_alpha (f);
3224 static void
3225 frame_unhighlight (struct frame *f)
3227 /* We used to only do this if Vx_no_window_manager was non-nil, but
3228 the ICCCM (section 4.1.6) says that the window's border pixmap
3229 and border pixel are window attributes which are "private to the
3230 client", so we can always change it to whatever we want. */
3231 block_input ();
3232 /* Same as above for XSetWindowBorder (bug#9310). */
3233 x_catch_errors (FRAME_X_DISPLAY (f));
3234 XSetWindowBorderPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3235 f->output_data.x->border_tile);
3236 x_uncatch_errors ();
3237 unblock_input ();
3238 x_update_cursor (f, 1);
3239 x_set_frame_alpha (f);
3242 /* The focus has changed. Update the frames as necessary to reflect
3243 the new situation. Note that we can't change the selected frame
3244 here, because the Lisp code we are interrupting might become confused.
3245 Each event gets marked with the frame in which it occurred, so the
3246 Lisp code can tell when the switch took place by examining the events. */
3248 static void
3249 x_new_focus_frame (struct x_display_info *dpyinfo, struct frame *frame)
3251 struct frame *old_focus = dpyinfo->x_focus_frame;
3253 if (frame != dpyinfo->x_focus_frame)
3255 /* Set this before calling other routines, so that they see
3256 the correct value of x_focus_frame. */
3257 dpyinfo->x_focus_frame = frame;
3259 if (old_focus && old_focus->auto_lower)
3260 x_lower_frame (old_focus);
3262 if (dpyinfo->x_focus_frame && dpyinfo->x_focus_frame->auto_raise)
3263 dpyinfo->x_pending_autoraise_frame = dpyinfo->x_focus_frame;
3264 else
3265 dpyinfo->x_pending_autoraise_frame = NULL;
3268 x_frame_rehighlight (dpyinfo);
3271 /* Handle FocusIn and FocusOut state changes for FRAME.
3272 If FRAME has focus and there exists more than one frame, puts
3273 a FOCUS_IN_EVENT into *BUFP. */
3275 static void
3276 x_focus_changed (int type, int state, struct x_display_info *dpyinfo, struct frame *frame, struct input_event *bufp)
3278 if (type == FocusIn)
3280 if (dpyinfo->x_focus_event_frame != frame)
3282 x_new_focus_frame (dpyinfo, frame);
3283 dpyinfo->x_focus_event_frame = frame;
3285 /* Don't stop displaying the initial startup message
3286 for a switch-frame event we don't need. */
3287 /* When run as a daemon, Vterminal_frame is always NIL. */
3288 bufp->arg = (((NILP (Vterminal_frame) || EQ (Fdaemonp (), Qt))
3289 && CONSP (Vframe_list)
3290 && !NILP (XCDR (Vframe_list)))
3291 ? Qt : Qnil);
3292 bufp->kind = FOCUS_IN_EVENT;
3293 XSETFRAME (bufp->frame_or_window, frame);
3296 frame->output_data.x->focus_state |= state;
3298 #ifdef HAVE_X_I18N
3299 if (FRAME_XIC (frame))
3300 XSetICFocus (FRAME_XIC (frame));
3301 #endif
3303 else if (type == FocusOut)
3305 frame->output_data.x->focus_state &= ~state;
3307 if (dpyinfo->x_focus_event_frame == frame)
3309 dpyinfo->x_focus_event_frame = 0;
3310 x_new_focus_frame (dpyinfo, 0);
3312 bufp->kind = FOCUS_OUT_EVENT;
3313 XSETFRAME (bufp->frame_or_window, frame);
3316 #ifdef HAVE_X_I18N
3317 if (FRAME_XIC (frame))
3318 XUnsetICFocus (FRAME_XIC (frame));
3319 #endif
3320 if (frame->pointer_invisible)
3321 XTtoggle_invisible_pointer (frame, 0);
3325 /* Return the Emacs frame-object corresponding to an X window.
3326 It could be the frame's main window or an icon window. */
3328 static struct frame *
3329 x_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
3331 Lisp_Object tail, frame;
3332 struct frame *f;
3334 if (wdesc == None)
3335 return NULL;
3337 FOR_EACH_FRAME (tail, frame)
3339 f = XFRAME (frame);
3340 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
3341 continue;
3342 if (f->output_data.x->hourglass_window == wdesc)
3343 return f;
3344 #ifdef USE_X_TOOLKIT
3345 if ((f->output_data.x->edit_widget
3346 && XtWindow (f->output_data.x->edit_widget) == wdesc)
3347 /* A tooltip frame? */
3348 || (!f->output_data.x->edit_widget
3349 && FRAME_X_WINDOW (f) == wdesc)
3350 || f->output_data.x->icon_desc == wdesc)
3351 return f;
3352 #else /* not USE_X_TOOLKIT */
3353 #ifdef USE_GTK
3354 if (f->output_data.x->edit_widget)
3356 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
3357 struct x_output *x = f->output_data.x;
3358 if (gwdesc != 0 && gwdesc == x->edit_widget)
3359 return f;
3361 #endif /* USE_GTK */
3362 if (FRAME_X_WINDOW (f) == wdesc
3363 || f->output_data.x->icon_desc == wdesc)
3364 return f;
3365 #endif /* not USE_X_TOOLKIT */
3367 return 0;
3370 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
3372 /* Like x_window_to_frame but also compares the window with the widget's
3373 windows. */
3375 static struct frame *
3376 x_any_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
3378 Lisp_Object tail, frame;
3379 struct frame *f, *found = NULL;
3380 struct x_output *x;
3382 if (wdesc == None)
3383 return NULL;
3385 FOR_EACH_FRAME (tail, frame)
3387 if (found)
3388 break;
3389 f = XFRAME (frame);
3390 if (FRAME_X_P (f) && FRAME_DISPLAY_INFO (f) == dpyinfo)
3392 /* This frame matches if the window is any of its widgets. */
3393 x = f->output_data.x;
3394 if (x->hourglass_window == wdesc)
3395 found = f;
3396 else if (x->widget)
3398 #ifdef USE_GTK
3399 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
3400 if (gwdesc != 0
3401 && gtk_widget_get_toplevel (gwdesc) == x->widget)
3402 found = f;
3403 #else
3404 if (wdesc == XtWindow (x->widget)
3405 || wdesc == XtWindow (x->column_widget)
3406 || wdesc == XtWindow (x->edit_widget))
3407 found = f;
3408 /* Match if the window is this frame's menubar. */
3409 else if (lw_window_is_in_menubar (wdesc, x->menubar_widget))
3410 found = f;
3411 #endif
3413 else if (FRAME_X_WINDOW (f) == wdesc)
3414 /* A tooltip frame. */
3415 found = f;
3419 return found;
3422 /* Likewise, but consider only the menu bar widget. */
3424 static struct frame *
3425 x_menubar_window_to_frame (struct x_display_info *dpyinfo,
3426 const XEvent *event)
3428 Window wdesc = event->xany.window;
3429 Lisp_Object tail, frame;
3430 struct frame *f;
3431 struct x_output *x;
3433 if (wdesc == None)
3434 return NULL;
3436 FOR_EACH_FRAME (tail, frame)
3438 f = XFRAME (frame);
3439 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
3440 continue;
3441 x = f->output_data.x;
3442 #ifdef USE_GTK
3443 if (x->menubar_widget && xg_event_is_for_menubar (f, event))
3444 return f;
3445 #else
3446 /* Match if the window is this frame's menubar. */
3447 if (x->menubar_widget
3448 && lw_window_is_in_menubar (wdesc, x->menubar_widget))
3449 return f;
3450 #endif
3452 return 0;
3455 /* Return the frame whose principal (outermost) window is WDESC.
3456 If WDESC is some other (smaller) window, we return 0. */
3458 struct frame *
3459 x_top_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
3461 Lisp_Object tail, frame;
3462 struct frame *f;
3463 struct x_output *x;
3465 if (wdesc == None)
3466 return NULL;
3468 FOR_EACH_FRAME (tail, frame)
3470 f = XFRAME (frame);
3471 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
3472 continue;
3473 x = f->output_data.x;
3475 if (x->widget)
3477 /* This frame matches if the window is its topmost widget. */
3478 #ifdef USE_GTK
3479 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
3480 if (gwdesc == x->widget)
3481 return f;
3482 #else
3483 if (wdesc == XtWindow (x->widget))
3484 return f;
3485 #endif
3487 else if (FRAME_X_WINDOW (f) == wdesc)
3488 /* Tooltip frame. */
3489 return f;
3491 return 0;
3494 #else /* !USE_X_TOOLKIT && !USE_GTK */
3496 #define x_any_window_to_frame(d, i) x_window_to_frame (d, i)
3497 #define x_top_window_to_frame(d, i) x_window_to_frame (d, i)
3499 #endif /* USE_X_TOOLKIT || USE_GTK */
3501 /* The focus may have changed. Figure out if it is a real focus change,
3502 by checking both FocusIn/Out and Enter/LeaveNotify events.
3504 Returns FOCUS_IN_EVENT event in *BUFP. */
3506 static void
3507 x_detect_focus_change (struct x_display_info *dpyinfo, struct frame *frame,
3508 const XEvent *event, struct input_event *bufp)
3510 if (!frame)
3511 return;
3513 switch (event->type)
3515 case EnterNotify:
3516 case LeaveNotify:
3518 struct frame *focus_frame = dpyinfo->x_focus_event_frame;
3519 int focus_state
3520 = focus_frame ? focus_frame->output_data.x->focus_state : 0;
3522 if (event->xcrossing.detail != NotifyInferior
3523 && event->xcrossing.focus
3524 && ! (focus_state & FOCUS_EXPLICIT))
3525 x_focus_changed ((event->type == EnterNotify ? FocusIn : FocusOut),
3526 FOCUS_IMPLICIT,
3527 dpyinfo, frame, bufp);
3529 break;
3531 case FocusIn:
3532 case FocusOut:
3533 x_focus_changed (event->type,
3534 (event->xfocus.detail == NotifyPointer ?
3535 FOCUS_IMPLICIT : FOCUS_EXPLICIT),
3536 dpyinfo, frame, bufp);
3537 break;
3539 case ClientMessage:
3540 if (event->xclient.message_type == dpyinfo->Xatom_XEMBED)
3542 enum xembed_message msg = event->xclient.data.l[1];
3543 x_focus_changed ((msg == XEMBED_FOCUS_IN ? FocusIn : FocusOut),
3544 FOCUS_EXPLICIT, dpyinfo, frame, bufp);
3546 break;
3551 #if !defined USE_X_TOOLKIT && !defined USE_GTK
3552 /* Handle an event saying the mouse has moved out of an Emacs frame. */
3554 void
3555 x_mouse_leave (struct x_display_info *dpyinfo)
3557 x_new_focus_frame (dpyinfo, dpyinfo->x_focus_event_frame);
3559 #endif
3561 /* The focus has changed, or we have redirected a frame's focus to
3562 another frame (this happens when a frame uses a surrogate
3563 mini-buffer frame). Shift the highlight as appropriate.
3565 The FRAME argument doesn't necessarily have anything to do with which
3566 frame is being highlighted or un-highlighted; we only use it to find
3567 the appropriate X display info. */
3569 static void
3570 XTframe_rehighlight (struct frame *frame)
3572 x_frame_rehighlight (FRAME_DISPLAY_INFO (frame));
3575 static void
3576 x_frame_rehighlight (struct x_display_info *dpyinfo)
3578 struct frame *old_highlight = dpyinfo->x_highlight_frame;
3580 if (dpyinfo->x_focus_frame)
3582 dpyinfo->x_highlight_frame
3583 = ((FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame)))
3584 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
3585 : dpyinfo->x_focus_frame);
3586 if (! FRAME_LIVE_P (dpyinfo->x_highlight_frame))
3588 fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
3589 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
3592 else
3593 dpyinfo->x_highlight_frame = 0;
3595 if (dpyinfo->x_highlight_frame != old_highlight)
3597 if (old_highlight)
3598 frame_unhighlight (old_highlight);
3599 if (dpyinfo->x_highlight_frame)
3600 frame_highlight (dpyinfo->x_highlight_frame);
3606 /* Keyboard processing - modifier keys, vendor-specific keysyms, etc. */
3608 /* Initialize mode_switch_bit and modifier_meaning. */
3609 static void
3610 x_find_modifier_meanings (struct x_display_info *dpyinfo)
3612 int min_code, max_code;
3613 KeySym *syms;
3614 int syms_per_code;
3615 XModifierKeymap *mods;
3617 dpyinfo->meta_mod_mask = 0;
3618 dpyinfo->shift_lock_mask = 0;
3619 dpyinfo->alt_mod_mask = 0;
3620 dpyinfo->super_mod_mask = 0;
3621 dpyinfo->hyper_mod_mask = 0;
3623 XDisplayKeycodes (dpyinfo->display, &min_code, &max_code);
3625 syms = XGetKeyboardMapping (dpyinfo->display,
3626 min_code, max_code - min_code + 1,
3627 &syms_per_code);
3628 mods = XGetModifierMapping (dpyinfo->display);
3630 /* Scan the modifier table to see which modifier bits the Meta and
3631 Alt keysyms are on. */
3633 int row, col; /* The row and column in the modifier table. */
3634 int found_alt_or_meta;
3636 for (row = 3; row < 8; row++)
3638 found_alt_or_meta = 0;
3639 for (col = 0; col < mods->max_keypermod; col++)
3641 KeyCode code = mods->modifiermap[(row * mods->max_keypermod) + col];
3643 /* Zeroes are used for filler. Skip them. */
3644 if (code == 0)
3645 continue;
3647 /* Are any of this keycode's keysyms a meta key? */
3649 int code_col;
3651 for (code_col = 0; code_col < syms_per_code; code_col++)
3653 int sym = syms[((code - min_code) * syms_per_code) + code_col];
3655 switch (sym)
3657 case XK_Meta_L:
3658 case XK_Meta_R:
3659 found_alt_or_meta = 1;
3660 dpyinfo->meta_mod_mask |= (1 << row);
3661 break;
3663 case XK_Alt_L:
3664 case XK_Alt_R:
3665 found_alt_or_meta = 1;
3666 dpyinfo->alt_mod_mask |= (1 << row);
3667 break;
3669 case XK_Hyper_L:
3670 case XK_Hyper_R:
3671 if (!found_alt_or_meta)
3672 dpyinfo->hyper_mod_mask |= (1 << row);
3673 code_col = syms_per_code;
3674 col = mods->max_keypermod;
3675 break;
3677 case XK_Super_L:
3678 case XK_Super_R:
3679 if (!found_alt_or_meta)
3680 dpyinfo->super_mod_mask |= (1 << row);
3681 code_col = syms_per_code;
3682 col = mods->max_keypermod;
3683 break;
3685 case XK_Shift_Lock:
3686 /* Ignore this if it's not on the lock modifier. */
3687 if (!found_alt_or_meta && ((1 << row) == LockMask))
3688 dpyinfo->shift_lock_mask = LockMask;
3689 code_col = syms_per_code;
3690 col = mods->max_keypermod;
3691 break;
3699 /* If we couldn't find any meta keys, accept any alt keys as meta keys. */
3700 if (! dpyinfo->meta_mod_mask)
3702 dpyinfo->meta_mod_mask = dpyinfo->alt_mod_mask;
3703 dpyinfo->alt_mod_mask = 0;
3706 /* If some keys are both alt and meta,
3707 make them just meta, not alt. */
3708 if (dpyinfo->alt_mod_mask & dpyinfo->meta_mod_mask)
3710 dpyinfo->alt_mod_mask &= ~dpyinfo->meta_mod_mask;
3713 XFree (syms);
3714 XFreeModifiermap (mods);
3717 /* Convert between the modifier bits X uses and the modifier bits
3718 Emacs uses. */
3721 x_x_to_emacs_modifiers (struct x_display_info *dpyinfo, int state)
3723 int mod_meta = meta_modifier;
3724 int mod_alt = alt_modifier;
3725 int mod_hyper = hyper_modifier;
3726 int mod_super = super_modifier;
3727 Lisp_Object tem;
3729 tem = Fget (Vx_alt_keysym, Qmodifier_value);
3730 if (INTEGERP (tem)) mod_alt = XINT (tem) & INT_MAX;
3731 tem = Fget (Vx_meta_keysym, Qmodifier_value);
3732 if (INTEGERP (tem)) mod_meta = XINT (tem) & INT_MAX;
3733 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
3734 if (INTEGERP (tem)) mod_hyper = XINT (tem) & INT_MAX;
3735 tem = Fget (Vx_super_keysym, Qmodifier_value);
3736 if (INTEGERP (tem)) mod_super = XINT (tem) & INT_MAX;
3738 return ( ((state & (ShiftMask | dpyinfo->shift_lock_mask)) ? shift_modifier : 0)
3739 | ((state & ControlMask) ? ctrl_modifier : 0)
3740 | ((state & dpyinfo->meta_mod_mask) ? mod_meta : 0)
3741 | ((state & dpyinfo->alt_mod_mask) ? mod_alt : 0)
3742 | ((state & dpyinfo->super_mod_mask) ? mod_super : 0)
3743 | ((state & dpyinfo->hyper_mod_mask) ? mod_hyper : 0));
3746 static int
3747 x_emacs_to_x_modifiers (struct x_display_info *dpyinfo, EMACS_INT state)
3749 EMACS_INT mod_meta = meta_modifier;
3750 EMACS_INT mod_alt = alt_modifier;
3751 EMACS_INT mod_hyper = hyper_modifier;
3752 EMACS_INT mod_super = super_modifier;
3754 Lisp_Object tem;
3756 tem = Fget (Vx_alt_keysym, Qmodifier_value);
3757 if (INTEGERP (tem)) mod_alt = XINT (tem);
3758 tem = Fget (Vx_meta_keysym, Qmodifier_value);
3759 if (INTEGERP (tem)) mod_meta = XINT (tem);
3760 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
3761 if (INTEGERP (tem)) mod_hyper = XINT (tem);
3762 tem = Fget (Vx_super_keysym, Qmodifier_value);
3763 if (INTEGERP (tem)) mod_super = XINT (tem);
3766 return ( ((state & mod_alt) ? dpyinfo->alt_mod_mask : 0)
3767 | ((state & mod_super) ? dpyinfo->super_mod_mask : 0)
3768 | ((state & mod_hyper) ? dpyinfo->hyper_mod_mask : 0)
3769 | ((state & shift_modifier) ? ShiftMask : 0)
3770 | ((state & ctrl_modifier) ? ControlMask : 0)
3771 | ((state & mod_meta) ? dpyinfo->meta_mod_mask : 0));
3774 /* Convert a keysym to its name. */
3776 char *
3777 x_get_keysym_name (int keysym)
3779 char *value;
3781 block_input ();
3782 value = XKeysymToString (keysym);
3783 unblock_input ();
3785 return value;
3788 /* Mouse clicks and mouse movement. Rah.
3790 Formerly, we used PointerMotionHintMask (in standard_event_mask)
3791 so that we would have to call XQueryPointer after each MotionNotify
3792 event to ask for another such event. However, this made mouse tracking
3793 slow, and there was a bug that made it eventually stop.
3795 Simply asking for MotionNotify all the time seems to work better.
3797 In order to avoid asking for motion events and then throwing most
3798 of them away or busy-polling the server for mouse positions, we ask
3799 the server for pointer motion hints. This means that we get only
3800 one event per group of mouse movements. "Groups" are delimited by
3801 other kinds of events (focus changes and button clicks, for
3802 example), or by XQueryPointer calls; when one of these happens, we
3803 get another MotionNotify event the next time the mouse moves. This
3804 is at least as efficient as getting motion events when mouse
3805 tracking is on, and I suspect only negligibly worse when tracking
3806 is off. */
3808 /* Prepare a mouse-event in *RESULT for placement in the input queue.
3810 If the event is a button press, then note that we have grabbed
3811 the mouse. */
3813 static Lisp_Object
3814 construct_mouse_click (struct input_event *result,
3815 const XButtonEvent *event,
3816 struct frame *f)
3818 /* Make the event type NO_EVENT; we'll change that when we decide
3819 otherwise. */
3820 result->kind = MOUSE_CLICK_EVENT;
3821 result->code = event->button - Button1;
3822 result->timestamp = event->time;
3823 result->modifiers = (x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO (f),
3824 event->state)
3825 | (event->type == ButtonRelease
3826 ? up_modifier
3827 : down_modifier));
3829 XSETINT (result->x, event->x);
3830 XSETINT (result->y, event->y);
3831 XSETFRAME (result->frame_or_window, f);
3832 result->arg = Qnil;
3833 return Qnil;
3836 /* Function to report a mouse movement to the mainstream Emacs code.
3837 The input handler calls this.
3839 We have received a mouse movement event, which is given in *event.
3840 If the mouse is over a different glyph than it was last time, tell
3841 the mainstream emacs code by setting mouse_moved. If not, ask for
3842 another motion event, so we can check again the next time it moves. */
3844 static int
3845 note_mouse_movement (struct frame *frame, const XMotionEvent *event)
3847 XRectangle *r;
3848 struct x_display_info *dpyinfo;
3850 if (!FRAME_X_OUTPUT (frame))
3851 return 0;
3853 dpyinfo = FRAME_DISPLAY_INFO (frame);
3854 dpyinfo->last_mouse_movement_time = event->time;
3855 dpyinfo->last_mouse_motion_frame = frame;
3856 dpyinfo->last_mouse_motion_x = event->x;
3857 dpyinfo->last_mouse_motion_y = event->y;
3859 if (event->window != FRAME_X_WINDOW (frame))
3861 frame->mouse_moved = 1;
3862 dpyinfo->last_mouse_scroll_bar = NULL;
3863 note_mouse_highlight (frame, -1, -1);
3864 dpyinfo->last_mouse_glyph_frame = NULL;
3865 return 1;
3869 /* Has the mouse moved off the glyph it was on at the last sighting? */
3870 r = &dpyinfo->last_mouse_glyph;
3871 if (frame != dpyinfo->last_mouse_glyph_frame
3872 || event->x < r->x || event->x >= r->x + r->width
3873 || event->y < r->y || event->y >= r->y + r->height)
3875 frame->mouse_moved = 1;
3876 dpyinfo->last_mouse_scroll_bar = NULL;
3877 note_mouse_highlight (frame, event->x, event->y);
3878 /* Remember which glyph we're now on. */
3879 remember_mouse_glyph (frame, event->x, event->y, r);
3880 dpyinfo->last_mouse_glyph_frame = frame;
3881 return 1;
3884 return 0;
3887 /* Return the current position of the mouse.
3888 *FP should be a frame which indicates which display to ask about.
3890 If the mouse movement started in a scroll bar, set *FP, *BAR_WINDOW,
3891 and *PART to the frame, window, and scroll bar part that the mouse
3892 is over. Set *X and *Y to the portion and whole of the mouse's
3893 position on the scroll bar.
3895 If the mouse movement started elsewhere, set *FP to the frame the
3896 mouse is on, *BAR_WINDOW to nil, and *X and *Y to the character cell
3897 the mouse is over.
3899 Set *TIMESTAMP to the server time-stamp for the time at which the mouse
3900 was at this position.
3902 Don't store anything if we don't have a valid set of values to report.
3904 This clears the mouse_moved flag, so we can wait for the next mouse
3905 movement. */
3907 static void
3908 XTmouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
3909 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
3910 Time *timestamp)
3912 struct frame *f1;
3913 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (*fp);
3915 block_input ();
3917 if (dpyinfo->last_mouse_scroll_bar && insist == 0)
3918 x_scroll_bar_report_motion (fp, bar_window, part, x, y, timestamp);
3919 else
3921 Window root;
3922 int root_x, root_y;
3924 Window dummy_window;
3925 int dummy;
3927 Lisp_Object frame, tail;
3929 /* Clear the mouse-moved flag for every frame on this display. */
3930 FOR_EACH_FRAME (tail, frame)
3931 if (FRAME_X_P (XFRAME (frame))
3932 && FRAME_X_DISPLAY (XFRAME (frame)) == FRAME_X_DISPLAY (*fp))
3933 XFRAME (frame)->mouse_moved = 0;
3935 dpyinfo->last_mouse_scroll_bar = NULL;
3937 /* Figure out which root window we're on. */
3938 XQueryPointer (FRAME_X_DISPLAY (*fp),
3939 DefaultRootWindow (FRAME_X_DISPLAY (*fp)),
3941 /* The root window which contains the pointer. */
3942 &root,
3944 /* Trash which we can't trust if the pointer is on
3945 a different screen. */
3946 &dummy_window,
3948 /* The position on that root window. */
3949 &root_x, &root_y,
3951 /* More trash we can't trust. */
3952 &dummy, &dummy,
3954 /* Modifier keys and pointer buttons, about which
3955 we don't care. */
3956 (unsigned int *) &dummy);
3958 /* Now we have a position on the root; find the innermost window
3959 containing the pointer. */
3961 Window win, child;
3962 int win_x, win_y;
3963 int parent_x = 0, parent_y = 0;
3965 win = root;
3967 /* XTranslateCoordinates can get errors if the window
3968 structure is changing at the same time this function
3969 is running. So at least we must not crash from them. */
3971 x_catch_errors (FRAME_X_DISPLAY (*fp));
3973 if (x_mouse_grabbed (dpyinfo))
3975 /* If mouse was grabbed on a frame, give coords for that frame
3976 even if the mouse is now outside it. */
3977 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
3979 /* From-window. */
3980 root,
3982 /* To-window. */
3983 FRAME_X_WINDOW (dpyinfo->last_mouse_frame),
3985 /* From-position, to-position. */
3986 root_x, root_y, &win_x, &win_y,
3988 /* Child of win. */
3989 &child);
3990 f1 = dpyinfo->last_mouse_frame;
3992 else
3994 while (1)
3996 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
3998 /* From-window, to-window. */
3999 root, win,
4001 /* From-position, to-position. */
4002 root_x, root_y, &win_x, &win_y,
4004 /* Child of win. */
4005 &child);
4007 if (child == None || child == win)
4008 break;
4009 #ifdef USE_GTK
4010 /* We don't wan't to know the innermost window. We
4011 want the edit window. For non-Gtk+ the innermost
4012 window is the edit window. For Gtk+ it might not
4013 be. It might be the tool bar for example. */
4014 if (x_window_to_frame (dpyinfo, win))
4015 break;
4016 #endif
4017 win = child;
4018 parent_x = win_x;
4019 parent_y = win_y;
4022 /* Now we know that:
4023 win is the innermost window containing the pointer
4024 (XTC says it has no child containing the pointer),
4025 win_x and win_y are the pointer's position in it
4026 (XTC did this the last time through), and
4027 parent_x and parent_y are the pointer's position in win's parent.
4028 (They are what win_x and win_y were when win was child.
4029 If win is the root window, it has no parent, and
4030 parent_{x,y} are invalid, but that's okay, because we'll
4031 never use them in that case.) */
4033 #ifdef USE_GTK
4034 /* We don't wan't to know the innermost window. We
4035 want the edit window. */
4036 f1 = x_window_to_frame (dpyinfo, win);
4037 #else
4038 /* Is win one of our frames? */
4039 f1 = x_any_window_to_frame (dpyinfo, win);
4040 #endif
4042 #ifdef USE_X_TOOLKIT
4043 /* If we end up with the menu bar window, say it's not
4044 on the frame. */
4045 if (f1 != NULL
4046 && f1->output_data.x->menubar_widget
4047 && win == XtWindow (f1->output_data.x->menubar_widget))
4048 f1 = NULL;
4049 #endif /* USE_X_TOOLKIT */
4052 if (x_had_errors_p (FRAME_X_DISPLAY (*fp)))
4053 f1 = 0;
4055 x_uncatch_errors ();
4057 /* If not, is it one of our scroll bars? */
4058 if (! f1)
4060 struct scroll_bar *bar;
4062 bar = x_window_to_scroll_bar (FRAME_X_DISPLAY (*fp), win);
4064 if (bar)
4066 f1 = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
4067 win_x = parent_x;
4068 win_y = parent_y;
4072 if (f1 == 0 && insist > 0)
4073 f1 = SELECTED_FRAME ();
4075 if (f1)
4077 /* Ok, we found a frame. Store all the values.
4078 last_mouse_glyph is a rectangle used to reduce the
4079 generation of mouse events. To not miss any motion
4080 events, we must divide the frame into rectangles of the
4081 size of the smallest character that could be displayed
4082 on it, i.e. into the same rectangles that matrices on
4083 the frame are divided into. */
4085 /* FIXME: what if F1 is not an X frame? */
4086 dpyinfo = FRAME_DISPLAY_INFO (f1);
4087 remember_mouse_glyph (f1, win_x, win_y, &dpyinfo->last_mouse_glyph);
4088 dpyinfo->last_mouse_glyph_frame = f1;
4090 *bar_window = Qnil;
4091 *part = 0;
4092 *fp = f1;
4093 XSETINT (*x, win_x);
4094 XSETINT (*y, win_y);
4095 *timestamp = dpyinfo->last_mouse_movement_time;
4100 unblock_input ();
4105 /***********************************************************************
4106 Scroll bars
4107 ***********************************************************************/
4109 /* Scroll bar support. */
4111 /* Given an X window ID and a DISPLAY, find the struct scroll_bar which
4112 manages it.
4113 This can be called in GC, so we have to make sure to strip off mark
4114 bits. */
4116 static struct scroll_bar *
4117 x_window_to_scroll_bar (Display *display, Window window_id)
4119 Lisp_Object tail, frame;
4121 #if defined (USE_GTK) && defined (USE_TOOLKIT_SCROLL_BARS)
4122 window_id = (Window) xg_get_scroll_id_for_window (display, window_id);
4123 #endif /* USE_GTK && USE_TOOLKIT_SCROLL_BARS */
4125 FOR_EACH_FRAME (tail, frame)
4127 Lisp_Object bar, condemned;
4129 if (! FRAME_X_P (XFRAME (frame)))
4130 continue;
4132 /* Scan this frame's scroll bar list for a scroll bar with the
4133 right window ID. */
4134 condemned = FRAME_CONDEMNED_SCROLL_BARS (XFRAME (frame));
4135 for (bar = FRAME_SCROLL_BARS (XFRAME (frame));
4136 /* This trick allows us to search both the ordinary and
4137 condemned scroll bar lists with one loop. */
4138 ! NILP (bar) || (bar = condemned,
4139 condemned = Qnil,
4140 ! NILP (bar));
4141 bar = XSCROLL_BAR (bar)->next)
4142 if (XSCROLL_BAR (bar)->x_window == window_id &&
4143 FRAME_X_DISPLAY (XFRAME (frame)) == display)
4144 return XSCROLL_BAR (bar);
4147 return NULL;
4151 #if defined USE_LUCID
4153 /* Return the Lucid menu bar WINDOW is part of. Return null
4154 if WINDOW is not part of a menu bar. */
4156 static Widget
4157 x_window_to_menu_bar (Window window)
4159 Lisp_Object tail, frame;
4161 FOR_EACH_FRAME (tail, frame)
4162 if (FRAME_X_P (XFRAME (frame)))
4164 Widget menu_bar = XFRAME (frame)->output_data.x->menubar_widget;
4166 if (menu_bar && xlwmenu_window_p (menu_bar, window))
4167 return menu_bar;
4169 return NULL;
4172 #endif /* USE_LUCID */
4175 /************************************************************************
4176 Toolkit scroll bars
4177 ************************************************************************/
4179 #ifdef USE_TOOLKIT_SCROLL_BARS
4181 static void x_send_scroll_bar_event (Lisp_Object, int, int, int);
4183 /* Lisp window being scrolled. Set when starting to interact with
4184 a toolkit scroll bar, reset to nil when ending the interaction. */
4186 static Lisp_Object window_being_scrolled;
4188 /* Whether this is an Xaw with arrow-scrollbars. This should imply
4189 that movements of 1/20 of the screen size are mapped to up/down. */
4191 #ifndef USE_GTK
4192 /* Id of action hook installed for scroll bars. */
4194 static XtActionHookId action_hook_id;
4196 static Boolean xaw3d_arrow_scroll;
4198 /* Whether the drag scrolling maintains the mouse at the top of the
4199 thumb. If not, resizing the thumb needs to be done more carefully
4200 to avoid jerkiness. */
4202 static Boolean xaw3d_pick_top;
4204 /* Action hook installed via XtAppAddActionHook when toolkit scroll
4205 bars are used.. The hook is responsible for detecting when
4206 the user ends an interaction with the scroll bar, and generates
4207 a `end-scroll' SCROLL_BAR_CLICK_EVENT' event if so. */
4209 static void
4210 xt_action_hook (Widget widget, XtPointer client_data, String action_name,
4211 XEvent *event, String *params, Cardinal *num_params)
4213 int scroll_bar_p;
4214 const char *end_action;
4216 #ifdef USE_MOTIF
4217 scroll_bar_p = XmIsScrollBar (widget);
4218 end_action = "Release";
4219 #else /* !USE_MOTIF i.e. use Xaw */
4220 scroll_bar_p = XtIsSubclass (widget, scrollbarWidgetClass);
4221 end_action = "EndScroll";
4222 #endif /* USE_MOTIF */
4224 if (scroll_bar_p
4225 && strcmp (action_name, end_action) == 0
4226 && WINDOWP (window_being_scrolled))
4228 struct window *w;
4229 struct scroll_bar *bar;
4231 x_send_scroll_bar_event (window_being_scrolled,
4232 scroll_bar_end_scroll, 0, 0);
4233 w = XWINDOW (window_being_scrolled);
4234 bar = XSCROLL_BAR (w->vertical_scroll_bar);
4236 if (bar->dragging != -1)
4238 bar->dragging = -1;
4239 /* The thumb size is incorrect while dragging: fix it. */
4240 set_vertical_scroll_bar (w);
4242 window_being_scrolled = Qnil;
4243 #if defined (USE_LUCID)
4244 bar->last_seen_part = scroll_bar_nowhere;
4245 #endif
4246 /* Xt timeouts no longer needed. */
4247 toolkit_scroll_bar_interaction = 0;
4250 #endif /* not USE_GTK */
4252 /* Send a client message with message type Xatom_Scrollbar for a
4253 scroll action to the frame of WINDOW. PART is a value identifying
4254 the part of the scroll bar that was clicked on. PORTION is the
4255 amount to scroll of a whole of WHOLE. */
4257 static void
4258 x_send_scroll_bar_event (Lisp_Object window, int part, int portion, int whole)
4260 XEvent event;
4261 XClientMessageEvent *ev = &event.xclient;
4262 struct window *w = XWINDOW (window);
4263 struct frame *f = XFRAME (w->frame);
4264 intptr_t iw = (intptr_t) w;
4265 enum { BITS_PER_INTPTR = CHAR_BIT * sizeof iw };
4266 verify (BITS_PER_INTPTR <= 64);
4267 int sign_shift = BITS_PER_INTPTR - 32;
4269 block_input ();
4271 /* Construct a ClientMessage event to send to the frame. */
4272 ev->type = ClientMessage;
4273 ev->message_type = FRAME_DISPLAY_INFO (f)->Xatom_Scrollbar;
4274 ev->display = FRAME_X_DISPLAY (f);
4275 ev->window = FRAME_X_WINDOW (f);
4276 ev->format = 32;
4278 /* A 32-bit X client on a 64-bit X server can pass a window pointer
4279 as-is. A 64-bit client on a 32-bit X server is in trouble
4280 because a pointer does not fit and would be truncated while
4281 passing through the server. So use two slots and hope that X12
4282 will resolve such issues someday. */
4283 ev->data.l[0] = iw >> 31 >> 1;
4284 ev->data.l[1] = sign_shift <= 0 ? iw : iw << sign_shift >> sign_shift;
4285 ev->data.l[2] = part;
4286 ev->data.l[3] = portion;
4287 ev->data.l[4] = whole;
4289 /* Make Xt timeouts work while the scroll bar is active. */
4290 #ifdef USE_X_TOOLKIT
4291 toolkit_scroll_bar_interaction = 1;
4292 x_activate_timeout_atimer ();
4293 #endif
4295 /* Setting the event mask to zero means that the message will
4296 be sent to the client that created the window, and if that
4297 window no longer exists, no event will be sent. */
4298 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), False, 0, &event);
4299 unblock_input ();
4303 /* Transform a scroll bar ClientMessage EVENT to an Emacs input event
4304 in *IEVENT. */
4306 static void
4307 x_scroll_bar_to_input_event (const XEvent *event,
4308 struct input_event *ievent)
4310 const XClientMessageEvent *ev = &event->xclient;
4311 Lisp_Object window;
4312 struct window *w;
4314 /* See the comment in the function above. */
4315 intptr_t iw0 = ev->data.l[0];
4316 intptr_t iw1 = ev->data.l[1];
4317 intptr_t iw = (iw0 << 31 << 1) + (iw1 & 0xffffffffu);
4318 w = (struct window *) iw;
4320 XSETWINDOW (window, w);
4322 ievent->kind = SCROLL_BAR_CLICK_EVENT;
4323 ievent->frame_or_window = window;
4324 ievent->arg = Qnil;
4325 #ifdef USE_GTK
4326 ievent->timestamp = CurrentTime;
4327 #else
4328 ievent->timestamp =
4329 XtLastTimestampProcessed (FRAME_X_DISPLAY (XFRAME (w->frame)));
4330 #endif
4331 ievent->code = 0;
4332 ievent->part = ev->data.l[2];
4333 ievent->x = make_number (ev->data.l[3]);
4334 ievent->y = make_number (ev->data.l[4]);
4335 ievent->modifiers = 0;
4339 #ifdef USE_MOTIF
4341 /* Minimum and maximum values used for Motif scroll bars. */
4343 #define XM_SB_MAX 10000000
4346 /* Scroll bar callback for Motif scroll bars. WIDGET is the scroll
4347 bar widget. CLIENT_DATA is a pointer to the scroll_bar structure.
4348 CALL_DATA is a pointer to a XmScrollBarCallbackStruct. */
4350 static void
4351 xm_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
4353 struct scroll_bar *bar = client_data;
4354 XmScrollBarCallbackStruct *cs = call_data;
4355 int part = -1, whole = 0, portion = 0;
4357 switch (cs->reason)
4359 case XmCR_DECREMENT:
4360 bar->dragging = -1;
4361 part = scroll_bar_up_arrow;
4362 break;
4364 case XmCR_INCREMENT:
4365 bar->dragging = -1;
4366 part = scroll_bar_down_arrow;
4367 break;
4369 case XmCR_PAGE_DECREMENT:
4370 bar->dragging = -1;
4371 part = scroll_bar_above_handle;
4372 break;
4374 case XmCR_PAGE_INCREMENT:
4375 bar->dragging = -1;
4376 part = scroll_bar_below_handle;
4377 break;
4379 case XmCR_TO_TOP:
4380 bar->dragging = -1;
4381 part = scroll_bar_to_top;
4382 break;
4384 case XmCR_TO_BOTTOM:
4385 bar->dragging = -1;
4386 part = scroll_bar_to_bottom;
4387 break;
4389 case XmCR_DRAG:
4391 int slider_size;
4393 /* Get the slider size. */
4394 block_input ();
4395 XtVaGetValues (widget, XmNsliderSize, &slider_size, NULL);
4396 unblock_input ();
4398 whole = XM_SB_MAX - slider_size;
4399 portion = min (cs->value, whole);
4400 part = scroll_bar_handle;
4401 bar->dragging = cs->value;
4403 break;
4405 case XmCR_VALUE_CHANGED:
4406 break;
4409 if (part >= 0)
4411 window_being_scrolled = bar->window;
4412 x_send_scroll_bar_event (bar->window, part, portion, whole);
4416 #elif defined USE_GTK
4418 /* Scroll bar callback for GTK scroll bars. WIDGET is the scroll
4419 bar widget. DATA is a pointer to the scroll_bar structure. */
4421 static gboolean
4422 xg_scroll_callback (GtkRange *range,
4423 GtkScrollType scroll,
4424 gdouble value,
4425 gpointer user_data)
4427 struct scroll_bar *bar = user_data;
4428 gdouble position;
4429 int part = -1, whole = 0, portion = 0;
4430 GtkAdjustment *adj = GTK_ADJUSTMENT (gtk_range_get_adjustment (range));
4431 struct frame *f = g_object_get_data (G_OBJECT (range), XG_FRAME_DATA);
4433 if (xg_ignore_gtk_scrollbar) return FALSE;
4434 position = gtk_adjustment_get_value (adj);
4437 switch (scroll)
4439 case GTK_SCROLL_JUMP:
4440 /* Buttons 1 2 or 3 must be grabbed. */
4441 if (FRAME_DISPLAY_INFO (f)->grabbed != 0
4442 && FRAME_DISPLAY_INFO (f)->grabbed < (1 << 4))
4444 part = scroll_bar_handle;
4445 whole = gtk_adjustment_get_upper (adj) -
4446 gtk_adjustment_get_page_size (adj);
4447 portion = min ((int)position, whole);
4448 bar->dragging = portion;
4450 break;
4451 case GTK_SCROLL_STEP_BACKWARD:
4452 part = scroll_bar_up_arrow;
4453 bar->dragging = -1;
4454 break;
4455 case GTK_SCROLL_STEP_FORWARD:
4456 part = scroll_bar_down_arrow;
4457 bar->dragging = -1;
4458 break;
4459 case GTK_SCROLL_PAGE_BACKWARD:
4460 part = scroll_bar_above_handle;
4461 bar->dragging = -1;
4462 break;
4463 case GTK_SCROLL_PAGE_FORWARD:
4464 part = scroll_bar_below_handle;
4465 bar->dragging = -1;
4466 break;
4469 if (part >= 0)
4471 window_being_scrolled = bar->window;
4472 x_send_scroll_bar_event (bar->window, part, portion, whole);
4475 return FALSE;
4478 /* Callback for button release. Sets dragging to -1 when dragging is done. */
4480 static gboolean
4481 xg_end_scroll_callback (GtkWidget *widget,
4482 GdkEventButton *event,
4483 gpointer user_data)
4485 struct scroll_bar *bar = user_data;
4486 bar->dragging = -1;
4487 if (WINDOWP (window_being_scrolled))
4489 x_send_scroll_bar_event (window_being_scrolled,
4490 scroll_bar_end_scroll, 0, 0);
4491 window_being_scrolled = Qnil;
4494 return FALSE;
4498 #else /* not USE_GTK and not USE_MOTIF */
4500 /* Xaw scroll bar callback. Invoked when the thumb is dragged.
4501 WIDGET is the scroll bar widget. CLIENT_DATA is a pointer to the
4502 scroll bar struct. CALL_DATA is a pointer to a float saying where
4503 the thumb is. */
4505 static void
4506 xaw_jump_callback (Widget widget, XtPointer client_data, XtPointer call_data)
4508 struct scroll_bar *bar = client_data;
4509 float *top_addr = call_data;
4510 float top = *top_addr;
4511 float shown;
4512 int whole, portion, height;
4513 enum scroll_bar_part part;
4515 /* Get the size of the thumb, a value between 0 and 1. */
4516 block_input ();
4517 XtVaGetValues (widget, XtNshown, &shown, XtNheight, &height, NULL);
4518 unblock_input ();
4520 whole = 10000000;
4521 portion = shown < 1 ? top * whole : 0;
4523 if (shown < 1 && (eabs (top + shown - 1) < 1.0f / height))
4524 /* Some derivatives of Xaw refuse to shrink the thumb when you reach
4525 the bottom, so we force the scrolling whenever we see that we're
4526 too close to the bottom (in x_set_toolkit_scroll_bar_thumb
4527 we try to ensure that we always stay two pixels away from the
4528 bottom). */
4529 part = scroll_bar_down_arrow;
4530 else
4531 part = scroll_bar_handle;
4533 window_being_scrolled = bar->window;
4534 bar->dragging = portion;
4535 bar->last_seen_part = part;
4536 x_send_scroll_bar_event (bar->window, part, portion, whole);
4540 /* Xaw scroll bar callback. Invoked for incremental scrolling.,
4541 i.e. line or page up or down. WIDGET is the Xaw scroll bar
4542 widget. CLIENT_DATA is a pointer to the scroll_bar structure for
4543 the scroll bar. CALL_DATA is an integer specifying the action that
4544 has taken place. Its magnitude is in the range 0..height of the
4545 scroll bar. Negative values mean scroll towards buffer start.
4546 Values < height of scroll bar mean line-wise movement. */
4548 static void
4549 xaw_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
4551 struct scroll_bar *bar = client_data;
4552 /* The position really is stored cast to a pointer. */
4553 int position = (intptr_t) call_data;
4554 Dimension height;
4555 enum scroll_bar_part part;
4557 /* Get the height of the scroll bar. */
4558 block_input ();
4559 XtVaGetValues (widget, XtNheight, &height, NULL);
4560 unblock_input ();
4562 if (eabs (position) >= height)
4563 part = (position < 0) ? scroll_bar_above_handle : scroll_bar_below_handle;
4565 /* If Xaw3d was compiled with ARROW_SCROLLBAR,
4566 it maps line-movement to call_data = max(5, height/20). */
4567 else if (xaw3d_arrow_scroll && eabs (position) <= max (5, height / 20))
4568 part = (position < 0) ? scroll_bar_up_arrow : scroll_bar_down_arrow;
4569 else
4570 part = scroll_bar_move_ratio;
4572 window_being_scrolled = bar->window;
4573 bar->dragging = -1;
4574 bar->last_seen_part = part;
4575 x_send_scroll_bar_event (bar->window, part, position, height);
4578 #endif /* not USE_GTK and not USE_MOTIF */
4580 #define SCROLL_BAR_NAME "verticalScrollBar"
4582 /* Create the widget for scroll bar BAR on frame F. Record the widget
4583 and X window of the scroll bar in BAR. */
4585 #ifdef USE_GTK
4586 static void
4587 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
4589 const char *scroll_bar_name = SCROLL_BAR_NAME;
4591 block_input ();
4592 xg_create_scroll_bar (f, bar, G_CALLBACK (xg_scroll_callback),
4593 G_CALLBACK (xg_end_scroll_callback),
4594 scroll_bar_name);
4595 unblock_input ();
4598 #else /* not USE_GTK */
4600 static void
4601 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
4603 Window xwindow;
4604 Widget widget;
4605 Arg av[20];
4606 int ac = 0;
4607 const char *scroll_bar_name = SCROLL_BAR_NAME;
4608 unsigned long pixel;
4610 block_input ();
4612 #ifdef USE_MOTIF
4613 /* Set resources. Create the widget. */
4614 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
4615 XtSetArg (av[ac], XmNminimum, 0); ++ac;
4616 XtSetArg (av[ac], XmNmaximum, XM_SB_MAX); ++ac;
4617 XtSetArg (av[ac], XmNorientation, XmVERTICAL); ++ac;
4618 XtSetArg (av[ac], XmNprocessingDirection, XmMAX_ON_BOTTOM), ++ac;
4619 XtSetArg (av[ac], XmNincrement, 1); ++ac;
4620 XtSetArg (av[ac], XmNpageIncrement, 1); ++ac;
4622 pixel = f->output_data.x->scroll_bar_foreground_pixel;
4623 if (pixel != -1)
4625 XtSetArg (av[ac], XmNforeground, pixel);
4626 ++ac;
4629 pixel = f->output_data.x->scroll_bar_background_pixel;
4630 if (pixel != -1)
4632 XtSetArg (av[ac], XmNbackground, pixel);
4633 ++ac;
4636 widget = XmCreateScrollBar (f->output_data.x->edit_widget,
4637 (char *) scroll_bar_name, av, ac);
4639 /* Add one callback for everything that can happen. */
4640 XtAddCallback (widget, XmNdecrementCallback, xm_scroll_callback,
4641 (XtPointer) bar);
4642 XtAddCallback (widget, XmNdragCallback, xm_scroll_callback,
4643 (XtPointer) bar);
4644 XtAddCallback (widget, XmNincrementCallback, xm_scroll_callback,
4645 (XtPointer) bar);
4646 XtAddCallback (widget, XmNpageDecrementCallback, xm_scroll_callback,
4647 (XtPointer) bar);
4648 XtAddCallback (widget, XmNpageIncrementCallback, xm_scroll_callback,
4649 (XtPointer) bar);
4650 XtAddCallback (widget, XmNtoBottomCallback, xm_scroll_callback,
4651 (XtPointer) bar);
4652 XtAddCallback (widget, XmNtoTopCallback, xm_scroll_callback,
4653 (XtPointer) bar);
4655 /* Realize the widget. Only after that is the X window created. */
4656 XtRealizeWidget (widget);
4658 /* Set the cursor to an arrow. I didn't find a resource to do that.
4659 And I'm wondering why it hasn't an arrow cursor by default. */
4660 XDefineCursor (XtDisplay (widget), XtWindow (widget),
4661 f->output_data.x->nontext_cursor);
4663 #else /* !USE_MOTIF i.e. use Xaw */
4665 /* Set resources. Create the widget. The background of the
4666 Xaw3d scroll bar widget is a little bit light for my taste.
4667 We don't alter it here to let users change it according
4668 to their taste with `emacs*verticalScrollBar.background: xxx'. */
4669 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
4670 XtSetArg (av[ac], XtNorientation, XtorientVertical); ++ac;
4671 /* For smoother scrolling with Xaw3d -sm */
4672 /* XtSetArg (av[ac], XtNpickTop, True); ++ac; */
4674 pixel = f->output_data.x->scroll_bar_foreground_pixel;
4675 if (pixel != -1)
4677 XtSetArg (av[ac], XtNforeground, pixel);
4678 ++ac;
4681 pixel = f->output_data.x->scroll_bar_background_pixel;
4682 if (pixel != -1)
4684 XtSetArg (av[ac], XtNbackground, pixel);
4685 ++ac;
4688 /* Top/bottom shadow colors. */
4690 /* Allocate them, if necessary. */
4691 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1)
4693 pixel = f->output_data.x->scroll_bar_background_pixel;
4694 if (pixel != -1)
4696 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
4697 FRAME_X_COLORMAP (f),
4698 &pixel, 1.2, 0x8000))
4699 pixel = -1;
4700 f->output_data.x->scroll_bar_top_shadow_pixel = pixel;
4703 if (f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
4705 pixel = f->output_data.x->scroll_bar_background_pixel;
4706 if (pixel != -1)
4708 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
4709 FRAME_X_COLORMAP (f),
4710 &pixel, 0.6, 0x4000))
4711 pixel = -1;
4712 f->output_data.x->scroll_bar_bottom_shadow_pixel = pixel;
4716 #ifdef XtNbeNiceToColormap
4717 /* Tell the toolkit about them. */
4718 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1
4719 || f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
4720 /* We tried to allocate a color for the top/bottom shadow, and
4721 failed, so tell Xaw3d to use dithering instead. */
4722 /* But only if we have a small colormap. Xaw3d can allocate nice
4723 colors itself. */
4725 XtSetArg (av[ac], XtNbeNiceToColormap,
4726 DefaultDepthOfScreen (FRAME_X_SCREEN (f)) < 16);
4727 ++ac;
4729 else
4730 /* Tell what colors Xaw3d should use for the top/bottom shadow, to
4731 be more consistent with other emacs 3d colors, and since Xaw3d is
4732 not good at dealing with allocation failure. */
4734 /* This tells Xaw3d to use real colors instead of dithering for
4735 the shadows. */
4736 XtSetArg (av[ac], XtNbeNiceToColormap, False);
4737 ++ac;
4739 /* Specify the colors. */
4740 pixel = f->output_data.x->scroll_bar_top_shadow_pixel;
4741 if (pixel != -1)
4743 XtSetArg (av[ac], XtNtopShadowPixel, pixel);
4744 ++ac;
4746 pixel = f->output_data.x->scroll_bar_bottom_shadow_pixel;
4747 if (pixel != -1)
4749 XtSetArg (av[ac], XtNbottomShadowPixel, pixel);
4750 ++ac;
4753 #endif
4755 widget = XtCreateWidget (scroll_bar_name, scrollbarWidgetClass,
4756 f->output_data.x->edit_widget, av, ac);
4759 char const *initial = "";
4760 char const *val = initial;
4761 XtVaGetValues (widget, XtNscrollVCursor, (XtPointer) &val,
4762 #ifdef XtNarrowScrollbars
4763 XtNarrowScrollbars, (XtPointer) &xaw3d_arrow_scroll,
4764 #endif
4765 XtNpickTop, (XtPointer) &xaw3d_pick_top, NULL);
4766 if (xaw3d_arrow_scroll || val == initial)
4767 { /* ARROW_SCROLL */
4768 xaw3d_arrow_scroll = True;
4769 /* Isn't that just a personal preference ? --Stef */
4770 XtVaSetValues (widget, XtNcursorName, "top_left_arrow", NULL);
4774 /* Define callbacks. */
4775 XtAddCallback (widget, XtNjumpProc, xaw_jump_callback, (XtPointer) bar);
4776 XtAddCallback (widget, XtNscrollProc, xaw_scroll_callback,
4777 (XtPointer) bar);
4779 /* Realize the widget. Only after that is the X window created. */
4780 XtRealizeWidget (widget);
4782 #endif /* !USE_MOTIF */
4784 /* Install an action hook that lets us detect when the user
4785 finishes interacting with a scroll bar. */
4786 if (action_hook_id == 0)
4787 action_hook_id = XtAppAddActionHook (Xt_app_con, xt_action_hook, 0);
4789 /* Remember X window and widget in the scroll bar vector. */
4790 SET_SCROLL_BAR_X_WIDGET (bar, widget);
4791 xwindow = XtWindow (widget);
4792 bar->x_window = xwindow;
4794 unblock_input ();
4796 #endif /* not USE_GTK */
4799 /* Set the thumb size and position of scroll bar BAR. We are currently
4800 displaying PORTION out of a whole WHOLE, and our position POSITION. */
4802 #ifdef USE_GTK
4803 static void
4804 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position, int whole)
4806 xg_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
4809 #else /* not USE_GTK */
4810 static void
4811 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position,
4812 int whole)
4814 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
4815 Widget widget = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
4816 float top, shown;
4818 block_input ();
4820 #ifdef USE_MOTIF
4822 if (scroll_bar_adjust_thumb_portion_p)
4824 /* We use an estimate of 30 chars per line rather than the real
4825 `portion' value. This has the disadvantage that the thumb size
4826 is not very representative, but it makes our life a lot easier.
4827 Otherwise, we have to constantly adjust the thumb size, which
4828 we can't always do quickly enough: while dragging, the size of
4829 the thumb might prevent the user from dragging the thumb all the
4830 way to the end. but Motif and some versions of Xaw3d don't allow
4831 updating the thumb size while dragging. Also, even if we can update
4832 its size, the update will often happen too late.
4833 If you don't believe it, check out revision 1.650 of xterm.c to see
4834 what hoops we were going through and the still poor behavior we got. */
4835 portion = WINDOW_TOTAL_LINES (XWINDOW (bar->window)) * 30;
4836 /* When the thumb is at the bottom, position == whole.
4837 So we need to increase `whole' to make space for the thumb. */
4838 whole += portion;
4841 if (whole <= 0)
4842 top = 0, shown = 1;
4843 else
4845 top = (float) position / whole;
4846 shown = (float) portion / whole;
4849 if (bar->dragging == -1)
4851 int size, value;
4853 /* Slider size. Must be in the range [1 .. MAX - MIN] where MAX
4854 is the scroll bar's maximum and MIN is the scroll bar's minimum
4855 value. */
4856 size = clip_to_bounds (1, shown * XM_SB_MAX, XM_SB_MAX);
4858 /* Position. Must be in the range [MIN .. MAX - SLIDER_SIZE]. */
4859 value = top * XM_SB_MAX;
4860 value = min (value, XM_SB_MAX - size);
4862 XmScrollBarSetValues (widget, value, size, 0, 0, False);
4864 #else /* !USE_MOTIF i.e. use Xaw */
4866 if (whole == 0)
4867 top = 0, shown = 1;
4868 else
4870 top = (float) position / whole;
4871 shown = (float) portion / whole;
4875 float old_top, old_shown;
4876 Dimension height;
4877 XtVaGetValues (widget,
4878 XtNtopOfThumb, &old_top,
4879 XtNshown, &old_shown,
4880 XtNheight, &height,
4881 NULL);
4883 /* Massage the top+shown values. */
4884 if (bar->dragging == -1 || bar->last_seen_part == scroll_bar_down_arrow)
4885 top = max (0, min (1, top));
4886 else
4887 top = old_top;
4888 #if ! defined (HAVE_XAW3D)
4889 /* With Xaw, 'top' values too closer to 1.0 may
4890 cause the thumb to disappear. Fix that. */
4891 top = min (top, 0.99f);
4892 #endif
4893 /* Keep two pixels available for moving the thumb down. */
4894 shown = max (0, min (1 - top - (2.0f / height), shown));
4895 #if ! defined (HAVE_XAW3D)
4896 /* Likewise with too small 'shown'. */
4897 shown = max (shown, 0.01f);
4898 #endif
4900 /* If the call to XawScrollbarSetThumb below doesn't seem to
4901 work, check that 'NARROWPROTO' is defined in src/config.h.
4902 If this is not so, most likely you need to fix configure. */
4903 if (top != old_top || shown != old_shown)
4905 if (bar->dragging == -1)
4906 XawScrollbarSetThumb (widget, top, shown);
4907 else
4909 /* Try to make the scrolling a tad smoother. */
4910 if (!xaw3d_pick_top)
4911 shown = min (shown, old_shown);
4913 XawScrollbarSetThumb (widget, top, shown);
4917 #endif /* !USE_MOTIF */
4919 unblock_input ();
4921 #endif /* not USE_GTK */
4923 #endif /* USE_TOOLKIT_SCROLL_BARS */
4927 /************************************************************************
4928 Scroll bars, general
4929 ************************************************************************/
4931 /* Create a scroll bar and return the scroll bar vector for it. W is
4932 the Emacs window on which to create the scroll bar. TOP, LEFT,
4933 WIDTH and HEIGHT are the pixel coordinates and dimensions of the
4934 scroll bar. */
4936 static struct scroll_bar *
4937 x_scroll_bar_create (struct window *w, int top, int left, int width, int height)
4939 struct frame *f = XFRAME (w->frame);
4940 struct scroll_bar *bar
4941 = ALLOCATE_PSEUDOVECTOR (struct scroll_bar, x_window, PVEC_OTHER);
4942 Lisp_Object barobj;
4944 block_input ();
4946 #ifdef USE_TOOLKIT_SCROLL_BARS
4947 x_create_toolkit_scroll_bar (f, bar);
4948 #else /* not USE_TOOLKIT_SCROLL_BARS */
4950 XSetWindowAttributes a;
4951 unsigned long mask;
4952 Window window;
4954 a.background_pixel = f->output_data.x->scroll_bar_background_pixel;
4955 if (a.background_pixel == -1)
4956 a.background_pixel = FRAME_BACKGROUND_PIXEL (f);
4958 a.event_mask = (ButtonPressMask | ButtonReleaseMask
4959 | ButtonMotionMask | PointerMotionHintMask
4960 | ExposureMask);
4961 a.cursor = FRAME_DISPLAY_INFO (f)->vertical_scroll_bar_cursor;
4963 mask = (CWBackPixel | CWEventMask | CWCursor);
4965 /* Clear the area of W that will serve as a scroll bar. This is
4966 for the case that a window has been split horizontally. In
4967 this case, no clear_frame is generated to reduce flickering. */
4968 if (width > 0 && window_box_height (w) > 0)
4969 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4970 left, top, width, window_box_height (w));
4972 window = XCreateWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4973 /* Position and size of scroll bar. */
4974 left, top, width, height,
4975 /* Border width, depth, class, and visual. */
4977 CopyFromParent,
4978 CopyFromParent,
4979 CopyFromParent,
4980 /* Attributes. */
4981 mask, &a);
4982 bar->x_window = window;
4984 #endif /* not USE_TOOLKIT_SCROLL_BARS */
4986 XSETWINDOW (bar->window, w);
4987 bar->top = top;
4988 bar->left = left;
4989 bar->width = width;
4990 bar->height = height;
4991 bar->start = 0;
4992 bar->end = 0;
4993 bar->dragging = -1;
4994 bar->fringe_extended_p = 0;
4995 #if defined (USE_TOOLKIT_SCROLL_BARS) && defined (USE_LUCID)
4996 bar->last_seen_part = scroll_bar_nowhere;
4997 #endif
4999 /* Add bar to its frame's list of scroll bars. */
5000 bar->next = FRAME_SCROLL_BARS (f);
5001 bar->prev = Qnil;
5002 XSETVECTOR (barobj, bar);
5003 fset_scroll_bars (f, barobj);
5004 if (!NILP (bar->next))
5005 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
5007 /* Map the window/widget. */
5008 #ifdef USE_TOOLKIT_SCROLL_BARS
5010 #ifdef USE_GTK
5011 xg_update_scrollbar_pos (f, bar->x_window, top,
5012 left,width, max (height, 1));
5013 #else /* not USE_GTK */
5014 Widget scroll_bar = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
5015 XtConfigureWidget (scroll_bar, left, top, width, max (height, 1), 0);
5016 XtMapWidget (scroll_bar);
5017 #endif /* not USE_GTK */
5019 #else /* not USE_TOOLKIT_SCROLL_BARS */
5020 XMapRaised (FRAME_X_DISPLAY (f), bar->x_window);
5021 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5023 unblock_input ();
5024 return bar;
5028 #ifndef USE_TOOLKIT_SCROLL_BARS
5030 /* Draw BAR's handle in the proper position.
5032 If the handle is already drawn from START to END, don't bother
5033 redrawing it, unless REBUILD is non-zero; in that case, always
5034 redraw it. (REBUILD is handy for drawing the handle after expose
5035 events.)
5037 Normally, we want to constrain the start and end of the handle to
5038 fit inside its rectangle, but if the user is dragging the scroll
5039 bar handle, we want to let them drag it down all the way, so that
5040 the bar's top is as far down as it goes; otherwise, there's no way
5041 to move to the very end of the buffer. */
5043 static void
5044 x_scroll_bar_set_handle (struct scroll_bar *bar, int start, int end, int rebuild)
5046 bool dragging = bar->dragging != -1;
5047 Window w = bar->x_window;
5048 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5049 GC gc = f->output_data.x->normal_gc;
5051 /* If the display is already accurate, do nothing. */
5052 if (! rebuild
5053 && start == bar->start
5054 && end == bar->end)
5055 return;
5057 block_input ();
5060 int inside_width = VERTICAL_SCROLL_BAR_INSIDE_WIDTH (f, bar->width);
5061 int inside_height = VERTICAL_SCROLL_BAR_INSIDE_HEIGHT (f, bar->height);
5062 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
5064 /* Make sure the values are reasonable, and try to preserve
5065 the distance between start and end. */
5067 int length = end - start;
5069 if (start < 0)
5070 start = 0;
5071 else if (start > top_range)
5072 start = top_range;
5073 end = start + length;
5075 if (end < start)
5076 end = start;
5077 else if (end > top_range && ! dragging)
5078 end = top_range;
5081 /* Store the adjusted setting in the scroll bar. */
5082 bar->start = start;
5083 bar->end = end;
5085 /* Clip the end position, just for display. */
5086 if (end > top_range)
5087 end = top_range;
5089 /* Draw bottom positions VERTICAL_SCROLL_BAR_MIN_HANDLE pixels
5090 below top positions, to make sure the handle is always at least
5091 that many pixels tall. */
5092 end += VERTICAL_SCROLL_BAR_MIN_HANDLE;
5094 /* Draw the empty space above the handle. Note that we can't clear
5095 zero-height areas; that means "clear to end of window." */
5096 if (start > 0)
5097 x_clear_area (FRAME_X_DISPLAY (f), w,
5098 VERTICAL_SCROLL_BAR_LEFT_BORDER,
5099 VERTICAL_SCROLL_BAR_TOP_BORDER,
5100 inside_width, start);
5102 /* Change to proper foreground color if one is specified. */
5103 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5104 XSetForeground (FRAME_X_DISPLAY (f), gc,
5105 f->output_data.x->scroll_bar_foreground_pixel);
5107 /* Draw the handle itself. */
5108 XFillRectangle (FRAME_X_DISPLAY (f), w, gc,
5109 /* x, y, width, height */
5110 VERTICAL_SCROLL_BAR_LEFT_BORDER,
5111 VERTICAL_SCROLL_BAR_TOP_BORDER + start,
5112 inside_width, end - start);
5114 /* Restore the foreground color of the GC if we changed it above. */
5115 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5116 XSetForeground (FRAME_X_DISPLAY (f), gc,
5117 FRAME_FOREGROUND_PIXEL (f));
5119 /* Draw the empty space below the handle. Note that we can't
5120 clear zero-height areas; that means "clear to end of window." */
5121 if (end < inside_height)
5122 x_clear_area (FRAME_X_DISPLAY (f), w,
5123 VERTICAL_SCROLL_BAR_LEFT_BORDER,
5124 VERTICAL_SCROLL_BAR_TOP_BORDER + end,
5125 inside_width, inside_height - end);
5128 unblock_input ();
5131 #endif /* !USE_TOOLKIT_SCROLL_BARS */
5133 /* Destroy scroll bar BAR, and set its Emacs window's scroll bar to
5134 nil. */
5136 static void
5137 x_scroll_bar_remove (struct scroll_bar *bar)
5139 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5140 block_input ();
5142 #ifdef USE_TOOLKIT_SCROLL_BARS
5143 #ifdef USE_GTK
5144 xg_remove_scroll_bar (f, bar->x_window);
5145 #else /* not USE_GTK */
5146 XtDestroyWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar));
5147 #endif /* not USE_GTK */
5148 #else
5149 XDestroyWindow (FRAME_X_DISPLAY (f), bar->x_window);
5150 #endif
5152 /* Dissociate this scroll bar from its window. */
5153 wset_vertical_scroll_bar (XWINDOW (bar->window), Qnil);
5155 unblock_input ();
5159 /* Set the handle of the vertical scroll bar for WINDOW to indicate
5160 that we are displaying PORTION characters out of a total of WHOLE
5161 characters, starting at POSITION. If WINDOW has no scroll bar,
5162 create one. */
5164 static void
5165 XTset_vertical_scroll_bar (struct window *w, int portion, int whole, int position)
5167 struct frame *f = XFRAME (w->frame);
5168 Lisp_Object barobj;
5169 struct scroll_bar *bar;
5170 int top, height, left, sb_left, width, sb_width;
5171 int window_y, window_height;
5172 #ifdef USE_TOOLKIT_SCROLL_BARS
5173 bool fringe_extended_p;
5174 #endif
5176 /* Get window dimensions. */
5177 window_box (w, ANY_AREA, 0, &window_y, 0, &window_height);
5178 top = window_y;
5179 width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
5180 height = window_height;
5182 /* Compute the left edge of the scroll bar area. */
5183 left = WINDOW_SCROLL_BAR_AREA_X (w);
5185 /* Compute the width of the scroll bar which might be less than
5186 the width of the area reserved for the scroll bar. */
5187 if (WINDOW_CONFIG_SCROLL_BAR_WIDTH (w) > 0)
5188 sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
5189 else
5190 sb_width = width;
5192 /* Compute the left edge of the scroll bar. */
5193 #ifdef USE_TOOLKIT_SCROLL_BARS
5194 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w))
5195 sb_left = left + (WINDOW_RIGHTMOST_P (w) ? width - sb_width : 0);
5196 else
5197 sb_left = left + (WINDOW_LEFTMOST_P (w) ? 0 : width - sb_width);
5198 #else
5199 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w))
5200 sb_left = left + width - sb_width;
5201 else
5202 sb_left = left;
5203 #endif
5205 #ifdef USE_TOOLKIT_SCROLL_BARS
5206 fringe_extended_p = WINDOW_FRINGE_EXTENDED_P (w);
5207 #endif
5209 /* Does the scroll bar exist yet? */
5210 if (NILP (w->vertical_scroll_bar))
5212 if (width > 0 && height > 0)
5214 block_input ();
5215 #ifdef USE_TOOLKIT_SCROLL_BARS
5216 if (fringe_extended_p)
5217 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5218 sb_left, top, sb_width, height);
5219 else
5220 #endif
5221 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5222 left, top, width, height);
5223 unblock_input ();
5226 bar = x_scroll_bar_create (w, top, sb_left, sb_width, max (height, 1));
5228 else
5230 /* It may just need to be moved and resized. */
5231 unsigned int mask = 0;
5233 bar = XSCROLL_BAR (w->vertical_scroll_bar);
5235 block_input ();
5237 if (sb_left != bar->left)
5238 mask |= CWX;
5239 if (top != bar->top)
5240 mask |= CWY;
5241 if (sb_width != bar->width)
5242 mask |= CWWidth;
5243 if (height != bar->height)
5244 mask |= CWHeight;
5246 #ifdef USE_TOOLKIT_SCROLL_BARS
5248 /* Move/size the scroll bar widget. */
5249 if (mask || bar->fringe_extended_p != fringe_extended_p)
5251 /* Since toolkit scroll bars are smaller than the space reserved
5252 for them on the frame, we have to clear "under" them. */
5253 if (width > 0 && height > 0)
5255 if (fringe_extended_p)
5256 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5257 sb_left, top, sb_width, height);
5258 else
5259 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5260 left, top, width, height);
5262 #ifdef USE_GTK
5263 xg_update_scrollbar_pos (f, bar->x_window, top,
5264 sb_left, sb_width, max (height, 1));
5265 #else /* not USE_GTK */
5266 XtConfigureWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar),
5267 sb_left, top, sb_width, max (height, 1), 0);
5268 #endif /* not USE_GTK */
5270 #else /* not USE_TOOLKIT_SCROLL_BARS */
5272 /* Clear areas not covered by the scroll bar because it's not as
5273 wide as the area reserved for it. This makes sure a
5274 previous mode line display is cleared after C-x 2 C-x 1, for
5275 example. */
5277 int area_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
5278 int rest = area_width - sb_width;
5279 if (rest > 0 && height > 0)
5281 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
5282 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5283 left + area_width - rest, top, rest, height);
5284 else
5285 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5286 left, top, rest, height);
5290 /* Move/size the scroll bar window. */
5291 if (mask)
5293 XWindowChanges wc;
5295 wc.x = sb_left;
5296 wc.y = top;
5297 wc.width = sb_width;
5298 wc.height = height;
5299 XConfigureWindow (FRAME_X_DISPLAY (f), bar->x_window,
5300 mask, &wc);
5303 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5305 /* Remember new settings. */
5306 bar->left = sb_left;
5307 bar->top = top;
5308 bar->width = sb_width;
5309 bar->height = height;
5311 unblock_input ();
5314 #ifdef USE_TOOLKIT_SCROLL_BARS
5315 bar->fringe_extended_p = fringe_extended_p;
5317 x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
5318 #else /* not USE_TOOLKIT_SCROLL_BARS */
5319 /* Set the scroll bar's current state, unless we're currently being
5320 dragged. */
5321 if (bar->dragging == -1)
5323 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, height);
5325 if (whole == 0)
5326 x_scroll_bar_set_handle (bar, 0, top_range, 0);
5327 else
5329 int start = ((double) position * top_range) / whole;
5330 int end = ((double) (position + portion) * top_range) / whole;
5331 x_scroll_bar_set_handle (bar, start, end, 0);
5334 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5336 XSETVECTOR (barobj, bar);
5337 wset_vertical_scroll_bar (w, barobj);
5341 /* The following three hooks are used when we're doing a thorough
5342 redisplay of the frame. We don't explicitly know which scroll bars
5343 are going to be deleted, because keeping track of when windows go
5344 away is a real pain - "Can you say set-window-configuration, boys
5345 and girls?" Instead, we just assert at the beginning of redisplay
5346 that *all* scroll bars are to be removed, and then save a scroll bar
5347 from the fiery pit when we actually redisplay its window. */
5349 /* Arrange for all scroll bars on FRAME to be removed at the next call
5350 to `*judge_scroll_bars_hook'. A scroll bar may be spared if
5351 `*redeem_scroll_bar_hook' is applied to its window before the judgment. */
5353 static void
5354 XTcondemn_scroll_bars (struct frame *frame)
5356 /* Transfer all the scroll bars to FRAME_CONDEMNED_SCROLL_BARS. */
5357 while (! NILP (FRAME_SCROLL_BARS (frame)))
5359 Lisp_Object bar;
5360 bar = FRAME_SCROLL_BARS (frame);
5361 fset_scroll_bars (frame, XSCROLL_BAR (bar)->next);
5362 XSCROLL_BAR (bar)->next = FRAME_CONDEMNED_SCROLL_BARS (frame);
5363 XSCROLL_BAR (bar)->prev = Qnil;
5364 if (! NILP (FRAME_CONDEMNED_SCROLL_BARS (frame)))
5365 XSCROLL_BAR (FRAME_CONDEMNED_SCROLL_BARS (frame))->prev = bar;
5366 fset_condemned_scroll_bars (frame, bar);
5371 /* Un-mark WINDOW's scroll bar for deletion in this judgment cycle.
5372 Note that WINDOW isn't necessarily condemned at all. */
5374 static void
5375 XTredeem_scroll_bar (struct window *window)
5377 struct scroll_bar *bar;
5378 struct frame *f;
5379 Lisp_Object barobj;
5381 /* We can't redeem this window's scroll bar if it doesn't have one. */
5382 if (NILP (window->vertical_scroll_bar))
5383 emacs_abort ();
5385 bar = XSCROLL_BAR (window->vertical_scroll_bar);
5387 /* Unlink it from the condemned list. */
5388 f = XFRAME (WINDOW_FRAME (window));
5389 if (NILP (bar->prev))
5391 /* If the prev pointer is nil, it must be the first in one of
5392 the lists. */
5393 if (EQ (FRAME_SCROLL_BARS (f), window->vertical_scroll_bar))
5394 /* It's not condemned. Everything's fine. */
5395 return;
5396 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
5397 window->vertical_scroll_bar))
5398 fset_condemned_scroll_bars (f, bar->next);
5399 else
5400 /* If its prev pointer is nil, it must be at the front of
5401 one or the other! */
5402 emacs_abort ();
5404 else
5405 XSCROLL_BAR (bar->prev)->next = bar->next;
5407 if (! NILP (bar->next))
5408 XSCROLL_BAR (bar->next)->prev = bar->prev;
5410 bar->next = FRAME_SCROLL_BARS (f);
5411 bar->prev = Qnil;
5412 XSETVECTOR (barobj, bar);
5413 fset_scroll_bars (f, barobj);
5414 if (! NILP (bar->next))
5415 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
5418 /* Remove all scroll bars on FRAME that haven't been saved since the
5419 last call to `*condemn_scroll_bars_hook'. */
5421 static void
5422 XTjudge_scroll_bars (struct frame *f)
5424 Lisp_Object bar, next;
5426 bar = FRAME_CONDEMNED_SCROLL_BARS (f);
5428 /* Clear out the condemned list now so we won't try to process any
5429 more events on the hapless scroll bars. */
5430 fset_condemned_scroll_bars (f, Qnil);
5432 for (; ! NILP (bar); bar = next)
5434 struct scroll_bar *b = XSCROLL_BAR (bar);
5436 x_scroll_bar_remove (b);
5438 next = b->next;
5439 b->next = b->prev = Qnil;
5442 /* Now there should be no references to the condemned scroll bars,
5443 and they should get garbage-collected. */
5447 #ifndef USE_TOOLKIT_SCROLL_BARS
5448 /* Handle an Expose or GraphicsExpose event on a scroll bar. This
5449 is a no-op when using toolkit scroll bars.
5451 This may be called from a signal handler, so we have to ignore GC
5452 mark bits. */
5454 static void
5455 x_scroll_bar_expose (struct scroll_bar *bar, const XEvent *event)
5457 Window w = bar->x_window;
5458 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5459 GC gc = f->output_data.x->normal_gc;
5461 block_input ();
5463 x_scroll_bar_set_handle (bar, bar->start, bar->end, 1);
5465 /* Switch to scroll bar foreground color. */
5466 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5467 XSetForeground (FRAME_X_DISPLAY (f), gc,
5468 f->output_data.x->scroll_bar_foreground_pixel);
5470 /* Draw a one-pixel border just inside the edges of the scroll bar. */
5471 XDrawRectangle (FRAME_X_DISPLAY (f), w, gc,
5472 /* x, y, width, height */
5473 0, 0, bar->width - 1, bar->height - 1);
5475 /* Restore the foreground color of the GC if we changed it above. */
5476 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5477 XSetForeground (FRAME_X_DISPLAY (f), gc,
5478 FRAME_FOREGROUND_PIXEL (f));
5480 unblock_input ();
5483 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5485 /* Handle a mouse click on the scroll bar BAR. If *EMACS_EVENT's kind
5486 is set to something other than NO_EVENT, it is enqueued.
5488 This may be called from a signal handler, so we have to ignore GC
5489 mark bits. */
5492 static void
5493 x_scroll_bar_handle_click (struct scroll_bar *bar,
5494 const XEvent *event,
5495 struct input_event *emacs_event)
5497 if (! WINDOWP (bar->window))
5498 emacs_abort ();
5500 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
5501 emacs_event->code = event->xbutton.button - Button1;
5502 emacs_event->modifiers
5503 = (x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO
5504 (XFRAME (WINDOW_FRAME (XWINDOW (bar->window)))),
5505 event->xbutton.state)
5506 | (event->type == ButtonRelease
5507 ? up_modifier
5508 : down_modifier));
5509 emacs_event->frame_or_window = bar->window;
5510 emacs_event->arg = Qnil;
5511 emacs_event->timestamp = event->xbutton.time;
5513 int top_range
5514 = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
5515 int y = event->xbutton.y - VERTICAL_SCROLL_BAR_TOP_BORDER;
5517 if (y < 0) y = 0;
5518 if (y > top_range) y = top_range;
5520 if (y < bar->start)
5521 emacs_event->part = scroll_bar_above_handle;
5522 else if (y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
5523 emacs_event->part = scroll_bar_handle;
5524 else
5525 emacs_event->part = scroll_bar_below_handle;
5527 #ifndef USE_TOOLKIT_SCROLL_BARS
5528 /* If the user has released the handle, set it to its final position. */
5529 if (event->type == ButtonRelease && bar->dragging != -1)
5531 int new_start = y - bar->dragging;
5532 int new_end = new_start + bar->end - bar->start;
5534 x_scroll_bar_set_handle (bar, new_start, new_end, 0);
5535 bar->dragging = -1;
5537 #endif
5539 XSETINT (emacs_event->x, y);
5540 XSETINT (emacs_event->y, top_range);
5544 #ifndef USE_TOOLKIT_SCROLL_BARS
5546 /* Handle some mouse motion while someone is dragging the scroll bar.
5548 This may be called from a signal handler, so we have to ignore GC
5549 mark bits. */
5551 static void
5552 x_scroll_bar_note_movement (struct scroll_bar *bar,
5553 const XMotionEvent *event)
5555 struct frame *f = XFRAME (XWINDOW (bar->window)->frame);
5556 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
5558 dpyinfo->last_mouse_movement_time = event->time;
5559 dpyinfo->last_mouse_scroll_bar = bar;
5560 f->mouse_moved = 1;
5562 /* If we're dragging the bar, display it. */
5563 if (bar->dragging != -1)
5565 /* Where should the handle be now? */
5566 int new_start = event->y - bar->dragging;
5568 if (new_start != bar->start)
5570 int new_end = new_start + bar->end - bar->start;
5572 x_scroll_bar_set_handle (bar, new_start, new_end, 0);
5577 #endif /* !USE_TOOLKIT_SCROLL_BARS */
5579 /* Return information to the user about the current position of the mouse
5580 on the scroll bar. */
5582 static void
5583 x_scroll_bar_report_motion (struct frame **fp, Lisp_Object *bar_window,
5584 enum scroll_bar_part *part, Lisp_Object *x,
5585 Lisp_Object *y, Time *timestamp)
5587 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (*fp);
5588 struct scroll_bar *bar = dpyinfo->last_mouse_scroll_bar;
5589 Window w = bar->x_window;
5590 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5591 int win_x, win_y;
5592 Window dummy_window;
5593 int dummy_coord;
5594 unsigned int dummy_mask;
5596 block_input ();
5598 /* Get the mouse's position relative to the scroll bar window, and
5599 report that. */
5600 if (XQueryPointer (FRAME_X_DISPLAY (f), w,
5602 /* Root, child, root x and root y. */
5603 &dummy_window, &dummy_window,
5604 &dummy_coord, &dummy_coord,
5606 /* Position relative to scroll bar. */
5607 &win_x, &win_y,
5609 /* Mouse buttons and modifier keys. */
5610 &dummy_mask))
5612 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
5614 win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
5616 if (bar->dragging != -1)
5617 win_y -= bar->dragging;
5619 if (win_y < 0)
5620 win_y = 0;
5621 if (win_y > top_range)
5622 win_y = top_range;
5624 *fp = f;
5625 *bar_window = bar->window;
5627 if (bar->dragging != -1)
5628 *part = scroll_bar_handle;
5629 else if (win_y < bar->start)
5630 *part = scroll_bar_above_handle;
5631 else if (win_y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
5632 *part = scroll_bar_handle;
5633 else
5634 *part = scroll_bar_below_handle;
5636 XSETINT (*x, win_y);
5637 XSETINT (*y, top_range);
5639 f->mouse_moved = 0;
5640 dpyinfo->last_mouse_scroll_bar = NULL;
5641 *timestamp = dpyinfo->last_mouse_movement_time;
5644 unblock_input ();
5648 /* The screen has been cleared so we may have changed foreground or
5649 background colors, and the scroll bars may need to be redrawn.
5650 Clear out the scroll bars, and ask for expose events, so we can
5651 redraw them. */
5653 static void
5654 x_scroll_bar_clear (struct frame *f)
5656 #ifndef USE_TOOLKIT_SCROLL_BARS
5657 Lisp_Object bar;
5659 /* We can have scroll bars even if this is 0,
5660 if we just turned off scroll bar mode.
5661 But in that case we should not clear them. */
5662 if (FRAME_HAS_VERTICAL_SCROLL_BARS (f))
5663 for (bar = FRAME_SCROLL_BARS (f); VECTORP (bar);
5664 bar = XSCROLL_BAR (bar)->next)
5665 XClearArea (FRAME_X_DISPLAY (f),
5666 XSCROLL_BAR (bar)->x_window,
5667 0, 0, 0, 0, True);
5668 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5671 #ifdef ENABLE_CHECKING
5673 /* Record the last 100 characters stored
5674 to help debug the loss-of-chars-during-GC problem. */
5676 static int temp_index;
5677 static short temp_buffer[100];
5679 #define STORE_KEYSYM_FOR_DEBUG(keysym) \
5680 if (temp_index == sizeof temp_buffer / sizeof (short)) \
5681 temp_index = 0; \
5682 temp_buffer[temp_index++] = (keysym)
5684 #else /* not ENABLE_CHECKING */
5686 #define STORE_KEYSYM_FOR_DEBUG(keysym) ((void)0)
5688 #endif /* ENABLE_CHECKING */
5690 /* Set this to nonzero to fake an "X I/O error"
5691 on a particular display. */
5693 static struct x_display_info *XTread_socket_fake_io_error;
5695 /* When we find no input here, we occasionally do a no-op command
5696 to verify that the X server is still running and we can still talk with it.
5697 We try all the open displays, one by one.
5698 This variable is used for cycling thru the displays. */
5700 static struct x_display_info *next_noop_dpyinfo;
5702 enum
5704 X_EVENT_NORMAL,
5705 X_EVENT_GOTO_OUT,
5706 X_EVENT_DROP
5709 /* Filter events for the current X input method.
5710 DPYINFO is the display this event is for.
5711 EVENT is the X event to filter.
5713 Returns non-zero if the event was filtered, caller shall not process
5714 this event further.
5715 Returns zero if event is wasn't filtered. */
5717 #ifdef HAVE_X_I18N
5718 static int
5719 x_filter_event (struct x_display_info *dpyinfo, XEvent *event)
5721 /* XFilterEvent returns non-zero if the input method has
5722 consumed the event. We pass the frame's X window to
5723 XFilterEvent because that's the one for which the IC
5724 was created. */
5726 struct frame *f1 = x_any_window_to_frame (dpyinfo,
5727 event->xclient.window);
5729 return XFilterEvent (event, f1 ? FRAME_X_WINDOW (f1) : None);
5731 #endif
5733 #ifdef USE_GTK
5734 static int current_count;
5735 static int current_finish;
5736 static struct input_event *current_hold_quit;
5738 /* This is the filter function invoked by the GTK event loop.
5739 It is invoked before the XEvent is translated to a GdkEvent,
5740 so we have a chance to act on the event before GTK. */
5741 static GdkFilterReturn
5742 event_handler_gdk (GdkXEvent *gxev, GdkEvent *ev, gpointer data)
5744 XEvent *xev = (XEvent *) gxev;
5746 block_input ();
5747 if (current_count >= 0)
5749 struct x_display_info *dpyinfo;
5751 dpyinfo = x_display_info_for_display (xev->xany.display);
5753 #ifdef HAVE_X_I18N
5754 /* Filter events for the current X input method.
5755 GTK calls XFilterEvent but not for key press and release,
5756 so we do it here. */
5757 if ((xev->type == KeyPress || xev->type == KeyRelease)
5758 && dpyinfo
5759 && x_filter_event (dpyinfo, xev))
5761 unblock_input ();
5762 return GDK_FILTER_REMOVE;
5764 #endif
5766 if (! dpyinfo)
5767 current_finish = X_EVENT_NORMAL;
5768 else
5769 current_count +=
5770 handle_one_xevent (dpyinfo, xev, &current_finish,
5771 current_hold_quit);
5773 else
5774 current_finish = x_dispatch_event (xev, xev->xany.display);
5776 unblock_input ();
5778 if (current_finish == X_EVENT_GOTO_OUT || current_finish == X_EVENT_DROP)
5779 return GDK_FILTER_REMOVE;
5781 return GDK_FILTER_CONTINUE;
5783 #endif /* USE_GTK */
5786 static void xembed_send_message (struct frame *f, Time,
5787 enum xembed_message,
5788 long detail, long data1, long data2);
5790 /* Handles the XEvent EVENT on display DPYINFO.
5792 *FINISH is X_EVENT_GOTO_OUT if caller should stop reading events.
5793 *FINISH is zero if caller should continue reading events.
5794 *FINISH is X_EVENT_DROP if event should not be passed to the toolkit.
5795 *EVENT is unchanged unless we're processing KeyPress event.
5797 We return the number of characters stored into the buffer. */
5799 static int
5800 handle_one_xevent (struct x_display_info *dpyinfo,
5801 const XEvent *event,
5802 int *finish, struct input_event *hold_quit)
5804 union {
5805 struct input_event ie;
5806 struct selection_input_event sie;
5807 } inev;
5808 int count = 0;
5809 int do_help = 0;
5810 ptrdiff_t nbytes = 0;
5811 struct frame *any, *f = NULL;
5812 struct coding_system coding;
5813 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
5814 /* This holds the state XLookupString needs to implement dead keys
5815 and other tricks known as "compose processing". _X Window System_
5816 says that a portable program can't use this, but Stephen Gildea assures
5817 me that letting the compiler initialize it to zeros will work okay. */
5818 static XComposeStatus compose_status;
5820 USE_SAFE_ALLOCA;
5822 *finish = X_EVENT_NORMAL;
5824 EVENT_INIT (inev.ie);
5825 inev.ie.kind = NO_EVENT;
5826 inev.ie.arg = Qnil;
5828 any = x_any_window_to_frame (dpyinfo, event->xany.window);
5830 if (any && any->wait_event_type == event->type)
5831 any->wait_event_type = 0; /* Indicates we got it. */
5833 switch (event->type)
5835 case ClientMessage:
5837 if (event->xclient.message_type == dpyinfo->Xatom_wm_protocols
5838 && event->xclient.format == 32)
5840 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_take_focus)
5842 /* Use the value returned by x_any_window_to_frame
5843 because this could be the shell widget window
5844 if the frame has no title bar. */
5845 f = any;
5846 #ifdef HAVE_X_I18N
5847 /* Not quite sure this is needed -pd */
5848 if (f && FRAME_XIC (f))
5849 XSetICFocus (FRAME_XIC (f));
5850 #endif
5851 #if 0 /* Emacs sets WM hints whose `input' field is `true'. This
5852 instructs the WM to set the input focus automatically for
5853 Emacs with a call to XSetInputFocus. Setting WM_TAKE_FOCUS
5854 tells the WM to send us a ClientMessage WM_TAKE_FOCUS after
5855 it has set the focus. So, XSetInputFocus below is not
5856 needed.
5858 The call to XSetInputFocus below has also caused trouble. In
5859 cases where the XSetInputFocus done by the WM and the one
5860 below are temporally close (on a fast machine), the call
5861 below can generate additional FocusIn events which confuse
5862 Emacs. */
5864 /* Since we set WM_TAKE_FOCUS, we must call
5865 XSetInputFocus explicitly. But not if f is null,
5866 since that might be an event for a deleted frame. */
5867 if (f)
5869 Display *d = event->xclient.display;
5870 /* Catch and ignore errors, in case window has been
5871 iconified by a window manager such as GWM. */
5872 x_catch_errors (d);
5873 XSetInputFocus (d, event->xclient.window,
5874 /* The ICCCM says this is
5875 the only valid choice. */
5876 RevertToParent,
5877 event->xclient.data.l[1]);
5878 /* This is needed to detect the error
5879 if there is an error. */
5880 XSync (d, False);
5881 x_uncatch_errors ();
5883 /* Not certain about handling scroll bars here */
5884 #endif /* 0 */
5885 goto done;
5888 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_save_yourself)
5890 /* Save state modify the WM_COMMAND property to
5891 something which can reinstate us. This notifies
5892 the session manager, who's looking for such a
5893 PropertyNotify. Can restart processing when
5894 a keyboard or mouse event arrives. */
5895 /* If we have a session manager, don't set this.
5896 KDE will then start two Emacsen, one for the
5897 session manager and one for this. */
5898 #ifdef HAVE_X_SM
5899 if (! x_session_have_connection ())
5900 #endif
5902 f = x_top_window_to_frame (dpyinfo,
5903 event->xclient.window);
5904 /* This is just so we only give real data once
5905 for a single Emacs process. */
5906 if (f == SELECTED_FRAME ())
5907 XSetCommand (FRAME_X_DISPLAY (f),
5908 event->xclient.window,
5909 initial_argv, initial_argc);
5910 else if (f)
5911 XSetCommand (FRAME_X_DISPLAY (f),
5912 event->xclient.window,
5913 0, 0);
5915 goto done;
5918 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_delete_window)
5920 f = any;
5921 if (!f)
5922 goto OTHER; /* May be a dialog that is to be removed */
5924 inev.ie.kind = DELETE_WINDOW_EVENT;
5925 XSETFRAME (inev.ie.frame_or_window, f);
5926 goto done;
5929 goto done;
5932 if (event->xclient.message_type == dpyinfo->Xatom_wm_configure_denied)
5933 goto done;
5935 if (event->xclient.message_type == dpyinfo->Xatom_wm_window_moved)
5937 int new_x, new_y;
5938 f = x_window_to_frame (dpyinfo, event->xclient.window);
5940 new_x = event->xclient.data.s[0];
5941 new_y = event->xclient.data.s[1];
5943 if (f)
5945 f->left_pos = new_x;
5946 f->top_pos = new_y;
5948 goto done;
5951 #ifdef HACK_EDITRES
5952 if (event->xclient.message_type == dpyinfo->Xatom_editres)
5954 f = any;
5955 if (f)
5956 _XEditResCheckMessages (f->output_data.x->widget,
5957 NULL, (XEvent *) event, NULL);
5958 goto done;
5960 #endif /* HACK_EDITRES */
5962 if (event->xclient.message_type == dpyinfo->Xatom_DONE
5963 || event->xclient.message_type == dpyinfo->Xatom_PAGE)
5965 /* Ghostview job completed. Kill it. We could
5966 reply with "Next" if we received "Page", but we
5967 currently never do because we are interested in
5968 images, only, which should have 1 page. */
5969 Pixmap pixmap = (Pixmap) event->xclient.data.l[1];
5970 f = x_window_to_frame (dpyinfo, event->xclient.window);
5971 if (!f)
5972 goto OTHER;
5973 x_kill_gs_process (pixmap, f);
5974 expose_frame (f, 0, 0, 0, 0);
5975 goto done;
5978 #ifdef USE_TOOLKIT_SCROLL_BARS
5979 /* Scroll bar callbacks send a ClientMessage from which
5980 we construct an input_event. */
5981 if (event->xclient.message_type == dpyinfo->Xatom_Scrollbar)
5983 x_scroll_bar_to_input_event (event, &inev.ie);
5984 *finish = X_EVENT_GOTO_OUT;
5985 goto done;
5987 #endif /* USE_TOOLKIT_SCROLL_BARS */
5989 /* XEmbed messages from the embedder (if any). */
5990 if (event->xclient.message_type == dpyinfo->Xatom_XEMBED)
5992 enum xembed_message msg = event->xclient.data.l[1];
5993 if (msg == XEMBED_FOCUS_IN || msg == XEMBED_FOCUS_OUT)
5994 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
5996 *finish = X_EVENT_GOTO_OUT;
5997 goto done;
6000 xft_settings_event (dpyinfo, event);
6002 f = any;
6003 if (!f)
6004 goto OTHER;
6005 if (x_handle_dnd_message (f, &event->xclient, dpyinfo, &inev.ie))
6006 *finish = X_EVENT_DROP;
6008 break;
6010 case SelectionNotify:
6011 dpyinfo->last_user_time = event->xselection.time;
6012 #ifdef USE_X_TOOLKIT
6013 if (! x_window_to_frame (dpyinfo, event->xselection.requestor))
6014 goto OTHER;
6015 #endif /* not USE_X_TOOLKIT */
6016 x_handle_selection_notify (&event->xselection);
6017 break;
6019 case SelectionClear: /* Someone has grabbed ownership. */
6020 dpyinfo->last_user_time = event->xselectionclear.time;
6021 #ifdef USE_X_TOOLKIT
6022 if (! x_window_to_frame (dpyinfo, event->xselectionclear.window))
6023 goto OTHER;
6024 #endif /* USE_X_TOOLKIT */
6026 const XSelectionClearEvent *eventp = &event->xselectionclear;
6028 inev.ie.kind = SELECTION_CLEAR_EVENT;
6029 SELECTION_EVENT_DISPLAY (&inev.sie) = eventp->display;
6030 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
6031 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
6033 break;
6035 case SelectionRequest: /* Someone wants our selection. */
6036 dpyinfo->last_user_time = event->xselectionrequest.time;
6037 #ifdef USE_X_TOOLKIT
6038 if (!x_window_to_frame (dpyinfo, event->xselectionrequest.owner))
6039 goto OTHER;
6040 #endif /* USE_X_TOOLKIT */
6042 const XSelectionRequestEvent *eventp = &event->xselectionrequest;
6044 inev.ie.kind = SELECTION_REQUEST_EVENT;
6045 SELECTION_EVENT_DISPLAY (&inev.sie) = eventp->display;
6046 SELECTION_EVENT_REQUESTOR (&inev.sie) = eventp->requestor;
6047 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
6048 SELECTION_EVENT_TARGET (&inev.sie) = eventp->target;
6049 SELECTION_EVENT_PROPERTY (&inev.sie) = eventp->property;
6050 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
6052 break;
6054 case PropertyNotify:
6055 dpyinfo->last_user_time = event->xproperty.time;
6056 f = x_top_window_to_frame (dpyinfo, event->xproperty.window);
6057 if (f && event->xproperty.atom == dpyinfo->Xatom_net_wm_state)
6058 if (x_handle_net_wm_state (f, &event->xproperty)
6059 && FRAME_ICONIFIED_P (f)
6060 && f->output_data.x->net_wm_state_hidden_seen)
6062 /* Gnome shell does not iconify us when C-z is pressed.
6063 It hides the frame. So if our state says we aren't
6064 hidden anymore, treat it as deiconified. */
6065 SET_FRAME_VISIBLE (f, 1);
6066 SET_FRAME_ICONIFIED (f, 0);
6067 f->output_data.x->has_been_visible = 1;
6068 f->output_data.x->net_wm_state_hidden_seen = 0;
6069 inev.ie.kind = DEICONIFY_EVENT;
6070 XSETFRAME (inev.ie.frame_or_window, f);
6073 x_handle_property_notify (&event->xproperty);
6074 xft_settings_event (dpyinfo, event);
6075 goto OTHER;
6077 case ReparentNotify:
6078 f = x_top_window_to_frame (dpyinfo, event->xreparent.window);
6079 if (f)
6081 f->output_data.x->parent_desc = event->xreparent.parent;
6082 x_real_positions (f, &f->left_pos, &f->top_pos);
6084 /* Perhaps reparented due to a WM restart. Reset this. */
6085 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_UNKNOWN;
6086 FRAME_DISPLAY_INFO (f)->net_supported_window = 0;
6088 x_set_frame_alpha (f);
6090 goto OTHER;
6092 case Expose:
6093 f = x_window_to_frame (dpyinfo, event->xexpose.window);
6094 if (f)
6096 if (!FRAME_VISIBLE_P (f))
6098 SET_FRAME_VISIBLE (f, 1);
6099 SET_FRAME_ICONIFIED (f, 0);
6100 f->output_data.x->has_been_visible = 1;
6101 SET_FRAME_GARBAGED (f);
6103 else
6105 #ifdef USE_GTK
6106 /* This seems to be needed for GTK 2.6 and later, see
6107 http://debbugs.gnu.org/cgi/bugreport.cgi?bug=15398. */
6108 x_clear_area (event->xexpose.display,
6109 event->xexpose.window,
6110 event->xexpose.x, event->xexpose.y,
6111 event->xexpose.width, event->xexpose.height);
6112 #endif
6113 expose_frame (f, event->xexpose.x, event->xexpose.y,
6114 event->xexpose.width, event->xexpose.height);
6117 else
6119 #ifndef USE_TOOLKIT_SCROLL_BARS
6120 struct scroll_bar *bar;
6121 #endif
6122 #if defined USE_LUCID
6123 /* Submenus of the Lucid menu bar aren't widgets
6124 themselves, so there's no way to dispatch events
6125 to them. Recognize this case separately. */
6127 Widget widget = x_window_to_menu_bar (event->xexpose.window);
6128 if (widget)
6129 xlwmenu_redisplay (widget);
6131 #endif /* USE_LUCID */
6133 #ifdef USE_TOOLKIT_SCROLL_BARS
6134 /* Dispatch event to the widget. */
6135 goto OTHER;
6136 #else /* not USE_TOOLKIT_SCROLL_BARS */
6137 bar = x_window_to_scroll_bar (event->xexpose.display,
6138 event->xexpose.window);
6140 if (bar)
6141 x_scroll_bar_expose (bar, event);
6142 #ifdef USE_X_TOOLKIT
6143 else
6144 goto OTHER;
6145 #endif /* USE_X_TOOLKIT */
6146 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6148 break;
6150 case GraphicsExpose: /* This occurs when an XCopyArea's
6151 source area was obscured or not
6152 available. */
6153 f = x_window_to_frame (dpyinfo, event->xgraphicsexpose.drawable);
6154 if (f)
6155 expose_frame (f, event->xgraphicsexpose.x,
6156 event->xgraphicsexpose.y,
6157 event->xgraphicsexpose.width,
6158 event->xgraphicsexpose.height);
6159 #ifdef USE_X_TOOLKIT
6160 else
6161 goto OTHER;
6162 #endif /* USE_X_TOOLKIT */
6163 break;
6165 case NoExpose: /* This occurs when an XCopyArea's
6166 source area was completely
6167 available. */
6168 break;
6170 case UnmapNotify:
6171 /* Redo the mouse-highlight after the tooltip has gone. */
6172 if (event->xunmap.window == tip_window)
6174 tip_window = 0;
6175 x_redo_mouse_highlight (dpyinfo);
6178 f = x_top_window_to_frame (dpyinfo, event->xunmap.window);
6179 if (f) /* F may no longer exist if
6180 the frame was deleted. */
6182 bool visible = FRAME_VISIBLE_P (f);
6183 /* While a frame is unmapped, display generation is
6184 disabled; you don't want to spend time updating a
6185 display that won't ever be seen. */
6186 SET_FRAME_VISIBLE (f, 0);
6187 /* We can't distinguish, from the event, whether the window
6188 has become iconified or invisible. So assume, if it
6189 was previously visible, than now it is iconified.
6190 But x_make_frame_invisible clears both
6191 the visible flag and the iconified flag;
6192 and that way, we know the window is not iconified now. */
6193 if (visible || FRAME_ICONIFIED_P (f))
6195 SET_FRAME_ICONIFIED (f, 1);
6196 inev.ie.kind = ICONIFY_EVENT;
6197 XSETFRAME (inev.ie.frame_or_window, f);
6200 goto OTHER;
6202 case MapNotify:
6203 if (event->xmap.window == tip_window)
6204 /* The tooltip has been drawn already. Avoid
6205 the SET_FRAME_GARBAGED below. */
6206 goto OTHER;
6208 /* We use x_top_window_to_frame because map events can
6209 come for sub-windows and they don't mean that the
6210 frame is visible. */
6211 f = x_top_window_to_frame (dpyinfo, event->xmap.window);
6212 if (f)
6214 bool iconified = FRAME_ICONIFIED_P (f);
6215 /* wait_reading_process_output will notice this and update
6216 the frame's display structures.
6217 If we where iconified, we should not set garbaged,
6218 because that stops redrawing on Expose events. This looks
6219 bad if we are called from a recursive event loop
6220 (x_dispatch_event), for example when a dialog is up. */
6221 if (!iconified)
6222 SET_FRAME_GARBAGED (f);
6224 /* Check if fullscreen was specified before we where mapped the
6225 first time, i.e. from the command line. */
6226 if (!f->output_data.x->has_been_visible)
6227 x_check_fullscreen (f);
6229 SET_FRAME_VISIBLE (f, 1);
6230 SET_FRAME_ICONIFIED (f, 0);
6231 f->output_data.x->has_been_visible = 1;
6233 if (iconified)
6235 inev.ie.kind = DEICONIFY_EVENT;
6236 XSETFRAME (inev.ie.frame_or_window, f);
6238 else if (! NILP (Vframe_list) && ! NILP (XCDR (Vframe_list)))
6239 /* Force a redisplay sooner or later to update the
6240 frame titles in case this is the second frame. */
6241 record_asynch_buffer_change ();
6243 #ifdef USE_GTK
6244 xg_frame_resized (f, -1, -1);
6245 #endif
6247 goto OTHER;
6249 case KeyPress:
6251 dpyinfo->last_user_time = event->xkey.time;
6252 ignore_next_mouse_click_timeout = 0;
6254 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
6255 /* Dispatch KeyPress events when in menu. */
6256 if (popup_activated ())
6257 goto OTHER;
6258 #endif
6260 f = any;
6262 #if ! defined (USE_GTK)
6263 /* If mouse-highlight is an integer, input clears out
6264 mouse highlighting. */
6265 if (!hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight)
6266 && (f == 0
6267 || !EQ (f->tool_bar_window, hlinfo->mouse_face_window)))
6269 clear_mouse_face (hlinfo);
6270 hlinfo->mouse_face_hidden = 1;
6272 #endif
6274 #if defined USE_MOTIF && defined USE_TOOLKIT_SCROLL_BARS
6275 if (f == 0)
6277 /* Scroll bars consume key events, but we want
6278 the keys to go to the scroll bar's frame. */
6279 Widget widget = XtWindowToWidget (dpyinfo->display,
6280 event->xkey.window);
6281 if (widget && XmIsScrollBar (widget))
6283 widget = XtParent (widget);
6284 f = x_any_window_to_frame (dpyinfo, XtWindow (widget));
6287 #endif /* USE_MOTIF and USE_TOOLKIT_SCROLL_BARS */
6289 if (f != 0)
6291 KeySym keysym, orig_keysym;
6292 /* al%imercury@uunet.uu.net says that making this 81
6293 instead of 80 fixed a bug whereby meta chars made
6294 his Emacs hang.
6296 It seems that some version of XmbLookupString has
6297 a bug of not returning XBufferOverflow in
6298 status_return even if the input is too long to
6299 fit in 81 bytes. So, we must prepare sufficient
6300 bytes for copy_buffer. 513 bytes (256 chars for
6301 two-byte character set) seems to be a fairly good
6302 approximation. -- 2000.8.10 handa@etl.go.jp */
6303 unsigned char copy_buffer[513];
6304 unsigned char *copy_bufptr = copy_buffer;
6305 int copy_bufsiz = sizeof (copy_buffer);
6306 int modifiers;
6307 Lisp_Object coding_system = Qlatin_1;
6308 Lisp_Object c;
6309 /* Event will be modified. */
6310 XKeyEvent xkey = event->xkey;
6312 #ifdef USE_GTK
6313 /* Don't pass keys to GTK. A Tab will shift focus to the
6314 tool bar in GTK 2.4. Keys will still go to menus and
6315 dialogs because in that case popup_activated is TRUE
6316 (see above). */
6317 *finish = X_EVENT_DROP;
6318 #endif
6320 xkey.state |= x_emacs_to_x_modifiers (FRAME_DISPLAY_INFO (f),
6321 extra_keyboard_modifiers);
6322 modifiers = xkey.state;
6324 /* This will have to go some day... */
6326 /* make_lispy_event turns chars into control chars.
6327 Don't do it here because XLookupString is too eager. */
6328 xkey.state &= ~ControlMask;
6329 xkey.state &= ~(dpyinfo->meta_mod_mask
6330 | dpyinfo->super_mod_mask
6331 | dpyinfo->hyper_mod_mask
6332 | dpyinfo->alt_mod_mask);
6334 /* In case Meta is ComposeCharacter,
6335 clear its status. According to Markus Ehrnsperger
6336 Markus.Ehrnsperger@lehrstuhl-bross.physik.uni-muenchen.de
6337 this enables ComposeCharacter to work whether or
6338 not it is combined with Meta. */
6339 if (modifiers & dpyinfo->meta_mod_mask)
6340 memset (&compose_status, 0, sizeof (compose_status));
6342 #ifdef HAVE_X_I18N
6343 if (FRAME_XIC (f))
6345 Status status_return;
6347 coding_system = Vlocale_coding_system;
6348 nbytes = XmbLookupString (FRAME_XIC (f),
6349 &xkey, (char *) copy_bufptr,
6350 copy_bufsiz, &keysym,
6351 &status_return);
6352 if (status_return == XBufferOverflow)
6354 copy_bufsiz = nbytes + 1;
6355 copy_bufptr = alloca (copy_bufsiz);
6356 nbytes = XmbLookupString (FRAME_XIC (f),
6357 &xkey, (char *) copy_bufptr,
6358 copy_bufsiz, &keysym,
6359 &status_return);
6361 /* Xutf8LookupString is a new but already deprecated interface. -stef */
6362 if (status_return == XLookupNone)
6363 break;
6364 else if (status_return == XLookupChars)
6366 keysym = NoSymbol;
6367 modifiers = 0;
6369 else if (status_return != XLookupKeySym
6370 && status_return != XLookupBoth)
6371 emacs_abort ();
6373 else
6374 nbytes = XLookupString (&xkey, (char *) copy_bufptr,
6375 copy_bufsiz, &keysym,
6376 &compose_status);
6377 #else
6378 nbytes = XLookupString (&xkey, (char *) copy_bufptr,
6379 copy_bufsiz, &keysym,
6380 &compose_status);
6381 #endif
6383 /* If not using XIM/XIC, and a compose sequence is in progress,
6384 we break here. Otherwise, chars_matched is always 0. */
6385 if (compose_status.chars_matched > 0 && nbytes == 0)
6386 break;
6388 memset (&compose_status, 0, sizeof (compose_status));
6389 orig_keysym = keysym;
6391 /* Common for all keysym input events. */
6392 XSETFRAME (inev.ie.frame_or_window, f);
6393 inev.ie.modifiers
6394 = x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO (f), modifiers);
6395 inev.ie.timestamp = xkey.time;
6397 /* First deal with keysyms which have defined
6398 translations to characters. */
6399 if (keysym >= 32 && keysym < 128)
6400 /* Avoid explicitly decoding each ASCII character. */
6402 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
6403 inev.ie.code = keysym;
6404 goto done_keysym;
6407 /* Keysyms directly mapped to Unicode characters. */
6408 if (keysym >= 0x01000000 && keysym <= 0x0110FFFF)
6410 if (keysym < 0x01000080)
6411 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
6412 else
6413 inev.ie.kind = MULTIBYTE_CHAR_KEYSTROKE_EVENT;
6414 inev.ie.code = keysym & 0xFFFFFF;
6415 goto done_keysym;
6418 /* Now non-ASCII. */
6419 if (HASH_TABLE_P (Vx_keysym_table)
6420 && (c = Fgethash (make_number (keysym),
6421 Vx_keysym_table,
6422 Qnil),
6423 NATNUMP (c)))
6425 inev.ie.kind = (SINGLE_BYTE_CHAR_P (XFASTINT (c))
6426 ? ASCII_KEYSTROKE_EVENT
6427 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
6428 inev.ie.code = XFASTINT (c);
6429 goto done_keysym;
6432 /* Random non-modifier sorts of keysyms. */
6433 if (((keysym >= XK_BackSpace && keysym <= XK_Escape)
6434 || keysym == XK_Delete
6435 #ifdef XK_ISO_Left_Tab
6436 || (keysym >= XK_ISO_Left_Tab
6437 && keysym <= XK_ISO_Enter)
6438 #endif
6439 || IsCursorKey (keysym) /* 0xff50 <= x < 0xff60 */
6440 || IsMiscFunctionKey (keysym) /* 0xff60 <= x < VARIES */
6441 #ifdef HPUX
6442 /* This recognizes the "extended function
6443 keys". It seems there's no cleaner way.
6444 Test IsModifierKey to avoid handling
6445 mode_switch incorrectly. */
6446 || (XK_Select <= keysym && keysym < XK_KP_Space)
6447 #endif
6448 #ifdef XK_dead_circumflex
6449 || orig_keysym == XK_dead_circumflex
6450 #endif
6451 #ifdef XK_dead_grave
6452 || orig_keysym == XK_dead_grave
6453 #endif
6454 #ifdef XK_dead_tilde
6455 || orig_keysym == XK_dead_tilde
6456 #endif
6457 #ifdef XK_dead_diaeresis
6458 || orig_keysym == XK_dead_diaeresis
6459 #endif
6460 #ifdef XK_dead_macron
6461 || orig_keysym == XK_dead_macron
6462 #endif
6463 #ifdef XK_dead_degree
6464 || orig_keysym == XK_dead_degree
6465 #endif
6466 #ifdef XK_dead_acute
6467 || orig_keysym == XK_dead_acute
6468 #endif
6469 #ifdef XK_dead_cedilla
6470 || orig_keysym == XK_dead_cedilla
6471 #endif
6472 #ifdef XK_dead_breve
6473 || orig_keysym == XK_dead_breve
6474 #endif
6475 #ifdef XK_dead_ogonek
6476 || orig_keysym == XK_dead_ogonek
6477 #endif
6478 #ifdef XK_dead_caron
6479 || orig_keysym == XK_dead_caron
6480 #endif
6481 #ifdef XK_dead_doubleacute
6482 || orig_keysym == XK_dead_doubleacute
6483 #endif
6484 #ifdef XK_dead_abovedot
6485 || orig_keysym == XK_dead_abovedot
6486 #endif
6487 || IsKeypadKey (keysym) /* 0xff80 <= x < 0xffbe */
6488 || IsFunctionKey (keysym) /* 0xffbe <= x < 0xffe1 */
6489 /* Any "vendor-specific" key is ok. */
6490 || (orig_keysym & (1 << 28))
6491 || (keysym != NoSymbol && nbytes == 0))
6492 && ! (IsModifierKey (orig_keysym)
6493 /* The symbols from XK_ISO_Lock
6494 to XK_ISO_Last_Group_Lock
6495 don't have real modifiers but
6496 should be treated similarly to
6497 Mode_switch by Emacs. */
6498 #if defined XK_ISO_Lock && defined XK_ISO_Last_Group_Lock
6499 || (XK_ISO_Lock <= orig_keysym
6500 && orig_keysym <= XK_ISO_Last_Group_Lock)
6501 #endif
6504 STORE_KEYSYM_FOR_DEBUG (keysym);
6505 /* make_lispy_event will convert this to a symbolic
6506 key. */
6507 inev.ie.kind = NON_ASCII_KEYSTROKE_EVENT;
6508 inev.ie.code = keysym;
6509 goto done_keysym;
6512 { /* Raw bytes, not keysym. */
6513 ptrdiff_t i;
6514 int nchars, len;
6516 for (i = 0, nchars = 0; i < nbytes; i++)
6518 if (ASCII_BYTE_P (copy_bufptr[i]))
6519 nchars++;
6520 STORE_KEYSYM_FOR_DEBUG (copy_bufptr[i]);
6523 if (nchars < nbytes)
6525 /* Decode the input data. */
6527 /* The input should be decoded with `coding_system'
6528 which depends on which X*LookupString function
6529 we used just above and the locale. */
6530 setup_coding_system (coding_system, &coding);
6531 coding.src_multibyte = 0;
6532 coding.dst_multibyte = 1;
6533 /* The input is converted to events, thus we can't
6534 handle composition. Anyway, there's no XIM that
6535 gives us composition information. */
6536 coding.common_flags &= ~CODING_ANNOTATION_MASK;
6538 SAFE_NALLOCA (coding.destination, MAX_MULTIBYTE_LENGTH,
6539 nbytes);
6540 coding.dst_bytes = MAX_MULTIBYTE_LENGTH * nbytes;
6541 coding.mode |= CODING_MODE_LAST_BLOCK;
6542 decode_coding_c_string (&coding, copy_bufptr, nbytes, Qnil);
6543 nbytes = coding.produced;
6544 nchars = coding.produced_char;
6545 copy_bufptr = coding.destination;
6548 /* Convert the input data to a sequence of
6549 character events. */
6550 for (i = 0; i < nbytes; i += len)
6552 int ch;
6553 if (nchars == nbytes)
6554 ch = copy_bufptr[i], len = 1;
6555 else
6556 ch = STRING_CHAR_AND_LENGTH (copy_bufptr + i, len);
6557 inev.ie.kind = (SINGLE_BYTE_CHAR_P (ch)
6558 ? ASCII_KEYSTROKE_EVENT
6559 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
6560 inev.ie.code = ch;
6561 kbd_buffer_store_event_hold (&inev.ie, hold_quit);
6564 count += nchars;
6566 inev.ie.kind = NO_EVENT; /* Already stored above. */
6568 if (keysym == NoSymbol)
6569 break;
6571 /* FIXME: check side effects and remove this. */
6572 ((XEvent *) event)->xkey = xkey;
6574 done_keysym:
6575 #ifdef HAVE_X_I18N
6576 /* Don't dispatch this event since XtDispatchEvent calls
6577 XFilterEvent, and two calls in a row may freeze the
6578 client. */
6579 break;
6580 #else
6581 goto OTHER;
6582 #endif
6584 case KeyRelease:
6585 dpyinfo->last_user_time = event->xkey.time;
6586 #ifdef HAVE_X_I18N
6587 /* Don't dispatch this event since XtDispatchEvent calls
6588 XFilterEvent, and two calls in a row may freeze the
6589 client. */
6590 break;
6591 #else
6592 goto OTHER;
6593 #endif
6595 case EnterNotify:
6596 dpyinfo->last_user_time = event->xcrossing.time;
6597 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
6599 f = any;
6601 if (f && x_mouse_click_focus_ignore_position)
6602 ignore_next_mouse_click_timeout = event->xmotion.time + 200;
6604 /* EnterNotify counts as mouse movement,
6605 so update things that depend on mouse position. */
6606 if (f && !f->output_data.x->hourglass_p)
6607 note_mouse_movement (f, &event->xmotion);
6608 #ifdef USE_GTK
6609 /* We may get an EnterNotify on the buttons in the toolbar. In that
6610 case we moved out of any highlighted area and need to note this. */
6611 if (!f && dpyinfo->last_mouse_glyph_frame)
6612 note_mouse_movement (dpyinfo->last_mouse_glyph_frame, &event->xmotion);
6613 #endif
6614 goto OTHER;
6616 case FocusIn:
6617 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
6618 goto OTHER;
6620 case LeaveNotify:
6621 dpyinfo->last_user_time = event->xcrossing.time;
6622 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
6624 f = x_top_window_to_frame (dpyinfo, event->xcrossing.window);
6625 if (f)
6627 if (f == hlinfo->mouse_face_mouse_frame)
6629 /* If we move outside the frame, then we're
6630 certainly no longer on any text in the frame. */
6631 clear_mouse_face (hlinfo);
6632 hlinfo->mouse_face_mouse_frame = 0;
6635 /* Generate a nil HELP_EVENT to cancel a help-echo.
6636 Do it only if there's something to cancel.
6637 Otherwise, the startup message is cleared when
6638 the mouse leaves the frame. */
6639 if (any_help_event_p)
6640 do_help = -1;
6642 #ifdef USE_GTK
6643 /* See comment in EnterNotify above */
6644 else if (dpyinfo->last_mouse_glyph_frame)
6645 note_mouse_movement (dpyinfo->last_mouse_glyph_frame, &event->xmotion);
6646 #endif
6647 goto OTHER;
6649 case FocusOut:
6650 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
6651 goto OTHER;
6653 case MotionNotify:
6655 dpyinfo->last_user_time = event->xmotion.time;
6656 previous_help_echo_string = help_echo_string;
6657 help_echo_string = Qnil;
6659 f = (x_mouse_grabbed (dpyinfo) ? dpyinfo->last_mouse_frame
6660 : x_window_to_frame (dpyinfo, event->xmotion.window));
6662 if (hlinfo->mouse_face_hidden)
6664 hlinfo->mouse_face_hidden = 0;
6665 clear_mouse_face (hlinfo);
6668 #ifdef USE_GTK
6669 if (f && xg_event_is_for_scrollbar (f, event))
6670 f = 0;
6671 #endif
6672 if (f)
6675 /* Generate SELECT_WINDOW_EVENTs when needed.
6676 Don't let popup menus influence things (bug#1261). */
6677 if (!NILP (Vmouse_autoselect_window) && !popup_activated ())
6679 static Lisp_Object last_mouse_window;
6680 Lisp_Object window = window_from_coordinates
6681 (f, event->xmotion.x, event->xmotion.y, 0, 0);
6683 /* Window will be selected only when it is not selected now and
6684 last mouse movement event was not in it. Minibuffer window
6685 will be selected only when it is active. */
6686 if (WINDOWP (window)
6687 && !EQ (window, last_mouse_window)
6688 && !EQ (window, selected_window)
6689 /* For click-to-focus window managers
6690 create event iff we don't leave the
6691 selected frame. */
6692 && (focus_follows_mouse
6693 || (EQ (XWINDOW (window)->frame,
6694 XWINDOW (selected_window)->frame))))
6696 inev.ie.kind = SELECT_WINDOW_EVENT;
6697 inev.ie.frame_or_window = window;
6699 /* Remember the last window where we saw the mouse. */
6700 last_mouse_window = window;
6702 if (!note_mouse_movement (f, &event->xmotion))
6703 help_echo_string = previous_help_echo_string;
6705 else
6707 #ifndef USE_TOOLKIT_SCROLL_BARS
6708 struct scroll_bar *bar
6709 = x_window_to_scroll_bar (event->xmotion.display,
6710 event->xmotion.window);
6712 if (bar)
6713 x_scroll_bar_note_movement (bar, &event->xmotion);
6714 #endif /* USE_TOOLKIT_SCROLL_BARS */
6716 /* If we move outside the frame, then we're
6717 certainly no longer on any text in the frame. */
6718 clear_mouse_face (hlinfo);
6721 /* If the contents of the global variable help_echo_string
6722 has changed, generate a HELP_EVENT. */
6723 if (!NILP (help_echo_string)
6724 || !NILP (previous_help_echo_string))
6725 do_help = 1;
6726 goto OTHER;
6729 case ConfigureNotify:
6730 f = x_top_window_to_frame (dpyinfo, event->xconfigure.window);
6731 #ifdef USE_GTK
6732 if (!f
6733 && (f = any)
6734 && event->xconfigure.window == FRAME_X_WINDOW (f))
6736 xg_frame_resized (f, event->xconfigure.width,
6737 event->xconfigure.height);
6738 f = 0;
6740 #endif
6741 if (f)
6743 #ifndef USE_X_TOOLKIT
6744 #ifndef USE_GTK
6745 int width = FRAME_PIXEL_TO_TEXT_WIDTH (f, event->xconfigure.width);
6746 int height = FRAME_PIXEL_TO_TEXT_HEIGHT (f, event->xconfigure.height);
6748 /* In the toolkit version, change_frame_size
6749 is called by the code that handles resizing
6750 of the EmacsFrame widget. */
6752 /* Even if the number of character rows and columns has
6753 not changed, the font size may have changed, so we need
6754 to check the pixel dimensions as well. */
6755 if (width != FRAME_TEXT_WIDTH (f)
6756 || height != FRAME_TEXT_HEIGHT (f)
6757 || event->xconfigure.width != FRAME_PIXEL_WIDTH (f)
6758 || event->xconfigure.height != FRAME_PIXEL_HEIGHT (f))
6760 change_frame_size (f, width, height, 0, 1, 0, 1);
6761 SET_FRAME_GARBAGED (f);
6762 cancel_mouse_face (f);
6765 FRAME_PIXEL_WIDTH (f) = event->xconfigure.width;
6766 FRAME_PIXEL_HEIGHT (f) = event->xconfigure.height;
6767 #endif /* not USE_GTK */
6768 #endif
6770 #ifdef USE_GTK
6771 /* GTK creates windows but doesn't map them.
6772 Only get real positions when mapped. */
6773 if (FRAME_GTK_OUTER_WIDGET (f)
6774 && gtk_widget_get_mapped (FRAME_GTK_OUTER_WIDGET (f)))
6775 #endif
6776 x_real_positions (f, &f->left_pos, &f->top_pos);
6778 #ifdef HAVE_X_I18N
6779 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMStatusArea))
6780 xic_set_statusarea (f);
6781 #endif
6784 goto OTHER;
6786 case ButtonRelease:
6787 case ButtonPress:
6789 /* If we decide we want to generate an event to be seen
6790 by the rest of Emacs, we put it here. */
6791 bool tool_bar_p = 0;
6793 memset (&compose_status, 0, sizeof (compose_status));
6794 dpyinfo->last_mouse_glyph_frame = NULL;
6795 dpyinfo->last_user_time = event->xbutton.time;
6797 f = (x_mouse_grabbed (dpyinfo) ? dpyinfo->last_mouse_frame
6798 : x_window_to_frame (dpyinfo, event->xbutton.window));
6800 #ifdef USE_GTK
6801 if (f && xg_event_is_for_scrollbar (f, event))
6802 f = 0;
6803 #endif
6804 if (f)
6806 #if ! defined (USE_GTK)
6807 /* Is this in the tool-bar? */
6808 if (WINDOWP (f->tool_bar_window)
6809 && WINDOW_TOTAL_LINES (XWINDOW (f->tool_bar_window)))
6811 Lisp_Object window;
6812 int x = event->xbutton.x;
6813 int y = event->xbutton.y;
6815 window = window_from_coordinates (f, x, y, 0, 1);
6816 tool_bar_p = EQ (window, f->tool_bar_window);
6818 if (tool_bar_p && event->xbutton.button < 4)
6819 handle_tool_bar_click
6820 (f, x, y, event->xbutton.type == ButtonPress,
6821 x_x_to_emacs_modifiers (dpyinfo, event->xbutton.state));
6823 #endif /* !USE_GTK */
6825 if (!tool_bar_p)
6826 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
6827 if (! popup_activated ())
6828 #endif
6830 if (ignore_next_mouse_click_timeout)
6832 if (event->type == ButtonPress
6833 && event->xbutton.time > ignore_next_mouse_click_timeout)
6835 ignore_next_mouse_click_timeout = 0;
6836 construct_mouse_click (&inev.ie, &event->xbutton, f);
6838 if (event->type == ButtonRelease)
6839 ignore_next_mouse_click_timeout = 0;
6841 else
6842 construct_mouse_click (&inev.ie, &event->xbutton, f);
6844 if (FRAME_X_EMBEDDED_P (f))
6845 xembed_send_message (f, event->xbutton.time,
6846 XEMBED_REQUEST_FOCUS, 0, 0, 0);
6848 else
6850 struct scroll_bar *bar
6851 = x_window_to_scroll_bar (event->xbutton.display,
6852 event->xbutton.window);
6854 #ifdef USE_TOOLKIT_SCROLL_BARS
6855 /* Make the "Ctrl-Mouse-2 splits window" work for toolkit
6856 scroll bars. */
6857 if (bar && event->xbutton.state & ControlMask)
6859 x_scroll_bar_handle_click (bar, event, &inev.ie);
6860 *finish = X_EVENT_DROP;
6862 #else /* not USE_TOOLKIT_SCROLL_BARS */
6863 if (bar)
6864 x_scroll_bar_handle_click (bar, event, &inev.ie);
6865 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6868 if (event->type == ButtonPress)
6870 dpyinfo->grabbed |= (1 << event->xbutton.button);
6871 dpyinfo->last_mouse_frame = f;
6873 if (!tool_bar_p)
6874 last_tool_bar_item = -1;
6876 else
6877 dpyinfo->grabbed &= ~(1 << event->xbutton.button);
6879 /* Ignore any mouse motion that happened before this event;
6880 any subsequent mouse-movement Emacs events should reflect
6881 only motion after the ButtonPress/Release. */
6882 if (f != 0)
6883 f->mouse_moved = 0;
6885 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
6886 f = x_menubar_window_to_frame (dpyinfo, event);
6887 /* For a down-event in the menu bar,
6888 don't pass it to Xt right now.
6889 Instead, save it away
6890 and we will pass it to Xt from kbd_buffer_get_event.
6891 That way, we can run some Lisp code first. */
6892 if (! popup_activated ()
6893 #ifdef USE_GTK
6894 /* Gtk+ menus only react to the first three buttons. */
6895 && event->xbutton.button < 3
6896 #endif
6897 && f && event->type == ButtonPress
6898 /* Verify the event is really within the menu bar
6899 and not just sent to it due to grabbing. */
6900 && event->xbutton.x >= 0
6901 && event->xbutton.x < FRAME_PIXEL_WIDTH (f)
6902 && event->xbutton.y >= 0
6903 && event->xbutton.y < f->output_data.x->menubar_height
6904 && event->xbutton.same_screen)
6906 if (!f->output_data.x->saved_menu_event)
6907 f->output_data.x->saved_menu_event = xmalloc (sizeof *event);
6908 *f->output_data.x->saved_menu_event = *event;
6909 inev.ie.kind = MENU_BAR_ACTIVATE_EVENT;
6910 XSETFRAME (inev.ie.frame_or_window, f);
6911 *finish = X_EVENT_DROP;
6913 else
6914 goto OTHER;
6915 #endif /* USE_X_TOOLKIT || USE_GTK */
6917 break;
6919 case CirculateNotify:
6920 goto OTHER;
6922 case CirculateRequest:
6923 goto OTHER;
6925 case VisibilityNotify:
6926 goto OTHER;
6928 case MappingNotify:
6929 /* Someone has changed the keyboard mapping - update the
6930 local cache. */
6931 switch (event->xmapping.request)
6933 case MappingModifier:
6934 x_find_modifier_meanings (dpyinfo);
6935 /* This is meant to fall through. */
6936 case MappingKeyboard:
6937 XRefreshKeyboardMapping ((XMappingEvent *) &event->xmapping);
6939 goto OTHER;
6941 case DestroyNotify:
6942 xft_settings_event (dpyinfo, event);
6943 break;
6945 default:
6946 OTHER:
6947 #ifdef USE_X_TOOLKIT
6948 block_input ();
6949 if (*finish != X_EVENT_DROP)
6950 XtDispatchEvent ((XEvent *) event);
6951 unblock_input ();
6952 #endif /* USE_X_TOOLKIT */
6953 break;
6956 done:
6957 if (inev.ie.kind != NO_EVENT)
6959 kbd_buffer_store_event_hold (&inev.ie, hold_quit);
6960 count++;
6963 if (do_help
6964 && !(hold_quit && hold_quit->kind != NO_EVENT))
6966 Lisp_Object frame;
6968 if (f)
6969 XSETFRAME (frame, f);
6970 else
6971 frame = Qnil;
6973 if (do_help > 0)
6975 any_help_event_p = 1;
6976 gen_help_event (help_echo_string, frame, help_echo_window,
6977 help_echo_object, help_echo_pos);
6979 else
6981 help_echo_string = Qnil;
6982 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
6984 count++;
6987 SAFE_FREE ();
6988 return count;
6991 #if defined USE_GTK || defined USE_X_TOOLKIT
6993 /* Handles the XEvent EVENT on display DISPLAY.
6994 This is used for event loops outside the normal event handling,
6995 i.e. looping while a popup menu or a dialog is posted.
6997 Returns the value handle_one_xevent sets in the finish argument. */
6999 x_dispatch_event (XEvent *event, Display *display)
7001 struct x_display_info *dpyinfo;
7002 int finish = X_EVENT_NORMAL;
7004 dpyinfo = x_display_info_for_display (display);
7006 if (dpyinfo)
7007 handle_one_xevent (dpyinfo, event, &finish, 0);
7009 return finish;
7011 #endif
7014 /* Read events coming from the X server.
7015 Return as soon as there are no more events to be read.
7017 Return the number of characters stored into the buffer,
7018 thus pretending to be `read' (except the characters we store
7019 in the keyboard buffer can be multibyte, so are not necessarily
7020 C chars). */
7022 static int
7023 XTread_socket (struct terminal *terminal, struct input_event *hold_quit)
7025 int count = 0;
7026 int event_found = 0;
7027 struct x_display_info *dpyinfo = terminal->display_info.x;
7029 block_input ();
7031 /* So people can tell when we have read the available input. */
7032 input_signal_count++;
7034 /* For debugging, this gives a way to fake an I/O error. */
7035 if (dpyinfo == XTread_socket_fake_io_error)
7037 XTread_socket_fake_io_error = 0;
7038 x_io_error_quitter (dpyinfo->display);
7041 #ifndef USE_GTK
7042 while (XPending (dpyinfo->display))
7044 int finish;
7045 XEvent event;
7047 XNextEvent (dpyinfo->display, &event);
7049 #ifdef HAVE_X_I18N
7050 /* Filter events for the current X input method. */
7051 if (x_filter_event (dpyinfo, &event))
7052 continue;
7053 #endif
7054 event_found = 1;
7056 count += handle_one_xevent (dpyinfo, &event, &finish, hold_quit);
7058 if (finish == X_EVENT_GOTO_OUT)
7059 break;
7062 #else /* USE_GTK */
7064 /* For GTK we must use the GTK event loop. But XEvents gets passed
7065 to our filter function above, and then to the big event switch.
7066 We use a bunch of globals to communicate with our filter function,
7067 that is kind of ugly, but it works.
7069 There is no way to do one display at the time, GTK just does events
7070 from all displays. */
7072 while (gtk_events_pending ())
7074 current_count = count;
7075 current_hold_quit = hold_quit;
7077 gtk_main_iteration ();
7079 count = current_count;
7080 current_count = -1;
7081 current_hold_quit = 0;
7083 if (current_finish == X_EVENT_GOTO_OUT)
7084 break;
7086 #endif /* USE_GTK */
7088 /* On some systems, an X bug causes Emacs to get no more events
7089 when the window is destroyed. Detect that. (1994.) */
7090 if (! event_found)
7092 /* Emacs and the X Server eats up CPU time if XNoOp is done every time.
7093 One XNOOP in 100 loops will make Emacs terminate.
7094 B. Bretthauer, 1994 */
7095 x_noop_count++;
7096 if (x_noop_count >= 100)
7098 x_noop_count=0;
7100 if (next_noop_dpyinfo == 0)
7101 next_noop_dpyinfo = x_display_list;
7103 XNoOp (next_noop_dpyinfo->display);
7105 /* Each time we get here, cycle through the displays now open. */
7106 next_noop_dpyinfo = next_noop_dpyinfo->next;
7110 /* If the focus was just given to an auto-raising frame,
7111 raise it now. FIXME: handle more than one such frame. */
7112 if (dpyinfo->x_pending_autoraise_frame)
7114 x_raise_frame (dpyinfo->x_pending_autoraise_frame);
7115 dpyinfo->x_pending_autoraise_frame = NULL;
7118 unblock_input ();
7120 return count;
7126 /***********************************************************************
7127 Text Cursor
7128 ***********************************************************************/
7130 /* Set clipping for output in glyph row ROW. W is the window in which
7131 we operate. GC is the graphics context to set clipping in.
7133 ROW may be a text row or, e.g., a mode line. Text rows must be
7134 clipped to the interior of the window dedicated to text display,
7135 mode lines must be clipped to the whole window. */
7137 static void
7138 x_clip_to_row (struct window *w, struct glyph_row *row,
7139 enum glyph_row_area area, GC gc)
7141 struct frame *f = XFRAME (WINDOW_FRAME (w));
7142 XRectangle clip_rect;
7143 int window_x, window_y, window_width;
7145 window_box (w, area, &window_x, &window_y, &window_width, 0);
7147 clip_rect.x = window_x;
7148 clip_rect.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
7149 clip_rect.y = max (clip_rect.y, window_y);
7150 clip_rect.width = window_width;
7151 clip_rect.height = row->visible_height;
7153 XSetClipRectangles (FRAME_X_DISPLAY (f), gc, 0, 0, &clip_rect, 1, Unsorted);
7157 /* Draw a hollow box cursor on window W in glyph row ROW. */
7159 static void
7160 x_draw_hollow_cursor (struct window *w, struct glyph_row *row)
7162 struct frame *f = XFRAME (WINDOW_FRAME (w));
7163 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
7164 Display *dpy = FRAME_X_DISPLAY (f);
7165 int x, y, wd, h;
7166 XGCValues xgcv;
7167 struct glyph *cursor_glyph;
7168 GC gc;
7170 /* Get the glyph the cursor is on. If we can't tell because
7171 the current matrix is invalid or such, give up. */
7172 cursor_glyph = get_phys_cursor_glyph (w);
7173 if (cursor_glyph == NULL)
7174 return;
7176 /* Compute frame-relative coordinates for phys cursor. */
7177 get_phys_cursor_geometry (w, row, cursor_glyph, &x, &y, &h);
7178 wd = w->phys_cursor_width;
7180 /* The foreground of cursor_gc is typically the same as the normal
7181 background color, which can cause the cursor box to be invisible. */
7182 xgcv.foreground = f->output_data.x->cursor_pixel;
7183 if (dpyinfo->scratch_cursor_gc)
7184 XChangeGC (dpy, dpyinfo->scratch_cursor_gc, GCForeground, &xgcv);
7185 else
7186 dpyinfo->scratch_cursor_gc = XCreateGC (dpy, FRAME_X_WINDOW (f),
7187 GCForeground, &xgcv);
7188 gc = dpyinfo->scratch_cursor_gc;
7190 /* Set clipping, draw the rectangle, and reset clipping again. */
7191 x_clip_to_row (w, row, TEXT_AREA, gc);
7192 XDrawRectangle (dpy, FRAME_X_WINDOW (f), gc, x, y, wd, h - 1);
7193 XSetClipMask (dpy, gc, None);
7197 /* Draw a bar cursor on window W in glyph row ROW.
7199 Implementation note: One would like to draw a bar cursor with an
7200 angle equal to the one given by the font property XA_ITALIC_ANGLE.
7201 Unfortunately, I didn't find a font yet that has this property set.
7202 --gerd. */
7204 static void
7205 x_draw_bar_cursor (struct window *w, struct glyph_row *row, int width, enum text_cursor_kinds kind)
7207 struct frame *f = XFRAME (w->frame);
7208 struct glyph *cursor_glyph;
7210 /* If cursor is out of bounds, don't draw garbage. This can happen
7211 in mini-buffer windows when switching between echo area glyphs
7212 and mini-buffer. */
7213 cursor_glyph = get_phys_cursor_glyph (w);
7214 if (cursor_glyph == NULL)
7215 return;
7217 /* If on an image, draw like a normal cursor. That's usually better
7218 visible than drawing a bar, esp. if the image is large so that
7219 the bar might not be in the window. */
7220 if (cursor_glyph->type == IMAGE_GLYPH)
7222 struct glyph_row *r;
7223 r = MATRIX_ROW (w->current_matrix, w->phys_cursor.vpos);
7224 draw_phys_cursor_glyph (w, r, DRAW_CURSOR);
7226 else
7228 Display *dpy = FRAME_X_DISPLAY (f);
7229 Window window = FRAME_X_WINDOW (f);
7230 GC gc = FRAME_DISPLAY_INFO (f)->scratch_cursor_gc;
7231 unsigned long mask = GCForeground | GCBackground | GCGraphicsExposures;
7232 struct face *face = FACE_FROM_ID (f, cursor_glyph->face_id);
7233 XGCValues xgcv;
7235 /* If the glyph's background equals the color we normally draw
7236 the bars cursor in, the bar cursor in its normal color is
7237 invisible. Use the glyph's foreground color instead in this
7238 case, on the assumption that the glyph's colors are chosen so
7239 that the glyph is legible. */
7240 if (face->background == f->output_data.x->cursor_pixel)
7241 xgcv.background = xgcv.foreground = face->foreground;
7242 else
7243 xgcv.background = xgcv.foreground = f->output_data.x->cursor_pixel;
7244 xgcv.graphics_exposures = 0;
7246 if (gc)
7247 XChangeGC (dpy, gc, mask, &xgcv);
7248 else
7250 gc = XCreateGC (dpy, window, mask, &xgcv);
7251 FRAME_DISPLAY_INFO (f)->scratch_cursor_gc = gc;
7254 x_clip_to_row (w, row, TEXT_AREA, gc);
7256 if (kind == BAR_CURSOR)
7258 int x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
7260 if (width < 0)
7261 width = FRAME_CURSOR_WIDTH (f);
7262 width = min (cursor_glyph->pixel_width, width);
7264 w->phys_cursor_width = width;
7266 /* If the character under cursor is R2L, draw the bar cursor
7267 on the right of its glyph, rather than on the left. */
7268 if ((cursor_glyph->resolved_level & 1) != 0)
7269 x += cursor_glyph->pixel_width - width;
7271 XFillRectangle (dpy, window, gc, x,
7272 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y),
7273 width, row->height);
7275 else
7277 int dummy_x, dummy_y, dummy_h;
7279 if (width < 0)
7280 width = row->height;
7282 width = min (row->height, width);
7284 get_phys_cursor_geometry (w, row, cursor_glyph, &dummy_x,
7285 &dummy_y, &dummy_h);
7287 XFillRectangle (dpy, window, gc,
7288 WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x),
7289 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y +
7290 row->height - width),
7291 w->phys_cursor_width, width);
7294 XSetClipMask (dpy, gc, None);
7299 /* RIF: Define cursor CURSOR on frame F. */
7301 static void
7302 x_define_frame_cursor (struct frame *f, Cursor cursor)
7304 if (!f->pointer_invisible
7305 && f->output_data.x->current_cursor != cursor)
7306 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), cursor);
7307 f->output_data.x->current_cursor = cursor;
7311 /* RIF: Clear area on frame F. */
7313 static void
7314 x_clear_frame_area (struct frame *f, int x, int y, int width, int height)
7316 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), x, y, width, height);
7317 #ifdef USE_GTK
7318 /* Must queue a redraw, because scroll bars might have been cleared. */
7319 if (FRAME_GTK_WIDGET (f))
7320 gtk_widget_queue_draw (FRAME_GTK_WIDGET (f));
7321 #endif
7325 /* RIF: Draw cursor on window W. */
7327 static void
7328 x_draw_window_cursor (struct window *w, struct glyph_row *glyph_row, int x,
7329 int y, enum text_cursor_kinds cursor_type,
7330 int cursor_width, bool on_p, bool active_p)
7332 struct frame *f = XFRAME (WINDOW_FRAME (w));
7334 if (on_p)
7336 w->phys_cursor_type = cursor_type;
7337 w->phys_cursor_on_p = 1;
7339 if (glyph_row->exact_window_width_line_p
7340 && (glyph_row->reversed_p
7341 ? (w->phys_cursor.hpos < 0)
7342 : (w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])))
7344 glyph_row->cursor_in_fringe_p = 1;
7345 draw_fringe_bitmap (w, glyph_row, glyph_row->reversed_p);
7347 else
7349 switch (cursor_type)
7351 case HOLLOW_BOX_CURSOR:
7352 x_draw_hollow_cursor (w, glyph_row);
7353 break;
7355 case FILLED_BOX_CURSOR:
7356 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
7357 break;
7359 case BAR_CURSOR:
7360 x_draw_bar_cursor (w, glyph_row, cursor_width, BAR_CURSOR);
7361 break;
7363 case HBAR_CURSOR:
7364 x_draw_bar_cursor (w, glyph_row, cursor_width, HBAR_CURSOR);
7365 break;
7367 case NO_CURSOR:
7368 w->phys_cursor_width = 0;
7369 break;
7371 default:
7372 emacs_abort ();
7376 #ifdef HAVE_X_I18N
7377 if (w == XWINDOW (f->selected_window))
7378 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMPreeditPosition))
7379 xic_set_preeditarea (w, x, y);
7380 #endif
7383 XFlush (FRAME_X_DISPLAY (f));
7387 /* Icons. */
7389 /* Make the x-window of frame F use the gnu icon bitmap. */
7392 x_bitmap_icon (struct frame *f, Lisp_Object file)
7394 ptrdiff_t bitmap_id;
7396 if (FRAME_X_WINDOW (f) == 0)
7397 return 1;
7399 /* Free up our existing icon bitmap and mask if any. */
7400 if (f->output_data.x->icon_bitmap > 0)
7401 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
7402 f->output_data.x->icon_bitmap = 0;
7404 if (STRINGP (file))
7406 #ifdef USE_GTK
7407 /* Use gtk_window_set_icon_from_file () if available,
7408 It's not restricted to bitmaps */
7409 if (xg_set_icon (f, file))
7410 return 0;
7411 #endif /* USE_GTK */
7412 bitmap_id = x_create_bitmap_from_file (f, file);
7413 x_create_bitmap_mask (f, bitmap_id);
7415 else
7417 /* Create the GNU bitmap and mask if necessary. */
7418 if (FRAME_DISPLAY_INFO (f)->icon_bitmap_id < 0)
7420 ptrdiff_t rc = -1;
7422 #ifdef USE_GTK
7424 if (xg_set_icon (f, xg_default_icon_file)
7425 || xg_set_icon_from_xpm_data (f, gnu_xpm_bits))
7426 return 0;
7428 #elif defined (HAVE_XPM) && defined (HAVE_X_WINDOWS)
7430 rc = x_create_bitmap_from_xpm_data (f, gnu_xpm_bits);
7431 if (rc != -1)
7432 FRAME_DISPLAY_INFO (f)->icon_bitmap_id = rc;
7434 #endif
7436 /* If all else fails, use the (black and white) xbm image. */
7437 if (rc == -1)
7439 rc = x_create_bitmap_from_data (f, (char *) gnu_xbm_bits,
7440 gnu_xbm_width, gnu_xbm_height);
7441 if (rc == -1)
7442 return 1;
7444 FRAME_DISPLAY_INFO (f)->icon_bitmap_id = rc;
7445 x_create_bitmap_mask (f, FRAME_DISPLAY_INFO (f)->icon_bitmap_id);
7449 /* The first time we create the GNU bitmap and mask,
7450 this increments the ref-count one extra time.
7451 As a result, the GNU bitmap and mask are never freed.
7452 That way, we don't have to worry about allocating it again. */
7453 x_reference_bitmap (f, FRAME_DISPLAY_INFO (f)->icon_bitmap_id);
7455 bitmap_id = FRAME_DISPLAY_INFO (f)->icon_bitmap_id;
7458 x_wm_set_icon_pixmap (f, bitmap_id);
7459 f->output_data.x->icon_bitmap = bitmap_id;
7461 return 0;
7465 /* Make the x-window of frame F use a rectangle with text.
7466 Use ICON_NAME as the text. */
7469 x_text_icon (struct frame *f, const char *icon_name)
7471 if (FRAME_X_WINDOW (f) == 0)
7472 return 1;
7475 XTextProperty text;
7476 text.value = (unsigned char *) icon_name;
7477 text.encoding = XA_STRING;
7478 text.format = 8;
7479 text.nitems = strlen (icon_name);
7480 XSetWMIconName (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f), &text);
7483 if (f->output_data.x->icon_bitmap > 0)
7484 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
7485 f->output_data.x->icon_bitmap = 0;
7486 x_wm_set_icon_pixmap (f, 0);
7488 return 0;
7491 #define X_ERROR_MESSAGE_SIZE 200
7493 /* If non-nil, this should be a string.
7494 It means catch X errors and store the error message in this string.
7496 The reason we use a stack is that x_catch_error/x_uncatch_error can
7497 be called from a signal handler.
7500 struct x_error_message_stack {
7501 char string[X_ERROR_MESSAGE_SIZE];
7502 Display *dpy;
7503 struct x_error_message_stack *prev;
7505 static struct x_error_message_stack *x_error_message;
7507 /* An X error handler which stores the error message in
7508 *x_error_message. This is called from x_error_handler if
7509 x_catch_errors is in effect. */
7511 static void
7512 x_error_catcher (Display *display, XErrorEvent *event)
7514 XGetErrorText (display, event->error_code,
7515 x_error_message->string,
7516 X_ERROR_MESSAGE_SIZE);
7519 /* Begin trapping X errors for display DPY. Actually we trap X errors
7520 for all displays, but DPY should be the display you are actually
7521 operating on.
7523 After calling this function, X protocol errors no longer cause
7524 Emacs to exit; instead, they are recorded in the string
7525 stored in *x_error_message.
7527 Calling x_check_errors signals an Emacs error if an X error has
7528 occurred since the last call to x_catch_errors or x_check_errors.
7530 Calling x_uncatch_errors resumes the normal error handling. */
7532 void
7533 x_catch_errors (Display *dpy)
7535 struct x_error_message_stack *data = xmalloc (sizeof *data);
7537 /* Make sure any errors from previous requests have been dealt with. */
7538 XSync (dpy, False);
7540 data->dpy = dpy;
7541 data->string[0] = 0;
7542 data->prev = x_error_message;
7543 x_error_message = data;
7546 /* Undo the last x_catch_errors call.
7547 DPY should be the display that was passed to x_catch_errors. */
7549 void
7550 x_uncatch_errors (void)
7552 struct x_error_message_stack *tmp;
7554 block_input ();
7556 /* The display may have been closed before this function is called.
7557 Check if it is still open before calling XSync. */
7558 if (x_display_info_for_display (x_error_message->dpy) != 0)
7559 XSync (x_error_message->dpy, False);
7561 tmp = x_error_message;
7562 x_error_message = x_error_message->prev;
7563 xfree (tmp);
7564 unblock_input ();
7567 /* If any X protocol errors have arrived since the last call to
7568 x_catch_errors or x_check_errors, signal an Emacs error using
7569 sprintf (a buffer, FORMAT, the x error message text) as the text. */
7571 void
7572 x_check_errors (Display *dpy, const char *format)
7574 /* Make sure to catch any errors incurred so far. */
7575 XSync (dpy, False);
7577 if (x_error_message->string[0])
7579 char string[X_ERROR_MESSAGE_SIZE];
7580 memcpy (string, x_error_message->string, X_ERROR_MESSAGE_SIZE);
7581 x_uncatch_errors ();
7582 error (format, string);
7586 /* Nonzero if we had any X protocol errors
7587 since we did x_catch_errors on DPY. */
7589 bool
7590 x_had_errors_p (Display *dpy)
7592 /* Make sure to catch any errors incurred so far. */
7593 XSync (dpy, False);
7595 return x_error_message->string[0] != 0;
7598 /* Forget about any errors we have had, since we did x_catch_errors on DPY. */
7600 void
7601 x_clear_errors (Display *dpy)
7603 x_error_message->string[0] = 0;
7606 #if 0 /* See comment in unwind_to_catch why calling this is a bad
7607 * idea. --lorentey */
7608 /* Close off all unclosed x_catch_errors calls. */
7610 void
7611 x_fully_uncatch_errors (void)
7613 while (x_error_message)
7614 x_uncatch_errors ();
7616 #endif
7618 #if 0
7619 static unsigned int x_wire_count;
7620 x_trace_wire (void)
7622 fprintf (stderr, "Lib call: %d\n", ++x_wire_count);
7624 #endif /* ! 0 */
7627 /************************************************************************
7628 Handling X errors
7629 ************************************************************************/
7631 /* Error message passed to x_connection_closed. */
7633 static char *error_msg;
7635 /* Handle the loss of connection to display DPY. ERROR_MESSAGE is
7636 the text of an error message that lead to the connection loss. */
7638 static void
7639 x_connection_closed (Display *dpy, const char *error_message)
7641 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
7642 Lisp_Object frame, tail;
7643 ptrdiff_t idx = SPECPDL_INDEX ();
7645 error_msg = alloca (strlen (error_message) + 1);
7646 strcpy (error_msg, error_message);
7648 /* Inhibit redisplay while frames are being deleted. */
7649 specbind (Qinhibit_redisplay, Qt);
7651 if (dpyinfo)
7653 /* Protect display from being closed when we delete the last
7654 frame on it. */
7655 dpyinfo->reference_count++;
7656 dpyinfo->terminal->reference_count++;
7659 /* First delete frames whose mini-buffers are on frames
7660 that are on the dead display. */
7661 FOR_EACH_FRAME (tail, frame)
7663 Lisp_Object minibuf_frame;
7664 minibuf_frame
7665 = WINDOW_FRAME (XWINDOW (FRAME_MINIBUF_WINDOW (XFRAME (frame))));
7666 if (FRAME_X_P (XFRAME (frame))
7667 && FRAME_X_P (XFRAME (minibuf_frame))
7668 && ! EQ (frame, minibuf_frame)
7669 && FRAME_DISPLAY_INFO (XFRAME (minibuf_frame)) == dpyinfo)
7670 delete_frame (frame, Qnoelisp);
7673 /* Now delete all remaining frames on the dead display.
7674 We are now sure none of these is used as the mini-buffer
7675 for another frame that we need to delete. */
7676 FOR_EACH_FRAME (tail, frame)
7677 if (FRAME_X_P (XFRAME (frame))
7678 && FRAME_DISPLAY_INFO (XFRAME (frame)) == dpyinfo)
7680 /* Set this to t so that delete_frame won't get confused
7681 trying to find a replacement. */
7682 kset_default_minibuffer_frame (FRAME_KBOARD (XFRAME (frame)), Qt);
7683 delete_frame (frame, Qnoelisp);
7686 /* If DPYINFO is null, this means we didn't open the display in the
7687 first place, so don't try to close it. */
7688 if (dpyinfo)
7690 /* We can not call XtCloseDisplay here because it calls XSync.
7691 XSync inside the error handler apparently hangs Emacs. On
7692 current Xt versions, this isn't needed either. */
7693 #ifdef USE_GTK
7694 /* A long-standing GTK bug prevents proper disconnect handling
7695 (https://bugzilla.gnome.org/show_bug.cgi?id=85715). Once,
7696 the resulting Glib error message loop filled a user's disk.
7697 To avoid this, kill Emacs unconditionally on disconnect. */
7698 shut_down_emacs (0, Qnil);
7699 fprintf (stderr, "%s\n\
7700 When compiled with GTK, Emacs cannot recover from X disconnects.\n\
7701 This is a GTK bug: https://bugzilla.gnome.org/show_bug.cgi?id=85715\n\
7702 For details, see etc/PROBLEMS.\n",
7703 error_msg);
7704 emacs_abort ();
7705 #endif /* USE_GTK */
7707 /* Indicate that this display is dead. */
7708 dpyinfo->display = 0;
7710 dpyinfo->reference_count--;
7711 dpyinfo->terminal->reference_count--;
7712 if (dpyinfo->reference_count != 0)
7713 /* We have just closed all frames on this display. */
7714 emacs_abort ();
7717 Lisp_Object tmp;
7718 XSETTERMINAL (tmp, dpyinfo->terminal);
7719 Fdelete_terminal (tmp, Qnoelisp);
7723 if (terminal_list == 0)
7725 fprintf (stderr, "%s\n", error_msg);
7726 Fkill_emacs (make_number (70));
7727 /* NOTREACHED */
7730 totally_unblock_input ();
7732 unbind_to (idx, Qnil);
7733 clear_waiting_for_input ();
7735 /* Tell GCC not to suggest attribute 'noreturn' for this function. */
7736 IF_LINT (if (! terminal_list) return; )
7738 /* Here, we absolutely have to use a non-local exit (e.g. signal, throw,
7739 longjmp), because returning from this function would get us back into
7740 Xlib's code which will directly call `exit'. */
7741 error ("%s", error_msg);
7744 /* We specifically use it before defining it, so that gcc doesn't inline it,
7745 otherwise gdb doesn't know how to properly put a breakpoint on it. */
7746 static void x_error_quitter (Display *, XErrorEvent *);
7748 /* This is the first-level handler for X protocol errors.
7749 It calls x_error_quitter or x_error_catcher. */
7751 static int
7752 x_error_handler (Display *display, XErrorEvent *event)
7754 #if defined USE_GTK && defined HAVE_GTK3
7755 if ((event->error_code == BadMatch || event->error_code == BadWindow)
7756 && event->request_code == X_SetInputFocus)
7758 return 0;
7760 #endif
7762 if (x_error_message)
7763 x_error_catcher (display, event);
7764 else
7765 x_error_quitter (display, event);
7766 return 0;
7769 /* This is the usual handler for X protocol errors.
7770 It kills all frames on the display that we got the error for.
7771 If that was the only one, it prints an error message and kills Emacs. */
7773 /* .gdbinit puts a breakpoint here, so make sure it is not inlined. */
7775 /* On older GCC versions, just putting x_error_quitter
7776 after x_error_handler prevents inlining into the former. */
7778 static void NO_INLINE
7779 x_error_quitter (Display *display, XErrorEvent *event)
7781 char buf[256], buf1[356];
7783 /* Ignore BadName errors. They can happen because of fonts
7784 or colors that are not defined. */
7786 if (event->error_code == BadName)
7787 return;
7789 /* Note that there is no real way portable across R3/R4 to get the
7790 original error handler. */
7792 XGetErrorText (display, event->error_code, buf, sizeof (buf));
7793 sprintf (buf1, "X protocol error: %s on protocol request %d",
7794 buf, event->request_code);
7795 x_connection_closed (display, buf1);
7799 /* This is the handler for X IO errors, always.
7800 It kills all frames on the display that we lost touch with.
7801 If that was the only one, it prints an error message and kills Emacs. */
7803 static int
7804 x_io_error_quitter (Display *display)
7806 char buf[256];
7808 snprintf (buf, sizeof buf, "Connection lost to X server `%s'",
7809 DisplayString (display));
7810 x_connection_closed (display, buf);
7811 return 0;
7814 /* Changing the font of the frame. */
7816 /* Give frame F the font FONT-OBJECT as its default font. The return
7817 value is FONT-OBJECT. FONTSET is an ID of the fontset for the
7818 frame. If it is negative, generate a new fontset from
7819 FONT-OBJECT. */
7821 Lisp_Object
7822 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
7824 struct font *font = XFONT_OBJECT (font_object);
7826 if (fontset < 0)
7827 fontset = fontset_from_font (font_object);
7828 FRAME_FONTSET (f) = fontset;
7829 if (FRAME_FONT (f) == font)
7830 /* This font is already set in frame F. There's nothing more to
7831 do. */
7832 return font_object;
7834 FRAME_FONT (f) = font;
7835 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
7836 FRAME_COLUMN_WIDTH (f) = font->average_width;
7837 FRAME_LINE_HEIGHT (f) = FONT_HEIGHT (font);
7839 compute_fringe_widths (f, 1);
7841 /* Compute the scroll bar width in character columns. */
7842 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
7844 int wid = FRAME_COLUMN_WIDTH (f);
7846 FRAME_CONFIG_SCROLL_BAR_COLS (f)
7847 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid-1) / wid;
7849 else
7851 int wid = FRAME_COLUMN_WIDTH (f);
7853 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = 14;
7854 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
7857 if (FRAME_X_WINDOW (f) != 0)
7859 /* Don't change the size of a tip frame; there's no point in
7860 doing it because it's done in Fx_show_tip, and it leads to
7861 problems because the tip frame has no widget. */
7862 if (NILP (tip_frame) || XFRAME (tip_frame) != f)
7863 x_set_window_size (f, 0, FRAME_TEXT_WIDTH (f), FRAME_TEXT_HEIGHT (f), 1);
7866 #ifdef HAVE_X_I18N
7867 if (FRAME_XIC (f)
7868 && (FRAME_XIC_STYLE (f) & (XIMPreeditPosition | XIMStatusArea)))
7870 block_input ();
7871 xic_set_xfontset (f, SSDATA (fontset_ascii (fontset)));
7872 unblock_input ();
7874 #endif
7876 return font_object;
7880 /***********************************************************************
7881 X Input Methods
7882 ***********************************************************************/
7884 #ifdef HAVE_X_I18N
7886 #ifdef HAVE_X11R6
7888 /* XIM destroy callback function, which is called whenever the
7889 connection to input method XIM dies. CLIENT_DATA contains a
7890 pointer to the x_display_info structure corresponding to XIM. */
7892 static void
7893 xim_destroy_callback (XIM xim, XPointer client_data, XPointer call_data)
7895 struct x_display_info *dpyinfo = (struct x_display_info *) client_data;
7896 Lisp_Object frame, tail;
7898 block_input ();
7900 /* No need to call XDestroyIC.. */
7901 FOR_EACH_FRAME (tail, frame)
7903 struct frame *f = XFRAME (frame);
7904 if (FRAME_X_P (f) && FRAME_DISPLAY_INFO (f) == dpyinfo)
7906 FRAME_XIC (f) = NULL;
7907 xic_free_xfontset (f);
7911 /* No need to call XCloseIM. */
7912 dpyinfo->xim = NULL;
7913 XFree (dpyinfo->xim_styles);
7914 unblock_input ();
7917 #endif /* HAVE_X11R6 */
7919 #ifdef HAVE_X11R6
7920 /* This isn't prototyped in OSF 5.0 or 5.1a. */
7921 extern char *XSetIMValues (XIM, ...);
7922 #endif
7924 /* Open the connection to the XIM server on display DPYINFO.
7925 RESOURCE_NAME is the resource name Emacs uses. */
7927 static void
7928 xim_open_dpy (struct x_display_info *dpyinfo, char *resource_name)
7930 XIM xim;
7932 #ifdef HAVE_XIM
7933 if (use_xim)
7935 if (dpyinfo->xim)
7936 XCloseIM (dpyinfo->xim);
7937 xim = XOpenIM (dpyinfo->display, dpyinfo->xrdb, resource_name,
7938 emacs_class);
7939 dpyinfo->xim = xim;
7941 if (xim)
7943 #ifdef HAVE_X11R6
7944 XIMCallback destroy;
7945 #endif
7947 /* Get supported styles and XIM values. */
7948 XGetIMValues (xim, XNQueryInputStyle, &dpyinfo->xim_styles, NULL);
7950 #ifdef HAVE_X11R6
7951 destroy.callback = xim_destroy_callback;
7952 destroy.client_data = (XPointer)dpyinfo;
7953 XSetIMValues (xim, XNDestroyCallback, &destroy, NULL);
7954 #endif
7958 else
7959 #endif /* HAVE_XIM */
7960 dpyinfo->xim = NULL;
7964 #ifdef HAVE_X11R6_XIM
7966 /* XIM instantiate callback function, which is called whenever an XIM
7967 server is available. DISPLAY is the display of the XIM.
7968 CLIENT_DATA contains a pointer to an xim_inst_t structure created
7969 when the callback was registered. */
7971 static void
7972 xim_instantiate_callback (Display *display, XPointer client_data, XPointer call_data)
7974 struct xim_inst_t *xim_inst = (struct xim_inst_t *) client_data;
7975 struct x_display_info *dpyinfo = xim_inst->dpyinfo;
7977 /* We don't support multiple XIM connections. */
7978 if (dpyinfo->xim)
7979 return;
7981 xim_open_dpy (dpyinfo, xim_inst->resource_name);
7983 /* Create XIC for the existing frames on the same display, as long
7984 as they have no XIC. */
7985 if (dpyinfo->xim && dpyinfo->reference_count > 0)
7987 Lisp_Object tail, frame;
7989 block_input ();
7990 FOR_EACH_FRAME (tail, frame)
7992 struct frame *f = XFRAME (frame);
7994 if (FRAME_X_P (f)
7995 && FRAME_DISPLAY_INFO (f) == xim_inst->dpyinfo)
7996 if (FRAME_XIC (f) == NULL)
7998 create_frame_xic (f);
7999 if (FRAME_XIC_STYLE (f) & XIMStatusArea)
8000 xic_set_statusarea (f);
8001 if (FRAME_XIC_STYLE (f) & XIMPreeditPosition)
8003 struct window *w = XWINDOW (f->selected_window);
8004 xic_set_preeditarea (w, w->cursor.x, w->cursor.y);
8009 unblock_input ();
8013 #endif /* HAVE_X11R6_XIM */
8016 /* Open a connection to the XIM server on display DPYINFO.
8017 RESOURCE_NAME is the resource name for Emacs. On X11R5, open the
8018 connection only at the first time. On X11R6, open the connection
8019 in the XIM instantiate callback function. */
8021 static void
8022 xim_initialize (struct x_display_info *dpyinfo, char *resource_name)
8024 dpyinfo->xim = NULL;
8025 #ifdef HAVE_XIM
8026 if (use_xim)
8028 #ifdef HAVE_X11R6_XIM
8029 struct xim_inst_t *xim_inst = xmalloc (sizeof *xim_inst);
8031 dpyinfo->xim_callback_data = xim_inst;
8032 xim_inst->dpyinfo = dpyinfo;
8033 xim_inst->resource_name = xstrdup (resource_name);
8034 XRegisterIMInstantiateCallback (dpyinfo->display, dpyinfo->xrdb,
8035 resource_name, emacs_class,
8036 xim_instantiate_callback,
8037 /* This is XPointer in XFree86
8038 but (XPointer *) on Tru64, at
8039 least, hence the configure test. */
8040 (XRegisterIMInstantiateCallback_arg6) xim_inst);
8041 #else /* not HAVE_X11R6_XIM */
8042 xim_open_dpy (dpyinfo, resource_name);
8043 #endif /* not HAVE_X11R6_XIM */
8045 #endif /* HAVE_XIM */
8049 /* Close the connection to the XIM server on display DPYINFO. */
8051 static void
8052 xim_close_dpy (struct x_display_info *dpyinfo)
8054 #ifdef HAVE_XIM
8055 if (use_xim)
8057 #ifdef HAVE_X11R6_XIM
8058 if (dpyinfo->display)
8059 XUnregisterIMInstantiateCallback (dpyinfo->display, dpyinfo->xrdb,
8060 NULL, emacs_class,
8061 xim_instantiate_callback, NULL);
8062 xfree (dpyinfo->xim_callback_data->resource_name);
8063 xfree (dpyinfo->xim_callback_data);
8064 #endif /* HAVE_X11R6_XIM */
8065 if (dpyinfo->display)
8066 XCloseIM (dpyinfo->xim);
8067 dpyinfo->xim = NULL;
8068 XFree (dpyinfo->xim_styles);
8070 #endif /* HAVE_XIM */
8073 #endif /* not HAVE_X11R6_XIM */
8077 /* Calculate the absolute position in frame F
8078 from its current recorded position values and gravity. */
8080 static void
8081 x_calc_absolute_position (struct frame *f)
8083 int flags = f->size_hint_flags;
8085 /* We have nothing to do if the current position
8086 is already for the top-left corner. */
8087 if (! ((flags & XNegative) || (flags & YNegative)))
8088 return;
8090 /* Treat negative positions as relative to the leftmost bottommost
8091 position that fits on the screen. */
8092 if (flags & XNegative)
8093 f->left_pos = x_display_pixel_width (FRAME_DISPLAY_INFO (f))
8094 - FRAME_PIXEL_WIDTH (f) + f->left_pos;
8097 int height = FRAME_PIXEL_HEIGHT (f);
8099 #if defined USE_X_TOOLKIT && defined USE_MOTIF
8100 /* Something is fishy here. When using Motif, starting Emacs with
8101 `-g -0-0', the frame appears too low by a few pixels.
8103 This seems to be so because initially, while Emacs is starting,
8104 the column widget's height and the frame's pixel height are
8105 different. The column widget's height is the right one. In
8106 later invocations, when Emacs is up, the frame's pixel height
8107 is right, though.
8109 It's not obvious where the initial small difference comes from.
8110 2000-12-01, gerd. */
8112 XtVaGetValues (f->output_data.x->column_widget, XtNheight, &height, NULL);
8113 #endif
8115 if (flags & YNegative)
8116 f->top_pos = x_display_pixel_height (FRAME_DISPLAY_INFO (f))
8117 - height + f->top_pos;
8120 /* The left_pos and top_pos
8121 are now relative to the top and left screen edges,
8122 so the flags should correspond. */
8123 f->size_hint_flags &= ~ (XNegative | YNegative);
8126 /* CHANGE_GRAVITY is 1 when calling from Fset_frame_position,
8127 to really change the position, and 0 when calling from
8128 x_make_frame_visible (in that case, XOFF and YOFF are the current
8129 position values). It is -1 when calling from x_set_frame_parameters,
8130 which means, do adjust for borders but don't change the gravity. */
8132 void
8133 x_set_offset (struct frame *f, register int xoff, register int yoff, int change_gravity)
8135 int modified_top, modified_left;
8137 if (change_gravity > 0)
8139 f->top_pos = yoff;
8140 f->left_pos = xoff;
8141 f->size_hint_flags &= ~ (XNegative | YNegative);
8142 if (xoff < 0)
8143 f->size_hint_flags |= XNegative;
8144 if (yoff < 0)
8145 f->size_hint_flags |= YNegative;
8146 f->win_gravity = NorthWestGravity;
8148 x_calc_absolute_position (f);
8150 block_input ();
8151 x_wm_set_size_hint (f, (long) 0, 0);
8153 modified_left = f->left_pos;
8154 modified_top = f->top_pos;
8156 if (change_gravity != 0 && FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A)
8158 /* Some WMs (twm, wmaker at least) has an offset that is smaller
8159 than the WM decorations. So we use the calculated offset instead
8160 of the WM decoration sizes here (x/y_pixels_outer_diff). */
8161 modified_left += FRAME_X_OUTPUT (f)->move_offset_left;
8162 modified_top += FRAME_X_OUTPUT (f)->move_offset_top;
8165 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8166 modified_left, modified_top);
8168 x_sync_with_move (f, f->left_pos, f->top_pos,
8169 FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN
8170 ? 1 : 0);
8172 /* change_gravity is non-zero when this function is called from Lisp to
8173 programmatically move a frame. In that case, we call
8174 x_check_expected_move to discover if we have a "Type A" or "Type B"
8175 window manager, and, for a "Type A" window manager, adjust the position
8176 of the frame.
8178 We call x_check_expected_move if a programmatic move occurred, and
8179 either the window manager type (A/B) is unknown or it is Type A but we
8180 need to compute the top/left offset adjustment for this frame. */
8182 if (change_gravity != 0 &&
8183 (FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN
8184 || (FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A
8185 && (FRAME_X_OUTPUT (f)->move_offset_left == 0
8186 && FRAME_X_OUTPUT (f)->move_offset_top == 0))))
8187 x_check_expected_move (f, modified_left, modified_top);
8189 unblock_input ();
8192 /* Return non-zero if _NET_SUPPORTING_WM_CHECK window exists and _NET_SUPPORTED
8193 on the root window for frame F contains ATOMNAME.
8194 This is how a WM check shall be done according to the Window Manager
8195 Specification/Extended Window Manager Hints at
8196 http://freedesktop.org/wiki/Specifications/wm-spec. */
8198 static int
8199 wm_supports (struct frame *f, Atom want_atom)
8201 Atom actual_type;
8202 unsigned long actual_size, bytes_remaining;
8203 int i, rc, actual_format;
8204 Window wmcheck_window;
8205 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
8206 Window target_window = dpyinfo->root_window;
8207 long max_len = 65536;
8208 Display *dpy = FRAME_X_DISPLAY (f);
8209 unsigned char *tmp_data = NULL;
8210 Atom target_type = XA_WINDOW;
8212 block_input ();
8214 x_catch_errors (dpy);
8215 rc = XGetWindowProperty (dpy, target_window,
8216 dpyinfo->Xatom_net_supporting_wm_check,
8217 0, max_len, False, target_type,
8218 &actual_type, &actual_format, &actual_size,
8219 &bytes_remaining, &tmp_data);
8221 if (rc != Success || actual_type != XA_WINDOW || x_had_errors_p (dpy))
8223 if (tmp_data) XFree (tmp_data);
8224 x_uncatch_errors ();
8225 unblock_input ();
8226 return 0;
8229 wmcheck_window = *(Window *) tmp_data;
8230 XFree (tmp_data);
8232 /* Check if window exists. */
8233 XSelectInput (dpy, wmcheck_window, StructureNotifyMask);
8234 x_sync (f);
8235 if (x_had_errors_p (dpy))
8237 x_uncatch_errors ();
8238 unblock_input ();
8239 return 0;
8242 if (dpyinfo->net_supported_window != wmcheck_window)
8244 /* Window changed, reload atoms */
8245 if (dpyinfo->net_supported_atoms != NULL)
8246 XFree (dpyinfo->net_supported_atoms);
8247 dpyinfo->net_supported_atoms = NULL;
8248 dpyinfo->nr_net_supported_atoms = 0;
8249 dpyinfo->net_supported_window = 0;
8251 target_type = XA_ATOM;
8252 tmp_data = NULL;
8253 rc = XGetWindowProperty (dpy, target_window,
8254 dpyinfo->Xatom_net_supported,
8255 0, max_len, False, target_type,
8256 &actual_type, &actual_format, &actual_size,
8257 &bytes_remaining, &tmp_data);
8259 if (rc != Success || actual_type != XA_ATOM || x_had_errors_p (dpy))
8261 if (tmp_data) XFree (tmp_data);
8262 x_uncatch_errors ();
8263 unblock_input ();
8264 return 0;
8267 dpyinfo->net_supported_atoms = (Atom *)tmp_data;
8268 dpyinfo->nr_net_supported_atoms = actual_size;
8269 dpyinfo->net_supported_window = wmcheck_window;
8272 rc = 0;
8274 for (i = 0; rc == 0 && i < dpyinfo->nr_net_supported_atoms; ++i)
8275 rc = dpyinfo->net_supported_atoms[i] == want_atom;
8277 x_uncatch_errors ();
8278 unblock_input ();
8280 return rc;
8283 static void
8284 set_wm_state (Lisp_Object frame, int add, Atom atom, Atom value)
8286 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (XFRAME (frame));
8288 x_send_client_event (frame, make_number (0), frame,
8289 dpyinfo->Xatom_net_wm_state,
8290 make_number (32),
8291 /* 1 = add, 0 = remove */
8292 Fcons
8293 (make_number (add ? 1 : 0),
8294 Fcons
8295 (make_fixnum_or_float (atom),
8296 (value != 0
8297 ? list1 (make_fixnum_or_float (value))
8298 : Qnil))));
8301 void
8302 x_set_sticky (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
8304 Lisp_Object frame;
8305 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
8307 XSETFRAME (frame, f);
8309 set_wm_state (frame, NILP (new_value) ? 0 : 1,
8310 dpyinfo->Xatom_net_wm_state_sticky, None);
8313 /* Return the current _NET_WM_STATE.
8314 SIZE_STATE is set to one of the FULLSCREEN_* values.
8315 STICKY is set to 1 if the sticky state is set, 0 if not.
8317 Return non-zero if we are not hidden, zero if we are. */
8319 static int
8320 get_current_wm_state (struct frame *f,
8321 Window window,
8322 int *size_state,
8323 int *sticky)
8325 Atom actual_type;
8326 unsigned long actual_size, bytes_remaining;
8327 int i, rc, actual_format, is_hidden = 0;
8328 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
8329 long max_len = 65536;
8330 Display *dpy = FRAME_X_DISPLAY (f);
8331 unsigned char *tmp_data = NULL;
8332 Atom target_type = XA_ATOM;
8334 *sticky = 0;
8335 *size_state = FULLSCREEN_NONE;
8337 block_input ();
8338 x_catch_errors (dpy);
8339 rc = XGetWindowProperty (dpy, window, dpyinfo->Xatom_net_wm_state,
8340 0, max_len, False, target_type,
8341 &actual_type, &actual_format, &actual_size,
8342 &bytes_remaining, &tmp_data);
8344 if (rc != Success || actual_type != target_type || x_had_errors_p (dpy))
8346 if (tmp_data) XFree (tmp_data);
8347 x_uncatch_errors ();
8348 unblock_input ();
8349 return !FRAME_ICONIFIED_P (f);
8352 x_uncatch_errors ();
8354 for (i = 0; i < actual_size; ++i)
8356 Atom a = ((Atom*)tmp_data)[i];
8357 if (a == dpyinfo->Xatom_net_wm_state_hidden)
8359 is_hidden = 1;
8360 f->output_data.x->net_wm_state_hidden_seen = 1;
8362 else if (a == dpyinfo->Xatom_net_wm_state_maximized_horz)
8364 if (*size_state == FULLSCREEN_HEIGHT)
8365 *size_state = FULLSCREEN_MAXIMIZED;
8366 else
8367 *size_state = FULLSCREEN_WIDTH;
8369 else if (a == dpyinfo->Xatom_net_wm_state_maximized_vert)
8371 if (*size_state == FULLSCREEN_WIDTH)
8372 *size_state = FULLSCREEN_MAXIMIZED;
8373 else
8374 *size_state = FULLSCREEN_HEIGHT;
8376 else if (a == dpyinfo->Xatom_net_wm_state_fullscreen)
8377 *size_state = FULLSCREEN_BOTH;
8378 else if (a == dpyinfo->Xatom_net_wm_state_sticky)
8379 *sticky = 1;
8382 if (tmp_data) XFree (tmp_data);
8383 unblock_input ();
8384 return ! is_hidden;
8387 /* Do fullscreen as specified in extended window manager hints */
8389 static int
8390 do_ewmh_fullscreen (struct frame *f)
8392 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
8393 int have_net_atom = wm_supports (f, dpyinfo->Xatom_net_wm_state);
8394 int cur, dummy;
8396 (void)get_current_wm_state (f, FRAME_OUTER_WINDOW (f), &cur, &dummy);
8398 /* Some window managers don't say they support _NET_WM_STATE, but they do say
8399 they support _NET_WM_STATE_FULLSCREEN. Try that also. */
8400 if (!have_net_atom)
8401 have_net_atom = wm_supports (f, dpyinfo->Xatom_net_wm_state_fullscreen);
8403 if (have_net_atom && cur != f->want_fullscreen)
8405 Lisp_Object frame;
8407 XSETFRAME (frame, f);
8409 /* Keep number of calls to set_wm_state as low as possible.
8410 Some window managers, or possible Gtk+, hangs when too many
8411 are sent at once. */
8412 switch (f->want_fullscreen)
8414 case FULLSCREEN_BOTH:
8415 if (cur == FULLSCREEN_WIDTH || cur == FULLSCREEN_MAXIMIZED
8416 || cur == FULLSCREEN_HEIGHT)
8417 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_maximized_horz,
8418 dpyinfo->Xatom_net_wm_state_maximized_vert);
8419 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_fullscreen, None);
8420 break;
8421 case FULLSCREEN_WIDTH:
8422 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_HEIGHT
8423 || cur == FULLSCREEN_MAXIMIZED)
8424 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen,
8425 dpyinfo->Xatom_net_wm_state_maximized_vert);
8426 if (cur != FULLSCREEN_MAXIMIZED)
8427 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_maximized_horz, None);
8428 break;
8429 case FULLSCREEN_HEIGHT:
8430 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_WIDTH
8431 || cur == FULLSCREEN_MAXIMIZED)
8432 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen,
8433 dpyinfo->Xatom_net_wm_state_maximized_horz);
8434 if (cur != FULLSCREEN_MAXIMIZED)
8435 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_maximized_vert, None);
8436 break;
8437 case FULLSCREEN_MAXIMIZED:
8438 if (cur == FULLSCREEN_BOTH)
8439 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen, None);
8440 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_maximized_horz,
8441 dpyinfo->Xatom_net_wm_state_maximized_vert);
8442 break;
8443 case FULLSCREEN_NONE:
8444 if (cur == FULLSCREEN_BOTH)
8445 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen, None);
8446 else
8447 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_maximized_horz,
8448 dpyinfo->Xatom_net_wm_state_maximized_vert);
8451 f->want_fullscreen = FULLSCREEN_NONE;
8455 return have_net_atom;
8458 static void
8459 XTfullscreen_hook (struct frame *f)
8461 if (FRAME_VISIBLE_P (f))
8463 block_input ();
8464 x_check_fullscreen (f);
8465 x_sync (f);
8466 unblock_input ();
8471 static int
8472 x_handle_net_wm_state (struct frame *f, const XPropertyEvent *event)
8474 int value = FULLSCREEN_NONE;
8475 Lisp_Object lval;
8476 int sticky = 0;
8477 int not_hidden = get_current_wm_state (f, event->window, &value, &sticky);
8479 lval = Qnil;
8480 switch (value)
8482 case FULLSCREEN_WIDTH:
8483 lval = Qfullwidth;
8484 break;
8485 case FULLSCREEN_HEIGHT:
8486 lval = Qfullheight;
8487 break;
8488 case FULLSCREEN_BOTH:
8489 lval = Qfullboth;
8490 break;
8491 case FULLSCREEN_MAXIMIZED:
8492 lval = Qmaximized;
8493 break;
8496 store_frame_param (f, Qfullscreen, lval);
8497 store_frame_param (f, Qsticky, sticky ? Qt : Qnil);
8499 return not_hidden;
8502 /* Check if we need to resize the frame due to a fullscreen request.
8503 If so needed, resize the frame. */
8504 static void
8505 x_check_fullscreen (struct frame *f)
8507 if (do_ewmh_fullscreen (f))
8508 return;
8510 if (f->output_data.x->parent_desc != FRAME_DISPLAY_INFO (f)->root_window)
8511 return; /* Only fullscreen without WM or with EWM hints (above). */
8513 /* Setting fullscreen to nil doesn't do anything. We could save the
8514 last non-fullscreen size and restore it, but it seems like a
8515 lot of work for this unusual case (no window manager running). */
8517 if (f->want_fullscreen != FULLSCREEN_NONE)
8519 int width = FRAME_PIXEL_WIDTH (f), height = FRAME_PIXEL_HEIGHT (f);
8520 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
8522 switch (f->want_fullscreen)
8524 /* No difference between these two when there is no WM */
8525 case FULLSCREEN_BOTH:
8526 case FULLSCREEN_MAXIMIZED:
8527 width = x_display_pixel_width (dpyinfo);
8528 height = x_display_pixel_height (dpyinfo);
8529 break;
8530 case FULLSCREEN_WIDTH:
8531 width = x_display_pixel_width (dpyinfo);
8532 break;
8533 case FULLSCREEN_HEIGHT:
8534 height = x_display_pixel_height (dpyinfo);
8537 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8538 width, height);
8542 /* This function is called by x_set_offset to determine whether the window
8543 manager interfered with the positioning of the frame. Type A window
8544 managers position the surrounding window manager decorations a small
8545 amount above and left of the user-supplied position. Type B window
8546 managers position the surrounding window manager decorations at the
8547 user-specified position. If we detect a Type A window manager, we
8548 compensate by moving the window right and down by the proper amount. */
8550 static void
8551 x_check_expected_move (struct frame *f, int expected_left, int expected_top)
8553 int current_left = 0, current_top = 0;
8555 /* x_real_positions returns the left and top offsets of the outermost
8556 window manager window around the frame. */
8558 x_real_positions (f, &current_left, &current_top);
8560 if (current_left != expected_left || current_top != expected_top)
8562 /* It's a "Type A" window manager. */
8564 int adjusted_left;
8565 int adjusted_top;
8567 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_A;
8568 FRAME_X_OUTPUT (f)->move_offset_left = expected_left - current_left;
8569 FRAME_X_OUTPUT (f)->move_offset_top = expected_top - current_top;
8571 /* Now fix the mispositioned frame's location. */
8573 adjusted_left = expected_left + FRAME_X_OUTPUT (f)->move_offset_left;
8574 adjusted_top = expected_top + FRAME_X_OUTPUT (f)->move_offset_top;
8576 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8577 adjusted_left, adjusted_top);
8579 x_sync_with_move (f, expected_left, expected_top, 0);
8581 else
8582 /* It's a "Type B" window manager. We don't have to adjust the
8583 frame's position. */
8585 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_B;
8589 /* Wait for XGetGeometry to return up-to-date position information for a
8590 recently-moved frame. Call this immediately after calling XMoveWindow.
8591 If FUZZY is non-zero, then LEFT and TOP are just estimates of where the
8592 frame has been moved to, so we use a fuzzy position comparison instead
8593 of an exact comparison. */
8595 static void
8596 x_sync_with_move (struct frame *f, int left, int top, int fuzzy)
8598 int count = 0;
8600 while (count++ < 50)
8602 int current_left = 0, current_top = 0;
8604 /* In theory, this call to XSync only needs to happen once, but in
8605 practice, it doesn't seem to work, hence the need for the surrounding
8606 loop. */
8608 XSync (FRAME_X_DISPLAY (f), False);
8609 x_real_positions (f, &current_left, &current_top);
8611 if (fuzzy)
8613 /* The left fuzz-factor is 10 pixels. The top fuzz-factor is 40
8614 pixels. */
8616 if (eabs (current_left - left) <= 10
8617 && eabs (current_top - top) <= 40)
8618 return;
8620 else if (current_left == left && current_top == top)
8621 return;
8624 /* As a last resort, just wait 0.5 seconds and hope that XGetGeometry
8625 will then return up-to-date position info. */
8627 wait_reading_process_output (0, 500000, 0, 0, Qnil, NULL, 0);
8631 /* Wait for an event on frame F matching EVENTTYPE. */
8632 void
8633 x_wait_for_event (struct frame *f, int eventtype)
8635 int level = interrupt_input_blocked;
8637 fd_set fds;
8638 struct timespec tmo, tmo_at, time_now;
8639 int fd = ConnectionNumber (FRAME_X_DISPLAY (f));
8641 f->wait_event_type = eventtype;
8643 /* Set timeout to 0.1 second. Hopefully not noticeable.
8644 Maybe it should be configurable. */
8645 tmo = make_timespec (0, 100 * 1000 * 1000);
8646 tmo_at = timespec_add (current_timespec (), tmo);
8648 while (f->wait_event_type)
8650 pending_signals = 1;
8651 totally_unblock_input ();
8652 /* XTread_socket is called after unblock. */
8653 block_input ();
8654 interrupt_input_blocked = level;
8656 FD_ZERO (&fds);
8657 FD_SET (fd, &fds);
8659 time_now = current_timespec ();
8660 if (timespec_cmp (tmo_at, time_now) < 0)
8661 break;
8663 tmo = timespec_sub (tmo_at, time_now);
8664 if (pselect (fd + 1, &fds, NULL, NULL, &tmo, NULL) == 0)
8665 break; /* Timeout */
8668 f->wait_event_type = 0;
8672 /* Change the size of frame F's X window to COLS/ROWS in the case F
8673 doesn't have a widget. If CHANGE_GRAVITY is 1, we change to
8674 top-left-corner window gravity for this size change and subsequent
8675 size changes. Otherwise we leave the window gravity unchanged. */
8677 static void
8678 x_set_window_size_1 (struct frame *f, int change_gravity, int width, int height, bool pixelwise)
8680 int pixelwidth, pixelheight;
8682 check_frame_size (f, &width, &height, pixelwise);
8683 f->scroll_bar_actual_width
8684 = (!FRAME_HAS_VERTICAL_SCROLL_BARS (f)
8686 : FRAME_CONFIG_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f));
8688 compute_fringe_widths (f, 0);
8690 pixelwidth =
8691 (pixelwise ? width : FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, width))
8692 + FRAME_TOOLBAR_WIDTH (f);
8693 pixelheight =
8694 (pixelwise ? height : FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, height))
8695 + FRAME_MENUBAR_HEIGHT (f) + FRAME_TOOLBAR_HEIGHT (f);
8697 if (change_gravity) f->win_gravity = NorthWestGravity;
8698 x_wm_set_size_hint (f, (long) 0, 0);
8699 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8700 pixelwidth, pixelheight);
8703 /* We've set {FRAME,PIXEL}_{WIDTH,HEIGHT} to the values we hope to
8704 receive in the ConfigureNotify event; if we get what we asked
8705 for, then the event won't cause the screen to become garbaged, so
8706 we have to make sure to do it here. */
8707 SET_FRAME_GARBAGED (f);
8709 /* Now, strictly speaking, we can't be sure that this is accurate,
8710 but the window manager will get around to dealing with the size
8711 change request eventually, and we'll hear how it went when the
8712 ConfigureNotify event gets here.
8714 We could just not bother storing any of this information here,
8715 and let the ConfigureNotify event set everything up, but that
8716 might be kind of confusing to the Lisp code, since size changes
8717 wouldn't be reported in the frame parameters until some random
8718 point in the future when the ConfigureNotify event arrives.
8720 We pass 1 for DELAY since we can't run Lisp code inside of
8721 a BLOCK_INPUT. */
8723 /* But the ConfigureNotify may in fact never arrive, and then this is
8724 not right if the frame is visible. Instead wait (with timeout)
8725 for the ConfigureNotify. */
8726 if (FRAME_VISIBLE_P (f))
8727 x_wait_for_event (f, ConfigureNotify);
8728 else
8730 change_frame_size (f, width, height, 0, 1, 0, 1);
8731 FRAME_PIXEL_WIDTH (f) = pixelwidth;
8732 FRAME_PIXEL_HEIGHT (f) = pixelheight;
8733 x_sync (f);
8738 /* Call this to change the size of frame F's x-window.
8739 If CHANGE_GRAVITY is 1, we change to top-left-corner window gravity
8740 for this size change and subsequent size changes.
8741 Otherwise we leave the window gravity unchanged. */
8743 void
8744 x_set_window_size (struct frame *f, int change_gravity, int width, int height, bool pixelwise)
8746 block_input ();
8748 if (NILP (tip_frame) || XFRAME (tip_frame) != f)
8750 int r, c, text_width, text_height;
8752 /* When the frame is maximized/fullscreen or running under for
8753 example Xmonad, x_set_window_size_1 will be a no-op.
8754 In that case, the right thing to do is extend rows/width to
8755 the current frame size. We do that first if x_set_window_size_1
8756 turns out to not be a no-op (there is no way to know).
8757 The size will be adjusted again if the frame gets a
8758 ConfigureNotify event as a result of x_set_window_size. */
8759 int pixelh = FRAME_PIXEL_HEIGHT (f);
8760 #ifdef USE_X_TOOLKIT
8761 /* The menu bar is not part of text lines. The tool bar
8762 is however. */
8763 pixelh -= FRAME_MENUBAR_HEIGHT (f);
8764 #endif
8765 text_width = FRAME_PIXEL_TO_TEXT_WIDTH (f, FRAME_PIXEL_WIDTH (f));
8766 text_height = FRAME_PIXEL_TO_TEXT_HEIGHT (f, pixelh);
8767 r = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, pixelh);
8768 /* Update f->scroll_bar_actual_width because it is used in
8769 FRAME_PIXEL_WIDTH_TO_TEXT_COLS. */
8770 f->scroll_bar_actual_width
8771 = FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f);
8772 c = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, FRAME_PIXEL_WIDTH (f));
8773 change_frame_size (f, text_width, text_height, 0, 1, 0, 1);
8776 #ifdef USE_GTK
8777 if (FRAME_GTK_WIDGET (f))
8778 xg_frame_set_char_size (f, width, height);
8779 else
8780 x_set_window_size_1 (f, change_gravity, width, height, pixelwise);
8781 #else /* not USE_GTK */
8783 x_set_window_size_1 (f, change_gravity, width, height, pixelwise);
8785 #endif /* not USE_GTK */
8787 /* If cursor was outside the new size, mark it as off. */
8788 mark_window_cursors_off (XWINDOW (f->root_window));
8790 /* Clear out any recollection of where the mouse highlighting was,
8791 since it might be in a place that's outside the new frame size.
8792 Actually checking whether it is outside is a pain in the neck,
8793 so don't try--just let the highlighting be done afresh with new size. */
8794 cancel_mouse_face (f);
8796 unblock_input ();
8799 /* Mouse warping. */
8801 void
8802 x_set_mouse_position (struct frame *f, int x, int y)
8804 int pix_x, pix_y;
8806 pix_x = FRAME_COL_TO_PIXEL_X (f, x) + FRAME_COLUMN_WIDTH (f) / 2;
8807 pix_y = FRAME_LINE_TO_PIXEL_Y (f, y) + FRAME_LINE_HEIGHT (f) / 2;
8809 if (pix_x < 0) pix_x = 0;
8810 if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
8812 if (pix_y < 0) pix_y = 0;
8813 if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
8815 block_input ();
8817 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
8818 0, 0, 0, 0, pix_x, pix_y);
8819 unblock_input ();
8822 /* Move the mouse to position pixel PIX_X, PIX_Y relative to frame F. */
8824 void
8825 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
8827 block_input ();
8829 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
8830 0, 0, 0, 0, pix_x, pix_y);
8831 unblock_input ();
8834 /* Raise frame F. */
8836 void
8837 x_raise_frame (struct frame *f)
8839 block_input ();
8840 if (FRAME_VISIBLE_P (f))
8841 XRaiseWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
8842 XFlush (FRAME_X_DISPLAY (f));
8843 unblock_input ();
8846 /* Lower frame F. */
8848 static void
8849 x_lower_frame (struct frame *f)
8851 if (FRAME_VISIBLE_P (f))
8853 block_input ();
8854 XLowerWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
8855 XFlush (FRAME_X_DISPLAY (f));
8856 unblock_input ();
8860 /* Request focus with XEmbed */
8862 void
8863 xembed_request_focus (struct frame *f)
8865 /* See XEmbed Protocol Specification at
8866 http://freedesktop.org/wiki/Specifications/xembed-spec */
8867 if (FRAME_VISIBLE_P (f))
8868 xembed_send_message (f, CurrentTime,
8869 XEMBED_REQUEST_FOCUS, 0, 0, 0);
8872 /* Activate frame with Extended Window Manager Hints */
8874 void
8875 x_ewmh_activate_frame (struct frame *f)
8877 /* See Window Manager Specification/Extended Window Manager Hints at
8878 http://freedesktop.org/wiki/Specifications/wm-spec */
8880 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
8882 if (FRAME_VISIBLE_P (f) && wm_supports (f, dpyinfo->Xatom_net_active_window))
8884 Lisp_Object frame;
8885 XSETFRAME (frame, f);
8886 x_send_client_event (frame, make_number (0), frame,
8887 dpyinfo->Xatom_net_active_window,
8888 make_number (32),
8889 list2i (1, dpyinfo->last_user_time));
8893 static void
8894 XTframe_raise_lower (struct frame *f, int raise_flag)
8896 if (raise_flag)
8897 x_raise_frame (f);
8898 else
8899 x_lower_frame (f);
8902 /* XEmbed implementation. */
8904 #if defined USE_X_TOOLKIT || ! defined USE_GTK
8906 /* XEmbed implementation. */
8908 #define XEMBED_VERSION 0
8910 static void
8911 xembed_set_info (struct frame *f, enum xembed_info flags)
8913 unsigned long data[2];
8914 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
8916 data[0] = XEMBED_VERSION;
8917 data[1] = flags;
8919 XChangeProperty (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8920 dpyinfo->Xatom_XEMBED_INFO, dpyinfo->Xatom_XEMBED_INFO,
8921 32, PropModeReplace, (unsigned char *) data, 2);
8923 #endif /* defined USE_X_TOOLKIT || ! defined USE_GTK */
8925 static void
8926 xembed_send_message (struct frame *f, Time t, enum xembed_message msg,
8927 long int detail, long int data1, long int data2)
8929 XEvent event;
8931 event.xclient.type = ClientMessage;
8932 event.xclient.window = FRAME_X_OUTPUT (f)->parent_desc;
8933 event.xclient.message_type = FRAME_DISPLAY_INFO (f)->Xatom_XEMBED;
8934 event.xclient.format = 32;
8935 event.xclient.data.l[0] = t;
8936 event.xclient.data.l[1] = msg;
8937 event.xclient.data.l[2] = detail;
8938 event.xclient.data.l[3] = data1;
8939 event.xclient.data.l[4] = data2;
8941 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_OUTPUT (f)->parent_desc,
8942 False, NoEventMask, &event);
8943 XSync (FRAME_X_DISPLAY (f), False);
8946 /* Change of visibility. */
8948 /* This tries to wait until the frame is really visible.
8949 However, if the window manager asks the user where to position
8950 the frame, this will return before the user finishes doing that.
8951 The frame will not actually be visible at that time,
8952 but it will become visible later when the window manager
8953 finishes with it. */
8955 void
8956 x_make_frame_visible (struct frame *f)
8958 int original_top, original_left;
8959 int retry_count = 2;
8961 retry:
8963 block_input ();
8965 x_set_bitmap_icon (f);
8967 if (! FRAME_VISIBLE_P (f))
8969 /* We test FRAME_GARBAGED_P here to make sure we don't
8970 call x_set_offset a second time
8971 if we get to x_make_frame_visible a second time
8972 before the window gets really visible. */
8973 if (! FRAME_ICONIFIED_P (f)
8974 && ! FRAME_X_EMBEDDED_P (f)
8975 && ! f->output_data.x->asked_for_visible)
8976 x_set_offset (f, f->left_pos, f->top_pos, 0);
8978 f->output_data.x->asked_for_visible = 1;
8980 if (! EQ (Vx_no_window_manager, Qt))
8981 x_wm_set_window_state (f, NormalState);
8982 #ifdef USE_X_TOOLKIT
8983 if (FRAME_X_EMBEDDED_P (f))
8984 xembed_set_info (f, XEMBED_MAPPED);
8985 else
8987 /* This was XtPopup, but that did nothing for an iconified frame. */
8988 XtMapWidget (f->output_data.x->widget);
8990 #else /* not USE_X_TOOLKIT */
8991 #ifdef USE_GTK
8992 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
8993 gtk_window_deiconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
8994 #else
8995 if (FRAME_X_EMBEDDED_P (f))
8996 xembed_set_info (f, XEMBED_MAPPED);
8997 else
8998 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
8999 #endif /* not USE_GTK */
9000 #endif /* not USE_X_TOOLKIT */
9003 XFlush (FRAME_X_DISPLAY (f));
9005 /* Synchronize to ensure Emacs knows the frame is visible
9006 before we do anything else. We do this loop with input not blocked
9007 so that incoming events are handled. */
9009 Lisp_Object frame;
9010 int count;
9011 /* This must be before UNBLOCK_INPUT
9012 since events that arrive in response to the actions above
9013 will set it when they are handled. */
9014 int previously_visible = f->output_data.x->has_been_visible;
9016 original_left = f->left_pos;
9017 original_top = f->top_pos;
9019 /* This must come after we set COUNT. */
9020 unblock_input ();
9022 /* We unblock here so that arriving X events are processed. */
9024 /* Now move the window back to where it was "supposed to be".
9025 But don't do it if the gravity is negative.
9026 When the gravity is negative, this uses a position
9027 that is 3 pixels too low. Perhaps that's really the border width.
9029 Don't do this if the window has never been visible before,
9030 because the window manager may choose the position
9031 and we don't want to override it. */
9033 if (! FRAME_VISIBLE_P (f)
9034 && ! FRAME_ICONIFIED_P (f)
9035 && ! FRAME_X_EMBEDDED_P (f)
9036 && f->win_gravity == NorthWestGravity
9037 && previously_visible)
9039 Drawable rootw;
9040 int x, y;
9041 unsigned int width, height, border, depth;
9043 block_input ();
9045 /* On some window managers (such as FVWM) moving an existing
9046 window, even to the same place, causes the window manager
9047 to introduce an offset. This can cause the window to move
9048 to an unexpected location. Check the geometry (a little
9049 slow here) and then verify that the window is in the right
9050 place. If the window is not in the right place, move it
9051 there, and take the potential window manager hit. */
9052 XGetGeometry (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
9053 &rootw, &x, &y, &width, &height, &border, &depth);
9055 if (original_left != x || original_top != y)
9056 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
9057 original_left, original_top);
9059 unblock_input ();
9062 XSETFRAME (frame, f);
9064 /* Wait until the frame is visible. Process X events until a
9065 MapNotify event has been seen, or until we think we won't get a
9066 MapNotify at all.. */
9067 for (count = input_signal_count + 10;
9068 input_signal_count < count && !FRAME_VISIBLE_P (f);)
9070 /* Force processing of queued events. */
9071 x_sync (f);
9073 /* Machines that do polling rather than SIGIO have been
9074 observed to go into a busy-wait here. So we'll fake an
9075 alarm signal to let the handler know that there's something
9076 to be read. We used to raise a real alarm, but it seems
9077 that the handler isn't always enabled here. This is
9078 probably a bug. */
9079 if (input_polling_used ())
9081 /* It could be confusing if a real alarm arrives while
9082 processing the fake one. Turn it off and let the
9083 handler reset it. */
9084 int old_poll_suppress_count = poll_suppress_count;
9085 poll_suppress_count = 1;
9086 poll_for_input_1 ();
9087 poll_suppress_count = old_poll_suppress_count;
9091 /* 2000-09-28: In
9093 (let ((f (selected-frame)))
9094 (iconify-frame f)
9095 (raise-frame f))
9097 the frame is not raised with various window managers on
9098 FreeBSD, GNU/Linux and Solaris. It turns out that, for some
9099 unknown reason, the call to XtMapWidget is completely ignored.
9100 Mapping the widget a second time works. */
9102 if (!FRAME_VISIBLE_P (f) && --retry_count != 0)
9103 goto retry;
9107 /* Change from mapped state to withdrawn state. */
9109 /* Make the frame visible (mapped and not iconified). */
9111 void
9112 x_make_frame_invisible (struct frame *f)
9114 Window window;
9116 /* Use the frame's outermost window, not the one we normally draw on. */
9117 window = FRAME_OUTER_WINDOW (f);
9119 /* Don't keep the highlight on an invisible frame. */
9120 if (FRAME_DISPLAY_INFO (f)->x_highlight_frame == f)
9121 FRAME_DISPLAY_INFO (f)->x_highlight_frame = 0;
9123 block_input ();
9125 /* Before unmapping the window, update the WM_SIZE_HINTS property to claim
9126 that the current position of the window is user-specified, rather than
9127 program-specified, so that when the window is mapped again, it will be
9128 placed at the same location, without forcing the user to position it
9129 by hand again (they have already done that once for this window.) */
9130 x_wm_set_size_hint (f, (long) 0, 1);
9132 #ifdef USE_GTK
9133 if (FRAME_GTK_OUTER_WIDGET (f))
9134 gtk_widget_hide (FRAME_GTK_OUTER_WIDGET (f));
9135 else
9136 #else
9137 if (FRAME_X_EMBEDDED_P (f))
9138 xembed_set_info (f, 0);
9139 else
9140 #endif
9143 if (! XWithdrawWindow (FRAME_X_DISPLAY (f), window,
9144 DefaultScreen (FRAME_X_DISPLAY (f))))
9146 unblock_input ();
9147 error ("Can't notify window manager of window withdrawal");
9151 /* We can't distinguish this from iconification
9152 just by the event that we get from the server.
9153 So we can't win using the usual strategy of letting
9154 FRAME_SAMPLE_VISIBILITY set this. So do it by hand,
9155 and synchronize with the server to make sure we agree. */
9156 SET_FRAME_VISIBLE (f, 0);
9157 SET_FRAME_ICONIFIED (f, 0);
9159 x_sync (f);
9161 unblock_input ();
9164 /* Change window state from mapped to iconified. */
9166 void
9167 x_iconify_frame (struct frame *f)
9169 #ifdef USE_X_TOOLKIT
9170 int result;
9171 #endif
9173 /* Don't keep the highlight on an invisible frame. */
9174 if (FRAME_DISPLAY_INFO (f)->x_highlight_frame == f)
9175 FRAME_DISPLAY_INFO (f)->x_highlight_frame = 0;
9177 if (FRAME_ICONIFIED_P (f))
9178 return;
9180 block_input ();
9182 x_set_bitmap_icon (f);
9184 #if defined (USE_GTK)
9185 if (FRAME_GTK_OUTER_WIDGET (f))
9187 if (! FRAME_VISIBLE_P (f))
9188 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
9190 gtk_window_iconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
9191 SET_FRAME_VISIBLE (f, 0);
9192 SET_FRAME_ICONIFIED (f, 1);
9193 unblock_input ();
9194 return;
9196 #endif
9198 #ifdef USE_X_TOOLKIT
9200 if (! FRAME_VISIBLE_P (f))
9202 if (! EQ (Vx_no_window_manager, Qt))
9203 x_wm_set_window_state (f, IconicState);
9204 /* This was XtPopup, but that did nothing for an iconified frame. */
9205 XtMapWidget (f->output_data.x->widget);
9206 /* The server won't give us any event to indicate
9207 that an invisible frame was changed to an icon,
9208 so we have to record it here. */
9209 SET_FRAME_VISIBLE (f, 0);
9210 SET_FRAME_ICONIFIED (f, 1);
9211 unblock_input ();
9212 return;
9215 result = XIconifyWindow (FRAME_X_DISPLAY (f),
9216 XtWindow (f->output_data.x->widget),
9217 DefaultScreen (FRAME_X_DISPLAY (f)));
9218 unblock_input ();
9220 if (!result)
9221 error ("Can't notify window manager of iconification");
9223 SET_FRAME_ICONIFIED (f, 1);
9224 SET_FRAME_VISIBLE (f, 0);
9226 block_input ();
9227 XFlush (FRAME_X_DISPLAY (f));
9228 unblock_input ();
9229 #else /* not USE_X_TOOLKIT */
9231 /* Make sure the X server knows where the window should be positioned,
9232 in case the user deiconifies with the window manager. */
9233 if (! FRAME_VISIBLE_P (f)
9234 && ! FRAME_ICONIFIED_P (f)
9235 && ! FRAME_X_EMBEDDED_P (f))
9236 x_set_offset (f, f->left_pos, f->top_pos, 0);
9238 /* Since we don't know which revision of X we're running, we'll use both
9239 the X11R3 and X11R4 techniques. I don't know if this is a good idea. */
9241 /* X11R4: send a ClientMessage to the window manager using the
9242 WM_CHANGE_STATE type. */
9244 XEvent msg;
9246 msg.xclient.window = FRAME_X_WINDOW (f);
9247 msg.xclient.type = ClientMessage;
9248 msg.xclient.message_type = FRAME_DISPLAY_INFO (f)->Xatom_wm_change_state;
9249 msg.xclient.format = 32;
9250 msg.xclient.data.l[0] = IconicState;
9252 if (! XSendEvent (FRAME_X_DISPLAY (f),
9253 DefaultRootWindow (FRAME_X_DISPLAY (f)),
9254 False,
9255 SubstructureRedirectMask | SubstructureNotifyMask,
9256 &msg))
9258 unblock_input ();
9259 error ("Can't notify window manager of iconification");
9263 /* X11R3: set the initial_state field of the window manager hints to
9264 IconicState. */
9265 x_wm_set_window_state (f, IconicState);
9267 if (!FRAME_VISIBLE_P (f))
9269 /* If the frame was withdrawn, before, we must map it. */
9270 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9273 SET_FRAME_ICONIFIED (f, 1);
9274 SET_FRAME_VISIBLE (f, 0);
9276 XFlush (FRAME_X_DISPLAY (f));
9277 unblock_input ();
9278 #endif /* not USE_X_TOOLKIT */
9282 /* Free X resources of frame F. */
9284 void
9285 x_free_frame_resources (struct frame *f)
9287 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
9288 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
9289 #ifdef USE_X_TOOLKIT
9290 Lisp_Object bar;
9291 struct scroll_bar *b;
9292 #endif
9294 block_input ();
9296 /* If a display connection is dead, don't try sending more
9297 commands to the X server. */
9298 if (dpyinfo->display)
9300 /* We must free faces before destroying windows because some
9301 font-driver (e.g. xft) access a window while finishing a
9302 face. */
9303 if (FRAME_FACE_CACHE (f))
9304 free_frame_faces (f);
9306 if (f->output_data.x->icon_desc)
9307 XDestroyWindow (FRAME_X_DISPLAY (f), f->output_data.x->icon_desc);
9309 #ifdef USE_X_TOOLKIT
9310 /* Explicitly destroy the scroll bars of the frame. Without
9311 this, we get "BadDrawable" errors from the toolkit later on,
9312 presumably from expose events generated for the disappearing
9313 toolkit scroll bars. */
9314 for (bar = FRAME_SCROLL_BARS (f); !NILP (bar); bar = b->next)
9316 b = XSCROLL_BAR (bar);
9317 x_scroll_bar_remove (b);
9319 #endif
9321 #ifdef HAVE_X_I18N
9322 if (FRAME_XIC (f))
9323 free_frame_xic (f);
9324 #endif
9326 #ifdef USE_X_TOOLKIT
9327 if (f->output_data.x->widget)
9329 XtDestroyWidget (f->output_data.x->widget);
9330 f->output_data.x->widget = NULL;
9332 /* Tooltips don't have widgets, only a simple X window, even if
9333 we are using a toolkit. */
9334 else if (FRAME_X_WINDOW (f))
9335 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9337 free_frame_menubar (f);
9338 #else /* !USE_X_TOOLKIT */
9340 #ifdef USE_GTK
9341 xg_free_frame_widgets (f);
9342 #endif /* USE_GTK */
9344 if (FRAME_X_WINDOW (f))
9345 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9346 #endif /* !USE_X_TOOLKIT */
9348 unload_color (f, FRAME_FOREGROUND_PIXEL (f));
9349 unload_color (f, FRAME_BACKGROUND_PIXEL (f));
9350 unload_color (f, f->output_data.x->cursor_pixel);
9351 unload_color (f, f->output_data.x->cursor_foreground_pixel);
9352 unload_color (f, f->output_data.x->border_pixel);
9353 unload_color (f, f->output_data.x->mouse_pixel);
9355 if (f->output_data.x->scroll_bar_background_pixel != -1)
9356 unload_color (f, f->output_data.x->scroll_bar_background_pixel);
9357 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
9358 unload_color (f, f->output_data.x->scroll_bar_foreground_pixel);
9359 #ifdef USE_TOOLKIT_SCROLL_BARS
9360 /* Scrollbar shadow colors. */
9361 if (f->output_data.x->scroll_bar_top_shadow_pixel != -1)
9362 unload_color (f, f->output_data.x->scroll_bar_top_shadow_pixel);
9363 if (f->output_data.x->scroll_bar_bottom_shadow_pixel != -1)
9364 unload_color (f, f->output_data.x->scroll_bar_bottom_shadow_pixel);
9365 #endif /* USE_TOOLKIT_SCROLL_BARS */
9366 if (f->output_data.x->white_relief.pixel != -1)
9367 unload_color (f, f->output_data.x->white_relief.pixel);
9368 if (f->output_data.x->black_relief.pixel != -1)
9369 unload_color (f, f->output_data.x->black_relief.pixel);
9371 x_free_gcs (f);
9373 /* Free extra GCs allocated by x_setup_relief_colors. */
9374 if (f->output_data.x->white_relief.gc)
9376 XFreeGC (dpyinfo->display, f->output_data.x->white_relief.gc);
9377 f->output_data.x->white_relief.gc = 0;
9379 if (f->output_data.x->black_relief.gc)
9381 XFreeGC (dpyinfo->display, f->output_data.x->black_relief.gc);
9382 f->output_data.x->black_relief.gc = 0;
9385 XFlush (FRAME_X_DISPLAY (f));
9388 xfree (f->output_data.x->saved_menu_event);
9389 xfree (f->output_data.x);
9390 f->output_data.x = NULL;
9392 if (f == dpyinfo->x_focus_frame)
9393 dpyinfo->x_focus_frame = 0;
9394 if (f == dpyinfo->x_focus_event_frame)
9395 dpyinfo->x_focus_event_frame = 0;
9396 if (f == dpyinfo->x_highlight_frame)
9397 dpyinfo->x_highlight_frame = 0;
9398 if (f == hlinfo->mouse_face_mouse_frame)
9399 reset_mouse_highlight (hlinfo);
9401 unblock_input ();
9405 /* Destroy the X window of frame F. */
9407 static void
9408 x_destroy_window (struct frame *f)
9410 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
9412 /* If a display connection is dead, don't try sending more
9413 commands to the X server. */
9414 if (dpyinfo->display != 0)
9415 x_free_frame_resources (f);
9417 dpyinfo->reference_count--;
9421 /* Setting window manager hints. */
9423 /* Set the normal size hints for the window manager, for frame F.
9424 FLAGS is the flags word to use--or 0 meaning preserve the flags
9425 that the window now has.
9426 If USER_POSITION, set the USPosition
9427 flag (this is useful when FLAGS is 0).
9428 The GTK version is in gtkutils.c. */
9430 #ifndef USE_GTK
9431 void
9432 x_wm_set_size_hint (struct frame *f, long flags, bool user_position)
9434 XSizeHints size_hints;
9435 Window window = FRAME_OUTER_WINDOW (f);
9437 #ifdef USE_X_TOOLKIT
9438 if (f->output_data.x->widget)
9440 widget_update_wm_size_hints (f->output_data.x->widget);
9441 return;
9443 #endif
9445 /* Setting PMaxSize caused various problems. */
9446 size_hints.flags = PResizeInc | PMinSize /* | PMaxSize */;
9448 size_hints.x = f->left_pos;
9449 size_hints.y = f->top_pos;
9451 size_hints.height = FRAME_PIXEL_HEIGHT (f);
9452 size_hints.width = FRAME_PIXEL_WIDTH (f);
9454 size_hints.width_inc = FRAME_COLUMN_WIDTH (f);
9455 size_hints.height_inc = FRAME_LINE_HEIGHT (f);
9456 size_hints.max_width = x_display_pixel_width (FRAME_DISPLAY_INFO (f))
9457 - FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
9458 size_hints.max_height = x_display_pixel_height (FRAME_DISPLAY_INFO (f))
9459 - FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
9461 /* Calculate the base and minimum sizes. */
9463 int base_width, base_height;
9464 int min_rows = 0, min_cols = 0;
9466 base_width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
9467 base_height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
9469 check_frame_size (f, &min_cols, &min_rows, 0);
9471 /* The window manager uses the base width hints to calculate the
9472 current number of rows and columns in the frame while
9473 resizing; min_width and min_height aren't useful for this
9474 purpose, since they might not give the dimensions for a
9475 zero-row, zero-column frame.
9477 We use the base_width and base_height members if we have
9478 them; otherwise, we set the min_width and min_height members
9479 to the size for a zero x zero frame. */
9481 size_hints.flags |= PBaseSize;
9482 size_hints.base_width = base_width;
9483 size_hints.base_height = base_height + FRAME_MENUBAR_HEIGHT (f);
9484 size_hints.min_width = base_width + min_cols * size_hints.width_inc;
9485 size_hints.min_height = base_height + min_rows * size_hints.height_inc;
9488 /* If we don't need the old flags, we don't need the old hint at all. */
9489 if (flags)
9491 size_hints.flags |= flags;
9492 goto no_read;
9496 XSizeHints hints; /* Sometimes I hate X Windows... */
9497 long supplied_return;
9498 int value;
9500 value = XGetWMNormalHints (FRAME_X_DISPLAY (f), window, &hints,
9501 &supplied_return);
9503 if (flags)
9504 size_hints.flags |= flags;
9505 else
9507 if (value == 0)
9508 hints.flags = 0;
9509 if (hints.flags & PSize)
9510 size_hints.flags |= PSize;
9511 if (hints.flags & PPosition)
9512 size_hints.flags |= PPosition;
9513 if (hints.flags & USPosition)
9514 size_hints.flags |= USPosition;
9515 if (hints.flags & USSize)
9516 size_hints.flags |= USSize;
9520 no_read:
9522 #ifdef PWinGravity
9523 size_hints.win_gravity = f->win_gravity;
9524 size_hints.flags |= PWinGravity;
9526 if (user_position)
9528 size_hints.flags &= ~ PPosition;
9529 size_hints.flags |= USPosition;
9531 #endif /* PWinGravity */
9533 XSetWMNormalHints (FRAME_X_DISPLAY (f), window, &size_hints);
9535 #endif /* not USE_GTK */
9537 /* Used for IconicState or NormalState */
9539 static void
9540 x_wm_set_window_state (struct frame *f, int state)
9542 #ifdef USE_X_TOOLKIT
9543 Arg al[1];
9545 XtSetArg (al[0], XtNinitialState, state);
9546 XtSetValues (f->output_data.x->widget, al, 1);
9547 #else /* not USE_X_TOOLKIT */
9548 Window window = FRAME_X_WINDOW (f);
9550 f->output_data.x->wm_hints.flags |= StateHint;
9551 f->output_data.x->wm_hints.initial_state = state;
9553 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
9554 #endif /* not USE_X_TOOLKIT */
9557 static void
9558 x_wm_set_icon_pixmap (struct frame *f, ptrdiff_t pixmap_id)
9560 Pixmap icon_pixmap, icon_mask;
9562 #if !defined USE_X_TOOLKIT && !defined USE_GTK
9563 Window window = FRAME_OUTER_WINDOW (f);
9564 #endif
9566 if (pixmap_id > 0)
9568 icon_pixmap = x_bitmap_pixmap (f, pixmap_id);
9569 f->output_data.x->wm_hints.icon_pixmap = icon_pixmap;
9570 icon_mask = x_bitmap_mask (f, pixmap_id);
9571 f->output_data.x->wm_hints.icon_mask = icon_mask;
9573 else
9575 /* It seems there is no way to turn off use of an icon
9576 pixmap. */
9577 return;
9581 #ifdef USE_GTK
9583 xg_set_frame_icon (f, icon_pixmap, icon_mask);
9584 return;
9587 #elif defined (USE_X_TOOLKIT) /* same as in x_wm_set_window_state. */
9590 Arg al[1];
9591 XtSetArg (al[0], XtNiconPixmap, icon_pixmap);
9592 XtSetValues (f->output_data.x->widget, al, 1);
9593 XtSetArg (al[0], XtNiconMask, icon_mask);
9594 XtSetValues (f->output_data.x->widget, al, 1);
9597 #else /* not USE_X_TOOLKIT && not USE_GTK */
9599 f->output_data.x->wm_hints.flags |= (IconPixmapHint | IconMaskHint);
9600 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
9602 #endif /* not USE_X_TOOLKIT && not USE_GTK */
9605 void
9606 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
9608 Window window = FRAME_OUTER_WINDOW (f);
9610 f->output_data.x->wm_hints.flags |= IconPositionHint;
9611 f->output_data.x->wm_hints.icon_x = icon_x;
9612 f->output_data.x->wm_hints.icon_y = icon_y;
9614 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
9618 /***********************************************************************
9619 Fonts
9620 ***********************************************************************/
9622 #ifdef GLYPH_DEBUG
9624 /* Check that FONT is valid on frame F. It is if it can be found in F's
9625 font table. */
9627 static void
9628 x_check_font (struct frame *f, struct font *font)
9630 eassert (font != NULL && ! NILP (font->props[FONT_TYPE_INDEX]));
9631 if (font->driver->check)
9632 eassert (font->driver->check (f, font) == 0);
9635 #endif /* GLYPH_DEBUG */
9638 /***********************************************************************
9639 Initialization
9640 ***********************************************************************/
9642 #ifdef USE_X_TOOLKIT
9643 static XrmOptionDescRec emacs_options[] = {
9644 {"-geometry", ".geometry", XrmoptionSepArg, NULL},
9645 {"-iconic", ".iconic", XrmoptionNoArg, (XtPointer) "yes"},
9647 {"-internal-border-width", "*EmacsScreen.internalBorderWidth",
9648 XrmoptionSepArg, NULL},
9649 {"-ib", "*EmacsScreen.internalBorderWidth", XrmoptionSepArg, NULL},
9651 {"-T", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
9652 {"-wn", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
9653 {"-title", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
9654 {"-iconname", "*EmacsShell.iconName", XrmoptionSepArg, (XtPointer) NULL},
9655 {"-in", "*EmacsShell.iconName", XrmoptionSepArg, (XtPointer) NULL},
9656 {"-mc", "*pointerColor", XrmoptionSepArg, (XtPointer) NULL},
9657 {"-cr", "*cursorColor", XrmoptionSepArg, (XtPointer) NULL}
9660 /* Whether atimer for Xt timeouts is activated or not. */
9662 static int x_timeout_atimer_activated_flag;
9664 #endif /* USE_X_TOOLKIT */
9666 static int x_initialized;
9668 /* Test whether two display-name strings agree up to the dot that separates
9669 the screen number from the server number. */
9670 static int
9671 same_x_server (const char *name1, const char *name2)
9673 int seen_colon = 0;
9674 const char *system_name = SSDATA (Vsystem_name);
9675 ptrdiff_t system_name_length = SBYTES (Vsystem_name);
9676 ptrdiff_t length_until_period = 0;
9678 while (system_name[length_until_period] != 0
9679 && system_name[length_until_period] != '.')
9680 length_until_period++;
9682 /* Treat `unix' like an empty host name. */
9683 if (! strncmp (name1, "unix:", 5))
9684 name1 += 4;
9685 if (! strncmp (name2, "unix:", 5))
9686 name2 += 4;
9687 /* Treat this host's name like an empty host name. */
9688 if (! strncmp (name1, system_name, system_name_length)
9689 && name1[system_name_length] == ':')
9690 name1 += system_name_length;
9691 if (! strncmp (name2, system_name, system_name_length)
9692 && name2[system_name_length] == ':')
9693 name2 += system_name_length;
9694 /* Treat this host's domainless name like an empty host name. */
9695 if (! strncmp (name1, system_name, length_until_period)
9696 && name1[length_until_period] == ':')
9697 name1 += length_until_period;
9698 if (! strncmp (name2, system_name, length_until_period)
9699 && name2[length_until_period] == ':')
9700 name2 += length_until_period;
9702 for (; *name1 != '\0' && *name1 == *name2; name1++, name2++)
9704 if (*name1 == ':')
9705 seen_colon = 1;
9706 if (seen_colon && *name1 == '.')
9707 return 1;
9709 return (seen_colon
9710 && (*name1 == '.' || *name1 == '\0')
9711 && (*name2 == '.' || *name2 == '\0'));
9714 /* Count number of set bits in mask and number of bits to shift to
9715 get to the first bit. With MASK 0x7e0, *BITS is set to 6, and *OFFSET
9716 to 5. */
9717 static void
9718 get_bits_and_offset (unsigned long mask, int *bits, int *offset)
9720 int nr = 0;
9721 int off = 0;
9723 while (!(mask & 1))
9725 off++;
9726 mask >>= 1;
9729 while (mask & 1)
9731 nr++;
9732 mask >>= 1;
9735 *offset = off;
9736 *bits = nr;
9739 /* Return 1 if display DISPLAY is available for use, 0 otherwise.
9740 But don't permanently open it, just test its availability. */
9742 bool
9743 x_display_ok (const char *display)
9745 Display *dpy = XOpenDisplay (display);
9746 return dpy ? (XCloseDisplay (dpy), 1) : 0;
9749 #ifdef USE_GTK
9750 static void
9751 my_log_handler (const gchar *log_domain, GLogLevelFlags log_level,
9752 const gchar *msg, gpointer user_data)
9754 if (!strstr (msg, "g_set_prgname"))
9755 fprintf (stderr, "%s-WARNING **: %s\n", log_domain, msg);
9757 #endif
9759 /* Open a connection to X display DISPLAY_NAME, and return
9760 the structure that describes the open display.
9761 If we cannot contact the display, return null. */
9763 struct x_display_info *
9764 x_term_init (Lisp_Object display_name, char *xrm_option, char *resource_name)
9766 int connection;
9767 Display *dpy;
9768 struct terminal *terminal;
9769 struct x_display_info *dpyinfo;
9770 XrmDatabase xrdb;
9771 ptrdiff_t lim;
9773 block_input ();
9775 if (!x_initialized)
9777 x_initialize ();
9778 ++x_initialized;
9781 if (! x_display_ok (SSDATA (display_name)))
9782 error ("Display %s can't be opened", SSDATA (display_name));
9784 #ifdef USE_GTK
9786 #define NUM_ARGV 10
9787 int argc;
9788 char *argv[NUM_ARGV];
9789 char **argv2 = argv;
9790 guint id;
9792 if (x_initialized++ > 1)
9794 xg_display_open (SSDATA (display_name), &dpy);
9796 else
9798 static char display_opt[] = "--display";
9799 static char name_opt[] = "--name";
9801 for (argc = 0; argc < NUM_ARGV; ++argc)
9802 argv[argc] = 0;
9804 argc = 0;
9805 argv[argc++] = initial_argv[0];
9807 if (! NILP (display_name))
9809 argv[argc++] = display_opt;
9810 argv[argc++] = SSDATA (display_name);
9813 argv[argc++] = name_opt;
9814 argv[argc++] = resource_name;
9816 XSetLocaleModifiers ("");
9818 /* Emacs can only handle core input events, so make sure
9819 Gtk doesn't use Xinput or Xinput2 extensions. */
9820 xputenv ("GDK_CORE_DEVICE_EVENTS=1");
9822 /* Work around GLib bug that outputs a faulty warning. See
9823 https://bugzilla.gnome.org/show_bug.cgi?id=563627. */
9824 id = g_log_set_handler ("GLib", G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
9825 | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
9827 /* NULL window -> events for all windows go to our function.
9828 Call before gtk_init so Gtk+ event filters comes after our. */
9829 gdk_window_add_filter (NULL, event_handler_gdk, NULL);
9831 /* gtk_init does set_locale. Fix locale before and after. */
9832 fixup_locale ();
9833 gtk_init (&argc, &argv2);
9834 fixup_locale ();
9836 g_log_remove_handler ("GLib", id);
9838 xg_initialize ();
9840 dpy = DEFAULT_GDK_DISPLAY ();
9842 #if ! GTK_CHECK_VERSION (2, 90, 0)
9843 /* Load our own gtkrc if it exists. */
9845 const char *file = "~/.emacs.d/gtkrc";
9846 Lisp_Object s, abs_file;
9848 s = build_string (file);
9849 abs_file = Fexpand_file_name (s, Qnil);
9851 if (! NILP (abs_file) && !NILP (Ffile_readable_p (abs_file)))
9852 gtk_rc_parse (SSDATA (abs_file));
9854 #endif
9856 XSetErrorHandler (x_error_handler);
9857 XSetIOErrorHandler (x_io_error_quitter);
9860 #else /* not USE_GTK */
9861 #ifdef USE_X_TOOLKIT
9862 /* weiner@footloose.sps.mot.com reports that this causes
9863 errors with X11R5:
9864 X protocol error: BadAtom (invalid Atom parameter)
9865 on protocol request 18skiloaf.
9866 So let's not use it until R6. */
9867 #ifdef HAVE_X11XTR6
9868 XtSetLanguageProc (NULL, NULL, NULL);
9869 #endif
9872 int argc = 0;
9873 char *argv[3];
9875 argv[0] = "";
9876 argc = 1;
9877 if (xrm_option)
9879 argv[argc++] = "-xrm";
9880 argv[argc++] = xrm_option;
9882 turn_on_atimers (0);
9883 dpy = XtOpenDisplay (Xt_app_con, SSDATA (display_name),
9884 resource_name, EMACS_CLASS,
9885 emacs_options, XtNumber (emacs_options),
9886 &argc, argv);
9887 turn_on_atimers (1);
9889 #ifdef HAVE_X11XTR6
9890 /* I think this is to compensate for XtSetLanguageProc. */
9891 fixup_locale ();
9892 #endif
9895 #else /* not USE_X_TOOLKIT */
9896 XSetLocaleModifiers ("");
9897 dpy = XOpenDisplay (SSDATA (display_name));
9898 #endif /* not USE_X_TOOLKIT */
9899 #endif /* not USE_GTK*/
9901 /* Detect failure. */
9902 if (dpy == 0)
9904 unblock_input ();
9905 return 0;
9908 /* We have definitely succeeded. Record the new connection. */
9910 dpyinfo = xzalloc (sizeof *dpyinfo);
9911 terminal = x_create_terminal (dpyinfo);
9914 struct x_display_info *share;
9916 for (share = x_display_list; share; share = share->next)
9917 if (same_x_server (SSDATA (XCAR (share->name_list_element)),
9918 SSDATA (display_name)))
9919 break;
9920 if (share)
9921 terminal->kboard = share->terminal->kboard;
9922 else
9924 terminal->kboard = allocate_kboard (Qx);
9926 if (!EQ (XSYMBOL (Qvendor_specific_keysyms)->function, Qunbound))
9928 char *vendor = ServerVendor (dpy);
9930 /* Protect terminal from GC before removing it from the
9931 list of terminals. */
9932 struct gcpro gcpro1;
9933 Lisp_Object gcpro_term;
9934 XSETTERMINAL (gcpro_term, terminal);
9935 GCPRO1 (gcpro_term);
9937 /* Temporarily hide the partially initialized terminal. */
9938 terminal_list = terminal->next_terminal;
9939 unblock_input ();
9940 kset_system_key_alist
9941 (terminal->kboard,
9942 call1 (Qvendor_specific_keysyms,
9943 vendor ? build_string (vendor) : empty_unibyte_string));
9944 block_input ();
9945 terminal->next_terminal = terminal_list;
9946 terminal_list = terminal;
9947 UNGCPRO;
9950 /* Don't let the initial kboard remain current longer than necessary.
9951 That would cause problems if a file loaded on startup tries to
9952 prompt in the mini-buffer. */
9953 if (current_kboard == initial_kboard)
9954 current_kboard = terminal->kboard;
9956 terminal->kboard->reference_count++;
9959 /* Put this display on the chain. */
9960 dpyinfo->next = x_display_list;
9961 x_display_list = dpyinfo;
9963 dpyinfo->name_list_element = Fcons (display_name, Qnil);
9964 dpyinfo->display = dpy;
9966 /* Set the name of the terminal. */
9967 terminal->name = xlispstrdup (display_name);
9969 #if 0
9970 XSetAfterFunction (x_current_display, x_trace_wire);
9971 #endif /* ! 0 */
9973 lim = min (PTRDIFF_MAX, SIZE_MAX) - sizeof "@";
9974 if (lim - SBYTES (Vinvocation_name) < SBYTES (Vsystem_name))
9975 memory_full (SIZE_MAX);
9976 dpyinfo->x_id_name = xmalloc (SBYTES (Vinvocation_name)
9977 + SBYTES (Vsystem_name) + 2);
9978 strcat (strcat (strcpy (dpyinfo->x_id_name, SSDATA (Vinvocation_name)), "@"),
9979 SSDATA (Vsystem_name));
9981 /* Figure out which modifier bits mean what. */
9982 x_find_modifier_meanings (dpyinfo);
9984 /* Get the scroll bar cursor. */
9985 #ifdef USE_GTK
9986 /* We must create a GTK cursor, it is required for GTK widgets. */
9987 dpyinfo->xg_cursor = xg_create_default_cursor (dpyinfo->display);
9988 #endif /* USE_GTK */
9990 dpyinfo->vertical_scroll_bar_cursor
9991 = XCreateFontCursor (dpyinfo->display, XC_sb_v_double_arrow);
9993 xrdb = x_load_resources (dpyinfo->display, xrm_option,
9994 resource_name, EMACS_CLASS);
9995 #ifdef HAVE_XRMSETDATABASE
9996 XrmSetDatabase (dpyinfo->display, xrdb);
9997 #else
9998 dpyinfo->display->db = xrdb;
9999 #endif
10000 /* Put the rdb where we can find it in a way that works on
10001 all versions. */
10002 dpyinfo->xrdb = xrdb;
10004 dpyinfo->screen = ScreenOfDisplay (dpyinfo->display,
10005 DefaultScreen (dpyinfo->display));
10006 select_visual (dpyinfo);
10007 dpyinfo->cmap = DefaultColormapOfScreen (dpyinfo->screen);
10008 dpyinfo->root_window = RootWindowOfScreen (dpyinfo->screen);
10009 dpyinfo->icon_bitmap_id = -1;
10010 dpyinfo->wm_type = X_WMTYPE_UNKNOWN;
10012 reset_mouse_highlight (&dpyinfo->mouse_highlight);
10014 /* See if we can construct pixel values from RGB values. */
10015 if (dpyinfo->visual->class == TrueColor)
10017 get_bits_and_offset (dpyinfo->visual->red_mask,
10018 &dpyinfo->red_bits, &dpyinfo->red_offset);
10019 get_bits_and_offset (dpyinfo->visual->blue_mask,
10020 &dpyinfo->blue_bits, &dpyinfo->blue_offset);
10021 get_bits_and_offset (dpyinfo->visual->green_mask,
10022 &dpyinfo->green_bits, &dpyinfo->green_offset);
10025 /* See if a private colormap is requested. */
10026 if (dpyinfo->visual == DefaultVisualOfScreen (dpyinfo->screen))
10028 if (dpyinfo->visual->class == PseudoColor)
10030 Lisp_Object value;
10031 value = display_x_get_resource (dpyinfo,
10032 build_string ("privateColormap"),
10033 build_string ("PrivateColormap"),
10034 Qnil, Qnil);
10035 if (STRINGP (value)
10036 && (!strcmp (SSDATA (value), "true")
10037 || !strcmp (SSDATA (value), "on")))
10038 dpyinfo->cmap = XCopyColormapAndFree (dpyinfo->display, dpyinfo->cmap);
10041 else
10042 dpyinfo->cmap = XCreateColormap (dpyinfo->display, dpyinfo->root_window,
10043 dpyinfo->visual, AllocNone);
10045 #ifdef HAVE_XFT
10047 /* If we are using Xft, check dpi value in X resources.
10048 It is better we use it as well, since Xft will use it, as will all
10049 Gnome applications. If our real DPI is smaller or larger than the
10050 one Xft uses, our font will look smaller or larger than other
10051 for other applications, even if it is the same font name (monospace-10
10052 for example). */
10053 char *v = XGetDefault (dpyinfo->display, "Xft", "dpi");
10054 double d;
10055 if (v != NULL && sscanf (v, "%lf", &d) == 1)
10056 dpyinfo->resy = dpyinfo->resx = d;
10058 #endif
10060 if (dpyinfo->resy < 1)
10062 int screen_number = XScreenNumberOfScreen (dpyinfo->screen);
10063 double pixels = DisplayHeight (dpyinfo->display, screen_number);
10064 double mm = DisplayHeightMM (dpyinfo->display, screen_number);
10065 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
10066 dpyinfo->resy = (mm < 1) ? 100 : pixels * 25.4 / mm;
10067 pixels = DisplayWidth (dpyinfo->display, screen_number);
10068 mm = DisplayWidthMM (dpyinfo->display, screen_number);
10069 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
10070 dpyinfo->resx = (mm < 1) ? 100 : pixels * 25.4 / mm;
10074 static const struct
10076 const char *name;
10077 int offset;
10078 } atom_refs[] = {
10079 #define ATOM_REFS_INIT(string, member) \
10080 { string, offsetof (struct x_display_info, member) },
10081 ATOM_REFS_INIT ("WM_PROTOCOLS", Xatom_wm_protocols)
10082 ATOM_REFS_INIT ("WM_TAKE_FOCUS", Xatom_wm_take_focus)
10083 ATOM_REFS_INIT ("WM_SAVE_YOURSELF", Xatom_wm_save_yourself)
10084 ATOM_REFS_INIT ("WM_DELETE_WINDOW", Xatom_wm_delete_window)
10085 ATOM_REFS_INIT ("WM_CHANGE_STATE", Xatom_wm_change_state)
10086 ATOM_REFS_INIT ("WM_CONFIGURE_DENIED", Xatom_wm_configure_denied)
10087 ATOM_REFS_INIT ("WM_MOVED", Xatom_wm_window_moved)
10088 ATOM_REFS_INIT ("WM_CLIENT_LEADER", Xatom_wm_client_leader)
10089 ATOM_REFS_INIT ("Editres", Xatom_editres)
10090 ATOM_REFS_INIT ("CLIPBOARD", Xatom_CLIPBOARD)
10091 ATOM_REFS_INIT ("TIMESTAMP", Xatom_TIMESTAMP)
10092 ATOM_REFS_INIT ("TEXT", Xatom_TEXT)
10093 ATOM_REFS_INIT ("COMPOUND_TEXT", Xatom_COMPOUND_TEXT)
10094 ATOM_REFS_INIT ("UTF8_STRING", Xatom_UTF8_STRING)
10095 ATOM_REFS_INIT ("DELETE", Xatom_DELETE)
10096 ATOM_REFS_INIT ("MULTIPLE", Xatom_MULTIPLE)
10097 ATOM_REFS_INIT ("INCR", Xatom_INCR)
10098 ATOM_REFS_INIT ("_EMACS_TMP_", Xatom_EMACS_TMP)
10099 ATOM_REFS_INIT ("TARGETS", Xatom_TARGETS)
10100 ATOM_REFS_INIT ("NULL", Xatom_NULL)
10101 ATOM_REFS_INIT ("ATOM", Xatom_ATOM)
10102 ATOM_REFS_INIT ("ATOM_PAIR", Xatom_ATOM_PAIR)
10103 ATOM_REFS_INIT ("CLIPBOARD_MANAGER", Xatom_CLIPBOARD_MANAGER)
10104 ATOM_REFS_INIT ("_XEMBED_INFO", Xatom_XEMBED_INFO)
10105 /* For properties of font. */
10106 ATOM_REFS_INIT ("PIXEL_SIZE", Xatom_PIXEL_SIZE)
10107 ATOM_REFS_INIT ("AVERAGE_WIDTH", Xatom_AVERAGE_WIDTH)
10108 ATOM_REFS_INIT ("_MULE_BASELINE_OFFSET", Xatom_MULE_BASELINE_OFFSET)
10109 ATOM_REFS_INIT ("_MULE_RELATIVE_COMPOSE", Xatom_MULE_RELATIVE_COMPOSE)
10110 ATOM_REFS_INIT ("_MULE_DEFAULT_ASCENT", Xatom_MULE_DEFAULT_ASCENT)
10111 /* Ghostscript support. */
10112 ATOM_REFS_INIT ("DONE", Xatom_DONE)
10113 ATOM_REFS_INIT ("PAGE", Xatom_PAGE)
10114 ATOM_REFS_INIT ("SCROLLBAR", Xatom_Scrollbar)
10115 ATOM_REFS_INIT ("_XEMBED", Xatom_XEMBED)
10116 /* EWMH */
10117 ATOM_REFS_INIT ("_NET_WM_STATE", Xatom_net_wm_state)
10118 ATOM_REFS_INIT ("_NET_WM_STATE_FULLSCREEN", Xatom_net_wm_state_fullscreen)
10119 ATOM_REFS_INIT ("_NET_WM_STATE_MAXIMIZED_HORZ",
10120 Xatom_net_wm_state_maximized_horz)
10121 ATOM_REFS_INIT ("_NET_WM_STATE_MAXIMIZED_VERT",
10122 Xatom_net_wm_state_maximized_vert)
10123 ATOM_REFS_INIT ("_NET_WM_STATE_STICKY", Xatom_net_wm_state_sticky)
10124 ATOM_REFS_INIT ("_NET_WM_STATE_HIDDEN", Xatom_net_wm_state_hidden)
10125 ATOM_REFS_INIT ("_NET_WM_WINDOW_TYPE", Xatom_net_window_type)
10126 ATOM_REFS_INIT ("_NET_WM_WINDOW_TYPE_TOOLTIP",
10127 Xatom_net_window_type_tooltip)
10128 ATOM_REFS_INIT ("_NET_WM_ICON_NAME", Xatom_net_wm_icon_name)
10129 ATOM_REFS_INIT ("_NET_WM_NAME", Xatom_net_wm_name)
10130 ATOM_REFS_INIT ("_NET_SUPPORTED", Xatom_net_supported)
10131 ATOM_REFS_INIT ("_NET_SUPPORTING_WM_CHECK", Xatom_net_supporting_wm_check)
10132 ATOM_REFS_INIT ("_NET_WM_WINDOW_OPACITY", Xatom_net_wm_window_opacity)
10133 ATOM_REFS_INIT ("_NET_ACTIVE_WINDOW", Xatom_net_active_window)
10134 ATOM_REFS_INIT ("_NET_FRAME_EXTENTS", Xatom_net_frame_extents)
10135 ATOM_REFS_INIT ("_NET_CURRENT_DESKTOP", Xatom_net_current_desktop)
10136 ATOM_REFS_INIT ("_NET_WORKAREA", Xatom_net_workarea)
10137 /* Session management */
10138 ATOM_REFS_INIT ("SM_CLIENT_ID", Xatom_SM_CLIENT_ID)
10139 ATOM_REFS_INIT ("_XSETTINGS_SETTINGS", Xatom_xsettings_prop)
10140 ATOM_REFS_INIT ("MANAGER", Xatom_xsettings_mgr)
10143 int i;
10144 const int atom_count = sizeof (atom_refs) / sizeof (atom_refs[0]);
10145 /* 1 for _XSETTINGS_SN */
10146 const int total_atom_count = 1 + atom_count;
10147 Atom *atoms_return = xmalloc (total_atom_count * sizeof *atoms_return);
10148 char **atom_names = xmalloc (total_atom_count * sizeof *atom_names);
10149 static char const xsettings_fmt[] = "_XSETTINGS_S%d";
10150 char xsettings_atom_name[sizeof xsettings_fmt - 2
10151 + INT_STRLEN_BOUND (int)];
10153 for (i = 0; i < atom_count; i++)
10154 atom_names[i] = (char *) atom_refs[i].name;
10156 /* Build _XSETTINGS_SN atom name */
10157 sprintf (xsettings_atom_name, xsettings_fmt,
10158 XScreenNumberOfScreen (dpyinfo->screen));
10159 atom_names[i] = xsettings_atom_name;
10161 XInternAtoms (dpyinfo->display, atom_names, total_atom_count,
10162 False, atoms_return);
10164 for (i = 0; i < atom_count; i++)
10165 *(Atom *) ((char *) dpyinfo + atom_refs[i].offset) = atoms_return[i];
10167 /* Manual copy of last atom */
10168 dpyinfo->Xatom_xsettings_sel = atoms_return[i];
10170 xfree (atom_names);
10171 xfree (atoms_return);
10174 dpyinfo->x_dnd_atoms_size = 8;
10175 dpyinfo->x_dnd_atoms = xmalloc (sizeof *dpyinfo->x_dnd_atoms
10176 * dpyinfo->x_dnd_atoms_size);
10177 dpyinfo->gray
10178 = XCreatePixmapFromBitmapData (dpyinfo->display, dpyinfo->root_window,
10179 gray_bits, gray_width, gray_height,
10180 1, 0, 1);
10182 #ifdef HAVE_X_I18N
10183 xim_initialize (dpyinfo, resource_name);
10184 #endif
10186 xsettings_initialize (dpyinfo);
10188 connection = ConnectionNumber (dpyinfo->display);
10190 /* This is only needed for distinguishing keyboard and process input. */
10191 if (connection != 0)
10192 add_keyboard_wait_descriptor (connection);
10194 #ifdef F_SETOWN
10195 fcntl (connection, F_SETOWN, getpid ());
10196 #endif /* ! defined (F_SETOWN) */
10198 if (interrupt_input)
10199 init_sigio (connection);
10201 #ifdef USE_LUCID
10203 XrmValue d, fr, to;
10204 Font font;
10206 dpy = dpyinfo->display;
10207 d.addr = (XPointer)&dpy;
10208 d.size = sizeof (Display *);
10209 fr.addr = XtDefaultFont;
10210 fr.size = sizeof (XtDefaultFont);
10211 to.size = sizeof (Font *);
10212 to.addr = (XPointer)&font;
10213 x_catch_errors (dpy);
10214 if (!XtCallConverter (dpy, XtCvtStringToFont, &d, 1, &fr, &to, NULL))
10215 emacs_abort ();
10216 if (x_had_errors_p (dpy) || !XQueryFont (dpy, font))
10217 XrmPutLineResource (&xrdb, "Emacs.dialog.*.font: 9x15");
10218 x_uncatch_errors ();
10220 #endif
10222 /* See if we should run in synchronous mode. This is useful
10223 for debugging X code. */
10225 Lisp_Object value;
10226 value = display_x_get_resource (dpyinfo,
10227 build_string ("synchronous"),
10228 build_string ("Synchronous"),
10229 Qnil, Qnil);
10230 if (STRINGP (value)
10231 && (!strcmp (SSDATA (value), "true")
10232 || !strcmp (SSDATA (value), "on")))
10233 XSynchronize (dpyinfo->display, True);
10237 Lisp_Object value;
10238 value = display_x_get_resource (dpyinfo,
10239 build_string ("useXIM"),
10240 build_string ("UseXIM"),
10241 Qnil, Qnil);
10242 #ifdef USE_XIM
10243 if (STRINGP (value)
10244 && (!strcmp (SSDATA (value), "false")
10245 || !strcmp (SSDATA (value), "off")))
10246 use_xim = 0;
10247 #else
10248 if (STRINGP (value)
10249 && (!strcmp (SSDATA (value), "true")
10250 || !strcmp (SSDATA (value), "on")))
10251 use_xim = 1;
10252 #endif
10255 #ifdef HAVE_X_SM
10256 /* Only do this for the very first display in the Emacs session.
10257 Ignore X session management when Emacs was first started on a
10258 tty. */
10259 if (terminal->id == 1)
10260 x_session_initialize (dpyinfo);
10261 #endif
10263 unblock_input ();
10265 return dpyinfo;
10268 /* Get rid of display DPYINFO, deleting all frames on it,
10269 and without sending any more commands to the X server. */
10271 static void
10272 x_delete_display (struct x_display_info *dpyinfo)
10274 struct terminal *t;
10276 /* Close all frames and delete the generic struct terminal for this
10277 X display. */
10278 for (t = terminal_list; t; t = t->next_terminal)
10279 if (t->type == output_x_window && t->display_info.x == dpyinfo)
10281 #ifdef HAVE_X_SM
10282 /* Close X session management when we close its display. */
10283 if (t->id == 1 && x_session_have_connection ())
10284 x_session_close ();
10285 #endif
10286 delete_terminal (t);
10287 break;
10290 if (next_noop_dpyinfo == dpyinfo)
10291 next_noop_dpyinfo = dpyinfo->next;
10293 if (x_display_list == dpyinfo)
10294 x_display_list = dpyinfo->next;
10295 else
10297 struct x_display_info *tail;
10299 for (tail = x_display_list; tail; tail = tail->next)
10300 if (tail->next == dpyinfo)
10301 tail->next = tail->next->next;
10304 xfree (dpyinfo->x_id_name);
10305 xfree (dpyinfo->x_dnd_atoms);
10306 xfree (dpyinfo->color_cells);
10307 xfree (dpyinfo);
10310 #ifdef USE_X_TOOLKIT
10312 /* Atimer callback function for TIMER. Called every 0.1s to process
10313 Xt timeouts, if needed. We must avoid calling XtAppPending as
10314 much as possible because that function does an implicit XFlush
10315 that slows us down. */
10317 static void
10318 x_process_timeouts (struct atimer *timer)
10320 block_input ();
10321 x_timeout_atimer_activated_flag = 0;
10322 if (toolkit_scroll_bar_interaction || popup_activated ())
10324 while (XtAppPending (Xt_app_con) & XtIMTimer)
10325 XtAppProcessEvent (Xt_app_con, XtIMTimer);
10326 /* Reactivate the atimer for next time. */
10327 x_activate_timeout_atimer ();
10329 unblock_input ();
10332 /* Install an asynchronous timer that processes Xt timeout events
10333 every 0.1s as long as either `toolkit_scroll_bar_interaction' or
10334 `popup_activated_flag' (in xmenu.c) is set. Make sure to call this
10335 function whenever these variables are set. This is necessary
10336 because some widget sets use timeouts internally, for example the
10337 LessTif menu bar, or the Xaw3d scroll bar. When Xt timeouts aren't
10338 processed, these widgets don't behave normally. */
10340 void
10341 x_activate_timeout_atimer (void)
10343 block_input ();
10344 if (!x_timeout_atimer_activated_flag)
10346 struct timespec interval = make_timespec (0, 100 * 1000 * 1000);
10347 start_atimer (ATIMER_RELATIVE, interval, x_process_timeouts, 0);
10348 x_timeout_atimer_activated_flag = 1;
10350 unblock_input ();
10353 #endif /* USE_X_TOOLKIT */
10356 /* Set up use of X before we make the first connection. */
10358 static struct redisplay_interface x_redisplay_interface =
10360 x_frame_parm_handlers,
10361 x_produce_glyphs,
10362 x_write_glyphs,
10363 x_insert_glyphs,
10364 x_clear_end_of_line,
10365 x_scroll_run,
10366 x_after_update_window_line,
10367 x_update_window_begin,
10368 x_update_window_end,
10369 x_flush,
10370 x_clear_window_mouse_face,
10371 x_get_glyph_overhangs,
10372 x_fix_overlapping_area,
10373 x_draw_fringe_bitmap,
10374 0, /* define_fringe_bitmap */
10375 0, /* destroy_fringe_bitmap */
10376 x_compute_glyph_string_overhangs,
10377 x_draw_glyph_string,
10378 x_define_frame_cursor,
10379 x_clear_frame_area,
10380 x_draw_window_cursor,
10381 x_draw_vertical_window_border,
10382 x_draw_window_divider,
10383 x_shift_glyphs_for_insert
10387 /* This function is called when the last frame on a display is deleted. */
10388 void
10389 x_delete_terminal (struct terminal *terminal)
10391 struct x_display_info *dpyinfo = terminal->display_info.x;
10392 int connection = -1;
10394 /* Protect against recursive calls. delete_frame in
10395 delete_terminal calls us back when it deletes our last frame. */
10396 if (!terminal->name)
10397 return;
10399 block_input ();
10400 #ifdef HAVE_X_I18N
10401 /* We must close our connection to the XIM server before closing the
10402 X display. */
10403 if (dpyinfo->xim)
10404 xim_close_dpy (dpyinfo);
10405 #endif
10407 /* If called from x_connection_closed, the display may already be closed
10408 and dpyinfo->display was set to 0 to indicate that. */
10409 if (dpyinfo->display)
10411 connection = ConnectionNumber (dpyinfo->display);
10413 x_destroy_all_bitmaps (dpyinfo);
10414 XSetCloseDownMode (dpyinfo->display, DestroyAll);
10416 /* Whether or not XCloseDisplay destroys the associated resource
10417 database depends on the version of libX11. To avoid both
10418 crash and memory leak, we dissociate the database from the
10419 display and then destroy dpyinfo->xrdb ourselves.
10421 Unfortunately, the above strategy does not work in some
10422 situations due to a bug in newer versions of libX11: because
10423 XrmSetDatabase doesn't clear the flag XlibDisplayDfltRMDB if
10424 dpy->db is NULL, XCloseDisplay destroys the associated
10425 database whereas it has not been created by XGetDefault
10426 (Bug#21974 in freedesktop.org Bugzilla). As a workaround, we
10427 don't destroy the database here in order to avoid the crash
10428 in the above situations for now, though that may cause memory
10429 leaks in other situations. */
10430 #if 0
10431 #ifdef HAVE_XRMSETDATABASE
10432 XrmSetDatabase (dpyinfo->display, NULL);
10433 #else
10434 dpyinfo->display->db = NULL;
10435 #endif
10436 /* We used to call XrmDestroyDatabase from x_delete_display, but
10437 some older versions of libX11 crash if we call it after
10438 closing all the displays. */
10439 XrmDestroyDatabase (dpyinfo->xrdb);
10440 #endif
10442 #ifdef USE_GTK
10443 xg_display_close (dpyinfo->display);
10444 #else
10445 #ifdef USE_X_TOOLKIT
10446 XtCloseDisplay (dpyinfo->display);
10447 #else
10448 XCloseDisplay (dpyinfo->display);
10449 #endif
10450 #endif /* ! USE_GTK */
10453 /* No more input on this descriptor. */
10454 if (connection != -1)
10455 delete_keyboard_wait_descriptor (connection);
10457 /* Mark as dead. */
10458 dpyinfo->display = NULL;
10459 x_delete_display (dpyinfo);
10460 unblock_input ();
10463 /* Create a struct terminal, initialize it with the X11 specific
10464 functions and make DISPLAY->TERMINAL point to it. */
10466 static struct terminal *
10467 x_create_terminal (struct x_display_info *dpyinfo)
10469 struct terminal *terminal;
10471 terminal = create_terminal ();
10473 terminal->type = output_x_window;
10474 terminal->display_info.x = dpyinfo;
10475 dpyinfo->terminal = terminal;
10477 /* kboard is initialized in x_term_init. */
10479 terminal->clear_frame_hook = x_clear_frame;
10480 terminal->ins_del_lines_hook = x_ins_del_lines;
10481 terminal->delete_glyphs_hook = x_delete_glyphs;
10482 terminal->ring_bell_hook = XTring_bell;
10483 terminal->toggle_invisible_pointer_hook = XTtoggle_invisible_pointer;
10484 terminal->reset_terminal_modes_hook = NULL;
10485 terminal->set_terminal_modes_hook = NULL;
10486 terminal->update_begin_hook = x_update_begin;
10487 terminal->update_end_hook = x_update_end;
10488 terminal->set_terminal_window_hook = NULL;
10489 terminal->read_socket_hook = XTread_socket;
10490 terminal->frame_up_to_date_hook = XTframe_up_to_date;
10491 terminal->mouse_position_hook = XTmouse_position;
10492 terminal->frame_rehighlight_hook = XTframe_rehighlight;
10493 terminal->frame_raise_lower_hook = XTframe_raise_lower;
10494 terminal->fullscreen_hook = XTfullscreen_hook;
10495 terminal->set_vertical_scroll_bar_hook = XTset_vertical_scroll_bar;
10496 terminal->condemn_scroll_bars_hook = XTcondemn_scroll_bars;
10497 terminal->redeem_scroll_bar_hook = XTredeem_scroll_bar;
10498 terminal->judge_scroll_bars_hook = XTjudge_scroll_bars;
10500 terminal->delete_frame_hook = x_destroy_window;
10501 terminal->delete_terminal_hook = x_delete_terminal;
10503 terminal->rif = &x_redisplay_interface;
10505 return terminal;
10508 void
10509 x_initialize (void)
10511 baud_rate = 19200;
10513 x_noop_count = 0;
10514 last_tool_bar_item = -1;
10515 any_help_event_p = 0;
10516 ignore_next_mouse_click_timeout = 0;
10518 #ifdef USE_GTK
10519 current_count = -1;
10520 #endif
10522 /* Try to use interrupt input; if we can't, then start polling. */
10523 Fset_input_interrupt_mode (Qt);
10525 #ifdef USE_X_TOOLKIT
10526 XtToolkitInitialize ();
10528 Xt_app_con = XtCreateApplicationContext ();
10530 /* Register a converter from strings to pixels, which uses
10531 Emacs' color allocation infrastructure. */
10532 XtAppSetTypeConverter (Xt_app_con,
10533 XtRString, XtRPixel, cvt_string_to_pixel,
10534 cvt_string_to_pixel_args,
10535 XtNumber (cvt_string_to_pixel_args),
10536 XtCacheByDisplay, cvt_pixel_dtor);
10538 XtAppSetFallbackResources (Xt_app_con, Xt_default_resources);
10539 #endif
10541 #ifdef USE_TOOLKIT_SCROLL_BARS
10542 #ifndef USE_GTK
10543 xaw3d_arrow_scroll = False;
10544 xaw3d_pick_top = True;
10545 #endif
10546 #endif
10548 /* Note that there is no real way portable across R3/R4 to get the
10549 original error handler. */
10550 XSetErrorHandler (x_error_handler);
10551 XSetIOErrorHandler (x_io_error_quitter);
10555 void
10556 syms_of_xterm (void)
10558 x_error_message = NULL;
10560 DEFSYM (Qvendor_specific_keysyms, "vendor-specific-keysyms");
10561 DEFSYM (Qlatin_1, "latin-1");
10563 #ifdef USE_GTK
10564 xg_default_icon_file = build_pure_c_string ("icons/hicolor/scalable/apps/emacs.svg");
10565 staticpro (&xg_default_icon_file);
10567 DEFSYM (Qx_gtk_map_stock, "x-gtk-map-stock");
10568 #endif
10570 DEFVAR_BOOL ("x-use-underline-position-properties",
10571 x_use_underline_position_properties,
10572 doc: /* Non-nil means make use of UNDERLINE_POSITION font properties.
10573 A value of nil means ignore them. If you encounter fonts with bogus
10574 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
10575 to 4.1, set this to nil. You can also use `underline-minimum-offset'
10576 to override the font's UNDERLINE_POSITION for small font display
10577 sizes. */);
10578 x_use_underline_position_properties = 1;
10580 DEFVAR_BOOL ("x-underline-at-descent-line",
10581 x_underline_at_descent_line,
10582 doc: /* Non-nil means to draw the underline at the same place as the descent line.
10583 A value of nil means to draw the underline according to the value of the
10584 variable `x-use-underline-position-properties', which is usually at the
10585 baseline level. The default value is nil. */);
10586 x_underline_at_descent_line = 0;
10588 DEFVAR_BOOL ("x-mouse-click-focus-ignore-position",
10589 x_mouse_click_focus_ignore_position,
10590 doc: /* Non-nil means that a mouse click to focus a frame does not move point.
10591 This variable is only used when the window manager requires that you
10592 click on a frame to select it (give it focus). In that case, a value
10593 of nil, means that the selected window and cursor position changes to
10594 reflect the mouse click position, while a non-nil value means that the
10595 selected window or cursor position is preserved. */);
10596 x_mouse_click_focus_ignore_position = 0;
10598 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
10599 doc: /* Which toolkit scroll bars Emacs uses, if any.
10600 A value of nil means Emacs doesn't use toolkit scroll bars.
10601 With the X Window system, the value is a symbol describing the
10602 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
10603 With MS Windows or Nextstep, the value is t. */);
10604 #ifdef USE_TOOLKIT_SCROLL_BARS
10605 #ifdef USE_MOTIF
10606 Vx_toolkit_scroll_bars = intern_c_string ("motif");
10607 #elif defined HAVE_XAW3D
10608 Vx_toolkit_scroll_bars = intern_c_string ("xaw3d");
10609 #elif USE_GTK
10610 Vx_toolkit_scroll_bars = intern_c_string ("gtk");
10611 #else
10612 Vx_toolkit_scroll_bars = intern_c_string ("xaw");
10613 #endif
10614 #else
10615 Vx_toolkit_scroll_bars = Qnil;
10616 #endif
10618 DEFSYM (Qmodifier_value, "modifier-value");
10619 DEFSYM (Qalt, "alt");
10620 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
10621 DEFSYM (Qhyper, "hyper");
10622 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
10623 DEFSYM (Qmeta, "meta");
10624 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
10625 DEFSYM (Qsuper, "super");
10626 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
10628 DEFVAR_LISP ("x-alt-keysym", Vx_alt_keysym,
10629 doc: /* Which keys Emacs uses for the alt modifier.
10630 This should be one of the symbols `alt', `hyper', `meta', `super'.
10631 For example, `alt' means use the Alt_L and Alt_R keysyms. The default
10632 is nil, which is the same as `alt'. */);
10633 Vx_alt_keysym = Qnil;
10635 DEFVAR_LISP ("x-hyper-keysym", Vx_hyper_keysym,
10636 doc: /* Which keys Emacs uses for the hyper modifier.
10637 This should be one of the symbols `alt', `hyper', `meta', `super'.
10638 For example, `hyper' means use the Hyper_L and Hyper_R keysyms. The
10639 default is nil, which is the same as `hyper'. */);
10640 Vx_hyper_keysym = Qnil;
10642 DEFVAR_LISP ("x-meta-keysym", Vx_meta_keysym,
10643 doc: /* Which keys Emacs uses for the meta modifier.
10644 This should be one of the symbols `alt', `hyper', `meta', `super'.
10645 For example, `meta' means use the Meta_L and Meta_R keysyms. The
10646 default is nil, which is the same as `meta'. */);
10647 Vx_meta_keysym = Qnil;
10649 DEFVAR_LISP ("x-super-keysym", Vx_super_keysym,
10650 doc: /* Which keys Emacs uses for the super modifier.
10651 This should be one of the symbols `alt', `hyper', `meta', `super'.
10652 For example, `super' means use the Super_L and Super_R keysyms. The
10653 default is nil, which is the same as `super'. */);
10654 Vx_super_keysym = Qnil;
10656 DEFVAR_LISP ("x-keysym-table", Vx_keysym_table,
10657 doc: /* Hash table of character codes indexed by X keysym codes. */);
10658 Vx_keysym_table = make_hash_table (hashtest_eql, make_number (900),
10659 make_float (DEFAULT_REHASH_SIZE),
10660 make_float (DEFAULT_REHASH_THRESHOLD),
10661 Qnil);