Remove an incorrect assertion on move_it_by_lines.
[emacs.git] / src / xterm.c
blob9ce166883c30eecae249a840793b5cc43f9ddaec
1 /* X Communication module for terminals which understand the X protocol.
3 Copyright (C) 1989, 1993-2012 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 <signal.h>
25 #include <stdio.h>
26 #include <setjmp.h>
28 #ifdef HAVE_X_WINDOWS
30 #include "lisp.h"
31 #include "blockinput.h"
33 /* Need syssignal.h for various externs and definitions that may be required
34 by some configurations for calls to signal later in this source file. */
35 #include "syssignal.h"
37 /* This may include sys/types.h, and that somehow loses
38 if this is not done before the other system files. */
39 #include "xterm.h"
40 #include <X11/cursorfont.h>
42 /* Load sys/types.h if not already loaded.
43 In some systems loading it twice is suicidal. */
44 #ifndef makedev
45 #include <sys/types.h>
46 #endif /* makedev */
48 #include <sys/ioctl.h>
50 #include "systime.h"
52 #include <fcntl.h>
53 #include <ctype.h>
54 #include <errno.h>
55 #include <setjmp.h>
56 #include <sys/stat.h>
57 /* Caused redefinition of DBL_DIG on Netbsd; seems not to be needed. */
58 /* #include <sys/param.h> */
60 #include "charset.h"
61 #include "character.h"
62 #include "coding.h"
63 #include "frame.h"
64 #include "dispextern.h"
65 #include "fontset.h"
66 #include "termhooks.h"
67 #include "termopts.h"
68 #include "termchar.h"
69 #include "emacs-icon.h"
70 #include "disptab.h"
71 #include "buffer.h"
72 #include "window.h"
73 #include "keyboard.h"
74 #include "intervals.h"
75 #include "process.h"
76 #include "atimer.h"
77 #include "keymap.h"
78 #include "font.h"
79 #include "fontset.h"
80 #include "xsettings.h"
81 #include "xgselect.h"
82 #include "sysselect.h"
84 #ifdef USE_X_TOOLKIT
85 #include <X11/Shell.h>
86 #endif
88 #ifdef HAVE_SYS_TIME_H
89 #include <sys/time.h>
90 #endif
92 #include <unistd.h>
94 #ifdef USE_GTK
95 #include "gtkutil.h"
96 #ifdef HAVE_GTK3
97 #include <X11/Xproto.h>
98 #endif
99 #endif
101 #ifdef USE_LUCID
102 #include "../lwlib/xlwmenu.h"
103 #endif
105 #ifdef USE_X_TOOLKIT
106 #if !defined (NO_EDITRES)
107 #define HACK_EDITRES
108 extern void _XEditResCheckMessages (Widget, XtPointer, XEvent *, Boolean *);
109 #endif /* not NO_EDITRES */
111 /* Include toolkit specific headers for the scroll bar widget. */
113 #ifdef USE_TOOLKIT_SCROLL_BARS
114 #if defined USE_MOTIF
115 #include <Xm/Xm.h> /* for LESSTIF_VERSION */
116 #include <Xm/ScrollBar.h>
117 #else /* !USE_MOTIF i.e. use Xaw */
119 #ifdef HAVE_XAW3D
120 #include <X11/Xaw3d/Simple.h>
121 #include <X11/Xaw3d/Scrollbar.h>
122 #include <X11/Xaw3d/ThreeD.h>
123 #else /* !HAVE_XAW3D */
124 #include <X11/Xaw/Simple.h>
125 #include <X11/Xaw/Scrollbar.h>
126 #endif /* !HAVE_XAW3D */
127 #ifndef XtNpickTop
128 #define XtNpickTop "pickTop"
129 #endif /* !XtNpickTop */
130 #endif /* !USE_MOTIF */
131 #endif /* USE_TOOLKIT_SCROLL_BARS */
133 #endif /* USE_X_TOOLKIT */
135 #ifdef USE_X_TOOLKIT
136 #include "widget.h"
137 #ifndef XtNinitialState
138 #define XtNinitialState "initialState"
139 #endif
140 #endif
142 /* Default to using XIM if available. */
143 #ifdef USE_XIM
144 int use_xim = 1;
145 #else
146 int use_xim = 0; /* configure --without-xim */
147 #endif
151 /* Non-zero means that a HELP_EVENT has been generated since Emacs
152 start. */
154 static int any_help_event_p;
156 /* Last window where we saw the mouse. Used by mouse-autoselect-window. */
157 static Lisp_Object last_window;
159 /* This is a chain of structures for all the X displays currently in
160 use. */
162 struct x_display_info *x_display_list;
164 /* This is a list of cons cells, each of the form (NAME
165 . FONT-LIST-CACHE), one for each element of x_display_list and in
166 the same order. NAME is the name of the frame. FONT-LIST-CACHE
167 records previous values returned by x-list-fonts. */
169 Lisp_Object x_display_name_list;
171 /* Frame being updated by update_frame. This is declared in term.c.
172 This is set by update_begin and looked at by all the XT functions.
173 It is zero while not inside an update. In that case, the XT
174 functions assume that `selected_frame' is the frame to apply to. */
176 extern struct frame *updating_frame;
178 /* This is a frame waiting to be auto-raised, within XTread_socket. */
180 static struct frame *pending_autoraise_frame;
182 /* This is a frame waiting for an event matching mask, within XTread_socket. */
184 static struct {
185 struct frame *f;
186 int eventtype;
187 } pending_event_wait;
189 #ifdef USE_X_TOOLKIT
190 /* The application context for Xt use. */
191 XtAppContext Xt_app_con;
192 static String Xt_default_resources[] = {0};
194 /* Non-zero means user is interacting with a toolkit scroll bar. */
196 static int toolkit_scroll_bar_interaction;
197 #endif /* USE_X_TOOLKIT */
199 /* Non-zero timeout value means ignore next mouse click if it arrives
200 before that timeout elapses (i.e. as part of the same sequence of
201 events resulting from clicking on a frame to select it). */
203 static unsigned long ignore_next_mouse_click_timeout;
205 /* Mouse movement.
207 Formerly, we used PointerMotionHintMask (in standard_event_mask)
208 so that we would have to call XQueryPointer after each MotionNotify
209 event to ask for another such event. However, this made mouse tracking
210 slow, and there was a bug that made it eventually stop.
212 Simply asking for MotionNotify all the time seems to work better.
214 In order to avoid asking for motion events and then throwing most
215 of them away or busy-polling the server for mouse positions, we ask
216 the server for pointer motion hints. This means that we get only
217 one event per group of mouse movements. "Groups" are delimited by
218 other kinds of events (focus changes and button clicks, for
219 example), or by XQueryPointer calls; when one of these happens, we
220 get another MotionNotify event the next time the mouse moves. This
221 is at least as efficient as getting motion events when mouse
222 tracking is on, and I suspect only negligibly worse when tracking
223 is off. */
225 /* Where the mouse was last time we reported a mouse event. */
227 static XRectangle last_mouse_glyph;
228 static FRAME_PTR last_mouse_glyph_frame;
229 static Lisp_Object last_mouse_press_frame;
231 /* The scroll bar in which the last X motion event occurred.
233 If the last X motion event occurred in a scroll bar, we set this so
234 XTmouse_position can know whether to report a scroll bar motion or
235 an ordinary motion.
237 If the last X motion event didn't occur in a scroll bar, we set
238 this to Qnil, to tell XTmouse_position to return an ordinary motion
239 event. */
241 static Lisp_Object last_mouse_scroll_bar;
243 /* This is a hack. We would really prefer that XTmouse_position would
244 return the time associated with the position it returns, but there
245 doesn't seem to be any way to wrest the time-stamp from the server
246 along with the position query. So, we just keep track of the time
247 of the last movement we received, and return that in hopes that
248 it's somewhat accurate. */
250 static Time last_mouse_movement_time;
252 /* Time for last user interaction as returned in X events. */
254 static Time last_user_time;
256 /* Incremented by XTread_socket whenever it really tries to read
257 events. */
259 #ifdef __STDC__
260 static int volatile input_signal_count;
261 #else
262 static int input_signal_count;
263 #endif
265 /* Used locally within XTread_socket. */
267 static int x_noop_count;
269 static Lisp_Object Qalt, Qhyper, Qmeta, Qsuper, Qmodifier_value;
271 static Lisp_Object Qvendor_specific_keysyms;
272 static Lisp_Object Qlatin_1;
274 #ifdef USE_GTK
275 /* The name of the Emacs icon file. */
276 static Lisp_Object xg_default_icon_file;
278 /* Used in gtkutil.c. */
279 Lisp_Object Qx_gtk_map_stock;
280 #endif
282 /* Some functions take this as char *, not const char *. */
283 static char emacs_class[] = EMACS_CLASS;
285 enum xembed_info
287 XEMBED_MAPPED = 1 << 0
290 enum xembed_message
292 XEMBED_EMBEDDED_NOTIFY = 0,
293 XEMBED_WINDOW_ACTIVATE = 1,
294 XEMBED_WINDOW_DEACTIVATE = 2,
295 XEMBED_REQUEST_FOCUS = 3,
296 XEMBED_FOCUS_IN = 4,
297 XEMBED_FOCUS_OUT = 5,
298 XEMBED_FOCUS_NEXT = 6,
299 XEMBED_FOCUS_PREV = 7,
301 XEMBED_MODALITY_ON = 10,
302 XEMBED_MODALITY_OFF = 11,
303 XEMBED_REGISTER_ACCELERATOR = 12,
304 XEMBED_UNREGISTER_ACCELERATOR = 13,
305 XEMBED_ACTIVATE_ACCELERATOR = 14
308 /* Used in x_flush. */
310 static int x_alloc_nearest_color_1 (Display *, Colormap, XColor *);
311 static void x_set_window_size_1 (struct frame *, int, int, int);
312 static void x_raise_frame (struct frame *);
313 static void x_lower_frame (struct frame *);
314 static const XColor *x_color_cells (Display *, int *);
315 static void x_update_window_end (struct window *, int, int);
317 static int x_io_error_quitter (Display *);
318 static struct terminal *x_create_terminal (struct x_display_info *);
319 void x_delete_terminal (struct terminal *);
320 static void x_update_end (struct frame *);
321 static void XTframe_up_to_date (struct frame *);
322 static void XTset_terminal_modes (struct terminal *);
323 static void XTreset_terminal_modes (struct terminal *);
324 static void x_clear_frame (struct frame *);
325 static void x_ins_del_lines (struct frame *, int, int) NO_RETURN;
326 static void frame_highlight (struct frame *);
327 static void frame_unhighlight (struct frame *);
328 static void x_new_focus_frame (struct x_display_info *, struct frame *);
329 static void x_focus_changed (int, int, struct x_display_info *,
330 struct frame *, struct input_event *);
331 static void x_detect_focus_change (struct x_display_info *,
332 XEvent *, struct input_event *);
333 static void XTframe_rehighlight (struct frame *);
334 static void x_frame_rehighlight (struct x_display_info *);
335 static void x_draw_hollow_cursor (struct window *, struct glyph_row *);
336 static void x_draw_bar_cursor (struct window *, struct glyph_row *, int,
337 enum text_cursor_kinds);
339 static void x_clip_to_row (struct window *, struct glyph_row *, int, GC);
340 static void x_flush (struct frame *f);
341 static void x_update_begin (struct frame *);
342 static void x_update_window_begin (struct window *);
343 static void x_after_update_window_line (struct glyph_row *);
344 static struct scroll_bar *x_window_to_scroll_bar (Display *, Window);
345 static void x_scroll_bar_report_motion (struct frame **, Lisp_Object *,
346 enum scroll_bar_part *,
347 Lisp_Object *, Lisp_Object *,
348 Time *);
349 static int x_handle_net_wm_state (struct frame *, XPropertyEvent *);
350 static void x_check_fullscreen (struct frame *);
351 static void x_check_expected_move (struct frame *, int, int);
352 static void x_sync_with_move (struct frame *, int, int, int);
353 static int handle_one_xevent (struct x_display_info *, XEvent *,
354 int *, struct input_event *);
355 #ifdef USE_GTK
356 static int x_dispatch_event (XEvent *, Display *);
357 #endif
358 /* Don't declare this NO_RETURN because we want no
359 interference with debugging failing X calls. */
360 static void x_connection_closed (Display *, const char *);
361 static void x_wm_set_window_state (struct frame *, int);
362 static void x_wm_set_icon_pixmap (struct frame *, ptrdiff_t);
363 static void x_initialize (void);
366 /* Flush display of frame F, or of all frames if F is null. */
368 static void
369 x_flush (struct frame *f)
371 /* Don't call XFlush when it is not safe to redisplay; the X
372 connection may be broken. */
373 if (!NILP (Vinhibit_redisplay))
374 return;
376 BLOCK_INPUT;
377 if (f == NULL)
379 Lisp_Object rest, frame;
380 FOR_EACH_FRAME (rest, frame)
381 if (FRAME_X_P (XFRAME (frame)))
382 x_flush (XFRAME (frame));
384 else if (FRAME_X_P (f))
385 XFlush (FRAME_X_DISPLAY (f));
386 UNBLOCK_INPUT;
390 /* Remove calls to XFlush by defining XFlush to an empty replacement.
391 Calls to XFlush should be unnecessary because the X output buffer
392 is flushed automatically as needed by calls to XPending,
393 XNextEvent, or XWindowEvent according to the XFlush man page.
394 XTread_socket calls XPending. Removing XFlush improves
395 performance. */
397 #define XFlush(DISPLAY) (void) 0
400 /***********************************************************************
401 Debugging
402 ***********************************************************************/
404 #if 0
406 /* This is a function useful for recording debugging information about
407 the sequence of occurrences in this file. */
409 struct record
411 char *locus;
412 int type;
415 struct record event_record[100];
417 int event_record_index;
419 void
420 record_event (char *locus, int type)
422 if (event_record_index == sizeof (event_record) / sizeof (struct record))
423 event_record_index = 0;
425 event_record[event_record_index].locus = locus;
426 event_record[event_record_index].type = type;
427 event_record_index++;
430 #endif /* 0 */
434 /* Return the struct x_display_info corresponding to DPY. */
436 struct x_display_info *
437 x_display_info_for_display (Display *dpy)
439 struct x_display_info *dpyinfo;
441 for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
442 if (dpyinfo->display == dpy)
443 return dpyinfo;
445 return 0;
448 static Window
449 x_find_topmost_parent (struct frame *f)
451 struct x_output *x = f->output_data.x;
452 Window win = None, wi = x->parent_desc;
453 Display *dpy = FRAME_X_DISPLAY (f);
455 while (wi != FRAME_X_DISPLAY_INFO (f)->root_window)
457 Window root;
458 Window *children;
459 unsigned int nchildren;
461 win = wi;
462 XQueryTree (dpy, win, &root, &wi, &children, &nchildren);
463 XFree (children);
466 return win;
469 #define OPAQUE 0xffffffff
471 void
472 x_set_frame_alpha (struct frame *f)
474 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
475 Display *dpy = FRAME_X_DISPLAY (f);
476 Window win = FRAME_OUTER_WINDOW (f);
477 double alpha = 1.0;
478 double alpha_min = 1.0;
479 unsigned long opac;
480 Window parent;
482 if (dpyinfo->x_highlight_frame == f)
483 alpha = f->alpha[0];
484 else
485 alpha = f->alpha[1];
487 if (FLOATP (Vframe_alpha_lower_limit))
488 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
489 else if (INTEGERP (Vframe_alpha_lower_limit))
490 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
492 if (alpha < 0.0)
493 return;
494 else if (alpha > 1.0)
495 alpha = 1.0;
496 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
497 alpha = alpha_min;
499 opac = alpha * OPAQUE;
501 x_catch_errors (dpy);
503 /* If there is a parent from the window manager, put the property there
504 also, to work around broken window managers that fail to do that.
505 Do this unconditionally as this function is called on reparent when
506 alpha has not changed on the frame. */
508 parent = x_find_topmost_parent (f);
509 if (parent != None)
510 XChangeProperty (dpy, parent, dpyinfo->Xatom_net_wm_window_opacity,
511 XA_CARDINAL, 32, PropModeReplace,
512 (unsigned char *) &opac, 1L);
514 /* return unless necessary */
516 unsigned char *data;
517 Atom actual;
518 int rc, format;
519 unsigned long n, left;
521 rc = XGetWindowProperty (dpy, win, dpyinfo->Xatom_net_wm_window_opacity,
522 0L, 1L, False, XA_CARDINAL,
523 &actual, &format, &n, &left,
524 &data);
526 if (rc == Success && actual != None)
528 unsigned long value = *(unsigned long *)data;
529 XFree ((void *) data);
530 if (value == opac)
532 x_uncatch_errors ();
533 return;
538 XChangeProperty (dpy, win, dpyinfo->Xatom_net_wm_window_opacity,
539 XA_CARDINAL, 32, PropModeReplace,
540 (unsigned char *) &opac, 1L);
541 x_uncatch_errors ();
545 x_display_pixel_height (struct x_display_info *dpyinfo)
547 return HeightOfScreen (dpyinfo->screen);
551 x_display_pixel_width (struct x_display_info *dpyinfo)
553 return WidthOfScreen (dpyinfo->screen);
557 /***********************************************************************
558 Starting and ending an update
559 ***********************************************************************/
561 /* Start an update of frame F. This function is installed as a hook
562 for update_begin, i.e. it is called when update_begin is called.
563 This function is called prior to calls to x_update_window_begin for
564 each window being updated. Currently, there is nothing to do here
565 because all interesting stuff is done on a window basis. */
567 static void
568 x_update_begin (struct frame *f)
570 /* Nothing to do. */
574 /* Start update of window W. Set the global variable updated_window
575 to the window being updated and set output_cursor to the cursor
576 position of W. */
578 static void
579 x_update_window_begin (struct window *w)
581 struct frame *f = XFRAME (WINDOW_FRAME (w));
582 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
584 updated_window = w;
585 set_output_cursor (&w->cursor);
587 BLOCK_INPUT;
589 if (f == hlinfo->mouse_face_mouse_frame)
591 /* Don't do highlighting for mouse motion during the update. */
592 hlinfo->mouse_face_defer = 1;
594 /* If F needs to be redrawn, simply forget about any prior mouse
595 highlighting. */
596 if (FRAME_GARBAGED_P (f))
597 hlinfo->mouse_face_window = Qnil;
600 UNBLOCK_INPUT;
604 /* Draw a vertical window border from (x,y0) to (x,y1) */
606 static void
607 x_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
609 struct frame *f = XFRAME (WINDOW_FRAME (w));
610 struct face *face;
612 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
613 if (face)
614 XSetForeground (FRAME_X_DISPLAY (f), f->output_data.x->normal_gc,
615 face->foreground);
617 XDrawLine (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
618 f->output_data.x->normal_gc, x, y0, x, y1);
621 /* End update of window W (which is equal to updated_window).
623 Draw vertical borders between horizontally adjacent windows, and
624 display W's cursor if CURSOR_ON_P is non-zero.
626 MOUSE_FACE_OVERWRITTEN_P non-zero means that some row containing
627 glyphs in mouse-face were overwritten. In that case we have to
628 make sure that the mouse-highlight is properly redrawn.
630 W may be a menu bar pseudo-window in case we don't have X toolkit
631 support. Such windows don't have a cursor, so don't display it
632 here. */
634 static void
635 x_update_window_end (struct window *w, int cursor_on_p, int mouse_face_overwritten_p)
637 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (XFRAME (w->frame));
639 if (!w->pseudo_window_p)
641 BLOCK_INPUT;
643 if (cursor_on_p)
644 display_and_set_cursor (w, 1, output_cursor.hpos,
645 output_cursor.vpos,
646 output_cursor.x, output_cursor.y);
648 if (draw_window_fringes (w, 1))
649 x_draw_vertical_border (w);
651 UNBLOCK_INPUT;
654 /* If a row with mouse-face was overwritten, arrange for
655 XTframe_up_to_date to redisplay the mouse highlight. */
656 if (mouse_face_overwritten_p)
658 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
659 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
660 hlinfo->mouse_face_window = Qnil;
663 updated_window = NULL;
667 /* End update of frame F. This function is installed as a hook in
668 update_end. */
670 static void
671 x_update_end (struct frame *f)
673 /* Mouse highlight may be displayed again. */
674 MOUSE_HL_INFO (f)->mouse_face_defer = 0;
676 #ifndef XFlush
677 BLOCK_INPUT;
678 XFlush (FRAME_X_DISPLAY (f));
679 UNBLOCK_INPUT;
680 #endif
684 /* This function is called from various places in xdisp.c whenever a
685 complete update has been performed. The global variable
686 updated_window is not available here. */
688 static void
689 XTframe_up_to_date (struct frame *f)
691 if (FRAME_X_P (f))
693 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
695 if (hlinfo->mouse_face_deferred_gc
696 || f == hlinfo->mouse_face_mouse_frame)
698 BLOCK_INPUT;
699 if (hlinfo->mouse_face_mouse_frame)
700 note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
701 hlinfo->mouse_face_mouse_x,
702 hlinfo->mouse_face_mouse_y);
703 hlinfo->mouse_face_deferred_gc = 0;
704 UNBLOCK_INPUT;
710 /* Draw truncation mark bitmaps, continuation mark bitmaps, overlay
711 arrow bitmaps, or clear the fringes if no bitmaps are required
712 before DESIRED_ROW is made current. The window being updated is
713 found in updated_window. This function It is called from
714 update_window_line only if it is known that there are differences
715 between bitmaps to be drawn between current row and DESIRED_ROW. */
717 static void
718 x_after_update_window_line (struct glyph_row *desired_row)
720 struct window *w = updated_window;
721 struct frame *f;
722 int width, height;
724 xassert (w);
726 if (!desired_row->mode_line_p && !w->pseudo_window_p)
727 desired_row->redraw_fringe_bitmaps_p = 1;
729 /* When a window has disappeared, make sure that no rest of
730 full-width rows stays visible in the internal border. Could
731 check here if updated_window is the leftmost/rightmost window,
732 but I guess it's not worth doing since vertically split windows
733 are almost never used, internal border is rarely set, and the
734 overhead is very small. */
735 if (windows_or_buffers_changed
736 && desired_row->full_width_p
737 && (f = XFRAME (w->frame),
738 width = FRAME_INTERNAL_BORDER_WIDTH (f),
739 width != 0)
740 && (height = desired_row->visible_height,
741 height > 0))
743 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
745 BLOCK_INPUT;
746 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
747 0, y, width, height, False);
748 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
749 FRAME_PIXEL_WIDTH (f) - width,
750 y, width, height, False);
751 UNBLOCK_INPUT;
755 static void
756 x_draw_fringe_bitmap (struct window *w, struct glyph_row *row, struct draw_fringe_bitmap_params *p)
758 struct frame *f = XFRAME (WINDOW_FRAME (w));
759 Display *display = FRAME_X_DISPLAY (f);
760 Window window = FRAME_X_WINDOW (f);
761 GC gc = f->output_data.x->normal_gc;
762 struct face *face = p->face;
764 /* Must clip because of partially visible lines. */
765 x_clip_to_row (w, row, -1, gc);
767 if (!p->overlay_p)
769 int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
771 /* In case the same realized face is used for fringes and
772 for something displayed in the text (e.g. face `region' on
773 mono-displays, the fill style may have been changed to
774 FillSolid in x_draw_glyph_string_background. */
775 if (face->stipple)
776 XSetFillStyle (display, face->gc, FillOpaqueStippled);
777 else
778 XSetForeground (display, face->gc, face->background);
780 #ifdef USE_TOOLKIT_SCROLL_BARS
781 /* If the fringe is adjacent to the left (right) scroll bar of a
782 leftmost (rightmost, respectively) window, then extend its
783 background to the gap between the fringe and the bar. */
784 if ((WINDOW_LEFTMOST_P (w)
785 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
786 || (WINDOW_RIGHTMOST_P (w)
787 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w)))
789 int sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
791 if (sb_width > 0)
793 int bar_area_x = WINDOW_SCROLL_BAR_AREA_X (w);
794 int bar_area_width = (WINDOW_CONFIG_SCROLL_BAR_COLS (w)
795 * FRAME_COLUMN_WIDTH (f));
797 if (bx < 0)
799 /* Bitmap fills the fringe. */
800 if (bar_area_x + bar_area_width == p->x)
801 bx = bar_area_x + sb_width;
802 else if (p->x + p->wd == bar_area_x)
803 bx = bar_area_x;
804 if (bx >= 0)
806 int header_line_height = WINDOW_HEADER_LINE_HEIGHT (w);
808 nx = bar_area_width - sb_width;
809 by = WINDOW_TO_FRAME_PIXEL_Y (w, max (header_line_height,
810 row->y));
811 ny = row->visible_height;
814 else
816 if (bar_area_x + bar_area_width == bx)
818 bx = bar_area_x + sb_width;
819 nx += bar_area_width - sb_width;
821 else if (bx + nx == bar_area_x)
822 nx += bar_area_width - sb_width;
826 #endif
827 if (bx >= 0 && nx > 0)
828 XFillRectangle (display, window, face->gc, bx, by, nx, ny);
830 if (!face->stipple)
831 XSetForeground (display, face->gc, face->foreground);
834 if (p->which)
836 char *bits;
837 Pixmap pixmap, clipmask = (Pixmap) 0;
838 int depth = DefaultDepthOfScreen (FRAME_X_SCREEN (f));
839 XGCValues gcv;
841 if (p->wd > 8)
842 bits = (char *) (p->bits + p->dh);
843 else
844 bits = (char *) p->bits + p->dh;
846 /* Draw the bitmap. I believe these small pixmaps can be cached
847 by the server. */
848 pixmap = XCreatePixmapFromBitmapData (display, window, bits, p->wd, p->h,
849 (p->cursor_p
850 ? (p->overlay_p ? face->background
851 : f->output_data.x->cursor_pixel)
852 : face->foreground),
853 face->background, depth);
855 if (p->overlay_p)
857 clipmask = XCreatePixmapFromBitmapData (display,
858 FRAME_X_DISPLAY_INFO (f)->root_window,
859 bits, p->wd, p->h,
860 1, 0, 1);
861 gcv.clip_mask = clipmask;
862 gcv.clip_x_origin = p->x;
863 gcv.clip_y_origin = p->y;
864 XChangeGC (display, gc, GCClipMask | GCClipXOrigin | GCClipYOrigin, &gcv);
867 XCopyArea (display, pixmap, window, gc, 0, 0,
868 p->wd, p->h, p->x, p->y);
869 XFreePixmap (display, pixmap);
871 if (p->overlay_p)
873 gcv.clip_mask = (Pixmap) 0;
874 XChangeGC (display, gc, GCClipMask, &gcv);
875 XFreePixmap (display, clipmask);
879 XSetClipMask (display, gc, None);
884 /* This is called when starting Emacs and when restarting after
885 suspend. When starting Emacs, no X window is mapped. And nothing
886 must be done to Emacs's own window if it is suspended (though that
887 rarely happens). */
889 static void
890 XTset_terminal_modes (struct terminal *terminal)
894 /* This is called when exiting or suspending Emacs. Exiting will make
895 the X-windows go away, and suspending requires no action. */
897 static void
898 XTreset_terminal_modes (struct terminal *terminal)
903 /***********************************************************************
904 Glyph display
905 ***********************************************************************/
909 static void x_set_glyph_string_clipping (struct glyph_string *);
910 static void x_set_glyph_string_gc (struct glyph_string *);
911 static void x_draw_glyph_string_background (struct glyph_string *,
912 int);
913 static void x_draw_glyph_string_foreground (struct glyph_string *);
914 static void x_draw_composite_glyph_string_foreground (struct glyph_string *);
915 static void x_draw_glyph_string_box (struct glyph_string *);
916 static void x_draw_glyph_string (struct glyph_string *);
917 static void x_delete_glyphs (struct frame *, int) NO_RETURN;
918 static void x_compute_glyph_string_overhangs (struct glyph_string *);
919 static void x_set_cursor_gc (struct glyph_string *);
920 static void x_set_mode_line_face_gc (struct glyph_string *);
921 static void x_set_mouse_face_gc (struct glyph_string *);
922 static int x_alloc_lighter_color (struct frame *, Display *, Colormap,
923 unsigned long *, double, int);
924 static void x_setup_relief_color (struct frame *, struct relief *,
925 double, int, unsigned long);
926 static void x_setup_relief_colors (struct glyph_string *);
927 static void x_draw_image_glyph_string (struct glyph_string *);
928 static void x_draw_image_relief (struct glyph_string *);
929 static void x_draw_image_foreground (struct glyph_string *);
930 static void x_draw_image_foreground_1 (struct glyph_string *, Pixmap);
931 static void x_clear_glyph_string_rect (struct glyph_string *, int,
932 int, int, int);
933 static void x_draw_relief_rect (struct frame *, int, int, int, int,
934 int, int, int, int, int, int,
935 XRectangle *);
936 static void x_draw_box_rect (struct glyph_string *, int, int, int, int,
937 int, int, int, XRectangle *);
938 static void x_scroll_bar_clear (struct frame *);
940 #if GLYPH_DEBUG
941 static void x_check_font (struct frame *, struct font *);
942 #endif
945 /* Set S->gc to a suitable GC for drawing glyph string S in cursor
946 face. */
948 static void
949 x_set_cursor_gc (struct glyph_string *s)
951 if (s->font == FRAME_FONT (s->f)
952 && s->face->background == FRAME_BACKGROUND_PIXEL (s->f)
953 && s->face->foreground == FRAME_FOREGROUND_PIXEL (s->f)
954 && !s->cmp)
955 s->gc = s->f->output_data.x->cursor_gc;
956 else
958 /* Cursor on non-default face: must merge. */
959 XGCValues xgcv;
960 unsigned long mask;
962 xgcv.background = s->f->output_data.x->cursor_pixel;
963 xgcv.foreground = s->face->background;
965 /* If the glyph would be invisible, try a different foreground. */
966 if (xgcv.foreground == xgcv.background)
967 xgcv.foreground = s->face->foreground;
968 if (xgcv.foreground == xgcv.background)
969 xgcv.foreground = s->f->output_data.x->cursor_foreground_pixel;
970 if (xgcv.foreground == xgcv.background)
971 xgcv.foreground = s->face->foreground;
973 /* Make sure the cursor is distinct from text in this face. */
974 if (xgcv.background == s->face->background
975 && xgcv.foreground == s->face->foreground)
977 xgcv.background = s->face->foreground;
978 xgcv.foreground = s->face->background;
981 IF_DEBUG (x_check_font (s->f, s->font));
982 xgcv.graphics_exposures = False;
983 mask = GCForeground | GCBackground | GCGraphicsExposures;
985 if (FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc)
986 XChangeGC (s->display, FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc,
987 mask, &xgcv);
988 else
989 FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc
990 = XCreateGC (s->display, s->window, mask, &xgcv);
992 s->gc = FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc;
997 /* Set up S->gc of glyph string S for drawing text in mouse face. */
999 static void
1000 x_set_mouse_face_gc (struct glyph_string *s)
1002 int face_id;
1003 struct face *face;
1005 /* What face has to be used last for the mouse face? */
1006 face_id = MOUSE_HL_INFO (s->f)->mouse_face_face_id;
1007 face = FACE_FROM_ID (s->f, face_id);
1008 if (face == NULL)
1009 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
1011 if (s->first_glyph->type == CHAR_GLYPH)
1012 face_id = FACE_FOR_CHAR (s->f, face, s->first_glyph->u.ch, -1, Qnil);
1013 else
1014 face_id = FACE_FOR_CHAR (s->f, face, 0, -1, Qnil);
1015 s->face = FACE_FROM_ID (s->f, face_id);
1016 PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
1018 if (s->font == s->face->font)
1019 s->gc = s->face->gc;
1020 else
1022 /* Otherwise construct scratch_cursor_gc with values from FACE
1023 except for FONT. */
1024 XGCValues xgcv;
1025 unsigned long mask;
1027 xgcv.background = s->face->background;
1028 xgcv.foreground = s->face->foreground;
1029 xgcv.graphics_exposures = False;
1030 mask = GCForeground | GCBackground | GCGraphicsExposures;
1032 if (FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc)
1033 XChangeGC (s->display, FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc,
1034 mask, &xgcv);
1035 else
1036 FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc
1037 = XCreateGC (s->display, s->window, mask, &xgcv);
1039 s->gc = FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc;
1042 xassert (s->gc != 0);
1046 /* Set S->gc of glyph string S to a GC suitable for drawing a mode line.
1047 Faces to use in the mode line have already been computed when the
1048 matrix was built, so there isn't much to do, here. */
1050 static inline void
1051 x_set_mode_line_face_gc (struct glyph_string *s)
1053 s->gc = s->face->gc;
1057 /* Set S->gc of glyph string S for drawing that glyph string. Set
1058 S->stippled_p to a non-zero value if the face of S has a stipple
1059 pattern. */
1061 static inline void
1062 x_set_glyph_string_gc (struct glyph_string *s)
1064 PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
1066 if (s->hl == DRAW_NORMAL_TEXT)
1068 s->gc = s->face->gc;
1069 s->stippled_p = s->face->stipple != 0;
1071 else if (s->hl == DRAW_INVERSE_VIDEO)
1073 x_set_mode_line_face_gc (s);
1074 s->stippled_p = s->face->stipple != 0;
1076 else if (s->hl == DRAW_CURSOR)
1078 x_set_cursor_gc (s);
1079 s->stippled_p = 0;
1081 else if (s->hl == DRAW_MOUSE_FACE)
1083 x_set_mouse_face_gc (s);
1084 s->stippled_p = s->face->stipple != 0;
1086 else if (s->hl == DRAW_IMAGE_RAISED
1087 || s->hl == DRAW_IMAGE_SUNKEN)
1089 s->gc = s->face->gc;
1090 s->stippled_p = s->face->stipple != 0;
1092 else
1094 s->gc = s->face->gc;
1095 s->stippled_p = s->face->stipple != 0;
1098 /* GC must have been set. */
1099 xassert (s->gc != 0);
1103 /* Set clipping for output of glyph string S. S may be part of a mode
1104 line or menu if we don't have X toolkit support. */
1106 static inline void
1107 x_set_glyph_string_clipping (struct glyph_string *s)
1109 XRectangle *r = s->clip;
1110 int n = get_glyph_string_clip_rects (s, r, 2);
1112 if (n > 0)
1113 XSetClipRectangles (s->display, s->gc, 0, 0, r, n, Unsorted);
1114 s->num_clips = n;
1118 /* Set SRC's clipping for output of glyph string DST. This is called
1119 when we are drawing DST's left_overhang or right_overhang only in
1120 the area of SRC. */
1122 static void
1123 x_set_glyph_string_clipping_exactly (struct glyph_string *src, struct glyph_string *dst)
1125 XRectangle r;
1127 r.x = src->x;
1128 r.width = src->width;
1129 r.y = src->y;
1130 r.height = src->height;
1131 dst->clip[0] = r;
1132 dst->num_clips = 1;
1133 XSetClipRectangles (dst->display, dst->gc, 0, 0, &r, 1, Unsorted);
1137 /* RIF:
1138 Compute left and right overhang of glyph string S. */
1140 static void
1141 x_compute_glyph_string_overhangs (struct glyph_string *s)
1143 if (s->cmp == NULL
1144 && (s->first_glyph->type == CHAR_GLYPH
1145 || s->first_glyph->type == COMPOSITE_GLYPH))
1147 struct font_metrics metrics;
1149 if (s->first_glyph->type == CHAR_GLYPH)
1151 unsigned *code = alloca (sizeof (unsigned) * s->nchars);
1152 struct font *font = s->font;
1153 int i;
1155 for (i = 0; i < s->nchars; i++)
1156 code[i] = (s->char2b[i].byte1 << 8) | s->char2b[i].byte2;
1157 font->driver->text_extents (font, code, s->nchars, &metrics);
1159 else
1161 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1163 composition_gstring_width (gstring, s->cmp_from, s->cmp_to, &metrics);
1165 s->right_overhang = (metrics.rbearing > metrics.width
1166 ? metrics.rbearing - metrics.width : 0);
1167 s->left_overhang = metrics.lbearing < 0 ? - metrics.lbearing : 0;
1169 else if (s->cmp)
1171 s->right_overhang = s->cmp->rbearing - s->cmp->pixel_width;
1172 s->left_overhang = - s->cmp->lbearing;
1177 /* Fill rectangle X, Y, W, H with background color of glyph string S. */
1179 static inline void
1180 x_clear_glyph_string_rect (struct glyph_string *s, int x, int y, int w, int h)
1182 XGCValues xgcv;
1183 XGetGCValues (s->display, s->gc, GCForeground | GCBackground, &xgcv);
1184 XSetForeground (s->display, s->gc, xgcv.background);
1185 XFillRectangle (s->display, s->window, s->gc, x, y, w, h);
1186 XSetForeground (s->display, s->gc, xgcv.foreground);
1190 /* Draw the background of glyph_string S. If S->background_filled_p
1191 is non-zero don't draw it. FORCE_P non-zero means draw the
1192 background even if it wouldn't be drawn normally. This is used
1193 when a string preceding S draws into the background of S, or S
1194 contains the first component of a composition. */
1196 static void
1197 x_draw_glyph_string_background (struct glyph_string *s, int force_p)
1199 /* Nothing to do if background has already been drawn or if it
1200 shouldn't be drawn in the first place. */
1201 if (!s->background_filled_p)
1203 int box_line_width = max (s->face->box_line_width, 0);
1205 if (s->stippled_p)
1207 /* Fill background with a stipple pattern. */
1208 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
1209 XFillRectangle (s->display, s->window, s->gc, s->x,
1210 s->y + box_line_width,
1211 s->background_width,
1212 s->height - 2 * box_line_width);
1213 XSetFillStyle (s->display, s->gc, FillSolid);
1214 s->background_filled_p = 1;
1216 else if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
1217 || s->font_not_found_p
1218 || s->extends_to_end_of_line_p
1219 || force_p)
1221 x_clear_glyph_string_rect (s, s->x, s->y + box_line_width,
1222 s->background_width,
1223 s->height - 2 * box_line_width);
1224 s->background_filled_p = 1;
1230 /* Draw the foreground of glyph string S. */
1232 static void
1233 x_draw_glyph_string_foreground (struct glyph_string *s)
1235 int i, x;
1237 /* If first glyph of S has a left box line, start drawing the text
1238 of S to the right of that box line. */
1239 if (s->face->box != FACE_NO_BOX
1240 && s->first_glyph->left_box_line_p)
1241 x = s->x + eabs (s->face->box_line_width);
1242 else
1243 x = s->x;
1245 /* Draw characters of S as rectangles if S's font could not be
1246 loaded. */
1247 if (s->font_not_found_p)
1249 for (i = 0; i < s->nchars; ++i)
1251 struct glyph *g = s->first_glyph + i;
1252 XDrawRectangle (s->display, s->window,
1253 s->gc, x, s->y, g->pixel_width - 1,
1254 s->height - 1);
1255 x += g->pixel_width;
1258 else
1260 struct font *font = s->font;
1261 int boff = font->baseline_offset;
1262 int y;
1264 if (font->vertical_centering)
1265 boff = VCENTER_BASELINE_OFFSET (font, s->f) - boff;
1267 y = s->ybase - boff;
1268 if (s->for_overlaps
1269 || (s->background_filled_p && s->hl != DRAW_CURSOR))
1270 font->driver->draw (s, 0, s->nchars, x, y, 0);
1271 else
1272 font->driver->draw (s, 0, s->nchars, x, y, 1);
1273 if (s->face->overstrike)
1274 font->driver->draw (s, 0, s->nchars, x + 1, y, 0);
1278 /* Draw the foreground of composite glyph string S. */
1280 static void
1281 x_draw_composite_glyph_string_foreground (struct glyph_string *s)
1283 int i, j, x;
1284 struct font *font = s->font;
1286 /* If first glyph of S has a left box line, start drawing the text
1287 of S to the right of that box line. */
1288 if (s->face && s->face->box != FACE_NO_BOX
1289 && s->first_glyph->left_box_line_p)
1290 x = s->x + eabs (s->face->box_line_width);
1291 else
1292 x = s->x;
1294 /* S is a glyph string for a composition. S->cmp_from is the index
1295 of the first character drawn for glyphs of this composition.
1296 S->cmp_from == 0 means we are drawing the very first character of
1297 this composition. */
1299 /* Draw a rectangle for the composition if the font for the very
1300 first character of the composition could not be loaded. */
1301 if (s->font_not_found_p)
1303 if (s->cmp_from == 0)
1304 XDrawRectangle (s->display, s->window, s->gc, x, s->y,
1305 s->width - 1, s->height - 1);
1307 else if (! s->first_glyph->u.cmp.automatic)
1309 int y = s->ybase;
1311 for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
1312 /* TAB in a composition means display glyphs with padding
1313 space on the left or right. */
1314 if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
1316 int xx = x + s->cmp->offsets[j * 2];
1317 int yy = y - s->cmp->offsets[j * 2 + 1];
1319 font->driver->draw (s, j, j + 1, xx, yy, 0);
1320 if (s->face->overstrike)
1321 font->driver->draw (s, j, j + 1, xx + 1, yy, 0);
1324 else
1326 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1327 Lisp_Object glyph;
1328 int y = s->ybase;
1329 int width = 0;
1331 for (i = j = s->cmp_from; i < s->cmp_to; i++)
1333 glyph = LGSTRING_GLYPH (gstring, i);
1334 if (NILP (LGLYPH_ADJUSTMENT (glyph)))
1335 width += LGLYPH_WIDTH (glyph);
1336 else
1338 int xoff, yoff, wadjust;
1340 if (j < i)
1342 font->driver->draw (s, j, i, x, y, 0);
1343 if (s->face->overstrike)
1344 font->driver->draw (s, j, i, x + 1, y, 0);
1345 x += width;
1347 xoff = LGLYPH_XOFF (glyph);
1348 yoff = LGLYPH_YOFF (glyph);
1349 wadjust = LGLYPH_WADJUST (glyph);
1350 font->driver->draw (s, i, i + 1, x + xoff, y + yoff, 0);
1351 if (s->face->overstrike)
1352 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff, 0);
1353 x += wadjust;
1354 j = i + 1;
1355 width = 0;
1358 if (j < i)
1360 font->driver->draw (s, j, i, x, y, 0);
1361 if (s->face->overstrike)
1362 font->driver->draw (s, j, i, x + 1, y, 0);
1368 /* Draw the foreground of glyph string S for glyphless characters. */
1370 static void
1371 x_draw_glyphless_glyph_string_foreground (struct glyph_string *s)
1373 struct glyph *glyph = s->first_glyph;
1374 XChar2b char2b[8];
1375 int x, i, j;
1377 /* If first glyph of S has a left box line, start drawing the text
1378 of S to the right of that box line. */
1379 if (s->face && s->face->box != FACE_NO_BOX
1380 && s->first_glyph->left_box_line_p)
1381 x = s->x + eabs (s->face->box_line_width);
1382 else
1383 x = s->x;
1385 s->char2b = char2b;
1387 for (i = 0; i < s->nchars; i++, glyph++)
1389 char buf[7], *str = NULL;
1390 int len = glyph->u.glyphless.len;
1392 if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_ACRONYM)
1394 if (len > 0
1395 && CHAR_TABLE_P (Vglyphless_char_display)
1396 && (CHAR_TABLE_EXTRA_SLOTS (XCHAR_TABLE (Vglyphless_char_display))
1397 >= 1))
1399 Lisp_Object acronym
1400 = (! glyph->u.glyphless.for_no_font
1401 ? CHAR_TABLE_REF (Vglyphless_char_display,
1402 glyph->u.glyphless.ch)
1403 : XCHAR_TABLE (Vglyphless_char_display)->extras[0]);
1404 if (STRINGP (acronym))
1405 str = SSDATA (acronym);
1408 else if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_HEX_CODE)
1410 sprintf ((char *) buf, "%0*X",
1411 glyph->u.glyphless.ch < 0x10000 ? 4 : 6,
1412 glyph->u.glyphless.ch);
1413 str = buf;
1416 if (str)
1418 int upper_len = (len + 1) / 2;
1419 unsigned code;
1421 /* It is assured that all LEN characters in STR is ASCII. */
1422 for (j = 0; j < len; j++)
1424 code = s->font->driver->encode_char (s->font, str[j]);
1425 STORE_XCHAR2B (char2b + j, code >> 8, code & 0xFF);
1427 s->font->driver->draw (s, 0, upper_len,
1428 x + glyph->slice.glyphless.upper_xoff,
1429 s->ybase + glyph->slice.glyphless.upper_yoff,
1431 s->font->driver->draw (s, upper_len, len,
1432 x + glyph->slice.glyphless.lower_xoff,
1433 s->ybase + glyph->slice.glyphless.lower_yoff,
1436 if (glyph->u.glyphless.method != GLYPHLESS_DISPLAY_THIN_SPACE)
1437 XDrawRectangle (s->display, s->window, s->gc,
1438 x, s->ybase - glyph->ascent,
1439 glyph->pixel_width - 1,
1440 glyph->ascent + glyph->descent - 1);
1441 x += glyph->pixel_width;
1445 #ifdef USE_X_TOOLKIT
1447 static struct frame *x_frame_of_widget (Widget);
1448 static Boolean cvt_string_to_pixel (Display *, XrmValue *, Cardinal *,
1449 XrmValue *, XrmValue *, XtPointer *);
1450 static void cvt_pixel_dtor (XtAppContext, XrmValue *, XtPointer,
1451 XrmValue *, Cardinal *);
1454 /* Return the frame on which widget WIDGET is used.. Abort if frame
1455 cannot be determined. */
1457 static struct frame *
1458 x_frame_of_widget (Widget widget)
1460 struct x_display_info *dpyinfo;
1461 Lisp_Object tail;
1462 struct frame *f;
1464 dpyinfo = x_display_info_for_display (XtDisplay (widget));
1466 /* Find the top-level shell of the widget. Note that this function
1467 can be called when the widget is not yet realized, so XtWindow
1468 (widget) == 0. That's the reason we can't simply use
1469 x_any_window_to_frame. */
1470 while (!XtIsTopLevelShell (widget))
1471 widget = XtParent (widget);
1473 /* Look for a frame with that top-level widget. Allocate the color
1474 on that frame to get the right gamma correction value. */
1475 for (tail = Vframe_list; CONSP (tail); tail = XCDR (tail))
1476 if (FRAMEP (XCAR (tail))
1477 && (f = XFRAME (XCAR (tail)),
1478 (FRAME_X_P (f)
1479 && f->output_data.nothing != 1
1480 && FRAME_X_DISPLAY_INFO (f) == dpyinfo))
1481 && f->output_data.x->widget == widget)
1482 return f;
1484 abort ();
1488 #ifdef USE_LUCID
1490 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
1491 or DELTA. Try a color with RGB values multiplied by FACTOR first.
1492 If this produces the same color as PIXEL, try a color where all RGB
1493 values have DELTA added. Return the allocated color in *PIXEL.
1494 DISPLAY is the X display, CMAP is the colormap to operate on.
1495 Value is non-zero if successful. */
1498 x_alloc_lighter_color_for_widget (Widget widget, Display *display, Colormap cmap,
1499 unsigned long *pixel, double factor, int delta)
1501 struct frame *f = x_frame_of_widget (widget);
1502 return x_alloc_lighter_color (f, display, cmap, pixel, factor, delta);
1505 #endif
1508 /* Structure specifying which arguments should be passed by Xt to
1509 cvt_string_to_pixel. We want the widget's screen and colormap. */
1511 static XtConvertArgRec cvt_string_to_pixel_args[] =
1513 {XtWidgetBaseOffset, (XtPointer) XtOffset (Widget, core.screen),
1514 sizeof (Screen *)},
1515 {XtWidgetBaseOffset, (XtPointer) XtOffset (Widget, core.colormap),
1516 sizeof (Colormap)}
1520 /* The address of this variable is returned by
1521 cvt_string_to_pixel. */
1523 static Pixel cvt_string_to_pixel_value;
1526 /* Convert a color name to a pixel color.
1528 DPY is the display we are working on.
1530 ARGS is an array of *NARGS XrmValue structures holding additional
1531 information about the widget for which the conversion takes place.
1532 The contents of this array are determined by the specification
1533 in cvt_string_to_pixel_args.
1535 FROM is a pointer to an XrmValue which points to the color name to
1536 convert. TO is an XrmValue in which to return the pixel color.
1538 CLOSURE_RET is a pointer to user-data, in which we record if
1539 we allocated the color or not.
1541 Value is True if successful, False otherwise. */
1543 static Boolean
1544 cvt_string_to_pixel (Display *dpy, XrmValue *args, Cardinal *nargs,
1545 XrmValue *from, XrmValue *to,
1546 XtPointer *closure_ret)
1548 Screen *screen;
1549 Colormap cmap;
1550 Pixel pixel;
1551 String color_name;
1552 XColor color;
1554 if (*nargs != 2)
1556 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
1557 "wrongParameters", "cvt_string_to_pixel",
1558 "XtToolkitError",
1559 "Screen and colormap args required", NULL, NULL);
1560 return False;
1563 screen = *(Screen **) args[0].addr;
1564 cmap = *(Colormap *) args[1].addr;
1565 color_name = (String) from->addr;
1567 if (strcmp (color_name, XtDefaultBackground) == 0)
1569 *closure_ret = (XtPointer) False;
1570 pixel = WhitePixelOfScreen (screen);
1572 else if (strcmp (color_name, XtDefaultForeground) == 0)
1574 *closure_ret = (XtPointer) False;
1575 pixel = BlackPixelOfScreen (screen);
1577 else if (XParseColor (dpy, cmap, color_name, &color)
1578 && x_alloc_nearest_color_1 (dpy, cmap, &color))
1580 pixel = color.pixel;
1581 *closure_ret = (XtPointer) True;
1583 else
1585 String params[1];
1586 Cardinal nparams = 1;
1588 params[0] = color_name;
1589 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
1590 "badValue", "cvt_string_to_pixel",
1591 "XtToolkitError", "Invalid color `%s'",
1592 params, &nparams);
1593 return False;
1596 if (to->addr != NULL)
1598 if (to->size < sizeof (Pixel))
1600 to->size = sizeof (Pixel);
1601 return False;
1604 *(Pixel *) to->addr = pixel;
1606 else
1608 cvt_string_to_pixel_value = pixel;
1609 to->addr = (XtPointer) &cvt_string_to_pixel_value;
1612 to->size = sizeof (Pixel);
1613 return True;
1617 /* Free a pixel color which was previously allocated via
1618 cvt_string_to_pixel. This is registered as the destructor
1619 for this type of resource via XtSetTypeConverter.
1621 APP is the application context in which we work.
1623 TO is a pointer to an XrmValue holding the color to free.
1624 CLOSURE is the value we stored in CLOSURE_RET for this color
1625 in cvt_string_to_pixel.
1627 ARGS and NARGS are like for cvt_string_to_pixel. */
1629 static void
1630 cvt_pixel_dtor (XtAppContext app, XrmValuePtr to, XtPointer closure, XrmValuePtr args,
1631 Cardinal *nargs)
1633 if (*nargs != 2)
1635 XtAppWarningMsg (app, "wrongParameters", "cvt_pixel_dtor",
1636 "XtToolkitError",
1637 "Screen and colormap arguments required",
1638 NULL, NULL);
1640 else if (closure != NULL)
1642 /* We did allocate the pixel, so free it. */
1643 Screen *screen = *(Screen **) args[0].addr;
1644 Colormap cmap = *(Colormap *) args[1].addr;
1645 x_free_dpy_colors (DisplayOfScreen (screen), screen, cmap,
1646 (Pixel *) to->addr, 1);
1651 #endif /* USE_X_TOOLKIT */
1654 /* Value is an array of XColor structures for the contents of the
1655 color map of display DPY. Set *NCELLS to the size of the array.
1656 Note that this probably shouldn't be called for large color maps,
1657 say a 24-bit TrueColor map. */
1659 static const XColor *
1660 x_color_cells (Display *dpy, int *ncells)
1662 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
1664 if (dpyinfo->color_cells == NULL)
1666 Screen *screen = dpyinfo->screen;
1667 int ncolor_cells = XDisplayCells (dpy, XScreenNumberOfScreen (screen));
1668 int i;
1670 dpyinfo->color_cells = xnmalloc (ncolor_cells,
1671 sizeof *dpyinfo->color_cells);
1672 dpyinfo->ncolor_cells = ncolor_cells;
1674 for (i = 0; i < ncolor_cells; ++i)
1675 dpyinfo->color_cells[i].pixel = i;
1677 XQueryColors (dpy, dpyinfo->cmap,
1678 dpyinfo->color_cells, ncolor_cells);
1681 *ncells = dpyinfo->ncolor_cells;
1682 return dpyinfo->color_cells;
1686 /* On frame F, translate pixel colors to RGB values for the NCOLORS
1687 colors in COLORS. Use cached information, if available. */
1689 void
1690 x_query_colors (struct frame *f, XColor *colors, int ncolors)
1692 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
1694 if (dpyinfo->color_cells)
1696 int i;
1697 for (i = 0; i < ncolors; ++i)
1699 unsigned long pixel = colors[i].pixel;
1700 xassert (pixel < dpyinfo->ncolor_cells);
1701 xassert (dpyinfo->color_cells[pixel].pixel == pixel);
1702 colors[i] = dpyinfo->color_cells[pixel];
1705 else
1706 XQueryColors (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), colors, ncolors);
1710 /* On frame F, translate pixel color to RGB values for the color in
1711 COLOR. Use cached information, if available. */
1713 void
1714 x_query_color (struct frame *f, XColor *color)
1716 x_query_colors (f, color, 1);
1720 /* Allocate the color COLOR->pixel on DISPLAY, colormap CMAP. If an
1721 exact match can't be allocated, try the nearest color available.
1722 Value is non-zero if successful. Set *COLOR to the color
1723 allocated. */
1725 static int
1726 x_alloc_nearest_color_1 (Display *dpy, Colormap cmap, XColor *color)
1728 int rc;
1730 rc = XAllocColor (dpy, cmap, color);
1731 if (rc == 0)
1733 /* If we got to this point, the colormap is full, so we're going
1734 to try to get the next closest color. The algorithm used is
1735 a least-squares matching, which is what X uses for closest
1736 color matching with StaticColor visuals. */
1737 int nearest, i;
1738 int max_color_delta = 255;
1739 int max_delta = 3 * max_color_delta;
1740 int nearest_delta = max_delta + 1;
1741 int ncells;
1742 const XColor *cells = x_color_cells (dpy, &ncells);
1744 for (nearest = i = 0; i < ncells; ++i)
1746 int dred = (color->red >> 8) - (cells[i].red >> 8);
1747 int dgreen = (color->green >> 8) - (cells[i].green >> 8);
1748 int dblue = (color->blue >> 8) - (cells[i].blue >> 8);
1749 int delta = dred * dred + dgreen * dgreen + dblue * dblue;
1751 if (delta < nearest_delta)
1753 nearest = i;
1754 nearest_delta = delta;
1758 color->red = cells[nearest].red;
1759 color->green = cells[nearest].green;
1760 color->blue = cells[nearest].blue;
1761 rc = XAllocColor (dpy, cmap, color);
1763 else
1765 /* If allocation succeeded, and the allocated pixel color is not
1766 equal to a cached pixel color recorded earlier, there was a
1767 change in the colormap, so clear the color cache. */
1768 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
1769 XColor *cached_color;
1771 if (dpyinfo->color_cells
1772 && (cached_color = &dpyinfo->color_cells[color->pixel],
1773 (cached_color->red != color->red
1774 || cached_color->blue != color->blue
1775 || cached_color->green != color->green)))
1777 xfree (dpyinfo->color_cells);
1778 dpyinfo->color_cells = NULL;
1779 dpyinfo->ncolor_cells = 0;
1783 #ifdef DEBUG_X_COLORS
1784 if (rc)
1785 register_color (color->pixel);
1786 #endif /* DEBUG_X_COLORS */
1788 return rc;
1792 /* Allocate the color COLOR->pixel on frame F, colormap CMAP. If an
1793 exact match can't be allocated, try the nearest color available.
1794 Value is non-zero if successful. Set *COLOR to the color
1795 allocated. */
1798 x_alloc_nearest_color (struct frame *f, Colormap cmap, XColor *color)
1800 gamma_correct (f, color);
1801 return x_alloc_nearest_color_1 (FRAME_X_DISPLAY (f), cmap, color);
1805 /* Allocate color PIXEL on frame F. PIXEL must already be allocated.
1806 It's necessary to do this instead of just using PIXEL directly to
1807 get color reference counts right. */
1809 unsigned long
1810 x_copy_color (struct frame *f, long unsigned int pixel)
1812 XColor color;
1814 color.pixel = pixel;
1815 BLOCK_INPUT;
1816 x_query_color (f, &color);
1817 XAllocColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &color);
1818 UNBLOCK_INPUT;
1819 #ifdef DEBUG_X_COLORS
1820 register_color (pixel);
1821 #endif
1822 return color.pixel;
1826 /* Brightness beyond which a color won't have its highlight brightness
1827 boosted.
1829 Nominally, highlight colors for `3d' faces are calculated by
1830 brightening an object's color by a constant scale factor, but this
1831 doesn't yield good results for dark colors, so for colors who's
1832 brightness is less than this value (on a scale of 0-65535) have an
1833 use an additional additive factor.
1835 The value here is set so that the default menu-bar/mode-line color
1836 (grey75) will not have its highlights changed at all. */
1837 #define HIGHLIGHT_COLOR_DARK_BOOST_LIMIT 48000
1840 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
1841 or DELTA. Try a color with RGB values multiplied by FACTOR first.
1842 If this produces the same color as PIXEL, try a color where all RGB
1843 values have DELTA added. Return the allocated color in *PIXEL.
1844 DISPLAY is the X display, CMAP is the colormap to operate on.
1845 Value is non-zero if successful. */
1847 static int
1848 x_alloc_lighter_color (struct frame *f, Display *display, Colormap cmap, long unsigned int *pixel, double factor, int delta)
1850 XColor color, new;
1851 long bright;
1852 int success_p;
1854 /* Get RGB color values. */
1855 color.pixel = *pixel;
1856 x_query_color (f, &color);
1858 /* Change RGB values by specified FACTOR. Avoid overflow! */
1859 xassert (factor >= 0);
1860 new.red = min (0xffff, factor * color.red);
1861 new.green = min (0xffff, factor * color.green);
1862 new.blue = min (0xffff, factor * color.blue);
1864 /* Calculate brightness of COLOR. */
1865 bright = (2 * color.red + 3 * color.green + color.blue) / 6;
1867 /* We only boost colors that are darker than
1868 HIGHLIGHT_COLOR_DARK_BOOST_LIMIT. */
1869 if (bright < HIGHLIGHT_COLOR_DARK_BOOST_LIMIT)
1870 /* Make an additive adjustment to NEW, because it's dark enough so
1871 that scaling by FACTOR alone isn't enough. */
1873 /* How far below the limit this color is (0 - 1, 1 being darker). */
1874 double dimness = 1 - (double)bright / HIGHLIGHT_COLOR_DARK_BOOST_LIMIT;
1875 /* The additive adjustment. */
1876 int min_delta = delta * dimness * factor / 2;
1878 if (factor < 1)
1880 new.red = max (0, new.red - min_delta);
1881 new.green = max (0, new.green - min_delta);
1882 new.blue = max (0, new.blue - min_delta);
1884 else
1886 new.red = min (0xffff, min_delta + new.red);
1887 new.green = min (0xffff, min_delta + new.green);
1888 new.blue = min (0xffff, min_delta + new.blue);
1892 /* Try to allocate the color. */
1893 success_p = x_alloc_nearest_color (f, cmap, &new);
1894 if (success_p)
1896 if (new.pixel == *pixel)
1898 /* If we end up with the same color as before, try adding
1899 delta to the RGB values. */
1900 x_free_colors (f, &new.pixel, 1);
1902 new.red = min (0xffff, delta + color.red);
1903 new.green = min (0xffff, delta + color.green);
1904 new.blue = min (0xffff, delta + color.blue);
1905 success_p = x_alloc_nearest_color (f, cmap, &new);
1907 else
1908 success_p = 1;
1909 *pixel = new.pixel;
1912 return success_p;
1916 /* Set up the foreground color for drawing relief lines of glyph
1917 string S. RELIEF is a pointer to a struct relief containing the GC
1918 with which lines will be drawn. Use a color that is FACTOR or
1919 DELTA lighter or darker than the relief's background which is found
1920 in S->f->output_data.x->relief_background. If such a color cannot
1921 be allocated, use DEFAULT_PIXEL, instead. */
1923 static void
1924 x_setup_relief_color (struct frame *f, struct relief *relief, double factor, int delta, long unsigned int default_pixel)
1926 XGCValues xgcv;
1927 struct x_output *di = f->output_data.x;
1928 unsigned long mask = GCForeground | GCLineWidth | GCGraphicsExposures;
1929 unsigned long pixel;
1930 unsigned long background = di->relief_background;
1931 Colormap cmap = FRAME_X_COLORMAP (f);
1932 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
1933 Display *dpy = FRAME_X_DISPLAY (f);
1935 xgcv.graphics_exposures = False;
1936 xgcv.line_width = 1;
1938 /* Free previously allocated color. The color cell will be reused
1939 when it has been freed as many times as it was allocated, so this
1940 doesn't affect faces using the same colors. */
1941 if (relief->gc
1942 && relief->allocated_p)
1944 x_free_colors (f, &relief->pixel, 1);
1945 relief->allocated_p = 0;
1948 /* Allocate new color. */
1949 xgcv.foreground = default_pixel;
1950 pixel = background;
1951 if (dpyinfo->n_planes != 1
1952 && x_alloc_lighter_color (f, dpy, cmap, &pixel, factor, delta))
1954 relief->allocated_p = 1;
1955 xgcv.foreground = relief->pixel = pixel;
1958 if (relief->gc == 0)
1960 xgcv.stipple = dpyinfo->gray;
1961 mask |= GCStipple;
1962 relief->gc = XCreateGC (dpy, FRAME_X_WINDOW (f), mask, &xgcv);
1964 else
1965 XChangeGC (dpy, relief->gc, mask, &xgcv);
1969 /* Set up colors for the relief lines around glyph string S. */
1971 static void
1972 x_setup_relief_colors (struct glyph_string *s)
1974 struct x_output *di = s->f->output_data.x;
1975 unsigned long color;
1977 if (s->face->use_box_color_for_shadows_p)
1978 color = s->face->box_color;
1979 else if (s->first_glyph->type == IMAGE_GLYPH
1980 && s->img->pixmap
1981 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
1982 color = IMAGE_BACKGROUND (s->img, s->f, 0);
1983 else
1985 XGCValues xgcv;
1987 /* Get the background color of the face. */
1988 XGetGCValues (s->display, s->gc, GCBackground, &xgcv);
1989 color = xgcv.background;
1992 if (di->white_relief.gc == 0
1993 || color != di->relief_background)
1995 di->relief_background = color;
1996 x_setup_relief_color (s->f, &di->white_relief, 1.2, 0x8000,
1997 WHITE_PIX_DEFAULT (s->f));
1998 x_setup_relief_color (s->f, &di->black_relief, 0.6, 0x4000,
1999 BLACK_PIX_DEFAULT (s->f));
2004 /* Draw a relief on frame F inside the rectangle given by LEFT_X,
2005 TOP_Y, RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the relief
2006 to draw, it must be >= 0. RAISED_P non-zero means draw a raised
2007 relief. LEFT_P non-zero means draw a relief on the left side of
2008 the rectangle. RIGHT_P non-zero means draw a relief on the right
2009 side of the rectangle. CLIP_RECT is the clipping rectangle to use
2010 when drawing. */
2012 static void
2013 x_draw_relief_rect (struct frame *f,
2014 int left_x, int top_y, int right_x, int bottom_y, int width,
2015 int raised_p, int top_p, int bot_p, int left_p, int right_p,
2016 XRectangle *clip_rect)
2018 Display *dpy = FRAME_X_DISPLAY (f);
2019 Window window = FRAME_X_WINDOW (f);
2020 int i;
2021 GC gc;
2023 if (raised_p)
2024 gc = f->output_data.x->white_relief.gc;
2025 else
2026 gc = f->output_data.x->black_relief.gc;
2027 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
2029 /* This code is more complicated than it has to be, because of two
2030 minor hacks to make the boxes look nicer: (i) if width > 1, draw
2031 the outermost line using the black relief. (ii) Omit the four
2032 corner pixels. */
2034 /* Top. */
2035 if (top_p)
2037 if (width == 1)
2038 XDrawLine (dpy, window, gc,
2039 left_x + (left_p ? 1 : 0), top_y,
2040 right_x + (right_p ? 0 : 1), top_y);
2042 for (i = 1; i < width; ++i)
2043 XDrawLine (dpy, window, gc,
2044 left_x + i * left_p, top_y + i,
2045 right_x + 1 - i * right_p, top_y + i);
2048 /* Left. */
2049 if (left_p)
2051 if (width == 1)
2052 XDrawLine (dpy, window, gc, left_x, top_y + 1, left_x, bottom_y);
2054 XClearArea (dpy, window, left_x, top_y, 1, 1, False);
2055 XClearArea (dpy, window, left_x, bottom_y, 1, 1, False);
2057 for (i = (width > 1 ? 1 : 0); i < width; ++i)
2058 XDrawLine (dpy, window, gc,
2059 left_x + i, top_y + i, left_x + i, bottom_y - i + 1);
2062 XSetClipMask (dpy, gc, None);
2063 if (raised_p)
2064 gc = f->output_data.x->black_relief.gc;
2065 else
2066 gc = f->output_data.x->white_relief.gc;
2067 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
2069 if (width > 1)
2071 /* Outermost top line. */
2072 if (top_p)
2073 XDrawLine (dpy, window, gc,
2074 left_x + (left_p ? 1 : 0), top_y,
2075 right_x + (right_p ? 0 : 1), top_y);
2077 /* Outermost left line. */
2078 if (left_p)
2079 XDrawLine (dpy, window, gc, left_x, top_y + 1, left_x, bottom_y);
2082 /* Bottom. */
2083 if (bot_p)
2085 XDrawLine (dpy, window, gc,
2086 left_x + (left_p ? 1 : 0), bottom_y,
2087 right_x + (right_p ? 0 : 1), bottom_y);
2088 for (i = 1; i < width; ++i)
2089 XDrawLine (dpy, window, gc,
2090 left_x + i * left_p, bottom_y - i,
2091 right_x + 1 - i * right_p, bottom_y - i);
2094 /* Right. */
2095 if (right_p)
2097 XClearArea (dpy, window, right_x, top_y, 1, 1, False);
2098 XClearArea (dpy, window, right_x, bottom_y, 1, 1, False);
2099 for (i = 0; i < width; ++i)
2100 XDrawLine (dpy, window, gc,
2101 right_x - i, top_y + i + 1, right_x - i, bottom_y - i);
2104 XSetClipMask (dpy, gc, None);
2108 /* Draw a box on frame F inside the rectangle given by LEFT_X, TOP_Y,
2109 RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the lines to
2110 draw, it must be >= 0. LEFT_P non-zero means draw a line on the
2111 left side of the rectangle. RIGHT_P non-zero means draw a line
2112 on the right side of the rectangle. CLIP_RECT is the clipping
2113 rectangle to use when drawing. */
2115 static void
2116 x_draw_box_rect (struct glyph_string *s,
2117 int left_x, int top_y, int right_x, int bottom_y, int width,
2118 int left_p, int right_p, XRectangle *clip_rect)
2120 XGCValues xgcv;
2122 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2123 XSetForeground (s->display, s->gc, s->face->box_color);
2124 XSetClipRectangles (s->display, s->gc, 0, 0, clip_rect, 1, Unsorted);
2126 /* Top. */
2127 XFillRectangle (s->display, s->window, s->gc,
2128 left_x, top_y, right_x - left_x + 1, width);
2130 /* Left. */
2131 if (left_p)
2132 XFillRectangle (s->display, s->window, s->gc,
2133 left_x, top_y, width, bottom_y - top_y + 1);
2135 /* Bottom. */
2136 XFillRectangle (s->display, s->window, s->gc,
2137 left_x, bottom_y - width + 1, right_x - left_x + 1, width);
2139 /* Right. */
2140 if (right_p)
2141 XFillRectangle (s->display, s->window, s->gc,
2142 right_x - width + 1, top_y, width, bottom_y - top_y + 1);
2144 XSetForeground (s->display, s->gc, xgcv.foreground);
2145 XSetClipMask (s->display, s->gc, None);
2149 /* Draw a box around glyph string S. */
2151 static void
2152 x_draw_glyph_string_box (struct glyph_string *s)
2154 int width, left_x, right_x, top_y, bottom_y, last_x, raised_p;
2155 int left_p, right_p;
2156 struct glyph *last_glyph;
2157 XRectangle clip_rect;
2159 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2160 ? WINDOW_RIGHT_EDGE_X (s->w)
2161 : window_box_right (s->w, s->area));
2163 /* The glyph that may have a right box line. */
2164 last_glyph = (s->cmp || s->img
2165 ? s->first_glyph
2166 : s->first_glyph + s->nchars - 1);
2168 width = eabs (s->face->box_line_width);
2169 raised_p = s->face->box == FACE_RAISED_BOX;
2170 left_x = s->x;
2171 right_x = (s->row->full_width_p && s->extends_to_end_of_line_p
2172 ? last_x - 1
2173 : min (last_x, s->x + s->background_width) - 1);
2174 top_y = s->y;
2175 bottom_y = top_y + s->height - 1;
2177 left_p = (s->first_glyph->left_box_line_p
2178 || (s->hl == DRAW_MOUSE_FACE
2179 && (s->prev == NULL
2180 || s->prev->hl != s->hl)));
2181 right_p = (last_glyph->right_box_line_p
2182 || (s->hl == DRAW_MOUSE_FACE
2183 && (s->next == NULL
2184 || s->next->hl != s->hl)));
2186 get_glyph_string_clip_rect (s, &clip_rect);
2188 if (s->face->box == FACE_SIMPLE_BOX)
2189 x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
2190 left_p, right_p, &clip_rect);
2191 else
2193 x_setup_relief_colors (s);
2194 x_draw_relief_rect (s->f, left_x, top_y, right_x, bottom_y,
2195 width, raised_p, 1, 1, left_p, right_p, &clip_rect);
2200 /* Draw foreground of image glyph string S. */
2202 static void
2203 x_draw_image_foreground (struct glyph_string *s)
2205 int x = s->x;
2206 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2208 /* If first glyph of S has a left box line, start drawing it to the
2209 right of that line. */
2210 if (s->face->box != FACE_NO_BOX
2211 && s->first_glyph->left_box_line_p
2212 && s->slice.x == 0)
2213 x += eabs (s->face->box_line_width);
2215 /* If there is a margin around the image, adjust x- and y-position
2216 by that margin. */
2217 if (s->slice.x == 0)
2218 x += s->img->hmargin;
2219 if (s->slice.y == 0)
2220 y += s->img->vmargin;
2222 if (s->img->pixmap)
2224 if (s->img->mask)
2226 /* We can't set both a clip mask and use XSetClipRectangles
2227 because the latter also sets a clip mask. We also can't
2228 trust on the shape extension to be available
2229 (XShapeCombineRegion). So, compute the rectangle to draw
2230 manually. */
2231 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
2232 | GCFunction);
2233 XGCValues xgcv;
2234 XRectangle clip_rect, image_rect, r;
2236 xgcv.clip_mask = s->img->mask;
2237 xgcv.clip_x_origin = x;
2238 xgcv.clip_y_origin = y;
2239 xgcv.function = GXcopy;
2240 XChangeGC (s->display, s->gc, mask, &xgcv);
2242 get_glyph_string_clip_rect (s, &clip_rect);
2243 image_rect.x = x;
2244 image_rect.y = y;
2245 image_rect.width = s->slice.width;
2246 image_rect.height = s->slice.height;
2247 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
2248 XCopyArea (s->display, s->img->pixmap, s->window, s->gc,
2249 s->slice.x + r.x - x, s->slice.y + r.y - y,
2250 r.width, r.height, r.x, r.y);
2252 else
2254 XRectangle clip_rect, image_rect, r;
2256 get_glyph_string_clip_rect (s, &clip_rect);
2257 image_rect.x = x;
2258 image_rect.y = y;
2259 image_rect.width = s->slice.width;
2260 image_rect.height = s->slice.height;
2261 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
2262 XCopyArea (s->display, s->img->pixmap, s->window, s->gc,
2263 s->slice.x + r.x - x, s->slice.y + r.y - y,
2264 r.width, r.height, r.x, r.y);
2266 /* When the image has a mask, we can expect that at
2267 least part of a mouse highlight or a block cursor will
2268 be visible. If the image doesn't have a mask, make
2269 a block cursor visible by drawing a rectangle around
2270 the image. I believe it's looking better if we do
2271 nothing here for mouse-face. */
2272 if (s->hl == DRAW_CURSOR)
2274 int relief = s->img->relief;
2275 if (relief < 0) relief = -relief;
2276 XDrawRectangle (s->display, s->window, s->gc,
2277 x - relief, y - relief,
2278 s->slice.width + relief*2 - 1,
2279 s->slice.height + relief*2 - 1);
2283 else
2284 /* Draw a rectangle if image could not be loaded. */
2285 XDrawRectangle (s->display, s->window, s->gc, x, y,
2286 s->slice.width - 1, s->slice.height - 1);
2290 /* Draw a relief around the image glyph string S. */
2292 static void
2293 x_draw_image_relief (struct glyph_string *s)
2295 int x0, y0, x1, y1, thick, raised_p;
2296 int extra_x, extra_y;
2297 XRectangle r;
2298 int x = s->x;
2299 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2301 /* If first glyph of S has a left box line, start drawing it to the
2302 right of that line. */
2303 if (s->face->box != FACE_NO_BOX
2304 && s->first_glyph->left_box_line_p
2305 && s->slice.x == 0)
2306 x += eabs (s->face->box_line_width);
2308 /* If there is a margin around the image, adjust x- and y-position
2309 by that margin. */
2310 if (s->slice.x == 0)
2311 x += s->img->hmargin;
2312 if (s->slice.y == 0)
2313 y += s->img->vmargin;
2315 if (s->hl == DRAW_IMAGE_SUNKEN
2316 || s->hl == DRAW_IMAGE_RAISED)
2318 thick = tool_bar_button_relief >= 0 ? tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
2319 raised_p = s->hl == DRAW_IMAGE_RAISED;
2321 else
2323 thick = eabs (s->img->relief);
2324 raised_p = s->img->relief > 0;
2327 extra_x = extra_y = 0;
2328 if (s->face->id == TOOL_BAR_FACE_ID)
2330 if (CONSP (Vtool_bar_button_margin)
2331 && INTEGERP (XCAR (Vtool_bar_button_margin))
2332 && INTEGERP (XCDR (Vtool_bar_button_margin)))
2334 extra_x = XINT (XCAR (Vtool_bar_button_margin));
2335 extra_y = XINT (XCDR (Vtool_bar_button_margin));
2337 else if (INTEGERP (Vtool_bar_button_margin))
2338 extra_x = extra_y = XINT (Vtool_bar_button_margin);
2341 x0 = x - thick - extra_x;
2342 y0 = y - thick - extra_y;
2343 x1 = x + s->slice.width + thick - 1 + extra_x;
2344 y1 = y + s->slice.height + thick - 1 + extra_y;
2346 x_setup_relief_colors (s);
2347 get_glyph_string_clip_rect (s, &r);
2348 x_draw_relief_rect (s->f, x0, y0, x1, y1, thick, raised_p,
2349 s->slice.y == 0,
2350 s->slice.y + s->slice.height == s->img->height,
2351 s->slice.x == 0,
2352 s->slice.x + s->slice.width == s->img->width,
2353 &r);
2357 /* Draw the foreground of image glyph string S to PIXMAP. */
2359 static void
2360 x_draw_image_foreground_1 (struct glyph_string *s, Pixmap pixmap)
2362 int x = 0;
2363 int y = s->ybase - s->y - image_ascent (s->img, s->face, &s->slice);
2365 /* If first glyph of S has a left box line, start drawing it to the
2366 right of that line. */
2367 if (s->face->box != FACE_NO_BOX
2368 && s->first_glyph->left_box_line_p
2369 && s->slice.x == 0)
2370 x += eabs (s->face->box_line_width);
2372 /* If there is a margin around the image, adjust x- and y-position
2373 by that margin. */
2374 if (s->slice.x == 0)
2375 x += s->img->hmargin;
2376 if (s->slice.y == 0)
2377 y += s->img->vmargin;
2379 if (s->img->pixmap)
2381 if (s->img->mask)
2383 /* We can't set both a clip mask and use XSetClipRectangles
2384 because the latter also sets a clip mask. We also can't
2385 trust on the shape extension to be available
2386 (XShapeCombineRegion). So, compute the rectangle to draw
2387 manually. */
2388 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
2389 | GCFunction);
2390 XGCValues xgcv;
2392 xgcv.clip_mask = s->img->mask;
2393 xgcv.clip_x_origin = x - s->slice.x;
2394 xgcv.clip_y_origin = y - s->slice.y;
2395 xgcv.function = GXcopy;
2396 XChangeGC (s->display, s->gc, mask, &xgcv);
2398 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
2399 s->slice.x, s->slice.y,
2400 s->slice.width, s->slice.height, x, y);
2401 XSetClipMask (s->display, s->gc, None);
2403 else
2405 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
2406 s->slice.x, s->slice.y,
2407 s->slice.width, s->slice.height, x, y);
2409 /* When the image has a mask, we can expect that at
2410 least part of a mouse highlight or a block cursor will
2411 be visible. If the image doesn't have a mask, make
2412 a block cursor visible by drawing a rectangle around
2413 the image. I believe it's looking better if we do
2414 nothing here for mouse-face. */
2415 if (s->hl == DRAW_CURSOR)
2417 int r = s->img->relief;
2418 if (r < 0) r = -r;
2419 XDrawRectangle (s->display, s->window, s->gc, x - r, y - r,
2420 s->slice.width + r*2 - 1,
2421 s->slice.height + r*2 - 1);
2425 else
2426 /* Draw a rectangle if image could not be loaded. */
2427 XDrawRectangle (s->display, pixmap, s->gc, x, y,
2428 s->slice.width - 1, s->slice.height - 1);
2432 /* Draw part of the background of glyph string S. X, Y, W, and H
2433 give the rectangle to draw. */
2435 static void
2436 x_draw_glyph_string_bg_rect (struct glyph_string *s, int x, int y, int w, int h)
2438 if (s->stippled_p)
2440 /* Fill background with a stipple pattern. */
2441 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
2442 XFillRectangle (s->display, s->window, s->gc, x, y, w, h);
2443 XSetFillStyle (s->display, s->gc, FillSolid);
2445 else
2446 x_clear_glyph_string_rect (s, x, y, w, h);
2450 /* Draw image glyph string S.
2452 s->y
2453 s->x +-------------------------
2454 | s->face->box
2456 | +-------------------------
2457 | | s->img->margin
2459 | | +-------------------
2460 | | | the image
2464 static void
2465 x_draw_image_glyph_string (struct glyph_string *s)
2467 int box_line_hwidth = eabs (s->face->box_line_width);
2468 int box_line_vwidth = max (s->face->box_line_width, 0);
2469 int height;
2470 Pixmap pixmap = None;
2472 height = s->height;
2473 if (s->slice.y == 0)
2474 height -= box_line_vwidth;
2475 if (s->slice.y + s->slice.height >= s->img->height)
2476 height -= box_line_vwidth;
2478 /* Fill background with face under the image. Do it only if row is
2479 taller than image or if image has a clip mask to reduce
2480 flickering. */
2481 s->stippled_p = s->face->stipple != 0;
2482 if (height > s->slice.height
2483 || s->img->hmargin
2484 || s->img->vmargin
2485 || s->img->mask
2486 || s->img->pixmap == 0
2487 || s->width != s->background_width)
2489 if (s->img->mask)
2491 /* Create a pixmap as large as the glyph string. Fill it
2492 with the background color. Copy the image to it, using
2493 its mask. Copy the temporary pixmap to the display. */
2494 Screen *screen = FRAME_X_SCREEN (s->f);
2495 int depth = DefaultDepthOfScreen (screen);
2497 /* Create a pixmap as large as the glyph string. */
2498 pixmap = XCreatePixmap (s->display, s->window,
2499 s->background_width,
2500 s->height, depth);
2502 /* Don't clip in the following because we're working on the
2503 pixmap. */
2504 XSetClipMask (s->display, s->gc, None);
2506 /* Fill the pixmap with the background color/stipple. */
2507 if (s->stippled_p)
2509 /* Fill background with a stipple pattern. */
2510 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
2511 XSetTSOrigin (s->display, s->gc, - s->x, - s->y);
2512 XFillRectangle (s->display, pixmap, s->gc,
2513 0, 0, s->background_width, s->height);
2514 XSetFillStyle (s->display, s->gc, FillSolid);
2515 XSetTSOrigin (s->display, s->gc, 0, 0);
2517 else
2519 XGCValues xgcv;
2520 XGetGCValues (s->display, s->gc, GCForeground | GCBackground,
2521 &xgcv);
2522 XSetForeground (s->display, s->gc, xgcv.background);
2523 XFillRectangle (s->display, pixmap, s->gc,
2524 0, 0, s->background_width, s->height);
2525 XSetForeground (s->display, s->gc, xgcv.foreground);
2528 else
2530 int x = s->x;
2531 int y = s->y;
2533 if (s->first_glyph->left_box_line_p
2534 && s->slice.x == 0)
2535 x += box_line_hwidth;
2537 if (s->slice.y == 0)
2538 y += box_line_vwidth;
2540 x_draw_glyph_string_bg_rect (s, x, y, s->background_width, height);
2543 s->background_filled_p = 1;
2546 /* Draw the foreground. */
2547 if (pixmap != None)
2549 x_draw_image_foreground_1 (s, pixmap);
2550 x_set_glyph_string_clipping (s);
2551 XCopyArea (s->display, pixmap, s->window, s->gc,
2552 0, 0, s->background_width, s->height, s->x, s->y);
2553 XFreePixmap (s->display, pixmap);
2555 else
2556 x_draw_image_foreground (s);
2558 /* If we must draw a relief around the image, do it. */
2559 if (s->img->relief
2560 || s->hl == DRAW_IMAGE_RAISED
2561 || s->hl == DRAW_IMAGE_SUNKEN)
2562 x_draw_image_relief (s);
2566 /* Draw stretch glyph string S. */
2568 static void
2569 x_draw_stretch_glyph_string (struct glyph_string *s)
2571 xassert (s->first_glyph->type == STRETCH_GLYPH);
2573 if (s->hl == DRAW_CURSOR
2574 && !x_stretch_cursor_p)
2576 /* If `x-stretch-cursor' is nil, don't draw a block cursor as
2577 wide as the stretch glyph. */
2578 int width, background_width = s->background_width;
2579 int x = s->x;
2581 if (!s->row->reversed_p)
2583 int left_x = window_box_left_offset (s->w, TEXT_AREA);
2585 if (x < left_x)
2587 background_width -= left_x - x;
2588 x = left_x;
2591 else
2593 /* In R2L rows, draw the cursor on the right edge of the
2594 stretch glyph. */
2595 int right_x = window_box_right_offset (s->w, TEXT_AREA);
2597 if (x + background_width > right_x)
2598 background_width -= x - right_x;
2599 x += background_width;
2601 width = min (FRAME_COLUMN_WIDTH (s->f), background_width);
2602 if (s->row->reversed_p)
2603 x -= width;
2605 /* Draw cursor. */
2606 x_draw_glyph_string_bg_rect (s, x, s->y, width, s->height);
2608 /* Clear rest using the GC of the original non-cursor face. */
2609 if (width < background_width)
2611 int y = s->y;
2612 int w = background_width - width, h = s->height;
2613 XRectangle r;
2614 GC gc;
2616 if (!s->row->reversed_p)
2617 x += width;
2618 else
2619 x = s->x;
2620 if (s->row->mouse_face_p
2621 && cursor_in_mouse_face_p (s->w))
2623 x_set_mouse_face_gc (s);
2624 gc = s->gc;
2626 else
2627 gc = s->face->gc;
2629 get_glyph_string_clip_rect (s, &r);
2630 XSetClipRectangles (s->display, gc, 0, 0, &r, 1, Unsorted);
2632 if (s->face->stipple)
2634 /* Fill background with a stipple pattern. */
2635 XSetFillStyle (s->display, gc, FillOpaqueStippled);
2636 XFillRectangle (s->display, s->window, gc, x, y, w, h);
2637 XSetFillStyle (s->display, gc, FillSolid);
2639 else
2641 XGCValues xgcv;
2642 XGetGCValues (s->display, gc, GCForeground | GCBackground, &xgcv);
2643 XSetForeground (s->display, gc, xgcv.background);
2644 XFillRectangle (s->display, s->window, gc, x, y, w, h);
2645 XSetForeground (s->display, gc, xgcv.foreground);
2649 else if (!s->background_filled_p)
2651 int background_width = s->background_width;
2652 int x = s->x, left_x = window_box_left_offset (s->w, TEXT_AREA);
2654 /* Don't draw into left margin, fringe or scrollbar area
2655 except for header line and mode line. */
2656 if (x < left_x && !s->row->mode_line_p)
2658 background_width -= left_x - x;
2659 x = left_x;
2661 if (background_width > 0)
2662 x_draw_glyph_string_bg_rect (s, x, s->y, background_width, s->height);
2665 s->background_filled_p = 1;
2669 /* Draw glyph string S. */
2671 static void
2672 x_draw_glyph_string (struct glyph_string *s)
2674 int relief_drawn_p = 0;
2676 /* If S draws into the background of its successors, draw the
2677 background of the successors first so that S can draw into it.
2678 This makes S->next use XDrawString instead of XDrawImageString. */
2679 if (s->next && s->right_overhang && !s->for_overlaps)
2681 int width;
2682 struct glyph_string *next;
2684 for (width = 0, next = s->next;
2685 next && width < s->right_overhang;
2686 width += next->width, next = next->next)
2687 if (next->first_glyph->type != IMAGE_GLYPH)
2689 x_set_glyph_string_gc (next);
2690 x_set_glyph_string_clipping (next);
2691 if (next->first_glyph->type == STRETCH_GLYPH)
2692 x_draw_stretch_glyph_string (next);
2693 else
2694 x_draw_glyph_string_background (next, 1);
2695 next->num_clips = 0;
2699 /* Set up S->gc, set clipping and draw S. */
2700 x_set_glyph_string_gc (s);
2702 /* Draw relief (if any) in advance for char/composition so that the
2703 glyph string can be drawn over it. */
2704 if (!s->for_overlaps
2705 && s->face->box != FACE_NO_BOX
2706 && (s->first_glyph->type == CHAR_GLYPH
2707 || s->first_glyph->type == COMPOSITE_GLYPH))
2710 x_set_glyph_string_clipping (s);
2711 x_draw_glyph_string_background (s, 1);
2712 x_draw_glyph_string_box (s);
2713 x_set_glyph_string_clipping (s);
2714 relief_drawn_p = 1;
2716 else if (!s->clip_head /* draw_glyphs didn't specify a clip mask. */
2717 && !s->clip_tail
2718 && ((s->prev && s->prev->hl != s->hl && s->left_overhang)
2719 || (s->next && s->next->hl != s->hl && s->right_overhang)))
2720 /* We must clip just this glyph. left_overhang part has already
2721 drawn when s->prev was drawn, and right_overhang part will be
2722 drawn later when s->next is drawn. */
2723 x_set_glyph_string_clipping_exactly (s, s);
2724 else
2725 x_set_glyph_string_clipping (s);
2727 switch (s->first_glyph->type)
2729 case IMAGE_GLYPH:
2730 x_draw_image_glyph_string (s);
2731 break;
2733 case STRETCH_GLYPH:
2734 x_draw_stretch_glyph_string (s);
2735 break;
2737 case CHAR_GLYPH:
2738 if (s->for_overlaps)
2739 s->background_filled_p = 1;
2740 else
2741 x_draw_glyph_string_background (s, 0);
2742 x_draw_glyph_string_foreground (s);
2743 break;
2745 case COMPOSITE_GLYPH:
2746 if (s->for_overlaps || (s->cmp_from > 0
2747 && ! s->first_glyph->u.cmp.automatic))
2748 s->background_filled_p = 1;
2749 else
2750 x_draw_glyph_string_background (s, 1);
2751 x_draw_composite_glyph_string_foreground (s);
2752 break;
2754 case GLYPHLESS_GLYPH:
2755 if (s->for_overlaps)
2756 s->background_filled_p = 1;
2757 else
2758 x_draw_glyph_string_background (s, 1);
2759 x_draw_glyphless_glyph_string_foreground (s);
2760 break;
2762 default:
2763 abort ();
2766 if (!s->for_overlaps)
2768 /* Draw underline. */
2769 if (s->face->underline_p)
2771 unsigned long thickness, position;
2772 int y;
2774 if (s->prev && s->prev->face->underline_p)
2776 /* We use the same underline style as the previous one. */
2777 thickness = s->prev->underline_thickness;
2778 position = s->prev->underline_position;
2780 else
2782 /* Get the underline thickness. Default is 1 pixel. */
2783 if (s->font && s->font->underline_thickness > 0)
2784 thickness = s->font->underline_thickness;
2785 else
2786 thickness = 1;
2787 if (x_underline_at_descent_line)
2788 position = (s->height - thickness) - (s->ybase - s->y);
2789 else
2791 /* Get the underline position. This is the recommended
2792 vertical offset in pixels from the baseline to the top of
2793 the underline. This is a signed value according to the
2794 specs, and its default is
2796 ROUND ((maximum descent) / 2), with
2797 ROUND(x) = floor (x + 0.5) */
2799 if (x_use_underline_position_properties
2800 && s->font && s->font->underline_position >= 0)
2801 position = s->font->underline_position;
2802 else if (s->font)
2803 position = (s->font->descent + 1) / 2;
2804 else
2805 position = underline_minimum_offset;
2807 position = max (position, underline_minimum_offset);
2809 /* Check the sanity of thickness and position. We should
2810 avoid drawing underline out of the current line area. */
2811 if (s->y + s->height <= s->ybase + position)
2812 position = (s->height - 1) - (s->ybase - s->y);
2813 if (s->y + s->height < s->ybase + position + thickness)
2814 thickness = (s->y + s->height) - (s->ybase + position);
2815 s->underline_thickness = thickness;
2816 s->underline_position = position;
2817 y = s->ybase + position;
2818 if (s->face->underline_defaulted_p)
2819 XFillRectangle (s->display, s->window, s->gc,
2820 s->x, y, s->width, thickness);
2821 else
2823 XGCValues xgcv;
2824 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2825 XSetForeground (s->display, s->gc, s->face->underline_color);
2826 XFillRectangle (s->display, s->window, s->gc,
2827 s->x, y, s->width, thickness);
2828 XSetForeground (s->display, s->gc, xgcv.foreground);
2832 /* Draw overline. */
2833 if (s->face->overline_p)
2835 unsigned long dy = 0, h = 1;
2837 if (s->face->overline_color_defaulted_p)
2838 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2839 s->width, h);
2840 else
2842 XGCValues xgcv;
2843 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2844 XSetForeground (s->display, s->gc, s->face->overline_color);
2845 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2846 s->width, h);
2847 XSetForeground (s->display, s->gc, xgcv.foreground);
2851 /* Draw strike-through. */
2852 if (s->face->strike_through_p)
2854 unsigned long h = 1;
2855 unsigned long dy = (s->height - h) / 2;
2857 if (s->face->strike_through_color_defaulted_p)
2858 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2859 s->width, h);
2860 else
2862 XGCValues xgcv;
2863 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2864 XSetForeground (s->display, s->gc, s->face->strike_through_color);
2865 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2866 s->width, h);
2867 XSetForeground (s->display, s->gc, xgcv.foreground);
2871 /* Draw relief if not yet drawn. */
2872 if (!relief_drawn_p && s->face->box != FACE_NO_BOX)
2873 x_draw_glyph_string_box (s);
2875 if (s->prev)
2877 struct glyph_string *prev;
2879 for (prev = s->prev; prev; prev = prev->prev)
2880 if (prev->hl != s->hl
2881 && prev->x + prev->width + prev->right_overhang > s->x)
2883 /* As prev was drawn while clipped to its own area, we
2884 must draw the right_overhang part using s->hl now. */
2885 enum draw_glyphs_face save = prev->hl;
2887 prev->hl = s->hl;
2888 x_set_glyph_string_gc (prev);
2889 x_set_glyph_string_clipping_exactly (s, prev);
2890 if (prev->first_glyph->type == CHAR_GLYPH)
2891 x_draw_glyph_string_foreground (prev);
2892 else
2893 x_draw_composite_glyph_string_foreground (prev);
2894 XSetClipMask (prev->display, prev->gc, None);
2895 prev->hl = save;
2896 prev->num_clips = 0;
2900 if (s->next)
2902 struct glyph_string *next;
2904 for (next = s->next; next; next = next->next)
2905 if (next->hl != s->hl
2906 && next->x - next->left_overhang < s->x + s->width)
2908 /* As next will be drawn while clipped to its own area,
2909 we must draw the left_overhang part using s->hl now. */
2910 enum draw_glyphs_face save = next->hl;
2912 next->hl = s->hl;
2913 x_set_glyph_string_gc (next);
2914 x_set_glyph_string_clipping_exactly (s, next);
2915 if (next->first_glyph->type == CHAR_GLYPH)
2916 x_draw_glyph_string_foreground (next);
2917 else
2918 x_draw_composite_glyph_string_foreground (next);
2919 XSetClipMask (next->display, next->gc, None);
2920 next->hl = save;
2921 next->num_clips = 0;
2926 /* Reset clipping. */
2927 XSetClipMask (s->display, s->gc, None);
2928 s->num_clips = 0;
2931 /* Shift display to make room for inserted glyphs. */
2933 static void
2934 x_shift_glyphs_for_insert (struct frame *f, int x, int y, int width, int height, int shift_by)
2936 XCopyArea (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), FRAME_X_WINDOW (f),
2937 f->output_data.x->normal_gc,
2938 x, y, width, height,
2939 x + shift_by, y);
2942 /* Delete N glyphs at the nominal cursor position. Not implemented
2943 for X frames. */
2945 static void
2946 x_delete_glyphs (struct frame *f, register int n)
2948 abort ();
2952 /* Like XClearArea, but check that WIDTH and HEIGHT are reasonable.
2953 If they are <= 0, this is probably an error. */
2955 void
2956 x_clear_area (Display *dpy, Window window, int x, int y, int width, int height, int exposures)
2958 xassert (width > 0 && height > 0);
2959 XClearArea (dpy, window, x, y, width, height, exposures);
2963 /* Clear an entire frame. */
2965 static void
2966 x_clear_frame (struct frame *f)
2968 /* Clearing the frame will erase any cursor, so mark them all as no
2969 longer visible. */
2970 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2971 output_cursor.hpos = output_cursor.vpos = 0;
2972 output_cursor.x = -1;
2974 /* We don't set the output cursor here because there will always
2975 follow an explicit cursor_to. */
2976 BLOCK_INPUT;
2978 XClearWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
2980 /* We have to clear the scroll bars. If we have changed colors or
2981 something like that, then they should be notified. */
2982 x_scroll_bar_clear (f);
2984 #if defined (USE_GTK) && defined (USE_TOOLKIT_SCROLL_BARS)
2985 /* Make sure scroll bars are redrawn. As they aren't redrawn by
2986 redisplay, do it here. */
2987 if (FRAME_GTK_WIDGET (f))
2988 gtk_widget_queue_draw (FRAME_GTK_WIDGET (f));
2989 #endif
2991 XFlush (FRAME_X_DISPLAY (f));
2993 UNBLOCK_INPUT;
2998 /* Invert the middle quarter of the frame for .15 sec. */
3000 /* We use the select system call to do the waiting, so we have to make
3001 sure it's available. If it isn't, we just won't do visual bells. */
3003 #if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
3006 /* Subtract the `struct timeval' values X and Y, storing the result in
3007 *RESULT. Return 1 if the difference is negative, otherwise 0. */
3009 static int
3010 timeval_subtract (struct timeval *result, struct timeval x, struct timeval y)
3012 /* Perform the carry for the later subtraction by updating y. This
3013 is safer because on some systems the tv_sec member is unsigned. */
3014 if (x.tv_usec < y.tv_usec)
3016 int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
3017 y.tv_usec -= 1000000 * nsec;
3018 y.tv_sec += nsec;
3021 if (x.tv_usec - y.tv_usec > 1000000)
3023 int nsec = (y.tv_usec - x.tv_usec) / 1000000;
3024 y.tv_usec += 1000000 * nsec;
3025 y.tv_sec -= nsec;
3028 /* Compute the time remaining to wait. tv_usec is certainly
3029 positive. */
3030 result->tv_sec = x.tv_sec - y.tv_sec;
3031 result->tv_usec = x.tv_usec - y.tv_usec;
3033 /* Return indication of whether the result should be considered
3034 negative. */
3035 return x.tv_sec < y.tv_sec;
3038 static void
3039 XTflash (struct frame *f)
3041 BLOCK_INPUT;
3044 #ifdef USE_GTK
3045 /* Use Gdk routines to draw. This way, we won't draw over scroll bars
3046 when the scroll bars and the edit widget share the same X window. */
3047 GdkWindow *window = gtk_widget_get_window (FRAME_GTK_WIDGET (f));
3048 #ifdef HAVE_GTK3
3049 cairo_t *cr = gdk_cairo_create (window);
3050 cairo_set_source_rgb (cr, 1, 1, 1);
3051 cairo_set_operator (cr, CAIRO_OPERATOR_DIFFERENCE);
3052 #define XFillRectangle(d, win, gc, x, y, w, h) \
3053 do { \
3054 cairo_rectangle (cr, x, y, w, h); \
3055 cairo_fill (cr); \
3057 while (0)
3058 #else /* ! HAVE_GTK3 */
3059 GdkGCValues vals;
3060 GdkGC *gc;
3061 vals.foreground.pixel = (FRAME_FOREGROUND_PIXEL (f)
3062 ^ FRAME_BACKGROUND_PIXEL (f));
3063 vals.function = GDK_XOR;
3064 gc = gdk_gc_new_with_values (window,
3065 &vals, GDK_GC_FUNCTION | GDK_GC_FOREGROUND);
3066 #define XFillRectangle(d, win, gc, x, y, w, h) \
3067 gdk_draw_rectangle (window, gc, TRUE, x, y, w, h)
3068 #endif /* ! HAVE_GTK3 */
3069 #else /* ! USE_GTK */
3070 GC gc;
3072 /* Create a GC that will use the GXxor function to flip foreground
3073 pixels into background pixels. */
3075 XGCValues values;
3077 values.function = GXxor;
3078 values.foreground = (FRAME_FOREGROUND_PIXEL (f)
3079 ^ FRAME_BACKGROUND_PIXEL (f));
3081 gc = XCreateGC (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3082 GCFunction | GCForeground, &values);
3084 #endif
3086 /* Get the height not including a menu bar widget. */
3087 int height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, FRAME_LINES (f));
3088 /* Height of each line to flash. */
3089 int flash_height = FRAME_LINE_HEIGHT (f);
3090 /* These will be the left and right margins of the rectangles. */
3091 int flash_left = FRAME_INTERNAL_BORDER_WIDTH (f);
3092 int flash_right = FRAME_PIXEL_WIDTH (f) - FRAME_INTERNAL_BORDER_WIDTH (f);
3094 int width;
3096 /* Don't flash the area between a scroll bar and the frame
3097 edge it is next to. */
3098 switch (FRAME_VERTICAL_SCROLL_BAR_TYPE (f))
3100 case vertical_scroll_bar_left:
3101 flash_left += VERTICAL_SCROLL_BAR_WIDTH_TRIM;
3102 break;
3104 case vertical_scroll_bar_right:
3105 flash_right -= VERTICAL_SCROLL_BAR_WIDTH_TRIM;
3106 break;
3108 default:
3109 break;
3112 width = flash_right - flash_left;
3114 /* If window is tall, flash top and bottom line. */
3115 if (height > 3 * FRAME_LINE_HEIGHT (f))
3117 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3118 flash_left,
3119 (FRAME_INTERNAL_BORDER_WIDTH (f)
3120 + FRAME_TOP_MARGIN_HEIGHT (f)),
3121 width, flash_height);
3122 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3123 flash_left,
3124 (height - flash_height
3125 - FRAME_INTERNAL_BORDER_WIDTH (f)),
3126 width, flash_height);
3129 else
3130 /* If it is short, flash it all. */
3131 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3132 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
3133 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
3135 x_flush (f);
3138 struct timeval wakeup;
3140 EMACS_GET_TIME (wakeup);
3142 /* Compute time to wait until, propagating carry from usecs. */
3143 wakeup.tv_usec += 150000;
3144 wakeup.tv_sec += (wakeup.tv_usec / 1000000);
3145 wakeup.tv_usec %= 1000000;
3147 /* Keep waiting until past the time wakeup or any input gets
3148 available. */
3149 while (! detect_input_pending ())
3151 struct timeval current;
3152 struct timeval timeout;
3154 EMACS_GET_TIME (current);
3156 /* Break if result would be negative. */
3157 if (timeval_subtract (&current, wakeup, current))
3158 break;
3160 /* How long `select' should wait. */
3161 timeout.tv_sec = 0;
3162 timeout.tv_usec = 10000;
3164 /* Try to wait that long--but we might wake up sooner. */
3165 select (0, NULL, NULL, NULL, &timeout);
3169 /* If window is tall, flash top and bottom line. */
3170 if (height > 3 * FRAME_LINE_HEIGHT (f))
3172 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3173 flash_left,
3174 (FRAME_INTERNAL_BORDER_WIDTH (f)
3175 + FRAME_TOP_MARGIN_HEIGHT (f)),
3176 width, flash_height);
3177 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3178 flash_left,
3179 (height - flash_height
3180 - FRAME_INTERNAL_BORDER_WIDTH (f)),
3181 width, flash_height);
3183 else
3184 /* If it is short, flash it all. */
3185 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3186 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
3187 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
3189 #ifdef USE_GTK
3190 #ifdef HAVE_GTK3
3191 cairo_destroy (cr);
3192 #else
3193 g_object_unref (G_OBJECT (gc));
3194 #endif
3195 #undef XFillRectangle
3196 #else
3197 XFreeGC (FRAME_X_DISPLAY (f), gc);
3198 #endif
3199 x_flush (f);
3203 UNBLOCK_INPUT;
3206 #endif /* defined (HAVE_TIMEVAL) && defined (HAVE_SELECT) */
3209 static void
3210 XTtoggle_invisible_pointer (FRAME_PTR f, int invisible)
3212 BLOCK_INPUT;
3213 if (invisible)
3215 if (FRAME_X_DISPLAY_INFO (f)->invisible_cursor != 0)
3216 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3217 FRAME_X_DISPLAY_INFO (f)->invisible_cursor);
3219 else
3220 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3221 f->output_data.x->current_cursor);
3222 f->pointer_invisible = invisible;
3223 UNBLOCK_INPUT;
3227 /* Make audible bell. */
3229 static void
3230 XTring_bell (struct frame *f)
3232 if (FRAME_X_DISPLAY (f))
3234 #if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
3235 if (visible_bell)
3236 XTflash (f);
3237 else
3238 #endif
3240 BLOCK_INPUT;
3241 XBell (FRAME_X_DISPLAY (f), 0);
3242 XFlush (FRAME_X_DISPLAY (f));
3243 UNBLOCK_INPUT;
3249 /* Specify how many text lines, from the top of the window,
3250 should be affected by insert-lines and delete-lines operations.
3251 This, and those operations, are used only within an update
3252 that is bounded by calls to x_update_begin and x_update_end. */
3254 static void
3255 XTset_terminal_window (struct frame *f, int n)
3257 /* This function intentionally left blank. */
3262 /***********************************************************************
3263 Line Dance
3264 ***********************************************************************/
3266 /* Perform an insert-lines or delete-lines operation, inserting N
3267 lines or deleting -N lines at vertical position VPOS. */
3269 static void
3270 x_ins_del_lines (struct frame *f, int vpos, int n)
3272 abort ();
3276 /* Scroll part of the display as described by RUN. */
3278 static void
3279 x_scroll_run (struct window *w, struct run *run)
3281 struct frame *f = XFRAME (w->frame);
3282 int x, y, width, height, from_y, to_y, bottom_y;
3284 /* Get frame-relative bounding box of the text display area of W,
3285 without mode lines. Include in this box the left and right
3286 fringe of W. */
3287 window_box (w, -1, &x, &y, &width, &height);
3289 #ifdef USE_TOOLKIT_SCROLL_BARS
3290 /* If the fringe is adjacent to the left (right) scroll bar of a
3291 leftmost (rightmost, respectively) window, then extend its
3292 background to the gap between the fringe and the bar. */
3293 if ((WINDOW_LEFTMOST_P (w)
3294 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
3295 || (WINDOW_RIGHTMOST_P (w)
3296 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w)))
3298 int sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
3300 if (sb_width > 0)
3302 int bar_area_x = WINDOW_SCROLL_BAR_AREA_X (w);
3303 int bar_area_width = (WINDOW_CONFIG_SCROLL_BAR_COLS (w)
3304 * FRAME_COLUMN_WIDTH (f));
3306 if (bar_area_x + bar_area_width == x)
3308 x = bar_area_x + sb_width;
3309 width += bar_area_width - sb_width;
3311 else if (x + width == bar_area_x)
3312 width += bar_area_width - sb_width;
3315 #endif
3317 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
3318 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
3319 bottom_y = y + height;
3321 if (to_y < from_y)
3323 /* Scrolling up. Make sure we don't copy part of the mode
3324 line at the bottom. */
3325 if (from_y + run->height > bottom_y)
3326 height = bottom_y - from_y;
3327 else
3328 height = run->height;
3330 else
3332 /* Scrolling down. Make sure we don't copy over the mode line.
3333 at the bottom. */
3334 if (to_y + run->height > bottom_y)
3335 height = bottom_y - to_y;
3336 else
3337 height = run->height;
3340 BLOCK_INPUT;
3342 /* Cursor off. Will be switched on again in x_update_window_end. */
3343 updated_window = w;
3344 x_clear_cursor (w);
3346 XCopyArea (FRAME_X_DISPLAY (f),
3347 FRAME_X_WINDOW (f), FRAME_X_WINDOW (f),
3348 f->output_data.x->normal_gc,
3349 x, from_y,
3350 width, height,
3351 x, to_y);
3353 UNBLOCK_INPUT;
3358 /***********************************************************************
3359 Exposure Events
3360 ***********************************************************************/
3363 static void
3364 frame_highlight (struct frame *f)
3366 /* We used to only do this if Vx_no_window_manager was non-nil, but
3367 the ICCCM (section 4.1.6) says that the window's border pixmap
3368 and border pixel are window attributes which are "private to the
3369 client", so we can always change it to whatever we want. */
3370 BLOCK_INPUT;
3371 /* I recently started to get errors in this XSetWindowBorder, depending on
3372 the window-manager in use, tho something more is at play since I've been
3373 using that same window-manager binary for ever. Let's not crash just
3374 because of this (bug#9310). */
3375 x_catch_errors (FRAME_X_DISPLAY (f));
3376 XSetWindowBorder (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3377 f->output_data.x->border_pixel);
3378 x_uncatch_errors ();
3379 UNBLOCK_INPUT;
3380 x_update_cursor (f, 1);
3381 x_set_frame_alpha (f);
3384 static void
3385 frame_unhighlight (struct frame *f)
3387 /* We used to only do this if Vx_no_window_manager was non-nil, but
3388 the ICCCM (section 4.1.6) says that the window's border pixmap
3389 and border pixel are window attributes which are "private to the
3390 client", so we can always change it to whatever we want. */
3391 BLOCK_INPUT;
3392 /* Same as above for XSetWindowBorder (bug#9310). */
3393 x_catch_errors (FRAME_X_DISPLAY (f));
3394 XSetWindowBorderPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3395 f->output_data.x->border_tile);
3396 x_uncatch_errors ();
3397 UNBLOCK_INPUT;
3398 x_update_cursor (f, 1);
3399 x_set_frame_alpha (f);
3402 /* The focus has changed. Update the frames as necessary to reflect
3403 the new situation. Note that we can't change the selected frame
3404 here, because the Lisp code we are interrupting might become confused.
3405 Each event gets marked with the frame in which it occurred, so the
3406 Lisp code can tell when the switch took place by examining the events. */
3408 static void
3409 x_new_focus_frame (struct x_display_info *dpyinfo, struct frame *frame)
3411 struct frame *old_focus = dpyinfo->x_focus_frame;
3413 if (frame != dpyinfo->x_focus_frame)
3415 /* Set this before calling other routines, so that they see
3416 the correct value of x_focus_frame. */
3417 dpyinfo->x_focus_frame = frame;
3419 if (old_focus && old_focus->auto_lower)
3420 x_lower_frame (old_focus);
3422 if (dpyinfo->x_focus_frame && dpyinfo->x_focus_frame->auto_raise)
3423 pending_autoraise_frame = dpyinfo->x_focus_frame;
3424 else
3425 pending_autoraise_frame = 0;
3428 x_frame_rehighlight (dpyinfo);
3431 /* Handle FocusIn and FocusOut state changes for FRAME.
3432 If FRAME has focus and there exists more than one frame, puts
3433 a FOCUS_IN_EVENT into *BUFP. */
3435 static void
3436 x_focus_changed (int type, int state, struct x_display_info *dpyinfo, struct frame *frame, struct input_event *bufp)
3438 if (type == FocusIn)
3440 if (dpyinfo->x_focus_event_frame != frame)
3442 x_new_focus_frame (dpyinfo, frame);
3443 dpyinfo->x_focus_event_frame = frame;
3445 /* Don't stop displaying the initial startup message
3446 for a switch-frame event we don't need. */
3447 if (NILP (Vterminal_frame)
3448 && CONSP (Vframe_list)
3449 && !NILP (XCDR (Vframe_list)))
3451 bufp->kind = FOCUS_IN_EVENT;
3452 XSETFRAME (bufp->frame_or_window, frame);
3456 frame->output_data.x->focus_state |= state;
3458 #ifdef HAVE_X_I18N
3459 if (FRAME_XIC (frame))
3460 XSetICFocus (FRAME_XIC (frame));
3461 #endif
3463 else if (type == FocusOut)
3465 frame->output_data.x->focus_state &= ~state;
3467 if (dpyinfo->x_focus_event_frame == frame)
3469 dpyinfo->x_focus_event_frame = 0;
3470 x_new_focus_frame (dpyinfo, 0);
3473 #ifdef HAVE_X_I18N
3474 if (FRAME_XIC (frame))
3475 XUnsetICFocus (FRAME_XIC (frame));
3476 #endif
3477 if (frame->pointer_invisible)
3478 XTtoggle_invisible_pointer (frame, 0);
3482 /* The focus may have changed. Figure out if it is a real focus change,
3483 by checking both FocusIn/Out and Enter/LeaveNotify events.
3485 Returns FOCUS_IN_EVENT event in *BUFP. */
3487 static void
3488 x_detect_focus_change (struct x_display_info *dpyinfo, XEvent *event, struct input_event *bufp)
3490 struct frame *frame;
3492 frame = x_any_window_to_frame (dpyinfo, event->xany.window);
3493 if (! frame)
3494 return;
3496 switch (event->type)
3498 case EnterNotify:
3499 case LeaveNotify:
3501 struct frame *focus_frame = dpyinfo->x_focus_event_frame;
3502 int focus_state
3503 = focus_frame ? focus_frame->output_data.x->focus_state : 0;
3505 if (event->xcrossing.detail != NotifyInferior
3506 && event->xcrossing.focus
3507 && ! (focus_state & FOCUS_EXPLICIT))
3508 x_focus_changed ((event->type == EnterNotify ? FocusIn : FocusOut),
3509 FOCUS_IMPLICIT,
3510 dpyinfo, frame, bufp);
3512 break;
3514 case FocusIn:
3515 case FocusOut:
3516 x_focus_changed (event->type,
3517 (event->xfocus.detail == NotifyPointer ?
3518 FOCUS_IMPLICIT : FOCUS_EXPLICIT),
3519 dpyinfo, frame, bufp);
3520 break;
3522 case ClientMessage:
3523 if (event->xclient.message_type == dpyinfo->Xatom_XEMBED)
3525 enum xembed_message msg = event->xclient.data.l[1];
3526 x_focus_changed ((msg == XEMBED_FOCUS_IN ? FocusIn : FocusOut),
3527 FOCUS_EXPLICIT, dpyinfo, frame, bufp);
3529 break;
3534 #if defined HAVE_MENUS && !defined USE_X_TOOLKIT && !defined USE_GTK
3535 /* Handle an event saying the mouse has moved out of an Emacs frame. */
3537 void
3538 x_mouse_leave (struct x_display_info *dpyinfo)
3540 x_new_focus_frame (dpyinfo, dpyinfo->x_focus_event_frame);
3542 #endif
3544 /* The focus has changed, or we have redirected a frame's focus to
3545 another frame (this happens when a frame uses a surrogate
3546 mini-buffer frame). Shift the highlight as appropriate.
3548 The FRAME argument doesn't necessarily have anything to do with which
3549 frame is being highlighted or un-highlighted; we only use it to find
3550 the appropriate X display info. */
3552 static void
3553 XTframe_rehighlight (struct frame *frame)
3555 x_frame_rehighlight (FRAME_X_DISPLAY_INFO (frame));
3558 static void
3559 x_frame_rehighlight (struct x_display_info *dpyinfo)
3561 struct frame *old_highlight = dpyinfo->x_highlight_frame;
3563 if (dpyinfo->x_focus_frame)
3565 dpyinfo->x_highlight_frame
3566 = ((FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame)))
3567 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
3568 : dpyinfo->x_focus_frame);
3569 if (! FRAME_LIVE_P (dpyinfo->x_highlight_frame))
3571 FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
3572 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
3575 else
3576 dpyinfo->x_highlight_frame = 0;
3578 if (dpyinfo->x_highlight_frame != old_highlight)
3580 if (old_highlight)
3581 frame_unhighlight (old_highlight);
3582 if (dpyinfo->x_highlight_frame)
3583 frame_highlight (dpyinfo->x_highlight_frame);
3589 /* Keyboard processing - modifier keys, vendor-specific keysyms, etc. */
3591 /* Initialize mode_switch_bit and modifier_meaning. */
3592 static void
3593 x_find_modifier_meanings (struct x_display_info *dpyinfo)
3595 int min_code, max_code;
3596 KeySym *syms;
3597 int syms_per_code;
3598 XModifierKeymap *mods;
3600 dpyinfo->meta_mod_mask = 0;
3601 dpyinfo->shift_lock_mask = 0;
3602 dpyinfo->alt_mod_mask = 0;
3603 dpyinfo->super_mod_mask = 0;
3604 dpyinfo->hyper_mod_mask = 0;
3606 XDisplayKeycodes (dpyinfo->display, &min_code, &max_code);
3608 syms = XGetKeyboardMapping (dpyinfo->display,
3609 min_code, max_code - min_code + 1,
3610 &syms_per_code);
3611 mods = XGetModifierMapping (dpyinfo->display);
3613 /* Scan the modifier table to see which modifier bits the Meta and
3614 Alt keysyms are on. */
3616 int row, col; /* The row and column in the modifier table. */
3617 int found_alt_or_meta;
3619 for (row = 3; row < 8; row++)
3621 found_alt_or_meta = 0;
3622 for (col = 0; col < mods->max_keypermod; col++)
3624 KeyCode code = mods->modifiermap[(row * mods->max_keypermod) + col];
3626 /* Zeroes are used for filler. Skip them. */
3627 if (code == 0)
3628 continue;
3630 /* Are any of this keycode's keysyms a meta key? */
3632 int code_col;
3634 for (code_col = 0; code_col < syms_per_code; code_col++)
3636 int sym = syms[((code - min_code) * syms_per_code) + code_col];
3638 switch (sym)
3640 case XK_Meta_L:
3641 case XK_Meta_R:
3642 found_alt_or_meta = 1;
3643 dpyinfo->meta_mod_mask |= (1 << row);
3644 break;
3646 case XK_Alt_L:
3647 case XK_Alt_R:
3648 found_alt_or_meta = 1;
3649 dpyinfo->alt_mod_mask |= (1 << row);
3650 break;
3652 case XK_Hyper_L:
3653 case XK_Hyper_R:
3654 if (!found_alt_or_meta)
3655 dpyinfo->hyper_mod_mask |= (1 << row);
3656 code_col = syms_per_code;
3657 col = mods->max_keypermod;
3658 break;
3660 case XK_Super_L:
3661 case XK_Super_R:
3662 if (!found_alt_or_meta)
3663 dpyinfo->super_mod_mask |= (1 << row);
3664 code_col = syms_per_code;
3665 col = mods->max_keypermod;
3666 break;
3668 case XK_Shift_Lock:
3669 /* Ignore this if it's not on the lock modifier. */
3670 if (!found_alt_or_meta && ((1 << row) == LockMask))
3671 dpyinfo->shift_lock_mask = LockMask;
3672 code_col = syms_per_code;
3673 col = mods->max_keypermod;
3674 break;
3682 /* If we couldn't find any meta keys, accept any alt keys as meta keys. */
3683 if (! dpyinfo->meta_mod_mask)
3685 dpyinfo->meta_mod_mask = dpyinfo->alt_mod_mask;
3686 dpyinfo->alt_mod_mask = 0;
3689 /* If some keys are both alt and meta,
3690 make them just meta, not alt. */
3691 if (dpyinfo->alt_mod_mask & dpyinfo->meta_mod_mask)
3693 dpyinfo->alt_mod_mask &= ~dpyinfo->meta_mod_mask;
3696 XFree ((char *) syms);
3697 XFreeModifiermap (mods);
3700 /* Convert between the modifier bits X uses and the modifier bits
3701 Emacs uses. */
3703 EMACS_INT
3704 x_x_to_emacs_modifiers (struct x_display_info *dpyinfo, int state)
3706 EMACS_INT mod_meta = meta_modifier;
3707 EMACS_INT mod_alt = alt_modifier;
3708 EMACS_INT mod_hyper = hyper_modifier;
3709 EMACS_INT mod_super = super_modifier;
3710 Lisp_Object tem;
3712 tem = Fget (Vx_alt_keysym, Qmodifier_value);
3713 if (INTEGERP (tem)) mod_alt = XINT (tem);
3714 tem = Fget (Vx_meta_keysym, Qmodifier_value);
3715 if (INTEGERP (tem)) mod_meta = XINT (tem);
3716 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
3717 if (INTEGERP (tem)) mod_hyper = XINT (tem);
3718 tem = Fget (Vx_super_keysym, Qmodifier_value);
3719 if (INTEGERP (tem)) mod_super = XINT (tem);
3722 return ( ((state & (ShiftMask | dpyinfo->shift_lock_mask)) ? shift_modifier : 0)
3723 | ((state & ControlMask) ? ctrl_modifier : 0)
3724 | ((state & dpyinfo->meta_mod_mask) ? mod_meta : 0)
3725 | ((state & dpyinfo->alt_mod_mask) ? mod_alt : 0)
3726 | ((state & dpyinfo->super_mod_mask) ? mod_super : 0)
3727 | ((state & dpyinfo->hyper_mod_mask) ? mod_hyper : 0));
3730 static int
3731 x_emacs_to_x_modifiers (struct x_display_info *dpyinfo, EMACS_INT state)
3733 int mod_meta = meta_modifier;
3734 int mod_alt = alt_modifier;
3735 int mod_hyper = hyper_modifier;
3736 int mod_super = super_modifier;
3738 Lisp_Object tem;
3740 tem = Fget (Vx_alt_keysym, Qmodifier_value);
3741 if (INTEGERP (tem)) mod_alt = XINT (tem);
3742 tem = Fget (Vx_meta_keysym, Qmodifier_value);
3743 if (INTEGERP (tem)) mod_meta = XINT (tem);
3744 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
3745 if (INTEGERP (tem)) mod_hyper = XINT (tem);
3746 tem = Fget (Vx_super_keysym, Qmodifier_value);
3747 if (INTEGERP (tem)) mod_super = XINT (tem);
3750 return ( ((state & mod_alt) ? dpyinfo->alt_mod_mask : 0)
3751 | ((state & mod_super) ? dpyinfo->super_mod_mask : 0)
3752 | ((state & mod_hyper) ? dpyinfo->hyper_mod_mask : 0)
3753 | ((state & shift_modifier) ? ShiftMask : 0)
3754 | ((state & ctrl_modifier) ? ControlMask : 0)
3755 | ((state & mod_meta) ? dpyinfo->meta_mod_mask : 0));
3758 /* Convert a keysym to its name. */
3760 char *
3761 x_get_keysym_name (int keysym)
3763 char *value;
3765 BLOCK_INPUT;
3766 value = XKeysymToString (keysym);
3767 UNBLOCK_INPUT;
3769 return value;
3774 /* Mouse clicks and mouse movement. Rah. */
3776 /* Prepare a mouse-event in *RESULT for placement in the input queue.
3778 If the event is a button press, then note that we have grabbed
3779 the mouse. */
3781 static Lisp_Object
3782 construct_mouse_click (struct input_event *result, XButtonEvent *event, struct frame *f)
3784 /* Make the event type NO_EVENT; we'll change that when we decide
3785 otherwise. */
3786 result->kind = MOUSE_CLICK_EVENT;
3787 result->code = event->button - Button1;
3788 result->timestamp = event->time;
3789 result->modifiers = (x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO (f),
3790 event->state)
3791 | (event->type == ButtonRelease
3792 ? up_modifier
3793 : down_modifier));
3795 XSETINT (result->x, event->x);
3796 XSETINT (result->y, event->y);
3797 XSETFRAME (result->frame_or_window, f);
3798 result->arg = Qnil;
3799 return Qnil;
3803 /* Function to report a mouse movement to the mainstream Emacs code.
3804 The input handler calls this.
3806 We have received a mouse movement event, which is given in *event.
3807 If the mouse is over a different glyph than it was last time, tell
3808 the mainstream emacs code by setting mouse_moved. If not, ask for
3809 another motion event, so we can check again the next time it moves. */
3811 static XMotionEvent last_mouse_motion_event;
3812 static Lisp_Object last_mouse_motion_frame;
3814 static int
3815 note_mouse_movement (FRAME_PTR frame, XMotionEvent *event)
3817 last_mouse_movement_time = event->time;
3818 last_mouse_motion_event = *event;
3819 XSETFRAME (last_mouse_motion_frame, frame);
3821 if (!FRAME_X_OUTPUT (frame))
3822 return 0;
3824 if (event->window != FRAME_X_WINDOW (frame))
3826 frame->mouse_moved = 1;
3827 last_mouse_scroll_bar = Qnil;
3828 note_mouse_highlight (frame, -1, -1);
3829 last_mouse_glyph_frame = 0;
3830 return 1;
3834 /* Has the mouse moved off the glyph it was on at the last sighting? */
3835 if (frame != last_mouse_glyph_frame
3836 || event->x < last_mouse_glyph.x
3837 || event->x >= last_mouse_glyph.x + last_mouse_glyph.width
3838 || event->y < last_mouse_glyph.y
3839 || event->y >= last_mouse_glyph.y + last_mouse_glyph.height)
3841 frame->mouse_moved = 1;
3842 last_mouse_scroll_bar = Qnil;
3843 note_mouse_highlight (frame, event->x, event->y);
3844 /* Remember which glyph we're now on. */
3845 remember_mouse_glyph (frame, event->x, event->y, &last_mouse_glyph);
3846 last_mouse_glyph_frame = frame;
3847 return 1;
3850 return 0;
3854 /************************************************************************
3855 Mouse Face
3856 ************************************************************************/
3858 static void
3859 redo_mouse_highlight (void)
3861 if (!NILP (last_mouse_motion_frame)
3862 && FRAME_LIVE_P (XFRAME (last_mouse_motion_frame)))
3863 note_mouse_highlight (XFRAME (last_mouse_motion_frame),
3864 last_mouse_motion_event.x,
3865 last_mouse_motion_event.y);
3870 /* Return the current position of the mouse.
3871 *FP should be a frame which indicates which display to ask about.
3873 If the mouse movement started in a scroll bar, set *FP, *BAR_WINDOW,
3874 and *PART to the frame, window, and scroll bar part that the mouse
3875 is over. Set *X and *Y to the portion and whole of the mouse's
3876 position on the scroll bar.
3878 If the mouse movement started elsewhere, set *FP to the frame the
3879 mouse is on, *BAR_WINDOW to nil, and *X and *Y to the character cell
3880 the mouse is over.
3882 Set *TIMESTAMP to the server time-stamp for the time at which the mouse
3883 was at this position.
3885 Don't store anything if we don't have a valid set of values to report.
3887 This clears the mouse_moved flag, so we can wait for the next mouse
3888 movement. */
3890 static void
3891 XTmouse_position (FRAME_PTR *fp, int insist, Lisp_Object *bar_window,
3892 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
3893 Time *timestamp)
3895 FRAME_PTR f1;
3897 BLOCK_INPUT;
3899 if (! NILP (last_mouse_scroll_bar) && insist == 0)
3900 x_scroll_bar_report_motion (fp, bar_window, part, x, y, timestamp);
3901 else
3903 Window root;
3904 int root_x, root_y;
3906 Window dummy_window;
3907 int dummy;
3909 Lisp_Object frame, tail;
3911 /* Clear the mouse-moved flag for every frame on this display. */
3912 FOR_EACH_FRAME (tail, frame)
3913 if (FRAME_X_P (XFRAME (frame))
3914 && FRAME_X_DISPLAY (XFRAME (frame)) == FRAME_X_DISPLAY (*fp))
3915 XFRAME (frame)->mouse_moved = 0;
3917 last_mouse_scroll_bar = Qnil;
3919 /* Figure out which root window we're on. */
3920 XQueryPointer (FRAME_X_DISPLAY (*fp),
3921 DefaultRootWindow (FRAME_X_DISPLAY (*fp)),
3923 /* The root window which contains the pointer. */
3924 &root,
3926 /* Trash which we can't trust if the pointer is on
3927 a different screen. */
3928 &dummy_window,
3930 /* The position on that root window. */
3931 &root_x, &root_y,
3933 /* More trash we can't trust. */
3934 &dummy, &dummy,
3936 /* Modifier keys and pointer buttons, about which
3937 we don't care. */
3938 (unsigned int *) &dummy);
3940 /* Now we have a position on the root; find the innermost window
3941 containing the pointer. */
3943 Window win, child;
3944 int win_x, win_y;
3945 int parent_x = 0, parent_y = 0;
3947 win = root;
3949 /* XTranslateCoordinates can get errors if the window
3950 structure is changing at the same time this function
3951 is running. So at least we must not crash from them. */
3953 x_catch_errors (FRAME_X_DISPLAY (*fp));
3955 if (FRAME_X_DISPLAY_INFO (*fp)->grabbed && last_mouse_frame
3956 && FRAME_LIVE_P (last_mouse_frame))
3958 /* If mouse was grabbed on a frame, give coords for that frame
3959 even if the mouse is now outside it. */
3960 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
3962 /* From-window, to-window. */
3963 root, FRAME_X_WINDOW (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 = 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 (FRAME_X_DISPLAY_INFO (*fp), 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 (FRAME_X_DISPLAY_INFO (*fp), win);
4017 #else
4018 /* Is win one of our frames? */
4019 f1 = x_any_window_to_frame (FRAME_X_DISPLAY_INFO (*fp), 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 remember_mouse_glyph (f1, win_x, win_y, &last_mouse_glyph);
4066 last_mouse_glyph_frame = f1;
4068 *bar_window = Qnil;
4069 *part = 0;
4070 *fp = f1;
4071 XSETINT (*x, win_x);
4072 XSETINT (*y, win_y);
4073 *timestamp = last_mouse_movement_time;
4078 UNBLOCK_INPUT;
4083 /***********************************************************************
4084 Scroll bars
4085 ***********************************************************************/
4087 /* Scroll bar support. */
4089 /* Given an X window ID and a DISPLAY, find the struct scroll_bar which
4090 manages it.
4091 This can be called in GC, so we have to make sure to strip off mark
4092 bits. */
4094 static struct scroll_bar *
4095 x_window_to_scroll_bar (Display *display, Window window_id)
4097 Lisp_Object tail;
4099 #if defined (USE_GTK) && defined (USE_TOOLKIT_SCROLL_BARS)
4100 window_id = (Window) xg_get_scroll_id_for_window (display, window_id);
4101 #endif /* USE_GTK && USE_TOOLKIT_SCROLL_BARS */
4103 for (tail = Vframe_list; CONSP (tail); tail = XCDR (tail))
4105 Lisp_Object frame, bar, condemned;
4107 frame = XCAR (tail);
4108 /* All elements of Vframe_list should be frames. */
4109 if (! FRAMEP (frame))
4110 abort ();
4112 if (! FRAME_X_P (XFRAME (frame)))
4113 continue;
4115 /* Scan this frame's scroll bar list for a scroll bar with the
4116 right window ID. */
4117 condemned = FRAME_CONDEMNED_SCROLL_BARS (XFRAME (frame));
4118 for (bar = FRAME_SCROLL_BARS (XFRAME (frame));
4119 /* This trick allows us to search both the ordinary and
4120 condemned scroll bar lists with one loop. */
4121 ! NILP (bar) || (bar = condemned,
4122 condemned = Qnil,
4123 ! NILP (bar));
4124 bar = XSCROLL_BAR (bar)->next)
4125 if (XSCROLL_BAR (bar)->x_window == window_id &&
4126 FRAME_X_DISPLAY (XFRAME (frame)) == display)
4127 return XSCROLL_BAR (bar);
4130 return NULL;
4134 #if defined USE_LUCID
4136 /* Return the Lucid menu bar WINDOW is part of. Return null
4137 if WINDOW is not part of a menu bar. */
4139 static Widget
4140 x_window_to_menu_bar (Window window)
4142 Lisp_Object tail;
4144 for (tail = Vframe_list; CONSP (tail); tail = XCDR (tail))
4146 if (FRAME_X_P (XFRAME (XCAR (tail))))
4148 Lisp_Object frame = XCAR (tail);
4149 Widget menu_bar = XFRAME (frame)->output_data.x->menubar_widget;
4151 if (menu_bar && xlwmenu_window_p (menu_bar, window))
4152 return menu_bar;
4156 return NULL;
4159 #endif /* USE_LUCID */
4162 /************************************************************************
4163 Toolkit scroll bars
4164 ************************************************************************/
4166 #ifdef USE_TOOLKIT_SCROLL_BARS
4168 static void x_scroll_bar_to_input_event (XEvent *, struct input_event *);
4169 static void x_send_scroll_bar_event (Lisp_Object, int, int, int);
4170 static void x_create_toolkit_scroll_bar (struct frame *,
4171 struct scroll_bar *);
4172 static void x_set_toolkit_scroll_bar_thumb (struct scroll_bar *,
4173 int, int, int);
4176 /* Lisp window being scrolled. Set when starting to interact with
4177 a toolkit scroll bar, reset to nil when ending the interaction. */
4179 static Lisp_Object window_being_scrolled;
4181 /* Last scroll bar part sent in xm_scroll_callback. */
4183 static int last_scroll_bar_part;
4185 /* Whether this is an Xaw with arrow-scrollbars. This should imply
4186 that movements of 1/20 of the screen size are mapped to up/down. */
4188 #ifndef USE_GTK
4189 /* Id of action hook installed for scroll bars. */
4191 static XtActionHookId action_hook_id;
4193 static Boolean xaw3d_arrow_scroll;
4195 /* Whether the drag scrolling maintains the mouse at the top of the
4196 thumb. If not, resizing the thumb needs to be done more carefully
4197 to avoid jerkiness. */
4199 static Boolean xaw3d_pick_top;
4201 /* Action hook installed via XtAppAddActionHook when toolkit scroll
4202 bars are used.. The hook is responsible for detecting when
4203 the user ends an interaction with the scroll bar, and generates
4204 a `end-scroll' SCROLL_BAR_CLICK_EVENT' event if so. */
4206 static void
4207 xt_action_hook (Widget widget, XtPointer client_data, String action_name,
4208 XEvent *event, String *params, Cardinal *num_params)
4210 int scroll_bar_p;
4211 const char *end_action;
4213 #ifdef USE_MOTIF
4214 scroll_bar_p = XmIsScrollBar (widget);
4215 end_action = "Release";
4216 #else /* !USE_MOTIF i.e. use Xaw */
4217 scroll_bar_p = XtIsSubclass (widget, scrollbarWidgetClass);
4218 end_action = "EndScroll";
4219 #endif /* USE_MOTIF */
4221 if (scroll_bar_p
4222 && strcmp (action_name, end_action) == 0
4223 && WINDOWP (window_being_scrolled))
4225 struct window *w;
4227 x_send_scroll_bar_event (window_being_scrolled,
4228 scroll_bar_end_scroll, 0, 0);
4229 w = XWINDOW (window_being_scrolled);
4231 if (!NILP (XSCROLL_BAR (w->vertical_scroll_bar)->dragging))
4233 XSCROLL_BAR (w->vertical_scroll_bar)->dragging = Qnil;
4234 /* The thumb size is incorrect while dragging: fix it. */
4235 set_vertical_scroll_bar (w);
4237 window_being_scrolled = Qnil;
4238 last_scroll_bar_part = -1;
4240 /* Xt timeouts no longer needed. */
4241 toolkit_scroll_bar_interaction = 0;
4244 #endif /* not USE_GTK */
4246 /* A vector of windows used for communication between
4247 x_send_scroll_bar_event and x_scroll_bar_to_input_event. */
4249 static struct window **scroll_bar_windows;
4250 static ptrdiff_t scroll_bar_windows_size;
4253 /* Send a client message with message type Xatom_Scrollbar for a
4254 scroll action to the frame of WINDOW. PART is a value identifying
4255 the part of the scroll bar that was clicked on. PORTION is the
4256 amount to scroll of a whole of WHOLE. */
4258 static void
4259 x_send_scroll_bar_event (Lisp_Object window, int part, int portion, int whole)
4261 XEvent event;
4262 XClientMessageEvent *ev = (XClientMessageEvent *) &event;
4263 struct window *w = XWINDOW (window);
4264 struct frame *f = XFRAME (w->frame);
4265 ptrdiff_t i;
4267 BLOCK_INPUT;
4269 /* Construct a ClientMessage event to send to the frame. */
4270 ev->type = ClientMessage;
4271 ev->message_type = FRAME_X_DISPLAY_INFO (f)->Xatom_Scrollbar;
4272 ev->display = FRAME_X_DISPLAY (f);
4273 ev->window = FRAME_X_WINDOW (f);
4274 ev->format = 32;
4276 /* We can only transfer 32 bits in the XClientMessageEvent, which is
4277 not enough to store a pointer or Lisp_Object on a 64 bit system.
4278 So, store the window in scroll_bar_windows and pass the index
4279 into that array in the event. */
4280 for (i = 0; i < scroll_bar_windows_size; ++i)
4281 if (scroll_bar_windows[i] == NULL)
4282 break;
4284 if (i == scroll_bar_windows_size)
4286 ptrdiff_t old_nbytes =
4287 scroll_bar_windows_size * sizeof *scroll_bar_windows;
4288 ptrdiff_t nbytes;
4289 enum { XClientMessageEvent_MAX = 0x7fffffff };
4290 scroll_bar_windows =
4291 xpalloc (scroll_bar_windows, &scroll_bar_windows_size, 1,
4292 XClientMessageEvent_MAX, sizeof *scroll_bar_windows);
4293 nbytes = scroll_bar_windows_size * sizeof *scroll_bar_windows;
4294 memset (&scroll_bar_windows[i], 0, nbytes - old_nbytes);
4297 scroll_bar_windows[i] = w;
4298 ev->data.l[0] = (long) i;
4299 ev->data.l[1] = (long) part;
4300 ev->data.l[2] = (long) 0;
4301 ev->data.l[3] = (long) portion;
4302 ev->data.l[4] = (long) whole;
4304 /* Make Xt timeouts work while the scroll bar is active. */
4305 #ifdef USE_X_TOOLKIT
4306 toolkit_scroll_bar_interaction = 1;
4307 x_activate_timeout_atimer ();
4308 #endif
4310 /* Setting the event mask to zero means that the message will
4311 be sent to the client that created the window, and if that
4312 window no longer exists, no event will be sent. */
4313 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), False, 0, &event);
4314 UNBLOCK_INPUT;
4318 /* Transform a scroll bar ClientMessage EVENT to an Emacs input event
4319 in *IEVENT. */
4321 static void
4322 x_scroll_bar_to_input_event (XEvent *event, struct input_event *ievent)
4324 XClientMessageEvent *ev = (XClientMessageEvent *) event;
4325 Lisp_Object window;
4326 struct window *w;
4328 w = scroll_bar_windows[ev->data.l[0]];
4329 scroll_bar_windows[ev->data.l[0]] = NULL;
4331 XSETWINDOW (window, w);
4333 ievent->kind = SCROLL_BAR_CLICK_EVENT;
4334 ievent->frame_or_window = window;
4335 ievent->arg = Qnil;
4336 #ifdef USE_GTK
4337 ievent->timestamp = CurrentTime;
4338 #else
4339 ievent->timestamp =
4340 XtLastTimestampProcessed (FRAME_X_DISPLAY (XFRAME (w->frame)));
4341 #endif
4342 ievent->part = ev->data.l[1];
4343 ievent->code = ev->data.l[2];
4344 ievent->x = make_number ((int) ev->data.l[3]);
4345 ievent->y = make_number ((int) ev->data.l[4]);
4346 ievent->modifiers = 0;
4350 #ifdef USE_MOTIF
4352 /* Minimum and maximum values used for Motif scroll bars. */
4354 #define XM_SB_MAX 10000000
4357 /* Scroll bar callback for Motif scroll bars. WIDGET is the scroll
4358 bar widget. CLIENT_DATA is a pointer to the scroll_bar structure.
4359 CALL_DATA is a pointer to a XmScrollBarCallbackStruct. */
4361 static void
4362 xm_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
4364 struct scroll_bar *bar = (struct scroll_bar *) client_data;
4365 XmScrollBarCallbackStruct *cs = (XmScrollBarCallbackStruct *) call_data;
4366 int part = -1, whole = 0, portion = 0;
4368 switch (cs->reason)
4370 case XmCR_DECREMENT:
4371 bar->dragging = Qnil;
4372 part = scroll_bar_up_arrow;
4373 break;
4375 case XmCR_INCREMENT:
4376 bar->dragging = Qnil;
4377 part = scroll_bar_down_arrow;
4378 break;
4380 case XmCR_PAGE_DECREMENT:
4381 bar->dragging = Qnil;
4382 part = scroll_bar_above_handle;
4383 break;
4385 case XmCR_PAGE_INCREMENT:
4386 bar->dragging = Qnil;
4387 part = scroll_bar_below_handle;
4388 break;
4390 case XmCR_TO_TOP:
4391 bar->dragging = Qnil;
4392 part = scroll_bar_to_top;
4393 break;
4395 case XmCR_TO_BOTTOM:
4396 bar->dragging = Qnil;
4397 part = scroll_bar_to_bottom;
4398 break;
4400 case XmCR_DRAG:
4402 int slider_size;
4404 /* Get the slider size. */
4405 BLOCK_INPUT;
4406 XtVaGetValues (widget, XmNsliderSize, &slider_size, NULL);
4407 UNBLOCK_INPUT;
4409 whole = XM_SB_MAX - slider_size;
4410 portion = min (cs->value, whole);
4411 part = scroll_bar_handle;
4412 bar->dragging = make_number (cs->value);
4414 break;
4416 case XmCR_VALUE_CHANGED:
4417 break;
4420 if (part >= 0)
4422 window_being_scrolled = bar->window;
4423 last_scroll_bar_part = part;
4424 x_send_scroll_bar_event (bar->window, part, portion, whole);
4428 #elif defined USE_GTK
4430 /* Scroll bar callback for GTK scroll bars. WIDGET is the scroll
4431 bar widget. DATA is a pointer to the scroll_bar structure. */
4433 static gboolean
4434 xg_scroll_callback (GtkRange *range,
4435 GtkScrollType scroll,
4436 gdouble value,
4437 gpointer user_data)
4439 struct scroll_bar *bar = (struct scroll_bar *) user_data;
4440 gdouble position;
4441 int part = -1, whole = 0, portion = 0;
4442 GtkAdjustment *adj = GTK_ADJUSTMENT (gtk_range_get_adjustment (range));
4443 FRAME_PTR f = (FRAME_PTR) g_object_get_data (G_OBJECT (range), XG_FRAME_DATA);
4445 if (xg_ignore_gtk_scrollbar) return FALSE;
4446 position = gtk_adjustment_get_value (adj);
4449 switch (scroll)
4451 case GTK_SCROLL_JUMP:
4452 /* Buttons 1 2 or 3 must be grabbed. */
4453 if (FRAME_X_DISPLAY_INFO (f)->grabbed != 0
4454 && FRAME_X_DISPLAY_INFO (f)->grabbed < (1 << 4))
4456 part = scroll_bar_handle;
4457 whole = gtk_adjustment_get_upper (adj) -
4458 gtk_adjustment_get_page_size (adj);
4459 portion = min ((int)position, whole);
4460 bar->dragging = make_number ((int)portion);
4462 break;
4463 case GTK_SCROLL_STEP_BACKWARD:
4464 part = scroll_bar_up_arrow;
4465 bar->dragging = Qnil;
4466 break;
4467 case GTK_SCROLL_STEP_FORWARD:
4468 part = scroll_bar_down_arrow;
4469 bar->dragging = Qnil;
4470 break;
4471 case GTK_SCROLL_PAGE_BACKWARD:
4472 part = scroll_bar_above_handle;
4473 bar->dragging = Qnil;
4474 break;
4475 case GTK_SCROLL_PAGE_FORWARD:
4476 part = scroll_bar_below_handle;
4477 bar->dragging = Qnil;
4478 break;
4481 if (part >= 0)
4483 window_being_scrolled = bar->window;
4484 last_scroll_bar_part = part;
4485 x_send_scroll_bar_event (bar->window, part, portion, whole);
4488 return FALSE;
4491 /* Callback for button release. Sets dragging to Qnil when dragging is done. */
4493 static gboolean
4494 xg_end_scroll_callback (GtkWidget *widget,
4495 GdkEventButton *event,
4496 gpointer user_data)
4498 struct scroll_bar *bar = (struct scroll_bar *) user_data;
4499 bar->dragging = Qnil;
4500 if (WINDOWP (window_being_scrolled))
4502 x_send_scroll_bar_event (window_being_scrolled,
4503 scroll_bar_end_scroll, 0, 0);
4504 window_being_scrolled = Qnil;
4507 return FALSE;
4511 #else /* not USE_GTK and not USE_MOTIF */
4513 /* Xaw scroll bar callback. Invoked when the thumb is dragged.
4514 WIDGET is the scroll bar widget. CLIENT_DATA is a pointer to the
4515 scroll bar struct. CALL_DATA is a pointer to a float saying where
4516 the thumb is. */
4518 static void
4519 xaw_jump_callback (Widget widget, XtPointer client_data, XtPointer call_data)
4521 struct scroll_bar *bar = (struct scroll_bar *) client_data;
4522 float top = *(float *) call_data;
4523 float shown;
4524 int whole, portion, height;
4525 int part;
4527 /* Get the size of the thumb, a value between 0 and 1. */
4528 BLOCK_INPUT;
4529 XtVaGetValues (widget, XtNshown, &shown, XtNheight, &height, NULL);
4530 UNBLOCK_INPUT;
4532 whole = 10000000;
4533 portion = shown < 1 ? top * whole : 0;
4535 if (shown < 1 && (eabs (top + shown - 1) < 1.0/height))
4536 /* Some derivatives of Xaw refuse to shrink the thumb when you reach
4537 the bottom, so we force the scrolling whenever we see that we're
4538 too close to the bottom (in x_set_toolkit_scroll_bar_thumb
4539 we try to ensure that we always stay two pixels away from the
4540 bottom). */
4541 part = scroll_bar_down_arrow;
4542 else
4543 part = scroll_bar_handle;
4545 window_being_scrolled = bar->window;
4546 bar->dragging = make_number (portion);
4547 last_scroll_bar_part = part;
4548 x_send_scroll_bar_event (bar->window, part, portion, whole);
4552 /* Xaw scroll bar callback. Invoked for incremental scrolling.,
4553 i.e. line or page up or down. WIDGET is the Xaw scroll bar
4554 widget. CLIENT_DATA is a pointer to the scroll_bar structure for
4555 the scroll bar. CALL_DATA is an integer specifying the action that
4556 has taken place. Its magnitude is in the range 0..height of the
4557 scroll bar. Negative values mean scroll towards buffer start.
4558 Values < height of scroll bar mean line-wise movement. */
4560 static void
4561 xaw_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
4563 struct scroll_bar *bar = (struct scroll_bar *) client_data;
4564 /* The position really is stored cast to a pointer. */
4565 int position = (long) call_data;
4566 Dimension height;
4567 int part;
4569 /* Get the height of the scroll bar. */
4570 BLOCK_INPUT;
4571 XtVaGetValues (widget, XtNheight, &height, NULL);
4572 UNBLOCK_INPUT;
4574 if (eabs (position) >= height)
4575 part = (position < 0) ? scroll_bar_above_handle : scroll_bar_below_handle;
4577 /* If Xaw3d was compiled with ARROW_SCROLLBAR,
4578 it maps line-movement to call_data = max(5, height/20). */
4579 else if (xaw3d_arrow_scroll && eabs (position) <= max (5, height / 20))
4580 part = (position < 0) ? scroll_bar_up_arrow : scroll_bar_down_arrow;
4581 else
4582 part = scroll_bar_move_ratio;
4584 window_being_scrolled = bar->window;
4585 bar->dragging = Qnil;
4586 last_scroll_bar_part = part;
4587 x_send_scroll_bar_event (bar->window, part, position, height);
4590 #endif /* not USE_GTK and not USE_MOTIF */
4592 #define SCROLL_BAR_NAME "verticalScrollBar"
4594 /* Create the widget for scroll bar BAR on frame F. Record the widget
4595 and X window of the scroll bar in BAR. */
4597 #ifdef USE_GTK
4598 static void
4599 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
4601 const char *scroll_bar_name = SCROLL_BAR_NAME;
4603 BLOCK_INPUT;
4604 xg_create_scroll_bar (f, bar, G_CALLBACK (xg_scroll_callback),
4605 G_CALLBACK (xg_end_scroll_callback),
4606 scroll_bar_name);
4607 UNBLOCK_INPUT;
4610 #else /* not USE_GTK */
4612 static void
4613 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
4615 Window xwindow;
4616 Widget widget;
4617 Arg av[20];
4618 int ac = 0;
4619 char const *scroll_bar_name = SCROLL_BAR_NAME;
4620 unsigned long pixel;
4622 BLOCK_INPUT;
4624 #ifdef USE_MOTIF
4625 /* Set resources. Create the widget. */
4626 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
4627 XtSetArg (av[ac], XmNminimum, 0); ++ac;
4628 XtSetArg (av[ac], XmNmaximum, XM_SB_MAX); ++ac;
4629 XtSetArg (av[ac], XmNorientation, XmVERTICAL); ++ac;
4630 XtSetArg (av[ac], XmNprocessingDirection, XmMAX_ON_BOTTOM), ++ac;
4631 XtSetArg (av[ac], XmNincrement, 1); ++ac;
4632 XtSetArg (av[ac], XmNpageIncrement, 1); ++ac;
4634 pixel = f->output_data.x->scroll_bar_foreground_pixel;
4635 if (pixel != -1)
4637 XtSetArg (av[ac], XmNforeground, pixel);
4638 ++ac;
4641 pixel = f->output_data.x->scroll_bar_background_pixel;
4642 if (pixel != -1)
4644 XtSetArg (av[ac], XmNbackground, pixel);
4645 ++ac;
4648 widget = XmCreateScrollBar (f->output_data.x->edit_widget,
4649 scroll_bar_name, av, ac);
4651 /* Add one callback for everything that can happen. */
4652 XtAddCallback (widget, XmNdecrementCallback, xm_scroll_callback,
4653 (XtPointer) bar);
4654 XtAddCallback (widget, XmNdragCallback, xm_scroll_callback,
4655 (XtPointer) bar);
4656 XtAddCallback (widget, XmNincrementCallback, xm_scroll_callback,
4657 (XtPointer) bar);
4658 XtAddCallback (widget, XmNpageDecrementCallback, xm_scroll_callback,
4659 (XtPointer) bar);
4660 XtAddCallback (widget, XmNpageIncrementCallback, xm_scroll_callback,
4661 (XtPointer) bar);
4662 XtAddCallback (widget, XmNtoBottomCallback, xm_scroll_callback,
4663 (XtPointer) bar);
4664 XtAddCallback (widget, XmNtoTopCallback, xm_scroll_callback,
4665 (XtPointer) bar);
4667 /* Realize the widget. Only after that is the X window created. */
4668 XtRealizeWidget (widget);
4670 /* Set the cursor to an arrow. I didn't find a resource to do that.
4671 And I'm wondering why it hasn't an arrow cursor by default. */
4672 XDefineCursor (XtDisplay (widget), XtWindow (widget),
4673 f->output_data.x->nontext_cursor);
4675 #else /* !USE_MOTIF i.e. use Xaw */
4677 /* Set resources. Create the widget. The background of the
4678 Xaw3d scroll bar widget is a little bit light for my taste.
4679 We don't alter it here to let users change it according
4680 to their taste with `emacs*verticalScrollBar.background: xxx'. */
4681 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
4682 XtSetArg (av[ac], XtNorientation, XtorientVertical); ++ac;
4683 /* For smoother scrolling with Xaw3d -sm */
4684 /* XtSetArg (av[ac], XtNpickTop, True); ++ac; */
4686 pixel = f->output_data.x->scroll_bar_foreground_pixel;
4687 if (pixel != -1)
4689 XtSetArg (av[ac], XtNforeground, pixel);
4690 ++ac;
4693 pixel = f->output_data.x->scroll_bar_background_pixel;
4694 if (pixel != -1)
4696 XtSetArg (av[ac], XtNbackground, pixel);
4697 ++ac;
4700 /* Top/bottom shadow colors. */
4702 /* Allocate them, if necessary. */
4703 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1)
4705 pixel = f->output_data.x->scroll_bar_background_pixel;
4706 if (pixel != -1)
4708 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
4709 FRAME_X_COLORMAP (f),
4710 &pixel, 1.2, 0x8000))
4711 pixel = -1;
4712 f->output_data.x->scroll_bar_top_shadow_pixel = pixel;
4715 if (f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
4717 pixel = f->output_data.x->scroll_bar_background_pixel;
4718 if (pixel != -1)
4720 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
4721 FRAME_X_COLORMAP (f),
4722 &pixel, 0.6, 0x4000))
4723 pixel = -1;
4724 f->output_data.x->scroll_bar_bottom_shadow_pixel = pixel;
4728 #ifdef XtNbeNiceToColormap
4729 /* Tell the toolkit about them. */
4730 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1
4731 || f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
4732 /* We tried to allocate a color for the top/bottom shadow, and
4733 failed, so tell Xaw3d to use dithering instead. */
4734 /* But only if we have a small colormap. Xaw3d can allocate nice
4735 colors itself. */
4737 XtSetArg (av[ac], XtNbeNiceToColormap,
4738 DefaultDepthOfScreen (FRAME_X_SCREEN (f)) < 16);
4739 ++ac;
4741 else
4742 /* Tell what colors Xaw3d should use for the top/bottom shadow, to
4743 be more consistent with other emacs 3d colors, and since Xaw3d is
4744 not good at dealing with allocation failure. */
4746 /* This tells Xaw3d to use real colors instead of dithering for
4747 the shadows. */
4748 XtSetArg (av[ac], XtNbeNiceToColormap, False);
4749 ++ac;
4751 /* Specify the colors. */
4752 pixel = f->output_data.x->scroll_bar_top_shadow_pixel;
4753 if (pixel != -1)
4755 XtSetArg (av[ac], XtNtopShadowPixel, pixel);
4756 ++ac;
4758 pixel = f->output_data.x->scroll_bar_bottom_shadow_pixel;
4759 if (pixel != -1)
4761 XtSetArg (av[ac], XtNbottomShadowPixel, pixel);
4762 ++ac;
4765 #endif
4767 widget = XtCreateWidget (scroll_bar_name, scrollbarWidgetClass,
4768 f->output_data.x->edit_widget, av, ac);
4771 char const *initial = "";
4772 char const *val = initial;
4773 XtVaGetValues (widget, XtNscrollVCursor, (XtPointer) &val,
4774 #ifdef XtNarrowScrollbars
4775 XtNarrowScrollbars, (XtPointer) &xaw3d_arrow_scroll,
4776 #endif
4777 XtNpickTop, (XtPointer) &xaw3d_pick_top, NULL);
4778 if (xaw3d_arrow_scroll || val == initial)
4779 { /* ARROW_SCROLL */
4780 xaw3d_arrow_scroll = True;
4781 /* Isn't that just a personal preference ? --Stef */
4782 XtVaSetValues (widget, XtNcursorName, "top_left_arrow", NULL);
4786 /* Define callbacks. */
4787 XtAddCallback (widget, XtNjumpProc, xaw_jump_callback, (XtPointer) bar);
4788 XtAddCallback (widget, XtNscrollProc, xaw_scroll_callback,
4789 (XtPointer) bar);
4791 /* Realize the widget. Only after that is the X window created. */
4792 XtRealizeWidget (widget);
4794 #endif /* !USE_MOTIF */
4796 /* Install an action hook that lets us detect when the user
4797 finishes interacting with a scroll bar. */
4798 if (action_hook_id == 0)
4799 action_hook_id = XtAppAddActionHook (Xt_app_con, xt_action_hook, 0);
4801 /* Remember X window and widget in the scroll bar vector. */
4802 SET_SCROLL_BAR_X_WIDGET (bar, widget);
4803 xwindow = XtWindow (widget);
4804 bar->x_window = xwindow;
4806 UNBLOCK_INPUT;
4808 #endif /* not USE_GTK */
4811 /* Set the thumb size and position of scroll bar BAR. We are currently
4812 displaying PORTION out of a whole WHOLE, and our position POSITION. */
4814 #ifdef USE_GTK
4815 static void
4816 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position, int whole)
4818 xg_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
4821 #else /* not USE_GTK */
4822 static void
4823 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position,
4824 int whole)
4826 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
4827 Widget widget = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
4828 float top, shown;
4830 BLOCK_INPUT;
4832 #ifdef USE_MOTIF
4834 /* We use an estimate of 30 chars per line rather than the real
4835 `portion' value. This has the disadvantage that the thumb size
4836 is not very representative, but it makes our life a lot easier.
4837 Otherwise, we have to constantly adjust the thumb size, which
4838 we can't always do quickly enough: while dragging, the size of
4839 the thumb might prevent the user from dragging the thumb all the
4840 way to the end. but Motif and some versions of Xaw3d don't allow
4841 updating the thumb size while dragging. Also, even if we can update
4842 its size, the update will often happen too late.
4843 If you don't believe it, check out revision 1.650 of xterm.c to see
4844 what hoops we were going through and the still poor behavior we got. */
4845 portion = WINDOW_TOTAL_LINES (XWINDOW (bar->window)) * 30;
4846 /* When the thumb is at the bottom, position == whole.
4847 So we need to increase `whole' to make space for the thumb. */
4848 whole += portion;
4850 if (whole <= 0)
4851 top = 0, shown = 1;
4852 else
4854 top = (float) position / whole;
4855 shown = (float) portion / whole;
4858 if (NILP (bar->dragging))
4860 int size, value;
4862 /* Slider size. Must be in the range [1 .. MAX - MIN] where MAX
4863 is the scroll bar's maximum and MIN is the scroll bar's minimum
4864 value. */
4865 size = shown * XM_SB_MAX;
4866 size = min (size, XM_SB_MAX);
4867 size = max (size, 1);
4869 /* Position. Must be in the range [MIN .. MAX - SLIDER_SIZE]. */
4870 value = top * XM_SB_MAX;
4871 value = min (value, XM_SB_MAX - size);
4873 XmScrollBarSetValues (widget, value, size, 0, 0, False);
4875 #else /* !USE_MOTIF i.e. use Xaw */
4877 if (whole == 0)
4878 top = 0, shown = 1;
4879 else
4881 top = (float) position / whole;
4882 shown = (float) portion / whole;
4886 float old_top, old_shown;
4887 Dimension height;
4888 XtVaGetValues (widget,
4889 XtNtopOfThumb, &old_top,
4890 XtNshown, &old_shown,
4891 XtNheight, &height,
4892 NULL);
4894 /* Massage the top+shown values. */
4895 if (NILP (bar->dragging) || last_scroll_bar_part == scroll_bar_down_arrow)
4896 top = max (0, min (1, top));
4897 else
4898 top = old_top;
4899 /* Keep two pixels available for moving the thumb down. */
4900 shown = max (0, min (1 - top - (2.0 / height), shown));
4902 /* If the call to XawScrollbarSetThumb below doesn't seem to work,
4903 check that your system's configuration file contains a define
4904 for `NARROWPROTO'. See s/freebsd.h for an example. */
4905 if (top != old_top || shown != old_shown)
4907 if (NILP (bar->dragging))
4908 XawScrollbarSetThumb (widget, top, shown);
4909 else
4911 /* Try to make the scrolling a tad smoother. */
4912 if (!xaw3d_pick_top)
4913 shown = min (shown, old_shown);
4915 XawScrollbarSetThumb (widget, top, shown);
4919 #endif /* !USE_MOTIF */
4921 UNBLOCK_INPUT;
4923 #endif /* not USE_GTK */
4925 #endif /* USE_TOOLKIT_SCROLL_BARS */
4929 /************************************************************************
4930 Scroll bars, general
4931 ************************************************************************/
4933 /* Create a scroll bar and return the scroll bar vector for it. W is
4934 the Emacs window on which to create the scroll bar. TOP, LEFT,
4935 WIDTH and HEIGHT are the pixel coordinates and dimensions of the
4936 scroll bar. */
4938 static struct scroll_bar *
4939 x_scroll_bar_create (struct window *w, int top, int left, int width, int height)
4941 struct frame *f = XFRAME (w->frame);
4942 struct scroll_bar *bar
4943 = ALLOCATE_PSEUDOVECTOR (struct scroll_bar, x_window, PVEC_OTHER);
4945 BLOCK_INPUT;
4947 #ifdef USE_TOOLKIT_SCROLL_BARS
4948 x_create_toolkit_scroll_bar (f, bar);
4949 #else /* not USE_TOOLKIT_SCROLL_BARS */
4951 XSetWindowAttributes a;
4952 unsigned long mask;
4953 Window window;
4955 a.background_pixel = f->output_data.x->scroll_bar_background_pixel;
4956 if (a.background_pixel == -1)
4957 a.background_pixel = FRAME_BACKGROUND_PIXEL (f);
4959 a.event_mask = (ButtonPressMask | ButtonReleaseMask
4960 | ButtonMotionMask | PointerMotionHintMask
4961 | ExposureMask);
4962 a.cursor = FRAME_X_DISPLAY_INFO (f)->vertical_scroll_bar_cursor;
4964 mask = (CWBackPixel | CWEventMask | CWCursor);
4966 /* Clear the area of W that will serve as a scroll bar. This is
4967 for the case that a window has been split horizontally. In
4968 this case, no clear_frame is generated to reduce flickering. */
4969 if (width > 0 && height > 0)
4970 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4971 left, top, width,
4972 window_box_height (w), False);
4974 window = XCreateWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4975 /* Position and size of scroll bar. */
4976 left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
4977 top,
4978 width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
4979 height,
4980 /* Border width, depth, class, and visual. */
4982 CopyFromParent,
4983 CopyFromParent,
4984 CopyFromParent,
4985 /* Attributes. */
4986 mask, &a);
4987 bar->x_window = window;
4989 #endif /* not USE_TOOLKIT_SCROLL_BARS */
4991 XSETWINDOW (bar->window, w);
4992 bar->top = top;
4993 bar->left = left;
4994 bar->width = width;
4995 bar->height = height;
4996 bar->start = 0;
4997 bar->end = 0;
4998 bar->dragging = Qnil;
4999 bar->fringe_extended_p = 0;
5001 /* Add bar to its frame's list of scroll bars. */
5002 bar->next = FRAME_SCROLL_BARS (f);
5003 bar->prev = Qnil;
5004 XSETVECTOR (FRAME_SCROLL_BARS (f), bar);
5005 if (!NILP (bar->next))
5006 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
5008 /* Map the window/widget. */
5009 #ifdef USE_TOOLKIT_SCROLL_BARS
5011 #ifdef USE_GTK
5012 xg_update_scrollbar_pos (f,
5013 bar->x_window,
5014 top,
5015 left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5016 width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
5017 max (height, 1));
5018 #else /* not USE_GTK */
5019 Widget scroll_bar = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
5020 XtConfigureWidget (scroll_bar,
5021 left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5022 top,
5023 width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
5024 max (height, 1), 0);
5025 XtMapWidget (scroll_bar);
5026 #endif /* not USE_GTK */
5028 #else /* not USE_TOOLKIT_SCROLL_BARS */
5029 XMapRaised (FRAME_X_DISPLAY (f), bar->x_window);
5030 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5032 UNBLOCK_INPUT;
5033 return bar;
5037 #ifndef USE_TOOLKIT_SCROLL_BARS
5039 /* Draw BAR's handle in the proper position.
5041 If the handle is already drawn from START to END, don't bother
5042 redrawing it, unless REBUILD is non-zero; in that case, always
5043 redraw it. (REBUILD is handy for drawing the handle after expose
5044 events.)
5046 Normally, we want to constrain the start and end of the handle to
5047 fit inside its rectangle, but if the user is dragging the scroll
5048 bar handle, we want to let them drag it down all the way, so that
5049 the bar's top is as far down as it goes; otherwise, there's no way
5050 to move to the very end of the buffer. */
5052 static void
5053 x_scroll_bar_set_handle (struct scroll_bar *bar, int start, int end, int rebuild)
5055 int dragging = ! NILP (bar->dragging);
5056 Window w = bar->x_window;
5057 FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5058 GC gc = f->output_data.x->normal_gc;
5060 /* If the display is already accurate, do nothing. */
5061 if (! rebuild
5062 && start == bar->start
5063 && end == bar->end)
5064 return;
5066 BLOCK_INPUT;
5069 int inside_width = VERTICAL_SCROLL_BAR_INSIDE_WIDTH (f, bar->width);
5070 int inside_height = VERTICAL_SCROLL_BAR_INSIDE_HEIGHT (f, bar->height);
5071 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
5073 /* Make sure the values are reasonable, and try to preserve
5074 the distance between start and end. */
5076 int length = end - start;
5078 if (start < 0)
5079 start = 0;
5080 else if (start > top_range)
5081 start = top_range;
5082 end = start + length;
5084 if (end < start)
5085 end = start;
5086 else if (end > top_range && ! dragging)
5087 end = top_range;
5090 /* Store the adjusted setting in the scroll bar. */
5091 bar->start = start;
5092 bar->end = end;
5094 /* Clip the end position, just for display. */
5095 if (end > top_range)
5096 end = top_range;
5098 /* Draw bottom positions VERTICAL_SCROLL_BAR_MIN_HANDLE pixels
5099 below top positions, to make sure the handle is always at least
5100 that many pixels tall. */
5101 end += VERTICAL_SCROLL_BAR_MIN_HANDLE;
5103 /* Draw the empty space above the handle. Note that we can't clear
5104 zero-height areas; that means "clear to end of window." */
5105 if (0 < start)
5106 x_clear_area (FRAME_X_DISPLAY (f), w,
5107 /* x, y, width, height, and exposures. */
5108 VERTICAL_SCROLL_BAR_LEFT_BORDER,
5109 VERTICAL_SCROLL_BAR_TOP_BORDER,
5110 inside_width, start,
5111 False);
5113 /* Change to proper foreground color if one is specified. */
5114 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5115 XSetForeground (FRAME_X_DISPLAY (f), gc,
5116 f->output_data.x->scroll_bar_foreground_pixel);
5118 /* Draw the handle itself. */
5119 XFillRectangle (FRAME_X_DISPLAY (f), w, gc,
5120 /* x, y, width, height */
5121 VERTICAL_SCROLL_BAR_LEFT_BORDER,
5122 VERTICAL_SCROLL_BAR_TOP_BORDER + start,
5123 inside_width, end - start);
5125 /* Restore the foreground color of the GC if we changed it above. */
5126 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5127 XSetForeground (FRAME_X_DISPLAY (f), gc,
5128 FRAME_FOREGROUND_PIXEL (f));
5130 /* Draw the empty space below the handle. Note that we can't
5131 clear zero-height areas; that means "clear to end of window." */
5132 if (end < inside_height)
5133 x_clear_area (FRAME_X_DISPLAY (f), w,
5134 /* x, y, width, height, and exposures. */
5135 VERTICAL_SCROLL_BAR_LEFT_BORDER,
5136 VERTICAL_SCROLL_BAR_TOP_BORDER + end,
5137 inside_width, inside_height - end,
5138 False);
5142 UNBLOCK_INPUT;
5145 #endif /* !USE_TOOLKIT_SCROLL_BARS */
5147 /* Destroy scroll bar BAR, and set its Emacs window's scroll bar to
5148 nil. */
5150 static void
5151 x_scroll_bar_remove (struct scroll_bar *bar)
5153 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5154 BLOCK_INPUT;
5156 #ifdef USE_TOOLKIT_SCROLL_BARS
5157 #ifdef USE_GTK
5158 xg_remove_scroll_bar (f, bar->x_window);
5159 #else /* not USE_GTK */
5160 XtDestroyWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar));
5161 #endif /* not USE_GTK */
5162 #else
5163 XDestroyWindow (FRAME_X_DISPLAY (f), bar->x_window);
5164 #endif
5166 /* Dissociate this scroll bar from its window. */
5167 XWINDOW (bar->window)->vertical_scroll_bar = Qnil;
5169 UNBLOCK_INPUT;
5173 /* Set the handle of the vertical scroll bar for WINDOW to indicate
5174 that we are displaying PORTION characters out of a total of WHOLE
5175 characters, starting at POSITION. If WINDOW has no scroll bar,
5176 create one. */
5178 static void
5179 XTset_vertical_scroll_bar (struct window *w, int portion, int whole, int position)
5181 struct frame *f = XFRAME (w->frame);
5182 struct scroll_bar *bar;
5183 int top, height, left, sb_left, width, sb_width;
5184 int window_y, window_height;
5185 #ifdef USE_TOOLKIT_SCROLL_BARS
5186 int fringe_extended_p;
5187 #endif
5189 /* Get window dimensions. */
5190 window_box (w, -1, 0, &window_y, 0, &window_height);
5191 top = window_y;
5192 width = WINDOW_CONFIG_SCROLL_BAR_COLS (w) * FRAME_COLUMN_WIDTH (f);
5193 height = window_height;
5195 /* Compute the left edge of the scroll bar area. */
5196 left = WINDOW_SCROLL_BAR_AREA_X (w);
5198 /* Compute the width of the scroll bar which might be less than
5199 the width of the area reserved for the scroll bar. */
5200 if (WINDOW_CONFIG_SCROLL_BAR_WIDTH (w) > 0)
5201 sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
5202 else
5203 sb_width = width;
5205 /* Compute the left edge of the scroll bar. */
5206 #ifdef USE_TOOLKIT_SCROLL_BARS
5207 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w))
5208 sb_left = left + (WINDOW_RIGHTMOST_P (w) ? width - sb_width : 0);
5209 else
5210 sb_left = left + (WINDOW_LEFTMOST_P (w) ? 0 : width - sb_width);
5211 #else
5212 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w))
5213 sb_left = left + width - sb_width;
5214 else
5215 sb_left = left;
5216 #endif
5218 #ifdef USE_TOOLKIT_SCROLL_BARS
5219 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
5220 fringe_extended_p = (WINDOW_LEFTMOST_P (w)
5221 && WINDOW_LEFT_FRINGE_WIDTH (w)
5222 && (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (w)
5223 || WINDOW_LEFT_MARGIN_COLS (w) == 0));
5224 else
5225 fringe_extended_p = (WINDOW_RIGHTMOST_P (w)
5226 && WINDOW_RIGHT_FRINGE_WIDTH (w)
5227 && (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (w)
5228 || WINDOW_RIGHT_MARGIN_COLS (w) == 0));
5229 #endif
5231 /* Does the scroll bar exist yet? */
5232 if (NILP (w->vertical_scroll_bar))
5234 if (width > 0 && height > 0)
5236 BLOCK_INPUT;
5237 #ifdef USE_TOOLKIT_SCROLL_BARS
5238 if (fringe_extended_p)
5239 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5240 sb_left, top, sb_width, height, False);
5241 else
5242 #endif
5243 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5244 left, top, width, height, False);
5245 UNBLOCK_INPUT;
5248 bar = x_scroll_bar_create (w, top, sb_left, sb_width, height);
5250 else
5252 /* It may just need to be moved and resized. */
5253 unsigned int mask = 0;
5255 bar = XSCROLL_BAR (w->vertical_scroll_bar);
5257 BLOCK_INPUT;
5259 if (sb_left != bar->left)
5260 mask |= CWX;
5261 if (top != bar->top)
5262 mask |= CWY;
5263 if (sb_width != bar->width)
5264 mask |= CWWidth;
5265 if (height != bar->height)
5266 mask |= CWHeight;
5268 #ifdef USE_TOOLKIT_SCROLL_BARS
5270 /* Move/size the scroll bar widget. */
5271 if (mask || bar->fringe_extended_p != fringe_extended_p)
5273 /* Since toolkit scroll bars are smaller than the space reserved
5274 for them on the frame, we have to clear "under" them. */
5275 if (width > 0 && height > 0)
5277 if (fringe_extended_p)
5278 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5279 sb_left, top, sb_width, height, False);
5280 else
5281 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5282 left, top, width, height, False);
5284 #ifdef USE_GTK
5285 xg_update_scrollbar_pos (f,
5286 bar->x_window,
5287 top,
5288 sb_left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5289 sb_width - VERTICAL_SCROLL_BAR_WIDTH_TRIM *2,
5290 max (height, 1));
5291 #else /* not USE_GTK */
5292 XtConfigureWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar),
5293 sb_left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5294 top,
5295 sb_width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
5296 max (height, 1), 0);
5297 #endif /* not USE_GTK */
5299 #else /* not USE_TOOLKIT_SCROLL_BARS */
5301 /* Clear areas not covered by the scroll bar because of
5302 VERTICAL_SCROLL_BAR_WIDTH_TRIM. */
5303 if (VERTICAL_SCROLL_BAR_WIDTH_TRIM)
5305 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5306 left, top, VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5307 height, False);
5308 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5309 left + width - VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5310 top, VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5311 height, False);
5314 /* Clear areas not covered by the scroll bar because it's not as
5315 wide as the area reserved for it. This makes sure a
5316 previous mode line display is cleared after C-x 2 C-x 1, for
5317 example. */
5319 int area_width = WINDOW_CONFIG_SCROLL_BAR_COLS (w) * FRAME_COLUMN_WIDTH (f);
5320 int rest = area_width - sb_width;
5321 if (rest > 0 && height > 0)
5323 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
5324 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5325 left + area_width - rest, top,
5326 rest, height, False);
5327 else
5328 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5329 left, top, rest, height, False);
5333 /* Move/size the scroll bar window. */
5334 if (mask)
5336 XWindowChanges wc;
5338 wc.x = sb_left + VERTICAL_SCROLL_BAR_WIDTH_TRIM;
5339 wc.y = top;
5340 wc.width = sb_width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2;
5341 wc.height = height;
5342 XConfigureWindow (FRAME_X_DISPLAY (f), bar->x_window,
5343 mask, &wc);
5346 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5348 /* Remember new settings. */
5349 bar->left = sb_left;
5350 bar->top = top;
5351 bar->width = sb_width;
5352 bar->height = height;
5354 UNBLOCK_INPUT;
5357 #ifdef USE_TOOLKIT_SCROLL_BARS
5358 bar->fringe_extended_p = fringe_extended_p;
5360 x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
5361 #else /* not USE_TOOLKIT_SCROLL_BARS */
5362 /* Set the scroll bar's current state, unless we're currently being
5363 dragged. */
5364 if (NILP (bar->dragging))
5366 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, height);
5368 if (whole == 0)
5369 x_scroll_bar_set_handle (bar, 0, top_range, 0);
5370 else
5372 int start = ((double) position * top_range) / whole;
5373 int end = ((double) (position + portion) * top_range) / whole;
5374 x_scroll_bar_set_handle (bar, start, end, 0);
5377 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5379 XSETVECTOR (w->vertical_scroll_bar, bar);
5383 /* The following three hooks are used when we're doing a thorough
5384 redisplay of the frame. We don't explicitly know which scroll bars
5385 are going to be deleted, because keeping track of when windows go
5386 away is a real pain - "Can you say set-window-configuration, boys
5387 and girls?" Instead, we just assert at the beginning of redisplay
5388 that *all* scroll bars are to be removed, and then save a scroll bar
5389 from the fiery pit when we actually redisplay its window. */
5391 /* Arrange for all scroll bars on FRAME to be removed at the next call
5392 to `*judge_scroll_bars_hook'. A scroll bar may be spared if
5393 `*redeem_scroll_bar_hook' is applied to its window before the judgment. */
5395 static void
5396 XTcondemn_scroll_bars (FRAME_PTR frame)
5398 /* Transfer all the scroll bars to FRAME_CONDEMNED_SCROLL_BARS. */
5399 while (! NILP (FRAME_SCROLL_BARS (frame)))
5401 Lisp_Object bar;
5402 bar = FRAME_SCROLL_BARS (frame);
5403 FRAME_SCROLL_BARS (frame) = XSCROLL_BAR (bar)->next;
5404 XSCROLL_BAR (bar)->next = FRAME_CONDEMNED_SCROLL_BARS (frame);
5405 XSCROLL_BAR (bar)->prev = Qnil;
5406 if (! NILP (FRAME_CONDEMNED_SCROLL_BARS (frame)))
5407 XSCROLL_BAR (FRAME_CONDEMNED_SCROLL_BARS (frame))->prev = bar;
5408 FRAME_CONDEMNED_SCROLL_BARS (frame) = bar;
5413 /* Un-mark WINDOW's scroll bar for deletion in this judgment cycle.
5414 Note that WINDOW isn't necessarily condemned at all. */
5416 static void
5417 XTredeem_scroll_bar (struct window *window)
5419 struct scroll_bar *bar;
5420 struct frame *f;
5422 /* We can't redeem this window's scroll bar if it doesn't have one. */
5423 if (NILP (window->vertical_scroll_bar))
5424 abort ();
5426 bar = XSCROLL_BAR (window->vertical_scroll_bar);
5428 /* Unlink it from the condemned list. */
5429 f = XFRAME (WINDOW_FRAME (window));
5430 if (NILP (bar->prev))
5432 /* If the prev pointer is nil, it must be the first in one of
5433 the lists. */
5434 if (EQ (FRAME_SCROLL_BARS (f), window->vertical_scroll_bar))
5435 /* It's not condemned. Everything's fine. */
5436 return;
5437 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
5438 window->vertical_scroll_bar))
5439 FRAME_CONDEMNED_SCROLL_BARS (f) = bar->next;
5440 else
5441 /* If its prev pointer is nil, it must be at the front of
5442 one or the other! */
5443 abort ();
5445 else
5446 XSCROLL_BAR (bar->prev)->next = bar->next;
5448 if (! NILP (bar->next))
5449 XSCROLL_BAR (bar->next)->prev = bar->prev;
5451 bar->next = FRAME_SCROLL_BARS (f);
5452 bar->prev = Qnil;
5453 XSETVECTOR (FRAME_SCROLL_BARS (f), bar);
5454 if (! NILP (bar->next))
5455 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
5458 /* Remove all scroll bars on FRAME that haven't been saved since the
5459 last call to `*condemn_scroll_bars_hook'. */
5461 static void
5462 XTjudge_scroll_bars (FRAME_PTR f)
5464 Lisp_Object bar, next;
5466 bar = FRAME_CONDEMNED_SCROLL_BARS (f);
5468 /* Clear out the condemned list now so we won't try to process any
5469 more events on the hapless scroll bars. */
5470 FRAME_CONDEMNED_SCROLL_BARS (f) = Qnil;
5472 for (; ! NILP (bar); bar = next)
5474 struct scroll_bar *b = XSCROLL_BAR (bar);
5476 x_scroll_bar_remove (b);
5478 next = b->next;
5479 b->next = b->prev = Qnil;
5482 /* Now there should be no references to the condemned scroll bars,
5483 and they should get garbage-collected. */
5487 #ifndef USE_TOOLKIT_SCROLL_BARS
5488 /* Handle an Expose or GraphicsExpose event on a scroll bar. This
5489 is a no-op when using toolkit scroll bars.
5491 This may be called from a signal handler, so we have to ignore GC
5492 mark bits. */
5494 static void
5495 x_scroll_bar_expose (struct scroll_bar *bar, XEvent *event)
5497 Window w = bar->x_window;
5498 FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5499 GC gc = f->output_data.x->normal_gc;
5500 int width_trim = VERTICAL_SCROLL_BAR_WIDTH_TRIM;
5502 BLOCK_INPUT;
5504 x_scroll_bar_set_handle (bar, bar->start, bar->end, 1);
5506 /* Switch to scroll bar foreground color. */
5507 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5508 XSetForeground (FRAME_X_DISPLAY (f), gc,
5509 f->output_data.x->scroll_bar_foreground_pixel);
5511 /* Draw a one-pixel border just inside the edges of the scroll bar. */
5512 XDrawRectangle (FRAME_X_DISPLAY (f), w, gc,
5514 /* x, y, width, height */
5515 0, 0,
5516 bar->width - 1 - width_trim - width_trim,
5517 bar->height - 1);
5519 /* Restore the foreground color of the GC if we changed it above. */
5520 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5521 XSetForeground (FRAME_X_DISPLAY (f), gc,
5522 FRAME_FOREGROUND_PIXEL (f));
5524 UNBLOCK_INPUT;
5527 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5529 /* Handle a mouse click on the scroll bar BAR. If *EMACS_EVENT's kind
5530 is set to something other than NO_EVENT, it is enqueued.
5532 This may be called from a signal handler, so we have to ignore GC
5533 mark bits. */
5536 static void
5537 x_scroll_bar_handle_click (struct scroll_bar *bar, XEvent *event, struct input_event *emacs_event)
5539 if (! WINDOWP (bar->window))
5540 abort ();
5542 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
5543 emacs_event->code = event->xbutton.button - Button1;
5544 emacs_event->modifiers
5545 = (x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO
5546 (XFRAME (WINDOW_FRAME (XWINDOW (bar->window)))),
5547 event->xbutton.state)
5548 | (event->type == ButtonRelease
5549 ? up_modifier
5550 : down_modifier));
5551 emacs_event->frame_or_window = bar->window;
5552 emacs_event->arg = Qnil;
5553 emacs_event->timestamp = event->xbutton.time;
5555 int top_range
5556 = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
5557 int y = event->xbutton.y - VERTICAL_SCROLL_BAR_TOP_BORDER;
5559 if (y < 0) y = 0;
5560 if (y > top_range) y = top_range;
5562 if (y < bar->start)
5563 emacs_event->part = scroll_bar_above_handle;
5564 else if (y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
5565 emacs_event->part = scroll_bar_handle;
5566 else
5567 emacs_event->part = scroll_bar_below_handle;
5569 #ifndef USE_TOOLKIT_SCROLL_BARS
5570 /* If the user has released the handle, set it to its final position. */
5571 if (event->type == ButtonRelease
5572 && ! NILP (bar->dragging))
5574 int new_start = y - XINT (bar->dragging);
5575 int new_end = new_start + bar->end - bar->start;
5577 x_scroll_bar_set_handle (bar, new_start, new_end, 0);
5578 bar->dragging = Qnil;
5580 #endif
5582 XSETINT (emacs_event->x, y);
5583 XSETINT (emacs_event->y, top_range);
5587 #ifndef USE_TOOLKIT_SCROLL_BARS
5589 /* Handle some mouse motion while someone is dragging the scroll bar.
5591 This may be called from a signal handler, so we have to ignore GC
5592 mark bits. */
5594 static void
5595 x_scroll_bar_note_movement (struct scroll_bar *bar, XEvent *event)
5597 FRAME_PTR f = XFRAME (XWINDOW (bar->window)->frame);
5599 last_mouse_movement_time = event->xmotion.time;
5601 f->mouse_moved = 1;
5602 XSETVECTOR (last_mouse_scroll_bar, bar);
5604 /* If we're dragging the bar, display it. */
5605 if (! NILP (bar->dragging))
5607 /* Where should the handle be now? */
5608 int new_start = event->xmotion.y - XINT (bar->dragging);
5610 if (new_start != bar->start)
5612 int new_end = new_start + bar->end - bar->start;
5614 x_scroll_bar_set_handle (bar, new_start, new_end, 0);
5619 #endif /* !USE_TOOLKIT_SCROLL_BARS */
5621 /* Return information to the user about the current position of the mouse
5622 on the scroll bar. */
5624 static void
5625 x_scroll_bar_report_motion (FRAME_PTR *fp, Lisp_Object *bar_window,
5626 enum scroll_bar_part *part, Lisp_Object *x,
5627 Lisp_Object *y, Time *timestamp)
5629 struct scroll_bar *bar = XSCROLL_BAR (last_mouse_scroll_bar);
5630 Window w = bar->x_window;
5631 FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5632 int win_x, win_y;
5633 Window dummy_window;
5634 int dummy_coord;
5635 unsigned int dummy_mask;
5637 BLOCK_INPUT;
5639 /* Get the mouse's position relative to the scroll bar window, and
5640 report that. */
5641 if (! XQueryPointer (FRAME_X_DISPLAY (f), w,
5643 /* Root, child, root x and root y. */
5644 &dummy_window, &dummy_window,
5645 &dummy_coord, &dummy_coord,
5647 /* Position relative to scroll bar. */
5648 &win_x, &win_y,
5650 /* Mouse buttons and modifier keys. */
5651 &dummy_mask))
5653 else
5655 int top_range
5656 = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
5658 win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
5660 if (! NILP (bar->dragging))
5661 win_y -= XINT (bar->dragging);
5663 if (win_y < 0)
5664 win_y = 0;
5665 if (win_y > top_range)
5666 win_y = top_range;
5668 *fp = f;
5669 *bar_window = bar->window;
5671 if (! NILP (bar->dragging))
5672 *part = scroll_bar_handle;
5673 else if (win_y < bar->start)
5674 *part = scroll_bar_above_handle;
5675 else if (win_y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
5676 *part = scroll_bar_handle;
5677 else
5678 *part = scroll_bar_below_handle;
5680 XSETINT (*x, win_y);
5681 XSETINT (*y, top_range);
5683 f->mouse_moved = 0;
5684 last_mouse_scroll_bar = Qnil;
5687 *timestamp = last_mouse_movement_time;
5689 UNBLOCK_INPUT;
5693 /* The screen has been cleared so we may have changed foreground or
5694 background colors, and the scroll bars may need to be redrawn.
5695 Clear out the scroll bars, and ask for expose events, so we can
5696 redraw them. */
5698 static void
5699 x_scroll_bar_clear (FRAME_PTR f)
5701 #ifndef USE_TOOLKIT_SCROLL_BARS
5702 Lisp_Object bar;
5704 /* We can have scroll bars even if this is 0,
5705 if we just turned off scroll bar mode.
5706 But in that case we should not clear them. */
5707 if (FRAME_HAS_VERTICAL_SCROLL_BARS (f))
5708 for (bar = FRAME_SCROLL_BARS (f); VECTORP (bar);
5709 bar = XSCROLL_BAR (bar)->next)
5710 XClearArea (FRAME_X_DISPLAY (f),
5711 XSCROLL_BAR (bar)->x_window,
5712 0, 0, 0, 0, True);
5713 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5717 /* The main X event-reading loop - XTread_socket. */
5719 /* This holds the state XLookupString needs to implement dead keys
5720 and other tricks known as "compose processing". _X Window System_
5721 says that a portable program can't use this, but Stephen Gildea assures
5722 me that letting the compiler initialize it to zeros will work okay.
5724 This must be defined outside of XTread_socket, for the same reasons
5725 given for enter_timestamp, above. */
5727 static XComposeStatus compose_status;
5729 /* Record the last 100 characters stored
5730 to help debug the loss-of-chars-during-GC problem. */
5732 static int temp_index;
5733 static short temp_buffer[100];
5735 #define STORE_KEYSYM_FOR_DEBUG(keysym) \
5736 if (temp_index == sizeof temp_buffer / sizeof (short)) \
5737 temp_index = 0; \
5738 temp_buffer[temp_index++] = (keysym)
5740 /* Set this to nonzero to fake an "X I/O error"
5741 on a particular display. */
5743 static struct x_display_info *XTread_socket_fake_io_error;
5745 /* When we find no input here, we occasionally do a no-op command
5746 to verify that the X server is still running and we can still talk with it.
5747 We try all the open displays, one by one.
5748 This variable is used for cycling thru the displays. */
5750 static struct x_display_info *next_noop_dpyinfo;
5752 #if defined USE_X_TOOLKIT || defined USE_GTK
5753 #define SET_SAVED_BUTTON_EVENT \
5754 do \
5756 if (f->output_data.x->saved_menu_event == 0) \
5757 f->output_data.x->saved_menu_event \
5758 = (XEvent *) xmalloc (sizeof (XEvent)); \
5759 *f->output_data.x->saved_menu_event = event; \
5760 inev.ie.kind = MENU_BAR_ACTIVATE_EVENT; \
5761 XSETFRAME (inev.ie.frame_or_window, f); \
5763 while (0)
5764 #endif
5766 enum
5768 X_EVENT_NORMAL,
5769 X_EVENT_GOTO_OUT,
5770 X_EVENT_DROP
5773 /* Filter events for the current X input method.
5774 DPYINFO is the display this event is for.
5775 EVENT is the X event to filter.
5777 Returns non-zero if the event was filtered, caller shall not process
5778 this event further.
5779 Returns zero if event is wasn't filtered. */
5781 #ifdef HAVE_X_I18N
5782 static int
5783 x_filter_event (struct x_display_info *dpyinfo, XEvent *event)
5785 /* XFilterEvent returns non-zero if the input method has
5786 consumed the event. We pass the frame's X window to
5787 XFilterEvent because that's the one for which the IC
5788 was created. */
5790 struct frame *f1 = x_any_window_to_frame (dpyinfo,
5791 event->xclient.window);
5793 return XFilterEvent (event, f1 ? FRAME_X_WINDOW (f1) : None);
5795 #endif
5797 #ifdef USE_GTK
5798 static int current_count;
5799 static int current_finish;
5800 static struct input_event *current_hold_quit;
5802 /* This is the filter function invoked by the GTK event loop.
5803 It is invoked before the XEvent is translated to a GdkEvent,
5804 so we have a chance to act on the event before GTK. */
5805 static GdkFilterReturn
5806 event_handler_gdk (GdkXEvent *gxev, GdkEvent *ev, gpointer data)
5808 XEvent *xev = (XEvent *) gxev;
5810 BLOCK_INPUT;
5811 if (current_count >= 0)
5813 struct x_display_info *dpyinfo;
5815 dpyinfo = x_display_info_for_display (xev->xany.display);
5817 #ifdef HAVE_X_I18N
5818 /* Filter events for the current X input method.
5819 GTK calls XFilterEvent but not for key press and release,
5820 so we do it here. */
5821 if ((xev->type == KeyPress || xev->type == KeyRelease)
5822 && dpyinfo
5823 && x_filter_event (dpyinfo, xev))
5825 UNBLOCK_INPUT;
5826 return GDK_FILTER_REMOVE;
5828 #endif
5830 if (! dpyinfo)
5831 current_finish = X_EVENT_NORMAL;
5832 else
5833 current_count +=
5834 handle_one_xevent (dpyinfo, xev, &current_finish,
5835 current_hold_quit);
5837 else
5838 current_finish = x_dispatch_event (xev, xev->xany.display);
5840 UNBLOCK_INPUT;
5842 if (current_finish == X_EVENT_GOTO_OUT || current_finish == X_EVENT_DROP)
5843 return GDK_FILTER_REMOVE;
5845 return GDK_FILTER_CONTINUE;
5847 #endif /* USE_GTK */
5850 static void xembed_send_message (struct frame *f, Time,
5851 enum xembed_message,
5852 long detail, long data1, long data2);
5854 /* Handles the XEvent EVENT on display DPYINFO.
5856 *FINISH is X_EVENT_GOTO_OUT if caller should stop reading events.
5857 *FINISH is zero if caller should continue reading events.
5858 *FINISH is X_EVENT_DROP if event should not be passed to the toolkit.
5860 We return the number of characters stored into the buffer. */
5862 static int
5863 handle_one_xevent (struct x_display_info *dpyinfo, XEvent *eventptr,
5864 int *finish, struct input_event *hold_quit)
5866 union {
5867 struct input_event ie;
5868 struct selection_input_event sie;
5869 } inev;
5870 int count = 0;
5871 int do_help = 0;
5872 ptrdiff_t nbytes = 0;
5873 struct frame *f = NULL;
5874 struct coding_system coding;
5875 XEvent event = *eventptr;
5876 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
5877 USE_SAFE_ALLOCA;
5879 *finish = X_EVENT_NORMAL;
5881 EVENT_INIT (inev.ie);
5882 inev.ie.kind = NO_EVENT;
5883 inev.ie.arg = Qnil;
5885 if (pending_event_wait.eventtype == event.type)
5886 pending_event_wait.eventtype = 0; /* Indicates we got it. */
5888 switch (event.type)
5890 case ClientMessage:
5892 if (event.xclient.message_type
5893 == dpyinfo->Xatom_wm_protocols
5894 && event.xclient.format == 32)
5896 if (event.xclient.data.l[0]
5897 == dpyinfo->Xatom_wm_take_focus)
5899 /* Use x_any_window_to_frame because this
5900 could be the shell widget window
5901 if the frame has no title bar. */
5902 f = x_any_window_to_frame (dpyinfo, event.xclient.window);
5903 #ifdef HAVE_X_I18N
5904 /* Not quite sure this is needed -pd */
5905 if (f && FRAME_XIC (f))
5906 XSetICFocus (FRAME_XIC (f));
5907 #endif
5908 #if 0 /* Emacs sets WM hints whose `input' field is `true'. This
5909 instructs the WM to set the input focus automatically for
5910 Emacs with a call to XSetInputFocus. Setting WM_TAKE_FOCUS
5911 tells the WM to send us a ClientMessage WM_TAKE_FOCUS after
5912 it has set the focus. So, XSetInputFocus below is not
5913 needed.
5915 The call to XSetInputFocus below has also caused trouble. In
5916 cases where the XSetInputFocus done by the WM and the one
5917 below are temporally close (on a fast machine), the call
5918 below can generate additional FocusIn events which confuse
5919 Emacs. */
5921 /* Since we set WM_TAKE_FOCUS, we must call
5922 XSetInputFocus explicitly. But not if f is null,
5923 since that might be an event for a deleted frame. */
5924 if (f)
5926 Display *d = event.xclient.display;
5927 /* Catch and ignore errors, in case window has been
5928 iconified by a window manager such as GWM. */
5929 x_catch_errors (d);
5930 XSetInputFocus (d, event.xclient.window,
5931 /* The ICCCM says this is
5932 the only valid choice. */
5933 RevertToParent,
5934 event.xclient.data.l[1]);
5935 /* This is needed to detect the error
5936 if there is an error. */
5937 XSync (d, False);
5938 x_uncatch_errors ();
5940 /* Not certain about handling scroll bars here */
5941 #endif /* 0 */
5942 goto done;
5945 if (event.xclient.data.l[0]
5946 == dpyinfo->Xatom_wm_save_yourself)
5948 /* Save state modify the WM_COMMAND property to
5949 something which can reinstate us. This notifies
5950 the session manager, who's looking for such a
5951 PropertyNotify. Can restart processing when
5952 a keyboard or mouse event arrives. */
5953 /* If we have a session manager, don't set this.
5954 KDE will then start two Emacsen, one for the
5955 session manager and one for this. */
5956 #ifdef HAVE_X_SM
5957 if (! x_session_have_connection ())
5958 #endif
5960 f = x_top_window_to_frame (dpyinfo,
5961 event.xclient.window);
5962 /* This is just so we only give real data once
5963 for a single Emacs process. */
5964 if (f == SELECTED_FRAME ())
5965 XSetCommand (FRAME_X_DISPLAY (f),
5966 event.xclient.window,
5967 initial_argv, initial_argc);
5968 else if (f)
5969 XSetCommand (FRAME_X_DISPLAY (f),
5970 event.xclient.window,
5971 0, 0);
5973 goto done;
5976 if (event.xclient.data.l[0]
5977 == dpyinfo->Xatom_wm_delete_window)
5979 f = x_any_window_to_frame (dpyinfo,
5980 event.xclient.window);
5981 if (!f)
5982 goto OTHER; /* May be a dialog that is to be removed */
5984 inev.ie.kind = DELETE_WINDOW_EVENT;
5985 XSETFRAME (inev.ie.frame_or_window, f);
5986 goto done;
5989 goto done;
5992 if (event.xclient.message_type
5993 == dpyinfo->Xatom_wm_configure_denied)
5995 goto done;
5998 if (event.xclient.message_type
5999 == dpyinfo->Xatom_wm_window_moved)
6001 int new_x, new_y;
6002 f = x_window_to_frame (dpyinfo, event.xclient.window);
6004 new_x = event.xclient.data.s[0];
6005 new_y = event.xclient.data.s[1];
6007 if (f)
6009 f->left_pos = new_x;
6010 f->top_pos = new_y;
6012 goto done;
6015 #ifdef HACK_EDITRES
6016 if (event.xclient.message_type
6017 == dpyinfo->Xatom_editres)
6019 f = x_any_window_to_frame (dpyinfo, event.xclient.window);
6020 if (f)
6021 _XEditResCheckMessages (f->output_data.x->widget, NULL,
6022 &event, NULL);
6023 goto done;
6025 #endif /* HACK_EDITRES */
6027 if ((event.xclient.message_type
6028 == dpyinfo->Xatom_DONE)
6029 || (event.xclient.message_type
6030 == dpyinfo->Xatom_PAGE))
6032 /* Ghostview job completed. Kill it. We could
6033 reply with "Next" if we received "Page", but we
6034 currently never do because we are interested in
6035 images, only, which should have 1 page. */
6036 Pixmap pixmap = (Pixmap) event.xclient.data.l[1];
6037 f = x_window_to_frame (dpyinfo, event.xclient.window);
6038 if (!f)
6039 goto OTHER;
6040 x_kill_gs_process (pixmap, f);
6041 expose_frame (f, 0, 0, 0, 0);
6042 goto done;
6045 #ifdef USE_TOOLKIT_SCROLL_BARS
6046 /* Scroll bar callbacks send a ClientMessage from which
6047 we construct an input_event. */
6048 if (event.xclient.message_type
6049 == dpyinfo->Xatom_Scrollbar)
6051 x_scroll_bar_to_input_event (&event, &inev.ie);
6052 *finish = X_EVENT_GOTO_OUT;
6053 goto done;
6055 #endif /* USE_TOOLKIT_SCROLL_BARS */
6057 /* XEmbed messages from the embedder (if any). */
6058 if (event.xclient.message_type
6059 == dpyinfo->Xatom_XEMBED)
6061 enum xembed_message msg = event.xclient.data.l[1];
6062 if (msg == XEMBED_FOCUS_IN || msg == XEMBED_FOCUS_OUT)
6063 x_detect_focus_change (dpyinfo, &event, &inev.ie);
6065 *finish = X_EVENT_GOTO_OUT;
6066 goto done;
6069 xft_settings_event (dpyinfo, &event);
6071 f = x_any_window_to_frame (dpyinfo, event.xclient.window);
6072 if (!f)
6073 goto OTHER;
6074 if (x_handle_dnd_message (f, &event.xclient, dpyinfo, &inev.ie))
6075 *finish = X_EVENT_DROP;
6077 break;
6079 case SelectionNotify:
6080 last_user_time = event.xselection.time;
6081 #ifdef USE_X_TOOLKIT
6082 if (! x_window_to_frame (dpyinfo, event.xselection.requestor))
6083 goto OTHER;
6084 #endif /* not USE_X_TOOLKIT */
6085 x_handle_selection_notify (&event.xselection);
6086 break;
6088 case SelectionClear: /* Someone has grabbed ownership. */
6089 last_user_time = event.xselectionclear.time;
6090 #ifdef USE_X_TOOLKIT
6091 if (! x_window_to_frame (dpyinfo, event.xselectionclear.window))
6092 goto OTHER;
6093 #endif /* USE_X_TOOLKIT */
6095 XSelectionClearEvent *eventp = &(event.xselectionclear);
6097 inev.ie.kind = SELECTION_CLEAR_EVENT;
6098 SELECTION_EVENT_DISPLAY (&inev.sie) = eventp->display;
6099 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
6100 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
6101 inev.ie.frame_or_window = Qnil;
6103 break;
6105 case SelectionRequest: /* Someone wants our selection. */
6106 last_user_time = event.xselectionrequest.time;
6107 #ifdef USE_X_TOOLKIT
6108 if (!x_window_to_frame (dpyinfo, event.xselectionrequest.owner))
6109 goto OTHER;
6110 #endif /* USE_X_TOOLKIT */
6112 XSelectionRequestEvent *eventp = &(event.xselectionrequest);
6114 inev.ie.kind = SELECTION_REQUEST_EVENT;
6115 SELECTION_EVENT_DISPLAY (&inev.sie) = eventp->display;
6116 SELECTION_EVENT_REQUESTOR (&inev.sie) = eventp->requestor;
6117 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
6118 SELECTION_EVENT_TARGET (&inev.sie) = eventp->target;
6119 SELECTION_EVENT_PROPERTY (&inev.sie) = eventp->property;
6120 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
6121 inev.ie.frame_or_window = Qnil;
6123 break;
6125 case PropertyNotify:
6126 last_user_time = event.xproperty.time;
6127 f = x_top_window_to_frame (dpyinfo, event.xproperty.window);
6128 if (f && event.xproperty.atom == dpyinfo->Xatom_net_wm_state)
6129 if (x_handle_net_wm_state (f, &event.xproperty) && f->iconified
6130 && f->output_data.x->net_wm_state_hidden_seen)
6132 /* Gnome shell does not iconify us when C-z is pressed. It hides
6133 the frame. So if our state says we aren't hidden anymore,
6134 treat it as deiconified. */
6135 if (! f->async_iconified)
6136 SET_FRAME_GARBAGED (f);
6137 f->async_visible = 1;
6138 f->async_iconified = 0;
6139 f->output_data.x->has_been_visible = 1;
6140 f->output_data.x->net_wm_state_hidden_seen = 0;
6141 inev.ie.kind = DEICONIFY_EVENT;
6142 XSETFRAME (inev.ie.frame_or_window, f);
6145 x_handle_property_notify (&event.xproperty);
6146 xft_settings_event (dpyinfo, &event);
6147 goto OTHER;
6149 case ReparentNotify:
6150 f = x_top_window_to_frame (dpyinfo, event.xreparent.window);
6151 if (f)
6153 int x, y;
6154 f->output_data.x->parent_desc = event.xreparent.parent;
6155 x_real_positions (f, &x, &y);
6156 f->left_pos = x;
6157 f->top_pos = y;
6159 /* Perhaps reparented due to a WM restart. Reset this. */
6160 FRAME_X_DISPLAY_INFO (f)->wm_type = X_WMTYPE_UNKNOWN;
6161 FRAME_X_DISPLAY_INFO (f)->net_supported_window = 0;
6163 x_set_frame_alpha (f);
6165 goto OTHER;
6167 case Expose:
6168 f = x_window_to_frame (dpyinfo, event.xexpose.window);
6169 if (f)
6171 #ifdef USE_GTK
6172 /* This seems to be needed for GTK 2.6. */
6173 x_clear_area (event.xexpose.display,
6174 event.xexpose.window,
6175 event.xexpose.x, event.xexpose.y,
6176 event.xexpose.width, event.xexpose.height,
6177 FALSE);
6178 #endif
6179 if (f->async_visible == 0)
6181 f->async_visible = 1;
6182 f->async_iconified = 0;
6183 f->output_data.x->has_been_visible = 1;
6184 SET_FRAME_GARBAGED (f);
6186 else
6187 expose_frame (f,
6188 event.xexpose.x, event.xexpose.y,
6189 event.xexpose.width, event.xexpose.height);
6191 else
6193 #ifndef USE_TOOLKIT_SCROLL_BARS
6194 struct scroll_bar *bar;
6195 #endif
6196 #if defined USE_LUCID
6197 /* Submenus of the Lucid menu bar aren't widgets
6198 themselves, so there's no way to dispatch events
6199 to them. Recognize this case separately. */
6201 Widget widget
6202 = x_window_to_menu_bar (event.xexpose.window);
6203 if (widget)
6204 xlwmenu_redisplay (widget);
6206 #endif /* USE_LUCID */
6208 #ifdef USE_TOOLKIT_SCROLL_BARS
6209 /* Dispatch event to the widget. */
6210 goto OTHER;
6211 #else /* not USE_TOOLKIT_SCROLL_BARS */
6212 bar = x_window_to_scroll_bar (event.xexpose.display,
6213 event.xexpose.window);
6215 if (bar)
6216 x_scroll_bar_expose (bar, &event);
6217 #ifdef USE_X_TOOLKIT
6218 else
6219 goto OTHER;
6220 #endif /* USE_X_TOOLKIT */
6221 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6223 break;
6225 case GraphicsExpose: /* This occurs when an XCopyArea's
6226 source area was obscured or not
6227 available. */
6228 f = x_window_to_frame (dpyinfo, event.xgraphicsexpose.drawable);
6229 if (f)
6231 expose_frame (f,
6232 event.xgraphicsexpose.x, event.xgraphicsexpose.y,
6233 event.xgraphicsexpose.width,
6234 event.xgraphicsexpose.height);
6236 #ifdef USE_X_TOOLKIT
6237 else
6238 goto OTHER;
6239 #endif /* USE_X_TOOLKIT */
6240 break;
6242 case NoExpose: /* This occurs when an XCopyArea's
6243 source area was completely
6244 available. */
6245 break;
6247 case UnmapNotify:
6248 /* Redo the mouse-highlight after the tooltip has gone. */
6249 if (event.xmap.window == tip_window)
6251 tip_window = 0;
6252 redo_mouse_highlight ();
6255 f = x_top_window_to_frame (dpyinfo, event.xunmap.window);
6256 if (f) /* F may no longer exist if
6257 the frame was deleted. */
6259 /* While a frame is unmapped, display generation is
6260 disabled; you don't want to spend time updating a
6261 display that won't ever be seen. */
6262 f->async_visible = 0;
6263 /* We can't distinguish, from the event, whether the window
6264 has become iconified or invisible. So assume, if it
6265 was previously visible, than now it is iconified.
6266 But x_make_frame_invisible clears both
6267 the visible flag and the iconified flag;
6268 and that way, we know the window is not iconified now. */
6269 if (FRAME_VISIBLE_P (f) || FRAME_ICONIFIED_P (f))
6271 f->async_iconified = 1;
6273 inev.ie.kind = ICONIFY_EVENT;
6274 XSETFRAME (inev.ie.frame_or_window, f);
6277 goto OTHER;
6279 case MapNotify:
6280 if (event.xmap.window == tip_window)
6281 /* The tooltip has been drawn already. Avoid
6282 the SET_FRAME_GARBAGED below. */
6283 goto OTHER;
6285 /* We use x_top_window_to_frame because map events can
6286 come for sub-windows and they don't mean that the
6287 frame is visible. */
6288 f = x_top_window_to_frame (dpyinfo, event.xmap.window);
6289 if (f)
6291 /* wait_reading_process_output will notice this and update
6292 the frame's display structures.
6293 If we where iconified, we should not set garbaged,
6294 because that stops redrawing on Expose events. This looks
6295 bad if we are called from a recursive event loop
6296 (x_dispatch_event), for example when a dialog is up. */
6297 if (! f->async_iconified)
6298 SET_FRAME_GARBAGED (f);
6300 /* Check if fullscreen was specified before we where mapped the
6301 first time, i.e. from the command line. */
6302 if (!f->output_data.x->has_been_visible)
6303 x_check_fullscreen (f);
6305 f->async_visible = 1;
6306 f->async_iconified = 0;
6307 f->output_data.x->has_been_visible = 1;
6309 if (f->iconified)
6311 inev.ie.kind = DEICONIFY_EVENT;
6312 XSETFRAME (inev.ie.frame_or_window, f);
6314 else if (! NILP (Vframe_list)
6315 && ! NILP (XCDR (Vframe_list)))
6316 /* Force a redisplay sooner or later
6317 to update the frame titles
6318 in case this is the second frame. */
6319 record_asynch_buffer_change ();
6321 #ifdef USE_GTK
6322 xg_frame_resized (f, -1, -1);
6323 #endif
6325 goto OTHER;
6327 case KeyPress:
6329 last_user_time = event.xkey.time;
6330 ignore_next_mouse_click_timeout = 0;
6332 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
6333 /* Dispatch KeyPress events when in menu. */
6334 if (popup_activated ())
6335 goto OTHER;
6336 #endif
6338 f = x_any_window_to_frame (dpyinfo, event.xkey.window);
6340 /* If mouse-highlight is an integer, input clears out
6341 mouse highlighting. */
6342 if (!hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight)
6343 && (f == 0
6344 || !EQ (f->tool_bar_window, hlinfo->mouse_face_window)))
6346 clear_mouse_face (hlinfo);
6347 hlinfo->mouse_face_hidden = 1;
6350 #if defined USE_MOTIF && defined USE_TOOLKIT_SCROLL_BARS
6351 if (f == 0)
6353 /* Scroll bars consume key events, but we want
6354 the keys to go to the scroll bar's frame. */
6355 Widget widget = XtWindowToWidget (dpyinfo->display,
6356 event.xkey.window);
6357 if (widget && XmIsScrollBar (widget))
6359 widget = XtParent (widget);
6360 f = x_any_window_to_frame (dpyinfo, XtWindow (widget));
6363 #endif /* USE_MOTIF and USE_TOOLKIT_SCROLL_BARS */
6365 if (f != 0)
6367 KeySym keysym, orig_keysym;
6368 /* al%imercury@uunet.uu.net says that making this 81
6369 instead of 80 fixed a bug whereby meta chars made
6370 his Emacs hang.
6372 It seems that some version of XmbLookupString has
6373 a bug of not returning XBufferOverflow in
6374 status_return even if the input is too long to
6375 fit in 81 bytes. So, we must prepare sufficient
6376 bytes for copy_buffer. 513 bytes (256 chars for
6377 two-byte character set) seems to be a fairly good
6378 approximation. -- 2000.8.10 handa@etl.go.jp */
6379 unsigned char copy_buffer[513];
6380 unsigned char *copy_bufptr = copy_buffer;
6381 int copy_bufsiz = sizeof (copy_buffer);
6382 int modifiers;
6383 Lisp_Object coding_system = Qlatin_1;
6384 Lisp_Object c;
6386 #ifdef USE_GTK
6387 /* Don't pass keys to GTK. A Tab will shift focus to the
6388 tool bar in GTK 2.4. Keys will still go to menus and
6389 dialogs because in that case popup_activated is TRUE
6390 (see above). */
6391 *finish = X_EVENT_DROP;
6392 #endif
6394 event.xkey.state
6395 |= x_emacs_to_x_modifiers (FRAME_X_DISPLAY_INFO (f),
6396 extra_keyboard_modifiers);
6397 modifiers = event.xkey.state;
6399 /* This will have to go some day... */
6401 /* make_lispy_event turns chars into control chars.
6402 Don't do it here because XLookupString is too eager. */
6403 event.xkey.state &= ~ControlMask;
6404 event.xkey.state &= ~(dpyinfo->meta_mod_mask
6405 | dpyinfo->super_mod_mask
6406 | dpyinfo->hyper_mod_mask
6407 | dpyinfo->alt_mod_mask);
6409 /* In case Meta is ComposeCharacter,
6410 clear its status. According to Markus Ehrnsperger
6411 Markus.Ehrnsperger@lehrstuhl-bross.physik.uni-muenchen.de
6412 this enables ComposeCharacter to work whether or
6413 not it is combined with Meta. */
6414 if (modifiers & dpyinfo->meta_mod_mask)
6415 memset (&compose_status, 0, sizeof (compose_status));
6417 #ifdef HAVE_X_I18N
6418 if (FRAME_XIC (f))
6420 Status status_return;
6422 coding_system = Vlocale_coding_system;
6423 nbytes = XmbLookupString (FRAME_XIC (f),
6424 &event.xkey, (char *) copy_bufptr,
6425 copy_bufsiz, &keysym,
6426 &status_return);
6427 if (status_return == XBufferOverflow)
6429 copy_bufsiz = nbytes + 1;
6430 copy_bufptr = (unsigned char *) alloca (copy_bufsiz);
6431 nbytes = XmbLookupString (FRAME_XIC (f),
6432 &event.xkey, (char *) copy_bufptr,
6433 copy_bufsiz, &keysym,
6434 &status_return);
6436 /* Xutf8LookupString is a new but already deprecated interface. -stef */
6437 if (status_return == XLookupNone)
6438 break;
6439 else if (status_return == XLookupChars)
6441 keysym = NoSymbol;
6442 modifiers = 0;
6444 else if (status_return != XLookupKeySym
6445 && status_return != XLookupBoth)
6446 abort ();
6448 else
6449 nbytes = XLookupString (&event.xkey, (char *) copy_bufptr,
6450 copy_bufsiz, &keysym,
6451 &compose_status);
6452 #else
6453 nbytes = XLookupString (&event.xkey, (char *) copy_bufptr,
6454 copy_bufsiz, &keysym,
6455 &compose_status);
6456 #endif
6458 /* If not using XIM/XIC, and a compose sequence is in progress,
6459 we break here. Otherwise, chars_matched is always 0. */
6460 if (compose_status.chars_matched > 0 && nbytes == 0)
6461 break;
6463 memset (&compose_status, 0, sizeof (compose_status));
6464 orig_keysym = keysym;
6466 /* Common for all keysym input events. */
6467 XSETFRAME (inev.ie.frame_or_window, f);
6468 inev.ie.modifiers
6469 = x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO (f), modifiers);
6470 inev.ie.timestamp = event.xkey.time;
6472 /* First deal with keysyms which have defined
6473 translations to characters. */
6474 if (keysym >= 32 && keysym < 128)
6475 /* Avoid explicitly decoding each ASCII character. */
6477 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
6478 inev.ie.code = keysym;
6479 goto done_keysym;
6482 /* Keysyms directly mapped to Unicode characters. */
6483 if (keysym >= 0x01000000 && keysym <= 0x0110FFFF)
6485 if (keysym < 0x01000080)
6486 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
6487 else
6488 inev.ie.kind = MULTIBYTE_CHAR_KEYSTROKE_EVENT;
6489 inev.ie.code = keysym & 0xFFFFFF;
6490 goto done_keysym;
6493 /* Now non-ASCII. */
6494 if (HASH_TABLE_P (Vx_keysym_table)
6495 && (NATNUMP (c = Fgethash (make_number (keysym),
6496 Vx_keysym_table,
6497 Qnil))))
6499 inev.ie.kind = (SINGLE_BYTE_CHAR_P (XFASTINT (c))
6500 ? ASCII_KEYSTROKE_EVENT
6501 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
6502 inev.ie.code = XFASTINT (c);
6503 goto done_keysym;
6506 /* Random non-modifier sorts of keysyms. */
6507 if (((keysym >= XK_BackSpace && keysym <= XK_Escape)
6508 || keysym == XK_Delete
6509 #ifdef XK_ISO_Left_Tab
6510 || (keysym >= XK_ISO_Left_Tab
6511 && keysym <= XK_ISO_Enter)
6512 #endif
6513 || IsCursorKey (keysym) /* 0xff50 <= x < 0xff60 */
6514 || IsMiscFunctionKey (keysym) /* 0xff60 <= x < VARIES */
6515 #ifdef HPUX
6516 /* This recognizes the "extended function
6517 keys". It seems there's no cleaner way.
6518 Test IsModifierKey to avoid handling
6519 mode_switch incorrectly. */
6520 || (XK_Select <= keysym && keysym < XK_KP_Space)
6521 #endif
6522 #ifdef XK_dead_circumflex
6523 || orig_keysym == XK_dead_circumflex
6524 #endif
6525 #ifdef XK_dead_grave
6526 || orig_keysym == XK_dead_grave
6527 #endif
6528 #ifdef XK_dead_tilde
6529 || orig_keysym == XK_dead_tilde
6530 #endif
6531 #ifdef XK_dead_diaeresis
6532 || orig_keysym == XK_dead_diaeresis
6533 #endif
6534 #ifdef XK_dead_macron
6535 || orig_keysym == XK_dead_macron
6536 #endif
6537 #ifdef XK_dead_degree
6538 || orig_keysym == XK_dead_degree
6539 #endif
6540 #ifdef XK_dead_acute
6541 || orig_keysym == XK_dead_acute
6542 #endif
6543 #ifdef XK_dead_cedilla
6544 || orig_keysym == XK_dead_cedilla
6545 #endif
6546 #ifdef XK_dead_breve
6547 || orig_keysym == XK_dead_breve
6548 #endif
6549 #ifdef XK_dead_ogonek
6550 || orig_keysym == XK_dead_ogonek
6551 #endif
6552 #ifdef XK_dead_caron
6553 || orig_keysym == XK_dead_caron
6554 #endif
6555 #ifdef XK_dead_doubleacute
6556 || orig_keysym == XK_dead_doubleacute
6557 #endif
6558 #ifdef XK_dead_abovedot
6559 || orig_keysym == XK_dead_abovedot
6560 #endif
6561 || IsKeypadKey (keysym) /* 0xff80 <= x < 0xffbe */
6562 || IsFunctionKey (keysym) /* 0xffbe <= x < 0xffe1 */
6563 /* Any "vendor-specific" key is ok. */
6564 || (orig_keysym & (1 << 28))
6565 || (keysym != NoSymbol && nbytes == 0))
6566 && ! (IsModifierKey (orig_keysym)
6567 /* The symbols from XK_ISO_Lock
6568 to XK_ISO_Last_Group_Lock
6569 don't have real modifiers but
6570 should be treated similarly to
6571 Mode_switch by Emacs. */
6572 #if defined XK_ISO_Lock && defined XK_ISO_Last_Group_Lock
6573 || (XK_ISO_Lock <= orig_keysym
6574 && orig_keysym <= XK_ISO_Last_Group_Lock)
6575 #endif
6578 STORE_KEYSYM_FOR_DEBUG (keysym);
6579 /* make_lispy_event will convert this to a symbolic
6580 key. */
6581 inev.ie.kind = NON_ASCII_KEYSTROKE_EVENT;
6582 inev.ie.code = keysym;
6583 goto done_keysym;
6586 { /* Raw bytes, not keysym. */
6587 ptrdiff_t i;
6588 int nchars, len;
6590 for (i = 0, nchars = 0; i < nbytes; i++)
6592 if (ASCII_BYTE_P (copy_bufptr[i]))
6593 nchars++;
6594 STORE_KEYSYM_FOR_DEBUG (copy_bufptr[i]);
6597 if (nchars < nbytes)
6599 /* Decode the input data. */
6601 /* The input should be decoded with `coding_system'
6602 which depends on which X*LookupString function
6603 we used just above and the locale. */
6604 setup_coding_system (coding_system, &coding);
6605 coding.src_multibyte = 0;
6606 coding.dst_multibyte = 1;
6607 /* The input is converted to events, thus we can't
6608 handle composition. Anyway, there's no XIM that
6609 gives us composition information. */
6610 coding.common_flags &= ~CODING_ANNOTATION_MASK;
6612 SAFE_NALLOCA (coding.destination, MAX_MULTIBYTE_LENGTH,
6613 nbytes);
6614 coding.dst_bytes = MAX_MULTIBYTE_LENGTH * nbytes;
6615 coding.mode |= CODING_MODE_LAST_BLOCK;
6616 decode_coding_c_string (&coding, copy_bufptr, nbytes, Qnil);
6617 nbytes = coding.produced;
6618 nchars = coding.produced_char;
6619 copy_bufptr = coding.destination;
6622 /* Convert the input data to a sequence of
6623 character events. */
6624 for (i = 0; i < nbytes; i += len)
6626 int ch;
6627 if (nchars == nbytes)
6628 ch = copy_bufptr[i], len = 1;
6629 else
6630 ch = STRING_CHAR_AND_LENGTH (copy_bufptr + i, len);
6631 inev.ie.kind = (SINGLE_BYTE_CHAR_P (ch)
6632 ? ASCII_KEYSTROKE_EVENT
6633 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
6634 inev.ie.code = ch;
6635 kbd_buffer_store_event_hold (&inev.ie, hold_quit);
6638 count += nchars;
6640 inev.ie.kind = NO_EVENT; /* Already stored above. */
6642 if (keysym == NoSymbol)
6643 break;
6646 done_keysym:
6647 #ifdef HAVE_X_I18N
6648 /* Don't dispatch this event since XtDispatchEvent calls
6649 XFilterEvent, and two calls in a row may freeze the
6650 client. */
6651 break;
6652 #else
6653 goto OTHER;
6654 #endif
6656 case KeyRelease:
6657 last_user_time = event.xkey.time;
6658 #ifdef HAVE_X_I18N
6659 /* Don't dispatch this event since XtDispatchEvent calls
6660 XFilterEvent, and two calls in a row may freeze the
6661 client. */
6662 break;
6663 #else
6664 goto OTHER;
6665 #endif
6667 case EnterNotify:
6668 last_user_time = event.xcrossing.time;
6669 x_detect_focus_change (dpyinfo, &event, &inev.ie);
6671 f = x_any_window_to_frame (dpyinfo, event.xcrossing.window);
6673 if (f && x_mouse_click_focus_ignore_position)
6674 ignore_next_mouse_click_timeout = event.xmotion.time + 200;
6676 /* EnterNotify counts as mouse movement,
6677 so update things that depend on mouse position. */
6678 if (f && !f->output_data.x->hourglass_p)
6679 note_mouse_movement (f, &event.xmotion);
6680 #ifdef USE_GTK
6681 /* We may get an EnterNotify on the buttons in the toolbar. In that
6682 case we moved out of any highlighted area and need to note this. */
6683 if (!f && last_mouse_glyph_frame)
6684 note_mouse_movement (last_mouse_glyph_frame, &event.xmotion);
6685 #endif
6686 goto OTHER;
6688 case FocusIn:
6689 x_detect_focus_change (dpyinfo, &event, &inev.ie);
6690 goto OTHER;
6692 case LeaveNotify:
6693 last_user_time = event.xcrossing.time;
6694 x_detect_focus_change (dpyinfo, &event, &inev.ie);
6696 f = x_top_window_to_frame (dpyinfo, event.xcrossing.window);
6697 if (f)
6699 if (f == hlinfo->mouse_face_mouse_frame)
6701 /* If we move outside the frame, then we're
6702 certainly no longer on any text in the frame. */
6703 clear_mouse_face (hlinfo);
6704 hlinfo->mouse_face_mouse_frame = 0;
6707 /* Generate a nil HELP_EVENT to cancel a help-echo.
6708 Do it only if there's something to cancel.
6709 Otherwise, the startup message is cleared when
6710 the mouse leaves the frame. */
6711 if (any_help_event_p)
6712 do_help = -1;
6714 #ifdef USE_GTK
6715 /* See comment in EnterNotify above */
6716 else if (last_mouse_glyph_frame)
6717 note_mouse_movement (last_mouse_glyph_frame, &event.xmotion);
6718 #endif
6719 goto OTHER;
6721 case FocusOut:
6722 x_detect_focus_change (dpyinfo, &event, &inev.ie);
6723 goto OTHER;
6725 case MotionNotify:
6727 last_user_time = event.xmotion.time;
6728 previous_help_echo_string = help_echo_string;
6729 help_echo_string = Qnil;
6731 if (dpyinfo->grabbed && last_mouse_frame
6732 && FRAME_LIVE_P (last_mouse_frame))
6733 f = last_mouse_frame;
6734 else
6735 f = x_window_to_frame (dpyinfo, event.xmotion.window);
6737 if (hlinfo->mouse_face_hidden)
6739 hlinfo->mouse_face_hidden = 0;
6740 clear_mouse_face (hlinfo);
6743 #ifdef USE_GTK
6744 if (f && xg_event_is_for_scrollbar (f, &event))
6745 f = 0;
6746 #endif
6747 if (f)
6750 /* Generate SELECT_WINDOW_EVENTs when needed.
6751 Don't let popup menus influence things (bug#1261). */
6752 if (!NILP (Vmouse_autoselect_window) && !popup_activated ())
6754 Lisp_Object window;
6756 window = window_from_coordinates (f,
6757 event.xmotion.x, event.xmotion.y,
6758 0, 0);
6760 /* Window will be selected only when it is not selected now and
6761 last mouse movement event was not in it. Minibuffer window
6762 will be selected only when it is active. */
6763 if (WINDOWP (window)
6764 && !EQ (window, last_window)
6765 && !EQ (window, selected_window)
6766 /* For click-to-focus window managers
6767 create event iff we don't leave the
6768 selected frame. */
6769 && (focus_follows_mouse
6770 || (EQ (XWINDOW (window)->frame,
6771 XWINDOW (selected_window)->frame))))
6773 inev.ie.kind = SELECT_WINDOW_EVENT;
6774 inev.ie.frame_or_window = window;
6777 last_window=window;
6779 if (!note_mouse_movement (f, &event.xmotion))
6780 help_echo_string = previous_help_echo_string;
6782 else
6784 #ifndef USE_TOOLKIT_SCROLL_BARS
6785 struct scroll_bar *bar
6786 = x_window_to_scroll_bar (event.xmotion.display,
6787 event.xmotion.window);
6789 if (bar)
6790 x_scroll_bar_note_movement (bar, &event);
6791 #endif /* USE_TOOLKIT_SCROLL_BARS */
6793 /* If we move outside the frame, then we're
6794 certainly no longer on any text in the frame. */
6795 clear_mouse_face (hlinfo);
6798 /* If the contents of the global variable help_echo_string
6799 has changed, generate a HELP_EVENT. */
6800 if (!NILP (help_echo_string)
6801 || !NILP (previous_help_echo_string))
6802 do_help = 1;
6803 goto OTHER;
6806 case ConfigureNotify:
6807 f = x_top_window_to_frame (dpyinfo, event.xconfigure.window);
6808 #ifdef USE_GTK
6809 if (!f
6810 && (f = x_any_window_to_frame (dpyinfo, event.xconfigure.window))
6811 && event.xconfigure.window == FRAME_X_WINDOW (f))
6813 xg_frame_resized (f, event.xconfigure.width,
6814 event.xconfigure.height);
6815 f = 0;
6817 #endif
6818 if (f)
6820 #ifndef USE_X_TOOLKIT
6821 #ifndef USE_GTK
6822 int rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, event.xconfigure.height);
6823 int columns = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, event.xconfigure.width);
6825 /* In the toolkit version, change_frame_size
6826 is called by the code that handles resizing
6827 of the EmacsFrame widget. */
6829 /* Even if the number of character rows and columns has
6830 not changed, the font size may have changed, so we need
6831 to check the pixel dimensions as well. */
6832 if (columns != FRAME_COLS (f)
6833 || rows != FRAME_LINES (f)
6834 || event.xconfigure.width != FRAME_PIXEL_WIDTH (f)
6835 || event.xconfigure.height != FRAME_PIXEL_HEIGHT (f))
6837 change_frame_size (f, rows, columns, 0, 1, 0);
6838 SET_FRAME_GARBAGED (f);
6839 cancel_mouse_face (f);
6842 FRAME_PIXEL_WIDTH (f) = event.xconfigure.width;
6843 FRAME_PIXEL_HEIGHT (f) = event.xconfigure.height;
6844 #endif /* not USE_GTK */
6845 #endif
6847 #ifdef USE_GTK
6848 /* GTK creates windows but doesn't map them.
6849 Only get real positions when mapped. */
6850 if (FRAME_GTK_OUTER_WIDGET (f)
6851 && gtk_widget_get_mapped (FRAME_GTK_OUTER_WIDGET (f)))
6852 #endif
6854 x_real_positions (f, &f->left_pos, &f->top_pos);
6857 #ifdef HAVE_X_I18N
6858 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMStatusArea))
6859 xic_set_statusarea (f);
6860 #endif
6863 goto OTHER;
6865 case ButtonRelease:
6866 case ButtonPress:
6868 /* If we decide we want to generate an event to be seen
6869 by the rest of Emacs, we put it here. */
6870 int tool_bar_p = 0;
6872 memset (&compose_status, 0, sizeof (compose_status));
6873 last_mouse_glyph_frame = 0;
6874 last_user_time = event.xbutton.time;
6876 if (dpyinfo->grabbed
6877 && last_mouse_frame
6878 && FRAME_LIVE_P (last_mouse_frame))
6879 f = last_mouse_frame;
6880 else
6881 f = x_window_to_frame (dpyinfo, event.xbutton.window);
6883 #ifdef USE_GTK
6884 if (f && xg_event_is_for_scrollbar (f, &event))
6885 f = 0;
6886 #endif
6887 if (f)
6889 /* Is this in the tool-bar? */
6890 if (WINDOWP (f->tool_bar_window)
6891 && WINDOW_TOTAL_LINES (XWINDOW (f->tool_bar_window)))
6893 Lisp_Object window;
6894 int x = event.xbutton.x;
6895 int y = event.xbutton.y;
6897 window = window_from_coordinates (f, x, y, 0, 1);
6898 tool_bar_p = EQ (window, f->tool_bar_window);
6900 if (tool_bar_p && event.xbutton.button < 4)
6902 handle_tool_bar_click (f, x, y,
6903 event.xbutton.type == ButtonPress,
6904 x_x_to_emacs_modifiers (dpyinfo,
6905 event.xbutton.state));
6909 if (!tool_bar_p)
6910 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
6911 if (! popup_activated ())
6912 #endif
6914 if (ignore_next_mouse_click_timeout)
6916 if (event.type == ButtonPress
6917 && (int)(event.xbutton.time - ignore_next_mouse_click_timeout) > 0)
6919 ignore_next_mouse_click_timeout = 0;
6920 construct_mouse_click (&inev.ie, &event.xbutton, f);
6922 if (event.type == ButtonRelease)
6923 ignore_next_mouse_click_timeout = 0;
6925 else
6926 construct_mouse_click (&inev.ie, &event.xbutton, f);
6928 if (FRAME_X_EMBEDDED_P (f))
6929 xembed_send_message (f, event.xbutton.time,
6930 XEMBED_REQUEST_FOCUS, 0, 0, 0);
6932 else
6934 struct scroll_bar *bar
6935 = x_window_to_scroll_bar (event.xbutton.display,
6936 event.xbutton.window);
6938 #ifdef USE_TOOLKIT_SCROLL_BARS
6939 /* Make the "Ctrl-Mouse-2 splits window" work for toolkit
6940 scroll bars. */
6941 if (bar && event.xbutton.state & ControlMask)
6943 x_scroll_bar_handle_click (bar, &event, &inev.ie);
6944 *finish = X_EVENT_DROP;
6946 #else /* not USE_TOOLKIT_SCROLL_BARS */
6947 if (bar)
6948 x_scroll_bar_handle_click (bar, &event, &inev.ie);
6949 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6952 if (event.type == ButtonPress)
6954 dpyinfo->grabbed |= (1 << event.xbutton.button);
6955 last_mouse_frame = f;
6957 if (!tool_bar_p)
6958 last_tool_bar_item = -1;
6960 else
6961 dpyinfo->grabbed &= ~(1 << event.xbutton.button);
6963 /* Ignore any mouse motion that happened before this event;
6964 any subsequent mouse-movement Emacs events should reflect
6965 only motion after the ButtonPress/Release. */
6966 if (f != 0)
6967 f->mouse_moved = 0;
6969 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
6970 f = x_menubar_window_to_frame (dpyinfo, &event);
6971 /* For a down-event in the menu bar,
6972 don't pass it to Xt right now.
6973 Instead, save it away
6974 and we will pass it to Xt from kbd_buffer_get_event.
6975 That way, we can run some Lisp code first. */
6976 if (! popup_activated ()
6977 #ifdef USE_GTK
6978 /* Gtk+ menus only react to the first three buttons. */
6979 && event.xbutton.button < 3
6980 #endif
6981 && f && event.type == ButtonPress
6982 /* Verify the event is really within the menu bar
6983 and not just sent to it due to grabbing. */
6984 && event.xbutton.x >= 0
6985 && event.xbutton.x < FRAME_PIXEL_WIDTH (f)
6986 && event.xbutton.y >= 0
6987 && event.xbutton.y < f->output_data.x->menubar_height
6988 && event.xbutton.same_screen)
6990 SET_SAVED_BUTTON_EVENT;
6991 XSETFRAME (last_mouse_press_frame, f);
6992 *finish = X_EVENT_DROP;
6994 else if (event.type == ButtonPress)
6996 last_mouse_press_frame = Qnil;
6997 goto OTHER;
6999 else
7000 goto OTHER;
7001 #endif /* USE_X_TOOLKIT || USE_GTK */
7003 break;
7005 case CirculateNotify:
7006 goto OTHER;
7008 case CirculateRequest:
7009 goto OTHER;
7011 case VisibilityNotify:
7012 goto OTHER;
7014 case MappingNotify:
7015 /* Someone has changed the keyboard mapping - update the
7016 local cache. */
7017 switch (event.xmapping.request)
7019 case MappingModifier:
7020 x_find_modifier_meanings (dpyinfo);
7021 /* This is meant to fall through. */
7022 case MappingKeyboard:
7023 XRefreshKeyboardMapping (&event.xmapping);
7025 goto OTHER;
7027 case DestroyNotify:
7028 xft_settings_event (dpyinfo, &event);
7029 break;
7031 default:
7032 OTHER:
7033 #ifdef USE_X_TOOLKIT
7034 BLOCK_INPUT;
7035 if (*finish != X_EVENT_DROP)
7036 XtDispatchEvent (&event);
7037 UNBLOCK_INPUT;
7038 #endif /* USE_X_TOOLKIT */
7039 break;
7042 done:
7043 if (inev.ie.kind != NO_EVENT)
7045 kbd_buffer_store_event_hold (&inev.ie, hold_quit);
7046 count++;
7049 if (do_help
7050 && !(hold_quit && hold_quit->kind != NO_EVENT))
7052 Lisp_Object frame;
7054 if (f)
7055 XSETFRAME (frame, f);
7056 else
7057 frame = Qnil;
7059 if (do_help > 0)
7061 any_help_event_p = 1;
7062 gen_help_event (help_echo_string, frame, help_echo_window,
7063 help_echo_object, help_echo_pos);
7065 else
7067 help_echo_string = Qnil;
7068 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
7070 count++;
7073 SAFE_FREE ();
7074 *eventptr = event;
7075 return count;
7078 #if defined USE_GTK || defined USE_X_TOOLKIT
7080 /* Handles the XEvent EVENT on display DISPLAY.
7081 This is used for event loops outside the normal event handling,
7082 i.e. looping while a popup menu or a dialog is posted.
7084 Returns the value handle_one_xevent sets in the finish argument. */
7086 x_dispatch_event (XEvent *event, Display *display)
7088 struct x_display_info *dpyinfo;
7089 int finish = X_EVENT_NORMAL;
7091 dpyinfo = x_display_info_for_display (display);
7093 if (dpyinfo)
7094 handle_one_xevent (dpyinfo, event, &finish, 0);
7096 return finish;
7098 #endif
7101 /* Read events coming from the X server.
7102 This routine is called by the SIGIO handler only if SYNC_INPUT is
7103 not defined.
7104 We return as soon as there are no more events to be read.
7106 We return the number of characters stored into the buffer,
7107 thus pretending to be `read' (except the characters we store
7108 in the keyboard buffer can be multibyte, so are not necessarily
7109 C chars).
7111 EXPECTED is nonzero if the caller knows input is available. */
7113 static int
7114 XTread_socket (struct terminal *terminal, int expected, struct input_event *hold_quit)
7116 int count = 0;
7117 int event_found = 0;
7119 if (interrupt_input_blocked)
7121 interrupt_input_pending = 1;
7122 #ifdef SYNC_INPUT
7123 pending_signals = 1;
7124 #endif
7125 return -1;
7128 interrupt_input_pending = 0;
7129 #ifdef SYNC_INPUT
7130 pending_signals = pending_atimers;
7131 #endif
7132 BLOCK_INPUT;
7134 /* So people can tell when we have read the available input. */
7135 input_signal_count++;
7137 #ifndef SYNC_INPUT
7138 ++handling_signal;
7139 #endif
7141 /* For debugging, this gives a way to fake an I/O error. */
7142 if (terminal->display_info.x == XTread_socket_fake_io_error)
7144 XTread_socket_fake_io_error = 0;
7145 x_io_error_quitter (terminal->display_info.x->display);
7148 #ifndef USE_GTK
7149 while (XPending (terminal->display_info.x->display))
7151 int finish;
7152 XEvent event;
7154 XNextEvent (terminal->display_info.x->display, &event);
7156 #ifdef HAVE_X_I18N
7157 /* Filter events for the current X input method. */
7158 if (x_filter_event (terminal->display_info.x, &event))
7159 continue;
7160 #endif
7161 event_found = 1;
7163 count += handle_one_xevent (terminal->display_info.x,
7164 &event, &finish, hold_quit);
7166 if (finish == X_EVENT_GOTO_OUT)
7167 goto out;
7170 out:;
7172 #else /* USE_GTK */
7174 /* For GTK we must use the GTK event loop. But XEvents gets passed
7175 to our filter function above, and then to the big event switch.
7176 We use a bunch of globals to communicate with our filter function,
7177 that is kind of ugly, but it works.
7179 There is no way to do one display at the time, GTK just does events
7180 from all displays. */
7182 while (gtk_events_pending ())
7184 current_count = count;
7185 current_hold_quit = hold_quit;
7187 gtk_main_iteration ();
7189 count = current_count;
7190 current_count = -1;
7191 current_hold_quit = 0;
7193 if (current_finish == X_EVENT_GOTO_OUT)
7194 break;
7196 #endif /* USE_GTK */
7198 /* On some systems, an X bug causes Emacs to get no more events
7199 when the window is destroyed. Detect that. (1994.) */
7200 if (! event_found)
7202 /* Emacs and the X Server eats up CPU time if XNoOp is done every time.
7203 One XNOOP in 100 loops will make Emacs terminate.
7204 B. Bretthauer, 1994 */
7205 x_noop_count++;
7206 if (x_noop_count >= 100)
7208 x_noop_count=0;
7210 if (next_noop_dpyinfo == 0)
7211 next_noop_dpyinfo = x_display_list;
7213 XNoOp (next_noop_dpyinfo->display);
7215 /* Each time we get here, cycle through the displays now open. */
7216 next_noop_dpyinfo = next_noop_dpyinfo->next;
7220 /* If the focus was just given to an auto-raising frame,
7221 raise it now. */
7222 /* ??? This ought to be able to handle more than one such frame. */
7223 if (pending_autoraise_frame)
7225 x_raise_frame (pending_autoraise_frame);
7226 pending_autoraise_frame = 0;
7229 #ifndef SYNC_INPUT
7230 --handling_signal;
7231 #endif
7232 UNBLOCK_INPUT;
7234 return count;
7240 /***********************************************************************
7241 Text Cursor
7242 ***********************************************************************/
7244 /* Set clipping for output in glyph row ROW. W is the window in which
7245 we operate. GC is the graphics context to set clipping in.
7247 ROW may be a text row or, e.g., a mode line. Text rows must be
7248 clipped to the interior of the window dedicated to text display,
7249 mode lines must be clipped to the whole window. */
7251 static void
7252 x_clip_to_row (struct window *w, struct glyph_row *row, int area, GC gc)
7254 struct frame *f = XFRAME (WINDOW_FRAME (w));
7255 XRectangle clip_rect;
7256 int window_x, window_y, window_width;
7258 window_box (w, area, &window_x, &window_y, &window_width, 0);
7260 clip_rect.x = window_x;
7261 clip_rect.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
7262 clip_rect.y = max (clip_rect.y, window_y);
7263 clip_rect.width = window_width;
7264 clip_rect.height = row->visible_height;
7266 XSetClipRectangles (FRAME_X_DISPLAY (f), gc, 0, 0, &clip_rect, 1, Unsorted);
7270 /* Draw a hollow box cursor on window W in glyph row ROW. */
7272 static void
7273 x_draw_hollow_cursor (struct window *w, struct glyph_row *row)
7275 struct frame *f = XFRAME (WINDOW_FRAME (w));
7276 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
7277 Display *dpy = FRAME_X_DISPLAY (f);
7278 int x, y, wd, h;
7279 XGCValues xgcv;
7280 struct glyph *cursor_glyph;
7281 GC gc;
7283 /* Get the glyph the cursor is on. If we can't tell because
7284 the current matrix is invalid or such, give up. */
7285 cursor_glyph = get_phys_cursor_glyph (w);
7286 if (cursor_glyph == NULL)
7287 return;
7289 /* Compute frame-relative coordinates for phys cursor. */
7290 get_phys_cursor_geometry (w, row, cursor_glyph, &x, &y, &h);
7291 wd = w->phys_cursor_width;
7293 /* The foreground of cursor_gc is typically the same as the normal
7294 background color, which can cause the cursor box to be invisible. */
7295 xgcv.foreground = f->output_data.x->cursor_pixel;
7296 if (dpyinfo->scratch_cursor_gc)
7297 XChangeGC (dpy, dpyinfo->scratch_cursor_gc, GCForeground, &xgcv);
7298 else
7299 dpyinfo->scratch_cursor_gc = XCreateGC (dpy, FRAME_X_WINDOW (f),
7300 GCForeground, &xgcv);
7301 gc = dpyinfo->scratch_cursor_gc;
7303 /* Set clipping, draw the rectangle, and reset clipping again. */
7304 x_clip_to_row (w, row, TEXT_AREA, gc);
7305 XDrawRectangle (dpy, FRAME_X_WINDOW (f), gc, x, y, wd, h - 1);
7306 XSetClipMask (dpy, gc, None);
7310 /* Draw a bar cursor on window W in glyph row ROW.
7312 Implementation note: One would like to draw a bar cursor with an
7313 angle equal to the one given by the font property XA_ITALIC_ANGLE.
7314 Unfortunately, I didn't find a font yet that has this property set.
7315 --gerd. */
7317 static void
7318 x_draw_bar_cursor (struct window *w, struct glyph_row *row, int width, enum text_cursor_kinds kind)
7320 struct frame *f = XFRAME (w->frame);
7321 struct glyph *cursor_glyph;
7323 /* If cursor is out of bounds, don't draw garbage. This can happen
7324 in mini-buffer windows when switching between echo area glyphs
7325 and mini-buffer. */
7326 cursor_glyph = get_phys_cursor_glyph (w);
7327 if (cursor_glyph == NULL)
7328 return;
7330 /* If on an image, draw like a normal cursor. That's usually better
7331 visible than drawing a bar, esp. if the image is large so that
7332 the bar might not be in the window. */
7333 if (cursor_glyph->type == IMAGE_GLYPH)
7335 struct glyph_row *r;
7336 r = MATRIX_ROW (w->current_matrix, w->phys_cursor.vpos);
7337 draw_phys_cursor_glyph (w, r, DRAW_CURSOR);
7339 else
7341 Display *dpy = FRAME_X_DISPLAY (f);
7342 Window window = FRAME_X_WINDOW (f);
7343 GC gc = FRAME_X_DISPLAY_INFO (f)->scratch_cursor_gc;
7344 unsigned long mask = GCForeground | GCBackground | GCGraphicsExposures;
7345 struct face *face = FACE_FROM_ID (f, cursor_glyph->face_id);
7346 XGCValues xgcv;
7348 /* If the glyph's background equals the color we normally draw
7349 the bars cursor in, the bar cursor in its normal color is
7350 invisible. Use the glyph's foreground color instead in this
7351 case, on the assumption that the glyph's colors are chosen so
7352 that the glyph is legible. */
7353 if (face->background == f->output_data.x->cursor_pixel)
7354 xgcv.background = xgcv.foreground = face->foreground;
7355 else
7356 xgcv.background = xgcv.foreground = f->output_data.x->cursor_pixel;
7357 xgcv.graphics_exposures = 0;
7359 if (gc)
7360 XChangeGC (dpy, gc, mask, &xgcv);
7361 else
7363 gc = XCreateGC (dpy, window, mask, &xgcv);
7364 FRAME_X_DISPLAY_INFO (f)->scratch_cursor_gc = gc;
7367 x_clip_to_row (w, row, TEXT_AREA, gc);
7369 if (kind == BAR_CURSOR)
7371 int x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
7373 if (width < 0)
7374 width = FRAME_CURSOR_WIDTH (f);
7375 width = min (cursor_glyph->pixel_width, width);
7377 w->phys_cursor_width = width;
7379 /* If the character under cursor is R2L, draw the bar cursor
7380 on the right of its glyph, rather than on the left. */
7381 if ((cursor_glyph->resolved_level & 1) != 0)
7382 x += cursor_glyph->pixel_width - width;
7384 XFillRectangle (dpy, window, gc, x,
7385 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y),
7386 width, row->height);
7388 else
7390 int dummy_x, dummy_y, dummy_h;
7392 if (width < 0)
7393 width = row->height;
7395 width = min (row->height, width);
7397 get_phys_cursor_geometry (w, row, cursor_glyph, &dummy_x,
7398 &dummy_y, &dummy_h);
7400 XFillRectangle (dpy, window, gc,
7401 WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x),
7402 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y +
7403 row->height - width),
7404 w->phys_cursor_width, width);
7407 XSetClipMask (dpy, gc, None);
7412 /* RIF: Define cursor CURSOR on frame F. */
7414 static void
7415 x_define_frame_cursor (struct frame *f, Cursor cursor)
7417 if (!f->pointer_invisible
7418 && f->output_data.x->current_cursor != cursor)
7419 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), cursor);
7420 f->output_data.x->current_cursor = cursor;
7424 /* RIF: Clear area on frame F. */
7426 static void
7427 x_clear_frame_area (struct frame *f, int x, int y, int width, int height)
7429 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
7430 x, y, width, height, False);
7431 #ifdef USE_GTK
7432 /* Must queue a redraw, because scroll bars might have been cleared. */
7433 if (FRAME_GTK_WIDGET (f))
7434 gtk_widget_queue_draw (FRAME_GTK_WIDGET (f));
7435 #endif
7439 /* RIF: Draw cursor on window W. */
7441 static void
7442 x_draw_window_cursor (struct window *w, struct glyph_row *glyph_row, int x, int y, int cursor_type, int cursor_width, int on_p, int active_p)
7444 struct frame *f = XFRAME (WINDOW_FRAME (w));
7446 if (on_p)
7448 w->phys_cursor_type = cursor_type;
7449 w->phys_cursor_on_p = 1;
7451 if (glyph_row->exact_window_width_line_p
7452 && (glyph_row->reversed_p
7453 ? (w->phys_cursor.hpos < 0)
7454 : (w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])))
7456 glyph_row->cursor_in_fringe_p = 1;
7457 draw_fringe_bitmap (w, glyph_row, glyph_row->reversed_p);
7459 else
7461 switch (cursor_type)
7463 case HOLLOW_BOX_CURSOR:
7464 x_draw_hollow_cursor (w, glyph_row);
7465 break;
7467 case FILLED_BOX_CURSOR:
7468 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
7469 break;
7471 case BAR_CURSOR:
7472 x_draw_bar_cursor (w, glyph_row, cursor_width, BAR_CURSOR);
7473 break;
7475 case HBAR_CURSOR:
7476 x_draw_bar_cursor (w, glyph_row, cursor_width, HBAR_CURSOR);
7477 break;
7479 case NO_CURSOR:
7480 w->phys_cursor_width = 0;
7481 break;
7483 default:
7484 abort ();
7488 #ifdef HAVE_X_I18N
7489 if (w == XWINDOW (f->selected_window))
7490 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMPreeditPosition))
7491 xic_set_preeditarea (w, x, y);
7492 #endif
7495 #ifndef XFlush
7496 XFlush (FRAME_X_DISPLAY (f));
7497 #endif
7501 /* Icons. */
7503 /* Make the x-window of frame F use the gnu icon bitmap. */
7506 x_bitmap_icon (struct frame *f, Lisp_Object file)
7508 ptrdiff_t bitmap_id;
7510 if (FRAME_X_WINDOW (f) == 0)
7511 return 1;
7513 /* Free up our existing icon bitmap and mask if any. */
7514 if (f->output_data.x->icon_bitmap > 0)
7515 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
7516 f->output_data.x->icon_bitmap = 0;
7518 if (STRINGP (file))
7520 #ifdef USE_GTK
7521 /* Use gtk_window_set_icon_from_file () if available,
7522 It's not restricted to bitmaps */
7523 if (xg_set_icon (f, file))
7524 return 0;
7525 #endif /* USE_GTK */
7526 bitmap_id = x_create_bitmap_from_file (f, file);
7527 x_create_bitmap_mask (f, bitmap_id);
7529 else
7531 /* Create the GNU bitmap and mask if necessary. */
7532 if (FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id < 0)
7534 ptrdiff_t rc = -1;
7536 #ifdef USE_GTK
7538 if (xg_set_icon (f, xg_default_icon_file)
7539 || xg_set_icon_from_xpm_data (f, gnu_xpm_bits))
7540 return 0;
7542 #elif defined (HAVE_XPM) && defined (HAVE_X_WINDOWS)
7544 rc = x_create_bitmap_from_xpm_data (f, gnu_xpm_bits);
7545 if (rc != -1)
7546 FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id = rc;
7548 #endif
7550 /* If all else fails, use the (black and white) xbm image. */
7551 if (rc == -1)
7553 rc = x_create_bitmap_from_data (f, (char *) gnu_xbm_bits,
7554 gnu_xbm_width, gnu_xbm_height);
7555 if (rc == -1)
7556 return 1;
7558 FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id = rc;
7559 x_create_bitmap_mask (f, FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id);
7563 /* The first time we create the GNU bitmap and mask,
7564 this increments the ref-count one extra time.
7565 As a result, the GNU bitmap and mask are never freed.
7566 That way, we don't have to worry about allocating it again. */
7567 x_reference_bitmap (f, FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id);
7569 bitmap_id = FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id;
7572 x_wm_set_icon_pixmap (f, bitmap_id);
7573 f->output_data.x->icon_bitmap = bitmap_id;
7575 return 0;
7579 /* Make the x-window of frame F use a rectangle with text.
7580 Use ICON_NAME as the text. */
7583 x_text_icon (struct frame *f, const char *icon_name)
7585 if (FRAME_X_WINDOW (f) == 0)
7586 return 1;
7589 XTextProperty text;
7590 text.value = (unsigned char *) icon_name;
7591 text.encoding = XA_STRING;
7592 text.format = 8;
7593 text.nitems = strlen (icon_name);
7594 XSetWMIconName (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f), &text);
7597 if (f->output_data.x->icon_bitmap > 0)
7598 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
7599 f->output_data.x->icon_bitmap = 0;
7600 x_wm_set_icon_pixmap (f, 0);
7602 return 0;
7605 #define X_ERROR_MESSAGE_SIZE 200
7607 /* If non-nil, this should be a string.
7608 It means catch X errors and store the error message in this string.
7610 The reason we use a stack is that x_catch_error/x_uncatch_error can
7611 be called from a signal handler.
7614 struct x_error_message_stack {
7615 char string[X_ERROR_MESSAGE_SIZE];
7616 Display *dpy;
7617 struct x_error_message_stack *prev;
7619 static struct x_error_message_stack *x_error_message;
7621 /* An X error handler which stores the error message in
7622 *x_error_message. This is called from x_error_handler if
7623 x_catch_errors is in effect. */
7625 static void
7626 x_error_catcher (Display *display, XErrorEvent *event)
7628 XGetErrorText (display, event->error_code,
7629 x_error_message->string,
7630 X_ERROR_MESSAGE_SIZE);
7633 /* Begin trapping X errors for display DPY. Actually we trap X errors
7634 for all displays, but DPY should be the display you are actually
7635 operating on.
7637 After calling this function, X protocol errors no longer cause
7638 Emacs to exit; instead, they are recorded in the string
7639 stored in *x_error_message.
7641 Calling x_check_errors signals an Emacs error if an X error has
7642 occurred since the last call to x_catch_errors or x_check_errors.
7644 Calling x_uncatch_errors resumes the normal error handling. */
7646 void
7647 x_catch_errors (Display *dpy)
7649 struct x_error_message_stack *data = xmalloc (sizeof (*data));
7651 /* Make sure any errors from previous requests have been dealt with. */
7652 XSync (dpy, False);
7654 data->dpy = dpy;
7655 data->string[0] = 0;
7656 data->prev = x_error_message;
7657 x_error_message = data;
7660 /* Undo the last x_catch_errors call.
7661 DPY should be the display that was passed to x_catch_errors. */
7663 void
7664 x_uncatch_errors (void)
7666 struct x_error_message_stack *tmp;
7668 BLOCK_INPUT;
7670 /* The display may have been closed before this function is called.
7671 Check if it is still open before calling XSync. */
7672 if (x_display_info_for_display (x_error_message->dpy) != 0)
7673 XSync (x_error_message->dpy, False);
7675 tmp = x_error_message;
7676 x_error_message = x_error_message->prev;
7677 xfree (tmp);
7678 UNBLOCK_INPUT;
7681 /* If any X protocol errors have arrived since the last call to
7682 x_catch_errors or x_check_errors, signal an Emacs error using
7683 sprintf (a buffer, FORMAT, the x error message text) as the text. */
7685 void
7686 x_check_errors (Display *dpy, const char *format)
7688 /* Make sure to catch any errors incurred so far. */
7689 XSync (dpy, False);
7691 if (x_error_message->string[0])
7693 char string[X_ERROR_MESSAGE_SIZE];
7694 memcpy (string, x_error_message->string, X_ERROR_MESSAGE_SIZE);
7695 x_uncatch_errors ();
7696 error (format, string);
7700 /* Nonzero if we had any X protocol errors
7701 since we did x_catch_errors on DPY. */
7704 x_had_errors_p (Display *dpy)
7706 /* Make sure to catch any errors incurred so far. */
7707 XSync (dpy, False);
7709 return x_error_message->string[0] != 0;
7712 /* Forget about any errors we have had, since we did x_catch_errors on DPY. */
7714 void
7715 x_clear_errors (Display *dpy)
7717 x_error_message->string[0] = 0;
7720 #if 0 /* See comment in unwind_to_catch why calling this is a bad
7721 * idea. --lorentey */
7722 /* Close off all unclosed x_catch_errors calls. */
7724 void
7725 x_fully_uncatch_errors (void)
7727 while (x_error_message)
7728 x_uncatch_errors ();
7730 #endif
7732 #if 0
7733 static unsigned int x_wire_count;
7734 x_trace_wire (void)
7736 fprintf (stderr, "Lib call: %d\n", ++x_wire_count);
7738 #endif /* ! 0 */
7741 /* Handle SIGPIPE, which can happen when the connection to a server
7742 simply goes away. SIGPIPE is handled by x_connection_signal.
7743 Don't need to do anything, because the write which caused the
7744 SIGPIPE will fail, causing Xlib to invoke the X IO error handler,
7745 which will do the appropriate cleanup for us. */
7747 static void
7748 x_connection_signal (int signalnum) /* If we don't have an argument, */
7749 /* some compilers complain in signal calls. */
7751 #ifdef USG
7752 /* USG systems forget handlers when they are used;
7753 must reestablish each time */
7754 signal (signalnum, x_connection_signal);
7755 #endif /* USG */
7759 /************************************************************************
7760 Handling X errors
7761 ************************************************************************/
7763 /* Error message passed to x_connection_closed. */
7765 static char *error_msg;
7767 /* Handle the loss of connection to display DPY. ERROR_MESSAGE is
7768 the text of an error message that lead to the connection loss. */
7770 static void
7771 x_connection_closed (Display *dpy, const char *error_message)
7773 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
7774 Lisp_Object frame, tail;
7775 int idx = SPECPDL_INDEX ();
7777 error_msg = (char *) alloca (strlen (error_message) + 1);
7778 strcpy (error_msg, error_message);
7779 handling_signal = 0;
7781 /* Inhibit redisplay while frames are being deleted. */
7782 specbind (Qinhibit_redisplay, Qt);
7784 if (dpyinfo)
7786 /* Protect display from being closed when we delete the last
7787 frame on it. */
7788 dpyinfo->reference_count++;
7789 dpyinfo->terminal->reference_count++;
7792 /* First delete frames whose mini-buffers are on frames
7793 that are on the dead display. */
7794 FOR_EACH_FRAME (tail, frame)
7796 Lisp_Object minibuf_frame;
7797 minibuf_frame
7798 = WINDOW_FRAME (XWINDOW (FRAME_MINIBUF_WINDOW (XFRAME (frame))));
7799 if (FRAME_X_P (XFRAME (frame))
7800 && FRAME_X_P (XFRAME (minibuf_frame))
7801 && ! EQ (frame, minibuf_frame)
7802 && FRAME_X_DISPLAY_INFO (XFRAME (minibuf_frame)) == dpyinfo)
7803 delete_frame (frame, Qnoelisp);
7806 /* Now delete all remaining frames on the dead display.
7807 We are now sure none of these is used as the mini-buffer
7808 for another frame that we need to delete. */
7809 FOR_EACH_FRAME (tail, frame)
7810 if (FRAME_X_P (XFRAME (frame))
7811 && FRAME_X_DISPLAY_INFO (XFRAME (frame)) == dpyinfo)
7813 /* Set this to t so that delete_frame won't get confused
7814 trying to find a replacement. */
7815 KVAR (FRAME_KBOARD (XFRAME (frame)), Vdefault_minibuffer_frame) = Qt;
7816 delete_frame (frame, Qnoelisp);
7819 /* If DPYINFO is null, this means we didn't open the display in the
7820 first place, so don't try to close it. */
7821 if (dpyinfo)
7823 /* We can not call XtCloseDisplay here because it calls XSync.
7824 XSync inside the error handler apparently hangs Emacs. On
7825 current Xt versions, this isn't needed either. */
7826 #ifdef USE_GTK
7827 /* A long-standing GTK bug prevents proper disconnect handling
7828 (https://bugzilla.gnome.org/show_bug.cgi?id=85715). Once,
7829 the resulting Glib error message loop filled a user's disk.
7830 To avoid this, kill Emacs unconditionally on disconnect. */
7831 shut_down_emacs (0, 0, Qnil);
7832 fprintf (stderr, "%s\n\
7833 When compiled with GTK, Emacs cannot recover from X disconnects.\n\
7834 This is a GTK bug: https://bugzilla.gnome.org/show_bug.cgi?id=85715\n\
7835 For details, see etc/PROBLEMS.\n",
7836 error_msg);
7837 abort ();
7838 #endif /* USE_GTK */
7840 /* Indicate that this display is dead. */
7841 dpyinfo->display = 0;
7843 dpyinfo->reference_count--;
7844 dpyinfo->terminal->reference_count--;
7845 if (dpyinfo->reference_count != 0)
7846 /* We have just closed all frames on this display. */
7847 abort ();
7850 Lisp_Object tmp;
7851 XSETTERMINAL (tmp, dpyinfo->terminal);
7852 Fdelete_terminal (tmp, Qnoelisp);
7856 if (terminal_list == 0)
7858 fprintf (stderr, "%s\n", error_msg);
7859 Fkill_emacs (make_number (70));
7860 /* NOTREACHED */
7863 /* Ordinary stack unwind doesn't deal with these. */
7864 #ifdef SIGIO
7865 sigunblock (sigmask (SIGIO));
7866 #endif
7867 sigunblock (sigmask (SIGALRM));
7868 TOTALLY_UNBLOCK_INPUT;
7870 unbind_to (idx, Qnil);
7871 clear_waiting_for_input ();
7873 /* Tell GCC not to suggest attribute 'noreturn' for this function. */
7874 IF_LINT (if (! terminal_list) return; )
7876 /* Here, we absolutely have to use a non-local exit (e.g. signal, throw,
7877 longjmp), because returning from this function would get us back into
7878 Xlib's code which will directly call `exit'. */
7879 error ("%s", error_msg);
7882 /* We specifically use it before defining it, so that gcc doesn't inline it,
7883 otherwise gdb doesn't know how to properly put a breakpoint on it. */
7884 static void x_error_quitter (Display *, XErrorEvent *);
7886 /* This is the first-level handler for X protocol errors.
7887 It calls x_error_quitter or x_error_catcher. */
7889 static int
7890 x_error_handler (Display *display, XErrorEvent *event)
7892 #ifdef HAVE_GTK3
7893 if (event->error_code == BadMatch
7894 && event->request_code == X_SetInputFocus
7895 && event->minor_code == 0)
7897 return 0;
7899 #endif
7901 if (x_error_message)
7902 x_error_catcher (display, event);
7903 else
7904 x_error_quitter (display, event);
7905 return 0;
7908 /* This is the usual handler for X protocol errors.
7909 It kills all frames on the display that we got the error for.
7910 If that was the only one, it prints an error message and kills Emacs. */
7912 /* .gdbinit puts a breakpoint here, so make sure it is not inlined. */
7914 /* On older GCC versions, just putting x_error_quitter
7915 after x_error_handler prevents inlining into the former. */
7917 static void NO_INLINE
7918 x_error_quitter (Display *display, XErrorEvent *event)
7920 char buf[256], buf1[356];
7922 /* Ignore BadName errors. They can happen because of fonts
7923 or colors that are not defined. */
7925 if (event->error_code == BadName)
7926 return;
7928 /* Note that there is no real way portable across R3/R4 to get the
7929 original error handler. */
7931 XGetErrorText (display, event->error_code, buf, sizeof (buf));
7932 sprintf (buf1, "X protocol error: %s on protocol request %d",
7933 buf, event->request_code);
7934 x_connection_closed (display, buf1);
7938 /* This is the handler for X IO errors, always.
7939 It kills all frames on the display that we lost touch with.
7940 If that was the only one, it prints an error message and kills Emacs. */
7942 static int
7943 x_io_error_quitter (Display *display)
7945 char buf[256];
7947 snprintf (buf, sizeof buf, "Connection lost to X server `%s'",
7948 DisplayString (display));
7949 x_connection_closed (display, buf);
7950 return 0;
7953 /* Changing the font of the frame. */
7955 /* Give frame F the font FONT-OBJECT as its default font. The return
7956 value is FONT-OBJECT. FONTSET is an ID of the fontset for the
7957 frame. If it is negative, generate a new fontset from
7958 FONT-OBJECT. */
7960 Lisp_Object
7961 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
7963 struct font *font = XFONT_OBJECT (font_object);
7965 if (fontset < 0)
7966 fontset = fontset_from_font (font_object);
7967 FRAME_FONTSET (f) = fontset;
7968 if (FRAME_FONT (f) == font)
7969 /* This font is already set in frame F. There's nothing more to
7970 do. */
7971 return font_object;
7973 FRAME_FONT (f) = font;
7974 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
7975 FRAME_COLUMN_WIDTH (f) = font->average_width;
7976 FRAME_SPACE_WIDTH (f) = font->space_width;
7977 FRAME_LINE_HEIGHT (f) = FONT_HEIGHT (font);
7979 compute_fringe_widths (f, 1);
7981 /* Compute the scroll bar width in character columns. */
7982 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
7984 int wid = FRAME_COLUMN_WIDTH (f);
7985 FRAME_CONFIG_SCROLL_BAR_COLS (f)
7986 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid-1) / wid;
7988 else
7990 int wid = FRAME_COLUMN_WIDTH (f);
7991 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
7994 if (FRAME_X_WINDOW (f) != 0)
7996 /* Don't change the size of a tip frame; there's no point in
7997 doing it because it's done in Fx_show_tip, and it leads to
7998 problems because the tip frame has no widget. */
7999 if (NILP (tip_frame) || XFRAME (tip_frame) != f)
8000 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
8003 #ifdef HAVE_X_I18N
8004 if (FRAME_XIC (f)
8005 && (FRAME_XIC_STYLE (f) & (XIMPreeditPosition | XIMStatusArea)))
8007 BLOCK_INPUT;
8008 xic_set_xfontset (f, SSDATA (fontset_ascii (fontset)));
8009 UNBLOCK_INPUT;
8011 #endif
8013 return font_object;
8017 /***********************************************************************
8018 X Input Methods
8019 ***********************************************************************/
8021 #ifdef HAVE_X_I18N
8023 #ifdef HAVE_X11R6
8025 /* XIM destroy callback function, which is called whenever the
8026 connection to input method XIM dies. CLIENT_DATA contains a
8027 pointer to the x_display_info structure corresponding to XIM. */
8029 static void
8030 xim_destroy_callback (XIM xim, XPointer client_data, XPointer call_data)
8032 struct x_display_info *dpyinfo = (struct x_display_info *) client_data;
8033 Lisp_Object frame, tail;
8035 BLOCK_INPUT;
8037 /* No need to call XDestroyIC.. */
8038 FOR_EACH_FRAME (tail, frame)
8040 struct frame *f = XFRAME (frame);
8041 if (FRAME_X_P (f) && FRAME_X_DISPLAY_INFO (f) == dpyinfo)
8043 FRAME_XIC (f) = NULL;
8044 xic_free_xfontset (f);
8048 /* No need to call XCloseIM. */
8049 dpyinfo->xim = NULL;
8050 XFree (dpyinfo->xim_styles);
8051 UNBLOCK_INPUT;
8054 #endif /* HAVE_X11R6 */
8056 #ifdef HAVE_X11R6
8057 /* This isn't prototyped in OSF 5.0 or 5.1a. */
8058 extern char *XSetIMValues (XIM, ...);
8059 #endif
8061 /* Open the connection to the XIM server on display DPYINFO.
8062 RESOURCE_NAME is the resource name Emacs uses. */
8064 static void
8065 xim_open_dpy (struct x_display_info *dpyinfo, char *resource_name)
8067 XIM xim;
8069 #ifdef HAVE_XIM
8070 if (use_xim)
8072 if (dpyinfo->xim)
8073 XCloseIM (dpyinfo->xim);
8074 xim = XOpenIM (dpyinfo->display, dpyinfo->xrdb, resource_name,
8075 emacs_class);
8076 dpyinfo->xim = xim;
8078 if (xim)
8080 #ifdef HAVE_X11R6
8081 XIMCallback destroy;
8082 #endif
8084 /* Get supported styles and XIM values. */
8085 XGetIMValues (xim, XNQueryInputStyle, &dpyinfo->xim_styles, NULL);
8087 #ifdef HAVE_X11R6
8088 destroy.callback = xim_destroy_callback;
8089 destroy.client_data = (XPointer)dpyinfo;
8090 XSetIMValues (xim, XNDestroyCallback, &destroy, NULL);
8091 #endif
8095 else
8096 #endif /* HAVE_XIM */
8097 dpyinfo->xim = NULL;
8101 #ifdef HAVE_X11R6_XIM
8103 /* XIM instantiate callback function, which is called whenever an XIM
8104 server is available. DISPLAY is the display of the XIM.
8105 CLIENT_DATA contains a pointer to an xim_inst_t structure created
8106 when the callback was registered. */
8108 static void
8109 xim_instantiate_callback (Display *display, XPointer client_data, XPointer call_data)
8111 struct xim_inst_t *xim_inst = (struct xim_inst_t *) client_data;
8112 struct x_display_info *dpyinfo = xim_inst->dpyinfo;
8114 /* We don't support multiple XIM connections. */
8115 if (dpyinfo->xim)
8116 return;
8118 xim_open_dpy (dpyinfo, xim_inst->resource_name);
8120 /* Create XIC for the existing frames on the same display, as long
8121 as they have no XIC. */
8122 if (dpyinfo->xim && dpyinfo->reference_count > 0)
8124 Lisp_Object tail, frame;
8126 BLOCK_INPUT;
8127 FOR_EACH_FRAME (tail, frame)
8129 struct frame *f = XFRAME (frame);
8131 if (FRAME_X_P (f)
8132 && FRAME_X_DISPLAY_INFO (f) == xim_inst->dpyinfo)
8133 if (FRAME_XIC (f) == NULL)
8135 create_frame_xic (f);
8136 if (FRAME_XIC_STYLE (f) & XIMStatusArea)
8137 xic_set_statusarea (f);
8138 if (FRAME_XIC_STYLE (f) & XIMPreeditPosition)
8140 struct window *w = XWINDOW (f->selected_window);
8141 xic_set_preeditarea (w, w->cursor.x, w->cursor.y);
8146 UNBLOCK_INPUT;
8150 #endif /* HAVE_X11R6_XIM */
8153 /* Open a connection to the XIM server on display DPYINFO.
8154 RESOURCE_NAME is the resource name for Emacs. On X11R5, open the
8155 connection only at the first time. On X11R6, open the connection
8156 in the XIM instantiate callback function. */
8158 static void
8159 xim_initialize (struct x_display_info *dpyinfo, char *resource_name)
8161 dpyinfo->xim = NULL;
8162 #ifdef HAVE_XIM
8163 if (use_xim)
8165 #ifdef HAVE_X11R6_XIM
8166 struct xim_inst_t *xim_inst;
8167 ptrdiff_t len;
8169 xim_inst = (struct xim_inst_t *) xmalloc (sizeof (struct xim_inst_t));
8170 dpyinfo->xim_callback_data = xim_inst;
8171 xim_inst->dpyinfo = dpyinfo;
8172 len = strlen (resource_name);
8173 xim_inst->resource_name = (char *) xmalloc (len + 1);
8174 memcpy (xim_inst->resource_name, resource_name, len + 1);
8175 XRegisterIMInstantiateCallback (dpyinfo->display, dpyinfo->xrdb,
8176 resource_name, emacs_class,
8177 xim_instantiate_callback,
8178 /* This is XPointer in XFree86
8179 but (XPointer *) on Tru64, at
8180 least, hence the configure test. */
8181 (XRegisterIMInstantiateCallback_arg6) xim_inst);
8182 #else /* not HAVE_X11R6_XIM */
8183 xim_open_dpy (dpyinfo, resource_name);
8184 #endif /* not HAVE_X11R6_XIM */
8186 #endif /* HAVE_XIM */
8190 /* Close the connection to the XIM server on display DPYINFO. */
8192 static void
8193 xim_close_dpy (struct x_display_info *dpyinfo)
8195 #ifdef HAVE_XIM
8196 if (use_xim)
8198 #ifdef HAVE_X11R6_XIM
8199 if (dpyinfo->display)
8200 XUnregisterIMInstantiateCallback (dpyinfo->display, dpyinfo->xrdb,
8201 NULL, emacs_class,
8202 xim_instantiate_callback, NULL);
8203 xfree (dpyinfo->xim_callback_data->resource_name);
8204 xfree (dpyinfo->xim_callback_data);
8205 #endif /* HAVE_X11R6_XIM */
8206 if (dpyinfo->display)
8207 XCloseIM (dpyinfo->xim);
8208 dpyinfo->xim = NULL;
8209 XFree (dpyinfo->xim_styles);
8211 #endif /* HAVE_XIM */
8214 #endif /* not HAVE_X11R6_XIM */
8218 /* Calculate the absolute position in frame F
8219 from its current recorded position values and gravity. */
8221 static void
8222 x_calc_absolute_position (struct frame *f)
8224 int flags = f->size_hint_flags;
8226 /* We have nothing to do if the current position
8227 is already for the top-left corner. */
8228 if (! ((flags & XNegative) || (flags & YNegative)))
8229 return;
8231 /* Treat negative positions as relative to the leftmost bottommost
8232 position that fits on the screen. */
8233 if (flags & XNegative)
8234 f->left_pos = x_display_pixel_width (FRAME_X_DISPLAY_INFO (f))
8235 - FRAME_PIXEL_WIDTH (f) + f->left_pos;
8238 int height = FRAME_PIXEL_HEIGHT (f);
8240 #if defined USE_X_TOOLKIT && defined USE_MOTIF
8241 /* Something is fishy here. When using Motif, starting Emacs with
8242 `-g -0-0', the frame appears too low by a few pixels.
8244 This seems to be so because initially, while Emacs is starting,
8245 the column widget's height and the frame's pixel height are
8246 different. The column widget's height is the right one. In
8247 later invocations, when Emacs is up, the frame's pixel height
8248 is right, though.
8250 It's not obvious where the initial small difference comes from.
8251 2000-12-01, gerd. */
8253 XtVaGetValues (f->output_data.x->column_widget, XtNheight, &height, NULL);
8254 #endif
8256 if (flags & YNegative)
8257 f->top_pos = x_display_pixel_height (FRAME_X_DISPLAY_INFO (f))
8258 - height + f->top_pos;
8261 /* The left_pos and top_pos
8262 are now relative to the top and left screen edges,
8263 so the flags should correspond. */
8264 f->size_hint_flags &= ~ (XNegative | YNegative);
8267 /* CHANGE_GRAVITY is 1 when calling from Fset_frame_position,
8268 to really change the position, and 0 when calling from
8269 x_make_frame_visible (in that case, XOFF and YOFF are the current
8270 position values). It is -1 when calling from x_set_frame_parameters,
8271 which means, do adjust for borders but don't change the gravity. */
8273 void
8274 x_set_offset (struct frame *f, register int xoff, register int yoff, int change_gravity)
8276 int modified_top, modified_left;
8278 if (change_gravity > 0)
8280 FRAME_X_OUTPUT (f)->left_before_move = f->left_pos;
8281 FRAME_X_OUTPUT (f)->top_before_move = f->top_pos;
8283 f->top_pos = yoff;
8284 f->left_pos = xoff;
8285 f->size_hint_flags &= ~ (XNegative | YNegative);
8286 if (xoff < 0)
8287 f->size_hint_flags |= XNegative;
8288 if (yoff < 0)
8289 f->size_hint_flags |= YNegative;
8290 f->win_gravity = NorthWestGravity;
8292 x_calc_absolute_position (f);
8294 BLOCK_INPUT;
8295 x_wm_set_size_hint (f, (long) 0, 0);
8297 modified_left = f->left_pos;
8298 modified_top = f->top_pos;
8300 if (change_gravity != 0 && FRAME_X_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A)
8302 /* Some WMs (twm, wmaker at least) has an offset that is smaller
8303 than the WM decorations. So we use the calculated offset instead
8304 of the WM decoration sizes here (x/y_pixels_outer_diff). */
8305 modified_left += FRAME_X_OUTPUT (f)->move_offset_left;
8306 modified_top += FRAME_X_OUTPUT (f)->move_offset_top;
8309 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8310 modified_left, modified_top);
8312 x_sync_with_move (f, f->left_pos, f->top_pos,
8313 FRAME_X_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN
8314 ? 1 : 0);
8316 /* change_gravity is non-zero when this function is called from Lisp to
8317 programmatically move a frame. In that case, we call
8318 x_check_expected_move to discover if we have a "Type A" or "Type B"
8319 window manager, and, for a "Type A" window manager, adjust the position
8320 of the frame.
8322 We call x_check_expected_move if a programmatic move occurred, and
8323 either the window manager type (A/B) is unknown or it is Type A but we
8324 need to compute the top/left offset adjustment for this frame. */
8326 if (change_gravity != 0 &&
8327 (FRAME_X_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN
8328 || (FRAME_X_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A
8329 && (FRAME_X_OUTPUT (f)->move_offset_left == 0
8330 && FRAME_X_OUTPUT (f)->move_offset_top == 0))))
8331 x_check_expected_move (f, modified_left, modified_top);
8333 UNBLOCK_INPUT;
8336 /* Return non-zero if _NET_SUPPORTING_WM_CHECK window exists and _NET_SUPPORTED
8337 on the root window for frame F contains ATOMNAME.
8338 This is how a WM check shall be done according to the Window Manager
8339 Specification/Extended Window Manager Hints at
8340 http://freedesktop.org/wiki/Specifications/wm-spec. */
8342 static int
8343 wm_supports (struct frame *f, Atom want_atom)
8345 Atom actual_type;
8346 unsigned long actual_size, bytes_remaining;
8347 int i, rc, actual_format;
8348 Window wmcheck_window;
8349 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8350 Window target_window = dpyinfo->root_window;
8351 long max_len = 65536;
8352 Display *dpy = FRAME_X_DISPLAY (f);
8353 unsigned char *tmp_data = NULL;
8354 Atom target_type = XA_WINDOW;
8356 BLOCK_INPUT;
8358 x_catch_errors (dpy);
8359 rc = XGetWindowProperty (dpy, target_window,
8360 dpyinfo->Xatom_net_supporting_wm_check,
8361 0, max_len, False, target_type,
8362 &actual_type, &actual_format, &actual_size,
8363 &bytes_remaining, &tmp_data);
8365 if (rc != Success || actual_type != XA_WINDOW || x_had_errors_p (dpy))
8367 if (tmp_data) XFree (tmp_data);
8368 x_uncatch_errors ();
8369 UNBLOCK_INPUT;
8370 return 0;
8373 wmcheck_window = *(Window *) tmp_data;
8374 XFree (tmp_data);
8376 /* Check if window exists. */
8377 XSelectInput (dpy, wmcheck_window, StructureNotifyMask);
8378 x_sync (f);
8379 if (x_had_errors_p (dpy))
8381 x_uncatch_errors ();
8382 UNBLOCK_INPUT;
8383 return 0;
8386 if (dpyinfo->net_supported_window != wmcheck_window)
8388 /* Window changed, reload atoms */
8389 if (dpyinfo->net_supported_atoms != NULL)
8390 XFree (dpyinfo->net_supported_atoms);
8391 dpyinfo->net_supported_atoms = NULL;
8392 dpyinfo->nr_net_supported_atoms = 0;
8393 dpyinfo->net_supported_window = 0;
8395 target_type = XA_ATOM;
8396 tmp_data = NULL;
8397 rc = XGetWindowProperty (dpy, target_window,
8398 dpyinfo->Xatom_net_supported,
8399 0, max_len, False, target_type,
8400 &actual_type, &actual_format, &actual_size,
8401 &bytes_remaining, &tmp_data);
8403 if (rc != Success || actual_type != XA_ATOM || x_had_errors_p (dpy))
8405 if (tmp_data) XFree (tmp_data);
8406 x_uncatch_errors ();
8407 UNBLOCK_INPUT;
8408 return 0;
8411 dpyinfo->net_supported_atoms = (Atom *)tmp_data;
8412 dpyinfo->nr_net_supported_atoms = actual_size;
8413 dpyinfo->net_supported_window = wmcheck_window;
8416 rc = 0;
8418 for (i = 0; rc == 0 && i < dpyinfo->nr_net_supported_atoms; ++i)
8419 rc = dpyinfo->net_supported_atoms[i] == want_atom;
8421 x_uncatch_errors ();
8422 UNBLOCK_INPUT;
8424 return rc;
8427 static void
8428 set_wm_state (Lisp_Object frame, int add, Atom atom, Atom value)
8430 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (XFRAME (frame));
8432 x_send_client_event (frame, make_number (0), frame,
8433 dpyinfo->Xatom_net_wm_state,
8434 make_number (32),
8435 /* 1 = add, 0 = remove */
8436 Fcons
8437 (make_number (add ? 1 : 0),
8438 Fcons
8439 (make_fixnum_or_float (atom),
8440 value != 0
8441 ? Fcons (make_fixnum_or_float (value), Qnil)
8442 : Qnil)));
8445 void
8446 x_set_sticky (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
8448 Lisp_Object frame;
8449 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8451 XSETFRAME (frame, f);
8453 set_wm_state (frame, NILP (new_value) ? 0 : 1,
8454 dpyinfo->Xatom_net_wm_state_sticky, None);
8457 /* Return the current _NET_WM_STATE.
8458 SIZE_STATE is set to one of the FULLSCREEN_* values.
8459 STICKY is set to 1 if the sticky state is set, 0 if not.
8461 Return non-zero if we are not hidden, zero if we are. */
8463 static int
8464 get_current_wm_state (struct frame *f,
8465 Window window,
8466 int *size_state,
8467 int *sticky)
8469 Atom actual_type;
8470 unsigned long actual_size, bytes_remaining;
8471 int i, rc, actual_format, is_hidden = 0;
8472 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8473 long max_len = 65536;
8474 Display *dpy = FRAME_X_DISPLAY (f);
8475 unsigned char *tmp_data = NULL;
8476 Atom target_type = XA_ATOM;
8478 *sticky = 0;
8479 *size_state = FULLSCREEN_NONE;
8481 BLOCK_INPUT;
8482 x_catch_errors (dpy);
8483 rc = XGetWindowProperty (dpy, window, dpyinfo->Xatom_net_wm_state,
8484 0, max_len, False, target_type,
8485 &actual_type, &actual_format, &actual_size,
8486 &bytes_remaining, &tmp_data);
8488 if (rc != Success || actual_type != target_type || x_had_errors_p (dpy))
8490 if (tmp_data) XFree (tmp_data);
8491 x_uncatch_errors ();
8492 UNBLOCK_INPUT;
8493 return ! f->iconified;
8496 x_uncatch_errors ();
8498 for (i = 0; i < actual_size; ++i)
8500 Atom a = ((Atom*)tmp_data)[i];
8501 if (a == dpyinfo->Xatom_net_wm_state_hidden)
8503 is_hidden = 1;
8504 f->output_data.x->net_wm_state_hidden_seen = 1;
8506 else if (a == dpyinfo->Xatom_net_wm_state_maximized_horz)
8508 if (*size_state == FULLSCREEN_HEIGHT)
8509 *size_state = FULLSCREEN_MAXIMIZED;
8510 else
8511 *size_state = FULLSCREEN_WIDTH;
8513 else if (a == dpyinfo->Xatom_net_wm_state_maximized_vert)
8515 if (*size_state == FULLSCREEN_WIDTH)
8516 *size_state = FULLSCREEN_MAXIMIZED;
8517 else
8518 *size_state = FULLSCREEN_HEIGHT;
8520 else if (a == dpyinfo->Xatom_net_wm_state_fullscreen)
8521 *size_state = FULLSCREEN_BOTH;
8522 else if (a == dpyinfo->Xatom_net_wm_state_sticky)
8523 *sticky = 1;
8526 if (tmp_data) XFree (tmp_data);
8527 UNBLOCK_INPUT;
8528 return ! is_hidden;
8531 /* Do fullscreen as specified in extended window manager hints */
8533 static int
8534 do_ewmh_fullscreen (struct frame *f)
8536 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8537 int have_net_atom = wm_supports (f, dpyinfo->Xatom_net_wm_state);
8538 int cur, dummy;
8540 (void)get_current_wm_state (f, FRAME_OUTER_WINDOW (f), &cur, &dummy);
8542 /* Some window managers don't say they support _NET_WM_STATE, but they do say
8543 they support _NET_WM_STATE_FULLSCREEN. Try that also. */
8544 if (!have_net_atom)
8545 have_net_atom = wm_supports (f, dpyinfo->Xatom_net_wm_state_fullscreen);
8547 if (have_net_atom && cur != f->want_fullscreen)
8549 Lisp_Object frame;
8551 XSETFRAME (frame, f);
8553 /* Keep number of calls to set_wm_state as low as possible.
8554 Some window managers, or possible Gtk+, hangs when too many
8555 are sent at once. */
8556 switch (f->want_fullscreen)
8558 case FULLSCREEN_BOTH:
8559 if (cur == FULLSCREEN_WIDTH || cur == FULLSCREEN_MAXIMIZED
8560 || cur == FULLSCREEN_HEIGHT)
8561 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_maximized_horz,
8562 dpyinfo->Xatom_net_wm_state_maximized_vert);
8563 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_fullscreen, None);
8564 break;
8565 case FULLSCREEN_WIDTH:
8566 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_HEIGHT
8567 || cur == FULLSCREEN_MAXIMIZED)
8568 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen,
8569 dpyinfo->Xatom_net_wm_state_maximized_vert);
8570 if (cur != FULLSCREEN_MAXIMIZED)
8571 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_maximized_horz, None);
8572 break;
8573 case FULLSCREEN_HEIGHT:
8574 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_WIDTH
8575 || cur == FULLSCREEN_MAXIMIZED)
8576 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen,
8577 dpyinfo->Xatom_net_wm_state_maximized_horz);
8578 if (cur != FULLSCREEN_MAXIMIZED)
8579 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_maximized_vert, None);
8580 break;
8581 case FULLSCREEN_MAXIMIZED:
8582 if (cur == FULLSCREEN_BOTH)
8583 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen, None);
8584 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_maximized_horz,
8585 dpyinfo->Xatom_net_wm_state_maximized_vert);
8586 break;
8587 case FULLSCREEN_NONE:
8588 if (cur == FULLSCREEN_BOTH)
8589 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen, None);
8590 else
8591 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_maximized_horz,
8592 dpyinfo->Xatom_net_wm_state_maximized_vert);
8595 f->want_fullscreen = FULLSCREEN_NONE;
8599 return have_net_atom;
8602 static void
8603 XTfullscreen_hook (FRAME_PTR f)
8605 if (f->async_visible)
8607 BLOCK_INPUT;
8608 x_check_fullscreen (f);
8609 x_sync (f);
8610 UNBLOCK_INPUT;
8615 static int
8616 x_handle_net_wm_state (struct frame *f, XPropertyEvent *event)
8618 int value = FULLSCREEN_NONE;
8619 Lisp_Object lval;
8620 int sticky = 0;
8621 int not_hidden = get_current_wm_state (f, event->window, &value, &sticky);
8623 lval = Qnil;
8624 switch (value)
8626 case FULLSCREEN_WIDTH:
8627 lval = Qfullwidth;
8628 break;
8629 case FULLSCREEN_HEIGHT:
8630 lval = Qfullheight;
8631 break;
8632 case FULLSCREEN_BOTH:
8633 lval = Qfullboth;
8634 break;
8635 case FULLSCREEN_MAXIMIZED:
8636 lval = Qmaximized;
8637 break;
8640 store_frame_param (f, Qfullscreen, lval);
8641 store_frame_param (f, Qsticky, sticky ? Qt : Qnil);
8643 return not_hidden;
8646 /* Check if we need to resize the frame due to a fullscreen request.
8647 If so needed, resize the frame. */
8648 static void
8649 x_check_fullscreen (struct frame *f)
8651 if (do_ewmh_fullscreen (f))
8652 return;
8654 if (f->output_data.x->parent_desc != FRAME_X_DISPLAY_INFO (f)->root_window)
8655 return; /* Only fullscreen without WM or with EWM hints (above). */
8657 /* Setting fullscreen to nil doesn't do anything. We could save the
8658 last non-fullscreen size and restore it, but it seems like a
8659 lot of work for this unusual case (no window manager running). */
8661 if (f->want_fullscreen != FULLSCREEN_NONE)
8663 int width = FRAME_PIXEL_WIDTH (f), height = FRAME_PIXEL_HEIGHT (f);
8664 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8666 switch (f->want_fullscreen)
8668 /* No difference between these two when there is no WM */
8669 case FULLSCREEN_BOTH:
8670 case FULLSCREEN_MAXIMIZED:
8671 width = x_display_pixel_width (dpyinfo);
8672 height = x_display_pixel_height (dpyinfo);
8673 break;
8674 case FULLSCREEN_WIDTH:
8675 width = x_display_pixel_width (dpyinfo);
8676 break;
8677 case FULLSCREEN_HEIGHT:
8678 height = x_display_pixel_height (dpyinfo);
8681 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8682 width, height);
8686 /* This function is called by x_set_offset to determine whether the window
8687 manager interfered with the positioning of the frame. Type A window
8688 managers position the surrounding window manager decorations a small
8689 amount above and left of the user-supplied position. Type B window
8690 managers position the surrounding window manager decorations at the
8691 user-specified position. If we detect a Type A window manager, we
8692 compensate by moving the window right and down by the proper amount. */
8694 static void
8695 x_check_expected_move (struct frame *f, int expected_left, int expected_top)
8697 int current_left = 0, current_top = 0;
8699 /* x_real_positions returns the left and top offsets of the outermost
8700 window manager window around the frame. */
8702 x_real_positions (f, &current_left, &current_top);
8704 if (current_left != expected_left || current_top != expected_top)
8706 /* It's a "Type A" window manager. */
8708 int adjusted_left;
8709 int adjusted_top;
8711 FRAME_X_DISPLAY_INFO (f)->wm_type = X_WMTYPE_A;
8712 FRAME_X_OUTPUT (f)->move_offset_left = expected_left - current_left;
8713 FRAME_X_OUTPUT (f)->move_offset_top = expected_top - current_top;
8715 /* Now fix the mispositioned frame's location. */
8717 adjusted_left = expected_left + FRAME_X_OUTPUT (f)->move_offset_left;
8718 adjusted_top = expected_top + FRAME_X_OUTPUT (f)->move_offset_top;
8720 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8721 adjusted_left, adjusted_top);
8723 x_sync_with_move (f, expected_left, expected_top, 0);
8725 else
8726 /* It's a "Type B" window manager. We don't have to adjust the
8727 frame's position. */
8729 FRAME_X_DISPLAY_INFO (f)->wm_type = X_WMTYPE_B;
8733 /* Wait for XGetGeometry to return up-to-date position information for a
8734 recently-moved frame. Call this immediately after calling XMoveWindow.
8735 If FUZZY is non-zero, then LEFT and TOP are just estimates of where the
8736 frame has been moved to, so we use a fuzzy position comparison instead
8737 of an exact comparison. */
8739 static void
8740 x_sync_with_move (struct frame *f, int left, int top, int fuzzy)
8742 int count = 0;
8744 while (count++ < 50)
8746 int current_left = 0, current_top = 0;
8748 /* In theory, this call to XSync only needs to happen once, but in
8749 practice, it doesn't seem to work, hence the need for the surrounding
8750 loop. */
8752 XSync (FRAME_X_DISPLAY (f), False);
8753 x_real_positions (f, &current_left, &current_top);
8755 if (fuzzy)
8757 /* The left fuzz-factor is 10 pixels. The top fuzz-factor is 40
8758 pixels. */
8760 if (eabs (current_left - left) <= 10
8761 && eabs (current_top - top) <= 40)
8762 return;
8764 else if (current_left == left && current_top == top)
8765 return;
8768 /* As a last resort, just wait 0.5 seconds and hope that XGetGeometry
8769 will then return up-to-date position info. */
8771 wait_reading_process_output (0, 500000, 0, 0, Qnil, NULL, 0);
8775 /* Wait for an event on frame F matching EVENTTYPE. */
8776 void
8777 x_wait_for_event (struct frame *f, int eventtype)
8779 int level = interrupt_input_blocked;
8781 SELECT_TYPE fds;
8782 EMACS_TIME tmo, tmo_at, time_now;
8783 int fd = ConnectionNumber (FRAME_X_DISPLAY (f));
8785 pending_event_wait.f = f;
8786 pending_event_wait.eventtype = eventtype;
8788 /* Set timeout to 0.1 second. Hopefully not noticeable.
8789 Maybe it should be configurable. */
8790 EMACS_SET_SECS_USECS (tmo, 0, 100000);
8791 EMACS_GET_TIME (tmo_at);
8792 EMACS_ADD_TIME (tmo_at, tmo_at, tmo);
8794 while (pending_event_wait.eventtype)
8796 interrupt_input_pending = 1;
8797 TOTALLY_UNBLOCK_INPUT;
8798 /* XTread_socket is called after unblock. */
8799 BLOCK_INPUT;
8800 interrupt_input_blocked = level;
8802 FD_ZERO (&fds);
8803 FD_SET (fd, &fds);
8805 EMACS_GET_TIME (time_now);
8806 EMACS_SUB_TIME (tmo, tmo_at, time_now);
8808 if (EMACS_TIME_NEG_P (tmo) || select (fd+1, &fds, NULL, NULL, &tmo) == 0)
8809 break; /* Timeout */
8811 pending_event_wait.f = 0;
8812 pending_event_wait.eventtype = 0;
8816 /* Change the size of frame F's X window to COLS/ROWS in the case F
8817 doesn't have a widget. If CHANGE_GRAVITY is 1, we change to
8818 top-left-corner window gravity for this size change and subsequent
8819 size changes. Otherwise we leave the window gravity unchanged. */
8821 static void
8822 x_set_window_size_1 (struct frame *f, int change_gravity, int cols, int rows)
8824 int pixelwidth, pixelheight;
8826 check_frame_size (f, &rows, &cols);
8827 f->scroll_bar_actual_width
8828 = (!FRAME_HAS_VERTICAL_SCROLL_BARS (f)
8830 : FRAME_CONFIG_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f));
8832 compute_fringe_widths (f, 0);
8834 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, cols)
8835 + FRAME_TOOLBAR_WIDTH (f);
8836 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows)
8837 + FRAME_MENUBAR_HEIGHT (f) + FRAME_TOOLBAR_HEIGHT (f);
8839 if (change_gravity) f->win_gravity = NorthWestGravity;
8840 x_wm_set_size_hint (f, (long) 0, 0);
8841 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8842 pixelwidth, pixelheight);
8845 /* We've set {FRAME,PIXEL}_{WIDTH,HEIGHT} to the values we hope to
8846 receive in the ConfigureNotify event; if we get what we asked
8847 for, then the event won't cause the screen to become garbaged, so
8848 we have to make sure to do it here. */
8849 SET_FRAME_GARBAGED (f);
8851 /* Now, strictly speaking, we can't be sure that this is accurate,
8852 but the window manager will get around to dealing with the size
8853 change request eventually, and we'll hear how it went when the
8854 ConfigureNotify event gets here.
8856 We could just not bother storing any of this information here,
8857 and let the ConfigureNotify event set everything up, but that
8858 might be kind of confusing to the Lisp code, since size changes
8859 wouldn't be reported in the frame parameters until some random
8860 point in the future when the ConfigureNotify event arrives.
8862 We pass 1 for DELAY since we can't run Lisp code inside of
8863 a BLOCK_INPUT. */
8865 /* But the ConfigureNotify may in fact never arrive, and then this is
8866 not right if the frame is visible. Instead wait (with timeout)
8867 for the ConfigureNotify. */
8868 if (f->async_visible)
8869 x_wait_for_event (f, ConfigureNotify);
8870 else
8872 change_frame_size (f, rows, cols, 0, 1, 0);
8873 FRAME_PIXEL_WIDTH (f) = pixelwidth;
8874 FRAME_PIXEL_HEIGHT (f) = pixelheight;
8875 x_sync (f);
8880 /* Call this to change the size of frame F's x-window.
8881 If CHANGE_GRAVITY is 1, we change to top-left-corner window gravity
8882 for this size change and subsequent size changes.
8883 Otherwise we leave the window gravity unchanged. */
8885 void
8886 x_set_window_size (struct frame *f, int change_gravity, int cols, int rows)
8888 BLOCK_INPUT;
8890 if (NILP (tip_frame) || XFRAME (tip_frame) != f)
8892 int r, c;
8894 /* When the frame is maximized/fullscreen or running under for
8895 example Xmonad, x_set_window_size_1 will be a no-op.
8896 In that case, the right thing to do is extend rows/cols to
8897 the current frame size. We do that first if x_set_window_size_1
8898 turns out to not be a no-op (there is no way to know).
8899 The size will be adjusted again if the frame gets a
8900 ConfigureNotify event as a result of x_set_window_size. */
8901 int pixelh = FRAME_PIXEL_HEIGHT (f);
8902 #ifdef USE_X_TOOLKIT
8903 /* The menu bar is not part of text lines. The tool bar
8904 is however. */
8905 pixelh -= FRAME_MENUBAR_HEIGHT (f);
8906 #endif
8907 r = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, pixelh);
8908 /* Update f->scroll_bar_actual_width because it is used in
8909 FRAME_PIXEL_WIDTH_TO_TEXT_COLS. */
8910 f->scroll_bar_actual_width
8911 = FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f);
8912 c = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, FRAME_PIXEL_WIDTH (f));
8913 change_frame_size (f, r, c, 0, 1, 0);
8916 #ifdef USE_GTK
8917 if (FRAME_GTK_WIDGET (f))
8918 xg_frame_set_char_size (f, cols, rows);
8919 else
8920 x_set_window_size_1 (f, change_gravity, cols, rows);
8921 #else /* not USE_GTK */
8923 x_set_window_size_1 (f, change_gravity, cols, rows);
8925 #endif /* not USE_GTK */
8927 /* If cursor was outside the new size, mark it as off. */
8928 mark_window_cursors_off (XWINDOW (f->root_window));
8930 /* Clear out any recollection of where the mouse highlighting was,
8931 since it might be in a place that's outside the new frame size.
8932 Actually checking whether it is outside is a pain in the neck,
8933 so don't try--just let the highlighting be done afresh with new size. */
8934 cancel_mouse_face (f);
8936 UNBLOCK_INPUT;
8939 /* Mouse warping. */
8941 void
8942 x_set_mouse_position (struct frame *f, int x, int y)
8944 int pix_x, pix_y;
8946 pix_x = FRAME_COL_TO_PIXEL_X (f, x) + FRAME_COLUMN_WIDTH (f) / 2;
8947 pix_y = FRAME_LINE_TO_PIXEL_Y (f, y) + FRAME_LINE_HEIGHT (f) / 2;
8949 if (pix_x < 0) pix_x = 0;
8950 if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
8952 if (pix_y < 0) pix_y = 0;
8953 if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
8955 BLOCK_INPUT;
8957 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
8958 0, 0, 0, 0, pix_x, pix_y);
8959 UNBLOCK_INPUT;
8962 /* Move the mouse to position pixel PIX_X, PIX_Y relative to frame F. */
8964 void
8965 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
8967 BLOCK_INPUT;
8969 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
8970 0, 0, 0, 0, pix_x, pix_y);
8971 UNBLOCK_INPUT;
8974 /* Raise frame F. */
8976 void
8977 x_raise_frame (struct frame *f)
8979 BLOCK_INPUT;
8980 if (f->async_visible)
8981 XRaiseWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
8983 XFlush (FRAME_X_DISPLAY (f));
8984 UNBLOCK_INPUT;
8987 /* Lower frame F. */
8989 static void
8990 x_lower_frame (struct frame *f)
8992 if (f->async_visible)
8994 BLOCK_INPUT;
8995 XLowerWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
8996 XFlush (FRAME_X_DISPLAY (f));
8997 UNBLOCK_INPUT;
9001 /* Request focus with XEmbed */
9003 void
9004 xembed_request_focus (FRAME_PTR f)
9006 /* See XEmbed Protocol Specification at
9007 http://freedesktop.org/wiki/Specifications/xembed-spec */
9008 if (f->async_visible)
9009 xembed_send_message (f, CurrentTime,
9010 XEMBED_REQUEST_FOCUS, 0, 0, 0);
9013 /* Activate frame with Extended Window Manager Hints */
9015 void
9016 x_ewmh_activate_frame (FRAME_PTR f)
9018 /* See Window Manager Specification/Extended Window Manager Hints at
9019 http://freedesktop.org/wiki/Specifications/wm-spec */
9021 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
9022 if (f->async_visible && wm_supports (f, dpyinfo->Xatom_net_active_window))
9024 Lisp_Object frame;
9025 XSETFRAME (frame, f);
9026 x_send_client_event (frame, make_number (0), frame,
9027 dpyinfo->Xatom_net_active_window,
9028 make_number (32),
9029 Fcons (make_number (1),
9030 Fcons (make_number (last_user_time),
9031 Qnil)));
9035 static void
9036 XTframe_raise_lower (FRAME_PTR f, int raise_flag)
9038 if (raise_flag)
9039 x_raise_frame (f);
9040 else
9041 x_lower_frame (f);
9044 /* XEmbed implementation. */
9046 #if defined USE_X_TOOLKIT || ! defined USE_GTK
9048 /* XEmbed implementation. */
9050 #define XEMBED_VERSION 0
9052 static void
9053 xembed_set_info (struct frame *f, enum xembed_info flags)
9055 unsigned long data[2];
9056 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
9058 data[0] = XEMBED_VERSION;
9059 data[1] = flags;
9061 XChangeProperty (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
9062 dpyinfo->Xatom_XEMBED_INFO, dpyinfo->Xatom_XEMBED_INFO,
9063 32, PropModeReplace, (unsigned char *) data, 2);
9065 #endif /* defined USE_X_TOOLKIT || ! defined USE_GTK */
9067 static void
9068 xembed_send_message (struct frame *f, Time t, enum xembed_message msg,
9069 long int detail, long int data1, long int data2)
9071 XEvent event;
9073 event.xclient.type = ClientMessage;
9074 event.xclient.window = FRAME_X_OUTPUT (f)->parent_desc;
9075 event.xclient.message_type = FRAME_X_DISPLAY_INFO (f)->Xatom_XEMBED;
9076 event.xclient.format = 32;
9077 event.xclient.data.l[0] = t;
9078 event.xclient.data.l[1] = msg;
9079 event.xclient.data.l[2] = detail;
9080 event.xclient.data.l[3] = data1;
9081 event.xclient.data.l[4] = data2;
9083 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_OUTPUT (f)->parent_desc,
9084 False, NoEventMask, &event);
9085 XSync (FRAME_X_DISPLAY (f), False);
9088 /* Change of visibility. */
9090 /* This tries to wait until the frame is really visible.
9091 However, if the window manager asks the user where to position
9092 the frame, this will return before the user finishes doing that.
9093 The frame will not actually be visible at that time,
9094 but it will become visible later when the window manager
9095 finishes with it. */
9097 void
9098 x_make_frame_visible (struct frame *f)
9100 Lisp_Object type;
9101 int original_top, original_left;
9102 int retry_count = 2;
9104 retry:
9106 BLOCK_INPUT;
9108 type = x_icon_type (f);
9109 if (!NILP (type))
9110 x_bitmap_icon (f, type);
9112 if (! FRAME_VISIBLE_P (f))
9114 /* We test FRAME_GARBAGED_P here to make sure we don't
9115 call x_set_offset a second time
9116 if we get to x_make_frame_visible a second time
9117 before the window gets really visible. */
9118 if (! FRAME_ICONIFIED_P (f)
9119 && ! FRAME_X_EMBEDDED_P (f)
9120 && ! f->output_data.x->asked_for_visible)
9121 x_set_offset (f, f->left_pos, f->top_pos, 0);
9123 f->output_data.x->asked_for_visible = 1;
9125 if (! EQ (Vx_no_window_manager, Qt))
9126 x_wm_set_window_state (f, NormalState);
9127 #ifdef USE_X_TOOLKIT
9128 if (FRAME_X_EMBEDDED_P (f))
9129 xembed_set_info (f, XEMBED_MAPPED);
9130 else
9132 /* This was XtPopup, but that did nothing for an iconified frame. */
9133 XtMapWidget (f->output_data.x->widget);
9135 #else /* not USE_X_TOOLKIT */
9136 #ifdef USE_GTK
9137 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
9138 gtk_window_deiconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
9139 #else
9140 if (FRAME_X_EMBEDDED_P (f))
9141 xembed_set_info (f, XEMBED_MAPPED);
9142 else
9143 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9144 #endif /* not USE_GTK */
9145 #endif /* not USE_X_TOOLKIT */
9148 XFlush (FRAME_X_DISPLAY (f));
9150 /* Synchronize to ensure Emacs knows the frame is visible
9151 before we do anything else. We do this loop with input not blocked
9152 so that incoming events are handled. */
9154 Lisp_Object frame;
9155 int count;
9156 /* This must be before UNBLOCK_INPUT
9157 since events that arrive in response to the actions above
9158 will set it when they are handled. */
9159 int previously_visible = f->output_data.x->has_been_visible;
9161 original_left = f->left_pos;
9162 original_top = f->top_pos;
9164 /* This must come after we set COUNT. */
9165 UNBLOCK_INPUT;
9167 /* We unblock here so that arriving X events are processed. */
9169 /* Now move the window back to where it was "supposed to be".
9170 But don't do it if the gravity is negative.
9171 When the gravity is negative, this uses a position
9172 that is 3 pixels too low. Perhaps that's really the border width.
9174 Don't do this if the window has never been visible before,
9175 because the window manager may choose the position
9176 and we don't want to override it. */
9178 if (! FRAME_VISIBLE_P (f)
9179 && ! FRAME_ICONIFIED_P (f)
9180 && ! FRAME_X_EMBEDDED_P (f)
9181 && f->win_gravity == NorthWestGravity
9182 && previously_visible)
9184 Drawable rootw;
9185 int x, y;
9186 unsigned int width, height, border, depth;
9188 BLOCK_INPUT;
9190 /* On some window managers (such as FVWM) moving an existing
9191 window, even to the same place, causes the window manager
9192 to introduce an offset. This can cause the window to move
9193 to an unexpected location. Check the geometry (a little
9194 slow here) and then verify that the window is in the right
9195 place. If the window is not in the right place, move it
9196 there, and take the potential window manager hit. */
9197 XGetGeometry (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
9198 &rootw, &x, &y, &width, &height, &border, &depth);
9200 if (original_left != x || original_top != y)
9201 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
9202 original_left, original_top);
9204 UNBLOCK_INPUT;
9207 XSETFRAME (frame, f);
9209 /* Wait until the frame is visible. Process X events until a
9210 MapNotify event has been seen, or until we think we won't get a
9211 MapNotify at all.. */
9212 for (count = input_signal_count + 10;
9213 input_signal_count < count && !FRAME_VISIBLE_P (f);)
9215 /* Force processing of queued events. */
9216 x_sync (f);
9218 /* Machines that do polling rather than SIGIO have been
9219 observed to go into a busy-wait here. So we'll fake an
9220 alarm signal to let the handler know that there's something
9221 to be read. We used to raise a real alarm, but it seems
9222 that the handler isn't always enabled here. This is
9223 probably a bug. */
9224 if (input_polling_used ())
9226 /* It could be confusing if a real alarm arrives while
9227 processing the fake one. Turn it off and let the
9228 handler reset it. */
9229 int old_poll_suppress_count = poll_suppress_count;
9230 poll_suppress_count = 1;
9231 poll_for_input_1 ();
9232 poll_suppress_count = old_poll_suppress_count;
9235 /* See if a MapNotify event has been processed. */
9236 FRAME_SAMPLE_VISIBILITY (f);
9239 /* 2000-09-28: In
9241 (let ((f (selected-frame)))
9242 (iconify-frame f)
9243 (raise-frame f))
9245 the frame is not raised with various window managers on
9246 FreeBSD, GNU/Linux and Solaris. It turns out that, for some
9247 unknown reason, the call to XtMapWidget is completely ignored.
9248 Mapping the widget a second time works. */
9250 if (!FRAME_VISIBLE_P (f) && --retry_count != 0)
9251 goto retry;
9255 /* Change from mapped state to withdrawn state. */
9257 /* Make the frame visible (mapped and not iconified). */
9259 void
9260 x_make_frame_invisible (struct frame *f)
9262 Window window;
9264 /* Use the frame's outermost window, not the one we normally draw on. */
9265 window = FRAME_OUTER_WINDOW (f);
9267 /* Don't keep the highlight on an invisible frame. */
9268 if (FRAME_X_DISPLAY_INFO (f)->x_highlight_frame == f)
9269 FRAME_X_DISPLAY_INFO (f)->x_highlight_frame = 0;
9271 BLOCK_INPUT;
9273 /* Before unmapping the window, update the WM_SIZE_HINTS property to claim
9274 that the current position of the window is user-specified, rather than
9275 program-specified, so that when the window is mapped again, it will be
9276 placed at the same location, without forcing the user to position it
9277 by hand again (they have already done that once for this window.) */
9278 x_wm_set_size_hint (f, (long) 0, 1);
9280 #ifdef USE_GTK
9281 if (FRAME_GTK_OUTER_WIDGET (f))
9282 gtk_widget_hide (FRAME_GTK_OUTER_WIDGET (f));
9283 else
9284 #else
9285 if (FRAME_X_EMBEDDED_P (f))
9286 xembed_set_info (f, 0);
9287 else
9288 #endif
9291 if (! XWithdrawWindow (FRAME_X_DISPLAY (f), window,
9292 DefaultScreen (FRAME_X_DISPLAY (f))))
9294 UNBLOCK_INPUT_RESIGNAL;
9295 error ("Can't notify window manager of window withdrawal");
9299 /* We can't distinguish this from iconification
9300 just by the event that we get from the server.
9301 So we can't win using the usual strategy of letting
9302 FRAME_SAMPLE_VISIBILITY set this. So do it by hand,
9303 and synchronize with the server to make sure we agree. */
9304 f->visible = 0;
9305 FRAME_ICONIFIED_P (f) = 0;
9306 f->async_visible = 0;
9307 f->async_iconified = 0;
9309 x_sync (f);
9311 UNBLOCK_INPUT;
9314 /* Change window state from mapped to iconified. */
9316 void
9317 x_iconify_frame (struct frame *f)
9319 #ifdef USE_X_TOOLKIT
9320 int result;
9321 #endif
9322 Lisp_Object type;
9324 /* Don't keep the highlight on an invisible frame. */
9325 if (FRAME_X_DISPLAY_INFO (f)->x_highlight_frame == f)
9326 FRAME_X_DISPLAY_INFO (f)->x_highlight_frame = 0;
9328 if (f->async_iconified)
9329 return;
9331 BLOCK_INPUT;
9333 FRAME_SAMPLE_VISIBILITY (f);
9335 type = x_icon_type (f);
9336 if (!NILP (type))
9337 x_bitmap_icon (f, type);
9339 #if defined (USE_GTK)
9340 if (FRAME_GTK_OUTER_WIDGET (f))
9342 if (! FRAME_VISIBLE_P (f))
9343 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
9345 gtk_window_iconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
9346 f->iconified = 1;
9347 f->visible = 1;
9348 f->async_iconified = 1;
9349 f->async_visible = 0;
9350 UNBLOCK_INPUT;
9351 return;
9353 #endif
9355 #ifdef USE_X_TOOLKIT
9357 if (! FRAME_VISIBLE_P (f))
9359 if (! EQ (Vx_no_window_manager, Qt))
9360 x_wm_set_window_state (f, IconicState);
9361 /* This was XtPopup, but that did nothing for an iconified frame. */
9362 XtMapWidget (f->output_data.x->widget);
9363 /* The server won't give us any event to indicate
9364 that an invisible frame was changed to an icon,
9365 so we have to record it here. */
9366 f->iconified = 1;
9367 f->visible = 1;
9368 f->async_iconified = 1;
9369 f->async_visible = 0;
9370 UNBLOCK_INPUT;
9371 return;
9374 result = XIconifyWindow (FRAME_X_DISPLAY (f),
9375 XtWindow (f->output_data.x->widget),
9376 DefaultScreen (FRAME_X_DISPLAY (f)));
9377 UNBLOCK_INPUT;
9379 if (!result)
9380 error ("Can't notify window manager of iconification");
9382 f->async_iconified = 1;
9383 f->async_visible = 0;
9386 BLOCK_INPUT;
9387 XFlush (FRAME_X_DISPLAY (f));
9388 UNBLOCK_INPUT;
9389 #else /* not USE_X_TOOLKIT */
9391 /* Make sure the X server knows where the window should be positioned,
9392 in case the user deiconifies with the window manager. */
9393 if (! FRAME_VISIBLE_P (f)
9394 && ! FRAME_ICONIFIED_P (f)
9395 && ! FRAME_X_EMBEDDED_P (f))
9396 x_set_offset (f, f->left_pos, f->top_pos, 0);
9398 /* Since we don't know which revision of X we're running, we'll use both
9399 the X11R3 and X11R4 techniques. I don't know if this is a good idea. */
9401 /* X11R4: send a ClientMessage to the window manager using the
9402 WM_CHANGE_STATE type. */
9404 XEvent msg;
9406 msg.xclient.window = FRAME_X_WINDOW (f);
9407 msg.xclient.type = ClientMessage;
9408 msg.xclient.message_type = FRAME_X_DISPLAY_INFO (f)->Xatom_wm_change_state;
9409 msg.xclient.format = 32;
9410 msg.xclient.data.l[0] = IconicState;
9412 if (! XSendEvent (FRAME_X_DISPLAY (f),
9413 DefaultRootWindow (FRAME_X_DISPLAY (f)),
9414 False,
9415 SubstructureRedirectMask | SubstructureNotifyMask,
9416 &msg))
9418 UNBLOCK_INPUT_RESIGNAL;
9419 error ("Can't notify window manager of iconification");
9423 /* X11R3: set the initial_state field of the window manager hints to
9424 IconicState. */
9425 x_wm_set_window_state (f, IconicState);
9427 if (!FRAME_VISIBLE_P (f))
9429 /* If the frame was withdrawn, before, we must map it. */
9430 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9433 f->async_iconified = 1;
9434 f->async_visible = 0;
9436 XFlush (FRAME_X_DISPLAY (f));
9437 UNBLOCK_INPUT;
9438 #endif /* not USE_X_TOOLKIT */
9442 /* Free X resources of frame F. */
9444 void
9445 x_free_frame_resources (struct frame *f)
9447 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
9448 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
9449 #ifdef USE_X_TOOLKIT
9450 Lisp_Object bar;
9451 struct scroll_bar *b;
9452 #endif
9454 BLOCK_INPUT;
9456 /* If a display connection is dead, don't try sending more
9457 commands to the X server. */
9458 if (dpyinfo->display)
9460 /* We must free faces before destroying windows because some
9461 font-driver (e.g. xft) access a window while finishing a
9462 face. */
9463 if (FRAME_FACE_CACHE (f))
9464 free_frame_faces (f);
9466 if (f->output_data.x->icon_desc)
9467 XDestroyWindow (FRAME_X_DISPLAY (f), f->output_data.x->icon_desc);
9469 #ifdef USE_X_TOOLKIT
9470 /* Explicitly destroy the scroll bars of the frame. Without
9471 this, we get "BadDrawable" errors from the toolkit later on,
9472 presumably from expose events generated for the disappearing
9473 toolkit scroll bars. */
9474 for (bar = FRAME_SCROLL_BARS (f); !NILP (bar); bar = b->next)
9476 b = XSCROLL_BAR (bar);
9477 x_scroll_bar_remove (b);
9479 #endif
9481 #ifdef HAVE_X_I18N
9482 if (FRAME_XIC (f))
9483 free_frame_xic (f);
9484 #endif
9486 #ifdef USE_X_TOOLKIT
9487 if (f->output_data.x->widget)
9489 XtDestroyWidget (f->output_data.x->widget);
9490 f->output_data.x->widget = NULL;
9492 /* Tooltips don't have widgets, only a simple X window, even if
9493 we are using a toolkit. */
9494 else if (FRAME_X_WINDOW (f))
9495 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9497 free_frame_menubar (f);
9498 #else /* !USE_X_TOOLKIT */
9500 #ifdef USE_GTK
9501 xg_free_frame_widgets (f);
9502 #endif /* USE_GTK */
9504 if (FRAME_X_WINDOW (f))
9505 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9506 #endif /* !USE_X_TOOLKIT */
9508 unload_color (f, FRAME_FOREGROUND_PIXEL (f));
9509 unload_color (f, FRAME_BACKGROUND_PIXEL (f));
9510 unload_color (f, f->output_data.x->cursor_pixel);
9511 unload_color (f, f->output_data.x->cursor_foreground_pixel);
9512 unload_color (f, f->output_data.x->border_pixel);
9513 unload_color (f, f->output_data.x->mouse_pixel);
9515 if (f->output_data.x->scroll_bar_background_pixel != -1)
9516 unload_color (f, f->output_data.x->scroll_bar_background_pixel);
9517 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
9518 unload_color (f, f->output_data.x->scroll_bar_foreground_pixel);
9519 #ifdef USE_TOOLKIT_SCROLL_BARS
9520 /* Scrollbar shadow colors. */
9521 if (f->output_data.x->scroll_bar_top_shadow_pixel != -1)
9522 unload_color (f, f->output_data.x->scroll_bar_top_shadow_pixel);
9523 if (f->output_data.x->scroll_bar_bottom_shadow_pixel != -1)
9524 unload_color (f, f->output_data.x->scroll_bar_bottom_shadow_pixel);
9525 #endif /* USE_TOOLKIT_SCROLL_BARS */
9526 if (f->output_data.x->white_relief.allocated_p)
9527 unload_color (f, f->output_data.x->white_relief.pixel);
9528 if (f->output_data.x->black_relief.allocated_p)
9529 unload_color (f, f->output_data.x->black_relief.pixel);
9531 x_free_gcs (f);
9532 XFlush (FRAME_X_DISPLAY (f));
9535 xfree (f->output_data.x->saved_menu_event);
9536 xfree (f->output_data.x);
9537 f->output_data.x = NULL;
9539 if (f == dpyinfo->x_focus_frame)
9540 dpyinfo->x_focus_frame = 0;
9541 if (f == dpyinfo->x_focus_event_frame)
9542 dpyinfo->x_focus_event_frame = 0;
9543 if (f == dpyinfo->x_highlight_frame)
9544 dpyinfo->x_highlight_frame = 0;
9546 if (f == hlinfo->mouse_face_mouse_frame)
9548 hlinfo->mouse_face_beg_row
9549 = hlinfo->mouse_face_beg_col = -1;
9550 hlinfo->mouse_face_end_row
9551 = hlinfo->mouse_face_end_col = -1;
9552 hlinfo->mouse_face_window = Qnil;
9553 hlinfo->mouse_face_deferred_gc = 0;
9554 hlinfo->mouse_face_mouse_frame = 0;
9557 UNBLOCK_INPUT;
9561 /* Destroy the X window of frame F. */
9563 static void
9564 x_destroy_window (struct frame *f)
9566 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
9568 /* If a display connection is dead, don't try sending more
9569 commands to the X server. */
9570 if (dpyinfo->display != 0)
9571 x_free_frame_resources (f);
9573 dpyinfo->reference_count--;
9577 /* Setting window manager hints. */
9579 /* Set the normal size hints for the window manager, for frame F.
9580 FLAGS is the flags word to use--or 0 meaning preserve the flags
9581 that the window now has.
9582 If USER_POSITION is nonzero, we set the USPosition
9583 flag (this is useful when FLAGS is 0).
9584 The GTK version is in gtkutils.c */
9586 #ifndef USE_GTK
9587 void
9588 x_wm_set_size_hint (struct frame *f, long flags, int user_position)
9590 XSizeHints size_hints;
9591 Window window = FRAME_OUTER_WINDOW (f);
9593 #ifdef USE_X_TOOLKIT
9594 if (f->output_data.x->widget)
9596 widget_update_wm_size_hints (f->output_data.x->widget);
9597 return;
9599 #endif
9601 /* Setting PMaxSize caused various problems. */
9602 size_hints.flags = PResizeInc | PMinSize /* | PMaxSize */;
9604 size_hints.x = f->left_pos;
9605 size_hints.y = f->top_pos;
9607 size_hints.height = FRAME_PIXEL_HEIGHT (f);
9608 size_hints.width = FRAME_PIXEL_WIDTH (f);
9610 size_hints.width_inc = FRAME_COLUMN_WIDTH (f);
9611 size_hints.height_inc = FRAME_LINE_HEIGHT (f);
9612 size_hints.max_width = x_display_pixel_width (FRAME_X_DISPLAY_INFO (f))
9613 - FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
9614 size_hints.max_height = x_display_pixel_height (FRAME_X_DISPLAY_INFO (f))
9615 - FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
9617 /* Calculate the base and minimum sizes. */
9619 int base_width, base_height;
9620 int min_rows = 0, min_cols = 0;
9622 base_width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
9623 base_height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
9625 check_frame_size (f, &min_rows, &min_cols);
9627 /* The window manager uses the base width hints to calculate the
9628 current number of rows and columns in the frame while
9629 resizing; min_width and min_height aren't useful for this
9630 purpose, since they might not give the dimensions for a
9631 zero-row, zero-column frame.
9633 We use the base_width and base_height members if we have
9634 them; otherwise, we set the min_width and min_height members
9635 to the size for a zero x zero frame. */
9637 size_hints.flags |= PBaseSize;
9638 size_hints.base_width = base_width;
9639 size_hints.base_height = base_height + FRAME_MENUBAR_HEIGHT (f);
9640 size_hints.min_width = base_width + min_cols * size_hints.width_inc;
9641 size_hints.min_height = base_height + min_rows * size_hints.height_inc;
9644 /* If we don't need the old flags, we don't need the old hint at all. */
9645 if (flags)
9647 size_hints.flags |= flags;
9648 goto no_read;
9652 XSizeHints hints; /* Sometimes I hate X Windows... */
9653 long supplied_return;
9654 int value;
9656 value = XGetWMNormalHints (FRAME_X_DISPLAY (f), window, &hints,
9657 &supplied_return);
9659 if (flags)
9660 size_hints.flags |= flags;
9661 else
9663 if (value == 0)
9664 hints.flags = 0;
9665 if (hints.flags & PSize)
9666 size_hints.flags |= PSize;
9667 if (hints.flags & PPosition)
9668 size_hints.flags |= PPosition;
9669 if (hints.flags & USPosition)
9670 size_hints.flags |= USPosition;
9671 if (hints.flags & USSize)
9672 size_hints.flags |= USSize;
9676 no_read:
9678 #ifdef PWinGravity
9679 size_hints.win_gravity = f->win_gravity;
9680 size_hints.flags |= PWinGravity;
9682 if (user_position)
9684 size_hints.flags &= ~ PPosition;
9685 size_hints.flags |= USPosition;
9687 #endif /* PWinGravity */
9689 XSetWMNormalHints (FRAME_X_DISPLAY (f), window, &size_hints);
9691 #endif /* not USE_GTK */
9693 /* Used for IconicState or NormalState */
9695 static void
9696 x_wm_set_window_state (struct frame *f, int state)
9698 #ifdef USE_X_TOOLKIT
9699 Arg al[1];
9701 XtSetArg (al[0], XtNinitialState, state);
9702 XtSetValues (f->output_data.x->widget, al, 1);
9703 #else /* not USE_X_TOOLKIT */
9704 Window window = FRAME_X_WINDOW (f);
9706 f->output_data.x->wm_hints.flags |= StateHint;
9707 f->output_data.x->wm_hints.initial_state = state;
9709 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
9710 #endif /* not USE_X_TOOLKIT */
9713 static void
9714 x_wm_set_icon_pixmap (struct frame *f, ptrdiff_t pixmap_id)
9716 Pixmap icon_pixmap, icon_mask;
9718 #if !defined USE_X_TOOLKIT && !defined USE_GTK
9719 Window window = FRAME_OUTER_WINDOW (f);
9720 #endif
9722 if (pixmap_id > 0)
9724 icon_pixmap = x_bitmap_pixmap (f, pixmap_id);
9725 f->output_data.x->wm_hints.icon_pixmap = icon_pixmap;
9726 icon_mask = x_bitmap_mask (f, pixmap_id);
9727 f->output_data.x->wm_hints.icon_mask = icon_mask;
9729 else
9731 /* It seems there is no way to turn off use of an icon
9732 pixmap. */
9733 return;
9737 #ifdef USE_GTK
9739 xg_set_frame_icon (f, icon_pixmap, icon_mask);
9740 return;
9743 #elif defined (USE_X_TOOLKIT) /* same as in x_wm_set_window_state. */
9746 Arg al[1];
9747 XtSetArg (al[0], XtNiconPixmap, icon_pixmap);
9748 XtSetValues (f->output_data.x->widget, al, 1);
9749 XtSetArg (al[0], XtNiconMask, icon_mask);
9750 XtSetValues (f->output_data.x->widget, al, 1);
9753 #else /* not USE_X_TOOLKIT && not USE_GTK */
9755 f->output_data.x->wm_hints.flags |= (IconPixmapHint | IconMaskHint);
9756 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
9758 #endif /* not USE_X_TOOLKIT && not USE_GTK */
9761 void
9762 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
9764 Window window = FRAME_OUTER_WINDOW (f);
9766 f->output_data.x->wm_hints.flags |= IconPositionHint;
9767 f->output_data.x->wm_hints.icon_x = icon_x;
9768 f->output_data.x->wm_hints.icon_y = icon_y;
9770 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
9774 /***********************************************************************
9775 Fonts
9776 ***********************************************************************/
9778 #if GLYPH_DEBUG
9780 /* Check that FONT is valid on frame F. It is if it can be found in F's
9781 font table. */
9783 static void
9784 x_check_font (struct frame *f, struct font *font)
9786 xassert (font != NULL && ! NILP (font->props[FONT_TYPE_INDEX]));
9787 if (font->driver->check)
9788 xassert (font->driver->check (f, font) == 0);
9791 #endif /* GLYPH_DEBUG != 0 */
9794 /***********************************************************************
9795 Initialization
9796 ***********************************************************************/
9798 #ifdef USE_X_TOOLKIT
9799 static XrmOptionDescRec emacs_options[] = {
9800 {"-geometry", ".geometry", XrmoptionSepArg, NULL},
9801 {"-iconic", ".iconic", XrmoptionNoArg, (XtPointer) "yes"},
9803 {"-internal-border-width", "*EmacsScreen.internalBorderWidth",
9804 XrmoptionSepArg, NULL},
9805 {"-ib", "*EmacsScreen.internalBorderWidth", XrmoptionSepArg, NULL},
9807 {"-T", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
9808 {"-wn", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
9809 {"-title", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
9810 {"-iconname", "*EmacsShell.iconName", XrmoptionSepArg, (XtPointer) NULL},
9811 {"-in", "*EmacsShell.iconName", XrmoptionSepArg, (XtPointer) NULL},
9812 {"-mc", "*pointerColor", XrmoptionSepArg, (XtPointer) NULL},
9813 {"-cr", "*cursorColor", XrmoptionSepArg, (XtPointer) NULL}
9816 /* Whether atimer for Xt timeouts is activated or not. */
9818 static int x_timeout_atimer_activated_flag;
9820 #endif /* USE_X_TOOLKIT */
9822 static int x_initialized;
9824 /* Test whether two display-name strings agree up to the dot that separates
9825 the screen number from the server number. */
9826 static int
9827 same_x_server (const char *name1, const char *name2)
9829 int seen_colon = 0;
9830 const char *system_name = SSDATA (Vsystem_name);
9831 ptrdiff_t system_name_length = SBYTES (Vsystem_name);
9832 ptrdiff_t length_until_period = 0;
9834 while (system_name[length_until_period] != 0
9835 && system_name[length_until_period] != '.')
9836 length_until_period++;
9838 /* Treat `unix' like an empty host name. */
9839 if (! strncmp (name1, "unix:", 5))
9840 name1 += 4;
9841 if (! strncmp (name2, "unix:", 5))
9842 name2 += 4;
9843 /* Treat this host's name like an empty host name. */
9844 if (! strncmp (name1, system_name, system_name_length)
9845 && name1[system_name_length] == ':')
9846 name1 += system_name_length;
9847 if (! strncmp (name2, system_name, system_name_length)
9848 && name2[system_name_length] == ':')
9849 name2 += system_name_length;
9850 /* Treat this host's domainless name like an empty host name. */
9851 if (! strncmp (name1, system_name, length_until_period)
9852 && name1[length_until_period] == ':')
9853 name1 += length_until_period;
9854 if (! strncmp (name2, system_name, length_until_period)
9855 && name2[length_until_period] == ':')
9856 name2 += length_until_period;
9858 for (; *name1 != '\0' && *name1 == *name2; name1++, name2++)
9860 if (*name1 == ':')
9861 seen_colon = 1;
9862 if (seen_colon && *name1 == '.')
9863 return 1;
9865 return (seen_colon
9866 && (*name1 == '.' || *name1 == '\0')
9867 && (*name2 == '.' || *name2 == '\0'));
9870 /* Count number of set bits in mask and number of bits to shift to
9871 get to the first bit. With MASK 0x7e0, *BITS is set to 6, and *OFFSET
9872 to 5. */
9873 static void
9874 get_bits_and_offset (long unsigned int mask, int *bits, int *offset)
9876 int nr = 0;
9877 int off = 0;
9879 while (!(mask & 1))
9881 off++;
9882 mask >>= 1;
9885 while (mask & 1)
9887 nr++;
9888 mask >>= 1;
9891 *offset = off;
9892 *bits = nr;
9895 /* Return 1 if display DISPLAY is available for use, 0 otherwise.
9896 But don't permanently open it, just test its availability. */
9899 x_display_ok (const char *display)
9901 int dpy_ok = 1;
9902 Display *dpy;
9904 dpy = XOpenDisplay (display);
9905 if (dpy)
9906 XCloseDisplay (dpy);
9907 else
9908 dpy_ok = 0;
9909 return dpy_ok;
9912 #ifdef USE_GTK
9913 static void
9914 my_log_handler (const gchar *log_domain, GLogLevelFlags log_level,
9915 const gchar *msg, gpointer user_data)
9917 if (!strstr (msg, "g_set_prgname"))
9918 fprintf (stderr, "%s-WARNING **: %s\n", log_domain, msg);
9920 #endif
9922 /* Open a connection to X display DISPLAY_NAME, and return
9923 the structure that describes the open display.
9924 If we cannot contact the display, return null. */
9926 struct x_display_info *
9927 x_term_init (Lisp_Object display_name, char *xrm_option, char *resource_name)
9929 int connection;
9930 Display *dpy;
9931 struct terminal *terminal;
9932 struct x_display_info *dpyinfo;
9933 XrmDatabase xrdb;
9934 Mouse_HLInfo *hlinfo;
9935 ptrdiff_t lim;
9937 BLOCK_INPUT;
9939 if (!x_initialized)
9941 x_initialize ();
9942 ++x_initialized;
9945 if (! x_display_ok (SSDATA (display_name)))
9946 error ("Display %s can't be opened", SSDATA (display_name));
9948 #ifdef USE_GTK
9950 #define NUM_ARGV 10
9951 int argc;
9952 char *argv[NUM_ARGV];
9953 char **argv2 = argv;
9954 guint id;
9956 if (x_initialized++ > 1)
9958 xg_display_open (SSDATA (display_name), &dpy);
9960 else
9962 static char display_opt[] = "--display";
9963 static char name_opt[] = "--name";
9965 for (argc = 0; argc < NUM_ARGV; ++argc)
9966 argv[argc] = 0;
9968 argc = 0;
9969 argv[argc++] = initial_argv[0];
9971 if (! NILP (display_name))
9973 argv[argc++] = display_opt;
9974 argv[argc++] = SSDATA (display_name);
9977 argv[argc++] = name_opt;
9978 argv[argc++] = resource_name;
9980 XSetLocaleModifiers ("");
9982 /* Emacs can only handle core input events, so make sure
9983 Gtk doesn't use Xinput or Xinput2 extensions. */
9985 static char fix_events[] = "GDK_CORE_DEVICE_EVENTS=1";
9986 putenv (fix_events);
9989 /* Work around GLib bug that outputs a faulty warning. See
9990 https://bugzilla.gnome.org/show_bug.cgi?id=563627. */
9991 id = g_log_set_handler ("GLib", G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
9992 | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
9994 /* NULL window -> events for all windows go to our function.
9995 Call before gtk_init so Gtk+ event filters comes after our. */
9996 gdk_window_add_filter (NULL, event_handler_gdk, NULL);
9998 gtk_init (&argc, &argv2);
9999 g_log_remove_handler ("GLib", id);
10001 /* gtk_init does set_locale. We must fix locale after calling it. */
10002 fixup_locale ();
10003 xg_initialize ();
10005 dpy = DEFAULT_GDK_DISPLAY ();
10007 #if GTK_MAJOR_VERSION <= 2 && GTK_MINOR_VERSION <= 90
10008 /* Load our own gtkrc if it exists. */
10010 const char *file = "~/.emacs.d/gtkrc";
10011 Lisp_Object s, abs_file;
10013 s = make_string (file, strlen (file));
10014 abs_file = Fexpand_file_name (s, Qnil);
10016 if (! NILP (abs_file) && !NILP (Ffile_readable_p (abs_file)))
10017 gtk_rc_parse (SSDATA (abs_file));
10019 #endif
10021 XSetErrorHandler (x_error_handler);
10022 XSetIOErrorHandler (x_io_error_quitter);
10025 #else /* not USE_GTK */
10026 #ifdef USE_X_TOOLKIT
10027 /* weiner@footloose.sps.mot.com reports that this causes
10028 errors with X11R5:
10029 X protocol error: BadAtom (invalid Atom parameter)
10030 on protocol request 18skiloaf.
10031 So let's not use it until R6. */
10032 #ifdef HAVE_X11XTR6
10033 XtSetLanguageProc (NULL, NULL, NULL);
10034 #endif
10037 int argc = 0;
10038 char *argv[3];
10040 argv[0] = "";
10041 argc = 1;
10042 if (xrm_option)
10044 argv[argc++] = "-xrm";
10045 argv[argc++] = xrm_option;
10047 turn_on_atimers (0);
10048 dpy = XtOpenDisplay (Xt_app_con, SSDATA (display_name),
10049 resource_name, EMACS_CLASS,
10050 emacs_options, XtNumber (emacs_options),
10051 &argc, argv);
10052 turn_on_atimers (1);
10054 #ifdef HAVE_X11XTR6
10055 /* I think this is to compensate for XtSetLanguageProc. */
10056 fixup_locale ();
10057 #endif
10060 #else /* not USE_X_TOOLKIT */
10061 XSetLocaleModifiers ("");
10062 dpy = XOpenDisplay (SSDATA (display_name));
10063 #endif /* not USE_X_TOOLKIT */
10064 #endif /* not USE_GTK*/
10066 /* Detect failure. */
10067 if (dpy == 0)
10069 UNBLOCK_INPUT;
10070 return 0;
10073 /* We have definitely succeeded. Record the new connection. */
10075 dpyinfo = (struct x_display_info *) xmalloc (sizeof (struct x_display_info));
10076 memset (dpyinfo, 0, sizeof *dpyinfo);
10077 hlinfo = &dpyinfo->mouse_highlight;
10079 terminal = x_create_terminal (dpyinfo);
10082 struct x_display_info *share;
10083 Lisp_Object tail;
10085 for (share = x_display_list, tail = x_display_name_list; share;
10086 share = share->next, tail = XCDR (tail))
10087 if (same_x_server (SSDATA (XCAR (XCAR (tail))),
10088 SSDATA (display_name)))
10089 break;
10090 if (share)
10091 terminal->kboard = share->terminal->kboard;
10092 else
10094 terminal->kboard = (KBOARD *) xmalloc (sizeof (KBOARD));
10095 init_kboard (terminal->kboard);
10096 KVAR (terminal->kboard, Vwindow_system) = Qx;
10098 /* Add the keyboard to the list before running Lisp code (via
10099 Qvendor_specific_keysyms below), since these are not traced
10100 via terminals but only through all_kboards. */
10101 terminal->kboard->next_kboard = all_kboards;
10102 all_kboards = terminal->kboard;
10104 if (!EQ (XSYMBOL (Qvendor_specific_keysyms)->function, Qunbound))
10106 char *vendor = ServerVendor (dpy);
10108 /* Protect terminal from GC before removing it from the
10109 list of terminals. */
10110 struct gcpro gcpro1;
10111 Lisp_Object gcpro_term;
10112 XSETTERMINAL (gcpro_term, terminal);
10113 GCPRO1 (gcpro_term);
10115 /* Temporarily hide the partially initialized terminal. */
10116 terminal_list = terminal->next_terminal;
10117 UNBLOCK_INPUT;
10118 KVAR (terminal->kboard, Vsystem_key_alist)
10119 = call1 (Qvendor_specific_keysyms,
10120 vendor ? build_string (vendor) : empty_unibyte_string);
10121 BLOCK_INPUT;
10122 terminal->next_terminal = terminal_list;
10123 terminal_list = terminal;
10124 UNGCPRO;
10127 /* Don't let the initial kboard remain current longer than necessary.
10128 That would cause problems if a file loaded on startup tries to
10129 prompt in the mini-buffer. */
10130 if (current_kboard == initial_kboard)
10131 current_kboard = terminal->kboard;
10133 terminal->kboard->reference_count++;
10136 /* Put this display on the chain. */
10137 dpyinfo->next = x_display_list;
10138 x_display_list = dpyinfo;
10140 /* Put it on x_display_name_list as well, to keep them parallel. */
10141 x_display_name_list = Fcons (Fcons (display_name, Qnil),
10142 x_display_name_list);
10143 dpyinfo->name_list_element = XCAR (x_display_name_list);
10145 dpyinfo->display = dpy;
10147 /* Set the name of the terminal. */
10148 terminal->name = (char *) xmalloc (SBYTES (display_name) + 1);
10149 strncpy (terminal->name, SSDATA (display_name), SBYTES (display_name));
10150 terminal->name[SBYTES (display_name)] = 0;
10152 #if 0
10153 XSetAfterFunction (x_current_display, x_trace_wire);
10154 #endif /* ! 0 */
10156 lim = min (PTRDIFF_MAX, SIZE_MAX) - sizeof "@";
10157 if (lim - SBYTES (Vinvocation_name) < SBYTES (Vsystem_name))
10158 memory_full (SIZE_MAX);
10159 dpyinfo->x_id_name
10160 = (char *) xmalloc (SBYTES (Vinvocation_name)
10161 + SBYTES (Vsystem_name)
10162 + 2);
10163 strcat (strcat (strcpy (dpyinfo->x_id_name, SSDATA (Vinvocation_name)), "@"),
10164 SSDATA (Vsystem_name));
10166 /* Figure out which modifier bits mean what. */
10167 x_find_modifier_meanings (dpyinfo);
10169 /* Get the scroll bar cursor. */
10170 #ifdef USE_GTK
10171 /* We must create a GTK cursor, it is required for GTK widgets. */
10172 dpyinfo->xg_cursor = xg_create_default_cursor (dpyinfo->display);
10173 #endif /* USE_GTK */
10175 dpyinfo->vertical_scroll_bar_cursor
10176 = XCreateFontCursor (dpyinfo->display, XC_sb_v_double_arrow);
10178 xrdb = x_load_resources (dpyinfo->display, xrm_option,
10179 resource_name, EMACS_CLASS);
10180 #ifdef HAVE_XRMSETDATABASE
10181 XrmSetDatabase (dpyinfo->display, xrdb);
10182 #else
10183 dpyinfo->display->db = xrdb;
10184 #endif
10185 /* Put the rdb where we can find it in a way that works on
10186 all versions. */
10187 dpyinfo->xrdb = xrdb;
10189 dpyinfo->screen = ScreenOfDisplay (dpyinfo->display,
10190 DefaultScreen (dpyinfo->display));
10191 select_visual (dpyinfo);
10192 dpyinfo->cmap = DefaultColormapOfScreen (dpyinfo->screen);
10193 dpyinfo->root_window = RootWindowOfScreen (dpyinfo->screen);
10194 dpyinfo->client_leader_window = 0;
10195 dpyinfo->grabbed = 0;
10196 dpyinfo->reference_count = 0;
10197 dpyinfo->icon_bitmap_id = -1;
10198 dpyinfo->n_fonts = 0;
10199 dpyinfo->bitmaps = 0;
10200 dpyinfo->bitmaps_size = 0;
10201 dpyinfo->bitmaps_last = 0;
10202 dpyinfo->scratch_cursor_gc = 0;
10203 hlinfo->mouse_face_mouse_frame = 0;
10204 hlinfo->mouse_face_deferred_gc = 0;
10205 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
10206 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
10207 hlinfo->mouse_face_face_id = DEFAULT_FACE_ID;
10208 hlinfo->mouse_face_window = Qnil;
10209 hlinfo->mouse_face_overlay = Qnil;
10210 hlinfo->mouse_face_mouse_x = hlinfo->mouse_face_mouse_y = 0;
10211 hlinfo->mouse_face_defer = 0;
10212 hlinfo->mouse_face_hidden = 0;
10213 dpyinfo->x_focus_frame = 0;
10214 dpyinfo->x_focus_event_frame = 0;
10215 dpyinfo->x_highlight_frame = 0;
10216 dpyinfo->wm_type = X_WMTYPE_UNKNOWN;
10218 /* See if we can construct pixel values from RGB values. */
10219 dpyinfo->red_bits = dpyinfo->blue_bits = dpyinfo->green_bits = 0;
10220 dpyinfo->red_offset = dpyinfo->blue_offset = dpyinfo->green_offset = 0;
10222 if (dpyinfo->visual->class == TrueColor)
10224 get_bits_and_offset (dpyinfo->visual->red_mask,
10225 &dpyinfo->red_bits, &dpyinfo->red_offset);
10226 get_bits_and_offset (dpyinfo->visual->blue_mask,
10227 &dpyinfo->blue_bits, &dpyinfo->blue_offset);
10228 get_bits_and_offset (dpyinfo->visual->green_mask,
10229 &dpyinfo->green_bits, &dpyinfo->green_offset);
10232 /* See if a private colormap is requested. */
10233 if (dpyinfo->visual == DefaultVisualOfScreen (dpyinfo->screen))
10235 if (dpyinfo->visual->class == PseudoColor)
10237 Lisp_Object value;
10238 value = display_x_get_resource (dpyinfo,
10239 build_string ("privateColormap"),
10240 build_string ("PrivateColormap"),
10241 Qnil, Qnil);
10242 if (STRINGP (value)
10243 && (!strcmp (SSDATA (value), "true")
10244 || !strcmp (SSDATA (value), "on")))
10245 dpyinfo->cmap = XCopyColormapAndFree (dpyinfo->display, dpyinfo->cmap);
10248 else
10249 dpyinfo->cmap = XCreateColormap (dpyinfo->display, dpyinfo->root_window,
10250 dpyinfo->visual, AllocNone);
10252 #ifdef HAVE_XFT
10254 /* If we are using Xft, check dpi value in X resources.
10255 It is better we use it as well, since Xft will use it, as will all
10256 Gnome applications. If our real DPI is smaller or larger than the
10257 one Xft uses, our font will look smaller or larger than other
10258 for other applications, even if it is the same font name (monospace-10
10259 for example). */
10260 char *v = XGetDefault (dpyinfo->display, "Xft", "dpi");
10261 double d;
10262 if (v != NULL && sscanf (v, "%lf", &d) == 1)
10263 dpyinfo->resy = dpyinfo->resx = d;
10265 #endif
10267 if (dpyinfo->resy < 1)
10269 int screen_number = XScreenNumberOfScreen (dpyinfo->screen);
10270 double pixels = DisplayHeight (dpyinfo->display, screen_number);
10271 double mm = DisplayHeightMM (dpyinfo->display, screen_number);
10272 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
10273 dpyinfo->resy = (mm < 1) ? 100 : pixels * 25.4 / mm;
10274 pixels = DisplayWidth (dpyinfo->display, screen_number);
10275 mm = DisplayWidthMM (dpyinfo->display, screen_number);
10276 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
10277 dpyinfo->resx = (mm < 1) ? 100 : pixels * 25.4 / mm;
10281 const struct
10283 const char *name;
10284 Atom *atom;
10285 } atom_refs[] = {
10286 { "WM_PROTOCOLS", &dpyinfo->Xatom_wm_protocols },
10287 { "WM_TAKE_FOCUS", &dpyinfo->Xatom_wm_take_focus },
10288 { "WM_SAVE_YOURSELF", &dpyinfo->Xatom_wm_save_yourself },
10289 { "WM_DELETE_WINDOW", &dpyinfo->Xatom_wm_delete_window },
10290 { "WM_CHANGE_STATE", &dpyinfo->Xatom_wm_change_state },
10291 { "WM_CONFIGURE_DENIED", &dpyinfo->Xatom_wm_configure_denied },
10292 { "WM_MOVED", &dpyinfo->Xatom_wm_window_moved },
10293 { "WM_CLIENT_LEADER", &dpyinfo->Xatom_wm_client_leader },
10294 { "Editres", &dpyinfo->Xatom_editres },
10295 { "CLIPBOARD", &dpyinfo->Xatom_CLIPBOARD },
10296 { "TIMESTAMP", &dpyinfo->Xatom_TIMESTAMP },
10297 { "TEXT", &dpyinfo->Xatom_TEXT },
10298 { "COMPOUND_TEXT", &dpyinfo->Xatom_COMPOUND_TEXT },
10299 { "UTF8_STRING", &dpyinfo->Xatom_UTF8_STRING },
10300 { "DELETE", &dpyinfo->Xatom_DELETE },
10301 { "MULTIPLE", &dpyinfo->Xatom_MULTIPLE },
10302 { "INCR", &dpyinfo->Xatom_INCR },
10303 { "_EMACS_TMP_", &dpyinfo->Xatom_EMACS_TMP },
10304 { "TARGETS", &dpyinfo->Xatom_TARGETS },
10305 { "NULL", &dpyinfo->Xatom_NULL },
10306 { "ATOM", &dpyinfo->Xatom_ATOM },
10307 { "ATOM_PAIR", &dpyinfo->Xatom_ATOM_PAIR },
10308 { "CLIPBOARD_MANAGER", &dpyinfo->Xatom_CLIPBOARD_MANAGER },
10309 { "_XEMBED_INFO", &dpyinfo->Xatom_XEMBED_INFO },
10310 /* For properties of font. */
10311 { "PIXEL_SIZE", &dpyinfo->Xatom_PIXEL_SIZE },
10312 { "AVERAGE_WIDTH", &dpyinfo->Xatom_AVERAGE_WIDTH },
10313 { "_MULE_BASELINE_OFFSET", &dpyinfo->Xatom_MULE_BASELINE_OFFSET },
10314 { "_MULE_RELATIVE_COMPOSE", &dpyinfo->Xatom_MULE_RELATIVE_COMPOSE },
10315 { "_MULE_DEFAULT_ASCENT", &dpyinfo->Xatom_MULE_DEFAULT_ASCENT },
10316 /* Ghostscript support. */
10317 { "DONE", &dpyinfo->Xatom_DONE },
10318 { "PAGE", &dpyinfo->Xatom_PAGE },
10319 { "SCROLLBAR", &dpyinfo->Xatom_Scrollbar },
10320 { "_XEMBED", &dpyinfo->Xatom_XEMBED },
10321 /* EWMH */
10322 { "_NET_WM_STATE", &dpyinfo->Xatom_net_wm_state },
10323 { "_NET_WM_STATE_FULLSCREEN", &dpyinfo->Xatom_net_wm_state_fullscreen },
10324 { "_NET_WM_STATE_MAXIMIZED_HORZ",
10325 &dpyinfo->Xatom_net_wm_state_maximized_horz },
10326 { "_NET_WM_STATE_MAXIMIZED_VERT",
10327 &dpyinfo->Xatom_net_wm_state_maximized_vert },
10328 { "_NET_WM_STATE_STICKY", &dpyinfo->Xatom_net_wm_state_sticky },
10329 { "_NET_WM_STATE_HIDDEN", &dpyinfo->Xatom_net_wm_state_hidden },
10330 { "_NET_WM_WINDOW_TYPE", &dpyinfo->Xatom_net_window_type },
10331 { "_NET_WM_WINDOW_TYPE_TOOLTIP",
10332 &dpyinfo->Xatom_net_window_type_tooltip },
10333 { "_NET_WM_ICON_NAME", &dpyinfo->Xatom_net_wm_icon_name },
10334 { "_NET_WM_NAME", &dpyinfo->Xatom_net_wm_name },
10335 { "_NET_SUPPORTED", &dpyinfo->Xatom_net_supported },
10336 { "_NET_SUPPORTING_WM_CHECK", &dpyinfo->Xatom_net_supporting_wm_check },
10337 { "_NET_WM_WINDOW_OPACITY", &dpyinfo->Xatom_net_wm_window_opacity },
10338 { "_NET_ACTIVE_WINDOW", &dpyinfo->Xatom_net_active_window },
10339 { "_NET_FRAME_EXTENTS", &dpyinfo->Xatom_net_frame_extents },
10340 /* Session management */
10341 { "SM_CLIENT_ID", &dpyinfo->Xatom_SM_CLIENT_ID },
10342 { "_XSETTINGS_SETTINGS", &dpyinfo->Xatom_xsettings_prop },
10343 { "MANAGER", &dpyinfo->Xatom_xsettings_mgr },
10346 int i;
10347 const int atom_count = sizeof (atom_refs) / sizeof (atom_refs[0]);
10348 /* 1 for _XSETTINGS_SN */
10349 const int total_atom_count = 1 + atom_count;
10350 Atom *atoms_return = xmalloc (sizeof (Atom) * total_atom_count);
10351 char **atom_names = xmalloc (sizeof (char *) * total_atom_count);
10352 char xsettings_atom_name[64];
10354 for (i = 0; i < atom_count; i++)
10355 atom_names[i] = (char *) atom_refs[i].name;
10357 /* Build _XSETTINGS_SN atom name */
10358 snprintf (xsettings_atom_name, sizeof (xsettings_atom_name),
10359 "_XSETTINGS_S%d", XScreenNumberOfScreen (dpyinfo->screen));
10360 atom_names[i] = xsettings_atom_name;
10362 XInternAtoms (dpyinfo->display, atom_names, total_atom_count,
10363 False, atoms_return);
10365 for (i = 0; i < atom_count; i++)
10366 *atom_refs[i].atom = atoms_return[i];
10368 /* Manual copy of last atom */
10369 dpyinfo->Xatom_xsettings_sel = atoms_return[i];
10371 xfree (atom_names);
10372 xfree (atoms_return);
10375 dpyinfo->x_dnd_atoms_size = 8;
10376 dpyinfo->x_dnd_atoms_length = 0;
10377 dpyinfo->x_dnd_atoms = xmalloc (sizeof (*dpyinfo->x_dnd_atoms)
10378 * dpyinfo->x_dnd_atoms_size);
10380 dpyinfo->net_supported_atoms = NULL;
10381 dpyinfo->nr_net_supported_atoms = 0;
10382 dpyinfo->net_supported_window = 0;
10384 connection = ConnectionNumber (dpyinfo->display);
10385 dpyinfo->connection = connection;
10388 dpyinfo->gray
10389 = XCreatePixmapFromBitmapData (dpyinfo->display, dpyinfo->root_window,
10390 gray_bitmap_bits,
10391 gray_bitmap_width, gray_bitmap_height,
10392 1, 0, 1);
10395 #ifdef HAVE_X_I18N
10396 xim_initialize (dpyinfo, resource_name);
10397 #endif
10399 xsettings_initialize (dpyinfo);
10401 /* This is only needed for distinguishing keyboard and process input. */
10402 if (connection != 0)
10403 add_keyboard_wait_descriptor (connection);
10405 #ifdef F_SETOWN
10406 fcntl (connection, F_SETOWN, getpid ());
10407 #endif /* ! defined (F_SETOWN) */
10409 #ifdef SIGIO
10410 if (interrupt_input)
10411 init_sigio (connection);
10412 #endif /* ! defined (SIGIO) */
10414 #ifdef USE_LUCID
10416 XrmValue d, fr, to;
10417 Font font;
10419 dpy = dpyinfo->display;
10420 d.addr = (XPointer)&dpy;
10421 d.size = sizeof (Display *);
10422 fr.addr = XtDefaultFont;
10423 fr.size = sizeof (XtDefaultFont);
10424 to.size = sizeof (Font *);
10425 to.addr = (XPointer)&font;
10426 x_catch_errors (dpy);
10427 if (!XtCallConverter (dpy, XtCvtStringToFont, &d, 1, &fr, &to, NULL))
10428 abort ();
10429 if (x_had_errors_p (dpy) || !XQueryFont (dpy, font))
10430 XrmPutLineResource (&xrdb, "Emacs.dialog.*.font: 9x15");
10431 x_uncatch_errors ();
10433 #endif
10435 /* See if we should run in synchronous mode. This is useful
10436 for debugging X code. */
10438 Lisp_Object value;
10439 value = display_x_get_resource (dpyinfo,
10440 build_string ("synchronous"),
10441 build_string ("Synchronous"),
10442 Qnil, Qnil);
10443 if (STRINGP (value)
10444 && (!strcmp (SSDATA (value), "true")
10445 || !strcmp (SSDATA (value), "on")))
10446 XSynchronize (dpyinfo->display, True);
10450 Lisp_Object value;
10451 value = display_x_get_resource (dpyinfo,
10452 build_string ("useXIM"),
10453 build_string ("UseXIM"),
10454 Qnil, Qnil);
10455 #ifdef USE_XIM
10456 if (STRINGP (value)
10457 && (!strcmp (SSDATA (value), "false")
10458 || !strcmp (SSDATA (value), "off")))
10459 use_xim = 0;
10460 #else
10461 if (STRINGP (value)
10462 && (!strcmp (SSDATA (value), "true")
10463 || !strcmp (SSDATA (value), "on")))
10464 use_xim = 1;
10465 #endif
10468 #ifdef HAVE_X_SM
10469 /* Only do this for the very first display in the Emacs session.
10470 Ignore X session management when Emacs was first started on a
10471 tty. */
10472 if (terminal->id == 1)
10473 x_session_initialize (dpyinfo);
10474 #endif
10476 UNBLOCK_INPUT;
10478 return dpyinfo;
10481 /* Get rid of display DPYINFO, deleting all frames on it,
10482 and without sending any more commands to the X server. */
10484 static void
10485 x_delete_display (struct x_display_info *dpyinfo)
10487 struct terminal *t;
10489 /* Close all frames and delete the generic struct terminal for this
10490 X display. */
10491 for (t = terminal_list; t; t = t->next_terminal)
10492 if (t->type == output_x_window && t->display_info.x == dpyinfo)
10494 #ifdef HAVE_X_SM
10495 /* Close X session management when we close its display. */
10496 if (t->id == 1 && x_session_have_connection ())
10497 x_session_close ();
10498 #endif
10499 delete_terminal (t);
10500 break;
10503 delete_keyboard_wait_descriptor (dpyinfo->connection);
10505 /* Discard this display from x_display_name_list and x_display_list.
10506 We can't use Fdelq because that can quit. */
10507 if (! NILP (x_display_name_list)
10508 && EQ (XCAR (x_display_name_list), dpyinfo->name_list_element))
10509 x_display_name_list = XCDR (x_display_name_list);
10510 else
10512 Lisp_Object tail;
10514 tail = x_display_name_list;
10515 while (CONSP (tail) && CONSP (XCDR (tail)))
10517 if (EQ (XCAR (XCDR (tail)), dpyinfo->name_list_element))
10519 XSETCDR (tail, XCDR (XCDR (tail)));
10520 break;
10522 tail = XCDR (tail);
10526 if (next_noop_dpyinfo == dpyinfo)
10527 next_noop_dpyinfo = dpyinfo->next;
10529 if (x_display_list == dpyinfo)
10530 x_display_list = dpyinfo->next;
10531 else
10533 struct x_display_info *tail;
10535 for (tail = x_display_list; tail; tail = tail->next)
10536 if (tail->next == dpyinfo)
10537 tail->next = tail->next->next;
10540 xfree (dpyinfo->x_id_name);
10541 xfree (dpyinfo->x_dnd_atoms);
10542 xfree (dpyinfo->color_cells);
10543 xfree (dpyinfo);
10546 #ifdef USE_X_TOOLKIT
10548 /* Atimer callback function for TIMER. Called every 0.1s to process
10549 Xt timeouts, if needed. We must avoid calling XtAppPending as
10550 much as possible because that function does an implicit XFlush
10551 that slows us down. */
10553 static void
10554 x_process_timeouts (struct atimer *timer)
10556 BLOCK_INPUT;
10557 x_timeout_atimer_activated_flag = 0;
10558 if (toolkit_scroll_bar_interaction || popup_activated ())
10560 while (XtAppPending (Xt_app_con) & XtIMTimer)
10561 XtAppProcessEvent (Xt_app_con, XtIMTimer);
10562 /* Reactivate the atimer for next time. */
10563 x_activate_timeout_atimer ();
10565 UNBLOCK_INPUT;
10568 /* Install an asynchronous timer that processes Xt timeout events
10569 every 0.1s as long as either `toolkit_scroll_bar_interaction' or
10570 `popup_activated_flag' (in xmenu.c) is set. Make sure to call this
10571 function whenever these variables are set. This is necessary
10572 because some widget sets use timeouts internally, for example the
10573 LessTif menu bar, or the Xaw3d scroll bar. When Xt timeouts aren't
10574 processed, these widgets don't behave normally. */
10576 void
10577 x_activate_timeout_atimer (void)
10579 BLOCK_INPUT;
10580 if (!x_timeout_atimer_activated_flag)
10582 EMACS_TIME interval;
10584 EMACS_SET_SECS_USECS (interval, 0, 100000);
10585 start_atimer (ATIMER_RELATIVE, interval, x_process_timeouts, 0);
10586 x_timeout_atimer_activated_flag = 1;
10588 UNBLOCK_INPUT;
10591 #endif /* USE_X_TOOLKIT */
10594 /* Set up use of X before we make the first connection. */
10596 extern frame_parm_handler x_frame_parm_handlers[];
10598 static struct redisplay_interface x_redisplay_interface =
10600 x_frame_parm_handlers,
10601 x_produce_glyphs,
10602 x_write_glyphs,
10603 x_insert_glyphs,
10604 x_clear_end_of_line,
10605 x_scroll_run,
10606 x_after_update_window_line,
10607 x_update_window_begin,
10608 x_update_window_end,
10609 x_cursor_to,
10610 x_flush,
10611 #ifdef XFlush
10612 x_flush,
10613 #else
10614 0, /* flush_display_optional */
10615 #endif
10616 x_clear_window_mouse_face,
10617 x_get_glyph_overhangs,
10618 x_fix_overlapping_area,
10619 x_draw_fringe_bitmap,
10620 0, /* define_fringe_bitmap */
10621 0, /* destroy_fringe_bitmap */
10622 x_compute_glyph_string_overhangs,
10623 x_draw_glyph_string,
10624 x_define_frame_cursor,
10625 x_clear_frame_area,
10626 x_draw_window_cursor,
10627 x_draw_vertical_window_border,
10628 x_shift_glyphs_for_insert
10632 /* This function is called when the last frame on a display is deleted. */
10633 void
10634 x_delete_terminal (struct terminal *terminal)
10636 struct x_display_info *dpyinfo = terminal->display_info.x;
10638 /* Protect against recursive calls. delete_frame in
10639 delete_terminal calls us back when it deletes our last frame. */
10640 if (!terminal->name)
10641 return;
10643 BLOCK_INPUT;
10644 #ifdef HAVE_X_I18N
10645 /* We must close our connection to the XIM server before closing the
10646 X display. */
10647 if (dpyinfo->xim)
10648 xim_close_dpy (dpyinfo);
10649 #endif
10651 /* If called from x_connection_closed, the display may already be closed
10652 and dpyinfo->display was set to 0 to indicate that. */
10653 if (dpyinfo->display)
10655 x_destroy_all_bitmaps (dpyinfo);
10656 XSetCloseDownMode (dpyinfo->display, DestroyAll);
10658 /* Whether or not XCloseDisplay destroys the associated resource
10659 database depends on the version of libX11. To avoid both
10660 crash and memory leak, we dissociate the database from the
10661 display and then destroy dpyinfo->xrdb ourselves.
10663 Unfortunately, the above strategy does not work in some
10664 situations due to a bug in newer versions of libX11: because
10665 XrmSetDatabase doesn't clear the flag XlibDisplayDfltRMDB if
10666 dpy->db is NULL, XCloseDisplay destroys the associated
10667 database whereas it has not been created by XGetDefault
10668 (Bug#21974 in freedesktop.org Bugzilla). As a workaround, we
10669 don't destroy the database here in order to avoid the crash
10670 in the above situations for now, though that may cause memory
10671 leaks in other situations. */
10672 #if 0
10673 #ifdef HAVE_XRMSETDATABASE
10674 XrmSetDatabase (dpyinfo->display, NULL);
10675 #else
10676 dpyinfo->display->db = NULL;
10677 #endif
10678 /* We used to call XrmDestroyDatabase from x_delete_display, but
10679 some older versions of libX11 crash if we call it after
10680 closing all the displays. */
10681 XrmDestroyDatabase (dpyinfo->xrdb);
10682 #endif
10684 #ifdef USE_GTK
10685 xg_display_close (dpyinfo->display);
10686 #else
10687 #ifdef USE_X_TOOLKIT
10688 XtCloseDisplay (dpyinfo->display);
10689 #else
10690 XCloseDisplay (dpyinfo->display);
10691 #endif
10692 #endif /* ! USE_GTK */
10695 /* Mark as dead. */
10696 dpyinfo->display = NULL;
10697 x_delete_display (dpyinfo);
10698 UNBLOCK_INPUT;
10701 /* Create a struct terminal, initialize it with the X11 specific
10702 functions and make DISPLAY->TERMINAL point to it. */
10704 static struct terminal *
10705 x_create_terminal (struct x_display_info *dpyinfo)
10707 struct terminal *terminal;
10709 terminal = create_terminal ();
10711 terminal->type = output_x_window;
10712 terminal->display_info.x = dpyinfo;
10713 dpyinfo->terminal = terminal;
10715 /* kboard is initialized in x_term_init. */
10717 terminal->clear_frame_hook = x_clear_frame;
10718 terminal->ins_del_lines_hook = x_ins_del_lines;
10719 terminal->delete_glyphs_hook = x_delete_glyphs;
10720 terminal->ring_bell_hook = XTring_bell;
10721 terminal->toggle_invisible_pointer_hook = XTtoggle_invisible_pointer;
10722 terminal->reset_terminal_modes_hook = XTreset_terminal_modes;
10723 terminal->set_terminal_modes_hook = XTset_terminal_modes;
10724 terminal->update_begin_hook = x_update_begin;
10725 terminal->update_end_hook = x_update_end;
10726 terminal->set_terminal_window_hook = XTset_terminal_window;
10727 terminal->read_socket_hook = XTread_socket;
10728 terminal->frame_up_to_date_hook = XTframe_up_to_date;
10729 terminal->mouse_position_hook = XTmouse_position;
10730 terminal->frame_rehighlight_hook = XTframe_rehighlight;
10731 terminal->frame_raise_lower_hook = XTframe_raise_lower;
10732 terminal->fullscreen_hook = XTfullscreen_hook;
10733 terminal->set_vertical_scroll_bar_hook = XTset_vertical_scroll_bar;
10734 terminal->condemn_scroll_bars_hook = XTcondemn_scroll_bars;
10735 terminal->redeem_scroll_bar_hook = XTredeem_scroll_bar;
10736 terminal->judge_scroll_bars_hook = XTjudge_scroll_bars;
10738 terminal->delete_frame_hook = x_destroy_window;
10739 terminal->delete_terminal_hook = x_delete_terminal;
10741 terminal->rif = &x_redisplay_interface;
10742 terminal->scroll_region_ok = 1; /* We'll scroll partial frames. */
10743 terminal->char_ins_del_ok = 1;
10744 terminal->line_ins_del_ok = 1; /* We'll just blt 'em. */
10745 terminal->fast_clear_end_of_line = 1; /* X does this well. */
10746 terminal->memory_below_frame = 0; /* We don't remember what scrolls
10747 off the bottom. */
10749 return terminal;
10752 void
10753 x_initialize (void)
10755 baud_rate = 19200;
10757 x_noop_count = 0;
10758 last_tool_bar_item = -1;
10759 any_help_event_p = 0;
10760 ignore_next_mouse_click_timeout = 0;
10762 #ifdef USE_GTK
10763 current_count = -1;
10764 #endif
10766 /* Try to use interrupt input; if we can't, then start polling. */
10767 Fset_input_interrupt_mode (Qt);
10769 #ifdef USE_X_TOOLKIT
10770 XtToolkitInitialize ();
10772 Xt_app_con = XtCreateApplicationContext ();
10774 /* Register a converter from strings to pixels, which uses
10775 Emacs' color allocation infrastructure. */
10776 XtAppSetTypeConverter (Xt_app_con,
10777 XtRString, XtRPixel, cvt_string_to_pixel,
10778 cvt_string_to_pixel_args,
10779 XtNumber (cvt_string_to_pixel_args),
10780 XtCacheByDisplay, cvt_pixel_dtor);
10782 XtAppSetFallbackResources (Xt_app_con, Xt_default_resources);
10783 #endif
10785 #ifdef USE_TOOLKIT_SCROLL_BARS
10786 #ifndef USE_GTK
10787 xaw3d_arrow_scroll = False;
10788 xaw3d_pick_top = True;
10789 #endif
10790 #endif
10792 pending_autoraise_frame = 0;
10793 pending_event_wait.f = 0;
10794 pending_event_wait.eventtype = 0;
10796 /* Note that there is no real way portable across R3/R4 to get the
10797 original error handler. */
10798 XSetErrorHandler (x_error_handler);
10799 XSetIOErrorHandler (x_io_error_quitter);
10801 signal (SIGPIPE, x_connection_signal);
10803 xgselect_initialize ();
10807 void
10808 syms_of_xterm (void)
10810 x_error_message = NULL;
10812 staticpro (&x_display_name_list);
10813 x_display_name_list = Qnil;
10815 staticpro (&last_mouse_scroll_bar);
10816 last_mouse_scroll_bar = Qnil;
10818 DEFSYM (Qvendor_specific_keysyms, "vendor-specific-keysyms");
10819 DEFSYM (Qlatin_1, "latin-1");
10821 staticpro (&last_mouse_press_frame);
10822 last_mouse_press_frame = Qnil;
10824 #ifdef USE_GTK
10825 xg_default_icon_file = make_pure_c_string ("icons/hicolor/scalable/apps/emacs.svg");
10826 staticpro (&xg_default_icon_file);
10828 DEFSYM (Qx_gtk_map_stock, "x-gtk-map-stock");
10829 #endif
10831 DEFVAR_BOOL ("x-use-underline-position-properties",
10832 x_use_underline_position_properties,
10833 doc: /* *Non-nil means make use of UNDERLINE_POSITION font properties.
10834 A value of nil means ignore them. If you encounter fonts with bogus
10835 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
10836 to 4.1, set this to nil. You can also use `underline-minimum-offset'
10837 to override the font's UNDERLINE_POSITION for small font display
10838 sizes. */);
10839 x_use_underline_position_properties = 1;
10841 DEFVAR_BOOL ("x-underline-at-descent-line",
10842 x_underline_at_descent_line,
10843 doc: /* *Non-nil means to draw the underline at the same place as the descent line.
10844 A value of nil means to draw the underline according to the value of the
10845 variable `x-use-underline-position-properties', which is usually at the
10846 baseline level. The default value is nil. */);
10847 x_underline_at_descent_line = 0;
10849 DEFVAR_BOOL ("x-mouse-click-focus-ignore-position",
10850 x_mouse_click_focus_ignore_position,
10851 doc: /* Non-nil means that a mouse click to focus a frame does not move point.
10852 This variable is only used when the window manager requires that you
10853 click on a frame to select it (give it focus). In that case, a value
10854 of nil, means that the selected window and cursor position changes to
10855 reflect the mouse click position, while a non-nil value means that the
10856 selected window or cursor position is preserved. */);
10857 x_mouse_click_focus_ignore_position = 0;
10859 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
10860 doc: /* Which toolkit scroll bars Emacs uses, if any.
10861 A value of nil means Emacs doesn't use toolkit scroll bars.
10862 With the X Window system, the value is a symbol describing the
10863 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
10864 With MS Windows or Nextstep, the value is t. */);
10865 #ifdef USE_TOOLKIT_SCROLL_BARS
10866 #ifdef USE_MOTIF
10867 Vx_toolkit_scroll_bars = intern_c_string ("motif");
10868 #elif defined HAVE_XAW3D
10869 Vx_toolkit_scroll_bars = intern_c_string ("xaw3d");
10870 #elif USE_GTK
10871 Vx_toolkit_scroll_bars = intern_c_string ("gtk");
10872 #else
10873 Vx_toolkit_scroll_bars = intern_c_string ("xaw");
10874 #endif
10875 #else
10876 Vx_toolkit_scroll_bars = Qnil;
10877 #endif
10879 staticpro (&last_mouse_motion_frame);
10880 last_mouse_motion_frame = Qnil;
10882 Qmodifier_value = intern_c_string ("modifier-value");
10883 Qalt = intern_c_string ("alt");
10884 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
10885 Qhyper = intern_c_string ("hyper");
10886 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
10887 Qmeta = intern_c_string ("meta");
10888 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
10889 Qsuper = intern_c_string ("super");
10890 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
10892 DEFVAR_LISP ("x-alt-keysym", Vx_alt_keysym,
10893 doc: /* Which keys Emacs uses for the alt modifier.
10894 This should be one of the symbols `alt', `hyper', `meta', `super'.
10895 For example, `alt' means use the Alt_L and Alt_R keysyms. The default
10896 is nil, which is the same as `alt'. */);
10897 Vx_alt_keysym = Qnil;
10899 DEFVAR_LISP ("x-hyper-keysym", Vx_hyper_keysym,
10900 doc: /* Which keys Emacs uses for the hyper modifier.
10901 This should be one of the symbols `alt', `hyper', `meta', `super'.
10902 For example, `hyper' means use the Hyper_L and Hyper_R keysyms. The
10903 default is nil, which is the same as `hyper'. */);
10904 Vx_hyper_keysym = Qnil;
10906 DEFVAR_LISP ("x-meta-keysym", Vx_meta_keysym,
10907 doc: /* Which keys Emacs uses for the meta modifier.
10908 This should be one of the symbols `alt', `hyper', `meta', `super'.
10909 For example, `meta' means use the Meta_L and Meta_R keysyms. The
10910 default is nil, which is the same as `meta'. */);
10911 Vx_meta_keysym = Qnil;
10913 DEFVAR_LISP ("x-super-keysym", Vx_super_keysym,
10914 doc: /* Which keys Emacs uses for the super modifier.
10915 This should be one of the symbols `alt', `hyper', `meta', `super'.
10916 For example, `super' means use the Super_L and Super_R keysyms. The
10917 default is nil, which is the same as `super'. */);
10918 Vx_super_keysym = Qnil;
10920 DEFVAR_LISP ("x-keysym-table", Vx_keysym_table,
10921 doc: /* Hash table of character codes indexed by X keysym codes. */);
10922 Vx_keysym_table = make_hash_table (Qeql, make_number (900),
10923 make_float (DEFAULT_REHASH_SIZE),
10924 make_float (DEFAULT_REHASH_THRESHOLD),
10925 Qnil, Qnil, Qnil);
10928 #endif /* HAVE_X_WINDOWS */