Merge from emacs-24; up to 2013-01-03T02:37:57Z!rgm@gnu.org
[emacs.git] / src / xterm.c
blob446b2cf1e45171182fda306b07dcabd0d5ae2977
1 /* X Communication module for terminals which understand the X protocol.
3 Copyright (C) 1989, 1993-2013 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 /* New display code by Gerd Moellmann <gerd@gnu.org>. */
21 /* Xt features made by Fred Pierresteguy. */
23 #include <config.h>
24 #include <stdio.h>
26 #include "lisp.h"
27 #include "blockinput.h"
28 #include "syssignal.h"
30 /* This may include sys/types.h, and that somehow loses
31 if this is not done before the other system files. */
32 #include "xterm.h"
33 #include <X11/cursorfont.h>
35 /* Load sys/types.h if not already loaded.
36 In some systems loading it twice is suicidal. */
37 #ifndef makedev
38 #include <sys/types.h>
39 #endif /* makedev */
41 #include <sys/ioctl.h>
43 #include "systime.h"
45 #include <fcntl.h>
46 #include <errno.h>
47 #include <sys/stat.h>
48 /* Caused redefinition of DBL_DIG on Netbsd; seems not to be needed. */
49 /* #include <sys/param.h> */
51 #include "charset.h"
52 #include "character.h"
53 #include "coding.h"
54 #include "frame.h"
55 #include "dispextern.h"
56 #include "fontset.h"
57 #include "termhooks.h"
58 #include "termopts.h"
59 #include "termchar.h"
60 #include "emacs-icon.h"
61 #include "disptab.h"
62 #include "buffer.h"
63 #include "window.h"
64 #include "keyboard.h"
65 #include "intervals.h"
66 #include "process.h"
67 #include "atimer.h"
68 #include "keymap.h"
69 #include "font.h"
70 #include "xsettings.h"
71 #include "xgselect.h"
72 #include "sysselect.h"
74 #ifdef USE_X_TOOLKIT
75 #include <X11/Shell.h>
76 #endif
78 #include <unistd.h>
80 #ifdef USE_GTK
81 #include "gtkutil.h"
82 #ifdef HAVE_GTK3
83 #include <X11/Xproto.h>
84 #endif
85 #endif
87 #if defined (USE_LUCID) || defined (USE_MOTIF)
88 #include "../lwlib/xlwmenu.h"
89 #endif
91 #ifdef USE_X_TOOLKIT
92 #if !defined (NO_EDITRES)
93 #define HACK_EDITRES
94 extern void _XEditResCheckMessages (Widget, XtPointer, XEvent *, Boolean *);
95 #endif /* not NO_EDITRES */
97 /* Include toolkit specific headers for the scroll bar widget. */
99 #ifdef USE_TOOLKIT_SCROLL_BARS
100 #if defined USE_MOTIF
101 #include <Xm/Xm.h> /* for LESSTIF_VERSION */
102 #include <Xm/ScrollBar.h>
103 #else /* !USE_MOTIF i.e. use Xaw */
105 #ifdef HAVE_XAW3D
106 #include <X11/Xaw3d/Simple.h>
107 #include <X11/Xaw3d/Scrollbar.h>
108 #include <X11/Xaw3d/ThreeD.h>
109 #else /* !HAVE_XAW3D */
110 #include <X11/Xaw/Simple.h>
111 #include <X11/Xaw/Scrollbar.h>
112 #endif /* !HAVE_XAW3D */
113 #ifndef XtNpickTop
114 #define XtNpickTop "pickTop"
115 #endif /* !XtNpickTop */
116 #endif /* !USE_MOTIF */
117 #endif /* USE_TOOLKIT_SCROLL_BARS */
119 #endif /* USE_X_TOOLKIT */
121 #ifdef USE_X_TOOLKIT
122 #include "widget.h"
123 #ifndef XtNinitialState
124 #define XtNinitialState "initialState"
125 #endif
126 #endif
128 #include "bitmaps/gray.xbm"
130 #ifdef HAVE_XKB
131 #include <X11/XKBlib.h>
132 #endif
134 /* Default to using XIM if available. */
135 #ifdef USE_XIM
136 int use_xim = 1;
137 #else
138 int use_xim = 0; /* configure --without-xim */
139 #endif
141 /* Non-zero means that a HELP_EVENT has been generated since Emacs
142 start. */
144 static bool any_help_event_p;
146 /* This is a chain of structures for all the X displays currently in
147 use. */
149 struct x_display_info *x_display_list;
151 #ifdef USE_X_TOOLKIT
153 /* The application context for Xt use. */
154 XtAppContext Xt_app_con;
155 static String Xt_default_resources[] = {0};
157 /* Non-zero means user is interacting with a toolkit scroll bar. */
158 static bool toolkit_scroll_bar_interaction;
160 #endif /* USE_X_TOOLKIT */
162 /* Non-zero timeout value means ignore next mouse click if it arrives
163 before that timeout elapses (i.e. as part of the same sequence of
164 events resulting from clicking on a frame to select it). */
166 static Time ignore_next_mouse_click_timeout;
168 /* Incremented by XTread_socket whenever it really tries to read
169 events. */
171 static int volatile input_signal_count;
173 /* Used locally within XTread_socket. */
175 static int x_noop_count;
177 static Lisp_Object Qalt, Qhyper, Qmeta, Qsuper, Qmodifier_value;
179 static Lisp_Object Qvendor_specific_keysyms;
180 static Lisp_Object Qlatin_1;
182 #ifdef USE_GTK
183 /* The name of the Emacs icon file. */
184 static Lisp_Object xg_default_icon_file;
186 /* Used in gtkutil.c. */
187 Lisp_Object Qx_gtk_map_stock;
188 #endif
190 /* Some functions take this as char *, not const char *. */
191 static char emacs_class[] = EMACS_CLASS;
193 enum xembed_info
195 XEMBED_MAPPED = 1 << 0
198 enum xembed_message
200 XEMBED_EMBEDDED_NOTIFY = 0,
201 XEMBED_WINDOW_ACTIVATE = 1,
202 XEMBED_WINDOW_DEACTIVATE = 2,
203 XEMBED_REQUEST_FOCUS = 3,
204 XEMBED_FOCUS_IN = 4,
205 XEMBED_FOCUS_OUT = 5,
206 XEMBED_FOCUS_NEXT = 6,
207 XEMBED_FOCUS_PREV = 7,
209 XEMBED_MODALITY_ON = 10,
210 XEMBED_MODALITY_OFF = 11,
211 XEMBED_REGISTER_ACCELERATOR = 12,
212 XEMBED_UNREGISTER_ACCELERATOR = 13,
213 XEMBED_ACTIVATE_ACCELERATOR = 14
216 static bool x_alloc_nearest_color_1 (Display *, Colormap, XColor *);
217 static void x_set_window_size_1 (struct frame *, int, int, int);
218 static void x_raise_frame (struct frame *);
219 static void x_lower_frame (struct frame *);
220 static const XColor *x_color_cells (Display *, int *);
221 static int x_io_error_quitter (Display *);
222 static struct terminal *x_create_terminal (struct x_display_info *);
223 void x_delete_terminal (struct terminal *);
224 static void x_update_end (struct frame *);
225 static void XTframe_up_to_date (struct frame *);
226 static void x_clear_frame (struct frame *);
227 static _Noreturn void x_ins_del_lines (struct frame *, int, int);
228 static void frame_highlight (struct frame *);
229 static void frame_unhighlight (struct frame *);
230 static void x_new_focus_frame (struct x_display_info *, struct frame *);
231 static void x_focus_changed (int, int, struct x_display_info *,
232 struct frame *, struct input_event *);
233 static void XTframe_rehighlight (struct frame *);
234 static void x_frame_rehighlight (struct x_display_info *);
235 static void x_draw_hollow_cursor (struct window *, struct glyph_row *);
236 static void x_draw_bar_cursor (struct window *, struct glyph_row *, int,
237 enum text_cursor_kinds);
239 static void x_clip_to_row (struct window *, struct glyph_row *,
240 enum glyph_row_area, GC);
241 static void x_flush (struct frame *f);
242 static void x_update_begin (struct frame *);
243 static void x_update_window_begin (struct window *);
244 static struct scroll_bar *x_window_to_scroll_bar (Display *, Window);
245 static void x_scroll_bar_report_motion (struct frame **, Lisp_Object *,
246 enum scroll_bar_part *,
247 Lisp_Object *, Lisp_Object *,
248 Time *);
249 static int x_handle_net_wm_state (struct frame *, const XPropertyEvent *);
250 static void x_check_fullscreen (struct frame *);
251 static void x_check_expected_move (struct frame *, int, int);
252 static void x_sync_with_move (struct frame *, int, int, int);
253 static int handle_one_xevent (struct x_display_info *,
254 const XEvent *, int *,
255 struct input_event *);
256 #ifdef USE_GTK
257 static int x_dispatch_event (XEvent *, Display *);
258 #endif
259 /* Don't declare this _Noreturn because we want no
260 interference with debugging failing X calls. */
261 static void x_connection_closed (Display *, const char *);
262 static void x_wm_set_window_state (struct frame *, int);
263 static void x_wm_set_icon_pixmap (struct frame *, ptrdiff_t);
264 static void x_initialize (void);
267 /* Flush display of frame F. */
269 static void
270 x_flush (struct frame *f)
272 eassert (f && FRAME_X_P (f));
273 /* Don't call XFlush when it is not safe to redisplay; the X
274 connection may be broken. */
275 if (!NILP (Vinhibit_redisplay))
276 return;
278 block_input ();
279 XFlush (FRAME_X_DISPLAY (f));
280 unblock_input ();
284 /* Remove calls to XFlush by defining XFlush to an empty replacement.
285 Calls to XFlush should be unnecessary because the X output buffer
286 is flushed automatically as needed by calls to XPending,
287 XNextEvent, or XWindowEvent according to the XFlush man page.
288 XTread_socket calls XPending. Removing XFlush improves
289 performance. */
291 #define XFlush(DISPLAY) (void) 0
294 /***********************************************************************
295 Debugging
296 ***********************************************************************/
298 #if 0
300 /* This is a function useful for recording debugging information about
301 the sequence of occurrences in this file. */
303 struct record
305 char *locus;
306 int type;
309 struct record event_record[100];
311 int event_record_index;
313 void
314 record_event (char *locus, int type)
316 if (event_record_index == sizeof (event_record) / sizeof (struct record))
317 event_record_index = 0;
319 event_record[event_record_index].locus = locus;
320 event_record[event_record_index].type = type;
321 event_record_index++;
324 #endif /* 0 */
328 /* Return the struct x_display_info corresponding to DPY. */
330 struct x_display_info *
331 x_display_info_for_display (Display *dpy)
333 struct x_display_info *dpyinfo;
335 for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
336 if (dpyinfo->display == dpy)
337 return dpyinfo;
339 return 0;
342 static Window
343 x_find_topmost_parent (struct frame *f)
345 struct x_output *x = f->output_data.x;
346 Window win = None, wi = x->parent_desc;
347 Display *dpy = FRAME_X_DISPLAY (f);
349 while (wi != FRAME_DISPLAY_INFO (f)->root_window)
351 Window root;
352 Window *children;
353 unsigned int nchildren;
355 win = wi;
356 XQueryTree (dpy, win, &root, &wi, &children, &nchildren);
357 XFree (children);
360 return win;
363 #define OPAQUE 0xffffffff
365 void
366 x_set_frame_alpha (struct frame *f)
368 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
369 Display *dpy = FRAME_X_DISPLAY (f);
370 Window win = FRAME_OUTER_WINDOW (f);
371 double alpha = 1.0;
372 double alpha_min = 1.0;
373 unsigned long opac;
374 Window parent;
376 if (dpyinfo->x_highlight_frame == f)
377 alpha = f->alpha[0];
378 else
379 alpha = f->alpha[1];
381 if (FLOATP (Vframe_alpha_lower_limit))
382 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
383 else if (INTEGERP (Vframe_alpha_lower_limit))
384 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
386 if (alpha < 0.0)
387 return;
388 else if (alpha > 1.0)
389 alpha = 1.0;
390 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
391 alpha = alpha_min;
393 opac = alpha * OPAQUE;
395 x_catch_errors (dpy);
397 /* If there is a parent from the window manager, put the property there
398 also, to work around broken window managers that fail to do that.
399 Do this unconditionally as this function is called on reparent when
400 alpha has not changed on the frame. */
402 parent = x_find_topmost_parent (f);
403 if (parent != None)
404 XChangeProperty (dpy, parent, dpyinfo->Xatom_net_wm_window_opacity,
405 XA_CARDINAL, 32, PropModeReplace,
406 (unsigned char *) &opac, 1L);
408 /* return unless necessary */
410 unsigned char *data;
411 Atom actual;
412 int rc, format;
413 unsigned long n, left;
415 rc = XGetWindowProperty (dpy, win, dpyinfo->Xatom_net_wm_window_opacity,
416 0L, 1L, False, XA_CARDINAL,
417 &actual, &format, &n, &left,
418 &data);
420 if (rc == Success && actual != None)
422 unsigned long value = *(unsigned long *)data;
423 XFree (data);
424 if (value == opac)
426 x_uncatch_errors ();
427 return;
432 XChangeProperty (dpy, win, dpyinfo->Xatom_net_wm_window_opacity,
433 XA_CARDINAL, 32, PropModeReplace,
434 (unsigned char *) &opac, 1L);
435 x_uncatch_errors ();
439 x_display_pixel_height (struct x_display_info *dpyinfo)
441 return HeightOfScreen (dpyinfo->screen);
445 x_display_pixel_width (struct x_display_info *dpyinfo)
447 return WidthOfScreen (dpyinfo->screen);
451 /***********************************************************************
452 Starting and ending an update
453 ***********************************************************************/
455 /* Start an update of frame F. This function is installed as a hook
456 for update_begin, i.e. it is called when update_begin is called.
457 This function is called prior to calls to x_update_window_begin for
458 each window being updated. Currently, there is nothing to do here
459 because all interesting stuff is done on a window basis. */
461 static void
462 x_update_begin (struct frame *f)
464 /* Nothing to do. */
468 /* Start update of window W. */
470 static void
471 x_update_window_begin (struct window *w)
473 struct frame *f = XFRAME (WINDOW_FRAME (w));
474 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
476 w->output_cursor = w->cursor;
478 block_input ();
480 if (f == hlinfo->mouse_face_mouse_frame)
482 /* Don't do highlighting for mouse motion during the update. */
483 hlinfo->mouse_face_defer = 1;
485 /* If F needs to be redrawn, simply forget about any prior mouse
486 highlighting. */
487 if (FRAME_GARBAGED_P (f))
488 hlinfo->mouse_face_window = Qnil;
491 unblock_input ();
495 /* Draw a vertical window border from (x,y0) to (x,y1) */
497 static void
498 x_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
500 struct frame *f = XFRAME (WINDOW_FRAME (w));
501 struct face *face;
503 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
504 if (face)
505 XSetForeground (FRAME_X_DISPLAY (f), f->output_data.x->normal_gc,
506 face->foreground);
508 XDrawLine (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
509 f->output_data.x->normal_gc, x, y0, x, y1);
512 /* End update of window W.
514 Draw vertical borders between horizontally adjacent windows, and
515 display W's cursor if CURSOR_ON_P is non-zero.
517 MOUSE_FACE_OVERWRITTEN_P non-zero means that some row containing
518 glyphs in mouse-face were overwritten. In that case we have to
519 make sure that the mouse-highlight is properly redrawn.
521 W may be a menu bar pseudo-window in case we don't have X toolkit
522 support. Such windows don't have a cursor, so don't display it
523 here. */
525 static void
526 x_update_window_end (struct window *w, bool cursor_on_p,
527 bool mouse_face_overwritten_p)
529 if (!w->pseudo_window_p)
531 block_input ();
533 if (cursor_on_p)
534 display_and_set_cursor (w, 1,
535 w->output_cursor.hpos, w->output_cursor.vpos,
536 w->output_cursor.x, w->output_cursor.y);
538 if (draw_window_fringes (w, 1))
539 x_draw_vertical_border (w);
541 unblock_input ();
544 /* If a row with mouse-face was overwritten, arrange for
545 XTframe_up_to_date to redisplay the mouse highlight. */
546 if (mouse_face_overwritten_p)
547 reset_mouse_highlight (MOUSE_HL_INFO (XFRAME (w->frame)));
551 /* End update of frame F. This function is installed as a hook in
552 update_end. */
554 static void
555 x_update_end (struct frame *f)
557 /* Mouse highlight may be displayed again. */
558 MOUSE_HL_INFO (f)->mouse_face_defer = 0;
560 #ifndef XFlush
561 block_input ();
562 XFlush (FRAME_X_DISPLAY (f));
563 unblock_input ();
564 #endif
568 /* This function is called from various places in xdisp.c
569 whenever a complete update has been performed. */
571 static void
572 XTframe_up_to_date (struct frame *f)
574 if (FRAME_X_P (f))
575 FRAME_MOUSE_UPDATE (f);
579 /* Draw truncation mark bitmaps, continuation mark bitmaps, overlay
580 arrow bitmaps, or clear the fringes if no bitmaps are required
581 before DESIRED_ROW is made current. This function is called from
582 update_window_line only if it is known that there are differences
583 between bitmaps to be drawn between current row and DESIRED_ROW. */
585 static void
586 x_after_update_window_line (struct window *w, struct glyph_row *desired_row)
588 struct frame *f;
589 int width, height;
591 eassert (w);
593 if (!desired_row->mode_line_p && !w->pseudo_window_p)
594 desired_row->redraw_fringe_bitmaps_p = 1;
596 /* When a window has disappeared, make sure that no rest of
597 full-width rows stays visible in the internal border. Could
598 check here if updated window is the leftmost/rightmost window,
599 but I guess it's not worth doing since vertically split windows
600 are almost never used, internal border is rarely set, and the
601 overhead is very small. */
602 if (windows_or_buffers_changed
603 && desired_row->full_width_p
604 && (f = XFRAME (w->frame),
605 width = FRAME_INTERNAL_BORDER_WIDTH (f),
606 width != 0)
607 && (height = desired_row->visible_height,
608 height > 0))
610 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
612 block_input ();
613 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
614 0, y, width, height);
615 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
616 FRAME_PIXEL_WIDTH (f) - width,
617 y, width, height);
618 unblock_input ();
622 static void
623 x_draw_fringe_bitmap (struct window *w, struct glyph_row *row, struct draw_fringe_bitmap_params *p)
625 struct frame *f = XFRAME (WINDOW_FRAME (w));
626 Display *display = FRAME_X_DISPLAY (f);
627 Window window = FRAME_X_WINDOW (f);
628 GC gc = f->output_data.x->normal_gc;
629 struct face *face = p->face;
631 /* Must clip because of partially visible lines. */
632 x_clip_to_row (w, row, ANY_AREA, gc);
634 if (!p->overlay_p)
636 int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
638 /* In case the same realized face is used for fringes and
639 for something displayed in the text (e.g. face `region' on
640 mono-displays, the fill style may have been changed to
641 FillSolid in x_draw_glyph_string_background. */
642 if (face->stipple)
643 XSetFillStyle (display, face->gc, FillOpaqueStippled);
644 else
645 XSetForeground (display, face->gc, face->background);
647 #ifdef USE_TOOLKIT_SCROLL_BARS
648 /* If the fringe is adjacent to the left (right) scroll bar of a
649 leftmost (rightmost, respectively) window, then extend its
650 background to the gap between the fringe and the bar. */
651 if ((WINDOW_LEFTMOST_P (w)
652 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
653 || (WINDOW_RIGHTMOST_P (w)
654 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w)))
656 int sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
658 if (sb_width > 0)
660 int bar_area_x = WINDOW_SCROLL_BAR_AREA_X (w);
661 int bar_area_width = (WINDOW_CONFIG_SCROLL_BAR_COLS (w)
662 * FRAME_COLUMN_WIDTH (f));
664 if (bx < 0)
666 /* Bitmap fills the fringe. */
667 if (bar_area_x + bar_area_width == p->x)
668 bx = bar_area_x + sb_width;
669 else if (p->x + p->wd == bar_area_x)
670 bx = bar_area_x;
671 if (bx >= 0)
673 int header_line_height = WINDOW_HEADER_LINE_HEIGHT (w);
675 nx = bar_area_width - sb_width;
676 by = WINDOW_TO_FRAME_PIXEL_Y (w, max (header_line_height,
677 row->y));
678 ny = row->visible_height;
681 else
683 if (bar_area_x + bar_area_width == bx)
685 bx = bar_area_x + sb_width;
686 nx += bar_area_width - sb_width;
688 else if (bx + nx == bar_area_x)
689 nx += bar_area_width - sb_width;
693 #endif
694 if (bx >= 0 && nx > 0)
695 XFillRectangle (display, window, face->gc, bx, by, nx, ny);
697 if (!face->stipple)
698 XSetForeground (display, face->gc, face->foreground);
701 if (p->which)
703 char *bits;
704 Pixmap pixmap, clipmask = (Pixmap) 0;
705 int depth = DefaultDepthOfScreen (FRAME_X_SCREEN (f));
706 XGCValues gcv;
708 if (p->wd > 8)
709 bits = (char *) (p->bits + p->dh);
710 else
711 bits = (char *) p->bits + p->dh;
713 /* Draw the bitmap. I believe these small pixmaps can be cached
714 by the server. */
715 pixmap = XCreatePixmapFromBitmapData (display, window, bits, p->wd, p->h,
716 (p->cursor_p
717 ? (p->overlay_p ? face->background
718 : f->output_data.x->cursor_pixel)
719 : face->foreground),
720 face->background, depth);
722 if (p->overlay_p)
724 clipmask = XCreatePixmapFromBitmapData (display,
725 FRAME_DISPLAY_INFO (f)->root_window,
726 bits, p->wd, p->h,
727 1, 0, 1);
728 gcv.clip_mask = clipmask;
729 gcv.clip_x_origin = p->x;
730 gcv.clip_y_origin = p->y;
731 XChangeGC (display, gc, GCClipMask | GCClipXOrigin | GCClipYOrigin, &gcv);
734 XCopyArea (display, pixmap, window, gc, 0, 0,
735 p->wd, p->h, p->x, p->y);
736 XFreePixmap (display, pixmap);
738 if (p->overlay_p)
740 gcv.clip_mask = (Pixmap) 0;
741 XChangeGC (display, gc, GCClipMask, &gcv);
742 XFreePixmap (display, clipmask);
746 XSetClipMask (display, gc, None);
749 /***********************************************************************
750 Glyph display
751 ***********************************************************************/
755 static void x_set_glyph_string_clipping (struct glyph_string *);
756 static void x_set_glyph_string_gc (struct glyph_string *);
757 static void x_draw_glyph_string_foreground (struct glyph_string *);
758 static void x_draw_composite_glyph_string_foreground (struct glyph_string *);
759 static void x_draw_glyph_string_box (struct glyph_string *);
760 static void x_draw_glyph_string (struct glyph_string *);
761 static _Noreturn void x_delete_glyphs (struct frame *, int);
762 static void x_compute_glyph_string_overhangs (struct glyph_string *);
763 static void x_set_cursor_gc (struct glyph_string *);
764 static void x_set_mode_line_face_gc (struct glyph_string *);
765 static void x_set_mouse_face_gc (struct glyph_string *);
766 static bool x_alloc_lighter_color (struct frame *, Display *, Colormap,
767 unsigned long *, double, int);
768 static void x_setup_relief_color (struct frame *, struct relief *,
769 double, int, unsigned long);
770 static void x_setup_relief_colors (struct glyph_string *);
771 static void x_draw_image_glyph_string (struct glyph_string *);
772 static void x_draw_image_relief (struct glyph_string *);
773 static void x_draw_image_foreground (struct glyph_string *);
774 static void x_draw_image_foreground_1 (struct glyph_string *, Pixmap);
775 static void x_clear_glyph_string_rect (struct glyph_string *, int,
776 int, int, int);
777 static void x_draw_relief_rect (struct frame *, int, int, int, int,
778 int, int, int, int, int, int,
779 XRectangle *);
780 static void x_draw_box_rect (struct glyph_string *, int, int, int, int,
781 int, int, int, XRectangle *);
782 static void x_scroll_bar_clear (struct frame *);
784 #ifdef GLYPH_DEBUG
785 static void x_check_font (struct frame *, struct font *);
786 #endif
789 /* Set S->gc to a suitable GC for drawing glyph string S in cursor
790 face. */
792 static void
793 x_set_cursor_gc (struct glyph_string *s)
795 if (s->font == FRAME_FONT (s->f)
796 && s->face->background == FRAME_BACKGROUND_PIXEL (s->f)
797 && s->face->foreground == FRAME_FOREGROUND_PIXEL (s->f)
798 && !s->cmp)
799 s->gc = s->f->output_data.x->cursor_gc;
800 else
802 /* Cursor on non-default face: must merge. */
803 XGCValues xgcv;
804 unsigned long mask;
806 xgcv.background = s->f->output_data.x->cursor_pixel;
807 xgcv.foreground = s->face->background;
809 /* If the glyph would be invisible, try a different foreground. */
810 if (xgcv.foreground == xgcv.background)
811 xgcv.foreground = s->face->foreground;
812 if (xgcv.foreground == xgcv.background)
813 xgcv.foreground = s->f->output_data.x->cursor_foreground_pixel;
814 if (xgcv.foreground == xgcv.background)
815 xgcv.foreground = s->face->foreground;
817 /* Make sure the cursor is distinct from text in this face. */
818 if (xgcv.background == s->face->background
819 && xgcv.foreground == s->face->foreground)
821 xgcv.background = s->face->foreground;
822 xgcv.foreground = s->face->background;
825 IF_DEBUG (x_check_font (s->f, s->font));
826 xgcv.graphics_exposures = False;
827 mask = GCForeground | GCBackground | GCGraphicsExposures;
829 if (FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc)
830 XChangeGC (s->display, FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc,
831 mask, &xgcv);
832 else
833 FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc
834 = XCreateGC (s->display, s->window, mask, &xgcv);
836 s->gc = FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc;
841 /* Set up S->gc of glyph string S for drawing text in mouse face. */
843 static void
844 x_set_mouse_face_gc (struct glyph_string *s)
846 int face_id;
847 struct face *face;
849 /* What face has to be used last for the mouse face? */
850 face_id = MOUSE_HL_INFO (s->f)->mouse_face_face_id;
851 face = FACE_FROM_ID (s->f, face_id);
852 if (face == NULL)
853 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
855 if (s->first_glyph->type == CHAR_GLYPH)
856 face_id = FACE_FOR_CHAR (s->f, face, s->first_glyph->u.ch, -1, Qnil);
857 else
858 face_id = FACE_FOR_CHAR (s->f, face, 0, -1, Qnil);
859 s->face = FACE_FROM_ID (s->f, face_id);
860 PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
862 if (s->font == s->face->font)
863 s->gc = s->face->gc;
864 else
866 /* Otherwise construct scratch_cursor_gc with values from FACE
867 except for FONT. */
868 XGCValues xgcv;
869 unsigned long mask;
871 xgcv.background = s->face->background;
872 xgcv.foreground = s->face->foreground;
873 xgcv.graphics_exposures = False;
874 mask = GCForeground | GCBackground | GCGraphicsExposures;
876 if (FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc)
877 XChangeGC (s->display, FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc,
878 mask, &xgcv);
879 else
880 FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc
881 = XCreateGC (s->display, s->window, mask, &xgcv);
883 s->gc = FRAME_DISPLAY_INFO (s->f)->scratch_cursor_gc;
886 eassert (s->gc != 0);
890 /* Set S->gc of glyph string S to a GC suitable for drawing a mode line.
891 Faces to use in the mode line have already been computed when the
892 matrix was built, so there isn't much to do, here. */
894 static void
895 x_set_mode_line_face_gc (struct glyph_string *s)
897 s->gc = s->face->gc;
901 /* Set S->gc of glyph string S for drawing that glyph string. Set
902 S->stippled_p to a non-zero value if the face of S has a stipple
903 pattern. */
905 static void
906 x_set_glyph_string_gc (struct glyph_string *s)
908 PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
910 if (s->hl == DRAW_NORMAL_TEXT)
912 s->gc = s->face->gc;
913 s->stippled_p = s->face->stipple != 0;
915 else if (s->hl == DRAW_INVERSE_VIDEO)
917 x_set_mode_line_face_gc (s);
918 s->stippled_p = s->face->stipple != 0;
920 else if (s->hl == DRAW_CURSOR)
922 x_set_cursor_gc (s);
923 s->stippled_p = 0;
925 else if (s->hl == DRAW_MOUSE_FACE)
927 x_set_mouse_face_gc (s);
928 s->stippled_p = s->face->stipple != 0;
930 else if (s->hl == DRAW_IMAGE_RAISED
931 || s->hl == DRAW_IMAGE_SUNKEN)
933 s->gc = s->face->gc;
934 s->stippled_p = s->face->stipple != 0;
936 else
938 s->gc = s->face->gc;
939 s->stippled_p = s->face->stipple != 0;
942 /* GC must have been set. */
943 eassert (s->gc != 0);
947 /* Set clipping for output of glyph string S. S may be part of a mode
948 line or menu if we don't have X toolkit support. */
950 static void
951 x_set_glyph_string_clipping (struct glyph_string *s)
953 XRectangle *r = s->clip;
954 int n = get_glyph_string_clip_rects (s, r, 2);
956 if (n > 0)
957 XSetClipRectangles (s->display, s->gc, 0, 0, r, n, Unsorted);
958 s->num_clips = n;
962 /* Set SRC's clipping for output of glyph string DST. This is called
963 when we are drawing DST's left_overhang or right_overhang only in
964 the area of SRC. */
966 static void
967 x_set_glyph_string_clipping_exactly (struct glyph_string *src, struct glyph_string *dst)
969 XRectangle r;
971 r.x = src->x;
972 r.width = src->width;
973 r.y = src->y;
974 r.height = src->height;
975 dst->clip[0] = r;
976 dst->num_clips = 1;
977 XSetClipRectangles (dst->display, dst->gc, 0, 0, &r, 1, Unsorted);
981 /* RIF:
982 Compute left and right overhang of glyph string S. */
984 static void
985 x_compute_glyph_string_overhangs (struct glyph_string *s)
987 if (s->cmp == NULL
988 && (s->first_glyph->type == CHAR_GLYPH
989 || s->first_glyph->type == COMPOSITE_GLYPH))
991 struct font_metrics metrics;
993 if (s->first_glyph->type == CHAR_GLYPH)
995 unsigned *code = alloca (sizeof (unsigned) * s->nchars);
996 struct font *font = s->font;
997 int i;
999 for (i = 0; i < s->nchars; i++)
1000 code[i] = (s->char2b[i].byte1 << 8) | s->char2b[i].byte2;
1001 font->driver->text_extents (font, code, s->nchars, &metrics);
1003 else
1005 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1007 composition_gstring_width (gstring, s->cmp_from, s->cmp_to, &metrics);
1009 s->right_overhang = (metrics.rbearing > metrics.width
1010 ? metrics.rbearing - metrics.width : 0);
1011 s->left_overhang = metrics.lbearing < 0 ? - metrics.lbearing : 0;
1013 else if (s->cmp)
1015 s->right_overhang = s->cmp->rbearing - s->cmp->pixel_width;
1016 s->left_overhang = - s->cmp->lbearing;
1021 /* Fill rectangle X, Y, W, H with background color of glyph string S. */
1023 static void
1024 x_clear_glyph_string_rect (struct glyph_string *s, int x, int y, int w, int h)
1026 XGCValues xgcv;
1027 XGetGCValues (s->display, s->gc, GCForeground | GCBackground, &xgcv);
1028 XSetForeground (s->display, s->gc, xgcv.background);
1029 XFillRectangle (s->display, s->window, s->gc, x, y, w, h);
1030 XSetForeground (s->display, s->gc, xgcv.foreground);
1034 /* Draw the background of glyph_string S. If S->background_filled_p
1035 is non-zero don't draw it. FORCE_P non-zero means draw the
1036 background even if it wouldn't be drawn normally. This is used
1037 when a string preceding S draws into the background of S, or S
1038 contains the first component of a composition. */
1040 static void
1041 x_draw_glyph_string_background (struct glyph_string *s, bool force_p)
1043 /* Nothing to do if background has already been drawn or if it
1044 shouldn't be drawn in the first place. */
1045 if (!s->background_filled_p)
1047 int box_line_width = max (s->face->box_line_width, 0);
1049 if (s->stippled_p)
1051 /* Fill background with a stipple pattern. */
1052 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
1053 XFillRectangle (s->display, s->window, s->gc, s->x,
1054 s->y + box_line_width,
1055 s->background_width,
1056 s->height - 2 * box_line_width);
1057 XSetFillStyle (s->display, s->gc, FillSolid);
1058 s->background_filled_p = 1;
1060 else if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
1061 || s->font_not_found_p
1062 || s->extends_to_end_of_line_p
1063 || force_p)
1065 x_clear_glyph_string_rect (s, s->x, s->y + box_line_width,
1066 s->background_width,
1067 s->height - 2 * box_line_width);
1068 s->background_filled_p = 1;
1074 /* Draw the foreground of glyph string S. */
1076 static void
1077 x_draw_glyph_string_foreground (struct glyph_string *s)
1079 int i, x;
1081 /* If first glyph of S has a left box line, start drawing the text
1082 of S to the right of that box line. */
1083 if (s->face->box != FACE_NO_BOX
1084 && s->first_glyph->left_box_line_p)
1085 x = s->x + eabs (s->face->box_line_width);
1086 else
1087 x = s->x;
1089 /* Draw characters of S as rectangles if S's font could not be
1090 loaded. */
1091 if (s->font_not_found_p)
1093 for (i = 0; i < s->nchars; ++i)
1095 struct glyph *g = s->first_glyph + i;
1096 XDrawRectangle (s->display, s->window,
1097 s->gc, x, s->y, g->pixel_width - 1,
1098 s->height - 1);
1099 x += g->pixel_width;
1102 else
1104 struct font *font = s->font;
1105 int boff = font->baseline_offset;
1106 int y;
1108 if (font->vertical_centering)
1109 boff = VCENTER_BASELINE_OFFSET (font, s->f) - boff;
1111 y = s->ybase - boff;
1112 if (s->for_overlaps
1113 || (s->background_filled_p && s->hl != DRAW_CURSOR))
1114 font->driver->draw (s, 0, s->nchars, x, y, 0);
1115 else
1116 font->driver->draw (s, 0, s->nchars, x, y, 1);
1117 if (s->face->overstrike)
1118 font->driver->draw (s, 0, s->nchars, x + 1, y, 0);
1122 /* Draw the foreground of composite glyph string S. */
1124 static void
1125 x_draw_composite_glyph_string_foreground (struct glyph_string *s)
1127 int i, j, x;
1128 struct font *font = s->font;
1130 /* If first glyph of S has a left box line, start drawing the text
1131 of S to the right of that box line. */
1132 if (s->face && s->face->box != FACE_NO_BOX
1133 && s->first_glyph->left_box_line_p)
1134 x = s->x + eabs (s->face->box_line_width);
1135 else
1136 x = s->x;
1138 /* S is a glyph string for a composition. S->cmp_from is the index
1139 of the first character drawn for glyphs of this composition.
1140 S->cmp_from == 0 means we are drawing the very first character of
1141 this composition. */
1143 /* Draw a rectangle for the composition if the font for the very
1144 first character of the composition could not be loaded. */
1145 if (s->font_not_found_p)
1147 if (s->cmp_from == 0)
1148 XDrawRectangle (s->display, s->window, s->gc, x, s->y,
1149 s->width - 1, s->height - 1);
1151 else if (! s->first_glyph->u.cmp.automatic)
1153 int y = s->ybase;
1155 for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
1156 /* TAB in a composition means display glyphs with padding
1157 space on the left or right. */
1158 if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
1160 int xx = x + s->cmp->offsets[j * 2];
1161 int yy = y - s->cmp->offsets[j * 2 + 1];
1163 font->driver->draw (s, j, j + 1, xx, yy, 0);
1164 if (s->face->overstrike)
1165 font->driver->draw (s, j, j + 1, xx + 1, yy, 0);
1168 else
1170 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1171 Lisp_Object glyph;
1172 int y = s->ybase;
1173 int width = 0;
1175 for (i = j = s->cmp_from; i < s->cmp_to; i++)
1177 glyph = LGSTRING_GLYPH (gstring, i);
1178 if (NILP (LGLYPH_ADJUSTMENT (glyph)))
1179 width += LGLYPH_WIDTH (glyph);
1180 else
1182 int xoff, yoff, wadjust;
1184 if (j < i)
1186 font->driver->draw (s, j, i, x, y, 0);
1187 if (s->face->overstrike)
1188 font->driver->draw (s, j, i, x + 1, y, 0);
1189 x += width;
1191 xoff = LGLYPH_XOFF (glyph);
1192 yoff = LGLYPH_YOFF (glyph);
1193 wadjust = LGLYPH_WADJUST (glyph);
1194 font->driver->draw (s, i, i + 1, x + xoff, y + yoff, 0);
1195 if (s->face->overstrike)
1196 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff, 0);
1197 x += wadjust;
1198 j = i + 1;
1199 width = 0;
1202 if (j < i)
1204 font->driver->draw (s, j, i, x, y, 0);
1205 if (s->face->overstrike)
1206 font->driver->draw (s, j, i, x + 1, y, 0);
1212 /* Draw the foreground of glyph string S for glyphless characters. */
1214 static void
1215 x_draw_glyphless_glyph_string_foreground (struct glyph_string *s)
1217 struct glyph *glyph = s->first_glyph;
1218 XChar2b char2b[8];
1219 int x, i, j;
1221 /* If first glyph of S has a left box line, start drawing the text
1222 of S to the right of that box line. */
1223 if (s->face && s->face->box != FACE_NO_BOX
1224 && s->first_glyph->left_box_line_p)
1225 x = s->x + eabs (s->face->box_line_width);
1226 else
1227 x = s->x;
1229 s->char2b = char2b;
1231 for (i = 0; i < s->nchars; i++, glyph++)
1233 char buf[7], *str = NULL;
1234 int len = glyph->u.glyphless.len;
1236 if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_ACRONYM)
1238 if (len > 0
1239 && CHAR_TABLE_P (Vglyphless_char_display)
1240 && (CHAR_TABLE_EXTRA_SLOTS (XCHAR_TABLE (Vglyphless_char_display))
1241 >= 1))
1243 Lisp_Object acronym
1244 = (! glyph->u.glyphless.for_no_font
1245 ? CHAR_TABLE_REF (Vglyphless_char_display,
1246 glyph->u.glyphless.ch)
1247 : XCHAR_TABLE (Vglyphless_char_display)->extras[0]);
1248 if (STRINGP (acronym))
1249 str = SSDATA (acronym);
1252 else if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_HEX_CODE)
1254 sprintf (buf, "%0*X",
1255 glyph->u.glyphless.ch < 0x10000 ? 4 : 6,
1256 glyph->u.glyphless.ch);
1257 str = buf;
1260 if (str)
1262 int upper_len = (len + 1) / 2;
1263 unsigned code;
1265 /* It is assured that all LEN characters in STR is ASCII. */
1266 for (j = 0; j < len; j++)
1268 code = s->font->driver->encode_char (s->font, str[j]);
1269 STORE_XCHAR2B (char2b + j, code >> 8, code & 0xFF);
1271 s->font->driver->draw (s, 0, upper_len,
1272 x + glyph->slice.glyphless.upper_xoff,
1273 s->ybase + glyph->slice.glyphless.upper_yoff,
1275 s->font->driver->draw (s, upper_len, len,
1276 x + glyph->slice.glyphless.lower_xoff,
1277 s->ybase + glyph->slice.glyphless.lower_yoff,
1280 if (glyph->u.glyphless.method != GLYPHLESS_DISPLAY_THIN_SPACE)
1281 XDrawRectangle (s->display, s->window, s->gc,
1282 x, s->ybase - glyph->ascent,
1283 glyph->pixel_width - 1,
1284 glyph->ascent + glyph->descent - 1);
1285 x += glyph->pixel_width;
1289 #ifdef USE_X_TOOLKIT
1291 #ifdef USE_LUCID
1293 /* Return the frame on which widget WIDGET is used.. Abort if frame
1294 cannot be determined. */
1296 static struct frame *
1297 x_frame_of_widget (Widget widget)
1299 struct x_display_info *dpyinfo;
1300 Lisp_Object tail, frame;
1301 struct frame *f;
1303 dpyinfo = x_display_info_for_display (XtDisplay (widget));
1305 /* Find the top-level shell of the widget. Note that this function
1306 can be called when the widget is not yet realized, so XtWindow
1307 (widget) == 0. That's the reason we can't simply use
1308 x_any_window_to_frame. */
1309 while (!XtIsTopLevelShell (widget))
1310 widget = XtParent (widget);
1312 /* Look for a frame with that top-level widget. Allocate the color
1313 on that frame to get the right gamma correction value. */
1314 FOR_EACH_FRAME (tail, frame)
1316 f = XFRAME (frame);
1317 if (FRAME_X_P (f)
1318 && f->output_data.nothing != 1
1319 && FRAME_DISPLAY_INFO (f) == dpyinfo
1320 && f->output_data.x->widget == widget)
1321 return f;
1323 emacs_abort ();
1326 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
1327 or DELTA. Try a color with RGB values multiplied by FACTOR first.
1328 If this produces the same color as PIXEL, try a color where all RGB
1329 values have DELTA added. Return the allocated color in *PIXEL.
1330 DISPLAY is the X display, CMAP is the colormap to operate on.
1331 Value is true if successful. */
1333 bool
1334 x_alloc_lighter_color_for_widget (Widget widget, Display *display, Colormap cmap,
1335 unsigned long *pixel, double factor, int delta)
1337 struct frame *f = x_frame_of_widget (widget);
1338 return x_alloc_lighter_color (f, display, cmap, pixel, factor, delta);
1341 #endif /* USE_LUCID */
1344 /* Structure specifying which arguments should be passed by Xt to
1345 cvt_string_to_pixel. We want the widget's screen and colormap. */
1347 static XtConvertArgRec cvt_string_to_pixel_args[] =
1349 {XtWidgetBaseOffset, (XtPointer) XtOffset (Widget, core.screen),
1350 sizeof (Screen *)},
1351 {XtWidgetBaseOffset, (XtPointer) XtOffset (Widget, core.colormap),
1352 sizeof (Colormap)}
1356 /* The address of this variable is returned by
1357 cvt_string_to_pixel. */
1359 static Pixel cvt_string_to_pixel_value;
1362 /* Convert a color name to a pixel color.
1364 DPY is the display we are working on.
1366 ARGS is an array of *NARGS XrmValue structures holding additional
1367 information about the widget for which the conversion takes place.
1368 The contents of this array are determined by the specification
1369 in cvt_string_to_pixel_args.
1371 FROM is a pointer to an XrmValue which points to the color name to
1372 convert. TO is an XrmValue in which to return the pixel color.
1374 CLOSURE_RET is a pointer to user-data, in which we record if
1375 we allocated the color or not.
1377 Value is True if successful, False otherwise. */
1379 static Boolean
1380 cvt_string_to_pixel (Display *dpy, XrmValue *args, Cardinal *nargs,
1381 XrmValue *from, XrmValue *to,
1382 XtPointer *closure_ret)
1384 Screen *screen;
1385 Colormap cmap;
1386 Pixel pixel;
1387 String color_name;
1388 XColor color;
1390 if (*nargs != 2)
1392 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
1393 "wrongParameters", "cvt_string_to_pixel",
1394 "XtToolkitError",
1395 "Screen and colormap args required", NULL, NULL);
1396 return False;
1399 screen = *(Screen **) args[0].addr;
1400 cmap = *(Colormap *) args[1].addr;
1401 color_name = (String) from->addr;
1403 if (strcmp (color_name, XtDefaultBackground) == 0)
1405 *closure_ret = (XtPointer) False;
1406 pixel = WhitePixelOfScreen (screen);
1408 else if (strcmp (color_name, XtDefaultForeground) == 0)
1410 *closure_ret = (XtPointer) False;
1411 pixel = BlackPixelOfScreen (screen);
1413 else if (XParseColor (dpy, cmap, color_name, &color)
1414 && x_alloc_nearest_color_1 (dpy, cmap, &color))
1416 pixel = color.pixel;
1417 *closure_ret = (XtPointer) True;
1419 else
1421 String params[1];
1422 Cardinal nparams = 1;
1424 params[0] = color_name;
1425 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
1426 "badValue", "cvt_string_to_pixel",
1427 "XtToolkitError", "Invalid color `%s'",
1428 params, &nparams);
1429 return False;
1432 if (to->addr != NULL)
1434 if (to->size < sizeof (Pixel))
1436 to->size = sizeof (Pixel);
1437 return False;
1440 *(Pixel *) to->addr = pixel;
1442 else
1444 cvt_string_to_pixel_value = pixel;
1445 to->addr = (XtPointer) &cvt_string_to_pixel_value;
1448 to->size = sizeof (Pixel);
1449 return True;
1453 /* Free a pixel color which was previously allocated via
1454 cvt_string_to_pixel. This is registered as the destructor
1455 for this type of resource via XtSetTypeConverter.
1457 APP is the application context in which we work.
1459 TO is a pointer to an XrmValue holding the color to free.
1460 CLOSURE is the value we stored in CLOSURE_RET for this color
1461 in cvt_string_to_pixel.
1463 ARGS and NARGS are like for cvt_string_to_pixel. */
1465 static void
1466 cvt_pixel_dtor (XtAppContext app, XrmValuePtr to, XtPointer closure, XrmValuePtr args,
1467 Cardinal *nargs)
1469 if (*nargs != 2)
1471 XtAppWarningMsg (app, "wrongParameters", "cvt_pixel_dtor",
1472 "XtToolkitError",
1473 "Screen and colormap arguments required",
1474 NULL, NULL);
1476 else if (closure != NULL)
1478 /* We did allocate the pixel, so free it. */
1479 Screen *screen = *(Screen **) args[0].addr;
1480 Colormap cmap = *(Colormap *) args[1].addr;
1481 x_free_dpy_colors (DisplayOfScreen (screen), screen, cmap,
1482 (Pixel *) to->addr, 1);
1487 #endif /* USE_X_TOOLKIT */
1490 /* Value is an array of XColor structures for the contents of the
1491 color map of display DPY. Set *NCELLS to the size of the array.
1492 Note that this probably shouldn't be called for large color maps,
1493 say a 24-bit TrueColor map. */
1495 static const XColor *
1496 x_color_cells (Display *dpy, int *ncells)
1498 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
1500 if (dpyinfo->color_cells == NULL)
1502 Screen *screen = dpyinfo->screen;
1503 int ncolor_cells = XDisplayCells (dpy, XScreenNumberOfScreen (screen));
1504 int i;
1506 dpyinfo->color_cells = xnmalloc (ncolor_cells,
1507 sizeof *dpyinfo->color_cells);
1508 dpyinfo->ncolor_cells = ncolor_cells;
1510 for (i = 0; i < ncolor_cells; ++i)
1511 dpyinfo->color_cells[i].pixel = i;
1513 XQueryColors (dpy, dpyinfo->cmap,
1514 dpyinfo->color_cells, ncolor_cells);
1517 *ncells = dpyinfo->ncolor_cells;
1518 return dpyinfo->color_cells;
1522 /* On frame F, translate pixel colors to RGB values for the NCOLORS
1523 colors in COLORS. Use cached information, if available. */
1525 void
1526 x_query_colors (struct frame *f, XColor *colors, int ncolors)
1528 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1530 if (dpyinfo->color_cells)
1532 int i;
1533 for (i = 0; i < ncolors; ++i)
1535 unsigned long pixel = colors[i].pixel;
1536 eassert (pixel < dpyinfo->ncolor_cells);
1537 eassert (dpyinfo->color_cells[pixel].pixel == pixel);
1538 colors[i] = dpyinfo->color_cells[pixel];
1541 else
1542 XQueryColors (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), colors, ncolors);
1546 /* On frame F, translate pixel color to RGB values for the color in
1547 COLOR. Use cached information, if available. */
1549 void
1550 x_query_color (struct frame *f, XColor *color)
1552 x_query_colors (f, color, 1);
1556 /* Allocate the color COLOR->pixel on DISPLAY, colormap CMAP. If an
1557 exact match can't be allocated, try the nearest color available.
1558 Value is true if successful. Set *COLOR to the color
1559 allocated. */
1561 static bool
1562 x_alloc_nearest_color_1 (Display *dpy, Colormap cmap, XColor *color)
1564 bool rc;
1566 rc = XAllocColor (dpy, cmap, color) != 0;
1567 if (rc == 0)
1569 /* If we got to this point, the colormap is full, so we're going
1570 to try to get the next closest color. The algorithm used is
1571 a least-squares matching, which is what X uses for closest
1572 color matching with StaticColor visuals. */
1573 int nearest, i;
1574 int max_color_delta = 255;
1575 int max_delta = 3 * max_color_delta;
1576 int nearest_delta = max_delta + 1;
1577 int ncells;
1578 const XColor *cells = x_color_cells (dpy, &ncells);
1580 for (nearest = i = 0; i < ncells; ++i)
1582 int dred = (color->red >> 8) - (cells[i].red >> 8);
1583 int dgreen = (color->green >> 8) - (cells[i].green >> 8);
1584 int dblue = (color->blue >> 8) - (cells[i].blue >> 8);
1585 int delta = dred * dred + dgreen * dgreen + dblue * dblue;
1587 if (delta < nearest_delta)
1589 nearest = i;
1590 nearest_delta = delta;
1594 color->red = cells[nearest].red;
1595 color->green = cells[nearest].green;
1596 color->blue = cells[nearest].blue;
1597 rc = XAllocColor (dpy, cmap, color) != 0;
1599 else
1601 /* If allocation succeeded, and the allocated pixel color is not
1602 equal to a cached pixel color recorded earlier, there was a
1603 change in the colormap, so clear the color cache. */
1604 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
1605 XColor *cached_color;
1607 if (dpyinfo->color_cells
1608 && (cached_color = &dpyinfo->color_cells[color->pixel],
1609 (cached_color->red != color->red
1610 || cached_color->blue != color->blue
1611 || cached_color->green != color->green)))
1613 xfree (dpyinfo->color_cells);
1614 dpyinfo->color_cells = NULL;
1615 dpyinfo->ncolor_cells = 0;
1619 #ifdef DEBUG_X_COLORS
1620 if (rc)
1621 register_color (color->pixel);
1622 #endif /* DEBUG_X_COLORS */
1624 return rc;
1628 /* Allocate the color COLOR->pixel on frame F, colormap CMAP. If an
1629 exact match can't be allocated, try the nearest color available.
1630 Value is true if successful. Set *COLOR to the color
1631 allocated. */
1633 bool
1634 x_alloc_nearest_color (struct frame *f, Colormap cmap, XColor *color)
1636 gamma_correct (f, color);
1637 return x_alloc_nearest_color_1 (FRAME_X_DISPLAY (f), cmap, color);
1641 /* Allocate color PIXEL on frame F. PIXEL must already be allocated.
1642 It's necessary to do this instead of just using PIXEL directly to
1643 get color reference counts right. */
1645 unsigned long
1646 x_copy_color (struct frame *f, unsigned long pixel)
1648 XColor color;
1650 color.pixel = pixel;
1651 block_input ();
1652 x_query_color (f, &color);
1653 XAllocColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &color);
1654 unblock_input ();
1655 #ifdef DEBUG_X_COLORS
1656 register_color (pixel);
1657 #endif
1658 return color.pixel;
1662 /* Brightness beyond which a color won't have its highlight brightness
1663 boosted.
1665 Nominally, highlight colors for `3d' faces are calculated by
1666 brightening an object's color by a constant scale factor, but this
1667 doesn't yield good results for dark colors, so for colors who's
1668 brightness is less than this value (on a scale of 0-65535) have an
1669 use an additional additive factor.
1671 The value here is set so that the default menu-bar/mode-line color
1672 (grey75) will not have its highlights changed at all. */
1673 #define HIGHLIGHT_COLOR_DARK_BOOST_LIMIT 48000
1676 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
1677 or DELTA. Try a color with RGB values multiplied by FACTOR first.
1678 If this produces the same color as PIXEL, try a color where all RGB
1679 values have DELTA added. Return the allocated color in *PIXEL.
1680 DISPLAY is the X display, CMAP is the colormap to operate on.
1681 Value is non-zero if successful. */
1683 static bool
1684 x_alloc_lighter_color (struct frame *f, Display *display, Colormap cmap,
1685 unsigned long *pixel, double factor, int delta)
1687 XColor color, new;
1688 long bright;
1689 bool success_p;
1691 /* Get RGB color values. */
1692 color.pixel = *pixel;
1693 x_query_color (f, &color);
1695 /* Change RGB values by specified FACTOR. Avoid overflow! */
1696 eassert (factor >= 0);
1697 new.red = min (0xffff, factor * color.red);
1698 new.green = min (0xffff, factor * color.green);
1699 new.blue = min (0xffff, factor * color.blue);
1701 /* Calculate brightness of COLOR. */
1702 bright = (2 * color.red + 3 * color.green + color.blue) / 6;
1704 /* We only boost colors that are darker than
1705 HIGHLIGHT_COLOR_DARK_BOOST_LIMIT. */
1706 if (bright < HIGHLIGHT_COLOR_DARK_BOOST_LIMIT)
1707 /* Make an additive adjustment to NEW, because it's dark enough so
1708 that scaling by FACTOR alone isn't enough. */
1710 /* How far below the limit this color is (0 - 1, 1 being darker). */
1711 double dimness = 1 - (double)bright / HIGHLIGHT_COLOR_DARK_BOOST_LIMIT;
1712 /* The additive adjustment. */
1713 int min_delta = delta * dimness * factor / 2;
1715 if (factor < 1)
1717 new.red = max (0, new.red - min_delta);
1718 new.green = max (0, new.green - min_delta);
1719 new.blue = max (0, new.blue - min_delta);
1721 else
1723 new.red = min (0xffff, min_delta + new.red);
1724 new.green = min (0xffff, min_delta + new.green);
1725 new.blue = min (0xffff, min_delta + new.blue);
1729 /* Try to allocate the color. */
1730 success_p = x_alloc_nearest_color (f, cmap, &new);
1731 if (success_p)
1733 if (new.pixel == *pixel)
1735 /* If we end up with the same color as before, try adding
1736 delta to the RGB values. */
1737 x_free_colors (f, &new.pixel, 1);
1739 new.red = min (0xffff, delta + color.red);
1740 new.green = min (0xffff, delta + color.green);
1741 new.blue = min (0xffff, delta + color.blue);
1742 success_p = x_alloc_nearest_color (f, cmap, &new);
1744 else
1745 success_p = 1;
1746 *pixel = new.pixel;
1749 return success_p;
1753 /* Set up the foreground color for drawing relief lines of glyph
1754 string S. RELIEF is a pointer to a struct relief containing the GC
1755 with which lines will be drawn. Use a color that is FACTOR or
1756 DELTA lighter or darker than the relief's background which is found
1757 in S->f->output_data.x->relief_background. If such a color cannot
1758 be allocated, use DEFAULT_PIXEL, instead. */
1760 static void
1761 x_setup_relief_color (struct frame *f, struct relief *relief, double factor,
1762 int delta, unsigned long default_pixel)
1764 XGCValues xgcv;
1765 struct x_output *di = f->output_data.x;
1766 unsigned long mask = GCForeground | GCLineWidth | GCGraphicsExposures;
1767 unsigned long pixel;
1768 unsigned long background = di->relief_background;
1769 Colormap cmap = FRAME_X_COLORMAP (f);
1770 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1771 Display *dpy = FRAME_X_DISPLAY (f);
1773 xgcv.graphics_exposures = False;
1774 xgcv.line_width = 1;
1776 /* Free previously allocated color. The color cell will be reused
1777 when it has been freed as many times as it was allocated, so this
1778 doesn't affect faces using the same colors. */
1779 if (relief->gc && relief->pixel != -1)
1781 x_free_colors (f, &relief->pixel, 1);
1782 relief->pixel = -1;
1785 /* Allocate new color. */
1786 xgcv.foreground = default_pixel;
1787 pixel = background;
1788 if (dpyinfo->n_planes != 1
1789 && x_alloc_lighter_color (f, dpy, cmap, &pixel, factor, delta))
1790 xgcv.foreground = relief->pixel = pixel;
1792 if (relief->gc == 0)
1794 xgcv.stipple = dpyinfo->gray;
1795 mask |= GCStipple;
1796 relief->gc = XCreateGC (dpy, FRAME_X_WINDOW (f), mask, &xgcv);
1798 else
1799 XChangeGC (dpy, relief->gc, mask, &xgcv);
1803 /* Set up colors for the relief lines around glyph string S. */
1805 static void
1806 x_setup_relief_colors (struct glyph_string *s)
1808 struct x_output *di = s->f->output_data.x;
1809 unsigned long color;
1811 if (s->face->use_box_color_for_shadows_p)
1812 color = s->face->box_color;
1813 else if (s->first_glyph->type == IMAGE_GLYPH
1814 && s->img->pixmap
1815 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
1816 color = IMAGE_BACKGROUND (s->img, s->f, 0);
1817 else
1819 XGCValues xgcv;
1821 /* Get the background color of the face. */
1822 XGetGCValues (s->display, s->gc, GCBackground, &xgcv);
1823 color = xgcv.background;
1826 if (di->white_relief.gc == 0
1827 || color != di->relief_background)
1829 di->relief_background = color;
1830 x_setup_relief_color (s->f, &di->white_relief, 1.2, 0x8000,
1831 WHITE_PIX_DEFAULT (s->f));
1832 x_setup_relief_color (s->f, &di->black_relief, 0.6, 0x4000,
1833 BLACK_PIX_DEFAULT (s->f));
1838 /* Draw a relief on frame F inside the rectangle given by LEFT_X,
1839 TOP_Y, RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the relief
1840 to draw, it must be >= 0. RAISED_P non-zero means draw a raised
1841 relief. LEFT_P non-zero means draw a relief on the left side of
1842 the rectangle. RIGHT_P non-zero means draw a relief on the right
1843 side of the rectangle. CLIP_RECT is the clipping rectangle to use
1844 when drawing. */
1846 static void
1847 x_draw_relief_rect (struct frame *f,
1848 int left_x, int top_y, int right_x, int bottom_y, int width,
1849 int raised_p, int top_p, int bot_p, int left_p, int right_p,
1850 XRectangle *clip_rect)
1852 Display *dpy = FRAME_X_DISPLAY (f);
1853 Window window = FRAME_X_WINDOW (f);
1854 int i;
1855 GC gc;
1857 if (raised_p)
1858 gc = f->output_data.x->white_relief.gc;
1859 else
1860 gc = f->output_data.x->black_relief.gc;
1861 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
1863 /* This code is more complicated than it has to be, because of two
1864 minor hacks to make the boxes look nicer: (i) if width > 1, draw
1865 the outermost line using the black relief. (ii) Omit the four
1866 corner pixels. */
1868 /* Top. */
1869 if (top_p)
1871 if (width == 1)
1872 XDrawLine (dpy, window, gc,
1873 left_x + (left_p ? 1 : 0), top_y,
1874 right_x + (right_p ? 0 : 1), top_y);
1876 for (i = 1; i < width; ++i)
1877 XDrawLine (dpy, window, gc,
1878 left_x + i * left_p, top_y + i,
1879 right_x + 1 - i * right_p, top_y + i);
1882 /* Left. */
1883 if (left_p)
1885 if (width == 1)
1886 XDrawLine (dpy, window, gc, left_x, top_y + 1, left_x, bottom_y);
1888 XClearArea (dpy, window, left_x, top_y, 1, 1, False);
1889 XClearArea (dpy, window, left_x, bottom_y, 1, 1, False);
1891 for (i = (width > 1 ? 1 : 0); i < width; ++i)
1892 XDrawLine (dpy, window, gc,
1893 left_x + i, top_y + (i + 1) * top_p,
1894 left_x + i, bottom_y + 1 - (i + 1) * bot_p);
1897 XSetClipMask (dpy, gc, None);
1898 if (raised_p)
1899 gc = f->output_data.x->black_relief.gc;
1900 else
1901 gc = f->output_data.x->white_relief.gc;
1902 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
1904 if (width > 1)
1906 /* Outermost top line. */
1907 if (top_p)
1908 XDrawLine (dpy, window, gc,
1909 left_x + (left_p ? 1 : 0), top_y,
1910 right_x + (right_p ? 0 : 1), top_y);
1912 /* Outermost left line. */
1913 if (left_p)
1914 XDrawLine (dpy, window, gc, left_x, top_y + 1, left_x, bottom_y);
1917 /* Bottom. */
1918 if (bot_p)
1920 XDrawLine (dpy, window, gc,
1921 left_x + (left_p ? 1 : 0), bottom_y,
1922 right_x + (right_p ? 0 : 1), bottom_y);
1923 for (i = 1; i < width; ++i)
1924 XDrawLine (dpy, window, gc,
1925 left_x + i * left_p, bottom_y - i,
1926 right_x + 1 - i * right_p, bottom_y - i);
1929 /* Right. */
1930 if (right_p)
1932 XClearArea (dpy, window, right_x, top_y, 1, 1, False);
1933 XClearArea (dpy, window, right_x, bottom_y, 1, 1, False);
1934 for (i = 0; i < width; ++i)
1935 XDrawLine (dpy, window, gc,
1936 right_x - i, top_y + (i + 1) * top_p,
1937 right_x - i, bottom_y + 1 - (i + 1) * bot_p);
1940 XSetClipMask (dpy, gc, None);
1944 /* Draw a box on frame F inside the rectangle given by LEFT_X, TOP_Y,
1945 RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the lines to
1946 draw, it must be >= 0. LEFT_P non-zero means draw a line on the
1947 left side of the rectangle. RIGHT_P non-zero means draw a line
1948 on the right side of the rectangle. CLIP_RECT is the clipping
1949 rectangle to use when drawing. */
1951 static void
1952 x_draw_box_rect (struct glyph_string *s,
1953 int left_x, int top_y, int right_x, int bottom_y, int width,
1954 int left_p, int right_p, XRectangle *clip_rect)
1956 XGCValues xgcv;
1958 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
1959 XSetForeground (s->display, s->gc, s->face->box_color);
1960 XSetClipRectangles (s->display, s->gc, 0, 0, clip_rect, 1, Unsorted);
1962 /* Top. */
1963 XFillRectangle (s->display, s->window, s->gc,
1964 left_x, top_y, right_x - left_x + 1, width);
1966 /* Left. */
1967 if (left_p)
1968 XFillRectangle (s->display, s->window, s->gc,
1969 left_x, top_y, width, bottom_y - top_y + 1);
1971 /* Bottom. */
1972 XFillRectangle (s->display, s->window, s->gc,
1973 left_x, bottom_y - width + 1, right_x - left_x + 1, width);
1975 /* Right. */
1976 if (right_p)
1977 XFillRectangle (s->display, s->window, s->gc,
1978 right_x - width + 1, top_y, width, bottom_y - top_y + 1);
1980 XSetForeground (s->display, s->gc, xgcv.foreground);
1981 XSetClipMask (s->display, s->gc, None);
1985 /* Draw a box around glyph string S. */
1987 static void
1988 x_draw_glyph_string_box (struct glyph_string *s)
1990 int width, left_x, right_x, top_y, bottom_y, last_x, raised_p;
1991 int left_p, right_p;
1992 struct glyph *last_glyph;
1993 XRectangle clip_rect;
1995 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
1996 ? WINDOW_RIGHT_EDGE_X (s->w)
1997 : window_box_right (s->w, s->area));
1999 /* The glyph that may have a right box line. */
2000 last_glyph = (s->cmp || s->img
2001 ? s->first_glyph
2002 : s->first_glyph + s->nchars - 1);
2004 width = eabs (s->face->box_line_width);
2005 raised_p = s->face->box == FACE_RAISED_BOX;
2006 left_x = s->x;
2007 right_x = (s->row->full_width_p && s->extends_to_end_of_line_p
2008 ? last_x - 1
2009 : min (last_x, s->x + s->background_width) - 1);
2010 top_y = s->y;
2011 bottom_y = top_y + s->height - 1;
2013 left_p = (s->first_glyph->left_box_line_p
2014 || (s->hl == DRAW_MOUSE_FACE
2015 && (s->prev == NULL
2016 || s->prev->hl != s->hl)));
2017 right_p = (last_glyph->right_box_line_p
2018 || (s->hl == DRAW_MOUSE_FACE
2019 && (s->next == NULL
2020 || s->next->hl != s->hl)));
2022 get_glyph_string_clip_rect (s, &clip_rect);
2024 if (s->face->box == FACE_SIMPLE_BOX)
2025 x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
2026 left_p, right_p, &clip_rect);
2027 else
2029 x_setup_relief_colors (s);
2030 x_draw_relief_rect (s->f, left_x, top_y, right_x, bottom_y,
2031 width, raised_p, 1, 1, left_p, right_p, &clip_rect);
2036 /* Draw foreground of image glyph string S. */
2038 static void
2039 x_draw_image_foreground (struct glyph_string *s)
2041 int x = s->x;
2042 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2044 /* If first glyph of S has a left box line, start drawing it to the
2045 right of that line. */
2046 if (s->face->box != FACE_NO_BOX
2047 && s->first_glyph->left_box_line_p
2048 && s->slice.x == 0)
2049 x += eabs (s->face->box_line_width);
2051 /* If there is a margin around the image, adjust x- and y-position
2052 by that margin. */
2053 if (s->slice.x == 0)
2054 x += s->img->hmargin;
2055 if (s->slice.y == 0)
2056 y += s->img->vmargin;
2058 if (s->img->pixmap)
2060 if (s->img->mask)
2062 /* We can't set both a clip mask and use XSetClipRectangles
2063 because the latter also sets a clip mask. We also can't
2064 trust on the shape extension to be available
2065 (XShapeCombineRegion). So, compute the rectangle to draw
2066 manually. */
2067 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
2068 | GCFunction);
2069 XGCValues xgcv;
2070 XRectangle clip_rect, image_rect, r;
2072 xgcv.clip_mask = s->img->mask;
2073 xgcv.clip_x_origin = x;
2074 xgcv.clip_y_origin = y;
2075 xgcv.function = GXcopy;
2076 XChangeGC (s->display, s->gc, mask, &xgcv);
2078 get_glyph_string_clip_rect (s, &clip_rect);
2079 image_rect.x = x;
2080 image_rect.y = y;
2081 image_rect.width = s->slice.width;
2082 image_rect.height = s->slice.height;
2083 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
2084 XCopyArea (s->display, s->img->pixmap, s->window, s->gc,
2085 s->slice.x + r.x - x, s->slice.y + r.y - y,
2086 r.width, r.height, r.x, r.y);
2088 else
2090 XRectangle clip_rect, image_rect, r;
2092 get_glyph_string_clip_rect (s, &clip_rect);
2093 image_rect.x = x;
2094 image_rect.y = y;
2095 image_rect.width = s->slice.width;
2096 image_rect.height = s->slice.height;
2097 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
2098 XCopyArea (s->display, s->img->pixmap, s->window, s->gc,
2099 s->slice.x + r.x - x, s->slice.y + r.y - y,
2100 r.width, r.height, r.x, r.y);
2102 /* When the image has a mask, we can expect that at
2103 least part of a mouse highlight or a block cursor will
2104 be visible. If the image doesn't have a mask, make
2105 a block cursor visible by drawing a rectangle around
2106 the image. I believe it's looking better if we do
2107 nothing here for mouse-face. */
2108 if (s->hl == DRAW_CURSOR)
2110 int relief = eabs (s->img->relief);
2111 XDrawRectangle (s->display, s->window, s->gc,
2112 x - relief, y - relief,
2113 s->slice.width + relief*2 - 1,
2114 s->slice.height + relief*2 - 1);
2118 else
2119 /* Draw a rectangle if image could not be loaded. */
2120 XDrawRectangle (s->display, s->window, s->gc, x, y,
2121 s->slice.width - 1, s->slice.height - 1);
2125 /* Draw a relief around the image glyph string S. */
2127 static void
2128 x_draw_image_relief (struct glyph_string *s)
2130 int x1, y1, thick, raised_p, top_p, bot_p, left_p, right_p;
2131 XRectangle r;
2132 int x = s->x;
2133 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2135 /* If first glyph of S has a left box line, start drawing it to the
2136 right of that line. */
2137 if (s->face->box != FACE_NO_BOX
2138 && s->first_glyph->left_box_line_p
2139 && s->slice.x == 0)
2140 x += eabs (s->face->box_line_width);
2142 /* If there is a margin around the image, adjust x- and y-position
2143 by that margin. */
2144 if (s->slice.x == 0)
2145 x += s->img->hmargin;
2146 if (s->slice.y == 0)
2147 y += s->img->vmargin;
2149 if (s->hl == DRAW_IMAGE_SUNKEN
2150 || s->hl == DRAW_IMAGE_RAISED)
2152 thick = tool_bar_button_relief >= 0 ? tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
2153 raised_p = s->hl == DRAW_IMAGE_RAISED;
2155 else
2157 thick = eabs (s->img->relief);
2158 raised_p = s->img->relief > 0;
2161 x1 = x + s->slice.width - 1;
2162 y1 = y + s->slice.height - 1;
2163 top_p = bot_p = left_p = right_p = 0;
2165 if (s->slice.x == 0)
2166 x -= thick, left_p = 1;
2167 if (s->slice.y == 0)
2168 y -= thick, top_p = 1;
2169 if (s->slice.x + s->slice.width == s->img->width)
2170 x1 += thick, right_p = 1;
2171 if (s->slice.y + s->slice.height == s->img->height)
2172 y1 += thick, bot_p = 1;
2174 x_setup_relief_colors (s);
2175 get_glyph_string_clip_rect (s, &r);
2176 x_draw_relief_rect (s->f, x, y, x1, y1, thick, raised_p,
2177 top_p, bot_p, left_p, right_p, &r);
2181 /* Draw the foreground of image glyph string S to PIXMAP. */
2183 static void
2184 x_draw_image_foreground_1 (struct glyph_string *s, Pixmap pixmap)
2186 int x = 0;
2187 int y = s->ybase - s->y - image_ascent (s->img, s->face, &s->slice);
2189 /* If first glyph of S has a left box line, start drawing it to the
2190 right of that line. */
2191 if (s->face->box != FACE_NO_BOX
2192 && s->first_glyph->left_box_line_p
2193 && s->slice.x == 0)
2194 x += eabs (s->face->box_line_width);
2196 /* If there is a margin around the image, adjust x- and y-position
2197 by that margin. */
2198 if (s->slice.x == 0)
2199 x += s->img->hmargin;
2200 if (s->slice.y == 0)
2201 y += s->img->vmargin;
2203 if (s->img->pixmap)
2205 if (s->img->mask)
2207 /* We can't set both a clip mask and use XSetClipRectangles
2208 because the latter also sets a clip mask. We also can't
2209 trust on the shape extension to be available
2210 (XShapeCombineRegion). So, compute the rectangle to draw
2211 manually. */
2212 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
2213 | GCFunction);
2214 XGCValues xgcv;
2216 xgcv.clip_mask = s->img->mask;
2217 xgcv.clip_x_origin = x - s->slice.x;
2218 xgcv.clip_y_origin = y - s->slice.y;
2219 xgcv.function = GXcopy;
2220 XChangeGC (s->display, s->gc, mask, &xgcv);
2222 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
2223 s->slice.x, s->slice.y,
2224 s->slice.width, s->slice.height, x, y);
2225 XSetClipMask (s->display, s->gc, None);
2227 else
2229 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
2230 s->slice.x, s->slice.y,
2231 s->slice.width, s->slice.height, x, y);
2233 /* When the image has a mask, we can expect that at
2234 least part of a mouse highlight or a block cursor will
2235 be visible. If the image doesn't have a mask, make
2236 a block cursor visible by drawing a rectangle around
2237 the image. I believe it's looking better if we do
2238 nothing here for mouse-face. */
2239 if (s->hl == DRAW_CURSOR)
2241 int r = eabs (s->img->relief);
2242 XDrawRectangle (s->display, s->window, s->gc, x - r, y - r,
2243 s->slice.width + r*2 - 1,
2244 s->slice.height + r*2 - 1);
2248 else
2249 /* Draw a rectangle if image could not be loaded. */
2250 XDrawRectangle (s->display, pixmap, s->gc, x, y,
2251 s->slice.width - 1, s->slice.height - 1);
2255 /* Draw part of the background of glyph string S. X, Y, W, and H
2256 give the rectangle to draw. */
2258 static void
2259 x_draw_glyph_string_bg_rect (struct glyph_string *s, int x, int y, int w, int h)
2261 if (s->stippled_p)
2263 /* Fill background with a stipple pattern. */
2264 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
2265 XFillRectangle (s->display, s->window, s->gc, x, y, w, h);
2266 XSetFillStyle (s->display, s->gc, FillSolid);
2268 else
2269 x_clear_glyph_string_rect (s, x, y, w, h);
2273 /* Draw image glyph string S.
2275 s->y
2276 s->x +-------------------------
2277 | s->face->box
2279 | +-------------------------
2280 | | s->img->margin
2282 | | +-------------------
2283 | | | the image
2287 static void
2288 x_draw_image_glyph_string (struct glyph_string *s)
2290 int box_line_hwidth = eabs (s->face->box_line_width);
2291 int box_line_vwidth = max (s->face->box_line_width, 0);
2292 int height;
2293 Pixmap pixmap = None;
2295 height = s->height;
2296 if (s->slice.y == 0)
2297 height -= box_line_vwidth;
2298 if (s->slice.y + s->slice.height >= s->img->height)
2299 height -= box_line_vwidth;
2301 /* Fill background with face under the image. Do it only if row is
2302 taller than image or if image has a clip mask to reduce
2303 flickering. */
2304 s->stippled_p = s->face->stipple != 0;
2305 if (height > s->slice.height
2306 || s->img->hmargin
2307 || s->img->vmargin
2308 || s->img->mask
2309 || s->img->pixmap == 0
2310 || s->width != s->background_width)
2312 if (s->img->mask)
2314 /* Create a pixmap as large as the glyph string. Fill it
2315 with the background color. Copy the image to it, using
2316 its mask. Copy the temporary pixmap to the display. */
2317 Screen *screen = FRAME_X_SCREEN (s->f);
2318 int depth = DefaultDepthOfScreen (screen);
2320 /* Create a pixmap as large as the glyph string. */
2321 pixmap = XCreatePixmap (s->display, s->window,
2322 s->background_width,
2323 s->height, depth);
2325 /* Don't clip in the following because we're working on the
2326 pixmap. */
2327 XSetClipMask (s->display, s->gc, None);
2329 /* Fill the pixmap with the background color/stipple. */
2330 if (s->stippled_p)
2332 /* Fill background with a stipple pattern. */
2333 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
2334 XSetTSOrigin (s->display, s->gc, - s->x, - s->y);
2335 XFillRectangle (s->display, pixmap, s->gc,
2336 0, 0, s->background_width, s->height);
2337 XSetFillStyle (s->display, s->gc, FillSolid);
2338 XSetTSOrigin (s->display, s->gc, 0, 0);
2340 else
2342 XGCValues xgcv;
2343 XGetGCValues (s->display, s->gc, GCForeground | GCBackground,
2344 &xgcv);
2345 XSetForeground (s->display, s->gc, xgcv.background);
2346 XFillRectangle (s->display, pixmap, s->gc,
2347 0, 0, s->background_width, s->height);
2348 XSetForeground (s->display, s->gc, xgcv.foreground);
2351 else
2353 int x = s->x;
2354 int y = s->y;
2356 if (s->first_glyph->left_box_line_p
2357 && s->slice.x == 0)
2358 x += box_line_hwidth;
2360 if (s->slice.y == 0)
2361 y += box_line_vwidth;
2363 x_draw_glyph_string_bg_rect (s, x, y, s->background_width, height);
2366 s->background_filled_p = 1;
2369 /* Draw the foreground. */
2370 if (pixmap != None)
2372 x_draw_image_foreground_1 (s, pixmap);
2373 x_set_glyph_string_clipping (s);
2374 XCopyArea (s->display, pixmap, s->window, s->gc,
2375 0, 0, s->background_width, s->height, s->x, s->y);
2376 XFreePixmap (s->display, pixmap);
2378 else
2379 x_draw_image_foreground (s);
2381 /* If we must draw a relief around the image, do it. */
2382 if (s->img->relief
2383 || s->hl == DRAW_IMAGE_RAISED
2384 || s->hl == DRAW_IMAGE_SUNKEN)
2385 x_draw_image_relief (s);
2389 /* Draw stretch glyph string S. */
2391 static void
2392 x_draw_stretch_glyph_string (struct glyph_string *s)
2394 eassert (s->first_glyph->type == STRETCH_GLYPH);
2396 if (s->hl == DRAW_CURSOR
2397 && !x_stretch_cursor_p)
2399 /* If `x-stretch-cursor' is nil, don't draw a block cursor as
2400 wide as the stretch glyph. */
2401 int width, background_width = s->background_width;
2402 int x = s->x;
2404 if (!s->row->reversed_p)
2406 int left_x = window_box_left_offset (s->w, TEXT_AREA);
2408 if (x < left_x)
2410 background_width -= left_x - x;
2411 x = left_x;
2414 else
2416 /* In R2L rows, draw the cursor on the right edge of the
2417 stretch glyph. */
2418 int right_x = window_box_right_offset (s->w, TEXT_AREA);
2420 if (x + background_width > right_x)
2421 background_width -= x - right_x;
2422 x += background_width;
2424 width = min (FRAME_COLUMN_WIDTH (s->f), background_width);
2425 if (s->row->reversed_p)
2426 x -= width;
2428 /* Draw cursor. */
2429 x_draw_glyph_string_bg_rect (s, x, s->y, width, s->height);
2431 /* Clear rest using the GC of the original non-cursor face. */
2432 if (width < background_width)
2434 int y = s->y;
2435 int w = background_width - width, h = s->height;
2436 XRectangle r;
2437 GC gc;
2439 if (!s->row->reversed_p)
2440 x += width;
2441 else
2442 x = s->x;
2443 if (s->row->mouse_face_p
2444 && cursor_in_mouse_face_p (s->w))
2446 x_set_mouse_face_gc (s);
2447 gc = s->gc;
2449 else
2450 gc = s->face->gc;
2452 get_glyph_string_clip_rect (s, &r);
2453 XSetClipRectangles (s->display, gc, 0, 0, &r, 1, Unsorted);
2455 if (s->face->stipple)
2457 /* Fill background with a stipple pattern. */
2458 XSetFillStyle (s->display, gc, FillOpaqueStippled);
2459 XFillRectangle (s->display, s->window, gc, x, y, w, h);
2460 XSetFillStyle (s->display, gc, FillSolid);
2462 else
2464 XGCValues xgcv;
2465 XGetGCValues (s->display, gc, GCForeground | GCBackground, &xgcv);
2466 XSetForeground (s->display, gc, xgcv.background);
2467 XFillRectangle (s->display, s->window, gc, x, y, w, h);
2468 XSetForeground (s->display, gc, xgcv.foreground);
2472 else if (!s->background_filled_p)
2474 int background_width = s->background_width;
2475 int x = s->x, left_x = window_box_left_offset (s->w, TEXT_AREA);
2477 /* Don't draw into left margin, fringe or scrollbar area
2478 except for header line and mode line. */
2479 if (x < left_x && !s->row->mode_line_p)
2481 background_width -= left_x - x;
2482 x = left_x;
2484 if (background_width > 0)
2485 x_draw_glyph_string_bg_rect (s, x, s->y, background_width, s->height);
2488 s->background_filled_p = 1;
2492 Draw a wavy line under S. The wave fills wave_height pixels from y0.
2494 x0 wave_length = 2
2496 y0 * * * * *
2497 |* * * * * * * * *
2498 wave_height = 3 | * * * *
2502 static void
2503 x_draw_underwave (struct glyph_string *s)
2505 int wave_height = 3, wave_length = 2;
2506 int dx, dy, x0, y0, width, x1, y1, x2, y2, odd, xmax;
2507 XRectangle wave_clip, string_clip, final_clip;
2509 dx = wave_length;
2510 dy = wave_height - 1;
2511 x0 = s->x;
2512 y0 = s->ybase - wave_height + 3;
2513 width = s->width;
2514 xmax = x0 + width;
2516 /* Find and set clipping rectangle */
2518 wave_clip.x = x0;
2519 wave_clip.y = y0;
2520 wave_clip.width = width;
2521 wave_clip.height = wave_height;
2522 get_glyph_string_clip_rect (s, &string_clip);
2524 if (!x_intersect_rectangles (&wave_clip, &string_clip, &final_clip))
2525 return;
2527 XSetClipRectangles (s->display, s->gc, 0, 0, &final_clip, 1, Unsorted);
2529 /* Draw the waves */
2531 x1 = x0 - (x0 % dx);
2532 x2 = x1 + dx;
2533 odd = (x1/dx) % 2;
2534 y1 = y2 = y0;
2536 if (odd)
2537 y1 += dy;
2538 else
2539 y2 += dy;
2541 if (INT_MAX - dx < xmax)
2542 emacs_abort ();
2544 while (x1 <= xmax)
2546 XDrawLine (s->display, s->window, s->gc, x1, y1, x2, y2);
2547 x1 = x2, y1 = y2;
2548 x2 += dx, y2 = y0 + odd*dy;
2549 odd = !odd;
2552 /* Restore previous clipping rectangle(s) */
2553 XSetClipRectangles (s->display, s->gc, 0, 0, s->clip, s->num_clips, Unsorted);
2557 /* Draw glyph string S. */
2559 static void
2560 x_draw_glyph_string (struct glyph_string *s)
2562 bool relief_drawn_p = 0;
2564 /* If S draws into the background of its successors, draw the
2565 background of the successors first so that S can draw into it.
2566 This makes S->next use XDrawString instead of XDrawImageString. */
2567 if (s->next && s->right_overhang && !s->for_overlaps)
2569 int width;
2570 struct glyph_string *next;
2572 for (width = 0, next = s->next;
2573 next && width < s->right_overhang;
2574 width += next->width, next = next->next)
2575 if (next->first_glyph->type != IMAGE_GLYPH)
2577 x_set_glyph_string_gc (next);
2578 x_set_glyph_string_clipping (next);
2579 if (next->first_glyph->type == STRETCH_GLYPH)
2580 x_draw_stretch_glyph_string (next);
2581 else
2582 x_draw_glyph_string_background (next, 1);
2583 next->num_clips = 0;
2587 /* Set up S->gc, set clipping and draw S. */
2588 x_set_glyph_string_gc (s);
2590 /* Draw relief (if any) in advance for char/composition so that the
2591 glyph string can be drawn over it. */
2592 if (!s->for_overlaps
2593 && s->face->box != FACE_NO_BOX
2594 && (s->first_glyph->type == CHAR_GLYPH
2595 || s->first_glyph->type == COMPOSITE_GLYPH))
2598 x_set_glyph_string_clipping (s);
2599 x_draw_glyph_string_background (s, 1);
2600 x_draw_glyph_string_box (s);
2601 x_set_glyph_string_clipping (s);
2602 relief_drawn_p = 1;
2604 else if (!s->clip_head /* draw_glyphs didn't specify a clip mask. */
2605 && !s->clip_tail
2606 && ((s->prev && s->prev->hl != s->hl && s->left_overhang)
2607 || (s->next && s->next->hl != s->hl && s->right_overhang)))
2608 /* We must clip just this glyph. left_overhang part has already
2609 drawn when s->prev was drawn, and right_overhang part will be
2610 drawn later when s->next is drawn. */
2611 x_set_glyph_string_clipping_exactly (s, s);
2612 else
2613 x_set_glyph_string_clipping (s);
2615 switch (s->first_glyph->type)
2617 case IMAGE_GLYPH:
2618 x_draw_image_glyph_string (s);
2619 break;
2621 case STRETCH_GLYPH:
2622 x_draw_stretch_glyph_string (s);
2623 break;
2625 case CHAR_GLYPH:
2626 if (s->for_overlaps)
2627 s->background_filled_p = 1;
2628 else
2629 x_draw_glyph_string_background (s, 0);
2630 x_draw_glyph_string_foreground (s);
2631 break;
2633 case COMPOSITE_GLYPH:
2634 if (s->for_overlaps || (s->cmp_from > 0
2635 && ! s->first_glyph->u.cmp.automatic))
2636 s->background_filled_p = 1;
2637 else
2638 x_draw_glyph_string_background (s, 1);
2639 x_draw_composite_glyph_string_foreground (s);
2640 break;
2642 case GLYPHLESS_GLYPH:
2643 if (s->for_overlaps)
2644 s->background_filled_p = 1;
2645 else
2646 x_draw_glyph_string_background (s, 1);
2647 x_draw_glyphless_glyph_string_foreground (s);
2648 break;
2650 default:
2651 emacs_abort ();
2654 if (!s->for_overlaps)
2656 /* Draw underline. */
2657 if (s->face->underline_p)
2659 if (s->face->underline_type == FACE_UNDER_WAVE)
2661 if (s->face->underline_defaulted_p)
2662 x_draw_underwave (s);
2663 else
2665 XGCValues xgcv;
2666 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2667 XSetForeground (s->display, s->gc, s->face->underline_color);
2668 x_draw_underwave (s);
2669 XSetForeground (s->display, s->gc, xgcv.foreground);
2672 else if (s->face->underline_type == FACE_UNDER_LINE)
2674 unsigned long thickness, position;
2675 int y;
2677 if (s->prev && s->prev->face->underline_p
2678 && s->prev->face->underline_type == FACE_UNDER_LINE)
2680 /* We use the same underline style as the previous one. */
2681 thickness = s->prev->underline_thickness;
2682 position = s->prev->underline_position;
2684 else
2686 /* Get the underline thickness. Default is 1 pixel. */
2687 if (s->font && s->font->underline_thickness > 0)
2688 thickness = s->font->underline_thickness;
2689 else
2690 thickness = 1;
2691 if (x_underline_at_descent_line)
2692 position = (s->height - thickness) - (s->ybase - s->y);
2693 else
2695 /* Get the underline position. This is the recommended
2696 vertical offset in pixels from the baseline to the top of
2697 the underline. This is a signed value according to the
2698 specs, and its default is
2700 ROUND ((maximum descent) / 2), with
2701 ROUND(x) = floor (x + 0.5) */
2703 if (x_use_underline_position_properties
2704 && s->font && s->font->underline_position >= 0)
2705 position = s->font->underline_position;
2706 else if (s->font)
2707 position = (s->font->descent + 1) / 2;
2708 else
2709 position = underline_minimum_offset;
2711 position = max (position, underline_minimum_offset);
2713 /* Check the sanity of thickness and position. We should
2714 avoid drawing underline out of the current line area. */
2715 if (s->y + s->height <= s->ybase + position)
2716 position = (s->height - 1) - (s->ybase - s->y);
2717 if (s->y + s->height < s->ybase + position + thickness)
2718 thickness = (s->y + s->height) - (s->ybase + position);
2719 s->underline_thickness = thickness;
2720 s->underline_position = position;
2721 y = s->ybase + position;
2722 if (s->face->underline_defaulted_p)
2723 XFillRectangle (s->display, s->window, s->gc,
2724 s->x, y, s->width, thickness);
2725 else
2727 XGCValues xgcv;
2728 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2729 XSetForeground (s->display, s->gc, s->face->underline_color);
2730 XFillRectangle (s->display, s->window, s->gc,
2731 s->x, y, s->width, thickness);
2732 XSetForeground (s->display, s->gc, xgcv.foreground);
2736 /* Draw overline. */
2737 if (s->face->overline_p)
2739 unsigned long dy = 0, h = 1;
2741 if (s->face->overline_color_defaulted_p)
2742 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2743 s->width, h);
2744 else
2746 XGCValues xgcv;
2747 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2748 XSetForeground (s->display, s->gc, s->face->overline_color);
2749 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2750 s->width, h);
2751 XSetForeground (s->display, s->gc, xgcv.foreground);
2755 /* Draw strike-through. */
2756 if (s->face->strike_through_p)
2758 unsigned long h = 1;
2759 unsigned long dy = (s->height - h) / 2;
2761 if (s->face->strike_through_color_defaulted_p)
2762 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2763 s->width, h);
2764 else
2766 XGCValues xgcv;
2767 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2768 XSetForeground (s->display, s->gc, s->face->strike_through_color);
2769 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2770 s->width, h);
2771 XSetForeground (s->display, s->gc, xgcv.foreground);
2775 /* Draw relief if not yet drawn. */
2776 if (!relief_drawn_p && s->face->box != FACE_NO_BOX)
2777 x_draw_glyph_string_box (s);
2779 if (s->prev)
2781 struct glyph_string *prev;
2783 for (prev = s->prev; prev; prev = prev->prev)
2784 if (prev->hl != s->hl
2785 && prev->x + prev->width + prev->right_overhang > s->x)
2787 /* As prev was drawn while clipped to its own area, we
2788 must draw the right_overhang part using s->hl now. */
2789 enum draw_glyphs_face save = prev->hl;
2791 prev->hl = s->hl;
2792 x_set_glyph_string_gc (prev);
2793 x_set_glyph_string_clipping_exactly (s, prev);
2794 if (prev->first_glyph->type == CHAR_GLYPH)
2795 x_draw_glyph_string_foreground (prev);
2796 else
2797 x_draw_composite_glyph_string_foreground (prev);
2798 XSetClipMask (prev->display, prev->gc, None);
2799 prev->hl = save;
2800 prev->num_clips = 0;
2804 if (s->next)
2806 struct glyph_string *next;
2808 for (next = s->next; next; next = next->next)
2809 if (next->hl != s->hl
2810 && next->x - next->left_overhang < s->x + s->width)
2812 /* As next will be drawn while clipped to its own area,
2813 we must draw the left_overhang part using s->hl now. */
2814 enum draw_glyphs_face save = next->hl;
2816 next->hl = s->hl;
2817 x_set_glyph_string_gc (next);
2818 x_set_glyph_string_clipping_exactly (s, next);
2819 if (next->first_glyph->type == CHAR_GLYPH)
2820 x_draw_glyph_string_foreground (next);
2821 else
2822 x_draw_composite_glyph_string_foreground (next);
2823 XSetClipMask (next->display, next->gc, None);
2824 next->hl = save;
2825 next->num_clips = 0;
2826 next->clip_head = s->next;
2831 /* Reset clipping. */
2832 XSetClipMask (s->display, s->gc, None);
2833 s->num_clips = 0;
2836 /* Shift display to make room for inserted glyphs. */
2838 static void
2839 x_shift_glyphs_for_insert (struct frame *f, int x, int y, int width, int height, int shift_by)
2841 XCopyArea (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), FRAME_X_WINDOW (f),
2842 f->output_data.x->normal_gc,
2843 x, y, width, height,
2844 x + shift_by, y);
2847 /* Delete N glyphs at the nominal cursor position. Not implemented
2848 for X frames. */
2850 static void
2851 x_delete_glyphs (struct frame *f, register int n)
2853 emacs_abort ();
2857 /* Like XClearArea, but check that WIDTH and HEIGHT are reasonable.
2858 If they are <= 0, this is probably an error. */
2860 void
2861 x_clear_area (Display *dpy, Window window, int x, int y, int width, int height)
2863 eassert (width > 0 && height > 0);
2864 XClearArea (dpy, window, x, y, width, height, False);
2868 /* Clear an entire frame. */
2870 static void
2871 x_clear_frame (struct frame *f)
2873 /* Clearing the frame will erase any cursor, so mark them all as no
2874 longer visible. */
2875 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2877 block_input ();
2879 XClearWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
2881 /* We have to clear the scroll bars. If we have changed colors or
2882 something like that, then they should be notified. */
2883 x_scroll_bar_clear (f);
2885 #if defined (USE_GTK) && defined (USE_TOOLKIT_SCROLL_BARS)
2886 /* Make sure scroll bars are redrawn. As they aren't redrawn by
2887 redisplay, do it here. */
2888 if (FRAME_GTK_WIDGET (f))
2889 gtk_widget_queue_draw (FRAME_GTK_WIDGET (f));
2890 #endif
2892 XFlush (FRAME_X_DISPLAY (f));
2894 unblock_input ();
2899 /* Invert the middle quarter of the frame for .15 sec. */
2901 static void
2902 XTflash (struct frame *f)
2904 block_input ();
2907 #ifdef USE_GTK
2908 /* Use Gdk routines to draw. This way, we won't draw over scroll bars
2909 when the scroll bars and the edit widget share the same X window. */
2910 GdkWindow *window = gtk_widget_get_window (FRAME_GTK_WIDGET (f));
2911 #ifdef HAVE_GTK3
2912 cairo_t *cr = gdk_cairo_create (window);
2913 cairo_set_source_rgb (cr, 1, 1, 1);
2914 cairo_set_operator (cr, CAIRO_OPERATOR_DIFFERENCE);
2915 #define XFillRectangle(d, win, gc, x, y, w, h) \
2916 do { \
2917 cairo_rectangle (cr, x, y, w, h); \
2918 cairo_fill (cr); \
2920 while (0)
2921 #else /* ! HAVE_GTK3 */
2922 GdkGCValues vals;
2923 GdkGC *gc;
2924 vals.foreground.pixel = (FRAME_FOREGROUND_PIXEL (f)
2925 ^ FRAME_BACKGROUND_PIXEL (f));
2926 vals.function = GDK_XOR;
2927 gc = gdk_gc_new_with_values (window,
2928 &vals, GDK_GC_FUNCTION | GDK_GC_FOREGROUND);
2929 #define XFillRectangle(d, win, gc, x, y, w, h) \
2930 gdk_draw_rectangle (window, gc, TRUE, x, y, w, h)
2931 #endif /* ! HAVE_GTK3 */
2932 #else /* ! USE_GTK */
2933 GC gc;
2935 /* Create a GC that will use the GXxor function to flip foreground
2936 pixels into background pixels. */
2938 XGCValues values;
2940 values.function = GXxor;
2941 values.foreground = (FRAME_FOREGROUND_PIXEL (f)
2942 ^ FRAME_BACKGROUND_PIXEL (f));
2944 gc = XCreateGC (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
2945 GCFunction | GCForeground, &values);
2947 #endif
2949 /* Get the height not including a menu bar widget. */
2950 int height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, FRAME_LINES (f));
2951 /* Height of each line to flash. */
2952 int flash_height = FRAME_LINE_HEIGHT (f);
2953 /* These will be the left and right margins of the rectangles. */
2954 int flash_left = FRAME_INTERNAL_BORDER_WIDTH (f);
2955 int flash_right = FRAME_PIXEL_WIDTH (f) - FRAME_INTERNAL_BORDER_WIDTH (f);
2956 int width = flash_right - flash_left;
2958 /* If window is tall, flash top and bottom line. */
2959 if (height > 3 * FRAME_LINE_HEIGHT (f))
2961 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
2962 flash_left,
2963 (FRAME_INTERNAL_BORDER_WIDTH (f)
2964 + FRAME_TOP_MARGIN_HEIGHT (f)),
2965 width, flash_height);
2966 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
2967 flash_left,
2968 (height - flash_height
2969 - FRAME_INTERNAL_BORDER_WIDTH (f)),
2970 width, flash_height);
2973 else
2974 /* If it is short, flash it all. */
2975 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
2976 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
2977 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
2979 x_flush (f);
2982 struct timespec delay = make_timespec (0, 150 * 1000 * 1000);
2983 struct timespec wakeup = timespec_add (current_timespec (), delay);
2985 /* Keep waiting until past the time wakeup or any input gets
2986 available. */
2987 while (! detect_input_pending ())
2989 struct timespec current = current_timespec ();
2990 struct timespec timeout;
2992 /* Break if result would not be positive. */
2993 if (timespec_cmp (wakeup, current) <= 0)
2994 break;
2996 /* How long `select' should wait. */
2997 timeout = make_timespec (0, 10 * 1000 * 1000);
2999 /* Try to wait that long--but we might wake up sooner. */
3000 pselect (0, NULL, NULL, NULL, &timeout, NULL);
3004 /* If window is tall, flash top and bottom line. */
3005 if (height > 3 * FRAME_LINE_HEIGHT (f))
3007 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3008 flash_left,
3009 (FRAME_INTERNAL_BORDER_WIDTH (f)
3010 + FRAME_TOP_MARGIN_HEIGHT (f)),
3011 width, flash_height);
3012 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3013 flash_left,
3014 (height - flash_height
3015 - FRAME_INTERNAL_BORDER_WIDTH (f)),
3016 width, flash_height);
3018 else
3019 /* If it is short, flash it all. */
3020 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3021 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
3022 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
3024 #ifdef USE_GTK
3025 #ifdef HAVE_GTK3
3026 cairo_destroy (cr);
3027 #else
3028 g_object_unref (G_OBJECT (gc));
3029 #endif
3030 #undef XFillRectangle
3031 #else
3032 XFreeGC (FRAME_X_DISPLAY (f), gc);
3033 #endif
3034 x_flush (f);
3038 unblock_input ();
3042 static void
3043 XTtoggle_invisible_pointer (struct frame *f, int invisible)
3045 block_input ();
3046 if (invisible)
3048 if (FRAME_DISPLAY_INFO (f)->invisible_cursor != 0)
3049 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3050 FRAME_DISPLAY_INFO (f)->invisible_cursor);
3052 else
3053 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3054 f->output_data.x->current_cursor);
3055 f->pointer_invisible = invisible;
3056 unblock_input ();
3060 /* Make audible bell. */
3062 static void
3063 XTring_bell (struct frame *f)
3065 if (FRAME_X_DISPLAY (f))
3067 if (visible_bell)
3068 XTflash (f);
3069 else
3071 block_input ();
3072 #ifdef HAVE_XKB
3073 XkbBell (FRAME_X_DISPLAY (f), None, 0, None);
3074 #else
3075 XBell (FRAME_X_DISPLAY (f), 0);
3076 #endif
3077 XFlush (FRAME_X_DISPLAY (f));
3078 unblock_input ();
3083 /***********************************************************************
3084 Line Dance
3085 ***********************************************************************/
3087 /* Perform an insert-lines or delete-lines operation, inserting N
3088 lines or deleting -N lines at vertical position VPOS. */
3090 static void
3091 x_ins_del_lines (struct frame *f, int vpos, int n)
3093 emacs_abort ();
3097 /* Scroll part of the display as described by RUN. */
3099 static void
3100 x_scroll_run (struct window *w, struct run *run)
3102 struct frame *f = XFRAME (w->frame);
3103 int x, y, width, height, from_y, to_y, bottom_y;
3105 /* Get frame-relative bounding box of the text display area of W,
3106 without mode lines. Include in this box the left and right
3107 fringe of W. */
3108 window_box (w, ANY_AREA, &x, &y, &width, &height);
3110 #ifdef USE_TOOLKIT_SCROLL_BARS
3111 /* If the fringe is adjacent to the left (right) scroll bar of a
3112 leftmost (rightmost, respectively) window, then extend its
3113 background to the gap between the fringe and the bar. */
3114 if ((WINDOW_LEFTMOST_P (w)
3115 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
3116 || (WINDOW_RIGHTMOST_P (w)
3117 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w)))
3119 int sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
3121 if (sb_width > 0)
3123 int bar_area_x = WINDOW_SCROLL_BAR_AREA_X (w);
3124 int bar_area_width = (WINDOW_CONFIG_SCROLL_BAR_COLS (w)
3125 * FRAME_COLUMN_WIDTH (f));
3127 if (bar_area_x + bar_area_width == x)
3129 x = bar_area_x + sb_width;
3130 width += bar_area_width - sb_width;
3132 else if (x + width == bar_area_x)
3133 width += bar_area_width - sb_width;
3136 #endif
3138 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
3139 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
3140 bottom_y = y + height;
3142 if (to_y < from_y)
3144 /* Scrolling up. Make sure we don't copy part of the mode
3145 line at the bottom. */
3146 if (from_y + run->height > bottom_y)
3147 height = bottom_y - from_y;
3148 else
3149 height = run->height;
3151 else
3153 /* Scrolling down. Make sure we don't copy over the mode line.
3154 at the bottom. */
3155 if (to_y + run->height > bottom_y)
3156 height = bottom_y - to_y;
3157 else
3158 height = run->height;
3161 block_input ();
3163 /* Cursor off. Will be switched on again in x_update_window_end. */
3164 x_clear_cursor (w);
3166 XCopyArea (FRAME_X_DISPLAY (f),
3167 FRAME_X_WINDOW (f), FRAME_X_WINDOW (f),
3168 f->output_data.x->normal_gc,
3169 x, from_y,
3170 width, height,
3171 x, to_y);
3173 unblock_input ();
3178 /***********************************************************************
3179 Exposure Events
3180 ***********************************************************************/
3183 static void
3184 frame_highlight (struct frame *f)
3186 /* We used to only do this if Vx_no_window_manager was non-nil, but
3187 the ICCCM (section 4.1.6) says that the window's border pixmap
3188 and border pixel are window attributes which are "private to the
3189 client", so we can always change it to whatever we want. */
3190 block_input ();
3191 /* I recently started to get errors in this XSetWindowBorder, depending on
3192 the window-manager in use, tho something more is at play since I've been
3193 using that same window-manager binary for ever. Let's not crash just
3194 because of this (bug#9310). */
3195 x_catch_errors (FRAME_X_DISPLAY (f));
3196 XSetWindowBorder (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3197 f->output_data.x->border_pixel);
3198 x_uncatch_errors ();
3199 unblock_input ();
3200 x_update_cursor (f, 1);
3201 x_set_frame_alpha (f);
3204 static void
3205 frame_unhighlight (struct frame *f)
3207 /* We used to only do this if Vx_no_window_manager was non-nil, but
3208 the ICCCM (section 4.1.6) says that the window's border pixmap
3209 and border pixel are window attributes which are "private to the
3210 client", so we can always change it to whatever we want. */
3211 block_input ();
3212 /* Same as above for XSetWindowBorder (bug#9310). */
3213 x_catch_errors (FRAME_X_DISPLAY (f));
3214 XSetWindowBorderPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3215 f->output_data.x->border_tile);
3216 x_uncatch_errors ();
3217 unblock_input ();
3218 x_update_cursor (f, 1);
3219 x_set_frame_alpha (f);
3222 /* The focus has changed. Update the frames as necessary to reflect
3223 the new situation. Note that we can't change the selected frame
3224 here, because the Lisp code we are interrupting might become confused.
3225 Each event gets marked with the frame in which it occurred, so the
3226 Lisp code can tell when the switch took place by examining the events. */
3228 static void
3229 x_new_focus_frame (struct x_display_info *dpyinfo, struct frame *frame)
3231 struct frame *old_focus = dpyinfo->x_focus_frame;
3233 if (frame != dpyinfo->x_focus_frame)
3235 /* Set this before calling other routines, so that they see
3236 the correct value of x_focus_frame. */
3237 dpyinfo->x_focus_frame = frame;
3239 if (old_focus && old_focus->auto_lower)
3240 x_lower_frame (old_focus);
3242 if (dpyinfo->x_focus_frame && dpyinfo->x_focus_frame->auto_raise)
3243 dpyinfo->x_pending_autoraise_frame = dpyinfo->x_focus_frame;
3244 else
3245 dpyinfo->x_pending_autoraise_frame = NULL;
3248 x_frame_rehighlight (dpyinfo);
3251 /* Handle FocusIn and FocusOut state changes for FRAME.
3252 If FRAME has focus and there exists more than one frame, puts
3253 a FOCUS_IN_EVENT into *BUFP. */
3255 static void
3256 x_focus_changed (int type, int state, struct x_display_info *dpyinfo, struct frame *frame, struct input_event *bufp)
3258 if (type == FocusIn)
3260 if (dpyinfo->x_focus_event_frame != frame)
3262 x_new_focus_frame (dpyinfo, frame);
3263 dpyinfo->x_focus_event_frame = frame;
3265 /* Don't stop displaying the initial startup message
3266 for a switch-frame event we don't need. */
3267 /* When run as a daemon, Vterminal_frame is always NIL. */
3268 bufp->arg = (((NILP (Vterminal_frame) || EQ (Fdaemonp (), Qt))
3269 && CONSP (Vframe_list)
3270 && !NILP (XCDR (Vframe_list)))
3271 ? Qt : Qnil);
3272 bufp->kind = FOCUS_IN_EVENT;
3273 XSETFRAME (bufp->frame_or_window, frame);
3276 frame->output_data.x->focus_state |= state;
3278 #ifdef HAVE_X_I18N
3279 if (FRAME_XIC (frame))
3280 XSetICFocus (FRAME_XIC (frame));
3281 #endif
3283 else if (type == FocusOut)
3285 frame->output_data.x->focus_state &= ~state;
3287 if (dpyinfo->x_focus_event_frame == frame)
3289 dpyinfo->x_focus_event_frame = 0;
3290 x_new_focus_frame (dpyinfo, 0);
3292 bufp->kind = FOCUS_OUT_EVENT;
3293 XSETFRAME (bufp->frame_or_window, frame);
3296 #ifdef HAVE_X_I18N
3297 if (FRAME_XIC (frame))
3298 XUnsetICFocus (FRAME_XIC (frame));
3299 #endif
3300 if (frame->pointer_invisible)
3301 XTtoggle_invisible_pointer (frame, 0);
3305 /* Return the Emacs frame-object corresponding to an X window.
3306 It could be the frame's main window or an icon window. */
3308 static struct frame *
3309 x_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
3311 Lisp_Object tail, frame;
3312 struct frame *f;
3314 if (wdesc == None)
3315 return NULL;
3317 FOR_EACH_FRAME (tail, frame)
3319 f = XFRAME (frame);
3320 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
3321 continue;
3322 if (f->output_data.x->hourglass_window == wdesc)
3323 return f;
3324 #ifdef USE_X_TOOLKIT
3325 if ((f->output_data.x->edit_widget
3326 && XtWindow (f->output_data.x->edit_widget) == wdesc)
3327 /* A tooltip frame? */
3328 || (!f->output_data.x->edit_widget
3329 && FRAME_X_WINDOW (f) == wdesc)
3330 || f->output_data.x->icon_desc == wdesc)
3331 return f;
3332 #else /* not USE_X_TOOLKIT */
3333 #ifdef USE_GTK
3334 if (f->output_data.x->edit_widget)
3336 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
3337 struct x_output *x = f->output_data.x;
3338 if (gwdesc != 0 && gwdesc == x->edit_widget)
3339 return f;
3341 #endif /* USE_GTK */
3342 if (FRAME_X_WINDOW (f) == wdesc
3343 || f->output_data.x->icon_desc == wdesc)
3344 return f;
3345 #endif /* not USE_X_TOOLKIT */
3347 return 0;
3350 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
3352 /* Like x_window_to_frame but also compares the window with the widget's
3353 windows. */
3355 static struct frame *
3356 x_any_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
3358 Lisp_Object tail, frame;
3359 struct frame *f, *found = NULL;
3360 struct x_output *x;
3362 if (wdesc == None)
3363 return NULL;
3365 FOR_EACH_FRAME (tail, frame)
3367 if (found)
3368 break;
3369 f = XFRAME (frame);
3370 if (FRAME_X_P (f) && FRAME_DISPLAY_INFO (f) == dpyinfo)
3372 /* This frame matches if the window is any of its widgets. */
3373 x = f->output_data.x;
3374 if (x->hourglass_window == wdesc)
3375 found = f;
3376 else if (x->widget)
3378 #ifdef USE_GTK
3379 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
3380 if (gwdesc != 0
3381 && gtk_widget_get_toplevel (gwdesc) == x->widget)
3382 found = f;
3383 #else
3384 if (wdesc == XtWindow (x->widget)
3385 || wdesc == XtWindow (x->column_widget)
3386 || wdesc == XtWindow (x->edit_widget))
3387 found = f;
3388 /* Match if the window is this frame's menubar. */
3389 else if (lw_window_is_in_menubar (wdesc, x->menubar_widget))
3390 found = f;
3391 #endif
3393 else if (FRAME_X_WINDOW (f) == wdesc)
3394 /* A tooltip frame. */
3395 found = f;
3399 return found;
3402 /* Likewise, but consider only the menu bar widget. */
3404 static struct frame *
3405 x_menubar_window_to_frame (struct x_display_info *dpyinfo,
3406 const XEvent *event)
3408 Window wdesc = event->xany.window;
3409 Lisp_Object tail, frame;
3410 struct frame *f;
3411 struct x_output *x;
3413 if (wdesc == None)
3414 return NULL;
3416 FOR_EACH_FRAME (tail, frame)
3418 f = XFRAME (frame);
3419 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
3420 continue;
3421 x = f->output_data.x;
3422 #ifdef USE_GTK
3423 if (x->menubar_widget && xg_event_is_for_menubar (f, event))
3424 return f;
3425 #else
3426 /* Match if the window is this frame's menubar. */
3427 if (x->menubar_widget
3428 && lw_window_is_in_menubar (wdesc, x->menubar_widget))
3429 return f;
3430 #endif
3432 return 0;
3435 /* Return the frame whose principal (outermost) window is WDESC.
3436 If WDESC is some other (smaller) window, we return 0. */
3438 struct frame *
3439 x_top_window_to_frame (struct x_display_info *dpyinfo, int wdesc)
3441 Lisp_Object tail, frame;
3442 struct frame *f;
3443 struct x_output *x;
3445 if (wdesc == None)
3446 return NULL;
3448 FOR_EACH_FRAME (tail, frame)
3450 f = XFRAME (frame);
3451 if (!FRAME_X_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
3452 continue;
3453 x = f->output_data.x;
3455 if (x->widget)
3457 /* This frame matches if the window is its topmost widget. */
3458 #ifdef USE_GTK
3459 GtkWidget *gwdesc = xg_win_to_widget (dpyinfo->display, wdesc);
3460 if (gwdesc == x->widget)
3461 return f;
3462 #else
3463 if (wdesc == XtWindow (x->widget))
3464 return f;
3465 #endif
3467 else if (FRAME_X_WINDOW (f) == wdesc)
3468 /* Tooltip frame. */
3469 return f;
3471 return 0;
3474 #else /* !USE_X_TOOLKIT && !USE_GTK */
3476 #define x_any_window_to_frame(d, i) x_window_to_frame (d, i)
3477 #define x_top_window_to_frame(d, i) x_window_to_frame (d, i)
3479 #endif /* USE_X_TOOLKIT || USE_GTK */
3481 /* The focus may have changed. Figure out if it is a real focus change,
3482 by checking both FocusIn/Out and Enter/LeaveNotify events.
3484 Returns FOCUS_IN_EVENT event in *BUFP. */
3486 static void
3487 x_detect_focus_change (struct x_display_info *dpyinfo, struct frame *frame,
3488 const XEvent *event, struct input_event *bufp)
3490 if (!frame)
3491 return;
3493 switch (event->type)
3495 case EnterNotify:
3496 case LeaveNotify:
3498 struct frame *focus_frame = dpyinfo->x_focus_event_frame;
3499 int focus_state
3500 = focus_frame ? focus_frame->output_data.x->focus_state : 0;
3502 if (event->xcrossing.detail != NotifyInferior
3503 && event->xcrossing.focus
3504 && ! (focus_state & FOCUS_EXPLICIT))
3505 x_focus_changed ((event->type == EnterNotify ? FocusIn : FocusOut),
3506 FOCUS_IMPLICIT,
3507 dpyinfo, frame, bufp);
3509 break;
3511 case FocusIn:
3512 case FocusOut:
3513 x_focus_changed (event->type,
3514 (event->xfocus.detail == NotifyPointer ?
3515 FOCUS_IMPLICIT : FOCUS_EXPLICIT),
3516 dpyinfo, frame, bufp);
3517 break;
3519 case ClientMessage:
3520 if (event->xclient.message_type == dpyinfo->Xatom_XEMBED)
3522 enum xembed_message msg = event->xclient.data.l[1];
3523 x_focus_changed ((msg == XEMBED_FOCUS_IN ? FocusIn : FocusOut),
3524 FOCUS_EXPLICIT, dpyinfo, frame, bufp);
3526 break;
3531 #if defined HAVE_MENUS && !defined USE_X_TOOLKIT && !defined USE_GTK
3532 /* Handle an event saying the mouse has moved out of an Emacs frame. */
3534 void
3535 x_mouse_leave (struct x_display_info *dpyinfo)
3537 x_new_focus_frame (dpyinfo, dpyinfo->x_focus_event_frame);
3539 #endif
3541 /* The focus has changed, or we have redirected a frame's focus to
3542 another frame (this happens when a frame uses a surrogate
3543 mini-buffer frame). Shift the highlight as appropriate.
3545 The FRAME argument doesn't necessarily have anything to do with which
3546 frame is being highlighted or un-highlighted; we only use it to find
3547 the appropriate X display info. */
3549 static void
3550 XTframe_rehighlight (struct frame *frame)
3552 x_frame_rehighlight (FRAME_DISPLAY_INFO (frame));
3555 static void
3556 x_frame_rehighlight (struct x_display_info *dpyinfo)
3558 struct frame *old_highlight = dpyinfo->x_highlight_frame;
3560 if (dpyinfo->x_focus_frame)
3562 dpyinfo->x_highlight_frame
3563 = ((FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame)))
3564 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
3565 : dpyinfo->x_focus_frame);
3566 if (! FRAME_LIVE_P (dpyinfo->x_highlight_frame))
3568 fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
3569 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
3572 else
3573 dpyinfo->x_highlight_frame = 0;
3575 if (dpyinfo->x_highlight_frame != old_highlight)
3577 if (old_highlight)
3578 frame_unhighlight (old_highlight);
3579 if (dpyinfo->x_highlight_frame)
3580 frame_highlight (dpyinfo->x_highlight_frame);
3586 /* Keyboard processing - modifier keys, vendor-specific keysyms, etc. */
3588 /* Initialize mode_switch_bit and modifier_meaning. */
3589 static void
3590 x_find_modifier_meanings (struct x_display_info *dpyinfo)
3592 int min_code, max_code;
3593 KeySym *syms;
3594 int syms_per_code;
3595 XModifierKeymap *mods;
3597 dpyinfo->meta_mod_mask = 0;
3598 dpyinfo->shift_lock_mask = 0;
3599 dpyinfo->alt_mod_mask = 0;
3600 dpyinfo->super_mod_mask = 0;
3601 dpyinfo->hyper_mod_mask = 0;
3603 XDisplayKeycodes (dpyinfo->display, &min_code, &max_code);
3605 syms = XGetKeyboardMapping (dpyinfo->display,
3606 min_code, max_code - min_code + 1,
3607 &syms_per_code);
3608 mods = XGetModifierMapping (dpyinfo->display);
3610 /* Scan the modifier table to see which modifier bits the Meta and
3611 Alt keysyms are on. */
3613 int row, col; /* The row and column in the modifier table. */
3614 int found_alt_or_meta;
3616 for (row = 3; row < 8; row++)
3618 found_alt_or_meta = 0;
3619 for (col = 0; col < mods->max_keypermod; col++)
3621 KeyCode code = mods->modifiermap[(row * mods->max_keypermod) + col];
3623 /* Zeroes are used for filler. Skip them. */
3624 if (code == 0)
3625 continue;
3627 /* Are any of this keycode's keysyms a meta key? */
3629 int code_col;
3631 for (code_col = 0; code_col < syms_per_code; code_col++)
3633 int sym = syms[((code - min_code) * syms_per_code) + code_col];
3635 switch (sym)
3637 case XK_Meta_L:
3638 case XK_Meta_R:
3639 found_alt_or_meta = 1;
3640 dpyinfo->meta_mod_mask |= (1 << row);
3641 break;
3643 case XK_Alt_L:
3644 case XK_Alt_R:
3645 found_alt_or_meta = 1;
3646 dpyinfo->alt_mod_mask |= (1 << row);
3647 break;
3649 case XK_Hyper_L:
3650 case XK_Hyper_R:
3651 if (!found_alt_or_meta)
3652 dpyinfo->hyper_mod_mask |= (1 << row);
3653 code_col = syms_per_code;
3654 col = mods->max_keypermod;
3655 break;
3657 case XK_Super_L:
3658 case XK_Super_R:
3659 if (!found_alt_or_meta)
3660 dpyinfo->super_mod_mask |= (1 << row);
3661 code_col = syms_per_code;
3662 col = mods->max_keypermod;
3663 break;
3665 case XK_Shift_Lock:
3666 /* Ignore this if it's not on the lock modifier. */
3667 if (!found_alt_or_meta && ((1 << row) == LockMask))
3668 dpyinfo->shift_lock_mask = LockMask;
3669 code_col = syms_per_code;
3670 col = mods->max_keypermod;
3671 break;
3679 /* If we couldn't find any meta keys, accept any alt keys as meta keys. */
3680 if (! dpyinfo->meta_mod_mask)
3682 dpyinfo->meta_mod_mask = dpyinfo->alt_mod_mask;
3683 dpyinfo->alt_mod_mask = 0;
3686 /* If some keys are both alt and meta,
3687 make them just meta, not alt. */
3688 if (dpyinfo->alt_mod_mask & dpyinfo->meta_mod_mask)
3690 dpyinfo->alt_mod_mask &= ~dpyinfo->meta_mod_mask;
3693 XFree (syms);
3694 XFreeModifiermap (mods);
3697 /* Convert between the modifier bits X uses and the modifier bits
3698 Emacs uses. */
3701 x_x_to_emacs_modifiers (struct x_display_info *dpyinfo, int state)
3703 int mod_meta = meta_modifier;
3704 int mod_alt = alt_modifier;
3705 int mod_hyper = hyper_modifier;
3706 int mod_super = super_modifier;
3707 Lisp_Object tem;
3709 tem = Fget (Vx_alt_keysym, Qmodifier_value);
3710 if (INTEGERP (tem)) mod_alt = XINT (tem) & INT_MAX;
3711 tem = Fget (Vx_meta_keysym, Qmodifier_value);
3712 if (INTEGERP (tem)) mod_meta = XINT (tem) & INT_MAX;
3713 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
3714 if (INTEGERP (tem)) mod_hyper = XINT (tem) & INT_MAX;
3715 tem = Fget (Vx_super_keysym, Qmodifier_value);
3716 if (INTEGERP (tem)) mod_super = XINT (tem) & INT_MAX;
3718 return ( ((state & (ShiftMask | dpyinfo->shift_lock_mask)) ? shift_modifier : 0)
3719 | ((state & ControlMask) ? ctrl_modifier : 0)
3720 | ((state & dpyinfo->meta_mod_mask) ? mod_meta : 0)
3721 | ((state & dpyinfo->alt_mod_mask) ? mod_alt : 0)
3722 | ((state & dpyinfo->super_mod_mask) ? mod_super : 0)
3723 | ((state & dpyinfo->hyper_mod_mask) ? mod_hyper : 0));
3726 static int
3727 x_emacs_to_x_modifiers (struct x_display_info *dpyinfo, EMACS_INT state)
3729 EMACS_INT mod_meta = meta_modifier;
3730 EMACS_INT mod_alt = alt_modifier;
3731 EMACS_INT mod_hyper = hyper_modifier;
3732 EMACS_INT mod_super = super_modifier;
3734 Lisp_Object tem;
3736 tem = Fget (Vx_alt_keysym, Qmodifier_value);
3737 if (INTEGERP (tem)) mod_alt = XINT (tem);
3738 tem = Fget (Vx_meta_keysym, Qmodifier_value);
3739 if (INTEGERP (tem)) mod_meta = XINT (tem);
3740 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
3741 if (INTEGERP (tem)) mod_hyper = XINT (tem);
3742 tem = Fget (Vx_super_keysym, Qmodifier_value);
3743 if (INTEGERP (tem)) mod_super = XINT (tem);
3746 return ( ((state & mod_alt) ? dpyinfo->alt_mod_mask : 0)
3747 | ((state & mod_super) ? dpyinfo->super_mod_mask : 0)
3748 | ((state & mod_hyper) ? dpyinfo->hyper_mod_mask : 0)
3749 | ((state & shift_modifier) ? ShiftMask : 0)
3750 | ((state & ctrl_modifier) ? ControlMask : 0)
3751 | ((state & mod_meta) ? dpyinfo->meta_mod_mask : 0));
3754 /* Convert a keysym to its name. */
3756 char *
3757 x_get_keysym_name (int keysym)
3759 char *value;
3761 block_input ();
3762 value = XKeysymToString (keysym);
3763 unblock_input ();
3765 return value;
3768 /* Mouse clicks and mouse movement. Rah.
3770 Formerly, we used PointerMotionHintMask (in standard_event_mask)
3771 so that we would have to call XQueryPointer after each MotionNotify
3772 event to ask for another such event. However, this made mouse tracking
3773 slow, and there was a bug that made it eventually stop.
3775 Simply asking for MotionNotify all the time seems to work better.
3777 In order to avoid asking for motion events and then throwing most
3778 of them away or busy-polling the server for mouse positions, we ask
3779 the server for pointer motion hints. This means that we get only
3780 one event per group of mouse movements. "Groups" are delimited by
3781 other kinds of events (focus changes and button clicks, for
3782 example), or by XQueryPointer calls; when one of these happens, we
3783 get another MotionNotify event the next time the mouse moves. This
3784 is at least as efficient as getting motion events when mouse
3785 tracking is on, and I suspect only negligibly worse when tracking
3786 is off. */
3788 /* Prepare a mouse-event in *RESULT for placement in the input queue.
3790 If the event is a button press, then note that we have grabbed
3791 the mouse. */
3793 static Lisp_Object
3794 construct_mouse_click (struct input_event *result,
3795 const XButtonEvent *event,
3796 struct frame *f)
3798 /* Make the event type NO_EVENT; we'll change that when we decide
3799 otherwise. */
3800 result->kind = MOUSE_CLICK_EVENT;
3801 result->code = event->button - Button1;
3802 result->timestamp = event->time;
3803 result->modifiers = (x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO (f),
3804 event->state)
3805 | (event->type == ButtonRelease
3806 ? up_modifier
3807 : down_modifier));
3809 XSETINT (result->x, event->x);
3810 XSETINT (result->y, event->y);
3811 XSETFRAME (result->frame_or_window, f);
3812 result->arg = Qnil;
3813 return Qnil;
3816 /* Function to report a mouse movement to the mainstream Emacs code.
3817 The input handler calls this.
3819 We have received a mouse movement event, which is given in *event.
3820 If the mouse is over a different glyph than it was last time, tell
3821 the mainstream emacs code by setting mouse_moved. If not, ask for
3822 another motion event, so we can check again the next time it moves. */
3824 static int
3825 note_mouse_movement (struct frame *frame, const XMotionEvent *event)
3827 XRectangle *r;
3828 struct x_display_info *dpyinfo;
3830 if (!FRAME_X_OUTPUT (frame))
3831 return 0;
3833 dpyinfo = FRAME_DISPLAY_INFO (frame);
3834 dpyinfo->last_mouse_movement_time = event->time;
3835 dpyinfo->last_mouse_motion_frame = frame;
3836 dpyinfo->last_mouse_motion_x = event->x;
3837 dpyinfo->last_mouse_motion_y = event->y;
3839 if (event->window != FRAME_X_WINDOW (frame))
3841 frame->mouse_moved = 1;
3842 dpyinfo->last_mouse_scroll_bar = NULL;
3843 note_mouse_highlight (frame, -1, -1);
3844 dpyinfo->last_mouse_glyph_frame = NULL;
3845 return 1;
3849 /* Has the mouse moved off the glyph it was on at the last sighting? */
3850 r = &dpyinfo->last_mouse_glyph;
3851 if (frame != dpyinfo->last_mouse_glyph_frame
3852 || event->x < r->x || event->x >= r->x + r->width
3853 || event->y < r->y || event->y >= r->y + r->height)
3855 frame->mouse_moved = 1;
3856 dpyinfo->last_mouse_scroll_bar = NULL;
3857 note_mouse_highlight (frame, event->x, event->y);
3858 /* Remember which glyph we're now on. */
3859 remember_mouse_glyph (frame, event->x, event->y, r);
3860 dpyinfo->last_mouse_glyph_frame = frame;
3861 return 1;
3864 return 0;
3867 /* Return the current position of the mouse.
3868 *FP should be a frame which indicates which display to ask about.
3870 If the mouse movement started in a scroll bar, set *FP, *BAR_WINDOW,
3871 and *PART to the frame, window, and scroll bar part that the mouse
3872 is over. Set *X and *Y to the portion and whole of the mouse's
3873 position on the scroll bar.
3875 If the mouse movement started elsewhere, set *FP to the frame the
3876 mouse is on, *BAR_WINDOW to nil, and *X and *Y to the character cell
3877 the mouse is over.
3879 Set *TIMESTAMP to the server time-stamp for the time at which the mouse
3880 was at this position.
3882 Don't store anything if we don't have a valid set of values to report.
3884 This clears the mouse_moved flag, so we can wait for the next mouse
3885 movement. */
3887 static void
3888 XTmouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
3889 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
3890 Time *timestamp)
3892 struct frame *f1;
3893 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (*fp);
3895 block_input ();
3897 if (dpyinfo->last_mouse_scroll_bar && insist == 0)
3898 x_scroll_bar_report_motion (fp, bar_window, part, x, y, timestamp);
3899 else
3901 Window root;
3902 int root_x, root_y;
3904 Window dummy_window;
3905 int dummy;
3907 Lisp_Object frame, tail;
3909 /* Clear the mouse-moved flag for every frame on this display. */
3910 FOR_EACH_FRAME (tail, frame)
3911 if (FRAME_X_P (XFRAME (frame))
3912 && FRAME_X_DISPLAY (XFRAME (frame)) == FRAME_X_DISPLAY (*fp))
3913 XFRAME (frame)->mouse_moved = 0;
3915 dpyinfo->last_mouse_scroll_bar = NULL;
3917 /* Figure out which root window we're on. */
3918 XQueryPointer (FRAME_X_DISPLAY (*fp),
3919 DefaultRootWindow (FRAME_X_DISPLAY (*fp)),
3921 /* The root window which contains the pointer. */
3922 &root,
3924 /* Trash which we can't trust if the pointer is on
3925 a different screen. */
3926 &dummy_window,
3928 /* The position on that root window. */
3929 &root_x, &root_y,
3931 /* More trash we can't trust. */
3932 &dummy, &dummy,
3934 /* Modifier keys and pointer buttons, about which
3935 we don't care. */
3936 (unsigned int *) &dummy);
3938 /* Now we have a position on the root; find the innermost window
3939 containing the pointer. */
3941 Window win, child;
3942 int win_x, win_y;
3943 int parent_x = 0, parent_y = 0;
3945 win = root;
3947 /* XTranslateCoordinates can get errors if the window
3948 structure is changing at the same time this function
3949 is running. So at least we must not crash from them. */
3951 x_catch_errors (FRAME_X_DISPLAY (*fp));
3953 if (x_mouse_grabbed (dpyinfo))
3955 /* If mouse was grabbed on a frame, give coords for that frame
3956 even if the mouse is now outside it. */
3957 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
3959 /* From-window. */
3960 root,
3962 /* To-window. */
3963 FRAME_X_WINDOW (dpyinfo->last_mouse_frame),
3965 /* From-position, to-position. */
3966 root_x, root_y, &win_x, &win_y,
3968 /* Child of win. */
3969 &child);
3970 f1 = dpyinfo->last_mouse_frame;
3972 else
3974 while (1)
3976 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
3978 /* From-window, to-window. */
3979 root, win,
3981 /* From-position, to-position. */
3982 root_x, root_y, &win_x, &win_y,
3984 /* Child of win. */
3985 &child);
3987 if (child == None || child == win)
3988 break;
3989 #ifdef USE_GTK
3990 /* We don't wan't to know the innermost window. We
3991 want the edit window. For non-Gtk+ the innermost
3992 window is the edit window. For Gtk+ it might not
3993 be. It might be the tool bar for example. */
3994 if (x_window_to_frame (dpyinfo, win))
3995 break;
3996 #endif
3997 win = child;
3998 parent_x = win_x;
3999 parent_y = win_y;
4002 /* Now we know that:
4003 win is the innermost window containing the pointer
4004 (XTC says it has no child containing the pointer),
4005 win_x and win_y are the pointer's position in it
4006 (XTC did this the last time through), and
4007 parent_x and parent_y are the pointer's position in win's parent.
4008 (They are what win_x and win_y were when win was child.
4009 If win is the root window, it has no parent, and
4010 parent_{x,y} are invalid, but that's okay, because we'll
4011 never use them in that case.) */
4013 #ifdef USE_GTK
4014 /* We don't wan't to know the innermost window. We
4015 want the edit window. */
4016 f1 = x_window_to_frame (dpyinfo, win);
4017 #else
4018 /* Is win one of our frames? */
4019 f1 = x_any_window_to_frame (dpyinfo, win);
4020 #endif
4022 #ifdef USE_X_TOOLKIT
4023 /* If we end up with the menu bar window, say it's not
4024 on the frame. */
4025 if (f1 != NULL
4026 && f1->output_data.x->menubar_widget
4027 && win == XtWindow (f1->output_data.x->menubar_widget))
4028 f1 = NULL;
4029 #endif /* USE_X_TOOLKIT */
4032 if (x_had_errors_p (FRAME_X_DISPLAY (*fp)))
4033 f1 = 0;
4035 x_uncatch_errors ();
4037 /* If not, is it one of our scroll bars? */
4038 if (! f1)
4040 struct scroll_bar *bar;
4042 bar = x_window_to_scroll_bar (FRAME_X_DISPLAY (*fp), win);
4044 if (bar)
4046 f1 = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
4047 win_x = parent_x;
4048 win_y = parent_y;
4052 if (f1 == 0 && insist > 0)
4053 f1 = SELECTED_FRAME ();
4055 if (f1)
4057 /* Ok, we found a frame. Store all the values.
4058 last_mouse_glyph is a rectangle used to reduce the
4059 generation of mouse events. To not miss any motion
4060 events, we must divide the frame into rectangles of the
4061 size of the smallest character that could be displayed
4062 on it, i.e. into the same rectangles that matrices on
4063 the frame are divided into. */
4065 /* FIXME: what if F1 is not an X frame? */
4066 dpyinfo = FRAME_DISPLAY_INFO (f1);
4067 remember_mouse_glyph (f1, win_x, win_y, &dpyinfo->last_mouse_glyph);
4068 dpyinfo->last_mouse_glyph_frame = f1;
4070 *bar_window = Qnil;
4071 *part = 0;
4072 *fp = f1;
4073 XSETINT (*x, win_x);
4074 XSETINT (*y, win_y);
4075 *timestamp = dpyinfo->last_mouse_movement_time;
4080 unblock_input ();
4085 /***********************************************************************
4086 Scroll bars
4087 ***********************************************************************/
4089 /* Scroll bar support. */
4091 /* Given an X window ID and a DISPLAY, find the struct scroll_bar which
4092 manages it.
4093 This can be called in GC, so we have to make sure to strip off mark
4094 bits. */
4096 static struct scroll_bar *
4097 x_window_to_scroll_bar (Display *display, Window window_id)
4099 Lisp_Object tail, frame;
4101 #if defined (USE_GTK) && defined (USE_TOOLKIT_SCROLL_BARS)
4102 window_id = (Window) xg_get_scroll_id_for_window (display, window_id);
4103 #endif /* USE_GTK && USE_TOOLKIT_SCROLL_BARS */
4105 FOR_EACH_FRAME (tail, frame)
4107 Lisp_Object bar, condemned;
4109 if (! FRAME_X_P (XFRAME (frame)))
4110 continue;
4112 /* Scan this frame's scroll bar list for a scroll bar with the
4113 right window ID. */
4114 condemned = FRAME_CONDEMNED_SCROLL_BARS (XFRAME (frame));
4115 for (bar = FRAME_SCROLL_BARS (XFRAME (frame));
4116 /* This trick allows us to search both the ordinary and
4117 condemned scroll bar lists with one loop. */
4118 ! NILP (bar) || (bar = condemned,
4119 condemned = Qnil,
4120 ! NILP (bar));
4121 bar = XSCROLL_BAR (bar)->next)
4122 if (XSCROLL_BAR (bar)->x_window == window_id &&
4123 FRAME_X_DISPLAY (XFRAME (frame)) == display)
4124 return XSCROLL_BAR (bar);
4127 return NULL;
4131 #if defined USE_LUCID
4133 /* Return the Lucid menu bar WINDOW is part of. Return null
4134 if WINDOW is not part of a menu bar. */
4136 static Widget
4137 x_window_to_menu_bar (Window window)
4139 Lisp_Object tail, frame;
4141 FOR_EACH_FRAME (tail, frame)
4142 if (FRAME_X_P (XFRAME (frame)))
4144 Widget menu_bar = XFRAME (frame)->output_data.x->menubar_widget;
4146 if (menu_bar && xlwmenu_window_p (menu_bar, window))
4147 return menu_bar;
4149 return NULL;
4152 #endif /* USE_LUCID */
4155 /************************************************************************
4156 Toolkit scroll bars
4157 ************************************************************************/
4159 #ifdef USE_TOOLKIT_SCROLL_BARS
4161 static void x_send_scroll_bar_event (Lisp_Object, int, int, int);
4163 /* Lisp window being scrolled. Set when starting to interact with
4164 a toolkit scroll bar, reset to nil when ending the interaction. */
4166 static Lisp_Object window_being_scrolled;
4168 /* Whether this is an Xaw with arrow-scrollbars. This should imply
4169 that movements of 1/20 of the screen size are mapped to up/down. */
4171 #ifndef USE_GTK
4172 /* Id of action hook installed for scroll bars. */
4174 static XtActionHookId action_hook_id;
4176 static Boolean xaw3d_arrow_scroll;
4178 /* Whether the drag scrolling maintains the mouse at the top of the
4179 thumb. If not, resizing the thumb needs to be done more carefully
4180 to avoid jerkiness. */
4182 static Boolean xaw3d_pick_top;
4184 /* Action hook installed via XtAppAddActionHook when toolkit scroll
4185 bars are used.. The hook is responsible for detecting when
4186 the user ends an interaction with the scroll bar, and generates
4187 a `end-scroll' SCROLL_BAR_CLICK_EVENT' event if so. */
4189 static void
4190 xt_action_hook (Widget widget, XtPointer client_data, String action_name,
4191 XEvent *event, String *params, Cardinal *num_params)
4193 int scroll_bar_p;
4194 const char *end_action;
4196 #ifdef USE_MOTIF
4197 scroll_bar_p = XmIsScrollBar (widget);
4198 end_action = "Release";
4199 #else /* !USE_MOTIF i.e. use Xaw */
4200 scroll_bar_p = XtIsSubclass (widget, scrollbarWidgetClass);
4201 end_action = "EndScroll";
4202 #endif /* USE_MOTIF */
4204 if (scroll_bar_p
4205 && strcmp (action_name, end_action) == 0
4206 && WINDOWP (window_being_scrolled))
4208 struct window *w;
4209 struct scroll_bar *bar;
4211 x_send_scroll_bar_event (window_being_scrolled,
4212 scroll_bar_end_scroll, 0, 0);
4213 w = XWINDOW (window_being_scrolled);
4214 bar = XSCROLL_BAR (w->vertical_scroll_bar);
4216 if (bar->dragging != -1)
4218 bar->dragging = -1;
4219 /* The thumb size is incorrect while dragging: fix it. */
4220 set_vertical_scroll_bar (w);
4222 window_being_scrolled = Qnil;
4223 #if defined (USE_LUCID)
4224 bar->last_seen_part = scroll_bar_nowhere;
4225 #endif
4226 /* Xt timeouts no longer needed. */
4227 toolkit_scroll_bar_interaction = 0;
4230 #endif /* not USE_GTK */
4232 /* Send a client message with message type Xatom_Scrollbar for a
4233 scroll action to the frame of WINDOW. PART is a value identifying
4234 the part of the scroll bar that was clicked on. PORTION is the
4235 amount to scroll of a whole of WHOLE. */
4237 static void
4238 x_send_scroll_bar_event (Lisp_Object window, int part, int portion, int whole)
4240 XEvent event;
4241 XClientMessageEvent *ev = &event.xclient;
4242 struct window *w = XWINDOW (window);
4243 struct frame *f = XFRAME (w->frame);
4244 intptr_t iw = (intptr_t) w;
4245 enum { BITS_PER_INTPTR = CHAR_BIT * sizeof iw };
4246 verify (BITS_PER_INTPTR <= 64);
4247 int sign_shift = BITS_PER_INTPTR - 32;
4249 block_input ();
4251 /* Construct a ClientMessage event to send to the frame. */
4252 ev->type = ClientMessage;
4253 ev->message_type = FRAME_DISPLAY_INFO (f)->Xatom_Scrollbar;
4254 ev->display = FRAME_X_DISPLAY (f);
4255 ev->window = FRAME_X_WINDOW (f);
4256 ev->format = 32;
4258 /* A 32-bit X client on a 64-bit X server can pass a window pointer
4259 as-is. A 64-bit client on a 32-bit X server is in trouble
4260 because a pointer does not fit and would be truncated while
4261 passing through the server. So use two slots and hope that X12
4262 will resolve such issues someday. */
4263 ev->data.l[0] = iw >> 31 >> 1;
4264 ev->data.l[1] = sign_shift <= 0 ? iw : iw << sign_shift >> sign_shift;
4265 ev->data.l[2] = part;
4266 ev->data.l[3] = portion;
4267 ev->data.l[4] = whole;
4269 /* Make Xt timeouts work while the scroll bar is active. */
4270 #ifdef USE_X_TOOLKIT
4271 toolkit_scroll_bar_interaction = 1;
4272 x_activate_timeout_atimer ();
4273 #endif
4275 /* Setting the event mask to zero means that the message will
4276 be sent to the client that created the window, and if that
4277 window no longer exists, no event will be sent. */
4278 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), False, 0, &event);
4279 unblock_input ();
4283 /* Transform a scroll bar ClientMessage EVENT to an Emacs input event
4284 in *IEVENT. */
4286 static void
4287 x_scroll_bar_to_input_event (const XEvent *event,
4288 struct input_event *ievent)
4290 const XClientMessageEvent *ev = &event->xclient;
4291 Lisp_Object window;
4292 struct window *w;
4294 /* See the comment in the function above. */
4295 intptr_t iw0 = ev->data.l[0];
4296 intptr_t iw1 = ev->data.l[1];
4297 intptr_t iw = (iw0 << 31 << 1) + (iw1 & 0xffffffffu);
4298 w = (struct window *) iw;
4300 XSETWINDOW (window, w);
4302 ievent->kind = SCROLL_BAR_CLICK_EVENT;
4303 ievent->frame_or_window = window;
4304 ievent->arg = Qnil;
4305 #ifdef USE_GTK
4306 ievent->timestamp = CurrentTime;
4307 #else
4308 ievent->timestamp =
4309 XtLastTimestampProcessed (FRAME_X_DISPLAY (XFRAME (w->frame)));
4310 #endif
4311 ievent->code = 0;
4312 ievent->part = ev->data.l[2];
4313 ievent->x = make_number (ev->data.l[3]);
4314 ievent->y = make_number (ev->data.l[4]);
4315 ievent->modifiers = 0;
4319 #ifdef USE_MOTIF
4321 /* Minimum and maximum values used for Motif scroll bars. */
4323 #define XM_SB_MAX 10000000
4326 /* Scroll bar callback for Motif scroll bars. WIDGET is the scroll
4327 bar widget. CLIENT_DATA is a pointer to the scroll_bar structure.
4328 CALL_DATA is a pointer to a XmScrollBarCallbackStruct. */
4330 static void
4331 xm_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
4333 struct scroll_bar *bar = client_data;
4334 XmScrollBarCallbackStruct *cs = call_data;
4335 int part = -1, whole = 0, portion = 0;
4337 switch (cs->reason)
4339 case XmCR_DECREMENT:
4340 bar->dragging = -1;
4341 part = scroll_bar_up_arrow;
4342 break;
4344 case XmCR_INCREMENT:
4345 bar->dragging = -1;
4346 part = scroll_bar_down_arrow;
4347 break;
4349 case XmCR_PAGE_DECREMENT:
4350 bar->dragging = -1;
4351 part = scroll_bar_above_handle;
4352 break;
4354 case XmCR_PAGE_INCREMENT:
4355 bar->dragging = -1;
4356 part = scroll_bar_below_handle;
4357 break;
4359 case XmCR_TO_TOP:
4360 bar->dragging = -1;
4361 part = scroll_bar_to_top;
4362 break;
4364 case XmCR_TO_BOTTOM:
4365 bar->dragging = -1;
4366 part = scroll_bar_to_bottom;
4367 break;
4369 case XmCR_DRAG:
4371 int slider_size;
4373 /* Get the slider size. */
4374 block_input ();
4375 XtVaGetValues (widget, XmNsliderSize, &slider_size, NULL);
4376 unblock_input ();
4378 whole = XM_SB_MAX - slider_size;
4379 portion = min (cs->value, whole);
4380 part = scroll_bar_handle;
4381 bar->dragging = cs->value;
4383 break;
4385 case XmCR_VALUE_CHANGED:
4386 break;
4389 if (part >= 0)
4391 window_being_scrolled = bar->window;
4392 x_send_scroll_bar_event (bar->window, part, portion, whole);
4396 #elif defined USE_GTK
4398 /* Scroll bar callback for GTK scroll bars. WIDGET is the scroll
4399 bar widget. DATA is a pointer to the scroll_bar structure. */
4401 static gboolean
4402 xg_scroll_callback (GtkRange *range,
4403 GtkScrollType scroll,
4404 gdouble value,
4405 gpointer user_data)
4407 struct scroll_bar *bar = user_data;
4408 gdouble position;
4409 int part = -1, whole = 0, portion = 0;
4410 GtkAdjustment *adj = GTK_ADJUSTMENT (gtk_range_get_adjustment (range));
4411 struct frame *f = g_object_get_data (G_OBJECT (range), XG_FRAME_DATA);
4413 if (xg_ignore_gtk_scrollbar) return FALSE;
4414 position = gtk_adjustment_get_value (adj);
4417 switch (scroll)
4419 case GTK_SCROLL_JUMP:
4420 /* Buttons 1 2 or 3 must be grabbed. */
4421 if (FRAME_DISPLAY_INFO (f)->grabbed != 0
4422 && FRAME_DISPLAY_INFO (f)->grabbed < (1 << 4))
4424 part = scroll_bar_handle;
4425 whole = gtk_adjustment_get_upper (adj) -
4426 gtk_adjustment_get_page_size (adj);
4427 portion = min ((int)position, whole);
4428 bar->dragging = portion;
4430 break;
4431 case GTK_SCROLL_STEP_BACKWARD:
4432 part = scroll_bar_up_arrow;
4433 bar->dragging = -1;
4434 break;
4435 case GTK_SCROLL_STEP_FORWARD:
4436 part = scroll_bar_down_arrow;
4437 bar->dragging = -1;
4438 break;
4439 case GTK_SCROLL_PAGE_BACKWARD:
4440 part = scroll_bar_above_handle;
4441 bar->dragging = -1;
4442 break;
4443 case GTK_SCROLL_PAGE_FORWARD:
4444 part = scroll_bar_below_handle;
4445 bar->dragging = -1;
4446 break;
4449 if (part >= 0)
4451 window_being_scrolled = bar->window;
4452 x_send_scroll_bar_event (bar->window, part, portion, whole);
4455 return FALSE;
4458 /* Callback for button release. Sets dragging to -1 when dragging is done. */
4460 static gboolean
4461 xg_end_scroll_callback (GtkWidget *widget,
4462 GdkEventButton *event,
4463 gpointer user_data)
4465 struct scroll_bar *bar = user_data;
4466 bar->dragging = -1;
4467 if (WINDOWP (window_being_scrolled))
4469 x_send_scroll_bar_event (window_being_scrolled,
4470 scroll_bar_end_scroll, 0, 0);
4471 window_being_scrolled = Qnil;
4474 return FALSE;
4478 #else /* not USE_GTK and not USE_MOTIF */
4480 /* Xaw scroll bar callback. Invoked when the thumb is dragged.
4481 WIDGET is the scroll bar widget. CLIENT_DATA is a pointer to the
4482 scroll bar struct. CALL_DATA is a pointer to a float saying where
4483 the thumb is. */
4485 static void
4486 xaw_jump_callback (Widget widget, XtPointer client_data, XtPointer call_data)
4488 struct scroll_bar *bar = client_data;
4489 float *top_addr = call_data;
4490 float top = *top_addr;
4491 float shown;
4492 int whole, portion, height;
4493 enum scroll_bar_part part;
4495 /* Get the size of the thumb, a value between 0 and 1. */
4496 block_input ();
4497 XtVaGetValues (widget, XtNshown, &shown, XtNheight, &height, NULL);
4498 unblock_input ();
4500 whole = 10000000;
4501 portion = shown < 1 ? top * whole : 0;
4503 if (shown < 1 && (eabs (top + shown - 1) < 1.0f / height))
4504 /* Some derivatives of Xaw refuse to shrink the thumb when you reach
4505 the bottom, so we force the scrolling whenever we see that we're
4506 too close to the bottom (in x_set_toolkit_scroll_bar_thumb
4507 we try to ensure that we always stay two pixels away from the
4508 bottom). */
4509 part = scroll_bar_down_arrow;
4510 else
4511 part = scroll_bar_handle;
4513 window_being_scrolled = bar->window;
4514 bar->dragging = portion;
4515 bar->last_seen_part = part;
4516 x_send_scroll_bar_event (bar->window, part, portion, whole);
4520 /* Xaw scroll bar callback. Invoked for incremental scrolling.,
4521 i.e. line or page up or down. WIDGET is the Xaw scroll bar
4522 widget. CLIENT_DATA is a pointer to the scroll_bar structure for
4523 the scroll bar. CALL_DATA is an integer specifying the action that
4524 has taken place. Its magnitude is in the range 0..height of the
4525 scroll bar. Negative values mean scroll towards buffer start.
4526 Values < height of scroll bar mean line-wise movement. */
4528 static void
4529 xaw_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
4531 struct scroll_bar *bar = client_data;
4532 /* The position really is stored cast to a pointer. */
4533 int position = (intptr_t) call_data;
4534 Dimension height;
4535 enum scroll_bar_part part;
4537 /* Get the height of the scroll bar. */
4538 block_input ();
4539 XtVaGetValues (widget, XtNheight, &height, NULL);
4540 unblock_input ();
4542 if (eabs (position) >= height)
4543 part = (position < 0) ? scroll_bar_above_handle : scroll_bar_below_handle;
4545 /* If Xaw3d was compiled with ARROW_SCROLLBAR,
4546 it maps line-movement to call_data = max(5, height/20). */
4547 else if (xaw3d_arrow_scroll && eabs (position) <= max (5, height / 20))
4548 part = (position < 0) ? scroll_bar_up_arrow : scroll_bar_down_arrow;
4549 else
4550 part = scroll_bar_move_ratio;
4552 window_being_scrolled = bar->window;
4553 bar->dragging = -1;
4554 bar->last_seen_part = part;
4555 x_send_scroll_bar_event (bar->window, part, position, height);
4558 #endif /* not USE_GTK and not USE_MOTIF */
4560 #define SCROLL_BAR_NAME "verticalScrollBar"
4562 /* Create the widget for scroll bar BAR on frame F. Record the widget
4563 and X window of the scroll bar in BAR. */
4565 #ifdef USE_GTK
4566 static void
4567 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
4569 const char *scroll_bar_name = SCROLL_BAR_NAME;
4571 block_input ();
4572 xg_create_scroll_bar (f, bar, G_CALLBACK (xg_scroll_callback),
4573 G_CALLBACK (xg_end_scroll_callback),
4574 scroll_bar_name);
4575 unblock_input ();
4578 #else /* not USE_GTK */
4580 static void
4581 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
4583 Window xwindow;
4584 Widget widget;
4585 Arg av[20];
4586 int ac = 0;
4587 const char *scroll_bar_name = SCROLL_BAR_NAME;
4588 unsigned long pixel;
4590 block_input ();
4592 #ifdef USE_MOTIF
4593 /* Set resources. Create the widget. */
4594 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
4595 XtSetArg (av[ac], XmNminimum, 0); ++ac;
4596 XtSetArg (av[ac], XmNmaximum, XM_SB_MAX); ++ac;
4597 XtSetArg (av[ac], XmNorientation, XmVERTICAL); ++ac;
4598 XtSetArg (av[ac], XmNprocessingDirection, XmMAX_ON_BOTTOM), ++ac;
4599 XtSetArg (av[ac], XmNincrement, 1); ++ac;
4600 XtSetArg (av[ac], XmNpageIncrement, 1); ++ac;
4602 pixel = f->output_data.x->scroll_bar_foreground_pixel;
4603 if (pixel != -1)
4605 XtSetArg (av[ac], XmNforeground, pixel);
4606 ++ac;
4609 pixel = f->output_data.x->scroll_bar_background_pixel;
4610 if (pixel != -1)
4612 XtSetArg (av[ac], XmNbackground, pixel);
4613 ++ac;
4616 widget = XmCreateScrollBar (f->output_data.x->edit_widget,
4617 (char *) scroll_bar_name, av, ac);
4619 /* Add one callback for everything that can happen. */
4620 XtAddCallback (widget, XmNdecrementCallback, xm_scroll_callback,
4621 (XtPointer) bar);
4622 XtAddCallback (widget, XmNdragCallback, xm_scroll_callback,
4623 (XtPointer) bar);
4624 XtAddCallback (widget, XmNincrementCallback, xm_scroll_callback,
4625 (XtPointer) bar);
4626 XtAddCallback (widget, XmNpageDecrementCallback, xm_scroll_callback,
4627 (XtPointer) bar);
4628 XtAddCallback (widget, XmNpageIncrementCallback, xm_scroll_callback,
4629 (XtPointer) bar);
4630 XtAddCallback (widget, XmNtoBottomCallback, xm_scroll_callback,
4631 (XtPointer) bar);
4632 XtAddCallback (widget, XmNtoTopCallback, xm_scroll_callback,
4633 (XtPointer) bar);
4635 /* Realize the widget. Only after that is the X window created. */
4636 XtRealizeWidget (widget);
4638 /* Set the cursor to an arrow. I didn't find a resource to do that.
4639 And I'm wondering why it hasn't an arrow cursor by default. */
4640 XDefineCursor (XtDisplay (widget), XtWindow (widget),
4641 f->output_data.x->nontext_cursor);
4643 #else /* !USE_MOTIF i.e. use Xaw */
4645 /* Set resources. Create the widget. The background of the
4646 Xaw3d scroll bar widget is a little bit light for my taste.
4647 We don't alter it here to let users change it according
4648 to their taste with `emacs*verticalScrollBar.background: xxx'. */
4649 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
4650 XtSetArg (av[ac], XtNorientation, XtorientVertical); ++ac;
4651 /* For smoother scrolling with Xaw3d -sm */
4652 /* XtSetArg (av[ac], XtNpickTop, True); ++ac; */
4654 pixel = f->output_data.x->scroll_bar_foreground_pixel;
4655 if (pixel != -1)
4657 XtSetArg (av[ac], XtNforeground, pixel);
4658 ++ac;
4661 pixel = f->output_data.x->scroll_bar_background_pixel;
4662 if (pixel != -1)
4664 XtSetArg (av[ac], XtNbackground, pixel);
4665 ++ac;
4668 /* Top/bottom shadow colors. */
4670 /* Allocate them, if necessary. */
4671 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1)
4673 pixel = f->output_data.x->scroll_bar_background_pixel;
4674 if (pixel != -1)
4676 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
4677 FRAME_X_COLORMAP (f),
4678 &pixel, 1.2, 0x8000))
4679 pixel = -1;
4680 f->output_data.x->scroll_bar_top_shadow_pixel = pixel;
4683 if (f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
4685 pixel = f->output_data.x->scroll_bar_background_pixel;
4686 if (pixel != -1)
4688 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
4689 FRAME_X_COLORMAP (f),
4690 &pixel, 0.6, 0x4000))
4691 pixel = -1;
4692 f->output_data.x->scroll_bar_bottom_shadow_pixel = pixel;
4696 #ifdef XtNbeNiceToColormap
4697 /* Tell the toolkit about them. */
4698 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1
4699 || f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
4700 /* We tried to allocate a color for the top/bottom shadow, and
4701 failed, so tell Xaw3d to use dithering instead. */
4702 /* But only if we have a small colormap. Xaw3d can allocate nice
4703 colors itself. */
4705 XtSetArg (av[ac], XtNbeNiceToColormap,
4706 DefaultDepthOfScreen (FRAME_X_SCREEN (f)) < 16);
4707 ++ac;
4709 else
4710 /* Tell what colors Xaw3d should use for the top/bottom shadow, to
4711 be more consistent with other emacs 3d colors, and since Xaw3d is
4712 not good at dealing with allocation failure. */
4714 /* This tells Xaw3d to use real colors instead of dithering for
4715 the shadows. */
4716 XtSetArg (av[ac], XtNbeNiceToColormap, False);
4717 ++ac;
4719 /* Specify the colors. */
4720 pixel = f->output_data.x->scroll_bar_top_shadow_pixel;
4721 if (pixel != -1)
4723 XtSetArg (av[ac], XtNtopShadowPixel, pixel);
4724 ++ac;
4726 pixel = f->output_data.x->scroll_bar_bottom_shadow_pixel;
4727 if (pixel != -1)
4729 XtSetArg (av[ac], XtNbottomShadowPixel, pixel);
4730 ++ac;
4733 #endif
4735 widget = XtCreateWidget (scroll_bar_name, scrollbarWidgetClass,
4736 f->output_data.x->edit_widget, av, ac);
4739 char const *initial = "";
4740 char const *val = initial;
4741 XtVaGetValues (widget, XtNscrollVCursor, (XtPointer) &val,
4742 #ifdef XtNarrowScrollbars
4743 XtNarrowScrollbars, (XtPointer) &xaw3d_arrow_scroll,
4744 #endif
4745 XtNpickTop, (XtPointer) &xaw3d_pick_top, NULL);
4746 if (xaw3d_arrow_scroll || val == initial)
4747 { /* ARROW_SCROLL */
4748 xaw3d_arrow_scroll = True;
4749 /* Isn't that just a personal preference ? --Stef */
4750 XtVaSetValues (widget, XtNcursorName, "top_left_arrow", NULL);
4754 /* Define callbacks. */
4755 XtAddCallback (widget, XtNjumpProc, xaw_jump_callback, (XtPointer) bar);
4756 XtAddCallback (widget, XtNscrollProc, xaw_scroll_callback,
4757 (XtPointer) bar);
4759 /* Realize the widget. Only after that is the X window created. */
4760 XtRealizeWidget (widget);
4762 #endif /* !USE_MOTIF */
4764 /* Install an action hook that lets us detect when the user
4765 finishes interacting with a scroll bar. */
4766 if (action_hook_id == 0)
4767 action_hook_id = XtAppAddActionHook (Xt_app_con, xt_action_hook, 0);
4769 /* Remember X window and widget in the scroll bar vector. */
4770 SET_SCROLL_BAR_X_WIDGET (bar, widget);
4771 xwindow = XtWindow (widget);
4772 bar->x_window = xwindow;
4774 unblock_input ();
4776 #endif /* not USE_GTK */
4779 /* Set the thumb size and position of scroll bar BAR. We are currently
4780 displaying PORTION out of a whole WHOLE, and our position POSITION. */
4782 #ifdef USE_GTK
4783 static void
4784 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position, int whole)
4786 xg_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
4789 #else /* not USE_GTK */
4790 static void
4791 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position,
4792 int whole)
4794 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
4795 Widget widget = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
4796 float top, shown;
4798 block_input ();
4800 #ifdef USE_MOTIF
4802 if (scroll_bar_adjust_thumb_portion_p)
4804 /* We use an estimate of 30 chars per line rather than the real
4805 `portion' value. This has the disadvantage that the thumb size
4806 is not very representative, but it makes our life a lot easier.
4807 Otherwise, we have to constantly adjust the thumb size, which
4808 we can't always do quickly enough: while dragging, the size of
4809 the thumb might prevent the user from dragging the thumb all the
4810 way to the end. but Motif and some versions of Xaw3d don't allow
4811 updating the thumb size while dragging. Also, even if we can update
4812 its size, the update will often happen too late.
4813 If you don't believe it, check out revision 1.650 of xterm.c to see
4814 what hoops we were going through and the still poor behavior we got. */
4815 portion = WINDOW_TOTAL_LINES (XWINDOW (bar->window)) * 30;
4816 /* When the thumb is at the bottom, position == whole.
4817 So we need to increase `whole' to make space for the thumb. */
4818 whole += portion;
4821 if (whole <= 0)
4822 top = 0, shown = 1;
4823 else
4825 top = (float) position / whole;
4826 shown = (float) portion / whole;
4829 if (bar->dragging == -1)
4831 int size, value;
4833 /* Slider size. Must be in the range [1 .. MAX - MIN] where MAX
4834 is the scroll bar's maximum and MIN is the scroll bar's minimum
4835 value. */
4836 size = clip_to_bounds (1, shown * XM_SB_MAX, XM_SB_MAX);
4838 /* Position. Must be in the range [MIN .. MAX - SLIDER_SIZE]. */
4839 value = top * XM_SB_MAX;
4840 value = min (value, XM_SB_MAX - size);
4842 XmScrollBarSetValues (widget, value, size, 0, 0, False);
4844 #else /* !USE_MOTIF i.e. use Xaw */
4846 if (whole == 0)
4847 top = 0, shown = 1;
4848 else
4850 top = (float) position / whole;
4851 shown = (float) portion / whole;
4855 float old_top, old_shown;
4856 Dimension height;
4857 XtVaGetValues (widget,
4858 XtNtopOfThumb, &old_top,
4859 XtNshown, &old_shown,
4860 XtNheight, &height,
4861 NULL);
4863 /* Massage the top+shown values. */
4864 if (bar->dragging == -1 || bar->last_seen_part == scroll_bar_down_arrow)
4865 top = max (0, min (1, top));
4866 else
4867 top = old_top;
4868 #if ! defined (HAVE_XAW3D)
4869 /* With Xaw, 'top' values too closer to 1.0 may
4870 cause the thumb to disappear. Fix that. */
4871 top = min (top, 0.99f);
4872 #endif
4873 /* Keep two pixels available for moving the thumb down. */
4874 shown = max (0, min (1 - top - (2.0f / height), shown));
4875 #if ! defined (HAVE_XAW3D)
4876 /* Likewise with too small 'shown'. */
4877 shown = max (shown, 0.01f);
4878 #endif
4880 /* If the call to XawScrollbarSetThumb below doesn't seem to
4881 work, check that 'NARROWPROTO' is defined in src/config.h.
4882 If this is not so, most likely you need to fix configure. */
4883 if (top != old_top || shown != old_shown)
4885 if (bar->dragging == -1)
4886 XawScrollbarSetThumb (widget, top, shown);
4887 else
4889 /* Try to make the scrolling a tad smoother. */
4890 if (!xaw3d_pick_top)
4891 shown = min (shown, old_shown);
4893 XawScrollbarSetThumb (widget, top, shown);
4897 #endif /* !USE_MOTIF */
4899 unblock_input ();
4901 #endif /* not USE_GTK */
4903 #endif /* USE_TOOLKIT_SCROLL_BARS */
4907 /************************************************************************
4908 Scroll bars, general
4909 ************************************************************************/
4911 /* Create a scroll bar and return the scroll bar vector for it. W is
4912 the Emacs window on which to create the scroll bar. TOP, LEFT,
4913 WIDTH and HEIGHT are the pixel coordinates and dimensions of the
4914 scroll bar. */
4916 static struct scroll_bar *
4917 x_scroll_bar_create (struct window *w, int top, int left, int width, int height)
4919 struct frame *f = XFRAME (w->frame);
4920 struct scroll_bar *bar
4921 = ALLOCATE_PSEUDOVECTOR (struct scroll_bar, x_window, PVEC_OTHER);
4922 Lisp_Object barobj;
4924 block_input ();
4926 #ifdef USE_TOOLKIT_SCROLL_BARS
4927 x_create_toolkit_scroll_bar (f, bar);
4928 #else /* not USE_TOOLKIT_SCROLL_BARS */
4930 XSetWindowAttributes a;
4931 unsigned long mask;
4932 Window window;
4934 a.background_pixel = f->output_data.x->scroll_bar_background_pixel;
4935 if (a.background_pixel == -1)
4936 a.background_pixel = FRAME_BACKGROUND_PIXEL (f);
4938 a.event_mask = (ButtonPressMask | ButtonReleaseMask
4939 | ButtonMotionMask | PointerMotionHintMask
4940 | ExposureMask);
4941 a.cursor = FRAME_DISPLAY_INFO (f)->vertical_scroll_bar_cursor;
4943 mask = (CWBackPixel | CWEventMask | CWCursor);
4945 /* Clear the area of W that will serve as a scroll bar. This is
4946 for the case that a window has been split horizontally. In
4947 this case, no clear_frame is generated to reduce flickering. */
4948 if (width > 0 && height > 0)
4949 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4950 left, top, width, window_box_height (w));
4952 window = XCreateWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4953 /* Position and size of scroll bar. */
4954 left, top, width, height,
4955 /* Border width, depth, class, and visual. */
4957 CopyFromParent,
4958 CopyFromParent,
4959 CopyFromParent,
4960 /* Attributes. */
4961 mask, &a);
4962 bar->x_window = window;
4964 #endif /* not USE_TOOLKIT_SCROLL_BARS */
4966 XSETWINDOW (bar->window, w);
4967 bar->top = top;
4968 bar->left = left;
4969 bar->width = width;
4970 bar->height = height;
4971 bar->start = 0;
4972 bar->end = 0;
4973 bar->dragging = -1;
4974 bar->fringe_extended_p = 0;
4975 #if defined (USE_TOOLKIT_SCROLL_BARS) && defined (USE_LUCID)
4976 bar->last_seen_part = scroll_bar_nowhere;
4977 #endif
4979 /* Add bar to its frame's list of scroll bars. */
4980 bar->next = FRAME_SCROLL_BARS (f);
4981 bar->prev = Qnil;
4982 XSETVECTOR (barobj, bar);
4983 fset_scroll_bars (f, barobj);
4984 if (!NILP (bar->next))
4985 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
4987 /* Map the window/widget. */
4988 #ifdef USE_TOOLKIT_SCROLL_BARS
4990 #ifdef USE_GTK
4991 xg_update_scrollbar_pos (f, bar->x_window, top,
4992 left,width, max (height, 1));
4993 #else /* not USE_GTK */
4994 Widget scroll_bar = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
4995 XtConfigureWidget (scroll_bar, left, top, width, max (height, 1), 0);
4996 XtMapWidget (scroll_bar);
4997 #endif /* not USE_GTK */
4999 #else /* not USE_TOOLKIT_SCROLL_BARS */
5000 XMapRaised (FRAME_X_DISPLAY (f), bar->x_window);
5001 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5003 unblock_input ();
5004 return bar;
5008 #ifndef USE_TOOLKIT_SCROLL_BARS
5010 /* Draw BAR's handle in the proper position.
5012 If the handle is already drawn from START to END, don't bother
5013 redrawing it, unless REBUILD is non-zero; in that case, always
5014 redraw it. (REBUILD is handy for drawing the handle after expose
5015 events.)
5017 Normally, we want to constrain the start and end of the handle to
5018 fit inside its rectangle, but if the user is dragging the scroll
5019 bar handle, we want to let them drag it down all the way, so that
5020 the bar's top is as far down as it goes; otherwise, there's no way
5021 to move to the very end of the buffer. */
5023 static void
5024 x_scroll_bar_set_handle (struct scroll_bar *bar, int start, int end, int rebuild)
5026 bool dragging = bar->dragging != -1;
5027 Window w = bar->x_window;
5028 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5029 GC gc = f->output_data.x->normal_gc;
5031 /* If the display is already accurate, do nothing. */
5032 if (! rebuild
5033 && start == bar->start
5034 && end == bar->end)
5035 return;
5037 block_input ();
5040 int inside_width = VERTICAL_SCROLL_BAR_INSIDE_WIDTH (f, bar->width);
5041 int inside_height = VERTICAL_SCROLL_BAR_INSIDE_HEIGHT (f, bar->height);
5042 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
5044 /* Make sure the values are reasonable, and try to preserve
5045 the distance between start and end. */
5047 int length = end - start;
5049 if (start < 0)
5050 start = 0;
5051 else if (start > top_range)
5052 start = top_range;
5053 end = start + length;
5055 if (end < start)
5056 end = start;
5057 else if (end > top_range && ! dragging)
5058 end = top_range;
5061 /* Store the adjusted setting in the scroll bar. */
5062 bar->start = start;
5063 bar->end = end;
5065 /* Clip the end position, just for display. */
5066 if (end > top_range)
5067 end = top_range;
5069 /* Draw bottom positions VERTICAL_SCROLL_BAR_MIN_HANDLE pixels
5070 below top positions, to make sure the handle is always at least
5071 that many pixels tall. */
5072 end += VERTICAL_SCROLL_BAR_MIN_HANDLE;
5074 /* Draw the empty space above the handle. Note that we can't clear
5075 zero-height areas; that means "clear to end of window." */
5076 if (start > 0)
5077 x_clear_area (FRAME_X_DISPLAY (f), w,
5078 VERTICAL_SCROLL_BAR_LEFT_BORDER,
5079 VERTICAL_SCROLL_BAR_TOP_BORDER,
5080 inside_width, start);
5082 /* Change to proper foreground color if one is specified. */
5083 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5084 XSetForeground (FRAME_X_DISPLAY (f), gc,
5085 f->output_data.x->scroll_bar_foreground_pixel);
5087 /* Draw the handle itself. */
5088 XFillRectangle (FRAME_X_DISPLAY (f), w, gc,
5089 /* x, y, width, height */
5090 VERTICAL_SCROLL_BAR_LEFT_BORDER,
5091 VERTICAL_SCROLL_BAR_TOP_BORDER + start,
5092 inside_width, end - start);
5094 /* Restore the foreground color of the GC if we changed it above. */
5095 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5096 XSetForeground (FRAME_X_DISPLAY (f), gc,
5097 FRAME_FOREGROUND_PIXEL (f));
5099 /* Draw the empty space below the handle. Note that we can't
5100 clear zero-height areas; that means "clear to end of window." */
5101 if (end < inside_height)
5102 x_clear_area (FRAME_X_DISPLAY (f), w,
5103 VERTICAL_SCROLL_BAR_LEFT_BORDER,
5104 VERTICAL_SCROLL_BAR_TOP_BORDER + end,
5105 inside_width, inside_height - end);
5108 unblock_input ();
5111 #endif /* !USE_TOOLKIT_SCROLL_BARS */
5113 /* Destroy scroll bar BAR, and set its Emacs window's scroll bar to
5114 nil. */
5116 static void
5117 x_scroll_bar_remove (struct scroll_bar *bar)
5119 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5120 block_input ();
5122 #ifdef USE_TOOLKIT_SCROLL_BARS
5123 #ifdef USE_GTK
5124 xg_remove_scroll_bar (f, bar->x_window);
5125 #else /* not USE_GTK */
5126 XtDestroyWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar));
5127 #endif /* not USE_GTK */
5128 #else
5129 XDestroyWindow (FRAME_X_DISPLAY (f), bar->x_window);
5130 #endif
5132 /* Dissociate this scroll bar from its window. */
5133 wset_vertical_scroll_bar (XWINDOW (bar->window), Qnil);
5135 unblock_input ();
5139 /* Set the handle of the vertical scroll bar for WINDOW to indicate
5140 that we are displaying PORTION characters out of a total of WHOLE
5141 characters, starting at POSITION. If WINDOW has no scroll bar,
5142 create one. */
5144 static void
5145 XTset_vertical_scroll_bar (struct window *w, int portion, int whole, int position)
5147 struct frame *f = XFRAME (w->frame);
5148 Lisp_Object barobj;
5149 struct scroll_bar *bar;
5150 int top, height, left, sb_left, width, sb_width;
5151 int window_y, window_height;
5152 #ifdef USE_TOOLKIT_SCROLL_BARS
5153 bool fringe_extended_p;
5154 #endif
5156 /* Get window dimensions. */
5157 window_box (w, ANY_AREA, 0, &window_y, 0, &window_height);
5158 top = window_y;
5159 width = WINDOW_CONFIG_SCROLL_BAR_COLS (w) * FRAME_COLUMN_WIDTH (f);
5160 height = window_height;
5162 /* Compute the left edge of the scroll bar area. */
5163 left = WINDOW_SCROLL_BAR_AREA_X (w);
5165 /* Compute the width of the scroll bar which might be less than
5166 the width of the area reserved for the scroll bar. */
5167 if (WINDOW_CONFIG_SCROLL_BAR_WIDTH (w) > 0)
5168 sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
5169 else
5170 sb_width = width;
5172 /* Compute the left edge of the scroll bar. */
5173 #ifdef USE_TOOLKIT_SCROLL_BARS
5174 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w))
5175 sb_left = left + (WINDOW_RIGHTMOST_P (w) ? width - sb_width : 0);
5176 else
5177 sb_left = left + (WINDOW_LEFTMOST_P (w) ? 0 : width - sb_width);
5178 #else
5179 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w))
5180 sb_left = left + width - sb_width;
5181 else
5182 sb_left = left;
5183 #endif
5185 #ifdef USE_TOOLKIT_SCROLL_BARS
5186 fringe_extended_p = WINDOW_FRINGE_EXTENDED_P (w);
5187 #endif
5189 /* Does the scroll bar exist yet? */
5190 if (NILP (w->vertical_scroll_bar))
5192 if (width > 0 && height > 0)
5194 block_input ();
5195 #ifdef USE_TOOLKIT_SCROLL_BARS
5196 if (fringe_extended_p)
5197 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5198 sb_left, top, sb_width, height);
5199 else
5200 #endif
5201 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5202 left, top, width, height);
5203 unblock_input ();
5206 bar = x_scroll_bar_create (w, top, sb_left, sb_width, height);
5208 else
5210 /* It may just need to be moved and resized. */
5211 unsigned int mask = 0;
5213 bar = XSCROLL_BAR (w->vertical_scroll_bar);
5215 block_input ();
5217 if (sb_left != bar->left)
5218 mask |= CWX;
5219 if (top != bar->top)
5220 mask |= CWY;
5221 if (sb_width != bar->width)
5222 mask |= CWWidth;
5223 if (height != bar->height)
5224 mask |= CWHeight;
5226 #ifdef USE_TOOLKIT_SCROLL_BARS
5228 /* Move/size the scroll bar widget. */
5229 if (mask || bar->fringe_extended_p != fringe_extended_p)
5231 /* Since toolkit scroll bars are smaller than the space reserved
5232 for them on the frame, we have to clear "under" them. */
5233 if (width > 0 && height > 0)
5235 if (fringe_extended_p)
5236 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5237 sb_left, top, sb_width, height);
5238 else
5239 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5240 left, top, width, height);
5242 #ifdef USE_GTK
5243 xg_update_scrollbar_pos (f, bar->x_window, top,
5244 sb_left, sb_width, max (height, 1));
5245 #else /* not USE_GTK */
5246 XtConfigureWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar),
5247 sb_left, top, sb_width, max (height, 1), 0);
5248 #endif /* not USE_GTK */
5250 #else /* not USE_TOOLKIT_SCROLL_BARS */
5252 /* Clear areas not covered by the scroll bar because it's not as
5253 wide as the area reserved for it. This makes sure a
5254 previous mode line display is cleared after C-x 2 C-x 1, for
5255 example. */
5257 int area_width = WINDOW_CONFIG_SCROLL_BAR_COLS (w) * FRAME_COLUMN_WIDTH (f);
5258 int rest = area_width - sb_width;
5259 if (rest > 0 && height > 0)
5261 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
5262 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5263 left + area_width - rest, top, rest, height);
5264 else
5265 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5266 left, top, rest, height);
5270 /* Move/size the scroll bar window. */
5271 if (mask)
5273 XWindowChanges wc;
5275 wc.x = sb_left;
5276 wc.y = top;
5277 wc.width = sb_width;
5278 wc.height = height;
5279 XConfigureWindow (FRAME_X_DISPLAY (f), bar->x_window,
5280 mask, &wc);
5283 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5285 /* Remember new settings. */
5286 bar->left = sb_left;
5287 bar->top = top;
5288 bar->width = sb_width;
5289 bar->height = height;
5291 unblock_input ();
5294 #ifdef USE_TOOLKIT_SCROLL_BARS
5295 bar->fringe_extended_p = fringe_extended_p;
5297 x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
5298 #else /* not USE_TOOLKIT_SCROLL_BARS */
5299 /* Set the scroll bar's current state, unless we're currently being
5300 dragged. */
5301 if (bar->dragging == -1)
5303 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, height);
5305 if (whole == 0)
5306 x_scroll_bar_set_handle (bar, 0, top_range, 0);
5307 else
5309 int start = ((double) position * top_range) / whole;
5310 int end = ((double) (position + portion) * top_range) / whole;
5311 x_scroll_bar_set_handle (bar, start, end, 0);
5314 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5316 XSETVECTOR (barobj, bar);
5317 wset_vertical_scroll_bar (w, barobj);
5321 /* The following three hooks are used when we're doing a thorough
5322 redisplay of the frame. We don't explicitly know which scroll bars
5323 are going to be deleted, because keeping track of when windows go
5324 away is a real pain - "Can you say set-window-configuration, boys
5325 and girls?" Instead, we just assert at the beginning of redisplay
5326 that *all* scroll bars are to be removed, and then save a scroll bar
5327 from the fiery pit when we actually redisplay its window. */
5329 /* Arrange for all scroll bars on FRAME to be removed at the next call
5330 to `*judge_scroll_bars_hook'. A scroll bar may be spared if
5331 `*redeem_scroll_bar_hook' is applied to its window before the judgment. */
5333 static void
5334 XTcondemn_scroll_bars (struct frame *frame)
5336 /* Transfer all the scroll bars to FRAME_CONDEMNED_SCROLL_BARS. */
5337 while (! NILP (FRAME_SCROLL_BARS (frame)))
5339 Lisp_Object bar;
5340 bar = FRAME_SCROLL_BARS (frame);
5341 fset_scroll_bars (frame, XSCROLL_BAR (bar)->next);
5342 XSCROLL_BAR (bar)->next = FRAME_CONDEMNED_SCROLL_BARS (frame);
5343 XSCROLL_BAR (bar)->prev = Qnil;
5344 if (! NILP (FRAME_CONDEMNED_SCROLL_BARS (frame)))
5345 XSCROLL_BAR (FRAME_CONDEMNED_SCROLL_BARS (frame))->prev = bar;
5346 fset_condemned_scroll_bars (frame, bar);
5351 /* Un-mark WINDOW's scroll bar for deletion in this judgment cycle.
5352 Note that WINDOW isn't necessarily condemned at all. */
5354 static void
5355 XTredeem_scroll_bar (struct window *window)
5357 struct scroll_bar *bar;
5358 struct frame *f;
5359 Lisp_Object barobj;
5361 /* We can't redeem this window's scroll bar if it doesn't have one. */
5362 if (NILP (window->vertical_scroll_bar))
5363 emacs_abort ();
5365 bar = XSCROLL_BAR (window->vertical_scroll_bar);
5367 /* Unlink it from the condemned list. */
5368 f = XFRAME (WINDOW_FRAME (window));
5369 if (NILP (bar->prev))
5371 /* If the prev pointer is nil, it must be the first in one of
5372 the lists. */
5373 if (EQ (FRAME_SCROLL_BARS (f), window->vertical_scroll_bar))
5374 /* It's not condemned. Everything's fine. */
5375 return;
5376 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
5377 window->vertical_scroll_bar))
5378 fset_condemned_scroll_bars (f, bar->next);
5379 else
5380 /* If its prev pointer is nil, it must be at the front of
5381 one or the other! */
5382 emacs_abort ();
5384 else
5385 XSCROLL_BAR (bar->prev)->next = bar->next;
5387 if (! NILP (bar->next))
5388 XSCROLL_BAR (bar->next)->prev = bar->prev;
5390 bar->next = FRAME_SCROLL_BARS (f);
5391 bar->prev = Qnil;
5392 XSETVECTOR (barobj, bar);
5393 fset_scroll_bars (f, barobj);
5394 if (! NILP (bar->next))
5395 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
5398 /* Remove all scroll bars on FRAME that haven't been saved since the
5399 last call to `*condemn_scroll_bars_hook'. */
5401 static void
5402 XTjudge_scroll_bars (struct frame *f)
5404 Lisp_Object bar, next;
5406 bar = FRAME_CONDEMNED_SCROLL_BARS (f);
5408 /* Clear out the condemned list now so we won't try to process any
5409 more events on the hapless scroll bars. */
5410 fset_condemned_scroll_bars (f, Qnil);
5412 for (; ! NILP (bar); bar = next)
5414 struct scroll_bar *b = XSCROLL_BAR (bar);
5416 x_scroll_bar_remove (b);
5418 next = b->next;
5419 b->next = b->prev = Qnil;
5422 /* Now there should be no references to the condemned scroll bars,
5423 and they should get garbage-collected. */
5427 #ifndef USE_TOOLKIT_SCROLL_BARS
5428 /* Handle an Expose or GraphicsExpose event on a scroll bar. This
5429 is a no-op when using toolkit scroll bars.
5431 This may be called from a signal handler, so we have to ignore GC
5432 mark bits. */
5434 static void
5435 x_scroll_bar_expose (struct scroll_bar *bar, const XEvent *event)
5437 Window w = bar->x_window;
5438 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5439 GC gc = f->output_data.x->normal_gc;
5441 block_input ();
5443 x_scroll_bar_set_handle (bar, bar->start, bar->end, 1);
5445 /* Switch to scroll bar foreground color. */
5446 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5447 XSetForeground (FRAME_X_DISPLAY (f), gc,
5448 f->output_data.x->scroll_bar_foreground_pixel);
5450 /* Draw a one-pixel border just inside the edges of the scroll bar. */
5451 XDrawRectangle (FRAME_X_DISPLAY (f), w, gc,
5452 /* x, y, width, height */
5453 0, 0, bar->width - 1, bar->height - 1);
5455 /* Restore the foreground color of the GC if we changed it above. */
5456 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5457 XSetForeground (FRAME_X_DISPLAY (f), gc,
5458 FRAME_FOREGROUND_PIXEL (f));
5460 unblock_input ();
5463 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5465 /* Handle a mouse click on the scroll bar BAR. If *EMACS_EVENT's kind
5466 is set to something other than NO_EVENT, it is enqueued.
5468 This may be called from a signal handler, so we have to ignore GC
5469 mark bits. */
5472 static void
5473 x_scroll_bar_handle_click (struct scroll_bar *bar,
5474 const XEvent *event,
5475 struct input_event *emacs_event)
5477 if (! WINDOWP (bar->window))
5478 emacs_abort ();
5480 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
5481 emacs_event->code = event->xbutton.button - Button1;
5482 emacs_event->modifiers
5483 = (x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO
5484 (XFRAME (WINDOW_FRAME (XWINDOW (bar->window)))),
5485 event->xbutton.state)
5486 | (event->type == ButtonRelease
5487 ? up_modifier
5488 : down_modifier));
5489 emacs_event->frame_or_window = bar->window;
5490 emacs_event->arg = Qnil;
5491 emacs_event->timestamp = event->xbutton.time;
5493 int top_range
5494 = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
5495 int y = event->xbutton.y - VERTICAL_SCROLL_BAR_TOP_BORDER;
5497 if (y < 0) y = 0;
5498 if (y > top_range) y = top_range;
5500 if (y < bar->start)
5501 emacs_event->part = scroll_bar_above_handle;
5502 else if (y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
5503 emacs_event->part = scroll_bar_handle;
5504 else
5505 emacs_event->part = scroll_bar_below_handle;
5507 #ifndef USE_TOOLKIT_SCROLL_BARS
5508 /* If the user has released the handle, set it to its final position. */
5509 if (event->type == ButtonRelease && bar->dragging != -1)
5511 int new_start = y - bar->dragging;
5512 int new_end = new_start + bar->end - bar->start;
5514 x_scroll_bar_set_handle (bar, new_start, new_end, 0);
5515 bar->dragging = -1;
5517 #endif
5519 XSETINT (emacs_event->x, y);
5520 XSETINT (emacs_event->y, top_range);
5524 #ifndef USE_TOOLKIT_SCROLL_BARS
5526 /* Handle some mouse motion while someone is dragging the scroll bar.
5528 This may be called from a signal handler, so we have to ignore GC
5529 mark bits. */
5531 static void
5532 x_scroll_bar_note_movement (struct scroll_bar *bar,
5533 const XMotionEvent *event)
5535 struct frame *f = XFRAME (XWINDOW (bar->window)->frame);
5536 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
5538 dpyinfo->last_mouse_movement_time = event->time;
5539 dpyinfo->last_mouse_scroll_bar = bar;
5540 f->mouse_moved = 1;
5542 /* If we're dragging the bar, display it. */
5543 if (bar->dragging != -1)
5545 /* Where should the handle be now? */
5546 int new_start = event->y - bar->dragging;
5548 if (new_start != bar->start)
5550 int new_end = new_start + bar->end - bar->start;
5552 x_scroll_bar_set_handle (bar, new_start, new_end, 0);
5557 #endif /* !USE_TOOLKIT_SCROLL_BARS */
5559 /* Return information to the user about the current position of the mouse
5560 on the scroll bar. */
5562 static void
5563 x_scroll_bar_report_motion (struct frame **fp, Lisp_Object *bar_window,
5564 enum scroll_bar_part *part, Lisp_Object *x,
5565 Lisp_Object *y, Time *timestamp)
5567 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (*fp);
5568 struct scroll_bar *bar = dpyinfo->last_mouse_scroll_bar;
5569 Window w = bar->x_window;
5570 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5571 int win_x, win_y;
5572 Window dummy_window;
5573 int dummy_coord;
5574 unsigned int dummy_mask;
5576 block_input ();
5578 /* Get the mouse's position relative to the scroll bar window, and
5579 report that. */
5580 if (XQueryPointer (FRAME_X_DISPLAY (f), w,
5582 /* Root, child, root x and root y. */
5583 &dummy_window, &dummy_window,
5584 &dummy_coord, &dummy_coord,
5586 /* Position relative to scroll bar. */
5587 &win_x, &win_y,
5589 /* Mouse buttons and modifier keys. */
5590 &dummy_mask))
5592 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
5594 win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
5596 if (bar->dragging != -1)
5597 win_y -= bar->dragging;
5599 if (win_y < 0)
5600 win_y = 0;
5601 if (win_y > top_range)
5602 win_y = top_range;
5604 *fp = f;
5605 *bar_window = bar->window;
5607 if (bar->dragging != -1)
5608 *part = scroll_bar_handle;
5609 else if (win_y < bar->start)
5610 *part = scroll_bar_above_handle;
5611 else if (win_y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
5612 *part = scroll_bar_handle;
5613 else
5614 *part = scroll_bar_below_handle;
5616 XSETINT (*x, win_y);
5617 XSETINT (*y, top_range);
5619 f->mouse_moved = 0;
5620 dpyinfo->last_mouse_scroll_bar = NULL;
5621 *timestamp = dpyinfo->last_mouse_movement_time;
5624 unblock_input ();
5628 /* The screen has been cleared so we may have changed foreground or
5629 background colors, and the scroll bars may need to be redrawn.
5630 Clear out the scroll bars, and ask for expose events, so we can
5631 redraw them. */
5633 static void
5634 x_scroll_bar_clear (struct frame *f)
5636 #ifndef USE_TOOLKIT_SCROLL_BARS
5637 Lisp_Object bar;
5639 /* We can have scroll bars even if this is 0,
5640 if we just turned off scroll bar mode.
5641 But in that case we should not clear them. */
5642 if (FRAME_HAS_VERTICAL_SCROLL_BARS (f))
5643 for (bar = FRAME_SCROLL_BARS (f); VECTORP (bar);
5644 bar = XSCROLL_BAR (bar)->next)
5645 XClearArea (FRAME_X_DISPLAY (f),
5646 XSCROLL_BAR (bar)->x_window,
5647 0, 0, 0, 0, True);
5648 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5651 #ifdef ENABLE_CHECKING
5653 /* Record the last 100 characters stored
5654 to help debug the loss-of-chars-during-GC problem. */
5656 static int temp_index;
5657 static short temp_buffer[100];
5659 #define STORE_KEYSYM_FOR_DEBUG(keysym) \
5660 if (temp_index == sizeof temp_buffer / sizeof (short)) \
5661 temp_index = 0; \
5662 temp_buffer[temp_index++] = (keysym)
5664 #else /* not ENABLE_CHECKING */
5666 #define STORE_KEYSYM_FOR_DEBUG(keysym) ((void)0)
5668 #endif /* ENABLE_CHECKING */
5670 /* Set this to nonzero to fake an "X I/O error"
5671 on a particular display. */
5673 static struct x_display_info *XTread_socket_fake_io_error;
5675 /* When we find no input here, we occasionally do a no-op command
5676 to verify that the X server is still running and we can still talk with it.
5677 We try all the open displays, one by one.
5678 This variable is used for cycling thru the displays. */
5680 static struct x_display_info *next_noop_dpyinfo;
5682 enum
5684 X_EVENT_NORMAL,
5685 X_EVENT_GOTO_OUT,
5686 X_EVENT_DROP
5689 /* Filter events for the current X input method.
5690 DPYINFO is the display this event is for.
5691 EVENT is the X event to filter.
5693 Returns non-zero if the event was filtered, caller shall not process
5694 this event further.
5695 Returns zero if event is wasn't filtered. */
5697 #ifdef HAVE_X_I18N
5698 static int
5699 x_filter_event (struct x_display_info *dpyinfo, XEvent *event)
5701 /* XFilterEvent returns non-zero if the input method has
5702 consumed the event. We pass the frame's X window to
5703 XFilterEvent because that's the one for which the IC
5704 was created. */
5706 struct frame *f1 = x_any_window_to_frame (dpyinfo,
5707 event->xclient.window);
5709 return XFilterEvent (event, f1 ? FRAME_X_WINDOW (f1) : None);
5711 #endif
5713 #ifdef USE_GTK
5714 static int current_count;
5715 static int current_finish;
5716 static struct input_event *current_hold_quit;
5718 /* This is the filter function invoked by the GTK event loop.
5719 It is invoked before the XEvent is translated to a GdkEvent,
5720 so we have a chance to act on the event before GTK. */
5721 static GdkFilterReturn
5722 event_handler_gdk (GdkXEvent *gxev, GdkEvent *ev, gpointer data)
5724 XEvent *xev = (XEvent *) gxev;
5726 block_input ();
5727 if (current_count >= 0)
5729 struct x_display_info *dpyinfo;
5731 dpyinfo = x_display_info_for_display (xev->xany.display);
5733 #ifdef HAVE_X_I18N
5734 /* Filter events for the current X input method.
5735 GTK calls XFilterEvent but not for key press and release,
5736 so we do it here. */
5737 if ((xev->type == KeyPress || xev->type == KeyRelease)
5738 && dpyinfo
5739 && x_filter_event (dpyinfo, xev))
5741 unblock_input ();
5742 return GDK_FILTER_REMOVE;
5744 #endif
5746 if (! dpyinfo)
5747 current_finish = X_EVENT_NORMAL;
5748 else
5749 current_count +=
5750 handle_one_xevent (dpyinfo, xev, &current_finish,
5751 current_hold_quit);
5753 else
5754 current_finish = x_dispatch_event (xev, xev->xany.display);
5756 unblock_input ();
5758 if (current_finish == X_EVENT_GOTO_OUT || current_finish == X_EVENT_DROP)
5759 return GDK_FILTER_REMOVE;
5761 return GDK_FILTER_CONTINUE;
5763 #endif /* USE_GTK */
5766 static void xembed_send_message (struct frame *f, Time,
5767 enum xembed_message,
5768 long detail, long data1, long data2);
5770 /* Handles the XEvent EVENT on display DPYINFO.
5772 *FINISH is X_EVENT_GOTO_OUT if caller should stop reading events.
5773 *FINISH is zero if caller should continue reading events.
5774 *FINISH is X_EVENT_DROP if event should not be passed to the toolkit.
5775 *EVENT is unchanged unless we're processing KeyPress event.
5777 We return the number of characters stored into the buffer. */
5779 static int
5780 handle_one_xevent (struct x_display_info *dpyinfo,
5781 const XEvent *event,
5782 int *finish, struct input_event *hold_quit)
5784 union {
5785 struct input_event ie;
5786 struct selection_input_event sie;
5787 } inev;
5788 int count = 0;
5789 int do_help = 0;
5790 ptrdiff_t nbytes = 0;
5791 struct frame *any, *f = NULL;
5792 struct coding_system coding;
5793 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
5794 /* This holds the state XLookupString needs to implement dead keys
5795 and other tricks known as "compose processing". _X Window System_
5796 says that a portable program can't use this, but Stephen Gildea assures
5797 me that letting the compiler initialize it to zeros will work okay. */
5798 static XComposeStatus compose_status;
5800 USE_SAFE_ALLOCA;
5802 *finish = X_EVENT_NORMAL;
5804 EVENT_INIT (inev.ie);
5805 inev.ie.kind = NO_EVENT;
5806 inev.ie.arg = Qnil;
5808 any = x_any_window_to_frame (dpyinfo, event->xany.window);
5810 if (any && any->wait_event_type == event->type)
5811 any->wait_event_type = 0; /* Indicates we got it. */
5813 switch (event->type)
5815 case ClientMessage:
5817 if (event->xclient.message_type == dpyinfo->Xatom_wm_protocols
5818 && event->xclient.format == 32)
5820 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_take_focus)
5822 /* Use the value returned by x_any_window_to_frame
5823 because this could be the shell widget window
5824 if the frame has no title bar. */
5825 f = any;
5826 #ifdef HAVE_X_I18N
5827 /* Not quite sure this is needed -pd */
5828 if (f && FRAME_XIC (f))
5829 XSetICFocus (FRAME_XIC (f));
5830 #endif
5831 #if 0 /* Emacs sets WM hints whose `input' field is `true'. This
5832 instructs the WM to set the input focus automatically for
5833 Emacs with a call to XSetInputFocus. Setting WM_TAKE_FOCUS
5834 tells the WM to send us a ClientMessage WM_TAKE_FOCUS after
5835 it has set the focus. So, XSetInputFocus below is not
5836 needed.
5838 The call to XSetInputFocus below has also caused trouble. In
5839 cases where the XSetInputFocus done by the WM and the one
5840 below are temporally close (on a fast machine), the call
5841 below can generate additional FocusIn events which confuse
5842 Emacs. */
5844 /* Since we set WM_TAKE_FOCUS, we must call
5845 XSetInputFocus explicitly. But not if f is null,
5846 since that might be an event for a deleted frame. */
5847 if (f)
5849 Display *d = event->xclient.display;
5850 /* Catch and ignore errors, in case window has been
5851 iconified by a window manager such as GWM. */
5852 x_catch_errors (d);
5853 XSetInputFocus (d, event->xclient.window,
5854 /* The ICCCM says this is
5855 the only valid choice. */
5856 RevertToParent,
5857 event->xclient.data.l[1]);
5858 /* This is needed to detect the error
5859 if there is an error. */
5860 XSync (d, False);
5861 x_uncatch_errors ();
5863 /* Not certain about handling scroll bars here */
5864 #endif /* 0 */
5865 goto done;
5868 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_save_yourself)
5870 /* Save state modify the WM_COMMAND property to
5871 something which can reinstate us. This notifies
5872 the session manager, who's looking for such a
5873 PropertyNotify. Can restart processing when
5874 a keyboard or mouse event arrives. */
5875 /* If we have a session manager, don't set this.
5876 KDE will then start two Emacsen, one for the
5877 session manager and one for this. */
5878 #ifdef HAVE_X_SM
5879 if (! x_session_have_connection ())
5880 #endif
5882 f = x_top_window_to_frame (dpyinfo,
5883 event->xclient.window);
5884 /* This is just so we only give real data once
5885 for a single Emacs process. */
5886 if (f == SELECTED_FRAME ())
5887 XSetCommand (FRAME_X_DISPLAY (f),
5888 event->xclient.window,
5889 initial_argv, initial_argc);
5890 else if (f)
5891 XSetCommand (FRAME_X_DISPLAY (f),
5892 event->xclient.window,
5893 0, 0);
5895 goto done;
5898 if (event->xclient.data.l[0] == dpyinfo->Xatom_wm_delete_window)
5900 f = any;
5901 if (!f)
5902 goto OTHER; /* May be a dialog that is to be removed */
5904 inev.ie.kind = DELETE_WINDOW_EVENT;
5905 XSETFRAME (inev.ie.frame_or_window, f);
5906 goto done;
5909 goto done;
5912 if (event->xclient.message_type == dpyinfo->Xatom_wm_configure_denied)
5913 goto done;
5915 if (event->xclient.message_type == dpyinfo->Xatom_wm_window_moved)
5917 int new_x, new_y;
5918 f = x_window_to_frame (dpyinfo, event->xclient.window);
5920 new_x = event->xclient.data.s[0];
5921 new_y = event->xclient.data.s[1];
5923 if (f)
5925 f->left_pos = new_x;
5926 f->top_pos = new_y;
5928 goto done;
5931 #ifdef HACK_EDITRES
5932 if (event->xclient.message_type == dpyinfo->Xatom_editres)
5934 f = any;
5935 if (f)
5936 _XEditResCheckMessages (f->output_data.x->widget,
5937 NULL, (XEvent *) event, NULL);
5938 goto done;
5940 #endif /* HACK_EDITRES */
5942 if (event->xclient.message_type == dpyinfo->Xatom_DONE
5943 || event->xclient.message_type == dpyinfo->Xatom_PAGE)
5945 /* Ghostview job completed. Kill it. We could
5946 reply with "Next" if we received "Page", but we
5947 currently never do because we are interested in
5948 images, only, which should have 1 page. */
5949 Pixmap pixmap = (Pixmap) event->xclient.data.l[1];
5950 f = x_window_to_frame (dpyinfo, event->xclient.window);
5951 if (!f)
5952 goto OTHER;
5953 x_kill_gs_process (pixmap, f);
5954 expose_frame (f, 0, 0, 0, 0);
5955 goto done;
5958 #ifdef USE_TOOLKIT_SCROLL_BARS
5959 /* Scroll bar callbacks send a ClientMessage from which
5960 we construct an input_event. */
5961 if (event->xclient.message_type == dpyinfo->Xatom_Scrollbar)
5963 x_scroll_bar_to_input_event (event, &inev.ie);
5964 *finish = X_EVENT_GOTO_OUT;
5965 goto done;
5967 #endif /* USE_TOOLKIT_SCROLL_BARS */
5969 /* XEmbed messages from the embedder (if any). */
5970 if (event->xclient.message_type == dpyinfo->Xatom_XEMBED)
5972 enum xembed_message msg = event->xclient.data.l[1];
5973 if (msg == XEMBED_FOCUS_IN || msg == XEMBED_FOCUS_OUT)
5974 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
5976 *finish = X_EVENT_GOTO_OUT;
5977 goto done;
5980 xft_settings_event (dpyinfo, event);
5982 f = any;
5983 if (!f)
5984 goto OTHER;
5985 if (x_handle_dnd_message (f, &event->xclient, dpyinfo, &inev.ie))
5986 *finish = X_EVENT_DROP;
5988 break;
5990 case SelectionNotify:
5991 dpyinfo->last_user_time = event->xselection.time;
5992 #ifdef USE_X_TOOLKIT
5993 if (! x_window_to_frame (dpyinfo, event->xselection.requestor))
5994 goto OTHER;
5995 #endif /* not USE_X_TOOLKIT */
5996 x_handle_selection_notify (&event->xselection);
5997 break;
5999 case SelectionClear: /* Someone has grabbed ownership. */
6000 dpyinfo->last_user_time = event->xselectionclear.time;
6001 #ifdef USE_X_TOOLKIT
6002 if (! x_window_to_frame (dpyinfo, event->xselectionclear.window))
6003 goto OTHER;
6004 #endif /* USE_X_TOOLKIT */
6006 const XSelectionClearEvent *eventp = &event->xselectionclear;
6008 inev.ie.kind = SELECTION_CLEAR_EVENT;
6009 SELECTION_EVENT_DISPLAY (&inev.sie) = eventp->display;
6010 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
6011 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
6013 break;
6015 case SelectionRequest: /* Someone wants our selection. */
6016 dpyinfo->last_user_time = event->xselectionrequest.time;
6017 #ifdef USE_X_TOOLKIT
6018 if (!x_window_to_frame (dpyinfo, event->xselectionrequest.owner))
6019 goto OTHER;
6020 #endif /* USE_X_TOOLKIT */
6022 const XSelectionRequestEvent *eventp = &event->xselectionrequest;
6024 inev.ie.kind = SELECTION_REQUEST_EVENT;
6025 SELECTION_EVENT_DISPLAY (&inev.sie) = eventp->display;
6026 SELECTION_EVENT_REQUESTOR (&inev.sie) = eventp->requestor;
6027 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
6028 SELECTION_EVENT_TARGET (&inev.sie) = eventp->target;
6029 SELECTION_EVENT_PROPERTY (&inev.sie) = eventp->property;
6030 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
6032 break;
6034 case PropertyNotify:
6035 dpyinfo->last_user_time = event->xproperty.time;
6036 f = x_top_window_to_frame (dpyinfo, event->xproperty.window);
6037 if (f && event->xproperty.atom == dpyinfo->Xatom_net_wm_state)
6038 if (x_handle_net_wm_state (f, &event->xproperty)
6039 && FRAME_ICONIFIED_P (f)
6040 && f->output_data.x->net_wm_state_hidden_seen)
6042 /* Gnome shell does not iconify us when C-z is pressed.
6043 It hides the frame. So if our state says we aren't
6044 hidden anymore, treat it as deiconified. */
6045 SET_FRAME_VISIBLE (f, 1);
6046 SET_FRAME_ICONIFIED (f, 0);
6047 f->output_data.x->has_been_visible = 1;
6048 f->output_data.x->net_wm_state_hidden_seen = 0;
6049 inev.ie.kind = DEICONIFY_EVENT;
6050 XSETFRAME (inev.ie.frame_or_window, f);
6053 x_handle_property_notify (&event->xproperty);
6054 xft_settings_event (dpyinfo, event);
6055 goto OTHER;
6057 case ReparentNotify:
6058 f = x_top_window_to_frame (dpyinfo, event->xreparent.window);
6059 if (f)
6061 f->output_data.x->parent_desc = event->xreparent.parent;
6062 x_real_positions (f, &f->left_pos, &f->top_pos);
6064 /* Perhaps reparented due to a WM restart. Reset this. */
6065 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_UNKNOWN;
6066 FRAME_DISPLAY_INFO (f)->net_supported_window = 0;
6068 x_set_frame_alpha (f);
6070 goto OTHER;
6072 case Expose:
6073 f = x_window_to_frame (dpyinfo, event->xexpose.window);
6074 if (f)
6076 if (!FRAME_VISIBLE_P (f))
6078 SET_FRAME_VISIBLE (f, 1);
6079 SET_FRAME_ICONIFIED (f, 0);
6080 f->output_data.x->has_been_visible = 1;
6081 SET_FRAME_GARBAGED (f);
6083 else
6085 #ifdef USE_GTK
6086 /* This seems to be needed for GTK 2.6 and later, see
6087 http://debbugs.gnu.org/cgi/bugreport.cgi?bug=15398. */
6088 x_clear_area (event->xexpose.display,
6089 event->xexpose.window,
6090 event->xexpose.x, event->xexpose.y,
6091 event->xexpose.width, event->xexpose.height);
6092 #endif
6093 expose_frame (f, event->xexpose.x, event->xexpose.y,
6094 event->xexpose.width, event->xexpose.height);
6097 else
6099 #ifndef USE_TOOLKIT_SCROLL_BARS
6100 struct scroll_bar *bar;
6101 #endif
6102 #if defined USE_LUCID
6103 /* Submenus of the Lucid menu bar aren't widgets
6104 themselves, so there's no way to dispatch events
6105 to them. Recognize this case separately. */
6107 Widget widget = x_window_to_menu_bar (event->xexpose.window);
6108 if (widget)
6109 xlwmenu_redisplay (widget);
6111 #endif /* USE_LUCID */
6113 #ifdef USE_TOOLKIT_SCROLL_BARS
6114 /* Dispatch event to the widget. */
6115 goto OTHER;
6116 #else /* not USE_TOOLKIT_SCROLL_BARS */
6117 bar = x_window_to_scroll_bar (event->xexpose.display,
6118 event->xexpose.window);
6120 if (bar)
6121 x_scroll_bar_expose (bar, event);
6122 #ifdef USE_X_TOOLKIT
6123 else
6124 goto OTHER;
6125 #endif /* USE_X_TOOLKIT */
6126 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6128 break;
6130 case GraphicsExpose: /* This occurs when an XCopyArea's
6131 source area was obscured or not
6132 available. */
6133 f = x_window_to_frame (dpyinfo, event->xgraphicsexpose.drawable);
6134 if (f)
6135 expose_frame (f, event->xgraphicsexpose.x,
6136 event->xgraphicsexpose.y,
6137 event->xgraphicsexpose.width,
6138 event->xgraphicsexpose.height);
6139 #ifdef USE_X_TOOLKIT
6140 else
6141 goto OTHER;
6142 #endif /* USE_X_TOOLKIT */
6143 break;
6145 case NoExpose: /* This occurs when an XCopyArea's
6146 source area was completely
6147 available. */
6148 break;
6150 case UnmapNotify:
6151 /* Redo the mouse-highlight after the tooltip has gone. */
6152 if (event->xunmap.window == tip_window)
6154 tip_window = 0;
6155 x_redo_mouse_highlight (dpyinfo);
6158 f = x_top_window_to_frame (dpyinfo, event->xunmap.window);
6159 if (f) /* F may no longer exist if
6160 the frame was deleted. */
6162 bool visible = FRAME_VISIBLE_P (f);
6163 /* While a frame is unmapped, display generation is
6164 disabled; you don't want to spend time updating a
6165 display that won't ever be seen. */
6166 SET_FRAME_VISIBLE (f, 0);
6167 /* We can't distinguish, from the event, whether the window
6168 has become iconified or invisible. So assume, if it
6169 was previously visible, than now it is iconified.
6170 But x_make_frame_invisible clears both
6171 the visible flag and the iconified flag;
6172 and that way, we know the window is not iconified now. */
6173 if (visible || FRAME_ICONIFIED_P (f))
6175 SET_FRAME_ICONIFIED (f, 1);
6176 inev.ie.kind = ICONIFY_EVENT;
6177 XSETFRAME (inev.ie.frame_or_window, f);
6180 goto OTHER;
6182 case MapNotify:
6183 if (event->xmap.window == tip_window)
6184 /* The tooltip has been drawn already. Avoid
6185 the SET_FRAME_GARBAGED below. */
6186 goto OTHER;
6188 /* We use x_top_window_to_frame because map events can
6189 come for sub-windows and they don't mean that the
6190 frame is visible. */
6191 f = x_top_window_to_frame (dpyinfo, event->xmap.window);
6192 if (f)
6194 bool iconified = FRAME_ICONIFIED_P (f);
6195 /* wait_reading_process_output will notice this and update
6196 the frame's display structures.
6197 If we where iconified, we should not set garbaged,
6198 because that stops redrawing on Expose events. This looks
6199 bad if we are called from a recursive event loop
6200 (x_dispatch_event), for example when a dialog is up. */
6201 if (!iconified)
6202 SET_FRAME_GARBAGED (f);
6204 /* Check if fullscreen was specified before we where mapped the
6205 first time, i.e. from the command line. */
6206 if (!f->output_data.x->has_been_visible)
6207 x_check_fullscreen (f);
6209 SET_FRAME_VISIBLE (f, 1);
6210 SET_FRAME_ICONIFIED (f, 0);
6211 f->output_data.x->has_been_visible = 1;
6213 if (iconified)
6215 inev.ie.kind = DEICONIFY_EVENT;
6216 XSETFRAME (inev.ie.frame_or_window, f);
6218 else if (! NILP (Vframe_list) && ! NILP (XCDR (Vframe_list)))
6219 /* Force a redisplay sooner or later to update the
6220 frame titles in case this is the second frame. */
6221 record_asynch_buffer_change ();
6223 #ifdef USE_GTK
6224 xg_frame_resized (f, -1, -1);
6225 #endif
6227 goto OTHER;
6229 case KeyPress:
6231 dpyinfo->last_user_time = event->xkey.time;
6232 ignore_next_mouse_click_timeout = 0;
6234 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
6235 /* Dispatch KeyPress events when in menu. */
6236 if (popup_activated ())
6237 goto OTHER;
6238 #endif
6240 f = any;
6242 #if ! defined (USE_GTK)
6243 /* If mouse-highlight is an integer, input clears out
6244 mouse highlighting. */
6245 if (!hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight)
6246 && (f == 0
6247 || !EQ (f->tool_bar_window, hlinfo->mouse_face_window)))
6249 clear_mouse_face (hlinfo);
6250 hlinfo->mouse_face_hidden = 1;
6252 #endif
6254 #if defined USE_MOTIF && defined USE_TOOLKIT_SCROLL_BARS
6255 if (f == 0)
6257 /* Scroll bars consume key events, but we want
6258 the keys to go to the scroll bar's frame. */
6259 Widget widget = XtWindowToWidget (dpyinfo->display,
6260 event->xkey.window);
6261 if (widget && XmIsScrollBar (widget))
6263 widget = XtParent (widget);
6264 f = x_any_window_to_frame (dpyinfo, XtWindow (widget));
6267 #endif /* USE_MOTIF and USE_TOOLKIT_SCROLL_BARS */
6269 if (f != 0)
6271 KeySym keysym, orig_keysym;
6272 /* al%imercury@uunet.uu.net says that making this 81
6273 instead of 80 fixed a bug whereby meta chars made
6274 his Emacs hang.
6276 It seems that some version of XmbLookupString has
6277 a bug of not returning XBufferOverflow in
6278 status_return even if the input is too long to
6279 fit in 81 bytes. So, we must prepare sufficient
6280 bytes for copy_buffer. 513 bytes (256 chars for
6281 two-byte character set) seems to be a fairly good
6282 approximation. -- 2000.8.10 handa@etl.go.jp */
6283 unsigned char copy_buffer[513];
6284 unsigned char *copy_bufptr = copy_buffer;
6285 int copy_bufsiz = sizeof (copy_buffer);
6286 int modifiers;
6287 Lisp_Object coding_system = Qlatin_1;
6288 Lisp_Object c;
6289 /* Event will be modified. */
6290 XKeyEvent xkey = event->xkey;
6292 #ifdef USE_GTK
6293 /* Don't pass keys to GTK. A Tab will shift focus to the
6294 tool bar in GTK 2.4. Keys will still go to menus and
6295 dialogs because in that case popup_activated is TRUE
6296 (see above). */
6297 *finish = X_EVENT_DROP;
6298 #endif
6300 xkey.state |= x_emacs_to_x_modifiers (FRAME_DISPLAY_INFO (f),
6301 extra_keyboard_modifiers);
6302 modifiers = xkey.state;
6304 /* This will have to go some day... */
6306 /* make_lispy_event turns chars into control chars.
6307 Don't do it here because XLookupString is too eager. */
6308 xkey.state &= ~ControlMask;
6309 xkey.state &= ~(dpyinfo->meta_mod_mask
6310 | dpyinfo->super_mod_mask
6311 | dpyinfo->hyper_mod_mask
6312 | dpyinfo->alt_mod_mask);
6314 /* In case Meta is ComposeCharacter,
6315 clear its status. According to Markus Ehrnsperger
6316 Markus.Ehrnsperger@lehrstuhl-bross.physik.uni-muenchen.de
6317 this enables ComposeCharacter to work whether or
6318 not it is combined with Meta. */
6319 if (modifiers & dpyinfo->meta_mod_mask)
6320 memset (&compose_status, 0, sizeof (compose_status));
6322 #ifdef HAVE_X_I18N
6323 if (FRAME_XIC (f))
6325 Status status_return;
6327 coding_system = Vlocale_coding_system;
6328 nbytes = XmbLookupString (FRAME_XIC (f),
6329 &xkey, (char *) copy_bufptr,
6330 copy_bufsiz, &keysym,
6331 &status_return);
6332 if (status_return == XBufferOverflow)
6334 copy_bufsiz = nbytes + 1;
6335 copy_bufptr = alloca (copy_bufsiz);
6336 nbytes = XmbLookupString (FRAME_XIC (f),
6337 &xkey, (char *) copy_bufptr,
6338 copy_bufsiz, &keysym,
6339 &status_return);
6341 /* Xutf8LookupString is a new but already deprecated interface. -stef */
6342 if (status_return == XLookupNone)
6343 break;
6344 else if (status_return == XLookupChars)
6346 keysym = NoSymbol;
6347 modifiers = 0;
6349 else if (status_return != XLookupKeySym
6350 && status_return != XLookupBoth)
6351 emacs_abort ();
6353 else
6354 nbytes = XLookupString (&xkey, (char *) copy_bufptr,
6355 copy_bufsiz, &keysym,
6356 &compose_status);
6357 #else
6358 nbytes = XLookupString (&xkey, (char *) copy_bufptr,
6359 copy_bufsiz, &keysym,
6360 &compose_status);
6361 #endif
6363 /* If not using XIM/XIC, and a compose sequence is in progress,
6364 we break here. Otherwise, chars_matched is always 0. */
6365 if (compose_status.chars_matched > 0 && nbytes == 0)
6366 break;
6368 memset (&compose_status, 0, sizeof (compose_status));
6369 orig_keysym = keysym;
6371 /* Common for all keysym input events. */
6372 XSETFRAME (inev.ie.frame_or_window, f);
6373 inev.ie.modifiers
6374 = x_x_to_emacs_modifiers (FRAME_DISPLAY_INFO (f), modifiers);
6375 inev.ie.timestamp = xkey.time;
6377 /* First deal with keysyms which have defined
6378 translations to characters. */
6379 if (keysym >= 32 && keysym < 128)
6380 /* Avoid explicitly decoding each ASCII character. */
6382 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
6383 inev.ie.code = keysym;
6384 goto done_keysym;
6387 /* Keysyms directly mapped to Unicode characters. */
6388 if (keysym >= 0x01000000 && keysym <= 0x0110FFFF)
6390 if (keysym < 0x01000080)
6391 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
6392 else
6393 inev.ie.kind = MULTIBYTE_CHAR_KEYSTROKE_EVENT;
6394 inev.ie.code = keysym & 0xFFFFFF;
6395 goto done_keysym;
6398 /* Now non-ASCII. */
6399 if (HASH_TABLE_P (Vx_keysym_table)
6400 && (c = Fgethash (make_number (keysym),
6401 Vx_keysym_table,
6402 Qnil),
6403 NATNUMP (c)))
6405 inev.ie.kind = (SINGLE_BYTE_CHAR_P (XFASTINT (c))
6406 ? ASCII_KEYSTROKE_EVENT
6407 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
6408 inev.ie.code = XFASTINT (c);
6409 goto done_keysym;
6412 /* Random non-modifier sorts of keysyms. */
6413 if (((keysym >= XK_BackSpace && keysym <= XK_Escape)
6414 || keysym == XK_Delete
6415 #ifdef XK_ISO_Left_Tab
6416 || (keysym >= XK_ISO_Left_Tab
6417 && keysym <= XK_ISO_Enter)
6418 #endif
6419 || IsCursorKey (keysym) /* 0xff50 <= x < 0xff60 */
6420 || IsMiscFunctionKey (keysym) /* 0xff60 <= x < VARIES */
6421 #ifdef HPUX
6422 /* This recognizes the "extended function
6423 keys". It seems there's no cleaner way.
6424 Test IsModifierKey to avoid handling
6425 mode_switch incorrectly. */
6426 || (XK_Select <= keysym && keysym < XK_KP_Space)
6427 #endif
6428 #ifdef XK_dead_circumflex
6429 || orig_keysym == XK_dead_circumflex
6430 #endif
6431 #ifdef XK_dead_grave
6432 || orig_keysym == XK_dead_grave
6433 #endif
6434 #ifdef XK_dead_tilde
6435 || orig_keysym == XK_dead_tilde
6436 #endif
6437 #ifdef XK_dead_diaeresis
6438 || orig_keysym == XK_dead_diaeresis
6439 #endif
6440 #ifdef XK_dead_macron
6441 || orig_keysym == XK_dead_macron
6442 #endif
6443 #ifdef XK_dead_degree
6444 || orig_keysym == XK_dead_degree
6445 #endif
6446 #ifdef XK_dead_acute
6447 || orig_keysym == XK_dead_acute
6448 #endif
6449 #ifdef XK_dead_cedilla
6450 || orig_keysym == XK_dead_cedilla
6451 #endif
6452 #ifdef XK_dead_breve
6453 || orig_keysym == XK_dead_breve
6454 #endif
6455 #ifdef XK_dead_ogonek
6456 || orig_keysym == XK_dead_ogonek
6457 #endif
6458 #ifdef XK_dead_caron
6459 || orig_keysym == XK_dead_caron
6460 #endif
6461 #ifdef XK_dead_doubleacute
6462 || orig_keysym == XK_dead_doubleacute
6463 #endif
6464 #ifdef XK_dead_abovedot
6465 || orig_keysym == XK_dead_abovedot
6466 #endif
6467 || IsKeypadKey (keysym) /* 0xff80 <= x < 0xffbe */
6468 || IsFunctionKey (keysym) /* 0xffbe <= x < 0xffe1 */
6469 /* Any "vendor-specific" key is ok. */
6470 || (orig_keysym & (1 << 28))
6471 || (keysym != NoSymbol && nbytes == 0))
6472 && ! (IsModifierKey (orig_keysym)
6473 /* The symbols from XK_ISO_Lock
6474 to XK_ISO_Last_Group_Lock
6475 don't have real modifiers but
6476 should be treated similarly to
6477 Mode_switch by Emacs. */
6478 #if defined XK_ISO_Lock && defined XK_ISO_Last_Group_Lock
6479 || (XK_ISO_Lock <= orig_keysym
6480 && orig_keysym <= XK_ISO_Last_Group_Lock)
6481 #endif
6484 STORE_KEYSYM_FOR_DEBUG (keysym);
6485 /* make_lispy_event will convert this to a symbolic
6486 key. */
6487 inev.ie.kind = NON_ASCII_KEYSTROKE_EVENT;
6488 inev.ie.code = keysym;
6489 goto done_keysym;
6492 { /* Raw bytes, not keysym. */
6493 ptrdiff_t i;
6494 int nchars, len;
6496 for (i = 0, nchars = 0; i < nbytes; i++)
6498 if (ASCII_BYTE_P (copy_bufptr[i]))
6499 nchars++;
6500 STORE_KEYSYM_FOR_DEBUG (copy_bufptr[i]);
6503 if (nchars < nbytes)
6505 /* Decode the input data. */
6507 /* The input should be decoded with `coding_system'
6508 which depends on which X*LookupString function
6509 we used just above and the locale. */
6510 setup_coding_system (coding_system, &coding);
6511 coding.src_multibyte = 0;
6512 coding.dst_multibyte = 1;
6513 /* The input is converted to events, thus we can't
6514 handle composition. Anyway, there's no XIM that
6515 gives us composition information. */
6516 coding.common_flags &= ~CODING_ANNOTATION_MASK;
6518 SAFE_NALLOCA (coding.destination, MAX_MULTIBYTE_LENGTH,
6519 nbytes);
6520 coding.dst_bytes = MAX_MULTIBYTE_LENGTH * nbytes;
6521 coding.mode |= CODING_MODE_LAST_BLOCK;
6522 decode_coding_c_string (&coding, copy_bufptr, nbytes, Qnil);
6523 nbytes = coding.produced;
6524 nchars = coding.produced_char;
6525 copy_bufptr = coding.destination;
6528 /* Convert the input data to a sequence of
6529 character events. */
6530 for (i = 0; i < nbytes; i += len)
6532 int ch;
6533 if (nchars == nbytes)
6534 ch = copy_bufptr[i], len = 1;
6535 else
6536 ch = STRING_CHAR_AND_LENGTH (copy_bufptr + i, len);
6537 inev.ie.kind = (SINGLE_BYTE_CHAR_P (ch)
6538 ? ASCII_KEYSTROKE_EVENT
6539 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
6540 inev.ie.code = ch;
6541 kbd_buffer_store_event_hold (&inev.ie, hold_quit);
6544 count += nchars;
6546 inev.ie.kind = NO_EVENT; /* Already stored above. */
6548 if (keysym == NoSymbol)
6549 break;
6551 /* FIXME: check side effects and remove this. */
6552 ((XEvent *) event)->xkey = xkey;
6554 done_keysym:
6555 #ifdef HAVE_X_I18N
6556 /* Don't dispatch this event since XtDispatchEvent calls
6557 XFilterEvent, and two calls in a row may freeze the
6558 client. */
6559 break;
6560 #else
6561 goto OTHER;
6562 #endif
6564 case KeyRelease:
6565 dpyinfo->last_user_time = event->xkey.time;
6566 #ifdef HAVE_X_I18N
6567 /* Don't dispatch this event since XtDispatchEvent calls
6568 XFilterEvent, and two calls in a row may freeze the
6569 client. */
6570 break;
6571 #else
6572 goto OTHER;
6573 #endif
6575 case EnterNotify:
6576 dpyinfo->last_user_time = event->xcrossing.time;
6577 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
6579 f = any;
6581 if (f && x_mouse_click_focus_ignore_position)
6582 ignore_next_mouse_click_timeout = event->xmotion.time + 200;
6584 /* EnterNotify counts as mouse movement,
6585 so update things that depend on mouse position. */
6586 if (f && !f->output_data.x->hourglass_p)
6587 note_mouse_movement (f, &event->xmotion);
6588 #ifdef USE_GTK
6589 /* We may get an EnterNotify on the buttons in the toolbar. In that
6590 case we moved out of any highlighted area and need to note this. */
6591 if (!f && dpyinfo->last_mouse_glyph_frame)
6592 note_mouse_movement (dpyinfo->last_mouse_glyph_frame, &event->xmotion);
6593 #endif
6594 goto OTHER;
6596 case FocusIn:
6597 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
6598 goto OTHER;
6600 case LeaveNotify:
6601 dpyinfo->last_user_time = event->xcrossing.time;
6602 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
6604 f = x_top_window_to_frame (dpyinfo, event->xcrossing.window);
6605 if (f)
6607 if (f == hlinfo->mouse_face_mouse_frame)
6609 /* If we move outside the frame, then we're
6610 certainly no longer on any text in the frame. */
6611 clear_mouse_face (hlinfo);
6612 hlinfo->mouse_face_mouse_frame = 0;
6615 /* Generate a nil HELP_EVENT to cancel a help-echo.
6616 Do it only if there's something to cancel.
6617 Otherwise, the startup message is cleared when
6618 the mouse leaves the frame. */
6619 if (any_help_event_p)
6620 do_help = -1;
6622 #ifdef USE_GTK
6623 /* See comment in EnterNotify above */
6624 else if (dpyinfo->last_mouse_glyph_frame)
6625 note_mouse_movement (dpyinfo->last_mouse_glyph_frame, &event->xmotion);
6626 #endif
6627 goto OTHER;
6629 case FocusOut:
6630 x_detect_focus_change (dpyinfo, any, event, &inev.ie);
6631 goto OTHER;
6633 case MotionNotify:
6635 dpyinfo->last_user_time = event->xmotion.time;
6636 previous_help_echo_string = help_echo_string;
6637 help_echo_string = Qnil;
6639 f = (x_mouse_grabbed (dpyinfo) ? dpyinfo->last_mouse_frame
6640 : x_window_to_frame (dpyinfo, event->xmotion.window));
6642 if (hlinfo->mouse_face_hidden)
6644 hlinfo->mouse_face_hidden = 0;
6645 clear_mouse_face (hlinfo);
6648 #ifdef USE_GTK
6649 if (f && xg_event_is_for_scrollbar (f, event))
6650 f = 0;
6651 #endif
6652 if (f)
6655 /* Generate SELECT_WINDOW_EVENTs when needed.
6656 Don't let popup menus influence things (bug#1261). */
6657 if (!NILP (Vmouse_autoselect_window) && !popup_activated ())
6659 static Lisp_Object last_mouse_window;
6660 Lisp_Object window = window_from_coordinates
6661 (f, event->xmotion.x, event->xmotion.y, 0, 0);
6663 /* Window will be selected only when it is not selected now and
6664 last mouse movement event was not in it. Minibuffer window
6665 will be selected only when it is active. */
6666 if (WINDOWP (window)
6667 && !EQ (window, last_mouse_window)
6668 && !EQ (window, selected_window)
6669 /* For click-to-focus window managers
6670 create event iff we don't leave the
6671 selected frame. */
6672 && (focus_follows_mouse
6673 || (EQ (XWINDOW (window)->frame,
6674 XWINDOW (selected_window)->frame))))
6676 inev.ie.kind = SELECT_WINDOW_EVENT;
6677 inev.ie.frame_or_window = window;
6679 /* Remember the last window where we saw the mouse. */
6680 last_mouse_window = window;
6682 if (!note_mouse_movement (f, &event->xmotion))
6683 help_echo_string = previous_help_echo_string;
6685 else
6687 #ifndef USE_TOOLKIT_SCROLL_BARS
6688 struct scroll_bar *bar
6689 = x_window_to_scroll_bar (event->xmotion.display,
6690 event->xmotion.window);
6692 if (bar)
6693 x_scroll_bar_note_movement (bar, &event->xmotion);
6694 #endif /* USE_TOOLKIT_SCROLL_BARS */
6696 /* If we move outside the frame, then we're
6697 certainly no longer on any text in the frame. */
6698 clear_mouse_face (hlinfo);
6701 /* If the contents of the global variable help_echo_string
6702 has changed, generate a HELP_EVENT. */
6703 if (!NILP (help_echo_string)
6704 || !NILP (previous_help_echo_string))
6705 do_help = 1;
6706 goto OTHER;
6709 case ConfigureNotify:
6710 f = x_top_window_to_frame (dpyinfo, event->xconfigure.window);
6711 #ifdef USE_GTK
6712 if (!f
6713 && (f = any)
6714 && event->xconfigure.window == FRAME_X_WINDOW (f))
6716 xg_frame_resized (f, event->xconfigure.width,
6717 event->xconfigure.height);
6718 f = 0;
6720 #endif
6721 if (f)
6723 #ifndef USE_X_TOOLKIT
6724 #ifndef USE_GTK
6725 int rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, event->xconfigure.height);
6726 int columns = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, event->xconfigure.width);
6728 /* In the toolkit version, change_frame_size
6729 is called by the code that handles resizing
6730 of the EmacsFrame widget. */
6732 /* Even if the number of character rows and columns has
6733 not changed, the font size may have changed, so we need
6734 to check the pixel dimensions as well. */
6735 if (columns != FRAME_COLS (f)
6736 || rows != FRAME_LINES (f)
6737 || event->xconfigure.width != FRAME_PIXEL_WIDTH (f)
6738 || event->xconfigure.height != FRAME_PIXEL_HEIGHT (f))
6740 change_frame_size (f, rows, columns, 0, 1, 0);
6741 SET_FRAME_GARBAGED (f);
6742 cancel_mouse_face (f);
6745 FRAME_PIXEL_WIDTH (f) = event->xconfigure.width;
6746 FRAME_PIXEL_HEIGHT (f) = event->xconfigure.height;
6747 #endif /* not USE_GTK */
6748 #endif
6750 #ifdef USE_GTK
6751 /* GTK creates windows but doesn't map them.
6752 Only get real positions when mapped. */
6753 if (FRAME_GTK_OUTER_WIDGET (f)
6754 && gtk_widget_get_mapped (FRAME_GTK_OUTER_WIDGET (f)))
6755 #endif
6756 x_real_positions (f, &f->left_pos, &f->top_pos);
6758 #ifdef HAVE_X_I18N
6759 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMStatusArea))
6760 xic_set_statusarea (f);
6761 #endif
6764 goto OTHER;
6766 case ButtonRelease:
6767 case ButtonPress:
6769 /* If we decide we want to generate an event to be seen
6770 by the rest of Emacs, we put it here. */
6771 bool tool_bar_p = 0;
6773 memset (&compose_status, 0, sizeof (compose_status));
6774 dpyinfo->last_mouse_glyph_frame = NULL;
6775 dpyinfo->last_user_time = event->xbutton.time;
6777 f = (x_mouse_grabbed (dpyinfo) ? dpyinfo->last_mouse_frame
6778 : x_window_to_frame (dpyinfo, event->xbutton.window));
6780 #ifdef USE_GTK
6781 if (f && xg_event_is_for_scrollbar (f, event))
6782 f = 0;
6783 #endif
6784 if (f)
6786 #if ! defined (USE_GTK)
6787 /* Is this in the tool-bar? */
6788 if (WINDOWP (f->tool_bar_window)
6789 && WINDOW_TOTAL_LINES (XWINDOW (f->tool_bar_window)))
6791 Lisp_Object window;
6792 int x = event->xbutton.x;
6793 int y = event->xbutton.y;
6795 window = window_from_coordinates (f, x, y, 0, 1);
6796 tool_bar_p = EQ (window, f->tool_bar_window);
6798 if (tool_bar_p && event->xbutton.button < 4)
6799 handle_tool_bar_click
6800 (f, x, y, event->xbutton.type == ButtonPress,
6801 x_x_to_emacs_modifiers (dpyinfo, event->xbutton.state));
6803 #endif /* !USE_GTK */
6805 if (!tool_bar_p)
6806 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
6807 if (! popup_activated ())
6808 #endif
6810 if (ignore_next_mouse_click_timeout)
6812 if (event->type == ButtonPress
6813 && event->xbutton.time > ignore_next_mouse_click_timeout)
6815 ignore_next_mouse_click_timeout = 0;
6816 construct_mouse_click (&inev.ie, &event->xbutton, f);
6818 if (event->type == ButtonRelease)
6819 ignore_next_mouse_click_timeout = 0;
6821 else
6822 construct_mouse_click (&inev.ie, &event->xbutton, f);
6824 if (FRAME_X_EMBEDDED_P (f))
6825 xembed_send_message (f, event->xbutton.time,
6826 XEMBED_REQUEST_FOCUS, 0, 0, 0);
6828 else
6830 struct scroll_bar *bar
6831 = x_window_to_scroll_bar (event->xbutton.display,
6832 event->xbutton.window);
6834 #ifdef USE_TOOLKIT_SCROLL_BARS
6835 /* Make the "Ctrl-Mouse-2 splits window" work for toolkit
6836 scroll bars. */
6837 if (bar && event->xbutton.state & ControlMask)
6839 x_scroll_bar_handle_click (bar, event, &inev.ie);
6840 *finish = X_EVENT_DROP;
6842 #else /* not USE_TOOLKIT_SCROLL_BARS */
6843 if (bar)
6844 x_scroll_bar_handle_click (bar, event, &inev.ie);
6845 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6848 if (event->type == ButtonPress)
6850 dpyinfo->grabbed |= (1 << event->xbutton.button);
6851 dpyinfo->last_mouse_frame = f;
6853 if (!tool_bar_p)
6854 last_tool_bar_item = -1;
6856 else
6857 dpyinfo->grabbed &= ~(1 << event->xbutton.button);
6859 /* Ignore any mouse motion that happened before this event;
6860 any subsequent mouse-movement Emacs events should reflect
6861 only motion after the ButtonPress/Release. */
6862 if (f != 0)
6863 f->mouse_moved = 0;
6865 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
6866 f = x_menubar_window_to_frame (dpyinfo, event);
6867 /* For a down-event in the menu bar,
6868 don't pass it to Xt right now.
6869 Instead, save it away
6870 and we will pass it to Xt from kbd_buffer_get_event.
6871 That way, we can run some Lisp code first. */
6872 if (! popup_activated ()
6873 #ifdef USE_GTK
6874 /* Gtk+ menus only react to the first three buttons. */
6875 && event->xbutton.button < 3
6876 #endif
6877 && f && event->type == ButtonPress
6878 /* Verify the event is really within the menu bar
6879 and not just sent to it due to grabbing. */
6880 && event->xbutton.x >= 0
6881 && event->xbutton.x < FRAME_PIXEL_WIDTH (f)
6882 && event->xbutton.y >= 0
6883 && event->xbutton.y < f->output_data.x->menubar_height
6884 && event->xbutton.same_screen)
6886 if (!f->output_data.x->saved_menu_event)
6887 f->output_data.x->saved_menu_event = xmalloc (sizeof *event);
6888 *f->output_data.x->saved_menu_event = *event;
6889 inev.ie.kind = MENU_BAR_ACTIVATE_EVENT;
6890 XSETFRAME (inev.ie.frame_or_window, f);
6891 *finish = X_EVENT_DROP;
6893 else
6894 goto OTHER;
6895 #endif /* USE_X_TOOLKIT || USE_GTK */
6897 break;
6899 case CirculateNotify:
6900 goto OTHER;
6902 case CirculateRequest:
6903 goto OTHER;
6905 case VisibilityNotify:
6906 goto OTHER;
6908 case MappingNotify:
6909 /* Someone has changed the keyboard mapping - update the
6910 local cache. */
6911 switch (event->xmapping.request)
6913 case MappingModifier:
6914 x_find_modifier_meanings (dpyinfo);
6915 /* This is meant to fall through. */
6916 case MappingKeyboard:
6917 XRefreshKeyboardMapping ((XMappingEvent *) &event->xmapping);
6919 goto OTHER;
6921 case DestroyNotify:
6922 xft_settings_event (dpyinfo, event);
6923 break;
6925 default:
6926 OTHER:
6927 #ifdef USE_X_TOOLKIT
6928 block_input ();
6929 if (*finish != X_EVENT_DROP)
6930 XtDispatchEvent ((XEvent *) event);
6931 unblock_input ();
6932 #endif /* USE_X_TOOLKIT */
6933 break;
6936 done:
6937 if (inev.ie.kind != NO_EVENT)
6939 kbd_buffer_store_event_hold (&inev.ie, hold_quit);
6940 count++;
6943 if (do_help
6944 && !(hold_quit && hold_quit->kind != NO_EVENT))
6946 Lisp_Object frame;
6948 if (f)
6949 XSETFRAME (frame, f);
6950 else
6951 frame = Qnil;
6953 if (do_help > 0)
6955 any_help_event_p = 1;
6956 gen_help_event (help_echo_string, frame, help_echo_window,
6957 help_echo_object, help_echo_pos);
6959 else
6961 help_echo_string = Qnil;
6962 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
6964 count++;
6967 SAFE_FREE ();
6968 return count;
6971 #if defined USE_GTK || defined USE_X_TOOLKIT
6973 /* Handles the XEvent EVENT on display DISPLAY.
6974 This is used for event loops outside the normal event handling,
6975 i.e. looping while a popup menu or a dialog is posted.
6977 Returns the value handle_one_xevent sets in the finish argument. */
6979 x_dispatch_event (XEvent *event, Display *display)
6981 struct x_display_info *dpyinfo;
6982 int finish = X_EVENT_NORMAL;
6984 dpyinfo = x_display_info_for_display (display);
6986 if (dpyinfo)
6987 handle_one_xevent (dpyinfo, event, &finish, 0);
6989 return finish;
6991 #endif
6994 /* Read events coming from the X server.
6995 Return as soon as there are no more events to be read.
6997 Return the number of characters stored into the buffer,
6998 thus pretending to be `read' (except the characters we store
6999 in the keyboard buffer can be multibyte, so are not necessarily
7000 C chars). */
7002 static int
7003 XTread_socket (struct terminal *terminal, struct input_event *hold_quit)
7005 int count = 0;
7006 int event_found = 0;
7007 struct x_display_info *dpyinfo = terminal->display_info.x;
7009 block_input ();
7011 /* So people can tell when we have read the available input. */
7012 input_signal_count++;
7014 /* For debugging, this gives a way to fake an I/O error. */
7015 if (dpyinfo == XTread_socket_fake_io_error)
7017 XTread_socket_fake_io_error = 0;
7018 x_io_error_quitter (dpyinfo->display);
7021 #ifndef USE_GTK
7022 while (XPending (dpyinfo->display))
7024 int finish;
7025 XEvent event;
7027 XNextEvent (dpyinfo->display, &event);
7029 #ifdef HAVE_X_I18N
7030 /* Filter events for the current X input method. */
7031 if (x_filter_event (dpyinfo, &event))
7032 continue;
7033 #endif
7034 event_found = 1;
7036 count += handle_one_xevent (dpyinfo, &event, &finish, hold_quit);
7038 if (finish == X_EVENT_GOTO_OUT)
7039 break;
7042 #else /* USE_GTK */
7044 /* For GTK we must use the GTK event loop. But XEvents gets passed
7045 to our filter function above, and then to the big event switch.
7046 We use a bunch of globals to communicate with our filter function,
7047 that is kind of ugly, but it works.
7049 There is no way to do one display at the time, GTK just does events
7050 from all displays. */
7052 while (gtk_events_pending ())
7054 current_count = count;
7055 current_hold_quit = hold_quit;
7057 gtk_main_iteration ();
7059 count = current_count;
7060 current_count = -1;
7061 current_hold_quit = 0;
7063 if (current_finish == X_EVENT_GOTO_OUT)
7064 break;
7066 #endif /* USE_GTK */
7068 /* On some systems, an X bug causes Emacs to get no more events
7069 when the window is destroyed. Detect that. (1994.) */
7070 if (! event_found)
7072 /* Emacs and the X Server eats up CPU time if XNoOp is done every time.
7073 One XNOOP in 100 loops will make Emacs terminate.
7074 B. Bretthauer, 1994 */
7075 x_noop_count++;
7076 if (x_noop_count >= 100)
7078 x_noop_count=0;
7080 if (next_noop_dpyinfo == 0)
7081 next_noop_dpyinfo = x_display_list;
7083 XNoOp (next_noop_dpyinfo->display);
7085 /* Each time we get here, cycle through the displays now open. */
7086 next_noop_dpyinfo = next_noop_dpyinfo->next;
7090 /* If the focus was just given to an auto-raising frame,
7091 raise it now. FIXME: handle more than one such frame. */
7092 if (dpyinfo->x_pending_autoraise_frame)
7094 x_raise_frame (dpyinfo->x_pending_autoraise_frame);
7095 dpyinfo->x_pending_autoraise_frame = NULL;
7098 unblock_input ();
7100 return count;
7106 /***********************************************************************
7107 Text Cursor
7108 ***********************************************************************/
7110 /* Set clipping for output in glyph row ROW. W is the window in which
7111 we operate. GC is the graphics context to set clipping in.
7113 ROW may be a text row or, e.g., a mode line. Text rows must be
7114 clipped to the interior of the window dedicated to text display,
7115 mode lines must be clipped to the whole window. */
7117 static void
7118 x_clip_to_row (struct window *w, struct glyph_row *row,
7119 enum glyph_row_area area, GC gc)
7121 struct frame *f = XFRAME (WINDOW_FRAME (w));
7122 XRectangle clip_rect;
7123 int window_x, window_y, window_width;
7125 window_box (w, area, &window_x, &window_y, &window_width, 0);
7127 clip_rect.x = window_x;
7128 clip_rect.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
7129 clip_rect.y = max (clip_rect.y, window_y);
7130 clip_rect.width = window_width;
7131 clip_rect.height = row->visible_height;
7133 XSetClipRectangles (FRAME_X_DISPLAY (f), gc, 0, 0, &clip_rect, 1, Unsorted);
7137 /* Draw a hollow box cursor on window W in glyph row ROW. */
7139 static void
7140 x_draw_hollow_cursor (struct window *w, struct glyph_row *row)
7142 struct frame *f = XFRAME (WINDOW_FRAME (w));
7143 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
7144 Display *dpy = FRAME_X_DISPLAY (f);
7145 int x, y, wd, h;
7146 XGCValues xgcv;
7147 struct glyph *cursor_glyph;
7148 GC gc;
7150 /* Get the glyph the cursor is on. If we can't tell because
7151 the current matrix is invalid or such, give up. */
7152 cursor_glyph = get_phys_cursor_glyph (w);
7153 if (cursor_glyph == NULL)
7154 return;
7156 /* Compute frame-relative coordinates for phys cursor. */
7157 get_phys_cursor_geometry (w, row, cursor_glyph, &x, &y, &h);
7158 wd = w->phys_cursor_width;
7160 /* The foreground of cursor_gc is typically the same as the normal
7161 background color, which can cause the cursor box to be invisible. */
7162 xgcv.foreground = f->output_data.x->cursor_pixel;
7163 if (dpyinfo->scratch_cursor_gc)
7164 XChangeGC (dpy, dpyinfo->scratch_cursor_gc, GCForeground, &xgcv);
7165 else
7166 dpyinfo->scratch_cursor_gc = XCreateGC (dpy, FRAME_X_WINDOW (f),
7167 GCForeground, &xgcv);
7168 gc = dpyinfo->scratch_cursor_gc;
7170 /* Set clipping, draw the rectangle, and reset clipping again. */
7171 x_clip_to_row (w, row, TEXT_AREA, gc);
7172 XDrawRectangle (dpy, FRAME_X_WINDOW (f), gc, x, y, wd, h - 1);
7173 XSetClipMask (dpy, gc, None);
7177 /* Draw a bar cursor on window W in glyph row ROW.
7179 Implementation note: One would like to draw a bar cursor with an
7180 angle equal to the one given by the font property XA_ITALIC_ANGLE.
7181 Unfortunately, I didn't find a font yet that has this property set.
7182 --gerd. */
7184 static void
7185 x_draw_bar_cursor (struct window *w, struct glyph_row *row, int width, enum text_cursor_kinds kind)
7187 struct frame *f = XFRAME (w->frame);
7188 struct glyph *cursor_glyph;
7190 /* If cursor is out of bounds, don't draw garbage. This can happen
7191 in mini-buffer windows when switching between echo area glyphs
7192 and mini-buffer. */
7193 cursor_glyph = get_phys_cursor_glyph (w);
7194 if (cursor_glyph == NULL)
7195 return;
7197 /* If on an image, draw like a normal cursor. That's usually better
7198 visible than drawing a bar, esp. if the image is large so that
7199 the bar might not be in the window. */
7200 if (cursor_glyph->type == IMAGE_GLYPH)
7202 struct glyph_row *r;
7203 r = MATRIX_ROW (w->current_matrix, w->phys_cursor.vpos);
7204 draw_phys_cursor_glyph (w, r, DRAW_CURSOR);
7206 else
7208 Display *dpy = FRAME_X_DISPLAY (f);
7209 Window window = FRAME_X_WINDOW (f);
7210 GC gc = FRAME_DISPLAY_INFO (f)->scratch_cursor_gc;
7211 unsigned long mask = GCForeground | GCBackground | GCGraphicsExposures;
7212 struct face *face = FACE_FROM_ID (f, cursor_glyph->face_id);
7213 XGCValues xgcv;
7215 /* If the glyph's background equals the color we normally draw
7216 the bars cursor in, the bar cursor in its normal color is
7217 invisible. Use the glyph's foreground color instead in this
7218 case, on the assumption that the glyph's colors are chosen so
7219 that the glyph is legible. */
7220 if (face->background == f->output_data.x->cursor_pixel)
7221 xgcv.background = xgcv.foreground = face->foreground;
7222 else
7223 xgcv.background = xgcv.foreground = f->output_data.x->cursor_pixel;
7224 xgcv.graphics_exposures = 0;
7226 if (gc)
7227 XChangeGC (dpy, gc, mask, &xgcv);
7228 else
7230 gc = XCreateGC (dpy, window, mask, &xgcv);
7231 FRAME_DISPLAY_INFO (f)->scratch_cursor_gc = gc;
7234 x_clip_to_row (w, row, TEXT_AREA, gc);
7236 if (kind == BAR_CURSOR)
7238 int x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
7240 if (width < 0)
7241 width = FRAME_CURSOR_WIDTH (f);
7242 width = min (cursor_glyph->pixel_width, width);
7244 w->phys_cursor_width = width;
7246 /* If the character under cursor is R2L, draw the bar cursor
7247 on the right of its glyph, rather than on the left. */
7248 if ((cursor_glyph->resolved_level & 1) != 0)
7249 x += cursor_glyph->pixel_width - width;
7251 XFillRectangle (dpy, window, gc, x,
7252 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y),
7253 width, row->height);
7255 else
7257 int dummy_x, dummy_y, dummy_h;
7259 if (width < 0)
7260 width = row->height;
7262 width = min (row->height, width);
7264 get_phys_cursor_geometry (w, row, cursor_glyph, &dummy_x,
7265 &dummy_y, &dummy_h);
7267 XFillRectangle (dpy, window, gc,
7268 WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x),
7269 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y +
7270 row->height - width),
7271 w->phys_cursor_width, width);
7274 XSetClipMask (dpy, gc, None);
7279 /* RIF: Define cursor CURSOR on frame F. */
7281 static void
7282 x_define_frame_cursor (struct frame *f, Cursor cursor)
7284 if (!f->pointer_invisible
7285 && f->output_data.x->current_cursor != cursor)
7286 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), cursor);
7287 f->output_data.x->current_cursor = cursor;
7291 /* RIF: Clear area on frame F. */
7293 static void
7294 x_clear_frame_area (struct frame *f, int x, int y, int width, int height)
7296 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), x, y, width, height);
7297 #ifdef USE_GTK
7298 /* Must queue a redraw, because scroll bars might have been cleared. */
7299 if (FRAME_GTK_WIDGET (f))
7300 gtk_widget_queue_draw (FRAME_GTK_WIDGET (f));
7301 #endif
7305 /* RIF: Draw cursor on window W. */
7307 static void
7308 x_draw_window_cursor (struct window *w, struct glyph_row *glyph_row, int x,
7309 int y, enum text_cursor_kinds cursor_type,
7310 int cursor_width, bool on_p, bool active_p)
7312 struct frame *f = XFRAME (WINDOW_FRAME (w));
7314 if (on_p)
7316 w->phys_cursor_type = cursor_type;
7317 w->phys_cursor_on_p = 1;
7319 if (glyph_row->exact_window_width_line_p
7320 && (glyph_row->reversed_p
7321 ? (w->phys_cursor.hpos < 0)
7322 : (w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])))
7324 glyph_row->cursor_in_fringe_p = 1;
7325 draw_fringe_bitmap (w, glyph_row, glyph_row->reversed_p);
7327 else
7329 switch (cursor_type)
7331 case HOLLOW_BOX_CURSOR:
7332 x_draw_hollow_cursor (w, glyph_row);
7333 break;
7335 case FILLED_BOX_CURSOR:
7336 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
7337 break;
7339 case BAR_CURSOR:
7340 x_draw_bar_cursor (w, glyph_row, cursor_width, BAR_CURSOR);
7341 break;
7343 case HBAR_CURSOR:
7344 x_draw_bar_cursor (w, glyph_row, cursor_width, HBAR_CURSOR);
7345 break;
7347 case NO_CURSOR:
7348 w->phys_cursor_width = 0;
7349 break;
7351 default:
7352 emacs_abort ();
7356 #ifdef HAVE_X_I18N
7357 if (w == XWINDOW (f->selected_window))
7358 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMPreeditPosition))
7359 xic_set_preeditarea (w, x, y);
7360 #endif
7363 XFlush (FRAME_X_DISPLAY (f));
7367 /* Icons. */
7369 /* Make the x-window of frame F use the gnu icon bitmap. */
7372 x_bitmap_icon (struct frame *f, Lisp_Object file)
7374 ptrdiff_t bitmap_id;
7376 if (FRAME_X_WINDOW (f) == 0)
7377 return 1;
7379 /* Free up our existing icon bitmap and mask if any. */
7380 if (f->output_data.x->icon_bitmap > 0)
7381 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
7382 f->output_data.x->icon_bitmap = 0;
7384 if (STRINGP (file))
7386 #ifdef USE_GTK
7387 /* Use gtk_window_set_icon_from_file () if available,
7388 It's not restricted to bitmaps */
7389 if (xg_set_icon (f, file))
7390 return 0;
7391 #endif /* USE_GTK */
7392 bitmap_id = x_create_bitmap_from_file (f, file);
7393 x_create_bitmap_mask (f, bitmap_id);
7395 else
7397 /* Create the GNU bitmap and mask if necessary. */
7398 if (FRAME_DISPLAY_INFO (f)->icon_bitmap_id < 0)
7400 ptrdiff_t rc = -1;
7402 #ifdef USE_GTK
7404 if (xg_set_icon (f, xg_default_icon_file)
7405 || xg_set_icon_from_xpm_data (f, gnu_xpm_bits))
7406 return 0;
7408 #elif defined (HAVE_XPM) && defined (HAVE_X_WINDOWS)
7410 rc = x_create_bitmap_from_xpm_data (f, gnu_xpm_bits);
7411 if (rc != -1)
7412 FRAME_DISPLAY_INFO (f)->icon_bitmap_id = rc;
7414 #endif
7416 /* If all else fails, use the (black and white) xbm image. */
7417 if (rc == -1)
7419 rc = x_create_bitmap_from_data (f, (char *) gnu_xbm_bits,
7420 gnu_xbm_width, gnu_xbm_height);
7421 if (rc == -1)
7422 return 1;
7424 FRAME_DISPLAY_INFO (f)->icon_bitmap_id = rc;
7425 x_create_bitmap_mask (f, FRAME_DISPLAY_INFO (f)->icon_bitmap_id);
7429 /* The first time we create the GNU bitmap and mask,
7430 this increments the ref-count one extra time.
7431 As a result, the GNU bitmap and mask are never freed.
7432 That way, we don't have to worry about allocating it again. */
7433 x_reference_bitmap (f, FRAME_DISPLAY_INFO (f)->icon_bitmap_id);
7435 bitmap_id = FRAME_DISPLAY_INFO (f)->icon_bitmap_id;
7438 x_wm_set_icon_pixmap (f, bitmap_id);
7439 f->output_data.x->icon_bitmap = bitmap_id;
7441 return 0;
7445 /* Make the x-window of frame F use a rectangle with text.
7446 Use ICON_NAME as the text. */
7449 x_text_icon (struct frame *f, const char *icon_name)
7451 if (FRAME_X_WINDOW (f) == 0)
7452 return 1;
7455 XTextProperty text;
7456 text.value = (unsigned char *) icon_name;
7457 text.encoding = XA_STRING;
7458 text.format = 8;
7459 text.nitems = strlen (icon_name);
7460 XSetWMIconName (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f), &text);
7463 if (f->output_data.x->icon_bitmap > 0)
7464 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
7465 f->output_data.x->icon_bitmap = 0;
7466 x_wm_set_icon_pixmap (f, 0);
7468 return 0;
7471 #define X_ERROR_MESSAGE_SIZE 200
7473 /* If non-nil, this should be a string.
7474 It means catch X errors and store the error message in this string.
7476 The reason we use a stack is that x_catch_error/x_uncatch_error can
7477 be called from a signal handler.
7480 struct x_error_message_stack {
7481 char string[X_ERROR_MESSAGE_SIZE];
7482 Display *dpy;
7483 struct x_error_message_stack *prev;
7485 static struct x_error_message_stack *x_error_message;
7487 /* An X error handler which stores the error message in
7488 *x_error_message. This is called from x_error_handler if
7489 x_catch_errors is in effect. */
7491 static void
7492 x_error_catcher (Display *display, XErrorEvent *event)
7494 XGetErrorText (display, event->error_code,
7495 x_error_message->string,
7496 X_ERROR_MESSAGE_SIZE);
7499 /* Begin trapping X errors for display DPY. Actually we trap X errors
7500 for all displays, but DPY should be the display you are actually
7501 operating on.
7503 After calling this function, X protocol errors no longer cause
7504 Emacs to exit; instead, they are recorded in the string
7505 stored in *x_error_message.
7507 Calling x_check_errors signals an Emacs error if an X error has
7508 occurred since the last call to x_catch_errors or x_check_errors.
7510 Calling x_uncatch_errors resumes the normal error handling. */
7512 void
7513 x_catch_errors (Display *dpy)
7515 struct x_error_message_stack *data = xmalloc (sizeof *data);
7517 /* Make sure any errors from previous requests have been dealt with. */
7518 XSync (dpy, False);
7520 data->dpy = dpy;
7521 data->string[0] = 0;
7522 data->prev = x_error_message;
7523 x_error_message = data;
7526 /* Undo the last x_catch_errors call.
7527 DPY should be the display that was passed to x_catch_errors. */
7529 void
7530 x_uncatch_errors (void)
7532 struct x_error_message_stack *tmp;
7534 block_input ();
7536 /* The display may have been closed before this function is called.
7537 Check if it is still open before calling XSync. */
7538 if (x_display_info_for_display (x_error_message->dpy) != 0)
7539 XSync (x_error_message->dpy, False);
7541 tmp = x_error_message;
7542 x_error_message = x_error_message->prev;
7543 xfree (tmp);
7544 unblock_input ();
7547 /* If any X protocol errors have arrived since the last call to
7548 x_catch_errors or x_check_errors, signal an Emacs error using
7549 sprintf (a buffer, FORMAT, the x error message text) as the text. */
7551 void
7552 x_check_errors (Display *dpy, const char *format)
7554 /* Make sure to catch any errors incurred so far. */
7555 XSync (dpy, False);
7557 if (x_error_message->string[0])
7559 char string[X_ERROR_MESSAGE_SIZE];
7560 memcpy (string, x_error_message->string, X_ERROR_MESSAGE_SIZE);
7561 x_uncatch_errors ();
7562 error (format, string);
7566 /* Nonzero if we had any X protocol errors
7567 since we did x_catch_errors on DPY. */
7569 bool
7570 x_had_errors_p (Display *dpy)
7572 /* Make sure to catch any errors incurred so far. */
7573 XSync (dpy, False);
7575 return x_error_message->string[0] != 0;
7578 /* Forget about any errors we have had, since we did x_catch_errors on DPY. */
7580 void
7581 x_clear_errors (Display *dpy)
7583 x_error_message->string[0] = 0;
7586 #if 0 /* See comment in unwind_to_catch why calling this is a bad
7587 * idea. --lorentey */
7588 /* Close off all unclosed x_catch_errors calls. */
7590 void
7591 x_fully_uncatch_errors (void)
7593 while (x_error_message)
7594 x_uncatch_errors ();
7596 #endif
7598 #if 0
7599 static unsigned int x_wire_count;
7600 x_trace_wire (void)
7602 fprintf (stderr, "Lib call: %d\n", ++x_wire_count);
7604 #endif /* ! 0 */
7607 /************************************************************************
7608 Handling X errors
7609 ************************************************************************/
7611 /* Error message passed to x_connection_closed. */
7613 static char *error_msg;
7615 /* Handle the loss of connection to display DPY. ERROR_MESSAGE is
7616 the text of an error message that lead to the connection loss. */
7618 static void
7619 x_connection_closed (Display *dpy, const char *error_message)
7621 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
7622 Lisp_Object frame, tail;
7623 ptrdiff_t idx = SPECPDL_INDEX ();
7625 error_msg = alloca (strlen (error_message) + 1);
7626 strcpy (error_msg, error_message);
7628 /* Inhibit redisplay while frames are being deleted. */
7629 specbind (Qinhibit_redisplay, Qt);
7631 if (dpyinfo)
7633 /* Protect display from being closed when we delete the last
7634 frame on it. */
7635 dpyinfo->reference_count++;
7636 dpyinfo->terminal->reference_count++;
7639 /* First delete frames whose mini-buffers are on frames
7640 that are on the dead display. */
7641 FOR_EACH_FRAME (tail, frame)
7643 Lisp_Object minibuf_frame;
7644 minibuf_frame
7645 = WINDOW_FRAME (XWINDOW (FRAME_MINIBUF_WINDOW (XFRAME (frame))));
7646 if (FRAME_X_P (XFRAME (frame))
7647 && FRAME_X_P (XFRAME (minibuf_frame))
7648 && ! EQ (frame, minibuf_frame)
7649 && FRAME_DISPLAY_INFO (XFRAME (minibuf_frame)) == dpyinfo)
7650 delete_frame (frame, Qnoelisp);
7653 /* Now delete all remaining frames on the dead display.
7654 We are now sure none of these is used as the mini-buffer
7655 for another frame that we need to delete. */
7656 FOR_EACH_FRAME (tail, frame)
7657 if (FRAME_X_P (XFRAME (frame))
7658 && FRAME_DISPLAY_INFO (XFRAME (frame)) == dpyinfo)
7660 /* Set this to t so that delete_frame won't get confused
7661 trying to find a replacement. */
7662 kset_default_minibuffer_frame (FRAME_KBOARD (XFRAME (frame)), Qt);
7663 delete_frame (frame, Qnoelisp);
7666 /* If DPYINFO is null, this means we didn't open the display in the
7667 first place, so don't try to close it. */
7668 if (dpyinfo)
7670 /* We can not call XtCloseDisplay here because it calls XSync.
7671 XSync inside the error handler apparently hangs Emacs. On
7672 current Xt versions, this isn't needed either. */
7673 #ifdef USE_GTK
7674 /* A long-standing GTK bug prevents proper disconnect handling
7675 (https://bugzilla.gnome.org/show_bug.cgi?id=85715). Once,
7676 the resulting Glib error message loop filled a user's disk.
7677 To avoid this, kill Emacs unconditionally on disconnect. */
7678 shut_down_emacs (0, Qnil);
7679 fprintf (stderr, "%s\n\
7680 When compiled with GTK, Emacs cannot recover from X disconnects.\n\
7681 This is a GTK bug: https://bugzilla.gnome.org/show_bug.cgi?id=85715\n\
7682 For details, see etc/PROBLEMS.\n",
7683 error_msg);
7684 emacs_abort ();
7685 #endif /* USE_GTK */
7687 /* Indicate that this display is dead. */
7688 dpyinfo->display = 0;
7690 dpyinfo->reference_count--;
7691 dpyinfo->terminal->reference_count--;
7692 if (dpyinfo->reference_count != 0)
7693 /* We have just closed all frames on this display. */
7694 emacs_abort ();
7697 Lisp_Object tmp;
7698 XSETTERMINAL (tmp, dpyinfo->terminal);
7699 Fdelete_terminal (tmp, Qnoelisp);
7703 if (terminal_list == 0)
7705 fprintf (stderr, "%s\n", error_msg);
7706 Fkill_emacs (make_number (70));
7707 /* NOTREACHED */
7710 totally_unblock_input ();
7712 unbind_to (idx, Qnil);
7713 clear_waiting_for_input ();
7715 /* Tell GCC not to suggest attribute 'noreturn' for this function. */
7716 IF_LINT (if (! terminal_list) return; )
7718 /* Here, we absolutely have to use a non-local exit (e.g. signal, throw,
7719 longjmp), because returning from this function would get us back into
7720 Xlib's code which will directly call `exit'. */
7721 error ("%s", error_msg);
7724 /* We specifically use it before defining it, so that gcc doesn't inline it,
7725 otherwise gdb doesn't know how to properly put a breakpoint on it. */
7726 static void x_error_quitter (Display *, XErrorEvent *);
7728 /* This is the first-level handler for X protocol errors.
7729 It calls x_error_quitter or x_error_catcher. */
7731 static int
7732 x_error_handler (Display *display, XErrorEvent *event)
7734 #if defined USE_GTK && defined HAVE_GTK3
7735 if ((event->error_code == BadMatch || event->error_code == BadWindow)
7736 && event->request_code == X_SetInputFocus)
7738 return 0;
7740 #endif
7742 if (x_error_message)
7743 x_error_catcher (display, event);
7744 else
7745 x_error_quitter (display, event);
7746 return 0;
7749 /* This is the usual handler for X protocol errors.
7750 It kills all frames on the display that we got the error for.
7751 If that was the only one, it prints an error message and kills Emacs. */
7753 /* .gdbinit puts a breakpoint here, so make sure it is not inlined. */
7755 /* On older GCC versions, just putting x_error_quitter
7756 after x_error_handler prevents inlining into the former. */
7758 static void NO_INLINE
7759 x_error_quitter (Display *display, XErrorEvent *event)
7761 char buf[256], buf1[356];
7763 /* Ignore BadName errors. They can happen because of fonts
7764 or colors that are not defined. */
7766 if (event->error_code == BadName)
7767 return;
7769 /* Note that there is no real way portable across R3/R4 to get the
7770 original error handler. */
7772 XGetErrorText (display, event->error_code, buf, sizeof (buf));
7773 sprintf (buf1, "X protocol error: %s on protocol request %d",
7774 buf, event->request_code);
7775 x_connection_closed (display, buf1);
7779 /* This is the handler for X IO errors, always.
7780 It kills all frames on the display that we lost touch with.
7781 If that was the only one, it prints an error message and kills Emacs. */
7783 static int
7784 x_io_error_quitter (Display *display)
7786 char buf[256];
7788 snprintf (buf, sizeof buf, "Connection lost to X server `%s'",
7789 DisplayString (display));
7790 x_connection_closed (display, buf);
7791 return 0;
7794 /* Changing the font of the frame. */
7796 /* Give frame F the font FONT-OBJECT as its default font. The return
7797 value is FONT-OBJECT. FONTSET is an ID of the fontset for the
7798 frame. If it is negative, generate a new fontset from
7799 FONT-OBJECT. */
7801 Lisp_Object
7802 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
7804 struct font *font = XFONT_OBJECT (font_object);
7806 if (fontset < 0)
7807 fontset = fontset_from_font (font_object);
7808 FRAME_FONTSET (f) = fontset;
7809 if (FRAME_FONT (f) == font)
7810 /* This font is already set in frame F. There's nothing more to
7811 do. */
7812 return font_object;
7814 FRAME_FONT (f) = font;
7815 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
7816 FRAME_COLUMN_WIDTH (f) = font->average_width;
7817 FRAME_LINE_HEIGHT (f) = FONT_HEIGHT (font);
7819 compute_fringe_widths (f, 1);
7821 /* Compute the scroll bar width in character columns. */
7822 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
7824 int wid = FRAME_COLUMN_WIDTH (f);
7825 FRAME_CONFIG_SCROLL_BAR_COLS (f)
7826 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid-1) / wid;
7828 else
7830 int wid = FRAME_COLUMN_WIDTH (f);
7831 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
7834 if (FRAME_X_WINDOW (f) != 0)
7836 /* Don't change the size of a tip frame; there's no point in
7837 doing it because it's done in Fx_show_tip, and it leads to
7838 problems because the tip frame has no widget. */
7839 if (NILP (tip_frame) || XFRAME (tip_frame) != f)
7840 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
7843 #ifdef HAVE_X_I18N
7844 if (FRAME_XIC (f)
7845 && (FRAME_XIC_STYLE (f) & (XIMPreeditPosition | XIMStatusArea)))
7847 block_input ();
7848 xic_set_xfontset (f, SSDATA (fontset_ascii (fontset)));
7849 unblock_input ();
7851 #endif
7853 return font_object;
7857 /***********************************************************************
7858 X Input Methods
7859 ***********************************************************************/
7861 #ifdef HAVE_X_I18N
7863 #ifdef HAVE_X11R6
7865 /* XIM destroy callback function, which is called whenever the
7866 connection to input method XIM dies. CLIENT_DATA contains a
7867 pointer to the x_display_info structure corresponding to XIM. */
7869 static void
7870 xim_destroy_callback (XIM xim, XPointer client_data, XPointer call_data)
7872 struct x_display_info *dpyinfo = (struct x_display_info *) client_data;
7873 Lisp_Object frame, tail;
7875 block_input ();
7877 /* No need to call XDestroyIC.. */
7878 FOR_EACH_FRAME (tail, frame)
7880 struct frame *f = XFRAME (frame);
7881 if (FRAME_X_P (f) && FRAME_DISPLAY_INFO (f) == dpyinfo)
7883 FRAME_XIC (f) = NULL;
7884 xic_free_xfontset (f);
7888 /* No need to call XCloseIM. */
7889 dpyinfo->xim = NULL;
7890 XFree (dpyinfo->xim_styles);
7891 unblock_input ();
7894 #endif /* HAVE_X11R6 */
7896 #ifdef HAVE_X11R6
7897 /* This isn't prototyped in OSF 5.0 or 5.1a. */
7898 extern char *XSetIMValues (XIM, ...);
7899 #endif
7901 /* Open the connection to the XIM server on display DPYINFO.
7902 RESOURCE_NAME is the resource name Emacs uses. */
7904 static void
7905 xim_open_dpy (struct x_display_info *dpyinfo, char *resource_name)
7907 XIM xim;
7909 #ifdef HAVE_XIM
7910 if (use_xim)
7912 if (dpyinfo->xim)
7913 XCloseIM (dpyinfo->xim);
7914 xim = XOpenIM (dpyinfo->display, dpyinfo->xrdb, resource_name,
7915 emacs_class);
7916 dpyinfo->xim = xim;
7918 if (xim)
7920 #ifdef HAVE_X11R6
7921 XIMCallback destroy;
7922 #endif
7924 /* Get supported styles and XIM values. */
7925 XGetIMValues (xim, XNQueryInputStyle, &dpyinfo->xim_styles, NULL);
7927 #ifdef HAVE_X11R6
7928 destroy.callback = xim_destroy_callback;
7929 destroy.client_data = (XPointer)dpyinfo;
7930 XSetIMValues (xim, XNDestroyCallback, &destroy, NULL);
7931 #endif
7935 else
7936 #endif /* HAVE_XIM */
7937 dpyinfo->xim = NULL;
7941 #ifdef HAVE_X11R6_XIM
7943 /* XIM instantiate callback function, which is called whenever an XIM
7944 server is available. DISPLAY is the display of the XIM.
7945 CLIENT_DATA contains a pointer to an xim_inst_t structure created
7946 when the callback was registered. */
7948 static void
7949 xim_instantiate_callback (Display *display, XPointer client_data, XPointer call_data)
7951 struct xim_inst_t *xim_inst = (struct xim_inst_t *) client_data;
7952 struct x_display_info *dpyinfo = xim_inst->dpyinfo;
7954 /* We don't support multiple XIM connections. */
7955 if (dpyinfo->xim)
7956 return;
7958 xim_open_dpy (dpyinfo, xim_inst->resource_name);
7960 /* Create XIC for the existing frames on the same display, as long
7961 as they have no XIC. */
7962 if (dpyinfo->xim && dpyinfo->reference_count > 0)
7964 Lisp_Object tail, frame;
7966 block_input ();
7967 FOR_EACH_FRAME (tail, frame)
7969 struct frame *f = XFRAME (frame);
7971 if (FRAME_X_P (f)
7972 && FRAME_DISPLAY_INFO (f) == xim_inst->dpyinfo)
7973 if (FRAME_XIC (f) == NULL)
7975 create_frame_xic (f);
7976 if (FRAME_XIC_STYLE (f) & XIMStatusArea)
7977 xic_set_statusarea (f);
7978 if (FRAME_XIC_STYLE (f) & XIMPreeditPosition)
7980 struct window *w = XWINDOW (f->selected_window);
7981 xic_set_preeditarea (w, w->cursor.x, w->cursor.y);
7986 unblock_input ();
7990 #endif /* HAVE_X11R6_XIM */
7993 /* Open a connection to the XIM server on display DPYINFO.
7994 RESOURCE_NAME is the resource name for Emacs. On X11R5, open the
7995 connection only at the first time. On X11R6, open the connection
7996 in the XIM instantiate callback function. */
7998 static void
7999 xim_initialize (struct x_display_info *dpyinfo, char *resource_name)
8001 dpyinfo->xim = NULL;
8002 #ifdef HAVE_XIM
8003 if (use_xim)
8005 #ifdef HAVE_X11R6_XIM
8006 struct xim_inst_t *xim_inst = xmalloc (sizeof *xim_inst);
8008 dpyinfo->xim_callback_data = xim_inst;
8009 xim_inst->dpyinfo = dpyinfo;
8010 xim_inst->resource_name = xstrdup (resource_name);
8011 XRegisterIMInstantiateCallback (dpyinfo->display, dpyinfo->xrdb,
8012 resource_name, emacs_class,
8013 xim_instantiate_callback,
8014 /* This is XPointer in XFree86
8015 but (XPointer *) on Tru64, at
8016 least, hence the configure test. */
8017 (XRegisterIMInstantiateCallback_arg6) xim_inst);
8018 #else /* not HAVE_X11R6_XIM */
8019 xim_open_dpy (dpyinfo, resource_name);
8020 #endif /* not HAVE_X11R6_XIM */
8022 #endif /* HAVE_XIM */
8026 /* Close the connection to the XIM server on display DPYINFO. */
8028 static void
8029 xim_close_dpy (struct x_display_info *dpyinfo)
8031 #ifdef HAVE_XIM
8032 if (use_xim)
8034 #ifdef HAVE_X11R6_XIM
8035 if (dpyinfo->display)
8036 XUnregisterIMInstantiateCallback (dpyinfo->display, dpyinfo->xrdb,
8037 NULL, emacs_class,
8038 xim_instantiate_callback, NULL);
8039 xfree (dpyinfo->xim_callback_data->resource_name);
8040 xfree (dpyinfo->xim_callback_data);
8041 #endif /* HAVE_X11R6_XIM */
8042 if (dpyinfo->display)
8043 XCloseIM (dpyinfo->xim);
8044 dpyinfo->xim = NULL;
8045 XFree (dpyinfo->xim_styles);
8047 #endif /* HAVE_XIM */
8050 #endif /* not HAVE_X11R6_XIM */
8054 /* Calculate the absolute position in frame F
8055 from its current recorded position values and gravity. */
8057 static void
8058 x_calc_absolute_position (struct frame *f)
8060 int flags = f->size_hint_flags;
8062 /* We have nothing to do if the current position
8063 is already for the top-left corner. */
8064 if (! ((flags & XNegative) || (flags & YNegative)))
8065 return;
8067 /* Treat negative positions as relative to the leftmost bottommost
8068 position that fits on the screen. */
8069 if (flags & XNegative)
8070 f->left_pos = x_display_pixel_width (FRAME_DISPLAY_INFO (f))
8071 - FRAME_PIXEL_WIDTH (f) + f->left_pos;
8074 int height = FRAME_PIXEL_HEIGHT (f);
8076 #if defined USE_X_TOOLKIT && defined USE_MOTIF
8077 /* Something is fishy here. When using Motif, starting Emacs with
8078 `-g -0-0', the frame appears too low by a few pixels.
8080 This seems to be so because initially, while Emacs is starting,
8081 the column widget's height and the frame's pixel height are
8082 different. The column widget's height is the right one. In
8083 later invocations, when Emacs is up, the frame's pixel height
8084 is right, though.
8086 It's not obvious where the initial small difference comes from.
8087 2000-12-01, gerd. */
8089 XtVaGetValues (f->output_data.x->column_widget, XtNheight, &height, NULL);
8090 #endif
8092 if (flags & YNegative)
8093 f->top_pos = x_display_pixel_height (FRAME_DISPLAY_INFO (f))
8094 - height + f->top_pos;
8097 /* The left_pos and top_pos
8098 are now relative to the top and left screen edges,
8099 so the flags should correspond. */
8100 f->size_hint_flags &= ~ (XNegative | YNegative);
8103 /* CHANGE_GRAVITY is 1 when calling from Fset_frame_position,
8104 to really change the position, and 0 when calling from
8105 x_make_frame_visible (in that case, XOFF and YOFF are the current
8106 position values). It is -1 when calling from x_set_frame_parameters,
8107 which means, do adjust for borders but don't change the gravity. */
8109 void
8110 x_set_offset (struct frame *f, register int xoff, register int yoff, int change_gravity)
8112 int modified_top, modified_left;
8114 if (change_gravity > 0)
8116 f->top_pos = yoff;
8117 f->left_pos = xoff;
8118 f->size_hint_flags &= ~ (XNegative | YNegative);
8119 if (xoff < 0)
8120 f->size_hint_flags |= XNegative;
8121 if (yoff < 0)
8122 f->size_hint_flags |= YNegative;
8123 f->win_gravity = NorthWestGravity;
8125 x_calc_absolute_position (f);
8127 block_input ();
8128 x_wm_set_size_hint (f, (long) 0, 0);
8130 modified_left = f->left_pos;
8131 modified_top = f->top_pos;
8133 if (change_gravity != 0 && FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A)
8135 /* Some WMs (twm, wmaker at least) has an offset that is smaller
8136 than the WM decorations. So we use the calculated offset instead
8137 of the WM decoration sizes here (x/y_pixels_outer_diff). */
8138 modified_left += FRAME_X_OUTPUT (f)->move_offset_left;
8139 modified_top += FRAME_X_OUTPUT (f)->move_offset_top;
8142 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8143 modified_left, modified_top);
8145 x_sync_with_move (f, f->left_pos, f->top_pos,
8146 FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN
8147 ? 1 : 0);
8149 /* change_gravity is non-zero when this function is called from Lisp to
8150 programmatically move a frame. In that case, we call
8151 x_check_expected_move to discover if we have a "Type A" or "Type B"
8152 window manager, and, for a "Type A" window manager, adjust the position
8153 of the frame.
8155 We call x_check_expected_move if a programmatic move occurred, and
8156 either the window manager type (A/B) is unknown or it is Type A but we
8157 need to compute the top/left offset adjustment for this frame. */
8159 if (change_gravity != 0 &&
8160 (FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN
8161 || (FRAME_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A
8162 && (FRAME_X_OUTPUT (f)->move_offset_left == 0
8163 && FRAME_X_OUTPUT (f)->move_offset_top == 0))))
8164 x_check_expected_move (f, modified_left, modified_top);
8166 unblock_input ();
8169 /* Return non-zero if _NET_SUPPORTING_WM_CHECK window exists and _NET_SUPPORTED
8170 on the root window for frame F contains ATOMNAME.
8171 This is how a WM check shall be done according to the Window Manager
8172 Specification/Extended Window Manager Hints at
8173 http://freedesktop.org/wiki/Specifications/wm-spec. */
8175 static int
8176 wm_supports (struct frame *f, Atom want_atom)
8178 Atom actual_type;
8179 unsigned long actual_size, bytes_remaining;
8180 int i, rc, actual_format;
8181 Window wmcheck_window;
8182 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
8183 Window target_window = dpyinfo->root_window;
8184 long max_len = 65536;
8185 Display *dpy = FRAME_X_DISPLAY (f);
8186 unsigned char *tmp_data = NULL;
8187 Atom target_type = XA_WINDOW;
8189 block_input ();
8191 x_catch_errors (dpy);
8192 rc = XGetWindowProperty (dpy, target_window,
8193 dpyinfo->Xatom_net_supporting_wm_check,
8194 0, max_len, False, target_type,
8195 &actual_type, &actual_format, &actual_size,
8196 &bytes_remaining, &tmp_data);
8198 if (rc != Success || actual_type != XA_WINDOW || x_had_errors_p (dpy))
8200 if (tmp_data) XFree (tmp_data);
8201 x_uncatch_errors ();
8202 unblock_input ();
8203 return 0;
8206 wmcheck_window = *(Window *) tmp_data;
8207 XFree (tmp_data);
8209 /* Check if window exists. */
8210 XSelectInput (dpy, wmcheck_window, StructureNotifyMask);
8211 x_sync (f);
8212 if (x_had_errors_p (dpy))
8214 x_uncatch_errors ();
8215 unblock_input ();
8216 return 0;
8219 if (dpyinfo->net_supported_window != wmcheck_window)
8221 /* Window changed, reload atoms */
8222 if (dpyinfo->net_supported_atoms != NULL)
8223 XFree (dpyinfo->net_supported_atoms);
8224 dpyinfo->net_supported_atoms = NULL;
8225 dpyinfo->nr_net_supported_atoms = 0;
8226 dpyinfo->net_supported_window = 0;
8228 target_type = XA_ATOM;
8229 tmp_data = NULL;
8230 rc = XGetWindowProperty (dpy, target_window,
8231 dpyinfo->Xatom_net_supported,
8232 0, max_len, False, target_type,
8233 &actual_type, &actual_format, &actual_size,
8234 &bytes_remaining, &tmp_data);
8236 if (rc != Success || actual_type != XA_ATOM || x_had_errors_p (dpy))
8238 if (tmp_data) XFree (tmp_data);
8239 x_uncatch_errors ();
8240 unblock_input ();
8241 return 0;
8244 dpyinfo->net_supported_atoms = (Atom *)tmp_data;
8245 dpyinfo->nr_net_supported_atoms = actual_size;
8246 dpyinfo->net_supported_window = wmcheck_window;
8249 rc = 0;
8251 for (i = 0; rc == 0 && i < dpyinfo->nr_net_supported_atoms; ++i)
8252 rc = dpyinfo->net_supported_atoms[i] == want_atom;
8254 x_uncatch_errors ();
8255 unblock_input ();
8257 return rc;
8260 static void
8261 set_wm_state (Lisp_Object frame, int add, Atom atom, Atom value)
8263 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (XFRAME (frame));
8265 x_send_client_event (frame, make_number (0), frame,
8266 dpyinfo->Xatom_net_wm_state,
8267 make_number (32),
8268 /* 1 = add, 0 = remove */
8269 Fcons
8270 (make_number (add ? 1 : 0),
8271 Fcons
8272 (make_fixnum_or_float (atom),
8273 (value != 0
8274 ? list1 (make_fixnum_or_float (value))
8275 : Qnil))));
8278 void
8279 x_set_sticky (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
8281 Lisp_Object frame;
8282 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
8284 XSETFRAME (frame, f);
8286 set_wm_state (frame, NILP (new_value) ? 0 : 1,
8287 dpyinfo->Xatom_net_wm_state_sticky, None);
8290 /* Return the current _NET_WM_STATE.
8291 SIZE_STATE is set to one of the FULLSCREEN_* values.
8292 STICKY is set to 1 if the sticky state is set, 0 if not.
8294 Return non-zero if we are not hidden, zero if we are. */
8296 static int
8297 get_current_wm_state (struct frame *f,
8298 Window window,
8299 int *size_state,
8300 int *sticky)
8302 Atom actual_type;
8303 unsigned long actual_size, bytes_remaining;
8304 int i, rc, actual_format, is_hidden = 0;
8305 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
8306 long max_len = 65536;
8307 Display *dpy = FRAME_X_DISPLAY (f);
8308 unsigned char *tmp_data = NULL;
8309 Atom target_type = XA_ATOM;
8311 *sticky = 0;
8312 *size_state = FULLSCREEN_NONE;
8314 block_input ();
8315 x_catch_errors (dpy);
8316 rc = XGetWindowProperty (dpy, window, dpyinfo->Xatom_net_wm_state,
8317 0, max_len, False, target_type,
8318 &actual_type, &actual_format, &actual_size,
8319 &bytes_remaining, &tmp_data);
8321 if (rc != Success || actual_type != target_type || x_had_errors_p (dpy))
8323 if (tmp_data) XFree (tmp_data);
8324 x_uncatch_errors ();
8325 unblock_input ();
8326 return !FRAME_ICONIFIED_P (f);
8329 x_uncatch_errors ();
8331 for (i = 0; i < actual_size; ++i)
8333 Atom a = ((Atom*)tmp_data)[i];
8334 if (a == dpyinfo->Xatom_net_wm_state_hidden)
8336 is_hidden = 1;
8337 f->output_data.x->net_wm_state_hidden_seen = 1;
8339 else if (a == dpyinfo->Xatom_net_wm_state_maximized_horz)
8341 if (*size_state == FULLSCREEN_HEIGHT)
8342 *size_state = FULLSCREEN_MAXIMIZED;
8343 else
8344 *size_state = FULLSCREEN_WIDTH;
8346 else if (a == dpyinfo->Xatom_net_wm_state_maximized_vert)
8348 if (*size_state == FULLSCREEN_WIDTH)
8349 *size_state = FULLSCREEN_MAXIMIZED;
8350 else
8351 *size_state = FULLSCREEN_HEIGHT;
8353 else if (a == dpyinfo->Xatom_net_wm_state_fullscreen)
8354 *size_state = FULLSCREEN_BOTH;
8355 else if (a == dpyinfo->Xatom_net_wm_state_sticky)
8356 *sticky = 1;
8359 if (tmp_data) XFree (tmp_data);
8360 unblock_input ();
8361 return ! is_hidden;
8364 /* Do fullscreen as specified in extended window manager hints */
8366 static int
8367 do_ewmh_fullscreen (struct frame *f)
8369 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
8370 int have_net_atom = wm_supports (f, dpyinfo->Xatom_net_wm_state);
8371 int cur, dummy;
8373 (void)get_current_wm_state (f, FRAME_OUTER_WINDOW (f), &cur, &dummy);
8375 /* Some window managers don't say they support _NET_WM_STATE, but they do say
8376 they support _NET_WM_STATE_FULLSCREEN. Try that also. */
8377 if (!have_net_atom)
8378 have_net_atom = wm_supports (f, dpyinfo->Xatom_net_wm_state_fullscreen);
8380 if (have_net_atom && cur != f->want_fullscreen)
8382 Lisp_Object frame;
8384 XSETFRAME (frame, f);
8386 /* Keep number of calls to set_wm_state as low as possible.
8387 Some window managers, or possible Gtk+, hangs when too many
8388 are sent at once. */
8389 switch (f->want_fullscreen)
8391 case FULLSCREEN_BOTH:
8392 if (cur == FULLSCREEN_WIDTH || cur == FULLSCREEN_MAXIMIZED
8393 || cur == FULLSCREEN_HEIGHT)
8394 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_maximized_horz,
8395 dpyinfo->Xatom_net_wm_state_maximized_vert);
8396 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_fullscreen, None);
8397 break;
8398 case FULLSCREEN_WIDTH:
8399 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_HEIGHT
8400 || cur == FULLSCREEN_MAXIMIZED)
8401 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen,
8402 dpyinfo->Xatom_net_wm_state_maximized_vert);
8403 if (cur != FULLSCREEN_MAXIMIZED)
8404 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_maximized_horz, None);
8405 break;
8406 case FULLSCREEN_HEIGHT:
8407 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_WIDTH
8408 || cur == FULLSCREEN_MAXIMIZED)
8409 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen,
8410 dpyinfo->Xatom_net_wm_state_maximized_horz);
8411 if (cur != FULLSCREEN_MAXIMIZED)
8412 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_maximized_vert, None);
8413 break;
8414 case FULLSCREEN_MAXIMIZED:
8415 if (cur == FULLSCREEN_BOTH)
8416 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen, None);
8417 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_maximized_horz,
8418 dpyinfo->Xatom_net_wm_state_maximized_vert);
8419 break;
8420 case FULLSCREEN_NONE:
8421 if (cur == FULLSCREEN_BOTH)
8422 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen, None);
8423 else
8424 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_maximized_horz,
8425 dpyinfo->Xatom_net_wm_state_maximized_vert);
8428 f->want_fullscreen = FULLSCREEN_NONE;
8432 return have_net_atom;
8435 static void
8436 XTfullscreen_hook (struct frame *f)
8438 if (FRAME_VISIBLE_P (f))
8440 block_input ();
8441 x_check_fullscreen (f);
8442 x_sync (f);
8443 unblock_input ();
8448 static int
8449 x_handle_net_wm_state (struct frame *f, const XPropertyEvent *event)
8451 int value = FULLSCREEN_NONE;
8452 Lisp_Object lval;
8453 int sticky = 0;
8454 int not_hidden = get_current_wm_state (f, event->window, &value, &sticky);
8456 lval = Qnil;
8457 switch (value)
8459 case FULLSCREEN_WIDTH:
8460 lval = Qfullwidth;
8461 break;
8462 case FULLSCREEN_HEIGHT:
8463 lval = Qfullheight;
8464 break;
8465 case FULLSCREEN_BOTH:
8466 lval = Qfullboth;
8467 break;
8468 case FULLSCREEN_MAXIMIZED:
8469 lval = Qmaximized;
8470 break;
8473 store_frame_param (f, Qfullscreen, lval);
8474 store_frame_param (f, Qsticky, sticky ? Qt : Qnil);
8476 return not_hidden;
8479 /* Check if we need to resize the frame due to a fullscreen request.
8480 If so needed, resize the frame. */
8481 static void
8482 x_check_fullscreen (struct frame *f)
8484 if (do_ewmh_fullscreen (f))
8485 return;
8487 if (f->output_data.x->parent_desc != FRAME_DISPLAY_INFO (f)->root_window)
8488 return; /* Only fullscreen without WM or with EWM hints (above). */
8490 /* Setting fullscreen to nil doesn't do anything. We could save the
8491 last non-fullscreen size and restore it, but it seems like a
8492 lot of work for this unusual case (no window manager running). */
8494 if (f->want_fullscreen != FULLSCREEN_NONE)
8496 int width = FRAME_PIXEL_WIDTH (f), height = FRAME_PIXEL_HEIGHT (f);
8497 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
8499 switch (f->want_fullscreen)
8501 /* No difference between these two when there is no WM */
8502 case FULLSCREEN_BOTH:
8503 case FULLSCREEN_MAXIMIZED:
8504 width = x_display_pixel_width (dpyinfo);
8505 height = x_display_pixel_height (dpyinfo);
8506 break;
8507 case FULLSCREEN_WIDTH:
8508 width = x_display_pixel_width (dpyinfo);
8509 break;
8510 case FULLSCREEN_HEIGHT:
8511 height = x_display_pixel_height (dpyinfo);
8514 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8515 width, height);
8519 /* This function is called by x_set_offset to determine whether the window
8520 manager interfered with the positioning of the frame. Type A window
8521 managers position the surrounding window manager decorations a small
8522 amount above and left of the user-supplied position. Type B window
8523 managers position the surrounding window manager decorations at the
8524 user-specified position. If we detect a Type A window manager, we
8525 compensate by moving the window right and down by the proper amount. */
8527 static void
8528 x_check_expected_move (struct frame *f, int expected_left, int expected_top)
8530 int current_left = 0, current_top = 0;
8532 /* x_real_positions returns the left and top offsets of the outermost
8533 window manager window around the frame. */
8535 x_real_positions (f, &current_left, &current_top);
8537 if (current_left != expected_left || current_top != expected_top)
8539 /* It's a "Type A" window manager. */
8541 int adjusted_left;
8542 int adjusted_top;
8544 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_A;
8545 FRAME_X_OUTPUT (f)->move_offset_left = expected_left - current_left;
8546 FRAME_X_OUTPUT (f)->move_offset_top = expected_top - current_top;
8548 /* Now fix the mispositioned frame's location. */
8550 adjusted_left = expected_left + FRAME_X_OUTPUT (f)->move_offset_left;
8551 adjusted_top = expected_top + FRAME_X_OUTPUT (f)->move_offset_top;
8553 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8554 adjusted_left, adjusted_top);
8556 x_sync_with_move (f, expected_left, expected_top, 0);
8558 else
8559 /* It's a "Type B" window manager. We don't have to adjust the
8560 frame's position. */
8562 FRAME_DISPLAY_INFO (f)->wm_type = X_WMTYPE_B;
8566 /* Wait for XGetGeometry to return up-to-date position information for a
8567 recently-moved frame. Call this immediately after calling XMoveWindow.
8568 If FUZZY is non-zero, then LEFT and TOP are just estimates of where the
8569 frame has been moved to, so we use a fuzzy position comparison instead
8570 of an exact comparison. */
8572 static void
8573 x_sync_with_move (struct frame *f, int left, int top, int fuzzy)
8575 int count = 0;
8577 while (count++ < 50)
8579 int current_left = 0, current_top = 0;
8581 /* In theory, this call to XSync only needs to happen once, but in
8582 practice, it doesn't seem to work, hence the need for the surrounding
8583 loop. */
8585 XSync (FRAME_X_DISPLAY (f), False);
8586 x_real_positions (f, &current_left, &current_top);
8588 if (fuzzy)
8590 /* The left fuzz-factor is 10 pixels. The top fuzz-factor is 40
8591 pixels. */
8593 if (eabs (current_left - left) <= 10
8594 && eabs (current_top - top) <= 40)
8595 return;
8597 else if (current_left == left && current_top == top)
8598 return;
8601 /* As a last resort, just wait 0.5 seconds and hope that XGetGeometry
8602 will then return up-to-date position info. */
8604 wait_reading_process_output (0, 500000, 0, 0, Qnil, NULL, 0);
8608 /* Wait for an event on frame F matching EVENTTYPE. */
8609 void
8610 x_wait_for_event (struct frame *f, int eventtype)
8612 int level = interrupt_input_blocked;
8614 fd_set fds;
8615 struct timespec tmo, tmo_at, time_now;
8616 int fd = ConnectionNumber (FRAME_X_DISPLAY (f));
8618 f->wait_event_type = eventtype;
8620 /* Set timeout to 0.1 second. Hopefully not noticeable.
8621 Maybe it should be configurable. */
8622 tmo = make_timespec (0, 100 * 1000 * 1000);
8623 tmo_at = timespec_add (current_timespec (), tmo);
8625 while (f->wait_event_type)
8627 pending_signals = 1;
8628 totally_unblock_input ();
8629 /* XTread_socket is called after unblock. */
8630 block_input ();
8631 interrupt_input_blocked = level;
8633 FD_ZERO (&fds);
8634 FD_SET (fd, &fds);
8636 time_now = current_timespec ();
8637 if (timespec_cmp (tmo_at, time_now) < 0)
8638 break;
8640 tmo = timespec_sub (tmo_at, time_now);
8641 if (pselect (fd + 1, &fds, NULL, NULL, &tmo, NULL) == 0)
8642 break; /* Timeout */
8645 f->wait_event_type = 0;
8649 /* Change the size of frame F's X window to COLS/ROWS in the case F
8650 doesn't have a widget. If CHANGE_GRAVITY is 1, we change to
8651 top-left-corner window gravity for this size change and subsequent
8652 size changes. Otherwise we leave the window gravity unchanged. */
8654 static void
8655 x_set_window_size_1 (struct frame *f, int change_gravity, int cols, int rows)
8657 int pixelwidth, pixelheight;
8659 check_frame_size (f, &rows, &cols);
8660 f->scroll_bar_actual_width
8661 = (!FRAME_HAS_VERTICAL_SCROLL_BARS (f)
8663 : FRAME_CONFIG_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f));
8665 compute_fringe_widths (f, 0);
8667 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, cols)
8668 + FRAME_TOOLBAR_WIDTH (f);
8669 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows)
8670 + FRAME_MENUBAR_HEIGHT (f) + FRAME_TOOLBAR_HEIGHT (f);
8672 if (change_gravity) f->win_gravity = NorthWestGravity;
8673 x_wm_set_size_hint (f, (long) 0, 0);
8674 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8675 pixelwidth, pixelheight);
8678 /* We've set {FRAME,PIXEL}_{WIDTH,HEIGHT} to the values we hope to
8679 receive in the ConfigureNotify event; if we get what we asked
8680 for, then the event won't cause the screen to become garbaged, so
8681 we have to make sure to do it here. */
8682 SET_FRAME_GARBAGED (f);
8684 /* Now, strictly speaking, we can't be sure that this is accurate,
8685 but the window manager will get around to dealing with the size
8686 change request eventually, and we'll hear how it went when the
8687 ConfigureNotify event gets here.
8689 We could just not bother storing any of this information here,
8690 and let the ConfigureNotify event set everything up, but that
8691 might be kind of confusing to the Lisp code, since size changes
8692 wouldn't be reported in the frame parameters until some random
8693 point in the future when the ConfigureNotify event arrives.
8695 We pass 1 for DELAY since we can't run Lisp code inside of
8696 a BLOCK_INPUT. */
8698 /* But the ConfigureNotify may in fact never arrive, and then this is
8699 not right if the frame is visible. Instead wait (with timeout)
8700 for the ConfigureNotify. */
8701 if (FRAME_VISIBLE_P (f))
8702 x_wait_for_event (f, ConfigureNotify);
8703 else
8705 change_frame_size (f, rows, cols, 0, 1, 0);
8706 FRAME_PIXEL_WIDTH (f) = pixelwidth;
8707 FRAME_PIXEL_HEIGHT (f) = pixelheight;
8708 x_sync (f);
8713 /* Call this to change the size of frame F's x-window.
8714 If CHANGE_GRAVITY is 1, we change to top-left-corner window gravity
8715 for this size change and subsequent size changes.
8716 Otherwise we leave the window gravity unchanged. */
8718 void
8719 x_set_window_size (struct frame *f, int change_gravity, int cols, int rows)
8721 block_input ();
8723 if (NILP (tip_frame) || XFRAME (tip_frame) != f)
8725 int r, c;
8727 /* When the frame is maximized/fullscreen or running under for
8728 example Xmonad, x_set_window_size_1 will be a no-op.
8729 In that case, the right thing to do is extend rows/cols to
8730 the current frame size. We do that first if x_set_window_size_1
8731 turns out to not be a no-op (there is no way to know).
8732 The size will be adjusted again if the frame gets a
8733 ConfigureNotify event as a result of x_set_window_size. */
8734 int pixelh = FRAME_PIXEL_HEIGHT (f);
8735 #ifdef USE_X_TOOLKIT
8736 /* The menu bar is not part of text lines. The tool bar
8737 is however. */
8738 pixelh -= FRAME_MENUBAR_HEIGHT (f);
8739 #endif
8740 r = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, pixelh);
8741 /* Update f->scroll_bar_actual_width because it is used in
8742 FRAME_PIXEL_WIDTH_TO_TEXT_COLS. */
8743 f->scroll_bar_actual_width
8744 = FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f);
8745 c = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, FRAME_PIXEL_WIDTH (f));
8746 change_frame_size (f, r, c, 0, 1, 0);
8749 #ifdef USE_GTK
8750 if (FRAME_GTK_WIDGET (f))
8751 xg_frame_set_char_size (f, cols, rows);
8752 else
8753 x_set_window_size_1 (f, change_gravity, cols, rows);
8754 #else /* not USE_GTK */
8756 x_set_window_size_1 (f, change_gravity, cols, rows);
8758 #endif /* not USE_GTK */
8760 /* If cursor was outside the new size, mark it as off. */
8761 mark_window_cursors_off (XWINDOW (f->root_window));
8763 /* Clear out any recollection of where the mouse highlighting was,
8764 since it might be in a place that's outside the new frame size.
8765 Actually checking whether it is outside is a pain in the neck,
8766 so don't try--just let the highlighting be done afresh with new size. */
8767 cancel_mouse_face (f);
8769 unblock_input ();
8772 /* Mouse warping. */
8774 void
8775 x_set_mouse_position (struct frame *f, int x, int y)
8777 int pix_x, pix_y;
8779 pix_x = FRAME_COL_TO_PIXEL_X (f, x) + FRAME_COLUMN_WIDTH (f) / 2;
8780 pix_y = FRAME_LINE_TO_PIXEL_Y (f, y) + FRAME_LINE_HEIGHT (f) / 2;
8782 if (pix_x < 0) pix_x = 0;
8783 if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
8785 if (pix_y < 0) pix_y = 0;
8786 if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
8788 block_input ();
8790 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
8791 0, 0, 0, 0, pix_x, pix_y);
8792 unblock_input ();
8795 /* Move the mouse to position pixel PIX_X, PIX_Y relative to frame F. */
8797 void
8798 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
8800 block_input ();
8802 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
8803 0, 0, 0, 0, pix_x, pix_y);
8804 unblock_input ();
8807 /* Raise frame F. */
8809 void
8810 x_raise_frame (struct frame *f)
8812 block_input ();
8813 if (FRAME_VISIBLE_P (f))
8814 XRaiseWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
8815 XFlush (FRAME_X_DISPLAY (f));
8816 unblock_input ();
8819 /* Lower frame F. */
8821 static void
8822 x_lower_frame (struct frame *f)
8824 if (FRAME_VISIBLE_P (f))
8826 block_input ();
8827 XLowerWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
8828 XFlush (FRAME_X_DISPLAY (f));
8829 unblock_input ();
8833 /* Request focus with XEmbed */
8835 void
8836 xembed_request_focus (struct frame *f)
8838 /* See XEmbed Protocol Specification at
8839 http://freedesktop.org/wiki/Specifications/xembed-spec */
8840 if (FRAME_VISIBLE_P (f))
8841 xembed_send_message (f, CurrentTime,
8842 XEMBED_REQUEST_FOCUS, 0, 0, 0);
8845 /* Activate frame with Extended Window Manager Hints */
8847 void
8848 x_ewmh_activate_frame (struct frame *f)
8850 /* See Window Manager Specification/Extended Window Manager Hints at
8851 http://freedesktop.org/wiki/Specifications/wm-spec */
8853 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
8855 if (FRAME_VISIBLE_P (f) && wm_supports (f, dpyinfo->Xatom_net_active_window))
8857 Lisp_Object frame;
8858 XSETFRAME (frame, f);
8859 x_send_client_event (frame, make_number (0), frame,
8860 dpyinfo->Xatom_net_active_window,
8861 make_number (32),
8862 list2i (1, dpyinfo->last_user_time));
8866 static void
8867 XTframe_raise_lower (struct frame *f, int raise_flag)
8869 if (raise_flag)
8870 x_raise_frame (f);
8871 else
8872 x_lower_frame (f);
8875 /* XEmbed implementation. */
8877 #if defined USE_X_TOOLKIT || ! defined USE_GTK
8879 /* XEmbed implementation. */
8881 #define XEMBED_VERSION 0
8883 static void
8884 xembed_set_info (struct frame *f, enum xembed_info flags)
8886 unsigned long data[2];
8887 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
8889 data[0] = XEMBED_VERSION;
8890 data[1] = flags;
8892 XChangeProperty (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8893 dpyinfo->Xatom_XEMBED_INFO, dpyinfo->Xatom_XEMBED_INFO,
8894 32, PropModeReplace, (unsigned char *) data, 2);
8896 #endif /* defined USE_X_TOOLKIT || ! defined USE_GTK */
8898 static void
8899 xembed_send_message (struct frame *f, Time t, enum xembed_message msg,
8900 long int detail, long int data1, long int data2)
8902 XEvent event;
8904 event.xclient.type = ClientMessage;
8905 event.xclient.window = FRAME_X_OUTPUT (f)->parent_desc;
8906 event.xclient.message_type = FRAME_DISPLAY_INFO (f)->Xatom_XEMBED;
8907 event.xclient.format = 32;
8908 event.xclient.data.l[0] = t;
8909 event.xclient.data.l[1] = msg;
8910 event.xclient.data.l[2] = detail;
8911 event.xclient.data.l[3] = data1;
8912 event.xclient.data.l[4] = data2;
8914 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_OUTPUT (f)->parent_desc,
8915 False, NoEventMask, &event);
8916 XSync (FRAME_X_DISPLAY (f), False);
8919 /* Change of visibility. */
8921 /* This tries to wait until the frame is really visible.
8922 However, if the window manager asks the user where to position
8923 the frame, this will return before the user finishes doing that.
8924 The frame will not actually be visible at that time,
8925 but it will become visible later when the window manager
8926 finishes with it. */
8928 void
8929 x_make_frame_visible (struct frame *f)
8931 int original_top, original_left;
8932 int retry_count = 2;
8934 retry:
8936 block_input ();
8938 x_set_bitmap_icon (f);
8940 if (! FRAME_VISIBLE_P (f))
8942 /* We test FRAME_GARBAGED_P here to make sure we don't
8943 call x_set_offset a second time
8944 if we get to x_make_frame_visible a second time
8945 before the window gets really visible. */
8946 if (! FRAME_ICONIFIED_P (f)
8947 && ! FRAME_X_EMBEDDED_P (f)
8948 && ! f->output_data.x->asked_for_visible)
8949 x_set_offset (f, f->left_pos, f->top_pos, 0);
8951 f->output_data.x->asked_for_visible = 1;
8953 if (! EQ (Vx_no_window_manager, Qt))
8954 x_wm_set_window_state (f, NormalState);
8955 #ifdef USE_X_TOOLKIT
8956 if (FRAME_X_EMBEDDED_P (f))
8957 xembed_set_info (f, XEMBED_MAPPED);
8958 else
8960 /* This was XtPopup, but that did nothing for an iconified frame. */
8961 XtMapWidget (f->output_data.x->widget);
8963 #else /* not USE_X_TOOLKIT */
8964 #ifdef USE_GTK
8965 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
8966 gtk_window_deiconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
8967 #else
8968 if (FRAME_X_EMBEDDED_P (f))
8969 xembed_set_info (f, XEMBED_MAPPED);
8970 else
8971 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
8972 #endif /* not USE_GTK */
8973 #endif /* not USE_X_TOOLKIT */
8976 XFlush (FRAME_X_DISPLAY (f));
8978 /* Synchronize to ensure Emacs knows the frame is visible
8979 before we do anything else. We do this loop with input not blocked
8980 so that incoming events are handled. */
8982 Lisp_Object frame;
8983 int count;
8984 /* This must be before UNBLOCK_INPUT
8985 since events that arrive in response to the actions above
8986 will set it when they are handled. */
8987 int previously_visible = f->output_data.x->has_been_visible;
8989 original_left = f->left_pos;
8990 original_top = f->top_pos;
8992 /* This must come after we set COUNT. */
8993 unblock_input ();
8995 /* We unblock here so that arriving X events are processed. */
8997 /* Now move the window back to where it was "supposed to be".
8998 But don't do it if the gravity is negative.
8999 When the gravity is negative, this uses a position
9000 that is 3 pixels too low. Perhaps that's really the border width.
9002 Don't do this if the window has never been visible before,
9003 because the window manager may choose the position
9004 and we don't want to override it. */
9006 if (! FRAME_VISIBLE_P (f)
9007 && ! FRAME_ICONIFIED_P (f)
9008 && ! FRAME_X_EMBEDDED_P (f)
9009 && f->win_gravity == NorthWestGravity
9010 && previously_visible)
9012 Drawable rootw;
9013 int x, y;
9014 unsigned int width, height, border, depth;
9016 block_input ();
9018 /* On some window managers (such as FVWM) moving an existing
9019 window, even to the same place, causes the window manager
9020 to introduce an offset. This can cause the window to move
9021 to an unexpected location. Check the geometry (a little
9022 slow here) and then verify that the window is in the right
9023 place. If the window is not in the right place, move it
9024 there, and take the potential window manager hit. */
9025 XGetGeometry (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
9026 &rootw, &x, &y, &width, &height, &border, &depth);
9028 if (original_left != x || original_top != y)
9029 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
9030 original_left, original_top);
9032 unblock_input ();
9035 XSETFRAME (frame, f);
9037 /* Wait until the frame is visible. Process X events until a
9038 MapNotify event has been seen, or until we think we won't get a
9039 MapNotify at all.. */
9040 for (count = input_signal_count + 10;
9041 input_signal_count < count && !FRAME_VISIBLE_P (f);)
9043 /* Force processing of queued events. */
9044 x_sync (f);
9046 /* Machines that do polling rather than SIGIO have been
9047 observed to go into a busy-wait here. So we'll fake an
9048 alarm signal to let the handler know that there's something
9049 to be read. We used to raise a real alarm, but it seems
9050 that the handler isn't always enabled here. This is
9051 probably a bug. */
9052 if (input_polling_used ())
9054 /* It could be confusing if a real alarm arrives while
9055 processing the fake one. Turn it off and let the
9056 handler reset it. */
9057 int old_poll_suppress_count = poll_suppress_count;
9058 poll_suppress_count = 1;
9059 poll_for_input_1 ();
9060 poll_suppress_count = old_poll_suppress_count;
9064 /* 2000-09-28: In
9066 (let ((f (selected-frame)))
9067 (iconify-frame f)
9068 (raise-frame f))
9070 the frame is not raised with various window managers on
9071 FreeBSD, GNU/Linux and Solaris. It turns out that, for some
9072 unknown reason, the call to XtMapWidget is completely ignored.
9073 Mapping the widget a second time works. */
9075 if (!FRAME_VISIBLE_P (f) && --retry_count != 0)
9076 goto retry;
9080 /* Change from mapped state to withdrawn state. */
9082 /* Make the frame visible (mapped and not iconified). */
9084 void
9085 x_make_frame_invisible (struct frame *f)
9087 Window window;
9089 /* Use the frame's outermost window, not the one we normally draw on. */
9090 window = FRAME_OUTER_WINDOW (f);
9092 /* Don't keep the highlight on an invisible frame. */
9093 if (FRAME_DISPLAY_INFO (f)->x_highlight_frame == f)
9094 FRAME_DISPLAY_INFO (f)->x_highlight_frame = 0;
9096 block_input ();
9098 /* Before unmapping the window, update the WM_SIZE_HINTS property to claim
9099 that the current position of the window is user-specified, rather than
9100 program-specified, so that when the window is mapped again, it will be
9101 placed at the same location, without forcing the user to position it
9102 by hand again (they have already done that once for this window.) */
9103 x_wm_set_size_hint (f, (long) 0, 1);
9105 #ifdef USE_GTK
9106 if (FRAME_GTK_OUTER_WIDGET (f))
9107 gtk_widget_hide (FRAME_GTK_OUTER_WIDGET (f));
9108 else
9109 #else
9110 if (FRAME_X_EMBEDDED_P (f))
9111 xembed_set_info (f, 0);
9112 else
9113 #endif
9116 if (! XWithdrawWindow (FRAME_X_DISPLAY (f), window,
9117 DefaultScreen (FRAME_X_DISPLAY (f))))
9119 unblock_input ();
9120 error ("Can't notify window manager of window withdrawal");
9124 /* We can't distinguish this from iconification
9125 just by the event that we get from the server.
9126 So we can't win using the usual strategy of letting
9127 FRAME_SAMPLE_VISIBILITY set this. So do it by hand,
9128 and synchronize with the server to make sure we agree. */
9129 SET_FRAME_VISIBLE (f, 0);
9130 SET_FRAME_ICONIFIED (f, 0);
9132 x_sync (f);
9134 unblock_input ();
9137 /* Change window state from mapped to iconified. */
9139 void
9140 x_iconify_frame (struct frame *f)
9142 #ifdef USE_X_TOOLKIT
9143 int result;
9144 #endif
9146 /* Don't keep the highlight on an invisible frame. */
9147 if (FRAME_DISPLAY_INFO (f)->x_highlight_frame == f)
9148 FRAME_DISPLAY_INFO (f)->x_highlight_frame = 0;
9150 if (FRAME_ICONIFIED_P (f))
9151 return;
9153 block_input ();
9155 x_set_bitmap_icon (f);
9157 #if defined (USE_GTK)
9158 if (FRAME_GTK_OUTER_WIDGET (f))
9160 if (! FRAME_VISIBLE_P (f))
9161 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
9163 gtk_window_iconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
9164 SET_FRAME_VISIBLE (f, 0);
9165 SET_FRAME_ICONIFIED (f, 1);
9166 unblock_input ();
9167 return;
9169 #endif
9171 #ifdef USE_X_TOOLKIT
9173 if (! FRAME_VISIBLE_P (f))
9175 if (! EQ (Vx_no_window_manager, Qt))
9176 x_wm_set_window_state (f, IconicState);
9177 /* This was XtPopup, but that did nothing for an iconified frame. */
9178 XtMapWidget (f->output_data.x->widget);
9179 /* The server won't give us any event to indicate
9180 that an invisible frame was changed to an icon,
9181 so we have to record it here. */
9182 SET_FRAME_VISIBLE (f, 0);
9183 SET_FRAME_ICONIFIED (f, 1);
9184 unblock_input ();
9185 return;
9188 result = XIconifyWindow (FRAME_X_DISPLAY (f),
9189 XtWindow (f->output_data.x->widget),
9190 DefaultScreen (FRAME_X_DISPLAY (f)));
9191 unblock_input ();
9193 if (!result)
9194 error ("Can't notify window manager of iconification");
9196 SET_FRAME_ICONIFIED (f, 1);
9197 SET_FRAME_VISIBLE (f, 0);
9199 block_input ();
9200 XFlush (FRAME_X_DISPLAY (f));
9201 unblock_input ();
9202 #else /* not USE_X_TOOLKIT */
9204 /* Make sure the X server knows where the window should be positioned,
9205 in case the user deiconifies with the window manager. */
9206 if (! FRAME_VISIBLE_P (f)
9207 && ! FRAME_ICONIFIED_P (f)
9208 && ! FRAME_X_EMBEDDED_P (f))
9209 x_set_offset (f, f->left_pos, f->top_pos, 0);
9211 /* Since we don't know which revision of X we're running, we'll use both
9212 the X11R3 and X11R4 techniques. I don't know if this is a good idea. */
9214 /* X11R4: send a ClientMessage to the window manager using the
9215 WM_CHANGE_STATE type. */
9217 XEvent msg;
9219 msg.xclient.window = FRAME_X_WINDOW (f);
9220 msg.xclient.type = ClientMessage;
9221 msg.xclient.message_type = FRAME_DISPLAY_INFO (f)->Xatom_wm_change_state;
9222 msg.xclient.format = 32;
9223 msg.xclient.data.l[0] = IconicState;
9225 if (! XSendEvent (FRAME_X_DISPLAY (f),
9226 DefaultRootWindow (FRAME_X_DISPLAY (f)),
9227 False,
9228 SubstructureRedirectMask | SubstructureNotifyMask,
9229 &msg))
9231 unblock_input ();
9232 error ("Can't notify window manager of iconification");
9236 /* X11R3: set the initial_state field of the window manager hints to
9237 IconicState. */
9238 x_wm_set_window_state (f, IconicState);
9240 if (!FRAME_VISIBLE_P (f))
9242 /* If the frame was withdrawn, before, we must map it. */
9243 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9246 SET_FRAME_ICONIFIED (f, 1);
9247 SET_FRAME_VISIBLE (f, 0);
9249 XFlush (FRAME_X_DISPLAY (f));
9250 unblock_input ();
9251 #endif /* not USE_X_TOOLKIT */
9255 /* Free X resources of frame F. */
9257 void
9258 x_free_frame_resources (struct frame *f)
9260 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
9261 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
9262 #ifdef USE_X_TOOLKIT
9263 Lisp_Object bar;
9264 struct scroll_bar *b;
9265 #endif
9267 block_input ();
9269 /* If a display connection is dead, don't try sending more
9270 commands to the X server. */
9271 if (dpyinfo->display)
9273 /* We must free faces before destroying windows because some
9274 font-driver (e.g. xft) access a window while finishing a
9275 face. */
9276 if (FRAME_FACE_CACHE (f))
9277 free_frame_faces (f);
9279 if (f->output_data.x->icon_desc)
9280 XDestroyWindow (FRAME_X_DISPLAY (f), f->output_data.x->icon_desc);
9282 #ifdef USE_X_TOOLKIT
9283 /* Explicitly destroy the scroll bars of the frame. Without
9284 this, we get "BadDrawable" errors from the toolkit later on,
9285 presumably from expose events generated for the disappearing
9286 toolkit scroll bars. */
9287 for (bar = FRAME_SCROLL_BARS (f); !NILP (bar); bar = b->next)
9289 b = XSCROLL_BAR (bar);
9290 x_scroll_bar_remove (b);
9292 #endif
9294 #ifdef HAVE_X_I18N
9295 if (FRAME_XIC (f))
9296 free_frame_xic (f);
9297 #endif
9299 #ifdef USE_X_TOOLKIT
9300 if (f->output_data.x->widget)
9302 XtDestroyWidget (f->output_data.x->widget);
9303 f->output_data.x->widget = NULL;
9305 /* Tooltips don't have widgets, only a simple X window, even if
9306 we are using a toolkit. */
9307 else if (FRAME_X_WINDOW (f))
9308 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9310 free_frame_menubar (f);
9311 #else /* !USE_X_TOOLKIT */
9313 #ifdef USE_GTK
9314 xg_free_frame_widgets (f);
9315 #endif /* USE_GTK */
9317 if (FRAME_X_WINDOW (f))
9318 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9319 #endif /* !USE_X_TOOLKIT */
9321 unload_color (f, FRAME_FOREGROUND_PIXEL (f));
9322 unload_color (f, FRAME_BACKGROUND_PIXEL (f));
9323 unload_color (f, f->output_data.x->cursor_pixel);
9324 unload_color (f, f->output_data.x->cursor_foreground_pixel);
9325 unload_color (f, f->output_data.x->border_pixel);
9326 unload_color (f, f->output_data.x->mouse_pixel);
9328 if (f->output_data.x->scroll_bar_background_pixel != -1)
9329 unload_color (f, f->output_data.x->scroll_bar_background_pixel);
9330 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
9331 unload_color (f, f->output_data.x->scroll_bar_foreground_pixel);
9332 #ifdef USE_TOOLKIT_SCROLL_BARS
9333 /* Scrollbar shadow colors. */
9334 if (f->output_data.x->scroll_bar_top_shadow_pixel != -1)
9335 unload_color (f, f->output_data.x->scroll_bar_top_shadow_pixel);
9336 if (f->output_data.x->scroll_bar_bottom_shadow_pixel != -1)
9337 unload_color (f, f->output_data.x->scroll_bar_bottom_shadow_pixel);
9338 #endif /* USE_TOOLKIT_SCROLL_BARS */
9339 if (f->output_data.x->white_relief.pixel != -1)
9340 unload_color (f, f->output_data.x->white_relief.pixel);
9341 if (f->output_data.x->black_relief.pixel != -1)
9342 unload_color (f, f->output_data.x->black_relief.pixel);
9344 x_free_gcs (f);
9346 /* Free extra GCs allocated by x_setup_relief_colors. */
9347 if (f->output_data.x->white_relief.gc)
9349 XFreeGC (dpyinfo->display, f->output_data.x->white_relief.gc);
9350 f->output_data.x->white_relief.gc = 0;
9352 if (f->output_data.x->black_relief.gc)
9354 XFreeGC (dpyinfo->display, f->output_data.x->black_relief.gc);
9355 f->output_data.x->black_relief.gc = 0;
9358 XFlush (FRAME_X_DISPLAY (f));
9361 xfree (f->output_data.x->saved_menu_event);
9362 xfree (f->output_data.x);
9363 f->output_data.x = NULL;
9365 if (f == dpyinfo->x_focus_frame)
9366 dpyinfo->x_focus_frame = 0;
9367 if (f == dpyinfo->x_focus_event_frame)
9368 dpyinfo->x_focus_event_frame = 0;
9369 if (f == dpyinfo->x_highlight_frame)
9370 dpyinfo->x_highlight_frame = 0;
9371 if (f == hlinfo->mouse_face_mouse_frame)
9372 reset_mouse_highlight (hlinfo);
9374 unblock_input ();
9378 /* Destroy the X window of frame F. */
9380 static void
9381 x_destroy_window (struct frame *f)
9383 struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
9385 /* If a display connection is dead, don't try sending more
9386 commands to the X server. */
9387 if (dpyinfo->display != 0)
9388 x_free_frame_resources (f);
9390 dpyinfo->reference_count--;
9394 /* Setting window manager hints. */
9396 /* Set the normal size hints for the window manager, for frame F.
9397 FLAGS is the flags word to use--or 0 meaning preserve the flags
9398 that the window now has.
9399 If USER_POSITION, set the USPosition
9400 flag (this is useful when FLAGS is 0).
9401 The GTK version is in gtkutils.c. */
9403 #ifndef USE_GTK
9404 void
9405 x_wm_set_size_hint (struct frame *f, long flags, bool user_position)
9407 XSizeHints size_hints;
9408 Window window = FRAME_OUTER_WINDOW (f);
9410 #ifdef USE_X_TOOLKIT
9411 if (f->output_data.x->widget)
9413 widget_update_wm_size_hints (f->output_data.x->widget);
9414 return;
9416 #endif
9418 /* Setting PMaxSize caused various problems. */
9419 size_hints.flags = PResizeInc | PMinSize /* | PMaxSize */;
9421 size_hints.x = f->left_pos;
9422 size_hints.y = f->top_pos;
9424 size_hints.height = FRAME_PIXEL_HEIGHT (f);
9425 size_hints.width = FRAME_PIXEL_WIDTH (f);
9427 size_hints.width_inc = FRAME_COLUMN_WIDTH (f);
9428 size_hints.height_inc = FRAME_LINE_HEIGHT (f);
9429 size_hints.max_width = x_display_pixel_width (FRAME_DISPLAY_INFO (f))
9430 - FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
9431 size_hints.max_height = x_display_pixel_height (FRAME_DISPLAY_INFO (f))
9432 - FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
9434 /* Calculate the base and minimum sizes. */
9436 int base_width, base_height;
9437 int min_rows = 0, min_cols = 0;
9439 base_width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
9440 base_height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
9442 check_frame_size (f, &min_rows, &min_cols);
9444 /* The window manager uses the base width hints to calculate the
9445 current number of rows and columns in the frame while
9446 resizing; min_width and min_height aren't useful for this
9447 purpose, since they might not give the dimensions for a
9448 zero-row, zero-column frame.
9450 We use the base_width and base_height members if we have
9451 them; otherwise, we set the min_width and min_height members
9452 to the size for a zero x zero frame. */
9454 size_hints.flags |= PBaseSize;
9455 size_hints.base_width = base_width;
9456 size_hints.base_height = base_height + FRAME_MENUBAR_HEIGHT (f);
9457 size_hints.min_width = base_width + min_cols * size_hints.width_inc;
9458 size_hints.min_height = base_height + min_rows * size_hints.height_inc;
9461 /* If we don't need the old flags, we don't need the old hint at all. */
9462 if (flags)
9464 size_hints.flags |= flags;
9465 goto no_read;
9469 XSizeHints hints; /* Sometimes I hate X Windows... */
9470 long supplied_return;
9471 int value;
9473 value = XGetWMNormalHints (FRAME_X_DISPLAY (f), window, &hints,
9474 &supplied_return);
9476 if (flags)
9477 size_hints.flags |= flags;
9478 else
9480 if (value == 0)
9481 hints.flags = 0;
9482 if (hints.flags & PSize)
9483 size_hints.flags |= PSize;
9484 if (hints.flags & PPosition)
9485 size_hints.flags |= PPosition;
9486 if (hints.flags & USPosition)
9487 size_hints.flags |= USPosition;
9488 if (hints.flags & USSize)
9489 size_hints.flags |= USSize;
9493 no_read:
9495 #ifdef PWinGravity
9496 size_hints.win_gravity = f->win_gravity;
9497 size_hints.flags |= PWinGravity;
9499 if (user_position)
9501 size_hints.flags &= ~ PPosition;
9502 size_hints.flags |= USPosition;
9504 #endif /* PWinGravity */
9506 XSetWMNormalHints (FRAME_X_DISPLAY (f), window, &size_hints);
9508 #endif /* not USE_GTK */
9510 /* Used for IconicState or NormalState */
9512 static void
9513 x_wm_set_window_state (struct frame *f, int state)
9515 #ifdef USE_X_TOOLKIT
9516 Arg al[1];
9518 XtSetArg (al[0], XtNinitialState, state);
9519 XtSetValues (f->output_data.x->widget, al, 1);
9520 #else /* not USE_X_TOOLKIT */
9521 Window window = FRAME_X_WINDOW (f);
9523 f->output_data.x->wm_hints.flags |= StateHint;
9524 f->output_data.x->wm_hints.initial_state = state;
9526 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
9527 #endif /* not USE_X_TOOLKIT */
9530 static void
9531 x_wm_set_icon_pixmap (struct frame *f, ptrdiff_t pixmap_id)
9533 Pixmap icon_pixmap, icon_mask;
9535 #if !defined USE_X_TOOLKIT && !defined USE_GTK
9536 Window window = FRAME_OUTER_WINDOW (f);
9537 #endif
9539 if (pixmap_id > 0)
9541 icon_pixmap = x_bitmap_pixmap (f, pixmap_id);
9542 f->output_data.x->wm_hints.icon_pixmap = icon_pixmap;
9543 icon_mask = x_bitmap_mask (f, pixmap_id);
9544 f->output_data.x->wm_hints.icon_mask = icon_mask;
9546 else
9548 /* It seems there is no way to turn off use of an icon
9549 pixmap. */
9550 return;
9554 #ifdef USE_GTK
9556 xg_set_frame_icon (f, icon_pixmap, icon_mask);
9557 return;
9560 #elif defined (USE_X_TOOLKIT) /* same as in x_wm_set_window_state. */
9563 Arg al[1];
9564 XtSetArg (al[0], XtNiconPixmap, icon_pixmap);
9565 XtSetValues (f->output_data.x->widget, al, 1);
9566 XtSetArg (al[0], XtNiconMask, icon_mask);
9567 XtSetValues (f->output_data.x->widget, al, 1);
9570 #else /* not USE_X_TOOLKIT && not USE_GTK */
9572 f->output_data.x->wm_hints.flags |= (IconPixmapHint | IconMaskHint);
9573 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
9575 #endif /* not USE_X_TOOLKIT && not USE_GTK */
9578 void
9579 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
9581 Window window = FRAME_OUTER_WINDOW (f);
9583 f->output_data.x->wm_hints.flags |= IconPositionHint;
9584 f->output_data.x->wm_hints.icon_x = icon_x;
9585 f->output_data.x->wm_hints.icon_y = icon_y;
9587 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
9591 /***********************************************************************
9592 Fonts
9593 ***********************************************************************/
9595 #ifdef GLYPH_DEBUG
9597 /* Check that FONT is valid on frame F. It is if it can be found in F's
9598 font table. */
9600 static void
9601 x_check_font (struct frame *f, struct font *font)
9603 eassert (font != NULL && ! NILP (font->props[FONT_TYPE_INDEX]));
9604 if (font->driver->check)
9605 eassert (font->driver->check (f, font) == 0);
9608 #endif /* GLYPH_DEBUG */
9611 /***********************************************************************
9612 Initialization
9613 ***********************************************************************/
9615 #ifdef USE_X_TOOLKIT
9616 static XrmOptionDescRec emacs_options[] = {
9617 {"-geometry", ".geometry", XrmoptionSepArg, NULL},
9618 {"-iconic", ".iconic", XrmoptionNoArg, (XtPointer) "yes"},
9620 {"-internal-border-width", "*EmacsScreen.internalBorderWidth",
9621 XrmoptionSepArg, NULL},
9622 {"-ib", "*EmacsScreen.internalBorderWidth", XrmoptionSepArg, NULL},
9624 {"-T", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
9625 {"-wn", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
9626 {"-title", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
9627 {"-iconname", "*EmacsShell.iconName", XrmoptionSepArg, (XtPointer) NULL},
9628 {"-in", "*EmacsShell.iconName", XrmoptionSepArg, (XtPointer) NULL},
9629 {"-mc", "*pointerColor", XrmoptionSepArg, (XtPointer) NULL},
9630 {"-cr", "*cursorColor", XrmoptionSepArg, (XtPointer) NULL}
9633 /* Whether atimer for Xt timeouts is activated or not. */
9635 static int x_timeout_atimer_activated_flag;
9637 #endif /* USE_X_TOOLKIT */
9639 static int x_initialized;
9641 /* Test whether two display-name strings agree up to the dot that separates
9642 the screen number from the server number. */
9643 static int
9644 same_x_server (const char *name1, const char *name2)
9646 int seen_colon = 0;
9647 const char *system_name = SSDATA (Vsystem_name);
9648 ptrdiff_t system_name_length = SBYTES (Vsystem_name);
9649 ptrdiff_t length_until_period = 0;
9651 while (system_name[length_until_period] != 0
9652 && system_name[length_until_period] != '.')
9653 length_until_period++;
9655 /* Treat `unix' like an empty host name. */
9656 if (! strncmp (name1, "unix:", 5))
9657 name1 += 4;
9658 if (! strncmp (name2, "unix:", 5))
9659 name2 += 4;
9660 /* Treat this host's name like an empty host name. */
9661 if (! strncmp (name1, system_name, system_name_length)
9662 && name1[system_name_length] == ':')
9663 name1 += system_name_length;
9664 if (! strncmp (name2, system_name, system_name_length)
9665 && name2[system_name_length] == ':')
9666 name2 += system_name_length;
9667 /* Treat this host's domainless name like an empty host name. */
9668 if (! strncmp (name1, system_name, length_until_period)
9669 && name1[length_until_period] == ':')
9670 name1 += length_until_period;
9671 if (! strncmp (name2, system_name, length_until_period)
9672 && name2[length_until_period] == ':')
9673 name2 += length_until_period;
9675 for (; *name1 != '\0' && *name1 == *name2; name1++, name2++)
9677 if (*name1 == ':')
9678 seen_colon = 1;
9679 if (seen_colon && *name1 == '.')
9680 return 1;
9682 return (seen_colon
9683 && (*name1 == '.' || *name1 == '\0')
9684 && (*name2 == '.' || *name2 == '\0'));
9687 /* Count number of set bits in mask and number of bits to shift to
9688 get to the first bit. With MASK 0x7e0, *BITS is set to 6, and *OFFSET
9689 to 5. */
9690 static void
9691 get_bits_and_offset (unsigned long mask, int *bits, int *offset)
9693 int nr = 0;
9694 int off = 0;
9696 while (!(mask & 1))
9698 off++;
9699 mask >>= 1;
9702 while (mask & 1)
9704 nr++;
9705 mask >>= 1;
9708 *offset = off;
9709 *bits = nr;
9712 /* Return 1 if display DISPLAY is available for use, 0 otherwise.
9713 But don't permanently open it, just test its availability. */
9715 bool
9716 x_display_ok (const char *display)
9718 Display *dpy = XOpenDisplay (display);
9719 return dpy ? (XCloseDisplay (dpy), 1) : 0;
9722 #ifdef USE_GTK
9723 static void
9724 my_log_handler (const gchar *log_domain, GLogLevelFlags log_level,
9725 const gchar *msg, gpointer user_data)
9727 if (!strstr (msg, "g_set_prgname"))
9728 fprintf (stderr, "%s-WARNING **: %s\n", log_domain, msg);
9730 #endif
9732 /* Open a connection to X display DISPLAY_NAME, and return
9733 the structure that describes the open display.
9734 If we cannot contact the display, return null. */
9736 struct x_display_info *
9737 x_term_init (Lisp_Object display_name, char *xrm_option, char *resource_name)
9739 int connection;
9740 Display *dpy;
9741 struct terminal *terminal;
9742 struct x_display_info *dpyinfo;
9743 XrmDatabase xrdb;
9744 ptrdiff_t lim;
9746 block_input ();
9748 if (!x_initialized)
9750 x_initialize ();
9751 ++x_initialized;
9754 if (! x_display_ok (SSDATA (display_name)))
9755 error ("Display %s can't be opened", SSDATA (display_name));
9757 #ifdef USE_GTK
9759 #define NUM_ARGV 10
9760 int argc;
9761 char *argv[NUM_ARGV];
9762 char **argv2 = argv;
9763 guint id;
9765 if (x_initialized++ > 1)
9767 xg_display_open (SSDATA (display_name), &dpy);
9769 else
9771 static char display_opt[] = "--display";
9772 static char name_opt[] = "--name";
9774 for (argc = 0; argc < NUM_ARGV; ++argc)
9775 argv[argc] = 0;
9777 argc = 0;
9778 argv[argc++] = initial_argv[0];
9780 if (! NILP (display_name))
9782 argv[argc++] = display_opt;
9783 argv[argc++] = SSDATA (display_name);
9786 argv[argc++] = name_opt;
9787 argv[argc++] = resource_name;
9789 XSetLocaleModifiers ("");
9791 /* Emacs can only handle core input events, so make sure
9792 Gtk doesn't use Xinput or Xinput2 extensions. */
9793 xputenv ("GDK_CORE_DEVICE_EVENTS=1");
9795 /* Work around GLib bug that outputs a faulty warning. See
9796 https://bugzilla.gnome.org/show_bug.cgi?id=563627. */
9797 id = g_log_set_handler ("GLib", G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
9798 | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
9800 /* NULL window -> events for all windows go to our function.
9801 Call before gtk_init so Gtk+ event filters comes after our. */
9802 gdk_window_add_filter (NULL, event_handler_gdk, NULL);
9804 /* gtk_init does set_locale. Fix locale before and after. */
9805 fixup_locale ();
9806 gtk_init (&argc, &argv2);
9807 fixup_locale ();
9809 g_log_remove_handler ("GLib", id);
9811 xg_initialize ();
9813 dpy = DEFAULT_GDK_DISPLAY ();
9815 #if ! GTK_CHECK_VERSION (2, 90, 0)
9816 /* Load our own gtkrc if it exists. */
9818 const char *file = "~/.emacs.d/gtkrc";
9819 Lisp_Object s, abs_file;
9821 s = build_string (file);
9822 abs_file = Fexpand_file_name (s, Qnil);
9824 if (! NILP (abs_file) && !NILP (Ffile_readable_p (abs_file)))
9825 gtk_rc_parse (SSDATA (abs_file));
9827 #endif
9829 XSetErrorHandler (x_error_handler);
9830 XSetIOErrorHandler (x_io_error_quitter);
9833 #else /* not USE_GTK */
9834 #ifdef USE_X_TOOLKIT
9835 /* weiner@footloose.sps.mot.com reports that this causes
9836 errors with X11R5:
9837 X protocol error: BadAtom (invalid Atom parameter)
9838 on protocol request 18skiloaf.
9839 So let's not use it until R6. */
9840 #ifdef HAVE_X11XTR6
9841 XtSetLanguageProc (NULL, NULL, NULL);
9842 #endif
9845 int argc = 0;
9846 char *argv[3];
9848 argv[0] = "";
9849 argc = 1;
9850 if (xrm_option)
9852 argv[argc++] = "-xrm";
9853 argv[argc++] = xrm_option;
9855 turn_on_atimers (0);
9856 dpy = XtOpenDisplay (Xt_app_con, SSDATA (display_name),
9857 resource_name, EMACS_CLASS,
9858 emacs_options, XtNumber (emacs_options),
9859 &argc, argv);
9860 turn_on_atimers (1);
9862 #ifdef HAVE_X11XTR6
9863 /* I think this is to compensate for XtSetLanguageProc. */
9864 fixup_locale ();
9865 #endif
9868 #else /* not USE_X_TOOLKIT */
9869 XSetLocaleModifiers ("");
9870 dpy = XOpenDisplay (SSDATA (display_name));
9871 #endif /* not USE_X_TOOLKIT */
9872 #endif /* not USE_GTK*/
9874 /* Detect failure. */
9875 if (dpy == 0)
9877 unblock_input ();
9878 return 0;
9881 /* We have definitely succeeded. Record the new connection. */
9883 dpyinfo = xzalloc (sizeof *dpyinfo);
9884 terminal = x_create_terminal (dpyinfo);
9887 struct x_display_info *share;
9889 for (share = x_display_list; share; share = share->next)
9890 if (same_x_server (SSDATA (XCAR (share->name_list_element)),
9891 SSDATA (display_name)))
9892 break;
9893 if (share)
9894 terminal->kboard = share->terminal->kboard;
9895 else
9897 terminal->kboard = allocate_kboard (Qx);
9899 if (!EQ (XSYMBOL (Qvendor_specific_keysyms)->function, Qunbound))
9901 char *vendor = ServerVendor (dpy);
9903 /* Protect terminal from GC before removing it from the
9904 list of terminals. */
9905 struct gcpro gcpro1;
9906 Lisp_Object gcpro_term;
9907 XSETTERMINAL (gcpro_term, terminal);
9908 GCPRO1 (gcpro_term);
9910 /* Temporarily hide the partially initialized terminal. */
9911 terminal_list = terminal->next_terminal;
9912 unblock_input ();
9913 kset_system_key_alist
9914 (terminal->kboard,
9915 call1 (Qvendor_specific_keysyms,
9916 vendor ? build_string (vendor) : empty_unibyte_string));
9917 block_input ();
9918 terminal->next_terminal = terminal_list;
9919 terminal_list = terminal;
9920 UNGCPRO;
9923 /* Don't let the initial kboard remain current longer than necessary.
9924 That would cause problems if a file loaded on startup tries to
9925 prompt in the mini-buffer. */
9926 if (current_kboard == initial_kboard)
9927 current_kboard = terminal->kboard;
9929 terminal->kboard->reference_count++;
9932 /* Put this display on the chain. */
9933 dpyinfo->next = x_display_list;
9934 x_display_list = dpyinfo;
9936 dpyinfo->name_list_element = Fcons (display_name, Qnil);
9937 dpyinfo->display = dpy;
9939 /* Set the name of the terminal. */
9940 terminal->name = xlispstrdup (display_name);
9942 #if 0
9943 XSetAfterFunction (x_current_display, x_trace_wire);
9944 #endif /* ! 0 */
9946 lim = min (PTRDIFF_MAX, SIZE_MAX) - sizeof "@";
9947 if (lim - SBYTES (Vinvocation_name) < SBYTES (Vsystem_name))
9948 memory_full (SIZE_MAX);
9949 dpyinfo->x_id_name = xmalloc (SBYTES (Vinvocation_name)
9950 + SBYTES (Vsystem_name) + 2);
9951 strcat (strcat (strcpy (dpyinfo->x_id_name, SSDATA (Vinvocation_name)), "@"),
9952 SSDATA (Vsystem_name));
9954 /* Figure out which modifier bits mean what. */
9955 x_find_modifier_meanings (dpyinfo);
9957 /* Get the scroll bar cursor. */
9958 #ifdef USE_GTK
9959 /* We must create a GTK cursor, it is required for GTK widgets. */
9960 dpyinfo->xg_cursor = xg_create_default_cursor (dpyinfo->display);
9961 #endif /* USE_GTK */
9963 dpyinfo->vertical_scroll_bar_cursor
9964 = XCreateFontCursor (dpyinfo->display, XC_sb_v_double_arrow);
9966 xrdb = x_load_resources (dpyinfo->display, xrm_option,
9967 resource_name, EMACS_CLASS);
9968 #ifdef HAVE_XRMSETDATABASE
9969 XrmSetDatabase (dpyinfo->display, xrdb);
9970 #else
9971 dpyinfo->display->db = xrdb;
9972 #endif
9973 /* Put the rdb where we can find it in a way that works on
9974 all versions. */
9975 dpyinfo->xrdb = xrdb;
9977 dpyinfo->screen = ScreenOfDisplay (dpyinfo->display,
9978 DefaultScreen (dpyinfo->display));
9979 select_visual (dpyinfo);
9980 dpyinfo->cmap = DefaultColormapOfScreen (dpyinfo->screen);
9981 dpyinfo->root_window = RootWindowOfScreen (dpyinfo->screen);
9982 dpyinfo->icon_bitmap_id = -1;
9983 dpyinfo->wm_type = X_WMTYPE_UNKNOWN;
9985 reset_mouse_highlight (&dpyinfo->mouse_highlight);
9987 /* See if we can construct pixel values from RGB values. */
9988 if (dpyinfo->visual->class == TrueColor)
9990 get_bits_and_offset (dpyinfo->visual->red_mask,
9991 &dpyinfo->red_bits, &dpyinfo->red_offset);
9992 get_bits_and_offset (dpyinfo->visual->blue_mask,
9993 &dpyinfo->blue_bits, &dpyinfo->blue_offset);
9994 get_bits_and_offset (dpyinfo->visual->green_mask,
9995 &dpyinfo->green_bits, &dpyinfo->green_offset);
9998 /* See if a private colormap is requested. */
9999 if (dpyinfo->visual == DefaultVisualOfScreen (dpyinfo->screen))
10001 if (dpyinfo->visual->class == PseudoColor)
10003 Lisp_Object value;
10004 value = display_x_get_resource (dpyinfo,
10005 build_string ("privateColormap"),
10006 build_string ("PrivateColormap"),
10007 Qnil, Qnil);
10008 if (STRINGP (value)
10009 && (!strcmp (SSDATA (value), "true")
10010 || !strcmp (SSDATA (value), "on")))
10011 dpyinfo->cmap = XCopyColormapAndFree (dpyinfo->display, dpyinfo->cmap);
10014 else
10015 dpyinfo->cmap = XCreateColormap (dpyinfo->display, dpyinfo->root_window,
10016 dpyinfo->visual, AllocNone);
10018 #ifdef HAVE_XFT
10020 /* If we are using Xft, check dpi value in X resources.
10021 It is better we use it as well, since Xft will use it, as will all
10022 Gnome applications. If our real DPI is smaller or larger than the
10023 one Xft uses, our font will look smaller or larger than other
10024 for other applications, even if it is the same font name (monospace-10
10025 for example). */
10026 char *v = XGetDefault (dpyinfo->display, "Xft", "dpi");
10027 double d;
10028 if (v != NULL && sscanf (v, "%lf", &d) == 1)
10029 dpyinfo->resy = dpyinfo->resx = d;
10031 #endif
10033 if (dpyinfo->resy < 1)
10035 int screen_number = XScreenNumberOfScreen (dpyinfo->screen);
10036 double pixels = DisplayHeight (dpyinfo->display, screen_number);
10037 double mm = DisplayHeightMM (dpyinfo->display, screen_number);
10038 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
10039 dpyinfo->resy = (mm < 1) ? 100 : pixels * 25.4 / mm;
10040 pixels = DisplayWidth (dpyinfo->display, screen_number);
10041 mm = DisplayWidthMM (dpyinfo->display, screen_number);
10042 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
10043 dpyinfo->resx = (mm < 1) ? 100 : pixels * 25.4 / mm;
10047 static const struct
10049 const char *name;
10050 int offset;
10051 } atom_refs[] = {
10052 #define ATOM_REFS_INIT(string, member) \
10053 { string, offsetof (struct x_display_info, member) },
10054 ATOM_REFS_INIT ("WM_PROTOCOLS", Xatom_wm_protocols)
10055 ATOM_REFS_INIT ("WM_TAKE_FOCUS", Xatom_wm_take_focus)
10056 ATOM_REFS_INIT ("WM_SAVE_YOURSELF", Xatom_wm_save_yourself)
10057 ATOM_REFS_INIT ("WM_DELETE_WINDOW", Xatom_wm_delete_window)
10058 ATOM_REFS_INIT ("WM_CHANGE_STATE", Xatom_wm_change_state)
10059 ATOM_REFS_INIT ("WM_CONFIGURE_DENIED", Xatom_wm_configure_denied)
10060 ATOM_REFS_INIT ("WM_MOVED", Xatom_wm_window_moved)
10061 ATOM_REFS_INIT ("WM_CLIENT_LEADER", Xatom_wm_client_leader)
10062 ATOM_REFS_INIT ("Editres", Xatom_editres)
10063 ATOM_REFS_INIT ("CLIPBOARD", Xatom_CLIPBOARD)
10064 ATOM_REFS_INIT ("TIMESTAMP", Xatom_TIMESTAMP)
10065 ATOM_REFS_INIT ("TEXT", Xatom_TEXT)
10066 ATOM_REFS_INIT ("COMPOUND_TEXT", Xatom_COMPOUND_TEXT)
10067 ATOM_REFS_INIT ("UTF8_STRING", Xatom_UTF8_STRING)
10068 ATOM_REFS_INIT ("DELETE", Xatom_DELETE)
10069 ATOM_REFS_INIT ("MULTIPLE", Xatom_MULTIPLE)
10070 ATOM_REFS_INIT ("INCR", Xatom_INCR)
10071 ATOM_REFS_INIT ("_EMACS_TMP_", Xatom_EMACS_TMP)
10072 ATOM_REFS_INIT ("TARGETS", Xatom_TARGETS)
10073 ATOM_REFS_INIT ("NULL", Xatom_NULL)
10074 ATOM_REFS_INIT ("ATOM", Xatom_ATOM)
10075 ATOM_REFS_INIT ("ATOM_PAIR", Xatom_ATOM_PAIR)
10076 ATOM_REFS_INIT ("CLIPBOARD_MANAGER", Xatom_CLIPBOARD_MANAGER)
10077 ATOM_REFS_INIT ("_XEMBED_INFO", Xatom_XEMBED_INFO)
10078 /* For properties of font. */
10079 ATOM_REFS_INIT ("PIXEL_SIZE", Xatom_PIXEL_SIZE)
10080 ATOM_REFS_INIT ("AVERAGE_WIDTH", Xatom_AVERAGE_WIDTH)
10081 ATOM_REFS_INIT ("_MULE_BASELINE_OFFSET", Xatom_MULE_BASELINE_OFFSET)
10082 ATOM_REFS_INIT ("_MULE_RELATIVE_COMPOSE", Xatom_MULE_RELATIVE_COMPOSE)
10083 ATOM_REFS_INIT ("_MULE_DEFAULT_ASCENT", Xatom_MULE_DEFAULT_ASCENT)
10084 /* Ghostscript support. */
10085 ATOM_REFS_INIT ("DONE", Xatom_DONE)
10086 ATOM_REFS_INIT ("PAGE", Xatom_PAGE)
10087 ATOM_REFS_INIT ("SCROLLBAR", Xatom_Scrollbar)
10088 ATOM_REFS_INIT ("_XEMBED", Xatom_XEMBED)
10089 /* EWMH */
10090 ATOM_REFS_INIT ("_NET_WM_STATE", Xatom_net_wm_state)
10091 ATOM_REFS_INIT ("_NET_WM_STATE_FULLSCREEN", Xatom_net_wm_state_fullscreen)
10092 ATOM_REFS_INIT ("_NET_WM_STATE_MAXIMIZED_HORZ",
10093 Xatom_net_wm_state_maximized_horz)
10094 ATOM_REFS_INIT ("_NET_WM_STATE_MAXIMIZED_VERT",
10095 Xatom_net_wm_state_maximized_vert)
10096 ATOM_REFS_INIT ("_NET_WM_STATE_STICKY", Xatom_net_wm_state_sticky)
10097 ATOM_REFS_INIT ("_NET_WM_STATE_HIDDEN", Xatom_net_wm_state_hidden)
10098 ATOM_REFS_INIT ("_NET_WM_WINDOW_TYPE", Xatom_net_window_type)
10099 ATOM_REFS_INIT ("_NET_WM_WINDOW_TYPE_TOOLTIP",
10100 Xatom_net_window_type_tooltip)
10101 ATOM_REFS_INIT ("_NET_WM_ICON_NAME", Xatom_net_wm_icon_name)
10102 ATOM_REFS_INIT ("_NET_WM_NAME", Xatom_net_wm_name)
10103 ATOM_REFS_INIT ("_NET_SUPPORTED", Xatom_net_supported)
10104 ATOM_REFS_INIT ("_NET_SUPPORTING_WM_CHECK", Xatom_net_supporting_wm_check)
10105 ATOM_REFS_INIT ("_NET_WM_WINDOW_OPACITY", Xatom_net_wm_window_opacity)
10106 ATOM_REFS_INIT ("_NET_ACTIVE_WINDOW", Xatom_net_active_window)
10107 ATOM_REFS_INIT ("_NET_FRAME_EXTENTS", Xatom_net_frame_extents)
10108 ATOM_REFS_INIT ("_NET_CURRENT_DESKTOP", Xatom_net_current_desktop)
10109 ATOM_REFS_INIT ("_NET_WORKAREA", Xatom_net_workarea)
10110 /* Session management */
10111 ATOM_REFS_INIT ("SM_CLIENT_ID", Xatom_SM_CLIENT_ID)
10112 ATOM_REFS_INIT ("_XSETTINGS_SETTINGS", Xatom_xsettings_prop)
10113 ATOM_REFS_INIT ("MANAGER", Xatom_xsettings_mgr)
10116 int i;
10117 const int atom_count = sizeof (atom_refs) / sizeof (atom_refs[0]);
10118 /* 1 for _XSETTINGS_SN */
10119 const int total_atom_count = 1 + atom_count;
10120 Atom *atoms_return = xmalloc (total_atom_count * sizeof *atoms_return);
10121 char **atom_names = xmalloc (total_atom_count * sizeof *atom_names);
10122 static char const xsettings_fmt[] = "_XSETTINGS_S%d";
10123 char xsettings_atom_name[sizeof xsettings_fmt - 2
10124 + INT_STRLEN_BOUND (int)];
10126 for (i = 0; i < atom_count; i++)
10127 atom_names[i] = (char *) atom_refs[i].name;
10129 /* Build _XSETTINGS_SN atom name */
10130 sprintf (xsettings_atom_name, xsettings_fmt,
10131 XScreenNumberOfScreen (dpyinfo->screen));
10132 atom_names[i] = xsettings_atom_name;
10134 XInternAtoms (dpyinfo->display, atom_names, total_atom_count,
10135 False, atoms_return);
10137 for (i = 0; i < atom_count; i++)
10138 *(Atom *) ((char *) dpyinfo + atom_refs[i].offset) = atoms_return[i];
10140 /* Manual copy of last atom */
10141 dpyinfo->Xatom_xsettings_sel = atoms_return[i];
10143 xfree (atom_names);
10144 xfree (atoms_return);
10147 dpyinfo->x_dnd_atoms_size = 8;
10148 dpyinfo->x_dnd_atoms = xmalloc (sizeof *dpyinfo->x_dnd_atoms
10149 * dpyinfo->x_dnd_atoms_size);
10150 dpyinfo->gray
10151 = XCreatePixmapFromBitmapData (dpyinfo->display, dpyinfo->root_window,
10152 gray_bits, gray_width, gray_height,
10153 1, 0, 1);
10155 #ifdef HAVE_X_I18N
10156 xim_initialize (dpyinfo, resource_name);
10157 #endif
10159 xsettings_initialize (dpyinfo);
10161 connection = ConnectionNumber (dpyinfo->display);
10163 /* This is only needed for distinguishing keyboard and process input. */
10164 if (connection != 0)
10165 add_keyboard_wait_descriptor (connection);
10167 #ifdef F_SETOWN
10168 fcntl (connection, F_SETOWN, getpid ());
10169 #endif /* ! defined (F_SETOWN) */
10171 if (interrupt_input)
10172 init_sigio (connection);
10174 #ifdef USE_LUCID
10176 XrmValue d, fr, to;
10177 Font font;
10179 dpy = dpyinfo->display;
10180 d.addr = (XPointer)&dpy;
10181 d.size = sizeof (Display *);
10182 fr.addr = XtDefaultFont;
10183 fr.size = sizeof (XtDefaultFont);
10184 to.size = sizeof (Font *);
10185 to.addr = (XPointer)&font;
10186 x_catch_errors (dpy);
10187 if (!XtCallConverter (dpy, XtCvtStringToFont, &d, 1, &fr, &to, NULL))
10188 emacs_abort ();
10189 if (x_had_errors_p (dpy) || !XQueryFont (dpy, font))
10190 XrmPutLineResource (&xrdb, "Emacs.dialog.*.font: 9x15");
10191 x_uncatch_errors ();
10193 #endif
10195 /* See if we should run in synchronous mode. This is useful
10196 for debugging X code. */
10198 Lisp_Object value;
10199 value = display_x_get_resource (dpyinfo,
10200 build_string ("synchronous"),
10201 build_string ("Synchronous"),
10202 Qnil, Qnil);
10203 if (STRINGP (value)
10204 && (!strcmp (SSDATA (value), "true")
10205 || !strcmp (SSDATA (value), "on")))
10206 XSynchronize (dpyinfo->display, True);
10210 Lisp_Object value;
10211 value = display_x_get_resource (dpyinfo,
10212 build_string ("useXIM"),
10213 build_string ("UseXIM"),
10214 Qnil, Qnil);
10215 #ifdef USE_XIM
10216 if (STRINGP (value)
10217 && (!strcmp (SSDATA (value), "false")
10218 || !strcmp (SSDATA (value), "off")))
10219 use_xim = 0;
10220 #else
10221 if (STRINGP (value)
10222 && (!strcmp (SSDATA (value), "true")
10223 || !strcmp (SSDATA (value), "on")))
10224 use_xim = 1;
10225 #endif
10228 #ifdef HAVE_X_SM
10229 /* Only do this for the very first display in the Emacs session.
10230 Ignore X session management when Emacs was first started on a
10231 tty. */
10232 if (terminal->id == 1)
10233 x_session_initialize (dpyinfo);
10234 #endif
10236 unblock_input ();
10238 return dpyinfo;
10241 /* Get rid of display DPYINFO, deleting all frames on it,
10242 and without sending any more commands to the X server. */
10244 static void
10245 x_delete_display (struct x_display_info *dpyinfo)
10247 struct terminal *t;
10249 /* Close all frames and delete the generic struct terminal for this
10250 X display. */
10251 for (t = terminal_list; t; t = t->next_terminal)
10252 if (t->type == output_x_window && t->display_info.x == dpyinfo)
10254 #ifdef HAVE_X_SM
10255 /* Close X session management when we close its display. */
10256 if (t->id == 1 && x_session_have_connection ())
10257 x_session_close ();
10258 #endif
10259 delete_terminal (t);
10260 break;
10263 if (next_noop_dpyinfo == dpyinfo)
10264 next_noop_dpyinfo = dpyinfo->next;
10266 if (x_display_list == dpyinfo)
10267 x_display_list = dpyinfo->next;
10268 else
10270 struct x_display_info *tail;
10272 for (tail = x_display_list; tail; tail = tail->next)
10273 if (tail->next == dpyinfo)
10274 tail->next = tail->next->next;
10277 xfree (dpyinfo->x_id_name);
10278 xfree (dpyinfo->x_dnd_atoms);
10279 xfree (dpyinfo->color_cells);
10280 xfree (dpyinfo);
10283 #ifdef USE_X_TOOLKIT
10285 /* Atimer callback function for TIMER. Called every 0.1s to process
10286 Xt timeouts, if needed. We must avoid calling XtAppPending as
10287 much as possible because that function does an implicit XFlush
10288 that slows us down. */
10290 static void
10291 x_process_timeouts (struct atimer *timer)
10293 block_input ();
10294 x_timeout_atimer_activated_flag = 0;
10295 if (toolkit_scroll_bar_interaction || popup_activated ())
10297 while (XtAppPending (Xt_app_con) & XtIMTimer)
10298 XtAppProcessEvent (Xt_app_con, XtIMTimer);
10299 /* Reactivate the atimer for next time. */
10300 x_activate_timeout_atimer ();
10302 unblock_input ();
10305 /* Install an asynchronous timer that processes Xt timeout events
10306 every 0.1s as long as either `toolkit_scroll_bar_interaction' or
10307 `popup_activated_flag' (in xmenu.c) is set. Make sure to call this
10308 function whenever these variables are set. This is necessary
10309 because some widget sets use timeouts internally, for example the
10310 LessTif menu bar, or the Xaw3d scroll bar. When Xt timeouts aren't
10311 processed, these widgets don't behave normally. */
10313 void
10314 x_activate_timeout_atimer (void)
10316 block_input ();
10317 if (!x_timeout_atimer_activated_flag)
10319 struct timespec interval = make_timespec (0, 100 * 1000 * 1000);
10320 start_atimer (ATIMER_RELATIVE, interval, x_process_timeouts, 0);
10321 x_timeout_atimer_activated_flag = 1;
10323 unblock_input ();
10326 #endif /* USE_X_TOOLKIT */
10329 /* Set up use of X before we make the first connection. */
10331 static struct redisplay_interface x_redisplay_interface =
10333 x_frame_parm_handlers,
10334 x_produce_glyphs,
10335 x_write_glyphs,
10336 x_insert_glyphs,
10337 x_clear_end_of_line,
10338 x_scroll_run,
10339 x_after_update_window_line,
10340 x_update_window_begin,
10341 x_update_window_end,
10342 x_flush,
10343 x_clear_window_mouse_face,
10344 x_get_glyph_overhangs,
10345 x_fix_overlapping_area,
10346 x_draw_fringe_bitmap,
10347 0, /* define_fringe_bitmap */
10348 0, /* destroy_fringe_bitmap */
10349 x_compute_glyph_string_overhangs,
10350 x_draw_glyph_string,
10351 x_define_frame_cursor,
10352 x_clear_frame_area,
10353 x_draw_window_cursor,
10354 x_draw_vertical_window_border,
10355 x_shift_glyphs_for_insert
10359 /* This function is called when the last frame on a display is deleted. */
10360 void
10361 x_delete_terminal (struct terminal *terminal)
10363 struct x_display_info *dpyinfo = terminal->display_info.x;
10364 int connection = -1;
10366 /* Protect against recursive calls. delete_frame in
10367 delete_terminal calls us back when it deletes our last frame. */
10368 if (!terminal->name)
10369 return;
10371 block_input ();
10372 #ifdef HAVE_X_I18N
10373 /* We must close our connection to the XIM server before closing the
10374 X display. */
10375 if (dpyinfo->xim)
10376 xim_close_dpy (dpyinfo);
10377 #endif
10379 /* If called from x_connection_closed, the display may already be closed
10380 and dpyinfo->display was set to 0 to indicate that. */
10381 if (dpyinfo->display)
10383 connection = ConnectionNumber (dpyinfo->display);
10385 x_destroy_all_bitmaps (dpyinfo);
10386 XSetCloseDownMode (dpyinfo->display, DestroyAll);
10388 /* Whether or not XCloseDisplay destroys the associated resource
10389 database depends on the version of libX11. To avoid both
10390 crash and memory leak, we dissociate the database from the
10391 display and then destroy dpyinfo->xrdb ourselves.
10393 Unfortunately, the above strategy does not work in some
10394 situations due to a bug in newer versions of libX11: because
10395 XrmSetDatabase doesn't clear the flag XlibDisplayDfltRMDB if
10396 dpy->db is NULL, XCloseDisplay destroys the associated
10397 database whereas it has not been created by XGetDefault
10398 (Bug#21974 in freedesktop.org Bugzilla). As a workaround, we
10399 don't destroy the database here in order to avoid the crash
10400 in the above situations for now, though that may cause memory
10401 leaks in other situations. */
10402 #if 0
10403 #ifdef HAVE_XRMSETDATABASE
10404 XrmSetDatabase (dpyinfo->display, NULL);
10405 #else
10406 dpyinfo->display->db = NULL;
10407 #endif
10408 /* We used to call XrmDestroyDatabase from x_delete_display, but
10409 some older versions of libX11 crash if we call it after
10410 closing all the displays. */
10411 XrmDestroyDatabase (dpyinfo->xrdb);
10412 #endif
10414 #ifdef USE_GTK
10415 xg_display_close (dpyinfo->display);
10416 #else
10417 #ifdef USE_X_TOOLKIT
10418 XtCloseDisplay (dpyinfo->display);
10419 #else
10420 XCloseDisplay (dpyinfo->display);
10421 #endif
10422 #endif /* ! USE_GTK */
10425 /* No more input on this descriptor. */
10426 if (connection != -1)
10427 delete_keyboard_wait_descriptor (connection);
10429 /* Mark as dead. */
10430 dpyinfo->display = NULL;
10431 x_delete_display (dpyinfo);
10432 unblock_input ();
10435 /* Create a struct terminal, initialize it with the X11 specific
10436 functions and make DISPLAY->TERMINAL point to it. */
10438 static struct terminal *
10439 x_create_terminal (struct x_display_info *dpyinfo)
10441 struct terminal *terminal;
10443 terminal = create_terminal ();
10445 terminal->type = output_x_window;
10446 terminal->display_info.x = dpyinfo;
10447 dpyinfo->terminal = terminal;
10449 /* kboard is initialized in x_term_init. */
10451 terminal->clear_frame_hook = x_clear_frame;
10452 terminal->ins_del_lines_hook = x_ins_del_lines;
10453 terminal->delete_glyphs_hook = x_delete_glyphs;
10454 terminal->ring_bell_hook = XTring_bell;
10455 terminal->toggle_invisible_pointer_hook = XTtoggle_invisible_pointer;
10456 terminal->reset_terminal_modes_hook = NULL;
10457 terminal->set_terminal_modes_hook = NULL;
10458 terminal->update_begin_hook = x_update_begin;
10459 terminal->update_end_hook = x_update_end;
10460 terminal->set_terminal_window_hook = NULL;
10461 terminal->read_socket_hook = XTread_socket;
10462 terminal->frame_up_to_date_hook = XTframe_up_to_date;
10463 terminal->mouse_position_hook = XTmouse_position;
10464 terminal->frame_rehighlight_hook = XTframe_rehighlight;
10465 terminal->frame_raise_lower_hook = XTframe_raise_lower;
10466 terminal->fullscreen_hook = XTfullscreen_hook;
10467 terminal->set_vertical_scroll_bar_hook = XTset_vertical_scroll_bar;
10468 terminal->condemn_scroll_bars_hook = XTcondemn_scroll_bars;
10469 terminal->redeem_scroll_bar_hook = XTredeem_scroll_bar;
10470 terminal->judge_scroll_bars_hook = XTjudge_scroll_bars;
10472 terminal->delete_frame_hook = x_destroy_window;
10473 terminal->delete_terminal_hook = x_delete_terminal;
10475 terminal->rif = &x_redisplay_interface;
10477 return terminal;
10480 void
10481 x_initialize (void)
10483 baud_rate = 19200;
10485 x_noop_count = 0;
10486 last_tool_bar_item = -1;
10487 any_help_event_p = 0;
10488 ignore_next_mouse_click_timeout = 0;
10490 #ifdef USE_GTK
10491 current_count = -1;
10492 #endif
10494 /* Try to use interrupt input; if we can't, then start polling. */
10495 Fset_input_interrupt_mode (Qt);
10497 #ifdef USE_X_TOOLKIT
10498 XtToolkitInitialize ();
10500 Xt_app_con = XtCreateApplicationContext ();
10502 /* Register a converter from strings to pixels, which uses
10503 Emacs' color allocation infrastructure. */
10504 XtAppSetTypeConverter (Xt_app_con,
10505 XtRString, XtRPixel, cvt_string_to_pixel,
10506 cvt_string_to_pixel_args,
10507 XtNumber (cvt_string_to_pixel_args),
10508 XtCacheByDisplay, cvt_pixel_dtor);
10510 XtAppSetFallbackResources (Xt_app_con, Xt_default_resources);
10511 #endif
10513 #ifdef USE_TOOLKIT_SCROLL_BARS
10514 #ifndef USE_GTK
10515 xaw3d_arrow_scroll = False;
10516 xaw3d_pick_top = True;
10517 #endif
10518 #endif
10520 /* Note that there is no real way portable across R3/R4 to get the
10521 original error handler. */
10522 XSetErrorHandler (x_error_handler);
10523 XSetIOErrorHandler (x_io_error_quitter);
10527 void
10528 syms_of_xterm (void)
10530 x_error_message = NULL;
10532 DEFSYM (Qvendor_specific_keysyms, "vendor-specific-keysyms");
10533 DEFSYM (Qlatin_1, "latin-1");
10535 #ifdef USE_GTK
10536 xg_default_icon_file = build_pure_c_string ("icons/hicolor/scalable/apps/emacs.svg");
10537 staticpro (&xg_default_icon_file);
10539 DEFSYM (Qx_gtk_map_stock, "x-gtk-map-stock");
10540 #endif
10542 DEFVAR_BOOL ("x-use-underline-position-properties",
10543 x_use_underline_position_properties,
10544 doc: /* Non-nil means make use of UNDERLINE_POSITION font properties.
10545 A value of nil means ignore them. If you encounter fonts with bogus
10546 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
10547 to 4.1, set this to nil. You can also use `underline-minimum-offset'
10548 to override the font's UNDERLINE_POSITION for small font display
10549 sizes. */);
10550 x_use_underline_position_properties = 1;
10552 DEFVAR_BOOL ("x-underline-at-descent-line",
10553 x_underline_at_descent_line,
10554 doc: /* Non-nil means to draw the underline at the same place as the descent line.
10555 A value of nil means to draw the underline according to the value of the
10556 variable `x-use-underline-position-properties', which is usually at the
10557 baseline level. The default value is nil. */);
10558 x_underline_at_descent_line = 0;
10560 DEFVAR_BOOL ("x-mouse-click-focus-ignore-position",
10561 x_mouse_click_focus_ignore_position,
10562 doc: /* Non-nil means that a mouse click to focus a frame does not move point.
10563 This variable is only used when the window manager requires that you
10564 click on a frame to select it (give it focus). In that case, a value
10565 of nil, means that the selected window and cursor position changes to
10566 reflect the mouse click position, while a non-nil value means that the
10567 selected window or cursor position is preserved. */);
10568 x_mouse_click_focus_ignore_position = 0;
10570 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
10571 doc: /* Which toolkit scroll bars Emacs uses, if any.
10572 A value of nil means Emacs doesn't use toolkit scroll bars.
10573 With the X Window system, the value is a symbol describing the
10574 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
10575 With MS Windows or Nextstep, the value is t. */);
10576 #ifdef USE_TOOLKIT_SCROLL_BARS
10577 #ifdef USE_MOTIF
10578 Vx_toolkit_scroll_bars = intern_c_string ("motif");
10579 #elif defined HAVE_XAW3D
10580 Vx_toolkit_scroll_bars = intern_c_string ("xaw3d");
10581 #elif USE_GTK
10582 Vx_toolkit_scroll_bars = intern_c_string ("gtk");
10583 #else
10584 Vx_toolkit_scroll_bars = intern_c_string ("xaw");
10585 #endif
10586 #else
10587 Vx_toolkit_scroll_bars = Qnil;
10588 #endif
10590 DEFSYM (Qmodifier_value, "modifier-value");
10591 DEFSYM (Qalt, "alt");
10592 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
10593 DEFSYM (Qhyper, "hyper");
10594 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
10595 DEFSYM (Qmeta, "meta");
10596 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
10597 DEFSYM (Qsuper, "super");
10598 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
10600 DEFVAR_LISP ("x-alt-keysym", Vx_alt_keysym,
10601 doc: /* Which keys Emacs uses for the alt modifier.
10602 This should be one of the symbols `alt', `hyper', `meta', `super'.
10603 For example, `alt' means use the Alt_L and Alt_R keysyms. The default
10604 is nil, which is the same as `alt'. */);
10605 Vx_alt_keysym = Qnil;
10607 DEFVAR_LISP ("x-hyper-keysym", Vx_hyper_keysym,
10608 doc: /* Which keys Emacs uses for the hyper modifier.
10609 This should be one of the symbols `alt', `hyper', `meta', `super'.
10610 For example, `hyper' means use the Hyper_L and Hyper_R keysyms. The
10611 default is nil, which is the same as `hyper'. */);
10612 Vx_hyper_keysym = Qnil;
10614 DEFVAR_LISP ("x-meta-keysym", Vx_meta_keysym,
10615 doc: /* Which keys Emacs uses for the meta modifier.
10616 This should be one of the symbols `alt', `hyper', `meta', `super'.
10617 For example, `meta' means use the Meta_L and Meta_R keysyms. The
10618 default is nil, which is the same as `meta'. */);
10619 Vx_meta_keysym = Qnil;
10621 DEFVAR_LISP ("x-super-keysym", Vx_super_keysym,
10622 doc: /* Which keys Emacs uses for the super modifier.
10623 This should be one of the symbols `alt', `hyper', `meta', `super'.
10624 For example, `super' means use the Super_L and Super_R keysyms. The
10625 default is nil, which is the same as `super'. */);
10626 Vx_super_keysym = Qnil;
10628 DEFVAR_LISP ("x-keysym-table", Vx_keysym_table,
10629 doc: /* Hash table of character codes indexed by X keysym codes. */);
10630 Vx_keysym_table = make_hash_table (hashtest_eql, make_number (900),
10631 make_float (DEFAULT_REHASH_SIZE),
10632 make_float (DEFAULT_REHASH_THRESHOLD),
10633 Qnil);