* alloc.c (valgrind_p): Use bool for boolean.
[emacs.git] / src / xterm.c
blob1ccc1ae649b318af068f9350b3537cadc68eca5d
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 /* This is a list of cons cells, each of the form (NAME
152 . FONT-LIST-CACHE), one for each element of x_display_list and in
153 the same order. NAME is the name of the frame. FONT-LIST-CACHE
154 records previous values returned by x-list-fonts. */
156 Lisp_Object x_display_name_list;
158 #ifdef USE_X_TOOLKIT
160 /* The application context for Xt use. */
161 XtAppContext Xt_app_con;
162 static String Xt_default_resources[] = {0};
164 /* Non-zero means user is interacting with a toolkit scroll bar. */
165 static bool toolkit_scroll_bar_interaction;
167 #endif /* USE_X_TOOLKIT */
169 /* Non-zero timeout value means ignore next mouse click if it arrives
170 before that timeout elapses (i.e. as part of the same sequence of
171 events resulting from clicking on a frame to select it). */
173 static Time ignore_next_mouse_click_timeout;
175 /* Incremented by XTread_socket whenever it really tries to read
176 events. */
178 static int volatile input_signal_count;
180 /* Used locally within XTread_socket. */
182 static int x_noop_count;
184 static Lisp_Object Qalt, Qhyper, Qmeta, Qsuper, Qmodifier_value;
186 static Lisp_Object Qvendor_specific_keysyms;
187 static Lisp_Object Qlatin_1;
189 #ifdef USE_GTK
190 /* The name of the Emacs icon file. */
191 static Lisp_Object xg_default_icon_file;
193 /* Used in gtkutil.c. */
194 Lisp_Object Qx_gtk_map_stock;
195 #endif
197 /* Some functions take this as char *, not const char *. */
198 static char emacs_class[] = EMACS_CLASS;
200 enum xembed_info
202 XEMBED_MAPPED = 1 << 0
205 enum xembed_message
207 XEMBED_EMBEDDED_NOTIFY = 0,
208 XEMBED_WINDOW_ACTIVATE = 1,
209 XEMBED_WINDOW_DEACTIVATE = 2,
210 XEMBED_REQUEST_FOCUS = 3,
211 XEMBED_FOCUS_IN = 4,
212 XEMBED_FOCUS_OUT = 5,
213 XEMBED_FOCUS_NEXT = 6,
214 XEMBED_FOCUS_PREV = 7,
216 XEMBED_MODALITY_ON = 10,
217 XEMBED_MODALITY_OFF = 11,
218 XEMBED_REGISTER_ACCELERATOR = 12,
219 XEMBED_UNREGISTER_ACCELERATOR = 13,
220 XEMBED_ACTIVATE_ACCELERATOR = 14
223 static bool x_alloc_nearest_color_1 (Display *, Colormap, XColor *);
224 static void x_set_window_size_1 (struct frame *, int, int, int);
225 static void x_raise_frame (struct frame *);
226 static void x_lower_frame (struct frame *);
227 static const XColor *x_color_cells (Display *, int *);
228 static int x_io_error_quitter (Display *);
229 static struct terminal *x_create_terminal (struct x_display_info *);
230 void x_delete_terminal (struct terminal *);
231 static void x_update_end (struct frame *);
232 static void XTframe_up_to_date (struct frame *);
233 static void x_clear_frame (struct frame *);
234 static _Noreturn void x_ins_del_lines (struct frame *, int, int);
235 static void frame_highlight (struct frame *);
236 static void frame_unhighlight (struct frame *);
237 static void x_new_focus_frame (struct x_display_info *, struct frame *);
238 static void x_focus_changed (int, int, struct x_display_info *,
239 struct frame *, struct input_event *);
240 static void XTframe_rehighlight (struct frame *);
241 static void x_frame_rehighlight (struct x_display_info *);
242 static void x_draw_hollow_cursor (struct window *, struct glyph_row *);
243 static void x_draw_bar_cursor (struct window *, struct glyph_row *, int,
244 enum text_cursor_kinds);
246 static void x_clip_to_row (struct window *, struct glyph_row *,
247 enum glyph_row_area, GC);
248 static void x_flush (struct frame *f);
249 static void x_update_begin (struct frame *);
250 static void x_update_window_begin (struct window *);
251 static struct scroll_bar *x_window_to_scroll_bar (Display *, Window);
252 static void x_scroll_bar_report_motion (struct frame **, Lisp_Object *,
253 enum scroll_bar_part *,
254 Lisp_Object *, Lisp_Object *,
255 Time *);
256 static int x_handle_net_wm_state (struct frame *, const XPropertyEvent *);
257 static void x_check_fullscreen (struct frame *);
258 static void x_check_expected_move (struct frame *, int, int);
259 static void x_sync_with_move (struct frame *, int, int, int);
260 static int handle_one_xevent (struct x_display_info *,
261 const XEvent *, int *,
262 struct input_event *);
263 #ifdef USE_GTK
264 static int x_dispatch_event (XEvent *, Display *);
265 #endif
266 /* Don't declare this _Noreturn because we want no
267 interference with debugging failing X calls. */
268 static void x_connection_closed (Display *, const char *);
269 static void x_wm_set_window_state (struct frame *, int);
270 static void x_wm_set_icon_pixmap (struct frame *, ptrdiff_t);
271 static void x_initialize (void);
274 /* Flush display of frame F. */
276 static void
277 x_flush (struct frame *f)
279 eassert (f && FRAME_X_P (f));
280 /* Don't call XFlush when it is not safe to redisplay; the X
281 connection may be broken. */
282 if (!NILP (Vinhibit_redisplay))
283 return;
285 block_input ();
286 XFlush (FRAME_X_DISPLAY (f));
287 unblock_input ();
291 /* Remove calls to XFlush by defining XFlush to an empty replacement.
292 Calls to XFlush should be unnecessary because the X output buffer
293 is flushed automatically as needed by calls to XPending,
294 XNextEvent, or XWindowEvent according to the XFlush man page.
295 XTread_socket calls XPending. Removing XFlush improves
296 performance. */
298 #define XFlush(DISPLAY) (void) 0
301 /***********************************************************************
302 Debugging
303 ***********************************************************************/
305 #if 0
307 /* This is a function useful for recording debugging information about
308 the sequence of occurrences in this file. */
310 struct record
312 char *locus;
313 int type;
316 struct record event_record[100];
318 int event_record_index;
320 void
321 record_event (char *locus, int type)
323 if (event_record_index == sizeof (event_record) / sizeof (struct record))
324 event_record_index = 0;
326 event_record[event_record_index].locus = locus;
327 event_record[event_record_index].type = type;
328 event_record_index++;
331 #endif /* 0 */
335 /* Return the struct x_display_info corresponding to DPY. */
337 struct x_display_info *
338 x_display_info_for_display (Display *dpy)
340 struct x_display_info *dpyinfo;
342 for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
343 if (dpyinfo->display == dpy)
344 return dpyinfo;
346 return 0;
349 static Window
350 x_find_topmost_parent (struct frame *f)
352 struct x_output *x = f->output_data.x;
353 Window win = None, wi = x->parent_desc;
354 Display *dpy = FRAME_X_DISPLAY (f);
356 while (wi != FRAME_DISPLAY_INFO (f)->root_window)
358 Window root;
359 Window *children;
360 unsigned int nchildren;
362 win = wi;
363 XQueryTree (dpy, win, &root, &wi, &children, &nchildren);
364 XFree (children);
367 return win;
370 #define OPAQUE 0xffffffff
372 void
373 x_set_frame_alpha (struct frame *f)
375 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
376 Display *dpy = FRAME_X_DISPLAY (f);
377 Window win = FRAME_OUTER_WINDOW (f);
378 double alpha = 1.0;
379 double alpha_min = 1.0;
380 unsigned long opac;
381 Window parent;
383 if (dpyinfo->x_highlight_frame == f)
384 alpha = f->alpha[0];
385 else
386 alpha = f->alpha[1];
388 if (FLOATP (Vframe_alpha_lower_limit))
389 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
390 else if (INTEGERP (Vframe_alpha_lower_limit))
391 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
393 if (alpha < 0.0)
394 return;
395 else if (alpha > 1.0)
396 alpha = 1.0;
397 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
398 alpha = alpha_min;
400 opac = alpha * OPAQUE;
402 x_catch_errors (dpy);
404 /* If there is a parent from the window manager, put the property there
405 also, to work around broken window managers that fail to do that.
406 Do this unconditionally as this function is called on reparent when
407 alpha has not changed on the frame. */
409 parent = x_find_topmost_parent (f);
410 if (parent != None)
411 XChangeProperty (dpy, parent, dpyinfo->Xatom_net_wm_window_opacity,
412 XA_CARDINAL, 32, PropModeReplace,
413 (unsigned char *) &opac, 1L);
415 /* return unless necessary */
417 unsigned char *data;
418 Atom actual;
419 int rc, format;
420 unsigned long n, left;
422 rc = XGetWindowProperty (dpy, win, dpyinfo->Xatom_net_wm_window_opacity,
423 0L, 1L, False, XA_CARDINAL,
424 &actual, &format, &n, &left,
425 &data);
427 if (rc == Success && actual != None)
429 unsigned long value = *(unsigned long *)data;
430 XFree (data);
431 if (value == opac)
433 x_uncatch_errors ();
434 return;
439 XChangeProperty (dpy, win, dpyinfo->Xatom_net_wm_window_opacity,
440 XA_CARDINAL, 32, PropModeReplace,
441 (unsigned char *) &opac, 1L);
442 x_uncatch_errors ();
446 x_display_pixel_height (struct x_display_info *dpyinfo)
448 return HeightOfScreen (dpyinfo->screen);
452 x_display_pixel_width (struct x_display_info *dpyinfo)
454 return WidthOfScreen (dpyinfo->screen);
458 /***********************************************************************
459 Starting and ending an update
460 ***********************************************************************/
462 /* Start an update of frame F. This function is installed as a hook
463 for update_begin, i.e. it is called when update_begin is called.
464 This function is called prior to calls to x_update_window_begin for
465 each window being updated. Currently, there is nothing to do here
466 because all interesting stuff is done on a window basis. */
468 static void
469 x_update_begin (struct frame *f)
471 /* Nothing to do. */
475 /* Start update of window W. */
477 static void
478 x_update_window_begin (struct window *w)
480 struct frame *f = XFRAME (WINDOW_FRAME (w));
481 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
483 w->output_cursor = w->cursor;
485 block_input ();
487 if (f == hlinfo->mouse_face_mouse_frame)
489 /* Don't do highlighting for mouse motion during the update. */
490 hlinfo->mouse_face_defer = 1;
492 /* If F needs to be redrawn, simply forget about any prior mouse
493 highlighting. */
494 if (FRAME_GARBAGED_P (f))
495 hlinfo->mouse_face_window = Qnil;
498 unblock_input ();
502 /* Draw a vertical window border from (x,y0) to (x,y1) */
504 static void
505 x_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
507 struct frame *f = XFRAME (WINDOW_FRAME (w));
508 struct face *face;
510 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
511 if (face)
512 XSetForeground (FRAME_X_DISPLAY (f), f->output_data.x->normal_gc,
513 face->foreground);
515 XDrawLine (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
516 f->output_data.x->normal_gc, x, y0, x, y1);
519 /* End update of window W.
521 Draw vertical borders between horizontally adjacent windows, and
522 display W's cursor if CURSOR_ON_P is non-zero.
524 MOUSE_FACE_OVERWRITTEN_P non-zero means that some row containing
525 glyphs in mouse-face were overwritten. In that case we have to
526 make sure that the mouse-highlight is properly redrawn.
528 W may be a menu bar pseudo-window in case we don't have X toolkit
529 support. Such windows don't have a cursor, so don't display it
530 here. */
532 static void
533 x_update_window_end (struct window *w, bool cursor_on_p,
534 bool mouse_face_overwritten_p)
536 if (!w->pseudo_window_p)
538 block_input ();
540 if (cursor_on_p)
541 display_and_set_cursor (w, 1,
542 w->output_cursor.hpos, w->output_cursor.vpos,
543 w->output_cursor.x, w->output_cursor.y);
545 if (draw_window_fringes (w, 1))
546 x_draw_vertical_border (w);
548 unblock_input ();
551 /* If a row with mouse-face was overwritten, arrange for
552 XTframe_up_to_date to redisplay the mouse highlight. */
553 if (mouse_face_overwritten_p)
554 reset_mouse_highlight (MOUSE_HL_INFO (XFRAME (w->frame)));
558 /* End update of frame F. This function is installed as a hook in
559 update_end. */
561 static void
562 x_update_end (struct frame *f)
564 /* Mouse highlight may be displayed again. */
565 MOUSE_HL_INFO (f)->mouse_face_defer = 0;
567 #ifndef XFlush
568 block_input ();
569 XFlush (FRAME_X_DISPLAY (f));
570 unblock_input ();
571 #endif
575 /* This function is called from various places in xdisp.c
576 whenever a complete update has been performed. */
578 static void
579 XTframe_up_to_date (struct frame *f)
581 if (FRAME_X_P (f))
582 FRAME_MOUSE_UPDATE (f);
586 /* Draw truncation mark bitmaps, continuation mark bitmaps, overlay
587 arrow bitmaps, or clear the fringes if no bitmaps are required
588 before DESIRED_ROW is made current. This function is called from
589 update_window_line only if it is known that there are differences
590 between bitmaps to be drawn between current row and DESIRED_ROW. */
592 static void
593 x_after_update_window_line (struct window *w, struct glyph_row *desired_row)
595 struct frame *f;
596 int width, height;
598 eassert (w);
600 if (!desired_row->mode_line_p && !w->pseudo_window_p)
601 desired_row->redraw_fringe_bitmaps_p = 1;
603 /* When a window has disappeared, make sure that no rest of
604 full-width rows stays visible in the internal border. Could
605 check here if updated window is the leftmost/rightmost window,
606 but I guess it's not worth doing since vertically split windows
607 are almost never used, internal border is rarely set, and the
608 overhead is very small. */
609 if (windows_or_buffers_changed
610 && desired_row->full_width_p
611 && (f = XFRAME (w->frame),
612 width = FRAME_INTERNAL_BORDER_WIDTH (f),
613 width != 0)
614 && (height = desired_row->visible_height,
615 height > 0))
617 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
619 block_input ();
620 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
621 0, y, width, height);
622 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
623 FRAME_PIXEL_WIDTH (f) - width,
624 y, width, height);
625 unblock_input ();
629 static void
630 x_draw_fringe_bitmap (struct window *w, struct glyph_row *row, struct draw_fringe_bitmap_params *p)
632 struct frame *f = XFRAME (WINDOW_FRAME (w));
633 Display *display = FRAME_X_DISPLAY (f);
634 Window window = FRAME_X_WINDOW (f);
635 GC gc = f->output_data.x->normal_gc;
636 struct face *face = p->face;
638 /* Must clip because of partially visible lines. */
639 x_clip_to_row (w, row, ANY_AREA, gc);
641 if (!p->overlay_p)
643 int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
645 /* In case the same realized face is used for fringes and
646 for something displayed in the text (e.g. face `region' on
647 mono-displays, the fill style may have been changed to
648 FillSolid in x_draw_glyph_string_background. */
649 if (face->stipple)
650 XSetFillStyle (display, face->gc, FillOpaqueStippled);
651 else
652 XSetForeground (display, face->gc, face->background);
654 #ifdef USE_TOOLKIT_SCROLL_BARS
655 /* If the fringe is adjacent to the left (right) scroll bar of a
656 leftmost (rightmost, respectively) window, then extend its
657 background to the gap between the fringe and the bar. */
658 if ((WINDOW_LEFTMOST_P (w)
659 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
660 || (WINDOW_RIGHTMOST_P (w)
661 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w)))
663 int sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
665 if (sb_width > 0)
667 int bar_area_x = WINDOW_SCROLL_BAR_AREA_X (w);
668 int bar_area_width = (WINDOW_CONFIG_SCROLL_BAR_COLS (w)
669 * FRAME_COLUMN_WIDTH (f));
671 if (bx < 0)
673 /* Bitmap fills the fringe. */
674 if (bar_area_x + bar_area_width == p->x)
675 bx = bar_area_x + sb_width;
676 else if (p->x + p->wd == bar_area_x)
677 bx = bar_area_x;
678 if (bx >= 0)
680 int header_line_height = WINDOW_HEADER_LINE_HEIGHT (w);
682 nx = bar_area_width - sb_width;
683 by = WINDOW_TO_FRAME_PIXEL_Y (w, max (header_line_height,
684 row->y));
685 ny = row->visible_height;
688 else
690 if (bar_area_x + bar_area_width == bx)
692 bx = bar_area_x + sb_width;
693 nx += bar_area_width - sb_width;
695 else if (bx + nx == bar_area_x)
696 nx += bar_area_width - sb_width;
700 #endif
701 if (bx >= 0 && nx > 0)
702 XFillRectangle (display, window, face->gc, bx, by, nx, ny);
704 if (!face->stipple)
705 XSetForeground (display, face->gc, face->foreground);
708 if (p->which)
710 char *bits;
711 Pixmap pixmap, clipmask = (Pixmap) 0;
712 int depth = DefaultDepthOfScreen (FRAME_X_SCREEN (f));
713 XGCValues gcv;
715 if (p->wd > 8)
716 bits = (char *) (p->bits + p->dh);
717 else
718 bits = (char *) p->bits + p->dh;
720 /* Draw the bitmap. I believe these small pixmaps can be cached
721 by the server. */
722 pixmap = XCreatePixmapFromBitmapData (display, window, bits, p->wd, p->h,
723 (p->cursor_p
724 ? (p->overlay_p ? face->background
725 : f->output_data.x->cursor_pixel)
726 : face->foreground),
727 face->background, depth);
729 if (p->overlay_p)
731 clipmask = XCreatePixmapFromBitmapData (display,
732 FRAME_DISPLAY_INFO (f)->root_window,
733 bits, p->wd, p->h,
734 1, 0, 1);
735 gcv.clip_mask = clipmask;
736 gcv.clip_x_origin = p->x;
737 gcv.clip_y_origin = p->y;
738 XChangeGC (display, gc, GCClipMask | GCClipXOrigin | GCClipYOrigin, &gcv);
741 XCopyArea (display, pixmap, window, gc, 0, 0,
742 p->wd, p->h, p->x, p->y);
743 XFreePixmap (display, pixmap);
745 if (p->overlay_p)
747 gcv.clip_mask = (Pixmap) 0;
748 XChangeGC (display, gc, GCClipMask, &gcv);
749 XFreePixmap (display, clipmask);
753 XSetClipMask (display, gc, None);
756 /***********************************************************************
757 Glyph display
758 ***********************************************************************/
762 static void x_set_glyph_string_clipping (struct glyph_string *);
763 static void x_set_glyph_string_gc (struct glyph_string *);
764 static void x_draw_glyph_string_foreground (struct glyph_string *);
765 static void x_draw_composite_glyph_string_foreground (struct glyph_string *);
766 static void x_draw_glyph_string_box (struct glyph_string *);
767 static void x_draw_glyph_string (struct glyph_string *);
768 static _Noreturn void x_delete_glyphs (struct frame *, int);
769 static void x_compute_glyph_string_overhangs (struct glyph_string *);
770 static void x_set_cursor_gc (struct glyph_string *);
771 static void x_set_mode_line_face_gc (struct glyph_string *);
772 static void x_set_mouse_face_gc (struct glyph_string *);
773 static bool x_alloc_lighter_color (struct frame *, Display *, Colormap,
774 unsigned long *, double, int);
775 static void x_setup_relief_color (struct frame *, struct relief *,
776 double, int, unsigned long);
777 static void x_setup_relief_colors (struct glyph_string *);
778 static void x_draw_image_glyph_string (struct glyph_string *);
779 static void x_draw_image_relief (struct glyph_string *);
780 static void x_draw_image_foreground (struct glyph_string *);
781 static void x_draw_image_foreground_1 (struct glyph_string *, Pixmap);
782 static void x_clear_glyph_string_rect (struct glyph_string *, int,
783 int, int, int);
784 static void x_draw_relief_rect (struct frame *, int, int, int, int,
785 int, int, int, int, int, int,
786 XRectangle *);
787 static void x_draw_box_rect (struct glyph_string *, int, int, int, int,
788 int, int, int, XRectangle *);
789 static void x_scroll_bar_clear (struct frame *);
791 #ifdef GLYPH_DEBUG
792 static void x_check_font (struct frame *, struct font *);
793 #endif
796 /* Set S->gc to a suitable GC for drawing glyph string S in cursor
797 face. */
799 static void
800 x_set_cursor_gc (struct glyph_string *s)
802 if (s->font == FRAME_FONT (s->f)
803 && s->face->background == FRAME_BACKGROUND_PIXEL (s->f)
804 && s->face->foreground == FRAME_FOREGROUND_PIXEL (s->f)
805 && !s->cmp)
806 s->gc = s->f->output_data.x->cursor_gc;
807 else
809 /* Cursor on non-default face: must merge. */
810 XGCValues xgcv;
811 unsigned long mask;
813 xgcv.background = s->f->output_data.x->cursor_pixel;
814 xgcv.foreground = s->face->background;
816 /* If the glyph would be invisible, try a different foreground. */
817 if (xgcv.foreground == xgcv.background)
818 xgcv.foreground = s->face->foreground;
819 if (xgcv.foreground == xgcv.background)
820 xgcv.foreground = s->f->output_data.x->cursor_foreground_pixel;
821 if (xgcv.foreground == xgcv.background)
822 xgcv.foreground = s->face->foreground;
824 /* Make sure the cursor is distinct from text in this face. */
825 if (xgcv.background == s->face->background
826 && xgcv.foreground == s->face->foreground)
828 xgcv.background = s->face->foreground;
829 xgcv.foreground = s->face->background;
832 IF_DEBUG (x_check_font (s->f, s->font));
833 xgcv.graphics_exposures = False;
834 mask = GCForeground | GCBackground | GCGraphicsExposures;
836 if (FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc)
837 XChangeGC (s->display, FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc,
838 mask, &xgcv);
839 else
840 FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc
841 = XCreateGC (s->display, s->window, mask, &xgcv);
843 s->gc = FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc;
848 /* Set up S->gc of glyph string S for drawing text in mouse face. */
850 static void
851 x_set_mouse_face_gc (struct glyph_string *s)
853 int face_id;
854 struct face *face;
856 /* What face has to be used last for the mouse face? */
857 face_id = MOUSE_HL_INFO (s->f)->mouse_face_face_id;
858 face = FACE_FROM_ID (s->f, face_id);
859 if (face == NULL)
860 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
862 if (s->first_glyph->type == CHAR_GLYPH)
863 face_id = FACE_FOR_CHAR (s->f, face, s->first_glyph->u.ch, -1, Qnil);
864 else
865 face_id = FACE_FOR_CHAR (s->f, face, 0, -1, Qnil);
866 s->face = FACE_FROM_ID (s->f, face_id);
867 PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
869 if (s->font == s->face->font)
870 s->gc = s->face->gc;
871 else
873 /* Otherwise construct scratch_cursor_gc with values from FACE
874 except for FONT. */
875 XGCValues xgcv;
876 unsigned long mask;
878 xgcv.background = s->face->background;
879 xgcv.foreground = s->face->foreground;
880 xgcv.graphics_exposures = False;
881 mask = GCForeground | GCBackground | GCGraphicsExposures;
883 if (FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc)
884 XChangeGC (s->display, FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc,
885 mask, &xgcv);
886 else
887 FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc
888 = XCreateGC (s->display, s->window, mask, &xgcv);
890 s->gc = FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc;
893 eassert (s->gc != 0);
897 /* Set S->gc of glyph string S to a GC suitable for drawing a mode line.
898 Faces to use in the mode line have already been computed when the
899 matrix was built, so there isn't much to do, here. */
901 static void
902 x_set_mode_line_face_gc (struct glyph_string *s)
904 s->gc = s->face->gc;
908 /* Set S->gc of glyph string S for drawing that glyph string. Set
909 S->stippled_p to a non-zero value if the face of S has a stipple
910 pattern. */
912 static void
913 x_set_glyph_string_gc (struct glyph_string *s)
915 PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
917 if (s->hl == DRAW_NORMAL_TEXT)
919 s->gc = s->face->gc;
920 s->stippled_p = s->face->stipple != 0;
922 else if (s->hl == DRAW_INVERSE_VIDEO)
924 x_set_mode_line_face_gc (s);
925 s->stippled_p = s->face->stipple != 0;
927 else if (s->hl == DRAW_CURSOR)
929 x_set_cursor_gc (s);
930 s->stippled_p = 0;
932 else if (s->hl == DRAW_MOUSE_FACE)
934 x_set_mouse_face_gc (s);
935 s->stippled_p = s->face->stipple != 0;
937 else if (s->hl == DRAW_IMAGE_RAISED
938 || s->hl == DRAW_IMAGE_SUNKEN)
940 s->gc = s->face->gc;
941 s->stippled_p = s->face->stipple != 0;
943 else
945 s->gc = s->face->gc;
946 s->stippled_p = s->face->stipple != 0;
949 /* GC must have been set. */
950 eassert (s->gc != 0);
954 /* Set clipping for output of glyph string S. S may be part of a mode
955 line or menu if we don't have X toolkit support. */
957 static void
958 x_set_glyph_string_clipping (struct glyph_string *s)
960 XRectangle *r = s->clip;
961 int n = get_glyph_string_clip_rects (s, r, 2);
963 if (n > 0)
964 XSetClipRectangles (s->display, s->gc, 0, 0, r, n, Unsorted);
965 s->num_clips = n;
969 /* Set SRC's clipping for output of glyph string DST. This is called
970 when we are drawing DST's left_overhang or right_overhang only in
971 the area of SRC. */
973 static void
974 x_set_glyph_string_clipping_exactly (struct glyph_string *src, struct glyph_string *dst)
976 XRectangle r;
978 r.x = src->x;
979 r.width = src->width;
980 r.y = src->y;
981 r.height = src->height;
982 dst->clip[0] = r;
983 dst->num_clips = 1;
984 XSetClipRectangles (dst->display, dst->gc, 0, 0, &r, 1, Unsorted);
988 /* RIF:
989 Compute left and right overhang of glyph string S. */
991 static void
992 x_compute_glyph_string_overhangs (struct glyph_string *s)
994 if (s->cmp == NULL
995 && (s->first_glyph->type == CHAR_GLYPH
996 || s->first_glyph->type == COMPOSITE_GLYPH))
998 struct font_metrics metrics;
1000 if (s->first_glyph->type == CHAR_GLYPH)
1002 unsigned *code = alloca (sizeof (unsigned) * s->nchars);
1003 struct font *font = s->font;
1004 int i;
1006 for (i = 0; i < s->nchars; i++)
1007 code[i] = (s->char2b[i].byte1 << 8) | s->char2b[i].byte2;
1008 font->driver->text_extents (font, code, s->nchars, &metrics);
1010 else
1012 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1014 composition_gstring_width (gstring, s->cmp_from, s->cmp_to, &metrics);
1016 s->right_overhang = (metrics.rbearing > metrics.width
1017 ? metrics.rbearing - metrics.width : 0);
1018 s->left_overhang = metrics.lbearing < 0 ? - metrics.lbearing : 0;
1020 else if (s->cmp)
1022 s->right_overhang = s->cmp->rbearing - s->cmp->pixel_width;
1023 s->left_overhang = - s->cmp->lbearing;
1028 /* Fill rectangle X, Y, W, H with background color of glyph string S. */
1030 static void
1031 x_clear_glyph_string_rect (struct glyph_string *s, int x, int y, int w, int h)
1033 XGCValues xgcv;
1034 XGetGCValues (s->display, s->gc, GCForeground | GCBackground, &xgcv);
1035 XSetForeground (s->display, s->gc, xgcv.background);
1036 XFillRectangle (s->display, s->window, s->gc, x, y, w, h);
1037 XSetForeground (s->display, s->gc, xgcv.foreground);
1041 /* Draw the background of glyph_string S. If S->background_filled_p
1042 is non-zero don't draw it. FORCE_P non-zero means draw the
1043 background even if it wouldn't be drawn normally. This is used
1044 when a string preceding S draws into the background of S, or S
1045 contains the first component of a composition. */
1047 static void
1048 x_draw_glyph_string_background (struct glyph_string *s, bool force_p)
1050 /* Nothing to do if background has already been drawn or if it
1051 shouldn't be drawn in the first place. */
1052 if (!s->background_filled_p)
1054 int box_line_width = max (s->face->box_line_width, 0);
1056 if (s->stippled_p)
1058 /* Fill background with a stipple pattern. */
1059 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
1060 XFillRectangle (s->display, s->window, s->gc, s->x,
1061 s->y + box_line_width,
1062 s->background_width,
1063 s->height - 2 * box_line_width);
1064 XSetFillStyle (s->display, s->gc, FillSolid);
1065 s->background_filled_p = 1;
1067 else if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
1068 || s->font_not_found_p
1069 || s->extends_to_end_of_line_p
1070 || force_p)
1072 x_clear_glyph_string_rect (s, s->x, s->y + box_line_width,
1073 s->background_width,
1074 s->height - 2 * box_line_width);
1075 s->background_filled_p = 1;
1081 /* Draw the foreground of glyph string S. */
1083 static void
1084 x_draw_glyph_string_foreground (struct glyph_string *s)
1086 int i, x;
1088 /* If first glyph of S has a left box line, start drawing the text
1089 of S to the right of that box line. */
1090 if (s->face->box != FACE_NO_BOX
1091 && s->first_glyph->left_box_line_p)
1092 x = s->x + eabs (s->face->box_line_width);
1093 else
1094 x = s->x;
1096 /* Draw characters of S as rectangles if S's font could not be
1097 loaded. */
1098 if (s->font_not_found_p)
1100 for (i = 0; i < s->nchars; ++i)
1102 struct glyph *g = s->first_glyph + i;
1103 XDrawRectangle (s->display, s->window,
1104 s->gc, x, s->y, g->pixel_width - 1,
1105 s->height - 1);
1106 x += g->pixel_width;
1109 else
1111 struct font *font = s->font;
1112 int boff = font->baseline_offset;
1113 int y;
1115 if (font->vertical_centering)
1116 boff = VCENTER_BASELINE_OFFSET (font, s->f) - boff;
1118 y = s->ybase - boff;
1119 if (s->for_overlaps
1120 || (s->background_filled_p && s->hl != DRAW_CURSOR))
1121 font->driver->draw (s, 0, s->nchars, x, y, 0);
1122 else
1123 font->driver->draw (s, 0, s->nchars, x, y, 1);
1124 if (s->face->overstrike)
1125 font->driver->draw (s, 0, s->nchars, x + 1, y, 0);
1129 /* Draw the foreground of composite glyph string S. */
1131 static void
1132 x_draw_composite_glyph_string_foreground (struct glyph_string *s)
1134 int i, j, x;
1135 struct font *font = s->font;
1137 /* If first glyph of S has a left box line, start drawing the text
1138 of S to the right of that box line. */
1139 if (s->face && s->face->box != FACE_NO_BOX
1140 && s->first_glyph->left_box_line_p)
1141 x = s->x + eabs (s->face->box_line_width);
1142 else
1143 x = s->x;
1145 /* S is a glyph string for a composition. S->cmp_from is the index
1146 of the first character drawn for glyphs of this composition.
1147 S->cmp_from == 0 means we are drawing the very first character of
1148 this composition. */
1150 /* Draw a rectangle for the composition if the font for the very
1151 first character of the composition could not be loaded. */
1152 if (s->font_not_found_p)
1154 if (s->cmp_from == 0)
1155 XDrawRectangle (s->display, s->window, s->gc, x, s->y,
1156 s->width - 1, s->height - 1);
1158 else if (! s->first_glyph->u.cmp.automatic)
1160 int y = s->ybase;
1162 for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
1163 /* TAB in a composition means display glyphs with padding
1164 space on the left or right. */
1165 if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
1167 int xx = x + s->cmp->offsets[j * 2];
1168 int yy = y - s->cmp->offsets[j * 2 + 1];
1170 font->driver->draw (s, j, j + 1, xx, yy, 0);
1171 if (s->face->overstrike)
1172 font->driver->draw (s, j, j + 1, xx + 1, yy, 0);
1175 else
1177 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1178 Lisp_Object glyph;
1179 int y = s->ybase;
1180 int width = 0;
1182 for (i = j = s->cmp_from; i < s->cmp_to; i++)
1184 glyph = LGSTRING_GLYPH (gstring, i);
1185 if (NILP (LGLYPH_ADJUSTMENT (glyph)))
1186 width += LGLYPH_WIDTH (glyph);
1187 else
1189 int xoff, yoff, wadjust;
1191 if (j < i)
1193 font->driver->draw (s, j, i, x, y, 0);
1194 if (s->face->overstrike)
1195 font->driver->draw (s, j, i, x + 1, y, 0);
1196 x += width;
1198 xoff = LGLYPH_XOFF (glyph);
1199 yoff = LGLYPH_YOFF (glyph);
1200 wadjust = LGLYPH_WADJUST (glyph);
1201 font->driver->draw (s, i, i + 1, x + xoff, y + yoff, 0);
1202 if (s->face->overstrike)
1203 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff, 0);
1204 x += wadjust;
1205 j = i + 1;
1206 width = 0;
1209 if (j < i)
1211 font->driver->draw (s, j, i, x, y, 0);
1212 if (s->face->overstrike)
1213 font->driver->draw (s, j, i, x + 1, y, 0);
1219 /* Draw the foreground of glyph string S for glyphless characters. */
1221 static void
1222 x_draw_glyphless_glyph_string_foreground (struct glyph_string *s)
1224 struct glyph *glyph = s->first_glyph;
1225 XChar2b char2b[8];
1226 int x, i, j;
1228 /* If first glyph of S has a left box line, start drawing the text
1229 of S to the right of that box line. */
1230 if (s->face && s->face->box != FACE_NO_BOX
1231 && s->first_glyph->left_box_line_p)
1232 x = s->x + eabs (s->face->box_line_width);
1233 else
1234 x = s->x;
1236 s->char2b = char2b;
1238 for (i = 0; i < s->nchars; i++, glyph++)
1240 char buf[7], *str = NULL;
1241 int len = glyph->u.glyphless.len;
1243 if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_ACRONYM)
1245 if (len > 0
1246 && CHAR_TABLE_P (Vglyphless_char_display)
1247 && (CHAR_TABLE_EXTRA_SLOTS (XCHAR_TABLE (Vglyphless_char_display))
1248 >= 1))
1250 Lisp_Object acronym
1251 = (! glyph->u.glyphless.for_no_font
1252 ? CHAR_TABLE_REF (Vglyphless_char_display,
1253 glyph->u.glyphless.ch)
1254 : XCHAR_TABLE (Vglyphless_char_display)->extras[0]);
1255 if (STRINGP (acronym))
1256 str = SSDATA (acronym);
1259 else if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_HEX_CODE)
1261 sprintf (buf, "%0*X",
1262 glyph->u.glyphless.ch < 0x10000 ? 4 : 6,
1263 glyph->u.glyphless.ch);
1264 str = buf;
1267 if (str)
1269 int upper_len = (len + 1) / 2;
1270 unsigned code;
1272 /* It is assured that all LEN characters in STR is ASCII. */
1273 for (j = 0; j < len; j++)
1275 code = s->font->driver->encode_char (s->font, str[j]);
1276 STORE_XCHAR2B (char2b + j, code >> 8, code & 0xFF);
1278 s->font->driver->draw (s, 0, upper_len,
1279 x + glyph->slice.glyphless.upper_xoff,
1280 s->ybase + glyph->slice.glyphless.upper_yoff,
1282 s->font->driver->draw (s, upper_len, len,
1283 x + glyph->slice.glyphless.lower_xoff,
1284 s->ybase + glyph->slice.glyphless.lower_yoff,
1287 if (glyph->u.glyphless.method != GLYPHLESS_DISPLAY_THIN_SPACE)
1288 XDrawRectangle (s->display, s->window, s->gc,
1289 x, s->ybase - glyph->ascent,
1290 glyph->pixel_width - 1,
1291 glyph->ascent + glyph->descent - 1);
1292 x += glyph->pixel_width;
1296 #ifdef USE_X_TOOLKIT
1298 #ifdef USE_LUCID
1300 /* Return the frame on which widget WIDGET is used.. Abort if frame
1301 cannot be determined. */
1303 static struct frame *
1304 x_frame_of_widget (Widget widget)
1306 struct x_display_info *dpyinfo;
1307 Lisp_Object tail, frame;
1308 struct frame *f;
1310 dpyinfo = x_display_info_for_display (XtDisplay (widget));
1312 /* Find the top-level shell of the widget. Note that this function
1313 can be called when the widget is not yet realized, so XtWindow
1314 (widget) == 0. That's the reason we can't simply use
1315 x_any_window_to_frame. */
1316 while (!XtIsTopLevelShell (widget))
1317 widget = XtParent (widget);
1319 /* Look for a frame with that top-level widget. Allocate the color
1320 on that frame to get the right gamma correction value. */
1321 FOR_EACH_FRAME (tail, frame)
1323 f = XFRAME (frame);
1324 if (FRAME_X_P (f)
1325 && f->output_data.nothing != 1
1326 && FRAME_DISPLAY_INFO (f) == dpyinfo
1327 && f->output_data.x->widget == widget)
1328 return f;
1330 emacs_abort ();
1333 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
1334 or DELTA. Try a color with RGB values multiplied by FACTOR first.
1335 If this produces the same color as PIXEL, try a color where all RGB
1336 values have DELTA added. Return the allocated color in *PIXEL.
1337 DISPLAY is the X display, CMAP is the colormap to operate on.
1338 Value is true if successful. */
1340 bool
1341 x_alloc_lighter_color_for_widget (Widget widget, Display *display, Colormap cmap,
1342 unsigned long *pixel, double factor, int delta)
1344 struct frame *f = x_frame_of_widget (widget);
1345 return x_alloc_lighter_color (f, display, cmap, pixel, factor, delta);
1348 #endif /* USE_LUCID */
1351 /* Structure specifying which arguments should be passed by Xt to
1352 cvt_string_to_pixel. We want the widget's screen and colormap. */
1354 static XtConvertArgRec cvt_string_to_pixel_args[] =
1356 {XtWidgetBaseOffset, (XtPointer) XtOffset (Widget, core.screen),
1357 sizeof (Screen *)},
1358 {XtWidgetBaseOffset, (XtPointer) XtOffset (Widget, core.colormap),
1359 sizeof (Colormap)}
1363 /* The address of this variable is returned by
1364 cvt_string_to_pixel. */
1366 static Pixel cvt_string_to_pixel_value;
1369 /* Convert a color name to a pixel color.
1371 DPY is the display we are working on.
1373 ARGS is an array of *NARGS XrmValue structures holding additional
1374 information about the widget for which the conversion takes place.
1375 The contents of this array are determined by the specification
1376 in cvt_string_to_pixel_args.
1378 FROM is a pointer to an XrmValue which points to the color name to
1379 convert. TO is an XrmValue in which to return the pixel color.
1381 CLOSURE_RET is a pointer to user-data, in which we record if
1382 we allocated the color or not.
1384 Value is True if successful, False otherwise. */
1386 static Boolean
1387 cvt_string_to_pixel (Display *dpy, XrmValue *args, Cardinal *nargs,
1388 XrmValue *from, XrmValue *to,
1389 XtPointer *closure_ret)
1391 Screen *screen;
1392 Colormap cmap;
1393 Pixel pixel;
1394 String color_name;
1395 XColor color;
1397 if (*nargs != 2)
1399 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
1400 "wrongParameters", "cvt_string_to_pixel",
1401 "XtToolkitError",
1402 "Screen and colormap args required", NULL, NULL);
1403 return False;
1406 screen = *(Screen **) args[0].addr;
1407 cmap = *(Colormap *) args[1].addr;
1408 color_name = (String) from->addr;
1410 if (strcmp (color_name, XtDefaultBackground) == 0)
1412 *closure_ret = (XtPointer) False;
1413 pixel = WhitePixelOfScreen (screen);
1415 else if (strcmp (color_name, XtDefaultForeground) == 0)
1417 *closure_ret = (XtPointer) False;
1418 pixel = BlackPixelOfScreen (screen);
1420 else if (XParseColor (dpy, cmap, color_name, &color)
1421 && x_alloc_nearest_color_1 (dpy, cmap, &color))
1423 pixel = color.pixel;
1424 *closure_ret = (XtPointer) True;
1426 else
1428 String params[1];
1429 Cardinal nparams = 1;
1431 params[0] = color_name;
1432 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
1433 "badValue", "cvt_string_to_pixel",
1434 "XtToolkitError", "Invalid color `%s'",
1435 params, &nparams);
1436 return False;
1439 if (to->addr != NULL)
1441 if (to->size < sizeof (Pixel))
1443 to->size = sizeof (Pixel);
1444 return False;
1447 *(Pixel *) to->addr = pixel;
1449 else
1451 cvt_string_to_pixel_value = pixel;
1452 to->addr = (XtPointer) &cvt_string_to_pixel_value;
1455 to->size = sizeof (Pixel);
1456 return True;
1460 /* Free a pixel color which was previously allocated via
1461 cvt_string_to_pixel. This is registered as the destructor
1462 for this type of resource via XtSetTypeConverter.
1464 APP is the application context in which we work.
1466 TO is a pointer to an XrmValue holding the color to free.
1467 CLOSURE is the value we stored in CLOSURE_RET for this color
1468 in cvt_string_to_pixel.
1470 ARGS and NARGS are like for cvt_string_to_pixel. */
1472 static void
1473 cvt_pixel_dtor (XtAppContext app, XrmValuePtr to, XtPointer closure, XrmValuePtr args,
1474 Cardinal *nargs)
1476 if (*nargs != 2)
1478 XtAppWarningMsg (app, "wrongParameters", "cvt_pixel_dtor",
1479 "XtToolkitError",
1480 "Screen and colormap arguments required",
1481 NULL, NULL);
1483 else if (closure != NULL)
1485 /* We did allocate the pixel, so free it. */
1486 Screen *screen = *(Screen **) args[0].addr;
1487 Colormap cmap = *(Colormap *) args[1].addr;
1488 x_free_dpy_colors (DisplayOfScreen (screen), screen, cmap,
1489 (Pixel *) to->addr, 1);
1494 #endif /* USE_X_TOOLKIT */
1497 /* Value is an array of XColor structures for the contents of the
1498 color map of display DPY. Set *NCELLS to the size of the array.
1499 Note that this probably shouldn't be called for large color maps,
1500 say a 24-bit TrueColor map. */
1502 static const XColor *
1503 x_color_cells (Display *dpy, int *ncells)
1505 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
1507 if (dpyinfo->color_cells == NULL)
1509 Screen *screen = dpyinfo->screen;
1510 int ncolor_cells = XDisplayCells (dpy, XScreenNumberOfScreen (screen));
1511 int i;
1513 dpyinfo->color_cells = xnmalloc (ncolor_cells,
1514 sizeof *dpyinfo->color_cells);
1515 dpyinfo->ncolor_cells = ncolor_cells;
1517 for (i = 0; i < ncolor_cells; ++i)
1518 dpyinfo->color_cells[i].pixel = i;
1520 XQueryColors (dpy, dpyinfo->cmap,
1521 dpyinfo->color_cells, ncolor_cells);
1524 *ncells = dpyinfo->ncolor_cells;
1525 return dpyinfo->color_cells;
1529 /* On frame F, translate pixel colors to RGB values for the NCOLORS
1530 colors in COLORS. Use cached information, if available. */
1532 void
1533 x_query_colors (struct frame *f, XColor *colors, int ncolors)
1535 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1537 if (dpyinfo->color_cells)
1539 int i;
1540 for (i = 0; i < ncolors; ++i)
1542 unsigned long pixel = colors[i].pixel;
1543 eassert (pixel < dpyinfo->ncolor_cells);
1544 eassert (dpyinfo->color_cells[pixel].pixel == pixel);
1545 colors[i] = dpyinfo->color_cells[pixel];
1548 else
1549 XQueryColors (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), colors, ncolors);
1553 /* On frame F, translate pixel color to RGB values for the color in
1554 COLOR. Use cached information, if available. */
1556 void
1557 x_query_color (struct frame *f, XColor *color)
1559 x_query_colors (f, color, 1);
1563 /* Allocate the color COLOR->pixel on DISPLAY, colormap CMAP. If an
1564 exact match can't be allocated, try the nearest color available.
1565 Value is true if successful. Set *COLOR to the color
1566 allocated. */
1568 static bool
1569 x_alloc_nearest_color_1 (Display *dpy, Colormap cmap, XColor *color)
1571 bool rc;
1573 rc = XAllocColor (dpy, cmap, color) != 0;
1574 if (rc == 0)
1576 /* If we got to this point, the colormap is full, so we're going
1577 to try to get the next closest color. The algorithm used is
1578 a least-squares matching, which is what X uses for closest
1579 color matching with StaticColor visuals. */
1580 int nearest, i;
1581 int max_color_delta = 255;
1582 int max_delta = 3 * max_color_delta;
1583 int nearest_delta = max_delta + 1;
1584 int ncells;
1585 const XColor *cells = x_color_cells (dpy, &ncells);
1587 for (nearest = i = 0; i < ncells; ++i)
1589 int dred = (color->red >> 8) - (cells[i].red >> 8);
1590 int dgreen = (color->green >> 8) - (cells[i].green >> 8);
1591 int dblue = (color->blue >> 8) - (cells[i].blue >> 8);
1592 int delta = dred * dred + dgreen * dgreen + dblue * dblue;
1594 if (delta < nearest_delta)
1596 nearest = i;
1597 nearest_delta = delta;
1601 color->red = cells[nearest].red;
1602 color->green = cells[nearest].green;
1603 color->blue = cells[nearest].blue;
1604 rc = XAllocColor (dpy, cmap, color) != 0;
1606 else
1608 /* If allocation succeeded, and the allocated pixel color is not
1609 equal to a cached pixel color recorded earlier, there was a
1610 change in the colormap, so clear the color cache. */
1611 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
1612 XColor *cached_color;
1614 if (dpyinfo->color_cells
1615 && (cached_color = &dpyinfo->color_cells[color->pixel],
1616 (cached_color->red != color->red
1617 || cached_color->blue != color->blue
1618 || cached_color->green != color->green)))
1620 xfree (dpyinfo->color_cells);
1621 dpyinfo->color_cells = NULL;
1622 dpyinfo->ncolor_cells = 0;
1626 #ifdef DEBUG_X_COLORS
1627 if (rc)
1628 register_color (color->pixel);
1629 #endif /* DEBUG_X_COLORS */
1631 return rc;
1635 /* Allocate the color COLOR->pixel on frame F, colormap CMAP. If an
1636 exact match can't be allocated, try the nearest color available.
1637 Value is true if successful. Set *COLOR to the color
1638 allocated. */
1640 bool
1641 x_alloc_nearest_color (struct frame *f, Colormap cmap, XColor *color)
1643 gamma_correct (f, color);
1644 return x_alloc_nearest_color_1 (FRAME_X_DISPLAY (f), cmap, color);
1648 /* Allocate color PIXEL on frame F. PIXEL must already be allocated.
1649 It's necessary to do this instead of just using PIXEL directly to
1650 get color reference counts right. */
1652 unsigned long
1653 x_copy_color (struct frame *f, long unsigned int pixel)
1655 XColor color;
1657 color.pixel = pixel;
1658 block_input ();
1659 x_query_color (f, &color);
1660 XAllocColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &color);
1661 unblock_input ();
1662 #ifdef DEBUG_X_COLORS
1663 register_color (pixel);
1664 #endif
1665 return color.pixel;
1669 /* Brightness beyond which a color won't have its highlight brightness
1670 boosted.
1672 Nominally, highlight colors for `3d' faces are calculated by
1673 brightening an object's color by a constant scale factor, but this
1674 doesn't yield good results for dark colors, so for colors who's
1675 brightness is less than this value (on a scale of 0-65535) have an
1676 use an additional additive factor.
1678 The value here is set so that the default menu-bar/mode-line color
1679 (grey75) will not have its highlights changed at all. */
1680 #define HIGHLIGHT_COLOR_DARK_BOOST_LIMIT 48000
1683 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
1684 or DELTA. Try a color with RGB values multiplied by FACTOR first.
1685 If this produces the same color as PIXEL, try a color where all RGB
1686 values have DELTA added. Return the allocated color in *PIXEL.
1687 DISPLAY is the X display, CMAP is the colormap to operate on.
1688 Value is non-zero if successful. */
1690 static bool
1691 x_alloc_lighter_color (struct frame *f, Display *display, Colormap cmap, long unsigned int *pixel, double factor, int delta)
1693 XColor color, new;
1694 long bright;
1695 bool success_p;
1697 /* Get RGB color values. */
1698 color.pixel = *pixel;
1699 x_query_color (f, &color);
1701 /* Change RGB values by specified FACTOR. Avoid overflow! */
1702 eassert (factor >= 0);
1703 new.red = min (0xffff, factor * color.red);
1704 new.green = min (0xffff, factor * color.green);
1705 new.blue = min (0xffff, factor * color.blue);
1707 /* Calculate brightness of COLOR. */
1708 bright = (2 * color.red + 3 * color.green + color.blue) / 6;
1710 /* We only boost colors that are darker than
1711 HIGHLIGHT_COLOR_DARK_BOOST_LIMIT. */
1712 if (bright < HIGHLIGHT_COLOR_DARK_BOOST_LIMIT)
1713 /* Make an additive adjustment to NEW, because it's dark enough so
1714 that scaling by FACTOR alone isn't enough. */
1716 /* How far below the limit this color is (0 - 1, 1 being darker). */
1717 double dimness = 1 - (double)bright / HIGHLIGHT_COLOR_DARK_BOOST_LIMIT;
1718 /* The additive adjustment. */
1719 int min_delta = delta * dimness * factor / 2;
1721 if (factor < 1)
1723 new.red = max (0, new.red - min_delta);
1724 new.green = max (0, new.green - min_delta);
1725 new.blue = max (0, new.blue - min_delta);
1727 else
1729 new.red = min (0xffff, min_delta + new.red);
1730 new.green = min (0xffff, min_delta + new.green);
1731 new.blue = min (0xffff, min_delta + new.blue);
1735 /* Try to allocate the color. */
1736 success_p = x_alloc_nearest_color (f, cmap, &new);
1737 if (success_p)
1739 if (new.pixel == *pixel)
1741 /* If we end up with the same color as before, try adding
1742 delta to the RGB values. */
1743 x_free_colors (f, &new.pixel, 1);
1745 new.red = min (0xffff, delta + color.red);
1746 new.green = min (0xffff, delta + color.green);
1747 new.blue = min (0xffff, delta + color.blue);
1748 success_p = x_alloc_nearest_color (f, cmap, &new);
1750 else
1751 success_p = 1;
1752 *pixel = new.pixel;
1755 return success_p;
1759 /* Set up the foreground color for drawing relief lines of glyph
1760 string S. RELIEF is a pointer to a struct relief containing the GC
1761 with which lines will be drawn. Use a color that is FACTOR or
1762 DELTA lighter or darker than the relief's background which is found
1763 in S->f->output_data.x->relief_background. If such a color cannot
1764 be allocated, use DEFAULT_PIXEL, instead. */
1766 static void
1767 x_setup_relief_color (struct frame *f, struct relief *relief, double factor, int delta, long unsigned int default_pixel)
1769 XGCValues xgcv;
1770 struct x_output *di = f->output_data.x;
1771 unsigned long mask = GCForeground | GCLineWidth | GCGraphicsExposures;
1772 unsigned long pixel;
1773 unsigned long background = di->relief_background;
1774 Colormap cmap = FRAME_X_COLORMAP (f);
1775 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1776 Display *dpy = FRAME_X_DISPLAY (f);
1778 xgcv.graphics_exposures = False;
1779 xgcv.line_width = 1;
1781 /* Free previously allocated color. The color cell will be reused
1782 when it has been freed as many times as it was allocated, so this
1783 doesn't affect faces using the same colors. */
1784 if (relief->gc
1785 && relief->allocated_p)
1787 x_free_colors (f, &relief->pixel, 1);
1788 relief->allocated_p = 0;
1791 /* Allocate new color. */
1792 xgcv.foreground = default_pixel;
1793 pixel = background;
1794 if (dpyinfo->n_planes != 1
1795 && x_alloc_lighter_color (f, dpy, cmap, &pixel, factor, delta))
1797 relief->allocated_p = 1;
1798 xgcv.foreground = relief->pixel = pixel;
1801 if (relief->gc == 0)
1803 xgcv.stipple = dpyinfo->gray;
1804 mask |= GCStipple;
1805 relief->gc = XCreateGC (dpy, FRAME_X_WINDOW (f), mask, &xgcv);
1807 else
1808 XChangeGC (dpy, relief->gc, mask, &xgcv);
1812 /* Set up colors for the relief lines around glyph string S. */
1814 static void
1815 x_setup_relief_colors (struct glyph_string *s)
1817 struct x_output *di = s->f->output_data.x;
1818 unsigned long color;
1820 if (s->face->use_box_color_for_shadows_p)
1821 color = s->face->box_color;
1822 else if (s->first_glyph->type == IMAGE_GLYPH
1823 && s->img->pixmap
1824 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
1825 color = IMAGE_BACKGROUND (s->img, s->f, 0);
1826 else
1828 XGCValues xgcv;
1830 /* Get the background color of the face. */
1831 XGetGCValues (s->display, s->gc, GCBackground, &xgcv);
1832 color = xgcv.background;
1835 if (di->white_relief.gc == 0
1836 || color != di->relief_background)
1838 di->relief_background = color;
1839 x_setup_relief_color (s->f, &di->white_relief, 1.2, 0x8000,
1840 WHITE_PIX_DEFAULT (s->f));
1841 x_setup_relief_color (s->f, &di->black_relief, 0.6, 0x4000,
1842 BLACK_PIX_DEFAULT (s->f));
1847 /* Draw a relief on frame F inside the rectangle given by LEFT_X,
1848 TOP_Y, RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the relief
1849 to draw, it must be >= 0. RAISED_P non-zero means draw a raised
1850 relief. LEFT_P non-zero means draw a relief on the left side of
1851 the rectangle. RIGHT_P non-zero means draw a relief on the right
1852 side of the rectangle. CLIP_RECT is the clipping rectangle to use
1853 when drawing. */
1855 static void
1856 x_draw_relief_rect (struct frame *f,
1857 int left_x, int top_y, int right_x, int bottom_y, int width,
1858 int raised_p, int top_p, int bot_p, int left_p, int right_p,
1859 XRectangle *clip_rect)
1861 Display *dpy = FRAME_X_DISPLAY (f);
1862 Window window = FRAME_X_WINDOW (f);
1863 int i;
1864 GC gc;
1866 if (raised_p)
1867 gc = f->output_data.x->white_relief.gc;
1868 else
1869 gc = f->output_data.x->black_relief.gc;
1870 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
1872 /* This code is more complicated than it has to be, because of two
1873 minor hacks to make the boxes look nicer: (i) if width > 1, draw
1874 the outermost line using the black relief. (ii) Omit the four
1875 corner pixels. */
1877 /* Top. */
1878 if (top_p)
1880 if (width == 1)
1881 XDrawLine (dpy, window, gc,
1882 left_x + (left_p ? 1 : 0), top_y,
1883 right_x + (right_p ? 0 : 1), top_y);
1885 for (i = 1; i < width; ++i)
1886 XDrawLine (dpy, window, gc,
1887 left_x + i * left_p, top_y + i,
1888 right_x + 1 - i * right_p, top_y + i);
1891 /* Left. */
1892 if (left_p)
1894 if (width == 1)
1895 XDrawLine (dpy, window, gc, left_x, top_y + 1, left_x, bottom_y);
1897 XClearArea (dpy, window, left_x, top_y, 1, 1, False);
1898 XClearArea (dpy, window, left_x, bottom_y, 1, 1, False);
1900 for (i = (width > 1 ? 1 : 0); i < width; ++i)
1901 XDrawLine (dpy, window, gc,
1902 left_x + i, top_y + (i + 1) * top_p,
1903 left_x + i, bottom_y + 1 - (i + 1) * bot_p);
1906 XSetClipMask (dpy, gc, None);
1907 if (raised_p)
1908 gc = f->output_data.x->black_relief.gc;
1909 else
1910 gc = f->output_data.x->white_relief.gc;
1911 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
1913 if (width > 1)
1915 /* Outermost top line. */
1916 if (top_p)
1917 XDrawLine (dpy, window, gc,
1918 left_x + (left_p ? 1 : 0), top_y,
1919 right_x + (right_p ? 0 : 1), top_y);
1921 /* Outermost left line. */
1922 if (left_p)
1923 XDrawLine (dpy, window, gc, left_x, top_y + 1, left_x, bottom_y);
1926 /* Bottom. */
1927 if (bot_p)
1929 XDrawLine (dpy, window, gc,
1930 left_x + (left_p ? 1 : 0), bottom_y,
1931 right_x + (right_p ? 0 : 1), bottom_y);
1932 for (i = 1; i < width; ++i)
1933 XDrawLine (dpy, window, gc,
1934 left_x + i * left_p, bottom_y - i,
1935 right_x + 1 - i * right_p, bottom_y - i);
1938 /* Right. */
1939 if (right_p)
1941 XClearArea (dpy, window, right_x, top_y, 1, 1, False);
1942 XClearArea (dpy, window, right_x, bottom_y, 1, 1, False);
1943 for (i = 0; i < width; ++i)
1944 XDrawLine (dpy, window, gc,
1945 right_x - i, top_y + (i + 1) * top_p,
1946 right_x - i, bottom_y + 1 - (i + 1) * bot_p);
1949 XSetClipMask (dpy, gc, None);
1953 /* Draw a box on frame F inside the rectangle given by LEFT_X, TOP_Y,
1954 RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the lines to
1955 draw, it must be >= 0. LEFT_P non-zero means draw a line on the
1956 left side of the rectangle. RIGHT_P non-zero means draw a line
1957 on the right side of the rectangle. CLIP_RECT is the clipping
1958 rectangle to use when drawing. */
1960 static void
1961 x_draw_box_rect (struct glyph_string *s,
1962 int left_x, int top_y, int right_x, int bottom_y, int width,
1963 int left_p, int right_p, XRectangle *clip_rect)
1965 XGCValues xgcv;
1967 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
1968 XSetForeground (s->display, s->gc, s->face->box_color);
1969 XSetClipRectangles (s->display, s->gc, 0, 0, clip_rect, 1, Unsorted);
1971 /* Top. */
1972 XFillRectangle (s->display, s->window, s->gc,
1973 left_x, top_y, right_x - left_x + 1, width);
1975 /* Left. */
1976 if (left_p)
1977 XFillRectangle (s->display, s->window, s->gc,
1978 left_x, top_y, width, bottom_y - top_y + 1);
1980 /* Bottom. */
1981 XFillRectangle (s->display, s->window, s->gc,
1982 left_x, bottom_y - width + 1, right_x - left_x + 1, width);
1984 /* Right. */
1985 if (right_p)
1986 XFillRectangle (s->display, s->window, s->gc,
1987 right_x - width + 1, top_y, width, bottom_y - top_y + 1);
1989 XSetForeground (s->display, s->gc, xgcv.foreground);
1990 XSetClipMask (s->display, s->gc, None);
1994 /* Draw a box around glyph string S. */
1996 static void
1997 x_draw_glyph_string_box (struct glyph_string *s)
1999 int width, left_x, right_x, top_y, bottom_y, last_x, raised_p;
2000 int left_p, right_p;
2001 struct glyph *last_glyph;
2002 XRectangle clip_rect;
2004 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2005 ? WINDOW_RIGHT_EDGE_X (s->w)
2006 : window_box_right (s->w, s->area));
2008 /* The glyph that may have a right box line. */
2009 last_glyph = (s->cmp || s->img
2010 ? s->first_glyph
2011 : s->first_glyph + s->nchars - 1);
2013 width = eabs (s->face->box_line_width);
2014 raised_p = s->face->box == FACE_RAISED_BOX;
2015 left_x = s->x;
2016 right_x = (s->row->full_width_p && s->extends_to_end_of_line_p
2017 ? last_x - 1
2018 : min (last_x, s->x + s->background_width) - 1);
2019 top_y = s->y;
2020 bottom_y = top_y + s->height - 1;
2022 left_p = (s->first_glyph->left_box_line_p
2023 || (s->hl == DRAW_MOUSE_FACE
2024 && (s->prev == NULL
2025 || s->prev->hl != s->hl)));
2026 right_p = (last_glyph->right_box_line_p
2027 || (s->hl == DRAW_MOUSE_FACE
2028 && (s->next == NULL
2029 || s->next->hl != s->hl)));
2031 get_glyph_string_clip_rect (s, &clip_rect);
2033 if (s->face->box == FACE_SIMPLE_BOX)
2034 x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
2035 left_p, right_p, &clip_rect);
2036 else
2038 x_setup_relief_colors (s);
2039 x_draw_relief_rect (s->f, left_x, top_y, right_x, bottom_y,
2040 width, raised_p, 1, 1, left_p, right_p, &clip_rect);
2045 /* Draw foreground of image glyph string S. */
2047 static void
2048 x_draw_image_foreground (struct glyph_string *s)
2050 int x = s->x;
2051 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2053 /* If first glyph of S has a left box line, start drawing it to the
2054 right of that line. */
2055 if (s->face->box != FACE_NO_BOX
2056 && s->first_glyph->left_box_line_p
2057 && s->slice.x == 0)
2058 x += eabs (s->face->box_line_width);
2060 /* If there is a margin around the image, adjust x- and y-position
2061 by that margin. */
2062 if (s->slice.x == 0)
2063 x += s->img->hmargin;
2064 if (s->slice.y == 0)
2065 y += s->img->vmargin;
2067 if (s->img->pixmap)
2069 if (s->img->mask)
2071 /* We can't set both a clip mask and use XSetClipRectangles
2072 because the latter also sets a clip mask. We also can't
2073 trust on the shape extension to be available
2074 (XShapeCombineRegion). So, compute the rectangle to draw
2075 manually. */
2076 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
2077 | GCFunction);
2078 XGCValues xgcv;
2079 XRectangle clip_rect, image_rect, r;
2081 xgcv.clip_mask = s->img->mask;
2082 xgcv.clip_x_origin = x;
2083 xgcv.clip_y_origin = y;
2084 xgcv.function = GXcopy;
2085 XChangeGC (s->display, s->gc, mask, &xgcv);
2087 get_glyph_string_clip_rect (s, &clip_rect);
2088 image_rect.x = x;
2089 image_rect.y = y;
2090 image_rect.width = s->slice.width;
2091 image_rect.height = s->slice.height;
2092 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
2093 XCopyArea (s->display, s->img->pixmap, s->window, s->gc,
2094 s->slice.x + r.x - x, s->slice.y + r.y - y,
2095 r.width, r.height, r.x, r.y);
2097 else
2099 XRectangle clip_rect, image_rect, r;
2101 get_glyph_string_clip_rect (s, &clip_rect);
2102 image_rect.x = x;
2103 image_rect.y = y;
2104 image_rect.width = s->slice.width;
2105 image_rect.height = s->slice.height;
2106 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
2107 XCopyArea (s->display, s->img->pixmap, s->window, s->gc,
2108 s->slice.x + r.x - x, s->slice.y + r.y - y,
2109 r.width, r.height, r.x, r.y);
2111 /* When the image has a mask, we can expect that at
2112 least part of a mouse highlight or a block cursor will
2113 be visible. If the image doesn't have a mask, make
2114 a block cursor visible by drawing a rectangle around
2115 the image. I believe it's looking better if we do
2116 nothing here for mouse-face. */
2117 if (s->hl == DRAW_CURSOR)
2119 int relief = eabs (s->img->relief);
2120 XDrawRectangle (s->display, s->window, s->gc,
2121 x - relief, y - relief,
2122 s->slice.width + relief*2 - 1,
2123 s->slice.height + relief*2 - 1);
2127 else
2128 /* Draw a rectangle if image could not be loaded. */
2129 XDrawRectangle (s->display, s->window, s->gc, x, y,
2130 s->slice.width - 1, s->slice.height - 1);
2134 /* Draw a relief around the image glyph string S. */
2136 static void
2137 x_draw_image_relief (struct glyph_string *s)
2139 int x1, y1, thick, raised_p, top_p, bot_p, left_p, right_p;
2140 XRectangle r;
2141 int x = s->x;
2142 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2144 /* If first glyph of S has a left box line, start drawing it to the
2145 right of that line. */
2146 if (s->face->box != FACE_NO_BOX
2147 && s->first_glyph->left_box_line_p
2148 && s->slice.x == 0)
2149 x += eabs (s->face->box_line_width);
2151 /* If there is a margin around the image, adjust x- and y-position
2152 by that margin. */
2153 if (s->slice.x == 0)
2154 x += s->img->hmargin;
2155 if (s->slice.y == 0)
2156 y += s->img->vmargin;
2158 if (s->hl == DRAW_IMAGE_SUNKEN
2159 || s->hl == DRAW_IMAGE_RAISED)
2161 thick = tool_bar_button_relief >= 0 ? tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
2162 raised_p = s->hl == DRAW_IMAGE_RAISED;
2164 else
2166 thick = eabs (s->img->relief);
2167 raised_p = s->img->relief > 0;
2170 x1 = x + s->slice.width - 1;
2171 y1 = y + s->slice.height - 1;
2172 top_p = bot_p = left_p = right_p = 0;
2174 if (s->slice.x == 0)
2175 x -= thick, left_p = 1;
2176 if (s->slice.y == 0)
2177 y -= thick, top_p = 1;
2178 if (s->slice.x + s->slice.width == s->img->width)
2179 x1 += thick, right_p = 1;
2180 if (s->slice.y + s->slice.height == s->img->height)
2181 y1 += thick, bot_p = 1;
2183 x_setup_relief_colors (s);
2184 get_glyph_string_clip_rect (s, &r);
2185 x_draw_relief_rect (s->f, x, y, x1, y1, thick, raised_p,
2186 top_p, bot_p, left_p, right_p, &r);
2190 /* Draw the foreground of image glyph string S to PIXMAP. */
2192 static void
2193 x_draw_image_foreground_1 (struct glyph_string *s, Pixmap pixmap)
2195 int x = 0;
2196 int y = s->ybase - s->y - image_ascent (s->img, s->face, &s->slice);
2198 /* If first glyph of S has a left box line, start drawing it to the
2199 right of that line. */
2200 if (s->face->box != FACE_NO_BOX
2201 && s->first_glyph->left_box_line_p
2202 && s->slice.x == 0)
2203 x += eabs (s->face->box_line_width);
2205 /* If there is a margin around the image, adjust x- and y-position
2206 by that margin. */
2207 if (s->slice.x == 0)
2208 x += s->img->hmargin;
2209 if (s->slice.y == 0)
2210 y += s->img->vmargin;
2212 if (s->img->pixmap)
2214 if (s->img->mask)
2216 /* We can't set both a clip mask and use XSetClipRectangles
2217 because the latter also sets a clip mask. We also can't
2218 trust on the shape extension to be available
2219 (XShapeCombineRegion). So, compute the rectangle to draw
2220 manually. */
2221 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
2222 | GCFunction);
2223 XGCValues xgcv;
2225 xgcv.clip_mask = s->img->mask;
2226 xgcv.clip_x_origin = x - s->slice.x;
2227 xgcv.clip_y_origin = y - s->slice.y;
2228 xgcv.function = GXcopy;
2229 XChangeGC (s->display, s->gc, mask, &xgcv);
2231 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
2232 s->slice.x, s->slice.y,
2233 s->slice.width, s->slice.height, x, y);
2234 XSetClipMask (s->display, s->gc, None);
2236 else
2238 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
2239 s->slice.x, s->slice.y,
2240 s->slice.width, s->slice.height, x, y);
2242 /* When the image has a mask, we can expect that at
2243 least part of a mouse highlight or a block cursor will
2244 be visible. If the image doesn't have a mask, make
2245 a block cursor visible by drawing a rectangle around
2246 the image. I believe it's looking better if we do
2247 nothing here for mouse-face. */
2248 if (s->hl == DRAW_CURSOR)
2250 int r = eabs (s->img->relief);
2251 XDrawRectangle (s->display, s->window, s->gc, x - r, y - r,
2252 s->slice.width + r*2 - 1,
2253 s->slice.height + r*2 - 1);
2257 else
2258 /* Draw a rectangle if image could not be loaded. */
2259 XDrawRectangle (s->display, pixmap, s->gc, x, y,
2260 s->slice.width - 1, s->slice.height - 1);
2264 /* Draw part of the background of glyph string S. X, Y, W, and H
2265 give the rectangle to draw. */
2267 static void
2268 x_draw_glyph_string_bg_rect (struct glyph_string *s, int x, int y, int w, int h)
2270 if (s->stippled_p)
2272 /* Fill background with a stipple pattern. */
2273 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
2274 XFillRectangle (s->display, s->window, s->gc, x, y, w, h);
2275 XSetFillStyle (s->display, s->gc, FillSolid);
2277 else
2278 x_clear_glyph_string_rect (s, x, y, w, h);
2282 /* Draw image glyph string S.
2284 s->y
2285 s->x +-------------------------
2286 | s->face->box
2288 | +-------------------------
2289 | | s->img->margin
2291 | | +-------------------
2292 | | | the image
2296 static void
2297 x_draw_image_glyph_string (struct glyph_string *s)
2299 int box_line_hwidth = eabs (s->face->box_line_width);
2300 int box_line_vwidth = max (s->face->box_line_width, 0);
2301 int height;
2302 Pixmap pixmap = None;
2304 height = s->height;
2305 if (s->slice.y == 0)
2306 height -= box_line_vwidth;
2307 if (s->slice.y + s->slice.height >= s->img->height)
2308 height -= box_line_vwidth;
2310 /* Fill background with face under the image. Do it only if row is
2311 taller than image or if image has a clip mask to reduce
2312 flickering. */
2313 s->stippled_p = s->face->stipple != 0;
2314 if (height > s->slice.height
2315 || s->img->hmargin
2316 || s->img->vmargin
2317 || s->img->mask
2318 || s->img->pixmap == 0
2319 || s->width != s->background_width)
2321 if (s->img->mask)
2323 /* Create a pixmap as large as the glyph string. Fill it
2324 with the background color. Copy the image to it, using
2325 its mask. Copy the temporary pixmap to the display. */
2326 Screen *screen = FRAME_X_SCREEN (s->f);
2327 int depth = DefaultDepthOfScreen (screen);
2329 /* Create a pixmap as large as the glyph string. */
2330 pixmap = XCreatePixmap (s->display, s->window,
2331 s->background_width,
2332 s->height, depth);
2334 /* Don't clip in the following because we're working on the
2335 pixmap. */
2336 XSetClipMask (s->display, s->gc, None);
2338 /* Fill the pixmap with the background color/stipple. */
2339 if (s->stippled_p)
2341 /* Fill background with a stipple pattern. */
2342 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
2343 XSetTSOrigin (s->display, s->gc, - s->x, - s->y);
2344 XFillRectangle (s->display, pixmap, s->gc,
2345 0, 0, s->background_width, s->height);
2346 XSetFillStyle (s->display, s->gc, FillSolid);
2347 XSetTSOrigin (s->display, s->gc, 0, 0);
2349 else
2351 XGCValues xgcv;
2352 XGetGCValues (s->display, s->gc, GCForeground | GCBackground,
2353 &xgcv);
2354 XSetForeground (s->display, s->gc, xgcv.background);
2355 XFillRectangle (s->display, pixmap, s->gc,
2356 0, 0, s->background_width, s->height);
2357 XSetForeground (s->display, s->gc, xgcv.foreground);
2360 else
2362 int x = s->x;
2363 int y = s->y;
2365 if (s->first_glyph->left_box_line_p
2366 && s->slice.x == 0)
2367 x += box_line_hwidth;
2369 if (s->slice.y == 0)
2370 y += box_line_vwidth;
2372 x_draw_glyph_string_bg_rect (s, x, y, s->background_width, height);
2375 s->background_filled_p = 1;
2378 /* Draw the foreground. */
2379 if (pixmap != None)
2381 x_draw_image_foreground_1 (s, pixmap);
2382 x_set_glyph_string_clipping (s);
2383 XCopyArea (s->display, pixmap, s->window, s->gc,
2384 0, 0, s->background_width, s->height, s->x, s->y);
2385 XFreePixmap (s->display, pixmap);
2387 else
2388 x_draw_image_foreground (s);
2390 /* If we must draw a relief around the image, do it. */
2391 if (s->img->relief
2392 || s->hl == DRAW_IMAGE_RAISED
2393 || s->hl == DRAW_IMAGE_SUNKEN)
2394 x_draw_image_relief (s);
2398 /* Draw stretch glyph string S. */
2400 static void
2401 x_draw_stretch_glyph_string (struct glyph_string *s)
2403 eassert (s->first_glyph->type == STRETCH_GLYPH);
2405 if (s->hl == DRAW_CURSOR
2406 && !x_stretch_cursor_p)
2408 /* If `x-stretch-cursor' is nil, don't draw a block cursor as
2409 wide as the stretch glyph. */
2410 int width, background_width = s->background_width;
2411 int x = s->x;
2413 if (!s->row->reversed_p)
2415 int left_x = window_box_left_offset (s->w, TEXT_AREA);
2417 if (x < left_x)
2419 background_width -= left_x - x;
2420 x = left_x;
2423 else
2425 /* In R2L rows, draw the cursor on the right edge of the
2426 stretch glyph. */
2427 int right_x = window_box_right_offset (s->w, TEXT_AREA);
2429 if (x + background_width > right_x)
2430 background_width -= x - right_x;
2431 x += background_width;
2433 width = min (FRAME_COLUMN_WIDTH (s->f), background_width);
2434 if (s->row->reversed_p)
2435 x -= width;
2437 /* Draw cursor. */
2438 x_draw_glyph_string_bg_rect (s, x, s->y, width, s->height);
2440 /* Clear rest using the GC of the original non-cursor face. */
2441 if (width < background_width)
2443 int y = s->y;
2444 int w = background_width - width, h = s->height;
2445 XRectangle r;
2446 GC gc;
2448 if (!s->row->reversed_p)
2449 x += width;
2450 else
2451 x = s->x;
2452 if (s->row->mouse_face_p
2453 && cursor_in_mouse_face_p (s->w))
2455 x_set_mouse_face_gc (s);
2456 gc = s->gc;
2458 else
2459 gc = s->face->gc;
2461 get_glyph_string_clip_rect (s, &r);
2462 XSetClipRectangles (s->display, gc, 0, 0, &r, 1, Unsorted);
2464 if (s->face->stipple)
2466 /* Fill background with a stipple pattern. */
2467 XSetFillStyle (s->display, gc, FillOpaqueStippled);
2468 XFillRectangle (s->display, s->window, gc, x, y, w, h);
2469 XSetFillStyle (s->display, gc, FillSolid);
2471 else
2473 XGCValues xgcv;
2474 XGetGCValues (s->display, gc, GCForeground | GCBackground, &xgcv);
2475 XSetForeground (s->display, gc, xgcv.background);
2476 XFillRectangle (s->display, s->window, gc, x, y, w, h);
2477 XSetForeground (s->display, gc, xgcv.foreground);
2481 else if (!s->background_filled_p)
2483 int background_width = s->background_width;
2484 int x = s->x, left_x = window_box_left_offset (s->w, TEXT_AREA);
2486 /* Don't draw into left margin, fringe or scrollbar area
2487 except for header line and mode line. */
2488 if (x < left_x && !s->row->mode_line_p)
2490 background_width -= left_x - x;
2491 x = left_x;
2493 if (background_width > 0)
2494 x_draw_glyph_string_bg_rect (s, x, s->y, background_width, s->height);
2497 s->background_filled_p = 1;
2501 Draw a wavy line under S. The wave fills wave_height pixels from y0.
2503 x0 wave_length = 2
2505 y0 * * * * *
2506 |* * * * * * * * *
2507 wave_height = 3 | * * * *
2511 static void
2512 x_draw_underwave (struct glyph_string *s)
2514 int wave_height = 3, wave_length = 2;
2515 int dx, dy, x0, y0, width, x1, y1, x2, y2, odd, xmax;
2516 XRectangle wave_clip, string_clip, final_clip;
2518 dx = wave_length;
2519 dy = wave_height - 1;
2520 x0 = s->x;
2521 y0 = s->ybase - wave_height + 3;
2522 width = s->width;
2523 xmax = x0 + width;
2525 /* Find and set clipping rectangle */
2527 wave_clip.x = x0;
2528 wave_clip.y = y0;
2529 wave_clip.width = width;
2530 wave_clip.height = wave_height;
2531 get_glyph_string_clip_rect (s, &string_clip);
2533 if (!x_intersect_rectangles (&wave_clip, &string_clip, &final_clip))
2534 return;
2536 XSetClipRectangles (s->display, s->gc, 0, 0, &final_clip, 1, Unsorted);
2538 /* Draw the waves */
2540 x1 = x0 - (x0 % dx);
2541 x2 = x1 + dx;
2542 odd = (x1/dx) % 2;
2543 y1 = y2 = y0;
2545 if (odd)
2546 y1 += dy;
2547 else
2548 y2 += dy;
2550 if (INT_MAX - dx < xmax)
2551 emacs_abort ();
2553 while (x1 <= xmax)
2555 XDrawLine (s->display, s->window, s->gc, x1, y1, x2, y2);
2556 x1 = x2, y1 = y2;
2557 x2 += dx, y2 = y0 + odd*dy;
2558 odd = !odd;
2561 /* Restore previous clipping rectangle(s) */
2562 XSetClipRectangles (s->display, s->gc, 0, 0, s->clip, s->num_clips, Unsorted);
2566 /* Draw glyph string S. */
2568 static void
2569 x_draw_glyph_string (struct glyph_string *s)
2571 bool relief_drawn_p = 0;
2573 /* If S draws into the background of its successors, draw the
2574 background of the successors first so that S can draw into it.
2575 This makes S->next use XDrawString instead of XDrawImageString. */
2576 if (s->next && s->right_overhang && !s->for_overlaps)
2578 int width;
2579 struct glyph_string *next;
2581 for (width = 0, next = s->next;
2582 next && width < s->right_overhang;
2583 width += next->width, next = next->next)
2584 if (next->first_glyph->type != IMAGE_GLYPH)
2586 x_set_glyph_string_gc (next);
2587 x_set_glyph_string_clipping (next);
2588 if (next->first_glyph->type == STRETCH_GLYPH)
2589 x_draw_stretch_glyph_string (next);
2590 else
2591 x_draw_glyph_string_background (next, 1);
2592 next->num_clips = 0;
2596 /* Set up S->gc, set clipping and draw S. */
2597 x_set_glyph_string_gc (s);
2599 /* Draw relief (if any) in advance for char/composition so that the
2600 glyph string can be drawn over it. */
2601 if (!s->for_overlaps
2602 && s->face->box != FACE_NO_BOX
2603 && (s->first_glyph->type == CHAR_GLYPH
2604 || s->first_glyph->type == COMPOSITE_GLYPH))
2607 x_set_glyph_string_clipping (s);
2608 x_draw_glyph_string_background (s, 1);
2609 x_draw_glyph_string_box (s);
2610 x_set_glyph_string_clipping (s);
2611 relief_drawn_p = 1;
2613 else if (!s->clip_head /* draw_glyphs didn't specify a clip mask. */
2614 && !s->clip_tail
2615 && ((s->prev && s->prev->hl != s->hl && s->left_overhang)
2616 || (s->next && s->next->hl != s->hl && s->right_overhang)))
2617 /* We must clip just this glyph. left_overhang part has already
2618 drawn when s->prev was drawn, and right_overhang part will be
2619 drawn later when s->next is drawn. */
2620 x_set_glyph_string_clipping_exactly (s, s);
2621 else
2622 x_set_glyph_string_clipping (s);
2624 switch (s->first_glyph->type)
2626 case IMAGE_GLYPH:
2627 x_draw_image_glyph_string (s);
2628 break;
2630 case STRETCH_GLYPH:
2631 x_draw_stretch_glyph_string (s);
2632 break;
2634 case CHAR_GLYPH:
2635 if (s->for_overlaps)
2636 s->background_filled_p = 1;
2637 else
2638 x_draw_glyph_string_background (s, 0);
2639 x_draw_glyph_string_foreground (s);
2640 break;
2642 case COMPOSITE_GLYPH:
2643 if (s->for_overlaps || (s->cmp_from > 0
2644 && ! s->first_glyph->u.cmp.automatic))
2645 s->background_filled_p = 1;
2646 else
2647 x_draw_glyph_string_background (s, 1);
2648 x_draw_composite_glyph_string_foreground (s);
2649 break;
2651 case GLYPHLESS_GLYPH:
2652 if (s->for_overlaps)
2653 s->background_filled_p = 1;
2654 else
2655 x_draw_glyph_string_background (s, 1);
2656 x_draw_glyphless_glyph_string_foreground (s);
2657 break;
2659 default:
2660 emacs_abort ();
2663 if (!s->for_overlaps)
2665 /* Draw underline. */
2666 if (s->face->underline_p)
2668 if (s->face->underline_type == FACE_UNDER_WAVE)
2670 if (s->face->underline_defaulted_p)
2671 x_draw_underwave (s);
2672 else
2674 XGCValues xgcv;
2675 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2676 XSetForeground (s->display, s->gc, s->face->underline_color);
2677 x_draw_underwave (s);
2678 XSetForeground (s->display, s->gc, xgcv.foreground);
2681 else if (s->face->underline_type == FACE_UNDER_LINE)
2683 unsigned long thickness, position;
2684 int y;
2686 if (s->prev && s->prev->face->underline_p
2687 && s->prev->face->underline_type == FACE_UNDER_LINE)
2689 /* We use the same underline style as the previous one. */
2690 thickness = s->prev->underline_thickness;
2691 position = s->prev->underline_position;
2693 else
2695 /* Get the underline thickness. Default is 1 pixel. */
2696 if (s->font && s->font->underline_thickness > 0)
2697 thickness = s->font->underline_thickness;
2698 else
2699 thickness = 1;
2700 if (x_underline_at_descent_line)
2701 position = (s->height - thickness) - (s->ybase - s->y);
2702 else
2704 /* Get the underline position. This is the recommended
2705 vertical offset in pixels from the baseline to the top of
2706 the underline. This is a signed value according to the
2707 specs, and its default is
2709 ROUND ((maximum descent) / 2), with
2710 ROUND(x) = floor (x + 0.5) */
2712 if (x_use_underline_position_properties
2713 && s->font && s->font->underline_position >= 0)
2714 position = s->font->underline_position;
2715 else if (s->font)
2716 position = (s->font->descent + 1) / 2;
2717 else
2718 position = underline_minimum_offset;
2720 position = max (position, underline_minimum_offset);
2722 /* Check the sanity of thickness and position. We should
2723 avoid drawing underline out of the current line area. */
2724 if (s->y + s->height <= s->ybase + position)
2725 position = (s->height - 1) - (s->ybase - s->y);
2726 if (s->y + s->height < s->ybase + position + thickness)
2727 thickness = (s->y + s->height) - (s->ybase + position);
2728 s->underline_thickness = thickness;
2729 s->underline_position = position;
2730 y = s->ybase + position;
2731 if (s->face->underline_defaulted_p)
2732 XFillRectangle (s->display, s->window, s->gc,
2733 s->x, y, s->width, thickness);
2734 else
2736 XGCValues xgcv;
2737 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2738 XSetForeground (s->display, s->gc, s->face->underline_color);
2739 XFillRectangle (s->display, s->window, s->gc,
2740 s->x, y, s->width, thickness);
2741 XSetForeground (s->display, s->gc, xgcv.foreground);
2745 /* Draw overline. */
2746 if (s->face->overline_p)
2748 unsigned long dy = 0, h = 1;
2750 if (s->face->overline_color_defaulted_p)
2751 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2752 s->width, h);
2753 else
2755 XGCValues xgcv;
2756 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2757 XSetForeground (s->display, s->gc, s->face->overline_color);
2758 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2759 s->width, h);
2760 XSetForeground (s->display, s->gc, xgcv.foreground);
2764 /* Draw strike-through. */
2765 if (s->face->strike_through_p)
2767 unsigned long h = 1;
2768 unsigned long dy = (s->height - h) / 2;
2770 if (s->face->strike_through_color_defaulted_p)
2771 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2772 s->width, h);
2773 else
2775 XGCValues xgcv;
2776 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2777 XSetForeground (s->display, s->gc, s->face->strike_through_color);
2778 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2779 s->width, h);
2780 XSetForeground (s->display, s->gc, xgcv.foreground);
2784 /* Draw relief if not yet drawn. */
2785 if (!relief_drawn_p && s->face->box != FACE_NO_BOX)
2786 x_draw_glyph_string_box (s);
2788 if (s->prev)
2790 struct glyph_string *prev;
2792 for (prev = s->prev; prev; prev = prev->prev)
2793 if (prev->hl != s->hl
2794 && prev->x + prev->width + prev->right_overhang > s->x)
2796 /* As prev was drawn while clipped to its own area, we
2797 must draw the right_overhang part using s->hl now. */
2798 enum draw_glyphs_face save = prev->hl;
2800 prev->hl = s->hl;
2801 x_set_glyph_string_gc (prev);
2802 x_set_glyph_string_clipping_exactly (s, prev);
2803 if (prev->first_glyph->type == CHAR_GLYPH)
2804 x_draw_glyph_string_foreground (prev);
2805 else
2806 x_draw_composite_glyph_string_foreground (prev);
2807 XSetClipMask (prev->display, prev->gc, None);
2808 prev->hl = save;
2809 prev->num_clips = 0;
2813 if (s->next)
2815 struct glyph_string *next;
2817 for (next = s->next; next; next = next->next)
2818 if (next->hl != s->hl
2819 && next->x - next->left_overhang < s->x + s->width)
2821 /* As next will be drawn while clipped to its own area,
2822 we must draw the left_overhang part using s->hl now. */
2823 enum draw_glyphs_face save = next->hl;
2825 next->hl = s->hl;
2826 x_set_glyph_string_gc (next);
2827 x_set_glyph_string_clipping_exactly (s, next);
2828 if (next->first_glyph->type == CHAR_GLYPH)
2829 x_draw_glyph_string_foreground (next);
2830 else
2831 x_draw_composite_glyph_string_foreground (next);
2832 XSetClipMask (next->display, next->gc, None);
2833 next->hl = save;
2834 next->num_clips = 0;
2835 next->clip_head = s->next;
2840 /* Reset clipping. */
2841 XSetClipMask (s->display, s->gc, None);
2842 s->num_clips = 0;
2845 /* Shift display to make room for inserted glyphs. */
2847 static void
2848 x_shift_glyphs_for_insert (struct frame *f, int x, int y, int width, int height, int shift_by)
2850 XCopyArea (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), FRAME_X_WINDOW (f),
2851 f->output_data.x->normal_gc,
2852 x, y, width, height,
2853 x + shift_by, y);
2856 /* Delete N glyphs at the nominal cursor position. Not implemented
2857 for X frames. */
2859 static void
2860 x_delete_glyphs (struct frame *f, register int n)
2862 emacs_abort ();
2866 /* Like XClearArea, but check that WIDTH and HEIGHT are reasonable.
2867 If they are <= 0, this is probably an error. */
2869 void
2870 x_clear_area (Display *dpy, Window window, int x, int y, int width, int height)
2872 eassert (width > 0 && height > 0);
2873 XClearArea (dpy, window, x, y, width, height, False);
2877 /* Clear an entire frame. */
2879 static void
2880 x_clear_frame (struct frame *f)
2882 /* Clearing the frame will erase any cursor, so mark them all as no
2883 longer visible. */
2884 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2886 block_input ();
2888 XClearWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
2890 /* We have to clear the scroll bars. If we have changed colors or
2891 something like that, then they should be notified. */
2892 x_scroll_bar_clear (f);
2894 #if defined (USE_GTK) && defined (USE_TOOLKIT_SCROLL_BARS)
2895 /* Make sure scroll bars are redrawn. As they aren't redrawn by
2896 redisplay, do it here. */
2897 if (FRAME_GTK_WIDGET (f))
2898 gtk_widget_queue_draw (FRAME_GTK_WIDGET (f));
2899 #endif
2901 XFlush (FRAME_X_DISPLAY (f));
2903 unblock_input ();
2908 /* Invert the middle quarter of the frame for .15 sec. */
2910 static void
2911 XTflash (struct frame *f)
2913 block_input ();
2916 #ifdef USE_GTK
2917 /* Use Gdk routines to draw. This way, we won't draw over scroll bars
2918 when the scroll bars and the edit widget share the same X window. */
2919 GdkWindow *window = gtk_widget_get_window (FRAME_GTK_WIDGET (f));
2920 #ifdef HAVE_GTK3
2921 cairo_t *cr = gdk_cairo_create (window);
2922 cairo_set_source_rgb (cr, 1, 1, 1);
2923 cairo_set_operator (cr, CAIRO_OPERATOR_DIFFERENCE);
2924 #define XFillRectangle(d, win, gc, x, y, w, h) \
2925 do { \
2926 cairo_rectangle (cr, x, y, w, h); \
2927 cairo_fill (cr); \
2929 while (0)
2930 #else /* ! HAVE_GTK3 */
2931 GdkGCValues vals;
2932 GdkGC *gc;
2933 vals.foreground.pixel = (FRAME_FOREGROUND_PIXEL (f)
2934 ^ FRAME_BACKGROUND_PIXEL (f));
2935 vals.function = GDK_XOR;
2936 gc = gdk_gc_new_with_values (window,
2937 &vals, GDK_GC_FUNCTION | GDK_GC_FOREGROUND);
2938 #define XFillRectangle(d, win, gc, x, y, w, h) \
2939 gdk_draw_rectangle (window, gc, TRUE, x, y, w, h)
2940 #endif /* ! HAVE_GTK3 */
2941 #else /* ! USE_GTK */
2942 GC gc;
2944 /* Create a GC that will use the GXxor function to flip foreground
2945 pixels into background pixels. */
2947 XGCValues values;
2949 values.function = GXxor;
2950 values.foreground = (FRAME_FOREGROUND_PIXEL (f)
2951 ^ FRAME_BACKGROUND_PIXEL (f));
2953 gc = XCreateGC (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
2954 GCFunction | GCForeground, &values);
2956 #endif
2958 /* Get the height not including a menu bar widget. */
2959 int height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, FRAME_LINES (f));
2960 /* Height of each line to flash. */
2961 int flash_height = FRAME_LINE_HEIGHT (f);
2962 /* These will be the left and right margins of the rectangles. */
2963 int flash_left = FRAME_INTERNAL_BORDER_WIDTH (f);
2964 int flash_right = FRAME_PIXEL_WIDTH (f) - FRAME_INTERNAL_BORDER_WIDTH (f);
2965 int width = flash_right - flash_left;
2967 /* If window is tall, flash top and bottom line. */
2968 if (height > 3 * FRAME_LINE_HEIGHT (f))
2970 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
2971 flash_left,
2972 (FRAME_INTERNAL_BORDER_WIDTH (f)
2973 + FRAME_TOP_MARGIN_HEIGHT (f)),
2974 width, flash_height);
2975 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
2976 flash_left,
2977 (height - flash_height
2978 - FRAME_INTERNAL_BORDER_WIDTH (f)),
2979 width, flash_height);
2982 else
2983 /* If it is short, flash it all. */
2984 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
2985 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
2986 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
2988 x_flush (f);
2991 struct timespec delay = make_timespec (0, 150 * 1000 * 1000);
2992 struct timespec wakeup = timespec_add (current_timespec (), delay);
2994 /* Keep waiting until past the time wakeup or any input gets
2995 available. */
2996 while (! detect_input_pending ())
2998 struct timespec current = current_timespec ();
2999 struct timespec timeout;
3001 /* Break if result would not be positive. */
3002 if (timespec_cmp (wakeup, current) <= 0)
3003 break;
3005 /* How long `select' should wait. */
3006 timeout = make_timespec (0, 10 * 1000 * 1000);
3008 /* Try to wait that long--but we might wake up sooner. */
3009 pselect (0, NULL, NULL, NULL, &timeout, NULL);
3013 /* If window is tall, flash top and bottom line. */
3014 if (height > 3 * FRAME_LINE_HEIGHT (f))
3016 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3017 flash_left,
3018 (FRAME_INTERNAL_BORDER_WIDTH (f)
3019 + FRAME_TOP_MARGIN_HEIGHT (f)),
3020 width, flash_height);
3021 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3022 flash_left,
3023 (height - flash_height
3024 - FRAME_INTERNAL_BORDER_WIDTH (f)),
3025 width, flash_height);
3027 else
3028 /* If it is short, flash it all. */
3029 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3030 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
3031 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
3033 #ifdef USE_GTK
3034 #ifdef HAVE_GTK3
3035 cairo_destroy (cr);
3036 #else
3037 g_object_unref (G_OBJECT (gc));
3038 #endif
3039 #undef XFillRectangle
3040 #else
3041 XFreeGC (FRAME_X_DISPLAY (f), gc);
3042 #endif
3043 x_flush (f);
3047 unblock_input ();
3051 static void
3052 XTtoggle_invisible_pointer (struct frame *f, int invisible)
3054 block_input ();
3055 if (invisible)
3057 if (FRAME_DISPLAY_INFO (f)->invisible_cursor != 0)
3058 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3059 FRAME_DISPLAY_INFO (f)->invisible_cursor);
3061 else
3062 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3063 f->output_data.x->current_cursor);
3064 f->pointer_invisible = invisible;
3065 unblock_input ();
3069 /* Make audible bell. */
3071 static void
3072 XTring_bell (struct frame *f)
3074 if (FRAME_X_DISPLAY (f))
3076 if (visible_bell)
3077 XTflash (f);
3078 else
3080 block_input ();
3081 #ifdef HAVE_XKB
3082 XkbBell (FRAME_X_DISPLAY (f), None, 0, None);
3083 #else
3084 XBell (FRAME_X_DISPLAY (f), 0);
3085 #endif
3086 XFlush (FRAME_X_DISPLAY (f));
3087 unblock_input ();
3092 /***********************************************************************
3093 Line Dance
3094 ***********************************************************************/
3096 /* Perform an insert-lines or delete-lines operation, inserting N
3097 lines or deleting -N lines at vertical position VPOS. */
3099 static void
3100 x_ins_del_lines (struct frame *f, int vpos, int n)
3102 emacs_abort ();
3106 /* Scroll part of the display as described by RUN. */
3108 static void
3109 x_scroll_run (struct window *w, struct run *run)
3111 struct frame *f = XFRAME (w->frame);
3112 int x, y, width, height, from_y, to_y, bottom_y;
3114 /* Get frame-relative bounding box of the text display area of W,
3115 without mode lines. Include in this box the left and right
3116 fringe of W. */
3117 window_box (w, ANY_AREA, &x, &y, &width, &height);
3119 #ifdef USE_TOOLKIT_SCROLL_BARS
3120 /* If the fringe is adjacent to the left (right) scroll bar of a
3121 leftmost (rightmost, respectively) window, then extend its
3122 background to the gap between the fringe and the bar. */
3123 if ((WINDOW_LEFTMOST_P (w)
3124 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
3125 || (WINDOW_RIGHTMOST_P (w)
3126 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w)))
3128 int sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
3130 if (sb_width > 0)
3132 int bar_area_x = WINDOW_SCROLL_BAR_AREA_X (w);
3133 int bar_area_width = (WINDOW_CONFIG_SCROLL_BAR_COLS (w)
3134 * FRAME_COLUMN_WIDTH (f));
3136 if (bar_area_x + bar_area_width == x)
3138 x = bar_area_x + sb_width;
3139 width += bar_area_width - sb_width;
3141 else if (x + width == bar_area_x)
3142 width += bar_area_width - sb_width;
3145 #endif
3147 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
3148 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
3149 bottom_y = y + height;
3151 if (to_y < from_y)
3153 /* Scrolling up. Make sure we don't copy part of the mode
3154 line at the bottom. */
3155 if (from_y + run->height > bottom_y)
3156 height = bottom_y - from_y;
3157 else
3158 height = run->height;
3160 else
3162 /* Scrolling down. Make sure we don't copy over the mode line.
3163 at the bottom. */
3164 if (to_y + run->height > bottom_y)
3165 height = bottom_y - to_y;
3166 else
3167 height = run->height;
3170 block_input ();
3172 /* Cursor off. Will be switched on again in x_update_window_end. */
3173 x_clear_cursor (w);
3175 XCopyArea (FRAME_X_DISPLAY (f),
3176 FRAME_X_WINDOW (f), FRAME_X_WINDOW (f),
3177 f->output_data.x->normal_gc,
3178 x, from_y,
3179 width, height,
3180 x, to_y);
3182 unblock_input ();
3187 /***********************************************************************
3188 Exposure Events
3189 ***********************************************************************/
3192 static void
3193 frame_highlight (struct frame *f)
3195 /* We used to only do this if Vx_no_window_manager was non-nil, but
3196 the ICCCM (section 4.1.6) says that the window's border pixmap
3197 and border pixel are window attributes which are "private to the
3198 client", so we can always change it to whatever we want. */
3199 block_input ();
3200 /* I recently started to get errors in this XSetWindowBorder, depending on
3201 the window-manager in use, tho something more is at play since I've been
3202 using that same window-manager binary for ever. Let's not crash just
3203 because of this (bug#9310). */
3204 x_catch_errors (FRAME_X_DISPLAY (f));
3205 XSetWindowBorder (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3206 f->output_data.x->border_pixel);
3207 x_uncatch_errors ();
3208 unblock_input ();
3209 x_update_cursor (f, 1);
3210 x_set_frame_alpha (f);
3213 static void
3214 frame_unhighlight (struct frame *f)
3216 /* We used to only do this if Vx_no_window_manager was non-nil, but
3217 the ICCCM (section 4.1.6) says that the window's border pixmap
3218 and border pixel are window attributes which are "private to the
3219 client", so we can always change it to whatever we want. */
3220 block_input ();
3221 /* Same as above for XSetWindowBorder (bug#9310). */
3222 x_catch_errors (FRAME_X_DISPLAY (f));
3223 XSetWindowBorderPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3224 f->output_data.x->border_tile);
3225 x_uncatch_errors ();
3226 unblock_input ();
3227 x_update_cursor (f, 1);
3228 x_set_frame_alpha (f);
3231 /* The focus has changed. Update the frames as necessary to reflect
3232 the new situation. Note that we can't change the selected frame
3233 here, because the Lisp code we are interrupting might become confused.
3234 Each event gets marked with the frame in which it occurred, so the
3235 Lisp code can tell when the switch took place by examining the events. */
3237 static void
3238 x_new_focus_frame (struct x_display_info *dpyinfo, struct frame *frame)
3240 struct frame *old_focus = dpyinfo->x_focus_frame;
3242 if (frame != dpyinfo->x_focus_frame)
3244 /* Set this before calling other routines, so that they see
3245 the correct value of x_focus_frame. */
3246 dpyinfo->x_focus_frame = frame;
3248 if (old_focus && old_focus->auto_lower)
3249 x_lower_frame (old_focus);
3251 if (dpyinfo->x_focus_frame && dpyinfo->x_focus_frame->auto_raise)
3252 dpyinfo->x_pending_autoraise_frame = dpyinfo->x_focus_frame;
3253 else
3254 dpyinfo->x_pending_autoraise_frame = NULL;
3257 x_frame_rehighlight (dpyinfo);
3260 /* Handle FocusIn and FocusOut state changes for FRAME.
3261 If FRAME has focus and there exists more than one frame, puts
3262 a FOCUS_IN_EVENT into *BUFP. */
3264 static void
3265 x_focus_changed (int type, int state, struct x_display_info *dpyinfo, struct frame *frame, struct input_event *bufp)
3267 if (type == FocusIn)
3269 if (dpyinfo->x_focus_event_frame != frame)
3271 x_new_focus_frame (dpyinfo, frame);
3272 dpyinfo->x_focus_event_frame = frame;
3274 /* Don't stop displaying the initial startup message
3275 for a switch-frame event we don't need. */
3276 /* When run as a daemon, Vterminal_frame is always NIL. */
3277 bufp->arg = (((NILP (Vterminal_frame) || EQ (Fdaemonp (), Qt))
3278 && CONSP (Vframe_list)
3279 && !NILP (XCDR (Vframe_list)))
3280 ? Qt : Qnil);
3281 bufp->kind = FOCUS_IN_EVENT;
3282 XSETFRAME (bufp->frame_or_window, frame);
3285 frame->output_data.x->focus_state |= state;
3287 #ifdef HAVE_X_I18N
3288 if (FRAME_XIC (frame))
3289 XSetICFocus (FRAME_XIC (frame));
3290 #endif
3292 else if (type == FocusOut)
3294 frame->output_data.x->focus_state &= ~state;
3296 if (dpyinfo->x_focus_event_frame == frame)
3298 dpyinfo->x_focus_event_frame = 0;
3299 x_new_focus_frame (dpyinfo, 0);
3301 bufp->kind = FOCUS_OUT_EVENT;
3302 XSETFRAME (bufp->frame_or_window, frame);
3305 #ifdef HAVE_X_I18N
3306 if (FRAME_XIC (frame))
3307 XUnsetICFocus (FRAME_XIC (frame));
3308 #endif
3309 if (frame->pointer_invisible)
3310 XTtoggle_invisible_pointer (frame, 0);
3314 /* Return the Emacs frame-object corresponding to an X window.
3315 It could be the frame's main window or an icon window. */
3317 static struct frame *
3318 x_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
3320 Lisp_Object tail, frame;
3321 struct frame *f;
3323 if (wdesc == None)
3324 return NULL;
3326 FOR_EACH_FRAME (tail, frame)
3328 f = XFRAME (frame);
3329 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
3330 continue;
3331 if (f->output_data.x->hourglass_window == wdesc)
3332 return f;
3333 #ifdef USE_X_TOOLKIT
3334 if ((f->output_data.x->edit_widget
3335 && XtWindow (f->output_data.x->edit_widget) == wdesc)
3336 /* A tooltip frame? */
3337 || (!f->output_data.x->edit_widget
3338 && FRAME_X_WINDOW (f) == wdesc)
3339 || f->output_data.x->icon_desc == wdesc)
3340 return f;
3341 #else /* not USE_X_TOOLKIT */
3342 #ifdef USE_GTK
3343 if (f->output_data.x->edit_widget)
3345 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
3346 struct x_output *x = f->output_data.x;
3347 if (gwdesc != 0 && gwdesc == x->edit_widget)
3348 return f;
3350 #endif /* USE_GTK */
3351 if (FRAME_X_WINDOW (f) == wdesc
3352 || f->output_data.x->icon_desc == wdesc)
3353 return f;
3354 #endif /* not USE_X_TOOLKIT */
3356 return 0;
3359 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
3361 /* Like x_window_to_frame but also compares the window with the widget's
3362 windows. */
3364 static struct frame *
3365 x_any_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
3367 Lisp_Object tail, frame;
3368 struct frame *f, *found = NULL;
3369 struct x_output *x;
3371 if (wdesc == None)
3372 return NULL;
3374 FOR_EACH_FRAME (tail, frame)
3376 if (found)
3377 break;
3378 f = XFRAME (frame);
3379 if (FRAME_X_P (f) && FRAME_DISPLAY_INFO (f) == dpyinfo)
3381 /* This frame matches if the window is any of its widgets. */
3382 x = f->output_data.x;
3383 if (x->hourglass_window == wdesc)
3384 found = f;
3385 else if (x->widget)
3387 #ifdef USE_GTK
3388 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
3389 if (gwdesc != 0
3390 && gtk_widget_get_toplevel (gwdesc) == x->widget)
3391 found = f;
3392 #else
3393 if (wdesc == XtWindow (x->widget)
3394 || wdesc == XtWindow (x->column_widget)
3395 || wdesc == XtWindow (x->edit_widget))
3396 found = f;
3397 /* Match if the window is this frame's menubar. */
3398 else if (lw_window_is_in_menubar (wdesc, x->menubar_widget))
3399 found = f;
3400 #endif
3402 else if (FRAME_X_WINDOW (f) == wdesc)
3403 /* A tooltip frame. */
3404 found = f;
3408 return found;
3411 /* Likewise, but consider only the menu bar widget. */
3413 static struct frame *
3414 x_menubar_window_to_frame (struct x_display_info *dpyinfo,
3415 const XEvent *event)
3417 Window wdesc = event->xany.window;
3418 Lisp_Object tail, frame;
3419 struct frame *f;
3420 struct x_output *x;
3422 if (wdesc == None)
3423 return NULL;
3425 FOR_EACH_FRAME (tail, frame)
3427 f = XFRAME (frame);
3428 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
3429 continue;
3430 x = f->output_data.x;
3431 #ifdef USE_GTK
3432 if (x->menubar_widget && xg_event_is_for_menubar (f, event))
3433 return f;
3434 #else
3435 /* Match if the window is this frame's menubar. */
3436 if (x->menubar_widget
3437 && lw_window_is_in_menubar (wdesc, x->menubar_widget))
3438 return f;
3439 #endif
3441 return 0;
3444 /* Return the frame whose principal (outermost) window is WDESC.
3445 If WDESC is some other (smaller) window, we return 0. */
3447 struct frame *
3448 x_top_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
3450 Lisp_Object tail, frame;
3451 struct frame *f;
3452 struct x_output *x;
3454 if (wdesc == None)
3455 return NULL;
3457 FOR_EACH_FRAME (tail, frame)
3459 f = XFRAME (frame);
3460 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
3461 continue;
3462 x = f->output_data.x;
3464 if (x->widget)
3466 /* This frame matches if the window is its topmost widget. */
3467 #ifdef USE_GTK
3468 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
3469 if (gwdesc == x->widget)
3470 return f;
3471 #else
3472 if (wdesc == XtWindow (x->widget))
3473 return f;
3474 #endif
3476 else if (FRAME_X_WINDOW (f) == wdesc)
3477 /* Tooltip frame. */
3478 return f;
3480 return 0;
3483 #else /* !USE_X_TOOLKIT && !USE_GTK */
3485 #define x_any_window_to_frame(d, i) x_window_to_frame (d, i)
3486 #define x_top_window_to_frame(d, i) x_window_to_frame (d, i)
3488 #endif /* USE_X_TOOLKIT || USE_GTK */
3490 /* The focus may have changed. Figure out if it is a real focus change,
3491 by checking both FocusIn/Out and Enter/LeaveNotify events.
3493 Returns FOCUS_IN_EVENT event in *BUFP. */
3495 static void
3496 x_detect_focus_change (struct x_display_info *dpyinfo, struct frame *frame,
3497 const XEvent *event, struct input_event *bufp)
3499 if (!frame)
3500 return;
3502 switch (event->type)
3504 case EnterNotify:
3505 case LeaveNotify:
3507 struct frame *focus_frame = dpyinfo->x_focus_event_frame;
3508 int focus_state
3509 = focus_frame ? focus_frame->output_data.x->focus_state : 0;
3511 if (event->xcrossing.detail != NotifyInferior
3512 && event->xcrossing.focus
3513 && ! (focus_state & FOCUS_EXPLICIT))
3514 x_focus_changed ((event->type == EnterNotify ? FocusIn : FocusOut),
3515 FOCUS_IMPLICIT,
3516 dpyinfo, frame, bufp);
3518 break;
3520 case FocusIn:
3521 case FocusOut:
3522 x_focus_changed (event->type,
3523 (event->xfocus.detail == NotifyPointer ?
3524 FOCUS_IMPLICIT : FOCUS_EXPLICIT),
3525 dpyinfo, frame, bufp);
3526 break;
3528 case ClientMessage:
3529 if (event->xclient.message_type == dpyinfo->Xatom_XEMBED)
3531 enum xembed_message msg = event->xclient.data.l[1];
3532 x_focus_changed ((msg == XEMBED_FOCUS_IN ? FocusIn : FocusOut),
3533 FOCUS_EXPLICIT, dpyinfo, frame, bufp);
3535 break;
3540 #if defined HAVE_MENUS && !defined USE_X_TOOLKIT && !defined USE_GTK
3541 /* Handle an event saying the mouse has moved out of an Emacs frame. */
3543 void
3544 x_mouse_leave (struct x_display_info *dpyinfo)
3546 x_new_focus_frame (dpyinfo, dpyinfo->x_focus_event_frame);
3548 #endif
3550 /* The focus has changed, or we have redirected a frame's focus to
3551 another frame (this happens when a frame uses a surrogate
3552 mini-buffer frame). Shift the highlight as appropriate.
3554 The FRAME argument doesn't necessarily have anything to do with which
3555 frame is being highlighted or un-highlighted; we only use it to find
3556 the appropriate X display info. */
3558 static void
3559 XTframe_rehighlight (struct frame *frame)
3561 x_frame_rehighlight (FRAME_DISPLAY_INFO (frame));
3564 static void
3565 x_frame_rehighlight (struct x_display_info *dpyinfo)
3567 struct frame *old_highlight = dpyinfo->x_highlight_frame;
3569 if (dpyinfo->x_focus_frame)
3571 dpyinfo->x_highlight_frame
3572 = ((FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame)))
3573 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
3574 : dpyinfo->x_focus_frame);
3575 if (! FRAME_LIVE_P (dpyinfo->x_highlight_frame))
3577 fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
3578 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
3581 else
3582 dpyinfo->x_highlight_frame = 0;
3584 if (dpyinfo->x_highlight_frame != old_highlight)
3586 if (old_highlight)
3587 frame_unhighlight (old_highlight);
3588 if (dpyinfo->x_highlight_frame)
3589 frame_highlight (dpyinfo->x_highlight_frame);
3595 /* Keyboard processing - modifier keys, vendor-specific keysyms, etc. */
3597 /* Initialize mode_switch_bit and modifier_meaning. */
3598 static void
3599 x_find_modifier_meanings (struct x_display_info *dpyinfo)
3601 int min_code, max_code;
3602 KeySym *syms;
3603 int syms_per_code;
3604 XModifierKeymap *mods;
3606 dpyinfo->meta_mod_mask = 0;
3607 dpyinfo->shift_lock_mask = 0;
3608 dpyinfo->alt_mod_mask = 0;
3609 dpyinfo->super_mod_mask = 0;
3610 dpyinfo->hyper_mod_mask = 0;
3612 XDisplayKeycodes (dpyinfo->display, &min_code, &max_code);
3614 syms = XGetKeyboardMapping (dpyinfo->display,
3615 min_code, max_code - min_code + 1,
3616 &syms_per_code);
3617 mods = XGetModifierMapping (dpyinfo->display);
3619 /* Scan the modifier table to see which modifier bits the Meta and
3620 Alt keysyms are on. */
3622 int row, col; /* The row and column in the modifier table. */
3623 int found_alt_or_meta;
3625 for (row = 3; row < 8; row++)
3627 found_alt_or_meta = 0;
3628 for (col = 0; col < mods->max_keypermod; col++)
3630 KeyCode code = mods->modifiermap[(row * mods->max_keypermod) + col];
3632 /* Zeroes are used for filler. Skip them. */
3633 if (code == 0)
3634 continue;
3636 /* Are any of this keycode's keysyms a meta key? */
3638 int code_col;
3640 for (code_col = 0; code_col < syms_per_code; code_col++)
3642 int sym = syms[((code - min_code) * syms_per_code) + code_col];
3644 switch (sym)
3646 case XK_Meta_L:
3647 case XK_Meta_R:
3648 found_alt_or_meta = 1;
3649 dpyinfo->meta_mod_mask |= (1 << row);
3650 break;
3652 case XK_Alt_L:
3653 case XK_Alt_R:
3654 found_alt_or_meta = 1;
3655 dpyinfo->alt_mod_mask |= (1 << row);
3656 break;
3658 case XK_Hyper_L:
3659 case XK_Hyper_R:
3660 if (!found_alt_or_meta)
3661 dpyinfo->hyper_mod_mask |= (1 << row);
3662 code_col = syms_per_code;
3663 col = mods->max_keypermod;
3664 break;
3666 case XK_Super_L:
3667 case XK_Super_R:
3668 if (!found_alt_or_meta)
3669 dpyinfo->super_mod_mask |= (1 << row);
3670 code_col = syms_per_code;
3671 col = mods->max_keypermod;
3672 break;
3674 case XK_Shift_Lock:
3675 /* Ignore this if it's not on the lock modifier. */
3676 if (!found_alt_or_meta && ((1 << row) == LockMask))
3677 dpyinfo->shift_lock_mask = LockMask;
3678 code_col = syms_per_code;
3679 col = mods->max_keypermod;
3680 break;
3688 /* If we couldn't find any meta keys, accept any alt keys as meta keys. */
3689 if (! dpyinfo->meta_mod_mask)
3691 dpyinfo->meta_mod_mask = dpyinfo->alt_mod_mask;
3692 dpyinfo->alt_mod_mask = 0;
3695 /* If some keys are both alt and meta,
3696 make them just meta, not alt. */
3697 if (dpyinfo->alt_mod_mask & dpyinfo->meta_mod_mask)
3699 dpyinfo->alt_mod_mask &= ~dpyinfo->meta_mod_mask;
3702 XFree (syms);
3703 XFreeModifiermap (mods);
3706 /* Convert between the modifier bits X uses and the modifier bits
3707 Emacs uses. */
3710 x_x_to_emacs_modifiers (struct x_display_info *dpyinfo, int state)
3712 int mod_meta = meta_modifier;
3713 int mod_alt = alt_modifier;
3714 int mod_hyper = hyper_modifier;
3715 int mod_super = super_modifier;
3716 Lisp_Object tem;
3718 tem = Fget (Vx_alt_keysym, Qmodifier_value);
3719 if (INTEGERP (tem)) mod_alt = XINT (tem) & INT_MAX;
3720 tem = Fget (Vx_meta_keysym, Qmodifier_value);
3721 if (INTEGERP (tem)) mod_meta = XINT (tem) & INT_MAX;
3722 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
3723 if (INTEGERP (tem)) mod_hyper = XINT (tem) & INT_MAX;
3724 tem = Fget (Vx_super_keysym, Qmodifier_value);
3725 if (INTEGERP (tem)) mod_super = XINT (tem) & INT_MAX;
3727 return ( ((state & (ShiftMask | dpyinfo->shift_lock_mask)) ? shift_modifier : 0)
3728 | ((state & ControlMask) ? ctrl_modifier : 0)
3729 | ((state & dpyinfo->meta_mod_mask) ? mod_meta : 0)
3730 | ((state & dpyinfo->alt_mod_mask) ? mod_alt : 0)
3731 | ((state & dpyinfo->super_mod_mask) ? mod_super : 0)
3732 | ((state & dpyinfo->hyper_mod_mask) ? mod_hyper : 0));
3735 static int
3736 x_emacs_to_x_modifiers (struct x_display_info *dpyinfo, EMACS_INT state)
3738 EMACS_INT mod_meta = meta_modifier;
3739 EMACS_INT mod_alt = alt_modifier;
3740 EMACS_INT mod_hyper = hyper_modifier;
3741 EMACS_INT mod_super = super_modifier;
3743 Lisp_Object tem;
3745 tem = Fget (Vx_alt_keysym, Qmodifier_value);
3746 if (INTEGERP (tem)) mod_alt = XINT (tem);
3747 tem = Fget (Vx_meta_keysym, Qmodifier_value);
3748 if (INTEGERP (tem)) mod_meta = XINT (tem);
3749 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
3750 if (INTEGERP (tem)) mod_hyper = XINT (tem);
3751 tem = Fget (Vx_super_keysym, Qmodifier_value);
3752 if (INTEGERP (tem)) mod_super = XINT (tem);
3755 return ( ((state & mod_alt) ? dpyinfo->alt_mod_mask : 0)
3756 | ((state & mod_super) ? dpyinfo->super_mod_mask : 0)
3757 | ((state & mod_hyper) ? dpyinfo->hyper_mod_mask : 0)
3758 | ((state & shift_modifier) ? ShiftMask : 0)
3759 | ((state & ctrl_modifier) ? ControlMask : 0)
3760 | ((state & mod_meta) ? dpyinfo->meta_mod_mask : 0));
3763 /* Convert a keysym to its name. */
3765 char *
3766 x_get_keysym_name (int keysym)
3768 char *value;
3770 block_input ();
3771 value = XKeysymToString (keysym);
3772 unblock_input ();
3774 return value;
3777 /* Mouse clicks and mouse movement. Rah.
3779 Formerly, we used PointerMotionHintMask (in standard_event_mask)
3780 so that we would have to call XQueryPointer after each MotionNotify
3781 event to ask for another such event. However, this made mouse tracking
3782 slow, and there was a bug that made it eventually stop.
3784 Simply asking for MotionNotify all the time seems to work better.
3786 In order to avoid asking for motion events and then throwing most
3787 of them away or busy-polling the server for mouse positions, we ask
3788 the server for pointer motion hints. This means that we get only
3789 one event per group of mouse movements. "Groups" are delimited by
3790 other kinds of events (focus changes and button clicks, for
3791 example), or by XQueryPointer calls; when one of these happens, we
3792 get another MotionNotify event the next time the mouse moves. This
3793 is at least as efficient as getting motion events when mouse
3794 tracking is on, and I suspect only negligibly worse when tracking
3795 is off. */
3797 /* Prepare a mouse-event in *RESULT for placement in the input queue.
3799 If the event is a button press, then note that we have grabbed
3800 the mouse. */
3802 static Lisp_Object
3803 construct_mouse_click (struct input_event *result,
3804 const XButtonEvent *event,
3805 struct frame *f)
3807 /* Make the event type NO_EVENT; we'll change that when we decide
3808 otherwise. */
3809 result->kind = MOUSE_CLICK_EVENT;
3810 result->code = event->button - Button1;
3811 result->timestamp = event->time;
3812 result->modifiers = (x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO (f),
3813 event->state)
3814 | (event->type == ButtonRelease
3815 ? up_modifier
3816 : down_modifier));
3818 XSETINT (result->x, event->x);
3819 XSETINT (result->y, event->y);
3820 XSETFRAME (result->frame_or_window, f);
3821 result->arg = Qnil;
3822 return Qnil;
3825 /* Function to report a mouse movement to the mainstream Emacs code.
3826 The input handler calls this.
3828 We have received a mouse movement event, which is given in *event.
3829 If the mouse is over a different glyph than it was last time, tell
3830 the mainstream emacs code by setting mouse_moved. If not, ask for
3831 another motion event, so we can check again the next time it moves. */
3833 static int
3834 note_mouse_movement (struct frame *frame, const XMotionEvent *event)
3836 XRectangle *r;
3837 struct x_display_info *dpyinfo;
3839 if (!FRAME_X_OUTPUT (frame))
3840 return 0;
3842 dpyinfo = FRAME_DISPLAY_INFO (frame);
3843 dpyinfo->last_mouse_movement_time = event->time;
3844 dpyinfo->last_mouse_motion_frame = frame;
3845 dpyinfo->last_mouse_motion_x = event->x;
3846 dpyinfo->last_mouse_motion_y = event->y;
3848 if (event->window != FRAME_X_WINDOW (frame))
3850 frame->mouse_moved = 1;
3851 dpyinfo->last_mouse_scroll_bar = NULL;
3852 note_mouse_highlight (frame, -1, -1);
3853 dpyinfo->last_mouse_glyph_frame = NULL;
3854 return 1;
3858 /* Has the mouse moved off the glyph it was on at the last sighting? */
3859 r = &dpyinfo->last_mouse_glyph;
3860 if (frame != dpyinfo->last_mouse_glyph_frame
3861 || event->x < r->x || event->x >= r->x + r->width
3862 || event->y < r->y || event->y >= r->y + r->height)
3864 frame->mouse_moved = 1;
3865 dpyinfo->last_mouse_scroll_bar = NULL;
3866 note_mouse_highlight (frame, event->x, event->y);
3867 /* Remember which glyph we're now on. */
3868 remember_mouse_glyph (frame, event->x, event->y, r);
3869 dpyinfo->last_mouse_glyph_frame = frame;
3870 return 1;
3873 return 0;
3876 /* Return the current position of the mouse.
3877 *FP should be a frame which indicates which display to ask about.
3879 If the mouse movement started in a scroll bar, set *FP, *BAR_WINDOW,
3880 and *PART to the frame, window, and scroll bar part that the mouse
3881 is over. Set *X and *Y to the portion and whole of the mouse's
3882 position on the scroll bar.
3884 If the mouse movement started elsewhere, set *FP to the frame the
3885 mouse is on, *BAR_WINDOW to nil, and *X and *Y to the character cell
3886 the mouse is over.
3888 Set *TIMESTAMP to the server time-stamp for the time at which the mouse
3889 was at this position.
3891 Don't store anything if we don't have a valid set of values to report.
3893 This clears the mouse_moved flag, so we can wait for the next mouse
3894 movement. */
3896 static void
3897 XTmouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
3898 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
3899 Time *timestamp)
3901 struct frame *f1;
3902 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (*fp);
3904 block_input ();
3906 if (dpyinfo->last_mouse_scroll_bar && insist == 0)
3907 x_scroll_bar_report_motion (fp, bar_window, part, x, y, timestamp);
3908 else
3910 Window root;
3911 int root_x, root_y;
3913 Window dummy_window;
3914 int dummy;
3916 Lisp_Object frame, tail;
3918 /* Clear the mouse-moved flag for every frame on this display. */
3919 FOR_EACH_FRAME (tail, frame)
3920 if (FRAME_X_P (XFRAME (frame))
3921 && FRAME_X_DISPLAY (XFRAME (frame)) == FRAME_X_DISPLAY (*fp))
3922 XFRAME (frame)->mouse_moved = 0;
3924 dpyinfo->last_mouse_scroll_bar = NULL;
3926 /* Figure out which root window we're on. */
3927 XQueryPointer (FRAME_X_DISPLAY (*fp),
3928 DefaultRootWindow (FRAME_X_DISPLAY (*fp)),
3930 /* The root window which contains the pointer. */
3931 &root,
3933 /* Trash which we can't trust if the pointer is on
3934 a different screen. */
3935 &dummy_window,
3937 /* The position on that root window. */
3938 &root_x, &root_y,
3940 /* More trash we can't trust. */
3941 &dummy, &dummy,
3943 /* Modifier keys and pointer buttons, about which
3944 we don't care. */
3945 (unsigned int *) &dummy);
3947 /* Now we have a position on the root; find the innermost window
3948 containing the pointer. */
3950 Window win, child;
3951 int win_x, win_y;
3952 int parent_x = 0, parent_y = 0;
3954 win = root;
3956 /* XTranslateCoordinates can get errors if the window
3957 structure is changing at the same time this function
3958 is running. So at least we must not crash from them. */
3960 x_catch_errors (FRAME_X_DISPLAY (*fp));
3962 if (x_mouse_grabbed (dpyinfo))
3964 /* If mouse was grabbed on a frame, give coords for that frame
3965 even if the mouse is now outside it. */
3966 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
3968 /* From-window. */
3969 root,
3971 /* To-window. */
3972 FRAME_X_WINDOW (dpyinfo->last_mouse_frame),
3974 /* From-position, to-position. */
3975 root_x, root_y, &win_x, &win_y,
3977 /* Child of win. */
3978 &child);
3979 f1 = dpyinfo->last_mouse_frame;
3981 else
3983 while (1)
3985 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
3987 /* From-window, to-window. */
3988 root, win,
3990 /* From-position, to-position. */
3991 root_x, root_y, &win_x, &win_y,
3993 /* Child of win. */
3994 &child);
3996 if (child == None || child == win)
3997 break;
3998 #ifdef USE_GTK
3999 /* We don't wan't to know the innermost window. We
4000 want the edit window. For non-Gtk+ the innermost
4001 window is the edit window. For Gtk+ it might not
4002 be. It might be the tool bar for example. */
4003 if (x_window_to_frame (dpyinfo, win))
4004 break;
4005 #endif
4006 win = child;
4007 parent_x = win_x;
4008 parent_y = win_y;
4011 /* Now we know that:
4012 win is the innermost window containing the pointer
4013 (XTC says it has no child containing the pointer),
4014 win_x and win_y are the pointer's position in it
4015 (XTC did this the last time through), and
4016 parent_x and parent_y are the pointer's position in win's parent.
4017 (They are what win_x and win_y were when win was child.
4018 If win is the root window, it has no parent, and
4019 parent_{x,y} are invalid, but that's okay, because we'll
4020 never use them in that case.) */
4022 #ifdef USE_GTK
4023 /* We don't wan't to know the innermost window. We
4024 want the edit window. */
4025 f1 = x_window_to_frame (dpyinfo, win);
4026 #else
4027 /* Is win one of our frames? */
4028 f1 = x_any_window_to_frame (dpyinfo, win);
4029 #endif
4031 #ifdef USE_X_TOOLKIT
4032 /* If we end up with the menu bar window, say it's not
4033 on the frame. */
4034 if (f1 != NULL
4035 && f1->output_data.x->menubar_widget
4036 && win == XtWindow (f1->output_data.x->menubar_widget))
4037 f1 = NULL;
4038 #endif /* USE_X_TOOLKIT */
4041 if (x_had_errors_p (FRAME_X_DISPLAY (*fp)))
4042 f1 = 0;
4044 x_uncatch_errors ();
4046 /* If not, is it one of our scroll bars? */
4047 if (! f1)
4049 struct scroll_bar *bar;
4051 bar = x_window_to_scroll_bar (FRAME_X_DISPLAY (*fp), win);
4053 if (bar)
4055 f1 = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
4056 win_x = parent_x;
4057 win_y = parent_y;
4061 if (f1 == 0 && insist > 0)
4062 f1 = SELECTED_FRAME ();
4064 if (f1)
4066 /* Ok, we found a frame. Store all the values.
4067 last_mouse_glyph is a rectangle used to reduce the
4068 generation of mouse events. To not miss any motion
4069 events, we must divide the frame into rectangles of the
4070 size of the smallest character that could be displayed
4071 on it, i.e. into the same rectangles that matrices on
4072 the frame are divided into. */
4074 /* FIXME: what if F1 is not an X frame? */
4075 dpyinfo = FRAME_DISPLAY_INFO (f1);
4076 remember_mouse_glyph (f1, win_x, win_y, &dpyinfo->last_mouse_glyph);
4077 dpyinfo->last_mouse_glyph_frame = f1;
4079 *bar_window = Qnil;
4080 *part = 0;
4081 *fp = f1;
4082 XSETINT (*x, win_x);
4083 XSETINT (*y, win_y);
4084 *timestamp = dpyinfo->last_mouse_movement_time;
4089 unblock_input ();
4094 /***********************************************************************
4095 Scroll bars
4096 ***********************************************************************/
4098 /* Scroll bar support. */
4100 /* Given an X window ID and a DISPLAY, find the struct scroll_bar which
4101 manages it.
4102 This can be called in GC, so we have to make sure to strip off mark
4103 bits. */
4105 static struct scroll_bar *
4106 x_window_to_scroll_bar (Display *display, Window window_id)
4108 Lisp_Object tail, frame;
4110 #if defined (USE_GTK) && defined (USE_TOOLKIT_SCROLL_BARS)
4111 window_id = (Window) xg_get_scroll_id_for_window (display, window_id);
4112 #endif /* USE_GTK && USE_TOOLKIT_SCROLL_BARS */
4114 FOR_EACH_FRAME (tail, frame)
4116 Lisp_Object bar, condemned;
4118 if (! FRAME_X_P (XFRAME (frame)))
4119 continue;
4121 /* Scan this frame's scroll bar list for a scroll bar with the
4122 right window ID. */
4123 condemned = FRAME_CONDEMNED_SCROLL_BARS (XFRAME (frame));
4124 for (bar = FRAME_SCROLL_BARS (XFRAME (frame));
4125 /* This trick allows us to search both the ordinary and
4126 condemned scroll bar lists with one loop. */
4127 ! NILP (bar) || (bar = condemned,
4128 condemned = Qnil,
4129 ! NILP (bar));
4130 bar = XSCROLL_BAR (bar)->next)
4131 if (XSCROLL_BAR (bar)->x_window == window_id &&
4132 FRAME_X_DISPLAY (XFRAME (frame)) == display)
4133 return XSCROLL_BAR (bar);
4136 return NULL;
4140 #if defined USE_LUCID
4142 /* Return the Lucid menu bar WINDOW is part of. Return null
4143 if WINDOW is not part of a menu bar. */
4145 static Widget
4146 x_window_to_menu_bar (Window window)
4148 Lisp_Object tail, frame;
4150 FOR_EACH_FRAME (tail, frame)
4151 if (FRAME_X_P (XFRAME (frame)))
4153 Widget menu_bar = XFRAME (frame)->output_data.x->menubar_widget;
4155 if (menu_bar && xlwmenu_window_p (menu_bar, window))
4156 return menu_bar;
4158 return NULL;
4161 #endif /* USE_LUCID */
4164 /************************************************************************
4165 Toolkit scroll bars
4166 ************************************************************************/
4168 #ifdef USE_TOOLKIT_SCROLL_BARS
4170 static void x_send_scroll_bar_event (Lisp_Object, int, int, int);
4172 /* Lisp window being scrolled. Set when starting to interact with
4173 a toolkit scroll bar, reset to nil when ending the interaction. */
4175 static Lisp_Object window_being_scrolled;
4177 /* Whether this is an Xaw with arrow-scrollbars. This should imply
4178 that movements of 1/20 of the screen size are mapped to up/down. */
4180 #ifndef USE_GTK
4181 /* Id of action hook installed for scroll bars. */
4183 static XtActionHookId action_hook_id;
4185 static Boolean xaw3d_arrow_scroll;
4187 /* Whether the drag scrolling maintains the mouse at the top of the
4188 thumb. If not, resizing the thumb needs to be done more carefully
4189 to avoid jerkiness. */
4191 static Boolean xaw3d_pick_top;
4193 /* Action hook installed via XtAppAddActionHook when toolkit scroll
4194 bars are used.. The hook is responsible for detecting when
4195 the user ends an interaction with the scroll bar, and generates
4196 a `end-scroll' SCROLL_BAR_CLICK_EVENT' event if so. */
4198 static void
4199 xt_action_hook (Widget widget, XtPointer client_data, String action_name,
4200 XEvent *event, String *params, Cardinal *num_params)
4202 int scroll_bar_p;
4203 const char *end_action;
4205 #ifdef USE_MOTIF
4206 scroll_bar_p = XmIsScrollBar (widget);
4207 end_action = "Release";
4208 #else /* !USE_MOTIF i.e. use Xaw */
4209 scroll_bar_p = XtIsSubclass (widget, scrollbarWidgetClass);
4210 end_action = "EndScroll";
4211 #endif /* USE_MOTIF */
4213 if (scroll_bar_p
4214 && strcmp (action_name, end_action) == 0
4215 && WINDOWP (window_being_scrolled))
4217 struct window *w;
4218 struct scroll_bar *bar;
4220 x_send_scroll_bar_event (window_being_scrolled,
4221 scroll_bar_end_scroll, 0, 0);
4222 w = XWINDOW (window_being_scrolled);
4223 bar = XSCROLL_BAR (w->vertical_scroll_bar);
4225 if (bar->dragging != -1)
4227 bar->dragging = -1;
4228 /* The thumb size is incorrect while dragging: fix it. */
4229 set_vertical_scroll_bar (w);
4231 window_being_scrolled = Qnil;
4232 #if defined (USE_LUCID)
4233 bar->last_seen_part = scroll_bar_nowhere;
4234 #endif
4235 /* Xt timeouts no longer needed. */
4236 toolkit_scroll_bar_interaction = 0;
4239 #endif /* not USE_GTK */
4241 /* Send a client message with message type Xatom_Scrollbar for a
4242 scroll action to the frame of WINDOW. PART is a value identifying
4243 the part of the scroll bar that was clicked on. PORTION is the
4244 amount to scroll of a whole of WHOLE. */
4246 static void
4247 x_send_scroll_bar_event (Lisp_Object window, int part, int portion, int whole)
4249 XEvent event;
4250 XClientMessageEvent *ev = &event.xclient;
4251 struct window *w = XWINDOW (window);
4252 struct frame *f = XFRAME (w->frame);
4253 intptr_t iw = (intptr_t) w;
4254 enum { BITS_PER_INTPTR = CHAR_BIT * sizeof iw };
4255 verify (BITS_PER_INTPTR <= 64);
4256 int sign_shift = BITS_PER_INTPTR - 32;
4258 block_input ();
4260 /* Construct a ClientMessage event to send to the frame. */
4261 ev->type = ClientMessage;
4262 ev->message_type = FRAME_DISPLAY_INFO (f)->Xatom_Scrollbar;
4263 ev->display = FRAME_X_DISPLAY (f);
4264 ev->window = FRAME_X_WINDOW (f);
4265 ev->format = 32;
4267 /* A 32-bit X client on a 64-bit X server can pass a window pointer
4268 as-is. A 64-bit client on a 32-bit X server is in trouble
4269 because a pointer does not fit and would be truncated while
4270 passing through the server. So use two slots and hope that X12
4271 will resolve such issues someday. */
4272 ev->data.l[0] = iw >> 31 >> 1;
4273 ev->data.l[1] = sign_shift <= 0 ? iw : iw << sign_shift >> sign_shift;
4274 ev->data.l[2] = part;
4275 ev->data.l[3] = portion;
4276 ev->data.l[4] = whole;
4278 /* Make Xt timeouts work while the scroll bar is active. */
4279 #ifdef USE_X_TOOLKIT
4280 toolkit_scroll_bar_interaction = 1;
4281 x_activate_timeout_atimer ();
4282 #endif
4284 /* Setting the event mask to zero means that the message will
4285 be sent to the client that created the window, and if that
4286 window no longer exists, no event will be sent. */
4287 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), False, 0, &event);
4288 unblock_input ();
4292 /* Transform a scroll bar ClientMessage EVENT to an Emacs input event
4293 in *IEVENT. */
4295 static void
4296 x_scroll_bar_to_input_event (const XEvent *event,
4297 struct input_event *ievent)
4299 const XClientMessageEvent *ev = &event->xclient;
4300 Lisp_Object window;
4301 struct window *w;
4303 /* See the comment in the function above. */
4304 intptr_t iw0 = ev->data.l[0];
4305 intptr_t iw1 = ev->data.l[1];
4306 intptr_t iw = (iw0 << 31 << 1) + (iw1 & 0xffffffffu);
4307 w = (struct window *) iw;
4309 XSETWINDOW (window, w);
4311 ievent->kind = SCROLL_BAR_CLICK_EVENT;
4312 ievent->frame_or_window = window;
4313 ievent->arg = Qnil;
4314 #ifdef USE_GTK
4315 ievent->timestamp = CurrentTime;
4316 #else
4317 ievent->timestamp =
4318 XtLastTimestampProcessed (FRAME_X_DISPLAY (XFRAME (w->frame)));
4319 #endif
4320 ievent->code = 0;
4321 ievent->part = ev->data.l[2];
4322 ievent->x = make_number (ev->data.l[3]);
4323 ievent->y = make_number (ev->data.l[4]);
4324 ievent->modifiers = 0;
4328 #ifdef USE_MOTIF
4330 /* Minimum and maximum values used for Motif scroll bars. */
4332 #define XM_SB_MAX 10000000
4335 /* Scroll bar callback for Motif scroll bars. WIDGET is the scroll
4336 bar widget. CLIENT_DATA is a pointer to the scroll_bar structure.
4337 CALL_DATA is a pointer to a XmScrollBarCallbackStruct. */
4339 static void
4340 xm_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
4342 struct scroll_bar *bar = client_data;
4343 XmScrollBarCallbackStruct *cs = call_data;
4344 int part = -1, whole = 0, portion = 0;
4346 switch (cs->reason)
4348 case XmCR_DECREMENT:
4349 bar->dragging = -1;
4350 part = scroll_bar_up_arrow;
4351 break;
4353 case XmCR_INCREMENT:
4354 bar->dragging = -1;
4355 part = scroll_bar_down_arrow;
4356 break;
4358 case XmCR_PAGE_DECREMENT:
4359 bar->dragging = -1;
4360 part = scroll_bar_above_handle;
4361 break;
4363 case XmCR_PAGE_INCREMENT:
4364 bar->dragging = -1;
4365 part = scroll_bar_below_handle;
4366 break;
4368 case XmCR_TO_TOP:
4369 bar->dragging = -1;
4370 part = scroll_bar_to_top;
4371 break;
4373 case XmCR_TO_BOTTOM:
4374 bar->dragging = -1;
4375 part = scroll_bar_to_bottom;
4376 break;
4378 case XmCR_DRAG:
4380 int slider_size;
4382 /* Get the slider size. */
4383 block_input ();
4384 XtVaGetValues (widget, XmNsliderSize, &slider_size, NULL);
4385 unblock_input ();
4387 whole = XM_SB_MAX - slider_size;
4388 portion = min (cs->value, whole);
4389 part = scroll_bar_handle;
4390 bar->dragging = cs->value;
4392 break;
4394 case XmCR_VALUE_CHANGED:
4395 break;
4398 if (part >= 0)
4400 window_being_scrolled = bar->window;
4401 x_send_scroll_bar_event (bar->window, part, portion, whole);
4405 #elif defined USE_GTK
4407 /* Scroll bar callback for GTK scroll bars. WIDGET is the scroll
4408 bar widget. DATA is a pointer to the scroll_bar structure. */
4410 static gboolean
4411 xg_scroll_callback (GtkRange *range,
4412 GtkScrollType scroll,
4413 gdouble value,
4414 gpointer user_data)
4416 struct scroll_bar *bar = user_data;
4417 gdouble position;
4418 int part = -1, whole = 0, portion = 0;
4419 GtkAdjustment *adj = GTK_ADJUSTMENT (gtk_range_get_adjustment (range));
4420 struct frame *f = g_object_get_data (G_OBJECT (range), XG_FRAME_DATA);
4422 if (xg_ignore_gtk_scrollbar) return FALSE;
4423 position = gtk_adjustment_get_value (adj);
4426 switch (scroll)
4428 case GTK_SCROLL_JUMP:
4429 /* Buttons 1 2 or 3 must be grabbed. */
4430 if (FRAME_DISPLAY_INFO (f)->grabbed != 0
4431 && FRAME_DISPLAY_INFO (f)->grabbed < (1 << 4))
4433 part = scroll_bar_handle;
4434 whole = gtk_adjustment_get_upper (adj) -
4435 gtk_adjustment_get_page_size (adj);
4436 portion = min ((int)position, whole);
4437 bar->dragging = portion;
4439 break;
4440 case GTK_SCROLL_STEP_BACKWARD:
4441 part = scroll_bar_up_arrow;
4442 bar->dragging = -1;
4443 break;
4444 case GTK_SCROLL_STEP_FORWARD:
4445 part = scroll_bar_down_arrow;
4446 bar->dragging = -1;
4447 break;
4448 case GTK_SCROLL_PAGE_BACKWARD:
4449 part = scroll_bar_above_handle;
4450 bar->dragging = -1;
4451 break;
4452 case GTK_SCROLL_PAGE_FORWARD:
4453 part = scroll_bar_below_handle;
4454 bar->dragging = -1;
4455 break;
4458 if (part >= 0)
4460 window_being_scrolled = bar->window;
4461 x_send_scroll_bar_event (bar->window, part, portion, whole);
4464 return FALSE;
4467 /* Callback for button release. Sets dragging to -1 when dragging is done. */
4469 static gboolean
4470 xg_end_scroll_callback (GtkWidget *widget,
4471 GdkEventButton *event,
4472 gpointer user_data)
4474 struct scroll_bar *bar = user_data;
4475 bar->dragging = -1;
4476 if (WINDOWP (window_being_scrolled))
4478 x_send_scroll_bar_event (window_being_scrolled,
4479 scroll_bar_end_scroll, 0, 0);
4480 window_being_scrolled = Qnil;
4483 return FALSE;
4487 #else /* not USE_GTK and not USE_MOTIF */
4489 /* Xaw scroll bar callback. Invoked when the thumb is dragged.
4490 WIDGET is the scroll bar widget. CLIENT_DATA is a pointer to the
4491 scroll bar struct. CALL_DATA is a pointer to a float saying where
4492 the thumb is. */
4494 static void
4495 xaw_jump_callback (Widget widget, XtPointer client_data, XtPointer call_data)
4497 struct scroll_bar *bar = client_data;
4498 float *top_addr = call_data;
4499 float top = *top_addr;
4500 float shown;
4501 int whole, portion, height;
4502 enum scroll_bar_part part;
4504 /* Get the size of the thumb, a value between 0 and 1. */
4505 block_input ();
4506 XtVaGetValues (widget, XtNshown, &shown, XtNheight, &height, NULL);
4507 unblock_input ();
4509 whole = 10000000;
4510 portion = shown < 1 ? top * whole : 0;
4512 if (shown < 1 && (eabs (top + shown - 1) < 1.0f / height))
4513 /* Some derivatives of Xaw refuse to shrink the thumb when you reach
4514 the bottom, so we force the scrolling whenever we see that we're
4515 too close to the bottom (in x_set_toolkit_scroll_bar_thumb
4516 we try to ensure that we always stay two pixels away from the
4517 bottom). */
4518 part = scroll_bar_down_arrow;
4519 else
4520 part = scroll_bar_handle;
4522 window_being_scrolled = bar->window;
4523 bar->dragging = portion;
4524 bar->last_seen_part = part;
4525 x_send_scroll_bar_event (bar->window, part, portion, whole);
4529 /* Xaw scroll bar callback. Invoked for incremental scrolling.,
4530 i.e. line or page up or down. WIDGET is the Xaw scroll bar
4531 widget. CLIENT_DATA is a pointer to the scroll_bar structure for
4532 the scroll bar. CALL_DATA is an integer specifying the action that
4533 has taken place. Its magnitude is in the range 0..height of the
4534 scroll bar. Negative values mean scroll towards buffer start.
4535 Values < height of scroll bar mean line-wise movement. */
4537 static void
4538 xaw_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
4540 struct scroll_bar *bar = client_data;
4541 /* The position really is stored cast to a pointer. */
4542 int position = (intptr_t) call_data;
4543 Dimension height;
4544 enum scroll_bar_part part;
4546 /* Get the height of the scroll bar. */
4547 block_input ();
4548 XtVaGetValues (widget, XtNheight, &height, NULL);
4549 unblock_input ();
4551 if (eabs (position) >= height)
4552 part = (position < 0) ? scroll_bar_above_handle : scroll_bar_below_handle;
4554 /* If Xaw3d was compiled with ARROW_SCROLLBAR,
4555 it maps line-movement to call_data = max(5, height/20). */
4556 else if (xaw3d_arrow_scroll && eabs (position) <= max (5, height / 20))
4557 part = (position < 0) ? scroll_bar_up_arrow : scroll_bar_down_arrow;
4558 else
4559 part = scroll_bar_move_ratio;
4561 window_being_scrolled = bar->window;
4562 bar->dragging = -1;
4563 bar->last_seen_part = part;
4564 x_send_scroll_bar_event (bar->window, part, position, height);
4567 #endif /* not USE_GTK and not USE_MOTIF */
4569 #define SCROLL_BAR_NAME "verticalScrollBar"
4571 /* Create the widget for scroll bar BAR on frame F. Record the widget
4572 and X window of the scroll bar in BAR. */
4574 #ifdef USE_GTK
4575 static void
4576 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
4578 const char *scroll_bar_name = SCROLL_BAR_NAME;
4580 block_input ();
4581 xg_create_scroll_bar (f, bar, G_CALLBACK (xg_scroll_callback),
4582 G_CALLBACK (xg_end_scroll_callback),
4583 scroll_bar_name);
4584 unblock_input ();
4587 #else /* not USE_GTK */
4589 static void
4590 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
4592 Window xwindow;
4593 Widget widget;
4594 Arg av[20];
4595 int ac = 0;
4596 const char *scroll_bar_name = SCROLL_BAR_NAME;
4597 unsigned long pixel;
4599 block_input ();
4601 #ifdef USE_MOTIF
4602 /* Set resources. Create the widget. */
4603 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
4604 XtSetArg (av[ac], XmNminimum, 0); ++ac;
4605 XtSetArg (av[ac], XmNmaximum, XM_SB_MAX); ++ac;
4606 XtSetArg (av[ac], XmNorientation, XmVERTICAL); ++ac;
4607 XtSetArg (av[ac], XmNprocessingDirection, XmMAX_ON_BOTTOM), ++ac;
4608 XtSetArg (av[ac], XmNincrement, 1); ++ac;
4609 XtSetArg (av[ac], XmNpageIncrement, 1); ++ac;
4611 pixel = f->output_data.x->scroll_bar_foreground_pixel;
4612 if (pixel != -1)
4614 XtSetArg (av[ac], XmNforeground, pixel);
4615 ++ac;
4618 pixel = f->output_data.x->scroll_bar_background_pixel;
4619 if (pixel != -1)
4621 XtSetArg (av[ac], XmNbackground, pixel);
4622 ++ac;
4625 widget = XmCreateScrollBar (f->output_data.x->edit_widget,
4626 (char *) scroll_bar_name, av, ac);
4628 /* Add one callback for everything that can happen. */
4629 XtAddCallback (widget, XmNdecrementCallback, xm_scroll_callback,
4630 (XtPointer) bar);
4631 XtAddCallback (widget, XmNdragCallback, xm_scroll_callback,
4632 (XtPointer) bar);
4633 XtAddCallback (widget, XmNincrementCallback, xm_scroll_callback,
4634 (XtPointer) bar);
4635 XtAddCallback (widget, XmNpageDecrementCallback, xm_scroll_callback,
4636 (XtPointer) bar);
4637 XtAddCallback (widget, XmNpageIncrementCallback, xm_scroll_callback,
4638 (XtPointer) bar);
4639 XtAddCallback (widget, XmNtoBottomCallback, xm_scroll_callback,
4640 (XtPointer) bar);
4641 XtAddCallback (widget, XmNtoTopCallback, xm_scroll_callback,
4642 (XtPointer) bar);
4644 /* Realize the widget. Only after that is the X window created. */
4645 XtRealizeWidget (widget);
4647 /* Set the cursor to an arrow. I didn't find a resource to do that.
4648 And I'm wondering why it hasn't an arrow cursor by default. */
4649 XDefineCursor (XtDisplay (widget), XtWindow (widget),
4650 f->output_data.x->nontext_cursor);
4652 #else /* !USE_MOTIF i.e. use Xaw */
4654 /* Set resources. Create the widget. The background of the
4655 Xaw3d scroll bar widget is a little bit light for my taste.
4656 We don't alter it here to let users change it according
4657 to their taste with `emacs*verticalScrollBar.background: xxx'. */
4658 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
4659 XtSetArg (av[ac], XtNorientation, XtorientVertical); ++ac;
4660 /* For smoother scrolling with Xaw3d -sm */
4661 /* XtSetArg (av[ac], XtNpickTop, True); ++ac; */
4663 pixel = f->output_data.x->scroll_bar_foreground_pixel;
4664 if (pixel != -1)
4666 XtSetArg (av[ac], XtNforeground, pixel);
4667 ++ac;
4670 pixel = f->output_data.x->scroll_bar_background_pixel;
4671 if (pixel != -1)
4673 XtSetArg (av[ac], XtNbackground, pixel);
4674 ++ac;
4677 /* Top/bottom shadow colors. */
4679 /* Allocate them, if necessary. */
4680 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1)
4682 pixel = f->output_data.x->scroll_bar_background_pixel;
4683 if (pixel != -1)
4685 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
4686 FRAME_X_COLORMAP (f),
4687 &pixel, 1.2, 0x8000))
4688 pixel = -1;
4689 f->output_data.x->scroll_bar_top_shadow_pixel = pixel;
4692 if (f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
4694 pixel = f->output_data.x->scroll_bar_background_pixel;
4695 if (pixel != -1)
4697 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
4698 FRAME_X_COLORMAP (f),
4699 &pixel, 0.6, 0x4000))
4700 pixel = -1;
4701 f->output_data.x->scroll_bar_bottom_shadow_pixel = pixel;
4705 #ifdef XtNbeNiceToColormap
4706 /* Tell the toolkit about them. */
4707 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1
4708 || f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
4709 /* We tried to allocate a color for the top/bottom shadow, and
4710 failed, so tell Xaw3d to use dithering instead. */
4711 /* But only if we have a small colormap. Xaw3d can allocate nice
4712 colors itself. */
4714 XtSetArg (av[ac], XtNbeNiceToColormap,
4715 DefaultDepthOfScreen (FRAME_X_SCREEN (f)) < 16);
4716 ++ac;
4718 else
4719 /* Tell what colors Xaw3d should use for the top/bottom shadow, to
4720 be more consistent with other emacs 3d colors, and since Xaw3d is
4721 not good at dealing with allocation failure. */
4723 /* This tells Xaw3d to use real colors instead of dithering for
4724 the shadows. */
4725 XtSetArg (av[ac], XtNbeNiceToColormap, False);
4726 ++ac;
4728 /* Specify the colors. */
4729 pixel = f->output_data.x->scroll_bar_top_shadow_pixel;
4730 if (pixel != -1)
4732 XtSetArg (av[ac], XtNtopShadowPixel, pixel);
4733 ++ac;
4735 pixel = f->output_data.x->scroll_bar_bottom_shadow_pixel;
4736 if (pixel != -1)
4738 XtSetArg (av[ac], XtNbottomShadowPixel, pixel);
4739 ++ac;
4742 #endif
4744 widget = XtCreateWidget (scroll_bar_name, scrollbarWidgetClass,
4745 f->output_data.x->edit_widget, av, ac);
4748 char const *initial = "";
4749 char const *val = initial;
4750 XtVaGetValues (widget, XtNscrollVCursor, (XtPointer) &val,
4751 #ifdef XtNarrowScrollbars
4752 XtNarrowScrollbars, (XtPointer) &xaw3d_arrow_scroll,
4753 #endif
4754 XtNpickTop, (XtPointer) &xaw3d_pick_top, NULL);
4755 if (xaw3d_arrow_scroll || val == initial)
4756 { /* ARROW_SCROLL */
4757 xaw3d_arrow_scroll = True;
4758 /* Isn't that just a personal preference ? --Stef */
4759 XtVaSetValues (widget, XtNcursorName, "top_left_arrow", NULL);
4763 /* Define callbacks. */
4764 XtAddCallback (widget, XtNjumpProc, xaw_jump_callback, (XtPointer) bar);
4765 XtAddCallback (widget, XtNscrollProc, xaw_scroll_callback,
4766 (XtPointer) bar);
4768 /* Realize the widget. Only after that is the X window created. */
4769 XtRealizeWidget (widget);
4771 #endif /* !USE_MOTIF */
4773 /* Install an action hook that lets us detect when the user
4774 finishes interacting with a scroll bar. */
4775 if (action_hook_id == 0)
4776 action_hook_id = XtAppAddActionHook (Xt_app_con, xt_action_hook, 0);
4778 /* Remember X window and widget in the scroll bar vector. */
4779 SET_SCROLL_BAR_X_WIDGET (bar, widget);
4780 xwindow = XtWindow (widget);
4781 bar->x_window = xwindow;
4783 unblock_input ();
4785 #endif /* not USE_GTK */
4788 /* Set the thumb size and position of scroll bar BAR. We are currently
4789 displaying PORTION out of a whole WHOLE, and our position POSITION. */
4791 #ifdef USE_GTK
4792 static void
4793 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position, int whole)
4795 xg_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
4798 #else /* not USE_GTK */
4799 static void
4800 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position,
4801 int whole)
4803 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
4804 Widget widget = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
4805 float top, shown;
4807 block_input ();
4809 #ifdef USE_MOTIF
4811 if (scroll_bar_adjust_thumb_portion_p)
4813 /* We use an estimate of 30 chars per line rather than the real
4814 `portion' value. This has the disadvantage that the thumb size
4815 is not very representative, but it makes our life a lot easier.
4816 Otherwise, we have to constantly adjust the thumb size, which
4817 we can't always do quickly enough: while dragging, the size of
4818 the thumb might prevent the user from dragging the thumb all the
4819 way to the end. but Motif and some versions of Xaw3d don't allow
4820 updating the thumb size while dragging. Also, even if we can update
4821 its size, the update will often happen too late.
4822 If you don't believe it, check out revision 1.650 of xterm.c to see
4823 what hoops we were going through and the still poor behavior we got. */
4824 portion = WINDOW_TOTAL_LINES (XWINDOW (bar->window)) * 30;
4825 /* When the thumb is at the bottom, position == whole.
4826 So we need to increase `whole' to make space for the thumb. */
4827 whole += portion;
4830 if (whole <= 0)
4831 top = 0, shown = 1;
4832 else
4834 top = (float) position / whole;
4835 shown = (float) portion / whole;
4838 if (bar->dragging == -1)
4840 int size, value;
4842 /* Slider size. Must be in the range [1 .. MAX - MIN] where MAX
4843 is the scroll bar's maximum and MIN is the scroll bar's minimum
4844 value. */
4845 size = clip_to_bounds (1, shown * XM_SB_MAX, XM_SB_MAX);
4847 /* Position. Must be in the range [MIN .. MAX - SLIDER_SIZE]. */
4848 value = top * XM_SB_MAX;
4849 value = min (value, XM_SB_MAX - size);
4851 XmScrollBarSetValues (widget, value, size, 0, 0, False);
4853 #else /* !USE_MOTIF i.e. use Xaw */
4855 if (whole == 0)
4856 top = 0, shown = 1;
4857 else
4859 top = (float) position / whole;
4860 shown = (float) portion / whole;
4864 float old_top, old_shown;
4865 Dimension height;
4866 XtVaGetValues (widget,
4867 XtNtopOfThumb, &old_top,
4868 XtNshown, &old_shown,
4869 XtNheight, &height,
4870 NULL);
4872 /* Massage the top+shown values. */
4873 if (bar->dragging == -1 || bar->last_seen_part == scroll_bar_down_arrow)
4874 top = max (0, min (1, top));
4875 else
4876 top = old_top;
4877 #if ! defined (HAVE_XAW3D)
4878 /* With Xaw, 'top' values too closer to 1.0 may
4879 cause the thumb to disappear. Fix that. */
4880 top = min (top, 0.99f);
4881 #endif
4882 /* Keep two pixels available for moving the thumb down. */
4883 shown = max (0, min (1 - top - (2.0f / height), shown));
4884 #if ! defined (HAVE_XAW3D)
4885 /* Likewise with too small 'shown'. */
4886 shown = max (shown, 0.01f);
4887 #endif
4889 /* If the call to XawScrollbarSetThumb below doesn't seem to
4890 work, check that 'NARROWPROTO' is defined in src/config.h.
4891 If this is not so, most likely you need to fix configure. */
4892 if (top != old_top || shown != old_shown)
4894 if (bar->dragging == -1)
4895 XawScrollbarSetThumb (widget, top, shown);
4896 else
4898 /* Try to make the scrolling a tad smoother. */
4899 if (!xaw3d_pick_top)
4900 shown = min (shown, old_shown);
4902 XawScrollbarSetThumb (widget, top, shown);
4906 #endif /* !USE_MOTIF */
4908 unblock_input ();
4910 #endif /* not USE_GTK */
4912 #endif /* USE_TOOLKIT_SCROLL_BARS */
4916 /************************************************************************
4917 Scroll bars, general
4918 ************************************************************************/
4920 /* Create a scroll bar and return the scroll bar vector for it. W is
4921 the Emacs window on which to create the scroll bar. TOP, LEFT,
4922 WIDTH and HEIGHT are the pixel coordinates and dimensions of the
4923 scroll bar. */
4925 static struct scroll_bar *
4926 x_scroll_bar_create (struct window *w, int top, int left, int width, int height)
4928 struct frame *f = XFRAME (w->frame);
4929 struct scroll_bar *bar
4930 = ALLOCATE_PSEUDOVECTOR (struct scroll_bar, x_window, PVEC_OTHER);
4931 Lisp_Object barobj;
4933 block_input ();
4935 #ifdef USE_TOOLKIT_SCROLL_BARS
4936 x_create_toolkit_scroll_bar (f, bar);
4937 #else /* not USE_TOOLKIT_SCROLL_BARS */
4939 XSetWindowAttributes a;
4940 unsigned long mask;
4941 Window window;
4943 a.background_pixel = f->output_data.x->scroll_bar_background_pixel;
4944 if (a.background_pixel == -1)
4945 a.background_pixel = FRAME_BACKGROUND_PIXEL (f);
4947 a.event_mask = (ButtonPressMask | ButtonReleaseMask
4948 | ButtonMotionMask | PointerMotionHintMask
4949 | ExposureMask);
4950 a.cursor = FRAME_DISPLAY_INFO (f)->vertical_scroll_bar_cursor;
4952 mask = (CWBackPixel | CWEventMask | CWCursor);
4954 /* Clear the area of W that will serve as a scroll bar. This is
4955 for the case that a window has been split horizontally. In
4956 this case, no clear_frame is generated to reduce flickering. */
4957 if (width > 0 && height > 0)
4958 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4959 left, top, width, window_box_height (w));
4961 window = XCreateWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4962 /* Position and size of scroll bar. */
4963 left, top, width, height,
4964 /* Border width, depth, class, and visual. */
4966 CopyFromParent,
4967 CopyFromParent,
4968 CopyFromParent,
4969 /* Attributes. */
4970 mask, &a);
4971 bar->x_window = window;
4973 #endif /* not USE_TOOLKIT_SCROLL_BARS */
4975 XSETWINDOW (bar->window, w);
4976 bar->top = top;
4977 bar->left = left;
4978 bar->width = width;
4979 bar->height = height;
4980 bar->start = 0;
4981 bar->end = 0;
4982 bar->dragging = -1;
4983 bar->fringe_extended_p = 0;
4984 #if defined (USE_TOOLKIT_SCROLL_BARS) && defined (USE_LUCID)
4985 bar->last_seen_part = scroll_bar_nowhere;
4986 #endif
4988 /* Add bar to its frame's list of scroll bars. */
4989 bar->next = FRAME_SCROLL_BARS (f);
4990 bar->prev = Qnil;
4991 XSETVECTOR (barobj, bar);
4992 fset_scroll_bars (f, barobj);
4993 if (!NILP (bar->next))
4994 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
4996 /* Map the window/widget. */
4997 #ifdef USE_TOOLKIT_SCROLL_BARS
4999 #ifdef USE_GTK
5000 xg_update_scrollbar_pos (f, bar->x_window, top,
5001 left,width, max (height, 1));
5002 #else /* not USE_GTK */
5003 Widget scroll_bar = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
5004 XtConfigureWidget (scroll_bar, left, top, width, max (height, 1), 0);
5005 XtMapWidget (scroll_bar);
5006 #endif /* not USE_GTK */
5008 #else /* not USE_TOOLKIT_SCROLL_BARS */
5009 XMapRaised (FRAME_X_DISPLAY (f), bar->x_window);
5010 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5012 unblock_input ();
5013 return bar;
5017 #ifndef USE_TOOLKIT_SCROLL_BARS
5019 /* Draw BAR's handle in the proper position.
5021 If the handle is already drawn from START to END, don't bother
5022 redrawing it, unless REBUILD is non-zero; in that case, always
5023 redraw it. (REBUILD is handy for drawing the handle after expose
5024 events.)
5026 Normally, we want to constrain the start and end of the handle to
5027 fit inside its rectangle, but if the user is dragging the scroll
5028 bar handle, we want to let them drag it down all the way, so that
5029 the bar's top is as far down as it goes; otherwise, there's no way
5030 to move to the very end of the buffer. */
5032 static void
5033 x_scroll_bar_set_handle (struct scroll_bar *bar, int start, int end, int rebuild)
5035 bool dragging = bar->dragging != -1;
5036 Window w = bar->x_window;
5037 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5038 GC gc = f->output_data.x->normal_gc;
5040 /* If the display is already accurate, do nothing. */
5041 if (! rebuild
5042 && start == bar->start
5043 && end == bar->end)
5044 return;
5046 block_input ();
5049 int inside_width = VERTICAL_SCROLL_BAR_INSIDE_WIDTH (f, bar->width);
5050 int inside_height = VERTICAL_SCROLL_BAR_INSIDE_HEIGHT (f, bar->height);
5051 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
5053 /* Make sure the values are reasonable, and try to preserve
5054 the distance between start and end. */
5056 int length = end - start;
5058 if (start < 0)
5059 start = 0;
5060 else if (start > top_range)
5061 start = top_range;
5062 end = start + length;
5064 if (end < start)
5065 end = start;
5066 else if (end > top_range && ! dragging)
5067 end = top_range;
5070 /* Store the adjusted setting in the scroll bar. */
5071 bar->start = start;
5072 bar->end = end;
5074 /* Clip the end position, just for display. */
5075 if (end > top_range)
5076 end = top_range;
5078 /* Draw bottom positions VERTICAL_SCROLL_BAR_MIN_HANDLE pixels
5079 below top positions, to make sure the handle is always at least
5080 that many pixels tall. */
5081 end += VERTICAL_SCROLL_BAR_MIN_HANDLE;
5083 /* Draw the empty space above the handle. Note that we can't clear
5084 zero-height areas; that means "clear to end of window." */
5085 if (start > 0)
5086 x_clear_area (FRAME_X_DISPLAY (f), w,
5087 VERTICAL_SCROLL_BAR_LEFT_BORDER,
5088 VERTICAL_SCROLL_BAR_TOP_BORDER,
5089 inside_width, start);
5091 /* Change to proper foreground color if one is specified. */
5092 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5093 XSetForeground (FRAME_X_DISPLAY (f), gc,
5094 f->output_data.x->scroll_bar_foreground_pixel);
5096 /* Draw the handle itself. */
5097 XFillRectangle (FRAME_X_DISPLAY (f), w, gc,
5098 /* x, y, width, height */
5099 VERTICAL_SCROLL_BAR_LEFT_BORDER,
5100 VERTICAL_SCROLL_BAR_TOP_BORDER + start,
5101 inside_width, end - start);
5103 /* Restore the foreground color of the GC if we changed it above. */
5104 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5105 XSetForeground (FRAME_X_DISPLAY (f), gc,
5106 FRAME_FOREGROUND_PIXEL (f));
5108 /* Draw the empty space below the handle. Note that we can't
5109 clear zero-height areas; that means "clear to end of window." */
5110 if (end < inside_height)
5111 x_clear_area (FRAME_X_DISPLAY (f), w,
5112 VERTICAL_SCROLL_BAR_LEFT_BORDER,
5113 VERTICAL_SCROLL_BAR_TOP_BORDER + end,
5114 inside_width, inside_height - end);
5117 unblock_input ();
5120 #endif /* !USE_TOOLKIT_SCROLL_BARS */
5122 /* Destroy scroll bar BAR, and set its Emacs window's scroll bar to
5123 nil. */
5125 static void
5126 x_scroll_bar_remove (struct scroll_bar *bar)
5128 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5129 block_input ();
5131 #ifdef USE_TOOLKIT_SCROLL_BARS
5132 #ifdef USE_GTK
5133 xg_remove_scroll_bar (f, bar->x_window);
5134 #else /* not USE_GTK */
5135 XtDestroyWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar));
5136 #endif /* not USE_GTK */
5137 #else
5138 XDestroyWindow (FRAME_X_DISPLAY (f), bar->x_window);
5139 #endif
5141 /* Dissociate this scroll bar from its window. */
5142 wset_vertical_scroll_bar (XWINDOW (bar->window), Qnil);
5144 unblock_input ();
5148 /* Set the handle of the vertical scroll bar for WINDOW to indicate
5149 that we are displaying PORTION characters out of a total of WHOLE
5150 characters, starting at POSITION. If WINDOW has no scroll bar,
5151 create one. */
5153 static void
5154 XTset_vertical_scroll_bar (struct window *w, int portion, int whole, int position)
5156 struct frame *f = XFRAME (w->frame);
5157 Lisp_Object barobj;
5158 struct scroll_bar *bar;
5159 int top, height, left, sb_left, width, sb_width;
5160 int window_y, window_height;
5161 #ifdef USE_TOOLKIT_SCROLL_BARS
5162 bool fringe_extended_p;
5163 #endif
5165 /* Get window dimensions. */
5166 window_box (w, ANY_AREA, 0, &window_y, 0, &window_height);
5167 top = window_y;
5168 width = WINDOW_CONFIG_SCROLL_BAR_COLS (w) * FRAME_COLUMN_WIDTH (f);
5169 height = window_height;
5171 /* Compute the left edge of the scroll bar area. */
5172 left = WINDOW_SCROLL_BAR_AREA_X (w);
5174 /* Compute the width of the scroll bar which might be less than
5175 the width of the area reserved for the scroll bar. */
5176 if (WINDOW_CONFIG_SCROLL_BAR_WIDTH (w) > 0)
5177 sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
5178 else
5179 sb_width = width;
5181 /* Compute the left edge of the scroll bar. */
5182 #ifdef USE_TOOLKIT_SCROLL_BARS
5183 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w))
5184 sb_left = left + (WINDOW_RIGHTMOST_P (w) ? width - sb_width : 0);
5185 else
5186 sb_left = left + (WINDOW_LEFTMOST_P (w) ? 0 : width - sb_width);
5187 #else
5188 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w))
5189 sb_left = left + width - sb_width;
5190 else
5191 sb_left = left;
5192 #endif
5194 #ifdef USE_TOOLKIT_SCROLL_BARS
5195 fringe_extended_p = WINDOW_FRINGE_EXTENDED_P (w);
5196 #endif
5198 /* Does the scroll bar exist yet? */
5199 if (NILP (w->vertical_scroll_bar))
5201 if (width > 0 && height > 0)
5203 block_input ();
5204 #ifdef USE_TOOLKIT_SCROLL_BARS
5205 if (fringe_extended_p)
5206 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5207 sb_left, top, sb_width, height);
5208 else
5209 #endif
5210 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5211 left, top, width, height);
5212 unblock_input ();
5215 bar = x_scroll_bar_create (w, top, sb_left, sb_width, height);
5217 else
5219 /* It may just need to be moved and resized. */
5220 unsigned int mask = 0;
5222 bar = XSCROLL_BAR (w->vertical_scroll_bar);
5224 block_input ();
5226 if (sb_left != bar->left)
5227 mask |= CWX;
5228 if (top != bar->top)
5229 mask |= CWY;
5230 if (sb_width != bar->width)
5231 mask |= CWWidth;
5232 if (height != bar->height)
5233 mask |= CWHeight;
5235 #ifdef USE_TOOLKIT_SCROLL_BARS
5237 /* Move/size the scroll bar widget. */
5238 if (mask || bar->fringe_extended_p != fringe_extended_p)
5240 /* Since toolkit scroll bars are smaller than the space reserved
5241 for them on the frame, we have to clear "under" them. */
5242 if (width > 0 && height > 0)
5244 if (fringe_extended_p)
5245 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5246 sb_left, top, sb_width, height);
5247 else
5248 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5249 left, top, width, height);
5251 #ifdef USE_GTK
5252 xg_update_scrollbar_pos (f, bar->x_window, top,
5253 sb_left, sb_width, max (height, 1));
5254 #else /* not USE_GTK */
5255 XtConfigureWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar),
5256 sb_left, top, sb_width, max (height, 1), 0);
5257 #endif /* not USE_GTK */
5259 #else /* not USE_TOOLKIT_SCROLL_BARS */
5261 /* Clear areas not covered by the scroll bar because it's not as
5262 wide as the area reserved for it. This makes sure a
5263 previous mode line display is cleared after C-x 2 C-x 1, for
5264 example. */
5266 int area_width = WINDOW_CONFIG_SCROLL_BAR_COLS (w) * FRAME_COLUMN_WIDTH (f);
5267 int rest = area_width - sb_width;
5268 if (rest > 0 && height > 0)
5270 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
5271 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5272 left + area_width - rest, top, rest, height);
5273 else
5274 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5275 left, top, rest, height);
5279 /* Move/size the scroll bar window. */
5280 if (mask)
5282 XWindowChanges wc;
5284 wc.x = sb_left;
5285 wc.y = top;
5286 wc.width = sb_width;
5287 wc.height = height;
5288 XConfigureWindow (FRAME_X_DISPLAY (f), bar->x_window,
5289 mask, &wc);
5292 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5294 /* Remember new settings. */
5295 bar->left = sb_left;
5296 bar->top = top;
5297 bar->width = sb_width;
5298 bar->height = height;
5300 unblock_input ();
5303 #ifdef USE_TOOLKIT_SCROLL_BARS
5304 bar->fringe_extended_p = fringe_extended_p;
5306 x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
5307 #else /* not USE_TOOLKIT_SCROLL_BARS */
5308 /* Set the scroll bar's current state, unless we're currently being
5309 dragged. */
5310 if (bar->dragging == -1)
5312 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, height);
5314 if (whole == 0)
5315 x_scroll_bar_set_handle (bar, 0, top_range, 0);
5316 else
5318 int start = ((double) position * top_range) / whole;
5319 int end = ((double) (position + portion) * top_range) / whole;
5320 x_scroll_bar_set_handle (bar, start, end, 0);
5323 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5325 XSETVECTOR (barobj, bar);
5326 wset_vertical_scroll_bar (w, barobj);
5330 /* The following three hooks are used when we're doing a thorough
5331 redisplay of the frame. We don't explicitly know which scroll bars
5332 are going to be deleted, because keeping track of when windows go
5333 away is a real pain - "Can you say set-window-configuration, boys
5334 and girls?" Instead, we just assert at the beginning of redisplay
5335 that *all* scroll bars are to be removed, and then save a scroll bar
5336 from the fiery pit when we actually redisplay its window. */
5338 /* Arrange for all scroll bars on FRAME to be removed at the next call
5339 to `*judge_scroll_bars_hook'. A scroll bar may be spared if
5340 `*redeem_scroll_bar_hook' is applied to its window before the judgment. */
5342 static void
5343 XTcondemn_scroll_bars (struct frame *frame)
5345 /* Transfer all the scroll bars to FRAME_CONDEMNED_SCROLL_BARS. */
5346 while (! NILP (FRAME_SCROLL_BARS (frame)))
5348 Lisp_Object bar;
5349 bar = FRAME_SCROLL_BARS (frame);
5350 fset_scroll_bars (frame, XSCROLL_BAR (bar)->next);
5351 XSCROLL_BAR (bar)->next = FRAME_CONDEMNED_SCROLL_BARS (frame);
5352 XSCROLL_BAR (bar)->prev = Qnil;
5353 if (! NILP (FRAME_CONDEMNED_SCROLL_BARS (frame)))
5354 XSCROLL_BAR (FRAME_CONDEMNED_SCROLL_BARS (frame))->prev = bar;
5355 fset_condemned_scroll_bars (frame, bar);
5360 /* Un-mark WINDOW's scroll bar for deletion in this judgment cycle.
5361 Note that WINDOW isn't necessarily condemned at all. */
5363 static void
5364 XTredeem_scroll_bar (struct window *window)
5366 struct scroll_bar *bar;
5367 struct frame *f;
5368 Lisp_Object barobj;
5370 /* We can't redeem this window's scroll bar if it doesn't have one. */
5371 if (NILP (window->vertical_scroll_bar))
5372 emacs_abort ();
5374 bar = XSCROLL_BAR (window->vertical_scroll_bar);
5376 /* Unlink it from the condemned list. */
5377 f = XFRAME (WINDOW_FRAME (window));
5378 if (NILP (bar->prev))
5380 /* If the prev pointer is nil, it must be the first in one of
5381 the lists. */
5382 if (EQ (FRAME_SCROLL_BARS (f), window->vertical_scroll_bar))
5383 /* It's not condemned. Everything's fine. */
5384 return;
5385 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
5386 window->vertical_scroll_bar))
5387 fset_condemned_scroll_bars (f, bar->next);
5388 else
5389 /* If its prev pointer is nil, it must be at the front of
5390 one or the other! */
5391 emacs_abort ();
5393 else
5394 XSCROLL_BAR (bar->prev)->next = bar->next;
5396 if (! NILP (bar->next))
5397 XSCROLL_BAR (bar->next)->prev = bar->prev;
5399 bar->next = FRAME_SCROLL_BARS (f);
5400 bar->prev = Qnil;
5401 XSETVECTOR (barobj, bar);
5402 fset_scroll_bars (f, barobj);
5403 if (! NILP (bar->next))
5404 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
5407 /* Remove all scroll bars on FRAME that haven't been saved since the
5408 last call to `*condemn_scroll_bars_hook'. */
5410 static void
5411 XTjudge_scroll_bars (struct frame *f)
5413 Lisp_Object bar, next;
5415 bar = FRAME_CONDEMNED_SCROLL_BARS (f);
5417 /* Clear out the condemned list now so we won't try to process any
5418 more events on the hapless scroll bars. */
5419 fset_condemned_scroll_bars (f, Qnil);
5421 for (; ! NILP (bar); bar = next)
5423 struct scroll_bar *b = XSCROLL_BAR (bar);
5425 x_scroll_bar_remove (b);
5427 next = b->next;
5428 b->next = b->prev = Qnil;
5431 /* Now there should be no references to the condemned scroll bars,
5432 and they should get garbage-collected. */
5436 #ifndef USE_TOOLKIT_SCROLL_BARS
5437 /* Handle an Expose or GraphicsExpose event on a scroll bar. This
5438 is a no-op when using toolkit scroll bars.
5440 This may be called from a signal handler, so we have to ignore GC
5441 mark bits. */
5443 static void
5444 x_scroll_bar_expose (struct scroll_bar *bar, const XEvent *event)
5446 Window w = bar->x_window;
5447 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5448 GC gc = f->output_data.x->normal_gc;
5450 block_input ();
5452 x_scroll_bar_set_handle (bar, bar->start, bar->end, 1);
5454 /* Switch to scroll bar foreground color. */
5455 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5456 XSetForeground (FRAME_X_DISPLAY (f), gc,
5457 f->output_data.x->scroll_bar_foreground_pixel);
5459 /* Draw a one-pixel border just inside the edges of the scroll bar. */
5460 XDrawRectangle (FRAME_X_DISPLAY (f), w, gc,
5461 /* x, y, width, height */
5462 0, 0, bar->width - 1, bar->height - 1);
5464 /* Restore the foreground color of the GC if we changed it above. */
5465 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5466 XSetForeground (FRAME_X_DISPLAY (f), gc,
5467 FRAME_FOREGROUND_PIXEL (f));
5469 unblock_input ();
5472 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5474 /* Handle a mouse click on the scroll bar BAR. If *EMACS_EVENT's kind
5475 is set to something other than NO_EVENT, it is enqueued.
5477 This may be called from a signal handler, so we have to ignore GC
5478 mark bits. */
5481 static void
5482 x_scroll_bar_handle_click (struct scroll_bar *bar,
5483 const XEvent *event,
5484 struct input_event *emacs_event)
5486 if (! WINDOWP (bar->window))
5487 emacs_abort ();
5489 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
5490 emacs_event->code = event->xbutton.button - Button1;
5491 emacs_event->modifiers
5492 = (x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO
5493 (XFRAME (WINDOW_FRAME (XWINDOW (bar->window)))),
5494 event->xbutton.state)
5495 | (event->type == ButtonRelease
5496 ? up_modifier
5497 : down_modifier));
5498 emacs_event->frame_or_window = bar->window;
5499 emacs_event->arg = Qnil;
5500 emacs_event->timestamp = event->xbutton.time;
5502 int top_range
5503 = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
5504 int y = event->xbutton.y - VERTICAL_SCROLL_BAR_TOP_BORDER;
5506 if (y < 0) y = 0;
5507 if (y > top_range) y = top_range;
5509 if (y < bar->start)
5510 emacs_event->part = scroll_bar_above_handle;
5511 else if (y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
5512 emacs_event->part = scroll_bar_handle;
5513 else
5514 emacs_event->part = scroll_bar_below_handle;
5516 #ifndef USE_TOOLKIT_SCROLL_BARS
5517 /* If the user has released the handle, set it to its final position. */
5518 if (event->type == ButtonRelease && bar->dragging != -1)
5520 int new_start = y - bar->dragging;
5521 int new_end = new_start + bar->end - bar->start;
5523 x_scroll_bar_set_handle (bar, new_start, new_end, 0);
5524 bar->dragging = -1;
5526 #endif
5528 XSETINT (emacs_event->x, y);
5529 XSETINT (emacs_event->y, top_range);
5533 #ifndef USE_TOOLKIT_SCROLL_BARS
5535 /* Handle some mouse motion while someone is dragging the scroll bar.
5537 This may be called from a signal handler, so we have to ignore GC
5538 mark bits. */
5540 static void
5541 x_scroll_bar_note_movement (struct scroll_bar *bar,
5542 const XMotionEvent *event)
5544 struct frame *f = XFRAME (XWINDOW (bar->window)->frame);
5545 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
5547 dpyinfo->last_mouse_movement_time = event->time;
5548 dpyinfo->last_mouse_scroll_bar = bar;
5549 f->mouse_moved = 1;
5551 /* If we're dragging the bar, display it. */
5552 if (bar->dragging != -1)
5554 /* Where should the handle be now? */
5555 int new_start = event->y - bar->dragging;
5557 if (new_start != bar->start)
5559 int new_end = new_start + bar->end - bar->start;
5561 x_scroll_bar_set_handle (bar, new_start, new_end, 0);
5566 #endif /* !USE_TOOLKIT_SCROLL_BARS */
5568 /* Return information to the user about the current position of the mouse
5569 on the scroll bar. */
5571 static void
5572 x_scroll_bar_report_motion (struct frame **fp, Lisp_Object *bar_window,
5573 enum scroll_bar_part *part, Lisp_Object *x,
5574 Lisp_Object *y, Time *timestamp)
5576 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (*fp);
5577 struct scroll_bar *bar = dpyinfo->last_mouse_scroll_bar;
5578 Window w = bar->x_window;
5579 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5580 int win_x, win_y;
5581 Window dummy_window;
5582 int dummy_coord;
5583 unsigned int dummy_mask;
5585 block_input ();
5587 /* Get the mouse's position relative to the scroll bar window, and
5588 report that. */
5589 if (XQueryPointer (FRAME_X_DISPLAY (f), w,
5591 /* Root, child, root x and root y. */
5592 &dummy_window, &dummy_window,
5593 &dummy_coord, &dummy_coord,
5595 /* Position relative to scroll bar. */
5596 &win_x, &win_y,
5598 /* Mouse buttons and modifier keys. */
5599 &dummy_mask))
5601 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
5603 win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
5605 if (bar->dragging != -1)
5606 win_y -= bar->dragging;
5608 if (win_y < 0)
5609 win_y = 0;
5610 if (win_y > top_range)
5611 win_y = top_range;
5613 *fp = f;
5614 *bar_window = bar->window;
5616 if (bar->dragging != -1)
5617 *part = scroll_bar_handle;
5618 else if (win_y < bar->start)
5619 *part = scroll_bar_above_handle;
5620 else if (win_y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
5621 *part = scroll_bar_handle;
5622 else
5623 *part = scroll_bar_below_handle;
5625 XSETINT (*x, win_y);
5626 XSETINT (*y, top_range);
5628 f->mouse_moved = 0;
5629 dpyinfo->last_mouse_scroll_bar = NULL;
5630 *timestamp = dpyinfo->last_mouse_movement_time;
5633 unblock_input ();
5637 /* The screen has been cleared so we may have changed foreground or
5638 background colors, and the scroll bars may need to be redrawn.
5639 Clear out the scroll bars, and ask for expose events, so we can
5640 redraw them. */
5642 static void
5643 x_scroll_bar_clear (struct frame *f)
5645 #ifndef USE_TOOLKIT_SCROLL_BARS
5646 Lisp_Object bar;
5648 /* We can have scroll bars even if this is 0,
5649 if we just turned off scroll bar mode.
5650 But in that case we should not clear them. */
5651 if (FRAME_HAS_VERTICAL_SCROLL_BARS (f))
5652 for (bar = FRAME_SCROLL_BARS (f); VECTORP (bar);
5653 bar = XSCROLL_BAR (bar)->next)
5654 XClearArea (FRAME_X_DISPLAY (f),
5655 XSCROLL_BAR (bar)->x_window,
5656 0, 0, 0, 0, True);
5657 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5660 #ifdef ENABLE_CHECKING
5662 /* Record the last 100 characters stored
5663 to help debug the loss-of-chars-during-GC problem. */
5665 static int temp_index;
5666 static short temp_buffer[100];
5668 #define STORE_KEYSYM_FOR_DEBUG(keysym) \
5669 if (temp_index == sizeof temp_buffer / sizeof (short)) \
5670 temp_index = 0; \
5671 temp_buffer[temp_index++] = (keysym)
5673 #else /* not ENABLE_CHECKING */
5675 #define STORE_KEYSYM_FOR_DEBUG(keysym) ((void)0)
5677 #endif /* ENABLE_CHECKING */
5679 /* Set this to nonzero to fake an "X I/O error"
5680 on a particular display. */
5682 static struct x_display_info *XTread_socket_fake_io_error;
5684 /* When we find no input here, we occasionally do a no-op command
5685 to verify that the X server is still running and we can still talk with it.
5686 We try all the open displays, one by one.
5687 This variable is used for cycling thru the displays. */
5689 static struct x_display_info *next_noop_dpyinfo;
5691 enum
5693 X_EVENT_NORMAL,
5694 X_EVENT_GOTO_OUT,
5695 X_EVENT_DROP
5698 /* Filter events for the current X input method.
5699 DPYINFO is the display this event is for.
5700 EVENT is the X event to filter.
5702 Returns non-zero if the event was filtered, caller shall not process
5703 this event further.
5704 Returns zero if event is wasn't filtered. */
5706 #ifdef HAVE_X_I18N
5707 static int
5708 x_filter_event (struct x_display_info *dpyinfo, XEvent *event)
5710 /* XFilterEvent returns non-zero if the input method has
5711 consumed the event. We pass the frame's X window to
5712 XFilterEvent because that's the one for which the IC
5713 was created. */
5715 struct frame *f1 = x_any_window_to_frame (dpyinfo,
5716 event->xclient.window);
5718 return XFilterEvent (event, f1 ? FRAME_X_WINDOW (f1) : None);
5720 #endif
5722 #ifdef USE_GTK
5723 static int current_count;
5724 static int current_finish;
5725 static struct input_event *current_hold_quit;
5727 /* This is the filter function invoked by the GTK event loop.
5728 It is invoked before the XEvent is translated to a GdkEvent,
5729 so we have a chance to act on the event before GTK. */
5730 static GdkFilterReturn
5731 event_handler_gdk (GdkXEvent *gxev, GdkEvent *ev, gpointer data)
5733 XEvent *xev = (XEvent *) gxev;
5735 block_input ();
5736 if (current_count >= 0)
5738 struct x_display_info *dpyinfo;
5740 dpyinfo = x_display_info_for_display (xev->xany.display);
5742 #ifdef HAVE_X_I18N
5743 /* Filter events for the current X input method.
5744 GTK calls XFilterEvent but not for key press and release,
5745 so we do it here. */
5746 if ((xev->type == KeyPress || xev->type == KeyRelease)
5747 && dpyinfo
5748 && x_filter_event (dpyinfo, xev))
5750 unblock_input ();
5751 return GDK_FILTER_REMOVE;
5753 #endif
5755 if (! dpyinfo)
5756 current_finish = X_EVENT_NORMAL;
5757 else
5758 current_count +=
5759 handle_one_xevent (dpyinfo, xev, &current_finish,
5760 current_hold_quit);
5762 else
5763 current_finish = x_dispatch_event (xev, xev->xany.display);
5765 unblock_input ();
5767 if (current_finish == X_EVENT_GOTO_OUT || current_finish == X_EVENT_DROP)
5768 return GDK_FILTER_REMOVE;
5770 return GDK_FILTER_CONTINUE;
5772 #endif /* USE_GTK */
5775 static void xembed_send_message (struct frame *f, Time,
5776 enum xembed_message,
5777 long detail, long data1, long data2);
5779 /* Handles the XEvent EVENT on display DPYINFO.
5781 *FINISH is X_EVENT_GOTO_OUT if caller should stop reading events.
5782 *FINISH is zero if caller should continue reading events.
5783 *FINISH is X_EVENT_DROP if event should not be passed to the toolkit.
5784 *EVENT is unchanged unless we're processing KeyPress event.
5786 We return the number of characters stored into the buffer. */
5788 static int
5789 handle_one_xevent (struct x_display_info *dpyinfo,
5790 const XEvent *event,
5791 int *finish, struct input_event *hold_quit)
5793 union {
5794 struct input_event ie;
5795 struct selection_input_event sie;
5796 } inev;
5797 int count = 0;
5798 int do_help = 0;
5799 ptrdiff_t nbytes = 0;
5800 struct frame *any, *f = NULL;
5801 struct coding_system coding;
5802 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
5803 /* This holds the state XLookupString needs to implement dead keys
5804 and other tricks known as "compose processing". _X Window System_
5805 says that a portable program can't use this, but Stephen Gildea assures
5806 me that letting the compiler initialize it to zeros will work okay. */
5807 static XComposeStatus compose_status;
5809 USE_SAFE_ALLOCA;
5811 *finish = X_EVENT_NORMAL;
5813 EVENT_INIT (inev.ie);
5814 inev.ie.kind = NO_EVENT;
5815 inev.ie.arg = Qnil;
5817 any = x_any_window_to_frame (dpyinfo, event->xany.window);
5819 if (any && any->wait_event_type == event->type)
5820 any->wait_event_type = 0; /* Indicates we got it. */
5822 switch (event->type)
5824 case ClientMessage:
5826 if (event->xclient.message_type == dpyinfo->Xatom_wm_protocols
5827 && event->xclient.format == 32)
5829 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_take_focus)
5831 /* Use the value returned by x_any_window_to_frame
5832 because this could be the shell widget window
5833 if the frame has no title bar. */
5834 f = any;
5835 #ifdef HAVE_X_I18N
5836 /* Not quite sure this is needed -pd */
5837 if (f && FRAME_XIC (f))
5838 XSetICFocus (FRAME_XIC (f));
5839 #endif
5840 #if 0 /* Emacs sets WM hints whose `input' field is `true'. This
5841 instructs the WM to set the input focus automatically for
5842 Emacs with a call to XSetInputFocus. Setting WM_TAKE_FOCUS
5843 tells the WM to send us a ClientMessage WM_TAKE_FOCUS after
5844 it has set the focus. So, XSetInputFocus below is not
5845 needed.
5847 The call to XSetInputFocus below has also caused trouble. In
5848 cases where the XSetInputFocus done by the WM and the one
5849 below are temporally close (on a fast machine), the call
5850 below can generate additional FocusIn events which confuse
5851 Emacs. */
5853 /* Since we set WM_TAKE_FOCUS, we must call
5854 XSetInputFocus explicitly. But not if f is null,
5855 since that might be an event for a deleted frame. */
5856 if (f)
5858 Display *d = event->xclient.display;
5859 /* Catch and ignore errors, in case window has been
5860 iconified by a window manager such as GWM. */
5861 x_catch_errors (d);
5862 XSetInputFocus (d, event->xclient.window,
5863 /* The ICCCM says this is
5864 the only valid choice. */
5865 RevertToParent,
5866 event->xclient.data.l[1]);
5867 /* This is needed to detect the error
5868 if there is an error. */
5869 XSync (d, False);
5870 x_uncatch_errors ();
5872 /* Not certain about handling scroll bars here */
5873 #endif /* 0 */
5874 goto done;
5877 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_save_yourself)
5879 /* Save state modify the WM_COMMAND property to
5880 something which can reinstate us. This notifies
5881 the session manager, who's looking for such a
5882 PropertyNotify. Can restart processing when
5883 a keyboard or mouse event arrives. */
5884 /* If we have a session manager, don't set this.
5885 KDE will then start two Emacsen, one for the
5886 session manager and one for this. */
5887 #ifdef HAVE_X_SM
5888 if (! x_session_have_connection ())
5889 #endif
5891 f = x_top_window_to_frame (dpyinfo,
5892 event->xclient.window);
5893 /* This is just so we only give real data once
5894 for a single Emacs process. */
5895 if (f == SELECTED_FRAME ())
5896 XSetCommand (FRAME_X_DISPLAY (f),
5897 event->xclient.window,
5898 initial_argv, initial_argc);
5899 else if (f)
5900 XSetCommand (FRAME_X_DISPLAY (f),
5901 event->xclient.window,
5902 0, 0);
5904 goto done;
5907 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_delete_window)
5909 f = any;
5910 if (!f)
5911 goto OTHER; /* May be a dialog that is to be removed */
5913 inev.ie.kind = DELETE_WINDOW_EVENT;
5914 XSETFRAME (inev.ie.frame_or_window, f);
5915 goto done;
5918 goto done;
5921 if (event->xclient.message_type == dpyinfo->Xatom_wm_configure_denied)
5922 goto done;
5924 if (event->xclient.message_type == dpyinfo->Xatom_wm_window_moved)
5926 int new_x, new_y;
5927 f = x_window_to_frame (dpyinfo, event->xclient.window);
5929 new_x = event->xclient.data.s[0];
5930 new_y = event->xclient.data.s[1];
5932 if (f)
5934 f->left_pos = new_x;
5935 f->top_pos = new_y;
5937 goto done;
5940 #ifdef HACK_EDITRES
5941 if (event->xclient.message_type == dpyinfo->Xatom_editres)
5943 f = any;
5944 if (f)
5945 _XEditResCheckMessages (f->output_data.x->widget,
5946 NULL, (XEvent *) event, NULL);
5947 goto done;
5949 #endif /* HACK_EDITRES */
5951 if (event->xclient.message_type == dpyinfo->Xatom_DONE
5952 || event->xclient.message_type == dpyinfo->Xatom_PAGE)
5954 /* Ghostview job completed. Kill it. We could
5955 reply with "Next" if we received "Page", but we
5956 currently never do because we are interested in
5957 images, only, which should have 1 page. */
5958 Pixmap pixmap = (Pixmap) event->xclient.data.l[1];
5959 f = x_window_to_frame (dpyinfo, event->xclient.window);
5960 if (!f)
5961 goto OTHER;
5962 x_kill_gs_process (pixmap, f);
5963 expose_frame (f, 0, 0, 0, 0);
5964 goto done;
5967 #ifdef USE_TOOLKIT_SCROLL_BARS
5968 /* Scroll bar callbacks send a ClientMessage from which
5969 we construct an input_event. */
5970 if (event->xclient.message_type == dpyinfo->Xatom_Scrollbar)
5972 x_scroll_bar_to_input_event (event, &inev.ie);
5973 *finish = X_EVENT_GOTO_OUT;
5974 goto done;
5976 #endif /* USE_TOOLKIT_SCROLL_BARS */
5978 /* XEmbed messages from the embedder (if any). */
5979 if (event->xclient.message_type == dpyinfo->Xatom_XEMBED)
5981 enum xembed_message msg = event->xclient.data.l[1];
5982 if (msg == XEMBED_FOCUS_IN || msg == XEMBED_FOCUS_OUT)
5983 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
5985 *finish = X_EVENT_GOTO_OUT;
5986 goto done;
5989 xft_settings_event (dpyinfo, event);
5991 f = any;
5992 if (!f)
5993 goto OTHER;
5994 if (x_handle_dnd_message (f, &event->xclient, dpyinfo, &inev.ie))
5995 *finish = X_EVENT_DROP;
5997 break;
5999 case SelectionNotify:
6000 dpyinfo->last_user_time = event->xselection.time;
6001 #ifdef USE_X_TOOLKIT
6002 if (! x_window_to_frame (dpyinfo, event->xselection.requestor))
6003 goto OTHER;
6004 #endif /* not USE_X_TOOLKIT */
6005 x_handle_selection_notify (&event->xselection);
6006 break;
6008 case SelectionClear: /* Someone has grabbed ownership. */
6009 dpyinfo->last_user_time = event->xselectionclear.time;
6010 #ifdef USE_X_TOOLKIT
6011 if (! x_window_to_frame (dpyinfo, event->xselectionclear.window))
6012 goto OTHER;
6013 #endif /* USE_X_TOOLKIT */
6015 const XSelectionClearEvent *eventp = &event->xselectionclear;
6017 inev.ie.kind = SELECTION_CLEAR_EVENT;
6018 SELECTION_EVENT_DISPLAY (&inev.sie) = eventp->display;
6019 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
6020 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
6022 break;
6024 case SelectionRequest: /* Someone wants our selection. */
6025 dpyinfo->last_user_time = event->xselectionrequest.time;
6026 #ifdef USE_X_TOOLKIT
6027 if (!x_window_to_frame (dpyinfo, event->xselectionrequest.owner))
6028 goto OTHER;
6029 #endif /* USE_X_TOOLKIT */
6031 const XSelectionRequestEvent *eventp = &event->xselectionrequest;
6033 inev.ie.kind = SELECTION_REQUEST_EVENT;
6034 SELECTION_EVENT_DISPLAY (&inev.sie) = eventp->display;
6035 SELECTION_EVENT_REQUESTOR (&inev.sie) = eventp->requestor;
6036 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
6037 SELECTION_EVENT_TARGET (&inev.sie) = eventp->target;
6038 SELECTION_EVENT_PROPERTY (&inev.sie) = eventp->property;
6039 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
6041 break;
6043 case PropertyNotify:
6044 dpyinfo->last_user_time = event->xproperty.time;
6045 f = x_top_window_to_frame (dpyinfo, event->xproperty.window);
6046 if (f && event->xproperty.atom == dpyinfo->Xatom_net_wm_state)
6047 if (x_handle_net_wm_state (f, &event->xproperty)
6048 && FRAME_ICONIFIED_P (f)
6049 && f->output_data.x->net_wm_state_hidden_seen)
6051 /* Gnome shell does not iconify us when C-z is pressed.
6052 It hides the frame. So if our state says we aren't
6053 hidden anymore, treat it as deiconified. */
6054 SET_FRAME_VISIBLE (f, 1);
6055 SET_FRAME_ICONIFIED (f, 0);
6056 f->output_data.x->has_been_visible = 1;
6057 f->output_data.x->net_wm_state_hidden_seen = 0;
6058 inev.ie.kind = DEICONIFY_EVENT;
6059 XSETFRAME (inev.ie.frame_or_window, f);
6062 x_handle_property_notify (&event->xproperty);
6063 xft_settings_event (dpyinfo, event);
6064 goto OTHER;
6066 case ReparentNotify:
6067 f = x_top_window_to_frame (dpyinfo, event->xreparent.window);
6068 if (f)
6070 f->output_data.x->parent_desc = event->xreparent.parent;
6071 x_real_positions (f, &f->left_pos, &f->top_pos);
6073 /* Perhaps reparented due to a WM restart. Reset this. */
6074 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_UNKNOWN;
6075 FRAME_DISPLAY_INFO (f)->net_supported_window = 0;
6077 x_set_frame_alpha (f);
6079 goto OTHER;
6081 case Expose:
6082 f = x_window_to_frame (dpyinfo, event->xexpose.window);
6083 if (f)
6085 if (!FRAME_VISIBLE_P (f))
6087 SET_FRAME_VISIBLE (f, 1);
6088 SET_FRAME_ICONIFIED (f, 0);
6089 f->output_data.x->has_been_visible = 1;
6090 SET_FRAME_GARBAGED (f);
6092 else
6094 #ifdef USE_GTK
6095 /* This seems to be needed for GTK 2.6 and later, see
6096 http://debbugs.gnu.org/cgi/bugreport.cgi?bug=15398. */
6097 x_clear_area (event->xexpose.display,
6098 event->xexpose.window,
6099 event->xexpose.x, event->xexpose.y,
6100 event->xexpose.width, event->xexpose.height);
6101 #endif
6102 expose_frame (f, event->xexpose.x, event->xexpose.y,
6103 event->xexpose.width, event->xexpose.height);
6106 else
6108 #ifndef USE_TOOLKIT_SCROLL_BARS
6109 struct scroll_bar *bar;
6110 #endif
6111 #if defined USE_LUCID
6112 /* Submenus of the Lucid menu bar aren't widgets
6113 themselves, so there's no way to dispatch events
6114 to them. Recognize this case separately. */
6116 Widget widget = x_window_to_menu_bar (event->xexpose.window);
6117 if (widget)
6118 xlwmenu_redisplay (widget);
6120 #endif /* USE_LUCID */
6122 #ifdef USE_TOOLKIT_SCROLL_BARS
6123 /* Dispatch event to the widget. */
6124 goto OTHER;
6125 #else /* not USE_TOOLKIT_SCROLL_BARS */
6126 bar = x_window_to_scroll_bar (event->xexpose.display,
6127 event->xexpose.window);
6129 if (bar)
6130 x_scroll_bar_expose (bar, event);
6131 #ifdef USE_X_TOOLKIT
6132 else
6133 goto OTHER;
6134 #endif /* USE_X_TOOLKIT */
6135 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6137 break;
6139 case GraphicsExpose: /* This occurs when an XCopyArea's
6140 source area was obscured or not
6141 available. */
6142 f = x_window_to_frame (dpyinfo, event->xgraphicsexpose.drawable);
6143 if (f)
6144 expose_frame (f, event->xgraphicsexpose.x,
6145 event->xgraphicsexpose.y,
6146 event->xgraphicsexpose.width,
6147 event->xgraphicsexpose.height);
6148 #ifdef USE_X_TOOLKIT
6149 else
6150 goto OTHER;
6151 #endif /* USE_X_TOOLKIT */
6152 break;
6154 case NoExpose: /* This occurs when an XCopyArea's
6155 source area was completely
6156 available. */
6157 break;
6159 case UnmapNotify:
6160 /* Redo the mouse-highlight after the tooltip has gone. */
6161 if (event->xunmap.window == tip_window)
6163 tip_window = 0;
6164 x_redo_mouse_highlight (dpyinfo);
6167 f = x_top_window_to_frame (dpyinfo, event->xunmap.window);
6168 if (f) /* F may no longer exist if
6169 the frame was deleted. */
6171 bool visible = FRAME_VISIBLE_P (f);
6172 /* While a frame is unmapped, display generation is
6173 disabled; you don't want to spend time updating a
6174 display that won't ever be seen. */
6175 SET_FRAME_VISIBLE (f, 0);
6176 /* We can't distinguish, from the event, whether the window
6177 has become iconified or invisible. So assume, if it
6178 was previously visible, than now it is iconified.
6179 But x_make_frame_invisible clears both
6180 the visible flag and the iconified flag;
6181 and that way, we know the window is not iconified now. */
6182 if (visible || FRAME_ICONIFIED_P (f))
6184 SET_FRAME_ICONIFIED (f, 1);
6185 inev.ie.kind = ICONIFY_EVENT;
6186 XSETFRAME (inev.ie.frame_or_window, f);
6189 goto OTHER;
6191 case MapNotify:
6192 if (event->xmap.window == tip_window)
6193 /* The tooltip has been drawn already. Avoid
6194 the SET_FRAME_GARBAGED below. */
6195 goto OTHER;
6197 /* We use x_top_window_to_frame because map events can
6198 come for sub-windows and they don't mean that the
6199 frame is visible. */
6200 f = x_top_window_to_frame (dpyinfo, event->xmap.window);
6201 if (f)
6203 bool iconified = FRAME_ICONIFIED_P (f);
6204 /* wait_reading_process_output will notice this and update
6205 the frame's display structures.
6206 If we where iconified, we should not set garbaged,
6207 because that stops redrawing on Expose events. This looks
6208 bad if we are called from a recursive event loop
6209 (x_dispatch_event), for example when a dialog is up. */
6210 if (!iconified)
6211 SET_FRAME_GARBAGED (f);
6213 /* Check if fullscreen was specified before we where mapped the
6214 first time, i.e. from the command line. */
6215 if (!f->output_data.x->has_been_visible)
6216 x_check_fullscreen (f);
6218 SET_FRAME_VISIBLE (f, 1);
6219 SET_FRAME_ICONIFIED (f, 0);
6220 f->output_data.x->has_been_visible = 1;
6222 if (iconified)
6224 inev.ie.kind = DEICONIFY_EVENT;
6225 XSETFRAME (inev.ie.frame_or_window, f);
6227 else if (! NILP (Vframe_list) && ! NILP (XCDR (Vframe_list)))
6228 /* Force a redisplay sooner or later to update the
6229 frame titles in case this is the second frame. */
6230 record_asynch_buffer_change ();
6232 #ifdef USE_GTK
6233 xg_frame_resized (f, -1, -1);
6234 #endif
6236 goto OTHER;
6238 case KeyPress:
6240 dpyinfo->last_user_time = event->xkey.time;
6241 ignore_next_mouse_click_timeout = 0;
6243 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
6244 /* Dispatch KeyPress events when in menu. */
6245 if (popup_activated ())
6246 goto OTHER;
6247 #endif
6249 f = any;
6251 #if ! defined (USE_GTK)
6252 /* If mouse-highlight is an integer, input clears out
6253 mouse highlighting. */
6254 if (!hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight)
6255 && (f == 0
6256 || !EQ (f->tool_bar_window, hlinfo->mouse_face_window)))
6258 clear_mouse_face (hlinfo);
6259 hlinfo->mouse_face_hidden = 1;
6261 #endif
6263 #if defined USE_MOTIF && defined USE_TOOLKIT_SCROLL_BARS
6264 if (f == 0)
6266 /* Scroll bars consume key events, but we want
6267 the keys to go to the scroll bar's frame. */
6268 Widget widget = XtWindowToWidget (dpyinfo->display,
6269 event->xkey.window);
6270 if (widget && XmIsScrollBar (widget))
6272 widget = XtParent (widget);
6273 f = x_any_window_to_frame (dpyinfo, XtWindow (widget));
6276 #endif /* USE_MOTIF and USE_TOOLKIT_SCROLL_BARS */
6278 if (f != 0)
6280 KeySym keysym, orig_keysym;
6281 /* al%imercury@uunet.uu.net says that making this 81
6282 instead of 80 fixed a bug whereby meta chars made
6283 his Emacs hang.
6285 It seems that some version of XmbLookupString has
6286 a bug of not returning XBufferOverflow in
6287 status_return even if the input is too long to
6288 fit in 81 bytes. So, we must prepare sufficient
6289 bytes for copy_buffer. 513 bytes (256 chars for
6290 two-byte character set) seems to be a fairly good
6291 approximation. -- 2000.8.10 handa@etl.go.jp */
6292 unsigned char copy_buffer[513];
6293 unsigned char *copy_bufptr = copy_buffer;
6294 int copy_bufsiz = sizeof (copy_buffer);
6295 int modifiers;
6296 Lisp_Object coding_system = Qlatin_1;
6297 Lisp_Object c;
6298 /* Event will be modified. */
6299 XKeyEvent xkey = event->xkey;
6301 #ifdef USE_GTK
6302 /* Don't pass keys to GTK. A Tab will shift focus to the
6303 tool bar in GTK 2.4. Keys will still go to menus and
6304 dialogs because in that case popup_activated is TRUE
6305 (see above). */
6306 *finish = X_EVENT_DROP;
6307 #endif
6309 xkey.state |= x_emacs_to_x_modifiers (FRAME_DISPLAY_INFO (f),
6310 extra_keyboard_modifiers);
6311 modifiers = xkey.state;
6313 /* This will have to go some day... */
6315 /* make_lispy_event turns chars into control chars.
6316 Don't do it here because XLookupString is too eager. */
6317 xkey.state &= ~ControlMask;
6318 xkey.state &= ~(dpyinfo->meta_mod_mask
6319 | dpyinfo->super_mod_mask
6320 | dpyinfo->hyper_mod_mask
6321 | dpyinfo->alt_mod_mask);
6323 /* In case Meta is ComposeCharacter,
6324 clear its status. According to Markus Ehrnsperger
6325 Markus.Ehrnsperger@lehrstuhl-bross.physik.uni-muenchen.de
6326 this enables ComposeCharacter to work whether or
6327 not it is combined with Meta. */
6328 if (modifiers & dpyinfo->meta_mod_mask)
6329 memset (&compose_status, 0, sizeof (compose_status));
6331 #ifdef HAVE_X_I18N
6332 if (FRAME_XIC (f))
6334 Status status_return;
6336 coding_system = Vlocale_coding_system;
6337 nbytes = XmbLookupString (FRAME_XIC (f),
6338 &xkey, (char *) copy_bufptr,
6339 copy_bufsiz, &keysym,
6340 &status_return);
6341 if (status_return == XBufferOverflow)
6343 copy_bufsiz = nbytes + 1;
6344 copy_bufptr = alloca (copy_bufsiz);
6345 nbytes = XmbLookupString (FRAME_XIC (f),
6346 &xkey, (char *) copy_bufptr,
6347 copy_bufsiz, &keysym,
6348 &status_return);
6350 /* Xutf8LookupString is a new but already deprecated interface. -stef */
6351 if (status_return == XLookupNone)
6352 break;
6353 else if (status_return == XLookupChars)
6355 keysym = NoSymbol;
6356 modifiers = 0;
6358 else if (status_return != XLookupKeySym
6359 && status_return != XLookupBoth)
6360 emacs_abort ();
6362 else
6363 nbytes = XLookupString (&xkey, (char *) copy_bufptr,
6364 copy_bufsiz, &keysym,
6365 &compose_status);
6366 #else
6367 nbytes = XLookupString (&xkey, (char *) copy_bufptr,
6368 copy_bufsiz, &keysym,
6369 &compose_status);
6370 #endif
6372 /* If not using XIM/XIC, and a compose sequence is in progress,
6373 we break here. Otherwise, chars_matched is always 0. */
6374 if (compose_status.chars_matched > 0 && nbytes == 0)
6375 break;
6377 memset (&compose_status, 0, sizeof (compose_status));
6378 orig_keysym = keysym;
6380 /* Common for all keysym input events. */
6381 XSETFRAME (inev.ie.frame_or_window, f);
6382 inev.ie.modifiers
6383 = x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO (f), modifiers);
6384 inev.ie.timestamp = xkey.time;
6386 /* First deal with keysyms which have defined
6387 translations to characters. */
6388 if (keysym >= 32 && keysym < 128)
6389 /* Avoid explicitly decoding each ASCII character. */
6391 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
6392 inev.ie.code = keysym;
6393 goto done_keysym;
6396 /* Keysyms directly mapped to Unicode characters. */
6397 if (keysym >= 0x01000000 && keysym <= 0x0110FFFF)
6399 if (keysym < 0x01000080)
6400 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
6401 else
6402 inev.ie.kind = MULTIBYTE_CHAR_KEYSTROKE_EVENT;
6403 inev.ie.code = keysym & 0xFFFFFF;
6404 goto done_keysym;
6407 /* Now non-ASCII. */
6408 if (HASH_TABLE_P (Vx_keysym_table)
6409 && (c = Fgethash (make_number (keysym),
6410 Vx_keysym_table,
6411 Qnil),
6412 NATNUMP (c)))
6414 inev.ie.kind = (SINGLE_BYTE_CHAR_P (XFASTINT (c))
6415 ? ASCII_KEYSTROKE_EVENT
6416 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
6417 inev.ie.code = XFASTINT (c);
6418 goto done_keysym;
6421 /* Random non-modifier sorts of keysyms. */
6422 if (((keysym >= XK_BackSpace && keysym <= XK_Escape)
6423 || keysym == XK_Delete
6424 #ifdef XK_ISO_Left_Tab
6425 || (keysym >= XK_ISO_Left_Tab
6426 && keysym <= XK_ISO_Enter)
6427 #endif
6428 || IsCursorKey (keysym) /* 0xff50 <= x < 0xff60 */
6429 || IsMiscFunctionKey (keysym) /* 0xff60 <= x < VARIES */
6430 #ifdef HPUX
6431 /* This recognizes the "extended function
6432 keys". It seems there's no cleaner way.
6433 Test IsModifierKey to avoid handling
6434 mode_switch incorrectly. */
6435 || (XK_Select <= keysym && keysym < XK_KP_Space)
6436 #endif
6437 #ifdef XK_dead_circumflex
6438 || orig_keysym == XK_dead_circumflex
6439 #endif
6440 #ifdef XK_dead_grave
6441 || orig_keysym == XK_dead_grave
6442 #endif
6443 #ifdef XK_dead_tilde
6444 || orig_keysym == XK_dead_tilde
6445 #endif
6446 #ifdef XK_dead_diaeresis
6447 || orig_keysym == XK_dead_diaeresis
6448 #endif
6449 #ifdef XK_dead_macron
6450 || orig_keysym == XK_dead_macron
6451 #endif
6452 #ifdef XK_dead_degree
6453 || orig_keysym == XK_dead_degree
6454 #endif
6455 #ifdef XK_dead_acute
6456 || orig_keysym == XK_dead_acute
6457 #endif
6458 #ifdef XK_dead_cedilla
6459 || orig_keysym == XK_dead_cedilla
6460 #endif
6461 #ifdef XK_dead_breve
6462 || orig_keysym == XK_dead_breve
6463 #endif
6464 #ifdef XK_dead_ogonek
6465 || orig_keysym == XK_dead_ogonek
6466 #endif
6467 #ifdef XK_dead_caron
6468 || orig_keysym == XK_dead_caron
6469 #endif
6470 #ifdef XK_dead_doubleacute
6471 || orig_keysym == XK_dead_doubleacute
6472 #endif
6473 #ifdef XK_dead_abovedot
6474 || orig_keysym == XK_dead_abovedot
6475 #endif
6476 || IsKeypadKey (keysym) /* 0xff80 <= x < 0xffbe */
6477 || IsFunctionKey (keysym) /* 0xffbe <= x < 0xffe1 */
6478 /* Any "vendor-specific" key is ok. */
6479 || (orig_keysym & (1 << 28))
6480 || (keysym != NoSymbol && nbytes == 0))
6481 && ! (IsModifierKey (orig_keysym)
6482 /* The symbols from XK_ISO_Lock
6483 to XK_ISO_Last_Group_Lock
6484 don't have real modifiers but
6485 should be treated similarly to
6486 Mode_switch by Emacs. */
6487 #if defined XK_ISO_Lock && defined XK_ISO_Last_Group_Lock
6488 || (XK_ISO_Lock <= orig_keysym
6489 && orig_keysym <= XK_ISO_Last_Group_Lock)
6490 #endif
6493 STORE_KEYSYM_FOR_DEBUG (keysym);
6494 /* make_lispy_event will convert this to a symbolic
6495 key. */
6496 inev.ie.kind = NON_ASCII_KEYSTROKE_EVENT;
6497 inev.ie.code = keysym;
6498 goto done_keysym;
6501 { /* Raw bytes, not keysym. */
6502 ptrdiff_t i;
6503 int nchars, len;
6505 for (i = 0, nchars = 0; i < nbytes; i++)
6507 if (ASCII_BYTE_P (copy_bufptr[i]))
6508 nchars++;
6509 STORE_KEYSYM_FOR_DEBUG (copy_bufptr[i]);
6512 if (nchars < nbytes)
6514 /* Decode the input data. */
6516 /* The input should be decoded with `coding_system'
6517 which depends on which X*LookupString function
6518 we used just above and the locale. */
6519 setup_coding_system (coding_system, &coding);
6520 coding.src_multibyte = 0;
6521 coding.dst_multibyte = 1;
6522 /* The input is converted to events, thus we can't
6523 handle composition. Anyway, there's no XIM that
6524 gives us composition information. */
6525 coding.common_flags &= ~CODING_ANNOTATION_MASK;
6527 SAFE_NALLOCA (coding.destination, MAX_MULTIBYTE_LENGTH,
6528 nbytes);
6529 coding.dst_bytes = MAX_MULTIBYTE_LENGTH * nbytes;
6530 coding.mode |= CODING_MODE_LAST_BLOCK;
6531 decode_coding_c_string (&coding, copy_bufptr, nbytes, Qnil);
6532 nbytes = coding.produced;
6533 nchars = coding.produced_char;
6534 copy_bufptr = coding.destination;
6537 /* Convert the input data to a sequence of
6538 character events. */
6539 for (i = 0; i < nbytes; i += len)
6541 int ch;
6542 if (nchars == nbytes)
6543 ch = copy_bufptr[i], len = 1;
6544 else
6545 ch = STRING_CHAR_AND_LENGTH (copy_bufptr + i, len);
6546 inev.ie.kind = (SINGLE_BYTE_CHAR_P (ch)
6547 ? ASCII_KEYSTROKE_EVENT
6548 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
6549 inev.ie.code = ch;
6550 kbd_buffer_store_event_hold (&inev.ie, hold_quit);
6553 count += nchars;
6555 inev.ie.kind = NO_EVENT; /* Already stored above. */
6557 if (keysym == NoSymbol)
6558 break;
6560 /* FIXME: check side effects and remove this. */
6561 ((XEvent *) event)->xkey = xkey;
6563 done_keysym:
6564 #ifdef HAVE_X_I18N
6565 /* Don't dispatch this event since XtDispatchEvent calls
6566 XFilterEvent, and two calls in a row may freeze the
6567 client. */
6568 break;
6569 #else
6570 goto OTHER;
6571 #endif
6573 case KeyRelease:
6574 dpyinfo->last_user_time = event->xkey.time;
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 EnterNotify:
6585 dpyinfo->last_user_time = event->xcrossing.time;
6586 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
6588 f = any;
6590 if (f && x_mouse_click_focus_ignore_position)
6591 ignore_next_mouse_click_timeout = event->xmotion.time + 200;
6593 /* EnterNotify counts as mouse movement,
6594 so update things that depend on mouse position. */
6595 if (f && !f->output_data.x->hourglass_p)
6596 note_mouse_movement (f, &event->xmotion);
6597 #ifdef USE_GTK
6598 /* We may get an EnterNotify on the buttons in the toolbar. In that
6599 case we moved out of any highlighted area and need to note this. */
6600 if (!f && dpyinfo->last_mouse_glyph_frame)
6601 note_mouse_movement (dpyinfo->last_mouse_glyph_frame, &event->xmotion);
6602 #endif
6603 goto OTHER;
6605 case FocusIn:
6606 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
6607 goto OTHER;
6609 case LeaveNotify:
6610 dpyinfo->last_user_time = event->xcrossing.time;
6611 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
6613 f = x_top_window_to_frame (dpyinfo, event->xcrossing.window);
6614 if (f)
6616 if (f == hlinfo->mouse_face_mouse_frame)
6618 /* If we move outside the frame, then we're
6619 certainly no longer on any text in the frame. */
6620 clear_mouse_face (hlinfo);
6621 hlinfo->mouse_face_mouse_frame = 0;
6624 /* Generate a nil HELP_EVENT to cancel a help-echo.
6625 Do it only if there's something to cancel.
6626 Otherwise, the startup message is cleared when
6627 the mouse leaves the frame. */
6628 if (any_help_event_p)
6629 do_help = -1;
6631 #ifdef USE_GTK
6632 /* See comment in EnterNotify above */
6633 else if (dpyinfo->last_mouse_glyph_frame)
6634 note_mouse_movement (dpyinfo->last_mouse_glyph_frame, &event->xmotion);
6635 #endif
6636 goto OTHER;
6638 case FocusOut:
6639 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
6640 goto OTHER;
6642 case MotionNotify:
6644 dpyinfo->last_user_time = event->xmotion.time;
6645 previous_help_echo_string = help_echo_string;
6646 help_echo_string = Qnil;
6648 f = (x_mouse_grabbed (dpyinfo) ? dpyinfo->last_mouse_frame
6649 : x_window_to_frame (dpyinfo, event->xmotion.window));
6651 if (hlinfo->mouse_face_hidden)
6653 hlinfo->mouse_face_hidden = 0;
6654 clear_mouse_face (hlinfo);
6657 #ifdef USE_GTK
6658 if (f && xg_event_is_for_scrollbar (f, event))
6659 f = 0;
6660 #endif
6661 if (f)
6664 /* Generate SELECT_WINDOW_EVENTs when needed.
6665 Don't let popup menus influence things (bug#1261). */
6666 if (!NILP (Vmouse_autoselect_window) && !popup_activated ())
6668 static Lisp_Object last_mouse_window;
6669 Lisp_Object window = window_from_coordinates
6670 (f, event->xmotion.x, event->xmotion.y, 0, 0);
6672 /* Window will be selected only when it is not selected now and
6673 last mouse movement event was not in it. Minibuffer window
6674 will be selected only when it is active. */
6675 if (WINDOWP (window)
6676 && !EQ (window, last_mouse_window)
6677 && !EQ (window, selected_window)
6678 /* For click-to-focus window managers
6679 create event iff we don't leave the
6680 selected frame. */
6681 && (focus_follows_mouse
6682 || (EQ (XWINDOW (window)->frame,
6683 XWINDOW (selected_window)->frame))))
6685 inev.ie.kind = SELECT_WINDOW_EVENT;
6686 inev.ie.frame_or_window = window;
6688 /* Remember the last window where we saw the mouse. */
6689 last_mouse_window = window;
6691 if (!note_mouse_movement (f, &event->xmotion))
6692 help_echo_string = previous_help_echo_string;
6694 else
6696 #ifndef USE_TOOLKIT_SCROLL_BARS
6697 struct scroll_bar *bar
6698 = x_window_to_scroll_bar (event->xmotion.display,
6699 event->xmotion.window);
6701 if (bar)
6702 x_scroll_bar_note_movement (bar, &event->xmotion);
6703 #endif /* USE_TOOLKIT_SCROLL_BARS */
6705 /* If we move outside the frame, then we're
6706 certainly no longer on any text in the frame. */
6707 clear_mouse_face (hlinfo);
6710 /* If the contents of the global variable help_echo_string
6711 has changed, generate a HELP_EVENT. */
6712 if (!NILP (help_echo_string)
6713 || !NILP (previous_help_echo_string))
6714 do_help = 1;
6715 goto OTHER;
6718 case ConfigureNotify:
6719 f = x_top_window_to_frame (dpyinfo, event->xconfigure.window);
6720 #ifdef USE_GTK
6721 if (!f
6722 && (f = any)
6723 && event->xconfigure.window == FRAME_X_WINDOW (f))
6725 xg_frame_resized (f, event->xconfigure.width,
6726 event->xconfigure.height);
6727 f = 0;
6729 #endif
6730 if (f)
6732 #ifndef USE_X_TOOLKIT
6733 #ifndef USE_GTK
6734 int rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, event->xconfigure.height);
6735 int columns = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, event->xconfigure.width);
6737 /* In the toolkit version, change_frame_size
6738 is called by the code that handles resizing
6739 of the EmacsFrame widget. */
6741 /* Even if the number of character rows and columns has
6742 not changed, the font size may have changed, so we need
6743 to check the pixel dimensions as well. */
6744 if (columns != FRAME_COLS (f)
6745 || rows != FRAME_LINES (f)
6746 || event->xconfigure.width != FRAME_PIXEL_WIDTH (f)
6747 || event->xconfigure.height != FRAME_PIXEL_HEIGHT (f))
6749 change_frame_size (f, rows, columns, 0, 1, 0);
6750 SET_FRAME_GARBAGED (f);
6751 cancel_mouse_face (f);
6754 FRAME_PIXEL_WIDTH (f) = event->xconfigure.width;
6755 FRAME_PIXEL_HEIGHT (f) = event->xconfigure.height;
6756 #endif /* not USE_GTK */
6757 #endif
6759 #ifdef USE_GTK
6760 /* GTK creates windows but doesn't map them.
6761 Only get real positions when mapped. */
6762 if (FRAME_GTK_OUTER_WIDGET (f)
6763 && gtk_widget_get_mapped (FRAME_GTK_OUTER_WIDGET (f)))
6764 #endif
6765 x_real_positions (f, &f->left_pos, &f->top_pos);
6767 #ifdef HAVE_X_I18N
6768 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMStatusArea))
6769 xic_set_statusarea (f);
6770 #endif
6773 goto OTHER;
6775 case ButtonRelease:
6776 case ButtonPress:
6778 /* If we decide we want to generate an event to be seen
6779 by the rest of Emacs, we put it here. */
6780 bool tool_bar_p = 0;
6782 memset (&compose_status, 0, sizeof (compose_status));
6783 dpyinfo->last_mouse_glyph_frame = NULL;
6784 dpyinfo->last_user_time = event->xbutton.time;
6786 f = (x_mouse_grabbed (dpyinfo) ? dpyinfo->last_mouse_frame
6787 : x_window_to_frame (dpyinfo, event->xbutton.window));
6789 #ifdef USE_GTK
6790 if (f && xg_event_is_for_scrollbar (f, event))
6791 f = 0;
6792 #endif
6793 if (f)
6795 #if ! defined (USE_GTK)
6796 /* Is this in the tool-bar? */
6797 if (WINDOWP (f->tool_bar_window)
6798 && WINDOW_TOTAL_LINES (XWINDOW (f->tool_bar_window)))
6800 Lisp_Object window;
6801 int x = event->xbutton.x;
6802 int y = event->xbutton.y;
6804 window = window_from_coordinates (f, x, y, 0, 1);
6805 tool_bar_p = EQ (window, f->tool_bar_window);
6807 if (tool_bar_p && event->xbutton.button < 4)
6808 handle_tool_bar_click
6809 (f, x, y, event->xbutton.type == ButtonPress,
6810 x_x_to_emacs_modifiers (dpyinfo, event->xbutton.state));
6812 #endif /* !USE_GTK */
6814 if (!tool_bar_p)
6815 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
6816 if (! popup_activated ())
6817 #endif
6819 if (ignore_next_mouse_click_timeout)
6821 if (event->type == ButtonPress
6822 && event->xbutton.time > ignore_next_mouse_click_timeout)
6824 ignore_next_mouse_click_timeout = 0;
6825 construct_mouse_click (&inev.ie, &event->xbutton, f);
6827 if (event->type == ButtonRelease)
6828 ignore_next_mouse_click_timeout = 0;
6830 else
6831 construct_mouse_click (&inev.ie, &event->xbutton, f);
6833 if (FRAME_X_EMBEDDED_P (f))
6834 xembed_send_message (f, event->xbutton.time,
6835 XEMBED_REQUEST_FOCUS, 0, 0, 0);
6837 else
6839 struct scroll_bar *bar
6840 = x_window_to_scroll_bar (event->xbutton.display,
6841 event->xbutton.window);
6843 #ifdef USE_TOOLKIT_SCROLL_BARS
6844 /* Make the "Ctrl-Mouse-2 splits window" work for toolkit
6845 scroll bars. */
6846 if (bar && event->xbutton.state & ControlMask)
6848 x_scroll_bar_handle_click (bar, event, &inev.ie);
6849 *finish = X_EVENT_DROP;
6851 #else /* not USE_TOOLKIT_SCROLL_BARS */
6852 if (bar)
6853 x_scroll_bar_handle_click (bar, event, &inev.ie);
6854 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6857 if (event->type == ButtonPress)
6859 dpyinfo->grabbed |= (1 << event->xbutton.button);
6860 dpyinfo->last_mouse_frame = f;
6862 if (!tool_bar_p)
6863 last_tool_bar_item = -1;
6865 else
6866 dpyinfo->grabbed &= ~(1 << event->xbutton.button);
6868 /* Ignore any mouse motion that happened before this event;
6869 any subsequent mouse-movement Emacs events should reflect
6870 only motion after the ButtonPress/Release. */
6871 if (f != 0)
6872 f->mouse_moved = 0;
6874 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
6875 f = x_menubar_window_to_frame (dpyinfo, event);
6876 /* For a down-event in the menu bar,
6877 don't pass it to Xt right now.
6878 Instead, save it away
6879 and we will pass it to Xt from kbd_buffer_get_event.
6880 That way, we can run some Lisp code first. */
6881 if (! popup_activated ()
6882 #ifdef USE_GTK
6883 /* Gtk+ menus only react to the first three buttons. */
6884 && event->xbutton.button < 3
6885 #endif
6886 && f && event->type == ButtonPress
6887 /* Verify the event is really within the menu bar
6888 and not just sent to it due to grabbing. */
6889 && event->xbutton.x >= 0
6890 && event->xbutton.x < FRAME_PIXEL_WIDTH (f)
6891 && event->xbutton.y >= 0
6892 && event->xbutton.y < f->output_data.x->menubar_height
6893 && event->xbutton.same_screen)
6895 if (!f->output_data.x->saved_menu_event)
6896 f->output_data.x->saved_menu_event = xmalloc (sizeof *event);
6897 *f->output_data.x->saved_menu_event = *event;
6898 inev.ie.kind = MENU_BAR_ACTIVATE_EVENT;
6899 XSETFRAME (inev.ie.frame_or_window, f);
6900 *finish = X_EVENT_DROP;
6902 else
6903 goto OTHER;
6904 #endif /* USE_X_TOOLKIT || USE_GTK */
6906 break;
6908 case CirculateNotify:
6909 goto OTHER;
6911 case CirculateRequest:
6912 goto OTHER;
6914 case VisibilityNotify:
6915 goto OTHER;
6917 case MappingNotify:
6918 /* Someone has changed the keyboard mapping - update the
6919 local cache. */
6920 switch (event->xmapping.request)
6922 case MappingModifier:
6923 x_find_modifier_meanings (dpyinfo);
6924 /* This is meant to fall through. */
6925 case MappingKeyboard:
6926 XRefreshKeyboardMapping ((XMappingEvent *) &event->xmapping);
6928 goto OTHER;
6930 case DestroyNotify:
6931 xft_settings_event (dpyinfo, event);
6932 break;
6934 default:
6935 OTHER:
6936 #ifdef USE_X_TOOLKIT
6937 block_input ();
6938 if (*finish != X_EVENT_DROP)
6939 XtDispatchEvent ((XEvent *) event);
6940 unblock_input ();
6941 #endif /* USE_X_TOOLKIT */
6942 break;
6945 done:
6946 if (inev.ie.kind != NO_EVENT)
6948 kbd_buffer_store_event_hold (&inev.ie, hold_quit);
6949 count++;
6952 if (do_help
6953 && !(hold_quit && hold_quit->kind != NO_EVENT))
6955 Lisp_Object frame;
6957 if (f)
6958 XSETFRAME (frame, f);
6959 else
6960 frame = Qnil;
6962 if (do_help > 0)
6964 any_help_event_p = 1;
6965 gen_help_event (help_echo_string, frame, help_echo_window,
6966 help_echo_object, help_echo_pos);
6968 else
6970 help_echo_string = Qnil;
6971 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
6973 count++;
6976 SAFE_FREE ();
6977 return count;
6980 #if defined USE_GTK || defined USE_X_TOOLKIT
6982 /* Handles the XEvent EVENT on display DISPLAY.
6983 This is used for event loops outside the normal event handling,
6984 i.e. looping while a popup menu or a dialog is posted.
6986 Returns the value handle_one_xevent sets in the finish argument. */
6988 x_dispatch_event (XEvent *event, Display *display)
6990 struct x_display_info *dpyinfo;
6991 int finish = X_EVENT_NORMAL;
6993 dpyinfo = x_display_info_for_display (display);
6995 if (dpyinfo)
6996 handle_one_xevent (dpyinfo, event, &finish, 0);
6998 return finish;
7000 #endif
7003 /* Read events coming from the X server.
7004 Return as soon as there are no more events to be read.
7006 Return the number of characters stored into the buffer,
7007 thus pretending to be `read' (except the characters we store
7008 in the keyboard buffer can be multibyte, so are not necessarily
7009 C chars). */
7011 static int
7012 XTread_socket (struct terminal *terminal, struct input_event *hold_quit)
7014 int count = 0;
7015 int event_found = 0;
7016 struct x_display_info *dpyinfo = terminal->display_info.x;
7018 block_input ();
7020 /* So people can tell when we have read the available input. */
7021 input_signal_count++;
7023 /* For debugging, this gives a way to fake an I/O error. */
7024 if (dpyinfo == XTread_socket_fake_io_error)
7026 XTread_socket_fake_io_error = 0;
7027 x_io_error_quitter (dpyinfo->display);
7030 #ifndef USE_GTK
7031 while (XPending (dpyinfo->display))
7033 int finish;
7034 XEvent event;
7036 XNextEvent (dpyinfo->display, &event);
7038 #ifdef HAVE_X_I18N
7039 /* Filter events for the current X input method. */
7040 if (x_filter_event (dpyinfo, &event))
7041 continue;
7042 #endif
7043 event_found = 1;
7045 count += handle_one_xevent (dpyinfo, &event, &finish, hold_quit);
7047 if (finish == X_EVENT_GOTO_OUT)
7048 break;
7051 #else /* USE_GTK */
7053 /* For GTK we must use the GTK event loop. But XEvents gets passed
7054 to our filter function above, and then to the big event switch.
7055 We use a bunch of globals to communicate with our filter function,
7056 that is kind of ugly, but it works.
7058 There is no way to do one display at the time, GTK just does events
7059 from all displays. */
7061 while (gtk_events_pending ())
7063 current_count = count;
7064 current_hold_quit = hold_quit;
7066 gtk_main_iteration ();
7068 count = current_count;
7069 current_count = -1;
7070 current_hold_quit = 0;
7072 if (current_finish == X_EVENT_GOTO_OUT)
7073 break;
7075 #endif /* USE_GTK */
7077 /* On some systems, an X bug causes Emacs to get no more events
7078 when the window is destroyed. Detect that. (1994.) */
7079 if (! event_found)
7081 /* Emacs and the X Server eats up CPU time if XNoOp is done every time.
7082 One XNOOP in 100 loops will make Emacs terminate.
7083 B. Bretthauer, 1994 */
7084 x_noop_count++;
7085 if (x_noop_count >= 100)
7087 x_noop_count=0;
7089 if (next_noop_dpyinfo == 0)
7090 next_noop_dpyinfo = x_display_list;
7092 XNoOp (next_noop_dpyinfo->display);
7094 /* Each time we get here, cycle through the displays now open. */
7095 next_noop_dpyinfo = next_noop_dpyinfo->next;
7099 /* If the focus was just given to an auto-raising frame,
7100 raise it now. FIXME: handle more than one such frame. */
7101 if (dpyinfo->x_pending_autoraise_frame)
7103 x_raise_frame (dpyinfo->x_pending_autoraise_frame);
7104 dpyinfo->x_pending_autoraise_frame = NULL;
7107 unblock_input ();
7109 return count;
7115 /***********************************************************************
7116 Text Cursor
7117 ***********************************************************************/
7119 /* Set clipping for output in glyph row ROW. W is the window in which
7120 we operate. GC is the graphics context to set clipping in.
7122 ROW may be a text row or, e.g., a mode line. Text rows must be
7123 clipped to the interior of the window dedicated to text display,
7124 mode lines must be clipped to the whole window. */
7126 static void
7127 x_clip_to_row (struct window *w, struct glyph_row *row,
7128 enum glyph_row_area area, GC gc)
7130 struct frame *f = XFRAME (WINDOW_FRAME (w));
7131 XRectangle clip_rect;
7132 int window_x, window_y, window_width;
7134 window_box (w, area, &window_x, &window_y, &window_width, 0);
7136 clip_rect.x = window_x;
7137 clip_rect.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
7138 clip_rect.y = max (clip_rect.y, window_y);
7139 clip_rect.width = window_width;
7140 clip_rect.height = row->visible_height;
7142 XSetClipRectangles (FRAME_X_DISPLAY (f), gc, 0, 0, &clip_rect, 1, Unsorted);
7146 /* Draw a hollow box cursor on window W in glyph row ROW. */
7148 static void
7149 x_draw_hollow_cursor (struct window *w, struct glyph_row *row)
7151 struct frame *f = XFRAME (WINDOW_FRAME (w));
7152 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
7153 Display *dpy = FRAME_X_DISPLAY (f);
7154 int x, y, wd, h;
7155 XGCValues xgcv;
7156 struct glyph *cursor_glyph;
7157 GC gc;
7159 /* Get the glyph the cursor is on. If we can't tell because
7160 the current matrix is invalid or such, give up. */
7161 cursor_glyph = get_phys_cursor_glyph (w);
7162 if (cursor_glyph == NULL)
7163 return;
7165 /* Compute frame-relative coordinates for phys cursor. */
7166 get_phys_cursor_geometry (w, row, cursor_glyph, &x, &y, &h);
7167 wd = w->phys_cursor_width;
7169 /* The foreground of cursor_gc is typically the same as the normal
7170 background color, which can cause the cursor box to be invisible. */
7171 xgcv.foreground = f->output_data.x->cursor_pixel;
7172 if (dpyinfo->scratch_cursor_gc)
7173 XChangeGC (dpy, dpyinfo->scratch_cursor_gc, GCForeground, &xgcv);
7174 else
7175 dpyinfo->scratch_cursor_gc = XCreateGC (dpy, FRAME_X_WINDOW (f),
7176 GCForeground, &xgcv);
7177 gc = dpyinfo->scratch_cursor_gc;
7179 /* Set clipping, draw the rectangle, and reset clipping again. */
7180 x_clip_to_row (w, row, TEXT_AREA, gc);
7181 XDrawRectangle (dpy, FRAME_X_WINDOW (f), gc, x, y, wd, h - 1);
7182 XSetClipMask (dpy, gc, None);
7186 /* Draw a bar cursor on window W in glyph row ROW.
7188 Implementation note: One would like to draw a bar cursor with an
7189 angle equal to the one given by the font property XA_ITALIC_ANGLE.
7190 Unfortunately, I didn't find a font yet that has this property set.
7191 --gerd. */
7193 static void
7194 x_draw_bar_cursor (struct window *w, struct glyph_row *row, int width, enum text_cursor_kinds kind)
7196 struct frame *f = XFRAME (w->frame);
7197 struct glyph *cursor_glyph;
7199 /* If cursor is out of bounds, don't draw garbage. This can happen
7200 in mini-buffer windows when switching between echo area glyphs
7201 and mini-buffer. */
7202 cursor_glyph = get_phys_cursor_glyph (w);
7203 if (cursor_glyph == NULL)
7204 return;
7206 /* If on an image, draw like a normal cursor. That's usually better
7207 visible than drawing a bar, esp. if the image is large so that
7208 the bar might not be in the window. */
7209 if (cursor_glyph->type == IMAGE_GLYPH)
7211 struct glyph_row *r;
7212 r = MATRIX_ROW (w->current_matrix, w->phys_cursor.vpos);
7213 draw_phys_cursor_glyph (w, r, DRAW_CURSOR);
7215 else
7217 Display *dpy = FRAME_X_DISPLAY (f);
7218 Window window = FRAME_X_WINDOW (f);
7219 GC gc = FRAME_DISPLAY_INFO (f)->scratch_cursor_gc;
7220 unsigned long mask = GCForeground | GCBackground | GCGraphicsExposures;
7221 struct face *face = FACE_FROM_ID (f, cursor_glyph->face_id);
7222 XGCValues xgcv;
7224 /* If the glyph's background equals the color we normally draw
7225 the bars cursor in, the bar cursor in its normal color is
7226 invisible. Use the glyph's foreground color instead in this
7227 case, on the assumption that the glyph's colors are chosen so
7228 that the glyph is legible. */
7229 if (face->background == f->output_data.x->cursor_pixel)
7230 xgcv.background = xgcv.foreground = face->foreground;
7231 else
7232 xgcv.background = xgcv.foreground = f->output_data.x->cursor_pixel;
7233 xgcv.graphics_exposures = 0;
7235 if (gc)
7236 XChangeGC (dpy, gc, mask, &xgcv);
7237 else
7239 gc = XCreateGC (dpy, window, mask, &xgcv);
7240 FRAME_DISPLAY_INFO (f)->scratch_cursor_gc = gc;
7243 x_clip_to_row (w, row, TEXT_AREA, gc);
7245 if (kind == BAR_CURSOR)
7247 int x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
7249 if (width < 0)
7250 width = FRAME_CURSOR_WIDTH (f);
7251 width = min (cursor_glyph->pixel_width, width);
7253 w->phys_cursor_width = width;
7255 /* If the character under cursor is R2L, draw the bar cursor
7256 on the right of its glyph, rather than on the left. */
7257 if ((cursor_glyph->resolved_level & 1) != 0)
7258 x += cursor_glyph->pixel_width - width;
7260 XFillRectangle (dpy, window, gc, x,
7261 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y),
7262 width, row->height);
7264 else
7266 int dummy_x, dummy_y, dummy_h;
7268 if (width < 0)
7269 width = row->height;
7271 width = min (row->height, width);
7273 get_phys_cursor_geometry (w, row, cursor_glyph, &dummy_x,
7274 &dummy_y, &dummy_h);
7276 XFillRectangle (dpy, window, gc,
7277 WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x),
7278 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y +
7279 row->height - width),
7280 w->phys_cursor_width, width);
7283 XSetClipMask (dpy, gc, None);
7288 /* RIF: Define cursor CURSOR on frame F. */
7290 static void
7291 x_define_frame_cursor (struct frame *f, Cursor cursor)
7293 if (!f->pointer_invisible
7294 && f->output_data.x->current_cursor != cursor)
7295 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), cursor);
7296 f->output_data.x->current_cursor = cursor;
7300 /* RIF: Clear area on frame F. */
7302 static void
7303 x_clear_frame_area (struct frame *f, int x, int y, int width, int height)
7305 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), x, y, width, height);
7306 #ifdef USE_GTK
7307 /* Must queue a redraw, because scroll bars might have been cleared. */
7308 if (FRAME_GTK_WIDGET (f))
7309 gtk_widget_queue_draw (FRAME_GTK_WIDGET (f));
7310 #endif
7314 /* RIF: Draw cursor on window W. */
7316 static void
7317 x_draw_window_cursor (struct window *w, struct glyph_row *glyph_row, int x,
7318 int y, enum text_cursor_kinds cursor_type,
7319 int cursor_width, bool on_p, bool active_p)
7321 struct frame *f = XFRAME (WINDOW_FRAME (w));
7323 if (on_p)
7325 w->phys_cursor_type = cursor_type;
7326 w->phys_cursor_on_p = 1;
7328 if (glyph_row->exact_window_width_line_p
7329 && (glyph_row->reversed_p
7330 ? (w->phys_cursor.hpos < 0)
7331 : (w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])))
7333 glyph_row->cursor_in_fringe_p = 1;
7334 draw_fringe_bitmap (w, glyph_row, glyph_row->reversed_p);
7336 else
7338 switch (cursor_type)
7340 case HOLLOW_BOX_CURSOR:
7341 x_draw_hollow_cursor (w, glyph_row);
7342 break;
7344 case FILLED_BOX_CURSOR:
7345 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
7346 break;
7348 case BAR_CURSOR:
7349 x_draw_bar_cursor (w, glyph_row, cursor_width, BAR_CURSOR);
7350 break;
7352 case HBAR_CURSOR:
7353 x_draw_bar_cursor (w, glyph_row, cursor_width, HBAR_CURSOR);
7354 break;
7356 case NO_CURSOR:
7357 w->phys_cursor_width = 0;
7358 break;
7360 default:
7361 emacs_abort ();
7365 #ifdef HAVE_X_I18N
7366 if (w == XWINDOW (f->selected_window))
7367 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMPreeditPosition))
7368 xic_set_preeditarea (w, x, y);
7369 #endif
7372 XFlush (FRAME_X_DISPLAY (f));
7376 /* Icons. */
7378 /* Make the x-window of frame F use the gnu icon bitmap. */
7381 x_bitmap_icon (struct frame *f, Lisp_Object file)
7383 ptrdiff_t bitmap_id;
7385 if (FRAME_X_WINDOW (f) == 0)
7386 return 1;
7388 /* Free up our existing icon bitmap and mask if any. */
7389 if (f->output_data.x->icon_bitmap > 0)
7390 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
7391 f->output_data.x->icon_bitmap = 0;
7393 if (STRINGP (file))
7395 #ifdef USE_GTK
7396 /* Use gtk_window_set_icon_from_file () if available,
7397 It's not restricted to bitmaps */
7398 if (xg_set_icon (f, file))
7399 return 0;
7400 #endif /* USE_GTK */
7401 bitmap_id = x_create_bitmap_from_file (f, file);
7402 x_create_bitmap_mask (f, bitmap_id);
7404 else
7406 /* Create the GNU bitmap and mask if necessary. */
7407 if (FRAME_DISPLAY_INFO (f)->icon_bitmap_id < 0)
7409 ptrdiff_t rc = -1;
7411 #ifdef USE_GTK
7413 if (xg_set_icon (f, xg_default_icon_file)
7414 || xg_set_icon_from_xpm_data (f, gnu_xpm_bits))
7415 return 0;
7417 #elif defined (HAVE_XPM) && defined (HAVE_X_WINDOWS)
7419 rc = x_create_bitmap_from_xpm_data (f, gnu_xpm_bits);
7420 if (rc != -1)
7421 FRAME_DISPLAY_INFO (f)->icon_bitmap_id = rc;
7423 #endif
7425 /* If all else fails, use the (black and white) xbm image. */
7426 if (rc == -1)
7428 rc = x_create_bitmap_from_data (f, (char *) gnu_xbm_bits,
7429 gnu_xbm_width, gnu_xbm_height);
7430 if (rc == -1)
7431 return 1;
7433 FRAME_DISPLAY_INFO (f)->icon_bitmap_id = rc;
7434 x_create_bitmap_mask (f, FRAME_DISPLAY_INFO (f)->icon_bitmap_id);
7438 /* The first time we create the GNU bitmap and mask,
7439 this increments the ref-count one extra time.
7440 As a result, the GNU bitmap and mask are never freed.
7441 That way, we don't have to worry about allocating it again. */
7442 x_reference_bitmap (f, FRAME_DISPLAY_INFO (f)->icon_bitmap_id);
7444 bitmap_id = FRAME_DISPLAY_INFO (f)->icon_bitmap_id;
7447 x_wm_set_icon_pixmap (f, bitmap_id);
7448 f->output_data.x->icon_bitmap = bitmap_id;
7450 return 0;
7454 /* Make the x-window of frame F use a rectangle with text.
7455 Use ICON_NAME as the text. */
7458 x_text_icon (struct frame *f, const char *icon_name)
7460 if (FRAME_X_WINDOW (f) == 0)
7461 return 1;
7464 XTextProperty text;
7465 text.value = (unsigned char *) icon_name;
7466 text.encoding = XA_STRING;
7467 text.format = 8;
7468 text.nitems = strlen (icon_name);
7469 XSetWMIconName (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f), &text);
7472 if (f->output_data.x->icon_bitmap > 0)
7473 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
7474 f->output_data.x->icon_bitmap = 0;
7475 x_wm_set_icon_pixmap (f, 0);
7477 return 0;
7480 #define X_ERROR_MESSAGE_SIZE 200
7482 /* If non-nil, this should be a string.
7483 It means catch X errors and store the error message in this string.
7485 The reason we use a stack is that x_catch_error/x_uncatch_error can
7486 be called from a signal handler.
7489 struct x_error_message_stack {
7490 char string[X_ERROR_MESSAGE_SIZE];
7491 Display *dpy;
7492 struct x_error_message_stack *prev;
7494 static struct x_error_message_stack *x_error_message;
7496 /* An X error handler which stores the error message in
7497 *x_error_message. This is called from x_error_handler if
7498 x_catch_errors is in effect. */
7500 static void
7501 x_error_catcher (Display *display, XErrorEvent *event)
7503 XGetErrorText (display, event->error_code,
7504 x_error_message->string,
7505 X_ERROR_MESSAGE_SIZE);
7508 /* Begin trapping X errors for display DPY. Actually we trap X errors
7509 for all displays, but DPY should be the display you are actually
7510 operating on.
7512 After calling this function, X protocol errors no longer cause
7513 Emacs to exit; instead, they are recorded in the string
7514 stored in *x_error_message.
7516 Calling x_check_errors signals an Emacs error if an X error has
7517 occurred since the last call to x_catch_errors or x_check_errors.
7519 Calling x_uncatch_errors resumes the normal error handling. */
7521 void
7522 x_catch_errors (Display *dpy)
7524 struct x_error_message_stack *data = xmalloc (sizeof *data);
7526 /* Make sure any errors from previous requests have been dealt with. */
7527 XSync (dpy, False);
7529 data->dpy = dpy;
7530 data->string[0] = 0;
7531 data->prev = x_error_message;
7532 x_error_message = data;
7535 /* Undo the last x_catch_errors call.
7536 DPY should be the display that was passed to x_catch_errors. */
7538 void
7539 x_uncatch_errors (void)
7541 struct x_error_message_stack *tmp;
7543 block_input ();
7545 /* The display may have been closed before this function is called.
7546 Check if it is still open before calling XSync. */
7547 if (x_display_info_for_display (x_error_message->dpy) != 0)
7548 XSync (x_error_message->dpy, False);
7550 tmp = x_error_message;
7551 x_error_message = x_error_message->prev;
7552 xfree (tmp);
7553 unblock_input ();
7556 /* If any X protocol errors have arrived since the last call to
7557 x_catch_errors or x_check_errors, signal an Emacs error using
7558 sprintf (a buffer, FORMAT, the x error message text) as the text. */
7560 void
7561 x_check_errors (Display *dpy, const char *format)
7563 /* Make sure to catch any errors incurred so far. */
7564 XSync (dpy, False);
7566 if (x_error_message->string[0])
7568 char string[X_ERROR_MESSAGE_SIZE];
7569 memcpy (string, x_error_message->string, X_ERROR_MESSAGE_SIZE);
7570 x_uncatch_errors ();
7571 error (format, string);
7575 /* Nonzero if we had any X protocol errors
7576 since we did x_catch_errors on DPY. */
7578 bool
7579 x_had_errors_p (Display *dpy)
7581 /* Make sure to catch any errors incurred so far. */
7582 XSync (dpy, False);
7584 return x_error_message->string[0] != 0;
7587 /* Forget about any errors we have had, since we did x_catch_errors on DPY. */
7589 void
7590 x_clear_errors (Display *dpy)
7592 x_error_message->string[0] = 0;
7595 #if 0 /* See comment in unwind_to_catch why calling this is a bad
7596 * idea. --lorentey */
7597 /* Close off all unclosed x_catch_errors calls. */
7599 void
7600 x_fully_uncatch_errors (void)
7602 while (x_error_message)
7603 x_uncatch_errors ();
7605 #endif
7607 #if 0
7608 static unsigned int x_wire_count;
7609 x_trace_wire (void)
7611 fprintf (stderr, "Lib call: %d\n", ++x_wire_count);
7613 #endif /* ! 0 */
7616 /************************************************************************
7617 Handling X errors
7618 ************************************************************************/
7620 /* Error message passed to x_connection_closed. */
7622 static char *error_msg;
7624 /* Handle the loss of connection to display DPY. ERROR_MESSAGE is
7625 the text of an error message that lead to the connection loss. */
7627 static void
7628 x_connection_closed (Display *dpy, const char *error_message)
7630 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
7631 Lisp_Object frame, tail;
7632 ptrdiff_t idx = SPECPDL_INDEX ();
7634 error_msg = alloca (strlen (error_message) + 1);
7635 strcpy (error_msg, error_message);
7637 /* Inhibit redisplay while frames are being deleted. */
7638 specbind (Qinhibit_redisplay, Qt);
7640 if (dpyinfo)
7642 /* Protect display from being closed when we delete the last
7643 frame on it. */
7644 dpyinfo->reference_count++;
7645 dpyinfo->terminal->reference_count++;
7648 /* First delete frames whose mini-buffers are on frames
7649 that are on the dead display. */
7650 FOR_EACH_FRAME (tail, frame)
7652 Lisp_Object minibuf_frame;
7653 minibuf_frame
7654 = WINDOW_FRAME (XWINDOW (FRAME_MINIBUF_WINDOW (XFRAME (frame))));
7655 if (FRAME_X_P (XFRAME (frame))
7656 && FRAME_X_P (XFRAME (minibuf_frame))
7657 && ! EQ (frame, minibuf_frame)
7658 && FRAME_DISPLAY_INFO (XFRAME (minibuf_frame)) == dpyinfo)
7659 delete_frame (frame, Qnoelisp);
7662 /* Now delete all remaining frames on the dead display.
7663 We are now sure none of these is used as the mini-buffer
7664 for another frame that we need to delete. */
7665 FOR_EACH_FRAME (tail, frame)
7666 if (FRAME_X_P (XFRAME (frame))
7667 && FRAME_DISPLAY_INFO (XFRAME (frame)) == dpyinfo)
7669 /* Set this to t so that delete_frame won't get confused
7670 trying to find a replacement. */
7671 kset_default_minibuffer_frame (FRAME_KBOARD (XFRAME (frame)), Qt);
7672 delete_frame (frame, Qnoelisp);
7675 /* If DPYINFO is null, this means we didn't open the display in the
7676 first place, so don't try to close it. */
7677 if (dpyinfo)
7679 /* We can not call XtCloseDisplay here because it calls XSync.
7680 XSync inside the error handler apparently hangs Emacs. On
7681 current Xt versions, this isn't needed either. */
7682 #ifdef USE_GTK
7683 /* A long-standing GTK bug prevents proper disconnect handling
7684 (https://bugzilla.gnome.org/show_bug.cgi?id=85715). Once,
7685 the resulting Glib error message loop filled a user's disk.
7686 To avoid this, kill Emacs unconditionally on disconnect. */
7687 shut_down_emacs (0, Qnil);
7688 fprintf (stderr, "%s\n\
7689 When compiled with GTK, Emacs cannot recover from X disconnects.\n\
7690 This is a GTK bug: https://bugzilla.gnome.org/show_bug.cgi?id=85715\n\
7691 For details, see etc/PROBLEMS.\n",
7692 error_msg);
7693 emacs_abort ();
7694 #endif /* USE_GTK */
7696 /* Indicate that this display is dead. */
7697 dpyinfo->display = 0;
7699 dpyinfo->reference_count--;
7700 dpyinfo->terminal->reference_count--;
7701 if (dpyinfo->reference_count != 0)
7702 /* We have just closed all frames on this display. */
7703 emacs_abort ();
7706 Lisp_Object tmp;
7707 XSETTERMINAL (tmp, dpyinfo->terminal);
7708 Fdelete_terminal (tmp, Qnoelisp);
7712 if (terminal_list == 0)
7714 fprintf (stderr, "%s\n", error_msg);
7715 Fkill_emacs (make_number (70));
7716 /* NOTREACHED */
7719 totally_unblock_input ();
7721 unbind_to (idx, Qnil);
7722 clear_waiting_for_input ();
7724 /* Tell GCC not to suggest attribute 'noreturn' for this function. */
7725 IF_LINT (if (! terminal_list) return; )
7727 /* Here, we absolutely have to use a non-local exit (e.g. signal, throw,
7728 longjmp), because returning from this function would get us back into
7729 Xlib's code which will directly call `exit'. */
7730 error ("%s", error_msg);
7733 /* We specifically use it before defining it, so that gcc doesn't inline it,
7734 otherwise gdb doesn't know how to properly put a breakpoint on it. */
7735 static void x_error_quitter (Display *, XErrorEvent *);
7737 /* This is the first-level handler for X protocol errors.
7738 It calls x_error_quitter or x_error_catcher. */
7740 static int
7741 x_error_handler (Display *display, XErrorEvent *event)
7743 #if defined USE_GTK && defined HAVE_GTK3
7744 if ((event->error_code == BadMatch || event->error_code == BadWindow)
7745 && event->request_code == X_SetInputFocus)
7747 return 0;
7749 #endif
7751 if (x_error_message)
7752 x_error_catcher (display, event);
7753 else
7754 x_error_quitter (display, event);
7755 return 0;
7758 /* This is the usual handler for X protocol errors.
7759 It kills all frames on the display that we got the error for.
7760 If that was the only one, it prints an error message and kills Emacs. */
7762 /* .gdbinit puts a breakpoint here, so make sure it is not inlined. */
7764 /* On older GCC versions, just putting x_error_quitter
7765 after x_error_handler prevents inlining into the former. */
7767 static void NO_INLINE
7768 x_error_quitter (Display *display, XErrorEvent *event)
7770 char buf[256], buf1[356];
7772 /* Ignore BadName errors. They can happen because of fonts
7773 or colors that are not defined. */
7775 if (event->error_code == BadName)
7776 return;
7778 /* Note that there is no real way portable across R3/R4 to get the
7779 original error handler. */
7781 XGetErrorText (display, event->error_code, buf, sizeof (buf));
7782 sprintf (buf1, "X protocol error: %s on protocol request %d",
7783 buf, event->request_code);
7784 x_connection_closed (display, buf1);
7788 /* This is the handler for X IO errors, always.
7789 It kills all frames on the display that we lost touch with.
7790 If that was the only one, it prints an error message and kills Emacs. */
7792 static int
7793 x_io_error_quitter (Display *display)
7795 char buf[256];
7797 snprintf (buf, sizeof buf, "Connection lost to X server `%s'",
7798 DisplayString (display));
7799 x_connection_closed (display, buf);
7800 return 0;
7803 /* Changing the font of the frame. */
7805 /* Give frame F the font FONT-OBJECT as its default font. The return
7806 value is FONT-OBJECT. FONTSET is an ID of the fontset for the
7807 frame. If it is negative, generate a new fontset from
7808 FONT-OBJECT. */
7810 Lisp_Object
7811 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
7813 struct font *font = XFONT_OBJECT (font_object);
7815 if (fontset < 0)
7816 fontset = fontset_from_font (font_object);
7817 FRAME_FONTSET (f) = fontset;
7818 if (FRAME_FONT (f) == font)
7819 /* This font is already set in frame F. There's nothing more to
7820 do. */
7821 return font_object;
7823 FRAME_FONT (f) = font;
7824 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
7825 FRAME_COLUMN_WIDTH (f) = font->average_width;
7826 FRAME_LINE_HEIGHT (f) = FONT_HEIGHT (font);
7828 compute_fringe_widths (f, 1);
7830 /* Compute the scroll bar width in character columns. */
7831 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
7833 int wid = FRAME_COLUMN_WIDTH (f);
7834 FRAME_CONFIG_SCROLL_BAR_COLS (f)
7835 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid-1) / wid;
7837 else
7839 int wid = FRAME_COLUMN_WIDTH (f);
7840 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
7843 if (FRAME_X_WINDOW (f) != 0)
7845 /* Don't change the size of a tip frame; there's no point in
7846 doing it because it's done in Fx_show_tip, and it leads to
7847 problems because the tip frame has no widget. */
7848 if (NILP (tip_frame) || XFRAME (tip_frame) != f)
7849 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
7852 #ifdef HAVE_X_I18N
7853 if (FRAME_XIC (f)
7854 && (FRAME_XIC_STYLE (f) & (XIMPreeditPosition | XIMStatusArea)))
7856 block_input ();
7857 xic_set_xfontset (f, SSDATA (fontset_ascii (fontset)));
7858 unblock_input ();
7860 #endif
7862 return font_object;
7866 /***********************************************************************
7867 X Input Methods
7868 ***********************************************************************/
7870 #ifdef HAVE_X_I18N
7872 #ifdef HAVE_X11R6
7874 /* XIM destroy callback function, which is called whenever the
7875 connection to input method XIM dies. CLIENT_DATA contains a
7876 pointer to the x_display_info structure corresponding to XIM. */
7878 static void
7879 xim_destroy_callback (XIM xim, XPointer client_data, XPointer call_data)
7881 struct x_display_info *dpyinfo = (struct x_display_info *) client_data;
7882 Lisp_Object frame, tail;
7884 block_input ();
7886 /* No need to call XDestroyIC.. */
7887 FOR_EACH_FRAME (tail, frame)
7889 struct frame *f = XFRAME (frame);
7890 if (FRAME_X_P (f) && FRAME_DISPLAY_INFO (f) == dpyinfo)
7892 FRAME_XIC (f) = NULL;
7893 xic_free_xfontset (f);
7897 /* No need to call XCloseIM. */
7898 dpyinfo->xim = NULL;
7899 XFree (dpyinfo->xim_styles);
7900 unblock_input ();
7903 #endif /* HAVE_X11R6 */
7905 #ifdef HAVE_X11R6
7906 /* This isn't prototyped in OSF 5.0 or 5.1a. */
7907 extern char *XSetIMValues (XIM, ...);
7908 #endif
7910 /* Open the connection to the XIM server on display DPYINFO.
7911 RESOURCE_NAME is the resource name Emacs uses. */
7913 static void
7914 xim_open_dpy (struct x_display_info *dpyinfo, char *resource_name)
7916 XIM xim;
7918 #ifdef HAVE_XIM
7919 if (use_xim)
7921 if (dpyinfo->xim)
7922 XCloseIM (dpyinfo->xim);
7923 xim = XOpenIM (dpyinfo->display, dpyinfo->xrdb, resource_name,
7924 emacs_class);
7925 dpyinfo->xim = xim;
7927 if (xim)
7929 #ifdef HAVE_X11R6
7930 XIMCallback destroy;
7931 #endif
7933 /* Get supported styles and XIM values. */
7934 XGetIMValues (xim, XNQueryInputStyle, &dpyinfo->xim_styles, NULL);
7936 #ifdef HAVE_X11R6
7937 destroy.callback = xim_destroy_callback;
7938 destroy.client_data = (XPointer)dpyinfo;
7939 XSetIMValues (xim, XNDestroyCallback, &destroy, NULL);
7940 #endif
7944 else
7945 #endif /* HAVE_XIM */
7946 dpyinfo->xim = NULL;
7950 #ifdef HAVE_X11R6_XIM
7952 /* XIM instantiate callback function, which is called whenever an XIM
7953 server is available. DISPLAY is the display of the XIM.
7954 CLIENT_DATA contains a pointer to an xim_inst_t structure created
7955 when the callback was registered. */
7957 static void
7958 xim_instantiate_callback (Display *display, XPointer client_data, XPointer call_data)
7960 struct xim_inst_t *xim_inst = (struct xim_inst_t *) client_data;
7961 struct x_display_info *dpyinfo = xim_inst->dpyinfo;
7963 /* We don't support multiple XIM connections. */
7964 if (dpyinfo->xim)
7965 return;
7967 xim_open_dpy (dpyinfo, xim_inst->resource_name);
7969 /* Create XIC for the existing frames on the same display, as long
7970 as they have no XIC. */
7971 if (dpyinfo->xim && dpyinfo->reference_count > 0)
7973 Lisp_Object tail, frame;
7975 block_input ();
7976 FOR_EACH_FRAME (tail, frame)
7978 struct frame *f = XFRAME (frame);
7980 if (FRAME_X_P (f)
7981 && FRAME_DISPLAY_INFO (f) == xim_inst->dpyinfo)
7982 if (FRAME_XIC (f) == NULL)
7984 create_frame_xic (f);
7985 if (FRAME_XIC_STYLE (f) & XIMStatusArea)
7986 xic_set_statusarea (f);
7987 if (FRAME_XIC_STYLE (f) & XIMPreeditPosition)
7989 struct window *w = XWINDOW (f->selected_window);
7990 xic_set_preeditarea (w, w->cursor.x, w->cursor.y);
7995 unblock_input ();
7999 #endif /* HAVE_X11R6_XIM */
8002 /* Open a connection to the XIM server on display DPYINFO.
8003 RESOURCE_NAME is the resource name for Emacs. On X11R5, open the
8004 connection only at the first time. On X11R6, open the connection
8005 in the XIM instantiate callback function. */
8007 static void
8008 xim_initialize (struct x_display_info *dpyinfo, char *resource_name)
8010 dpyinfo->xim = NULL;
8011 #ifdef HAVE_XIM
8012 if (use_xim)
8014 #ifdef HAVE_X11R6_XIM
8015 struct xim_inst_t *xim_inst = xmalloc (sizeof *xim_inst);
8017 dpyinfo->xim_callback_data = xim_inst;
8018 xim_inst->dpyinfo = dpyinfo;
8019 xim_inst->resource_name = xstrdup (resource_name);
8020 XRegisterIMInstantiateCallback (dpyinfo->display, dpyinfo->xrdb,
8021 resource_name, emacs_class,
8022 xim_instantiate_callback,
8023 /* This is XPointer in XFree86
8024 but (XPointer *) on Tru64, at
8025 least, hence the configure test. */
8026 (XRegisterIMInstantiateCallback_arg6) xim_inst);
8027 #else /* not HAVE_X11R6_XIM */
8028 xim_open_dpy (dpyinfo, resource_name);
8029 #endif /* not HAVE_X11R6_XIM */
8031 #endif /* HAVE_XIM */
8035 /* Close the connection to the XIM server on display DPYINFO. */
8037 static void
8038 xim_close_dpy (struct x_display_info *dpyinfo)
8040 #ifdef HAVE_XIM
8041 if (use_xim)
8043 #ifdef HAVE_X11R6_XIM
8044 if (dpyinfo->display)
8045 XUnregisterIMInstantiateCallback (dpyinfo->display, dpyinfo->xrdb,
8046 NULL, emacs_class,
8047 xim_instantiate_callback, NULL);
8048 xfree (dpyinfo->xim_callback_data->resource_name);
8049 xfree (dpyinfo->xim_callback_data);
8050 #endif /* HAVE_X11R6_XIM */
8051 if (dpyinfo->display)
8052 XCloseIM (dpyinfo->xim);
8053 dpyinfo->xim = NULL;
8054 XFree (dpyinfo->xim_styles);
8056 #endif /* HAVE_XIM */
8059 #endif /* not HAVE_X11R6_XIM */
8063 /* Calculate the absolute position in frame F
8064 from its current recorded position values and gravity. */
8066 static void
8067 x_calc_absolute_position (struct frame *f)
8069 int flags = f->size_hint_flags;
8071 /* We have nothing to do if the current position
8072 is already for the top-left corner. */
8073 if (! ((flags & XNegative) || (flags & YNegative)))
8074 return;
8076 /* Treat negative positions as relative to the leftmost bottommost
8077 position that fits on the screen. */
8078 if (flags & XNegative)
8079 f->left_pos = x_display_pixel_width (FRAME_DISPLAY_INFO (f))
8080 - FRAME_PIXEL_WIDTH (f) + f->left_pos;
8083 int height = FRAME_PIXEL_HEIGHT (f);
8085 #if defined USE_X_TOOLKIT && defined USE_MOTIF
8086 /* Something is fishy here. When using Motif, starting Emacs with
8087 `-g -0-0', the frame appears too low by a few pixels.
8089 This seems to be so because initially, while Emacs is starting,
8090 the column widget's height and the frame's pixel height are
8091 different. The column widget's height is the right one. In
8092 later invocations, when Emacs is up, the frame's pixel height
8093 is right, though.
8095 It's not obvious where the initial small difference comes from.
8096 2000-12-01, gerd. */
8098 XtVaGetValues (f->output_data.x->column_widget, XtNheight, &height, NULL);
8099 #endif
8101 if (flags & YNegative)
8102 f->top_pos = x_display_pixel_height (FRAME_DISPLAY_INFO (f))
8103 - height + f->top_pos;
8106 /* The left_pos and top_pos
8107 are now relative to the top and left screen edges,
8108 so the flags should correspond. */
8109 f->size_hint_flags &= ~ (XNegative | YNegative);
8112 /* CHANGE_GRAVITY is 1 when calling from Fset_frame_position,
8113 to really change the position, and 0 when calling from
8114 x_make_frame_visible (in that case, XOFF and YOFF are the current
8115 position values). It is -1 when calling from x_set_frame_parameters,
8116 which means, do adjust for borders but don't change the gravity. */
8118 void
8119 x_set_offset (struct frame *f, register int xoff, register int yoff, int change_gravity)
8121 int modified_top, modified_left;
8123 if (change_gravity > 0)
8125 f->top_pos = yoff;
8126 f->left_pos = xoff;
8127 f->size_hint_flags &= ~ (XNegative | YNegative);
8128 if (xoff < 0)
8129 f->size_hint_flags |= XNegative;
8130 if (yoff < 0)
8131 f->size_hint_flags |= YNegative;
8132 f->win_gravity = NorthWestGravity;
8134 x_calc_absolute_position (f);
8136 block_input ();
8137 x_wm_set_size_hint (f, (long) 0, 0);
8139 modified_left = f->left_pos;
8140 modified_top = f->top_pos;
8142 if (change_gravity != 0 && FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A)
8144 /* Some WMs (twm, wmaker at least) has an offset that is smaller
8145 than the WM decorations. So we use the calculated offset instead
8146 of the WM decoration sizes here (x/y_pixels_outer_diff). */
8147 modified_left += FRAME_X_OUTPUT (f)->move_offset_left;
8148 modified_top += FRAME_X_OUTPUT (f)->move_offset_top;
8151 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8152 modified_left, modified_top);
8154 x_sync_with_move (f, f->left_pos, f->top_pos,
8155 FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN
8156 ? 1 : 0);
8158 /* change_gravity is non-zero when this function is called from Lisp to
8159 programmatically move a frame. In that case, we call
8160 x_check_expected_move to discover if we have a "Type A" or "Type B"
8161 window manager, and, for a "Type A" window manager, adjust the position
8162 of the frame.
8164 We call x_check_expected_move if a programmatic move occurred, and
8165 either the window manager type (A/B) is unknown or it is Type A but we
8166 need to compute the top/left offset adjustment for this frame. */
8168 if (change_gravity != 0 &&
8169 (FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN
8170 || (FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A
8171 && (FRAME_X_OUTPUT (f)->move_offset_left == 0
8172 && FRAME_X_OUTPUT (f)->move_offset_top == 0))))
8173 x_check_expected_move (f, modified_left, modified_top);
8175 unblock_input ();
8178 /* Return non-zero if _NET_SUPPORTING_WM_CHECK window exists and _NET_SUPPORTED
8179 on the root window for frame F contains ATOMNAME.
8180 This is how a WM check shall be done according to the Window Manager
8181 Specification/Extended Window Manager Hints at
8182 http://freedesktop.org/wiki/Specifications/wm-spec. */
8184 static int
8185 wm_supports (struct frame *f, Atom want_atom)
8187 Atom actual_type;
8188 unsigned long actual_size, bytes_remaining;
8189 int i, rc, actual_format;
8190 Window wmcheck_window;
8191 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
8192 Window target_window = dpyinfo->root_window;
8193 long max_len = 65536;
8194 Display *dpy = FRAME_X_DISPLAY (f);
8195 unsigned char *tmp_data = NULL;
8196 Atom target_type = XA_WINDOW;
8198 block_input ();
8200 x_catch_errors (dpy);
8201 rc = XGetWindowProperty (dpy, target_window,
8202 dpyinfo->Xatom_net_supporting_wm_check,
8203 0, max_len, False, target_type,
8204 &actual_type, &actual_format, &actual_size,
8205 &bytes_remaining, &tmp_data);
8207 if (rc != Success || actual_type != XA_WINDOW || x_had_errors_p (dpy))
8209 if (tmp_data) XFree (tmp_data);
8210 x_uncatch_errors ();
8211 unblock_input ();
8212 return 0;
8215 wmcheck_window = *(Window *) tmp_data;
8216 XFree (tmp_data);
8218 /* Check if window exists. */
8219 XSelectInput (dpy, wmcheck_window, StructureNotifyMask);
8220 x_sync (f);
8221 if (x_had_errors_p (dpy))
8223 x_uncatch_errors ();
8224 unblock_input ();
8225 return 0;
8228 if (dpyinfo->net_supported_window != wmcheck_window)
8230 /* Window changed, reload atoms */
8231 if (dpyinfo->net_supported_atoms != NULL)
8232 XFree (dpyinfo->net_supported_atoms);
8233 dpyinfo->net_supported_atoms = NULL;
8234 dpyinfo->nr_net_supported_atoms = 0;
8235 dpyinfo->net_supported_window = 0;
8237 target_type = XA_ATOM;
8238 tmp_data = NULL;
8239 rc = XGetWindowProperty (dpy, target_window,
8240 dpyinfo->Xatom_net_supported,
8241 0, max_len, False, target_type,
8242 &actual_type, &actual_format, &actual_size,
8243 &bytes_remaining, &tmp_data);
8245 if (rc != Success || actual_type != XA_ATOM || x_had_errors_p (dpy))
8247 if (tmp_data) XFree (tmp_data);
8248 x_uncatch_errors ();
8249 unblock_input ();
8250 return 0;
8253 dpyinfo->net_supported_atoms = (Atom *)tmp_data;
8254 dpyinfo->nr_net_supported_atoms = actual_size;
8255 dpyinfo->net_supported_window = wmcheck_window;
8258 rc = 0;
8260 for (i = 0; rc == 0 && i < dpyinfo->nr_net_supported_atoms; ++i)
8261 rc = dpyinfo->net_supported_atoms[i] == want_atom;
8263 x_uncatch_errors ();
8264 unblock_input ();
8266 return rc;
8269 static void
8270 set_wm_state (Lisp_Object frame, int add, Atom atom, Atom value)
8272 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (XFRAME (frame));
8274 x_send_client_event (frame, make_number (0), frame,
8275 dpyinfo->Xatom_net_wm_state,
8276 make_number (32),
8277 /* 1 = add, 0 = remove */
8278 Fcons
8279 (make_number (add ? 1 : 0),
8280 Fcons
8281 (make_fixnum_or_float (atom),
8282 (value != 0
8283 ? list1 (make_fixnum_or_float (value))
8284 : Qnil))));
8287 void
8288 x_set_sticky (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
8290 Lisp_Object frame;
8291 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
8293 XSETFRAME (frame, f);
8295 set_wm_state (frame, NILP (new_value) ? 0 : 1,
8296 dpyinfo->Xatom_net_wm_state_sticky, None);
8299 /* Return the current _NET_WM_STATE.
8300 SIZE_STATE is set to one of the FULLSCREEN_* values.
8301 STICKY is set to 1 if the sticky state is set, 0 if not.
8303 Return non-zero if we are not hidden, zero if we are. */
8305 static int
8306 get_current_wm_state (struct frame *f,
8307 Window window,
8308 int *size_state,
8309 int *sticky)
8311 Atom actual_type;
8312 unsigned long actual_size, bytes_remaining;
8313 int i, rc, actual_format, is_hidden = 0;
8314 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
8315 long max_len = 65536;
8316 Display *dpy = FRAME_X_DISPLAY (f);
8317 unsigned char *tmp_data = NULL;
8318 Atom target_type = XA_ATOM;
8320 *sticky = 0;
8321 *size_state = FULLSCREEN_NONE;
8323 block_input ();
8324 x_catch_errors (dpy);
8325 rc = XGetWindowProperty (dpy, window, dpyinfo->Xatom_net_wm_state,
8326 0, max_len, False, target_type,
8327 &actual_type, &actual_format, &actual_size,
8328 &bytes_remaining, &tmp_data);
8330 if (rc != Success || actual_type != target_type || x_had_errors_p (dpy))
8332 if (tmp_data) XFree (tmp_data);
8333 x_uncatch_errors ();
8334 unblock_input ();
8335 return !FRAME_ICONIFIED_P (f);
8338 x_uncatch_errors ();
8340 for (i = 0; i < actual_size; ++i)
8342 Atom a = ((Atom*)tmp_data)[i];
8343 if (a == dpyinfo->Xatom_net_wm_state_hidden)
8345 is_hidden = 1;
8346 f->output_data.x->net_wm_state_hidden_seen = 1;
8348 else if (a == dpyinfo->Xatom_net_wm_state_maximized_horz)
8350 if (*size_state == FULLSCREEN_HEIGHT)
8351 *size_state = FULLSCREEN_MAXIMIZED;
8352 else
8353 *size_state = FULLSCREEN_WIDTH;
8355 else if (a == dpyinfo->Xatom_net_wm_state_maximized_vert)
8357 if (*size_state == FULLSCREEN_WIDTH)
8358 *size_state = FULLSCREEN_MAXIMIZED;
8359 else
8360 *size_state = FULLSCREEN_HEIGHT;
8362 else if (a == dpyinfo->Xatom_net_wm_state_fullscreen)
8363 *size_state = FULLSCREEN_BOTH;
8364 else if (a == dpyinfo->Xatom_net_wm_state_sticky)
8365 *sticky = 1;
8368 if (tmp_data) XFree (tmp_data);
8369 unblock_input ();
8370 return ! is_hidden;
8373 /* Do fullscreen as specified in extended window manager hints */
8375 static int
8376 do_ewmh_fullscreen (struct frame *f)
8378 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
8379 int have_net_atom = wm_supports (f, dpyinfo->Xatom_net_wm_state);
8380 int cur, dummy;
8382 (void)get_current_wm_state (f, FRAME_OUTER_WINDOW (f), &cur, &dummy);
8384 /* Some window managers don't say they support _NET_WM_STATE, but they do say
8385 they support _NET_WM_STATE_FULLSCREEN. Try that also. */
8386 if (!have_net_atom)
8387 have_net_atom = wm_supports (f, dpyinfo->Xatom_net_wm_state_fullscreen);
8389 if (have_net_atom && cur != f->want_fullscreen)
8391 Lisp_Object frame;
8393 XSETFRAME (frame, f);
8395 /* Keep number of calls to set_wm_state as low as possible.
8396 Some window managers, or possible Gtk+, hangs when too many
8397 are sent at once. */
8398 switch (f->want_fullscreen)
8400 case FULLSCREEN_BOTH:
8401 if (cur == FULLSCREEN_WIDTH || cur == FULLSCREEN_MAXIMIZED
8402 || cur == FULLSCREEN_HEIGHT)
8403 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_maximized_horz,
8404 dpyinfo->Xatom_net_wm_state_maximized_vert);
8405 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_fullscreen, None);
8406 break;
8407 case FULLSCREEN_WIDTH:
8408 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_HEIGHT
8409 || cur == FULLSCREEN_MAXIMIZED)
8410 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen,
8411 dpyinfo->Xatom_net_wm_state_maximized_vert);
8412 if (cur != FULLSCREEN_MAXIMIZED)
8413 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_maximized_horz, None);
8414 break;
8415 case FULLSCREEN_HEIGHT:
8416 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_WIDTH
8417 || cur == FULLSCREEN_MAXIMIZED)
8418 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen,
8419 dpyinfo->Xatom_net_wm_state_maximized_horz);
8420 if (cur != FULLSCREEN_MAXIMIZED)
8421 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_maximized_vert, None);
8422 break;
8423 case FULLSCREEN_MAXIMIZED:
8424 if (cur == FULLSCREEN_BOTH)
8425 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen, None);
8426 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_maximized_horz,
8427 dpyinfo->Xatom_net_wm_state_maximized_vert);
8428 break;
8429 case FULLSCREEN_NONE:
8430 if (cur == FULLSCREEN_BOTH)
8431 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen, None);
8432 else
8433 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_maximized_horz,
8434 dpyinfo->Xatom_net_wm_state_maximized_vert);
8437 f->want_fullscreen = FULLSCREEN_NONE;
8441 return have_net_atom;
8444 static void
8445 XTfullscreen_hook (struct frame *f)
8447 if (FRAME_VISIBLE_P (f))
8449 block_input ();
8450 x_check_fullscreen (f);
8451 x_sync (f);
8452 unblock_input ();
8457 static int
8458 x_handle_net_wm_state (struct frame *f, const XPropertyEvent *event)
8460 int value = FULLSCREEN_NONE;
8461 Lisp_Object lval;
8462 int sticky = 0;
8463 int not_hidden = get_current_wm_state (f, event->window, &value, &sticky);
8465 lval = Qnil;
8466 switch (value)
8468 case FULLSCREEN_WIDTH:
8469 lval = Qfullwidth;
8470 break;
8471 case FULLSCREEN_HEIGHT:
8472 lval = Qfullheight;
8473 break;
8474 case FULLSCREEN_BOTH:
8475 lval = Qfullboth;
8476 break;
8477 case FULLSCREEN_MAXIMIZED:
8478 lval = Qmaximized;
8479 break;
8482 store_frame_param (f, Qfullscreen, lval);
8483 store_frame_param (f, Qsticky, sticky ? Qt : Qnil);
8485 return not_hidden;
8488 /* Check if we need to resize the frame due to a fullscreen request.
8489 If so needed, resize the frame. */
8490 static void
8491 x_check_fullscreen (struct frame *f)
8493 if (do_ewmh_fullscreen (f))
8494 return;
8496 if (f->output_data.x->parent_desc != FRAME_DISPLAY_INFO (f)->root_window)
8497 return; /* Only fullscreen without WM or with EWM hints (above). */
8499 /* Setting fullscreen to nil doesn't do anything. We could save the
8500 last non-fullscreen size and restore it, but it seems like a
8501 lot of work for this unusual case (no window manager running). */
8503 if (f->want_fullscreen != FULLSCREEN_NONE)
8505 int width = FRAME_PIXEL_WIDTH (f), height = FRAME_PIXEL_HEIGHT (f);
8506 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
8508 switch (f->want_fullscreen)
8510 /* No difference between these two when there is no WM */
8511 case FULLSCREEN_BOTH:
8512 case FULLSCREEN_MAXIMIZED:
8513 width = x_display_pixel_width (dpyinfo);
8514 height = x_display_pixel_height (dpyinfo);
8515 break;
8516 case FULLSCREEN_WIDTH:
8517 width = x_display_pixel_width (dpyinfo);
8518 break;
8519 case FULLSCREEN_HEIGHT:
8520 height = x_display_pixel_height (dpyinfo);
8523 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8524 width, height);
8528 /* This function is called by x_set_offset to determine whether the window
8529 manager interfered with the positioning of the frame. Type A window
8530 managers position the surrounding window manager decorations a small
8531 amount above and left of the user-supplied position. Type B window
8532 managers position the surrounding window manager decorations at the
8533 user-specified position. If we detect a Type A window manager, we
8534 compensate by moving the window right and down by the proper amount. */
8536 static void
8537 x_check_expected_move (struct frame *f, int expected_left, int expected_top)
8539 int current_left = 0, current_top = 0;
8541 /* x_real_positions returns the left and top offsets of the outermost
8542 window manager window around the frame. */
8544 x_real_positions (f, &current_left, &current_top);
8546 if (current_left != expected_left || current_top != expected_top)
8548 /* It's a "Type A" window manager. */
8550 int adjusted_left;
8551 int adjusted_top;
8553 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_A;
8554 FRAME_X_OUTPUT (f)->move_offset_left = expected_left - current_left;
8555 FRAME_X_OUTPUT (f)->move_offset_top = expected_top - current_top;
8557 /* Now fix the mispositioned frame's location. */
8559 adjusted_left = expected_left + FRAME_X_OUTPUT (f)->move_offset_left;
8560 adjusted_top = expected_top + FRAME_X_OUTPUT (f)->move_offset_top;
8562 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8563 adjusted_left, adjusted_top);
8565 x_sync_with_move (f, expected_left, expected_top, 0);
8567 else
8568 /* It's a "Type B" window manager. We don't have to adjust the
8569 frame's position. */
8571 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_B;
8575 /* Wait for XGetGeometry to return up-to-date position information for a
8576 recently-moved frame. Call this immediately after calling XMoveWindow.
8577 If FUZZY is non-zero, then LEFT and TOP are just estimates of where the
8578 frame has been moved to, so we use a fuzzy position comparison instead
8579 of an exact comparison. */
8581 static void
8582 x_sync_with_move (struct frame *f, int left, int top, int fuzzy)
8584 int count = 0;
8586 while (count++ < 50)
8588 int current_left = 0, current_top = 0;
8590 /* In theory, this call to XSync only needs to happen once, but in
8591 practice, it doesn't seem to work, hence the need for the surrounding
8592 loop. */
8594 XSync (FRAME_X_DISPLAY (f), False);
8595 x_real_positions (f, &current_left, &current_top);
8597 if (fuzzy)
8599 /* The left fuzz-factor is 10 pixels. The top fuzz-factor is 40
8600 pixels. */
8602 if (eabs (current_left - left) <= 10
8603 && eabs (current_top - top) <= 40)
8604 return;
8606 else if (current_left == left && current_top == top)
8607 return;
8610 /* As a last resort, just wait 0.5 seconds and hope that XGetGeometry
8611 will then return up-to-date position info. */
8613 wait_reading_process_output (0, 500000, 0, 0, Qnil, NULL, 0);
8617 /* Wait for an event on frame F matching EVENTTYPE. */
8618 void
8619 x_wait_for_event (struct frame *f, int eventtype)
8621 int level = interrupt_input_blocked;
8623 fd_set fds;
8624 struct timespec tmo, tmo_at, time_now;
8625 int fd = ConnectionNumber (FRAME_X_DISPLAY (f));
8627 f->wait_event_type = eventtype;
8629 /* Set timeout to 0.1 second. Hopefully not noticeable.
8630 Maybe it should be configurable. */
8631 tmo = make_timespec (0, 100 * 1000 * 1000);
8632 tmo_at = timespec_add (current_timespec (), tmo);
8634 while (f->wait_event_type)
8636 pending_signals = 1;
8637 totally_unblock_input ();
8638 /* XTread_socket is called after unblock. */
8639 block_input ();
8640 interrupt_input_blocked = level;
8642 FD_ZERO (&fds);
8643 FD_SET (fd, &fds);
8645 time_now = current_timespec ();
8646 if (timespec_cmp (tmo_at, time_now) < 0)
8647 break;
8649 tmo = timespec_sub (tmo_at, time_now);
8650 if (pselect (fd + 1, &fds, NULL, NULL, &tmo, NULL) == 0)
8651 break; /* Timeout */
8654 f->wait_event_type = 0;
8658 /* Change the size of frame F's X window to COLS/ROWS in the case F
8659 doesn't have a widget. If CHANGE_GRAVITY is 1, we change to
8660 top-left-corner window gravity for this size change and subsequent
8661 size changes. Otherwise we leave the window gravity unchanged. */
8663 static void
8664 x_set_window_size_1 (struct frame *f, int change_gravity, int cols, int rows)
8666 int pixelwidth, pixelheight;
8668 check_frame_size (f, &rows, &cols);
8669 f->scroll_bar_actual_width
8670 = (!FRAME_HAS_VERTICAL_SCROLL_BARS (f)
8672 : FRAME_CONFIG_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f));
8674 compute_fringe_widths (f, 0);
8676 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, cols)
8677 + FRAME_TOOLBAR_WIDTH (f);
8678 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows)
8679 + FRAME_MENUBAR_HEIGHT (f) + FRAME_TOOLBAR_HEIGHT (f);
8681 if (change_gravity) f->win_gravity = NorthWestGravity;
8682 x_wm_set_size_hint (f, (long) 0, 0);
8683 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8684 pixelwidth, pixelheight);
8687 /* We've set {FRAME,PIXEL}_{WIDTH,HEIGHT} to the values we hope to
8688 receive in the ConfigureNotify event; if we get what we asked
8689 for, then the event won't cause the screen to become garbaged, so
8690 we have to make sure to do it here. */
8691 SET_FRAME_GARBAGED (f);
8693 /* Now, strictly speaking, we can't be sure that this is accurate,
8694 but the window manager will get around to dealing with the size
8695 change request eventually, and we'll hear how it went when the
8696 ConfigureNotify event gets here.
8698 We could just not bother storing any of this information here,
8699 and let the ConfigureNotify event set everything up, but that
8700 might be kind of confusing to the Lisp code, since size changes
8701 wouldn't be reported in the frame parameters until some random
8702 point in the future when the ConfigureNotify event arrives.
8704 We pass 1 for DELAY since we can't run Lisp code inside of
8705 a BLOCK_INPUT. */
8707 /* But the ConfigureNotify may in fact never arrive, and then this is
8708 not right if the frame is visible. Instead wait (with timeout)
8709 for the ConfigureNotify. */
8710 if (FRAME_VISIBLE_P (f))
8711 x_wait_for_event (f, ConfigureNotify);
8712 else
8714 change_frame_size (f, rows, cols, 0, 1, 0);
8715 FRAME_PIXEL_WIDTH (f) = pixelwidth;
8716 FRAME_PIXEL_HEIGHT (f) = pixelheight;
8717 x_sync (f);
8722 /* Call this to change the size of frame F's x-window.
8723 If CHANGE_GRAVITY is 1, we change to top-left-corner window gravity
8724 for this size change and subsequent size changes.
8725 Otherwise we leave the window gravity unchanged. */
8727 void
8728 x_set_window_size (struct frame *f, int change_gravity, int cols, int rows)
8730 block_input ();
8732 if (NILP (tip_frame) || XFRAME (tip_frame) != f)
8734 int r, c;
8736 /* When the frame is maximized/fullscreen or running under for
8737 example Xmonad, x_set_window_size_1 will be a no-op.
8738 In that case, the right thing to do is extend rows/cols to
8739 the current frame size. We do that first if x_set_window_size_1
8740 turns out to not be a no-op (there is no way to know).
8741 The size will be adjusted again if the frame gets a
8742 ConfigureNotify event as a result of x_set_window_size. */
8743 int pixelh = FRAME_PIXEL_HEIGHT (f);
8744 #ifdef USE_X_TOOLKIT
8745 /* The menu bar is not part of text lines. The tool bar
8746 is however. */
8747 pixelh -= FRAME_MENUBAR_HEIGHT (f);
8748 #endif
8749 r = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, pixelh);
8750 /* Update f->scroll_bar_actual_width because it is used in
8751 FRAME_PIXEL_WIDTH_TO_TEXT_COLS. */
8752 f->scroll_bar_actual_width
8753 = FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f);
8754 c = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, FRAME_PIXEL_WIDTH (f));
8755 change_frame_size (f, r, c, 0, 1, 0);
8758 #ifdef USE_GTK
8759 if (FRAME_GTK_WIDGET (f))
8760 xg_frame_set_char_size (f, cols, rows);
8761 else
8762 x_set_window_size_1 (f, change_gravity, cols, rows);
8763 #else /* not USE_GTK */
8765 x_set_window_size_1 (f, change_gravity, cols, rows);
8767 #endif /* not USE_GTK */
8769 /* If cursor was outside the new size, mark it as off. */
8770 mark_window_cursors_off (XWINDOW (f->root_window));
8772 /* Clear out any recollection of where the mouse highlighting was,
8773 since it might be in a place that's outside the new frame size.
8774 Actually checking whether it is outside is a pain in the neck,
8775 so don't try--just let the highlighting be done afresh with new size. */
8776 cancel_mouse_face (f);
8778 unblock_input ();
8781 /* Mouse warping. */
8783 void
8784 x_set_mouse_position (struct frame *f, int x, int y)
8786 int pix_x, pix_y;
8788 pix_x = FRAME_COL_TO_PIXEL_X (f, x) + FRAME_COLUMN_WIDTH (f) / 2;
8789 pix_y = FRAME_LINE_TO_PIXEL_Y (f, y) + FRAME_LINE_HEIGHT (f) / 2;
8791 if (pix_x < 0) pix_x = 0;
8792 if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
8794 if (pix_y < 0) pix_y = 0;
8795 if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
8797 block_input ();
8799 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
8800 0, 0, 0, 0, pix_x, pix_y);
8801 unblock_input ();
8804 /* Move the mouse to position pixel PIX_X, PIX_Y relative to frame F. */
8806 void
8807 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
8809 block_input ();
8811 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
8812 0, 0, 0, 0, pix_x, pix_y);
8813 unblock_input ();
8816 /* Raise frame F. */
8818 void
8819 x_raise_frame (struct frame *f)
8821 block_input ();
8822 if (FRAME_VISIBLE_P (f))
8823 XRaiseWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
8824 XFlush (FRAME_X_DISPLAY (f));
8825 unblock_input ();
8828 /* Lower frame F. */
8830 static void
8831 x_lower_frame (struct frame *f)
8833 if (FRAME_VISIBLE_P (f))
8835 block_input ();
8836 XLowerWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
8837 XFlush (FRAME_X_DISPLAY (f));
8838 unblock_input ();
8842 /* Request focus with XEmbed */
8844 void
8845 xembed_request_focus (struct frame *f)
8847 /* See XEmbed Protocol Specification at
8848 http://freedesktop.org/wiki/Specifications/xembed-spec */
8849 if (FRAME_VISIBLE_P (f))
8850 xembed_send_message (f, CurrentTime,
8851 XEMBED_REQUEST_FOCUS, 0, 0, 0);
8854 /* Activate frame with Extended Window Manager Hints */
8856 void
8857 x_ewmh_activate_frame (struct frame *f)
8859 /* See Window Manager Specification/Extended Window Manager Hints at
8860 http://freedesktop.org/wiki/Specifications/wm-spec */
8862 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
8864 if (FRAME_VISIBLE_P (f) && wm_supports (f, dpyinfo->Xatom_net_active_window))
8866 Lisp_Object frame;
8867 XSETFRAME (frame, f);
8868 x_send_client_event (frame, make_number (0), frame,
8869 dpyinfo->Xatom_net_active_window,
8870 make_number (32),
8871 list2i (1, dpyinfo->last_user_time));
8875 static void
8876 XTframe_raise_lower (struct frame *f, int raise_flag)
8878 if (raise_flag)
8879 x_raise_frame (f);
8880 else
8881 x_lower_frame (f);
8884 /* XEmbed implementation. */
8886 #if defined USE_X_TOOLKIT || ! defined USE_GTK
8888 /* XEmbed implementation. */
8890 #define XEMBED_VERSION 0
8892 static void
8893 xembed_set_info (struct frame *f, enum xembed_info flags)
8895 unsigned long data[2];
8896 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
8898 data[0] = XEMBED_VERSION;
8899 data[1] = flags;
8901 XChangeProperty (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8902 dpyinfo->Xatom_XEMBED_INFO, dpyinfo->Xatom_XEMBED_INFO,
8903 32, PropModeReplace, (unsigned char *) data, 2);
8905 #endif /* defined USE_X_TOOLKIT || ! defined USE_GTK */
8907 static void
8908 xembed_send_message (struct frame *f, Time t, enum xembed_message msg,
8909 long int detail, long int data1, long int data2)
8911 XEvent event;
8913 event.xclient.type = ClientMessage;
8914 event.xclient.window = FRAME_X_OUTPUT (f)->parent_desc;
8915 event.xclient.message_type = FRAME_DISPLAY_INFO (f)->Xatom_XEMBED;
8916 event.xclient.format = 32;
8917 event.xclient.data.l[0] = t;
8918 event.xclient.data.l[1] = msg;
8919 event.xclient.data.l[2] = detail;
8920 event.xclient.data.l[3] = data1;
8921 event.xclient.data.l[4] = data2;
8923 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_OUTPUT (f)->parent_desc,
8924 False, NoEventMask, &event);
8925 XSync (FRAME_X_DISPLAY (f), False);
8928 /* Change of visibility. */
8930 /* This tries to wait until the frame is really visible.
8931 However, if the window manager asks the user where to position
8932 the frame, this will return before the user finishes doing that.
8933 The frame will not actually be visible at that time,
8934 but it will become visible later when the window manager
8935 finishes with it. */
8937 void
8938 x_make_frame_visible (struct frame *f)
8940 int original_top, original_left;
8941 int retry_count = 2;
8943 retry:
8945 block_input ();
8947 x_set_bitmap_icon (f);
8949 if (! FRAME_VISIBLE_P (f))
8951 /* We test FRAME_GARBAGED_P here to make sure we don't
8952 call x_set_offset a second time
8953 if we get to x_make_frame_visible a second time
8954 before the window gets really visible. */
8955 if (! FRAME_ICONIFIED_P (f)
8956 && ! FRAME_X_EMBEDDED_P (f)
8957 && ! f->output_data.x->asked_for_visible)
8958 x_set_offset (f, f->left_pos, f->top_pos, 0);
8960 f->output_data.x->asked_for_visible = 1;
8962 if (! EQ (Vx_no_window_manager, Qt))
8963 x_wm_set_window_state (f, NormalState);
8964 #ifdef USE_X_TOOLKIT
8965 if (FRAME_X_EMBEDDED_P (f))
8966 xembed_set_info (f, XEMBED_MAPPED);
8967 else
8969 /* This was XtPopup, but that did nothing for an iconified frame. */
8970 XtMapWidget (f->output_data.x->widget);
8972 #else /* not USE_X_TOOLKIT */
8973 #ifdef USE_GTK
8974 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
8975 gtk_window_deiconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
8976 #else
8977 if (FRAME_X_EMBEDDED_P (f))
8978 xembed_set_info (f, XEMBED_MAPPED);
8979 else
8980 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
8981 #endif /* not USE_GTK */
8982 #endif /* not USE_X_TOOLKIT */
8985 XFlush (FRAME_X_DISPLAY (f));
8987 /* Synchronize to ensure Emacs knows the frame is visible
8988 before we do anything else. We do this loop with input not blocked
8989 so that incoming events are handled. */
8991 Lisp_Object frame;
8992 int count;
8993 /* This must be before UNBLOCK_INPUT
8994 since events that arrive in response to the actions above
8995 will set it when they are handled. */
8996 int previously_visible = f->output_data.x->has_been_visible;
8998 original_left = f->left_pos;
8999 original_top = f->top_pos;
9001 /* This must come after we set COUNT. */
9002 unblock_input ();
9004 /* We unblock here so that arriving X events are processed. */
9006 /* Now move the window back to where it was "supposed to be".
9007 But don't do it if the gravity is negative.
9008 When the gravity is negative, this uses a position
9009 that is 3 pixels too low. Perhaps that's really the border width.
9011 Don't do this if the window has never been visible before,
9012 because the window manager may choose the position
9013 and we don't want to override it. */
9015 if (! FRAME_VISIBLE_P (f)
9016 && ! FRAME_ICONIFIED_P (f)
9017 && ! FRAME_X_EMBEDDED_P (f)
9018 && f->win_gravity == NorthWestGravity
9019 && previously_visible)
9021 Drawable rootw;
9022 int x, y;
9023 unsigned int width, height, border, depth;
9025 block_input ();
9027 /* On some window managers (such as FVWM) moving an existing
9028 window, even to the same place, causes the window manager
9029 to introduce an offset. This can cause the window to move
9030 to an unexpected location. Check the geometry (a little
9031 slow here) and then verify that the window is in the right
9032 place. If the window is not in the right place, move it
9033 there, and take the potential window manager hit. */
9034 XGetGeometry (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
9035 &rootw, &x, &y, &width, &height, &border, &depth);
9037 if (original_left != x || original_top != y)
9038 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
9039 original_left, original_top);
9041 unblock_input ();
9044 XSETFRAME (frame, f);
9046 /* Wait until the frame is visible. Process X events until a
9047 MapNotify event has been seen, or until we think we won't get a
9048 MapNotify at all.. */
9049 for (count = input_signal_count + 10;
9050 input_signal_count < count && !FRAME_VISIBLE_P (f);)
9052 /* Force processing of queued events. */
9053 x_sync (f);
9055 /* Machines that do polling rather than SIGIO have been
9056 observed to go into a busy-wait here. So we'll fake an
9057 alarm signal to let the handler know that there's something
9058 to be read. We used to raise a real alarm, but it seems
9059 that the handler isn't always enabled here. This is
9060 probably a bug. */
9061 if (input_polling_used ())
9063 /* It could be confusing if a real alarm arrives while
9064 processing the fake one. Turn it off and let the
9065 handler reset it. */
9066 int old_poll_suppress_count = poll_suppress_count;
9067 poll_suppress_count = 1;
9068 poll_for_input_1 ();
9069 poll_suppress_count = old_poll_suppress_count;
9073 /* 2000-09-28: In
9075 (let ((f (selected-frame)))
9076 (iconify-frame f)
9077 (raise-frame f))
9079 the frame is not raised with various window managers on
9080 FreeBSD, GNU/Linux and Solaris. It turns out that, for some
9081 unknown reason, the call to XtMapWidget is completely ignored.
9082 Mapping the widget a second time works. */
9084 if (!FRAME_VISIBLE_P (f) && --retry_count != 0)
9085 goto retry;
9089 /* Change from mapped state to withdrawn state. */
9091 /* Make the frame visible (mapped and not iconified). */
9093 void
9094 x_make_frame_invisible (struct frame *f)
9096 Window window;
9098 /* Use the frame's outermost window, not the one we normally draw on. */
9099 window = FRAME_OUTER_WINDOW (f);
9101 /* Don't keep the highlight on an invisible frame. */
9102 if (FRAME_DISPLAY_INFO (f)->x_highlight_frame == f)
9103 FRAME_DISPLAY_INFO (f)->x_highlight_frame = 0;
9105 block_input ();
9107 /* Before unmapping the window, update the WM_SIZE_HINTS property to claim
9108 that the current position of the window is user-specified, rather than
9109 program-specified, so that when the window is mapped again, it will be
9110 placed at the same location, without forcing the user to position it
9111 by hand again (they have already done that once for this window.) */
9112 x_wm_set_size_hint (f, (long) 0, 1);
9114 #ifdef USE_GTK
9115 if (FRAME_GTK_OUTER_WIDGET (f))
9116 gtk_widget_hide (FRAME_GTK_OUTER_WIDGET (f));
9117 else
9118 #else
9119 if (FRAME_X_EMBEDDED_P (f))
9120 xembed_set_info (f, 0);
9121 else
9122 #endif
9125 if (! XWithdrawWindow (FRAME_X_DISPLAY (f), window,
9126 DefaultScreen (FRAME_X_DISPLAY (f))))
9128 unblock_input ();
9129 error ("Can't notify window manager of window withdrawal");
9133 /* We can't distinguish this from iconification
9134 just by the event that we get from the server.
9135 So we can't win using the usual strategy of letting
9136 FRAME_SAMPLE_VISIBILITY set this. So do it by hand,
9137 and synchronize with the server to make sure we agree. */
9138 SET_FRAME_VISIBLE (f, 0);
9139 SET_FRAME_ICONIFIED (f, 0);
9141 x_sync (f);
9143 unblock_input ();
9146 /* Change window state from mapped to iconified. */
9148 void
9149 x_iconify_frame (struct frame *f)
9151 #ifdef USE_X_TOOLKIT
9152 int result;
9153 #endif
9155 /* Don't keep the highlight on an invisible frame. */
9156 if (FRAME_DISPLAY_INFO (f)->x_highlight_frame == f)
9157 FRAME_DISPLAY_INFO (f)->x_highlight_frame = 0;
9159 if (FRAME_ICONIFIED_P (f))
9160 return;
9162 block_input ();
9164 x_set_bitmap_icon (f);
9166 #if defined (USE_GTK)
9167 if (FRAME_GTK_OUTER_WIDGET (f))
9169 if (! FRAME_VISIBLE_P (f))
9170 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
9172 gtk_window_iconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
9173 SET_FRAME_VISIBLE (f, 0);
9174 SET_FRAME_ICONIFIED (f, 1);
9175 unblock_input ();
9176 return;
9178 #endif
9180 #ifdef USE_X_TOOLKIT
9182 if (! FRAME_VISIBLE_P (f))
9184 if (! EQ (Vx_no_window_manager, Qt))
9185 x_wm_set_window_state (f, IconicState);
9186 /* This was XtPopup, but that did nothing for an iconified frame. */
9187 XtMapWidget (f->output_data.x->widget);
9188 /* The server won't give us any event to indicate
9189 that an invisible frame was changed to an icon,
9190 so we have to record it here. */
9191 SET_FRAME_VISIBLE (f, 0);
9192 SET_FRAME_ICONIFIED (f, 1);
9193 unblock_input ();
9194 return;
9197 result = XIconifyWindow (FRAME_X_DISPLAY (f),
9198 XtWindow (f->output_data.x->widget),
9199 DefaultScreen (FRAME_X_DISPLAY (f)));
9200 unblock_input ();
9202 if (!result)
9203 error ("Can't notify window manager of iconification");
9205 SET_FRAME_ICONIFIED (f, 1);
9206 SET_FRAME_VISIBLE (f, 0);
9208 block_input ();
9209 XFlush (FRAME_X_DISPLAY (f));
9210 unblock_input ();
9211 #else /* not USE_X_TOOLKIT */
9213 /* Make sure the X server knows where the window should be positioned,
9214 in case the user deiconifies with the window manager. */
9215 if (! FRAME_VISIBLE_P (f)
9216 && ! FRAME_ICONIFIED_P (f)
9217 && ! FRAME_X_EMBEDDED_P (f))
9218 x_set_offset (f, f->left_pos, f->top_pos, 0);
9220 /* Since we don't know which revision of X we're running, we'll use both
9221 the X11R3 and X11R4 techniques. I don't know if this is a good idea. */
9223 /* X11R4: send a ClientMessage to the window manager using the
9224 WM_CHANGE_STATE type. */
9226 XEvent msg;
9228 msg.xclient.window = FRAME_X_WINDOW (f);
9229 msg.xclient.type = ClientMessage;
9230 msg.xclient.message_type = FRAME_DISPLAY_INFO (f)->Xatom_wm_change_state;
9231 msg.xclient.format = 32;
9232 msg.xclient.data.l[0] = IconicState;
9234 if (! XSendEvent (FRAME_X_DISPLAY (f),
9235 DefaultRootWindow (FRAME_X_DISPLAY (f)),
9236 False,
9237 SubstructureRedirectMask | SubstructureNotifyMask,
9238 &msg))
9240 unblock_input ();
9241 error ("Can't notify window manager of iconification");
9245 /* X11R3: set the initial_state field of the window manager hints to
9246 IconicState. */
9247 x_wm_set_window_state (f, IconicState);
9249 if (!FRAME_VISIBLE_P (f))
9251 /* If the frame was withdrawn, before, we must map it. */
9252 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9255 SET_FRAME_ICONIFIED (f, 1);
9256 SET_FRAME_VISIBLE (f, 0);
9258 XFlush (FRAME_X_DISPLAY (f));
9259 unblock_input ();
9260 #endif /* not USE_X_TOOLKIT */
9264 /* Free X resources of frame F. */
9266 void
9267 x_free_frame_resources (struct frame *f)
9269 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
9270 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
9271 #ifdef USE_X_TOOLKIT
9272 Lisp_Object bar;
9273 struct scroll_bar *b;
9274 #endif
9276 block_input ();
9278 /* If a display connection is dead, don't try sending more
9279 commands to the X server. */
9280 if (dpyinfo->display)
9282 /* We must free faces before destroying windows because some
9283 font-driver (e.g. xft) access a window while finishing a
9284 face. */
9285 if (FRAME_FACE_CACHE (f))
9286 free_frame_faces (f);
9288 if (f->output_data.x->icon_desc)
9289 XDestroyWindow (FRAME_X_DISPLAY (f), f->output_data.x->icon_desc);
9291 #ifdef USE_X_TOOLKIT
9292 /* Explicitly destroy the scroll bars of the frame. Without
9293 this, we get "BadDrawable" errors from the toolkit later on,
9294 presumably from expose events generated for the disappearing
9295 toolkit scroll bars. */
9296 for (bar = FRAME_SCROLL_BARS (f); !NILP (bar); bar = b->next)
9298 b = XSCROLL_BAR (bar);
9299 x_scroll_bar_remove (b);
9301 #endif
9303 #ifdef HAVE_X_I18N
9304 if (FRAME_XIC (f))
9305 free_frame_xic (f);
9306 #endif
9308 #ifdef USE_X_TOOLKIT
9309 if (f->output_data.x->widget)
9311 XtDestroyWidget (f->output_data.x->widget);
9312 f->output_data.x->widget = NULL;
9314 /* Tooltips don't have widgets, only a simple X window, even if
9315 we are using a toolkit. */
9316 else if (FRAME_X_WINDOW (f))
9317 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9319 free_frame_menubar (f);
9320 #else /* !USE_X_TOOLKIT */
9322 #ifdef USE_GTK
9323 xg_free_frame_widgets (f);
9324 #endif /* USE_GTK */
9326 if (FRAME_X_WINDOW (f))
9327 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9328 #endif /* !USE_X_TOOLKIT */
9330 unload_color (f, FRAME_FOREGROUND_PIXEL (f));
9331 unload_color (f, FRAME_BACKGROUND_PIXEL (f));
9332 unload_color (f, f->output_data.x->cursor_pixel);
9333 unload_color (f, f->output_data.x->cursor_foreground_pixel);
9334 unload_color (f, f->output_data.x->border_pixel);
9335 unload_color (f, f->output_data.x->mouse_pixel);
9337 if (f->output_data.x->scroll_bar_background_pixel != -1)
9338 unload_color (f, f->output_data.x->scroll_bar_background_pixel);
9339 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
9340 unload_color (f, f->output_data.x->scroll_bar_foreground_pixel);
9341 #ifdef USE_TOOLKIT_SCROLL_BARS
9342 /* Scrollbar shadow colors. */
9343 if (f->output_data.x->scroll_bar_top_shadow_pixel != -1)
9344 unload_color (f, f->output_data.x->scroll_bar_top_shadow_pixel);
9345 if (f->output_data.x->scroll_bar_bottom_shadow_pixel != -1)
9346 unload_color (f, f->output_data.x->scroll_bar_bottom_shadow_pixel);
9347 #endif /* USE_TOOLKIT_SCROLL_BARS */
9348 if (f->output_data.x->white_relief.allocated_p)
9349 unload_color (f, f->output_data.x->white_relief.pixel);
9350 if (f->output_data.x->black_relief.allocated_p)
9351 unload_color (f, f->output_data.x->black_relief.pixel);
9353 x_free_gcs (f);
9355 /* Free extra GCs allocated by x_setup_relief_colors. */
9356 if (f->output_data.x->white_relief.gc)
9358 XFreeGC (dpyinfo->display, f->output_data.x->white_relief.gc);
9359 f->output_data.x->white_relief.gc = 0;
9361 if (f->output_data.x->black_relief.gc)
9363 XFreeGC (dpyinfo->display, f->output_data.x->black_relief.gc);
9364 f->output_data.x->black_relief.gc = 0;
9367 XFlush (FRAME_X_DISPLAY (f));
9370 xfree (f->output_data.x->saved_menu_event);
9371 xfree (f->output_data.x);
9372 f->output_data.x = NULL;
9374 if (f == dpyinfo->x_focus_frame)
9375 dpyinfo->x_focus_frame = 0;
9376 if (f == dpyinfo->x_focus_event_frame)
9377 dpyinfo->x_focus_event_frame = 0;
9378 if (f == dpyinfo->x_highlight_frame)
9379 dpyinfo->x_highlight_frame = 0;
9380 if (f == hlinfo->mouse_face_mouse_frame)
9381 reset_mouse_highlight (hlinfo);
9383 unblock_input ();
9387 /* Destroy the X window of frame F. */
9389 static void
9390 x_destroy_window (struct frame *f)
9392 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
9394 /* If a display connection is dead, don't try sending more
9395 commands to the X server. */
9396 if (dpyinfo->display != 0)
9397 x_free_frame_resources (f);
9399 dpyinfo->reference_count--;
9403 /* Setting window manager hints. */
9405 /* Set the normal size hints for the window manager, for frame F.
9406 FLAGS is the flags word to use--or 0 meaning preserve the flags
9407 that the window now has.
9408 If USER_POSITION, set the USPosition
9409 flag (this is useful when FLAGS is 0).
9410 The GTK version is in gtkutils.c. */
9412 #ifndef USE_GTK
9413 void
9414 x_wm_set_size_hint (struct frame *f, long flags, bool user_position)
9416 XSizeHints size_hints;
9417 Window window = FRAME_OUTER_WINDOW (f);
9419 #ifdef USE_X_TOOLKIT
9420 if (f->output_data.x->widget)
9422 widget_update_wm_size_hints (f->output_data.x->widget);
9423 return;
9425 #endif
9427 /* Setting PMaxSize caused various problems. */
9428 size_hints.flags = PResizeInc | PMinSize /* | PMaxSize */;
9430 size_hints.x = f->left_pos;
9431 size_hints.y = f->top_pos;
9433 size_hints.height = FRAME_PIXEL_HEIGHT (f);
9434 size_hints.width = FRAME_PIXEL_WIDTH (f);
9436 size_hints.width_inc = FRAME_COLUMN_WIDTH (f);
9437 size_hints.height_inc = FRAME_LINE_HEIGHT (f);
9438 size_hints.max_width = x_display_pixel_width (FRAME_DISPLAY_INFO (f))
9439 - FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
9440 size_hints.max_height = x_display_pixel_height (FRAME_DISPLAY_INFO (f))
9441 - FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
9443 /* Calculate the base and minimum sizes. */
9445 int base_width, base_height;
9446 int min_rows = 0, min_cols = 0;
9448 base_width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
9449 base_height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
9451 check_frame_size (f, &min_rows, &min_cols);
9453 /* The window manager uses the base width hints to calculate the
9454 current number of rows and columns in the frame while
9455 resizing; min_width and min_height aren't useful for this
9456 purpose, since they might not give the dimensions for a
9457 zero-row, zero-column frame.
9459 We use the base_width and base_height members if we have
9460 them; otherwise, we set the min_width and min_height members
9461 to the size for a zero x zero frame. */
9463 size_hints.flags |= PBaseSize;
9464 size_hints.base_width = base_width;
9465 size_hints.base_height = base_height + FRAME_MENUBAR_HEIGHT (f);
9466 size_hints.min_width = base_width + min_cols * size_hints.width_inc;
9467 size_hints.min_height = base_height + min_rows * size_hints.height_inc;
9470 /* If we don't need the old flags, we don't need the old hint at all. */
9471 if (flags)
9473 size_hints.flags |= flags;
9474 goto no_read;
9478 XSizeHints hints; /* Sometimes I hate X Windows... */
9479 long supplied_return;
9480 int value;
9482 value = XGetWMNormalHints (FRAME_X_DISPLAY (f), window, &hints,
9483 &supplied_return);
9485 if (flags)
9486 size_hints.flags |= flags;
9487 else
9489 if (value == 0)
9490 hints.flags = 0;
9491 if (hints.flags & PSize)
9492 size_hints.flags |= PSize;
9493 if (hints.flags & PPosition)
9494 size_hints.flags |= PPosition;
9495 if (hints.flags & USPosition)
9496 size_hints.flags |= USPosition;
9497 if (hints.flags & USSize)
9498 size_hints.flags |= USSize;
9502 no_read:
9504 #ifdef PWinGravity
9505 size_hints.win_gravity = f->win_gravity;
9506 size_hints.flags |= PWinGravity;
9508 if (user_position)
9510 size_hints.flags &= ~ PPosition;
9511 size_hints.flags |= USPosition;
9513 #endif /* PWinGravity */
9515 XSetWMNormalHints (FRAME_X_DISPLAY (f), window, &size_hints);
9517 #endif /* not USE_GTK */
9519 /* Used for IconicState or NormalState */
9521 static void
9522 x_wm_set_window_state (struct frame *f, int state)
9524 #ifdef USE_X_TOOLKIT
9525 Arg al[1];
9527 XtSetArg (al[0], XtNinitialState, state);
9528 XtSetValues (f->output_data.x->widget, al, 1);
9529 #else /* not USE_X_TOOLKIT */
9530 Window window = FRAME_X_WINDOW (f);
9532 f->output_data.x->wm_hints.flags |= StateHint;
9533 f->output_data.x->wm_hints.initial_state = state;
9535 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
9536 #endif /* not USE_X_TOOLKIT */
9539 static void
9540 x_wm_set_icon_pixmap (struct frame *f, ptrdiff_t pixmap_id)
9542 Pixmap icon_pixmap, icon_mask;
9544 #if !defined USE_X_TOOLKIT && !defined USE_GTK
9545 Window window = FRAME_OUTER_WINDOW (f);
9546 #endif
9548 if (pixmap_id > 0)
9550 icon_pixmap = x_bitmap_pixmap (f, pixmap_id);
9551 f->output_data.x->wm_hints.icon_pixmap = icon_pixmap;
9552 icon_mask = x_bitmap_mask (f, pixmap_id);
9553 f->output_data.x->wm_hints.icon_mask = icon_mask;
9555 else
9557 /* It seems there is no way to turn off use of an icon
9558 pixmap. */
9559 return;
9563 #ifdef USE_GTK
9565 xg_set_frame_icon (f, icon_pixmap, icon_mask);
9566 return;
9569 #elif defined (USE_X_TOOLKIT) /* same as in x_wm_set_window_state. */
9572 Arg al[1];
9573 XtSetArg (al[0], XtNiconPixmap, icon_pixmap);
9574 XtSetValues (f->output_data.x->widget, al, 1);
9575 XtSetArg (al[0], XtNiconMask, icon_mask);
9576 XtSetValues (f->output_data.x->widget, al, 1);
9579 #else /* not USE_X_TOOLKIT && not USE_GTK */
9581 f->output_data.x->wm_hints.flags |= (IconPixmapHint | IconMaskHint);
9582 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
9584 #endif /* not USE_X_TOOLKIT && not USE_GTK */
9587 void
9588 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
9590 Window window = FRAME_OUTER_WINDOW (f);
9592 f->output_data.x->wm_hints.flags |= IconPositionHint;
9593 f->output_data.x->wm_hints.icon_x = icon_x;
9594 f->output_data.x->wm_hints.icon_y = icon_y;
9596 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
9600 /***********************************************************************
9601 Fonts
9602 ***********************************************************************/
9604 #ifdef GLYPH_DEBUG
9606 /* Check that FONT is valid on frame F. It is if it can be found in F's
9607 font table. */
9609 static void
9610 x_check_font (struct frame *f, struct font *font)
9612 eassert (font != NULL && ! NILP (font->props[FONT_TYPE_INDEX]));
9613 if (font->driver->check)
9614 eassert (font->driver->check (f, font) == 0);
9617 #endif /* GLYPH_DEBUG */
9620 /***********************************************************************
9621 Initialization
9622 ***********************************************************************/
9624 #ifdef USE_X_TOOLKIT
9625 static XrmOptionDescRec emacs_options[] = {
9626 {"-geometry", ".geometry", XrmoptionSepArg, NULL},
9627 {"-iconic", ".iconic", XrmoptionNoArg, (XtPointer) "yes"},
9629 {"-internal-border-width", "*EmacsScreen.internalBorderWidth",
9630 XrmoptionSepArg, NULL},
9631 {"-ib", "*EmacsScreen.internalBorderWidth", XrmoptionSepArg, NULL},
9633 {"-T", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
9634 {"-wn", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
9635 {"-title", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
9636 {"-iconname", "*EmacsShell.iconName", XrmoptionSepArg, (XtPointer) NULL},
9637 {"-in", "*EmacsShell.iconName", XrmoptionSepArg, (XtPointer) NULL},
9638 {"-mc", "*pointerColor", XrmoptionSepArg, (XtPointer) NULL},
9639 {"-cr", "*cursorColor", XrmoptionSepArg, (XtPointer) NULL}
9642 /* Whether atimer for Xt timeouts is activated or not. */
9644 static int x_timeout_atimer_activated_flag;
9646 #endif /* USE_X_TOOLKIT */
9648 static int x_initialized;
9650 /* Test whether two display-name strings agree up to the dot that separates
9651 the screen number from the server number. */
9652 static int
9653 same_x_server (const char *name1, const char *name2)
9655 int seen_colon = 0;
9656 const char *system_name = SSDATA (Vsystem_name);
9657 ptrdiff_t system_name_length = SBYTES (Vsystem_name);
9658 ptrdiff_t length_until_period = 0;
9660 while (system_name[length_until_period] != 0
9661 && system_name[length_until_period] != '.')
9662 length_until_period++;
9664 /* Treat `unix' like an empty host name. */
9665 if (! strncmp (name1, "unix:", 5))
9666 name1 += 4;
9667 if (! strncmp (name2, "unix:", 5))
9668 name2 += 4;
9669 /* Treat this host's name like an empty host name. */
9670 if (! strncmp (name1, system_name, system_name_length)
9671 && name1[system_name_length] == ':')
9672 name1 += system_name_length;
9673 if (! strncmp (name2, system_name, system_name_length)
9674 && name2[system_name_length] == ':')
9675 name2 += system_name_length;
9676 /* Treat this host's domainless name like an empty host name. */
9677 if (! strncmp (name1, system_name, length_until_period)
9678 && name1[length_until_period] == ':')
9679 name1 += length_until_period;
9680 if (! strncmp (name2, system_name, length_until_period)
9681 && name2[length_until_period] == ':')
9682 name2 += length_until_period;
9684 for (; *name1 != '\0' && *name1 == *name2; name1++, name2++)
9686 if (*name1 == ':')
9687 seen_colon = 1;
9688 if (seen_colon && *name1 == '.')
9689 return 1;
9691 return (seen_colon
9692 && (*name1 == '.' || *name1 == '\0')
9693 && (*name2 == '.' || *name2 == '\0'));
9696 /* Count number of set bits in mask and number of bits to shift to
9697 get to the first bit. With MASK 0x7e0, *BITS is set to 6, and *OFFSET
9698 to 5. */
9699 static void
9700 get_bits_and_offset (long unsigned int mask, int *bits, int *offset)
9702 int nr = 0;
9703 int off = 0;
9705 while (!(mask & 1))
9707 off++;
9708 mask >>= 1;
9711 while (mask & 1)
9713 nr++;
9714 mask >>= 1;
9717 *offset = off;
9718 *bits = nr;
9721 /* Return 1 if display DISPLAY is available for use, 0 otherwise.
9722 But don't permanently open it, just test its availability. */
9724 bool
9725 x_display_ok (const char *display)
9727 Display *dpy = XOpenDisplay (display);
9728 return dpy ? (XCloseDisplay (dpy), 1) : 0;
9731 #ifdef USE_GTK
9732 static void
9733 my_log_handler (const gchar *log_domain, GLogLevelFlags log_level,
9734 const gchar *msg, gpointer user_data)
9736 if (!strstr (msg, "g_set_prgname"))
9737 fprintf (stderr, "%s-WARNING **: %s\n", log_domain, msg);
9739 #endif
9741 /* Open a connection to X display DISPLAY_NAME, and return
9742 the structure that describes the open display.
9743 If we cannot contact the display, return null. */
9745 struct x_display_info *
9746 x_term_init (Lisp_Object display_name, char *xrm_option, char *resource_name)
9748 int connection;
9749 Display *dpy;
9750 struct terminal *terminal;
9751 struct x_display_info *dpyinfo;
9752 XrmDatabase xrdb;
9753 ptrdiff_t lim;
9755 block_input ();
9757 if (!x_initialized)
9759 x_initialize ();
9760 ++x_initialized;
9763 if (! x_display_ok (SSDATA (display_name)))
9764 error ("Display %s can't be opened", SSDATA (display_name));
9766 #ifdef USE_GTK
9768 #define NUM_ARGV 10
9769 int argc;
9770 char *argv[NUM_ARGV];
9771 char **argv2 = argv;
9772 guint id;
9774 if (x_initialized++ > 1)
9776 xg_display_open (SSDATA (display_name), &dpy);
9778 else
9780 static char display_opt[] = "--display";
9781 static char name_opt[] = "--name";
9783 for (argc = 0; argc < NUM_ARGV; ++argc)
9784 argv[argc] = 0;
9786 argc = 0;
9787 argv[argc++] = initial_argv[0];
9789 if (! NILP (display_name))
9791 argv[argc++] = display_opt;
9792 argv[argc++] = SSDATA (display_name);
9795 argv[argc++] = name_opt;
9796 argv[argc++] = resource_name;
9798 XSetLocaleModifiers ("");
9800 /* Emacs can only handle core input events, so make sure
9801 Gtk doesn't use Xinput or Xinput2 extensions. */
9802 xputenv ("GDK_CORE_DEVICE_EVENTS=1");
9804 /* Work around GLib bug that outputs a faulty warning. See
9805 https://bugzilla.gnome.org/show_bug.cgi?id=563627. */
9806 id = g_log_set_handler ("GLib", G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
9807 | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
9809 /* NULL window -> events for all windows go to our function.
9810 Call before gtk_init so Gtk+ event filters comes after our. */
9811 gdk_window_add_filter (NULL, event_handler_gdk, NULL);
9813 /* gtk_init does set_locale. Fix locale before and after. */
9814 fixup_locale ();
9815 gtk_init (&argc, &argv2);
9816 fixup_locale ();
9818 g_log_remove_handler ("GLib", id);
9820 xg_initialize ();
9822 dpy = DEFAULT_GDK_DISPLAY ();
9824 #if ! GTK_CHECK_VERSION (2, 90, 0)
9825 /* Load our own gtkrc if it exists. */
9827 const char *file = "~/.emacs.d/gtkrc";
9828 Lisp_Object s, abs_file;
9830 s = build_string (file);
9831 abs_file = Fexpand_file_name (s, Qnil);
9833 if (! NILP (abs_file) && !NILP (Ffile_readable_p (abs_file)))
9834 gtk_rc_parse (SSDATA (abs_file));
9836 #endif
9838 XSetErrorHandler (x_error_handler);
9839 XSetIOErrorHandler (x_io_error_quitter);
9842 #else /* not USE_GTK */
9843 #ifdef USE_X_TOOLKIT
9844 /* weiner@footloose.sps.mot.com reports that this causes
9845 errors with X11R5:
9846 X protocol error: BadAtom (invalid Atom parameter)
9847 on protocol request 18skiloaf.
9848 So let's not use it until R6. */
9849 #ifdef HAVE_X11XTR6
9850 XtSetLanguageProc (NULL, NULL, NULL);
9851 #endif
9854 int argc = 0;
9855 char *argv[3];
9857 argv[0] = "";
9858 argc = 1;
9859 if (xrm_option)
9861 argv[argc++] = "-xrm";
9862 argv[argc++] = xrm_option;
9864 turn_on_atimers (0);
9865 dpy = XtOpenDisplay (Xt_app_con, SSDATA (display_name),
9866 resource_name, EMACS_CLASS,
9867 emacs_options, XtNumber (emacs_options),
9868 &argc, argv);
9869 turn_on_atimers (1);
9871 #ifdef HAVE_X11XTR6
9872 /* I think this is to compensate for XtSetLanguageProc. */
9873 fixup_locale ();
9874 #endif
9877 #else /* not USE_X_TOOLKIT */
9878 XSetLocaleModifiers ("");
9879 dpy = XOpenDisplay (SSDATA (display_name));
9880 #endif /* not USE_X_TOOLKIT */
9881 #endif /* not USE_GTK*/
9883 /* Detect failure. */
9884 if (dpy == 0)
9886 unblock_input ();
9887 return 0;
9890 /* We have definitely succeeded. Record the new connection. */
9892 dpyinfo = xzalloc (sizeof *dpyinfo);
9893 terminal = x_create_terminal (dpyinfo);
9896 struct x_display_info *share;
9897 Lisp_Object tail;
9899 for (share = x_display_list, tail = x_display_name_list; share;
9900 share = share->next, tail = XCDR (tail))
9901 if (same_x_server (SSDATA (XCAR (XCAR (tail))),
9902 SSDATA (display_name)))
9903 break;
9904 if (share)
9905 terminal->kboard = share->terminal->kboard;
9906 else
9908 terminal->kboard = xmalloc (sizeof *terminal->kboard);
9909 init_kboard (terminal->kboard);
9910 kset_window_system (terminal->kboard, Qx);
9912 /* Add the keyboard to the list before running Lisp code (via
9913 Qvendor_specific_keysyms below), since these are not traced
9914 via terminals but only through all_kboards. */
9915 terminal->kboard->next_kboard = all_kboards;
9916 all_kboards = terminal->kboard;
9918 if (!EQ (XSYMBOL (Qvendor_specific_keysyms)->function, Qunbound))
9920 char *vendor = ServerVendor (dpy);
9922 /* Protect terminal from GC before removing it from the
9923 list of terminals. */
9924 struct gcpro gcpro1;
9925 Lisp_Object gcpro_term;
9926 XSETTERMINAL (gcpro_term, terminal);
9927 GCPRO1 (gcpro_term);
9929 /* Temporarily hide the partially initialized terminal. */
9930 terminal_list = terminal->next_terminal;
9931 unblock_input ();
9932 kset_system_key_alist
9933 (terminal->kboard,
9934 call1 (Qvendor_specific_keysyms,
9935 vendor ? build_string (vendor) : empty_unibyte_string));
9936 block_input ();
9937 terminal->next_terminal = terminal_list;
9938 terminal_list = terminal;
9939 UNGCPRO;
9942 /* Don't let the initial kboard remain current longer than necessary.
9943 That would cause problems if a file loaded on startup tries to
9944 prompt in the mini-buffer. */
9945 if (current_kboard == initial_kboard)
9946 current_kboard = terminal->kboard;
9948 terminal->kboard->reference_count++;
9951 /* Put this display on the chain. */
9952 dpyinfo->next = x_display_list;
9953 x_display_list = dpyinfo;
9955 /* Put it on x_display_name_list as well, to keep them parallel. */
9956 x_display_name_list = Fcons (Fcons (display_name, Qnil),
9957 x_display_name_list);
9958 dpyinfo->name_list_element = XCAR (x_display_name_list);
9960 dpyinfo->display = dpy;
9962 /* Set the name of the terminal. */
9963 terminal->name = xlispstrdup (display_name);
9965 #if 0
9966 XSetAfterFunction (x_current_display, x_trace_wire);
9967 #endif /* ! 0 */
9969 lim = min (PTRDIFF_MAX, SIZE_MAX) - sizeof "@";
9970 if (lim - SBYTES (Vinvocation_name) < SBYTES (Vsystem_name))
9971 memory_full (SIZE_MAX);
9972 dpyinfo->x_id_name = xmalloc (SBYTES (Vinvocation_name)
9973 + SBYTES (Vsystem_name) + 2);
9974 strcat (strcat (strcpy (dpyinfo->x_id_name, SSDATA (Vinvocation_name)), "@"),
9975 SSDATA (Vsystem_name));
9977 /* Figure out which modifier bits mean what. */
9978 x_find_modifier_meanings (dpyinfo);
9980 /* Get the scroll bar cursor. */
9981 #ifdef USE_GTK
9982 /* We must create a GTK cursor, it is required for GTK widgets. */
9983 dpyinfo->xg_cursor = xg_create_default_cursor (dpyinfo->display);
9984 #endif /* USE_GTK */
9986 dpyinfo->vertical_scroll_bar_cursor
9987 = XCreateFontCursor (dpyinfo->display, XC_sb_v_double_arrow);
9989 xrdb = x_load_resources (dpyinfo->display, xrm_option,
9990 resource_name, EMACS_CLASS);
9991 #ifdef HAVE_XRMSETDATABASE
9992 XrmSetDatabase (dpyinfo->display, xrdb);
9993 #else
9994 dpyinfo->display->db = xrdb;
9995 #endif
9996 /* Put the rdb where we can find it in a way that works on
9997 all versions. */
9998 dpyinfo->xrdb = xrdb;
10000 dpyinfo->screen = ScreenOfDisplay (dpyinfo->display,
10001 DefaultScreen (dpyinfo->display));
10002 select_visual (dpyinfo);
10003 dpyinfo->cmap = DefaultColormapOfScreen (dpyinfo->screen);
10004 dpyinfo->root_window = RootWindowOfScreen (dpyinfo->screen);
10005 dpyinfo->icon_bitmap_id = -1;
10006 dpyinfo->wm_type = X_WMTYPE_UNKNOWN;
10008 reset_mouse_highlight (&dpyinfo->mouse_highlight);
10010 /* See if we can construct pixel values from RGB values. */
10011 if (dpyinfo->visual->class == TrueColor)
10013 get_bits_and_offset (dpyinfo->visual->red_mask,
10014 &dpyinfo->red_bits, &dpyinfo->red_offset);
10015 get_bits_and_offset (dpyinfo->visual->blue_mask,
10016 &dpyinfo->blue_bits, &dpyinfo->blue_offset);
10017 get_bits_and_offset (dpyinfo->visual->green_mask,
10018 &dpyinfo->green_bits, &dpyinfo->green_offset);
10021 /* See if a private colormap is requested. */
10022 if (dpyinfo->visual == DefaultVisualOfScreen (dpyinfo->screen))
10024 if (dpyinfo->visual->class == PseudoColor)
10026 Lisp_Object value;
10027 value = display_x_get_resource (dpyinfo,
10028 build_string ("privateColormap"),
10029 build_string ("PrivateColormap"),
10030 Qnil, Qnil);
10031 if (STRINGP (value)
10032 && (!strcmp (SSDATA (value), "true")
10033 || !strcmp (SSDATA (value), "on")))
10034 dpyinfo->cmap = XCopyColormapAndFree (dpyinfo->display, dpyinfo->cmap);
10037 else
10038 dpyinfo->cmap = XCreateColormap (dpyinfo->display, dpyinfo->root_window,
10039 dpyinfo->visual, AllocNone);
10041 #ifdef HAVE_XFT
10043 /* If we are using Xft, check dpi value in X resources.
10044 It is better we use it as well, since Xft will use it, as will all
10045 Gnome applications. If our real DPI is smaller or larger than the
10046 one Xft uses, our font will look smaller or larger than other
10047 for other applications, even if it is the same font name (monospace-10
10048 for example). */
10049 char *v = XGetDefault (dpyinfo->display, "Xft", "dpi");
10050 double d;
10051 if (v != NULL && sscanf (v, "%lf", &d) == 1)
10052 dpyinfo->resy = dpyinfo->resx = d;
10054 #endif
10056 if (dpyinfo->resy < 1)
10058 int screen_number = XScreenNumberOfScreen (dpyinfo->screen);
10059 double pixels = DisplayHeight (dpyinfo->display, screen_number);
10060 double mm = DisplayHeightMM (dpyinfo->display, screen_number);
10061 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
10062 dpyinfo->resy = (mm < 1) ? 100 : pixels * 25.4 / mm;
10063 pixels = DisplayWidth (dpyinfo->display, screen_number);
10064 mm = DisplayWidthMM (dpyinfo->display, screen_number);
10065 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
10066 dpyinfo->resx = (mm < 1) ? 100 : pixels * 25.4 / mm;
10070 static const struct
10072 const char *name;
10073 int offset;
10074 } atom_refs[] = {
10075 #define ATOM_REFS_INIT(string, member) \
10076 { string, offsetof (struct x_display_info, member) },
10077 ATOM_REFS_INIT ("WM_PROTOCOLS", Xatom_wm_protocols)
10078 ATOM_REFS_INIT ("WM_TAKE_FOCUS", Xatom_wm_take_focus)
10079 ATOM_REFS_INIT ("WM_SAVE_YOURSELF", Xatom_wm_save_yourself)
10080 ATOM_REFS_INIT ("WM_DELETE_WINDOW", Xatom_wm_delete_window)
10081 ATOM_REFS_INIT ("WM_CHANGE_STATE", Xatom_wm_change_state)
10082 ATOM_REFS_INIT ("WM_CONFIGURE_DENIED", Xatom_wm_configure_denied)
10083 ATOM_REFS_INIT ("WM_MOVED", Xatom_wm_window_moved)
10084 ATOM_REFS_INIT ("WM_CLIENT_LEADER", Xatom_wm_client_leader)
10085 ATOM_REFS_INIT ("Editres", Xatom_editres)
10086 ATOM_REFS_INIT ("CLIPBOARD", Xatom_CLIPBOARD)
10087 ATOM_REFS_INIT ("TIMESTAMP", Xatom_TIMESTAMP)
10088 ATOM_REFS_INIT ("TEXT", Xatom_TEXT)
10089 ATOM_REFS_INIT ("COMPOUND_TEXT", Xatom_COMPOUND_TEXT)
10090 ATOM_REFS_INIT ("UTF8_STRING", Xatom_UTF8_STRING)
10091 ATOM_REFS_INIT ("DELETE", Xatom_DELETE)
10092 ATOM_REFS_INIT ("MULTIPLE", Xatom_MULTIPLE)
10093 ATOM_REFS_INIT ("INCR", Xatom_INCR)
10094 ATOM_REFS_INIT ("_EMACS_TMP_", Xatom_EMACS_TMP)
10095 ATOM_REFS_INIT ("TARGETS", Xatom_TARGETS)
10096 ATOM_REFS_INIT ("NULL", Xatom_NULL)
10097 ATOM_REFS_INIT ("ATOM", Xatom_ATOM)
10098 ATOM_REFS_INIT ("ATOM_PAIR", Xatom_ATOM_PAIR)
10099 ATOM_REFS_INIT ("CLIPBOARD_MANAGER", Xatom_CLIPBOARD_MANAGER)
10100 ATOM_REFS_INIT ("_XEMBED_INFO", Xatom_XEMBED_INFO)
10101 /* For properties of font. */
10102 ATOM_REFS_INIT ("PIXEL_SIZE", Xatom_PIXEL_SIZE)
10103 ATOM_REFS_INIT ("AVERAGE_WIDTH", Xatom_AVERAGE_WIDTH)
10104 ATOM_REFS_INIT ("_MULE_BASELINE_OFFSET", Xatom_MULE_BASELINE_OFFSET)
10105 ATOM_REFS_INIT ("_MULE_RELATIVE_COMPOSE", Xatom_MULE_RELATIVE_COMPOSE)
10106 ATOM_REFS_INIT ("_MULE_DEFAULT_ASCENT", Xatom_MULE_DEFAULT_ASCENT)
10107 /* Ghostscript support. */
10108 ATOM_REFS_INIT ("DONE", Xatom_DONE)
10109 ATOM_REFS_INIT ("PAGE", Xatom_PAGE)
10110 ATOM_REFS_INIT ("SCROLLBAR", Xatom_Scrollbar)
10111 ATOM_REFS_INIT ("_XEMBED", Xatom_XEMBED)
10112 /* EWMH */
10113 ATOM_REFS_INIT ("_NET_WM_STATE", Xatom_net_wm_state)
10114 ATOM_REFS_INIT ("_NET_WM_STATE_FULLSCREEN", Xatom_net_wm_state_fullscreen)
10115 ATOM_REFS_INIT ("_NET_WM_STATE_MAXIMIZED_HORZ",
10116 Xatom_net_wm_state_maximized_horz)
10117 ATOM_REFS_INIT ("_NET_WM_STATE_MAXIMIZED_VERT",
10118 Xatom_net_wm_state_maximized_vert)
10119 ATOM_REFS_INIT ("_NET_WM_STATE_STICKY", Xatom_net_wm_state_sticky)
10120 ATOM_REFS_INIT ("_NET_WM_STATE_HIDDEN", Xatom_net_wm_state_hidden)
10121 ATOM_REFS_INIT ("_NET_WM_WINDOW_TYPE", Xatom_net_window_type)
10122 ATOM_REFS_INIT ("_NET_WM_WINDOW_TYPE_TOOLTIP",
10123 Xatom_net_window_type_tooltip)
10124 ATOM_REFS_INIT ("_NET_WM_ICON_NAME", Xatom_net_wm_icon_name)
10125 ATOM_REFS_INIT ("_NET_WM_NAME", Xatom_net_wm_name)
10126 ATOM_REFS_INIT ("_NET_SUPPORTED", Xatom_net_supported)
10127 ATOM_REFS_INIT ("_NET_SUPPORTING_WM_CHECK", Xatom_net_supporting_wm_check)
10128 ATOM_REFS_INIT ("_NET_WM_WINDOW_OPACITY", Xatom_net_wm_window_opacity)
10129 ATOM_REFS_INIT ("_NET_ACTIVE_WINDOW", Xatom_net_active_window)
10130 ATOM_REFS_INIT ("_NET_FRAME_EXTENTS", Xatom_net_frame_extents)
10131 ATOM_REFS_INIT ("_NET_CURRENT_DESKTOP", Xatom_net_current_desktop)
10132 ATOM_REFS_INIT ("_NET_WORKAREA", Xatom_net_workarea)
10133 /* Session management */
10134 ATOM_REFS_INIT ("SM_CLIENT_ID", Xatom_SM_CLIENT_ID)
10135 ATOM_REFS_INIT ("_XSETTINGS_SETTINGS", Xatom_xsettings_prop)
10136 ATOM_REFS_INIT ("MANAGER", Xatom_xsettings_mgr)
10139 int i;
10140 const int atom_count = sizeof (atom_refs) / sizeof (atom_refs[0]);
10141 /* 1 for _XSETTINGS_SN */
10142 const int total_atom_count = 1 + atom_count;
10143 Atom *atoms_return = xmalloc (total_atom_count * sizeof *atoms_return);
10144 char **atom_names = xmalloc (total_atom_count * sizeof *atom_names);
10145 static char const xsettings_fmt[] = "_XSETTINGS_S%d";
10146 char xsettings_atom_name[sizeof xsettings_fmt - 2
10147 + INT_STRLEN_BOUND (int)];
10149 for (i = 0; i < atom_count; i++)
10150 atom_names[i] = (char *) atom_refs[i].name;
10152 /* Build _XSETTINGS_SN atom name */
10153 sprintf (xsettings_atom_name, xsettings_fmt,
10154 XScreenNumberOfScreen (dpyinfo->screen));
10155 atom_names[i] = xsettings_atom_name;
10157 XInternAtoms (dpyinfo->display, atom_names, total_atom_count,
10158 False, atoms_return);
10160 for (i = 0; i < atom_count; i++)
10161 *(Atom *) ((char *) dpyinfo + atom_refs[i].offset) = atoms_return[i];
10163 /* Manual copy of last atom */
10164 dpyinfo->Xatom_xsettings_sel = atoms_return[i];
10166 xfree (atom_names);
10167 xfree (atoms_return);
10170 dpyinfo->x_dnd_atoms_size = 8;
10171 dpyinfo->x_dnd_atoms = xmalloc (sizeof *dpyinfo->x_dnd_atoms
10172 * dpyinfo->x_dnd_atoms_size);
10173 dpyinfo->gray
10174 = XCreatePixmapFromBitmapData (dpyinfo->display, dpyinfo->root_window,
10175 gray_bits, gray_width, gray_height,
10176 1, 0, 1);
10178 #ifdef HAVE_X_I18N
10179 xim_initialize (dpyinfo, resource_name);
10180 #endif
10182 xsettings_initialize (dpyinfo);
10184 connection = ConnectionNumber (dpyinfo->display);
10186 /* This is only needed for distinguishing keyboard and process input. */
10187 if (connection != 0)
10188 add_keyboard_wait_descriptor (connection);
10190 #ifdef F_SETOWN
10191 fcntl (connection, F_SETOWN, getpid ());
10192 #endif /* ! defined (F_SETOWN) */
10194 if (interrupt_input)
10195 init_sigio (connection);
10197 #ifdef USE_LUCID
10199 XrmValue d, fr, to;
10200 Font font;
10202 dpy = dpyinfo->display;
10203 d.addr = (XPointer)&dpy;
10204 d.size = sizeof (Display *);
10205 fr.addr = XtDefaultFont;
10206 fr.size = sizeof (XtDefaultFont);
10207 to.size = sizeof (Font *);
10208 to.addr = (XPointer)&font;
10209 x_catch_errors (dpy);
10210 if (!XtCallConverter (dpy, XtCvtStringToFont, &d, 1, &fr, &to, NULL))
10211 emacs_abort ();
10212 if (x_had_errors_p (dpy) || !XQueryFont (dpy, font))
10213 XrmPutLineResource (&xrdb, "Emacs.dialog.*.font: 9x15");
10214 x_uncatch_errors ();
10216 #endif
10218 /* See if we should run in synchronous mode. This is useful
10219 for debugging X code. */
10221 Lisp_Object value;
10222 value = display_x_get_resource (dpyinfo,
10223 build_string ("synchronous"),
10224 build_string ("Synchronous"),
10225 Qnil, Qnil);
10226 if (STRINGP (value)
10227 && (!strcmp (SSDATA (value), "true")
10228 || !strcmp (SSDATA (value), "on")))
10229 XSynchronize (dpyinfo->display, True);
10233 Lisp_Object value;
10234 value = display_x_get_resource (dpyinfo,
10235 build_string ("useXIM"),
10236 build_string ("UseXIM"),
10237 Qnil, Qnil);
10238 #ifdef USE_XIM
10239 if (STRINGP (value)
10240 && (!strcmp (SSDATA (value), "false")
10241 || !strcmp (SSDATA (value), "off")))
10242 use_xim = 0;
10243 #else
10244 if (STRINGP (value)
10245 && (!strcmp (SSDATA (value), "true")
10246 || !strcmp (SSDATA (value), "on")))
10247 use_xim = 1;
10248 #endif
10251 #ifdef HAVE_X_SM
10252 /* Only do this for the very first display in the Emacs session.
10253 Ignore X session management when Emacs was first started on a
10254 tty. */
10255 if (terminal->id == 1)
10256 x_session_initialize (dpyinfo);
10257 #endif
10259 unblock_input ();
10261 return dpyinfo;
10264 /* Get rid of display DPYINFO, deleting all frames on it,
10265 and without sending any more commands to the X server. */
10267 static void
10268 x_delete_display (struct x_display_info *dpyinfo)
10270 struct terminal *t;
10272 /* Close all frames and delete the generic struct terminal for this
10273 X display. */
10274 for (t = terminal_list; t; t = t->next_terminal)
10275 if (t->type == output_x_window && t->display_info.x == dpyinfo)
10277 #ifdef HAVE_X_SM
10278 /* Close X session management when we close its display. */
10279 if (t->id == 1 && x_session_have_connection ())
10280 x_session_close ();
10281 #endif
10282 delete_terminal (t);
10283 break;
10286 /* Discard this display from x_display_name_list and x_display_list.
10287 We can't use Fdelq because that can quit. */
10288 if (! NILP (x_display_name_list)
10289 && EQ (XCAR (x_display_name_list), dpyinfo->name_list_element))
10290 x_display_name_list = XCDR (x_display_name_list);
10291 else
10293 Lisp_Object tail;
10295 tail = x_display_name_list;
10296 while (CONSP (tail) && CONSP (XCDR (tail)))
10298 if (EQ (XCAR (XCDR (tail)), dpyinfo->name_list_element))
10300 XSETCDR (tail, XCDR (XCDR (tail)));
10301 break;
10303 tail = XCDR (tail);
10307 if (next_noop_dpyinfo == dpyinfo)
10308 next_noop_dpyinfo = dpyinfo->next;
10310 if (x_display_list == dpyinfo)
10311 x_display_list = dpyinfo->next;
10312 else
10314 struct x_display_info *tail;
10316 for (tail = x_display_list; tail; tail = tail->next)
10317 if (tail->next == dpyinfo)
10318 tail->next = tail->next->next;
10321 xfree (dpyinfo->x_id_name);
10322 xfree (dpyinfo->x_dnd_atoms);
10323 xfree (dpyinfo->color_cells);
10324 xfree (dpyinfo);
10327 #ifdef USE_X_TOOLKIT
10329 /* Atimer callback function for TIMER. Called every 0.1s to process
10330 Xt timeouts, if needed. We must avoid calling XtAppPending as
10331 much as possible because that function does an implicit XFlush
10332 that slows us down. */
10334 static void
10335 x_process_timeouts (struct atimer *timer)
10337 block_input ();
10338 x_timeout_atimer_activated_flag = 0;
10339 if (toolkit_scroll_bar_interaction || popup_activated ())
10341 while (XtAppPending (Xt_app_con) & XtIMTimer)
10342 XtAppProcessEvent (Xt_app_con, XtIMTimer);
10343 /* Reactivate the atimer for next time. */
10344 x_activate_timeout_atimer ();
10346 unblock_input ();
10349 /* Install an asynchronous timer that processes Xt timeout events
10350 every 0.1s as long as either `toolkit_scroll_bar_interaction' or
10351 `popup_activated_flag' (in xmenu.c) is set. Make sure to call this
10352 function whenever these variables are set. This is necessary
10353 because some widget sets use timeouts internally, for example the
10354 LessTif menu bar, or the Xaw3d scroll bar. When Xt timeouts aren't
10355 processed, these widgets don't behave normally. */
10357 void
10358 x_activate_timeout_atimer (void)
10360 block_input ();
10361 if (!x_timeout_atimer_activated_flag)
10363 struct timespec interval = make_timespec (0, 100 * 1000 * 1000);
10364 start_atimer (ATIMER_RELATIVE, interval, x_process_timeouts, 0);
10365 x_timeout_atimer_activated_flag = 1;
10367 unblock_input ();
10370 #endif /* USE_X_TOOLKIT */
10373 /* Set up use of X before we make the first connection. */
10375 static struct redisplay_interface x_redisplay_interface =
10377 x_frame_parm_handlers,
10378 x_produce_glyphs,
10379 x_write_glyphs,
10380 x_insert_glyphs,
10381 x_clear_end_of_line,
10382 x_scroll_run,
10383 x_after_update_window_line,
10384 x_update_window_begin,
10385 x_update_window_end,
10386 x_flush,
10387 x_clear_window_mouse_face,
10388 x_get_glyph_overhangs,
10389 x_fix_overlapping_area,
10390 x_draw_fringe_bitmap,
10391 0, /* define_fringe_bitmap */
10392 0, /* destroy_fringe_bitmap */
10393 x_compute_glyph_string_overhangs,
10394 x_draw_glyph_string,
10395 x_define_frame_cursor,
10396 x_clear_frame_area,
10397 x_draw_window_cursor,
10398 x_draw_vertical_window_border,
10399 x_shift_glyphs_for_insert
10403 /* This function is called when the last frame on a display is deleted. */
10404 void
10405 x_delete_terminal (struct terminal *terminal)
10407 struct x_display_info *dpyinfo = terminal->display_info.x;
10408 int connection = -1;
10410 /* Protect against recursive calls. delete_frame in
10411 delete_terminal calls us back when it deletes our last frame. */
10412 if (!terminal->name)
10413 return;
10415 block_input ();
10416 #ifdef HAVE_X_I18N
10417 /* We must close our connection to the XIM server before closing the
10418 X display. */
10419 if (dpyinfo->xim)
10420 xim_close_dpy (dpyinfo);
10421 #endif
10423 /* If called from x_connection_closed, the display may already be closed
10424 and dpyinfo->display was set to 0 to indicate that. */
10425 if (dpyinfo->display)
10427 connection = ConnectionNumber (dpyinfo->display);
10429 x_destroy_all_bitmaps (dpyinfo);
10430 XSetCloseDownMode (dpyinfo->display, DestroyAll);
10432 /* Whether or not XCloseDisplay destroys the associated resource
10433 database depends on the version of libX11. To avoid both
10434 crash and memory leak, we dissociate the database from the
10435 display and then destroy dpyinfo->xrdb ourselves.
10437 Unfortunately, the above strategy does not work in some
10438 situations due to a bug in newer versions of libX11: because
10439 XrmSetDatabase doesn't clear the flag XlibDisplayDfltRMDB if
10440 dpy->db is NULL, XCloseDisplay destroys the associated
10441 database whereas it has not been created by XGetDefault
10442 (Bug#21974 in freedesktop.org Bugzilla). As a workaround, we
10443 don't destroy the database here in order to avoid the crash
10444 in the above situations for now, though that may cause memory
10445 leaks in other situations. */
10446 #if 0
10447 #ifdef HAVE_XRMSETDATABASE
10448 XrmSetDatabase (dpyinfo->display, NULL);
10449 #else
10450 dpyinfo->display->db = NULL;
10451 #endif
10452 /* We used to call XrmDestroyDatabase from x_delete_display, but
10453 some older versions of libX11 crash if we call it after
10454 closing all the displays. */
10455 XrmDestroyDatabase (dpyinfo->xrdb);
10456 #endif
10458 #ifdef USE_GTK
10459 xg_display_close (dpyinfo->display);
10460 #else
10461 #ifdef USE_X_TOOLKIT
10462 XtCloseDisplay (dpyinfo->display);
10463 #else
10464 XCloseDisplay (dpyinfo->display);
10465 #endif
10466 #endif /* ! USE_GTK */
10469 /* No more input on this descriptor. */
10470 if (connection != -1)
10471 delete_keyboard_wait_descriptor (connection);
10473 /* Mark as dead. */
10474 dpyinfo->display = NULL;
10475 x_delete_display (dpyinfo);
10476 unblock_input ();
10479 /* Create a struct terminal, initialize it with the X11 specific
10480 functions and make DISPLAY->TERMINAL point to it. */
10482 static struct terminal *
10483 x_create_terminal (struct x_display_info *dpyinfo)
10485 struct terminal *terminal;
10487 terminal = create_terminal ();
10489 terminal->type = output_x_window;
10490 terminal->display_info.x = dpyinfo;
10491 dpyinfo->terminal = terminal;
10493 /* kboard is initialized in x_term_init. */
10495 terminal->clear_frame_hook = x_clear_frame;
10496 terminal->ins_del_lines_hook = x_ins_del_lines;
10497 terminal->delete_glyphs_hook = x_delete_glyphs;
10498 terminal->ring_bell_hook = XTring_bell;
10499 terminal->toggle_invisible_pointer_hook = XTtoggle_invisible_pointer;
10500 terminal->reset_terminal_modes_hook = NULL;
10501 terminal->set_terminal_modes_hook = NULL;
10502 terminal->update_begin_hook = x_update_begin;
10503 terminal->update_end_hook = x_update_end;
10504 terminal->set_terminal_window_hook = NULL;
10505 terminal->read_socket_hook = XTread_socket;
10506 terminal->frame_up_to_date_hook = XTframe_up_to_date;
10507 terminal->mouse_position_hook = XTmouse_position;
10508 terminal->frame_rehighlight_hook = XTframe_rehighlight;
10509 terminal->frame_raise_lower_hook = XTframe_raise_lower;
10510 terminal->fullscreen_hook = XTfullscreen_hook;
10511 terminal->set_vertical_scroll_bar_hook = XTset_vertical_scroll_bar;
10512 terminal->condemn_scroll_bars_hook = XTcondemn_scroll_bars;
10513 terminal->redeem_scroll_bar_hook = XTredeem_scroll_bar;
10514 terminal->judge_scroll_bars_hook = XTjudge_scroll_bars;
10516 terminal->delete_frame_hook = x_destroy_window;
10517 terminal->delete_terminal_hook = x_delete_terminal;
10519 terminal->rif = &x_redisplay_interface;
10520 terminal->scroll_region_ok = 1; /* We'll scroll partial frames. */
10521 terminal->char_ins_del_ok = 1;
10522 terminal->line_ins_del_ok = 1; /* We'll just blt 'em. */
10523 terminal->fast_clear_end_of_line = 1; /* X does this well. */
10524 terminal->memory_below_frame = 0; /* We don't remember what scrolls
10525 off the bottom. */
10527 return terminal;
10530 void
10531 x_initialize (void)
10533 baud_rate = 19200;
10535 x_noop_count = 0;
10536 last_tool_bar_item = -1;
10537 any_help_event_p = 0;
10538 ignore_next_mouse_click_timeout = 0;
10540 #ifdef USE_GTK
10541 current_count = -1;
10542 #endif
10544 /* Try to use interrupt input; if we can't, then start polling. */
10545 Fset_input_interrupt_mode (Qt);
10547 #ifdef USE_X_TOOLKIT
10548 XtToolkitInitialize ();
10550 Xt_app_con = XtCreateApplicationContext ();
10552 /* Register a converter from strings to pixels, which uses
10553 Emacs' color allocation infrastructure. */
10554 XtAppSetTypeConverter (Xt_app_con,
10555 XtRString, XtRPixel, cvt_string_to_pixel,
10556 cvt_string_to_pixel_args,
10557 XtNumber (cvt_string_to_pixel_args),
10558 XtCacheByDisplay, cvt_pixel_dtor);
10560 XtAppSetFallbackResources (Xt_app_con, Xt_default_resources);
10561 #endif
10563 #ifdef USE_TOOLKIT_SCROLL_BARS
10564 #ifndef USE_GTK
10565 xaw3d_arrow_scroll = False;
10566 xaw3d_pick_top = True;
10567 #endif
10568 #endif
10570 /* Note that there is no real way portable across R3/R4 to get the
10571 original error handler. */
10572 XSetErrorHandler (x_error_handler);
10573 XSetIOErrorHandler (x_io_error_quitter);
10577 void
10578 syms_of_xterm (void)
10580 x_error_message = NULL;
10582 staticpro (&x_display_name_list);
10583 x_display_name_list = Qnil;
10585 DEFSYM (Qvendor_specific_keysyms, "vendor-specific-keysyms");
10586 DEFSYM (Qlatin_1, "latin-1");
10588 #ifdef USE_GTK
10589 xg_default_icon_file = build_pure_c_string ("icons/hicolor/scalable/apps/emacs.svg");
10590 staticpro (&xg_default_icon_file);
10592 DEFSYM (Qx_gtk_map_stock, "x-gtk-map-stock");
10593 #endif
10595 DEFVAR_BOOL ("x-use-underline-position-properties",
10596 x_use_underline_position_properties,
10597 doc: /* Non-nil means make use of UNDERLINE_POSITION font properties.
10598 A value of nil means ignore them. If you encounter fonts with bogus
10599 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
10600 to 4.1, set this to nil. You can also use `underline-minimum-offset'
10601 to override the font's UNDERLINE_POSITION for small font display
10602 sizes. */);
10603 x_use_underline_position_properties = 1;
10605 DEFVAR_BOOL ("x-underline-at-descent-line",
10606 x_underline_at_descent_line,
10607 doc: /* Non-nil means to draw the underline at the same place as the descent line.
10608 A value of nil means to draw the underline according to the value of the
10609 variable `x-use-underline-position-properties', which is usually at the
10610 baseline level. The default value is nil. */);
10611 x_underline_at_descent_line = 0;
10613 DEFVAR_BOOL ("x-mouse-click-focus-ignore-position",
10614 x_mouse_click_focus_ignore_position,
10615 doc: /* Non-nil means that a mouse click to focus a frame does not move point.
10616 This variable is only used when the window manager requires that you
10617 click on a frame to select it (give it focus). In that case, a value
10618 of nil, means that the selected window and cursor position changes to
10619 reflect the mouse click position, while a non-nil value means that the
10620 selected window or cursor position is preserved. */);
10621 x_mouse_click_focus_ignore_position = 0;
10623 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
10624 doc: /* Which toolkit scroll bars Emacs uses, if any.
10625 A value of nil means Emacs doesn't use toolkit scroll bars.
10626 With the X Window system, the value is a symbol describing the
10627 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
10628 With MS Windows or Nextstep, the value is t. */);
10629 #ifdef USE_TOOLKIT_SCROLL_BARS
10630 #ifdef USE_MOTIF
10631 Vx_toolkit_scroll_bars = intern_c_string ("motif");
10632 #elif defined HAVE_XAW3D
10633 Vx_toolkit_scroll_bars = intern_c_string ("xaw3d");
10634 #elif USE_GTK
10635 Vx_toolkit_scroll_bars = intern_c_string ("gtk");
10636 #else
10637 Vx_toolkit_scroll_bars = intern_c_string ("xaw");
10638 #endif
10639 #else
10640 Vx_toolkit_scroll_bars = Qnil;
10641 #endif
10643 Qmodifier_value = intern_c_string ("modifier-value");
10644 Qalt = intern_c_string ("alt");
10645 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
10646 Qhyper = intern_c_string ("hyper");
10647 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
10648 Qmeta = intern_c_string ("meta");
10649 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
10650 Qsuper = intern_c_string ("super");
10651 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
10653 DEFVAR_LISP ("x-alt-keysym", Vx_alt_keysym,
10654 doc: /* Which keys Emacs uses for the alt modifier.
10655 This should be one of the symbols `alt', `hyper', `meta', `super'.
10656 For example, `alt' means use the Alt_L and Alt_R keysyms. The default
10657 is nil, which is the same as `alt'. */);
10658 Vx_alt_keysym = Qnil;
10660 DEFVAR_LISP ("x-hyper-keysym", Vx_hyper_keysym,
10661 doc: /* Which keys Emacs uses for the hyper modifier.
10662 This should be one of the symbols `alt', `hyper', `meta', `super'.
10663 For example, `hyper' means use the Hyper_L and Hyper_R keysyms. The
10664 default is nil, which is the same as `hyper'. */);
10665 Vx_hyper_keysym = Qnil;
10667 DEFVAR_LISP ("x-meta-keysym", Vx_meta_keysym,
10668 doc: /* Which keys Emacs uses for the meta modifier.
10669 This should be one of the symbols `alt', `hyper', `meta', `super'.
10670 For example, `meta' means use the Meta_L and Meta_R keysyms. The
10671 default is nil, which is the same as `meta'. */);
10672 Vx_meta_keysym = Qnil;
10674 DEFVAR_LISP ("x-super-keysym", Vx_super_keysym,
10675 doc: /* Which keys Emacs uses for the super modifier.
10676 This should be one of the symbols `alt', `hyper', `meta', `super'.
10677 For example, `super' means use the Super_L and Super_R keysyms. The
10678 default is nil, which is the same as `super'. */);
10679 Vx_super_keysym = Qnil;
10681 DEFVAR_LISP ("x-keysym-table", Vx_keysym_table,
10682 doc: /* Hash table of character codes indexed by X keysym codes. */);
10683 Vx_keysym_table = make_hash_table (hashtest_eql, make_number (900),
10684 make_float (DEFAULT_REHASH_SIZE),
10685 make_float (DEFAULT_REHASH_THRESHOLD),
10686 Qnil);