Fix display by Rmail of bidirectional text in MIME email messages.
[emacs.git] / src / xterm.c
blobc07caec6c783362148526f3ae4b50830715f566c
1 /* X Communication module for terminals which understand the X protocol.
3 Copyright (C) 1989, 1993-2011 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 #endif
98 #ifdef USE_LUCID
99 #include "../lwlib/xlwmenu.h"
100 #endif
102 #ifdef USE_X_TOOLKIT
103 #if !defined(NO_EDITRES)
104 #define HACK_EDITRES
105 extern void _XEditResCheckMessages (Widget, XtPointer, XEvent *, Boolean *);
106 #endif /* not NO_EDITRES */
108 /* Include toolkit specific headers for the scroll bar widget. */
110 #ifdef USE_TOOLKIT_SCROLL_BARS
111 #if defined USE_MOTIF
112 #include <Xm/Xm.h> /* for LESSTIF_VERSION */
113 #include <Xm/ScrollBar.h>
114 #else /* !USE_MOTIF i.e. use Xaw */
116 #ifdef HAVE_XAW3D
117 #include <X11/Xaw3d/Simple.h>
118 #include <X11/Xaw3d/Scrollbar.h>
119 #include <X11/Xaw3d/ThreeD.h>
120 #else /* !HAVE_XAW3D */
121 #include <X11/Xaw/Simple.h>
122 #include <X11/Xaw/Scrollbar.h>
123 #endif /* !HAVE_XAW3D */
124 #ifndef XtNpickTop
125 #define XtNpickTop "pickTop"
126 #endif /* !XtNpickTop */
127 #endif /* !USE_MOTIF */
128 #endif /* USE_TOOLKIT_SCROLL_BARS */
130 #endif /* USE_X_TOOLKIT */
132 #ifdef USE_X_TOOLKIT
133 #include "widget.h"
134 #ifndef XtNinitialState
135 #define XtNinitialState "initialState"
136 #endif
137 #endif
139 /* Default to using XIM if available. */
140 #ifdef USE_XIM
141 int use_xim = 1;
142 #else
143 int use_xim = 0; /* configure --without-xim */
144 #endif
148 /* Non-zero means that a HELP_EVENT has been generated since Emacs
149 start. */
151 static int any_help_event_p;
153 /* Last window where we saw the mouse. Used by mouse-autoselect-window. */
154 static Lisp_Object last_window;
156 /* This is a chain of structures for all the X displays currently in
157 use. */
159 struct x_display_info *x_display_list;
161 /* This is a list of cons cells, each of the form (NAME
162 . FONT-LIST-CACHE), one for each element of x_display_list and in
163 the same order. NAME is the name of the frame. FONT-LIST-CACHE
164 records previous values returned by x-list-fonts. */
166 Lisp_Object x_display_name_list;
168 /* Frame being updated by update_frame. This is declared in term.c.
169 This is set by update_begin and looked at by all the XT functions.
170 It is zero while not inside an update. In that case, the XT
171 functions assume that `selected_frame' is the frame to apply to. */
173 extern struct frame *updating_frame;
175 /* This is a frame waiting to be auto-raised, within XTread_socket. */
177 static struct frame *pending_autoraise_frame;
179 /* This is a frame waiting for an event matching mask, within XTread_socket. */
181 static struct {
182 struct frame *f;
183 int eventtype;
184 } pending_event_wait;
186 #ifdef USE_X_TOOLKIT
187 /* The application context for Xt use. */
188 XtAppContext Xt_app_con;
189 static String Xt_default_resources[] = {0};
191 /* Non-zero means user is interacting with a toolkit scroll bar. */
193 static int toolkit_scroll_bar_interaction;
194 #endif /* USE_X_TOOLKIT */
196 /* Non-zero timeout value means ignore next mouse click if it arrives
197 before that timeout elapses (i.e. as part of the same sequence of
198 events resulting from clicking on a frame to select it). */
200 static unsigned long ignore_next_mouse_click_timeout;
202 /* Mouse movement.
204 Formerly, we used PointerMotionHintMask (in standard_event_mask)
205 so that we would have to call XQueryPointer after each MotionNotify
206 event to ask for another such event. However, this made mouse tracking
207 slow, and there was a bug that made it eventually stop.
209 Simply asking for MotionNotify all the time seems to work better.
211 In order to avoid asking for motion events and then throwing most
212 of them away or busy-polling the server for mouse positions, we ask
213 the server for pointer motion hints. This means that we get only
214 one event per group of mouse movements. "Groups" are delimited by
215 other kinds of events (focus changes and button clicks, for
216 example), or by XQueryPointer calls; when one of these happens, we
217 get another MotionNotify event the next time the mouse moves. This
218 is at least as efficient as getting motion events when mouse
219 tracking is on, and I suspect only negligibly worse when tracking
220 is off. */
222 /* Where the mouse was last time we reported a mouse event. */
224 static XRectangle last_mouse_glyph;
225 static FRAME_PTR last_mouse_glyph_frame;
226 static Lisp_Object last_mouse_press_frame;
228 /* The scroll bar in which the last X motion event occurred.
230 If the last X motion event occurred in a scroll bar, we set this so
231 XTmouse_position can know whether to report a scroll bar motion or
232 an ordinary motion.
234 If the last X motion event didn't occur in a scroll bar, we set
235 this to Qnil, to tell XTmouse_position to return an ordinary motion
236 event. */
238 static Lisp_Object last_mouse_scroll_bar;
240 /* This is a hack. We would really prefer that XTmouse_position would
241 return the time associated with the position it returns, but there
242 doesn't seem to be any way to wrest the time-stamp from the server
243 along with the position query. So, we just keep track of the time
244 of the last movement we received, and return that in hopes that
245 it's somewhat accurate. */
247 static Time last_mouse_movement_time;
249 /* Time for last user interaction as returned in X events. */
251 static Time last_user_time;
253 /* Incremented by XTread_socket whenever it really tries to read
254 events. */
256 #ifdef __STDC__
257 static int volatile input_signal_count;
258 #else
259 static int input_signal_count;
260 #endif
262 /* Used locally within XTread_socket. */
264 static int x_noop_count;
266 static Lisp_Object Qalt, Qhyper, Qmeta, Qsuper, Qmodifier_value;
268 static Lisp_Object Qvendor_specific_keysyms;
269 static Lisp_Object Qlatin_1;
271 #ifdef USE_GTK
272 /* The name of the Emacs icon file. */
273 static Lisp_Object xg_default_icon_file;
275 /* Used in gtkutil.c. */
276 Lisp_Object Qx_gtk_map_stock;
277 #endif
279 /* Some functions take this as char *, not const char *. */
280 static char emacs_class[] = EMACS_CLASS;
282 enum xembed_info
284 XEMBED_MAPPED = 1 << 0
287 enum xembed_message
289 XEMBED_EMBEDDED_NOTIFY = 0,
290 XEMBED_WINDOW_ACTIVATE = 1,
291 XEMBED_WINDOW_DEACTIVATE = 2,
292 XEMBED_REQUEST_FOCUS = 3,
293 XEMBED_FOCUS_IN = 4,
294 XEMBED_FOCUS_OUT = 5,
295 XEMBED_FOCUS_NEXT = 6,
296 XEMBED_FOCUS_PREV = 7,
298 XEMBED_MODALITY_ON = 10,
299 XEMBED_MODALITY_OFF = 11,
300 XEMBED_REGISTER_ACCELERATOR = 12,
301 XEMBED_UNREGISTER_ACCELERATOR = 13,
302 XEMBED_ACTIVATE_ACCELERATOR = 14
305 /* Used in x_flush. */
307 static int x_alloc_nearest_color_1 (Display *, Colormap, XColor *);
308 static void x_set_window_size_1 (struct frame *, int, int, int);
309 static void x_raise_frame (struct frame *);
310 static void x_lower_frame (struct frame *);
311 static const XColor *x_color_cells (Display *, int *);
312 static void x_update_window_end (struct window *, int, int);
314 static int x_io_error_quitter (Display *);
315 static struct terminal *x_create_terminal (struct x_display_info *);
316 void x_delete_terminal (struct terminal *);
317 static void x_update_end (struct frame *);
318 static void XTframe_up_to_date (struct frame *);
319 static void XTset_terminal_modes (struct terminal *);
320 static void XTreset_terminal_modes (struct terminal *);
321 static void x_clear_frame (struct frame *);
322 static void x_ins_del_lines (struct frame *, int, int) NO_RETURN;
323 static void frame_highlight (struct frame *);
324 static void frame_unhighlight (struct frame *);
325 static void x_new_focus_frame (struct x_display_info *, struct frame *);
326 static void x_focus_changed (int, int, struct x_display_info *,
327 struct frame *, struct input_event *);
328 static void x_detect_focus_change (struct x_display_info *,
329 XEvent *, struct input_event *);
330 static void XTframe_rehighlight (struct frame *);
331 static void x_frame_rehighlight (struct x_display_info *);
332 static void x_draw_hollow_cursor (struct window *, struct glyph_row *);
333 static void x_draw_bar_cursor (struct window *, struct glyph_row *, int,
334 enum text_cursor_kinds);
336 static void x_clip_to_row (struct window *, struct glyph_row *, int, GC);
337 static void x_flush (struct frame *f);
338 static void x_update_begin (struct frame *);
339 static void x_update_window_begin (struct window *);
340 static void x_after_update_window_line (struct glyph_row *);
341 static struct scroll_bar *x_window_to_scroll_bar (Display *, Window);
342 static void x_scroll_bar_report_motion (struct frame **, Lisp_Object *,
343 enum scroll_bar_part *,
344 Lisp_Object *, Lisp_Object *,
345 Time *);
346 static void x_handle_net_wm_state (struct frame *, XPropertyEvent *);
347 static void x_check_fullscreen (struct frame *);
348 static void x_check_expected_move (struct frame *, int, int);
349 static void x_sync_with_move (struct frame *, int, int, int);
350 static int handle_one_xevent (struct x_display_info *, XEvent *,
351 int *, struct input_event *);
352 #ifdef USE_GTK
353 static int x_dispatch_event (XEvent *, Display *);
354 #endif
355 /* Don't declare this NO_RETURN because we want no
356 interference with debugging failing X calls. */
357 static void x_connection_closed (Display *, const char *);
358 static void x_wm_set_window_state (struct frame *, int);
359 static void x_wm_set_icon_pixmap (struct frame *, ptrdiff_t);
360 static void x_initialize (void);
363 /* Flush display of frame F, or of all frames if F is null. */
365 static void
366 x_flush (struct frame *f)
368 /* Don't call XFlush when it is not safe to redisplay; the X
369 connection may be broken. */
370 if (!NILP (Vinhibit_redisplay))
371 return;
373 BLOCK_INPUT;
374 if (f == NULL)
376 Lisp_Object rest, frame;
377 FOR_EACH_FRAME (rest, frame)
378 if (FRAME_X_P (XFRAME (frame)))
379 x_flush (XFRAME (frame));
381 else if (FRAME_X_P (f))
382 XFlush (FRAME_X_DISPLAY (f));
383 UNBLOCK_INPUT;
387 /* Remove calls to XFlush by defining XFlush to an empty replacement.
388 Calls to XFlush should be unnecessary because the X output buffer
389 is flushed automatically as needed by calls to XPending,
390 XNextEvent, or XWindowEvent according to the XFlush man page.
391 XTread_socket calls XPending. Removing XFlush improves
392 performance. */
394 #define XFlush(DISPLAY) (void) 0
397 /***********************************************************************
398 Debugging
399 ***********************************************************************/
401 #if 0
403 /* This is a function useful for recording debugging information about
404 the sequence of occurrences in this file. */
406 struct record
408 char *locus;
409 int type;
412 struct record event_record[100];
414 int event_record_index;
416 void
417 record_event (char *locus, int type)
419 if (event_record_index == sizeof (event_record) / sizeof (struct record))
420 event_record_index = 0;
422 event_record[event_record_index].locus = locus;
423 event_record[event_record_index].type = type;
424 event_record_index++;
427 #endif /* 0 */
431 /* Return the struct x_display_info corresponding to DPY. */
433 struct x_display_info *
434 x_display_info_for_display (Display *dpy)
436 struct x_display_info *dpyinfo;
438 for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
439 if (dpyinfo->display == dpy)
440 return dpyinfo;
442 return 0;
445 static Window
446 x_find_topmost_parent (struct frame *f)
448 struct x_output *x = f->output_data.x;
449 Window win = None, wi = x->parent_desc;
450 Display *dpy = FRAME_X_DISPLAY (f);
452 while (wi != FRAME_X_DISPLAY_INFO (f)->root_window)
454 Window root;
455 Window *children;
456 unsigned int nchildren;
458 win = wi;
459 XQueryTree (dpy, win, &root, &wi, &children, &nchildren);
460 XFree (children);
463 return win;
466 #define OPAQUE 0xffffffff
468 void
469 x_set_frame_alpha (struct frame *f)
471 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
472 Display *dpy = FRAME_X_DISPLAY (f);
473 Window win = FRAME_OUTER_WINDOW (f);
474 double alpha = 1.0;
475 double alpha_min = 1.0;
476 unsigned long opac;
477 Window parent;
479 if (dpyinfo->x_highlight_frame == f)
480 alpha = f->alpha[0];
481 else
482 alpha = f->alpha[1];
484 if (FLOATP (Vframe_alpha_lower_limit))
485 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
486 else if (INTEGERP (Vframe_alpha_lower_limit))
487 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
489 if (alpha < 0.0)
490 return;
491 else if (alpha > 1.0)
492 alpha = 1.0;
493 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
494 alpha = alpha_min;
496 opac = alpha * OPAQUE;
498 x_catch_errors (dpy);
500 /* If there is a parent from the window manager, put the property there
501 also, to work around broken window managers that fail to do that.
502 Do this unconditionally as this function is called on reparent when
503 alpha has not changed on the frame. */
505 parent = x_find_topmost_parent (f);
506 if (parent != None)
507 XChangeProperty (dpy, parent, dpyinfo->Xatom_net_wm_window_opacity,
508 XA_CARDINAL, 32, PropModeReplace,
509 (unsigned char *) &opac, 1L);
511 /* return unless necessary */
513 unsigned char *data;
514 Atom actual;
515 int rc, format;
516 unsigned long n, left;
518 rc = XGetWindowProperty (dpy, win, dpyinfo->Xatom_net_wm_window_opacity,
519 0L, 1L, False, XA_CARDINAL,
520 &actual, &format, &n, &left,
521 &data);
523 if (rc == Success && actual != None)
525 unsigned long value = *(unsigned long *)data;
526 XFree ((void *) data);
527 if (value == opac)
529 x_uncatch_errors ();
530 return;
535 XChangeProperty (dpy, win, dpyinfo->Xatom_net_wm_window_opacity,
536 XA_CARDINAL, 32, PropModeReplace,
537 (unsigned char *) &opac, 1L);
538 x_uncatch_errors ();
542 x_display_pixel_height (struct x_display_info *dpyinfo)
544 return HeightOfScreen (dpyinfo->screen);
548 x_display_pixel_width (struct x_display_info *dpyinfo)
550 return WidthOfScreen (dpyinfo->screen);
554 /***********************************************************************
555 Starting and ending an update
556 ***********************************************************************/
558 /* Start an update of frame F. This function is installed as a hook
559 for update_begin, i.e. it is called when update_begin is called.
560 This function is called prior to calls to x_update_window_begin for
561 each window being updated. Currently, there is nothing to do here
562 because all interesting stuff is done on a window basis. */
564 static void
565 x_update_begin (struct frame *f)
567 /* Nothing to do. */
571 /* Start update of window W. Set the global variable updated_window
572 to the window being updated and set output_cursor to the cursor
573 position of W. */
575 static void
576 x_update_window_begin (struct window *w)
578 struct frame *f = XFRAME (WINDOW_FRAME (w));
579 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
581 updated_window = w;
582 set_output_cursor (&w->cursor);
584 BLOCK_INPUT;
586 if (f == hlinfo->mouse_face_mouse_frame)
588 /* Don't do highlighting for mouse motion during the update. */
589 hlinfo->mouse_face_defer = 1;
591 /* If F needs to be redrawn, simply forget about any prior mouse
592 highlighting. */
593 if (FRAME_GARBAGED_P (f))
594 hlinfo->mouse_face_window = Qnil;
597 UNBLOCK_INPUT;
601 /* Draw a vertical window border from (x,y0) to (x,y1) */
603 static void
604 x_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
606 struct frame *f = XFRAME (WINDOW_FRAME (w));
607 struct face *face;
609 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
610 if (face)
611 XSetForeground (FRAME_X_DISPLAY (f), f->output_data.x->normal_gc,
612 face->foreground);
614 XDrawLine (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
615 f->output_data.x->normal_gc, x, y0, x, y1);
618 /* End update of window W (which is equal to updated_window).
620 Draw vertical borders between horizontally adjacent windows, and
621 display W's cursor if CURSOR_ON_P is non-zero.
623 MOUSE_FACE_OVERWRITTEN_P non-zero means that some row containing
624 glyphs in mouse-face were overwritten. In that case we have to
625 make sure that the mouse-highlight is properly redrawn.
627 W may be a menu bar pseudo-window in case we don't have X toolkit
628 support. Such windows don't have a cursor, so don't display it
629 here. */
631 static void
632 x_update_window_end (struct window *w, int cursor_on_p, int mouse_face_overwritten_p)
634 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (XFRAME (w->frame));
636 if (!w->pseudo_window_p)
638 BLOCK_INPUT;
640 if (cursor_on_p)
641 display_and_set_cursor (w, 1, output_cursor.hpos,
642 output_cursor.vpos,
643 output_cursor.x, output_cursor.y);
645 if (draw_window_fringes (w, 1))
646 x_draw_vertical_border (w);
648 UNBLOCK_INPUT;
651 /* If a row with mouse-face was overwritten, arrange for
652 XTframe_up_to_date to redisplay the mouse highlight. */
653 if (mouse_face_overwritten_p)
655 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
656 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
657 hlinfo->mouse_face_window = Qnil;
660 updated_window = NULL;
664 /* End update of frame F. This function is installed as a hook in
665 update_end. */
667 static void
668 x_update_end (struct frame *f)
670 /* Mouse highlight may be displayed again. */
671 MOUSE_HL_INFO (f)->mouse_face_defer = 0;
673 #ifndef XFlush
674 BLOCK_INPUT;
675 XFlush (FRAME_X_DISPLAY (f));
676 UNBLOCK_INPUT;
677 #endif
681 /* This function is called from various places in xdisp.c whenever a
682 complete update has been performed. The global variable
683 updated_window is not available here. */
685 static void
686 XTframe_up_to_date (struct frame *f)
688 if (FRAME_X_P (f))
690 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
692 if (hlinfo->mouse_face_deferred_gc
693 || f == hlinfo->mouse_face_mouse_frame)
695 BLOCK_INPUT;
696 if (hlinfo->mouse_face_mouse_frame)
697 note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
698 hlinfo->mouse_face_mouse_x,
699 hlinfo->mouse_face_mouse_y);
700 hlinfo->mouse_face_deferred_gc = 0;
701 UNBLOCK_INPUT;
707 /* Draw truncation mark bitmaps, continuation mark bitmaps, overlay
708 arrow bitmaps, or clear the fringes if no bitmaps are required
709 before DESIRED_ROW is made current. The window being updated is
710 found in updated_window. This function It is called from
711 update_window_line only if it is known that there are differences
712 between bitmaps to be drawn between current row and DESIRED_ROW. */
714 static void
715 x_after_update_window_line (struct glyph_row *desired_row)
717 struct window *w = updated_window;
718 struct frame *f;
719 int width, height;
721 xassert (w);
723 if (!desired_row->mode_line_p && !w->pseudo_window_p)
724 desired_row->redraw_fringe_bitmaps_p = 1;
726 /* When a window has disappeared, make sure that no rest of
727 full-width rows stays visible in the internal border. Could
728 check here if updated_window is the leftmost/rightmost window,
729 but I guess it's not worth doing since vertically split windows
730 are almost never used, internal border is rarely set, and the
731 overhead is very small. */
732 if (windows_or_buffers_changed
733 && desired_row->full_width_p
734 && (f = XFRAME (w->frame),
735 width = FRAME_INTERNAL_BORDER_WIDTH (f),
736 width != 0)
737 && (height = desired_row->visible_height,
738 height > 0))
740 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
742 BLOCK_INPUT;
743 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
744 0, y, width, height, False);
745 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
746 FRAME_PIXEL_WIDTH (f) - width,
747 y, width, height, False);
748 UNBLOCK_INPUT;
752 static void
753 x_draw_fringe_bitmap (struct window *w, struct glyph_row *row, struct draw_fringe_bitmap_params *p)
755 struct frame *f = XFRAME (WINDOW_FRAME (w));
756 Display *display = FRAME_X_DISPLAY (f);
757 Window window = FRAME_X_WINDOW (f);
758 GC gc = f->output_data.x->normal_gc;
759 struct face *face = p->face;
761 /* Must clip because of partially visible lines. */
762 x_clip_to_row (w, row, -1, gc);
764 if (!p->overlay_p)
766 int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
768 /* In case the same realized face is used for fringes and
769 for something displayed in the text (e.g. face `region' on
770 mono-displays, the fill style may have been changed to
771 FillSolid in x_draw_glyph_string_background. */
772 if (face->stipple)
773 XSetFillStyle (display, face->gc, FillOpaqueStippled);
774 else
775 XSetForeground (display, face->gc, face->background);
777 #ifdef USE_TOOLKIT_SCROLL_BARS
778 /* If the fringe is adjacent to the left (right) scroll bar of a
779 leftmost (rightmost, respectively) window, then extend its
780 background to the gap between the fringe and the bar. */
781 if ((WINDOW_LEFTMOST_P (w)
782 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
783 || (WINDOW_RIGHTMOST_P (w)
784 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w)))
786 int sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
788 if (sb_width > 0)
790 int bar_area_x = WINDOW_SCROLL_BAR_AREA_X (w);
791 int bar_area_width = (WINDOW_CONFIG_SCROLL_BAR_COLS (w)
792 * FRAME_COLUMN_WIDTH (f));
794 if (bx < 0)
796 /* Bitmap fills the fringe. */
797 if (bar_area_x + bar_area_width == p->x)
798 bx = bar_area_x + sb_width;
799 else if (p->x + p->wd == bar_area_x)
800 bx = bar_area_x;
801 if (bx >= 0)
803 int header_line_height = WINDOW_HEADER_LINE_HEIGHT (w);
805 nx = bar_area_width - sb_width;
806 by = WINDOW_TO_FRAME_PIXEL_Y (w, max (header_line_height,
807 row->y));
808 ny = row->visible_height;
811 else
813 if (bar_area_x + bar_area_width == bx)
815 bx = bar_area_x + sb_width;
816 nx += bar_area_width - sb_width;
818 else if (bx + nx == bar_area_x)
819 nx += bar_area_width - sb_width;
823 #endif
824 if (bx >= 0 && nx > 0)
825 XFillRectangle (display, window, face->gc, bx, by, nx, ny);
827 if (!face->stipple)
828 XSetForeground (display, face->gc, face->foreground);
831 if (p->which)
833 char *bits;
834 Pixmap pixmap, clipmask = (Pixmap) 0;
835 int depth = DefaultDepthOfScreen (FRAME_X_SCREEN (f));
836 XGCValues gcv;
838 if (p->wd > 8)
839 bits = (char *) (p->bits + p->dh);
840 else
841 bits = (char *) p->bits + p->dh;
843 /* Draw the bitmap. I believe these small pixmaps can be cached
844 by the server. */
845 pixmap = XCreatePixmapFromBitmapData (display, window, bits, p->wd, p->h,
846 (p->cursor_p
847 ? (p->overlay_p ? face->background
848 : f->output_data.x->cursor_pixel)
849 : face->foreground),
850 face->background, depth);
852 if (p->overlay_p)
854 clipmask = XCreatePixmapFromBitmapData (display,
855 FRAME_X_DISPLAY_INFO (f)->root_window,
856 bits, p->wd, p->h,
857 1, 0, 1);
858 gcv.clip_mask = clipmask;
859 gcv.clip_x_origin = p->x;
860 gcv.clip_y_origin = p->y;
861 XChangeGC (display, gc, GCClipMask | GCClipXOrigin | GCClipYOrigin, &gcv);
864 XCopyArea (display, pixmap, window, gc, 0, 0,
865 p->wd, p->h, p->x, p->y);
866 XFreePixmap (display, pixmap);
868 if (p->overlay_p)
870 gcv.clip_mask = (Pixmap) 0;
871 XChangeGC (display, gc, GCClipMask, &gcv);
872 XFreePixmap (display, clipmask);
876 XSetClipMask (display, gc, None);
881 /* This is called when starting Emacs and when restarting after
882 suspend. When starting Emacs, no X window is mapped. And nothing
883 must be done to Emacs's own window if it is suspended (though that
884 rarely happens). */
886 static void
887 XTset_terminal_modes (struct terminal *terminal)
891 /* This is called when exiting or suspending Emacs. Exiting will make
892 the X-windows go away, and suspending requires no action. */
894 static void
895 XTreset_terminal_modes (struct terminal *terminal)
900 /***********************************************************************
901 Glyph display
902 ***********************************************************************/
906 static void x_set_glyph_string_clipping (struct glyph_string *);
907 static void x_set_glyph_string_gc (struct glyph_string *);
908 static void x_draw_glyph_string_background (struct glyph_string *,
909 int);
910 static void x_draw_glyph_string_foreground (struct glyph_string *);
911 static void x_draw_composite_glyph_string_foreground (struct glyph_string *);
912 static void x_draw_glyph_string_box (struct glyph_string *);
913 static void x_draw_glyph_string (struct glyph_string *);
914 static void x_delete_glyphs (struct frame *, int) NO_RETURN;
915 static void x_compute_glyph_string_overhangs (struct glyph_string *);
916 static void x_set_cursor_gc (struct glyph_string *);
917 static void x_set_mode_line_face_gc (struct glyph_string *);
918 static void x_set_mouse_face_gc (struct glyph_string *);
919 static int x_alloc_lighter_color (struct frame *, Display *, Colormap,
920 unsigned long *, double, int);
921 static void x_setup_relief_color (struct frame *, struct relief *,
922 double, int, unsigned long);
923 static void x_setup_relief_colors (struct glyph_string *);
924 static void x_draw_image_glyph_string (struct glyph_string *);
925 static void x_draw_image_relief (struct glyph_string *);
926 static void x_draw_image_foreground (struct glyph_string *);
927 static void x_draw_image_foreground_1 (struct glyph_string *, Pixmap);
928 static void x_clear_glyph_string_rect (struct glyph_string *, int,
929 int, int, int);
930 static void x_draw_relief_rect (struct frame *, int, int, int, int,
931 int, int, int, int, int, int,
932 XRectangle *);
933 static void x_draw_box_rect (struct glyph_string *, int, int, int, int,
934 int, int, int, XRectangle *);
935 static void x_scroll_bar_clear (struct frame *);
937 #if GLYPH_DEBUG
938 static void x_check_font (struct frame *, struct font *);
939 #endif
942 /* Set S->gc to a suitable GC for drawing glyph string S in cursor
943 face. */
945 static void
946 x_set_cursor_gc (struct glyph_string *s)
948 if (s->font == FRAME_FONT (s->f)
949 && s->face->background == FRAME_BACKGROUND_PIXEL (s->f)
950 && s->face->foreground == FRAME_FOREGROUND_PIXEL (s->f)
951 && !s->cmp)
952 s->gc = s->f->output_data.x->cursor_gc;
953 else
955 /* Cursor on non-default face: must merge. */
956 XGCValues xgcv;
957 unsigned long mask;
959 xgcv.background = s->f->output_data.x->cursor_pixel;
960 xgcv.foreground = s->face->background;
962 /* If the glyph would be invisible, try a different foreground. */
963 if (xgcv.foreground == xgcv.background)
964 xgcv.foreground = s->face->foreground;
965 if (xgcv.foreground == xgcv.background)
966 xgcv.foreground = s->f->output_data.x->cursor_foreground_pixel;
967 if (xgcv.foreground == xgcv.background)
968 xgcv.foreground = s->face->foreground;
970 /* Make sure the cursor is distinct from text in this face. */
971 if (xgcv.background == s->face->background
972 && xgcv.foreground == s->face->foreground)
974 xgcv.background = s->face->foreground;
975 xgcv.foreground = s->face->background;
978 IF_DEBUG (x_check_font (s->f, s->font));
979 xgcv.graphics_exposures = False;
980 mask = GCForeground | GCBackground | GCGraphicsExposures;
982 if (FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc)
983 XChangeGC (s->display, FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc,
984 mask, &xgcv);
985 else
986 FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc
987 = XCreateGC (s->display, s->window, mask, &xgcv);
989 s->gc = FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc;
994 /* Set up S->gc of glyph string S for drawing text in mouse face. */
996 static void
997 x_set_mouse_face_gc (struct glyph_string *s)
999 int face_id;
1000 struct face *face;
1002 /* What face has to be used last for the mouse face? */
1003 face_id = MOUSE_HL_INFO (s->f)->mouse_face_face_id;
1004 face = FACE_FROM_ID (s->f, face_id);
1005 if (face == NULL)
1006 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
1008 if (s->first_glyph->type == CHAR_GLYPH)
1009 face_id = FACE_FOR_CHAR (s->f, face, s->first_glyph->u.ch, -1, Qnil);
1010 else
1011 face_id = FACE_FOR_CHAR (s->f, face, 0, -1, Qnil);
1012 s->face = FACE_FROM_ID (s->f, face_id);
1013 PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
1015 if (s->font == s->face->font)
1016 s->gc = s->face->gc;
1017 else
1019 /* Otherwise construct scratch_cursor_gc with values from FACE
1020 except for FONT. */
1021 XGCValues xgcv;
1022 unsigned long mask;
1024 xgcv.background = s->face->background;
1025 xgcv.foreground = s->face->foreground;
1026 xgcv.graphics_exposures = False;
1027 mask = GCForeground | GCBackground | GCGraphicsExposures;
1029 if (FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc)
1030 XChangeGC (s->display, FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc,
1031 mask, &xgcv);
1032 else
1033 FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc
1034 = XCreateGC (s->display, s->window, mask, &xgcv);
1036 s->gc = FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc;
1039 xassert (s->gc != 0);
1043 /* Set S->gc of glyph string S to a GC suitable for drawing a mode line.
1044 Faces to use in the mode line have already been computed when the
1045 matrix was built, so there isn't much to do, here. */
1047 static inline void
1048 x_set_mode_line_face_gc (struct glyph_string *s)
1050 s->gc = s->face->gc;
1054 /* Set S->gc of glyph string S for drawing that glyph string. Set
1055 S->stippled_p to a non-zero value if the face of S has a stipple
1056 pattern. */
1058 static inline void
1059 x_set_glyph_string_gc (struct glyph_string *s)
1061 PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
1063 if (s->hl == DRAW_NORMAL_TEXT)
1065 s->gc = s->face->gc;
1066 s->stippled_p = s->face->stipple != 0;
1068 else if (s->hl == DRAW_INVERSE_VIDEO)
1070 x_set_mode_line_face_gc (s);
1071 s->stippled_p = s->face->stipple != 0;
1073 else if (s->hl == DRAW_CURSOR)
1075 x_set_cursor_gc (s);
1076 s->stippled_p = 0;
1078 else if (s->hl == DRAW_MOUSE_FACE)
1080 x_set_mouse_face_gc (s);
1081 s->stippled_p = s->face->stipple != 0;
1083 else if (s->hl == DRAW_IMAGE_RAISED
1084 || s->hl == DRAW_IMAGE_SUNKEN)
1086 s->gc = s->face->gc;
1087 s->stippled_p = s->face->stipple != 0;
1089 else
1091 s->gc = s->face->gc;
1092 s->stippled_p = s->face->stipple != 0;
1095 /* GC must have been set. */
1096 xassert (s->gc != 0);
1100 /* Set clipping for output of glyph string S. S may be part of a mode
1101 line or menu if we don't have X toolkit support. */
1103 static inline void
1104 x_set_glyph_string_clipping (struct glyph_string *s)
1106 XRectangle *r = s->clip;
1107 int n = get_glyph_string_clip_rects (s, r, 2);
1109 if (n > 0)
1110 XSetClipRectangles (s->display, s->gc, 0, 0, r, n, Unsorted);
1111 s->num_clips = n;
1115 /* Set SRC's clipping for output of glyph string DST. This is called
1116 when we are drawing DST's left_overhang or right_overhang only in
1117 the area of SRC. */
1119 static void
1120 x_set_glyph_string_clipping_exactly (struct glyph_string *src, struct glyph_string *dst)
1122 XRectangle r;
1124 r.x = src->x;
1125 r.width = src->width;
1126 r.y = src->y;
1127 r.height = src->height;
1128 dst->clip[0] = r;
1129 dst->num_clips = 1;
1130 XSetClipRectangles (dst->display, dst->gc, 0, 0, &r, 1, Unsorted);
1134 /* RIF:
1135 Compute left and right overhang of glyph string S. */
1137 static void
1138 x_compute_glyph_string_overhangs (struct glyph_string *s)
1140 if (s->cmp == NULL
1141 && (s->first_glyph->type == CHAR_GLYPH
1142 || s->first_glyph->type == COMPOSITE_GLYPH))
1144 struct font_metrics metrics;
1146 if (s->first_glyph->type == CHAR_GLYPH)
1148 unsigned *code = alloca (sizeof (unsigned) * s->nchars);
1149 struct font *font = s->font;
1150 int i;
1152 for (i = 0; i < s->nchars; i++)
1153 code[i] = (s->char2b[i].byte1 << 8) | s->char2b[i].byte2;
1154 font->driver->text_extents (font, code, s->nchars, &metrics);
1156 else
1158 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1160 composition_gstring_width (gstring, s->cmp_from, s->cmp_to, &metrics);
1162 s->right_overhang = (metrics.rbearing > metrics.width
1163 ? metrics.rbearing - metrics.width : 0);
1164 s->left_overhang = metrics.lbearing < 0 ? - metrics.lbearing : 0;
1166 else if (s->cmp)
1168 s->right_overhang = s->cmp->rbearing - s->cmp->pixel_width;
1169 s->left_overhang = - s->cmp->lbearing;
1174 /* Fill rectangle X, Y, W, H with background color of glyph string S. */
1176 static inline void
1177 x_clear_glyph_string_rect (struct glyph_string *s, int x, int y, int w, int h)
1179 XGCValues xgcv;
1180 XGetGCValues (s->display, s->gc, GCForeground | GCBackground, &xgcv);
1181 XSetForeground (s->display, s->gc, xgcv.background);
1182 XFillRectangle (s->display, s->window, s->gc, x, y, w, h);
1183 XSetForeground (s->display, s->gc, xgcv.foreground);
1187 /* Draw the background of glyph_string S. If S->background_filled_p
1188 is non-zero don't draw it. FORCE_P non-zero means draw the
1189 background even if it wouldn't be drawn normally. This is used
1190 when a string preceding S draws into the background of S, or S
1191 contains the first component of a composition. */
1193 static void
1194 x_draw_glyph_string_background (struct glyph_string *s, int force_p)
1196 /* Nothing to do if background has already been drawn or if it
1197 shouldn't be drawn in the first place. */
1198 if (!s->background_filled_p)
1200 int box_line_width = max (s->face->box_line_width, 0);
1202 if (s->stippled_p)
1204 /* Fill background with a stipple pattern. */
1205 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
1206 XFillRectangle (s->display, s->window, s->gc, s->x,
1207 s->y + box_line_width,
1208 s->background_width,
1209 s->height - 2 * box_line_width);
1210 XSetFillStyle (s->display, s->gc, FillSolid);
1211 s->background_filled_p = 1;
1213 else if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
1214 || s->font_not_found_p
1215 || s->extends_to_end_of_line_p
1216 || force_p)
1218 x_clear_glyph_string_rect (s, s->x, s->y + box_line_width,
1219 s->background_width,
1220 s->height - 2 * box_line_width);
1221 s->background_filled_p = 1;
1227 /* Draw the foreground of glyph string S. */
1229 static void
1230 x_draw_glyph_string_foreground (struct glyph_string *s)
1232 int i, x;
1234 /* If first glyph of S has a left box line, start drawing the text
1235 of S to the right of that box line. */
1236 if (s->face->box != FACE_NO_BOX
1237 && s->first_glyph->left_box_line_p)
1238 x = s->x + eabs (s->face->box_line_width);
1239 else
1240 x = s->x;
1242 /* Draw characters of S as rectangles if S's font could not be
1243 loaded. */
1244 if (s->font_not_found_p)
1246 for (i = 0; i < s->nchars; ++i)
1248 struct glyph *g = s->first_glyph + i;
1249 XDrawRectangle (s->display, s->window,
1250 s->gc, x, s->y, g->pixel_width - 1,
1251 s->height - 1);
1252 x += g->pixel_width;
1255 else
1257 struct font *font = s->font;
1258 int boff = font->baseline_offset;
1259 int y;
1261 if (font->vertical_centering)
1262 boff = VCENTER_BASELINE_OFFSET (font, s->f) - boff;
1264 y = s->ybase - boff;
1265 if (s->for_overlaps
1266 || (s->background_filled_p && s->hl != DRAW_CURSOR))
1267 font->driver->draw (s, 0, s->nchars, x, y, 0);
1268 else
1269 font->driver->draw (s, 0, s->nchars, x, y, 1);
1270 if (s->face->overstrike)
1271 font->driver->draw (s, 0, s->nchars, x + 1, y, 0);
1275 /* Draw the foreground of composite glyph string S. */
1277 static void
1278 x_draw_composite_glyph_string_foreground (struct glyph_string *s)
1280 int i, j, x;
1281 struct font *font = s->font;
1283 /* If first glyph of S has a left box line, start drawing the text
1284 of S to the right of that box line. */
1285 if (s->face && s->face->box != FACE_NO_BOX
1286 && s->first_glyph->left_box_line_p)
1287 x = s->x + eabs (s->face->box_line_width);
1288 else
1289 x = s->x;
1291 /* S is a glyph string for a composition. S->cmp_from is the index
1292 of the first character drawn for glyphs of this composition.
1293 S->cmp_from == 0 means we are drawing the very first character of
1294 this composition. */
1296 /* Draw a rectangle for the composition if the font for the very
1297 first character of the composition could not be loaded. */
1298 if (s->font_not_found_p)
1300 if (s->cmp_from == 0)
1301 XDrawRectangle (s->display, s->window, s->gc, x, s->y,
1302 s->width - 1, s->height - 1);
1304 else if (! s->first_glyph->u.cmp.automatic)
1306 int y = s->ybase;
1308 for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
1309 if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
1311 int xx = x + s->cmp->offsets[j * 2];
1312 int yy = y - s->cmp->offsets[j * 2 + 1];
1314 font->driver->draw (s, j, j + 1, xx, yy, 0);
1315 if (s->face->overstrike)
1316 font->driver->draw (s, j, j + 1, xx + 1, yy, 0);
1319 else
1321 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1322 Lisp_Object glyph;
1323 int y = s->ybase;
1324 int width = 0;
1326 for (i = j = s->cmp_from; i < s->cmp_to; i++)
1328 glyph = LGSTRING_GLYPH (gstring, i);
1329 if (NILP (LGLYPH_ADJUSTMENT (glyph)))
1330 width += LGLYPH_WIDTH (glyph);
1331 else
1333 int xoff, yoff, wadjust;
1335 if (j < i)
1337 font->driver->draw (s, j, i, x, y, 0);
1338 if (s->face->overstrike)
1339 font->driver->draw (s, j, i, x + 1, y, 0);
1340 x += width;
1342 xoff = LGLYPH_XOFF (glyph);
1343 yoff = LGLYPH_YOFF (glyph);
1344 wadjust = LGLYPH_WADJUST (glyph);
1345 font->driver->draw (s, i, i + 1, x + xoff, y + yoff, 0);
1346 if (s->face->overstrike)
1347 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff, 0);
1348 x += wadjust;
1349 j = i + 1;
1350 width = 0;
1353 if (j < i)
1355 font->driver->draw (s, j, i, x, y, 0);
1356 if (s->face->overstrike)
1357 font->driver->draw (s, j, i, x + 1, y, 0);
1363 /* Draw the foreground of glyph string S for glyphless characters. */
1365 static void
1366 x_draw_glyphless_glyph_string_foreground (struct glyph_string *s)
1368 struct glyph *glyph = s->first_glyph;
1369 XChar2b char2b[8];
1370 int x, i, j;
1372 /* If first glyph of S has a left box line, start drawing the text
1373 of S to the right of that box line. */
1374 if (s->face && s->face->box != FACE_NO_BOX
1375 && s->first_glyph->left_box_line_p)
1376 x = s->x + eabs (s->face->box_line_width);
1377 else
1378 x = s->x;
1380 s->char2b = char2b;
1382 for (i = 0; i < s->nchars; i++, glyph++)
1384 char buf[7], *str = NULL;
1385 int len = glyph->u.glyphless.len;
1387 if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_ACRONYM)
1389 if (len > 0
1390 && CHAR_TABLE_P (Vglyphless_char_display)
1391 && (CHAR_TABLE_EXTRA_SLOTS (XCHAR_TABLE (Vglyphless_char_display))
1392 >= 1))
1394 Lisp_Object acronym
1395 = (! glyph->u.glyphless.for_no_font
1396 ? CHAR_TABLE_REF (Vglyphless_char_display,
1397 glyph->u.glyphless.ch)
1398 : XCHAR_TABLE (Vglyphless_char_display)->extras[0]);
1399 if (STRINGP (acronym))
1400 str = SSDATA (acronym);
1403 else if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_HEX_CODE)
1405 sprintf ((char *) buf, "%0*X",
1406 glyph->u.glyphless.ch < 0x10000 ? 4 : 6,
1407 glyph->u.glyphless.ch);
1408 str = buf;
1411 if (str)
1413 int upper_len = (len + 1) / 2;
1414 unsigned code;
1416 /* It is assured that all LEN characters in STR is ASCII. */
1417 for (j = 0; j < len; j++)
1419 code = s->font->driver->encode_char (s->font, str[j]);
1420 STORE_XCHAR2B (char2b + j, code >> 8, code & 0xFF);
1422 s->font->driver->draw (s, 0, upper_len,
1423 x + glyph->slice.glyphless.upper_xoff,
1424 s->ybase + glyph->slice.glyphless.upper_yoff,
1426 s->font->driver->draw (s, upper_len, len,
1427 x + glyph->slice.glyphless.lower_xoff,
1428 s->ybase + glyph->slice.glyphless.lower_yoff,
1431 if (glyph->u.glyphless.method != GLYPHLESS_DISPLAY_THIN_SPACE)
1432 XDrawRectangle (s->display, s->window, s->gc,
1433 x, s->ybase - glyph->ascent,
1434 glyph->pixel_width - 1,
1435 glyph->ascent + glyph->descent - 1);
1436 x += glyph->pixel_width;
1440 #ifdef USE_X_TOOLKIT
1442 static struct frame *x_frame_of_widget (Widget);
1443 static Boolean cvt_string_to_pixel (Display *, XrmValue *, Cardinal *,
1444 XrmValue *, XrmValue *, XtPointer *);
1445 static void cvt_pixel_dtor (XtAppContext, XrmValue *, XtPointer,
1446 XrmValue *, Cardinal *);
1449 /* Return the frame on which widget WIDGET is used.. Abort if frame
1450 cannot be determined. */
1452 static struct frame *
1453 x_frame_of_widget (Widget widget)
1455 struct x_display_info *dpyinfo;
1456 Lisp_Object tail;
1457 struct frame *f;
1459 dpyinfo = x_display_info_for_display (XtDisplay (widget));
1461 /* Find the top-level shell of the widget. Note that this function
1462 can be called when the widget is not yet realized, so XtWindow
1463 (widget) == 0. That's the reason we can't simply use
1464 x_any_window_to_frame. */
1465 while (!XtIsTopLevelShell (widget))
1466 widget = XtParent (widget);
1468 /* Look for a frame with that top-level widget. Allocate the color
1469 on that frame to get the right gamma correction value. */
1470 for (tail = Vframe_list; CONSP (tail); tail = XCDR (tail))
1471 if (FRAMEP (XCAR (tail))
1472 && (f = XFRAME (XCAR (tail)),
1473 (FRAME_X_P (f)
1474 && f->output_data.nothing != 1
1475 && FRAME_X_DISPLAY_INFO (f) == dpyinfo))
1476 && f->output_data.x->widget == widget)
1477 return f;
1479 abort ();
1483 #ifdef USE_LUCID
1485 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
1486 or DELTA. Try a color with RGB values multiplied by FACTOR first.
1487 If this produces the same color as PIXEL, try a color where all RGB
1488 values have DELTA added. Return the allocated color in *PIXEL.
1489 DISPLAY is the X display, CMAP is the colormap to operate on.
1490 Value is non-zero if successful. */
1493 x_alloc_lighter_color_for_widget (Widget widget, Display *display, Colormap cmap,
1494 unsigned long *pixel, double factor, int delta)
1496 struct frame *f = x_frame_of_widget (widget);
1497 return x_alloc_lighter_color (f, display, cmap, pixel, factor, delta);
1500 #endif
1503 /* Structure specifying which arguments should be passed by Xt to
1504 cvt_string_to_pixel. We want the widget's screen and colormap. */
1506 static XtConvertArgRec cvt_string_to_pixel_args[] =
1508 {XtWidgetBaseOffset, (XtPointer) XtOffset (Widget, core.screen),
1509 sizeof (Screen *)},
1510 {XtWidgetBaseOffset, (XtPointer) XtOffset (Widget, core.colormap),
1511 sizeof (Colormap)}
1515 /* The address of this variable is returned by
1516 cvt_string_to_pixel. */
1518 static Pixel cvt_string_to_pixel_value;
1521 /* Convert a color name to a pixel color.
1523 DPY is the display we are working on.
1525 ARGS is an array of *NARGS XrmValue structures holding additional
1526 information about the widget for which the conversion takes place.
1527 The contents of this array are determined by the specification
1528 in cvt_string_to_pixel_args.
1530 FROM is a pointer to an XrmValue which points to the color name to
1531 convert. TO is an XrmValue in which to return the pixel color.
1533 CLOSURE_RET is a pointer to user-data, in which we record if
1534 we allocated the color or not.
1536 Value is True if successful, False otherwise. */
1538 static Boolean
1539 cvt_string_to_pixel (Display *dpy, XrmValue *args, Cardinal *nargs,
1540 XrmValue *from, XrmValue *to,
1541 XtPointer *closure_ret)
1543 Screen *screen;
1544 Colormap cmap;
1545 Pixel pixel;
1546 String color_name;
1547 XColor color;
1549 if (*nargs != 2)
1551 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
1552 "wrongParameters", "cvt_string_to_pixel",
1553 "XtToolkitError",
1554 "Screen and colormap args required", NULL, NULL);
1555 return False;
1558 screen = *(Screen **) args[0].addr;
1559 cmap = *(Colormap *) args[1].addr;
1560 color_name = (String) from->addr;
1562 if (strcmp (color_name, XtDefaultBackground) == 0)
1564 *closure_ret = (XtPointer) False;
1565 pixel = WhitePixelOfScreen (screen);
1567 else if (strcmp (color_name, XtDefaultForeground) == 0)
1569 *closure_ret = (XtPointer) False;
1570 pixel = BlackPixelOfScreen (screen);
1572 else if (XParseColor (dpy, cmap, color_name, &color)
1573 && x_alloc_nearest_color_1 (dpy, cmap, &color))
1575 pixel = color.pixel;
1576 *closure_ret = (XtPointer) True;
1578 else
1580 String params[1];
1581 Cardinal nparams = 1;
1583 params[0] = color_name;
1584 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
1585 "badValue", "cvt_string_to_pixel",
1586 "XtToolkitError", "Invalid color `%s'",
1587 params, &nparams);
1588 return False;
1591 if (to->addr != NULL)
1593 if (to->size < sizeof (Pixel))
1595 to->size = sizeof (Pixel);
1596 return False;
1599 *(Pixel *) to->addr = pixel;
1601 else
1603 cvt_string_to_pixel_value = pixel;
1604 to->addr = (XtPointer) &cvt_string_to_pixel_value;
1607 to->size = sizeof (Pixel);
1608 return True;
1612 /* Free a pixel color which was previously allocated via
1613 cvt_string_to_pixel. This is registered as the destructor
1614 for this type of resource via XtSetTypeConverter.
1616 APP is the application context in which we work.
1618 TO is a pointer to an XrmValue holding the color to free.
1619 CLOSURE is the value we stored in CLOSURE_RET for this color
1620 in cvt_string_to_pixel.
1622 ARGS and NARGS are like for cvt_string_to_pixel. */
1624 static void
1625 cvt_pixel_dtor (XtAppContext app, XrmValuePtr to, XtPointer closure, XrmValuePtr args,
1626 Cardinal *nargs)
1628 if (*nargs != 2)
1630 XtAppWarningMsg (app, "wrongParameters", "cvt_pixel_dtor",
1631 "XtToolkitError",
1632 "Screen and colormap arguments required",
1633 NULL, NULL);
1635 else if (closure != NULL)
1637 /* We did allocate the pixel, so free it. */
1638 Screen *screen = *(Screen **) args[0].addr;
1639 Colormap cmap = *(Colormap *) args[1].addr;
1640 x_free_dpy_colors (DisplayOfScreen (screen), screen, cmap,
1641 (Pixel *) to->addr, 1);
1646 #endif /* USE_X_TOOLKIT */
1649 /* Value is an array of XColor structures for the contents of the
1650 color map of display DPY. Set *NCELLS to the size of the array.
1651 Note that this probably shouldn't be called for large color maps,
1652 say a 24-bit TrueColor map. */
1654 static const XColor *
1655 x_color_cells (Display *dpy, int *ncells)
1657 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
1659 if (dpyinfo->color_cells == NULL)
1661 Screen *screen = dpyinfo->screen;
1662 int ncolor_cells = XDisplayCells (dpy, XScreenNumberOfScreen (screen));
1663 int i;
1665 dpyinfo->color_cells = xnmalloc (ncolor_cells,
1666 sizeof *dpyinfo->color_cells);
1667 dpyinfo->ncolor_cells = ncolor_cells;
1669 for (i = 0; i < ncolor_cells; ++i)
1670 dpyinfo->color_cells[i].pixel = i;
1672 XQueryColors (dpy, dpyinfo->cmap,
1673 dpyinfo->color_cells, ncolor_cells);
1676 *ncells = dpyinfo->ncolor_cells;
1677 return dpyinfo->color_cells;
1681 /* On frame F, translate pixel colors to RGB values for the NCOLORS
1682 colors in COLORS. Use cached information, if available. */
1684 void
1685 x_query_colors (struct frame *f, XColor *colors, int ncolors)
1687 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
1689 if (dpyinfo->color_cells)
1691 int i;
1692 for (i = 0; i < ncolors; ++i)
1694 unsigned long pixel = colors[i].pixel;
1695 xassert (pixel < dpyinfo->ncolor_cells);
1696 xassert (dpyinfo->color_cells[pixel].pixel == pixel);
1697 colors[i] = dpyinfo->color_cells[pixel];
1700 else
1701 XQueryColors (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), colors, ncolors);
1705 /* On frame F, translate pixel color to RGB values for the color in
1706 COLOR. Use cached information, if available. */
1708 void
1709 x_query_color (struct frame *f, XColor *color)
1711 x_query_colors (f, color, 1);
1715 /* Allocate the color COLOR->pixel on DISPLAY, colormap CMAP. If an
1716 exact match can't be allocated, try the nearest color available.
1717 Value is non-zero if successful. Set *COLOR to the color
1718 allocated. */
1720 static int
1721 x_alloc_nearest_color_1 (Display *dpy, Colormap cmap, XColor *color)
1723 int rc;
1725 rc = XAllocColor (dpy, cmap, color);
1726 if (rc == 0)
1728 /* If we got to this point, the colormap is full, so we're going
1729 to try to get the next closest color. The algorithm used is
1730 a least-squares matching, which is what X uses for closest
1731 color matching with StaticColor visuals. */
1732 int nearest, i;
1733 int max_color_delta = 255;
1734 int max_delta = 3 * max_color_delta;
1735 int nearest_delta = max_delta + 1;
1736 int ncells;
1737 const XColor *cells = x_color_cells (dpy, &ncells);
1739 for (nearest = i = 0; i < ncells; ++i)
1741 int dred = (color->red >> 8) - (cells[i].red >> 8);
1742 int dgreen = (color->green >> 8) - (cells[i].green >> 8);
1743 int dblue = (color->blue >> 8) - (cells[i].blue >> 8);
1744 int delta = dred * dred + dgreen * dgreen + dblue * dblue;
1746 if (delta < nearest_delta)
1748 nearest = i;
1749 nearest_delta = delta;
1753 color->red = cells[nearest].red;
1754 color->green = cells[nearest].green;
1755 color->blue = cells[nearest].blue;
1756 rc = XAllocColor (dpy, cmap, color);
1758 else
1760 /* If allocation succeeded, and the allocated pixel color is not
1761 equal to a cached pixel color recorded earlier, there was a
1762 change in the colormap, so clear the color cache. */
1763 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
1764 XColor *cached_color;
1766 if (dpyinfo->color_cells
1767 && (cached_color = &dpyinfo->color_cells[color->pixel],
1768 (cached_color->red != color->red
1769 || cached_color->blue != color->blue
1770 || cached_color->green != color->green)))
1772 xfree (dpyinfo->color_cells);
1773 dpyinfo->color_cells = NULL;
1774 dpyinfo->ncolor_cells = 0;
1778 #ifdef DEBUG_X_COLORS
1779 if (rc)
1780 register_color (color->pixel);
1781 #endif /* DEBUG_X_COLORS */
1783 return rc;
1787 /* Allocate the color COLOR->pixel on frame F, colormap CMAP. If an
1788 exact match can't be allocated, try the nearest color available.
1789 Value is non-zero if successful. Set *COLOR to the color
1790 allocated. */
1793 x_alloc_nearest_color (struct frame *f, Colormap cmap, XColor *color)
1795 gamma_correct (f, color);
1796 return x_alloc_nearest_color_1 (FRAME_X_DISPLAY (f), cmap, color);
1800 /* Allocate color PIXEL on frame F. PIXEL must already be allocated.
1801 It's necessary to do this instead of just using PIXEL directly to
1802 get color reference counts right. */
1804 unsigned long
1805 x_copy_color (struct frame *f, long unsigned int pixel)
1807 XColor color;
1809 color.pixel = pixel;
1810 BLOCK_INPUT;
1811 x_query_color (f, &color);
1812 XAllocColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &color);
1813 UNBLOCK_INPUT;
1814 #ifdef DEBUG_X_COLORS
1815 register_color (pixel);
1816 #endif
1817 return color.pixel;
1821 /* Brightness beyond which a color won't have its highlight brightness
1822 boosted.
1824 Nominally, highlight colors for `3d' faces are calculated by
1825 brightening an object's color by a constant scale factor, but this
1826 doesn't yield good results for dark colors, so for colors who's
1827 brightness is less than this value (on a scale of 0-65535) have an
1828 use an additional additive factor.
1830 The value here is set so that the default menu-bar/mode-line color
1831 (grey75) will not have its highlights changed at all. */
1832 #define HIGHLIGHT_COLOR_DARK_BOOST_LIMIT 48000
1835 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
1836 or DELTA. Try a color with RGB values multiplied by FACTOR first.
1837 If this produces the same color as PIXEL, try a color where all RGB
1838 values have DELTA added. Return the allocated color in *PIXEL.
1839 DISPLAY is the X display, CMAP is the colormap to operate on.
1840 Value is non-zero if successful. */
1842 static int
1843 x_alloc_lighter_color (struct frame *f, Display *display, Colormap cmap, long unsigned int *pixel, double factor, int delta)
1845 XColor color, new;
1846 long bright;
1847 int success_p;
1849 /* Get RGB color values. */
1850 color.pixel = *pixel;
1851 x_query_color (f, &color);
1853 /* Change RGB values by specified FACTOR. Avoid overflow! */
1854 xassert (factor >= 0);
1855 new.red = min (0xffff, factor * color.red);
1856 new.green = min (0xffff, factor * color.green);
1857 new.blue = min (0xffff, factor * color.blue);
1859 /* Calculate brightness of COLOR. */
1860 bright = (2 * color.red + 3 * color.green + color.blue) / 6;
1862 /* We only boost colors that are darker than
1863 HIGHLIGHT_COLOR_DARK_BOOST_LIMIT. */
1864 if (bright < HIGHLIGHT_COLOR_DARK_BOOST_LIMIT)
1865 /* Make an additive adjustment to NEW, because it's dark enough so
1866 that scaling by FACTOR alone isn't enough. */
1868 /* How far below the limit this color is (0 - 1, 1 being darker). */
1869 double dimness = 1 - (double)bright / HIGHLIGHT_COLOR_DARK_BOOST_LIMIT;
1870 /* The additive adjustment. */
1871 int min_delta = delta * dimness * factor / 2;
1873 if (factor < 1)
1875 new.red = max (0, new.red - min_delta);
1876 new.green = max (0, new.green - min_delta);
1877 new.blue = max (0, new.blue - min_delta);
1879 else
1881 new.red = min (0xffff, min_delta + new.red);
1882 new.green = min (0xffff, min_delta + new.green);
1883 new.blue = min (0xffff, min_delta + new.blue);
1887 /* Try to allocate the color. */
1888 success_p = x_alloc_nearest_color (f, cmap, &new);
1889 if (success_p)
1891 if (new.pixel == *pixel)
1893 /* If we end up with the same color as before, try adding
1894 delta to the RGB values. */
1895 x_free_colors (f, &new.pixel, 1);
1897 new.red = min (0xffff, delta + color.red);
1898 new.green = min (0xffff, delta + color.green);
1899 new.blue = min (0xffff, delta + color.blue);
1900 success_p = x_alloc_nearest_color (f, cmap, &new);
1902 else
1903 success_p = 1;
1904 *pixel = new.pixel;
1907 return success_p;
1911 /* Set up the foreground color for drawing relief lines of glyph
1912 string S. RELIEF is a pointer to a struct relief containing the GC
1913 with which lines will be drawn. Use a color that is FACTOR or
1914 DELTA lighter or darker than the relief's background which is found
1915 in S->f->output_data.x->relief_background. If such a color cannot
1916 be allocated, use DEFAULT_PIXEL, instead. */
1918 static void
1919 x_setup_relief_color (struct frame *f, struct relief *relief, double factor, int delta, long unsigned int default_pixel)
1921 XGCValues xgcv;
1922 struct x_output *di = f->output_data.x;
1923 unsigned long mask = GCForeground | GCLineWidth | GCGraphicsExposures;
1924 unsigned long pixel;
1925 unsigned long background = di->relief_background;
1926 Colormap cmap = FRAME_X_COLORMAP (f);
1927 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
1928 Display *dpy = FRAME_X_DISPLAY (f);
1930 xgcv.graphics_exposures = False;
1931 xgcv.line_width = 1;
1933 /* Free previously allocated color. The color cell will be reused
1934 when it has been freed as many times as it was allocated, so this
1935 doesn't affect faces using the same colors. */
1936 if (relief->gc
1937 && relief->allocated_p)
1939 x_free_colors (f, &relief->pixel, 1);
1940 relief->allocated_p = 0;
1943 /* Allocate new color. */
1944 xgcv.foreground = default_pixel;
1945 pixel = background;
1946 if (dpyinfo->n_planes != 1
1947 && x_alloc_lighter_color (f, dpy, cmap, &pixel, factor, delta))
1949 relief->allocated_p = 1;
1950 xgcv.foreground = relief->pixel = pixel;
1953 if (relief->gc == 0)
1955 xgcv.stipple = dpyinfo->gray;
1956 mask |= GCStipple;
1957 relief->gc = XCreateGC (dpy, FRAME_X_WINDOW (f), mask, &xgcv);
1959 else
1960 XChangeGC (dpy, relief->gc, mask, &xgcv);
1964 /* Set up colors for the relief lines around glyph string S. */
1966 static void
1967 x_setup_relief_colors (struct glyph_string *s)
1969 struct x_output *di = s->f->output_data.x;
1970 unsigned long color;
1972 if (s->face->use_box_color_for_shadows_p)
1973 color = s->face->box_color;
1974 else if (s->first_glyph->type == IMAGE_GLYPH
1975 && s->img->pixmap
1976 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
1977 color = IMAGE_BACKGROUND (s->img, s->f, 0);
1978 else
1980 XGCValues xgcv;
1982 /* Get the background color of the face. */
1983 XGetGCValues (s->display, s->gc, GCBackground, &xgcv);
1984 color = xgcv.background;
1987 if (di->white_relief.gc == 0
1988 || color != di->relief_background)
1990 di->relief_background = color;
1991 x_setup_relief_color (s->f, &di->white_relief, 1.2, 0x8000,
1992 WHITE_PIX_DEFAULT (s->f));
1993 x_setup_relief_color (s->f, &di->black_relief, 0.6, 0x4000,
1994 BLACK_PIX_DEFAULT (s->f));
1999 /* Draw a relief on frame F inside the rectangle given by LEFT_X,
2000 TOP_Y, RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the relief
2001 to draw, it must be >= 0. RAISED_P non-zero means draw a raised
2002 relief. LEFT_P non-zero means draw a relief on the left side of
2003 the rectangle. RIGHT_P non-zero means draw a relief on the right
2004 side of the rectangle. CLIP_RECT is the clipping rectangle to use
2005 when drawing. */
2007 static void
2008 x_draw_relief_rect (struct frame *f,
2009 int left_x, int top_y, int right_x, int bottom_y, int width,
2010 int raised_p, int top_p, int bot_p, int left_p, int right_p,
2011 XRectangle *clip_rect)
2013 Display *dpy = FRAME_X_DISPLAY (f);
2014 Window window = FRAME_X_WINDOW (f);
2015 int i;
2016 GC gc;
2018 if (raised_p)
2019 gc = f->output_data.x->white_relief.gc;
2020 else
2021 gc = f->output_data.x->black_relief.gc;
2022 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
2024 /* This code is more complicated than it has to be, because of two
2025 minor hacks to make the boxes look nicer: (i) if width > 1, draw
2026 the outermost line using the black relief. (ii) Omit the four
2027 corner pixels. */
2029 /* Top. */
2030 if (top_p)
2032 if (width == 1)
2033 XDrawLine (dpy, window, gc,
2034 left_x + (left_p ? 1 : 0), top_y,
2035 right_x + (right_p ? 0 : 1), top_y);
2037 for (i = 1; i < width; ++i)
2038 XDrawLine (dpy, window, gc,
2039 left_x + i * left_p, top_y + i,
2040 right_x + 1 - i * right_p, top_y + i);
2043 /* Left. */
2044 if (left_p)
2046 if (width == 1)
2047 XDrawLine (dpy, window, gc, left_x, top_y + 1, left_x, bottom_y);
2049 XClearArea (dpy, window, left_x, top_y, 1, 1, False);
2050 XClearArea (dpy, window, left_x, bottom_y, 1, 1, False);
2052 for (i = (width > 1 ? 1 : 0); i < width; ++i)
2053 XDrawLine (dpy, window, gc,
2054 left_x + i, top_y + i, left_x + i, bottom_y - i + 1);
2057 XSetClipMask (dpy, gc, None);
2058 if (raised_p)
2059 gc = f->output_data.x->black_relief.gc;
2060 else
2061 gc = f->output_data.x->white_relief.gc;
2062 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
2064 if (width > 1)
2066 /* Outermost top line. */
2067 if (top_p)
2068 XDrawLine (dpy, window, gc,
2069 left_x + (left_p ? 1 : 0), top_y,
2070 right_x + (right_p ? 0 : 1), top_y);
2072 /* Outermost left line. */
2073 if (left_p)
2074 XDrawLine (dpy, window, gc, left_x, top_y + 1, left_x, bottom_y);
2077 /* Bottom. */
2078 if (bot_p)
2080 XDrawLine (dpy, window, gc,
2081 left_x + (left_p ? 1 : 0), bottom_y,
2082 right_x + (right_p ? 0 : 1), bottom_y);
2083 for (i = 1; i < width; ++i)
2084 XDrawLine (dpy, window, gc,
2085 left_x + i * left_p, bottom_y - i,
2086 right_x + 1 - i * right_p, bottom_y - i);
2089 /* Right. */
2090 if (right_p)
2092 XClearArea (dpy, window, right_x, top_y, 1, 1, False);
2093 XClearArea (dpy, window, right_x, bottom_y, 1, 1, False);
2094 for (i = 0; i < width; ++i)
2095 XDrawLine (dpy, window, gc,
2096 right_x - i, top_y + i + 1, right_x - i, bottom_y - i);
2099 XSetClipMask (dpy, gc, None);
2103 /* Draw a box on frame F inside the rectangle given by LEFT_X, TOP_Y,
2104 RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the lines to
2105 draw, it must be >= 0. LEFT_P non-zero means draw a line on the
2106 left side of the rectangle. RIGHT_P non-zero means draw a line
2107 on the right side of the rectangle. CLIP_RECT is the clipping
2108 rectangle to use when drawing. */
2110 static void
2111 x_draw_box_rect (struct glyph_string *s,
2112 int left_x, int top_y, int right_x, int bottom_y, int width,
2113 int left_p, int right_p, XRectangle *clip_rect)
2115 XGCValues xgcv;
2117 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2118 XSetForeground (s->display, s->gc, s->face->box_color);
2119 XSetClipRectangles (s->display, s->gc, 0, 0, clip_rect, 1, Unsorted);
2121 /* Top. */
2122 XFillRectangle (s->display, s->window, s->gc,
2123 left_x, top_y, right_x - left_x + 1, width);
2125 /* Left. */
2126 if (left_p)
2127 XFillRectangle (s->display, s->window, s->gc,
2128 left_x, top_y, width, bottom_y - top_y + 1);
2130 /* Bottom. */
2131 XFillRectangle (s->display, s->window, s->gc,
2132 left_x, bottom_y - width + 1, right_x - left_x + 1, width);
2134 /* Right. */
2135 if (right_p)
2136 XFillRectangle (s->display, s->window, s->gc,
2137 right_x - width + 1, top_y, width, bottom_y - top_y + 1);
2139 XSetForeground (s->display, s->gc, xgcv.foreground);
2140 XSetClipMask (s->display, s->gc, None);
2144 /* Draw a box around glyph string S. */
2146 static void
2147 x_draw_glyph_string_box (struct glyph_string *s)
2149 int width, left_x, right_x, top_y, bottom_y, last_x, raised_p;
2150 int left_p, right_p;
2151 struct glyph *last_glyph;
2152 XRectangle clip_rect;
2154 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2155 ? WINDOW_RIGHT_EDGE_X (s->w)
2156 : window_box_right (s->w, s->area));
2158 /* The glyph that may have a right box line. */
2159 last_glyph = (s->cmp || s->img
2160 ? s->first_glyph
2161 : s->first_glyph + s->nchars - 1);
2163 width = eabs (s->face->box_line_width);
2164 raised_p = s->face->box == FACE_RAISED_BOX;
2165 left_x = s->x;
2166 right_x = (s->row->full_width_p && s->extends_to_end_of_line_p
2167 ? last_x - 1
2168 : min (last_x, s->x + s->background_width) - 1);
2169 top_y = s->y;
2170 bottom_y = top_y + s->height - 1;
2172 left_p = (s->first_glyph->left_box_line_p
2173 || (s->hl == DRAW_MOUSE_FACE
2174 && (s->prev == NULL
2175 || s->prev->hl != s->hl)));
2176 right_p = (last_glyph->right_box_line_p
2177 || (s->hl == DRAW_MOUSE_FACE
2178 && (s->next == NULL
2179 || s->next->hl != s->hl)));
2181 get_glyph_string_clip_rect (s, &clip_rect);
2183 if (s->face->box == FACE_SIMPLE_BOX)
2184 x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
2185 left_p, right_p, &clip_rect);
2186 else
2188 x_setup_relief_colors (s);
2189 x_draw_relief_rect (s->f, left_x, top_y, right_x, bottom_y,
2190 width, raised_p, 1, 1, left_p, right_p, &clip_rect);
2195 /* Draw foreground of image glyph string S. */
2197 static void
2198 x_draw_image_foreground (struct glyph_string *s)
2200 int x = s->x;
2201 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2203 /* If first glyph of S has a left box line, start drawing it to the
2204 right of that line. */
2205 if (s->face->box != FACE_NO_BOX
2206 && s->first_glyph->left_box_line_p
2207 && s->slice.x == 0)
2208 x += eabs (s->face->box_line_width);
2210 /* If there is a margin around the image, adjust x- and y-position
2211 by that margin. */
2212 if (s->slice.x == 0)
2213 x += s->img->hmargin;
2214 if (s->slice.y == 0)
2215 y += s->img->vmargin;
2217 if (s->img->pixmap)
2219 if (s->img->mask)
2221 /* We can't set both a clip mask and use XSetClipRectangles
2222 because the latter also sets a clip mask. We also can't
2223 trust on the shape extension to be available
2224 (XShapeCombineRegion). So, compute the rectangle to draw
2225 manually. */
2226 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
2227 | GCFunction);
2228 XGCValues xgcv;
2229 XRectangle clip_rect, image_rect, r;
2231 xgcv.clip_mask = s->img->mask;
2232 xgcv.clip_x_origin = x;
2233 xgcv.clip_y_origin = y;
2234 xgcv.function = GXcopy;
2235 XChangeGC (s->display, s->gc, mask, &xgcv);
2237 get_glyph_string_clip_rect (s, &clip_rect);
2238 image_rect.x = x;
2239 image_rect.y = y;
2240 image_rect.width = s->slice.width;
2241 image_rect.height = s->slice.height;
2242 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
2243 XCopyArea (s->display, s->img->pixmap, s->window, s->gc,
2244 s->slice.x + r.x - x, s->slice.y + r.y - y,
2245 r.width, r.height, r.x, r.y);
2247 else
2249 XRectangle clip_rect, image_rect, r;
2251 get_glyph_string_clip_rect (s, &clip_rect);
2252 image_rect.x = x;
2253 image_rect.y = y;
2254 image_rect.width = s->slice.width;
2255 image_rect.height = s->slice.height;
2256 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
2257 XCopyArea (s->display, s->img->pixmap, s->window, s->gc,
2258 s->slice.x + r.x - x, s->slice.y + r.y - y,
2259 r.width, r.height, r.x, r.y);
2261 /* When the image has a mask, we can expect that at
2262 least part of a mouse highlight or a block cursor will
2263 be visible. If the image doesn't have a mask, make
2264 a block cursor visible by drawing a rectangle around
2265 the image. I believe it's looking better if we do
2266 nothing here for mouse-face. */
2267 if (s->hl == DRAW_CURSOR)
2269 int relief = s->img->relief;
2270 if (relief < 0) relief = -relief;
2271 XDrawRectangle (s->display, s->window, s->gc,
2272 x - relief, y - relief,
2273 s->slice.width + relief*2 - 1,
2274 s->slice.height + relief*2 - 1);
2278 else
2279 /* Draw a rectangle if image could not be loaded. */
2280 XDrawRectangle (s->display, s->window, s->gc, x, y,
2281 s->slice.width - 1, s->slice.height - 1);
2285 /* Draw a relief around the image glyph string S. */
2287 static void
2288 x_draw_image_relief (struct glyph_string *s)
2290 int x0, y0, x1, y1, thick, raised_p, extra;
2291 XRectangle r;
2292 int x = s->x;
2293 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2295 /* If first glyph of S has a left box line, start drawing it to the
2296 right of that line. */
2297 if (s->face->box != FACE_NO_BOX
2298 && s->first_glyph->left_box_line_p
2299 && s->slice.x == 0)
2300 x += eabs (s->face->box_line_width);
2302 /* If there is a margin around the image, adjust x- and y-position
2303 by that margin. */
2304 if (s->slice.x == 0)
2305 x += s->img->hmargin;
2306 if (s->slice.y == 0)
2307 y += s->img->vmargin;
2309 if (s->hl == DRAW_IMAGE_SUNKEN
2310 || s->hl == DRAW_IMAGE_RAISED)
2312 thick = tool_bar_button_relief >= 0 ? tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
2313 raised_p = s->hl == DRAW_IMAGE_RAISED;
2315 else
2317 thick = eabs (s->img->relief);
2318 raised_p = s->img->relief > 0;
2321 extra = s->face->id == TOOL_BAR_FACE_ID
2322 ? XINT (Vtool_bar_button_margin) : 0;
2324 x0 = x - thick - extra;
2325 y0 = y - thick - extra;
2326 x1 = x + s->slice.width + thick - 1 + extra;
2327 y1 = y + s->slice.height + thick - 1 + extra;
2329 x_setup_relief_colors (s);
2330 get_glyph_string_clip_rect (s, &r);
2331 x_draw_relief_rect (s->f, x0, y0, x1, y1, thick, raised_p,
2332 s->slice.y == 0,
2333 s->slice.y + s->slice.height == s->img->height,
2334 s->slice.x == 0,
2335 s->slice.x + s->slice.width == s->img->width,
2336 &r);
2340 /* Draw the foreground of image glyph string S to PIXMAP. */
2342 static void
2343 x_draw_image_foreground_1 (struct glyph_string *s, Pixmap pixmap)
2345 int x = 0;
2346 int y = s->ybase - s->y - image_ascent (s->img, s->face, &s->slice);
2348 /* If first glyph of S has a left box line, start drawing it to the
2349 right of that line. */
2350 if (s->face->box != FACE_NO_BOX
2351 && s->first_glyph->left_box_line_p
2352 && s->slice.x == 0)
2353 x += eabs (s->face->box_line_width);
2355 /* If there is a margin around the image, adjust x- and y-position
2356 by that margin. */
2357 if (s->slice.x == 0)
2358 x += s->img->hmargin;
2359 if (s->slice.y == 0)
2360 y += s->img->vmargin;
2362 if (s->img->pixmap)
2364 if (s->img->mask)
2366 /* We can't set both a clip mask and use XSetClipRectangles
2367 because the latter also sets a clip mask. We also can't
2368 trust on the shape extension to be available
2369 (XShapeCombineRegion). So, compute the rectangle to draw
2370 manually. */
2371 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
2372 | GCFunction);
2373 XGCValues xgcv;
2375 xgcv.clip_mask = s->img->mask;
2376 xgcv.clip_x_origin = x - s->slice.x;
2377 xgcv.clip_y_origin = y - s->slice.y;
2378 xgcv.function = GXcopy;
2379 XChangeGC (s->display, s->gc, mask, &xgcv);
2381 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
2382 s->slice.x, s->slice.y,
2383 s->slice.width, s->slice.height, x, y);
2384 XSetClipMask (s->display, s->gc, None);
2386 else
2388 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
2389 s->slice.x, s->slice.y,
2390 s->slice.width, s->slice.height, x, y);
2392 /* When the image has a mask, we can expect that at
2393 least part of a mouse highlight or a block cursor will
2394 be visible. If the image doesn't have a mask, make
2395 a block cursor visible by drawing a rectangle around
2396 the image. I believe it's looking better if we do
2397 nothing here for mouse-face. */
2398 if (s->hl == DRAW_CURSOR)
2400 int r = s->img->relief;
2401 if (r < 0) r = -r;
2402 XDrawRectangle (s->display, s->window, s->gc, x - r, y - r,
2403 s->slice.width + r*2 - 1,
2404 s->slice.height + r*2 - 1);
2408 else
2409 /* Draw a rectangle if image could not be loaded. */
2410 XDrawRectangle (s->display, pixmap, s->gc, x, y,
2411 s->slice.width - 1, s->slice.height - 1);
2415 /* Draw part of the background of glyph string S. X, Y, W, and H
2416 give the rectangle to draw. */
2418 static void
2419 x_draw_glyph_string_bg_rect (struct glyph_string *s, int x, int y, int w, int h)
2421 if (s->stippled_p)
2423 /* Fill background with a stipple pattern. */
2424 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
2425 XFillRectangle (s->display, s->window, s->gc, x, y, w, h);
2426 XSetFillStyle (s->display, s->gc, FillSolid);
2428 else
2429 x_clear_glyph_string_rect (s, x, y, w, h);
2433 /* Draw image glyph string S.
2435 s->y
2436 s->x +-------------------------
2437 | s->face->box
2439 | +-------------------------
2440 | | s->img->margin
2442 | | +-------------------
2443 | | | the image
2447 static void
2448 x_draw_image_glyph_string (struct glyph_string *s)
2450 int box_line_hwidth = eabs (s->face->box_line_width);
2451 int box_line_vwidth = max (s->face->box_line_width, 0);
2452 int height;
2453 Pixmap pixmap = None;
2455 height = s->height;
2456 if (s->slice.y == 0)
2457 height -= box_line_vwidth;
2458 if (s->slice.y + s->slice.height >= s->img->height)
2459 height -= box_line_vwidth;
2461 /* Fill background with face under the image. Do it only if row is
2462 taller than image or if image has a clip mask to reduce
2463 flickering. */
2464 s->stippled_p = s->face->stipple != 0;
2465 if (height > s->slice.height
2466 || s->img->hmargin
2467 || s->img->vmargin
2468 || s->img->mask
2469 || s->img->pixmap == 0
2470 || s->width != s->background_width)
2472 if (s->img->mask)
2474 /* Create a pixmap as large as the glyph string. Fill it
2475 with the background color. Copy the image to it, using
2476 its mask. Copy the temporary pixmap to the display. */
2477 Screen *screen = FRAME_X_SCREEN (s->f);
2478 int depth = DefaultDepthOfScreen (screen);
2480 /* Create a pixmap as large as the glyph string. */
2481 pixmap = XCreatePixmap (s->display, s->window,
2482 s->background_width,
2483 s->height, depth);
2485 /* Don't clip in the following because we're working on the
2486 pixmap. */
2487 XSetClipMask (s->display, s->gc, None);
2489 /* Fill the pixmap with the background color/stipple. */
2490 if (s->stippled_p)
2492 /* Fill background with a stipple pattern. */
2493 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
2494 XSetTSOrigin (s->display, s->gc, - s->x, - s->y);
2495 XFillRectangle (s->display, pixmap, s->gc,
2496 0, 0, s->background_width, s->height);
2497 XSetFillStyle (s->display, s->gc, FillSolid);
2498 XSetTSOrigin (s->display, s->gc, 0, 0);
2500 else
2502 XGCValues xgcv;
2503 XGetGCValues (s->display, s->gc, GCForeground | GCBackground,
2504 &xgcv);
2505 XSetForeground (s->display, s->gc, xgcv.background);
2506 XFillRectangle (s->display, pixmap, s->gc,
2507 0, 0, s->background_width, s->height);
2508 XSetForeground (s->display, s->gc, xgcv.foreground);
2511 else
2513 int x = s->x;
2514 int y = s->y;
2516 if (s->first_glyph->left_box_line_p
2517 && s->slice.x == 0)
2518 x += box_line_hwidth;
2520 if (s->slice.y == 0)
2521 y += box_line_vwidth;
2523 x_draw_glyph_string_bg_rect (s, x, y, s->background_width, height);
2526 s->background_filled_p = 1;
2529 /* Draw the foreground. */
2530 if (pixmap != None)
2532 x_draw_image_foreground_1 (s, pixmap);
2533 x_set_glyph_string_clipping (s);
2534 XCopyArea (s->display, pixmap, s->window, s->gc,
2535 0, 0, s->background_width, s->height, s->x, s->y);
2536 XFreePixmap (s->display, pixmap);
2538 else
2539 x_draw_image_foreground (s);
2541 /* If we must draw a relief around the image, do it. */
2542 if (s->img->relief
2543 || s->hl == DRAW_IMAGE_RAISED
2544 || s->hl == DRAW_IMAGE_SUNKEN)
2545 x_draw_image_relief (s);
2549 /* Draw stretch glyph string S. */
2551 static void
2552 x_draw_stretch_glyph_string (struct glyph_string *s)
2554 xassert (s->first_glyph->type == STRETCH_GLYPH);
2556 if (s->hl == DRAW_CURSOR
2557 && !x_stretch_cursor_p)
2559 /* If `x-stretch-cursor' is nil, don't draw a block cursor as
2560 wide as the stretch glyph. */
2561 int width, background_width = s->background_width;
2562 int x = s->x;
2564 if (!s->row->reversed_p)
2566 int left_x = window_box_left_offset (s->w, TEXT_AREA);
2568 if (x < left_x)
2570 background_width -= left_x - x;
2571 x = left_x;
2574 else
2576 /* In R2L rows, draw the cursor on the right edge of the
2577 stretch glyph. */
2578 int right_x = window_box_right_offset (s->w, TEXT_AREA);
2580 if (x + background_width > right_x)
2581 background_width -= x - right_x;
2582 x += background_width;
2584 width = min (FRAME_COLUMN_WIDTH (s->f), background_width);
2585 if (s->row->reversed_p)
2586 x -= width;
2588 /* Draw cursor. */
2589 x_draw_glyph_string_bg_rect (s, x, s->y, width, s->height);
2591 /* Clear rest using the GC of the original non-cursor face. */
2592 if (width < background_width)
2594 int y = s->y;
2595 int w = background_width - width, h = s->height;
2596 XRectangle r;
2597 GC gc;
2599 if (!s->row->reversed_p)
2600 x += width;
2601 else
2602 x = s->x;
2603 if (s->row->mouse_face_p
2604 && cursor_in_mouse_face_p (s->w))
2606 x_set_mouse_face_gc (s);
2607 gc = s->gc;
2609 else
2610 gc = s->face->gc;
2612 get_glyph_string_clip_rect (s, &r);
2613 XSetClipRectangles (s->display, gc, 0, 0, &r, 1, Unsorted);
2615 if (s->face->stipple)
2617 /* Fill background with a stipple pattern. */
2618 XSetFillStyle (s->display, gc, FillOpaqueStippled);
2619 XFillRectangle (s->display, s->window, gc, x, y, w, h);
2620 XSetFillStyle (s->display, gc, FillSolid);
2622 else
2624 XGCValues xgcv;
2625 XGetGCValues (s->display, gc, GCForeground | GCBackground, &xgcv);
2626 XSetForeground (s->display, gc, xgcv.background);
2627 XFillRectangle (s->display, s->window, gc, x, y, w, h);
2628 XSetForeground (s->display, gc, xgcv.foreground);
2632 else if (!s->background_filled_p)
2634 int background_width = s->background_width;
2635 int x = s->x, left_x = window_box_left_offset (s->w, TEXT_AREA);
2637 /* Don't draw into left margin, fringe or scrollbar area
2638 except for header line and mode line. */
2639 if (x < left_x && !s->row->mode_line_p)
2641 background_width -= left_x - x;
2642 x = left_x;
2644 if (background_width > 0)
2645 x_draw_glyph_string_bg_rect (s, x, s->y, background_width, s->height);
2648 s->background_filled_p = 1;
2652 /* Draw glyph string S. */
2654 static void
2655 x_draw_glyph_string (struct glyph_string *s)
2657 int relief_drawn_p = 0;
2659 /* If S draws into the background of its successors, draw the
2660 background of the successors first so that S can draw into it.
2661 This makes S->next use XDrawString instead of XDrawImageString. */
2662 if (s->next && s->right_overhang && !s->for_overlaps)
2664 int width;
2665 struct glyph_string *next;
2667 for (width = 0, next = s->next;
2668 next && width < s->right_overhang;
2669 width += next->width, next = next->next)
2670 if (next->first_glyph->type != IMAGE_GLYPH)
2672 x_set_glyph_string_gc (next);
2673 x_set_glyph_string_clipping (next);
2674 if (next->first_glyph->type == STRETCH_GLYPH)
2675 x_draw_stretch_glyph_string (next);
2676 else
2677 x_draw_glyph_string_background (next, 1);
2678 next->num_clips = 0;
2682 /* Set up S->gc, set clipping and draw S. */
2683 x_set_glyph_string_gc (s);
2685 /* Draw relief (if any) in advance for char/composition so that the
2686 glyph string can be drawn over it. */
2687 if (!s->for_overlaps
2688 && s->face->box != FACE_NO_BOX
2689 && (s->first_glyph->type == CHAR_GLYPH
2690 || s->first_glyph->type == COMPOSITE_GLYPH))
2693 x_set_glyph_string_clipping (s);
2694 x_draw_glyph_string_background (s, 1);
2695 x_draw_glyph_string_box (s);
2696 x_set_glyph_string_clipping (s);
2697 relief_drawn_p = 1;
2699 else if (!s->clip_head /* draw_glyphs didn't specify a clip mask. */
2700 && !s->clip_tail
2701 && ((s->prev && s->prev->hl != s->hl && s->left_overhang)
2702 || (s->next && s->next->hl != s->hl && s->right_overhang)))
2703 /* We must clip just this glyph. left_overhang part has already
2704 drawn when s->prev was drawn, and right_overhang part will be
2705 drawn later when s->next is drawn. */
2706 x_set_glyph_string_clipping_exactly (s, s);
2707 else
2708 x_set_glyph_string_clipping (s);
2710 switch (s->first_glyph->type)
2712 case IMAGE_GLYPH:
2713 x_draw_image_glyph_string (s);
2714 break;
2716 case STRETCH_GLYPH:
2717 x_draw_stretch_glyph_string (s);
2718 break;
2720 case CHAR_GLYPH:
2721 if (s->for_overlaps)
2722 s->background_filled_p = 1;
2723 else
2724 x_draw_glyph_string_background (s, 0);
2725 x_draw_glyph_string_foreground (s);
2726 break;
2728 case COMPOSITE_GLYPH:
2729 if (s->for_overlaps || (s->cmp_from > 0
2730 && ! s->first_glyph->u.cmp.automatic))
2731 s->background_filled_p = 1;
2732 else
2733 x_draw_glyph_string_background (s, 1);
2734 x_draw_composite_glyph_string_foreground (s);
2735 break;
2737 case GLYPHLESS_GLYPH:
2738 if (s->for_overlaps)
2739 s->background_filled_p = 1;
2740 else
2741 x_draw_glyph_string_background (s, 1);
2742 x_draw_glyphless_glyph_string_foreground (s);
2743 break;
2745 default:
2746 abort ();
2749 if (!s->for_overlaps)
2751 /* Draw underline. */
2752 if (s->face->underline_p)
2754 unsigned long thickness, position;
2755 int y;
2757 if (s->prev && s->prev->face->underline_p)
2759 /* We use the same underline style as the previous one. */
2760 thickness = s->prev->underline_thickness;
2761 position = s->prev->underline_position;
2763 else
2765 /* Get the underline thickness. Default is 1 pixel. */
2766 if (s->font && s->font->underline_thickness > 0)
2767 thickness = s->font->underline_thickness;
2768 else
2769 thickness = 1;
2770 if (x_underline_at_descent_line)
2771 position = (s->height - thickness) - (s->ybase - s->y);
2772 else
2774 /* Get the underline position. This is the recommended
2775 vertical offset in pixels from the baseline to the top of
2776 the underline. This is a signed value according to the
2777 specs, and its default is
2779 ROUND ((maximum descent) / 2), with
2780 ROUND(x) = floor (x + 0.5) */
2782 if (x_use_underline_position_properties
2783 && s->font && s->font->underline_position >= 0)
2784 position = s->font->underline_position;
2785 else if (s->font)
2786 position = (s->font->descent + 1) / 2;
2787 else
2788 position = underline_minimum_offset;
2790 position = max (position, underline_minimum_offset);
2792 /* Check the sanity of thickness and position. We should
2793 avoid drawing underline out of the current line area. */
2794 if (s->y + s->height <= s->ybase + position)
2795 position = (s->height - 1) - (s->ybase - s->y);
2796 if (s->y + s->height < s->ybase + position + thickness)
2797 thickness = (s->y + s->height) - (s->ybase + position);
2798 s->underline_thickness = thickness;
2799 s->underline_position = position;
2800 y = s->ybase + position;
2801 if (s->face->underline_defaulted_p)
2802 XFillRectangle (s->display, s->window, s->gc,
2803 s->x, y, s->width, thickness);
2804 else
2806 XGCValues xgcv;
2807 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2808 XSetForeground (s->display, s->gc, s->face->underline_color);
2809 XFillRectangle (s->display, s->window, s->gc,
2810 s->x, y, s->width, thickness);
2811 XSetForeground (s->display, s->gc, xgcv.foreground);
2815 /* Draw overline. */
2816 if (s->face->overline_p)
2818 unsigned long dy = 0, h = 1;
2820 if (s->face->overline_color_defaulted_p)
2821 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2822 s->width, h);
2823 else
2825 XGCValues xgcv;
2826 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2827 XSetForeground (s->display, s->gc, s->face->overline_color);
2828 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2829 s->width, h);
2830 XSetForeground (s->display, s->gc, xgcv.foreground);
2834 /* Draw strike-through. */
2835 if (s->face->strike_through_p)
2837 unsigned long h = 1;
2838 unsigned long dy = (s->height - h) / 2;
2840 if (s->face->strike_through_color_defaulted_p)
2841 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2842 s->width, h);
2843 else
2845 XGCValues xgcv;
2846 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2847 XSetForeground (s->display, s->gc, s->face->strike_through_color);
2848 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2849 s->width, h);
2850 XSetForeground (s->display, s->gc, xgcv.foreground);
2854 /* Draw relief if not yet drawn. */
2855 if (!relief_drawn_p && s->face->box != FACE_NO_BOX)
2856 x_draw_glyph_string_box (s);
2858 if (s->prev)
2860 struct glyph_string *prev;
2862 for (prev = s->prev; prev; prev = prev->prev)
2863 if (prev->hl != s->hl
2864 && prev->x + prev->width + prev->right_overhang > s->x)
2866 /* As prev was drawn while clipped to its own area, we
2867 must draw the right_overhang part using s->hl now. */
2868 enum draw_glyphs_face save = prev->hl;
2870 prev->hl = s->hl;
2871 x_set_glyph_string_gc (prev);
2872 x_set_glyph_string_clipping_exactly (s, prev);
2873 if (prev->first_glyph->type == CHAR_GLYPH)
2874 x_draw_glyph_string_foreground (prev);
2875 else
2876 x_draw_composite_glyph_string_foreground (prev);
2877 XSetClipMask (prev->display, prev->gc, None);
2878 prev->hl = save;
2879 prev->num_clips = 0;
2883 if (s->next)
2885 struct glyph_string *next;
2887 for (next = s->next; next; next = next->next)
2888 if (next->hl != s->hl
2889 && next->x - next->left_overhang < s->x + s->width)
2891 /* As next will be drawn while clipped to its own area,
2892 we must draw the left_overhang part using s->hl now. */
2893 enum draw_glyphs_face save = next->hl;
2895 next->hl = s->hl;
2896 x_set_glyph_string_gc (next);
2897 x_set_glyph_string_clipping_exactly (s, next);
2898 if (next->first_glyph->type == CHAR_GLYPH)
2899 x_draw_glyph_string_foreground (next);
2900 else
2901 x_draw_composite_glyph_string_foreground (next);
2902 XSetClipMask (next->display, next->gc, None);
2903 next->hl = save;
2904 next->num_clips = 0;
2909 /* Reset clipping. */
2910 XSetClipMask (s->display, s->gc, None);
2911 s->num_clips = 0;
2914 /* Shift display to make room for inserted glyphs. */
2916 static void
2917 x_shift_glyphs_for_insert (struct frame *f, int x, int y, int width, int height, int shift_by)
2919 XCopyArea (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), FRAME_X_WINDOW (f),
2920 f->output_data.x->normal_gc,
2921 x, y, width, height,
2922 x + shift_by, y);
2925 /* Delete N glyphs at the nominal cursor position. Not implemented
2926 for X frames. */
2928 static void
2929 x_delete_glyphs (struct frame *f, register int n)
2931 abort ();
2935 /* Like XClearArea, but check that WIDTH and HEIGHT are reasonable.
2936 If they are <= 0, this is probably an error. */
2938 void
2939 x_clear_area (Display *dpy, Window window, int x, int y, int width, int height, int exposures)
2941 xassert (width > 0 && height > 0);
2942 XClearArea (dpy, window, x, y, width, height, exposures);
2946 /* Clear an entire frame. */
2948 static void
2949 x_clear_frame (struct frame *f)
2951 /* Clearing the frame will erase any cursor, so mark them all as no
2952 longer visible. */
2953 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2954 output_cursor.hpos = output_cursor.vpos = 0;
2955 output_cursor.x = -1;
2957 /* We don't set the output cursor here because there will always
2958 follow an explicit cursor_to. */
2959 BLOCK_INPUT;
2961 /* The following call is commented out because it does not seem to accomplish
2962 anything, apart from causing flickering during window resize. */
2963 /* XClearWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f)); */
2965 /* We have to clear the scroll bars. If we have changed colors or
2966 something like that, then they should be notified. */
2967 x_scroll_bar_clear (f);
2969 #if defined (USE_GTK) && defined (USE_TOOLKIT_SCROLL_BARS)
2970 /* Make sure scroll bars are redrawn. As they aren't redrawn by
2971 redisplay, do it here. */
2972 if (FRAME_GTK_WIDGET (f))
2973 gtk_widget_queue_draw (FRAME_GTK_WIDGET (f));
2974 #endif
2976 XFlush (FRAME_X_DISPLAY (f));
2978 UNBLOCK_INPUT;
2983 /* Invert the middle quarter of the frame for .15 sec. */
2985 /* We use the select system call to do the waiting, so we have to make
2986 sure it's available. If it isn't, we just won't do visual bells. */
2988 #if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
2991 /* Subtract the `struct timeval' values X and Y, storing the result in
2992 *RESULT. Return 1 if the difference is negative, otherwise 0. */
2994 static int
2995 timeval_subtract (struct timeval *result, struct timeval x, struct timeval y)
2997 /* Perform the carry for the later subtraction by updating y. This
2998 is safer because on some systems the tv_sec member is unsigned. */
2999 if (x.tv_usec < y.tv_usec)
3001 int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
3002 y.tv_usec -= 1000000 * nsec;
3003 y.tv_sec += nsec;
3006 if (x.tv_usec - y.tv_usec > 1000000)
3008 int nsec = (y.tv_usec - x.tv_usec) / 1000000;
3009 y.tv_usec += 1000000 * nsec;
3010 y.tv_sec -= nsec;
3013 /* Compute the time remaining to wait. tv_usec is certainly
3014 positive. */
3015 result->tv_sec = x.tv_sec - y.tv_sec;
3016 result->tv_usec = x.tv_usec - y.tv_usec;
3018 /* Return indication of whether the result should be considered
3019 negative. */
3020 return x.tv_sec < y.tv_sec;
3023 static void
3024 XTflash (struct frame *f)
3026 BLOCK_INPUT;
3029 #ifdef USE_GTK
3030 /* Use Gdk routines to draw. This way, we won't draw over scroll bars
3031 when the scroll bars and the edit widget share the same X window. */
3032 GdkWindow *window = gtk_widget_get_window (FRAME_GTK_WIDGET (f));
3033 #ifdef HAVE_GTK3
3034 cairo_t *cr = gdk_cairo_create (window);
3035 cairo_set_source_rgb (cr, 1, 1, 1);
3036 cairo_set_operator (cr, CAIRO_OPERATOR_DIFFERENCE);
3037 #define XFillRectangle(d, win, gc, x, y, w, h) \
3038 do { \
3039 cairo_rectangle (cr, x, y, w, h); \
3040 cairo_fill (cr); \
3042 while (0)
3043 #else /* ! HAVE_GTK3 */
3044 GdkGCValues vals;
3045 GdkGC *gc;
3046 vals.foreground.pixel = (FRAME_FOREGROUND_PIXEL (f)
3047 ^ FRAME_BACKGROUND_PIXEL (f));
3048 vals.function = GDK_XOR;
3049 gc = gdk_gc_new_with_values (window,
3050 &vals, GDK_GC_FUNCTION | GDK_GC_FOREGROUND);
3051 #define XFillRectangle(d, win, gc, x, y, w, h) \
3052 gdk_draw_rectangle (window, gc, TRUE, x, y, w, h)
3053 #endif /* ! HAVE_GTK3 */
3054 #else /* ! USE_GTK */
3055 GC gc;
3057 /* Create a GC that will use the GXxor function to flip foreground
3058 pixels into background pixels. */
3060 XGCValues values;
3062 values.function = GXxor;
3063 values.foreground = (FRAME_FOREGROUND_PIXEL (f)
3064 ^ FRAME_BACKGROUND_PIXEL (f));
3066 gc = XCreateGC (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3067 GCFunction | GCForeground, &values);
3069 #endif
3071 /* Get the height not including a menu bar widget. */
3072 int height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, FRAME_LINES (f));
3073 /* Height of each line to flash. */
3074 int flash_height = FRAME_LINE_HEIGHT (f);
3075 /* These will be the left and right margins of the rectangles. */
3076 int flash_left = FRAME_INTERNAL_BORDER_WIDTH (f);
3077 int flash_right = FRAME_PIXEL_WIDTH (f) - FRAME_INTERNAL_BORDER_WIDTH (f);
3079 int width;
3081 /* Don't flash the area between a scroll bar and the frame
3082 edge it is next to. */
3083 switch (FRAME_VERTICAL_SCROLL_BAR_TYPE (f))
3085 case vertical_scroll_bar_left:
3086 flash_left += VERTICAL_SCROLL_BAR_WIDTH_TRIM;
3087 break;
3089 case vertical_scroll_bar_right:
3090 flash_right -= VERTICAL_SCROLL_BAR_WIDTH_TRIM;
3091 break;
3093 default:
3094 break;
3097 width = flash_right - flash_left;
3099 /* If window is tall, flash top and bottom line. */
3100 if (height > 3 * FRAME_LINE_HEIGHT (f))
3102 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3103 flash_left,
3104 (FRAME_INTERNAL_BORDER_WIDTH (f)
3105 + FRAME_TOP_MARGIN_HEIGHT (f)),
3106 width, flash_height);
3107 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3108 flash_left,
3109 (height - flash_height
3110 - FRAME_INTERNAL_BORDER_WIDTH (f)),
3111 width, flash_height);
3114 else
3115 /* If it is short, flash it all. */
3116 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3117 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
3118 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
3120 x_flush (f);
3123 struct timeval wakeup;
3125 EMACS_GET_TIME (wakeup);
3127 /* Compute time to wait until, propagating carry from usecs. */
3128 wakeup.tv_usec += 150000;
3129 wakeup.tv_sec += (wakeup.tv_usec / 1000000);
3130 wakeup.tv_usec %= 1000000;
3132 /* Keep waiting until past the time wakeup or any input gets
3133 available. */
3134 while (! detect_input_pending ())
3136 struct timeval current;
3137 struct timeval timeout;
3139 EMACS_GET_TIME (current);
3141 /* Break if result would be negative. */
3142 if (timeval_subtract (&current, wakeup, current))
3143 break;
3145 /* How long `select' should wait. */
3146 timeout.tv_sec = 0;
3147 timeout.tv_usec = 10000;
3149 /* Try to wait that long--but we might wake up sooner. */
3150 select (0, NULL, NULL, NULL, &timeout);
3154 /* If window is tall, flash top and bottom line. */
3155 if (height > 3 * FRAME_LINE_HEIGHT (f))
3157 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3158 flash_left,
3159 (FRAME_INTERNAL_BORDER_WIDTH (f)
3160 + FRAME_TOP_MARGIN_HEIGHT (f)),
3161 width, flash_height);
3162 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3163 flash_left,
3164 (height - flash_height
3165 - FRAME_INTERNAL_BORDER_WIDTH (f)),
3166 width, flash_height);
3168 else
3169 /* If it is short, flash it all. */
3170 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3171 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
3172 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
3174 #ifdef USE_GTK
3175 #ifdef HAVE_GTK3
3176 cairo_destroy (cr);
3177 #else
3178 g_object_unref (G_OBJECT (gc));
3179 #endif
3180 #undef XFillRectangle
3181 #else
3182 XFreeGC (FRAME_X_DISPLAY (f), gc);
3183 #endif
3184 x_flush (f);
3188 UNBLOCK_INPUT;
3191 #endif /* defined (HAVE_TIMEVAL) && defined (HAVE_SELECT) */
3194 static void
3195 XTtoggle_invisible_pointer (FRAME_PTR f, int invisible)
3197 BLOCK_INPUT;
3198 if (invisible)
3200 if (FRAME_X_DISPLAY_INFO (f)->invisible_cursor != 0)
3201 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3202 FRAME_X_DISPLAY_INFO (f)->invisible_cursor);
3204 else
3205 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3206 f->output_data.x->current_cursor);
3207 f->pointer_invisible = invisible;
3208 UNBLOCK_INPUT;
3212 /* Make audible bell. */
3214 static void
3215 XTring_bell (struct frame *f)
3217 if (FRAME_X_DISPLAY (f))
3219 #if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
3220 if (visible_bell)
3221 XTflash (f);
3222 else
3223 #endif
3225 BLOCK_INPUT;
3226 XBell (FRAME_X_DISPLAY (f), 0);
3227 XFlush (FRAME_X_DISPLAY (f));
3228 UNBLOCK_INPUT;
3234 /* Specify how many text lines, from the top of the window,
3235 should be affected by insert-lines and delete-lines operations.
3236 This, and those operations, are used only within an update
3237 that is bounded by calls to x_update_begin and x_update_end. */
3239 static void
3240 XTset_terminal_window (struct frame *f, int n)
3242 /* This function intentionally left blank. */
3247 /***********************************************************************
3248 Line Dance
3249 ***********************************************************************/
3251 /* Perform an insert-lines or delete-lines operation, inserting N
3252 lines or deleting -N lines at vertical position VPOS. */
3254 static void
3255 x_ins_del_lines (struct frame *f, int vpos, int n)
3257 abort ();
3261 /* Scroll part of the display as described by RUN. */
3263 static void
3264 x_scroll_run (struct window *w, struct run *run)
3266 struct frame *f = XFRAME (w->frame);
3267 int x, y, width, height, from_y, to_y, bottom_y;
3269 /* Get frame-relative bounding box of the text display area of W,
3270 without mode lines. Include in this box the left and right
3271 fringe of W. */
3272 window_box (w, -1, &x, &y, &width, &height);
3274 #ifdef USE_TOOLKIT_SCROLL_BARS
3275 /* If the fringe is adjacent to the left (right) scroll bar of a
3276 leftmost (rightmost, respectively) window, then extend its
3277 background to the gap between the fringe and the bar. */
3278 if ((WINDOW_LEFTMOST_P (w)
3279 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
3280 || (WINDOW_RIGHTMOST_P (w)
3281 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w)))
3283 int sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
3285 if (sb_width > 0)
3287 int bar_area_x = WINDOW_SCROLL_BAR_AREA_X (w);
3288 int bar_area_width = (WINDOW_CONFIG_SCROLL_BAR_COLS (w)
3289 * FRAME_COLUMN_WIDTH (f));
3291 if (bar_area_x + bar_area_width == x)
3293 x = bar_area_x + sb_width;
3294 width += bar_area_width - sb_width;
3296 else if (x + width == bar_area_x)
3297 width += bar_area_width - sb_width;
3300 #endif
3302 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
3303 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
3304 bottom_y = y + height;
3306 if (to_y < from_y)
3308 /* Scrolling up. Make sure we don't copy part of the mode
3309 line at the bottom. */
3310 if (from_y + run->height > bottom_y)
3311 height = bottom_y - from_y;
3312 else
3313 height = run->height;
3315 else
3317 /* Scolling down. Make sure we don't copy over the mode line.
3318 at the bottom. */
3319 if (to_y + run->height > bottom_y)
3320 height = bottom_y - to_y;
3321 else
3322 height = run->height;
3325 BLOCK_INPUT;
3327 /* Cursor off. Will be switched on again in x_update_window_end. */
3328 updated_window = w;
3329 x_clear_cursor (w);
3331 XCopyArea (FRAME_X_DISPLAY (f),
3332 FRAME_X_WINDOW (f), FRAME_X_WINDOW (f),
3333 f->output_data.x->normal_gc,
3334 x, from_y,
3335 width, height,
3336 x, to_y);
3338 UNBLOCK_INPUT;
3343 /***********************************************************************
3344 Exposure Events
3345 ***********************************************************************/
3348 static void
3349 frame_highlight (struct frame *f)
3351 /* We used to only do this if Vx_no_window_manager was non-nil, but
3352 the ICCCM (section 4.1.6) says that the window's border pixmap
3353 and border pixel are window attributes which are "private to the
3354 client", so we can always change it to whatever we want. */
3355 BLOCK_INPUT;
3356 XSetWindowBorder (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3357 f->output_data.x->border_pixel);
3358 UNBLOCK_INPUT;
3359 x_update_cursor (f, 1);
3360 x_set_frame_alpha (f);
3363 static void
3364 frame_unhighlight (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 XSetWindowBorderPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3372 f->output_data.x->border_tile);
3373 UNBLOCK_INPUT;
3374 x_update_cursor (f, 1);
3375 x_set_frame_alpha (f);
3378 /* The focus has changed. Update the frames as necessary to reflect
3379 the new situation. Note that we can't change the selected frame
3380 here, because the Lisp code we are interrupting might become confused.
3381 Each event gets marked with the frame in which it occurred, so the
3382 Lisp code can tell when the switch took place by examining the events. */
3384 static void
3385 x_new_focus_frame (struct x_display_info *dpyinfo, struct frame *frame)
3387 struct frame *old_focus = dpyinfo->x_focus_frame;
3389 if (frame != dpyinfo->x_focus_frame)
3391 /* Set this before calling other routines, so that they see
3392 the correct value of x_focus_frame. */
3393 dpyinfo->x_focus_frame = frame;
3395 if (old_focus && old_focus->auto_lower)
3396 x_lower_frame (old_focus);
3398 if (dpyinfo->x_focus_frame && dpyinfo->x_focus_frame->auto_raise)
3399 pending_autoraise_frame = dpyinfo->x_focus_frame;
3400 else
3401 pending_autoraise_frame = 0;
3404 x_frame_rehighlight (dpyinfo);
3407 /* Handle FocusIn and FocusOut state changes for FRAME.
3408 If FRAME has focus and there exists more than one frame, puts
3409 a FOCUS_IN_EVENT into *BUFP. */
3411 static void
3412 x_focus_changed (int type, int state, struct x_display_info *dpyinfo, struct frame *frame, struct input_event *bufp)
3414 if (type == FocusIn)
3416 if (dpyinfo->x_focus_event_frame != frame)
3418 x_new_focus_frame (dpyinfo, frame);
3419 dpyinfo->x_focus_event_frame = frame;
3421 /* Don't stop displaying the initial startup message
3422 for a switch-frame event we don't need. */
3423 if (NILP (Vterminal_frame)
3424 && CONSP (Vframe_list)
3425 && !NILP (XCDR (Vframe_list)))
3427 bufp->kind = FOCUS_IN_EVENT;
3428 XSETFRAME (bufp->frame_or_window, frame);
3432 frame->output_data.x->focus_state |= state;
3434 #ifdef HAVE_X_I18N
3435 if (FRAME_XIC (frame))
3436 XSetICFocus (FRAME_XIC (frame));
3437 #endif
3439 else if (type == FocusOut)
3441 frame->output_data.x->focus_state &= ~state;
3443 if (dpyinfo->x_focus_event_frame == frame)
3445 dpyinfo->x_focus_event_frame = 0;
3446 x_new_focus_frame (dpyinfo, 0);
3449 #ifdef HAVE_X_I18N
3450 if (FRAME_XIC (frame))
3451 XUnsetICFocus (FRAME_XIC (frame));
3452 #endif
3453 if (frame->pointer_invisible)
3454 XTtoggle_invisible_pointer (frame, 0);
3458 /* The focus may have changed. Figure out if it is a real focus change,
3459 by checking both FocusIn/Out and Enter/LeaveNotify events.
3461 Returns FOCUS_IN_EVENT event in *BUFP. */
3463 static void
3464 x_detect_focus_change (struct x_display_info *dpyinfo, XEvent *event, struct input_event *bufp)
3466 struct frame *frame;
3468 frame = x_any_window_to_frame (dpyinfo, event->xany.window);
3469 if (! frame)
3470 return;
3472 switch (event->type)
3474 case EnterNotify:
3475 case LeaveNotify:
3477 struct frame *focus_frame = dpyinfo->x_focus_event_frame;
3478 int focus_state
3479 = focus_frame ? focus_frame->output_data.x->focus_state : 0;
3481 if (event->xcrossing.detail != NotifyInferior
3482 && event->xcrossing.focus
3483 && ! (focus_state & FOCUS_EXPLICIT))
3484 x_focus_changed ((event->type == EnterNotify ? FocusIn : FocusOut),
3485 FOCUS_IMPLICIT,
3486 dpyinfo, frame, bufp);
3488 break;
3490 case FocusIn:
3491 case FocusOut:
3492 x_focus_changed (event->type,
3493 (event->xfocus.detail == NotifyPointer ?
3494 FOCUS_IMPLICIT : FOCUS_EXPLICIT),
3495 dpyinfo, frame, bufp);
3496 break;
3498 case ClientMessage:
3499 if (event->xclient.message_type == dpyinfo->Xatom_XEMBED)
3501 enum xembed_message msg = event->xclient.data.l[1];
3502 x_focus_changed ((msg == XEMBED_FOCUS_IN ? FocusIn : FocusOut),
3503 FOCUS_EXPLICIT, dpyinfo, frame, bufp);
3505 break;
3510 #if defined HAVE_MENUS && !defined USE_X_TOOLKIT && !defined USE_GTK
3511 /* Handle an event saying the mouse has moved out of an Emacs frame. */
3513 void
3514 x_mouse_leave (struct x_display_info *dpyinfo)
3516 x_new_focus_frame (dpyinfo, dpyinfo->x_focus_event_frame);
3518 #endif
3520 /* The focus has changed, or we have redirected a frame's focus to
3521 another frame (this happens when a frame uses a surrogate
3522 mini-buffer frame). Shift the highlight as appropriate.
3524 The FRAME argument doesn't necessarily have anything to do with which
3525 frame is being highlighted or un-highlighted; we only use it to find
3526 the appropriate X display info. */
3528 static void
3529 XTframe_rehighlight (struct frame *frame)
3531 x_frame_rehighlight (FRAME_X_DISPLAY_INFO (frame));
3534 static void
3535 x_frame_rehighlight (struct x_display_info *dpyinfo)
3537 struct frame *old_highlight = dpyinfo->x_highlight_frame;
3539 if (dpyinfo->x_focus_frame)
3541 dpyinfo->x_highlight_frame
3542 = ((FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame)))
3543 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
3544 : dpyinfo->x_focus_frame);
3545 if (! FRAME_LIVE_P (dpyinfo->x_highlight_frame))
3547 FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
3548 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
3551 else
3552 dpyinfo->x_highlight_frame = 0;
3554 if (dpyinfo->x_highlight_frame != old_highlight)
3556 if (old_highlight)
3557 frame_unhighlight (old_highlight);
3558 if (dpyinfo->x_highlight_frame)
3559 frame_highlight (dpyinfo->x_highlight_frame);
3565 /* Keyboard processing - modifier keys, vendor-specific keysyms, etc. */
3567 /* Initialize mode_switch_bit and modifier_meaning. */
3568 static void
3569 x_find_modifier_meanings (struct x_display_info *dpyinfo)
3571 int min_code, max_code;
3572 KeySym *syms;
3573 int syms_per_code;
3574 XModifierKeymap *mods;
3576 dpyinfo->meta_mod_mask = 0;
3577 dpyinfo->shift_lock_mask = 0;
3578 dpyinfo->alt_mod_mask = 0;
3579 dpyinfo->super_mod_mask = 0;
3580 dpyinfo->hyper_mod_mask = 0;
3582 XDisplayKeycodes (dpyinfo->display, &min_code, &max_code);
3584 syms = XGetKeyboardMapping (dpyinfo->display,
3585 min_code, max_code - min_code + 1,
3586 &syms_per_code);
3587 mods = XGetModifierMapping (dpyinfo->display);
3589 /* Scan the modifier table to see which modifier bits the Meta and
3590 Alt keysyms are on. */
3592 int row, col; /* The row and column in the modifier table. */
3593 int found_alt_or_meta;
3595 for (row = 3; row < 8; row++)
3597 found_alt_or_meta = 0;
3598 for (col = 0; col < mods->max_keypermod; col++)
3600 KeyCode code = mods->modifiermap[(row * mods->max_keypermod) + col];
3602 /* Zeroes are used for filler. Skip them. */
3603 if (code == 0)
3604 continue;
3606 /* Are any of this keycode's keysyms a meta key? */
3608 int code_col;
3610 for (code_col = 0; code_col < syms_per_code; code_col++)
3612 int sym = syms[((code - min_code) * syms_per_code) + code_col];
3614 switch (sym)
3616 case XK_Meta_L:
3617 case XK_Meta_R:
3618 found_alt_or_meta = 1;
3619 dpyinfo->meta_mod_mask |= (1 << row);
3620 break;
3622 case XK_Alt_L:
3623 case XK_Alt_R:
3624 found_alt_or_meta = 1;
3625 dpyinfo->alt_mod_mask |= (1 << row);
3626 break;
3628 case XK_Hyper_L:
3629 case XK_Hyper_R:
3630 if (!found_alt_or_meta)
3631 dpyinfo->hyper_mod_mask |= (1 << row);
3632 code_col = syms_per_code;
3633 col = mods->max_keypermod;
3634 break;
3636 case XK_Super_L:
3637 case XK_Super_R:
3638 if (!found_alt_or_meta)
3639 dpyinfo->super_mod_mask |= (1 << row);
3640 code_col = syms_per_code;
3641 col = mods->max_keypermod;
3642 break;
3644 case XK_Shift_Lock:
3645 /* Ignore this if it's not on the lock modifier. */
3646 if (!found_alt_or_meta && ((1 << row) == LockMask))
3647 dpyinfo->shift_lock_mask = LockMask;
3648 code_col = syms_per_code;
3649 col = mods->max_keypermod;
3650 break;
3658 /* If we couldn't find any meta keys, accept any alt keys as meta keys. */
3659 if (! dpyinfo->meta_mod_mask)
3661 dpyinfo->meta_mod_mask = dpyinfo->alt_mod_mask;
3662 dpyinfo->alt_mod_mask = 0;
3665 /* If some keys are both alt and meta,
3666 make them just meta, not alt. */
3667 if (dpyinfo->alt_mod_mask & dpyinfo->meta_mod_mask)
3669 dpyinfo->alt_mod_mask &= ~dpyinfo->meta_mod_mask;
3672 XFree ((char *) syms);
3673 XFreeModifiermap (mods);
3676 /* Convert between the modifier bits X uses and the modifier bits
3677 Emacs uses. */
3679 EMACS_INT
3680 x_x_to_emacs_modifiers (struct x_display_info *dpyinfo, int state)
3682 EMACS_INT mod_meta = meta_modifier;
3683 EMACS_INT mod_alt = alt_modifier;
3684 EMACS_INT mod_hyper = hyper_modifier;
3685 EMACS_INT mod_super = super_modifier;
3686 Lisp_Object tem;
3688 tem = Fget (Vx_alt_keysym, Qmodifier_value);
3689 if (INTEGERP (tem)) mod_alt = XINT (tem);
3690 tem = Fget (Vx_meta_keysym, Qmodifier_value);
3691 if (INTEGERP (tem)) mod_meta = XINT (tem);
3692 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
3693 if (INTEGERP (tem)) mod_hyper = XINT (tem);
3694 tem = Fget (Vx_super_keysym, Qmodifier_value);
3695 if (INTEGERP (tem)) mod_super = XINT (tem);
3698 return ( ((state & (ShiftMask | dpyinfo->shift_lock_mask)) ? shift_modifier : 0)
3699 | ((state & ControlMask) ? ctrl_modifier : 0)
3700 | ((state & dpyinfo->meta_mod_mask) ? mod_meta : 0)
3701 | ((state & dpyinfo->alt_mod_mask) ? mod_alt : 0)
3702 | ((state & dpyinfo->super_mod_mask) ? mod_super : 0)
3703 | ((state & dpyinfo->hyper_mod_mask) ? mod_hyper : 0));
3706 static int
3707 x_emacs_to_x_modifiers (struct x_display_info *dpyinfo, EMACS_INT state)
3709 int mod_meta = meta_modifier;
3710 int mod_alt = alt_modifier;
3711 int mod_hyper = hyper_modifier;
3712 int mod_super = super_modifier;
3714 Lisp_Object tem;
3716 tem = Fget (Vx_alt_keysym, Qmodifier_value);
3717 if (INTEGERP (tem)) mod_alt = XINT (tem);
3718 tem = Fget (Vx_meta_keysym, Qmodifier_value);
3719 if (INTEGERP (tem)) mod_meta = XINT (tem);
3720 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
3721 if (INTEGERP (tem)) mod_hyper = XINT (tem);
3722 tem = Fget (Vx_super_keysym, Qmodifier_value);
3723 if (INTEGERP (tem)) mod_super = XINT (tem);
3726 return ( ((state & mod_alt) ? dpyinfo->alt_mod_mask : 0)
3727 | ((state & mod_super) ? dpyinfo->super_mod_mask : 0)
3728 | ((state & mod_hyper) ? dpyinfo->hyper_mod_mask : 0)
3729 | ((state & shift_modifier) ? ShiftMask : 0)
3730 | ((state & ctrl_modifier) ? ControlMask : 0)
3731 | ((state & mod_meta) ? dpyinfo->meta_mod_mask : 0));
3734 /* Convert a keysym to its name. */
3736 char *
3737 x_get_keysym_name (int keysym)
3739 char *value;
3741 BLOCK_INPUT;
3742 value = XKeysymToString (keysym);
3743 UNBLOCK_INPUT;
3745 return value;
3750 /* Mouse clicks and mouse movement. Rah. */
3752 /* Prepare a mouse-event in *RESULT for placement in the input queue.
3754 If the event is a button press, then note that we have grabbed
3755 the mouse. */
3757 static Lisp_Object
3758 construct_mouse_click (struct input_event *result, XButtonEvent *event, struct frame *f)
3760 /* Make the event type NO_EVENT; we'll change that when we decide
3761 otherwise. */
3762 result->kind = MOUSE_CLICK_EVENT;
3763 result->code = event->button - Button1;
3764 result->timestamp = event->time;
3765 result->modifiers = (x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO (f),
3766 event->state)
3767 | (event->type == ButtonRelease
3768 ? up_modifier
3769 : down_modifier));
3771 XSETINT (result->x, event->x);
3772 XSETINT (result->y, event->y);
3773 XSETFRAME (result->frame_or_window, f);
3774 result->arg = Qnil;
3775 return Qnil;
3779 /* Function to report a mouse movement to the mainstream Emacs code.
3780 The input handler calls this.
3782 We have received a mouse movement event, which is given in *event.
3783 If the mouse is over a different glyph than it was last time, tell
3784 the mainstream emacs code by setting mouse_moved. If not, ask for
3785 another motion event, so we can check again the next time it moves. */
3787 static XMotionEvent last_mouse_motion_event;
3788 static Lisp_Object last_mouse_motion_frame;
3790 static int
3791 note_mouse_movement (FRAME_PTR frame, XMotionEvent *event)
3793 last_mouse_movement_time = event->time;
3794 last_mouse_motion_event = *event;
3795 XSETFRAME (last_mouse_motion_frame, frame);
3797 if (!FRAME_X_OUTPUT (frame))
3798 return 0;
3800 if (event->window != FRAME_X_WINDOW (frame))
3802 frame->mouse_moved = 1;
3803 last_mouse_scroll_bar = Qnil;
3804 note_mouse_highlight (frame, -1, -1);
3805 last_mouse_glyph_frame = 0;
3806 return 1;
3810 /* Has the mouse moved off the glyph it was on at the last sighting? */
3811 if (frame != last_mouse_glyph_frame
3812 || event->x < last_mouse_glyph.x
3813 || event->x >= last_mouse_glyph.x + last_mouse_glyph.width
3814 || event->y < last_mouse_glyph.y
3815 || event->y >= last_mouse_glyph.y + last_mouse_glyph.height)
3817 frame->mouse_moved = 1;
3818 last_mouse_scroll_bar = Qnil;
3819 note_mouse_highlight (frame, event->x, event->y);
3820 /* Remember which glyph we're now on. */
3821 remember_mouse_glyph (frame, event->x, event->y, &last_mouse_glyph);
3822 last_mouse_glyph_frame = frame;
3823 return 1;
3826 return 0;
3830 /************************************************************************
3831 Mouse Face
3832 ************************************************************************/
3834 static void
3835 redo_mouse_highlight (void)
3837 if (!NILP (last_mouse_motion_frame)
3838 && FRAME_LIVE_P (XFRAME (last_mouse_motion_frame)))
3839 note_mouse_highlight (XFRAME (last_mouse_motion_frame),
3840 last_mouse_motion_event.x,
3841 last_mouse_motion_event.y);
3846 /* Return the current position of the mouse.
3847 *FP should be a frame which indicates which display to ask about.
3849 If the mouse movement started in a scroll bar, set *FP, *BAR_WINDOW,
3850 and *PART to the frame, window, and scroll bar part that the mouse
3851 is over. Set *X and *Y to the portion and whole of the mouse's
3852 position on the scroll bar.
3854 If the mouse movement started elsewhere, set *FP to the frame the
3855 mouse is on, *BAR_WINDOW to nil, and *X and *Y to the character cell
3856 the mouse is over.
3858 Set *TIMESTAMP to the server time-stamp for the time at which the mouse
3859 was at this position.
3861 Don't store anything if we don't have a valid set of values to report.
3863 This clears the mouse_moved flag, so we can wait for the next mouse
3864 movement. */
3866 static void
3867 XTmouse_position (FRAME_PTR *fp, int insist, Lisp_Object *bar_window,
3868 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
3869 Time *timestamp)
3871 FRAME_PTR f1;
3873 BLOCK_INPUT;
3875 if (! NILP (last_mouse_scroll_bar) && insist == 0)
3876 x_scroll_bar_report_motion (fp, bar_window, part, x, y, timestamp);
3877 else
3879 Window root;
3880 int root_x, root_y;
3882 Window dummy_window;
3883 int dummy;
3885 Lisp_Object frame, tail;
3887 /* Clear the mouse-moved flag for every frame on this display. */
3888 FOR_EACH_FRAME (tail, frame)
3889 if (FRAME_X_P (XFRAME (frame))
3890 && FRAME_X_DISPLAY (XFRAME (frame)) == FRAME_X_DISPLAY (*fp))
3891 XFRAME (frame)->mouse_moved = 0;
3893 last_mouse_scroll_bar = Qnil;
3895 /* Figure out which root window we're on. */
3896 XQueryPointer (FRAME_X_DISPLAY (*fp),
3897 DefaultRootWindow (FRAME_X_DISPLAY (*fp)),
3899 /* The root window which contains the pointer. */
3900 &root,
3902 /* Trash which we can't trust if the pointer is on
3903 a different screen. */
3904 &dummy_window,
3906 /* The position on that root window. */
3907 &root_x, &root_y,
3909 /* More trash we can't trust. */
3910 &dummy, &dummy,
3912 /* Modifier keys and pointer buttons, about which
3913 we don't care. */
3914 (unsigned int *) &dummy);
3916 /* Now we have a position on the root; find the innermost window
3917 containing the pointer. */
3919 Window win, child;
3920 int win_x, win_y;
3921 int parent_x = 0, parent_y = 0;
3923 win = root;
3925 /* XTranslateCoordinates can get errors if the window
3926 structure is changing at the same time this function
3927 is running. So at least we must not crash from them. */
3929 x_catch_errors (FRAME_X_DISPLAY (*fp));
3931 if (FRAME_X_DISPLAY_INFO (*fp)->grabbed && last_mouse_frame
3932 && FRAME_LIVE_P (last_mouse_frame))
3934 /* If mouse was grabbed on a frame, give coords for that frame
3935 even if the mouse is now outside it. */
3936 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
3938 /* From-window, to-window. */
3939 root, FRAME_X_WINDOW (last_mouse_frame),
3941 /* From-position, to-position. */
3942 root_x, root_y, &win_x, &win_y,
3944 /* Child of win. */
3945 &child);
3946 f1 = last_mouse_frame;
3948 else
3950 while (1)
3952 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
3954 /* From-window, to-window. */
3955 root, win,
3957 /* From-position, to-position. */
3958 root_x, root_y, &win_x, &win_y,
3960 /* Child of win. */
3961 &child);
3963 if (child == None || child == win)
3964 break;
3965 #ifdef USE_GTK
3966 /* We don't wan't to know the innermost window. We
3967 want the edit window. For non-Gtk+ the innermost
3968 window is the edit window. For Gtk+ it might not
3969 be. It might be the tool bar for example. */
3970 if (x_window_to_frame (FRAME_X_DISPLAY_INFO (*fp), win))
3971 break;
3972 #endif
3973 win = child;
3974 parent_x = win_x;
3975 parent_y = win_y;
3978 /* Now we know that:
3979 win is the innermost window containing the pointer
3980 (XTC says it has no child containing the pointer),
3981 win_x and win_y are the pointer's position in it
3982 (XTC did this the last time through), and
3983 parent_x and parent_y are the pointer's position in win's parent.
3984 (They are what win_x and win_y were when win was child.
3985 If win is the root window, it has no parent, and
3986 parent_{x,y} are invalid, but that's okay, because we'll
3987 never use them in that case.) */
3989 #ifdef USE_GTK
3990 /* We don't wan't to know the innermost window. We
3991 want the edit window. */
3992 f1 = x_window_to_frame (FRAME_X_DISPLAY_INFO (*fp), win);
3993 #else
3994 /* Is win one of our frames? */
3995 f1 = x_any_window_to_frame (FRAME_X_DISPLAY_INFO (*fp), win);
3996 #endif
3998 #ifdef USE_X_TOOLKIT
3999 /* If we end up with the menu bar window, say it's not
4000 on the frame. */
4001 if (f1 != NULL
4002 && f1->output_data.x->menubar_widget
4003 && win == XtWindow (f1->output_data.x->menubar_widget))
4004 f1 = NULL;
4005 #endif /* USE_X_TOOLKIT */
4008 if (x_had_errors_p (FRAME_X_DISPLAY (*fp)))
4009 f1 = 0;
4011 x_uncatch_errors ();
4013 /* If not, is it one of our scroll bars? */
4014 if (! f1)
4016 struct scroll_bar *bar;
4018 bar = x_window_to_scroll_bar (FRAME_X_DISPLAY (*fp), win);
4020 if (bar)
4022 f1 = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
4023 win_x = parent_x;
4024 win_y = parent_y;
4028 if (f1 == 0 && insist > 0)
4029 f1 = SELECTED_FRAME ();
4031 if (f1)
4033 /* Ok, we found a frame. Store all the values.
4034 last_mouse_glyph is a rectangle used to reduce the
4035 generation of mouse events. To not miss any motion
4036 events, we must divide the frame into rectangles of the
4037 size of the smallest character that could be displayed
4038 on it, i.e. into the same rectangles that matrices on
4039 the frame are divided into. */
4041 remember_mouse_glyph (f1, win_x, win_y, &last_mouse_glyph);
4042 last_mouse_glyph_frame = f1;
4044 *bar_window = Qnil;
4045 *part = 0;
4046 *fp = f1;
4047 XSETINT (*x, win_x);
4048 XSETINT (*y, win_y);
4049 *timestamp = last_mouse_movement_time;
4054 UNBLOCK_INPUT;
4059 /***********************************************************************
4060 Scroll bars
4061 ***********************************************************************/
4063 /* Scroll bar support. */
4065 /* Given an X window ID and a DISPLAY, find the struct scroll_bar which
4066 manages it.
4067 This can be called in GC, so we have to make sure to strip off mark
4068 bits. */
4070 static struct scroll_bar *
4071 x_window_to_scroll_bar (Display *display, Window window_id)
4073 Lisp_Object tail;
4075 #if defined (USE_GTK) && defined (USE_TOOLKIT_SCROLL_BARS)
4076 window_id = (Window) xg_get_scroll_id_for_window (display, window_id);
4077 #endif /* USE_GTK && USE_TOOLKIT_SCROLL_BARS */
4079 for (tail = Vframe_list; CONSP (tail); tail = XCDR (tail))
4081 Lisp_Object frame, bar, condemned;
4083 frame = XCAR (tail);
4084 /* All elements of Vframe_list should be frames. */
4085 if (! FRAMEP (frame))
4086 abort ();
4088 if (! FRAME_X_P (XFRAME (frame)))
4089 continue;
4091 /* Scan this frame's scroll bar list for a scroll bar with the
4092 right window ID. */
4093 condemned = FRAME_CONDEMNED_SCROLL_BARS (XFRAME (frame));
4094 for (bar = FRAME_SCROLL_BARS (XFRAME (frame));
4095 /* This trick allows us to search both the ordinary and
4096 condemned scroll bar lists with one loop. */
4097 ! NILP (bar) || (bar = condemned,
4098 condemned = Qnil,
4099 ! NILP (bar));
4100 bar = XSCROLL_BAR (bar)->next)
4101 if (XSCROLL_BAR (bar)->x_window == window_id &&
4102 FRAME_X_DISPLAY (XFRAME (frame)) == display)
4103 return XSCROLL_BAR (bar);
4106 return NULL;
4110 #if defined USE_LUCID
4112 /* Return the Lucid menu bar WINDOW is part of. Return null
4113 if WINDOW is not part of a menu bar. */
4115 static Widget
4116 x_window_to_menu_bar (Window window)
4118 Lisp_Object tail;
4120 for (tail = Vframe_list; CONSP (tail); tail = XCDR (tail))
4122 if (FRAME_X_P (XFRAME (XCAR (tail))))
4124 Lisp_Object frame = XCAR (tail);
4125 Widget menu_bar = XFRAME (frame)->output_data.x->menubar_widget;
4127 if (menu_bar && xlwmenu_window_p (menu_bar, window))
4128 return menu_bar;
4132 return NULL;
4135 #endif /* USE_LUCID */
4138 /************************************************************************
4139 Toolkit scroll bars
4140 ************************************************************************/
4142 #ifdef USE_TOOLKIT_SCROLL_BARS
4144 static void x_scroll_bar_to_input_event (XEvent *, struct input_event *);
4145 static void x_send_scroll_bar_event (Lisp_Object, int, int, int);
4146 static void x_create_toolkit_scroll_bar (struct frame *,
4147 struct scroll_bar *);
4148 static void x_set_toolkit_scroll_bar_thumb (struct scroll_bar *,
4149 int, int, int);
4152 /* Lisp window being scrolled. Set when starting to interact with
4153 a toolkit scroll bar, reset to nil when ending the interaction. */
4155 static Lisp_Object window_being_scrolled;
4157 /* Last scroll bar part sent in xm_scroll_callback. */
4159 static int last_scroll_bar_part;
4161 /* Whether this is an Xaw with arrow-scrollbars. This should imply
4162 that movements of 1/20 of the screen size are mapped to up/down. */
4164 #ifndef USE_GTK
4165 /* Id of action hook installed for scroll bars. */
4167 static XtActionHookId action_hook_id;
4169 static Boolean xaw3d_arrow_scroll;
4171 /* Whether the drag scrolling maintains the mouse at the top of the
4172 thumb. If not, resizing the thumb needs to be done more carefully
4173 to avoid jerkyness. */
4175 static Boolean xaw3d_pick_top;
4177 /* Action hook installed via XtAppAddActionHook when toolkit scroll
4178 bars are used.. The hook is responsible for detecting when
4179 the user ends an interaction with the scroll bar, and generates
4180 a `end-scroll' SCROLL_BAR_CLICK_EVENT' event if so. */
4182 static void
4183 xt_action_hook (Widget widget, XtPointer client_data, String action_name,
4184 XEvent *event, String *params, Cardinal *num_params)
4186 int scroll_bar_p;
4187 const char *end_action;
4189 #ifdef USE_MOTIF
4190 scroll_bar_p = XmIsScrollBar (widget);
4191 end_action = "Release";
4192 #else /* !USE_MOTIF i.e. use Xaw */
4193 scroll_bar_p = XtIsSubclass (widget, scrollbarWidgetClass);
4194 end_action = "EndScroll";
4195 #endif /* USE_MOTIF */
4197 if (scroll_bar_p
4198 && strcmp (action_name, end_action) == 0
4199 && WINDOWP (window_being_scrolled))
4201 struct window *w;
4203 x_send_scroll_bar_event (window_being_scrolled,
4204 scroll_bar_end_scroll, 0, 0);
4205 w = XWINDOW (window_being_scrolled);
4207 if (!NILP (XSCROLL_BAR (w->vertical_scroll_bar)->dragging))
4209 XSCROLL_BAR (w->vertical_scroll_bar)->dragging = Qnil;
4210 /* The thumb size is incorrect while dragging: fix it. */
4211 set_vertical_scroll_bar (w);
4213 window_being_scrolled = Qnil;
4214 last_scroll_bar_part = -1;
4216 /* Xt timeouts no longer needed. */
4217 toolkit_scroll_bar_interaction = 0;
4220 #endif /* not USE_GTK */
4222 /* A vector of windows used for communication between
4223 x_send_scroll_bar_event and x_scroll_bar_to_input_event. */
4225 static struct window **scroll_bar_windows;
4226 static ptrdiff_t scroll_bar_windows_size;
4229 /* Send a client message with message type Xatom_Scrollbar for a
4230 scroll action to the frame of WINDOW. PART is a value identifying
4231 the part of the scroll bar that was clicked on. PORTION is the
4232 amount to scroll of a whole of WHOLE. */
4234 static void
4235 x_send_scroll_bar_event (Lisp_Object window, int part, int portion, int whole)
4237 XEvent event;
4238 XClientMessageEvent *ev = (XClientMessageEvent *) &event;
4239 struct window *w = XWINDOW (window);
4240 struct frame *f = XFRAME (w->frame);
4241 ptrdiff_t i;
4243 BLOCK_INPUT;
4245 /* Construct a ClientMessage event to send to the frame. */
4246 ev->type = ClientMessage;
4247 ev->message_type = FRAME_X_DISPLAY_INFO (f)->Xatom_Scrollbar;
4248 ev->display = FRAME_X_DISPLAY (f);
4249 ev->window = FRAME_X_WINDOW (f);
4250 ev->format = 32;
4252 /* We can only transfer 32 bits in the XClientMessageEvent, which is
4253 not enough to store a pointer or Lisp_Object on a 64 bit system.
4254 So, store the window in scroll_bar_windows and pass the index
4255 into that array in the event. */
4256 for (i = 0; i < scroll_bar_windows_size; ++i)
4257 if (scroll_bar_windows[i] == NULL)
4258 break;
4260 if (i == scroll_bar_windows_size)
4262 ptrdiff_t old_nbytes =
4263 scroll_bar_windows_size * sizeof *scroll_bar_windows;
4264 ptrdiff_t nbytes;
4265 enum { XClientMessageEvent_MAX = 0x7fffffff };
4266 scroll_bar_windows =
4267 xpalloc (scroll_bar_windows, &scroll_bar_windows_size, 1,
4268 XClientMessageEvent_MAX, sizeof *scroll_bar_windows);
4269 nbytes = scroll_bar_windows_size * sizeof *scroll_bar_windows;
4270 memset (&scroll_bar_windows[i], 0, nbytes - old_nbytes);
4273 scroll_bar_windows[i] = w;
4274 ev->data.l[0] = (long) i;
4275 ev->data.l[1] = (long) part;
4276 ev->data.l[2] = (long) 0;
4277 ev->data.l[3] = (long) portion;
4278 ev->data.l[4] = (long) whole;
4280 /* Make Xt timeouts work while the scroll bar is active. */
4281 #ifdef USE_X_TOOLKIT
4282 toolkit_scroll_bar_interaction = 1;
4283 x_activate_timeout_atimer ();
4284 #endif
4286 /* Setting the event mask to zero means that the message will
4287 be sent to the client that created the window, and if that
4288 window no longer exists, no event will be sent. */
4289 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), False, 0, &event);
4290 UNBLOCK_INPUT;
4294 /* Transform a scroll bar ClientMessage EVENT to an Emacs input event
4295 in *IEVENT. */
4297 static void
4298 x_scroll_bar_to_input_event (XEvent *event, struct input_event *ievent)
4300 XClientMessageEvent *ev = (XClientMessageEvent *) event;
4301 Lisp_Object window;
4302 struct window *w;
4304 w = scroll_bar_windows[ev->data.l[0]];
4305 scroll_bar_windows[ev->data.l[0]] = NULL;
4307 XSETWINDOW (window, w);
4309 ievent->kind = SCROLL_BAR_CLICK_EVENT;
4310 ievent->frame_or_window = window;
4311 ievent->arg = Qnil;
4312 #ifdef USE_GTK
4313 ievent->timestamp = CurrentTime;
4314 #else
4315 ievent->timestamp =
4316 XtLastTimestampProcessed (FRAME_X_DISPLAY (XFRAME (w->frame)));
4317 #endif
4318 ievent->part = ev->data.l[1];
4319 ievent->code = ev->data.l[2];
4320 ievent->x = make_number ((int) ev->data.l[3]);
4321 ievent->y = make_number ((int) ev->data.l[4]);
4322 ievent->modifiers = 0;
4326 #ifdef USE_MOTIF
4328 /* Minimum and maximum values used for Motif scroll bars. */
4330 #define XM_SB_MAX 10000000
4333 /* Scroll bar callback for Motif scroll bars. WIDGET is the scroll
4334 bar widget. CLIENT_DATA is a pointer to the scroll_bar structure.
4335 CALL_DATA is a pointer to a XmScrollBarCallbackStruct. */
4337 static void
4338 xm_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
4340 struct scroll_bar *bar = (struct scroll_bar *) client_data;
4341 XmScrollBarCallbackStruct *cs = (XmScrollBarCallbackStruct *) call_data;
4342 int part = -1, whole = 0, portion = 0;
4344 switch (cs->reason)
4346 case XmCR_DECREMENT:
4347 bar->dragging = Qnil;
4348 part = scroll_bar_up_arrow;
4349 break;
4351 case XmCR_INCREMENT:
4352 bar->dragging = Qnil;
4353 part = scroll_bar_down_arrow;
4354 break;
4356 case XmCR_PAGE_DECREMENT:
4357 bar->dragging = Qnil;
4358 part = scroll_bar_above_handle;
4359 break;
4361 case XmCR_PAGE_INCREMENT:
4362 bar->dragging = Qnil;
4363 part = scroll_bar_below_handle;
4364 break;
4366 case XmCR_TO_TOP:
4367 bar->dragging = Qnil;
4368 part = scroll_bar_to_top;
4369 break;
4371 case XmCR_TO_BOTTOM:
4372 bar->dragging = Qnil;
4373 part = scroll_bar_to_bottom;
4374 break;
4376 case XmCR_DRAG:
4378 int slider_size;
4380 /* Get the slider size. */
4381 BLOCK_INPUT;
4382 XtVaGetValues (widget, XmNsliderSize, &slider_size, NULL);
4383 UNBLOCK_INPUT;
4385 whole = XM_SB_MAX - slider_size;
4386 portion = min (cs->value, whole);
4387 part = scroll_bar_handle;
4388 bar->dragging = make_number (cs->value);
4390 break;
4392 case XmCR_VALUE_CHANGED:
4393 break;
4396 if (part >= 0)
4398 window_being_scrolled = bar->window;
4399 last_scroll_bar_part = part;
4400 x_send_scroll_bar_event (bar->window, part, portion, whole);
4404 #elif defined USE_GTK
4406 /* Scroll bar callback for GTK scroll bars. WIDGET is the scroll
4407 bar widget. DATA is a pointer to the scroll_bar structure. */
4409 static gboolean
4410 xg_scroll_callback (GtkRange *range,
4411 GtkScrollType scroll,
4412 gdouble value,
4413 gpointer user_data)
4415 struct scroll_bar *bar = (struct scroll_bar *) user_data;
4416 gdouble position;
4417 int part = -1, whole = 0, portion = 0;
4418 GtkAdjustment *adj = GTK_ADJUSTMENT (gtk_range_get_adjustment (range));
4419 FRAME_PTR f = (FRAME_PTR) g_object_get_data (G_OBJECT (range), XG_FRAME_DATA);
4421 if (xg_ignore_gtk_scrollbar) return FALSE;
4422 position = gtk_adjustment_get_value (adj);
4425 switch (scroll)
4427 case GTK_SCROLL_JUMP:
4428 /* Buttons 1 2 or 3 must be grabbed. */
4429 if (FRAME_X_DISPLAY_INFO (f)->grabbed != 0
4430 && FRAME_X_DISPLAY_INFO (f)->grabbed < (1 << 4))
4432 part = scroll_bar_handle;
4433 whole = gtk_adjustment_get_upper (adj) -
4434 gtk_adjustment_get_page_size (adj);
4435 portion = min ((int)position, whole);
4436 bar->dragging = make_number ((int)portion);
4438 break;
4439 case GTK_SCROLL_STEP_BACKWARD:
4440 part = scroll_bar_up_arrow;
4441 bar->dragging = Qnil;
4442 break;
4443 case GTK_SCROLL_STEP_FORWARD:
4444 part = scroll_bar_down_arrow;
4445 bar->dragging = Qnil;
4446 break;
4447 case GTK_SCROLL_PAGE_BACKWARD:
4448 part = scroll_bar_above_handle;
4449 bar->dragging = Qnil;
4450 break;
4451 case GTK_SCROLL_PAGE_FORWARD:
4452 part = scroll_bar_below_handle;
4453 bar->dragging = Qnil;
4454 break;
4457 if (part >= 0)
4459 window_being_scrolled = bar->window;
4460 last_scroll_bar_part = part;
4461 x_send_scroll_bar_event (bar->window, part, portion, whole);
4464 return FALSE;
4467 /* Callback for button release. Sets dragging to Qnil when dragging is done. */
4469 static gboolean
4470 xg_end_scroll_callback (GtkWidget *widget,
4471 GdkEventButton *event,
4472 gpointer user_data)
4474 struct scroll_bar *bar = (struct scroll_bar *) user_data;
4475 bar->dragging = Qnil;
4476 if (WINDOWP (window_being_scrolled))
4478 x_send_scroll_bar_event (window_being_scrolled,
4479 scroll_bar_end_scroll, 0, 0);
4480 window_being_scrolled = Qnil;
4483 return FALSE;
4487 #else /* not USE_GTK and not USE_MOTIF */
4489 /* Xaw scroll bar callback. Invoked when the thumb is dragged.
4490 WIDGET is the scroll bar widget. CLIENT_DATA is a pointer to the
4491 scroll bar struct. CALL_DATA is a pointer to a float saying where
4492 the thumb is. */
4494 static void
4495 xaw_jump_callback (Widget widget, XtPointer client_data, XtPointer call_data)
4497 struct scroll_bar *bar = (struct scroll_bar *) client_data;
4498 float top = *(float *) call_data;
4499 float shown;
4500 int whole, portion, height;
4501 int part;
4503 /* Get the size of the thumb, a value between 0 and 1. */
4504 BLOCK_INPUT;
4505 XtVaGetValues (widget, XtNshown, &shown, XtNheight, &height, NULL);
4506 UNBLOCK_INPUT;
4508 whole = 10000000;
4509 portion = shown < 1 ? top * whole : 0;
4511 if (shown < 1 && (eabs (top + shown - 1) < 1.0/height))
4512 /* Some derivatives of Xaw refuse to shrink the thumb when you reach
4513 the bottom, so we force the scrolling whenever we see that we're
4514 too close to the bottom (in x_set_toolkit_scroll_bar_thumb
4515 we try to ensure that we always stay two pixels away from the
4516 bottom). */
4517 part = scroll_bar_down_arrow;
4518 else
4519 part = scroll_bar_handle;
4521 window_being_scrolled = bar->window;
4522 bar->dragging = make_number (portion);
4523 last_scroll_bar_part = part;
4524 x_send_scroll_bar_event (bar->window, part, portion, whole);
4528 /* Xaw scroll bar callback. Invoked for incremental scrolling.,
4529 i.e. line or page up or down. WIDGET is the Xaw scroll bar
4530 widget. CLIENT_DATA is a pointer to the scroll_bar structure for
4531 the scroll bar. CALL_DATA is an integer specifying the action that
4532 has taken place. Its magnitude is in the range 0..height of the
4533 scroll bar. Negative values mean scroll towards buffer start.
4534 Values < height of scroll bar mean line-wise movement. */
4536 static void
4537 xaw_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
4539 struct scroll_bar *bar = (struct scroll_bar *) client_data;
4540 /* The position really is stored cast to a pointer. */
4541 int position = (long) call_data;
4542 Dimension height;
4543 int part;
4545 /* Get the height of the scroll bar. */
4546 BLOCK_INPUT;
4547 XtVaGetValues (widget, XtNheight, &height, NULL);
4548 UNBLOCK_INPUT;
4550 if (eabs (position) >= height)
4551 part = (position < 0) ? scroll_bar_above_handle : scroll_bar_below_handle;
4553 /* If Xaw3d was compiled with ARROW_SCROLLBAR,
4554 it maps line-movement to call_data = max(5, height/20). */
4555 else if (xaw3d_arrow_scroll && eabs (position) <= max (5, height / 20))
4556 part = (position < 0) ? scroll_bar_up_arrow : scroll_bar_down_arrow;
4557 else
4558 part = scroll_bar_move_ratio;
4560 window_being_scrolled = bar->window;
4561 bar->dragging = Qnil;
4562 last_scroll_bar_part = part;
4563 x_send_scroll_bar_event (bar->window, part, position, height);
4566 #endif /* not USE_GTK and not USE_MOTIF */
4568 #define SCROLL_BAR_NAME "verticalScrollBar"
4570 /* Create the widget for scroll bar BAR on frame F. Record the widget
4571 and X window of the scroll bar in BAR. */
4573 #ifdef USE_GTK
4574 static void
4575 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
4577 const char *scroll_bar_name = SCROLL_BAR_NAME;
4579 BLOCK_INPUT;
4580 xg_create_scroll_bar (f, bar, G_CALLBACK (xg_scroll_callback),
4581 G_CALLBACK (xg_end_scroll_callback),
4582 scroll_bar_name);
4583 UNBLOCK_INPUT;
4586 #else /* not USE_GTK */
4588 static void
4589 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
4591 Window xwindow;
4592 Widget widget;
4593 Arg av[20];
4594 int ac = 0;
4595 char const *scroll_bar_name = SCROLL_BAR_NAME;
4596 unsigned long pixel;
4598 BLOCK_INPUT;
4600 #ifdef USE_MOTIF
4601 /* Set resources. Create the widget. */
4602 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
4603 XtSetArg (av[ac], XmNminimum, 0); ++ac;
4604 XtSetArg (av[ac], XmNmaximum, XM_SB_MAX); ++ac;
4605 XtSetArg (av[ac], XmNorientation, XmVERTICAL); ++ac;
4606 XtSetArg (av[ac], XmNprocessingDirection, XmMAX_ON_BOTTOM), ++ac;
4607 XtSetArg (av[ac], XmNincrement, 1); ++ac;
4608 XtSetArg (av[ac], XmNpageIncrement, 1); ++ac;
4610 pixel = f->output_data.x->scroll_bar_foreground_pixel;
4611 if (pixel != -1)
4613 XtSetArg (av[ac], XmNforeground, pixel);
4614 ++ac;
4617 pixel = f->output_data.x->scroll_bar_background_pixel;
4618 if (pixel != -1)
4620 XtSetArg (av[ac], XmNbackground, pixel);
4621 ++ac;
4624 widget = XmCreateScrollBar (f->output_data.x->edit_widget,
4625 scroll_bar_name, av, ac);
4627 /* Add one callback for everything that can happen. */
4628 XtAddCallback (widget, XmNdecrementCallback, xm_scroll_callback,
4629 (XtPointer) bar);
4630 XtAddCallback (widget, XmNdragCallback, xm_scroll_callback,
4631 (XtPointer) bar);
4632 XtAddCallback (widget, XmNincrementCallback, xm_scroll_callback,
4633 (XtPointer) bar);
4634 XtAddCallback (widget, XmNpageDecrementCallback, xm_scroll_callback,
4635 (XtPointer) bar);
4636 XtAddCallback (widget, XmNpageIncrementCallback, xm_scroll_callback,
4637 (XtPointer) bar);
4638 XtAddCallback (widget, XmNtoBottomCallback, xm_scroll_callback,
4639 (XtPointer) bar);
4640 XtAddCallback (widget, XmNtoTopCallback, xm_scroll_callback,
4641 (XtPointer) bar);
4643 /* Realize the widget. Only after that is the X window created. */
4644 XtRealizeWidget (widget);
4646 /* Set the cursor to an arrow. I didn't find a resource to do that.
4647 And I'm wondering why it hasn't an arrow cursor by default. */
4648 XDefineCursor (XtDisplay (widget), XtWindow (widget),
4649 f->output_data.x->nontext_cursor);
4651 #else /* !USE_MOTIF i.e. use Xaw */
4653 /* Set resources. Create the widget. The background of the
4654 Xaw3d scroll bar widget is a little bit light for my taste.
4655 We don't alter it here to let users change it according
4656 to their taste with `emacs*verticalScrollBar.background: xxx'. */
4657 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
4658 XtSetArg (av[ac], XtNorientation, XtorientVertical); ++ac;
4659 /* For smoother scrolling with Xaw3d -sm */
4660 /* XtSetArg (av[ac], XtNpickTop, True); ++ac; */
4662 pixel = f->output_data.x->scroll_bar_foreground_pixel;
4663 if (pixel != -1)
4665 XtSetArg (av[ac], XtNforeground, pixel);
4666 ++ac;
4669 pixel = f->output_data.x->scroll_bar_background_pixel;
4670 if (pixel != -1)
4672 XtSetArg (av[ac], XtNbackground, pixel);
4673 ++ac;
4676 /* Top/bottom shadow colors. */
4678 /* Allocate them, if necessary. */
4679 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1)
4681 pixel = f->output_data.x->scroll_bar_background_pixel;
4682 if (pixel != -1)
4684 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
4685 FRAME_X_COLORMAP (f),
4686 &pixel, 1.2, 0x8000))
4687 pixel = -1;
4688 f->output_data.x->scroll_bar_top_shadow_pixel = pixel;
4691 if (f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
4693 pixel = f->output_data.x->scroll_bar_background_pixel;
4694 if (pixel != -1)
4696 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
4697 FRAME_X_COLORMAP (f),
4698 &pixel, 0.6, 0x4000))
4699 pixel = -1;
4700 f->output_data.x->scroll_bar_bottom_shadow_pixel = pixel;
4704 #ifdef XtNbeNiceToColormap
4705 /* Tell the toolkit about them. */
4706 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1
4707 || f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
4708 /* We tried to allocate a color for the top/bottom shadow, and
4709 failed, so tell Xaw3d to use dithering instead. */
4710 /* But only if we have a small colormap. Xaw3d can allocate nice
4711 colors itself. */
4713 XtSetArg (av[ac], XtNbeNiceToColormap,
4714 DefaultDepthOfScreen (FRAME_X_SCREEN (f)) < 16);
4715 ++ac;
4717 else
4718 /* Tell what colors Xaw3d should use for the top/bottom shadow, to
4719 be more consistent with other emacs 3d colors, and since Xaw3d is
4720 not good at dealing with allocation failure. */
4722 /* This tells Xaw3d to use real colors instead of dithering for
4723 the shadows. */
4724 XtSetArg (av[ac], XtNbeNiceToColormap, False);
4725 ++ac;
4727 /* Specify the colors. */
4728 pixel = f->output_data.x->scroll_bar_top_shadow_pixel;
4729 if (pixel != -1)
4731 XtSetArg (av[ac], XtNtopShadowPixel, pixel);
4732 ++ac;
4734 pixel = f->output_data.x->scroll_bar_bottom_shadow_pixel;
4735 if (pixel != -1)
4737 XtSetArg (av[ac], XtNbottomShadowPixel, pixel);
4738 ++ac;
4741 #endif
4743 widget = XtCreateWidget (scroll_bar_name, scrollbarWidgetClass,
4744 f->output_data.x->edit_widget, av, ac);
4747 char const *initial = "";
4748 char const *val = initial;
4749 XtVaGetValues (widget, XtNscrollVCursor, (XtPointer) &val,
4750 #ifdef XtNarrowScrollbars
4751 XtNarrowScrollbars, (XtPointer) &xaw3d_arrow_scroll,
4752 #endif
4753 XtNpickTop, (XtPointer) &xaw3d_pick_top, NULL);
4754 if (xaw3d_arrow_scroll || val == initial)
4755 { /* ARROW_SCROLL */
4756 xaw3d_arrow_scroll = True;
4757 /* Isn't that just a personal preference ? --Stef */
4758 XtVaSetValues (widget, XtNcursorName, "top_left_arrow", NULL);
4762 /* Define callbacks. */
4763 XtAddCallback (widget, XtNjumpProc, xaw_jump_callback, (XtPointer) bar);
4764 XtAddCallback (widget, XtNscrollProc, xaw_scroll_callback,
4765 (XtPointer) bar);
4767 /* Realize the widget. Only after that is the X window created. */
4768 XtRealizeWidget (widget);
4770 #endif /* !USE_MOTIF */
4772 /* Install an action hook that lets us detect when the user
4773 finishes interacting with a scroll bar. */
4774 if (action_hook_id == 0)
4775 action_hook_id = XtAppAddActionHook (Xt_app_con, xt_action_hook, 0);
4777 /* Remember X window and widget in the scroll bar vector. */
4778 SET_SCROLL_BAR_X_WIDGET (bar, widget);
4779 xwindow = XtWindow (widget);
4780 bar->x_window = xwindow;
4782 UNBLOCK_INPUT;
4784 #endif /* not USE_GTK */
4787 /* Set the thumb size and position of scroll bar BAR. We are currently
4788 displaying PORTION out of a whole WHOLE, and our position POSITION. */
4790 #ifdef USE_GTK
4791 static void
4792 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position, int whole)
4794 xg_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
4797 #else /* not USE_GTK */
4798 static void
4799 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position,
4800 int whole)
4802 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
4803 Widget widget = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
4804 float top, shown;
4806 BLOCK_INPUT;
4808 #ifdef USE_MOTIF
4810 /* We use an estimate of 30 chars per line rather than the real
4811 `portion' value. This has the disadvantage that the thumb size
4812 is not very representative, but it makes our life a lot easier.
4813 Otherwise, we have to constantly adjust the thumb size, which
4814 we can't always do quickly enough: while dragging, the size of
4815 the thumb might prevent the user from dragging the thumb all the
4816 way to the end. but Motif and some versions of Xaw3d don't allow
4817 updating the thumb size while dragging. Also, even if we can update
4818 its size, the update will often happen too late.
4819 If you don't believe it, check out revision 1.650 of xterm.c to see
4820 what hoops we were going through and the still poor behavior we got. */
4821 portion = WINDOW_TOTAL_LINES (XWINDOW (bar->window)) * 30;
4822 /* When the thumb is at the bottom, position == whole.
4823 So we need to increase `whole' to make space for the thumb. */
4824 whole += portion;
4826 if (whole <= 0)
4827 top = 0, shown = 1;
4828 else
4830 top = (float) position / whole;
4831 shown = (float) portion / whole;
4834 if (NILP (bar->dragging))
4836 int size, value;
4838 /* Slider size. Must be in the range [1 .. MAX - MIN] where MAX
4839 is the scroll bar's maximum and MIN is the scroll bar's minimum
4840 value. */
4841 size = shown * XM_SB_MAX;
4842 size = min (size, XM_SB_MAX);
4843 size = max (size, 1);
4845 /* Position. Must be in the range [MIN .. MAX - SLIDER_SIZE]. */
4846 value = top * XM_SB_MAX;
4847 value = min (value, XM_SB_MAX - size);
4849 XmScrollBarSetValues (widget, value, size, 0, 0, False);
4851 #else /* !USE_MOTIF i.e. use Xaw */
4853 if (whole == 0)
4854 top = 0, shown = 1;
4855 else
4857 top = (float) position / whole;
4858 shown = (float) portion / whole;
4862 float old_top, old_shown;
4863 Dimension height;
4864 XtVaGetValues (widget,
4865 XtNtopOfThumb, &old_top,
4866 XtNshown, &old_shown,
4867 XtNheight, &height,
4868 NULL);
4870 /* Massage the top+shown values. */
4871 if (NILP (bar->dragging) || last_scroll_bar_part == scroll_bar_down_arrow)
4872 top = max (0, min (1, top));
4873 else
4874 top = old_top;
4875 /* Keep two pixels available for moving the thumb down. */
4876 shown = max (0, min (1 - top - (2.0 / height), shown));
4878 /* If the call to XawScrollbarSetThumb below doesn't seem to work,
4879 check that your system's configuration file contains a define
4880 for `NARROWPROTO'. See s/freebsd.h for an example. */
4881 if (top != old_top || shown != old_shown)
4883 if (NILP (bar->dragging))
4884 XawScrollbarSetThumb (widget, top, shown);
4885 else
4887 /* Try to make the scrolling a tad smoother. */
4888 if (!xaw3d_pick_top)
4889 shown = min (shown, old_shown);
4891 XawScrollbarSetThumb (widget, top, shown);
4895 #endif /* !USE_MOTIF */
4897 UNBLOCK_INPUT;
4899 #endif /* not USE_GTK */
4901 #endif /* USE_TOOLKIT_SCROLL_BARS */
4905 /************************************************************************
4906 Scroll bars, general
4907 ************************************************************************/
4909 /* Create a scroll bar and return the scroll bar vector for it. W is
4910 the Emacs window on which to create the scroll bar. TOP, LEFT,
4911 WIDTH and HEIGHT are the pixel coordinates and dimensions of the
4912 scroll bar. */
4914 static struct scroll_bar *
4915 x_scroll_bar_create (struct window *w, int top, int left, int width, int height)
4917 struct frame *f = XFRAME (w->frame);
4918 struct scroll_bar *bar
4919 = ALLOCATE_PSEUDOVECTOR (struct scroll_bar, x_window, PVEC_OTHER);
4921 BLOCK_INPUT;
4923 #ifdef USE_TOOLKIT_SCROLL_BARS
4924 x_create_toolkit_scroll_bar (f, bar);
4925 #else /* not USE_TOOLKIT_SCROLL_BARS */
4927 XSetWindowAttributes a;
4928 unsigned long mask;
4929 Window window;
4931 a.background_pixel = f->output_data.x->scroll_bar_background_pixel;
4932 if (a.background_pixel == -1)
4933 a.background_pixel = FRAME_BACKGROUND_PIXEL (f);
4935 a.event_mask = (ButtonPressMask | ButtonReleaseMask
4936 | ButtonMotionMask | PointerMotionHintMask
4937 | ExposureMask);
4938 a.cursor = FRAME_X_DISPLAY_INFO (f)->vertical_scroll_bar_cursor;
4940 mask = (CWBackPixel | CWEventMask | CWCursor);
4942 /* Clear the area of W that will serve as a scroll bar. This is
4943 for the case that a window has been split horizontally. In
4944 this case, no clear_frame is generated to reduce flickering. */
4945 if (width > 0 && height > 0)
4946 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4947 left, top, width,
4948 window_box_height (w), False);
4950 window = XCreateWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4951 /* Position and size of scroll bar. */
4952 left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
4953 top,
4954 width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
4955 height,
4956 /* Border width, depth, class, and visual. */
4958 CopyFromParent,
4959 CopyFromParent,
4960 CopyFromParent,
4961 /* Attributes. */
4962 mask, &a);
4963 bar->x_window = window;
4965 #endif /* not USE_TOOLKIT_SCROLL_BARS */
4967 XSETWINDOW (bar->window, w);
4968 bar->top = top;
4969 bar->left = left;
4970 bar->width = width;
4971 bar->height = height;
4972 bar->start = 0;
4973 bar->end = 0;
4974 bar->dragging = Qnil;
4975 bar->fringe_extended_p = 0;
4977 /* Add bar to its frame's list of scroll bars. */
4978 bar->next = FRAME_SCROLL_BARS (f);
4979 bar->prev = Qnil;
4980 XSETVECTOR (FRAME_SCROLL_BARS (f), bar);
4981 if (!NILP (bar->next))
4982 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
4984 /* Map the window/widget. */
4985 #ifdef USE_TOOLKIT_SCROLL_BARS
4987 #ifdef USE_GTK
4988 xg_update_scrollbar_pos (f,
4989 bar->x_window,
4990 top,
4991 left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
4992 width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
4993 max (height, 1));
4994 #else /* not USE_GTK */
4995 Widget scroll_bar = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
4996 XtConfigureWidget (scroll_bar,
4997 left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
4998 top,
4999 width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
5000 max (height, 1), 0);
5001 XtMapWidget (scroll_bar);
5002 #endif /* not USE_GTK */
5004 #else /* not USE_TOOLKIT_SCROLL_BARS */
5005 XMapRaised (FRAME_X_DISPLAY (f), bar->x_window);
5006 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5008 UNBLOCK_INPUT;
5009 return bar;
5013 #ifndef USE_TOOLKIT_SCROLL_BARS
5015 /* Draw BAR's handle in the proper position.
5017 If the handle is already drawn from START to END, don't bother
5018 redrawing it, unless REBUILD is non-zero; in that case, always
5019 redraw it. (REBUILD is handy for drawing the handle after expose
5020 events.)
5022 Normally, we want to constrain the start and end of the handle to
5023 fit inside its rectangle, but if the user is dragging the scroll
5024 bar handle, we want to let them drag it down all the way, so that
5025 the bar's top is as far down as it goes; otherwise, there's no way
5026 to move to the very end of the buffer. */
5028 static void
5029 x_scroll_bar_set_handle (struct scroll_bar *bar, int start, int end, int rebuild)
5031 int dragging = ! NILP (bar->dragging);
5032 Window w = bar->x_window;
5033 FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5034 GC gc = f->output_data.x->normal_gc;
5036 /* If the display is already accurate, do nothing. */
5037 if (! rebuild
5038 && start == bar->start
5039 && end == bar->end)
5040 return;
5042 BLOCK_INPUT;
5045 int inside_width = VERTICAL_SCROLL_BAR_INSIDE_WIDTH (f, bar->width);
5046 int inside_height = VERTICAL_SCROLL_BAR_INSIDE_HEIGHT (f, bar->height);
5047 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
5049 /* Make sure the values are reasonable, and try to preserve
5050 the distance between start and end. */
5052 int length = end - start;
5054 if (start < 0)
5055 start = 0;
5056 else if (start > top_range)
5057 start = top_range;
5058 end = start + length;
5060 if (end < start)
5061 end = start;
5062 else if (end > top_range && ! dragging)
5063 end = top_range;
5066 /* Store the adjusted setting in the scroll bar. */
5067 bar->start = start;
5068 bar->end = end;
5070 /* Clip the end position, just for display. */
5071 if (end > top_range)
5072 end = top_range;
5074 /* Draw bottom positions VERTICAL_SCROLL_BAR_MIN_HANDLE pixels
5075 below top positions, to make sure the handle is always at least
5076 that many pixels tall. */
5077 end += VERTICAL_SCROLL_BAR_MIN_HANDLE;
5079 /* Draw the empty space above the handle. Note that we can't clear
5080 zero-height areas; that means "clear to end of window." */
5081 if (0 < start)
5082 x_clear_area (FRAME_X_DISPLAY (f), w,
5083 /* x, y, width, height, and exposures. */
5084 VERTICAL_SCROLL_BAR_LEFT_BORDER,
5085 VERTICAL_SCROLL_BAR_TOP_BORDER,
5086 inside_width, start,
5087 False);
5089 /* Change to proper foreground color if one is specified. */
5090 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5091 XSetForeground (FRAME_X_DISPLAY (f), gc,
5092 f->output_data.x->scroll_bar_foreground_pixel);
5094 /* Draw the handle itself. */
5095 XFillRectangle (FRAME_X_DISPLAY (f), w, gc,
5096 /* x, y, width, height */
5097 VERTICAL_SCROLL_BAR_LEFT_BORDER,
5098 VERTICAL_SCROLL_BAR_TOP_BORDER + start,
5099 inside_width, end - start);
5101 /* Restore the foreground color of the GC if we changed it above. */
5102 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5103 XSetForeground (FRAME_X_DISPLAY (f), gc,
5104 FRAME_FOREGROUND_PIXEL (f));
5106 /* Draw the empty space below the handle. Note that we can't
5107 clear zero-height areas; that means "clear to end of window." */
5108 if (end < inside_height)
5109 x_clear_area (FRAME_X_DISPLAY (f), w,
5110 /* x, y, width, height, and exposures. */
5111 VERTICAL_SCROLL_BAR_LEFT_BORDER,
5112 VERTICAL_SCROLL_BAR_TOP_BORDER + end,
5113 inside_width, inside_height - end,
5114 False);
5118 UNBLOCK_INPUT;
5121 #endif /* !USE_TOOLKIT_SCROLL_BARS */
5123 /* Destroy scroll bar BAR, and set its Emacs window's scroll bar to
5124 nil. */
5126 static void
5127 x_scroll_bar_remove (struct scroll_bar *bar)
5129 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5130 BLOCK_INPUT;
5132 #ifdef USE_TOOLKIT_SCROLL_BARS
5133 #ifdef USE_GTK
5134 xg_remove_scroll_bar (f, bar->x_window);
5135 #else /* not USE_GTK */
5136 XtDestroyWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar));
5137 #endif /* not USE_GTK */
5138 #else
5139 XDestroyWindow (FRAME_X_DISPLAY (f), bar->x_window);
5140 #endif
5142 /* Disassociate this scroll bar from its window. */
5143 XWINDOW (bar->window)->vertical_scroll_bar = Qnil;
5145 UNBLOCK_INPUT;
5149 /* Set the handle of the vertical scroll bar for WINDOW to indicate
5150 that we are displaying PORTION characters out of a total of WHOLE
5151 characters, starting at POSITION. If WINDOW has no scroll bar,
5152 create one. */
5154 static void
5155 XTset_vertical_scroll_bar (struct window *w, int portion, int whole, int position)
5157 struct frame *f = XFRAME (w->frame);
5158 struct scroll_bar *bar;
5159 int top, height, left, sb_left, width, sb_width;
5160 int window_y, window_height;
5161 #ifdef USE_TOOLKIT_SCROLL_BARS
5162 int fringe_extended_p;
5163 #endif
5165 /* Get window dimensions. */
5166 window_box (w, -1, 0, &window_y, 0, &window_height);
5167 top = window_y;
5168 width = WINDOW_CONFIG_SCROLL_BAR_COLS (w) * FRAME_COLUMN_WIDTH (f);
5169 height = window_height;
5171 /* Compute the left edge of the scroll bar area. */
5172 left = WINDOW_SCROLL_BAR_AREA_X (w);
5174 /* Compute the width of the scroll bar which might be less than
5175 the width of the area reserved for the scroll bar. */
5176 if (WINDOW_CONFIG_SCROLL_BAR_WIDTH (w) > 0)
5177 sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
5178 else
5179 sb_width = width;
5181 /* Compute the left edge of the scroll bar. */
5182 #ifdef USE_TOOLKIT_SCROLL_BARS
5183 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w))
5184 sb_left = left + (WINDOW_RIGHTMOST_P (w) ? width - sb_width : 0);
5185 else
5186 sb_left = left + (WINDOW_LEFTMOST_P (w) ? 0 : width - sb_width);
5187 #else
5188 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w))
5189 sb_left = left + width - sb_width;
5190 else
5191 sb_left = left;
5192 #endif
5194 #ifdef USE_TOOLKIT_SCROLL_BARS
5195 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
5196 fringe_extended_p = (WINDOW_LEFTMOST_P (w)
5197 && WINDOW_LEFT_FRINGE_WIDTH (w)
5198 && (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (w)
5199 || WINDOW_LEFT_MARGIN_COLS (w) == 0));
5200 else
5201 fringe_extended_p = (WINDOW_RIGHTMOST_P (w)
5202 && WINDOW_RIGHT_FRINGE_WIDTH (w)
5203 && (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (w)
5204 || WINDOW_RIGHT_MARGIN_COLS (w) == 0));
5205 #endif
5207 /* Does the scroll bar exist yet? */
5208 if (NILP (w->vertical_scroll_bar))
5210 if (width > 0 && height > 0)
5212 BLOCK_INPUT;
5213 #ifdef USE_TOOLKIT_SCROLL_BARS
5214 if (fringe_extended_p)
5215 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5216 sb_left, top, sb_width, height, False);
5217 else
5218 #endif
5219 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5220 left, top, width, height, False);
5221 UNBLOCK_INPUT;
5224 bar = x_scroll_bar_create (w, top, sb_left, sb_width, height);
5226 else
5228 /* It may just need to be moved and resized. */
5229 unsigned int mask = 0;
5231 bar = XSCROLL_BAR (w->vertical_scroll_bar);
5233 BLOCK_INPUT;
5235 if (sb_left != bar->left)
5236 mask |= CWX;
5237 if (top != bar->top)
5238 mask |= CWY;
5239 if (sb_width != bar->width)
5240 mask |= CWWidth;
5241 if (height != bar->height)
5242 mask |= CWHeight;
5244 #ifdef USE_TOOLKIT_SCROLL_BARS
5246 /* Move/size the scroll bar widget. */
5247 if (mask || bar->fringe_extended_p != fringe_extended_p)
5249 /* Since toolkit scroll bars are smaller than the space reserved
5250 for them on the frame, we have to clear "under" them. */
5251 if (width > 0 && height > 0)
5253 if (fringe_extended_p)
5254 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5255 sb_left, top, sb_width, height, False);
5256 else
5257 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5258 left, top, width, height, False);
5260 #ifdef USE_GTK
5261 xg_update_scrollbar_pos (f,
5262 bar->x_window,
5263 top,
5264 sb_left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5265 sb_width - VERTICAL_SCROLL_BAR_WIDTH_TRIM *2,
5266 max (height, 1));
5267 #else /* not USE_GTK */
5268 XtConfigureWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar),
5269 sb_left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5270 top,
5271 sb_width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
5272 max (height, 1), 0);
5273 #endif /* not USE_GTK */
5275 #else /* not USE_TOOLKIT_SCROLL_BARS */
5277 /* Clear areas not covered by the scroll bar because of
5278 VERTICAL_SCROLL_BAR_WIDTH_TRIM. */
5279 if (VERTICAL_SCROLL_BAR_WIDTH_TRIM)
5281 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5282 left, top, VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5283 height, False);
5284 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5285 left + width - VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5286 top, VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5287 height, False);
5290 /* Clear areas not covered by the scroll bar because it's not as
5291 wide as the area reserved for it. This makes sure a
5292 previous mode line display is cleared after C-x 2 C-x 1, for
5293 example. */
5295 int area_width = WINDOW_CONFIG_SCROLL_BAR_COLS (w) * FRAME_COLUMN_WIDTH (f);
5296 int rest = area_width - sb_width;
5297 if (rest > 0 && height > 0)
5299 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
5300 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5301 left + area_width - rest, top,
5302 rest, height, False);
5303 else
5304 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5305 left, top, rest, height, False);
5309 /* Move/size the scroll bar window. */
5310 if (mask)
5312 XWindowChanges wc;
5314 wc.x = sb_left + VERTICAL_SCROLL_BAR_WIDTH_TRIM;
5315 wc.y = top;
5316 wc.width = sb_width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2;
5317 wc.height = height;
5318 XConfigureWindow (FRAME_X_DISPLAY (f), bar->x_window,
5319 mask, &wc);
5322 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5324 /* Remember new settings. */
5325 bar->left = sb_left;
5326 bar->top = top;
5327 bar->width = sb_width;
5328 bar->height = height;
5330 UNBLOCK_INPUT;
5333 #ifdef USE_TOOLKIT_SCROLL_BARS
5334 bar->fringe_extended_p = fringe_extended_p;
5336 x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
5337 #else /* not USE_TOOLKIT_SCROLL_BARS */
5338 /* Set the scroll bar's current state, unless we're currently being
5339 dragged. */
5340 if (NILP (bar->dragging))
5342 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, height);
5344 if (whole == 0)
5345 x_scroll_bar_set_handle (bar, 0, top_range, 0);
5346 else
5348 int start = ((double) position * top_range) / whole;
5349 int end = ((double) (position + portion) * top_range) / whole;
5350 x_scroll_bar_set_handle (bar, start, end, 0);
5353 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5355 XSETVECTOR (w->vertical_scroll_bar, bar);
5359 /* The following three hooks are used when we're doing a thorough
5360 redisplay of the frame. We don't explicitly know which scroll bars
5361 are going to be deleted, because keeping track of when windows go
5362 away is a real pain - "Can you say set-window-configuration, boys
5363 and girls?" Instead, we just assert at the beginning of redisplay
5364 that *all* scroll bars are to be removed, and then save a scroll bar
5365 from the fiery pit when we actually redisplay its window. */
5367 /* Arrange for all scroll bars on FRAME to be removed at the next call
5368 to `*judge_scroll_bars_hook'. A scroll bar may be spared if
5369 `*redeem_scroll_bar_hook' is applied to its window before the judgment. */
5371 static void
5372 XTcondemn_scroll_bars (FRAME_PTR frame)
5374 /* Transfer all the scroll bars to FRAME_CONDEMNED_SCROLL_BARS. */
5375 while (! NILP (FRAME_SCROLL_BARS (frame)))
5377 Lisp_Object bar;
5378 bar = FRAME_SCROLL_BARS (frame);
5379 FRAME_SCROLL_BARS (frame) = XSCROLL_BAR (bar)->next;
5380 XSCROLL_BAR (bar)->next = FRAME_CONDEMNED_SCROLL_BARS (frame);
5381 XSCROLL_BAR (bar)->prev = Qnil;
5382 if (! NILP (FRAME_CONDEMNED_SCROLL_BARS (frame)))
5383 XSCROLL_BAR (FRAME_CONDEMNED_SCROLL_BARS (frame))->prev = bar;
5384 FRAME_CONDEMNED_SCROLL_BARS (frame) = bar;
5389 /* Un-mark WINDOW's scroll bar for deletion in this judgment cycle.
5390 Note that WINDOW isn't necessarily condemned at all. */
5392 static void
5393 XTredeem_scroll_bar (struct window *window)
5395 struct scroll_bar *bar;
5396 struct frame *f;
5398 /* We can't redeem this window's scroll bar if it doesn't have one. */
5399 if (NILP (window->vertical_scroll_bar))
5400 abort ();
5402 bar = XSCROLL_BAR (window->vertical_scroll_bar);
5404 /* Unlink it from the condemned list. */
5405 f = XFRAME (WINDOW_FRAME (window));
5406 if (NILP (bar->prev))
5408 /* If the prev pointer is nil, it must be the first in one of
5409 the lists. */
5410 if (EQ (FRAME_SCROLL_BARS (f), window->vertical_scroll_bar))
5411 /* It's not condemned. Everything's fine. */
5412 return;
5413 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
5414 window->vertical_scroll_bar))
5415 FRAME_CONDEMNED_SCROLL_BARS (f) = bar->next;
5416 else
5417 /* If its prev pointer is nil, it must be at the front of
5418 one or the other! */
5419 abort ();
5421 else
5422 XSCROLL_BAR (bar->prev)->next = bar->next;
5424 if (! NILP (bar->next))
5425 XSCROLL_BAR (bar->next)->prev = bar->prev;
5427 bar->next = FRAME_SCROLL_BARS (f);
5428 bar->prev = Qnil;
5429 XSETVECTOR (FRAME_SCROLL_BARS (f), bar);
5430 if (! NILP (bar->next))
5431 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
5434 /* Remove all scroll bars on FRAME that haven't been saved since the
5435 last call to `*condemn_scroll_bars_hook'. */
5437 static void
5438 XTjudge_scroll_bars (FRAME_PTR f)
5440 Lisp_Object bar, next;
5442 bar = FRAME_CONDEMNED_SCROLL_BARS (f);
5444 /* Clear out the condemned list now so we won't try to process any
5445 more events on the hapless scroll bars. */
5446 FRAME_CONDEMNED_SCROLL_BARS (f) = Qnil;
5448 for (; ! NILP (bar); bar = next)
5450 struct scroll_bar *b = XSCROLL_BAR (bar);
5452 x_scroll_bar_remove (b);
5454 next = b->next;
5455 b->next = b->prev = Qnil;
5458 /* Now there should be no references to the condemned scroll bars,
5459 and they should get garbage-collected. */
5463 #ifndef USE_TOOLKIT_SCROLL_BARS
5464 /* Handle an Expose or GraphicsExpose event on a scroll bar. This
5465 is a no-op when using toolkit scroll bars.
5467 This may be called from a signal handler, so we have to ignore GC
5468 mark bits. */
5470 static void
5471 x_scroll_bar_expose (struct scroll_bar *bar, XEvent *event)
5473 Window w = bar->x_window;
5474 FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5475 GC gc = f->output_data.x->normal_gc;
5476 int width_trim = VERTICAL_SCROLL_BAR_WIDTH_TRIM;
5478 BLOCK_INPUT;
5480 x_scroll_bar_set_handle (bar, bar->start, bar->end, 1);
5482 /* Switch to scroll bar foreground color. */
5483 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5484 XSetForeground (FRAME_X_DISPLAY (f), gc,
5485 f->output_data.x->scroll_bar_foreground_pixel);
5487 /* Draw a one-pixel border just inside the edges of the scroll bar. */
5488 XDrawRectangle (FRAME_X_DISPLAY (f), w, gc,
5490 /* x, y, width, height */
5491 0, 0,
5492 bar->width - 1 - width_trim - width_trim,
5493 bar->height - 1);
5495 /* Restore the foreground color of the GC if we changed it above. */
5496 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5497 XSetForeground (FRAME_X_DISPLAY (f), gc,
5498 FRAME_FOREGROUND_PIXEL (f));
5500 UNBLOCK_INPUT;
5503 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5505 /* Handle a mouse click on the scroll bar BAR. If *EMACS_EVENT's kind
5506 is set to something other than NO_EVENT, it is enqueued.
5508 This may be called from a signal handler, so we have to ignore GC
5509 mark bits. */
5512 static void
5513 x_scroll_bar_handle_click (struct scroll_bar *bar, XEvent *event, struct input_event *emacs_event)
5515 if (! WINDOWP (bar->window))
5516 abort ();
5518 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
5519 emacs_event->code = event->xbutton.button - Button1;
5520 emacs_event->modifiers
5521 = (x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO
5522 (XFRAME (WINDOW_FRAME (XWINDOW (bar->window)))),
5523 event->xbutton.state)
5524 | (event->type == ButtonRelease
5525 ? up_modifier
5526 : down_modifier));
5527 emacs_event->frame_or_window = bar->window;
5528 emacs_event->arg = Qnil;
5529 emacs_event->timestamp = event->xbutton.time;
5531 int top_range
5532 = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
5533 int y = event->xbutton.y - VERTICAL_SCROLL_BAR_TOP_BORDER;
5535 if (y < 0) y = 0;
5536 if (y > top_range) y = top_range;
5538 if (y < bar->start)
5539 emacs_event->part = scroll_bar_above_handle;
5540 else if (y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
5541 emacs_event->part = scroll_bar_handle;
5542 else
5543 emacs_event->part = scroll_bar_below_handle;
5545 #ifndef USE_TOOLKIT_SCROLL_BARS
5546 /* If the user has released the handle, set it to its final position. */
5547 if (event->type == ButtonRelease
5548 && ! NILP (bar->dragging))
5550 int new_start = y - XINT (bar->dragging);
5551 int new_end = new_start + bar->end - bar->start;
5553 x_scroll_bar_set_handle (bar, new_start, new_end, 0);
5554 bar->dragging = Qnil;
5556 #endif
5558 XSETINT (emacs_event->x, y);
5559 XSETINT (emacs_event->y, top_range);
5563 #ifndef USE_TOOLKIT_SCROLL_BARS
5565 /* Handle some mouse motion while someone is dragging the scroll bar.
5567 This may be called from a signal handler, so we have to ignore GC
5568 mark bits. */
5570 static void
5571 x_scroll_bar_note_movement (struct scroll_bar *bar, XEvent *event)
5573 FRAME_PTR f = XFRAME (XWINDOW (bar->window)->frame);
5575 last_mouse_movement_time = event->xmotion.time;
5577 f->mouse_moved = 1;
5578 XSETVECTOR (last_mouse_scroll_bar, bar);
5580 /* If we're dragging the bar, display it. */
5581 if (! NILP (bar->dragging))
5583 /* Where should the handle be now? */
5584 int new_start = event->xmotion.y - XINT (bar->dragging);
5586 if (new_start != bar->start)
5588 int new_end = new_start + bar->end - bar->start;
5590 x_scroll_bar_set_handle (bar, new_start, new_end, 0);
5595 #endif /* !USE_TOOLKIT_SCROLL_BARS */
5597 /* Return information to the user about the current position of the mouse
5598 on the scroll bar. */
5600 static void
5601 x_scroll_bar_report_motion (FRAME_PTR *fp, Lisp_Object *bar_window,
5602 enum scroll_bar_part *part, Lisp_Object *x,
5603 Lisp_Object *y, Time *timestamp)
5605 struct scroll_bar *bar = XSCROLL_BAR (last_mouse_scroll_bar);
5606 Window w = bar->x_window;
5607 FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5608 int win_x, win_y;
5609 Window dummy_window;
5610 int dummy_coord;
5611 unsigned int dummy_mask;
5613 BLOCK_INPUT;
5615 /* Get the mouse's position relative to the scroll bar window, and
5616 report that. */
5617 if (! XQueryPointer (FRAME_X_DISPLAY (f), w,
5619 /* Root, child, root x and root y. */
5620 &dummy_window, &dummy_window,
5621 &dummy_coord, &dummy_coord,
5623 /* Position relative to scroll bar. */
5624 &win_x, &win_y,
5626 /* Mouse buttons and modifier keys. */
5627 &dummy_mask))
5629 else
5631 int top_range
5632 = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
5634 win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
5636 if (! NILP (bar->dragging))
5637 win_y -= XINT (bar->dragging);
5639 if (win_y < 0)
5640 win_y = 0;
5641 if (win_y > top_range)
5642 win_y = top_range;
5644 *fp = f;
5645 *bar_window = bar->window;
5647 if (! NILP (bar->dragging))
5648 *part = scroll_bar_handle;
5649 else if (win_y < bar->start)
5650 *part = scroll_bar_above_handle;
5651 else if (win_y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
5652 *part = scroll_bar_handle;
5653 else
5654 *part = scroll_bar_below_handle;
5656 XSETINT (*x, win_y);
5657 XSETINT (*y, top_range);
5659 f->mouse_moved = 0;
5660 last_mouse_scroll_bar = Qnil;
5663 *timestamp = last_mouse_movement_time;
5665 UNBLOCK_INPUT;
5669 /* The screen has been cleared so we may have changed foreground or
5670 background colors, and the scroll bars may need to be redrawn.
5671 Clear out the scroll bars, and ask for expose events, so we can
5672 redraw them. */
5674 static void
5675 x_scroll_bar_clear (FRAME_PTR f)
5677 #ifndef USE_TOOLKIT_SCROLL_BARS
5678 Lisp_Object bar;
5680 /* We can have scroll bars even if this is 0,
5681 if we just turned off scroll bar mode.
5682 But in that case we should not clear them. */
5683 if (FRAME_HAS_VERTICAL_SCROLL_BARS (f))
5684 for (bar = FRAME_SCROLL_BARS (f); VECTORP (bar);
5685 bar = XSCROLL_BAR (bar)->next)
5686 XClearArea (FRAME_X_DISPLAY (f),
5687 XSCROLL_BAR (bar)->x_window,
5688 0, 0, 0, 0, True);
5689 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5693 /* The main X event-reading loop - XTread_socket. */
5695 /* This holds the state XLookupString needs to implement dead keys
5696 and other tricks known as "compose processing". _X Window System_
5697 says that a portable program can't use this, but Stephen Gildea assures
5698 me that letting the compiler initialize it to zeros will work okay.
5700 This must be defined outside of XTread_socket, for the same reasons
5701 given for enter_timestamp, above. */
5703 static XComposeStatus compose_status;
5705 /* Record the last 100 characters stored
5706 to help debug the loss-of-chars-during-GC problem. */
5708 static int temp_index;
5709 static short temp_buffer[100];
5711 #define STORE_KEYSYM_FOR_DEBUG(keysym) \
5712 if (temp_index == sizeof temp_buffer / sizeof (short)) \
5713 temp_index = 0; \
5714 temp_buffer[temp_index++] = (keysym)
5716 /* Set this to nonzero to fake an "X I/O error"
5717 on a particular display. */
5719 static struct x_display_info *XTread_socket_fake_io_error;
5721 /* When we find no input here, we occasionally do a no-op command
5722 to verify that the X server is still running and we can still talk with it.
5723 We try all the open displays, one by one.
5724 This variable is used for cycling thru the displays. */
5726 static struct x_display_info *next_noop_dpyinfo;
5728 #if defined USE_X_TOOLKIT || defined USE_GTK
5729 #define SET_SAVED_BUTTON_EVENT \
5730 do \
5732 if (f->output_data.x->saved_menu_event == 0) \
5733 f->output_data.x->saved_menu_event \
5734 = (XEvent *) xmalloc (sizeof (XEvent)); \
5735 *f->output_data.x->saved_menu_event = event; \
5736 inev.ie.kind = MENU_BAR_ACTIVATE_EVENT; \
5737 XSETFRAME (inev.ie.frame_or_window, f); \
5739 while (0)
5740 #endif
5742 enum
5744 X_EVENT_NORMAL,
5745 X_EVENT_GOTO_OUT,
5746 X_EVENT_DROP
5749 /* Filter events for the current X input method.
5750 DPYINFO is the display this event is for.
5751 EVENT is the X event to filter.
5753 Returns non-zero if the event was filtered, caller shall not process
5754 this event further.
5755 Returns zero if event is wasn't filtered. */
5757 #ifdef HAVE_X_I18N
5758 static int
5759 x_filter_event (struct x_display_info *dpyinfo, XEvent *event)
5761 /* XFilterEvent returns non-zero if the input method has
5762 consumed the event. We pass the frame's X window to
5763 XFilterEvent because that's the one for which the IC
5764 was created. */
5766 struct frame *f1 = x_any_window_to_frame (dpyinfo,
5767 event->xclient.window);
5769 return XFilterEvent (event, f1 ? FRAME_X_WINDOW (f1) : None);
5771 #endif
5773 #ifdef USE_GTK
5774 static int current_count;
5775 static int current_finish;
5776 static struct input_event *current_hold_quit;
5778 /* This is the filter function invoked by the GTK event loop.
5779 It is invoked before the XEvent is translated to a GdkEvent,
5780 so we have a chance to act on the event before GTK. */
5781 static GdkFilterReturn
5782 event_handler_gdk (GdkXEvent *gxev, GdkEvent *ev, gpointer data)
5784 XEvent *xev = (XEvent *) gxev;
5786 BLOCK_INPUT;
5787 if (current_count >= 0)
5789 struct x_display_info *dpyinfo;
5791 dpyinfo = x_display_info_for_display (xev->xany.display);
5793 #ifdef HAVE_X_I18N
5794 /* Filter events for the current X input method.
5795 GTK calls XFilterEvent but not for key press and release,
5796 so we do it here. */
5797 if ((xev->type == KeyPress || xev->type == KeyRelease)
5798 && dpyinfo
5799 && x_filter_event (dpyinfo, xev))
5801 UNBLOCK_INPUT;
5802 return GDK_FILTER_REMOVE;
5804 #endif
5806 if (! dpyinfo)
5807 current_finish = X_EVENT_NORMAL;
5808 else
5809 current_count +=
5810 handle_one_xevent (dpyinfo, xev, &current_finish,
5811 current_hold_quit);
5813 else
5814 current_finish = x_dispatch_event (xev, xev->xany.display);
5816 UNBLOCK_INPUT;
5818 if (current_finish == X_EVENT_GOTO_OUT || current_finish == X_EVENT_DROP)
5819 return GDK_FILTER_REMOVE;
5821 return GDK_FILTER_CONTINUE;
5823 #endif /* USE_GTK */
5826 static void xembed_send_message (struct frame *f, Time,
5827 enum xembed_message,
5828 long detail, long data1, long data2);
5830 /* Handles the XEvent EVENT on display DPYINFO.
5832 *FINISH is X_EVENT_GOTO_OUT if caller should stop reading events.
5833 *FINISH is zero if caller should continue reading events.
5834 *FINISH is X_EVENT_DROP if event should not be passed to the toolkit.
5836 We return the number of characters stored into the buffer. */
5838 static int
5839 handle_one_xevent (struct x_display_info *dpyinfo, XEvent *eventptr,
5840 int *finish, struct input_event *hold_quit)
5842 union {
5843 struct input_event ie;
5844 struct selection_input_event sie;
5845 } inev;
5846 int count = 0;
5847 int do_help = 0;
5848 ptrdiff_t nbytes = 0;
5849 struct frame *f = NULL;
5850 struct coding_system coding;
5851 XEvent event = *eventptr;
5852 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
5853 USE_SAFE_ALLOCA;
5855 *finish = X_EVENT_NORMAL;
5857 EVENT_INIT (inev.ie);
5858 inev.ie.kind = NO_EVENT;
5859 inev.ie.arg = Qnil;
5861 if (pending_event_wait.eventtype == event.type)
5862 pending_event_wait.eventtype = 0; /* Indicates we got it. */
5864 switch (event.type)
5866 case ClientMessage:
5868 if (event.xclient.message_type
5869 == dpyinfo->Xatom_wm_protocols
5870 && event.xclient.format == 32)
5872 if (event.xclient.data.l[0]
5873 == dpyinfo->Xatom_wm_take_focus)
5875 /* Use x_any_window_to_frame because this
5876 could be the shell widget window
5877 if the frame has no title bar. */
5878 f = x_any_window_to_frame (dpyinfo, event.xclient.window);
5879 #ifdef HAVE_X_I18N
5880 /* Not quite sure this is needed -pd */
5881 if (f && FRAME_XIC (f))
5882 XSetICFocus (FRAME_XIC (f));
5883 #endif
5884 #if 0 /* Emacs sets WM hints whose `input' field is `true'. This
5885 instructs the WM to set the input focus automatically for
5886 Emacs with a call to XSetInputFocus. Setting WM_TAKE_FOCUS
5887 tells the WM to send us a ClientMessage WM_TAKE_FOCUS after
5888 it has set the focus. So, XSetInputFocus below is not
5889 needed.
5891 The call to XSetInputFocus below has also caused trouble. In
5892 cases where the XSetInputFocus done by the WM and the one
5893 below are temporally close (on a fast machine), the call
5894 below can generate additional FocusIn events which confuse
5895 Emacs. */
5897 /* Since we set WM_TAKE_FOCUS, we must call
5898 XSetInputFocus explicitly. But not if f is null,
5899 since that might be an event for a deleted frame. */
5900 if (f)
5902 Display *d = event.xclient.display;
5903 /* Catch and ignore errors, in case window has been
5904 iconified by a window manager such as GWM. */
5905 x_catch_errors (d);
5906 XSetInputFocus (d, event.xclient.window,
5907 /* The ICCCM says this is
5908 the only valid choice. */
5909 RevertToParent,
5910 event.xclient.data.l[1]);
5911 /* This is needed to detect the error
5912 if there is an error. */
5913 XSync (d, False);
5914 x_uncatch_errors ();
5916 /* Not certain about handling scroll bars here */
5917 #endif /* 0 */
5918 goto done;
5921 if (event.xclient.data.l[0]
5922 == dpyinfo->Xatom_wm_save_yourself)
5924 /* Save state modify the WM_COMMAND property to
5925 something which can reinstate us. This notifies
5926 the session manager, who's looking for such a
5927 PropertyNotify. Can restart processing when
5928 a keyboard or mouse event arrives. */
5929 /* If we have a session manager, don't set this.
5930 KDE will then start two Emacsen, one for the
5931 session manager and one for this. */
5932 #ifdef HAVE_X_SM
5933 if (! x_session_have_connection ())
5934 #endif
5936 f = x_top_window_to_frame (dpyinfo,
5937 event.xclient.window);
5938 /* This is just so we only give real data once
5939 for a single Emacs process. */
5940 if (f == SELECTED_FRAME ())
5941 XSetCommand (FRAME_X_DISPLAY (f),
5942 event.xclient.window,
5943 initial_argv, initial_argc);
5944 else if (f)
5945 XSetCommand (FRAME_X_DISPLAY (f),
5946 event.xclient.window,
5947 0, 0);
5949 goto done;
5952 if (event.xclient.data.l[0]
5953 == dpyinfo->Xatom_wm_delete_window)
5955 f = x_any_window_to_frame (dpyinfo,
5956 event.xclient.window);
5957 if (!f)
5958 goto OTHER; /* May be a dialog that is to be removed */
5960 inev.ie.kind = DELETE_WINDOW_EVENT;
5961 XSETFRAME (inev.ie.frame_or_window, f);
5962 goto done;
5965 goto done;
5968 if (event.xclient.message_type
5969 == dpyinfo->Xatom_wm_configure_denied)
5971 goto done;
5974 if (event.xclient.message_type
5975 == dpyinfo->Xatom_wm_window_moved)
5977 int new_x, new_y;
5978 f = x_window_to_frame (dpyinfo, event.xclient.window);
5980 new_x = event.xclient.data.s[0];
5981 new_y = event.xclient.data.s[1];
5983 if (f)
5985 f->left_pos = new_x;
5986 f->top_pos = new_y;
5988 goto done;
5991 #ifdef HACK_EDITRES
5992 if (event.xclient.message_type
5993 == dpyinfo->Xatom_editres)
5995 f = x_any_window_to_frame (dpyinfo, event.xclient.window);
5996 if (f)
5997 _XEditResCheckMessages (f->output_data.x->widget, NULL,
5998 &event, NULL);
5999 goto done;
6001 #endif /* HACK_EDITRES */
6003 if ((event.xclient.message_type
6004 == dpyinfo->Xatom_DONE)
6005 || (event.xclient.message_type
6006 == dpyinfo->Xatom_PAGE))
6008 /* Ghostview job completed. Kill it. We could
6009 reply with "Next" if we received "Page", but we
6010 currently never do because we are interested in
6011 images, only, which should have 1 page. */
6012 Pixmap pixmap = (Pixmap) event.xclient.data.l[1];
6013 f = x_window_to_frame (dpyinfo, event.xclient.window);
6014 if (!f)
6015 goto OTHER;
6016 x_kill_gs_process (pixmap, f);
6017 expose_frame (f, 0, 0, 0, 0);
6018 goto done;
6021 #ifdef USE_TOOLKIT_SCROLL_BARS
6022 /* Scroll bar callbacks send a ClientMessage from which
6023 we construct an input_event. */
6024 if (event.xclient.message_type
6025 == dpyinfo->Xatom_Scrollbar)
6027 x_scroll_bar_to_input_event (&event, &inev.ie);
6028 *finish = X_EVENT_GOTO_OUT;
6029 goto done;
6031 #endif /* USE_TOOLKIT_SCROLL_BARS */
6033 /* XEmbed messages from the embedder (if any). */
6034 if (event.xclient.message_type
6035 == dpyinfo->Xatom_XEMBED)
6037 enum xembed_message msg = event.xclient.data.l[1];
6038 if (msg == XEMBED_FOCUS_IN || msg == XEMBED_FOCUS_OUT)
6039 x_detect_focus_change (dpyinfo, &event, &inev.ie);
6041 *finish = X_EVENT_GOTO_OUT;
6042 goto done;
6045 xft_settings_event (dpyinfo, &event);
6047 f = x_any_window_to_frame (dpyinfo, event.xclient.window);
6048 if (!f)
6049 goto OTHER;
6050 if (x_handle_dnd_message (f, &event.xclient, dpyinfo, &inev.ie))
6051 *finish = X_EVENT_DROP;
6053 break;
6055 case SelectionNotify:
6056 last_user_time = event.xselection.time;
6057 #ifdef USE_X_TOOLKIT
6058 if (! x_window_to_frame (dpyinfo, event.xselection.requestor))
6059 goto OTHER;
6060 #endif /* not USE_X_TOOLKIT */
6061 x_handle_selection_notify (&event.xselection);
6062 break;
6064 case SelectionClear: /* Someone has grabbed ownership. */
6065 last_user_time = event.xselectionclear.time;
6066 #ifdef USE_X_TOOLKIT
6067 if (! x_window_to_frame (dpyinfo, event.xselectionclear.window))
6068 goto OTHER;
6069 #endif /* USE_X_TOOLKIT */
6071 XSelectionClearEvent *eventp = &(event.xselectionclear);
6073 inev.ie.kind = SELECTION_CLEAR_EVENT;
6074 SELECTION_EVENT_DISPLAY (&inev.sie) = eventp->display;
6075 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
6076 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
6077 inev.ie.frame_or_window = Qnil;
6079 break;
6081 case SelectionRequest: /* Someone wants our selection. */
6082 last_user_time = event.xselectionrequest.time;
6083 #ifdef USE_X_TOOLKIT
6084 if (!x_window_to_frame (dpyinfo, event.xselectionrequest.owner))
6085 goto OTHER;
6086 #endif /* USE_X_TOOLKIT */
6088 XSelectionRequestEvent *eventp = &(event.xselectionrequest);
6090 inev.ie.kind = SELECTION_REQUEST_EVENT;
6091 SELECTION_EVENT_DISPLAY (&inev.sie) = eventp->display;
6092 SELECTION_EVENT_REQUESTOR (&inev.sie) = eventp->requestor;
6093 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
6094 SELECTION_EVENT_TARGET (&inev.sie) = eventp->target;
6095 SELECTION_EVENT_PROPERTY (&inev.sie) = eventp->property;
6096 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
6097 inev.ie.frame_or_window = Qnil;
6099 break;
6101 case PropertyNotify:
6102 last_user_time = event.xproperty.time;
6103 f = x_top_window_to_frame (dpyinfo, event.xproperty.window);
6104 if (f && event.xproperty.atom == dpyinfo->Xatom_net_wm_state)
6105 x_handle_net_wm_state (f, &event.xproperty);
6107 x_handle_property_notify (&event.xproperty);
6108 xft_settings_event (dpyinfo, &event);
6109 goto OTHER;
6111 case ReparentNotify:
6112 f = x_top_window_to_frame (dpyinfo, event.xreparent.window);
6113 if (f)
6115 int x, y;
6116 f->output_data.x->parent_desc = event.xreparent.parent;
6117 x_real_positions (f, &x, &y);
6118 f->left_pos = x;
6119 f->top_pos = y;
6121 /* Perhaps reparented due to a WM restart. Reset this. */
6122 FRAME_X_DISPLAY_INFO (f)->wm_type = X_WMTYPE_UNKNOWN;
6123 FRAME_X_DISPLAY_INFO (f)->net_supported_window = 0;
6125 x_set_frame_alpha (f);
6127 goto OTHER;
6129 case Expose:
6130 f = x_window_to_frame (dpyinfo, event.xexpose.window);
6131 if (f)
6133 #ifdef USE_GTK
6134 /* This seems to be needed for GTK 2.6. */
6135 x_clear_area (event.xexpose.display,
6136 event.xexpose.window,
6137 event.xexpose.x, event.xexpose.y,
6138 event.xexpose.width, event.xexpose.height,
6139 FALSE);
6140 #endif
6141 if (f->async_visible == 0)
6143 f->async_visible = 1;
6144 f->async_iconified = 0;
6145 f->output_data.x->has_been_visible = 1;
6146 SET_FRAME_GARBAGED (f);
6148 else
6149 expose_frame (f,
6150 event.xexpose.x, event.xexpose.y,
6151 event.xexpose.width, event.xexpose.height);
6153 else
6155 #ifndef USE_TOOLKIT_SCROLL_BARS
6156 struct scroll_bar *bar;
6157 #endif
6158 #if defined USE_LUCID
6159 /* Submenus of the Lucid menu bar aren't widgets
6160 themselves, so there's no way to dispatch events
6161 to them. Recognize this case separately. */
6163 Widget widget
6164 = x_window_to_menu_bar (event.xexpose.window);
6165 if (widget)
6166 xlwmenu_redisplay (widget);
6168 #endif /* USE_LUCID */
6170 #ifdef USE_TOOLKIT_SCROLL_BARS
6171 /* Dispatch event to the widget. */
6172 goto OTHER;
6173 #else /* not USE_TOOLKIT_SCROLL_BARS */
6174 bar = x_window_to_scroll_bar (event.xexpose.display,
6175 event.xexpose.window);
6177 if (bar)
6178 x_scroll_bar_expose (bar, &event);
6179 #ifdef USE_X_TOOLKIT
6180 else
6181 goto OTHER;
6182 #endif /* USE_X_TOOLKIT */
6183 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6185 break;
6187 case GraphicsExpose: /* This occurs when an XCopyArea's
6188 source area was obscured or not
6189 available. */
6190 f = x_window_to_frame (dpyinfo, event.xgraphicsexpose.drawable);
6191 if (f)
6193 expose_frame (f,
6194 event.xgraphicsexpose.x, event.xgraphicsexpose.y,
6195 event.xgraphicsexpose.width,
6196 event.xgraphicsexpose.height);
6198 #ifdef USE_X_TOOLKIT
6199 else
6200 goto OTHER;
6201 #endif /* USE_X_TOOLKIT */
6202 break;
6204 case NoExpose: /* This occurs when an XCopyArea's
6205 source area was completely
6206 available. */
6207 break;
6209 case UnmapNotify:
6210 /* Redo the mouse-highlight after the tooltip has gone. */
6211 if (event.xmap.window == tip_window)
6213 tip_window = 0;
6214 redo_mouse_highlight ();
6217 f = x_top_window_to_frame (dpyinfo, event.xunmap.window);
6218 if (f) /* F may no longer exist if
6219 the frame was deleted. */
6221 /* While a frame is unmapped, display generation is
6222 disabled; you don't want to spend time updating a
6223 display that won't ever be seen. */
6224 f->async_visible = 0;
6225 /* We can't distinguish, from the event, whether the window
6226 has become iconified or invisible. So assume, if it
6227 was previously visible, than now it is iconified.
6228 But x_make_frame_invisible clears both
6229 the visible flag and the iconified flag;
6230 and that way, we know the window is not iconified now. */
6231 if (FRAME_VISIBLE_P (f) || FRAME_ICONIFIED_P (f))
6233 f->async_iconified = 1;
6235 inev.ie.kind = ICONIFY_EVENT;
6236 XSETFRAME (inev.ie.frame_or_window, f);
6239 goto OTHER;
6241 case MapNotify:
6242 if (event.xmap.window == tip_window)
6243 /* The tooltip has been drawn already. Avoid
6244 the SET_FRAME_GARBAGED below. */
6245 goto OTHER;
6247 /* We use x_top_window_to_frame because map events can
6248 come for sub-windows and they don't mean that the
6249 frame is visible. */
6250 f = x_top_window_to_frame (dpyinfo, event.xmap.window);
6251 if (f)
6253 /* wait_reading_process_output will notice this and update
6254 the frame's display structures.
6255 If we where iconified, we should not set garbaged,
6256 because that stops redrawing on Expose events. This looks
6257 bad if we are called from a recursive event loop
6258 (x_dispatch_event), for example when a dialog is up. */
6259 if (! f->async_iconified)
6260 SET_FRAME_GARBAGED (f);
6262 /* Check if fullscreen was specified before we where mapped the
6263 first time, i.e. from the command line. */
6264 if (!f->output_data.x->has_been_visible)
6265 x_check_fullscreen (f);
6267 f->async_visible = 1;
6268 f->async_iconified = 0;
6269 f->output_data.x->has_been_visible = 1;
6271 if (f->iconified)
6273 inev.ie.kind = DEICONIFY_EVENT;
6274 XSETFRAME (inev.ie.frame_or_window, f);
6276 else if (! NILP (Vframe_list)
6277 && ! NILP (XCDR (Vframe_list)))
6278 /* Force a redisplay sooner or later
6279 to update the frame titles
6280 in case this is the second frame. */
6281 record_asynch_buffer_change ();
6283 #ifdef USE_GTK
6284 xg_frame_resized (f, -1, -1);
6285 #endif
6287 goto OTHER;
6289 case KeyPress:
6291 last_user_time = event.xkey.time;
6292 ignore_next_mouse_click_timeout = 0;
6294 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
6295 /* Dispatch KeyPress events when in menu. */
6296 if (popup_activated ())
6297 goto OTHER;
6298 #endif
6300 f = x_any_window_to_frame (dpyinfo, event.xkey.window);
6302 /* If mouse-highlight is an integer, input clears out
6303 mouse highlighting. */
6304 if (!hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight)
6305 && (f == 0
6306 || !EQ (f->tool_bar_window, hlinfo->mouse_face_window)))
6308 clear_mouse_face (hlinfo);
6309 hlinfo->mouse_face_hidden = 1;
6312 #if defined USE_MOTIF && defined USE_TOOLKIT_SCROLL_BARS
6313 if (f == 0)
6315 /* Scroll bars consume key events, but we want
6316 the keys to go to the scroll bar's frame. */
6317 Widget widget = XtWindowToWidget (dpyinfo->display,
6318 event.xkey.window);
6319 if (widget && XmIsScrollBar (widget))
6321 widget = XtParent (widget);
6322 f = x_any_window_to_frame (dpyinfo, XtWindow (widget));
6325 #endif /* USE_MOTIF and USE_TOOLKIT_SCROLL_BARS */
6327 if (f != 0)
6329 KeySym keysym, orig_keysym;
6330 /* al%imercury@uunet.uu.net says that making this 81
6331 instead of 80 fixed a bug whereby meta chars made
6332 his Emacs hang.
6334 It seems that some version of XmbLookupString has
6335 a bug of not returning XBufferOverflow in
6336 status_return even if the input is too long to
6337 fit in 81 bytes. So, we must prepare sufficient
6338 bytes for copy_buffer. 513 bytes (256 chars for
6339 two-byte character set) seems to be a fairly good
6340 approximation. -- 2000.8.10 handa@etl.go.jp */
6341 unsigned char copy_buffer[513];
6342 unsigned char *copy_bufptr = copy_buffer;
6343 int copy_bufsiz = sizeof (copy_buffer);
6344 int modifiers;
6345 Lisp_Object coding_system = Qlatin_1;
6346 Lisp_Object c;
6348 #ifdef USE_GTK
6349 /* Don't pass keys to GTK. A Tab will shift focus to the
6350 tool bar in GTK 2.4. Keys will still go to menus and
6351 dialogs because in that case popup_activated is TRUE
6352 (see above). */
6353 *finish = X_EVENT_DROP;
6354 #endif
6356 event.xkey.state
6357 |= x_emacs_to_x_modifiers (FRAME_X_DISPLAY_INFO (f),
6358 extra_keyboard_modifiers);
6359 modifiers = event.xkey.state;
6361 /* This will have to go some day... */
6363 /* make_lispy_event turns chars into control chars.
6364 Don't do it here because XLookupString is too eager. */
6365 event.xkey.state &= ~ControlMask;
6366 event.xkey.state &= ~(dpyinfo->meta_mod_mask
6367 | dpyinfo->super_mod_mask
6368 | dpyinfo->hyper_mod_mask
6369 | dpyinfo->alt_mod_mask);
6371 /* In case Meta is ComposeCharacter,
6372 clear its status. According to Markus Ehrnsperger
6373 Markus.Ehrnsperger@lehrstuhl-bross.physik.uni-muenchen.de
6374 this enables ComposeCharacter to work whether or
6375 not it is combined with Meta. */
6376 if (modifiers & dpyinfo->meta_mod_mask)
6377 memset (&compose_status, 0, sizeof (compose_status));
6379 #ifdef HAVE_X_I18N
6380 if (FRAME_XIC (f))
6382 Status status_return;
6384 coding_system = Vlocale_coding_system;
6385 nbytes = XmbLookupString (FRAME_XIC (f),
6386 &event.xkey, (char *) copy_bufptr,
6387 copy_bufsiz, &keysym,
6388 &status_return);
6389 if (status_return == XBufferOverflow)
6391 copy_bufsiz = nbytes + 1;
6392 copy_bufptr = (unsigned char *) alloca (copy_bufsiz);
6393 nbytes = XmbLookupString (FRAME_XIC (f),
6394 &event.xkey, (char *) copy_bufptr,
6395 copy_bufsiz, &keysym,
6396 &status_return);
6398 /* Xutf8LookupString is a new but already deprecated interface. -stef */
6399 if (status_return == XLookupNone)
6400 break;
6401 else if (status_return == XLookupChars)
6403 keysym = NoSymbol;
6404 modifiers = 0;
6406 else if (status_return != XLookupKeySym
6407 && status_return != XLookupBoth)
6408 abort ();
6410 else
6411 nbytes = XLookupString (&event.xkey, (char *) copy_bufptr,
6412 copy_bufsiz, &keysym,
6413 &compose_status);
6414 #else
6415 nbytes = XLookupString (&event.xkey, (char *) copy_bufptr,
6416 copy_bufsiz, &keysym,
6417 &compose_status);
6418 #endif
6420 /* If not using XIM/XIC, and a compose sequence is in progress,
6421 we break here. Otherwise, chars_matched is always 0. */
6422 if (compose_status.chars_matched > 0 && nbytes == 0)
6423 break;
6425 memset (&compose_status, 0, sizeof (compose_status));
6426 orig_keysym = keysym;
6428 /* Common for all keysym input events. */
6429 XSETFRAME (inev.ie.frame_or_window, f);
6430 inev.ie.modifiers
6431 = x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO (f), modifiers);
6432 inev.ie.timestamp = event.xkey.time;
6434 /* First deal with keysyms which have defined
6435 translations to characters. */
6436 if (keysym >= 32 && keysym < 128)
6437 /* Avoid explicitly decoding each ASCII character. */
6439 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
6440 inev.ie.code = keysym;
6441 goto done_keysym;
6444 /* Keysyms directly mapped to Unicode characters. */
6445 if (keysym >= 0x01000000 && keysym <= 0x0110FFFF)
6447 if (keysym < 0x01000080)
6448 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
6449 else
6450 inev.ie.kind = MULTIBYTE_CHAR_KEYSTROKE_EVENT;
6451 inev.ie.code = keysym & 0xFFFFFF;
6452 goto done_keysym;
6455 /* Now non-ASCII. */
6456 if (HASH_TABLE_P (Vx_keysym_table)
6457 && (NATNUMP (c = Fgethash (make_number (keysym),
6458 Vx_keysym_table,
6459 Qnil))))
6461 inev.ie.kind = (SINGLE_BYTE_CHAR_P (XFASTINT (c))
6462 ? ASCII_KEYSTROKE_EVENT
6463 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
6464 inev.ie.code = XFASTINT (c);
6465 goto done_keysym;
6468 /* Random non-modifier sorts of keysyms. */
6469 if (((keysym >= XK_BackSpace && keysym <= XK_Escape)
6470 || keysym == XK_Delete
6471 #ifdef XK_ISO_Left_Tab
6472 || (keysym >= XK_ISO_Left_Tab
6473 && keysym <= XK_ISO_Enter)
6474 #endif
6475 || IsCursorKey (keysym) /* 0xff50 <= x < 0xff60 */
6476 || IsMiscFunctionKey (keysym) /* 0xff60 <= x < VARIES */
6477 #ifdef HPUX
6478 /* This recognizes the "extended function
6479 keys". It seems there's no cleaner way.
6480 Test IsModifierKey to avoid handling
6481 mode_switch incorrectly. */
6482 || (XK_Select <= keysym && keysym < XK_KP_Space)
6483 #endif
6484 #ifdef XK_dead_circumflex
6485 || orig_keysym == XK_dead_circumflex
6486 #endif
6487 #ifdef XK_dead_grave
6488 || orig_keysym == XK_dead_grave
6489 #endif
6490 #ifdef XK_dead_tilde
6491 || orig_keysym == XK_dead_tilde
6492 #endif
6493 #ifdef XK_dead_diaeresis
6494 || orig_keysym == XK_dead_diaeresis
6495 #endif
6496 #ifdef XK_dead_macron
6497 || orig_keysym == XK_dead_macron
6498 #endif
6499 #ifdef XK_dead_degree
6500 || orig_keysym == XK_dead_degree
6501 #endif
6502 #ifdef XK_dead_acute
6503 || orig_keysym == XK_dead_acute
6504 #endif
6505 #ifdef XK_dead_cedilla
6506 || orig_keysym == XK_dead_cedilla
6507 #endif
6508 #ifdef XK_dead_breve
6509 || orig_keysym == XK_dead_breve
6510 #endif
6511 #ifdef XK_dead_ogonek
6512 || orig_keysym == XK_dead_ogonek
6513 #endif
6514 #ifdef XK_dead_caron
6515 || orig_keysym == XK_dead_caron
6516 #endif
6517 #ifdef XK_dead_doubleacute
6518 || orig_keysym == XK_dead_doubleacute
6519 #endif
6520 #ifdef XK_dead_abovedot
6521 || orig_keysym == XK_dead_abovedot
6522 #endif
6523 || IsKeypadKey (keysym) /* 0xff80 <= x < 0xffbe */
6524 || IsFunctionKey (keysym) /* 0xffbe <= x < 0xffe1 */
6525 /* Any "vendor-specific" key is ok. */
6526 || (orig_keysym & (1 << 28))
6527 || (keysym != NoSymbol && nbytes == 0))
6528 && ! (IsModifierKey (orig_keysym)
6529 /* The symbols from XK_ISO_Lock
6530 to XK_ISO_Last_Group_Lock
6531 don't have real modifiers but
6532 should be treated similarly to
6533 Mode_switch by Emacs. */
6534 #if defined XK_ISO_Lock && defined XK_ISO_Last_Group_Lock
6535 || (XK_ISO_Lock <= orig_keysym
6536 && orig_keysym <= XK_ISO_Last_Group_Lock)
6537 #endif
6540 STORE_KEYSYM_FOR_DEBUG (keysym);
6541 /* make_lispy_event will convert this to a symbolic
6542 key. */
6543 inev.ie.kind = NON_ASCII_KEYSTROKE_EVENT;
6544 inev.ie.code = keysym;
6545 goto done_keysym;
6548 { /* Raw bytes, not keysym. */
6549 ptrdiff_t i;
6550 int nchars, len;
6552 for (i = 0, nchars = 0; i < nbytes; i++)
6554 if (ASCII_BYTE_P (copy_bufptr[i]))
6555 nchars++;
6556 STORE_KEYSYM_FOR_DEBUG (copy_bufptr[i]);
6559 if (nchars < nbytes)
6561 /* Decode the input data. */
6563 /* The input should be decoded with `coding_system'
6564 which depends on which X*LookupString function
6565 we used just above and the locale. */
6566 setup_coding_system (coding_system, &coding);
6567 coding.src_multibyte = 0;
6568 coding.dst_multibyte = 1;
6569 /* The input is converted to events, thus we can't
6570 handle composition. Anyway, there's no XIM that
6571 gives us composition information. */
6572 coding.common_flags &= ~CODING_ANNOTATION_MASK;
6574 SAFE_NALLOCA (coding.destination, MAX_MULTIBYTE_LENGTH,
6575 nbytes);
6576 coding.dst_bytes = MAX_MULTIBYTE_LENGTH * nbytes;
6577 coding.mode |= CODING_MODE_LAST_BLOCK;
6578 decode_coding_c_string (&coding, copy_bufptr, nbytes, Qnil);
6579 nbytes = coding.produced;
6580 nchars = coding.produced_char;
6581 copy_bufptr = coding.destination;
6584 /* Convert the input data to a sequence of
6585 character events. */
6586 for (i = 0; i < nbytes; i += len)
6588 int ch;
6589 if (nchars == nbytes)
6590 ch = copy_bufptr[i], len = 1;
6591 else
6592 ch = STRING_CHAR_AND_LENGTH (copy_bufptr + i, len);
6593 inev.ie.kind = (SINGLE_BYTE_CHAR_P (ch)
6594 ? ASCII_KEYSTROKE_EVENT
6595 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
6596 inev.ie.code = ch;
6597 kbd_buffer_store_event_hold (&inev.ie, hold_quit);
6600 count += nchars;
6602 inev.ie.kind = NO_EVENT; /* Already stored above. */
6604 if (keysym == NoSymbol)
6605 break;
6608 done_keysym:
6609 #ifdef HAVE_X_I18N
6610 /* Don't dispatch this event since XtDispatchEvent calls
6611 XFilterEvent, and two calls in a row may freeze the
6612 client. */
6613 break;
6614 #else
6615 goto OTHER;
6616 #endif
6618 case KeyRelease:
6619 last_user_time = event.xkey.time;
6620 #ifdef HAVE_X_I18N
6621 /* Don't dispatch this event since XtDispatchEvent calls
6622 XFilterEvent, and two calls in a row may freeze the
6623 client. */
6624 break;
6625 #else
6626 goto OTHER;
6627 #endif
6629 case EnterNotify:
6630 last_user_time = event.xcrossing.time;
6631 x_detect_focus_change (dpyinfo, &event, &inev.ie);
6633 f = x_any_window_to_frame (dpyinfo, event.xcrossing.window);
6635 if (f && x_mouse_click_focus_ignore_position)
6636 ignore_next_mouse_click_timeout = event.xmotion.time + 200;
6638 /* EnterNotify counts as mouse movement,
6639 so update things that depend on mouse position. */
6640 if (f && !f->output_data.x->hourglass_p)
6641 note_mouse_movement (f, &event.xmotion);
6642 #ifdef USE_GTK
6643 /* We may get an EnterNotify on the buttons in the toolbar. In that
6644 case we moved out of any highlighted area and need to note this. */
6645 if (!f && last_mouse_glyph_frame)
6646 note_mouse_movement (last_mouse_glyph_frame, &event.xmotion);
6647 #endif
6648 goto OTHER;
6650 case FocusIn:
6651 x_detect_focus_change (dpyinfo, &event, &inev.ie);
6652 goto OTHER;
6654 case LeaveNotify:
6655 last_user_time = event.xcrossing.time;
6656 x_detect_focus_change (dpyinfo, &event, &inev.ie);
6658 f = x_top_window_to_frame (dpyinfo, event.xcrossing.window);
6659 if (f)
6661 if (f == hlinfo->mouse_face_mouse_frame)
6663 /* If we move outside the frame, then we're
6664 certainly no longer on any text in the frame. */
6665 clear_mouse_face (hlinfo);
6666 hlinfo->mouse_face_mouse_frame = 0;
6669 /* Generate a nil HELP_EVENT to cancel a help-echo.
6670 Do it only if there's something to cancel.
6671 Otherwise, the startup message is cleared when
6672 the mouse leaves the frame. */
6673 if (any_help_event_p)
6674 do_help = -1;
6676 #ifdef USE_GTK
6677 /* See comment in EnterNotify above */
6678 else if (last_mouse_glyph_frame)
6679 note_mouse_movement (last_mouse_glyph_frame, &event.xmotion);
6680 #endif
6681 goto OTHER;
6683 case FocusOut:
6684 x_detect_focus_change (dpyinfo, &event, &inev.ie);
6685 goto OTHER;
6687 case MotionNotify:
6689 last_user_time = event.xmotion.time;
6690 previous_help_echo_string = help_echo_string;
6691 help_echo_string = Qnil;
6693 if (dpyinfo->grabbed && last_mouse_frame
6694 && FRAME_LIVE_P (last_mouse_frame))
6695 f = last_mouse_frame;
6696 else
6697 f = x_window_to_frame (dpyinfo, event.xmotion.window);
6699 if (hlinfo->mouse_face_hidden)
6701 hlinfo->mouse_face_hidden = 0;
6702 clear_mouse_face (hlinfo);
6705 #ifdef USE_GTK
6706 if (f && xg_event_is_for_scrollbar (f, &event))
6707 f = 0;
6708 #endif
6709 if (f)
6712 /* Generate SELECT_WINDOW_EVENTs when needed.
6713 Don't let popup menus influence things (bug#1261). */
6714 if (!NILP (Vmouse_autoselect_window) && !popup_activated ())
6716 Lisp_Object window;
6718 window = window_from_coordinates (f,
6719 event.xmotion.x, event.xmotion.y,
6720 0, 0);
6722 /* Window will be selected only when it is not selected now and
6723 last mouse movement event was not in it. Minibuffer window
6724 will be selected only when it is active. */
6725 if (WINDOWP (window)
6726 && !EQ (window, last_window)
6727 && !EQ (window, selected_window)
6728 /* For click-to-focus window managers
6729 create event iff we don't leave the
6730 selected frame. */
6731 && (focus_follows_mouse
6732 || (EQ (XWINDOW (window)->frame,
6733 XWINDOW (selected_window)->frame))))
6735 inev.ie.kind = SELECT_WINDOW_EVENT;
6736 inev.ie.frame_or_window = window;
6739 last_window=window;
6741 if (!note_mouse_movement (f, &event.xmotion))
6742 help_echo_string = previous_help_echo_string;
6744 else
6746 #ifndef USE_TOOLKIT_SCROLL_BARS
6747 struct scroll_bar *bar
6748 = x_window_to_scroll_bar (event.xmotion.display,
6749 event.xmotion.window);
6751 if (bar)
6752 x_scroll_bar_note_movement (bar, &event);
6753 #endif /* USE_TOOLKIT_SCROLL_BARS */
6755 /* If we move outside the frame, then we're
6756 certainly no longer on any text in the frame. */
6757 clear_mouse_face (hlinfo);
6760 /* If the contents of the global variable help_echo_string
6761 has changed, generate a HELP_EVENT. */
6762 if (!NILP (help_echo_string)
6763 || !NILP (previous_help_echo_string))
6764 do_help = 1;
6765 goto OTHER;
6768 case ConfigureNotify:
6769 f = x_top_window_to_frame (dpyinfo, event.xconfigure.window);
6770 #ifdef USE_GTK
6771 if (!f
6772 && (f = x_any_window_to_frame (dpyinfo, event.xconfigure.window))
6773 && event.xconfigure.window == FRAME_X_WINDOW (f))
6775 xg_frame_resized (f, event.xconfigure.width,
6776 event.xconfigure.height);
6777 f = 0;
6779 #endif
6780 if (f)
6782 #ifndef USE_X_TOOLKIT
6783 #ifndef USE_GTK
6784 int rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, event.xconfigure.height);
6785 int columns = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, event.xconfigure.width);
6787 /* In the toolkit version, change_frame_size
6788 is called by the code that handles resizing
6789 of the EmacsFrame widget. */
6791 /* Even if the number of character rows and columns has
6792 not changed, the font size may have changed, so we need
6793 to check the pixel dimensions as well. */
6794 if (columns != FRAME_COLS (f)
6795 || rows != FRAME_LINES (f)
6796 || event.xconfigure.width != FRAME_PIXEL_WIDTH (f)
6797 || event.xconfigure.height != FRAME_PIXEL_HEIGHT (f))
6799 change_frame_size (f, rows, columns, 0, 1, 0);
6800 SET_FRAME_GARBAGED (f);
6801 cancel_mouse_face (f);
6804 FRAME_PIXEL_WIDTH (f) = event.xconfigure.width;
6805 FRAME_PIXEL_HEIGHT (f) = event.xconfigure.height;
6806 #endif /* not USE_GTK */
6807 #endif
6809 #ifdef USE_GTK
6810 /* GTK creates windows but doesn't map them.
6811 Only get real positions when mapped. */
6812 if (FRAME_GTK_OUTER_WIDGET (f)
6813 && gtk_widget_get_mapped (FRAME_GTK_OUTER_WIDGET (f)))
6814 #endif
6816 x_real_positions (f, &f->left_pos, &f->top_pos);
6819 #ifdef HAVE_X_I18N
6820 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMStatusArea))
6821 xic_set_statusarea (f);
6822 #endif
6825 goto OTHER;
6827 case ButtonRelease:
6828 case ButtonPress:
6830 /* If we decide we want to generate an event to be seen
6831 by the rest of Emacs, we put it here. */
6832 int tool_bar_p = 0;
6834 memset (&compose_status, 0, sizeof (compose_status));
6835 last_mouse_glyph_frame = 0;
6836 last_user_time = event.xbutton.time;
6838 if (dpyinfo->grabbed
6839 && last_mouse_frame
6840 && FRAME_LIVE_P (last_mouse_frame))
6841 f = last_mouse_frame;
6842 else
6843 f = x_window_to_frame (dpyinfo, event.xbutton.window);
6845 #ifdef USE_GTK
6846 if (f && xg_event_is_for_scrollbar (f, &event))
6847 f = 0;
6848 #endif
6849 if (f)
6851 /* Is this in the tool-bar? */
6852 if (WINDOWP (f->tool_bar_window)
6853 && WINDOW_TOTAL_LINES (XWINDOW (f->tool_bar_window)))
6855 Lisp_Object window;
6856 int x = event.xbutton.x;
6857 int y = event.xbutton.y;
6859 window = window_from_coordinates (f, x, y, 0, 1);
6860 tool_bar_p = EQ (window, f->tool_bar_window);
6862 if (tool_bar_p && event.xbutton.button < 4)
6864 handle_tool_bar_click (f, x, y,
6865 event.xbutton.type == ButtonPress,
6866 x_x_to_emacs_modifiers (dpyinfo,
6867 event.xbutton.state));
6871 if (!tool_bar_p)
6872 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
6873 if (! popup_activated ())
6874 #endif
6876 if (ignore_next_mouse_click_timeout)
6878 if (event.type == ButtonPress
6879 && (int)(event.xbutton.time - ignore_next_mouse_click_timeout) > 0)
6881 ignore_next_mouse_click_timeout = 0;
6882 construct_mouse_click (&inev.ie, &event.xbutton, f);
6884 if (event.type == ButtonRelease)
6885 ignore_next_mouse_click_timeout = 0;
6887 else
6888 construct_mouse_click (&inev.ie, &event.xbutton, f);
6890 if (FRAME_X_EMBEDDED_P (f))
6891 xembed_send_message (f, event.xbutton.time,
6892 XEMBED_REQUEST_FOCUS, 0, 0, 0);
6894 else
6896 struct scroll_bar *bar
6897 = x_window_to_scroll_bar (event.xbutton.display,
6898 event.xbutton.window);
6900 #ifdef USE_TOOLKIT_SCROLL_BARS
6901 /* Make the "Ctrl-Mouse-2 splits window" work for toolkit
6902 scroll bars. */
6903 if (bar && event.xbutton.state & ControlMask)
6905 x_scroll_bar_handle_click (bar, &event, &inev.ie);
6906 *finish = X_EVENT_DROP;
6908 #else /* not USE_TOOLKIT_SCROLL_BARS */
6909 if (bar)
6910 x_scroll_bar_handle_click (bar, &event, &inev.ie);
6911 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6914 if (event.type == ButtonPress)
6916 dpyinfo->grabbed |= (1 << event.xbutton.button);
6917 last_mouse_frame = f;
6919 if (!tool_bar_p)
6920 last_tool_bar_item = -1;
6922 else
6923 dpyinfo->grabbed &= ~(1 << event.xbutton.button);
6925 /* Ignore any mouse motion that happened before this event;
6926 any subsequent mouse-movement Emacs events should reflect
6927 only motion after the ButtonPress/Release. */
6928 if (f != 0)
6929 f->mouse_moved = 0;
6931 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
6932 f = x_menubar_window_to_frame (dpyinfo, &event);
6933 /* For a down-event in the menu bar,
6934 don't pass it to Xt right now.
6935 Instead, save it away
6936 and we will pass it to Xt from kbd_buffer_get_event.
6937 That way, we can run some Lisp code first. */
6938 if (! popup_activated ()
6939 #ifdef USE_GTK
6940 /* Gtk+ menus only react to the first three buttons. */
6941 && event.xbutton.button < 3
6942 #endif
6943 && f && event.type == ButtonPress
6944 /* Verify the event is really within the menu bar
6945 and not just sent to it due to grabbing. */
6946 && event.xbutton.x >= 0
6947 && event.xbutton.x < FRAME_PIXEL_WIDTH (f)
6948 && event.xbutton.y >= 0
6949 && event.xbutton.y < f->output_data.x->menubar_height
6950 && event.xbutton.same_screen)
6952 SET_SAVED_BUTTON_EVENT;
6953 XSETFRAME (last_mouse_press_frame, f);
6954 *finish = X_EVENT_DROP;
6956 else if (event.type == ButtonPress)
6958 last_mouse_press_frame = Qnil;
6959 goto OTHER;
6961 else
6962 goto OTHER;
6963 #endif /* USE_X_TOOLKIT || USE_GTK */
6965 break;
6967 case CirculateNotify:
6968 goto OTHER;
6970 case CirculateRequest:
6971 goto OTHER;
6973 case VisibilityNotify:
6974 goto OTHER;
6976 case MappingNotify:
6977 /* Someone has changed the keyboard mapping - update the
6978 local cache. */
6979 switch (event.xmapping.request)
6981 case MappingModifier:
6982 x_find_modifier_meanings (dpyinfo);
6983 /* This is meant to fall through. */
6984 case MappingKeyboard:
6985 XRefreshKeyboardMapping (&event.xmapping);
6987 goto OTHER;
6989 case DestroyNotify:
6990 xft_settings_event (dpyinfo, &event);
6991 break;
6993 default:
6994 OTHER:
6995 #ifdef USE_X_TOOLKIT
6996 BLOCK_INPUT;
6997 if (*finish != X_EVENT_DROP)
6998 XtDispatchEvent (&event);
6999 UNBLOCK_INPUT;
7000 #endif /* USE_X_TOOLKIT */
7001 break;
7004 done:
7005 if (inev.ie.kind != NO_EVENT)
7007 kbd_buffer_store_event_hold (&inev.ie, hold_quit);
7008 count++;
7011 if (do_help
7012 && !(hold_quit && hold_quit->kind != NO_EVENT))
7014 Lisp_Object frame;
7016 if (f)
7017 XSETFRAME (frame, f);
7018 else
7019 frame = Qnil;
7021 if (do_help > 0)
7023 any_help_event_p = 1;
7024 gen_help_event (help_echo_string, frame, help_echo_window,
7025 help_echo_object, help_echo_pos);
7027 else
7029 help_echo_string = Qnil;
7030 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
7032 count++;
7035 SAFE_FREE ();
7036 *eventptr = event;
7037 return count;
7040 #if defined USE_GTK || defined USE_X_TOOLKIT
7042 /* Handles the XEvent EVENT on display DISPLAY.
7043 This is used for event loops outside the normal event handling,
7044 i.e. looping while a popup menu or a dialog is posted.
7046 Returns the value handle_one_xevent sets in the finish argument. */
7048 x_dispatch_event (XEvent *event, Display *display)
7050 struct x_display_info *dpyinfo;
7051 int finish = X_EVENT_NORMAL;
7053 dpyinfo = x_display_info_for_display (display);
7055 if (dpyinfo)
7056 handle_one_xevent (dpyinfo, event, &finish, 0);
7058 return finish;
7060 #endif
7063 /* Read events coming from the X server.
7064 This routine is called by the SIGIO handler.
7065 We return as soon as there are no more events to be read.
7067 We return the number of characters stored into the buffer,
7068 thus pretending to be `read' (except the characters we store
7069 in the keyboard buffer can be multibyte, so are not necessarily
7070 C chars).
7072 EXPECTED is nonzero if the caller knows input is available. */
7074 static int
7075 XTread_socket (struct terminal *terminal, int expected, struct input_event *hold_quit)
7077 int count = 0;
7078 int event_found = 0;
7080 if (interrupt_input_blocked)
7082 interrupt_input_pending = 1;
7083 #ifdef SYNC_INPUT
7084 pending_signals = 1;
7085 #endif
7086 return -1;
7089 interrupt_input_pending = 0;
7090 #ifdef SYNC_INPUT
7091 pending_signals = pending_atimers;
7092 #endif
7093 BLOCK_INPUT;
7095 /* So people can tell when we have read the available input. */
7096 input_signal_count++;
7098 ++handling_signal;
7100 /* For debugging, this gives a way to fake an I/O error. */
7101 if (terminal->display_info.x == XTread_socket_fake_io_error)
7103 XTread_socket_fake_io_error = 0;
7104 x_io_error_quitter (terminal->display_info.x->display);
7107 #ifndef USE_GTK
7108 while (XPending (terminal->display_info.x->display))
7110 int finish;
7111 XEvent event;
7113 XNextEvent (terminal->display_info.x->display, &event);
7115 #ifdef HAVE_X_I18N
7116 /* Filter events for the current X input method. */
7117 if (x_filter_event (terminal->display_info.x, &event))
7118 continue;
7119 #endif
7120 event_found = 1;
7122 count += handle_one_xevent (terminal->display_info.x,
7123 &event, &finish, hold_quit);
7125 if (finish == X_EVENT_GOTO_OUT)
7126 goto out;
7129 out:;
7131 #else /* USE_GTK */
7133 /* For GTK we must use the GTK event loop. But XEvents gets passed
7134 to our filter function above, and then to the big event switch.
7135 We use a bunch of globals to communicate with our filter function,
7136 that is kind of ugly, but it works.
7138 There is no way to do one display at the time, GTK just does events
7139 from all displays. */
7141 while (gtk_events_pending ())
7143 current_count = count;
7144 current_hold_quit = hold_quit;
7146 gtk_main_iteration ();
7148 count = current_count;
7149 current_count = -1;
7150 current_hold_quit = 0;
7152 if (current_finish == X_EVENT_GOTO_OUT)
7153 break;
7155 #endif /* USE_GTK */
7157 /* On some systems, an X bug causes Emacs to get no more events
7158 when the window is destroyed. Detect that. (1994.) */
7159 if (! event_found)
7161 /* Emacs and the X Server eats up CPU time if XNoOp is done every time.
7162 One XNOOP in 100 loops will make Emacs terminate.
7163 B. Bretthauer, 1994 */
7164 x_noop_count++;
7165 if (x_noop_count >= 100)
7167 x_noop_count=0;
7169 if (next_noop_dpyinfo == 0)
7170 next_noop_dpyinfo = x_display_list;
7172 XNoOp (next_noop_dpyinfo->display);
7174 /* Each time we get here, cycle through the displays now open. */
7175 next_noop_dpyinfo = next_noop_dpyinfo->next;
7179 /* If the focus was just given to an auto-raising frame,
7180 raise it now. */
7181 /* ??? This ought to be able to handle more than one such frame. */
7182 if (pending_autoraise_frame)
7184 x_raise_frame (pending_autoraise_frame);
7185 pending_autoraise_frame = 0;
7188 --handling_signal;
7189 UNBLOCK_INPUT;
7191 return count;
7197 /***********************************************************************
7198 Text Cursor
7199 ***********************************************************************/
7201 /* Set clipping for output in glyph row ROW. W is the window in which
7202 we operate. GC is the graphics context to set clipping in.
7204 ROW may be a text row or, e.g., a mode line. Text rows must be
7205 clipped to the interior of the window dedicated to text display,
7206 mode lines must be clipped to the whole window. */
7208 static void
7209 x_clip_to_row (struct window *w, struct glyph_row *row, int area, GC gc)
7211 struct frame *f = XFRAME (WINDOW_FRAME (w));
7212 XRectangle clip_rect;
7213 int window_x, window_y, window_width;
7215 window_box (w, area, &window_x, &window_y, &window_width, 0);
7217 clip_rect.x = window_x;
7218 clip_rect.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
7219 clip_rect.y = max (clip_rect.y, window_y);
7220 clip_rect.width = window_width;
7221 clip_rect.height = row->visible_height;
7223 XSetClipRectangles (FRAME_X_DISPLAY (f), gc, 0, 0, &clip_rect, 1, Unsorted);
7227 /* Draw a hollow box cursor on window W in glyph row ROW. */
7229 static void
7230 x_draw_hollow_cursor (struct window *w, struct glyph_row *row)
7232 struct frame *f = XFRAME (WINDOW_FRAME (w));
7233 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
7234 Display *dpy = FRAME_X_DISPLAY (f);
7235 int x, y, wd, h;
7236 XGCValues xgcv;
7237 struct glyph *cursor_glyph;
7238 GC gc;
7240 /* Get the glyph the cursor is on. If we can't tell because
7241 the current matrix is invalid or such, give up. */
7242 cursor_glyph = get_phys_cursor_glyph (w);
7243 if (cursor_glyph == NULL)
7244 return;
7246 /* Compute frame-relative coordinates for phys cursor. */
7247 get_phys_cursor_geometry (w, row, cursor_glyph, &x, &y, &h);
7248 wd = w->phys_cursor_width;
7250 /* The foreground of cursor_gc is typically the same as the normal
7251 background color, which can cause the cursor box to be invisible. */
7252 xgcv.foreground = f->output_data.x->cursor_pixel;
7253 if (dpyinfo->scratch_cursor_gc)
7254 XChangeGC (dpy, dpyinfo->scratch_cursor_gc, GCForeground, &xgcv);
7255 else
7256 dpyinfo->scratch_cursor_gc = XCreateGC (dpy, FRAME_X_WINDOW (f),
7257 GCForeground, &xgcv);
7258 gc = dpyinfo->scratch_cursor_gc;
7260 /* Set clipping, draw the rectangle, and reset clipping again. */
7261 x_clip_to_row (w, row, TEXT_AREA, gc);
7262 XDrawRectangle (dpy, FRAME_X_WINDOW (f), gc, x, y, wd, h - 1);
7263 XSetClipMask (dpy, gc, None);
7267 /* Draw a bar cursor on window W in glyph row ROW.
7269 Implementation note: One would like to draw a bar cursor with an
7270 angle equal to the one given by the font property XA_ITALIC_ANGLE.
7271 Unfortunately, I didn't find a font yet that has this property set.
7272 --gerd. */
7274 static void
7275 x_draw_bar_cursor (struct window *w, struct glyph_row *row, int width, enum text_cursor_kinds kind)
7277 struct frame *f = XFRAME (w->frame);
7278 struct glyph *cursor_glyph;
7280 /* If cursor is out of bounds, don't draw garbage. This can happen
7281 in mini-buffer windows when switching between echo area glyphs
7282 and mini-buffer. */
7283 cursor_glyph = get_phys_cursor_glyph (w);
7284 if (cursor_glyph == NULL)
7285 return;
7287 /* If on an image, draw like a normal cursor. That's usually better
7288 visible than drawing a bar, esp. if the image is large so that
7289 the bar might not be in the window. */
7290 if (cursor_glyph->type == IMAGE_GLYPH)
7292 struct glyph_row *r;
7293 r = MATRIX_ROW (w->current_matrix, w->phys_cursor.vpos);
7294 draw_phys_cursor_glyph (w, r, DRAW_CURSOR);
7296 else
7298 Display *dpy = FRAME_X_DISPLAY (f);
7299 Window window = FRAME_X_WINDOW (f);
7300 GC gc = FRAME_X_DISPLAY_INFO (f)->scratch_cursor_gc;
7301 unsigned long mask = GCForeground | GCBackground | GCGraphicsExposures;
7302 struct face *face = FACE_FROM_ID (f, cursor_glyph->face_id);
7303 XGCValues xgcv;
7305 /* If the glyph's background equals the color we normally draw
7306 the bars cursor in, the bar cursor in its normal color is
7307 invisible. Use the glyph's foreground color instead in this
7308 case, on the assumption that the glyph's colors are chosen so
7309 that the glyph is legible. */
7310 if (face->background == f->output_data.x->cursor_pixel)
7311 xgcv.background = xgcv.foreground = face->foreground;
7312 else
7313 xgcv.background = xgcv.foreground = f->output_data.x->cursor_pixel;
7314 xgcv.graphics_exposures = 0;
7316 if (gc)
7317 XChangeGC (dpy, gc, mask, &xgcv);
7318 else
7320 gc = XCreateGC (dpy, window, mask, &xgcv);
7321 FRAME_X_DISPLAY_INFO (f)->scratch_cursor_gc = gc;
7324 x_clip_to_row (w, row, TEXT_AREA, gc);
7326 if (kind == BAR_CURSOR)
7328 int x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
7330 if (width < 0)
7331 width = FRAME_CURSOR_WIDTH (f);
7332 width = min (cursor_glyph->pixel_width, width);
7334 w->phys_cursor_width = width;
7336 /* If the character under cursor is R2L, draw the bar cursor
7337 on the right of its glyph, rather than on the left. */
7338 if ((cursor_glyph->resolved_level & 1) != 0)
7339 x += cursor_glyph->pixel_width - width;
7341 XFillRectangle (dpy, window, gc, x,
7342 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y),
7343 width, row->height);
7345 else
7347 int dummy_x, dummy_y, dummy_h;
7349 if (width < 0)
7350 width = row->height;
7352 width = min (row->height, width);
7354 get_phys_cursor_geometry (w, row, cursor_glyph, &dummy_x,
7355 &dummy_y, &dummy_h);
7357 XFillRectangle (dpy, window, gc,
7358 WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x),
7359 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y +
7360 row->height - width),
7361 w->phys_cursor_width, width);
7364 XSetClipMask (dpy, gc, None);
7369 /* RIF: Define cursor CURSOR on frame F. */
7371 static void
7372 x_define_frame_cursor (struct frame *f, Cursor cursor)
7374 if (!f->pointer_invisible
7375 && f->output_data.x->current_cursor != cursor)
7376 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), cursor);
7377 f->output_data.x->current_cursor = cursor;
7381 /* RIF: Clear area on frame F. */
7383 static void
7384 x_clear_frame_area (struct frame *f, int x, int y, int width, int height)
7386 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
7387 x, y, width, height, False);
7388 #ifdef USE_GTK
7389 /* Must queue a redraw, because scroll bars might have been cleared. */
7390 if (FRAME_GTK_WIDGET (f))
7391 gtk_widget_queue_draw (FRAME_GTK_WIDGET (f));
7392 #endif
7396 /* RIF: Draw cursor on window W. */
7398 static void
7399 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)
7401 struct frame *f = XFRAME (WINDOW_FRAME (w));
7403 if (on_p)
7405 w->phys_cursor_type = cursor_type;
7406 w->phys_cursor_on_p = 1;
7408 if (glyph_row->exact_window_width_line_p
7409 && (glyph_row->reversed_p
7410 ? (w->phys_cursor.hpos < 0)
7411 : (w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])))
7413 glyph_row->cursor_in_fringe_p = 1;
7414 draw_fringe_bitmap (w, glyph_row, glyph_row->reversed_p);
7416 else
7418 switch (cursor_type)
7420 case HOLLOW_BOX_CURSOR:
7421 x_draw_hollow_cursor (w, glyph_row);
7422 break;
7424 case FILLED_BOX_CURSOR:
7425 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
7426 break;
7428 case BAR_CURSOR:
7429 x_draw_bar_cursor (w, glyph_row, cursor_width, BAR_CURSOR);
7430 break;
7432 case HBAR_CURSOR:
7433 x_draw_bar_cursor (w, glyph_row, cursor_width, HBAR_CURSOR);
7434 break;
7436 case NO_CURSOR:
7437 w->phys_cursor_width = 0;
7438 break;
7440 default:
7441 abort ();
7445 #ifdef HAVE_X_I18N
7446 if (w == XWINDOW (f->selected_window))
7447 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMPreeditPosition))
7448 xic_set_preeditarea (w, x, y);
7449 #endif
7452 #ifndef XFlush
7453 XFlush (FRAME_X_DISPLAY (f));
7454 #endif
7458 /* Icons. */
7460 /* Make the x-window of frame F use the gnu icon bitmap. */
7463 x_bitmap_icon (struct frame *f, Lisp_Object file)
7465 ptrdiff_t bitmap_id;
7467 if (FRAME_X_WINDOW (f) == 0)
7468 return 1;
7470 /* Free up our existing icon bitmap and mask if any. */
7471 if (f->output_data.x->icon_bitmap > 0)
7472 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
7473 f->output_data.x->icon_bitmap = 0;
7475 if (STRINGP (file))
7477 #ifdef USE_GTK
7478 /* Use gtk_window_set_icon_from_file () if available,
7479 It's not restricted to bitmaps */
7480 if (xg_set_icon (f, file))
7481 return 0;
7482 #endif /* USE_GTK */
7483 bitmap_id = x_create_bitmap_from_file (f, file);
7484 x_create_bitmap_mask (f, bitmap_id);
7486 else
7488 /* Create the GNU bitmap and mask if necessary. */
7489 if (FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id < 0)
7491 ptrdiff_t rc = -1;
7493 #ifdef USE_GTK
7495 if (xg_set_icon (f, xg_default_icon_file)
7496 || xg_set_icon_from_xpm_data (f, gnu_xpm_bits))
7497 return 0;
7499 #elif defined (HAVE_XPM) && defined (HAVE_X_WINDOWS)
7501 rc = x_create_bitmap_from_xpm_data (f, gnu_xpm_bits);
7502 if (rc != -1)
7503 FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id = rc;
7505 #endif
7507 /* If all else fails, use the (black and white) xbm image. */
7508 if (rc == -1)
7510 rc = x_create_bitmap_from_data (f, (char *) gnu_xbm_bits,
7511 gnu_xbm_width, gnu_xbm_height);
7512 if (rc == -1)
7513 return 1;
7515 FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id = rc;
7516 x_create_bitmap_mask (f, FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id);
7520 /* The first time we create the GNU bitmap and mask,
7521 this increments the ref-count one extra time.
7522 As a result, the GNU bitmap and mask are never freed.
7523 That way, we don't have to worry about allocating it again. */
7524 x_reference_bitmap (f, FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id);
7526 bitmap_id = FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id;
7529 x_wm_set_icon_pixmap (f, bitmap_id);
7530 f->output_data.x->icon_bitmap = bitmap_id;
7532 return 0;
7536 /* Make the x-window of frame F use a rectangle with text.
7537 Use ICON_NAME as the text. */
7540 x_text_icon (struct frame *f, const char *icon_name)
7542 if (FRAME_X_WINDOW (f) == 0)
7543 return 1;
7546 XTextProperty text;
7547 text.value = (unsigned char *) icon_name;
7548 text.encoding = XA_STRING;
7549 text.format = 8;
7550 text.nitems = strlen (icon_name);
7551 XSetWMIconName (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f), &text);
7554 if (f->output_data.x->icon_bitmap > 0)
7555 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
7556 f->output_data.x->icon_bitmap = 0;
7557 x_wm_set_icon_pixmap (f, 0);
7559 return 0;
7562 #define X_ERROR_MESSAGE_SIZE 200
7564 /* If non-nil, this should be a string.
7565 It means catch X errors and store the error message in this string.
7567 The reason we use a stack is that x_catch_error/x_uncatch_error can
7568 be called from a signal handler.
7571 struct x_error_message_stack {
7572 char string[X_ERROR_MESSAGE_SIZE];
7573 Display *dpy;
7574 struct x_error_message_stack *prev;
7576 static struct x_error_message_stack *x_error_message;
7578 /* An X error handler which stores the error message in
7579 *x_error_message. This is called from x_error_handler if
7580 x_catch_errors is in effect. */
7582 static void
7583 x_error_catcher (Display *display, XErrorEvent *event)
7585 XGetErrorText (display, event->error_code,
7586 x_error_message->string,
7587 X_ERROR_MESSAGE_SIZE);
7590 /* Begin trapping X errors for display DPY. Actually we trap X errors
7591 for all displays, but DPY should be the display you are actually
7592 operating on.
7594 After calling this function, X protocol errors no longer cause
7595 Emacs to exit; instead, they are recorded in the string
7596 stored in *x_error_message.
7598 Calling x_check_errors signals an Emacs error if an X error has
7599 occurred since the last call to x_catch_errors or x_check_errors.
7601 Calling x_uncatch_errors resumes the normal error handling. */
7603 void
7604 x_catch_errors (Display *dpy)
7606 struct x_error_message_stack *data = xmalloc (sizeof (*data));
7608 /* Make sure any errors from previous requests have been dealt with. */
7609 XSync (dpy, False);
7611 data->dpy = dpy;
7612 data->string[0] = 0;
7613 data->prev = x_error_message;
7614 x_error_message = data;
7617 /* Undo the last x_catch_errors call.
7618 DPY should be the display that was passed to x_catch_errors. */
7620 void
7621 x_uncatch_errors (void)
7623 struct x_error_message_stack *tmp;
7625 BLOCK_INPUT;
7627 /* The display may have been closed before this function is called.
7628 Check if it is still open before calling XSync. */
7629 if (x_display_info_for_display (x_error_message->dpy) != 0)
7630 XSync (x_error_message->dpy, False);
7632 tmp = x_error_message;
7633 x_error_message = x_error_message->prev;
7634 xfree (tmp);
7635 UNBLOCK_INPUT;
7638 /* If any X protocol errors have arrived since the last call to
7639 x_catch_errors or x_check_errors, signal an Emacs error using
7640 sprintf (a buffer, FORMAT, the x error message text) as the text. */
7642 void
7643 x_check_errors (Display *dpy, const char *format)
7645 /* Make sure to catch any errors incurred so far. */
7646 XSync (dpy, False);
7648 if (x_error_message->string[0])
7650 char string[X_ERROR_MESSAGE_SIZE];
7651 memcpy (string, x_error_message->string, X_ERROR_MESSAGE_SIZE);
7652 x_uncatch_errors ();
7653 error (format, string);
7657 /* Nonzero if we had any X protocol errors
7658 since we did x_catch_errors on DPY. */
7661 x_had_errors_p (Display *dpy)
7663 /* Make sure to catch any errors incurred so far. */
7664 XSync (dpy, False);
7666 return x_error_message->string[0] != 0;
7669 /* Forget about any errors we have had, since we did x_catch_errors on DPY. */
7671 void
7672 x_clear_errors (Display *dpy)
7674 x_error_message->string[0] = 0;
7677 #if 0 /* See comment in unwind_to_catch why calling this is a bad
7678 * idea. --lorentey */
7679 /* Close off all unclosed x_catch_errors calls. */
7681 void
7682 x_fully_uncatch_errors (void)
7684 while (x_error_message)
7685 x_uncatch_errors ();
7687 #endif
7689 /* Nonzero if x_catch_errors has been done and not yet canceled. */
7692 x_catching_errors (void)
7694 return x_error_message != 0;
7697 #if 0
7698 static unsigned int x_wire_count;
7699 x_trace_wire (void)
7701 fprintf (stderr, "Lib call: %d\n", ++x_wire_count);
7703 #endif /* ! 0 */
7706 /* Handle SIGPIPE, which can happen when the connection to a server
7707 simply goes away. SIGPIPE is handled by x_connection_signal.
7708 Don't need to do anything, because the write which caused the
7709 SIGPIPE will fail, causing Xlib to invoke the X IO error handler,
7710 which will do the appropriate cleanup for us. */
7712 static void
7713 x_connection_signal (int signalnum) /* If we don't have an argument, */
7714 /* some compilers complain in signal calls. */
7716 #ifdef USG
7717 /* USG systems forget handlers when they are used;
7718 must reestablish each time */
7719 signal (signalnum, x_connection_signal);
7720 #endif /* USG */
7724 /************************************************************************
7725 Handling X errors
7726 ************************************************************************/
7728 /* Error message passed to x_connection_closed. */
7730 static char *error_msg;
7732 /* Handle the loss of connection to display DPY. ERROR_MESSAGE is
7733 the text of an error message that lead to the connection loss. */
7735 static void
7736 x_connection_closed (Display *dpy, const char *error_message)
7738 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
7739 Lisp_Object frame, tail;
7740 int idx = SPECPDL_INDEX ();
7742 error_msg = (char *) alloca (strlen (error_message) + 1);
7743 strcpy (error_msg, error_message);
7744 handling_signal = 0;
7746 /* Inhibit redisplay while frames are being deleted. */
7747 specbind (Qinhibit_redisplay, Qt);
7749 if (dpyinfo)
7751 /* Protect display from being closed when we delete the last
7752 frame on it. */
7753 dpyinfo->reference_count++;
7754 dpyinfo->terminal->reference_count++;
7757 /* First delete frames whose mini-buffers are on frames
7758 that are on the dead display. */
7759 FOR_EACH_FRAME (tail, frame)
7761 Lisp_Object minibuf_frame;
7762 minibuf_frame
7763 = WINDOW_FRAME (XWINDOW (FRAME_MINIBUF_WINDOW (XFRAME (frame))));
7764 if (FRAME_X_P (XFRAME (frame))
7765 && FRAME_X_P (XFRAME (minibuf_frame))
7766 && ! EQ (frame, minibuf_frame)
7767 && FRAME_X_DISPLAY_INFO (XFRAME (minibuf_frame)) == dpyinfo)
7768 delete_frame (frame, Qnoelisp);
7771 /* Now delete all remaining frames on the dead display.
7772 We are now sure none of these is used as the mini-buffer
7773 for another frame that we need to delete. */
7774 FOR_EACH_FRAME (tail, frame)
7775 if (FRAME_X_P (XFRAME (frame))
7776 && FRAME_X_DISPLAY_INFO (XFRAME (frame)) == dpyinfo)
7778 /* Set this to t so that delete_frame won't get confused
7779 trying to find a replacement. */
7780 KVAR (FRAME_KBOARD (XFRAME (frame)), Vdefault_minibuffer_frame) = Qt;
7781 delete_frame (frame, Qnoelisp);
7784 /* If DPYINFO is null, this means we didn't open the display in the
7785 first place, so don't try to close it. */
7786 if (dpyinfo)
7788 /* We can not call XtCloseDisplay here because it calls XSync.
7789 XSync inside the error handler apparently hangs Emacs. On
7790 current Xt versions, this isn't needed either. */
7791 #ifdef USE_GTK
7792 /* A long-standing GTK bug prevents proper disconnect handling
7793 (https://bugzilla.gnome.org/show_bug.cgi?id=85715). Once,
7794 the resulting Glib error message loop filled a user's disk.
7795 To avoid this, kill Emacs unconditionally on disconnect. */
7796 shut_down_emacs (0, 0, Qnil);
7797 fprintf (stderr, "%s\n\
7798 When compiled with GTK, Emacs cannot recover from X disconnects.\n\
7799 This is a GTK bug: https://bugzilla.gnome.org/show_bug.cgi?id=85715\n\
7800 For details, see etc/PROBLEMS.\n",
7801 error_msg);
7802 abort ();
7803 #endif /* USE_GTK */
7805 /* Indicate that this display is dead. */
7806 dpyinfo->display = 0;
7808 dpyinfo->reference_count--;
7809 dpyinfo->terminal->reference_count--;
7810 if (dpyinfo->reference_count != 0)
7811 /* We have just closed all frames on this display. */
7812 abort ();
7815 Lisp_Object tmp;
7816 XSETTERMINAL (tmp, dpyinfo->terminal);
7817 Fdelete_terminal (tmp, Qnoelisp);
7821 if (terminal_list == 0)
7823 fprintf (stderr, "%s\n", error_msg);
7824 Fkill_emacs (make_number (70));
7825 /* NOTREACHED */
7828 /* Ordinary stack unwind doesn't deal with these. */
7829 #ifdef SIGIO
7830 sigunblock (sigmask (SIGIO));
7831 #endif
7832 sigunblock (sigmask (SIGALRM));
7833 TOTALLY_UNBLOCK_INPUT;
7835 unbind_to (idx, Qnil);
7836 clear_waiting_for_input ();
7838 /* Tell GCC not to suggest attribute 'noreturn' for this function. */
7839 IF_LINT (if (! terminal_list) return; )
7841 /* Here, we absolutely have to use a non-local exit (e.g. signal, throw,
7842 longjmp), because returning from this function would get us back into
7843 Xlib's code which will directly call `exit'. */
7844 error ("%s", error_msg);
7847 /* We specifically use it before defining it, so that gcc doesn't inline it,
7848 otherwise gdb doesn't know how to properly put a breakpoint on it. */
7849 static void x_error_quitter (Display *, XErrorEvent *);
7851 /* This is the first-level handler for X protocol errors.
7852 It calls x_error_quitter or x_error_catcher. */
7854 static int
7855 x_error_handler (Display *display, XErrorEvent *event)
7857 if (x_error_message)
7858 x_error_catcher (display, event);
7859 else
7860 x_error_quitter (display, event);
7861 return 0;
7864 /* This is the usual handler for X protocol errors.
7865 It kills all frames on the display that we got the error for.
7866 If that was the only one, it prints an error message and kills Emacs. */
7868 /* .gdbinit puts a breakpoint here, so make sure it is not inlined. */
7870 /* On older GCC versions, just putting x_error_quitter
7871 after x_error_handler prevents inlining into the former. */
7873 static void NO_INLINE
7874 x_error_quitter (Display *display, XErrorEvent *event)
7876 char buf[256], buf1[356];
7878 /* Ignore BadName errors. They can happen because of fonts
7879 or colors that are not defined. */
7881 if (event->error_code == BadName)
7882 return;
7884 /* Note that there is no real way portable across R3/R4 to get the
7885 original error handler. */
7887 XGetErrorText (display, event->error_code, buf, sizeof (buf));
7888 sprintf (buf1, "X protocol error: %s on protocol request %d",
7889 buf, event->request_code);
7890 x_connection_closed (display, buf1);
7894 /* This is the handler for X IO errors, always.
7895 It kills all frames on the display that we lost touch with.
7896 If that was the only one, it prints an error message and kills Emacs. */
7898 static int
7899 x_io_error_quitter (Display *display)
7901 char buf[256];
7903 sprintf (buf, "Connection lost to X server `%s'", DisplayString (display));
7904 x_connection_closed (display, buf);
7905 return 0;
7908 /* Changing the font of the frame. */
7910 /* Give frame F the font FONT-OBJECT as its default font. The return
7911 value is FONT-OBJECT. FONTSET is an ID of the fontset for the
7912 frame. If it is negative, generate a new fontset from
7913 FONT-OBJECT. */
7915 Lisp_Object
7916 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
7918 struct font *font = XFONT_OBJECT (font_object);
7920 if (fontset < 0)
7921 fontset = fontset_from_font (font_object);
7922 FRAME_FONTSET (f) = fontset;
7923 if (FRAME_FONT (f) == font)
7924 /* This font is already set in frame F. There's nothing more to
7925 do. */
7926 return font_object;
7928 FRAME_FONT (f) = font;
7929 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
7930 FRAME_COLUMN_WIDTH (f) = font->average_width;
7931 FRAME_SPACE_WIDTH (f) = font->space_width;
7932 FRAME_LINE_HEIGHT (f) = FONT_HEIGHT (font);
7934 compute_fringe_widths (f, 1);
7936 /* Compute the scroll bar width in character columns. */
7937 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
7939 int wid = FRAME_COLUMN_WIDTH (f);
7940 FRAME_CONFIG_SCROLL_BAR_COLS (f)
7941 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid-1) / wid;
7943 else
7945 int wid = FRAME_COLUMN_WIDTH (f);
7946 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
7949 if (FRAME_X_WINDOW (f) != 0)
7951 /* Don't change the size of a tip frame; there's no point in
7952 doing it because it's done in Fx_show_tip, and it leads to
7953 problems because the tip frame has no widget. */
7954 if (NILP (tip_frame) || XFRAME (tip_frame) != f)
7955 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
7958 #ifdef HAVE_X_I18N
7959 if (FRAME_XIC (f)
7960 && (FRAME_XIC_STYLE (f) & (XIMPreeditPosition | XIMStatusArea)))
7962 BLOCK_INPUT;
7963 xic_set_xfontset (f, SSDATA (fontset_ascii (fontset)));
7964 UNBLOCK_INPUT;
7966 #endif
7968 return font_object;
7972 /***********************************************************************
7973 X Input Methods
7974 ***********************************************************************/
7976 #ifdef HAVE_X_I18N
7978 #ifdef HAVE_X11R6
7980 /* XIM destroy callback function, which is called whenever the
7981 connection to input method XIM dies. CLIENT_DATA contains a
7982 pointer to the x_display_info structure corresponding to XIM. */
7984 static void
7985 xim_destroy_callback (XIM xim, XPointer client_data, XPointer call_data)
7987 struct x_display_info *dpyinfo = (struct x_display_info *) client_data;
7988 Lisp_Object frame, tail;
7990 BLOCK_INPUT;
7992 /* No need to call XDestroyIC.. */
7993 FOR_EACH_FRAME (tail, frame)
7995 struct frame *f = XFRAME (frame);
7996 if (FRAME_X_P (f) && FRAME_X_DISPLAY_INFO (f) == dpyinfo)
7998 FRAME_XIC (f) = NULL;
7999 xic_free_xfontset (f);
8003 /* No need to call XCloseIM. */
8004 dpyinfo->xim = NULL;
8005 XFree (dpyinfo->xim_styles);
8006 UNBLOCK_INPUT;
8009 #endif /* HAVE_X11R6 */
8011 #ifdef HAVE_X11R6
8012 /* This isn't prototyped in OSF 5.0 or 5.1a. */
8013 extern char *XSetIMValues (XIM, ...);
8014 #endif
8016 /* Open the connection to the XIM server on display DPYINFO.
8017 RESOURCE_NAME is the resource name Emacs uses. */
8019 static void
8020 xim_open_dpy (struct x_display_info *dpyinfo, char *resource_name)
8022 XIM xim;
8024 #ifdef HAVE_XIM
8025 if (use_xim)
8027 if (dpyinfo->xim)
8028 XCloseIM (dpyinfo->xim);
8029 xim = XOpenIM (dpyinfo->display, dpyinfo->xrdb, resource_name,
8030 emacs_class);
8031 dpyinfo->xim = xim;
8033 if (xim)
8035 #ifdef HAVE_X11R6
8036 XIMCallback destroy;
8037 #endif
8039 /* Get supported styles and XIM values. */
8040 XGetIMValues (xim, XNQueryInputStyle, &dpyinfo->xim_styles, NULL);
8042 #ifdef HAVE_X11R6
8043 destroy.callback = xim_destroy_callback;
8044 destroy.client_data = (XPointer)dpyinfo;
8045 XSetIMValues (xim, XNDestroyCallback, &destroy, NULL);
8046 #endif
8050 else
8051 #endif /* HAVE_XIM */
8052 dpyinfo->xim = NULL;
8056 #ifdef HAVE_X11R6_XIM
8058 /* XIM instantiate callback function, which is called whenever an XIM
8059 server is available. DISPLAY is the display of the XIM.
8060 CLIENT_DATA contains a pointer to an xim_inst_t structure created
8061 when the callback was registered. */
8063 static void
8064 xim_instantiate_callback (Display *display, XPointer client_data, XPointer call_data)
8066 struct xim_inst_t *xim_inst = (struct xim_inst_t *) client_data;
8067 struct x_display_info *dpyinfo = xim_inst->dpyinfo;
8069 /* We don't support multiple XIM connections. */
8070 if (dpyinfo->xim)
8071 return;
8073 xim_open_dpy (dpyinfo, xim_inst->resource_name);
8075 /* Create XIC for the existing frames on the same display, as long
8076 as they have no XIC. */
8077 if (dpyinfo->xim && dpyinfo->reference_count > 0)
8079 Lisp_Object tail, frame;
8081 BLOCK_INPUT;
8082 FOR_EACH_FRAME (tail, frame)
8084 struct frame *f = XFRAME (frame);
8086 if (FRAME_X_P (f)
8087 && FRAME_X_DISPLAY_INFO (f) == xim_inst->dpyinfo)
8088 if (FRAME_XIC (f) == NULL)
8090 create_frame_xic (f);
8091 if (FRAME_XIC_STYLE (f) & XIMStatusArea)
8092 xic_set_statusarea (f);
8093 if (FRAME_XIC_STYLE (f) & XIMPreeditPosition)
8095 struct window *w = XWINDOW (f->selected_window);
8096 xic_set_preeditarea (w, w->cursor.x, w->cursor.y);
8101 UNBLOCK_INPUT;
8105 #endif /* HAVE_X11R6_XIM */
8108 /* Open a connection to the XIM server on display DPYINFO.
8109 RESOURCE_NAME is the resource name for Emacs. On X11R5, open the
8110 connection only at the first time. On X11R6, open the connection
8111 in the XIM instantiate callback function. */
8113 static void
8114 xim_initialize (struct x_display_info *dpyinfo, char *resource_name)
8116 dpyinfo->xim = NULL;
8117 #ifdef HAVE_XIM
8118 if (use_xim)
8120 #ifdef HAVE_X11R6_XIM
8121 struct xim_inst_t *xim_inst;
8122 ptrdiff_t len;
8124 xim_inst = (struct xim_inst_t *) xmalloc (sizeof (struct xim_inst_t));
8125 dpyinfo->xim_callback_data = xim_inst;
8126 xim_inst->dpyinfo = dpyinfo;
8127 len = strlen (resource_name);
8128 xim_inst->resource_name = (char *) xmalloc (len + 1);
8129 memcpy (xim_inst->resource_name, resource_name, len + 1);
8130 XRegisterIMInstantiateCallback (dpyinfo->display, dpyinfo->xrdb,
8131 resource_name, emacs_class,
8132 xim_instantiate_callback,
8133 /* This is XPointer in XFree86
8134 but (XPointer *) on Tru64, at
8135 least, hence the configure test. */
8136 (XRegisterIMInstantiateCallback_arg6) xim_inst);
8137 #else /* not HAVE_X11R6_XIM */
8138 xim_open_dpy (dpyinfo, resource_name);
8139 #endif /* not HAVE_X11R6_XIM */
8141 #endif /* HAVE_XIM */
8145 /* Close the connection to the XIM server on display DPYINFO. */
8147 static void
8148 xim_close_dpy (struct x_display_info *dpyinfo)
8150 #ifdef HAVE_XIM
8151 if (use_xim)
8153 #ifdef HAVE_X11R6_XIM
8154 if (dpyinfo->display)
8155 XUnregisterIMInstantiateCallback (dpyinfo->display, dpyinfo->xrdb,
8156 NULL, emacs_class,
8157 xim_instantiate_callback, NULL);
8158 xfree (dpyinfo->xim_callback_data->resource_name);
8159 xfree (dpyinfo->xim_callback_data);
8160 #endif /* HAVE_X11R6_XIM */
8161 if (dpyinfo->display)
8162 XCloseIM (dpyinfo->xim);
8163 dpyinfo->xim = NULL;
8164 XFree (dpyinfo->xim_styles);
8166 #endif /* HAVE_XIM */
8169 #endif /* not HAVE_X11R6_XIM */
8173 /* Calculate the absolute position in frame F
8174 from its current recorded position values and gravity. */
8176 static void
8177 x_calc_absolute_position (struct frame *f)
8179 int flags = f->size_hint_flags;
8181 /* We have nothing to do if the current position
8182 is already for the top-left corner. */
8183 if (! ((flags & XNegative) || (flags & YNegative)))
8184 return;
8186 /* Treat negative positions as relative to the leftmost bottommost
8187 position that fits on the screen. */
8188 if (flags & XNegative)
8189 f->left_pos = x_display_pixel_width (FRAME_X_DISPLAY_INFO (f))
8190 - FRAME_PIXEL_WIDTH (f) + f->left_pos;
8193 int height = FRAME_PIXEL_HEIGHT (f);
8195 #if defined USE_X_TOOLKIT && defined USE_MOTIF
8196 /* Something is fishy here. When using Motif, starting Emacs with
8197 `-g -0-0', the frame appears too low by a few pixels.
8199 This seems to be so because initially, while Emacs is starting,
8200 the column widget's height and the frame's pixel height are
8201 different. The column widget's height is the right one. In
8202 later invocations, when Emacs is up, the frame's pixel height
8203 is right, though.
8205 It's not obvious where the initial small difference comes from.
8206 2000-12-01, gerd. */
8208 XtVaGetValues (f->output_data.x->column_widget, XtNheight, &height, NULL);
8209 #endif
8211 if (flags & YNegative)
8212 f->top_pos = x_display_pixel_height (FRAME_X_DISPLAY_INFO (f))
8213 - height + f->top_pos;
8216 /* The left_pos and top_pos
8217 are now relative to the top and left screen edges,
8218 so the flags should correspond. */
8219 f->size_hint_flags &= ~ (XNegative | YNegative);
8222 /* CHANGE_GRAVITY is 1 when calling from Fset_frame_position,
8223 to really change the position, and 0 when calling from
8224 x_make_frame_visible (in that case, XOFF and YOFF are the current
8225 position values). It is -1 when calling from x_set_frame_parameters,
8226 which means, do adjust for borders but don't change the gravity. */
8228 void
8229 x_set_offset (struct frame *f, register int xoff, register int yoff, int change_gravity)
8231 int modified_top, modified_left;
8233 if (change_gravity > 0)
8235 FRAME_X_OUTPUT (f)->left_before_move = f->left_pos;
8236 FRAME_X_OUTPUT (f)->top_before_move = f->top_pos;
8238 f->top_pos = yoff;
8239 f->left_pos = xoff;
8240 f->size_hint_flags &= ~ (XNegative | YNegative);
8241 if (xoff < 0)
8242 f->size_hint_flags |= XNegative;
8243 if (yoff < 0)
8244 f->size_hint_flags |= YNegative;
8245 f->win_gravity = NorthWestGravity;
8247 x_calc_absolute_position (f);
8249 BLOCK_INPUT;
8250 x_wm_set_size_hint (f, (long) 0, 0);
8252 modified_left = f->left_pos;
8253 modified_top = f->top_pos;
8255 if (change_gravity != 0 && FRAME_X_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A)
8257 /* Some WMs (twm, wmaker at least) has an offset that is smaller
8258 than the WM decorations. So we use the calculated offset instead
8259 of the WM decoration sizes here (x/y_pixels_outer_diff). */
8260 modified_left += FRAME_X_OUTPUT (f)->move_offset_left;
8261 modified_top += FRAME_X_OUTPUT (f)->move_offset_top;
8264 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8265 modified_left, modified_top);
8267 x_sync_with_move (f, f->left_pos, f->top_pos,
8268 FRAME_X_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN
8269 ? 1 : 0);
8271 /* change_gravity is non-zero when this function is called from Lisp to
8272 programmatically move a frame. In that case, we call
8273 x_check_expected_move to discover if we have a "Type A" or "Type B"
8274 window manager, and, for a "Type A" window manager, adjust the position
8275 of the frame.
8277 We call x_check_expected_move if a programmatic move occurred, and
8278 either the window manager type (A/B) is unknown or it is Type A but we
8279 need to compute the top/left offset adjustment for this frame. */
8281 if (change_gravity != 0 &&
8282 (FRAME_X_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN
8283 || (FRAME_X_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A
8284 && (FRAME_X_OUTPUT (f)->move_offset_left == 0
8285 && FRAME_X_OUTPUT (f)->move_offset_top == 0))))
8286 x_check_expected_move (f, modified_left, modified_top);
8288 UNBLOCK_INPUT;
8291 /* Return non-zero if _NET_SUPPORTING_WM_CHECK window exists and _NET_SUPPORTED
8292 on the root window for frame F contains ATOMNAME.
8293 This is how a WM check shall be done according to the Window Manager
8294 Specification/Extended Window Manager Hints at
8295 http://freedesktop.org/wiki/Specifications/wm-spec. */
8297 static int
8298 wm_supports (struct frame *f, Atom want_atom)
8300 Atom actual_type;
8301 unsigned long actual_size, bytes_remaining;
8302 int i, rc, actual_format;
8303 Window wmcheck_window;
8304 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8305 Window target_window = dpyinfo->root_window;
8306 long max_len = 65536;
8307 Display *dpy = FRAME_X_DISPLAY (f);
8308 unsigned char *tmp_data = NULL;
8309 Atom target_type = XA_WINDOW;
8311 BLOCK_INPUT;
8313 x_catch_errors (dpy);
8314 rc = XGetWindowProperty (dpy, target_window,
8315 dpyinfo->Xatom_net_supporting_wm_check,
8316 0, max_len, False, target_type,
8317 &actual_type, &actual_format, &actual_size,
8318 &bytes_remaining, &tmp_data);
8320 if (rc != Success || actual_type != XA_WINDOW || x_had_errors_p (dpy))
8322 if (tmp_data) XFree (tmp_data);
8323 x_uncatch_errors ();
8324 UNBLOCK_INPUT;
8325 return 0;
8328 wmcheck_window = *(Window *) tmp_data;
8329 XFree (tmp_data);
8331 /* Check if window exists. */
8332 XSelectInput (dpy, wmcheck_window, StructureNotifyMask);
8333 x_sync (f);
8334 if (x_had_errors_p (dpy))
8336 x_uncatch_errors ();
8337 UNBLOCK_INPUT;
8338 return 0;
8341 if (dpyinfo->net_supported_window != wmcheck_window)
8343 /* Window changed, reload atoms */
8344 if (dpyinfo->net_supported_atoms != NULL)
8345 XFree (dpyinfo->net_supported_atoms);
8346 dpyinfo->net_supported_atoms = NULL;
8347 dpyinfo->nr_net_supported_atoms = 0;
8348 dpyinfo->net_supported_window = 0;
8350 target_type = XA_ATOM;
8351 tmp_data = NULL;
8352 rc = XGetWindowProperty (dpy, target_window,
8353 dpyinfo->Xatom_net_supported,
8354 0, max_len, False, target_type,
8355 &actual_type, &actual_format, &actual_size,
8356 &bytes_remaining, &tmp_data);
8358 if (rc != Success || actual_type != XA_ATOM || x_had_errors_p (dpy))
8360 if (tmp_data) XFree (tmp_data);
8361 x_uncatch_errors ();
8362 UNBLOCK_INPUT;
8363 return 0;
8366 dpyinfo->net_supported_atoms = (Atom *)tmp_data;
8367 dpyinfo->nr_net_supported_atoms = actual_size;
8368 dpyinfo->net_supported_window = wmcheck_window;
8371 rc = 0;
8373 for (i = 0; rc == 0 && i < dpyinfo->nr_net_supported_atoms; ++i)
8374 rc = dpyinfo->net_supported_atoms[i] == want_atom;
8376 x_uncatch_errors ();
8377 UNBLOCK_INPUT;
8379 return rc;
8382 static void
8383 set_wm_state (Lisp_Object frame, int add, Atom atom, Atom value)
8385 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (XFRAME (frame));
8387 x_send_client_event (frame, make_number (0), frame,
8388 dpyinfo->Xatom_net_wm_state,
8389 make_number (32),
8390 /* 1 = add, 0 = remove */
8391 Fcons
8392 (make_number (add ? 1 : 0),
8393 Fcons
8394 (make_fixnum_or_float (atom),
8395 value != 0
8396 ? Fcons (make_fixnum_or_float (value), Qnil)
8397 : Qnil)));
8400 void
8401 x_set_sticky (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
8403 Lisp_Object frame;
8404 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8406 XSETFRAME (frame, f);
8408 set_wm_state (frame, NILP (new_value) ? 0 : 1,
8409 dpyinfo->Xatom_net_wm_state_sticky, None);
8412 /* Return the current _NET_WM_STATE.
8413 SIZE_STATE is set to one of the FULLSCREEN_* values.
8414 STICKY is set to 1 if the sticky state is set, 0 if not. */
8416 static void
8417 get_current_wm_state (struct frame *f,
8418 Window window,
8419 int *size_state,
8420 int *sticky)
8422 Atom actual_type;
8423 unsigned long actual_size, bytes_remaining;
8424 int i, rc, actual_format;
8425 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8426 long max_len = 65536;
8427 Display *dpy = FRAME_X_DISPLAY (f);
8428 unsigned char *tmp_data = NULL;
8429 Atom target_type = XA_ATOM;
8431 *sticky = 0;
8432 *size_state = FULLSCREEN_NONE;
8434 BLOCK_INPUT;
8435 x_catch_errors (dpy);
8436 rc = XGetWindowProperty (dpy, window, dpyinfo->Xatom_net_wm_state,
8437 0, max_len, False, target_type,
8438 &actual_type, &actual_format, &actual_size,
8439 &bytes_remaining, &tmp_data);
8441 if (rc != Success || actual_type != target_type || x_had_errors_p (dpy))
8443 if (tmp_data) XFree (tmp_data);
8444 x_uncatch_errors ();
8445 UNBLOCK_INPUT;
8446 return;
8449 x_uncatch_errors ();
8451 for (i = 0; i < actual_size; ++i)
8453 Atom a = ((Atom*)tmp_data)[i];
8454 if (a == dpyinfo->Xatom_net_wm_state_maximized_horz)
8456 if (*size_state == FULLSCREEN_HEIGHT)
8457 *size_state = FULLSCREEN_MAXIMIZED;
8458 else
8459 *size_state = FULLSCREEN_WIDTH;
8461 else if (a == dpyinfo->Xatom_net_wm_state_maximized_vert)
8463 if (*size_state == FULLSCREEN_WIDTH)
8464 *size_state = FULLSCREEN_MAXIMIZED;
8465 else
8466 *size_state = FULLSCREEN_HEIGHT;
8468 else if (a == dpyinfo->Xatom_net_wm_state_fullscreen)
8469 *size_state = FULLSCREEN_BOTH;
8470 else if (a == dpyinfo->Xatom_net_wm_state_sticky)
8471 *sticky = 1;
8474 if (tmp_data) XFree (tmp_data);
8475 UNBLOCK_INPUT;
8478 /* Do fullscreen as specified in extended window manager hints */
8480 static int
8481 do_ewmh_fullscreen (struct frame *f)
8483 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8484 int have_net_atom = wm_supports (f, dpyinfo->Xatom_net_wm_state);
8485 int cur, dummy;
8487 get_current_wm_state (f, FRAME_OUTER_WINDOW (f), &cur, &dummy);
8489 /* Some window managers don't say they support _NET_WM_STATE, but they do say
8490 they support _NET_WM_STATE_FULLSCREEN. Try that also. */
8491 if (!have_net_atom)
8492 have_net_atom = wm_supports (f, dpyinfo->Xatom_net_wm_state_fullscreen);
8494 if (have_net_atom && cur != f->want_fullscreen)
8496 Lisp_Object frame;
8498 XSETFRAME (frame, f);
8500 /* Keep number of calls to set_wm_state as low as possible.
8501 Some window managers, or possible Gtk+, hangs when too many
8502 are sent at once. */
8503 switch (f->want_fullscreen)
8505 case FULLSCREEN_BOTH:
8506 if (cur == FULLSCREEN_WIDTH || cur == FULLSCREEN_MAXIMIZED
8507 || cur == FULLSCREEN_HEIGHT)
8508 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_maximized_horz,
8509 dpyinfo->Xatom_net_wm_state_maximized_vert);
8510 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_fullscreen, None);
8511 break;
8512 case FULLSCREEN_WIDTH:
8513 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_HEIGHT
8514 || cur == FULLSCREEN_MAXIMIZED)
8515 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen,
8516 dpyinfo->Xatom_net_wm_state_maximized_vert);
8517 if (cur != FULLSCREEN_MAXIMIZED)
8518 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_maximized_horz, None);
8519 break;
8520 case FULLSCREEN_HEIGHT:
8521 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_WIDTH
8522 || cur == FULLSCREEN_MAXIMIZED)
8523 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen,
8524 dpyinfo->Xatom_net_wm_state_maximized_horz);
8525 if (cur != FULLSCREEN_MAXIMIZED)
8526 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_maximized_vert, None);
8527 break;
8528 case FULLSCREEN_MAXIMIZED:
8529 if (cur == FULLSCREEN_BOTH)
8530 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen, None);
8531 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_maximized_horz,
8532 dpyinfo->Xatom_net_wm_state_maximized_vert);
8533 break;
8534 case FULLSCREEN_NONE:
8535 if (cur == FULLSCREEN_BOTH)
8536 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen, None);
8537 else
8538 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_maximized_horz,
8539 dpyinfo->Xatom_net_wm_state_maximized_vert);
8542 f->want_fullscreen = FULLSCREEN_NONE;
8546 return have_net_atom;
8549 static void
8550 XTfullscreen_hook (FRAME_PTR f)
8552 if (f->async_visible)
8554 BLOCK_INPUT;
8555 x_check_fullscreen (f);
8556 x_sync (f);
8557 UNBLOCK_INPUT;
8562 static void
8563 x_handle_net_wm_state (struct frame *f, XPropertyEvent *event)
8565 int value = FULLSCREEN_NONE;
8566 Lisp_Object lval;
8567 int sticky = 0;
8569 get_current_wm_state (f, event->window, &value, &sticky);
8570 lval = Qnil;
8571 switch (value)
8573 case FULLSCREEN_WIDTH:
8574 lval = Qfullwidth;
8575 break;
8576 case FULLSCREEN_HEIGHT:
8577 lval = Qfullheight;
8578 break;
8579 case FULLSCREEN_BOTH:
8580 lval = Qfullboth;
8581 break;
8582 case FULLSCREEN_MAXIMIZED:
8583 lval = Qmaximized;
8584 break;
8587 store_frame_param (f, Qfullscreen, lval);
8588 store_frame_param (f, Qsticky, sticky ? Qt : Qnil);
8591 /* Check if we need to resize the frame due to a fullscreen request.
8592 If so needed, resize the frame. */
8593 static void
8594 x_check_fullscreen (struct frame *f)
8596 if (do_ewmh_fullscreen (f))
8597 return;
8599 if (f->output_data.x->parent_desc != FRAME_X_DISPLAY_INFO (f)->root_window)
8600 return; /* Only fullscreen without WM or with EWM hints (above). */
8602 /* Setting fullscreen to nil doesn't do anything. We could save the
8603 last non-fullscreen size and restore it, but it seems like a
8604 lot of work for this unusual case (no window manager running). */
8606 if (f->want_fullscreen != FULLSCREEN_NONE)
8608 int width = FRAME_PIXEL_WIDTH (f), height = FRAME_PIXEL_HEIGHT (f);
8609 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8611 switch (f->want_fullscreen)
8613 /* No difference between these two when there is no WM */
8614 case FULLSCREEN_BOTH:
8615 case FULLSCREEN_MAXIMIZED:
8616 width = x_display_pixel_width (dpyinfo);
8617 height = x_display_pixel_height (dpyinfo);
8618 break;
8619 case FULLSCREEN_WIDTH:
8620 width = x_display_pixel_width (dpyinfo);
8621 break;
8622 case FULLSCREEN_HEIGHT:
8623 height = x_display_pixel_height (dpyinfo);
8626 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8627 width, height);
8631 /* This function is called by x_set_offset to determine whether the window
8632 manager interfered with the positioning of the frame. Type A window
8633 managers position the surrounding window manager decorations a small
8634 amount above and left of the user-supplied position. Type B window
8635 managers position the surrounding window manager decorations at the
8636 user-specified position. If we detect a Type A window manager, we
8637 compensate by moving the window right and down by the proper amount. */
8639 static void
8640 x_check_expected_move (struct frame *f, int expected_left, int expected_top)
8642 int current_left = 0, current_top = 0;
8644 /* x_real_positions returns the left and top offsets of the outermost
8645 window manager window around the frame. */
8647 x_real_positions (f, &current_left, &current_top);
8649 if (current_left != expected_left || current_top != expected_top)
8651 /* It's a "Type A" window manager. */
8653 int adjusted_left;
8654 int adjusted_top;
8656 FRAME_X_DISPLAY_INFO (f)->wm_type = X_WMTYPE_A;
8657 FRAME_X_OUTPUT (f)->move_offset_left = expected_left - current_left;
8658 FRAME_X_OUTPUT (f)->move_offset_top = expected_top - current_top;
8660 /* Now fix the mispositioned frame's location. */
8662 adjusted_left = expected_left + FRAME_X_OUTPUT (f)->move_offset_left;
8663 adjusted_top = expected_top + FRAME_X_OUTPUT (f)->move_offset_top;
8665 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8666 adjusted_left, adjusted_top);
8668 x_sync_with_move (f, expected_left, expected_top, 0);
8670 else
8671 /* It's a "Type B" window manager. We don't have to adjust the
8672 frame's position. */
8674 FRAME_X_DISPLAY_INFO (f)->wm_type = X_WMTYPE_B;
8678 /* Wait for XGetGeometry to return up-to-date position information for a
8679 recently-moved frame. Call this immediately after calling XMoveWindow.
8680 If FUZZY is non-zero, then LEFT and TOP are just estimates of where the
8681 frame has been moved to, so we use a fuzzy position comparison instead
8682 of an exact comparison. */
8684 static void
8685 x_sync_with_move (struct frame *f, int left, int top, int fuzzy)
8687 int count = 0;
8689 while (count++ < 50)
8691 int current_left = 0, current_top = 0;
8693 /* In theory, this call to XSync only needs to happen once, but in
8694 practice, it doesn't seem to work, hence the need for the surrounding
8695 loop. */
8697 XSync (FRAME_X_DISPLAY (f), False);
8698 x_real_positions (f, &current_left, &current_top);
8700 if (fuzzy)
8702 /* The left fuzz-factor is 10 pixels. The top fuzz-factor is 40
8703 pixels. */
8705 if (eabs (current_left - left) <= 10
8706 && eabs (current_top - top) <= 40)
8707 return;
8709 else if (current_left == left && current_top == top)
8710 return;
8713 /* As a last resort, just wait 0.5 seconds and hope that XGetGeometry
8714 will then return up-to-date position info. */
8716 wait_reading_process_output (0, 500000, 0, 0, Qnil, NULL, 0);
8720 /* Wait for an event on frame F matching EVENTTYPE. */
8721 void
8722 x_wait_for_event (struct frame *f, int eventtype)
8724 int level = interrupt_input_blocked;
8726 SELECT_TYPE fds;
8727 EMACS_TIME tmo, tmo_at, time_now;
8728 int fd = ConnectionNumber (FRAME_X_DISPLAY (f));
8730 pending_event_wait.f = f;
8731 pending_event_wait.eventtype = eventtype;
8733 /* Set timeout to 0.1 second. Hopefully not noticable.
8734 Maybe it should be configurable. */
8735 EMACS_SET_SECS_USECS (tmo, 0, 100000);
8736 EMACS_GET_TIME (tmo_at);
8737 EMACS_ADD_TIME (tmo_at, tmo_at, tmo);
8739 while (pending_event_wait.eventtype)
8741 interrupt_input_pending = 1;
8742 TOTALLY_UNBLOCK_INPUT;
8743 /* XTread_socket is called after unblock. */
8744 BLOCK_INPUT;
8745 interrupt_input_blocked = level;
8747 FD_ZERO (&fds);
8748 FD_SET (fd, &fds);
8750 EMACS_GET_TIME (time_now);
8751 EMACS_SUB_TIME (tmo, tmo_at, time_now);
8753 if (EMACS_TIME_NEG_P (tmo) || select (fd+1, &fds, NULL, NULL, &tmo) == 0)
8754 break; /* Timeout */
8756 pending_event_wait.f = 0;
8757 pending_event_wait.eventtype = 0;
8761 /* Change the size of frame F's X window to COLS/ROWS in the case F
8762 doesn't have a widget. If CHANGE_GRAVITY is 1, we change to
8763 top-left-corner window gravity for this size change and subsequent
8764 size changes. Otherwise we leave the window gravity unchanged. */
8766 static void
8767 x_set_window_size_1 (struct frame *f, int change_gravity, int cols, int rows)
8769 int pixelwidth, pixelheight;
8771 check_frame_size (f, &rows, &cols);
8772 f->scroll_bar_actual_width
8773 = (!FRAME_HAS_VERTICAL_SCROLL_BARS (f)
8775 : FRAME_CONFIG_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f));
8777 compute_fringe_widths (f, 0);
8779 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, cols)
8780 + FRAME_TOOLBAR_WIDTH (f);
8781 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows)
8782 + FRAME_MENUBAR_HEIGHT (f) + FRAME_TOOLBAR_HEIGHT (f);
8784 if (change_gravity) f->win_gravity = NorthWestGravity;
8785 x_wm_set_size_hint (f, (long) 0, 0);
8786 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8787 pixelwidth, pixelheight);
8790 /* We've set {FRAME,PIXEL}_{WIDTH,HEIGHT} to the values we hope to
8791 receive in the ConfigureNotify event; if we get what we asked
8792 for, then the event won't cause the screen to become garbaged, so
8793 we have to make sure to do it here. */
8794 SET_FRAME_GARBAGED (f);
8796 /* Now, strictly speaking, we can't be sure that this is accurate,
8797 but the window manager will get around to dealing with the size
8798 change request eventually, and we'll hear how it went when the
8799 ConfigureNotify event gets here.
8801 We could just not bother storing any of this information here,
8802 and let the ConfigureNotify event set everything up, but that
8803 might be kind of confusing to the Lisp code, since size changes
8804 wouldn't be reported in the frame parameters until some random
8805 point in the future when the ConfigureNotify event arrives.
8807 We pass 1 for DELAY since we can't run Lisp code inside of
8808 a BLOCK_INPUT. */
8810 /* But the ConfigureNotify may in fact never arrive, and then this is
8811 not right if the frame is visible. Instead wait (with timeout)
8812 for the ConfigureNotify. */
8813 if (f->async_visible)
8814 x_wait_for_event (f, ConfigureNotify);
8815 else
8817 change_frame_size (f, rows, cols, 0, 1, 0);
8818 FRAME_PIXEL_WIDTH (f) = pixelwidth;
8819 FRAME_PIXEL_HEIGHT (f) = pixelheight;
8820 x_sync (f);
8825 /* Call this to change the size of frame F's x-window.
8826 If CHANGE_GRAVITY is 1, we change to top-left-corner window gravity
8827 for this size change and subsequent size changes.
8828 Otherwise we leave the window gravity unchanged. */
8830 void
8831 x_set_window_size (struct frame *f, int change_gravity, int cols, int rows)
8833 BLOCK_INPUT;
8835 if (NILP (tip_frame) || XFRAME (tip_frame) != f)
8837 int r, c;
8839 /* When the frame is maximized/fullscreen or running under for
8840 example Xmonad, x_set_window_size_1 will be a no-op.
8841 In that case, the right thing to do is extend rows/cols to
8842 the current frame size. We do that first if x_set_window_size_1
8843 turns out to not be a no-op (there is no way to know).
8844 The size will be adjusted again if the frame gets a
8845 ConfigureNotify event as a result of x_set_window_size. */
8846 int pixelh = FRAME_PIXEL_HEIGHT (f);
8847 #ifdef USE_X_TOOLKIT
8848 /* The menu bar is not part of text lines. The tool bar
8849 is however. */
8850 pixelh -= FRAME_MENUBAR_HEIGHT (f);
8851 #endif
8852 r = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, pixelh);
8853 /* Update f->scroll_bar_actual_width because it is used in
8854 FRAME_PIXEL_WIDTH_TO_TEXT_COLS. */
8855 f->scroll_bar_actual_width
8856 = FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f);
8857 c = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, FRAME_PIXEL_WIDTH (f));
8858 change_frame_size (f, r, c, 0, 1, 0);
8861 #ifdef USE_GTK
8862 if (FRAME_GTK_WIDGET (f))
8863 xg_frame_set_char_size (f, cols, rows);
8864 else
8865 x_set_window_size_1 (f, change_gravity, cols, rows);
8866 #else /* not USE_GTK */
8868 x_set_window_size_1 (f, change_gravity, cols, rows);
8870 #endif /* not USE_GTK */
8872 /* If cursor was outside the new size, mark it as off. */
8873 mark_window_cursors_off (XWINDOW (f->root_window));
8875 /* Clear out any recollection of where the mouse highlighting was,
8876 since it might be in a place that's outside the new frame size.
8877 Actually checking whether it is outside is a pain in the neck,
8878 so don't try--just let the highlighting be done afresh with new size. */
8879 cancel_mouse_face (f);
8881 UNBLOCK_INPUT;
8884 /* Mouse warping. */
8886 void
8887 x_set_mouse_position (struct frame *f, int x, int y)
8889 int pix_x, pix_y;
8891 pix_x = FRAME_COL_TO_PIXEL_X (f, x) + FRAME_COLUMN_WIDTH (f) / 2;
8892 pix_y = FRAME_LINE_TO_PIXEL_Y (f, y) + FRAME_LINE_HEIGHT (f) / 2;
8894 if (pix_x < 0) pix_x = 0;
8895 if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
8897 if (pix_y < 0) pix_y = 0;
8898 if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
8900 BLOCK_INPUT;
8902 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
8903 0, 0, 0, 0, pix_x, pix_y);
8904 UNBLOCK_INPUT;
8907 /* Move the mouse to position pixel PIX_X, PIX_Y relative to frame F. */
8909 void
8910 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
8912 BLOCK_INPUT;
8914 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
8915 0, 0, 0, 0, pix_x, pix_y);
8916 UNBLOCK_INPUT;
8919 /* Raise frame F. */
8921 void
8922 x_raise_frame (struct frame *f)
8924 BLOCK_INPUT;
8925 if (f->async_visible)
8926 XRaiseWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
8928 XFlush (FRAME_X_DISPLAY (f));
8929 UNBLOCK_INPUT;
8932 /* Lower frame F. */
8934 static void
8935 x_lower_frame (struct frame *f)
8937 if (f->async_visible)
8939 BLOCK_INPUT;
8940 XLowerWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
8941 XFlush (FRAME_X_DISPLAY (f));
8942 UNBLOCK_INPUT;
8946 /* Activate frame with Extended Window Manager Hints */
8948 void
8949 x_ewmh_activate_frame (FRAME_PTR f)
8951 /* See Window Manager Specification/Extended Window Manager Hints at
8952 http://freedesktop.org/wiki/Specifications/wm-spec */
8954 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8955 if (f->async_visible && wm_supports (f, dpyinfo->Xatom_net_active_window))
8957 Lisp_Object frame;
8958 XSETFRAME (frame, f);
8959 x_send_client_event (frame, make_number (0), frame,
8960 dpyinfo->Xatom_net_active_window,
8961 make_number (32),
8962 Fcons (make_number (1),
8963 Fcons (make_number (last_user_time),
8964 Qnil)));
8968 static void
8969 XTframe_raise_lower (FRAME_PTR f, int raise_flag)
8971 if (raise_flag)
8972 x_raise_frame (f);
8973 else
8974 x_lower_frame (f);
8977 /* XEmbed implementation. */
8979 #if defined USE_X_TOOLKIT || ! defined USE_GTK
8981 /* XEmbed implementation. */
8983 #define XEMBED_VERSION 0
8985 static void
8986 xembed_set_info (struct frame *f, enum xembed_info flags)
8988 unsigned long data[2];
8989 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8991 data[0] = XEMBED_VERSION;
8992 data[1] = flags;
8994 XChangeProperty (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8995 dpyinfo->Xatom_XEMBED_INFO, dpyinfo->Xatom_XEMBED_INFO,
8996 32, PropModeReplace, (unsigned char *) data, 2);
8998 #endif /* defined USE_X_TOOLKIT || ! defined USE_GTK */
9000 static void
9001 xembed_send_message (struct frame *f, Time t, enum xembed_message msg,
9002 long int detail, long int data1, long int data2)
9004 XEvent event;
9006 event.xclient.type = ClientMessage;
9007 event.xclient.window = FRAME_X_OUTPUT (f)->parent_desc;
9008 event.xclient.message_type = FRAME_X_DISPLAY_INFO (f)->Xatom_XEMBED;
9009 event.xclient.format = 32;
9010 event.xclient.data.l[0] = t;
9011 event.xclient.data.l[1] = msg;
9012 event.xclient.data.l[2] = detail;
9013 event.xclient.data.l[3] = data1;
9014 event.xclient.data.l[4] = data2;
9016 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_OUTPUT (f)->parent_desc,
9017 False, NoEventMask, &event);
9018 XSync (FRAME_X_DISPLAY (f), False);
9021 /* Change of visibility. */
9023 /* This tries to wait until the frame is really visible.
9024 However, if the window manager asks the user where to position
9025 the frame, this will return before the user finishes doing that.
9026 The frame will not actually be visible at that time,
9027 but it will become visible later when the window manager
9028 finishes with it. */
9030 void
9031 x_make_frame_visible (struct frame *f)
9033 Lisp_Object type;
9034 int original_top, original_left;
9035 int retry_count = 2;
9037 retry:
9039 BLOCK_INPUT;
9041 type = x_icon_type (f);
9042 if (!NILP (type))
9043 x_bitmap_icon (f, type);
9045 if (! FRAME_VISIBLE_P (f))
9047 /* We test FRAME_GARBAGED_P here to make sure we don't
9048 call x_set_offset a second time
9049 if we get to x_make_frame_visible a second time
9050 before the window gets really visible. */
9051 if (! FRAME_ICONIFIED_P (f)
9052 && ! FRAME_X_EMBEDDED_P (f)
9053 && ! f->output_data.x->asked_for_visible)
9054 x_set_offset (f, f->left_pos, f->top_pos, 0);
9056 f->output_data.x->asked_for_visible = 1;
9058 if (! EQ (Vx_no_window_manager, Qt))
9059 x_wm_set_window_state (f, NormalState);
9060 #ifdef USE_X_TOOLKIT
9061 if (FRAME_X_EMBEDDED_P (f))
9062 xembed_set_info (f, XEMBED_MAPPED);
9063 else
9065 /* This was XtPopup, but that did nothing for an iconified frame. */
9066 XtMapWidget (f->output_data.x->widget);
9068 #else /* not USE_X_TOOLKIT */
9069 #ifdef USE_GTK
9070 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
9071 gtk_window_deiconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
9072 #else
9073 if (FRAME_X_EMBEDDED_P (f))
9074 xembed_set_info (f, XEMBED_MAPPED);
9075 else
9076 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9077 #endif /* not USE_GTK */
9078 #endif /* not USE_X_TOOLKIT */
9081 XFlush (FRAME_X_DISPLAY (f));
9083 /* Synchronize to ensure Emacs knows the frame is visible
9084 before we do anything else. We do this loop with input not blocked
9085 so that incoming events are handled. */
9087 Lisp_Object frame;
9088 int count;
9089 /* This must be before UNBLOCK_INPUT
9090 since events that arrive in response to the actions above
9091 will set it when they are handled. */
9092 int previously_visible = f->output_data.x->has_been_visible;
9094 original_left = f->left_pos;
9095 original_top = f->top_pos;
9097 /* This must come after we set COUNT. */
9098 UNBLOCK_INPUT;
9100 /* We unblock here so that arriving X events are processed. */
9102 /* Now move the window back to where it was "supposed to be".
9103 But don't do it if the gravity is negative.
9104 When the gravity is negative, this uses a position
9105 that is 3 pixels too low. Perhaps that's really the border width.
9107 Don't do this if the window has never been visible before,
9108 because the window manager may choose the position
9109 and we don't want to override it. */
9111 if (! FRAME_VISIBLE_P (f)
9112 && ! FRAME_ICONIFIED_P (f)
9113 && ! FRAME_X_EMBEDDED_P (f)
9114 && f->win_gravity == NorthWestGravity
9115 && previously_visible)
9117 Drawable rootw;
9118 int x, y;
9119 unsigned int width, height, border, depth;
9121 BLOCK_INPUT;
9123 /* On some window managers (such as FVWM) moving an existing
9124 window, even to the same place, causes the window manager
9125 to introduce an offset. This can cause the window to move
9126 to an unexpected location. Check the geometry (a little
9127 slow here) and then verify that the window is in the right
9128 place. If the window is not in the right place, move it
9129 there, and take the potential window manager hit. */
9130 XGetGeometry (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
9131 &rootw, &x, &y, &width, &height, &border, &depth);
9133 if (original_left != x || original_top != y)
9134 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
9135 original_left, original_top);
9137 UNBLOCK_INPUT;
9140 XSETFRAME (frame, f);
9142 /* Wait until the frame is visible. Process X events until a
9143 MapNotify event has been seen, or until we think we won't get a
9144 MapNotify at all.. */
9145 for (count = input_signal_count + 10;
9146 input_signal_count < count && !FRAME_VISIBLE_P (f);)
9148 /* Force processing of queued events. */
9149 x_sync (f);
9151 /* Machines that do polling rather than SIGIO have been
9152 observed to go into a busy-wait here. So we'll fake an
9153 alarm signal to let the handler know that there's something
9154 to be read. We used to raise a real alarm, but it seems
9155 that the handler isn't always enabled here. This is
9156 probably a bug. */
9157 if (input_polling_used ())
9159 /* It could be confusing if a real alarm arrives while
9160 processing the fake one. Turn it off and let the
9161 handler reset it. */
9162 int old_poll_suppress_count = poll_suppress_count;
9163 poll_suppress_count = 1;
9164 poll_for_input_1 ();
9165 poll_suppress_count = old_poll_suppress_count;
9168 /* See if a MapNotify event has been processed. */
9169 FRAME_SAMPLE_VISIBILITY (f);
9172 /* 2000-09-28: In
9174 (let ((f (selected-frame)))
9175 (iconify-frame f)
9176 (raise-frame f))
9178 the frame is not raised with various window managers on
9179 FreeBSD, GNU/Linux and Solaris. It turns out that, for some
9180 unknown reason, the call to XtMapWidget is completely ignored.
9181 Mapping the widget a second time works. */
9183 if (!FRAME_VISIBLE_P (f) && --retry_count != 0)
9184 goto retry;
9188 /* Change from mapped state to withdrawn state. */
9190 /* Make the frame visible (mapped and not iconified). */
9192 void
9193 x_make_frame_invisible (struct frame *f)
9195 Window window;
9197 /* Use the frame's outermost window, not the one we normally draw on. */
9198 window = FRAME_OUTER_WINDOW (f);
9200 /* Don't keep the highlight on an invisible frame. */
9201 if (FRAME_X_DISPLAY_INFO (f)->x_highlight_frame == f)
9202 FRAME_X_DISPLAY_INFO (f)->x_highlight_frame = 0;
9204 BLOCK_INPUT;
9206 /* Before unmapping the window, update the WM_SIZE_HINTS property to claim
9207 that the current position of the window is user-specified, rather than
9208 program-specified, so that when the window is mapped again, it will be
9209 placed at the same location, without forcing the user to position it
9210 by hand again (they have already done that once for this window.) */
9211 x_wm_set_size_hint (f, (long) 0, 1);
9213 #ifdef USE_GTK
9214 if (FRAME_GTK_OUTER_WIDGET (f))
9215 gtk_widget_hide (FRAME_GTK_OUTER_WIDGET (f));
9216 else
9217 #else
9218 if (FRAME_X_EMBEDDED_P (f))
9219 xembed_set_info (f, 0);
9220 else
9221 #endif
9224 if (! XWithdrawWindow (FRAME_X_DISPLAY (f), window,
9225 DefaultScreen (FRAME_X_DISPLAY (f))))
9227 UNBLOCK_INPUT_RESIGNAL;
9228 error ("Can't notify window manager of window withdrawal");
9232 /* We can't distinguish this from iconification
9233 just by the event that we get from the server.
9234 So we can't win using the usual strategy of letting
9235 FRAME_SAMPLE_VISIBILITY set this. So do it by hand,
9236 and synchronize with the server to make sure we agree. */
9237 f->visible = 0;
9238 FRAME_ICONIFIED_P (f) = 0;
9239 f->async_visible = 0;
9240 f->async_iconified = 0;
9242 x_sync (f);
9244 UNBLOCK_INPUT;
9247 /* Change window state from mapped to iconified. */
9249 void
9250 x_iconify_frame (struct frame *f)
9252 #ifdef USE_X_TOOLKIT
9253 int result;
9254 #endif
9255 Lisp_Object type;
9257 /* Don't keep the highlight on an invisible frame. */
9258 if (FRAME_X_DISPLAY_INFO (f)->x_highlight_frame == f)
9259 FRAME_X_DISPLAY_INFO (f)->x_highlight_frame = 0;
9261 if (f->async_iconified)
9262 return;
9264 BLOCK_INPUT;
9266 FRAME_SAMPLE_VISIBILITY (f);
9268 type = x_icon_type (f);
9269 if (!NILP (type))
9270 x_bitmap_icon (f, type);
9272 #ifdef USE_GTK
9273 if (FRAME_GTK_OUTER_WIDGET (f))
9275 if (! FRAME_VISIBLE_P (f))
9276 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
9278 gtk_window_iconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
9279 f->iconified = 1;
9280 f->visible = 1;
9281 f->async_iconified = 1;
9282 f->async_visible = 0;
9283 UNBLOCK_INPUT;
9284 return;
9286 #endif
9288 #ifdef USE_X_TOOLKIT
9290 if (! FRAME_VISIBLE_P (f))
9292 if (! EQ (Vx_no_window_manager, Qt))
9293 x_wm_set_window_state (f, IconicState);
9294 /* This was XtPopup, but that did nothing for an iconified frame. */
9295 XtMapWidget (f->output_data.x->widget);
9296 /* The server won't give us any event to indicate
9297 that an invisible frame was changed to an icon,
9298 so we have to record it here. */
9299 f->iconified = 1;
9300 f->visible = 1;
9301 f->async_iconified = 1;
9302 f->async_visible = 0;
9303 UNBLOCK_INPUT;
9304 return;
9307 result = XIconifyWindow (FRAME_X_DISPLAY (f),
9308 XtWindow (f->output_data.x->widget),
9309 DefaultScreen (FRAME_X_DISPLAY (f)));
9310 UNBLOCK_INPUT;
9312 if (!result)
9313 error ("Can't notify window manager of iconification");
9315 f->async_iconified = 1;
9316 f->async_visible = 0;
9319 BLOCK_INPUT;
9320 XFlush (FRAME_X_DISPLAY (f));
9321 UNBLOCK_INPUT;
9322 #else /* not USE_X_TOOLKIT */
9324 /* Make sure the X server knows where the window should be positioned,
9325 in case the user deiconifies with the window manager. */
9326 if (! FRAME_VISIBLE_P (f)
9327 && ! FRAME_ICONIFIED_P (f)
9328 && ! FRAME_X_EMBEDDED_P (f))
9329 x_set_offset (f, f->left_pos, f->top_pos, 0);
9331 /* Since we don't know which revision of X we're running, we'll use both
9332 the X11R3 and X11R4 techniques. I don't know if this is a good idea. */
9334 /* X11R4: send a ClientMessage to the window manager using the
9335 WM_CHANGE_STATE type. */
9337 XEvent msg;
9339 msg.xclient.window = FRAME_X_WINDOW (f);
9340 msg.xclient.type = ClientMessage;
9341 msg.xclient.message_type = FRAME_X_DISPLAY_INFO (f)->Xatom_wm_change_state;
9342 msg.xclient.format = 32;
9343 msg.xclient.data.l[0] = IconicState;
9345 if (! XSendEvent (FRAME_X_DISPLAY (f),
9346 DefaultRootWindow (FRAME_X_DISPLAY (f)),
9347 False,
9348 SubstructureRedirectMask | SubstructureNotifyMask,
9349 &msg))
9351 UNBLOCK_INPUT_RESIGNAL;
9352 error ("Can't notify window manager of iconification");
9356 /* X11R3: set the initial_state field of the window manager hints to
9357 IconicState. */
9358 x_wm_set_window_state (f, IconicState);
9360 if (!FRAME_VISIBLE_P (f))
9362 /* If the frame was withdrawn, before, we must map it. */
9363 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9366 f->async_iconified = 1;
9367 f->async_visible = 0;
9369 XFlush (FRAME_X_DISPLAY (f));
9370 UNBLOCK_INPUT;
9371 #endif /* not USE_X_TOOLKIT */
9375 /* Free X resources of frame F. */
9377 void
9378 x_free_frame_resources (struct frame *f)
9380 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
9381 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
9382 #ifdef USE_X_TOOLKIT
9383 Lisp_Object bar;
9384 struct scroll_bar *b;
9385 #endif
9387 BLOCK_INPUT;
9389 /* If a display connection is dead, don't try sending more
9390 commands to the X server. */
9391 if (dpyinfo->display)
9393 /* We must free faces before destroying windows because some
9394 font-driver (e.g. xft) access a window while finishing a
9395 face. */
9396 if (FRAME_FACE_CACHE (f))
9397 free_frame_faces (f);
9399 if (f->output_data.x->icon_desc)
9400 XDestroyWindow (FRAME_X_DISPLAY (f), f->output_data.x->icon_desc);
9402 #ifdef USE_X_TOOLKIT
9403 /* Explicitly destroy the scroll bars of the frame. Without
9404 this, we get "BadDrawable" errors from the toolkit later on,
9405 presumably from expose events generated for the disappearing
9406 toolkit scroll bars. */
9407 for (bar = FRAME_SCROLL_BARS (f); !NILP (bar); bar = b->next)
9409 b = XSCROLL_BAR (bar);
9410 x_scroll_bar_remove (b);
9412 #endif
9414 #ifdef HAVE_X_I18N
9415 if (FRAME_XIC (f))
9416 free_frame_xic (f);
9417 #endif
9419 #ifdef USE_X_TOOLKIT
9420 if (f->output_data.x->widget)
9422 XtDestroyWidget (f->output_data.x->widget);
9423 f->output_data.x->widget = NULL;
9425 /* Tooltips don't have widgets, only a simple X window, even if
9426 we are using a toolkit. */
9427 else if (FRAME_X_WINDOW (f))
9428 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9430 free_frame_menubar (f);
9431 #else /* !USE_X_TOOLKIT */
9433 #ifdef USE_GTK
9434 xg_free_frame_widgets (f);
9435 #endif /* USE_GTK */
9437 if (FRAME_X_WINDOW (f))
9438 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9439 #endif /* !USE_X_TOOLKIT */
9441 unload_color (f, FRAME_FOREGROUND_PIXEL (f));
9442 unload_color (f, FRAME_BACKGROUND_PIXEL (f));
9443 unload_color (f, f->output_data.x->cursor_pixel);
9444 unload_color (f, f->output_data.x->cursor_foreground_pixel);
9445 unload_color (f, f->output_data.x->border_pixel);
9446 unload_color (f, f->output_data.x->mouse_pixel);
9448 if (f->output_data.x->scroll_bar_background_pixel != -1)
9449 unload_color (f, f->output_data.x->scroll_bar_background_pixel);
9450 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
9451 unload_color (f, f->output_data.x->scroll_bar_foreground_pixel);
9452 #ifdef USE_TOOLKIT_SCROLL_BARS
9453 /* Scrollbar shadow colors. */
9454 if (f->output_data.x->scroll_bar_top_shadow_pixel != -1)
9455 unload_color (f, f->output_data.x->scroll_bar_top_shadow_pixel);
9456 if (f->output_data.x->scroll_bar_bottom_shadow_pixel != -1)
9457 unload_color (f, f->output_data.x->scroll_bar_bottom_shadow_pixel);
9458 #endif /* USE_TOOLKIT_SCROLL_BARS */
9459 if (f->output_data.x->white_relief.allocated_p)
9460 unload_color (f, f->output_data.x->white_relief.pixel);
9461 if (f->output_data.x->black_relief.allocated_p)
9462 unload_color (f, f->output_data.x->black_relief.pixel);
9464 x_free_gcs (f);
9465 XFlush (FRAME_X_DISPLAY (f));
9468 xfree (f->output_data.x->saved_menu_event);
9469 xfree (f->output_data.x);
9470 f->output_data.x = NULL;
9472 if (f == dpyinfo->x_focus_frame)
9473 dpyinfo->x_focus_frame = 0;
9474 if (f == dpyinfo->x_focus_event_frame)
9475 dpyinfo->x_focus_event_frame = 0;
9476 if (f == dpyinfo->x_highlight_frame)
9477 dpyinfo->x_highlight_frame = 0;
9479 if (f == hlinfo->mouse_face_mouse_frame)
9481 hlinfo->mouse_face_beg_row
9482 = hlinfo->mouse_face_beg_col = -1;
9483 hlinfo->mouse_face_end_row
9484 = hlinfo->mouse_face_end_col = -1;
9485 hlinfo->mouse_face_window = Qnil;
9486 hlinfo->mouse_face_deferred_gc = 0;
9487 hlinfo->mouse_face_mouse_frame = 0;
9490 UNBLOCK_INPUT;
9494 /* Destroy the X window of frame F. */
9496 static void
9497 x_destroy_window (struct frame *f)
9499 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
9501 /* If a display connection is dead, don't try sending more
9502 commands to the X server. */
9503 if (dpyinfo->display != 0)
9504 x_free_frame_resources (f);
9506 dpyinfo->reference_count--;
9510 /* Setting window manager hints. */
9512 /* Set the normal size hints for the window manager, for frame F.
9513 FLAGS is the flags word to use--or 0 meaning preserve the flags
9514 that the window now has.
9515 If USER_POSITION is nonzero, we set the USPosition
9516 flag (this is useful when FLAGS is 0).
9517 The GTK version is in gtkutils.c */
9519 #ifndef USE_GTK
9520 void
9521 x_wm_set_size_hint (struct frame *f, long flags, int user_position)
9523 XSizeHints size_hints;
9524 Window window = FRAME_OUTER_WINDOW (f);
9526 /* Setting PMaxSize caused various problems. */
9527 size_hints.flags = PResizeInc | PMinSize /* | PMaxSize */;
9529 size_hints.x = f->left_pos;
9530 size_hints.y = f->top_pos;
9532 size_hints.height = FRAME_PIXEL_HEIGHT (f);
9533 size_hints.width = FRAME_PIXEL_WIDTH (f);
9535 size_hints.width_inc = FRAME_COLUMN_WIDTH (f);
9536 size_hints.height_inc = FRAME_LINE_HEIGHT (f);
9537 size_hints.max_width = x_display_pixel_width (FRAME_X_DISPLAY_INFO (f))
9538 - FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
9539 size_hints.max_height = x_display_pixel_height (FRAME_X_DISPLAY_INFO (f))
9540 - FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
9542 /* Calculate the base and minimum sizes. */
9544 int base_width, base_height;
9545 int min_rows = 0, min_cols = 0;
9547 base_width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
9548 base_height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
9550 check_frame_size (f, &min_rows, &min_cols);
9552 /* The window manager uses the base width hints to calculate the
9553 current number of rows and columns in the frame while
9554 resizing; min_width and min_height aren't useful for this
9555 purpose, since they might not give the dimensions for a
9556 zero-row, zero-column frame.
9558 We use the base_width and base_height members if we have
9559 them; otherwise, we set the min_width and min_height members
9560 to the size for a zero x zero frame. */
9562 size_hints.flags |= PBaseSize;
9563 size_hints.base_width = base_width;
9564 size_hints.base_height = base_height + FRAME_MENUBAR_HEIGHT (f);
9565 size_hints.min_width = base_width + min_cols * size_hints.width_inc;
9566 size_hints.min_height = base_height + min_rows * size_hints.height_inc;
9569 /* If we don't need the old flags, we don't need the old hint at all. */
9570 if (flags)
9572 size_hints.flags |= flags;
9573 goto no_read;
9577 XSizeHints hints; /* Sometimes I hate X Windows... */
9578 long supplied_return;
9579 int value;
9581 value = XGetWMNormalHints (FRAME_X_DISPLAY (f), window, &hints,
9582 &supplied_return);
9584 if (flags)
9585 size_hints.flags |= flags;
9586 else
9588 if (value == 0)
9589 hints.flags = 0;
9590 if (hints.flags & PSize)
9591 size_hints.flags |= PSize;
9592 if (hints.flags & PPosition)
9593 size_hints.flags |= PPosition;
9594 if (hints.flags & USPosition)
9595 size_hints.flags |= USPosition;
9596 if (hints.flags & USSize)
9597 size_hints.flags |= USSize;
9601 no_read:
9603 #ifdef PWinGravity
9604 size_hints.win_gravity = f->win_gravity;
9605 size_hints.flags |= PWinGravity;
9607 if (user_position)
9609 size_hints.flags &= ~ PPosition;
9610 size_hints.flags |= USPosition;
9612 #endif /* PWinGravity */
9614 XSetWMNormalHints (FRAME_X_DISPLAY (f), window, &size_hints);
9616 #endif /* not USE_GTK */
9618 /* Used for IconicState or NormalState */
9620 static void
9621 x_wm_set_window_state (struct frame *f, int state)
9623 #ifdef USE_X_TOOLKIT
9624 Arg al[1];
9626 XtSetArg (al[0], XtNinitialState, state);
9627 XtSetValues (f->output_data.x->widget, al, 1);
9628 #else /* not USE_X_TOOLKIT */
9629 Window window = FRAME_X_WINDOW (f);
9631 f->output_data.x->wm_hints.flags |= StateHint;
9632 f->output_data.x->wm_hints.initial_state = state;
9634 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
9635 #endif /* not USE_X_TOOLKIT */
9638 static void
9639 x_wm_set_icon_pixmap (struct frame *f, ptrdiff_t pixmap_id)
9641 Pixmap icon_pixmap, icon_mask;
9643 #if !defined USE_X_TOOLKIT && !defined USE_GTK
9644 Window window = FRAME_OUTER_WINDOW (f);
9645 #endif
9647 if (pixmap_id > 0)
9649 icon_pixmap = x_bitmap_pixmap (f, pixmap_id);
9650 f->output_data.x->wm_hints.icon_pixmap = icon_pixmap;
9651 icon_mask = x_bitmap_mask (f, pixmap_id);
9652 f->output_data.x->wm_hints.icon_mask = icon_mask;
9654 else
9656 /* It seems there is no way to turn off use of an icon
9657 pixmap. */
9658 return;
9662 #ifdef USE_GTK
9664 xg_set_frame_icon (f, icon_pixmap, icon_mask);
9665 return;
9668 #elif defined (USE_X_TOOLKIT) /* same as in x_wm_set_window_state. */
9671 Arg al[1];
9672 XtSetArg (al[0], XtNiconPixmap, icon_pixmap);
9673 XtSetValues (f->output_data.x->widget, al, 1);
9674 XtSetArg (al[0], XtNiconMask, icon_mask);
9675 XtSetValues (f->output_data.x->widget, al, 1);
9678 #else /* not USE_X_TOOLKIT && not USE_GTK */
9680 f->output_data.x->wm_hints.flags |= (IconPixmapHint | IconMaskHint);
9681 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
9683 #endif /* not USE_X_TOOLKIT && not USE_GTK */
9686 void
9687 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
9689 Window window = FRAME_OUTER_WINDOW (f);
9691 f->output_data.x->wm_hints.flags |= IconPositionHint;
9692 f->output_data.x->wm_hints.icon_x = icon_x;
9693 f->output_data.x->wm_hints.icon_y = icon_y;
9695 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
9699 /***********************************************************************
9700 Fonts
9701 ***********************************************************************/
9703 #if GLYPH_DEBUG
9705 /* Check that FONT is valid on frame F. It is if it can be found in F's
9706 font table. */
9708 static void
9709 x_check_font (struct frame *f, struct font *font)
9711 xassert (font != NULL && ! NILP (font->props[FONT_TYPE_INDEX]));
9712 if (font->driver->check)
9713 xassert (font->driver->check (f, font) == 0);
9716 #endif /* GLYPH_DEBUG != 0 */
9719 /***********************************************************************
9720 Initialization
9721 ***********************************************************************/
9723 #ifdef USE_X_TOOLKIT
9724 static XrmOptionDescRec emacs_options[] = {
9725 {"-geometry", ".geometry", XrmoptionSepArg, NULL},
9726 {"-iconic", ".iconic", XrmoptionNoArg, (XtPointer) "yes"},
9728 {"-internal-border-width", "*EmacsScreen.internalBorderWidth",
9729 XrmoptionSepArg, NULL},
9730 {"-ib", "*EmacsScreen.internalBorderWidth", XrmoptionSepArg, NULL},
9732 {"-T", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
9733 {"-wn", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
9734 {"-title", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
9735 {"-iconname", "*EmacsShell.iconName", XrmoptionSepArg, (XtPointer) NULL},
9736 {"-in", "*EmacsShell.iconName", XrmoptionSepArg, (XtPointer) NULL},
9737 {"-mc", "*pointerColor", XrmoptionSepArg, (XtPointer) NULL},
9738 {"-cr", "*cursorColor", XrmoptionSepArg, (XtPointer) NULL}
9741 /* Whether atimer for Xt timeouts is activated or not. */
9743 static int x_timeout_atimer_activated_flag;
9745 #endif /* USE_X_TOOLKIT */
9747 static int x_initialized;
9749 /* Test whether two display-name strings agree up to the dot that separates
9750 the screen number from the server number. */
9751 static int
9752 same_x_server (const char *name1, const char *name2)
9754 int seen_colon = 0;
9755 const char *system_name = SSDATA (Vsystem_name);
9756 ptrdiff_t system_name_length = SBYTES (Vsystem_name);
9757 ptrdiff_t length_until_period = 0;
9759 while (system_name[length_until_period] != 0
9760 && system_name[length_until_period] != '.')
9761 length_until_period++;
9763 /* Treat `unix' like an empty host name. */
9764 if (! strncmp (name1, "unix:", 5))
9765 name1 += 4;
9766 if (! strncmp (name2, "unix:", 5))
9767 name2 += 4;
9768 /* Treat this host's name like an empty host name. */
9769 if (! strncmp (name1, system_name, system_name_length)
9770 && name1[system_name_length] == ':')
9771 name1 += system_name_length;
9772 if (! strncmp (name2, system_name, system_name_length)
9773 && name2[system_name_length] == ':')
9774 name2 += system_name_length;
9775 /* Treat this host's domainless name like an empty host name. */
9776 if (! strncmp (name1, system_name, length_until_period)
9777 && name1[length_until_period] == ':')
9778 name1 += length_until_period;
9779 if (! strncmp (name2, system_name, length_until_period)
9780 && name2[length_until_period] == ':')
9781 name2 += length_until_period;
9783 for (; *name1 != '\0' && *name1 == *name2; name1++, name2++)
9785 if (*name1 == ':')
9786 seen_colon = 1;
9787 if (seen_colon && *name1 == '.')
9788 return 1;
9790 return (seen_colon
9791 && (*name1 == '.' || *name1 == '\0')
9792 && (*name2 == '.' || *name2 == '\0'));
9795 /* Count number of set bits in mask and number of bits to shift to
9796 get to the first bit. With MASK 0x7e0, *BITS is set to 6, and *OFFSET
9797 to 5. */
9798 static void
9799 get_bits_and_offset (long unsigned int mask, int *bits, int *offset)
9801 int nr = 0;
9802 int off = 0;
9804 while (!(mask & 1))
9806 off++;
9807 mask >>= 1;
9810 while (mask & 1)
9812 nr++;
9813 mask >>= 1;
9816 *offset = off;
9817 *bits = nr;
9820 /* Return 1 if display DISPLAY is available for use, 0 otherwise.
9821 But don't permanently open it, just test its availability. */
9824 x_display_ok (const char *display)
9826 int dpy_ok = 1;
9827 Display *dpy;
9829 dpy = XOpenDisplay (display);
9830 if (dpy)
9831 XCloseDisplay (dpy);
9832 else
9833 dpy_ok = 0;
9834 return dpy_ok;
9837 #ifdef USE_GTK
9838 static void
9839 my_log_handler (const gchar *log_domain, GLogLevelFlags log_level,
9840 const gchar *msg, gpointer user_data)
9842 if (!strstr (msg, "g_set_prgname"))
9843 fprintf (stderr, "%s-WARNING **: %s\n", log_domain, msg);
9845 #endif
9847 /* Open a connection to X display DISPLAY_NAME, and return
9848 the structure that describes the open display.
9849 If we cannot contact the display, return null. */
9851 struct x_display_info *
9852 x_term_init (Lisp_Object display_name, char *xrm_option, char *resource_name)
9854 int connection;
9855 Display *dpy;
9856 struct terminal *terminal;
9857 struct x_display_info *dpyinfo;
9858 XrmDatabase xrdb;
9859 Mouse_HLInfo *hlinfo;
9860 ptrdiff_t lim;
9862 BLOCK_INPUT;
9864 if (!x_initialized)
9866 x_initialize ();
9867 ++x_initialized;
9870 if (! x_display_ok (SSDATA (display_name)))
9871 error ("Display %s can't be opened", SSDATA (display_name));
9873 #ifdef USE_GTK
9875 #define NUM_ARGV 10
9876 int argc;
9877 char *argv[NUM_ARGV];
9878 char **argv2 = argv;
9879 guint id;
9881 if (x_initialized++ > 1)
9883 xg_display_open (SSDATA (display_name), &dpy);
9885 else
9887 static char display_opt[] = "--display";
9888 static char name_opt[] = "--name";
9890 for (argc = 0; argc < NUM_ARGV; ++argc)
9891 argv[argc] = 0;
9893 argc = 0;
9894 argv[argc++] = initial_argv[0];
9896 if (! NILP (display_name))
9898 argv[argc++] = display_opt;
9899 argv[argc++] = SSDATA (display_name);
9902 argv[argc++] = name_opt;
9903 argv[argc++] = resource_name;
9905 XSetLocaleModifiers ("");
9907 /* Emacs can only handle core input events, so make sure
9908 Gtk doesn't use Xinput or Xinput2 extensions. */
9910 static char fix_events[] = "GDK_CORE_DEVICE_EVENTS=1";
9911 putenv (fix_events);
9914 /* Work around GLib bug that outputs a faulty warning. See
9915 https://bugzilla.gnome.org/show_bug.cgi?id=563627. */
9916 id = g_log_set_handler ("GLib", G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
9917 | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
9918 gtk_init (&argc, &argv2);
9919 g_log_remove_handler ("GLib", id);
9921 /* gtk_init does set_locale. We must fix locale after calling it. */
9922 fixup_locale ();
9923 xg_initialize ();
9925 dpy = DEFAULT_GDK_DISPLAY ();
9927 /* NULL window -> events for all windows go to our function */
9928 gdk_window_add_filter (NULL, event_handler_gdk, NULL);
9930 #if GTK_MAJOR_VERSION <= 2 && GTK_MINOR_VERSION <= 90
9931 /* Load our own gtkrc if it exists. */
9933 const char *file = "~/.emacs.d/gtkrc";
9934 Lisp_Object s, abs_file;
9936 s = make_string (file, strlen (file));
9937 abs_file = Fexpand_file_name (s, Qnil);
9939 if (! NILP (abs_file) && !NILP (Ffile_readable_p (abs_file)))
9940 gtk_rc_parse (SSDATA (abs_file));
9942 #endif
9944 XSetErrorHandler (x_error_handler);
9945 XSetIOErrorHandler (x_io_error_quitter);
9948 #else /* not USE_GTK */
9949 #ifdef USE_X_TOOLKIT
9950 /* weiner@footloose.sps.mot.com reports that this causes
9951 errors with X11R5:
9952 X protocol error: BadAtom (invalid Atom parameter)
9953 on protocol request 18skiloaf.
9954 So let's not use it until R6. */
9955 #ifdef HAVE_X11XTR6
9956 XtSetLanguageProc (NULL, NULL, NULL);
9957 #endif
9960 int argc = 0;
9961 char *argv[3];
9963 argv[0] = "";
9964 argc = 1;
9965 if (xrm_option)
9967 argv[argc++] = "-xrm";
9968 argv[argc++] = xrm_option;
9970 turn_on_atimers (0);
9971 dpy = XtOpenDisplay (Xt_app_con, SSDATA (display_name),
9972 resource_name, EMACS_CLASS,
9973 emacs_options, XtNumber (emacs_options),
9974 &argc, argv);
9975 turn_on_atimers (1);
9977 #ifdef HAVE_X11XTR6
9978 /* I think this is to compensate for XtSetLanguageProc. */
9979 fixup_locale ();
9980 #endif
9983 #else /* not USE_X_TOOLKIT */
9984 XSetLocaleModifiers ("");
9985 dpy = XOpenDisplay (SSDATA (display_name));
9986 #endif /* not USE_X_TOOLKIT */
9987 #endif /* not USE_GTK*/
9989 /* Detect failure. */
9990 if (dpy == 0)
9992 UNBLOCK_INPUT;
9993 return 0;
9996 /* We have definitely succeeded. Record the new connection. */
9998 dpyinfo = (struct x_display_info *) xmalloc (sizeof (struct x_display_info));
9999 memset (dpyinfo, 0, sizeof *dpyinfo);
10000 hlinfo = &dpyinfo->mouse_highlight;
10002 terminal = x_create_terminal (dpyinfo);
10005 struct x_display_info *share;
10006 Lisp_Object tail;
10008 for (share = x_display_list, tail = x_display_name_list; share;
10009 share = share->next, tail = XCDR (tail))
10010 if (same_x_server (SSDATA (XCAR (XCAR (tail))),
10011 SSDATA (display_name)))
10012 break;
10013 if (share)
10014 terminal->kboard = share->terminal->kboard;
10015 else
10017 terminal->kboard = (KBOARD *) xmalloc (sizeof (KBOARD));
10018 init_kboard (terminal->kboard);
10019 KVAR (terminal->kboard, Vwindow_system) = Qx;
10021 /* Add the keyboard to the list before running Lisp code (via
10022 Qvendor_specific_keysyms below), since these are not traced
10023 via terminals but only through all_kboards. */
10024 terminal->kboard->next_kboard = all_kboards;
10025 all_kboards = terminal->kboard;
10027 if (!EQ (XSYMBOL (Qvendor_specific_keysyms)->function, Qunbound))
10029 char *vendor = ServerVendor (dpy);
10031 /* Protect terminal from GC before removing it from the
10032 list of terminals. */
10033 struct gcpro gcpro1;
10034 Lisp_Object gcpro_term;
10035 XSETTERMINAL (gcpro_term, terminal);
10036 GCPRO1 (gcpro_term);
10038 /* Temporarily hide the partially initialized terminal. */
10039 terminal_list = terminal->next_terminal;
10040 UNBLOCK_INPUT;
10041 KVAR (terminal->kboard, Vsystem_key_alist)
10042 = call1 (Qvendor_specific_keysyms,
10043 vendor ? build_string (vendor) : empty_unibyte_string);
10044 BLOCK_INPUT;
10045 terminal->next_terminal = terminal_list;
10046 terminal_list = terminal;
10047 UNGCPRO;
10050 /* Don't let the initial kboard remain current longer than necessary.
10051 That would cause problems if a file loaded on startup tries to
10052 prompt in the mini-buffer. */
10053 if (current_kboard == initial_kboard)
10054 current_kboard = terminal->kboard;
10056 terminal->kboard->reference_count++;
10059 /* Put this display on the chain. */
10060 dpyinfo->next = x_display_list;
10061 x_display_list = dpyinfo;
10063 /* Put it on x_display_name_list as well, to keep them parallel. */
10064 x_display_name_list = Fcons (Fcons (display_name, Qnil),
10065 x_display_name_list);
10066 dpyinfo->name_list_element = XCAR (x_display_name_list);
10068 dpyinfo->display = dpy;
10070 /* Set the name of the terminal. */
10071 terminal->name = (char *) xmalloc (SBYTES (display_name) + 1);
10072 strncpy (terminal->name, SSDATA (display_name), SBYTES (display_name));
10073 terminal->name[SBYTES (display_name)] = 0;
10075 #if 0
10076 XSetAfterFunction (x_current_display, x_trace_wire);
10077 #endif /* ! 0 */
10079 lim = min (PTRDIFF_MAX, SIZE_MAX) - sizeof "@";
10080 if (lim - SBYTES (Vinvocation_name) < SBYTES (Vsystem_name))
10081 memory_full (SIZE_MAX);
10082 dpyinfo->x_id_name
10083 = (char *) xmalloc (SBYTES (Vinvocation_name)
10084 + SBYTES (Vsystem_name)
10085 + 2);
10086 strcat (strcat (strcpy (dpyinfo->x_id_name, SSDATA (Vinvocation_name)), "@"),
10087 SSDATA (Vsystem_name));
10089 /* Figure out which modifier bits mean what. */
10090 x_find_modifier_meanings (dpyinfo);
10092 /* Get the scroll bar cursor. */
10093 #ifdef USE_GTK
10094 /* We must create a GTK cursor, it is required for GTK widgets. */
10095 dpyinfo->xg_cursor = xg_create_default_cursor (dpyinfo->display);
10096 #endif /* USE_GTK */
10098 dpyinfo->vertical_scroll_bar_cursor
10099 = XCreateFontCursor (dpyinfo->display, XC_sb_v_double_arrow);
10101 xrdb = x_load_resources (dpyinfo->display, xrm_option,
10102 resource_name, EMACS_CLASS);
10103 #ifdef HAVE_XRMSETDATABASE
10104 XrmSetDatabase (dpyinfo->display, xrdb);
10105 #else
10106 dpyinfo->display->db = xrdb;
10107 #endif
10108 /* Put the rdb where we can find it in a way that works on
10109 all versions. */
10110 dpyinfo->xrdb = xrdb;
10112 dpyinfo->screen = ScreenOfDisplay (dpyinfo->display,
10113 DefaultScreen (dpyinfo->display));
10114 select_visual (dpyinfo);
10115 dpyinfo->cmap = DefaultColormapOfScreen (dpyinfo->screen);
10116 dpyinfo->root_window = RootWindowOfScreen (dpyinfo->screen);
10117 dpyinfo->client_leader_window = 0;
10118 dpyinfo->grabbed = 0;
10119 dpyinfo->reference_count = 0;
10120 dpyinfo->icon_bitmap_id = -1;
10121 dpyinfo->n_fonts = 0;
10122 dpyinfo->bitmaps = 0;
10123 dpyinfo->bitmaps_size = 0;
10124 dpyinfo->bitmaps_last = 0;
10125 dpyinfo->scratch_cursor_gc = 0;
10126 hlinfo->mouse_face_mouse_frame = 0;
10127 hlinfo->mouse_face_deferred_gc = 0;
10128 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
10129 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
10130 hlinfo->mouse_face_face_id = DEFAULT_FACE_ID;
10131 hlinfo->mouse_face_window = Qnil;
10132 hlinfo->mouse_face_overlay = Qnil;
10133 hlinfo->mouse_face_mouse_x = hlinfo->mouse_face_mouse_y = 0;
10134 hlinfo->mouse_face_defer = 0;
10135 hlinfo->mouse_face_hidden = 0;
10136 dpyinfo->x_focus_frame = 0;
10137 dpyinfo->x_focus_event_frame = 0;
10138 dpyinfo->x_highlight_frame = 0;
10139 dpyinfo->wm_type = X_WMTYPE_UNKNOWN;
10141 /* See if we can construct pixel values from RGB values. */
10142 dpyinfo->red_bits = dpyinfo->blue_bits = dpyinfo->green_bits = 0;
10143 dpyinfo->red_offset = dpyinfo->blue_offset = dpyinfo->green_offset = 0;
10145 if (dpyinfo->visual->class == TrueColor)
10147 get_bits_and_offset (dpyinfo->visual->red_mask,
10148 &dpyinfo->red_bits, &dpyinfo->red_offset);
10149 get_bits_and_offset (dpyinfo->visual->blue_mask,
10150 &dpyinfo->blue_bits, &dpyinfo->blue_offset);
10151 get_bits_and_offset (dpyinfo->visual->green_mask,
10152 &dpyinfo->green_bits, &dpyinfo->green_offset);
10155 /* See if a private colormap is requested. */
10156 if (dpyinfo->visual == DefaultVisualOfScreen (dpyinfo->screen))
10158 if (dpyinfo->visual->class == PseudoColor)
10160 Lisp_Object value;
10161 value = display_x_get_resource (dpyinfo,
10162 build_string ("privateColormap"),
10163 build_string ("PrivateColormap"),
10164 Qnil, Qnil);
10165 if (STRINGP (value)
10166 && (!strcmp (SSDATA (value), "true")
10167 || !strcmp (SSDATA (value), "on")))
10168 dpyinfo->cmap = XCopyColormapAndFree (dpyinfo->display, dpyinfo->cmap);
10171 else
10172 dpyinfo->cmap = XCreateColormap (dpyinfo->display, dpyinfo->root_window,
10173 dpyinfo->visual, AllocNone);
10175 #ifdef HAVE_XFT
10177 /* If we are using Xft, check dpi value in X resources.
10178 It is better we use it as well, since Xft will use it, as will all
10179 Gnome applications. If our real DPI is smaller or larger than the
10180 one Xft uses, our font will look smaller or larger than other
10181 for other applications, even if it is the same font name (monospace-10
10182 for example). */
10183 char *v = XGetDefault (dpyinfo->display, "Xft", "dpi");
10184 double d;
10185 if (v != NULL && sscanf (v, "%lf", &d) == 1)
10186 dpyinfo->resy = dpyinfo->resx = d;
10188 #endif
10190 if (dpyinfo->resy < 1)
10192 int screen_number = XScreenNumberOfScreen (dpyinfo->screen);
10193 double pixels = DisplayHeight (dpyinfo->display, screen_number);
10194 double mm = DisplayHeightMM (dpyinfo->display, screen_number);
10195 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
10196 dpyinfo->resy = (mm < 1) ? 100 : pixels * 25.4 / mm;
10197 pixels = DisplayWidth (dpyinfo->display, screen_number);
10198 mm = DisplayWidthMM (dpyinfo->display, screen_number);
10199 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
10200 dpyinfo->resx = (mm < 1) ? 100 : pixels * 25.4 / mm;
10204 const struct
10206 const char *name;
10207 Atom *atom;
10208 } atom_refs[] = {
10209 { "WM_PROTOCOLS", &dpyinfo->Xatom_wm_protocols },
10210 { "WM_TAKE_FOCUS", &dpyinfo->Xatom_wm_take_focus },
10211 { "WM_SAVE_YOURSELF", &dpyinfo->Xatom_wm_save_yourself },
10212 { "WM_DELETE_WINDOW", &dpyinfo->Xatom_wm_delete_window },
10213 { "WM_CHANGE_STATE", &dpyinfo->Xatom_wm_change_state },
10214 { "WM_CONFIGURE_DENIED", &dpyinfo->Xatom_wm_configure_denied },
10215 { "WM_MOVED", &dpyinfo->Xatom_wm_window_moved },
10216 { "WM_CLIENT_LEADER", &dpyinfo->Xatom_wm_client_leader },
10217 { "Editres", &dpyinfo->Xatom_editres },
10218 { "CLIPBOARD", &dpyinfo->Xatom_CLIPBOARD },
10219 { "TIMESTAMP", &dpyinfo->Xatom_TIMESTAMP },
10220 { "TEXT", &dpyinfo->Xatom_TEXT },
10221 { "COMPOUND_TEXT", &dpyinfo->Xatom_COMPOUND_TEXT },
10222 { "UTF8_STRING", &dpyinfo->Xatom_UTF8_STRING },
10223 { "DELETE", &dpyinfo->Xatom_DELETE },
10224 { "MULTIPLE", &dpyinfo->Xatom_MULTIPLE },
10225 { "INCR", &dpyinfo->Xatom_INCR },
10226 { "_EMACS_TMP_", &dpyinfo->Xatom_EMACS_TMP },
10227 { "TARGETS", &dpyinfo->Xatom_TARGETS },
10228 { "NULL", &dpyinfo->Xatom_NULL },
10229 { "ATOM", &dpyinfo->Xatom_ATOM },
10230 { "ATOM_PAIR", &dpyinfo->Xatom_ATOM_PAIR },
10231 { "CLIPBOARD_MANAGER", &dpyinfo->Xatom_CLIPBOARD_MANAGER },
10232 { "_XEMBED_INFO", &dpyinfo->Xatom_XEMBED_INFO },
10233 /* For properties of font. */
10234 { "PIXEL_SIZE", &dpyinfo->Xatom_PIXEL_SIZE },
10235 { "AVERAGE_WIDTH", &dpyinfo->Xatom_AVERAGE_WIDTH },
10236 { "_MULE_BASELINE_OFFSET", &dpyinfo->Xatom_MULE_BASELINE_OFFSET },
10237 { "_MULE_RELATIVE_COMPOSE", &dpyinfo->Xatom_MULE_RELATIVE_COMPOSE },
10238 { "_MULE_DEFAULT_ASCENT", &dpyinfo->Xatom_MULE_DEFAULT_ASCENT },
10239 /* Ghostscript support. */
10240 { "DONE", &dpyinfo->Xatom_DONE },
10241 { "PAGE", &dpyinfo->Xatom_PAGE },
10242 { "SCROLLBAR", &dpyinfo->Xatom_Scrollbar },
10243 { "_XEMBED", &dpyinfo->Xatom_XEMBED },
10244 /* EWMH */
10245 { "_NET_WM_STATE", &dpyinfo->Xatom_net_wm_state },
10246 { "_NET_WM_STATE_FULLSCREEN", &dpyinfo->Xatom_net_wm_state_fullscreen },
10247 { "_NET_WM_STATE_MAXIMIZED_HORZ",
10248 &dpyinfo->Xatom_net_wm_state_maximized_horz },
10249 { "_NET_WM_STATE_MAXIMIZED_VERT",
10250 &dpyinfo->Xatom_net_wm_state_maximized_vert },
10251 { "_NET_WM_STATE_STICKY", &dpyinfo->Xatom_net_wm_state_sticky },
10252 { "_NET_WM_WINDOW_TYPE", &dpyinfo->Xatom_net_window_type },
10253 { "_NET_WM_WINDOW_TYPE_TOOLTIP",
10254 &dpyinfo->Xatom_net_window_type_tooltip },
10255 { "_NET_WM_ICON_NAME", &dpyinfo->Xatom_net_wm_icon_name },
10256 { "_NET_WM_NAME", &dpyinfo->Xatom_net_wm_name },
10257 { "_NET_SUPPORTED", &dpyinfo->Xatom_net_supported },
10258 { "_NET_SUPPORTING_WM_CHECK", &dpyinfo->Xatom_net_supporting_wm_check },
10259 { "_NET_WM_WINDOW_OPACITY", &dpyinfo->Xatom_net_wm_window_opacity },
10260 { "_NET_ACTIVE_WINDOW", &dpyinfo->Xatom_net_active_window },
10261 { "_NET_FRAME_EXTENTS", &dpyinfo->Xatom_net_frame_extents },
10262 /* Session management */
10263 { "SM_CLIENT_ID", &dpyinfo->Xatom_SM_CLIENT_ID },
10264 { "_XSETTINGS_SETTINGS", &dpyinfo->Xatom_xsettings_prop },
10265 { "MANAGER", &dpyinfo->Xatom_xsettings_mgr },
10268 int i;
10269 const int atom_count = sizeof (atom_refs) / sizeof (atom_refs[0]);
10270 /* 1 for _XSETTINGS_SN */
10271 const int total_atom_count = 1 + atom_count;
10272 Atom *atoms_return = xmalloc (sizeof (Atom) * total_atom_count);
10273 char **atom_names = xmalloc (sizeof (char *) * total_atom_count);
10274 char xsettings_atom_name[64];
10276 for (i = 0; i < atom_count; i++)
10277 atom_names[i] = (char *) atom_refs[i].name;
10279 /* Build _XSETTINGS_SN atom name */
10280 snprintf (xsettings_atom_name, sizeof (xsettings_atom_name),
10281 "_XSETTINGS_S%d", XScreenNumberOfScreen (dpyinfo->screen));
10282 atom_names[i] = xsettings_atom_name;
10284 XInternAtoms (dpyinfo->display, atom_names, total_atom_count,
10285 False, atoms_return);
10287 for (i = 0; i < atom_count; i++)
10288 *atom_refs[i].atom = atoms_return[i];
10290 /* Manual copy of last atom */
10291 dpyinfo->Xatom_xsettings_sel = atoms_return[i];
10293 xfree (atom_names);
10294 xfree (atoms_return);
10297 dpyinfo->x_dnd_atoms_size = 8;
10298 dpyinfo->x_dnd_atoms_length = 0;
10299 dpyinfo->x_dnd_atoms = xmalloc (sizeof (*dpyinfo->x_dnd_atoms)
10300 * dpyinfo->x_dnd_atoms_size);
10302 dpyinfo->net_supported_atoms = NULL;
10303 dpyinfo->nr_net_supported_atoms = 0;
10304 dpyinfo->net_supported_window = 0;
10306 connection = ConnectionNumber (dpyinfo->display);
10307 dpyinfo->connection = connection;
10310 dpyinfo->gray
10311 = XCreatePixmapFromBitmapData (dpyinfo->display, dpyinfo->root_window,
10312 gray_bitmap_bits,
10313 gray_bitmap_width, gray_bitmap_height,
10314 1, 0, 1);
10317 #ifdef HAVE_X_I18N
10318 xim_initialize (dpyinfo, resource_name);
10319 #endif
10321 xsettings_initialize (dpyinfo);
10323 /* This is only needed for distinguishing keyboard and process input. */
10324 if (connection != 0)
10325 add_keyboard_wait_descriptor (connection);
10327 #ifdef F_SETOWN
10328 fcntl (connection, F_SETOWN, getpid ());
10329 #endif /* ! defined (F_SETOWN) */
10331 #ifdef SIGIO
10332 if (interrupt_input)
10333 init_sigio (connection);
10334 #endif /* ! defined (SIGIO) */
10336 #ifdef USE_LUCID
10338 XrmValue d, fr, to;
10339 Font font;
10341 dpy = dpyinfo->display;
10342 d.addr = (XPointer)&dpy;
10343 d.size = sizeof (Display *);
10344 fr.addr = XtDefaultFont;
10345 fr.size = sizeof (XtDefaultFont);
10346 to.size = sizeof (Font *);
10347 to.addr = (XPointer)&font;
10348 x_catch_errors (dpy);
10349 if (!XtCallConverter (dpy, XtCvtStringToFont, &d, 1, &fr, &to, NULL))
10350 abort ();
10351 if (x_had_errors_p (dpy) || !XQueryFont (dpy, font))
10352 XrmPutLineResource (&xrdb, "Emacs.dialog.*.font: 9x15");
10353 x_uncatch_errors ();
10355 #endif
10357 /* See if we should run in synchronous mode. This is useful
10358 for debugging X code. */
10360 Lisp_Object value;
10361 value = display_x_get_resource (dpyinfo,
10362 build_string ("synchronous"),
10363 build_string ("Synchronous"),
10364 Qnil, Qnil);
10365 if (STRINGP (value)
10366 && (!strcmp (SSDATA (value), "true")
10367 || !strcmp (SSDATA (value), "on")))
10368 XSynchronize (dpyinfo->display, True);
10372 Lisp_Object value;
10373 value = display_x_get_resource (dpyinfo,
10374 build_string ("useXIM"),
10375 build_string ("UseXIM"),
10376 Qnil, Qnil);
10377 #ifdef USE_XIM
10378 if (STRINGP (value)
10379 && (!strcmp (SSDATA (value), "false")
10380 || !strcmp (SSDATA (value), "off")))
10381 use_xim = 0;
10382 #else
10383 if (STRINGP (value)
10384 && (!strcmp (SSDATA (value), "true")
10385 || !strcmp (SSDATA (value), "on")))
10386 use_xim = 1;
10387 #endif
10390 #ifdef HAVE_X_SM
10391 /* Only do this for the very first display in the Emacs session.
10392 Ignore X session management when Emacs was first started on a
10393 tty. */
10394 if (terminal->id == 1)
10395 x_session_initialize (dpyinfo);
10396 #endif
10398 UNBLOCK_INPUT;
10400 return dpyinfo;
10403 /* Get rid of display DPYINFO, deleting all frames on it,
10404 and without sending any more commands to the X server. */
10406 static void
10407 x_delete_display (struct x_display_info *dpyinfo)
10409 struct terminal *t;
10411 /* Close all frames and delete the generic struct terminal for this
10412 X display. */
10413 for (t = terminal_list; t; t = t->next_terminal)
10414 if (t->type == output_x_window && t->display_info.x == dpyinfo)
10416 #ifdef HAVE_X_SM
10417 /* Close X session management when we close its display. */
10418 if (t->id == 1 && x_session_have_connection ())
10419 x_session_close ();
10420 #endif
10421 delete_terminal (t);
10422 break;
10425 delete_keyboard_wait_descriptor (dpyinfo->connection);
10427 /* Discard this display from x_display_name_list and x_display_list.
10428 We can't use Fdelq because that can quit. */
10429 if (! NILP (x_display_name_list)
10430 && EQ (XCAR (x_display_name_list), dpyinfo->name_list_element))
10431 x_display_name_list = XCDR (x_display_name_list);
10432 else
10434 Lisp_Object tail;
10436 tail = x_display_name_list;
10437 while (CONSP (tail) && CONSP (XCDR (tail)))
10439 if (EQ (XCAR (XCDR (tail)), dpyinfo->name_list_element))
10441 XSETCDR (tail, XCDR (XCDR (tail)));
10442 break;
10444 tail = XCDR (tail);
10448 if (next_noop_dpyinfo == dpyinfo)
10449 next_noop_dpyinfo = dpyinfo->next;
10451 if (x_display_list == dpyinfo)
10452 x_display_list = dpyinfo->next;
10453 else
10455 struct x_display_info *tail;
10457 for (tail = x_display_list; tail; tail = tail->next)
10458 if (tail->next == dpyinfo)
10459 tail->next = tail->next->next;
10462 xfree (dpyinfo->x_id_name);
10463 xfree (dpyinfo->x_dnd_atoms);
10464 xfree (dpyinfo->color_cells);
10465 xfree (dpyinfo);
10468 #ifdef USE_X_TOOLKIT
10470 /* Atimer callback function for TIMER. Called every 0.1s to process
10471 Xt timeouts, if needed. We must avoid calling XtAppPending as
10472 much as possible because that function does an implicit XFlush
10473 that slows us down. */
10475 static void
10476 x_process_timeouts (struct atimer *timer)
10478 BLOCK_INPUT;
10479 x_timeout_atimer_activated_flag = 0;
10480 if (toolkit_scroll_bar_interaction || popup_activated ())
10482 while (XtAppPending (Xt_app_con) & XtIMTimer)
10483 XtAppProcessEvent (Xt_app_con, XtIMTimer);
10484 /* Reactivate the atimer for next time. */
10485 x_activate_timeout_atimer ();
10487 UNBLOCK_INPUT;
10490 /* Install an asynchronous timer that processes Xt timeout events
10491 every 0.1s as long as either `toolkit_scroll_bar_interaction' or
10492 `popup_activated_flag' (in xmenu.c) is set. Make sure to call this
10493 function whenever these variables are set. This is necessary
10494 because some widget sets use timeouts internally, for example the
10495 LessTif menu bar, or the Xaw3d scroll bar. When Xt timeouts aren't
10496 processed, these widgets don't behave normally. */
10498 void
10499 x_activate_timeout_atimer (void)
10501 BLOCK_INPUT;
10502 if (!x_timeout_atimer_activated_flag)
10504 EMACS_TIME interval;
10506 EMACS_SET_SECS_USECS (interval, 0, 100000);
10507 start_atimer (ATIMER_RELATIVE, interval, x_process_timeouts, 0);
10508 x_timeout_atimer_activated_flag = 1;
10510 UNBLOCK_INPUT;
10513 #endif /* USE_X_TOOLKIT */
10516 /* Set up use of X before we make the first connection. */
10518 extern frame_parm_handler x_frame_parm_handlers[];
10520 static struct redisplay_interface x_redisplay_interface =
10522 x_frame_parm_handlers,
10523 x_produce_glyphs,
10524 x_write_glyphs,
10525 x_insert_glyphs,
10526 x_clear_end_of_line,
10527 x_scroll_run,
10528 x_after_update_window_line,
10529 x_update_window_begin,
10530 x_update_window_end,
10531 x_cursor_to,
10532 x_flush,
10533 #ifdef XFlush
10534 x_flush,
10535 #else
10536 0, /* flush_display_optional */
10537 #endif
10538 x_clear_window_mouse_face,
10539 x_get_glyph_overhangs,
10540 x_fix_overlapping_area,
10541 x_draw_fringe_bitmap,
10542 0, /* define_fringe_bitmap */
10543 0, /* destroy_fringe_bitmap */
10544 x_compute_glyph_string_overhangs,
10545 x_draw_glyph_string,
10546 x_define_frame_cursor,
10547 x_clear_frame_area,
10548 x_draw_window_cursor,
10549 x_draw_vertical_window_border,
10550 x_shift_glyphs_for_insert
10554 /* This function is called when the last frame on a display is deleted. */
10555 void
10556 x_delete_terminal (struct terminal *terminal)
10558 struct x_display_info *dpyinfo = terminal->display_info.x;
10560 /* Protect against recursive calls. delete_frame in
10561 delete_terminal calls us back when it deletes our last frame. */
10562 if (!terminal->name)
10563 return;
10565 BLOCK_INPUT;
10566 #ifdef HAVE_X_I18N
10567 /* We must close our connection to the XIM server before closing the
10568 X display. */
10569 if (dpyinfo->xim)
10570 xim_close_dpy (dpyinfo);
10571 #endif
10573 /* If called from x_connection_closed, the display may already be closed
10574 and dpyinfo->display was set to 0 to indicate that. */
10575 if (dpyinfo->display)
10577 x_destroy_all_bitmaps (dpyinfo);
10578 XSetCloseDownMode (dpyinfo->display, DestroyAll);
10580 /* Whether or not XCloseDisplay destroys the associated resource
10581 database depends on the version of libX11. To avoid both
10582 crash and memory leak, we dissociate the database from the
10583 display and then destroy dpyinfo->xrdb ourselves.
10585 Unfortunately, the above strategy does not work in some
10586 situations due to a bug in newer versions of libX11: because
10587 XrmSetDatabase doesn't clear the flag XlibDisplayDfltRMDB if
10588 dpy->db is NULL, XCloseDisplay destroys the associated
10589 database whereas it has not been created by XGetDefault
10590 (Bug#21974 in freedesktop.org Bugzilla). As a workaround, we
10591 don't destroy the database here in order to avoid the crash
10592 in the above situations for now, though that may cause memory
10593 leaks in other situations. */
10594 #if 0
10595 #ifdef HAVE_XRMSETDATABASE
10596 XrmSetDatabase (dpyinfo->display, NULL);
10597 #else
10598 dpyinfo->display->db = NULL;
10599 #endif
10600 /* We used to call XrmDestroyDatabase from x_delete_display, but
10601 some older versions of libX11 crash if we call it after
10602 closing all the displays. */
10603 XrmDestroyDatabase (dpyinfo->xrdb);
10604 #endif
10606 #ifdef USE_GTK
10607 xg_display_close (dpyinfo->display);
10608 #else
10609 #ifdef USE_X_TOOLKIT
10610 XtCloseDisplay (dpyinfo->display);
10611 #else
10612 XCloseDisplay (dpyinfo->display);
10613 #endif
10614 #endif /* ! USE_GTK */
10617 /* Mark as dead. */
10618 dpyinfo->display = NULL;
10619 x_delete_display (dpyinfo);
10620 UNBLOCK_INPUT;
10623 /* Create a struct terminal, initialize it with the X11 specific
10624 functions and make DISPLAY->TERMINAL point to it. */
10626 static struct terminal *
10627 x_create_terminal (struct x_display_info *dpyinfo)
10629 struct terminal *terminal;
10631 terminal = create_terminal ();
10633 terminal->type = output_x_window;
10634 terminal->display_info.x = dpyinfo;
10635 dpyinfo->terminal = terminal;
10637 /* kboard is initialized in x_term_init. */
10639 terminal->clear_frame_hook = x_clear_frame;
10640 terminal->ins_del_lines_hook = x_ins_del_lines;
10641 terminal->delete_glyphs_hook = x_delete_glyphs;
10642 terminal->ring_bell_hook = XTring_bell;
10643 terminal->toggle_invisible_pointer_hook = XTtoggle_invisible_pointer;
10644 terminal->reset_terminal_modes_hook = XTreset_terminal_modes;
10645 terminal->set_terminal_modes_hook = XTset_terminal_modes;
10646 terminal->update_begin_hook = x_update_begin;
10647 terminal->update_end_hook = x_update_end;
10648 terminal->set_terminal_window_hook = XTset_terminal_window;
10649 terminal->read_socket_hook = XTread_socket;
10650 terminal->frame_up_to_date_hook = XTframe_up_to_date;
10651 terminal->mouse_position_hook = XTmouse_position;
10652 terminal->frame_rehighlight_hook = XTframe_rehighlight;
10653 terminal->frame_raise_lower_hook = XTframe_raise_lower;
10654 terminal->fullscreen_hook = XTfullscreen_hook;
10655 terminal->set_vertical_scroll_bar_hook = XTset_vertical_scroll_bar;
10656 terminal->condemn_scroll_bars_hook = XTcondemn_scroll_bars;
10657 terminal->redeem_scroll_bar_hook = XTredeem_scroll_bar;
10658 terminal->judge_scroll_bars_hook = XTjudge_scroll_bars;
10660 terminal->delete_frame_hook = x_destroy_window;
10661 terminal->delete_terminal_hook = x_delete_terminal;
10663 terminal->rif = &x_redisplay_interface;
10664 terminal->scroll_region_ok = 1; /* We'll scroll partial frames. */
10665 terminal->char_ins_del_ok = 1;
10666 terminal->line_ins_del_ok = 1; /* We'll just blt 'em. */
10667 terminal->fast_clear_end_of_line = 1; /* X does this well. */
10668 terminal->memory_below_frame = 0; /* We don't remember what scrolls
10669 off the bottom. */
10671 return terminal;
10674 void
10675 x_initialize (void)
10677 baud_rate = 19200;
10679 x_noop_count = 0;
10680 last_tool_bar_item = -1;
10681 any_help_event_p = 0;
10682 ignore_next_mouse_click_timeout = 0;
10684 #ifdef USE_GTK
10685 current_count = -1;
10686 #endif
10688 /* Try to use interrupt input; if we can't, then start polling. */
10689 Fset_input_interrupt_mode (Qt);
10691 #ifdef USE_X_TOOLKIT
10692 XtToolkitInitialize ();
10694 Xt_app_con = XtCreateApplicationContext ();
10696 /* Register a converter from strings to pixels, which uses
10697 Emacs' color allocation infrastructure. */
10698 XtAppSetTypeConverter (Xt_app_con,
10699 XtRString, XtRPixel, cvt_string_to_pixel,
10700 cvt_string_to_pixel_args,
10701 XtNumber (cvt_string_to_pixel_args),
10702 XtCacheByDisplay, cvt_pixel_dtor);
10704 XtAppSetFallbackResources (Xt_app_con, Xt_default_resources);
10705 #endif
10707 #ifdef USE_TOOLKIT_SCROLL_BARS
10708 #ifndef USE_GTK
10709 xaw3d_arrow_scroll = False;
10710 xaw3d_pick_top = True;
10711 #endif
10712 #endif
10714 pending_autoraise_frame = 0;
10715 pending_event_wait.f = 0;
10716 pending_event_wait.eventtype = 0;
10718 /* Note that there is no real way portable across R3/R4 to get the
10719 original error handler. */
10720 XSetErrorHandler (x_error_handler);
10721 XSetIOErrorHandler (x_io_error_quitter);
10723 signal (SIGPIPE, x_connection_signal);
10725 xgselect_initialize ();
10729 void
10730 syms_of_xterm (void)
10732 x_error_message = NULL;
10734 staticpro (&x_display_name_list);
10735 x_display_name_list = Qnil;
10737 staticpro (&last_mouse_scroll_bar);
10738 last_mouse_scroll_bar = Qnil;
10740 DEFSYM (Qvendor_specific_keysyms, "vendor-specific-keysyms");
10741 DEFSYM (Qlatin_1, "latin-1");
10743 staticpro (&last_mouse_press_frame);
10744 last_mouse_press_frame = Qnil;
10746 #ifdef USE_GTK
10747 xg_default_icon_file = make_pure_c_string ("icons/hicolor/scalable/apps/emacs.svg");
10748 staticpro (&xg_default_icon_file);
10750 DEFSYM (Qx_gtk_map_stock, "x-gtk-map-stock");
10751 #endif
10753 DEFVAR_BOOL ("x-use-underline-position-properties",
10754 x_use_underline_position_properties,
10755 doc: /* *Non-nil means make use of UNDERLINE_POSITION font properties.
10756 A value of nil means ignore them. If you encounter fonts with bogus
10757 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
10758 to 4.1, set this to nil. You can also use `underline-minimum-offset'
10759 to override the font's UNDERLINE_POSITION for small font display
10760 sizes. */);
10761 x_use_underline_position_properties = 1;
10763 DEFVAR_BOOL ("x-underline-at-descent-line",
10764 x_underline_at_descent_line,
10765 doc: /* *Non-nil means to draw the underline at the same place as the descent line.
10766 A value of nil means to draw the underline according to the value of the
10767 variable `x-use-underline-position-properties', which is usually at the
10768 baseline level. The default value is nil. */);
10769 x_underline_at_descent_line = 0;
10771 DEFVAR_BOOL ("x-mouse-click-focus-ignore-position",
10772 x_mouse_click_focus_ignore_position,
10773 doc: /* Non-nil means that a mouse click to focus a frame does not move point.
10774 This variable is only used when the window manager requires that you
10775 click on a frame to select it (give it focus). In that case, a value
10776 of nil, means that the selected window and cursor position changes to
10777 reflect the mouse click position, while a non-nil value means that the
10778 selected window or cursor position is preserved. */);
10779 x_mouse_click_focus_ignore_position = 0;
10781 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
10782 doc: /* Which toolkit scroll bars Emacs uses, if any.
10783 A value of nil means Emacs doesn't use toolkit scroll bars.
10784 With the X Window system, the value is a symbol describing the
10785 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
10786 With MS Windows, the value is t. */);
10787 #ifdef USE_TOOLKIT_SCROLL_BARS
10788 #ifdef USE_MOTIF
10789 Vx_toolkit_scroll_bars = intern_c_string ("motif");
10790 #elif defined HAVE_XAW3D
10791 Vx_toolkit_scroll_bars = intern_c_string ("xaw3d");
10792 #elif USE_GTK
10793 Vx_toolkit_scroll_bars = intern_c_string ("gtk");
10794 #else
10795 Vx_toolkit_scroll_bars = intern_c_string ("xaw");
10796 #endif
10797 #else
10798 Vx_toolkit_scroll_bars = Qnil;
10799 #endif
10801 staticpro (&last_mouse_motion_frame);
10802 last_mouse_motion_frame = Qnil;
10804 Qmodifier_value = intern_c_string ("modifier-value");
10805 Qalt = intern_c_string ("alt");
10806 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
10807 Qhyper = intern_c_string ("hyper");
10808 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
10809 Qmeta = intern_c_string ("meta");
10810 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
10811 Qsuper = intern_c_string ("super");
10812 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
10814 DEFVAR_LISP ("x-alt-keysym", Vx_alt_keysym,
10815 doc: /* Which keys Emacs uses for the alt modifier.
10816 This should be one of the symbols `alt', `hyper', `meta', `super'.
10817 For example, `alt' means use the Alt_L and Alt_R keysyms. The default
10818 is nil, which is the same as `alt'. */);
10819 Vx_alt_keysym = Qnil;
10821 DEFVAR_LISP ("x-hyper-keysym", Vx_hyper_keysym,
10822 doc: /* Which keys Emacs uses for the hyper modifier.
10823 This should be one of the symbols `alt', `hyper', `meta', `super'.
10824 For example, `hyper' means use the Hyper_L and Hyper_R keysyms. The
10825 default is nil, which is the same as `hyper'. */);
10826 Vx_hyper_keysym = Qnil;
10828 DEFVAR_LISP ("x-meta-keysym", Vx_meta_keysym,
10829 doc: /* Which keys Emacs uses for the meta modifier.
10830 This should be one of the symbols `alt', `hyper', `meta', `super'.
10831 For example, `meta' means use the Meta_L and Meta_R keysyms. The
10832 default is nil, which is the same as `meta'. */);
10833 Vx_meta_keysym = Qnil;
10835 DEFVAR_LISP ("x-super-keysym", Vx_super_keysym,
10836 doc: /* Which keys Emacs uses for the super modifier.
10837 This should be one of the symbols `alt', `hyper', `meta', `super'.
10838 For example, `super' means use the Super_L and Super_R keysyms. The
10839 default is nil, which is the same as `super'. */);
10840 Vx_super_keysym = Qnil;
10842 DEFVAR_LISP ("x-keysym-table", Vx_keysym_table,
10843 doc: /* Hash table of character codes indexed by X keysym codes. */);
10844 Vx_keysym_table = make_hash_table (Qeql, make_number (900),
10845 make_float (DEFAULT_REHASH_SIZE),
10846 make_float (DEFAULT_REHASH_THRESHOLD),
10847 Qnil, Qnil, Qnil);
10850 #endif /* HAVE_X_WINDOWS */