Merge from mainline.
[emacs.git] / src / xterm.c
blobc15539182f63f71d21ad446ec2b2db492f0db9fe
1 /* X Communication module for terminals which understand the X protocol.
2 Copyright (C) 1989, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
3 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
4 Free Software Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 /* New display code by Gerd Moellmann <gerd@gnu.org>. */
22 /* Xt features made by Fred Pierresteguy. */
24 #include <config.h>
25 #include <signal.h>
26 #include <stdio.h>
27 #include <setjmp.h>
29 #ifdef HAVE_X_WINDOWS
31 #include "lisp.h"
32 #include "blockinput.h"
34 /* Need syssignal.h for various externs and definitions that may be required
35 by some configurations for calls to signal later in this source file. */
36 #include "syssignal.h"
38 /* This may include sys/types.h, and that somehow loses
39 if this is not done before the other system files. */
40 #include "xterm.h"
41 #include <X11/cursorfont.h>
43 /* Load sys/types.h if not already loaded.
44 In some systems loading it twice is suicidal. */
45 #ifndef makedev
46 #include <sys/types.h>
47 #endif /* makedev */
49 #include <sys/ioctl.h>
51 #include "systime.h"
53 #include <fcntl.h>
54 #include <ctype.h>
55 #include <errno.h>
56 #include <setjmp.h>
57 #include <sys/stat.h>
58 /* Caused redefinition of DBL_DIG on Netbsd; seems not to be needed. */
59 /* #include <sys/param.h> */
61 #include "charset.h"
62 #include "character.h"
63 #include "coding.h"
64 #include "frame.h"
65 #include "dispextern.h"
66 #include "fontset.h"
67 #include "termhooks.h"
68 #include "termopts.h"
69 #include "termchar.h"
70 #include "emacs-icon.h"
71 #include "disptab.h"
72 #include "buffer.h"
73 #include "window.h"
74 #include "keyboard.h"
75 #include "intervals.h"
76 #include "process.h"
77 #include "atimer.h"
78 #include "keymap.h"
79 #include "font.h"
80 #include "fontset.h"
81 #include "xsettings.h"
82 #include "xgselect.h"
83 #include "sysselect.h"
85 #ifdef USE_X_TOOLKIT
86 #include <X11/Shell.h>
87 #endif
89 #ifdef HAVE_SYS_TIME_H
90 #include <sys/time.h>
91 #endif
93 #include <unistd.h>
95 #ifdef USE_GTK
96 #include "gtkutil.h"
97 #endif
99 #ifdef USE_LUCID
100 #include "../lwlib/xlwmenu.h"
101 #endif
103 #ifdef USE_X_TOOLKIT
104 #if !defined(NO_EDITRES)
105 #define HACK_EDITRES
106 extern void _XEditResCheckMessages ();
107 #endif /* not NO_EDITRES */
109 /* Include toolkit specific headers for the scroll bar widget. */
111 #ifdef USE_TOOLKIT_SCROLL_BARS
112 #if defined USE_MOTIF
113 #include <Xm/Xm.h> /* for LESSTIF_VERSION */
114 #include <Xm/ScrollBar.h>
115 #else /* !USE_MOTIF i.e. use Xaw */
117 #ifdef HAVE_XAW3D
118 #include <X11/Xaw3d/Simple.h>
119 #include <X11/Xaw3d/Scrollbar.h>
120 #include <X11/Xaw3d/ThreeD.h>
121 #else /* !HAVE_XAW3D */
122 #include <X11/Xaw/Simple.h>
123 #include <X11/Xaw/Scrollbar.h>
124 #endif /* !HAVE_XAW3D */
125 #ifndef XtNpickTop
126 #define XtNpickTop "pickTop"
127 #endif /* !XtNpickTop */
128 #endif /* !USE_MOTIF */
129 #endif /* USE_TOOLKIT_SCROLL_BARS */
131 #endif /* USE_X_TOOLKIT */
133 #ifdef USE_X_TOOLKIT
134 #include "widget.h"
135 #ifndef XtNinitialState
136 #define XtNinitialState "initialState"
137 #endif
138 #endif
140 /* Default to using XIM if available. */
141 #ifdef USE_XIM
142 int use_xim = 1;
143 #else
144 int use_xim = 0; /* configure --without-xim */
145 #endif
149 /* Non-nil means Emacs uses toolkit scroll bars. */
151 Lisp_Object Vx_toolkit_scroll_bars;
153 /* Non-zero means that a HELP_EVENT has been generated since Emacs
154 start. */
156 static int any_help_event_p;
158 /* Last window where we saw the mouse. Used by mouse-autoselect-window. */
159 static Lisp_Object last_window;
161 /* Non-zero means make use of UNDERLINE_POSITION font properties. */
163 int x_use_underline_position_properties;
165 /* Non-zero means to draw the underline at the same place as the descent line. */
167 int x_underline_at_descent_line;
169 /* This is a chain of structures for all the X displays currently in
170 use. */
172 struct x_display_info *x_display_list;
174 /* This is a list of cons cells, each of the form (NAME
175 . FONT-LIST-CACHE), one for each element of x_display_list and in
176 the same order. NAME is the name of the frame. FONT-LIST-CACHE
177 records previous values returned by x-list-fonts. */
179 Lisp_Object x_display_name_list;
181 /* Frame being updated by update_frame. This is declared in term.c.
182 This is set by update_begin and looked at by all the XT functions.
183 It is zero while not inside an update. In that case, the XT
184 functions assume that `selected_frame' is the frame to apply to. */
186 extern struct frame *updating_frame;
188 /* This is a frame waiting to be auto-raised, within XTread_socket. */
190 static struct frame *pending_autoraise_frame;
192 /* This is a frame waiting for an event matching mask, within XTread_socket. */
194 static struct {
195 struct frame *f;
196 int eventtype;
197 } pending_event_wait;
199 #ifdef USE_X_TOOLKIT
200 /* The application context for Xt use. */
201 XtAppContext Xt_app_con;
202 static String Xt_default_resources[] = {0};
203 #endif /* USE_X_TOOLKIT */
205 /* Non-zero means user is interacting with a toolkit scroll bar. */
207 static int toolkit_scroll_bar_interaction;
209 /* Non-zero means to not move point as a result of clicking on a
210 frame to focus it (when focus-follows-mouse is nil). */
212 int x_mouse_click_focus_ignore_position;
214 /* Non-zero timeout value means ignore next mouse click if it arrives
215 before that timeout elapses (i.e. as part of the same sequence of
216 events resulting from clicking on a frame to select it). */
218 static unsigned long ignore_next_mouse_click_timeout;
220 /* Mouse movement.
222 Formerly, we used PointerMotionHintMask (in standard_event_mask)
223 so that we would have to call XQueryPointer after each MotionNotify
224 event to ask for another such event. However, this made mouse tracking
225 slow, and there was a bug that made it eventually stop.
227 Simply asking for MotionNotify all the time seems to work better.
229 In order to avoid asking for motion events and then throwing most
230 of them away or busy-polling the server for mouse positions, we ask
231 the server for pointer motion hints. This means that we get only
232 one event per group of mouse movements. "Groups" are delimited by
233 other kinds of events (focus changes and button clicks, for
234 example), or by XQueryPointer calls; when one of these happens, we
235 get another MotionNotify event the next time the mouse moves. This
236 is at least as efficient as getting motion events when mouse
237 tracking is on, and I suspect only negligibly worse when tracking
238 is off. */
240 /* Where the mouse was last time we reported a mouse event. */
242 static XRectangle last_mouse_glyph;
243 static FRAME_PTR last_mouse_glyph_frame;
244 static Lisp_Object last_mouse_press_frame;
246 /* The scroll bar in which the last X motion event occurred.
248 If the last X motion event occurred in a scroll bar, we set this so
249 XTmouse_position can know whether to report a scroll bar motion or
250 an ordinary motion.
252 If the last X motion event didn't occur in a scroll bar, we set
253 this to Qnil, to tell XTmouse_position to return an ordinary motion
254 event. */
256 static Lisp_Object last_mouse_scroll_bar;
258 /* This is a hack. We would really prefer that XTmouse_position would
259 return the time associated with the position it returns, but there
260 doesn't seem to be any way to wrest the time-stamp from the server
261 along with the position query. So, we just keep track of the time
262 of the last movement we received, and return that in hopes that
263 it's somewhat accurate. */
265 static Time last_mouse_movement_time;
267 /* Time for last user interaction as returned in X events. */
269 static Time last_user_time;
271 /* Incremented by XTread_socket whenever it really tries to read
272 events. */
274 #ifdef __STDC__
275 static int volatile input_signal_count;
276 #else
277 static int input_signal_count;
278 #endif
280 /* Used locally within XTread_socket. */
282 static int x_noop_count;
284 /* The keysyms to use for the various modifiers. */
286 Lisp_Object Vx_alt_keysym, Vx_hyper_keysym, Vx_meta_keysym, Vx_super_keysym;
287 Lisp_Object Vx_keysym_table;
288 static Lisp_Object Qalt, Qhyper, Qmeta, Qsuper, Qmodifier_value;
290 static Lisp_Object Qvendor_specific_keysyms;
291 static Lisp_Object Qlatin_1;
293 #ifdef USE_GTK
294 /* The name of the Emacs icon file. */
295 static Lisp_Object xg_default_icon_file;
297 /* Used in gtkutil.c. */
298 Lisp_Object Qx_gtk_map_stock;
299 #endif
301 /* Some functions take this as char *, not const char *. */
302 static char emacs_class[] = EMACS_CLASS;
304 /* XEmbed implementation. */
306 #define XEMBED_VERSION 0
308 enum xembed_info
310 XEMBED_MAPPED = 1 << 0
313 enum xembed_message
315 XEMBED_EMBEDDED_NOTIFY = 0,
316 XEMBED_WINDOW_ACTIVATE = 1,
317 XEMBED_WINDOW_DEACTIVATE = 2,
318 XEMBED_REQUEST_FOCUS = 3,
319 XEMBED_FOCUS_IN = 4,
320 XEMBED_FOCUS_OUT = 5,
321 XEMBED_FOCUS_NEXT = 6,
322 XEMBED_FOCUS_PREV = 7,
324 XEMBED_MODALITY_ON = 10,
325 XEMBED_MODALITY_OFF = 11,
326 XEMBED_REGISTER_ACCELERATOR = 12,
327 XEMBED_UNREGISTER_ACCELERATOR = 13,
328 XEMBED_ACTIVATE_ACCELERATOR = 14
331 /* Used in x_flush. */
333 static int x_alloc_nearest_color_1 (Display *, Colormap, XColor *);
334 static void x_set_window_size_1 (struct frame *, int, int, int);
335 static const XColor *x_color_cells (Display *, int *);
336 static void x_update_window_end (struct window *, int, int);
338 static int x_io_error_quitter (Display *);
339 static struct terminal *x_create_terminal (struct x_display_info *);
340 void x_delete_terminal (struct terminal *);
341 static void x_update_end (struct frame *);
342 static void XTframe_up_to_date (struct frame *);
343 static void XTset_terminal_modes (struct terminal *);
344 static void XTreset_terminal_modes (struct terminal *);
345 static void x_clear_frame (struct frame *);
346 static void frame_highlight (struct frame *);
347 static void frame_unhighlight (struct frame *);
348 static void x_new_focus_frame (struct x_display_info *, struct frame *);
349 static void x_focus_changed (int, int, struct x_display_info *,
350 struct frame *, struct input_event *);
351 static void x_detect_focus_change (struct x_display_info *,
352 XEvent *, struct input_event *);
353 static void XTframe_rehighlight (struct frame *);
354 static void x_frame_rehighlight (struct x_display_info *);
355 static void x_draw_hollow_cursor (struct window *, struct glyph_row *);
356 static void x_draw_bar_cursor (struct window *, struct glyph_row *, int,
357 enum text_cursor_kinds);
359 static void x_clip_to_row (struct window *, struct glyph_row *, int, GC);
360 static void x_flush (struct frame *f);
361 static void x_update_begin (struct frame *);
362 static void x_update_window_begin (struct window *);
363 static void x_after_update_window_line (struct glyph_row *);
364 static struct scroll_bar *x_window_to_scroll_bar (Display *, Window);
365 static void x_scroll_bar_report_motion (struct frame **, Lisp_Object *,
366 enum scroll_bar_part *,
367 Lisp_Object *, Lisp_Object *,
368 unsigned long *);
369 static void x_handle_net_wm_state (struct frame *, XPropertyEvent *);
370 static void x_check_fullscreen (struct frame *);
371 static void x_check_expected_move (struct frame *, int, int);
372 static void x_sync_with_move (struct frame *, int, int, int);
373 static int handle_one_xevent (struct x_display_info *, XEvent *,
374 int *, struct input_event *);
375 /* Don't declare this NO_RETURN because we want no
376 interference with debugging failing X calls. */
377 static SIGTYPE x_connection_closed (Display *, const char *);
380 /* Flush display of frame F, or of all frames if F is null. */
382 static void
383 x_flush (struct frame *f)
385 /* Don't call XFlush when it is not safe to redisplay; the X
386 connection may be broken. */
387 if (!NILP (Vinhibit_redisplay))
388 return;
390 BLOCK_INPUT;
391 if (f == NULL)
393 Lisp_Object rest, frame;
394 FOR_EACH_FRAME (rest, frame)
395 if (FRAME_X_P (XFRAME (frame)))
396 x_flush (XFRAME (frame));
398 else if (FRAME_X_P (f))
399 XFlush (FRAME_X_DISPLAY (f));
400 UNBLOCK_INPUT;
404 /* Remove calls to XFlush by defining XFlush to an empty replacement.
405 Calls to XFlush should be unnecessary because the X output buffer
406 is flushed automatically as needed by calls to XPending,
407 XNextEvent, or XWindowEvent according to the XFlush man page.
408 XTread_socket calls XPending. Removing XFlush improves
409 performance. */
411 #define XFlush(DISPLAY) (void) 0
414 /***********************************************************************
415 Debugging
416 ***********************************************************************/
418 #if 0
420 /* This is a function useful for recording debugging information about
421 the sequence of occurrences in this file. */
423 struct record
425 char *locus;
426 int type;
429 struct record event_record[100];
431 int event_record_index;
433 void
434 record_event (char *locus, int type)
436 if (event_record_index == sizeof (event_record) / sizeof (struct record))
437 event_record_index = 0;
439 event_record[event_record_index].locus = locus;
440 event_record[event_record_index].type = type;
441 event_record_index++;
444 #endif /* 0 */
448 /* Return the struct x_display_info corresponding to DPY. */
450 struct x_display_info *
451 x_display_info_for_display (Display *dpy)
453 struct x_display_info *dpyinfo;
455 for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
456 if (dpyinfo->display == dpy)
457 return dpyinfo;
459 return 0;
462 #define OPAQUE 0xffffffff
464 void
465 x_set_frame_alpha (struct frame *f)
467 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
468 Display *dpy = FRAME_X_DISPLAY (f);
469 Window win = FRAME_OUTER_WINDOW (f);
470 double alpha = 1.0;
471 double alpha_min = 1.0;
472 unsigned long opac;
474 if (FRAME_X_DISPLAY_INFO (f)->root_window != FRAME_X_OUTPUT (f)->parent_desc)
475 /* Since the WM decoration lies under the FRAME_OUTER_WINDOW,
476 we must treat the former instead of the latter. */
477 win = FRAME_X_OUTPUT (f)->parent_desc;
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 /* return unless necessary */
500 unsigned char *data;
501 Atom actual;
502 int rc, format;
503 unsigned long n, left;
505 x_catch_errors (dpy);
506 rc = XGetWindowProperty (dpy, win, dpyinfo->Xatom_net_wm_window_opacity,
507 0L, 1L, False, XA_CARDINAL,
508 &actual, &format, &n, &left,
509 &data);
511 if (rc == Success && actual != None)
513 XFree ((void *) data);
514 if (*(unsigned long *)data == opac)
516 x_uncatch_errors ();
517 return;
520 x_uncatch_errors ();
523 x_catch_errors (dpy);
524 XChangeProperty (dpy, win, dpyinfo->Xatom_net_wm_window_opacity,
525 XA_CARDINAL, 32, PropModeReplace,
526 (unsigned char *) &opac, 1L);
527 x_uncatch_errors ();
531 x_display_pixel_height (struct x_display_info *dpyinfo)
533 return HeightOfScreen (dpyinfo->screen);
537 x_display_pixel_width (struct x_display_info *dpyinfo)
539 return WidthOfScreen (dpyinfo->screen);
543 /***********************************************************************
544 Starting and ending an update
545 ***********************************************************************/
547 /* Start an update of frame F. This function is installed as a hook
548 for update_begin, i.e. it is called when update_begin is called.
549 This function is called prior to calls to x_update_window_begin for
550 each window being updated. Currently, there is nothing to do here
551 because all interesting stuff is done on a window basis. */
553 static void
554 x_update_begin (struct frame *f)
556 /* Nothing to do. */
560 /* Start update of window W. Set the global variable updated_window
561 to the window being updated and set output_cursor to the cursor
562 position of W. */
564 static void
565 x_update_window_begin (struct window *w)
567 struct frame *f = XFRAME (WINDOW_FRAME (w));
568 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
570 updated_window = w;
571 set_output_cursor (&w->cursor);
573 BLOCK_INPUT;
575 if (f == hlinfo->mouse_face_mouse_frame)
577 /* Don't do highlighting for mouse motion during the update. */
578 hlinfo->mouse_face_defer = 1;
580 /* If F needs to be redrawn, simply forget about any prior mouse
581 highlighting. */
582 if (FRAME_GARBAGED_P (f))
583 hlinfo->mouse_face_window = Qnil;
586 UNBLOCK_INPUT;
590 /* Draw a vertical window border from (x,y0) to (x,y1) */
592 static void
593 x_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
595 struct frame *f = XFRAME (WINDOW_FRAME (w));
596 struct face *face;
598 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
599 if (face)
600 XSetForeground (FRAME_X_DISPLAY (f), f->output_data.x->normal_gc,
601 face->foreground);
603 XDrawLine (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
604 f->output_data.x->normal_gc, x, y0, x, y1);
607 /* End update of window W (which is equal to updated_window).
609 Draw vertical borders between horizontally adjacent windows, and
610 display W's cursor if CURSOR_ON_P is non-zero.
612 MOUSE_FACE_OVERWRITTEN_P non-zero means that some row containing
613 glyphs in mouse-face were overwritten. In that case we have to
614 make sure that the mouse-highlight is properly redrawn.
616 W may be a menu bar pseudo-window in case we don't have X toolkit
617 support. Such windows don't have a cursor, so don't display it
618 here. */
620 static void
621 x_update_window_end (struct window *w, int cursor_on_p, int mouse_face_overwritten_p)
623 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (XFRAME (w->frame));
625 if (!w->pseudo_window_p)
627 BLOCK_INPUT;
629 if (cursor_on_p)
630 display_and_set_cursor (w, 1, output_cursor.hpos,
631 output_cursor.vpos,
632 output_cursor.x, output_cursor.y);
634 if (draw_window_fringes (w, 1))
635 x_draw_vertical_border (w);
637 UNBLOCK_INPUT;
640 /* If a row with mouse-face was overwritten, arrange for
641 XTframe_up_to_date to redisplay the mouse highlight. */
642 if (mouse_face_overwritten_p)
644 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
645 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
646 hlinfo->mouse_face_window = Qnil;
649 updated_window = NULL;
653 /* End update of frame F. This function is installed as a hook in
654 update_end. */
656 static void
657 x_update_end (struct frame *f)
659 /* Mouse highlight may be displayed again. */
660 MOUSE_HL_INFO (f)->mouse_face_defer = 0;
662 #ifndef XFlush
663 BLOCK_INPUT;
664 XFlush (FRAME_X_DISPLAY (f));
665 UNBLOCK_INPUT;
666 #endif
670 /* This function is called from various places in xdisp.c whenever a
671 complete update has been performed. The global variable
672 updated_window is not available here. */
674 static void
675 XTframe_up_to_date (struct frame *f)
677 if (FRAME_X_P (f))
679 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
681 if (hlinfo->mouse_face_deferred_gc
682 || f == hlinfo->mouse_face_mouse_frame)
684 BLOCK_INPUT;
685 if (hlinfo->mouse_face_mouse_frame)
686 note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
687 hlinfo->mouse_face_mouse_x,
688 hlinfo->mouse_face_mouse_y);
689 hlinfo->mouse_face_deferred_gc = 0;
690 UNBLOCK_INPUT;
696 /* Draw truncation mark bitmaps, continuation mark bitmaps, overlay
697 arrow bitmaps, or clear the fringes if no bitmaps are required
698 before DESIRED_ROW is made current. The window being updated is
699 found in updated_window. This function It is called from
700 update_window_line only if it is known that there are differences
701 between bitmaps to be drawn between current row and DESIRED_ROW. */
703 static void
704 x_after_update_window_line (struct glyph_row *desired_row)
706 struct window *w = updated_window;
707 struct frame *f;
708 int width, height;
710 xassert (w);
712 if (!desired_row->mode_line_p && !w->pseudo_window_p)
713 desired_row->redraw_fringe_bitmaps_p = 1;
715 /* When a window has disappeared, make sure that no rest of
716 full-width rows stays visible in the internal border. Could
717 check here if updated_window is the leftmost/rightmost window,
718 but I guess it's not worth doing since vertically split windows
719 are almost never used, internal border is rarely set, and the
720 overhead is very small. */
721 if (windows_or_buffers_changed
722 && desired_row->full_width_p
723 && (f = XFRAME (w->frame),
724 width = FRAME_INTERNAL_BORDER_WIDTH (f),
725 width != 0)
726 && (height = desired_row->visible_height,
727 height > 0))
729 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
731 BLOCK_INPUT;
732 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
733 0, y, width, height, False);
734 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
735 FRAME_PIXEL_WIDTH (f) - width,
736 y, width, height, False);
737 UNBLOCK_INPUT;
741 static void
742 x_draw_fringe_bitmap (struct window *w, struct glyph_row *row, struct draw_fringe_bitmap_params *p)
744 struct frame *f = XFRAME (WINDOW_FRAME (w));
745 Display *display = FRAME_X_DISPLAY (f);
746 Window window = FRAME_X_WINDOW (f);
747 GC gc = f->output_data.x->normal_gc;
748 struct face *face = p->face;
750 /* Must clip because of partially visible lines. */
751 x_clip_to_row (w, row, -1, gc);
753 if (!p->overlay_p)
755 int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
757 /* In case the same realized face is used for fringes and
758 for something displayed in the text (e.g. face `region' on
759 mono-displays, the fill style may have been changed to
760 FillSolid in x_draw_glyph_string_background. */
761 if (face->stipple)
762 XSetFillStyle (display, face->gc, FillOpaqueStippled);
763 else
764 XSetForeground (display, face->gc, face->background);
766 #ifdef USE_TOOLKIT_SCROLL_BARS
767 /* If the fringe is adjacent to the left (right) scroll bar of a
768 leftmost (rightmost, respectively) window, then extend its
769 background to the gap between the fringe and the bar. */
770 if ((WINDOW_LEFTMOST_P (w)
771 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
772 || (WINDOW_RIGHTMOST_P (w)
773 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w)))
775 int sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
777 if (sb_width > 0)
779 int left = WINDOW_SCROLL_BAR_AREA_X (w);
780 int width = (WINDOW_CONFIG_SCROLL_BAR_COLS (w)
781 * FRAME_COLUMN_WIDTH (f));
783 if (bx < 0)
785 /* Bitmap fills the fringe. */
786 if (left + width == p->x)
787 bx = left + sb_width;
788 else if (p->x + p->wd == left)
789 bx = left;
790 if (bx >= 0)
792 int header_line_height = WINDOW_HEADER_LINE_HEIGHT (w);
794 nx = width - sb_width;
795 by = WINDOW_TO_FRAME_PIXEL_Y (w, max (header_line_height,
796 row->y));
797 ny = row->visible_height;
800 else
802 if (left + width == bx)
804 bx = left + sb_width;
805 nx += width - sb_width;
807 else if (bx + nx == left)
808 nx += width - sb_width;
812 #endif
813 if (bx >= 0 && nx > 0)
814 XFillRectangle (display, window, face->gc, bx, by, nx, ny);
816 if (!face->stipple)
817 XSetForeground (display, face->gc, face->foreground);
820 if (p->which)
822 unsigned char *bits;
823 Pixmap pixmap, clipmask = (Pixmap) 0;
824 int depth = DefaultDepthOfScreen (FRAME_X_SCREEN (f));
825 XGCValues gcv;
827 if (p->wd > 8)
828 bits = (unsigned char *)(p->bits + p->dh);
829 else
830 bits = (unsigned char *)p->bits + p->dh;
832 /* Draw the bitmap. I believe these small pixmaps can be cached
833 by the server. */
834 pixmap = XCreatePixmapFromBitmapData (display, window, bits, p->wd, p->h,
835 (p->cursor_p
836 ? (p->overlay_p ? face->background
837 : f->output_data.x->cursor_pixel)
838 : face->foreground),
839 face->background, depth);
841 if (p->overlay_p)
843 clipmask = XCreatePixmapFromBitmapData (display,
844 FRAME_X_DISPLAY_INFO (f)->root_window,
845 bits, p->wd, p->h,
846 1, 0, 1);
847 gcv.clip_mask = clipmask;
848 gcv.clip_x_origin = p->x;
849 gcv.clip_y_origin = p->y;
850 XChangeGC (display, gc, GCClipMask | GCClipXOrigin | GCClipYOrigin, &gcv);
853 XCopyArea (display, pixmap, window, gc, 0, 0,
854 p->wd, p->h, p->x, p->y);
855 XFreePixmap (display, pixmap);
857 if (p->overlay_p)
859 gcv.clip_mask = (Pixmap) 0;
860 XChangeGC (display, gc, GCClipMask, &gcv);
861 XFreePixmap (display, clipmask);
865 XSetClipMask (display, gc, None);
870 /* This is called when starting Emacs and when restarting after
871 suspend. When starting Emacs, no X window is mapped. And nothing
872 must be done to Emacs's own window if it is suspended (though that
873 rarely happens). */
875 static void
876 XTset_terminal_modes (struct terminal *terminal)
880 /* This is called when exiting or suspending Emacs. Exiting will make
881 the X-windows go away, and suspending requires no action. */
883 static void
884 XTreset_terminal_modes (struct terminal *terminal)
889 /***********************************************************************
890 Glyph display
891 ***********************************************************************/
895 static void x_set_glyph_string_clipping (struct glyph_string *);
896 static void x_set_glyph_string_gc (struct glyph_string *);
897 static void x_draw_glyph_string_background (struct glyph_string *,
898 int);
899 static void x_draw_glyph_string_foreground (struct glyph_string *);
900 static void x_draw_composite_glyph_string_foreground (struct glyph_string *);
901 static void x_draw_glyph_string_box (struct glyph_string *);
902 static void x_draw_glyph_string (struct glyph_string *);
903 static void x_compute_glyph_string_overhangs (struct glyph_string *);
904 static void x_set_cursor_gc (struct glyph_string *);
905 static void x_set_mode_line_face_gc (struct glyph_string *);
906 static void x_set_mouse_face_gc (struct glyph_string *);
907 static int x_alloc_lighter_color (struct frame *, Display *, Colormap,
908 unsigned long *, double, int);
909 static void x_setup_relief_color (struct frame *, struct relief *,
910 double, int, unsigned long);
911 static void x_setup_relief_colors (struct glyph_string *);
912 static void x_draw_image_glyph_string (struct glyph_string *);
913 static void x_draw_image_relief (struct glyph_string *);
914 static void x_draw_image_foreground (struct glyph_string *);
915 static void x_draw_image_foreground_1 (struct glyph_string *, Pixmap);
916 static void x_clear_glyph_string_rect (struct glyph_string *, int,
917 int, int, int);
918 static void x_draw_relief_rect (struct frame *, int, int, int, int,
919 int, int, int, int, int, int,
920 XRectangle *);
921 static void x_draw_box_rect (struct glyph_string *, int, int, int, int,
922 int, int, int, XRectangle *);
923 static void x_scroll_bar_clear (struct frame *);
925 #if GLYPH_DEBUG
926 static void x_check_font (struct frame *, struct font *);
927 #endif
930 /* Set S->gc to a suitable GC for drawing glyph string S in cursor
931 face. */
933 static void
934 x_set_cursor_gc (struct glyph_string *s)
936 if (s->font == FRAME_FONT (s->f)
937 && s->face->background == FRAME_BACKGROUND_PIXEL (s->f)
938 && s->face->foreground == FRAME_FOREGROUND_PIXEL (s->f)
939 && !s->cmp)
940 s->gc = s->f->output_data.x->cursor_gc;
941 else
943 /* Cursor on non-default face: must merge. */
944 XGCValues xgcv;
945 unsigned long mask;
947 xgcv.background = s->f->output_data.x->cursor_pixel;
948 xgcv.foreground = s->face->background;
950 /* If the glyph would be invisible, try a different foreground. */
951 if (xgcv.foreground == xgcv.background)
952 xgcv.foreground = s->face->foreground;
953 if (xgcv.foreground == xgcv.background)
954 xgcv.foreground = s->f->output_data.x->cursor_foreground_pixel;
955 if (xgcv.foreground == xgcv.background)
956 xgcv.foreground = s->face->foreground;
958 /* Make sure the cursor is distinct from text in this face. */
959 if (xgcv.background == s->face->background
960 && xgcv.foreground == s->face->foreground)
962 xgcv.background = s->face->foreground;
963 xgcv.foreground = s->face->background;
966 IF_DEBUG (x_check_font (s->f, s->font));
967 xgcv.graphics_exposures = False;
968 mask = GCForeground | GCBackground | GCGraphicsExposures;
970 if (FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc)
971 XChangeGC (s->display, FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc,
972 mask, &xgcv);
973 else
974 FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc
975 = XCreateGC (s->display, s->window, mask, &xgcv);
977 s->gc = FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc;
982 /* Set up S->gc of glyph string S for drawing text in mouse face. */
984 static void
985 x_set_mouse_face_gc (struct glyph_string *s)
987 int face_id;
988 struct face *face;
990 /* What face has to be used last for the mouse face? */
991 face_id = MOUSE_HL_INFO (s->f)->mouse_face_face_id;
992 face = FACE_FROM_ID (s->f, face_id);
993 if (face == NULL)
994 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
996 if (s->first_glyph->type == CHAR_GLYPH)
997 face_id = FACE_FOR_CHAR (s->f, face, s->first_glyph->u.ch, -1, Qnil);
998 else
999 face_id = FACE_FOR_CHAR (s->f, face, 0, -1, Qnil);
1000 s->face = FACE_FROM_ID (s->f, face_id);
1001 PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
1003 if (s->font == s->face->font)
1004 s->gc = s->face->gc;
1005 else
1007 /* Otherwise construct scratch_cursor_gc with values from FACE
1008 except for FONT. */
1009 XGCValues xgcv;
1010 unsigned long mask;
1012 xgcv.background = s->face->background;
1013 xgcv.foreground = s->face->foreground;
1014 xgcv.graphics_exposures = False;
1015 mask = GCForeground | GCBackground | GCGraphicsExposures;
1017 if (FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc)
1018 XChangeGC (s->display, FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc,
1019 mask, &xgcv);
1020 else
1021 FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc
1022 = XCreateGC (s->display, s->window, mask, &xgcv);
1024 s->gc = FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc;
1027 xassert (s->gc != 0);
1031 /* Set S->gc of glyph string S to a GC suitable for drawing a mode line.
1032 Faces to use in the mode line have already been computed when the
1033 matrix was built, so there isn't much to do, here. */
1035 static INLINE void
1036 x_set_mode_line_face_gc (struct glyph_string *s)
1038 s->gc = s->face->gc;
1042 /* Set S->gc of glyph string S for drawing that glyph string. Set
1043 S->stippled_p to a non-zero value if the face of S has a stipple
1044 pattern. */
1046 static INLINE void
1047 x_set_glyph_string_gc (struct glyph_string *s)
1049 PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
1051 if (s->hl == DRAW_NORMAL_TEXT)
1053 s->gc = s->face->gc;
1054 s->stippled_p = s->face->stipple != 0;
1056 else if (s->hl == DRAW_INVERSE_VIDEO)
1058 x_set_mode_line_face_gc (s);
1059 s->stippled_p = s->face->stipple != 0;
1061 else if (s->hl == DRAW_CURSOR)
1063 x_set_cursor_gc (s);
1064 s->stippled_p = 0;
1066 else if (s->hl == DRAW_MOUSE_FACE)
1068 x_set_mouse_face_gc (s);
1069 s->stippled_p = s->face->stipple != 0;
1071 else if (s->hl == DRAW_IMAGE_RAISED
1072 || s->hl == DRAW_IMAGE_SUNKEN)
1074 s->gc = s->face->gc;
1075 s->stippled_p = s->face->stipple != 0;
1077 else
1079 s->gc = s->face->gc;
1080 s->stippled_p = s->face->stipple != 0;
1083 /* GC must have been set. */
1084 xassert (s->gc != 0);
1088 /* Set clipping for output of glyph string S. S may be part of a mode
1089 line or menu if we don't have X toolkit support. */
1091 static INLINE void
1092 x_set_glyph_string_clipping (struct glyph_string *s)
1094 XRectangle *r = s->clip;
1095 int n = get_glyph_string_clip_rects (s, r, 2);
1097 if (n > 0)
1098 XSetClipRectangles (s->display, s->gc, 0, 0, r, n, Unsorted);
1099 s->num_clips = n;
1103 /* Set SRC's clipping for output of glyph string DST. This is called
1104 when we are drawing DST's left_overhang or right_overhang only in
1105 the area of SRC. */
1107 static void
1108 x_set_glyph_string_clipping_exactly (struct glyph_string *src, struct glyph_string *dst)
1110 XRectangle r;
1112 r.x = src->x;
1113 r.width = src->width;
1114 r.y = src->y;
1115 r.height = src->height;
1116 dst->clip[0] = r;
1117 dst->num_clips = 1;
1118 XSetClipRectangles (dst->display, dst->gc, 0, 0, &r, 1, Unsorted);
1122 /* RIF:
1123 Compute left and right overhang of glyph string S. */
1125 static void
1126 x_compute_glyph_string_overhangs (struct glyph_string *s)
1128 if (s->cmp == NULL
1129 && (s->first_glyph->type == CHAR_GLYPH
1130 || s->first_glyph->type == COMPOSITE_GLYPH))
1132 struct font_metrics metrics;
1134 if (s->first_glyph->type == CHAR_GLYPH)
1136 unsigned *code = alloca (sizeof (unsigned) * s->nchars);
1137 struct font *font = s->font;
1138 int i;
1140 for (i = 0; i < s->nchars; i++)
1141 code[i] = (s->char2b[i].byte1 << 8) | s->char2b[i].byte2;
1142 font->driver->text_extents (font, code, s->nchars, &metrics);
1144 else
1146 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1148 composition_gstring_width (gstring, s->cmp_from, s->cmp_to, &metrics);
1150 s->right_overhang = (metrics.rbearing > metrics.width
1151 ? metrics.rbearing - metrics.width : 0);
1152 s->left_overhang = metrics.lbearing < 0 ? - metrics.lbearing : 0;
1154 else if (s->cmp)
1156 s->right_overhang = s->cmp->rbearing - s->cmp->pixel_width;
1157 s->left_overhang = - s->cmp->lbearing;
1162 /* Fill rectangle X, Y, W, H with background color of glyph string S. */
1164 static INLINE void
1165 x_clear_glyph_string_rect (struct glyph_string *s, int x, int y, int w, int h)
1167 XGCValues xgcv;
1168 XGetGCValues (s->display, s->gc, GCForeground | GCBackground, &xgcv);
1169 XSetForeground (s->display, s->gc, xgcv.background);
1170 XFillRectangle (s->display, s->window, s->gc, x, y, w, h);
1171 XSetForeground (s->display, s->gc, xgcv.foreground);
1175 /* Draw the background of glyph_string S. If S->background_filled_p
1176 is non-zero don't draw it. FORCE_P non-zero means draw the
1177 background even if it wouldn't be drawn normally. This is used
1178 when a string preceding S draws into the background of S, or S
1179 contains the first component of a composition. */
1181 static void
1182 x_draw_glyph_string_background (struct glyph_string *s, int force_p)
1184 /* Nothing to do if background has already been drawn or if it
1185 shouldn't be drawn in the first place. */
1186 if (!s->background_filled_p)
1188 int box_line_width = max (s->face->box_line_width, 0);
1190 if (s->stippled_p)
1192 /* Fill background with a stipple pattern. */
1193 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
1194 XFillRectangle (s->display, s->window, s->gc, s->x,
1195 s->y + box_line_width,
1196 s->background_width,
1197 s->height - 2 * box_line_width);
1198 XSetFillStyle (s->display, s->gc, FillSolid);
1199 s->background_filled_p = 1;
1201 else if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
1202 || s->font_not_found_p
1203 || s->extends_to_end_of_line_p
1204 || force_p)
1206 x_clear_glyph_string_rect (s, s->x, s->y + box_line_width,
1207 s->background_width,
1208 s->height - 2 * box_line_width);
1209 s->background_filled_p = 1;
1215 /* Draw the foreground of glyph string S. */
1217 static void
1218 x_draw_glyph_string_foreground (struct glyph_string *s)
1220 int i, x;
1222 /* If first glyph of S has a left box line, start drawing the text
1223 of S to the right of that box line. */
1224 if (s->face->box != FACE_NO_BOX
1225 && s->first_glyph->left_box_line_p)
1226 x = s->x + eabs (s->face->box_line_width);
1227 else
1228 x = s->x;
1230 /* Draw characters of S as rectangles if S's font could not be
1231 loaded. */
1232 if (s->font_not_found_p)
1234 for (i = 0; i < s->nchars; ++i)
1236 struct glyph *g = s->first_glyph + i;
1237 XDrawRectangle (s->display, s->window,
1238 s->gc, x, s->y, g->pixel_width - 1,
1239 s->height - 1);
1240 x += g->pixel_width;
1243 else
1245 struct font *font = s->font;
1246 int boff = font->baseline_offset;
1247 int y;
1249 if (font->vertical_centering)
1250 boff = VCENTER_BASELINE_OFFSET (font, s->f) - boff;
1252 y = s->ybase - boff;
1253 if (s->for_overlaps
1254 || (s->background_filled_p && s->hl != DRAW_CURSOR))
1255 font->driver->draw (s, 0, s->nchars, x, y, 0);
1256 else
1257 font->driver->draw (s, 0, s->nchars, x, y, 1);
1258 if (s->face->overstrike)
1259 font->driver->draw (s, 0, s->nchars, x + 1, y, 0);
1263 /* Draw the foreground of composite glyph string S. */
1265 static void
1266 x_draw_composite_glyph_string_foreground (struct glyph_string *s)
1268 int i, j, x;
1269 struct font *font = s->font;
1271 /* If first glyph of S has a left box line, start drawing the text
1272 of S to the right of that box line. */
1273 if (s->face && s->face->box != FACE_NO_BOX
1274 && s->first_glyph->left_box_line_p)
1275 x = s->x + eabs (s->face->box_line_width);
1276 else
1277 x = s->x;
1279 /* S is a glyph string for a composition. S->cmp_from is the index
1280 of the first character drawn for glyphs of this composition.
1281 S->cmp_from == 0 means we are drawing the very first character of
1282 this composition. */
1284 /* Draw a rectangle for the composition if the font for the very
1285 first character of the composition could not be loaded. */
1286 if (s->font_not_found_p)
1288 if (s->cmp_from == 0)
1289 XDrawRectangle (s->display, s->window, s->gc, x, s->y,
1290 s->width - 1, s->height - 1);
1292 else if (! s->first_glyph->u.cmp.automatic)
1294 int y = s->ybase;
1296 for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
1297 if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
1299 int xx = x + s->cmp->offsets[j * 2];
1300 int yy = y - s->cmp->offsets[j * 2 + 1];
1302 font->driver->draw (s, j, j + 1, xx, yy, 0);
1303 if (s->face->overstrike)
1304 font->driver->draw (s, j, j + 1, xx + 1, yy, 0);
1307 else
1309 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1310 Lisp_Object glyph;
1311 int y = s->ybase;
1312 int width = 0;
1314 for (i = j = s->cmp_from; i < s->cmp_to; i++)
1316 glyph = LGSTRING_GLYPH (gstring, i);
1317 if (NILP (LGLYPH_ADJUSTMENT (glyph)))
1318 width += LGLYPH_WIDTH (glyph);
1319 else
1321 int xoff, yoff, wadjust;
1323 if (j < i)
1325 font->driver->draw (s, j, i, x, y, 0);
1326 if (s->face->overstrike)
1327 font->driver->draw (s, j, i, x + 1, y, 0);
1328 x += width;
1330 xoff = LGLYPH_XOFF (glyph);
1331 yoff = LGLYPH_YOFF (glyph);
1332 wadjust = LGLYPH_WADJUST (glyph);
1333 font->driver->draw (s, i, i + 1, x + xoff, y + yoff, 0);
1334 if (s->face->overstrike)
1335 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff, 0);
1336 x += wadjust;
1337 j = i + 1;
1338 width = 0;
1341 if (j < i)
1343 font->driver->draw (s, j, i, x, y, 0);
1344 if (s->face->overstrike)
1345 font->driver->draw (s, j, i, x + 1, y, 0);
1351 /* Draw the foreground of glyph string S for glyphless characters. */
1353 static void
1354 x_draw_glyphless_glyph_string_foreground (struct glyph_string *s)
1356 struct glyph *glyph = s->first_glyph;
1357 XChar2b char2b[8];
1358 int x, i, j;
1360 /* If first glyph of S has a left box line, start drawing the text
1361 of S to the right of that box line. */
1362 if (s->face && s->face->box != FACE_NO_BOX
1363 && s->first_glyph->left_box_line_p)
1364 x = s->x + eabs (s->face->box_line_width);
1365 else
1366 x = s->x;
1368 s->char2b = char2b;
1370 for (i = 0; i < s->nchars; i++, glyph++)
1372 char buf[7], *str = NULL;
1373 int len = glyph->u.glyphless.len;
1375 if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_ACRONYM)
1377 if (len > 0
1378 && CHAR_TABLE_P (Vglyphless_char_display)
1379 && (CHAR_TABLE_EXTRA_SLOTS (XCHAR_TABLE (Vglyphless_char_display))
1380 >= 1))
1382 Lisp_Object acronym
1383 = (! glyph->u.glyphless.for_no_font
1384 ? CHAR_TABLE_REF (Vglyphless_char_display,
1385 glyph->u.glyphless.ch)
1386 : XCHAR_TABLE (Vglyphless_char_display)->extras[0]);
1387 if (STRINGP (acronym))
1388 str = (char *) SDATA (acronym);
1391 else if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_HEX_CODE)
1393 sprintf ((char *) buf, "%0*X",
1394 glyph->u.glyphless.ch < 0x10000 ? 4 : 6,
1395 glyph->u.glyphless.ch);
1396 str = buf;
1399 if (str)
1401 int upper_len = (len + 1) / 2;
1402 unsigned code;
1404 /* It is assured that all LEN characters in STR is ASCII. */
1405 for (j = 0; j < len; j++)
1407 code = s->font->driver->encode_char (s->font, str[j]);
1408 STORE_XCHAR2B (char2b + j, code >> 8, code & 0xFF);
1410 s->font->driver->draw (s, 0, upper_len,
1411 x + glyph->slice.glyphless.upper_xoff,
1412 s->ybase + glyph->slice.glyphless.upper_yoff,
1414 s->font->driver->draw (s, upper_len, len,
1415 x + glyph->slice.glyphless.lower_xoff,
1416 s->ybase + glyph->slice.glyphless.lower_yoff,
1419 if (glyph->u.glyphless.method != GLYPHLESS_DISPLAY_THIN_SPACE)
1420 XDrawRectangle (s->display, s->window, s->gc,
1421 x, s->ybase - glyph->ascent,
1422 glyph->pixel_width - 1,
1423 glyph->ascent + glyph->descent - 1);
1424 x += glyph->pixel_width;
1428 #ifdef USE_X_TOOLKIT
1430 static struct frame *x_frame_of_widget (Widget);
1431 static Boolean cvt_string_to_pixel (Display *, XrmValue *, Cardinal *,
1432 XrmValue *, XrmValue *, XtPointer *);
1433 static void cvt_pixel_dtor (XtAppContext, XrmValue *, XtPointer,
1434 XrmValue *, Cardinal *);
1437 /* Return the frame on which widget WIDGET is used.. Abort if frame
1438 cannot be determined. */
1440 static struct frame *
1441 x_frame_of_widget (Widget widget)
1443 struct x_display_info *dpyinfo;
1444 Lisp_Object tail;
1445 struct frame *f;
1447 dpyinfo = x_display_info_for_display (XtDisplay (widget));
1449 /* Find the top-level shell of the widget. Note that this function
1450 can be called when the widget is not yet realized, so XtWindow
1451 (widget) == 0. That's the reason we can't simply use
1452 x_any_window_to_frame. */
1453 while (!XtIsTopLevelShell (widget))
1454 widget = XtParent (widget);
1456 /* Look for a frame with that top-level widget. Allocate the color
1457 on that frame to get the right gamma correction value. */
1458 for (tail = Vframe_list; CONSP (tail); tail = XCDR (tail))
1459 if (FRAMEP (XCAR (tail))
1460 && (f = XFRAME (XCAR (tail)),
1461 (FRAME_X_P (f)
1462 && f->output_data.nothing != 1
1463 && FRAME_X_DISPLAY_INFO (f) == dpyinfo))
1464 && f->output_data.x->widget == widget)
1465 return f;
1467 abort ();
1471 /* Allocate the color COLOR->pixel on the screen and display of
1472 widget WIDGET in colormap CMAP. If an exact match cannot be
1473 allocated, try the nearest color available. Value is non-zero
1474 if successful. This is called from lwlib. */
1477 x_alloc_nearest_color_for_widget (Widget widget, Colormap cmap, XColor *color)
1479 struct frame *f = x_frame_of_widget (widget);
1480 return x_alloc_nearest_color (f, cmap, color);
1484 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
1485 or DELTA. Try a color with RGB values multiplied by FACTOR first.
1486 If this produces the same color as PIXEL, try a color where all RGB
1487 values have DELTA added. Return the allocated color in *PIXEL.
1488 DISPLAY is the X display, CMAP is the colormap to operate on.
1489 Value is non-zero if successful. */
1492 x_alloc_lighter_color_for_widget (Widget widget, Display *display, Colormap cmap,
1493 unsigned long *pixel, double factor, int delta)
1495 struct frame *f = x_frame_of_widget (widget);
1496 return x_alloc_lighter_color (f, display, cmap, pixel, factor, delta);
1500 /* Structure specifying which arguments should be passed by Xt to
1501 cvt_string_to_pixel. We want the widget's screen and colormap. */
1503 static XtConvertArgRec cvt_string_to_pixel_args[] =
1505 {XtWidgetBaseOffset, (XtPointer) XtOffset (Widget, core.screen),
1506 sizeof (Screen *)},
1507 {XtWidgetBaseOffset, (XtPointer) XtOffset (Widget, core.colormap),
1508 sizeof (Colormap)}
1512 /* The address of this variable is returned by
1513 cvt_string_to_pixel. */
1515 static Pixel cvt_string_to_pixel_value;
1518 /* Convert a color name to a pixel color.
1520 DPY is the display we are working on.
1522 ARGS is an array of *NARGS XrmValue structures holding additional
1523 information about the widget for which the conversion takes place.
1524 The contents of this array are determined by the specification
1525 in cvt_string_to_pixel_args.
1527 FROM is a pointer to an XrmValue which points to the color name to
1528 convert. TO is an XrmValue in which to return the pixel color.
1530 CLOSURE_RET is a pointer to user-data, in which we record if
1531 we allocated the color or not.
1533 Value is True if successful, False otherwise. */
1535 static Boolean
1536 cvt_string_to_pixel (Display *dpy, XrmValue *args, Cardinal *nargs,
1537 XrmValue *from, XrmValue *to,
1538 XtPointer *closure_ret)
1540 Screen *screen;
1541 Colormap cmap;
1542 Pixel pixel;
1543 String color_name;
1544 XColor color;
1546 if (*nargs != 2)
1548 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
1549 "wrongParameters", "cvt_string_to_pixel",
1550 "XtToolkitError",
1551 "Screen and colormap args required", NULL, NULL);
1552 return False;
1555 screen = *(Screen **) args[0].addr;
1556 cmap = *(Colormap *) args[1].addr;
1557 color_name = (String) from->addr;
1559 if (strcmp (color_name, XtDefaultBackground) == 0)
1561 *closure_ret = (XtPointer) False;
1562 pixel = WhitePixelOfScreen (screen);
1564 else if (strcmp (color_name, XtDefaultForeground) == 0)
1566 *closure_ret = (XtPointer) False;
1567 pixel = BlackPixelOfScreen (screen);
1569 else if (XParseColor (dpy, cmap, color_name, &color)
1570 && x_alloc_nearest_color_1 (dpy, cmap, &color))
1572 pixel = color.pixel;
1573 *closure_ret = (XtPointer) True;
1575 else
1577 String params[1];
1578 Cardinal nparams = 1;
1580 params[0] = color_name;
1581 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
1582 "badValue", "cvt_string_to_pixel",
1583 "XtToolkitError", "Invalid color `%s'",
1584 params, &nparams);
1585 return False;
1588 if (to->addr != NULL)
1590 if (to->size < sizeof (Pixel))
1592 to->size = sizeof (Pixel);
1593 return False;
1596 *(Pixel *) to->addr = pixel;
1598 else
1600 cvt_string_to_pixel_value = pixel;
1601 to->addr = (XtPointer) &cvt_string_to_pixel_value;
1604 to->size = sizeof (Pixel);
1605 return True;
1609 /* Free a pixel color which was previously allocated via
1610 cvt_string_to_pixel. This is registered as the destructor
1611 for this type of resource via XtSetTypeConverter.
1613 APP is the application context in which we work.
1615 TO is a pointer to an XrmValue holding the color to free.
1616 CLOSURE is the value we stored in CLOSURE_RET for this color
1617 in cvt_string_to_pixel.
1619 ARGS and NARGS are like for cvt_string_to_pixel. */
1621 static void
1622 cvt_pixel_dtor (XtAppContext app, XrmValuePtr to, XtPointer closure, XrmValuePtr args,
1623 Cardinal *nargs)
1625 if (*nargs != 2)
1627 XtAppWarningMsg (app, "wrongParameters", "cvt_pixel_dtor",
1628 "XtToolkitError",
1629 "Screen and colormap arguments required",
1630 NULL, NULL);
1632 else if (closure != NULL)
1634 /* We did allocate the pixel, so free it. */
1635 Screen *screen = *(Screen **) args[0].addr;
1636 Colormap cmap = *(Colormap *) args[1].addr;
1637 x_free_dpy_colors (DisplayOfScreen (screen), screen, cmap,
1638 (Pixel *) to->addr, 1);
1643 #endif /* USE_X_TOOLKIT */
1646 /* Value is an array of XColor structures for the contents of the
1647 color map of display DPY. Set *NCELLS to the size of the array.
1648 Note that this probably shouldn't be called for large color maps,
1649 say a 24-bit TrueColor map. */
1651 static const XColor *
1652 x_color_cells (Display *dpy, int *ncells)
1654 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
1656 if (dpyinfo->color_cells == NULL)
1658 Screen *screen = dpyinfo->screen;
1659 int i;
1661 dpyinfo->ncolor_cells
1662 = XDisplayCells (dpy, XScreenNumberOfScreen (screen));
1663 dpyinfo->color_cells
1664 = (XColor *) xmalloc (dpyinfo->ncolor_cells
1665 * sizeof *dpyinfo->color_cells);
1667 for (i = 0; i < dpyinfo->ncolor_cells; ++i)
1668 dpyinfo->color_cells[i].pixel = i;
1670 XQueryColors (dpy, dpyinfo->cmap,
1671 dpyinfo->color_cells, dpyinfo->ncolor_cells);
1674 *ncells = dpyinfo->ncolor_cells;
1675 return dpyinfo->color_cells;
1679 /* On frame F, translate pixel colors to RGB values for the NCOLORS
1680 colors in COLORS. Use cached information, if available. */
1682 void
1683 x_query_colors (struct frame *f, XColor *colors, int ncolors)
1685 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
1687 if (dpyinfo->color_cells)
1689 int i;
1690 for (i = 0; i < ncolors; ++i)
1692 unsigned long pixel = colors[i].pixel;
1693 xassert (pixel < dpyinfo->ncolor_cells);
1694 xassert (dpyinfo->color_cells[pixel].pixel == pixel);
1695 colors[i] = dpyinfo->color_cells[pixel];
1698 else
1699 XQueryColors (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), colors, ncolors);
1703 /* On frame F, translate pixel color to RGB values for the color in
1704 COLOR. Use cached information, if available. */
1706 void
1707 x_query_color (struct frame *f, XColor *color)
1709 x_query_colors (f, color, 1);
1713 /* Allocate the color COLOR->pixel on DISPLAY, colormap CMAP. If an
1714 exact match can't be allocated, try the nearest color available.
1715 Value is non-zero if successful. Set *COLOR to the color
1716 allocated. */
1718 static int
1719 x_alloc_nearest_color_1 (Display *dpy, Colormap cmap, XColor *color)
1721 int rc;
1723 rc = XAllocColor (dpy, cmap, color);
1724 if (rc == 0)
1726 /* If we got to this point, the colormap is full, so we're going
1727 to try to get the next closest color. The algorithm used is
1728 a least-squares matching, which is what X uses for closest
1729 color matching with StaticColor visuals. */
1730 int nearest, i;
1731 unsigned long nearest_delta = ~0;
1732 int ncells;
1733 const XColor *cells = x_color_cells (dpy, &ncells);
1735 for (nearest = i = 0; i < ncells; ++i)
1737 long dred = (color->red >> 8) - (cells[i].red >> 8);
1738 long dgreen = (color->green >> 8) - (cells[i].green >> 8);
1739 long dblue = (color->blue >> 8) - (cells[i].blue >> 8);
1740 unsigned long delta = dred * dred + dgreen * dgreen + dblue * dblue;
1742 if (delta < nearest_delta)
1744 nearest = i;
1745 nearest_delta = delta;
1749 color->red = cells[nearest].red;
1750 color->green = cells[nearest].green;
1751 color->blue = cells[nearest].blue;
1752 rc = XAllocColor (dpy, cmap, color);
1754 else
1756 /* If allocation succeeded, and the allocated pixel color is not
1757 equal to a cached pixel color recorded earlier, there was a
1758 change in the colormap, so clear the color cache. */
1759 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
1760 XColor *cached_color;
1762 if (dpyinfo->color_cells
1763 && (cached_color = &dpyinfo->color_cells[color->pixel],
1764 (cached_color->red != color->red
1765 || cached_color->blue != color->blue
1766 || cached_color->green != color->green)))
1768 xfree (dpyinfo->color_cells);
1769 dpyinfo->color_cells = NULL;
1770 dpyinfo->ncolor_cells = 0;
1774 #ifdef DEBUG_X_COLORS
1775 if (rc)
1776 register_color (color->pixel);
1777 #endif /* DEBUG_X_COLORS */
1779 return rc;
1783 /* Allocate the color COLOR->pixel on frame F, colormap CMAP. If an
1784 exact match can't be allocated, try the nearest color available.
1785 Value is non-zero if successful. Set *COLOR to the color
1786 allocated. */
1789 x_alloc_nearest_color (struct frame *f, Colormap cmap, XColor *color)
1791 gamma_correct (f, color);
1792 return x_alloc_nearest_color_1 (FRAME_X_DISPLAY (f), cmap, color);
1796 /* Allocate color PIXEL on frame F. PIXEL must already be allocated.
1797 It's necessary to do this instead of just using PIXEL directly to
1798 get color reference counts right. */
1800 unsigned long
1801 x_copy_color (struct frame *f, long unsigned int pixel)
1803 XColor color;
1805 color.pixel = pixel;
1806 BLOCK_INPUT;
1807 x_query_color (f, &color);
1808 XAllocColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &color);
1809 UNBLOCK_INPUT;
1810 #ifdef DEBUG_X_COLORS
1811 register_color (pixel);
1812 #endif
1813 return color.pixel;
1817 /* Allocate color PIXEL on display DPY. PIXEL must already be allocated.
1818 It's necessary to do this instead of just using PIXEL directly to
1819 get color reference counts right. */
1821 unsigned long
1822 x_copy_dpy_color (Display *dpy, Colormap cmap, long unsigned int pixel)
1824 XColor color;
1826 color.pixel = pixel;
1827 BLOCK_INPUT;
1828 XQueryColor (dpy, cmap, &color);
1829 XAllocColor (dpy, cmap, &color);
1830 UNBLOCK_INPUT;
1831 #ifdef DEBUG_X_COLORS
1832 register_color (pixel);
1833 #endif
1834 return color.pixel;
1838 /* Brightness beyond which a color won't have its highlight brightness
1839 boosted.
1841 Nominally, highlight colors for `3d' faces are calculated by
1842 brightening an object's color by a constant scale factor, but this
1843 doesn't yield good results for dark colors, so for colors who's
1844 brightness is less than this value (on a scale of 0-65535) have an
1845 use an additional additive factor.
1847 The value here is set so that the default menu-bar/mode-line color
1848 (grey75) will not have its highlights changed at all. */
1849 #define HIGHLIGHT_COLOR_DARK_BOOST_LIMIT 48000
1852 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
1853 or DELTA. Try a color with RGB values multiplied by FACTOR first.
1854 If this produces the same color as PIXEL, try a color where all RGB
1855 values have DELTA added. Return the allocated color in *PIXEL.
1856 DISPLAY is the X display, CMAP is the colormap to operate on.
1857 Value is non-zero if successful. */
1859 static int
1860 x_alloc_lighter_color (struct frame *f, Display *display, Colormap cmap, long unsigned int *pixel, double factor, int delta)
1862 XColor color, new;
1863 long bright;
1864 int success_p;
1866 /* Get RGB color values. */
1867 color.pixel = *pixel;
1868 x_query_color (f, &color);
1870 /* Change RGB values by specified FACTOR. Avoid overflow! */
1871 xassert (factor >= 0);
1872 new.red = min (0xffff, factor * color.red);
1873 new.green = min (0xffff, factor * color.green);
1874 new.blue = min (0xffff, factor * color.blue);
1876 /* Calculate brightness of COLOR. */
1877 bright = (2 * color.red + 3 * color.green + color.blue) / 6;
1879 /* We only boost colors that are darker than
1880 HIGHLIGHT_COLOR_DARK_BOOST_LIMIT. */
1881 if (bright < HIGHLIGHT_COLOR_DARK_BOOST_LIMIT)
1882 /* Make an additive adjustment to NEW, because it's dark enough so
1883 that scaling by FACTOR alone isn't enough. */
1885 /* How far below the limit this color is (0 - 1, 1 being darker). */
1886 double dimness = 1 - (double)bright / HIGHLIGHT_COLOR_DARK_BOOST_LIMIT;
1887 /* The additive adjustment. */
1888 int min_delta = delta * dimness * factor / 2;
1890 if (factor < 1)
1892 new.red = max (0, new.red - min_delta);
1893 new.green = max (0, new.green - min_delta);
1894 new.blue = max (0, new.blue - min_delta);
1896 else
1898 new.red = min (0xffff, min_delta + new.red);
1899 new.green = min (0xffff, min_delta + new.green);
1900 new.blue = min (0xffff, min_delta + new.blue);
1904 /* Try to allocate the color. */
1905 success_p = x_alloc_nearest_color (f, cmap, &new);
1906 if (success_p)
1908 if (new.pixel == *pixel)
1910 /* If we end up with the same color as before, try adding
1911 delta to the RGB values. */
1912 x_free_colors (f, &new.pixel, 1);
1914 new.red = min (0xffff, delta + color.red);
1915 new.green = min (0xffff, delta + color.green);
1916 new.blue = min (0xffff, delta + color.blue);
1917 success_p = x_alloc_nearest_color (f, cmap, &new);
1919 else
1920 success_p = 1;
1921 *pixel = new.pixel;
1924 return success_p;
1928 /* Set up the foreground color for drawing relief lines of glyph
1929 string S. RELIEF is a pointer to a struct relief containing the GC
1930 with which lines will be drawn. Use a color that is FACTOR or
1931 DELTA lighter or darker than the relief's background which is found
1932 in S->f->output_data.x->relief_background. If such a color cannot
1933 be allocated, use DEFAULT_PIXEL, instead. */
1935 static void
1936 x_setup_relief_color (struct frame *f, struct relief *relief, double factor, int delta, long unsigned int default_pixel)
1938 XGCValues xgcv;
1939 struct x_output *di = f->output_data.x;
1940 unsigned long mask = GCForeground | GCLineWidth | GCGraphicsExposures;
1941 unsigned long pixel;
1942 unsigned long background = di->relief_background;
1943 Colormap cmap = FRAME_X_COLORMAP (f);
1944 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
1945 Display *dpy = FRAME_X_DISPLAY (f);
1947 xgcv.graphics_exposures = False;
1948 xgcv.line_width = 1;
1950 /* Free previously allocated color. The color cell will be reused
1951 when it has been freed as many times as it was allocated, so this
1952 doesn't affect faces using the same colors. */
1953 if (relief->gc
1954 && relief->allocated_p)
1956 x_free_colors (f, &relief->pixel, 1);
1957 relief->allocated_p = 0;
1960 /* Allocate new color. */
1961 xgcv.foreground = default_pixel;
1962 pixel = background;
1963 if (dpyinfo->n_planes != 1
1964 && x_alloc_lighter_color (f, dpy, cmap, &pixel, factor, delta))
1966 relief->allocated_p = 1;
1967 xgcv.foreground = relief->pixel = pixel;
1970 if (relief->gc == 0)
1972 xgcv.stipple = dpyinfo->gray;
1973 mask |= GCStipple;
1974 relief->gc = XCreateGC (dpy, FRAME_X_WINDOW (f), mask, &xgcv);
1976 else
1977 XChangeGC (dpy, relief->gc, mask, &xgcv);
1981 /* Set up colors for the relief lines around glyph string S. */
1983 static void
1984 x_setup_relief_colors (struct glyph_string *s)
1986 struct x_output *di = s->f->output_data.x;
1987 unsigned long color;
1989 if (s->face->use_box_color_for_shadows_p)
1990 color = s->face->box_color;
1991 else if (s->first_glyph->type == IMAGE_GLYPH
1992 && s->img->pixmap
1993 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
1994 color = IMAGE_BACKGROUND (s->img, s->f, 0);
1995 else
1997 XGCValues xgcv;
1999 /* Get the background color of the face. */
2000 XGetGCValues (s->display, s->gc, GCBackground, &xgcv);
2001 color = xgcv.background;
2004 if (di->white_relief.gc == 0
2005 || color != di->relief_background)
2007 di->relief_background = color;
2008 x_setup_relief_color (s->f, &di->white_relief, 1.2, 0x8000,
2009 WHITE_PIX_DEFAULT (s->f));
2010 x_setup_relief_color (s->f, &di->black_relief, 0.6, 0x4000,
2011 BLACK_PIX_DEFAULT (s->f));
2016 /* Draw a relief on frame F inside the rectangle given by LEFT_X,
2017 TOP_Y, RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the relief
2018 to draw, it must be >= 0. RAISED_P non-zero means draw a raised
2019 relief. LEFT_P non-zero means draw a relief on the left side of
2020 the rectangle. RIGHT_P non-zero means draw a relief on the right
2021 side of the rectangle. CLIP_RECT is the clipping rectangle to use
2022 when drawing. */
2024 static void
2025 x_draw_relief_rect (struct frame *f,
2026 int left_x, int top_y, int right_x, int bottom_y, int width,
2027 int raised_p, int top_p, int bot_p, int left_p, int right_p,
2028 XRectangle *clip_rect)
2030 Display *dpy = FRAME_X_DISPLAY (f);
2031 Window window = FRAME_X_WINDOW (f);
2032 int i;
2033 GC gc;
2035 if (raised_p)
2036 gc = f->output_data.x->white_relief.gc;
2037 else
2038 gc = f->output_data.x->black_relief.gc;
2039 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
2041 /* This code is more complicated than it has to be, because of two
2042 minor hacks to make the boxes look nicer: (i) if width > 1, draw
2043 the outermost line using the black relief. (ii) Omit the four
2044 corner pixels. */
2046 /* Top. */
2047 if (top_p)
2049 if (width == 1)
2050 XDrawLine (dpy, window, gc,
2051 left_x + (left_p ? 1 : 0), top_y,
2052 right_x + (right_p ? 0 : 1), top_y);
2054 for (i = 1; i < width; ++i)
2055 XDrawLine (dpy, window, gc,
2056 left_x + i * left_p, top_y + i,
2057 right_x + 1 - i * right_p, top_y + i);
2060 /* Left. */
2061 if (left_p)
2063 if (width == 1)
2064 XDrawLine (dpy, window, gc, left_x, top_y + 1, left_x, bottom_y);
2066 XClearArea (dpy, window, left_x, top_y, 1, 1, False);
2067 XClearArea (dpy, window, left_x, bottom_y, 1, 1, False);
2069 for (i = (width > 1 ? 1 : 0); i < width; ++i)
2070 XDrawLine (dpy, window, gc,
2071 left_x + i, top_y + i, left_x + i, bottom_y - i + 1);
2074 XSetClipMask (dpy, gc, None);
2075 if (raised_p)
2076 gc = f->output_data.x->black_relief.gc;
2077 else
2078 gc = f->output_data.x->white_relief.gc;
2079 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
2081 if (width > 1)
2083 /* Outermost top line. */
2084 if (top_p)
2085 XDrawLine (dpy, window, gc,
2086 left_x + (left_p ? 1 : 0), top_y,
2087 right_x + (right_p ? 0 : 1), top_y);
2089 /* Outermost left line. */
2090 if (left_p)
2091 XDrawLine (dpy, window, gc, left_x, top_y + 1, left_x, bottom_y);
2094 /* Bottom. */
2095 if (bot_p)
2097 XDrawLine (dpy, window, gc,
2098 left_x + (left_p ? 1 : 0), bottom_y,
2099 right_x + (right_p ? 0 : 1), bottom_y);
2100 for (i = 1; i < width; ++i)
2101 XDrawLine (dpy, window, gc,
2102 left_x + i * left_p, bottom_y - i,
2103 right_x + 1 - i * right_p, bottom_y - i);
2106 /* Right. */
2107 if (right_p)
2109 XClearArea (dpy, window, right_x, top_y, 1, 1, False);
2110 XClearArea (dpy, window, right_x, bottom_y, 1, 1, False);
2111 for (i = 0; i < width; ++i)
2112 XDrawLine (dpy, window, gc,
2113 right_x - i, top_y + i + 1, right_x - i, bottom_y - i);
2116 XSetClipMask (dpy, gc, None);
2120 /* Draw a box on frame F inside the rectangle given by LEFT_X, TOP_Y,
2121 RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the lines to
2122 draw, it must be >= 0. LEFT_P non-zero means draw a line on the
2123 left side of the rectangle. RIGHT_P non-zero means draw a line
2124 on the right side of the rectangle. CLIP_RECT is the clipping
2125 rectangle to use when drawing. */
2127 static void
2128 x_draw_box_rect (struct glyph_string *s,
2129 int left_x, int top_y, int right_x, int bottom_y, int width,
2130 int left_p, int right_p, XRectangle *clip_rect)
2132 XGCValues xgcv;
2134 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2135 XSetForeground (s->display, s->gc, s->face->box_color);
2136 XSetClipRectangles (s->display, s->gc, 0, 0, clip_rect, 1, Unsorted);
2138 /* Top. */
2139 XFillRectangle (s->display, s->window, s->gc,
2140 left_x, top_y, right_x - left_x + 1, width);
2142 /* Left. */
2143 if (left_p)
2144 XFillRectangle (s->display, s->window, s->gc,
2145 left_x, top_y, width, bottom_y - top_y + 1);
2147 /* Bottom. */
2148 XFillRectangle (s->display, s->window, s->gc,
2149 left_x, bottom_y - width + 1, right_x - left_x + 1, width);
2151 /* Right. */
2152 if (right_p)
2153 XFillRectangle (s->display, s->window, s->gc,
2154 right_x - width + 1, top_y, width, bottom_y - top_y + 1);
2156 XSetForeground (s->display, s->gc, xgcv.foreground);
2157 XSetClipMask (s->display, s->gc, None);
2161 /* Draw a box around glyph string S. */
2163 static void
2164 x_draw_glyph_string_box (struct glyph_string *s)
2166 int width, left_x, right_x, top_y, bottom_y, last_x, raised_p;
2167 int left_p, right_p;
2168 struct glyph *last_glyph;
2169 XRectangle clip_rect;
2171 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2172 ? WINDOW_RIGHT_EDGE_X (s->w)
2173 : window_box_right (s->w, s->area));
2175 /* The glyph that may have a right box line. */
2176 last_glyph = (s->cmp || s->img
2177 ? s->first_glyph
2178 : s->first_glyph + s->nchars - 1);
2180 width = eabs (s->face->box_line_width);
2181 raised_p = s->face->box == FACE_RAISED_BOX;
2182 left_x = s->x;
2183 right_x = (s->row->full_width_p && s->extends_to_end_of_line_p
2184 ? last_x - 1
2185 : min (last_x, s->x + s->background_width) - 1);
2186 top_y = s->y;
2187 bottom_y = top_y + s->height - 1;
2189 left_p = (s->first_glyph->left_box_line_p
2190 || (s->hl == DRAW_MOUSE_FACE
2191 && (s->prev == NULL
2192 || s->prev->hl != s->hl)));
2193 right_p = (last_glyph->right_box_line_p
2194 || (s->hl == DRAW_MOUSE_FACE
2195 && (s->next == NULL
2196 || s->next->hl != s->hl)));
2198 get_glyph_string_clip_rect (s, &clip_rect);
2200 if (s->face->box == FACE_SIMPLE_BOX)
2201 x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
2202 left_p, right_p, &clip_rect);
2203 else
2205 x_setup_relief_colors (s);
2206 x_draw_relief_rect (s->f, left_x, top_y, right_x, bottom_y,
2207 width, raised_p, 1, 1, left_p, right_p, &clip_rect);
2212 /* Draw foreground of image glyph string S. */
2214 static void
2215 x_draw_image_foreground (struct glyph_string *s)
2217 int x = s->x;
2218 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2220 /* If first glyph of S has a left box line, start drawing it to the
2221 right of that line. */
2222 if (s->face->box != FACE_NO_BOX
2223 && s->first_glyph->left_box_line_p
2224 && s->slice.x == 0)
2225 x += eabs (s->face->box_line_width);
2227 /* If there is a margin around the image, adjust x- and y-position
2228 by that margin. */
2229 if (s->slice.x == 0)
2230 x += s->img->hmargin;
2231 if (s->slice.y == 0)
2232 y += s->img->vmargin;
2234 if (s->img->pixmap)
2236 if (s->img->mask)
2238 /* We can't set both a clip mask and use XSetClipRectangles
2239 because the latter also sets a clip mask. We also can't
2240 trust on the shape extension to be available
2241 (XShapeCombineRegion). So, compute the rectangle to draw
2242 manually. */
2243 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
2244 | GCFunction);
2245 XGCValues xgcv;
2246 XRectangle clip_rect, image_rect, r;
2248 xgcv.clip_mask = s->img->mask;
2249 xgcv.clip_x_origin = x;
2250 xgcv.clip_y_origin = y;
2251 xgcv.function = GXcopy;
2252 XChangeGC (s->display, s->gc, mask, &xgcv);
2254 get_glyph_string_clip_rect (s, &clip_rect);
2255 image_rect.x = x;
2256 image_rect.y = y;
2257 image_rect.width = s->slice.width;
2258 image_rect.height = s->slice.height;
2259 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
2260 XCopyArea (s->display, s->img->pixmap, s->window, s->gc,
2261 s->slice.x + r.x - x, s->slice.y + r.y - y,
2262 r.width, r.height, r.x, r.y);
2264 else
2266 XRectangle clip_rect, image_rect, r;
2268 get_glyph_string_clip_rect (s, &clip_rect);
2269 image_rect.x = x;
2270 image_rect.y = y;
2271 image_rect.width = s->slice.width;
2272 image_rect.height = s->slice.height;
2273 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
2274 XCopyArea (s->display, s->img->pixmap, s->window, s->gc,
2275 s->slice.x + r.x - x, s->slice.y + r.y - y,
2276 r.width, r.height, r.x, r.y);
2278 /* When the image has a mask, we can expect that at
2279 least part of a mouse highlight or a block cursor will
2280 be visible. If the image doesn't have a mask, make
2281 a block cursor visible by drawing a rectangle around
2282 the image. I believe it's looking better if we do
2283 nothing here for mouse-face. */
2284 if (s->hl == DRAW_CURSOR)
2286 int r = s->img->relief;
2287 if (r < 0) r = -r;
2288 XDrawRectangle (s->display, s->window, s->gc,
2289 x - r, y - r,
2290 s->slice.width + r*2 - 1,
2291 s->slice.height + r*2 - 1);
2295 else
2296 /* Draw a rectangle if image could not be loaded. */
2297 XDrawRectangle (s->display, s->window, s->gc, x, y,
2298 s->slice.width - 1, s->slice.height - 1);
2302 /* Draw a relief around the image glyph string S. */
2304 static void
2305 x_draw_image_relief (struct glyph_string *s)
2307 int x0, y0, x1, y1, thick, raised_p, extra;
2308 XRectangle r;
2309 int x = s->x;
2310 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2312 /* If first glyph of S has a left box line, start drawing it to the
2313 right of that line. */
2314 if (s->face->box != FACE_NO_BOX
2315 && s->first_glyph->left_box_line_p
2316 && s->slice.x == 0)
2317 x += eabs (s->face->box_line_width);
2319 /* If there is a margin around the image, adjust x- and y-position
2320 by that margin. */
2321 if (s->slice.x == 0)
2322 x += s->img->hmargin;
2323 if (s->slice.y == 0)
2324 y += s->img->vmargin;
2326 if (s->hl == DRAW_IMAGE_SUNKEN
2327 || s->hl == DRAW_IMAGE_RAISED)
2329 thick = tool_bar_button_relief >= 0 ? tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
2330 raised_p = s->hl == DRAW_IMAGE_RAISED;
2332 else
2334 thick = eabs (s->img->relief);
2335 raised_p = s->img->relief > 0;
2338 extra = s->face->id == TOOL_BAR_FACE_ID
2339 ? XINT (Vtool_bar_button_margin) : 0;
2341 x0 = x - thick - extra;
2342 y0 = y - thick - extra;
2343 x1 = x + s->slice.width + thick - 1 + extra;
2344 y1 = y + s->slice.height + thick - 1 + extra;
2346 x_setup_relief_colors (s);
2347 get_glyph_string_clip_rect (s, &r);
2348 x_draw_relief_rect (s->f, x0, y0, x1, y1, thick, raised_p,
2349 s->slice.y == 0,
2350 s->slice.y + s->slice.height == s->img->height,
2351 s->slice.x == 0,
2352 s->slice.x + s->slice.width == s->img->width,
2353 &r);
2357 /* Draw the foreground of image glyph string S to PIXMAP. */
2359 static void
2360 x_draw_image_foreground_1 (struct glyph_string *s, Pixmap pixmap)
2362 int x = 0;
2363 int y = s->ybase - s->y - image_ascent (s->img, s->face, &s->slice);
2365 /* If first glyph of S has a left box line, start drawing it to the
2366 right of that line. */
2367 if (s->face->box != FACE_NO_BOX
2368 && s->first_glyph->left_box_line_p
2369 && s->slice.x == 0)
2370 x += eabs (s->face->box_line_width);
2372 /* If there is a margin around the image, adjust x- and y-position
2373 by that margin. */
2374 if (s->slice.x == 0)
2375 x += s->img->hmargin;
2376 if (s->slice.y == 0)
2377 y += s->img->vmargin;
2379 if (s->img->pixmap)
2381 if (s->img->mask)
2383 /* We can't set both a clip mask and use XSetClipRectangles
2384 because the latter also sets a clip mask. We also can't
2385 trust on the shape extension to be available
2386 (XShapeCombineRegion). So, compute the rectangle to draw
2387 manually. */
2388 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
2389 | GCFunction);
2390 XGCValues xgcv;
2392 xgcv.clip_mask = s->img->mask;
2393 xgcv.clip_x_origin = x - s->slice.x;
2394 xgcv.clip_y_origin = y - s->slice.y;
2395 xgcv.function = GXcopy;
2396 XChangeGC (s->display, s->gc, mask, &xgcv);
2398 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
2399 s->slice.x, s->slice.y,
2400 s->slice.width, s->slice.height, x, y);
2401 XSetClipMask (s->display, s->gc, None);
2403 else
2405 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
2406 s->slice.x, s->slice.y,
2407 s->slice.width, s->slice.height, x, y);
2409 /* When the image has a mask, we can expect that at
2410 least part of a mouse highlight or a block cursor will
2411 be visible. If the image doesn't have a mask, make
2412 a block cursor visible by drawing a rectangle around
2413 the image. I believe it's looking better if we do
2414 nothing here for mouse-face. */
2415 if (s->hl == DRAW_CURSOR)
2417 int r = s->img->relief;
2418 if (r < 0) r = -r;
2419 XDrawRectangle (s->display, s->window, s->gc, x - r, y - r,
2420 s->slice.width + r*2 - 1,
2421 s->slice.height + r*2 - 1);
2425 else
2426 /* Draw a rectangle if image could not be loaded. */
2427 XDrawRectangle (s->display, pixmap, s->gc, x, y,
2428 s->slice.width - 1, s->slice.height - 1);
2432 /* Draw part of the background of glyph string S. X, Y, W, and H
2433 give the rectangle to draw. */
2435 static void
2436 x_draw_glyph_string_bg_rect (struct glyph_string *s, int x, int y, int w, int h)
2438 if (s->stippled_p)
2440 /* Fill background with a stipple pattern. */
2441 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
2442 XFillRectangle (s->display, s->window, s->gc, x, y, w, h);
2443 XSetFillStyle (s->display, s->gc, FillSolid);
2445 else
2446 x_clear_glyph_string_rect (s, x, y, w, h);
2450 /* Draw image glyph string S.
2452 s->y
2453 s->x +-------------------------
2454 | s->face->box
2456 | +-------------------------
2457 | | s->img->margin
2459 | | +-------------------
2460 | | | the image
2464 static void
2465 x_draw_image_glyph_string (struct glyph_string *s)
2467 int box_line_hwidth = eabs (s->face->box_line_width);
2468 int box_line_vwidth = max (s->face->box_line_width, 0);
2469 int height;
2470 Pixmap pixmap = None;
2472 height = s->height;
2473 if (s->slice.y == 0)
2474 height -= box_line_vwidth;
2475 if (s->slice.y + s->slice.height >= s->img->height)
2476 height -= box_line_vwidth;
2478 /* Fill background with face under the image. Do it only if row is
2479 taller than image or if image has a clip mask to reduce
2480 flickering. */
2481 s->stippled_p = s->face->stipple != 0;
2482 if (height > s->slice.height
2483 || s->img->hmargin
2484 || s->img->vmargin
2485 || s->img->mask
2486 || s->img->pixmap == 0
2487 || s->width != s->background_width)
2489 if (s->img->mask)
2491 /* Create a pixmap as large as the glyph string. Fill it
2492 with the background color. Copy the image to it, using
2493 its mask. Copy the temporary pixmap to the display. */
2494 Screen *screen = FRAME_X_SCREEN (s->f);
2495 int depth = DefaultDepthOfScreen (screen);
2497 /* Create a pixmap as large as the glyph string. */
2498 pixmap = XCreatePixmap (s->display, s->window,
2499 s->background_width,
2500 s->height, depth);
2502 /* Don't clip in the following because we're working on the
2503 pixmap. */
2504 XSetClipMask (s->display, s->gc, None);
2506 /* Fill the pixmap with the background color/stipple. */
2507 if (s->stippled_p)
2509 /* Fill background with a stipple pattern. */
2510 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
2511 XSetTSOrigin (s->display, s->gc, - s->x, - s->y);
2512 XFillRectangle (s->display, pixmap, s->gc,
2513 0, 0, s->background_width, s->height);
2514 XSetFillStyle (s->display, s->gc, FillSolid);
2515 XSetTSOrigin (s->display, s->gc, 0, 0);
2517 else
2519 XGCValues xgcv;
2520 XGetGCValues (s->display, s->gc, GCForeground | GCBackground,
2521 &xgcv);
2522 XSetForeground (s->display, s->gc, xgcv.background);
2523 XFillRectangle (s->display, pixmap, s->gc,
2524 0, 0, s->background_width, s->height);
2525 XSetForeground (s->display, s->gc, xgcv.foreground);
2528 else
2530 int x = s->x;
2531 int y = s->y;
2533 if (s->first_glyph->left_box_line_p
2534 && s->slice.x == 0)
2535 x += box_line_hwidth;
2537 if (s->slice.y == 0)
2538 y += box_line_vwidth;
2540 x_draw_glyph_string_bg_rect (s, x, y, s->background_width, height);
2543 s->background_filled_p = 1;
2546 /* Draw the foreground. */
2547 if (pixmap != None)
2549 x_draw_image_foreground_1 (s, pixmap);
2550 x_set_glyph_string_clipping (s);
2551 XCopyArea (s->display, pixmap, s->window, s->gc,
2552 0, 0, s->background_width, s->height, s->x, s->y);
2553 XFreePixmap (s->display, pixmap);
2555 else
2556 x_draw_image_foreground (s);
2558 /* If we must draw a relief around the image, do it. */
2559 if (s->img->relief
2560 || s->hl == DRAW_IMAGE_RAISED
2561 || s->hl == DRAW_IMAGE_SUNKEN)
2562 x_draw_image_relief (s);
2566 /* Draw stretch glyph string S. */
2568 static void
2569 x_draw_stretch_glyph_string (struct glyph_string *s)
2571 xassert (s->first_glyph->type == STRETCH_GLYPH);
2573 if (s->hl == DRAW_CURSOR
2574 && !x_stretch_cursor_p)
2576 /* If `x-stretch-cursor' is nil, don't draw a block cursor as
2577 wide as the stretch glyph. */
2578 int width, background_width = s->background_width;
2579 int x = s->x;
2581 if (!s->row->reversed_p)
2583 int left_x = window_box_left_offset (s->w, TEXT_AREA);
2585 if (x < left_x)
2587 background_width -= left_x - x;
2588 x = left_x;
2591 else
2593 /* In R2L rows, draw the cursor on the right edge of the
2594 stretch glyph. */
2595 int right_x = window_box_right_offset (s->w, TEXT_AREA);
2597 if (x + background_width > right_x)
2598 background_width -= x - right_x;
2599 x += background_width;
2601 width = min (FRAME_COLUMN_WIDTH (s->f), background_width);
2602 if (s->row->reversed_p)
2603 x -= width;
2605 /* Draw cursor. */
2606 x_draw_glyph_string_bg_rect (s, x, s->y, width, s->height);
2608 /* Clear rest using the GC of the original non-cursor face. */
2609 if (width < background_width)
2611 int y = s->y;
2612 int w = background_width - width, h = s->height;
2613 XRectangle r;
2614 GC gc;
2616 if (!s->row->reversed_p)
2617 x += width;
2618 else
2619 x = s->x;
2620 if (s->row->mouse_face_p
2621 && cursor_in_mouse_face_p (s->w))
2623 x_set_mouse_face_gc (s);
2624 gc = s->gc;
2626 else
2627 gc = s->face->gc;
2629 get_glyph_string_clip_rect (s, &r);
2630 XSetClipRectangles (s->display, gc, 0, 0, &r, 1, Unsorted);
2632 if (s->face->stipple)
2634 /* Fill background with a stipple pattern. */
2635 XSetFillStyle (s->display, gc, FillOpaqueStippled);
2636 XFillRectangle (s->display, s->window, gc, x, y, w, h);
2637 XSetFillStyle (s->display, gc, FillSolid);
2639 else
2641 XGCValues xgcv;
2642 XGetGCValues (s->display, gc, GCForeground | GCBackground, &xgcv);
2643 XSetForeground (s->display, gc, xgcv.background);
2644 XFillRectangle (s->display, s->window, gc, x, y, w, h);
2645 XSetForeground (s->display, gc, xgcv.foreground);
2649 else if (!s->background_filled_p)
2651 int background_width = s->background_width;
2652 int x = s->x, left_x = window_box_left_offset (s->w, TEXT_AREA);
2654 /* Don't draw into left margin, fringe or scrollbar area
2655 except for header line and mode line. */
2656 if (x < left_x && !s->row->mode_line_p)
2658 background_width -= left_x - x;
2659 x = left_x;
2661 if (background_width > 0)
2662 x_draw_glyph_string_bg_rect (s, x, s->y, background_width, s->height);
2665 s->background_filled_p = 1;
2669 /* Draw glyph string S. */
2671 static void
2672 x_draw_glyph_string (struct glyph_string *s)
2674 int relief_drawn_p = 0;
2676 /* If S draws into the background of its successors, draw the
2677 background of the successors first so that S can draw into it.
2678 This makes S->next use XDrawString instead of XDrawImageString. */
2679 if (s->next && s->right_overhang && !s->for_overlaps)
2681 int width;
2682 struct glyph_string *next;
2684 for (width = 0, next = s->next;
2685 next && width < s->right_overhang;
2686 width += next->width, next = next->next)
2687 if (next->first_glyph->type != IMAGE_GLYPH)
2689 x_set_glyph_string_gc (next);
2690 x_set_glyph_string_clipping (next);
2691 if (next->first_glyph->type == STRETCH_GLYPH)
2692 x_draw_stretch_glyph_string (next);
2693 else
2694 x_draw_glyph_string_background (next, 1);
2695 next->num_clips = 0;
2699 /* Set up S->gc, set clipping and draw S. */
2700 x_set_glyph_string_gc (s);
2702 /* Draw relief (if any) in advance for char/composition so that the
2703 glyph string can be drawn over it. */
2704 if (!s->for_overlaps
2705 && s->face->box != FACE_NO_BOX
2706 && (s->first_glyph->type == CHAR_GLYPH
2707 || s->first_glyph->type == COMPOSITE_GLYPH))
2710 x_set_glyph_string_clipping (s);
2711 x_draw_glyph_string_background (s, 1);
2712 x_draw_glyph_string_box (s);
2713 x_set_glyph_string_clipping (s);
2714 relief_drawn_p = 1;
2716 else if (!s->clip_head /* draw_glyphs didn't specify a clip mask. */
2717 && !s->clip_tail
2718 && ((s->prev && s->prev->hl != s->hl && s->left_overhang)
2719 || (s->next && s->next->hl != s->hl && s->right_overhang)))
2720 /* We must clip just this glyph. left_overhang part has already
2721 drawn when s->prev was drawn, and right_overhang part will be
2722 drawn later when s->next is drawn. */
2723 x_set_glyph_string_clipping_exactly (s, s);
2724 else
2725 x_set_glyph_string_clipping (s);
2727 switch (s->first_glyph->type)
2729 case IMAGE_GLYPH:
2730 x_draw_image_glyph_string (s);
2731 break;
2733 case STRETCH_GLYPH:
2734 x_draw_stretch_glyph_string (s);
2735 break;
2737 case CHAR_GLYPH:
2738 if (s->for_overlaps)
2739 s->background_filled_p = 1;
2740 else
2741 x_draw_glyph_string_background (s, 0);
2742 x_draw_glyph_string_foreground (s);
2743 break;
2745 case COMPOSITE_GLYPH:
2746 if (s->for_overlaps || (s->cmp_from > 0
2747 && ! s->first_glyph->u.cmp.automatic))
2748 s->background_filled_p = 1;
2749 else
2750 x_draw_glyph_string_background (s, 1);
2751 x_draw_composite_glyph_string_foreground (s);
2752 break;
2754 case GLYPHLESS_GLYPH:
2755 if (s->for_overlaps)
2756 s->background_filled_p = 1;
2757 else
2758 x_draw_glyph_string_background (s, 1);
2759 x_draw_glyphless_glyph_string_foreground (s);
2760 break;
2762 default:
2763 abort ();
2766 if (!s->for_overlaps)
2768 /* Draw underline. */
2769 if (s->face->underline_p)
2771 unsigned long thickness, position;
2772 int y;
2774 if (s->prev && s->prev->face->underline_p)
2776 /* We use the same underline style as the previous one. */
2777 thickness = s->prev->underline_thickness;
2778 position = s->prev->underline_position;
2780 else
2782 /* Get the underline thickness. Default is 1 pixel. */
2783 if (s->font && s->font->underline_thickness > 0)
2784 thickness = s->font->underline_thickness;
2785 else
2786 thickness = 1;
2787 if (x_underline_at_descent_line)
2788 position = (s->height - thickness) - (s->ybase - s->y);
2789 else
2791 /* Get the underline position. This is the recommended
2792 vertical offset in pixels from the baseline to the top of
2793 the underline. This is a signed value according to the
2794 specs, and its default is
2796 ROUND ((maximum descent) / 2), with
2797 ROUND(x) = floor (x + 0.5) */
2799 if (x_use_underline_position_properties
2800 && s->font && s->font->underline_position >= 0)
2801 position = s->font->underline_position;
2802 else if (s->font)
2803 position = (s->font->descent + 1) / 2;
2804 else
2805 position = underline_minimum_offset;
2807 position = max (position, underline_minimum_offset);
2809 /* Check the sanity of thickness and position. We should
2810 avoid drawing underline out of the current line area. */
2811 if (s->y + s->height <= s->ybase + position)
2812 position = (s->height - 1) - (s->ybase - s->y);
2813 if (s->y + s->height < s->ybase + position + thickness)
2814 thickness = (s->y + s->height) - (s->ybase + position);
2815 s->underline_thickness = thickness;
2816 s->underline_position = position;
2817 y = s->ybase + position;
2818 if (s->face->underline_defaulted_p)
2819 XFillRectangle (s->display, s->window, s->gc,
2820 s->x, y, s->width, thickness);
2821 else
2823 XGCValues xgcv;
2824 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2825 XSetForeground (s->display, s->gc, s->face->underline_color);
2826 XFillRectangle (s->display, s->window, s->gc,
2827 s->x, y, s->width, thickness);
2828 XSetForeground (s->display, s->gc, xgcv.foreground);
2832 /* Draw overline. */
2833 if (s->face->overline_p)
2835 unsigned long dy = 0, h = 1;
2837 if (s->face->overline_color_defaulted_p)
2838 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2839 s->width, h);
2840 else
2842 XGCValues xgcv;
2843 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2844 XSetForeground (s->display, s->gc, s->face->overline_color);
2845 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2846 s->width, h);
2847 XSetForeground (s->display, s->gc, xgcv.foreground);
2851 /* Draw strike-through. */
2852 if (s->face->strike_through_p)
2854 unsigned long h = 1;
2855 unsigned long dy = (s->height - h) / 2;
2857 if (s->face->strike_through_color_defaulted_p)
2858 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2859 s->width, h);
2860 else
2862 XGCValues xgcv;
2863 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2864 XSetForeground (s->display, s->gc, s->face->strike_through_color);
2865 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2866 s->width, h);
2867 XSetForeground (s->display, s->gc, xgcv.foreground);
2871 /* Draw relief if not yet drawn. */
2872 if (!relief_drawn_p && s->face->box != FACE_NO_BOX)
2873 x_draw_glyph_string_box (s);
2875 if (s->prev)
2877 struct glyph_string *prev;
2879 for (prev = s->prev; prev; prev = prev->prev)
2880 if (prev->hl != s->hl
2881 && prev->x + prev->width + prev->right_overhang > s->x)
2883 /* As prev was drawn while clipped to its own area, we
2884 must draw the right_overhang part using s->hl now. */
2885 enum draw_glyphs_face save = prev->hl;
2887 prev->hl = s->hl;
2888 x_set_glyph_string_gc (prev);
2889 x_set_glyph_string_clipping_exactly (s, prev);
2890 if (prev->first_glyph->type == CHAR_GLYPH)
2891 x_draw_glyph_string_foreground (prev);
2892 else
2893 x_draw_composite_glyph_string_foreground (prev);
2894 XSetClipMask (prev->display, prev->gc, None);
2895 prev->hl = save;
2896 prev->num_clips = 0;
2900 if (s->next)
2902 struct glyph_string *next;
2904 for (next = s->next; next; next = next->next)
2905 if (next->hl != s->hl
2906 && next->x - next->left_overhang < s->x + s->width)
2908 /* As next will be drawn while clipped to its own area,
2909 we must draw the left_overhang part using s->hl now. */
2910 enum draw_glyphs_face save = next->hl;
2912 next->hl = s->hl;
2913 x_set_glyph_string_gc (next);
2914 x_set_glyph_string_clipping_exactly (s, next);
2915 if (next->first_glyph->type == CHAR_GLYPH)
2916 x_draw_glyph_string_foreground (next);
2917 else
2918 x_draw_composite_glyph_string_foreground (next);
2919 XSetClipMask (next->display, next->gc, None);
2920 next->hl = save;
2921 next->num_clips = 0;
2926 /* Reset clipping. */
2927 XSetClipMask (s->display, s->gc, None);
2928 s->num_clips = 0;
2931 /* Shift display to make room for inserted glyphs. */
2933 void
2934 x_shift_glyphs_for_insert (struct frame *f, int x, int y, int width, int height, int shift_by)
2936 XCopyArea (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), FRAME_X_WINDOW (f),
2937 f->output_data.x->normal_gc,
2938 x, y, width, height,
2939 x + shift_by, y);
2942 /* Delete N glyphs at the nominal cursor position. Not implemented
2943 for X frames. */
2945 static void
2946 x_delete_glyphs (struct frame *f, register int n)
2948 abort ();
2952 /* Like XClearArea, but check that WIDTH and HEIGHT are reasonable.
2953 If they are <= 0, this is probably an error. */
2955 void
2956 x_clear_area (Display *dpy, Window window, int x, int y, int width, int height, int exposures)
2958 xassert (width > 0 && height > 0);
2959 XClearArea (dpy, window, x, y, width, height, exposures);
2963 /* Clear an entire frame. */
2965 static void
2966 x_clear_frame (struct frame *f)
2968 /* Clearing the frame will erase any cursor, so mark them all as no
2969 longer visible. */
2970 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2971 output_cursor.hpos = output_cursor.vpos = 0;
2972 output_cursor.x = -1;
2974 /* We don't set the output cursor here because there will always
2975 follow an explicit cursor_to. */
2976 BLOCK_INPUT;
2977 XClearWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
2979 /* We have to clear the scroll bars, too. If we have changed
2980 colors or something like that, then they should be notified. */
2981 x_scroll_bar_clear (f);
2983 #if defined (USE_GTK) && defined (USE_TOOLKIT_SCROLL_BARS)
2984 /* Make sure scroll bars are redrawn. As they aren't redrawn by
2985 redisplay, do it here. */
2986 if (FRAME_GTK_WIDGET (f))
2987 gtk_widget_queue_draw (FRAME_GTK_WIDGET (f));
2988 #endif
2990 XFlush (FRAME_X_DISPLAY (f));
2992 UNBLOCK_INPUT;
2997 /* Invert the middle quarter of the frame for .15 sec. */
2999 /* We use the select system call to do the waiting, so we have to make
3000 sure it's available. If it isn't, we just won't do visual bells. */
3002 #if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
3005 /* Subtract the `struct timeval' values X and Y, storing the result in
3006 *RESULT. Return 1 if the difference is negative, otherwise 0. */
3008 static int
3009 timeval_subtract (struct timeval *result, struct timeval x, struct timeval y)
3011 /* Perform the carry for the later subtraction by updating y. This
3012 is safer because on some systems the tv_sec member is unsigned. */
3013 if (x.tv_usec < y.tv_usec)
3015 int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
3016 y.tv_usec -= 1000000 * nsec;
3017 y.tv_sec += nsec;
3020 if (x.tv_usec - y.tv_usec > 1000000)
3022 int nsec = (y.tv_usec - x.tv_usec) / 1000000;
3023 y.tv_usec += 1000000 * nsec;
3024 y.tv_sec -= nsec;
3027 /* Compute the time remaining to wait. tv_usec is certainly
3028 positive. */
3029 result->tv_sec = x.tv_sec - y.tv_sec;
3030 result->tv_usec = x.tv_usec - y.tv_usec;
3032 /* Return indication of whether the result should be considered
3033 negative. */
3034 return x.tv_sec < y.tv_sec;
3037 void
3038 XTflash (struct frame *f)
3040 BLOCK_INPUT;
3043 #ifdef USE_GTK
3044 /* Use Gdk routines to draw. This way, we won't draw over scroll bars
3045 when the scroll bars and the edit widget share the same X window. */
3046 GdkWindow *window = gtk_widget_get_window (FRAME_GTK_WIDGET (f));
3047 GdkGCValues vals;
3048 GdkGC *gc;
3049 vals.foreground.pixel = (FRAME_FOREGROUND_PIXEL (f)
3050 ^ FRAME_BACKGROUND_PIXEL (f));
3051 vals.function = GDK_XOR;
3052 gc = gdk_gc_new_with_values (window,
3053 &vals, GDK_GC_FUNCTION | GDK_GC_FOREGROUND);
3054 #define XFillRectangle(d, win, gc, x, y, w, h) \
3055 gdk_draw_rectangle (window, gc, TRUE, x, y, w, h)
3056 #else
3057 GC gc;
3059 /* Create a GC that will use the GXxor function to flip foreground
3060 pixels into background pixels. */
3062 XGCValues values;
3064 values.function = GXxor;
3065 values.foreground = (FRAME_FOREGROUND_PIXEL (f)
3066 ^ FRAME_BACKGROUND_PIXEL (f));
3068 gc = XCreateGC (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3069 GCFunction | GCForeground, &values);
3071 #endif
3073 /* Get the height not including a menu bar widget. */
3074 int height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, FRAME_LINES (f));
3075 /* Height of each line to flash. */
3076 int flash_height = FRAME_LINE_HEIGHT (f);
3077 /* These will be the left and right margins of the rectangles. */
3078 int flash_left = FRAME_INTERNAL_BORDER_WIDTH (f);
3079 int flash_right = FRAME_PIXEL_WIDTH (f) - FRAME_INTERNAL_BORDER_WIDTH (f);
3081 int width;
3083 /* Don't flash the area between a scroll bar and the frame
3084 edge it is next to. */
3085 switch (FRAME_VERTICAL_SCROLL_BAR_TYPE (f))
3087 case vertical_scroll_bar_left:
3088 flash_left += VERTICAL_SCROLL_BAR_WIDTH_TRIM;
3089 break;
3091 case vertical_scroll_bar_right:
3092 flash_right -= VERTICAL_SCROLL_BAR_WIDTH_TRIM;
3093 break;
3095 default:
3096 break;
3099 width = flash_right - flash_left;
3101 /* If window is tall, flash top and bottom line. */
3102 if (height > 3 * FRAME_LINE_HEIGHT (f))
3104 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3105 flash_left,
3106 (FRAME_INTERNAL_BORDER_WIDTH (f)
3107 + FRAME_TOP_MARGIN_HEIGHT (f)),
3108 width, flash_height);
3109 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3110 flash_left,
3111 (height - flash_height
3112 - FRAME_INTERNAL_BORDER_WIDTH (f)),
3113 width, flash_height);
3116 else
3117 /* If it is short, flash it all. */
3118 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3119 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
3120 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
3122 x_flush (f);
3125 struct timeval wakeup;
3127 EMACS_GET_TIME (wakeup);
3129 /* Compute time to wait until, propagating carry from usecs. */
3130 wakeup.tv_usec += 150000;
3131 wakeup.tv_sec += (wakeup.tv_usec / 1000000);
3132 wakeup.tv_usec %= 1000000;
3134 /* Keep waiting until past the time wakeup or any input gets
3135 available. */
3136 while (! detect_input_pending ())
3138 struct timeval current;
3139 struct timeval timeout;
3141 EMACS_GET_TIME (current);
3143 /* Break if result would be negative. */
3144 if (timeval_subtract (&current, wakeup, current))
3145 break;
3147 /* How long `select' should wait. */
3148 timeout.tv_sec = 0;
3149 timeout.tv_usec = 10000;
3151 /* Try to wait that long--but we might wake up sooner. */
3152 select (0, NULL, NULL, NULL, &timeout);
3156 /* If window is tall, flash top and bottom line. */
3157 if (height > 3 * FRAME_LINE_HEIGHT (f))
3159 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3160 flash_left,
3161 (FRAME_INTERNAL_BORDER_WIDTH (f)
3162 + FRAME_TOP_MARGIN_HEIGHT (f)),
3163 width, flash_height);
3164 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3165 flash_left,
3166 (height - flash_height
3167 - FRAME_INTERNAL_BORDER_WIDTH (f)),
3168 width, flash_height);
3170 else
3171 /* If it is short, flash it all. */
3172 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3173 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
3174 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
3176 #ifdef USE_GTK
3177 g_object_unref (G_OBJECT (gc));
3178 #undef XFillRectangle
3179 #else
3180 XFreeGC (FRAME_X_DISPLAY (f), gc);
3181 #endif
3182 x_flush (f);
3186 UNBLOCK_INPUT;
3189 #endif /* defined (HAVE_TIMEVAL) && defined (HAVE_SELECT) */
3192 static void
3193 XTtoggle_invisible_pointer (FRAME_PTR f, int invisible)
3195 BLOCK_INPUT;
3196 if (invisible)
3198 if (FRAME_X_DISPLAY_INFO (f)->invisible_cursor != 0)
3199 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3200 FRAME_X_DISPLAY_INFO (f)->invisible_cursor);
3202 else
3203 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3204 f->output_data.x->current_cursor);
3205 f->pointer_invisible = invisible;
3206 UNBLOCK_INPUT;
3210 /* Make audible bell. */
3212 void
3213 XTring_bell (struct frame *f)
3215 if (FRAME_X_DISPLAY (f))
3217 #if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
3218 if (visible_bell)
3219 XTflash (f);
3220 else
3221 #endif
3223 BLOCK_INPUT;
3224 XBell (FRAME_X_DISPLAY (f), 0);
3225 XFlush (FRAME_X_DISPLAY (f));
3226 UNBLOCK_INPUT;
3232 /* Specify how many text lines, from the top of the window,
3233 should be affected by insert-lines and delete-lines operations.
3234 This, and those operations, are used only within an update
3235 that is bounded by calls to x_update_begin and x_update_end. */
3237 static void
3238 XTset_terminal_window (struct frame *f, int n)
3240 /* This function intentionally left blank. */
3245 /***********************************************************************
3246 Line Dance
3247 ***********************************************************************/
3249 /* Perform an insert-lines or delete-lines operation, inserting N
3250 lines or deleting -N lines at vertical position VPOS. */
3252 static void
3253 x_ins_del_lines (struct frame *f, int vpos, int n)
3255 abort ();
3259 /* Scroll part of the display as described by RUN. */
3261 static void
3262 x_scroll_run (struct window *w, struct run *run)
3264 struct frame *f = XFRAME (w->frame);
3265 int x, y, width, height, from_y, to_y, bottom_y;
3267 /* Get frame-relative bounding box of the text display area of W,
3268 without mode lines. Include in this box the left and right
3269 fringe of W. */
3270 window_box (w, -1, &x, &y, &width, &height);
3272 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
3273 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
3274 bottom_y = y + height;
3276 if (to_y < from_y)
3278 /* Scrolling up. Make sure we don't copy part of the mode
3279 line at the bottom. */
3280 if (from_y + run->height > bottom_y)
3281 height = bottom_y - from_y;
3282 else
3283 height = run->height;
3285 else
3287 /* Scolling down. Make sure we don't copy over the mode line.
3288 at the bottom. */
3289 if (to_y + run->height > bottom_y)
3290 height = bottom_y - to_y;
3291 else
3292 height = run->height;
3295 BLOCK_INPUT;
3297 /* Cursor off. Will be switched on again in x_update_window_end. */
3298 updated_window = w;
3299 x_clear_cursor (w);
3301 XCopyArea (FRAME_X_DISPLAY (f),
3302 FRAME_X_WINDOW (f), FRAME_X_WINDOW (f),
3303 f->output_data.x->normal_gc,
3304 x, from_y,
3305 width, height,
3306 x, to_y);
3308 UNBLOCK_INPUT;
3313 /***********************************************************************
3314 Exposure Events
3315 ***********************************************************************/
3318 static void
3319 frame_highlight (struct frame *f)
3321 /* We used to only do this if Vx_no_window_manager was non-nil, but
3322 the ICCCM (section 4.1.6) says that the window's border pixmap
3323 and border pixel are window attributes which are "private to the
3324 client", so we can always change it to whatever we want. */
3325 BLOCK_INPUT;
3326 XSetWindowBorder (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3327 f->output_data.x->border_pixel);
3328 UNBLOCK_INPUT;
3329 x_update_cursor (f, 1);
3330 x_set_frame_alpha (f);
3333 static void
3334 frame_unhighlight (struct frame *f)
3336 /* We used to only do this if Vx_no_window_manager was non-nil, but
3337 the ICCCM (section 4.1.6) says that the window's border pixmap
3338 and border pixel are window attributes which are "private to the
3339 client", so we can always change it to whatever we want. */
3340 BLOCK_INPUT;
3341 XSetWindowBorderPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3342 f->output_data.x->border_tile);
3343 UNBLOCK_INPUT;
3344 x_update_cursor (f, 1);
3345 x_set_frame_alpha (f);
3348 /* The focus has changed. Update the frames as necessary to reflect
3349 the new situation. Note that we can't change the selected frame
3350 here, because the Lisp code we are interrupting might become confused.
3351 Each event gets marked with the frame in which it occurred, so the
3352 Lisp code can tell when the switch took place by examining the events. */
3354 static void
3355 x_new_focus_frame (struct x_display_info *dpyinfo, struct frame *frame)
3357 struct frame *old_focus = dpyinfo->x_focus_frame;
3359 if (frame != dpyinfo->x_focus_frame)
3361 /* Set this before calling other routines, so that they see
3362 the correct value of x_focus_frame. */
3363 dpyinfo->x_focus_frame = frame;
3365 if (old_focus && old_focus->auto_lower)
3366 x_lower_frame (old_focus);
3368 if (dpyinfo->x_focus_frame && dpyinfo->x_focus_frame->auto_raise)
3369 pending_autoraise_frame = dpyinfo->x_focus_frame;
3370 else
3371 pending_autoraise_frame = 0;
3374 x_frame_rehighlight (dpyinfo);
3377 /* Handle FocusIn and FocusOut state changes for FRAME.
3378 If FRAME has focus and there exists more than one frame, puts
3379 a FOCUS_IN_EVENT into *BUFP. */
3381 static void
3382 x_focus_changed (int type, int state, struct x_display_info *dpyinfo, struct frame *frame, struct input_event *bufp)
3384 if (type == FocusIn)
3386 if (dpyinfo->x_focus_event_frame != frame)
3388 x_new_focus_frame (dpyinfo, frame);
3389 dpyinfo->x_focus_event_frame = frame;
3391 /* Don't stop displaying the initial startup message
3392 for a switch-frame event we don't need. */
3393 if (NILP (Vterminal_frame)
3394 && CONSP (Vframe_list)
3395 && !NILP (XCDR (Vframe_list)))
3397 bufp->kind = FOCUS_IN_EVENT;
3398 XSETFRAME (bufp->frame_or_window, frame);
3402 frame->output_data.x->focus_state |= state;
3404 #ifdef HAVE_X_I18N
3405 if (FRAME_XIC (frame))
3406 XSetICFocus (FRAME_XIC (frame));
3407 #endif
3409 else if (type == FocusOut)
3411 frame->output_data.x->focus_state &= ~state;
3413 if (dpyinfo->x_focus_event_frame == frame)
3415 dpyinfo->x_focus_event_frame = 0;
3416 x_new_focus_frame (dpyinfo, 0);
3419 #ifdef HAVE_X_I18N
3420 if (FRAME_XIC (frame))
3421 XUnsetICFocus (FRAME_XIC (frame));
3422 #endif
3423 if (frame->pointer_invisible)
3424 XTtoggle_invisible_pointer (frame, 0);
3428 /* The focus may have changed. Figure out if it is a real focus change,
3429 by checking both FocusIn/Out and Enter/LeaveNotify events.
3431 Returns FOCUS_IN_EVENT event in *BUFP. */
3433 static void
3434 x_detect_focus_change (struct x_display_info *dpyinfo, XEvent *event, struct input_event *bufp)
3436 struct frame *frame;
3438 frame = x_any_window_to_frame (dpyinfo, event->xany.window);
3439 if (! frame)
3440 return;
3442 switch (event->type)
3444 case EnterNotify:
3445 case LeaveNotify:
3447 struct frame *focus_frame = dpyinfo->x_focus_event_frame;
3448 int focus_state
3449 = focus_frame ? focus_frame->output_data.x->focus_state : 0;
3451 if (event->xcrossing.detail != NotifyInferior
3452 && event->xcrossing.focus
3453 && ! (focus_state & FOCUS_EXPLICIT))
3454 x_focus_changed ((event->type == EnterNotify ? FocusIn : FocusOut),
3455 FOCUS_IMPLICIT,
3456 dpyinfo, frame, bufp);
3458 break;
3460 case FocusIn:
3461 case FocusOut:
3462 x_focus_changed (event->type,
3463 (event->xfocus.detail == NotifyPointer ?
3464 FOCUS_IMPLICIT : FOCUS_EXPLICIT),
3465 dpyinfo, frame, bufp);
3466 break;
3468 case ClientMessage:
3469 if (event->xclient.message_type == dpyinfo->Xatom_XEMBED)
3471 enum xembed_message msg = event->xclient.data.l[1];
3472 x_focus_changed ((msg == XEMBED_FOCUS_IN ? FocusIn : FocusOut),
3473 FOCUS_EXPLICIT, dpyinfo, frame, bufp);
3475 break;
3480 /* Handle an event saying the mouse has moved out of an Emacs frame. */
3482 void
3483 x_mouse_leave (struct x_display_info *dpyinfo)
3485 x_new_focus_frame (dpyinfo, dpyinfo->x_focus_event_frame);
3488 /* The focus has changed, or we have redirected a frame's focus to
3489 another frame (this happens when a frame uses a surrogate
3490 mini-buffer frame). Shift the highlight as appropriate.
3492 The FRAME argument doesn't necessarily have anything to do with which
3493 frame is being highlighted or un-highlighted; we only use it to find
3494 the appropriate X display info. */
3496 static void
3497 XTframe_rehighlight (struct frame *frame)
3499 x_frame_rehighlight (FRAME_X_DISPLAY_INFO (frame));
3502 static void
3503 x_frame_rehighlight (struct x_display_info *dpyinfo)
3505 struct frame *old_highlight = dpyinfo->x_highlight_frame;
3507 if (dpyinfo->x_focus_frame)
3509 dpyinfo->x_highlight_frame
3510 = ((FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame)))
3511 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
3512 : dpyinfo->x_focus_frame);
3513 if (! FRAME_LIVE_P (dpyinfo->x_highlight_frame))
3515 FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
3516 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
3519 else
3520 dpyinfo->x_highlight_frame = 0;
3522 if (dpyinfo->x_highlight_frame != old_highlight)
3524 if (old_highlight)
3525 frame_unhighlight (old_highlight);
3526 if (dpyinfo->x_highlight_frame)
3527 frame_highlight (dpyinfo->x_highlight_frame);
3533 /* Keyboard processing - modifier keys, vendor-specific keysyms, etc. */
3535 /* Initialize mode_switch_bit and modifier_meaning. */
3536 static void
3537 x_find_modifier_meanings (struct x_display_info *dpyinfo)
3539 int min_code, max_code;
3540 KeySym *syms;
3541 int syms_per_code;
3542 XModifierKeymap *mods;
3544 dpyinfo->meta_mod_mask = 0;
3545 dpyinfo->shift_lock_mask = 0;
3546 dpyinfo->alt_mod_mask = 0;
3547 dpyinfo->super_mod_mask = 0;
3548 dpyinfo->hyper_mod_mask = 0;
3550 XDisplayKeycodes (dpyinfo->display, &min_code, &max_code);
3552 syms = XGetKeyboardMapping (dpyinfo->display,
3553 min_code, max_code - min_code + 1,
3554 &syms_per_code);
3555 mods = XGetModifierMapping (dpyinfo->display);
3557 /* Scan the modifier table to see which modifier bits the Meta and
3558 Alt keysyms are on. */
3560 int row, col; /* The row and column in the modifier table. */
3561 int found_alt_or_meta;
3563 for (row = 3; row < 8; row++)
3565 found_alt_or_meta = 0;
3566 for (col = 0; col < mods->max_keypermod; col++)
3568 KeyCode code = mods->modifiermap[(row * mods->max_keypermod) + col];
3570 /* Zeroes are used for filler. Skip them. */
3571 if (code == 0)
3572 continue;
3574 /* Are any of this keycode's keysyms a meta key? */
3576 int code_col;
3578 for (code_col = 0; code_col < syms_per_code; code_col++)
3580 int sym = syms[((code - min_code) * syms_per_code) + code_col];
3582 switch (sym)
3584 case XK_Meta_L:
3585 case XK_Meta_R:
3586 found_alt_or_meta = 1;
3587 dpyinfo->meta_mod_mask |= (1 << row);
3588 break;
3590 case XK_Alt_L:
3591 case XK_Alt_R:
3592 found_alt_or_meta = 1;
3593 dpyinfo->alt_mod_mask |= (1 << row);
3594 break;
3596 case XK_Hyper_L:
3597 case XK_Hyper_R:
3598 if (!found_alt_or_meta)
3599 dpyinfo->hyper_mod_mask |= (1 << row);
3600 code_col = syms_per_code;
3601 col = mods->max_keypermod;
3602 break;
3604 case XK_Super_L:
3605 case XK_Super_R:
3606 if (!found_alt_or_meta)
3607 dpyinfo->super_mod_mask |= (1 << row);
3608 code_col = syms_per_code;
3609 col = mods->max_keypermod;
3610 break;
3612 case XK_Shift_Lock:
3613 /* Ignore this if it's not on the lock modifier. */
3614 if (!found_alt_or_meta && ((1 << row) == LockMask))
3615 dpyinfo->shift_lock_mask = LockMask;
3616 code_col = syms_per_code;
3617 col = mods->max_keypermod;
3618 break;
3626 /* If we couldn't find any meta keys, accept any alt keys as meta keys. */
3627 if (! dpyinfo->meta_mod_mask)
3629 dpyinfo->meta_mod_mask = dpyinfo->alt_mod_mask;
3630 dpyinfo->alt_mod_mask = 0;
3633 /* If some keys are both alt and meta,
3634 make them just meta, not alt. */
3635 if (dpyinfo->alt_mod_mask & dpyinfo->meta_mod_mask)
3637 dpyinfo->alt_mod_mask &= ~dpyinfo->meta_mod_mask;
3640 XFree ((char *) syms);
3641 XFreeModifiermap (mods);
3644 /* Convert between the modifier bits X uses and the modifier bits
3645 Emacs uses. */
3647 unsigned int
3648 x_x_to_emacs_modifiers (struct x_display_info *dpyinfo, unsigned int state)
3650 EMACS_UINT mod_meta = meta_modifier;
3651 EMACS_UINT mod_alt = alt_modifier;
3652 EMACS_UINT mod_hyper = hyper_modifier;
3653 EMACS_UINT mod_super = super_modifier;
3654 Lisp_Object tem;
3656 tem = Fget (Vx_alt_keysym, Qmodifier_value);
3657 if (! EQ (tem, Qnil)) mod_alt = XUINT (tem);
3658 tem = Fget (Vx_meta_keysym, Qmodifier_value);
3659 if (! EQ (tem, Qnil)) mod_meta = XUINT (tem);
3660 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
3661 if (! EQ (tem, Qnil)) mod_hyper = XUINT (tem);
3662 tem = Fget (Vx_super_keysym, Qmodifier_value);
3663 if (! EQ (tem, Qnil)) mod_super = XUINT (tem);
3666 return ( ((state & (ShiftMask | dpyinfo->shift_lock_mask)) ? shift_modifier : 0)
3667 | ((state & ControlMask) ? ctrl_modifier : 0)
3668 | ((state & dpyinfo->meta_mod_mask) ? mod_meta : 0)
3669 | ((state & dpyinfo->alt_mod_mask) ? mod_alt : 0)
3670 | ((state & dpyinfo->super_mod_mask) ? mod_super : 0)
3671 | ((state & dpyinfo->hyper_mod_mask) ? mod_hyper : 0));
3674 static unsigned int
3675 x_emacs_to_x_modifiers (struct x_display_info *dpyinfo, unsigned int state)
3677 EMACS_UINT mod_meta = meta_modifier;
3678 EMACS_UINT mod_alt = alt_modifier;
3679 EMACS_UINT mod_hyper = hyper_modifier;
3680 EMACS_UINT mod_super = super_modifier;
3682 Lisp_Object tem;
3684 tem = Fget (Vx_alt_keysym, Qmodifier_value);
3685 if (! EQ (tem, Qnil)) mod_alt = XUINT (tem);
3686 tem = Fget (Vx_meta_keysym, Qmodifier_value);
3687 if (! EQ (tem, Qnil)) mod_meta = XUINT (tem);
3688 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
3689 if (! EQ (tem, Qnil)) mod_hyper = XUINT (tem);
3690 tem = Fget (Vx_super_keysym, Qmodifier_value);
3691 if (! EQ (tem, Qnil)) mod_super = XUINT (tem);
3694 return ( ((state & mod_alt) ? dpyinfo->alt_mod_mask : 0)
3695 | ((state & mod_super) ? dpyinfo->super_mod_mask : 0)
3696 | ((state & mod_hyper) ? dpyinfo->hyper_mod_mask : 0)
3697 | ((state & shift_modifier) ? ShiftMask : 0)
3698 | ((state & ctrl_modifier) ? ControlMask : 0)
3699 | ((state & mod_meta) ? dpyinfo->meta_mod_mask : 0));
3702 /* Convert a keysym to its name. */
3704 char *
3705 x_get_keysym_name (int keysym)
3707 char *value;
3709 BLOCK_INPUT;
3710 value = XKeysymToString (keysym);
3711 UNBLOCK_INPUT;
3713 return value;
3718 /* Mouse clicks and mouse movement. Rah. */
3720 /* Prepare a mouse-event in *RESULT for placement in the input queue.
3722 If the event is a button press, then note that we have grabbed
3723 the mouse. */
3725 static Lisp_Object
3726 construct_mouse_click (struct input_event *result, XButtonEvent *event, struct frame *f)
3728 /* Make the event type NO_EVENT; we'll change that when we decide
3729 otherwise. */
3730 result->kind = MOUSE_CLICK_EVENT;
3731 result->code = event->button - Button1;
3732 result->timestamp = event->time;
3733 result->modifiers = (x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO (f),
3734 event->state)
3735 | (event->type == ButtonRelease
3736 ? up_modifier
3737 : down_modifier));
3739 XSETINT (result->x, event->x);
3740 XSETINT (result->y, event->y);
3741 XSETFRAME (result->frame_or_window, f);
3742 result->arg = Qnil;
3743 return Qnil;
3747 /* Function to report a mouse movement to the mainstream Emacs code.
3748 The input handler calls this.
3750 We have received a mouse movement event, which is given in *event.
3751 If the mouse is over a different glyph than it was last time, tell
3752 the mainstream emacs code by setting mouse_moved. If not, ask for
3753 another motion event, so we can check again the next time it moves. */
3755 static XMotionEvent last_mouse_motion_event;
3756 static Lisp_Object last_mouse_motion_frame;
3758 static int
3759 note_mouse_movement (FRAME_PTR frame, XMotionEvent *event)
3761 last_mouse_movement_time = event->time;
3762 last_mouse_motion_event = *event;
3763 XSETFRAME (last_mouse_motion_frame, frame);
3765 if (!FRAME_X_OUTPUT (frame))
3766 return 0;
3768 if (event->window != FRAME_X_WINDOW (frame))
3770 frame->mouse_moved = 1;
3771 last_mouse_scroll_bar = Qnil;
3772 note_mouse_highlight (frame, -1, -1);
3773 last_mouse_glyph_frame = 0;
3774 return 1;
3778 /* Has the mouse moved off the glyph it was on at the last sighting? */
3779 if (frame != last_mouse_glyph_frame
3780 || event->x < last_mouse_glyph.x
3781 || event->x >= last_mouse_glyph.x + last_mouse_glyph.width
3782 || event->y < last_mouse_glyph.y
3783 || event->y >= last_mouse_glyph.y + last_mouse_glyph.height)
3785 frame->mouse_moved = 1;
3786 last_mouse_scroll_bar = Qnil;
3787 note_mouse_highlight (frame, event->x, event->y);
3788 /* Remember which glyph we're now on. */
3789 remember_mouse_glyph (frame, event->x, event->y, &last_mouse_glyph);
3790 last_mouse_glyph_frame = frame;
3791 return 1;
3794 return 0;
3798 /************************************************************************
3799 Mouse Face
3800 ************************************************************************/
3802 static void
3803 redo_mouse_highlight (void)
3805 if (!NILP (last_mouse_motion_frame)
3806 && FRAME_LIVE_P (XFRAME (last_mouse_motion_frame)))
3807 note_mouse_highlight (XFRAME (last_mouse_motion_frame),
3808 last_mouse_motion_event.x,
3809 last_mouse_motion_event.y);
3814 /* Return the current position of the mouse.
3815 *FP should be a frame which indicates which display to ask about.
3817 If the mouse movement started in a scroll bar, set *FP, *BAR_WINDOW,
3818 and *PART to the frame, window, and scroll bar part that the mouse
3819 is over. Set *X and *Y to the portion and whole of the mouse's
3820 position on the scroll bar.
3822 If the mouse movement started elsewhere, set *FP to the frame the
3823 mouse is on, *BAR_WINDOW to nil, and *X and *Y to the character cell
3824 the mouse is over.
3826 Set *TIME to the server time-stamp for the time at which the mouse
3827 was at this position.
3829 Don't store anything if we don't have a valid set of values to report.
3831 This clears the mouse_moved flag, so we can wait for the next mouse
3832 movement. */
3834 static void
3835 XTmouse_position (FRAME_PTR *fp, int insist, Lisp_Object *bar_window, enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y, long unsigned int *time)
3837 FRAME_PTR f1;
3839 BLOCK_INPUT;
3841 if (! NILP (last_mouse_scroll_bar) && insist == 0)
3842 x_scroll_bar_report_motion (fp, bar_window, part, x, y, time);
3843 else
3845 Window root;
3846 int root_x, root_y;
3848 Window dummy_window;
3849 int dummy;
3851 Lisp_Object frame, tail;
3853 /* Clear the mouse-moved flag for every frame on this display. */
3854 FOR_EACH_FRAME (tail, frame)
3855 if (FRAME_X_P (XFRAME (frame))
3856 && FRAME_X_DISPLAY (XFRAME (frame)) == FRAME_X_DISPLAY (*fp))
3857 XFRAME (frame)->mouse_moved = 0;
3859 last_mouse_scroll_bar = Qnil;
3861 /* Figure out which root window we're on. */
3862 XQueryPointer (FRAME_X_DISPLAY (*fp),
3863 DefaultRootWindow (FRAME_X_DISPLAY (*fp)),
3865 /* The root window which contains the pointer. */
3866 &root,
3868 /* Trash which we can't trust if the pointer is on
3869 a different screen. */
3870 &dummy_window,
3872 /* The position on that root window. */
3873 &root_x, &root_y,
3875 /* More trash we can't trust. */
3876 &dummy, &dummy,
3878 /* Modifier keys and pointer buttons, about which
3879 we don't care. */
3880 (unsigned int *) &dummy);
3882 /* Now we have a position on the root; find the innermost window
3883 containing the pointer. */
3885 Window win, child;
3886 int win_x, win_y;
3887 int parent_x = 0, parent_y = 0;
3889 win = root;
3891 /* XTranslateCoordinates can get errors if the window
3892 structure is changing at the same time this function
3893 is running. So at least we must not crash from them. */
3895 x_catch_errors (FRAME_X_DISPLAY (*fp));
3897 if (FRAME_X_DISPLAY_INFO (*fp)->grabbed && last_mouse_frame
3898 && FRAME_LIVE_P (last_mouse_frame))
3900 /* If mouse was grabbed on a frame, give coords for that frame
3901 even if the mouse is now outside it. */
3902 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
3904 /* From-window, to-window. */
3905 root, FRAME_X_WINDOW (last_mouse_frame),
3907 /* From-position, to-position. */
3908 root_x, root_y, &win_x, &win_y,
3910 /* Child of win. */
3911 &child);
3912 f1 = last_mouse_frame;
3914 else
3916 while (1)
3918 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
3920 /* From-window, to-window. */
3921 root, win,
3923 /* From-position, to-position. */
3924 root_x, root_y, &win_x, &win_y,
3926 /* Child of win. */
3927 &child);
3929 if (child == None || child == win)
3930 break;
3931 #ifdef USE_GTK
3932 /* We don't wan't to know the innermost window. We
3933 want the edit window. For non-Gtk+ the innermost
3934 window is the edit window. For Gtk+ it might not
3935 be. It might be the tool bar for example. */
3936 if (x_window_to_frame (FRAME_X_DISPLAY_INFO (*fp), win))
3937 break;
3938 #endif
3939 win = child;
3940 parent_x = win_x;
3941 parent_y = win_y;
3944 /* Now we know that:
3945 win is the innermost window containing the pointer
3946 (XTC says it has no child containing the pointer),
3947 win_x and win_y are the pointer's position in it
3948 (XTC did this the last time through), and
3949 parent_x and parent_y are the pointer's position in win's parent.
3950 (They are what win_x and win_y were when win was child.
3951 If win is the root window, it has no parent, and
3952 parent_{x,y} are invalid, but that's okay, because we'll
3953 never use them in that case.) */
3955 #ifdef USE_GTK
3956 /* We don't wan't to know the innermost window. We
3957 want the edit window. */
3958 f1 = x_window_to_frame (FRAME_X_DISPLAY_INFO (*fp), win);
3959 #else
3960 /* Is win one of our frames? */
3961 f1 = x_any_window_to_frame (FRAME_X_DISPLAY_INFO (*fp), win);
3962 #endif
3964 #ifdef USE_X_TOOLKIT
3965 /* If we end up with the menu bar window, say it's not
3966 on the frame. */
3967 if (f1 != NULL
3968 && f1->output_data.x->menubar_widget
3969 && win == XtWindow (f1->output_data.x->menubar_widget))
3970 f1 = NULL;
3971 #endif /* USE_X_TOOLKIT */
3974 if (x_had_errors_p (FRAME_X_DISPLAY (*fp)))
3975 f1 = 0;
3977 x_uncatch_errors ();
3979 /* If not, is it one of our scroll bars? */
3980 if (! f1)
3982 struct scroll_bar *bar;
3984 bar = x_window_to_scroll_bar (FRAME_X_DISPLAY (*fp), win);
3986 if (bar)
3988 f1 = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
3989 win_x = parent_x;
3990 win_y = parent_y;
3994 if (f1 == 0 && insist > 0)
3995 f1 = SELECTED_FRAME ();
3997 if (f1)
3999 /* Ok, we found a frame. Store all the values.
4000 last_mouse_glyph is a rectangle used to reduce the
4001 generation of mouse events. To not miss any motion
4002 events, we must divide the frame into rectangles of the
4003 size of the smallest character that could be displayed
4004 on it, i.e. into the same rectangles that matrices on
4005 the frame are divided into. */
4007 remember_mouse_glyph (f1, win_x, win_y, &last_mouse_glyph);
4008 last_mouse_glyph_frame = f1;
4010 *bar_window = Qnil;
4011 *part = 0;
4012 *fp = f1;
4013 XSETINT (*x, win_x);
4014 XSETINT (*y, win_y);
4015 *time = last_mouse_movement_time;
4020 UNBLOCK_INPUT;
4025 /***********************************************************************
4026 Scroll bars
4027 ***********************************************************************/
4029 /* Scroll bar support. */
4031 /* Given an X window ID and a DISPLAY, find the struct scroll_bar which
4032 manages it.
4033 This can be called in GC, so we have to make sure to strip off mark
4034 bits. */
4036 static struct scroll_bar *
4037 x_window_to_scroll_bar (Display *display, Window window_id)
4039 Lisp_Object tail;
4041 #if defined (USE_GTK) && defined (USE_TOOLKIT_SCROLL_BARS)
4042 window_id = (Window) xg_get_scroll_id_for_window (display, window_id);
4043 #endif /* USE_GTK && USE_TOOLKIT_SCROLL_BARS */
4045 for (tail = Vframe_list; CONSP (tail); tail = XCDR (tail))
4047 Lisp_Object frame, bar, condemned;
4049 frame = XCAR (tail);
4050 /* All elements of Vframe_list should be frames. */
4051 if (! FRAMEP (frame))
4052 abort ();
4054 if (! FRAME_X_P (XFRAME (frame)))
4055 continue;
4057 /* Scan this frame's scroll bar list for a scroll bar with the
4058 right window ID. */
4059 condemned = FRAME_CONDEMNED_SCROLL_BARS (XFRAME (frame));
4060 for (bar = FRAME_SCROLL_BARS (XFRAME (frame));
4061 /* This trick allows us to search both the ordinary and
4062 condemned scroll bar lists with one loop. */
4063 ! NILP (bar) || (bar = condemned,
4064 condemned = Qnil,
4065 ! NILP (bar));
4066 bar = XSCROLL_BAR (bar)->next)
4067 if (XSCROLL_BAR (bar)->x_window == window_id &&
4068 FRAME_X_DISPLAY (XFRAME (frame)) == display)
4069 return XSCROLL_BAR (bar);
4072 return 0;
4076 #if defined USE_LUCID
4078 /* Return the Lucid menu bar WINDOW is part of. Return null
4079 if WINDOW is not part of a menu bar. */
4081 static Widget
4082 x_window_to_menu_bar (Window window)
4084 Lisp_Object tail;
4086 for (tail = Vframe_list; CONSP (tail); tail = XCDR (tail))
4088 if (FRAME_X_P (XFRAME (XCAR (tail))))
4090 Lisp_Object frame = XCAR (tail);
4091 Widget menu_bar = XFRAME (frame)->output_data.x->menubar_widget;
4093 if (menu_bar && xlwmenu_window_p (menu_bar, window))
4094 return menu_bar;
4098 return NULL;
4101 #endif /* USE_LUCID */
4104 /************************************************************************
4105 Toolkit scroll bars
4106 ************************************************************************/
4108 #ifdef USE_TOOLKIT_SCROLL_BARS
4110 static void x_scroll_bar_to_input_event (XEvent *, struct input_event *);
4111 static void x_send_scroll_bar_event (Lisp_Object, int, int, int);
4112 static void x_create_toolkit_scroll_bar (struct frame *,
4113 struct scroll_bar *);
4114 static void x_set_toolkit_scroll_bar_thumb (struct scroll_bar *,
4115 int, int, int);
4118 /* Lisp window being scrolled. Set when starting to interact with
4119 a toolkit scroll bar, reset to nil when ending the interaction. */
4121 static Lisp_Object window_being_scrolled;
4123 /* Last scroll bar part sent in xm_scroll_callback. */
4125 static int last_scroll_bar_part;
4127 /* Whether this is an Xaw with arrow-scrollbars. This should imply
4128 that movements of 1/20 of the screen size are mapped to up/down. */
4130 #ifndef USE_GTK
4131 /* Id of action hook installed for scroll bars. */
4133 static XtActionHookId action_hook_id;
4135 static Boolean xaw3d_arrow_scroll;
4137 /* Whether the drag scrolling maintains the mouse at the top of the
4138 thumb. If not, resizing the thumb needs to be done more carefully
4139 to avoid jerkyness. */
4141 static Boolean xaw3d_pick_top;
4143 /* Action hook installed via XtAppAddActionHook when toolkit scroll
4144 bars are used.. The hook is responsible for detecting when
4145 the user ends an interaction with the scroll bar, and generates
4146 a `end-scroll' SCROLL_BAR_CLICK_EVENT' event if so. */
4148 static void
4149 xt_action_hook (Widget widget, XtPointer client_data, String action_name,
4150 XEvent *event, String *params, Cardinal *num_params)
4152 int scroll_bar_p;
4153 const char *end_action;
4155 #ifdef USE_MOTIF
4156 scroll_bar_p = XmIsScrollBar (widget);
4157 end_action = "Release";
4158 #else /* !USE_MOTIF i.e. use Xaw */
4159 scroll_bar_p = XtIsSubclass (widget, scrollbarWidgetClass);
4160 end_action = "EndScroll";
4161 #endif /* USE_MOTIF */
4163 if (scroll_bar_p
4164 && strcmp (action_name, end_action) == 0
4165 && WINDOWP (window_being_scrolled))
4167 struct window *w;
4169 x_send_scroll_bar_event (window_being_scrolled,
4170 scroll_bar_end_scroll, 0, 0);
4171 w = XWINDOW (window_being_scrolled);
4173 if (!NILP (XSCROLL_BAR (w->vertical_scroll_bar)->dragging))
4175 XSCROLL_BAR (w->vertical_scroll_bar)->dragging = Qnil;
4176 /* The thumb size is incorrect while dragging: fix it. */
4177 set_vertical_scroll_bar (w);
4179 window_being_scrolled = Qnil;
4180 last_scroll_bar_part = -1;
4182 /* Xt timeouts no longer needed. */
4183 toolkit_scroll_bar_interaction = 0;
4186 #endif /* not USE_GTK */
4188 /* A vector of windows used for communication between
4189 x_send_scroll_bar_event and x_scroll_bar_to_input_event. */
4191 static struct window **scroll_bar_windows;
4192 static int scroll_bar_windows_size;
4195 /* Send a client message with message type Xatom_Scrollbar for a
4196 scroll action to the frame of WINDOW. PART is a value identifying
4197 the part of the scroll bar that was clicked on. PORTION is the
4198 amount to scroll of a whole of WHOLE. */
4200 static void
4201 x_send_scroll_bar_event (Lisp_Object window, int part, int portion, int whole)
4203 XEvent event;
4204 XClientMessageEvent *ev = (XClientMessageEvent *) &event;
4205 struct window *w = XWINDOW (window);
4206 struct frame *f = XFRAME (w->frame);
4207 int i;
4209 BLOCK_INPUT;
4211 /* Construct a ClientMessage event to send to the frame. */
4212 ev->type = ClientMessage;
4213 ev->message_type = FRAME_X_DISPLAY_INFO (f)->Xatom_Scrollbar;
4214 ev->display = FRAME_X_DISPLAY (f);
4215 ev->window = FRAME_X_WINDOW (f);
4216 ev->format = 32;
4218 /* We can only transfer 32 bits in the XClientMessageEvent, which is
4219 not enough to store a pointer or Lisp_Object on a 64 bit system.
4220 So, store the window in scroll_bar_windows and pass the index
4221 into that array in the event. */
4222 for (i = 0; i < scroll_bar_windows_size; ++i)
4223 if (scroll_bar_windows[i] == NULL)
4224 break;
4226 if (i == scroll_bar_windows_size)
4228 int new_size = max (10, 2 * scroll_bar_windows_size);
4229 size_t nbytes = new_size * sizeof *scroll_bar_windows;
4230 size_t old_nbytes = scroll_bar_windows_size * sizeof *scroll_bar_windows;
4232 scroll_bar_windows = (struct window **) xrealloc (scroll_bar_windows,
4233 nbytes);
4234 memset (&scroll_bar_windows[i], 0, nbytes - old_nbytes);
4235 scroll_bar_windows_size = new_size;
4238 scroll_bar_windows[i] = w;
4239 ev->data.l[0] = (long) i;
4240 ev->data.l[1] = (long) part;
4241 ev->data.l[2] = (long) 0;
4242 ev->data.l[3] = (long) portion;
4243 ev->data.l[4] = (long) whole;
4245 /* Make Xt timeouts work while the scroll bar is active. */
4246 toolkit_scroll_bar_interaction = 1;
4247 #ifdef USE_X_TOOLKIT
4248 x_activate_timeout_atimer ();
4249 #endif
4251 /* Setting the event mask to zero means that the message will
4252 be sent to the client that created the window, and if that
4253 window no longer exists, no event will be sent. */
4254 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), False, 0, &event);
4255 UNBLOCK_INPUT;
4259 /* Transform a scroll bar ClientMessage EVENT to an Emacs input event
4260 in *IEVENT. */
4262 static void
4263 x_scroll_bar_to_input_event (XEvent *event, struct input_event *ievent)
4265 XClientMessageEvent *ev = (XClientMessageEvent *) event;
4266 Lisp_Object window;
4267 struct frame *f;
4268 struct window *w;
4270 w = scroll_bar_windows[ev->data.l[0]];
4271 scroll_bar_windows[ev->data.l[0]] = NULL;
4273 XSETWINDOW (window, w);
4274 f = XFRAME (w->frame);
4276 ievent->kind = SCROLL_BAR_CLICK_EVENT;
4277 ievent->frame_or_window = window;
4278 ievent->arg = Qnil;
4279 #ifdef USE_GTK
4280 ievent->timestamp = CurrentTime;
4281 #else
4282 ievent->timestamp = XtLastTimestampProcessed (FRAME_X_DISPLAY (f));
4283 #endif
4284 ievent->part = ev->data.l[1];
4285 ievent->code = ev->data.l[2];
4286 ievent->x = make_number ((int) ev->data.l[3]);
4287 ievent->y = make_number ((int) ev->data.l[4]);
4288 ievent->modifiers = 0;
4292 #ifdef USE_MOTIF
4294 /* Minimum and maximum values used for Motif scroll bars. */
4296 #define XM_SB_MAX 10000000
4299 /* Scroll bar callback for Motif scroll bars. WIDGET is the scroll
4300 bar widget. CLIENT_DATA is a pointer to the scroll_bar structure.
4301 CALL_DATA is a pointer to a XmScrollBarCallbackStruct. */
4303 static void
4304 xm_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
4306 struct scroll_bar *bar = (struct scroll_bar *) client_data;
4307 XmScrollBarCallbackStruct *cs = (XmScrollBarCallbackStruct *) call_data;
4308 int part = -1, whole = 0, portion = 0;
4310 switch (cs->reason)
4312 case XmCR_DECREMENT:
4313 bar->dragging = Qnil;
4314 part = scroll_bar_up_arrow;
4315 break;
4317 case XmCR_INCREMENT:
4318 bar->dragging = Qnil;
4319 part = scroll_bar_down_arrow;
4320 break;
4322 case XmCR_PAGE_DECREMENT:
4323 bar->dragging = Qnil;
4324 part = scroll_bar_above_handle;
4325 break;
4327 case XmCR_PAGE_INCREMENT:
4328 bar->dragging = Qnil;
4329 part = scroll_bar_below_handle;
4330 break;
4332 case XmCR_TO_TOP:
4333 bar->dragging = Qnil;
4334 part = scroll_bar_to_top;
4335 break;
4337 case XmCR_TO_BOTTOM:
4338 bar->dragging = Qnil;
4339 part = scroll_bar_to_bottom;
4340 break;
4342 case XmCR_DRAG:
4344 int slider_size;
4346 /* Get the slider size. */
4347 BLOCK_INPUT;
4348 XtVaGetValues (widget, XmNsliderSize, &slider_size, NULL);
4349 UNBLOCK_INPUT;
4351 whole = XM_SB_MAX - slider_size;
4352 portion = min (cs->value, whole);
4353 part = scroll_bar_handle;
4354 bar->dragging = make_number (cs->value);
4356 break;
4358 case XmCR_VALUE_CHANGED:
4359 break;
4362 if (part >= 0)
4364 window_being_scrolled = bar->window;
4365 last_scroll_bar_part = part;
4366 x_send_scroll_bar_event (bar->window, part, portion, whole);
4370 #elif defined USE_GTK
4372 /* Scroll bar callback for GTK scroll bars. WIDGET is the scroll
4373 bar widget. DATA is a pointer to the scroll_bar structure. */
4375 static gboolean
4376 xg_scroll_callback (GtkRange *range,
4377 GtkScrollType scroll,
4378 gdouble value,
4379 gpointer user_data)
4381 struct scroll_bar *bar = (struct scroll_bar *) user_data;
4382 gdouble position;
4383 int part = -1, whole = 0, portion = 0;
4384 GtkAdjustment *adj = GTK_ADJUSTMENT (gtk_range_get_adjustment (range));
4385 FRAME_PTR f = (FRAME_PTR) g_object_get_data (G_OBJECT (range), XG_FRAME_DATA);
4387 if (xg_ignore_gtk_scrollbar) return FALSE;
4388 position = gtk_adjustment_get_value (adj);
4391 switch (scroll)
4393 case GTK_SCROLL_JUMP:
4394 /* Buttons 1 2 or 3 must be grabbed. */
4395 if (FRAME_X_DISPLAY_INFO (f)->grabbed != 0
4396 && FRAME_X_DISPLAY_INFO (f)->grabbed < (1 << 4))
4398 part = scroll_bar_handle;
4399 whole = gtk_adjustment_get_upper (adj) -
4400 gtk_adjustment_get_page_size (adj);
4401 portion = min ((int)position, whole);
4402 bar->dragging = make_number ((int)portion);
4404 break;
4405 case GTK_SCROLL_STEP_BACKWARD:
4406 part = scroll_bar_up_arrow;
4407 bar->dragging = Qnil;
4408 break;
4409 case GTK_SCROLL_STEP_FORWARD:
4410 part = scroll_bar_down_arrow;
4411 bar->dragging = Qnil;
4412 break;
4413 case GTK_SCROLL_PAGE_BACKWARD:
4414 part = scroll_bar_above_handle;
4415 bar->dragging = Qnil;
4416 break;
4417 case GTK_SCROLL_PAGE_FORWARD:
4418 part = scroll_bar_below_handle;
4419 bar->dragging = Qnil;
4420 break;
4423 if (part >= 0)
4425 window_being_scrolled = bar->window;
4426 last_scroll_bar_part = part;
4427 x_send_scroll_bar_event (bar->window, part, portion, whole);
4430 return FALSE;
4433 /* Callback for button release. Sets dragging to Qnil when dragging is done. */
4435 static gboolean
4436 xg_end_scroll_callback (GtkWidget *widget,
4437 GdkEventButton *event,
4438 gpointer user_data)
4440 struct scroll_bar *bar = (struct scroll_bar *) user_data;
4441 bar->dragging = Qnil;
4442 if (WINDOWP (window_being_scrolled))
4444 x_send_scroll_bar_event (window_being_scrolled,
4445 scroll_bar_end_scroll, 0, 0);
4446 window_being_scrolled = Qnil;
4449 return FALSE;
4453 #else /* not USE_GTK and not USE_MOTIF */
4455 /* Xaw scroll bar callback. Invoked when the thumb is dragged.
4456 WIDGET is the scroll bar widget. CLIENT_DATA is a pointer to the
4457 scroll bar struct. CALL_DATA is a pointer to a float saying where
4458 the thumb is. */
4460 static void
4461 xaw_jump_callback (Widget widget, XtPointer client_data, XtPointer call_data)
4463 struct scroll_bar *bar = (struct scroll_bar *) client_data;
4464 float top = *(float *) call_data;
4465 float shown;
4466 int whole, portion, height;
4467 int part;
4469 /* Get the size of the thumb, a value between 0 and 1. */
4470 BLOCK_INPUT;
4471 XtVaGetValues (widget, XtNshown, &shown, XtNheight, &height, NULL);
4472 UNBLOCK_INPUT;
4474 whole = 10000000;
4475 portion = shown < 1 ? top * whole : 0;
4477 if (shown < 1 && (eabs (top + shown - 1) < 1.0/height))
4478 /* Some derivatives of Xaw refuse to shrink the thumb when you reach
4479 the bottom, so we force the scrolling whenever we see that we're
4480 too close to the bottom (in x_set_toolkit_scroll_bar_thumb
4481 we try to ensure that we always stay two pixels away from the
4482 bottom). */
4483 part = scroll_bar_down_arrow;
4484 else
4485 part = scroll_bar_handle;
4487 window_being_scrolled = bar->window;
4488 bar->dragging = make_number (portion);
4489 last_scroll_bar_part = part;
4490 x_send_scroll_bar_event (bar->window, part, portion, whole);
4494 /* Xaw scroll bar callback. Invoked for incremental scrolling.,
4495 i.e. line or page up or down. WIDGET is the Xaw scroll bar
4496 widget. CLIENT_DATA is a pointer to the scroll_bar structure for
4497 the scroll bar. CALL_DATA is an integer specifying the action that
4498 has taken place. Its magnitude is in the range 0..height of the
4499 scroll bar. Negative values mean scroll towards buffer start.
4500 Values < height of scroll bar mean line-wise movement. */
4502 static void
4503 xaw_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
4505 struct scroll_bar *bar = (struct scroll_bar *) client_data;
4506 /* The position really is stored cast to a pointer. */
4507 int position = (long) call_data;
4508 Dimension height;
4509 int part;
4511 /* Get the height of the scroll bar. */
4512 BLOCK_INPUT;
4513 XtVaGetValues (widget, XtNheight, &height, NULL);
4514 UNBLOCK_INPUT;
4516 if (eabs (position) >= height)
4517 part = (position < 0) ? scroll_bar_above_handle : scroll_bar_below_handle;
4519 /* If Xaw3d was compiled with ARROW_SCROLLBAR,
4520 it maps line-movement to call_data = max(5, height/20). */
4521 else if (xaw3d_arrow_scroll && eabs (position) <= max (5, height / 20))
4522 part = (position < 0) ? scroll_bar_up_arrow : scroll_bar_down_arrow;
4523 else
4524 part = scroll_bar_move_ratio;
4526 window_being_scrolled = bar->window;
4527 bar->dragging = Qnil;
4528 last_scroll_bar_part = part;
4529 x_send_scroll_bar_event (bar->window, part, position, height);
4532 #endif /* not USE_GTK and not USE_MOTIF */
4534 #define SCROLL_BAR_NAME "verticalScrollBar"
4536 /* Create the widget for scroll bar BAR on frame F. Record the widget
4537 and X window of the scroll bar in BAR. */
4539 #ifdef USE_GTK
4540 static void
4541 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
4543 const char *scroll_bar_name = SCROLL_BAR_NAME;
4545 BLOCK_INPUT;
4546 xg_create_scroll_bar (f, bar, G_CALLBACK (xg_scroll_callback),
4547 G_CALLBACK (xg_end_scroll_callback),
4548 scroll_bar_name);
4549 UNBLOCK_INPUT;
4552 #else /* not USE_GTK */
4554 static void
4555 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
4557 Window xwindow;
4558 Widget widget;
4559 Arg av[20];
4560 int ac = 0;
4561 char *scroll_bar_name = SCROLL_BAR_NAME;
4562 unsigned long pixel;
4564 BLOCK_INPUT;
4566 #ifdef USE_MOTIF
4567 /* Set resources. Create the widget. */
4568 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
4569 XtSetArg (av[ac], XmNminimum, 0); ++ac;
4570 XtSetArg (av[ac], XmNmaximum, XM_SB_MAX); ++ac;
4571 XtSetArg (av[ac], XmNorientation, XmVERTICAL); ++ac;
4572 XtSetArg (av[ac], XmNprocessingDirection, XmMAX_ON_BOTTOM), ++ac;
4573 XtSetArg (av[ac], XmNincrement, 1); ++ac;
4574 XtSetArg (av[ac], XmNpageIncrement, 1); ++ac;
4576 pixel = f->output_data.x->scroll_bar_foreground_pixel;
4577 if (pixel != -1)
4579 XtSetArg (av[ac], XmNforeground, pixel);
4580 ++ac;
4583 pixel = f->output_data.x->scroll_bar_background_pixel;
4584 if (pixel != -1)
4586 XtSetArg (av[ac], XmNbackground, pixel);
4587 ++ac;
4590 widget = XmCreateScrollBar (f->output_data.x->edit_widget,
4591 scroll_bar_name, av, ac);
4593 /* Add one callback for everything that can happen. */
4594 XtAddCallback (widget, XmNdecrementCallback, xm_scroll_callback,
4595 (XtPointer) bar);
4596 XtAddCallback (widget, XmNdragCallback, xm_scroll_callback,
4597 (XtPointer) bar);
4598 XtAddCallback (widget, XmNincrementCallback, xm_scroll_callback,
4599 (XtPointer) bar);
4600 XtAddCallback (widget, XmNpageDecrementCallback, xm_scroll_callback,
4601 (XtPointer) bar);
4602 XtAddCallback (widget, XmNpageIncrementCallback, xm_scroll_callback,
4603 (XtPointer) bar);
4604 XtAddCallback (widget, XmNtoBottomCallback, xm_scroll_callback,
4605 (XtPointer) bar);
4606 XtAddCallback (widget, XmNtoTopCallback, xm_scroll_callback,
4607 (XtPointer) bar);
4609 /* Realize the widget. Only after that is the X window created. */
4610 XtRealizeWidget (widget);
4612 /* Set the cursor to an arrow. I didn't find a resource to do that.
4613 And I'm wondering why it hasn't an arrow cursor by default. */
4614 XDefineCursor (XtDisplay (widget), XtWindow (widget),
4615 f->output_data.x->nontext_cursor);
4617 #else /* !USE_MOTIF i.e. use Xaw */
4619 /* Set resources. Create the widget. The background of the
4620 Xaw3d scroll bar widget is a little bit light for my taste.
4621 We don't alter it here to let users change it according
4622 to their taste with `emacs*verticalScrollBar.background: xxx'. */
4623 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
4624 XtSetArg (av[ac], XtNorientation, XtorientVertical); ++ac;
4625 /* For smoother scrolling with Xaw3d -sm */
4626 /* XtSetArg (av[ac], XtNpickTop, True); ++ac; */
4628 pixel = f->output_data.x->scroll_bar_foreground_pixel;
4629 if (pixel != -1)
4631 XtSetArg (av[ac], XtNforeground, pixel);
4632 ++ac;
4635 pixel = f->output_data.x->scroll_bar_background_pixel;
4636 if (pixel != -1)
4638 XtSetArg (av[ac], XtNbackground, pixel);
4639 ++ac;
4642 /* Top/bottom shadow colors. */
4644 /* Allocate them, if necessary. */
4645 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1)
4647 pixel = f->output_data.x->scroll_bar_background_pixel;
4648 if (pixel != -1)
4650 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
4651 FRAME_X_COLORMAP (f),
4652 &pixel, 1.2, 0x8000))
4653 pixel = -1;
4654 f->output_data.x->scroll_bar_top_shadow_pixel = pixel;
4657 if (f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
4659 pixel = f->output_data.x->scroll_bar_background_pixel;
4660 if (pixel != -1)
4662 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
4663 FRAME_X_COLORMAP (f),
4664 &pixel, 0.6, 0x4000))
4665 pixel = -1;
4666 f->output_data.x->scroll_bar_bottom_shadow_pixel = pixel;
4670 #ifdef XtNbeNiceToColormap
4671 /* Tell the toolkit about them. */
4672 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1
4673 || f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
4674 /* We tried to allocate a color for the top/bottom shadow, and
4675 failed, so tell Xaw3d to use dithering instead. */
4676 /* But only if we have a small colormap. Xaw3d can allocate nice
4677 colors itself. */
4679 XtSetArg (av[ac], XtNbeNiceToColormap,
4680 DefaultDepthOfScreen (FRAME_X_SCREEN (f)) < 16);
4681 ++ac;
4683 else
4684 /* Tell what colors Xaw3d should use for the top/bottom shadow, to
4685 be more consistent with other emacs 3d colors, and since Xaw3d is
4686 not good at dealing with allocation failure. */
4688 /* This tells Xaw3d to use real colors instead of dithering for
4689 the shadows. */
4690 XtSetArg (av[ac], XtNbeNiceToColormap, False);
4691 ++ac;
4693 /* Specify the colors. */
4694 pixel = f->output_data.x->scroll_bar_top_shadow_pixel;
4695 if (pixel != -1)
4697 XtSetArg (av[ac], XtNtopShadowPixel, pixel);
4698 ++ac;
4700 pixel = f->output_data.x->scroll_bar_bottom_shadow_pixel;
4701 if (pixel != -1)
4703 XtSetArg (av[ac], XtNbottomShadowPixel, pixel);
4704 ++ac;
4707 #endif
4709 widget = XtCreateWidget (scroll_bar_name, scrollbarWidgetClass,
4710 f->output_data.x->edit_widget, av, ac);
4713 char *initial = "";
4714 char *val = initial;
4715 XtVaGetValues (widget, XtNscrollVCursor, (XtPointer) &val,
4716 #ifdef XtNarrowScrollbars
4717 XtNarrowScrollbars, (XtPointer) &xaw3d_arrow_scroll,
4718 #endif
4719 XtNpickTop, (XtPointer) &xaw3d_pick_top, NULL);
4720 if (xaw3d_arrow_scroll || val == initial)
4721 { /* ARROW_SCROLL */
4722 xaw3d_arrow_scroll = True;
4723 /* Isn't that just a personal preference ? --Stef */
4724 XtVaSetValues (widget, XtNcursorName, "top_left_arrow", NULL);
4728 /* Define callbacks. */
4729 XtAddCallback (widget, XtNjumpProc, xaw_jump_callback, (XtPointer) bar);
4730 XtAddCallback (widget, XtNscrollProc, xaw_scroll_callback,
4731 (XtPointer) bar);
4733 /* Realize the widget. Only after that is the X window created. */
4734 XtRealizeWidget (widget);
4736 #endif /* !USE_MOTIF */
4738 /* Install an action hook that lets us detect when the user
4739 finishes interacting with a scroll bar. */
4740 if (action_hook_id == 0)
4741 action_hook_id = XtAppAddActionHook (Xt_app_con, xt_action_hook, 0);
4743 /* Remember X window and widget in the scroll bar vector. */
4744 SET_SCROLL_BAR_X_WIDGET (bar, widget);
4745 xwindow = XtWindow (widget);
4746 bar->x_window = xwindow;
4748 UNBLOCK_INPUT;
4750 #endif /* not USE_GTK */
4753 /* Set the thumb size and position of scroll bar BAR. We are currently
4754 displaying PORTION out of a whole WHOLE, and our position POSITION. */
4756 #ifdef USE_GTK
4757 static void
4758 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position, int whole)
4760 xg_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
4763 #else /* not USE_GTK */
4764 static void
4765 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position,
4766 int whole)
4768 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
4769 Widget widget = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
4770 float top, shown;
4772 BLOCK_INPUT;
4774 #ifdef USE_MOTIF
4776 /* We use an estimate of 30 chars per line rather than the real
4777 `portion' value. This has the disadvantage that the thumb size
4778 is not very representative, but it makes our life a lot easier.
4779 Otherwise, we have to constantly adjust the thumb size, which
4780 we can't always do quickly enough: while dragging, the size of
4781 the thumb might prevent the user from dragging the thumb all the
4782 way to the end. but Motif and some versions of Xaw3d don't allow
4783 updating the thumb size while dragging. Also, even if we can update
4784 its size, the update will often happen too late.
4785 If you don't believe it, check out revision 1.650 of xterm.c to see
4786 what hoops we were going through and the still poor behavior we got. */
4787 portion = WINDOW_TOTAL_LINES (XWINDOW (bar->window)) * 30;
4788 /* When the thumb is at the bottom, position == whole.
4789 So we need to increase `whole' to make space for the thumb. */
4790 whole += portion;
4792 if (whole <= 0)
4793 top = 0, shown = 1;
4794 else
4796 top = (float) position / whole;
4797 shown = (float) portion / whole;
4800 if (NILP (bar->dragging))
4802 int size, value;
4804 /* Slider size. Must be in the range [1 .. MAX - MIN] where MAX
4805 is the scroll bar's maximum and MIN is the scroll bar's minimum
4806 value. */
4807 size = shown * XM_SB_MAX;
4808 size = min (size, XM_SB_MAX);
4809 size = max (size, 1);
4811 /* Position. Must be in the range [MIN .. MAX - SLIDER_SIZE]. */
4812 value = top * XM_SB_MAX;
4813 value = min (value, XM_SB_MAX - size);
4815 XmScrollBarSetValues (widget, value, size, 0, 0, False);
4817 #else /* !USE_MOTIF i.e. use Xaw */
4819 if (whole == 0)
4820 top = 0, shown = 1;
4821 else
4823 top = (float) position / whole;
4824 shown = (float) portion / whole;
4828 float old_top, old_shown;
4829 Dimension height;
4830 XtVaGetValues (widget,
4831 XtNtopOfThumb, &old_top,
4832 XtNshown, &old_shown,
4833 XtNheight, &height,
4834 NULL);
4836 /* Massage the top+shown values. */
4837 if (NILP (bar->dragging) || last_scroll_bar_part == scroll_bar_down_arrow)
4838 top = max (0, min (1, top));
4839 else
4840 top = old_top;
4841 /* Keep two pixels available for moving the thumb down. */
4842 shown = max (0, min (1 - top - (2.0 / height), shown));
4844 /* If the call to XawScrollbarSetThumb below doesn't seem to work,
4845 check that your system's configuration file contains a define
4846 for `NARROWPROTO'. See s/freebsd.h for an example. */
4847 if (top != old_top || shown != old_shown)
4849 if (NILP (bar->dragging))
4850 XawScrollbarSetThumb (widget, top, shown);
4851 else
4853 /* Try to make the scrolling a tad smoother. */
4854 if (!xaw3d_pick_top)
4855 shown = min (shown, old_shown);
4857 XawScrollbarSetThumb (widget, top, shown);
4861 #endif /* !USE_MOTIF */
4863 UNBLOCK_INPUT;
4865 #endif /* not USE_GTK */
4867 #endif /* USE_TOOLKIT_SCROLL_BARS */
4871 /************************************************************************
4872 Scroll bars, general
4873 ************************************************************************/
4875 /* Create a scroll bar and return the scroll bar vector for it. W is
4876 the Emacs window on which to create the scroll bar. TOP, LEFT,
4877 WIDTH and HEIGHT are the pixel coordinates and dimensions of the
4878 scroll bar. */
4880 static struct scroll_bar *
4881 x_scroll_bar_create (struct window *w, int top, int left, int width, int height)
4883 struct frame *f = XFRAME (w->frame);
4884 struct scroll_bar *bar
4885 = ALLOCATE_PSEUDOVECTOR (struct scroll_bar, x_window, PVEC_OTHER);
4887 BLOCK_INPUT;
4889 #ifdef USE_TOOLKIT_SCROLL_BARS
4890 x_create_toolkit_scroll_bar (f, bar);
4891 #else /* not USE_TOOLKIT_SCROLL_BARS */
4893 XSetWindowAttributes a;
4894 unsigned long mask;
4895 Window window;
4897 a.background_pixel = f->output_data.x->scroll_bar_background_pixel;
4898 if (a.background_pixel == -1)
4899 a.background_pixel = FRAME_BACKGROUND_PIXEL (f);
4901 a.event_mask = (ButtonPressMask | ButtonReleaseMask
4902 | ButtonMotionMask | PointerMotionHintMask
4903 | ExposureMask);
4904 a.cursor = FRAME_X_DISPLAY_INFO (f)->vertical_scroll_bar_cursor;
4906 mask = (CWBackPixel | CWEventMask | CWCursor);
4908 /* Clear the area of W that will serve as a scroll bar. This is
4909 for the case that a window has been split horizontally. In
4910 this case, no clear_frame is generated to reduce flickering. */
4911 if (width > 0 && height > 0)
4912 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4913 left, top, width,
4914 window_box_height (w), False);
4916 window = XCreateWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4917 /* Position and size of scroll bar. */
4918 left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
4919 top,
4920 width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
4921 height,
4922 /* Border width, depth, class, and visual. */
4924 CopyFromParent,
4925 CopyFromParent,
4926 CopyFromParent,
4927 /* Attributes. */
4928 mask, &a);
4929 bar->x_window = window;
4931 #endif /* not USE_TOOLKIT_SCROLL_BARS */
4933 XSETWINDOW (bar->window, w);
4934 bar->top = top;
4935 bar->left = left;
4936 bar->width = width;
4937 bar->height = height;
4938 bar->start = 0;
4939 bar->end = 0;
4940 bar->dragging = Qnil;
4941 bar->fringe_extended_p = 0;
4943 /* Add bar to its frame's list of scroll bars. */
4944 bar->next = FRAME_SCROLL_BARS (f);
4945 bar->prev = Qnil;
4946 XSETVECTOR (FRAME_SCROLL_BARS (f), bar);
4947 if (!NILP (bar->next))
4948 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
4950 /* Map the window/widget. */
4951 #ifdef USE_TOOLKIT_SCROLL_BARS
4953 #ifdef USE_GTK
4954 xg_update_scrollbar_pos (f,
4955 bar->x_window,
4956 top,
4957 left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
4958 width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
4959 max (height, 1));
4960 #else /* not USE_GTK */
4961 Widget scroll_bar = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
4962 XtConfigureWidget (scroll_bar,
4963 left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
4964 top,
4965 width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
4966 max (height, 1), 0);
4967 XtMapWidget (scroll_bar);
4968 #endif /* not USE_GTK */
4970 #else /* not USE_TOOLKIT_SCROLL_BARS */
4971 XMapRaised (FRAME_X_DISPLAY (f), bar->x_window);
4972 #endif /* not USE_TOOLKIT_SCROLL_BARS */
4974 UNBLOCK_INPUT;
4975 return bar;
4979 #ifndef USE_TOOLKIT_SCROLL_BARS
4981 /* Draw BAR's handle in the proper position.
4983 If the handle is already drawn from START to END, don't bother
4984 redrawing it, unless REBUILD is non-zero; in that case, always
4985 redraw it. (REBUILD is handy for drawing the handle after expose
4986 events.)
4988 Normally, we want to constrain the start and end of the handle to
4989 fit inside its rectangle, but if the user is dragging the scroll
4990 bar handle, we want to let them drag it down all the way, so that
4991 the bar's top is as far down as it goes; otherwise, there's no way
4992 to move to the very end of the buffer. */
4994 static void
4995 x_scroll_bar_set_handle (struct scroll_bar *bar, int start, int end, int rebuild)
4997 int dragging = ! NILP (bar->dragging);
4998 Window w = bar->x_window;
4999 FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5000 GC gc = f->output_data.x->normal_gc;
5002 /* If the display is already accurate, do nothing. */
5003 if (! rebuild
5004 && start == bar->start
5005 && end == bar->end)
5006 return;
5008 BLOCK_INPUT;
5011 int inside_width = VERTICAL_SCROLL_BAR_INSIDE_WIDTH (f, bar->width);
5012 int inside_height = VERTICAL_SCROLL_BAR_INSIDE_HEIGHT (f, bar->height);
5013 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
5015 /* Make sure the values are reasonable, and try to preserve
5016 the distance between start and end. */
5018 int length = end - start;
5020 if (start < 0)
5021 start = 0;
5022 else if (start > top_range)
5023 start = top_range;
5024 end = start + length;
5026 if (end < start)
5027 end = start;
5028 else if (end > top_range && ! dragging)
5029 end = top_range;
5032 /* Store the adjusted setting in the scroll bar. */
5033 bar->start = start;
5034 bar->end = end;
5036 /* Clip the end position, just for display. */
5037 if (end > top_range)
5038 end = top_range;
5040 /* Draw bottom positions VERTICAL_SCROLL_BAR_MIN_HANDLE pixels
5041 below top positions, to make sure the handle is always at least
5042 that many pixels tall. */
5043 end += VERTICAL_SCROLL_BAR_MIN_HANDLE;
5045 /* Draw the empty space above the handle. Note that we can't clear
5046 zero-height areas; that means "clear to end of window." */
5047 if (0 < start)
5048 x_clear_area (FRAME_X_DISPLAY (f), w,
5049 /* x, y, width, height, and exposures. */
5050 VERTICAL_SCROLL_BAR_LEFT_BORDER,
5051 VERTICAL_SCROLL_BAR_TOP_BORDER,
5052 inside_width, start,
5053 False);
5055 /* Change to proper foreground color if one is specified. */
5056 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5057 XSetForeground (FRAME_X_DISPLAY (f), gc,
5058 f->output_data.x->scroll_bar_foreground_pixel);
5060 /* Draw the handle itself. */
5061 XFillRectangle (FRAME_X_DISPLAY (f), w, gc,
5062 /* x, y, width, height */
5063 VERTICAL_SCROLL_BAR_LEFT_BORDER,
5064 VERTICAL_SCROLL_BAR_TOP_BORDER + start,
5065 inside_width, end - start);
5067 /* Restore the foreground color of the GC if we changed it above. */
5068 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5069 XSetForeground (FRAME_X_DISPLAY (f), gc,
5070 FRAME_FOREGROUND_PIXEL (f));
5072 /* Draw the empty space below the handle. Note that we can't
5073 clear zero-height areas; that means "clear to end of window." */
5074 if (end < inside_height)
5075 x_clear_area (FRAME_X_DISPLAY (f), w,
5076 /* x, y, width, height, and exposures. */
5077 VERTICAL_SCROLL_BAR_LEFT_BORDER,
5078 VERTICAL_SCROLL_BAR_TOP_BORDER + end,
5079 inside_width, inside_height - end,
5080 False);
5084 UNBLOCK_INPUT;
5087 #endif /* !USE_TOOLKIT_SCROLL_BARS */
5089 /* Destroy scroll bar BAR, and set its Emacs window's scroll bar to
5090 nil. */
5092 static void
5093 x_scroll_bar_remove (struct scroll_bar *bar)
5095 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5096 BLOCK_INPUT;
5098 #ifdef USE_TOOLKIT_SCROLL_BARS
5099 #ifdef USE_GTK
5100 xg_remove_scroll_bar (f, bar->x_window);
5101 #else /* not USE_GTK */
5102 XtDestroyWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar));
5103 #endif /* not USE_GTK */
5104 #else
5105 XDestroyWindow (FRAME_X_DISPLAY (f), bar->x_window);
5106 #endif
5108 /* Disassociate this scroll bar from its window. */
5109 XWINDOW (bar->window)->vertical_scroll_bar = Qnil;
5111 UNBLOCK_INPUT;
5115 /* Set the handle of the vertical scroll bar for WINDOW to indicate
5116 that we are displaying PORTION characters out of a total of WHOLE
5117 characters, starting at POSITION. If WINDOW has no scroll bar,
5118 create one. */
5120 static void
5121 XTset_vertical_scroll_bar (struct window *w, int portion, int whole, int position)
5123 struct frame *f = XFRAME (w->frame);
5124 struct scroll_bar *bar;
5125 int top, height, left, sb_left, width, sb_width;
5126 int window_y, window_height;
5127 #ifdef USE_TOOLKIT_SCROLL_BARS
5128 int fringe_extended_p;
5129 #endif
5131 /* Get window dimensions. */
5132 window_box (w, -1, 0, &window_y, 0, &window_height);
5133 top = window_y;
5134 width = WINDOW_CONFIG_SCROLL_BAR_COLS (w) * FRAME_COLUMN_WIDTH (f);
5135 height = window_height;
5137 /* Compute the left edge of the scroll bar area. */
5138 left = WINDOW_SCROLL_BAR_AREA_X (w);
5140 /* Compute the width of the scroll bar which might be less than
5141 the width of the area reserved for the scroll bar. */
5142 if (WINDOW_CONFIG_SCROLL_BAR_WIDTH (w) > 0)
5143 sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
5144 else
5145 sb_width = width;
5147 /* Compute the left edge of the scroll bar. */
5148 #ifdef USE_TOOLKIT_SCROLL_BARS
5149 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w))
5150 sb_left = left + (WINDOW_RIGHTMOST_P (w) ? width - sb_width : 0);
5151 else
5152 sb_left = left + (WINDOW_LEFTMOST_P (w) ? 0 : width - sb_width);
5153 #else
5154 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w))
5155 sb_left = left + width - sb_width;
5156 else
5157 sb_left = left;
5158 #endif
5160 #ifdef USE_TOOLKIT_SCROLL_BARS
5161 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
5162 fringe_extended_p = (WINDOW_LEFTMOST_P (w)
5163 && WINDOW_LEFT_FRINGE_WIDTH (w)
5164 && (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (w)
5165 || WINDOW_LEFT_MARGIN_COLS (w) == 0));
5166 else
5167 fringe_extended_p = (WINDOW_RIGHTMOST_P (w)
5168 && WINDOW_RIGHT_FRINGE_WIDTH (w)
5169 && (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (w)
5170 || WINDOW_RIGHT_MARGIN_COLS (w) == 0));
5171 #endif
5173 /* Does the scroll bar exist yet? */
5174 if (NILP (w->vertical_scroll_bar))
5176 if (width > 0 && height > 0)
5178 BLOCK_INPUT;
5179 #ifdef USE_TOOLKIT_SCROLL_BARS
5180 if (fringe_extended_p)
5181 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5182 sb_left, top, sb_width, height, False);
5183 else
5184 #endif
5185 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5186 left, top, width, height, False);
5187 UNBLOCK_INPUT;
5190 bar = x_scroll_bar_create (w, top, sb_left, sb_width, height);
5192 else
5194 /* It may just need to be moved and resized. */
5195 unsigned int mask = 0;
5197 bar = XSCROLL_BAR (w->vertical_scroll_bar);
5199 BLOCK_INPUT;
5201 if (sb_left != bar->left)
5202 mask |= CWX;
5203 if (top != bar->top)
5204 mask |= CWY;
5205 if (sb_width != bar->width)
5206 mask |= CWWidth;
5207 if (height != bar->height)
5208 mask |= CWHeight;
5210 #ifdef USE_TOOLKIT_SCROLL_BARS
5212 /* Move/size the scroll bar widget. */
5213 if (mask || bar->fringe_extended_p != fringe_extended_p)
5215 /* Since toolkit scroll bars are smaller than the space reserved
5216 for them on the frame, we have to clear "under" them. */
5217 if (width > 0 && height > 0)
5219 if (fringe_extended_p)
5220 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5221 sb_left, top, sb_width, height, False);
5222 else
5223 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5224 left, top, width, height, False);
5226 #ifdef USE_GTK
5227 xg_update_scrollbar_pos (f,
5228 bar->x_window,
5229 top,
5230 sb_left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5231 sb_width - VERTICAL_SCROLL_BAR_WIDTH_TRIM *2,
5232 max (height, 1));
5233 #else /* not USE_GTK */
5234 XtConfigureWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar),
5235 sb_left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5236 top,
5237 sb_width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
5238 max (height, 1), 0);
5239 #endif /* not USE_GTK */
5241 #else /* not USE_TOOLKIT_SCROLL_BARS */
5243 /* Clear areas not covered by the scroll bar because of
5244 VERTICAL_SCROLL_BAR_WIDTH_TRIM. */
5245 if (VERTICAL_SCROLL_BAR_WIDTH_TRIM)
5247 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5248 left, top, VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5249 height, False);
5250 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5251 left + width - VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5252 top, VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5253 height, False);
5256 /* Clear areas not covered by the scroll bar because it's not as
5257 wide as the area reserved for it. This makes sure a
5258 previous mode line display is cleared after C-x 2 C-x 1, for
5259 example. */
5261 int area_width = WINDOW_CONFIG_SCROLL_BAR_COLS (w) * FRAME_COLUMN_WIDTH (f);
5262 int rest = area_width - sb_width;
5263 if (rest > 0 && height > 0)
5265 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
5266 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5267 left + area_width - rest, top,
5268 rest, height, False);
5269 else
5270 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5271 left, top, rest, height, False);
5275 /* Move/size the scroll bar window. */
5276 if (mask)
5278 XWindowChanges wc;
5280 wc.x = sb_left + VERTICAL_SCROLL_BAR_WIDTH_TRIM;
5281 wc.y = top;
5282 wc.width = sb_width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2;
5283 wc.height = height;
5284 XConfigureWindow (FRAME_X_DISPLAY (f), bar->x_window,
5285 mask, &wc);
5288 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5290 /* Remember new settings. */
5291 bar->left = sb_left;
5292 bar->top = top;
5293 bar->width = sb_width;
5294 bar->height = height;
5296 UNBLOCK_INPUT;
5299 #ifdef USE_TOOLKIT_SCROLL_BARS
5300 bar->fringe_extended_p = fringe_extended_p;
5302 x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
5303 #else /* not USE_TOOLKIT_SCROLL_BARS */
5304 /* Set the scroll bar's current state, unless we're currently being
5305 dragged. */
5306 if (NILP (bar->dragging))
5308 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, height);
5310 if (whole == 0)
5311 x_scroll_bar_set_handle (bar, 0, top_range, 0);
5312 else
5314 int start = ((double) position * top_range) / whole;
5315 int end = ((double) (position + portion) * top_range) / whole;
5316 x_scroll_bar_set_handle (bar, start, end, 0);
5319 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5321 XSETVECTOR (w->vertical_scroll_bar, bar);
5325 /* The following three hooks are used when we're doing a thorough
5326 redisplay of the frame. We don't explicitly know which scroll bars
5327 are going to be deleted, because keeping track of when windows go
5328 away is a real pain - "Can you say set-window-configuration, boys
5329 and girls?" Instead, we just assert at the beginning of redisplay
5330 that *all* scroll bars are to be removed, and then save a scroll bar
5331 from the fiery pit when we actually redisplay its window. */
5333 /* Arrange for all scroll bars on FRAME to be removed at the next call
5334 to `*judge_scroll_bars_hook'. A scroll bar may be spared if
5335 `*redeem_scroll_bar_hook' is applied to its window before the judgment. */
5337 static void
5338 XTcondemn_scroll_bars (FRAME_PTR frame)
5340 /* Transfer all the scroll bars to FRAME_CONDEMNED_SCROLL_BARS. */
5341 while (! NILP (FRAME_SCROLL_BARS (frame)))
5343 Lisp_Object bar;
5344 bar = FRAME_SCROLL_BARS (frame);
5345 FRAME_SCROLL_BARS (frame) = XSCROLL_BAR (bar)->next;
5346 XSCROLL_BAR (bar)->next = FRAME_CONDEMNED_SCROLL_BARS (frame);
5347 XSCROLL_BAR (bar)->prev = Qnil;
5348 if (! NILP (FRAME_CONDEMNED_SCROLL_BARS (frame)))
5349 XSCROLL_BAR (FRAME_CONDEMNED_SCROLL_BARS (frame))->prev = bar;
5350 FRAME_CONDEMNED_SCROLL_BARS (frame) = bar;
5355 /* Un-mark WINDOW's scroll bar for deletion in this judgment cycle.
5356 Note that WINDOW isn't necessarily condemned at all. */
5358 static void
5359 XTredeem_scroll_bar (struct window *window)
5361 struct scroll_bar *bar;
5362 struct frame *f;
5364 /* We can't redeem this window's scroll bar if it doesn't have one. */
5365 if (NILP (window->vertical_scroll_bar))
5366 abort ();
5368 bar = XSCROLL_BAR (window->vertical_scroll_bar);
5370 /* Unlink it from the condemned list. */
5371 f = XFRAME (WINDOW_FRAME (window));
5372 if (NILP (bar->prev))
5374 /* If the prev pointer is nil, it must be the first in one of
5375 the lists. */
5376 if (EQ (FRAME_SCROLL_BARS (f), window->vertical_scroll_bar))
5377 /* It's not condemned. Everything's fine. */
5378 return;
5379 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
5380 window->vertical_scroll_bar))
5381 FRAME_CONDEMNED_SCROLL_BARS (f) = bar->next;
5382 else
5383 /* If its prev pointer is nil, it must be at the front of
5384 one or the other! */
5385 abort ();
5387 else
5388 XSCROLL_BAR (bar->prev)->next = bar->next;
5390 if (! NILP (bar->next))
5391 XSCROLL_BAR (bar->next)->prev = bar->prev;
5393 bar->next = FRAME_SCROLL_BARS (f);
5394 bar->prev = Qnil;
5395 XSETVECTOR (FRAME_SCROLL_BARS (f), bar);
5396 if (! NILP (bar->next))
5397 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
5400 /* Remove all scroll bars on FRAME that haven't been saved since the
5401 last call to `*condemn_scroll_bars_hook'. */
5403 static void
5404 XTjudge_scroll_bars (FRAME_PTR f)
5406 Lisp_Object bar, next;
5408 bar = FRAME_CONDEMNED_SCROLL_BARS (f);
5410 /* Clear out the condemned list now so we won't try to process any
5411 more events on the hapless scroll bars. */
5412 FRAME_CONDEMNED_SCROLL_BARS (f) = Qnil;
5414 for (; ! NILP (bar); bar = next)
5416 struct scroll_bar *b = XSCROLL_BAR (bar);
5418 x_scroll_bar_remove (b);
5420 next = b->next;
5421 b->next = b->prev = Qnil;
5424 /* Now there should be no references to the condemned scroll bars,
5425 and they should get garbage-collected. */
5429 #ifndef USE_TOOLKIT_SCROLL_BARS
5430 /* Handle an Expose or GraphicsExpose event on a scroll bar. This
5431 is a no-op when using toolkit scroll bars.
5433 This may be called from a signal handler, so we have to ignore GC
5434 mark bits. */
5436 static void
5437 x_scroll_bar_expose (struct scroll_bar *bar, XEvent *event)
5439 Window w = bar->x_window;
5440 FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5441 GC gc = f->output_data.x->normal_gc;
5442 int width_trim = VERTICAL_SCROLL_BAR_WIDTH_TRIM;
5444 BLOCK_INPUT;
5446 x_scroll_bar_set_handle (bar, bar->start, bar->end, 1);
5448 /* Switch to scroll bar foreground color. */
5449 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5450 XSetForeground (FRAME_X_DISPLAY (f), gc,
5451 f->output_data.x->scroll_bar_foreground_pixel);
5453 /* Draw a one-pixel border just inside the edges of the scroll bar. */
5454 XDrawRectangle (FRAME_X_DISPLAY (f), w, gc,
5456 /* x, y, width, height */
5457 0, 0,
5458 bar->width - 1 - width_trim - width_trim,
5459 bar->height - 1);
5461 /* Restore the foreground color of the GC if we changed it above. */
5462 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5463 XSetForeground (FRAME_X_DISPLAY (f), gc,
5464 FRAME_FOREGROUND_PIXEL (f));
5466 UNBLOCK_INPUT;
5469 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5471 /* Handle a mouse click on the scroll bar BAR. If *EMACS_EVENT's kind
5472 is set to something other than NO_EVENT, it is enqueued.
5474 This may be called from a signal handler, so we have to ignore GC
5475 mark bits. */
5478 static void
5479 x_scroll_bar_handle_click (struct scroll_bar *bar, XEvent *event, struct input_event *emacs_event)
5481 if (! WINDOWP (bar->window))
5482 abort ();
5484 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
5485 emacs_event->code = event->xbutton.button - Button1;
5486 emacs_event->modifiers
5487 = (x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO
5488 (XFRAME (WINDOW_FRAME (XWINDOW (bar->window)))),
5489 event->xbutton.state)
5490 | (event->type == ButtonRelease
5491 ? up_modifier
5492 : down_modifier));
5493 emacs_event->frame_or_window = bar->window;
5494 emacs_event->arg = Qnil;
5495 emacs_event->timestamp = event->xbutton.time;
5497 int top_range
5498 = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
5499 int y = event->xbutton.y - VERTICAL_SCROLL_BAR_TOP_BORDER;
5501 if (y < 0) y = 0;
5502 if (y > top_range) y = top_range;
5504 if (y < bar->start)
5505 emacs_event->part = scroll_bar_above_handle;
5506 else if (y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
5507 emacs_event->part = scroll_bar_handle;
5508 else
5509 emacs_event->part = scroll_bar_below_handle;
5511 #ifndef USE_TOOLKIT_SCROLL_BARS
5512 /* If the user has released the handle, set it to its final position. */
5513 if (event->type == ButtonRelease
5514 && ! NILP (bar->dragging))
5516 int new_start = y - XINT (bar->dragging);
5517 int new_end = new_start + bar->end - bar->start;
5519 x_scroll_bar_set_handle (bar, new_start, new_end, 0);
5520 bar->dragging = Qnil;
5522 #endif
5524 XSETINT (emacs_event->x, y);
5525 XSETINT (emacs_event->y, top_range);
5529 #ifndef USE_TOOLKIT_SCROLL_BARS
5531 /* Handle some mouse motion while someone is dragging the scroll bar.
5533 This may be called from a signal handler, so we have to ignore GC
5534 mark bits. */
5536 static void
5537 x_scroll_bar_note_movement (struct scroll_bar *bar, XEvent *event)
5539 FRAME_PTR f = XFRAME (XWINDOW (bar->window)->frame);
5541 last_mouse_movement_time = event->xmotion.time;
5543 f->mouse_moved = 1;
5544 XSETVECTOR (last_mouse_scroll_bar, bar);
5546 /* If we're dragging the bar, display it. */
5547 if (! NILP (bar->dragging))
5549 /* Where should the handle be now? */
5550 int new_start = event->xmotion.y - XINT (bar->dragging);
5552 if (new_start != bar->start)
5554 int new_end = new_start + bar->end - bar->start;
5556 x_scroll_bar_set_handle (bar, new_start, new_end, 0);
5561 #endif /* !USE_TOOLKIT_SCROLL_BARS */
5563 /* Return information to the user about the current position of the mouse
5564 on the scroll bar. */
5566 static void
5567 x_scroll_bar_report_motion (FRAME_PTR *fp, Lisp_Object *bar_window, enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y, long unsigned int *time)
5569 struct scroll_bar *bar = XSCROLL_BAR (last_mouse_scroll_bar);
5570 Window w = bar->x_window;
5571 FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5572 int win_x, win_y;
5573 Window dummy_window;
5574 int dummy_coord;
5575 unsigned int dummy_mask;
5577 BLOCK_INPUT;
5579 /* Get the mouse's position relative to the scroll bar window, and
5580 report that. */
5581 if (! XQueryPointer (FRAME_X_DISPLAY (f), w,
5583 /* Root, child, root x and root y. */
5584 &dummy_window, &dummy_window,
5585 &dummy_coord, &dummy_coord,
5587 /* Position relative to scroll bar. */
5588 &win_x, &win_y,
5590 /* Mouse buttons and modifier keys. */
5591 &dummy_mask))
5593 else
5595 int top_range
5596 = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
5598 win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
5600 if (! NILP (bar->dragging))
5601 win_y -= XINT (bar->dragging);
5603 if (win_y < 0)
5604 win_y = 0;
5605 if (win_y > top_range)
5606 win_y = top_range;
5608 *fp = f;
5609 *bar_window = bar->window;
5611 if (! NILP (bar->dragging))
5612 *part = scroll_bar_handle;
5613 else if (win_y < bar->start)
5614 *part = scroll_bar_above_handle;
5615 else if (win_y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
5616 *part = scroll_bar_handle;
5617 else
5618 *part = scroll_bar_below_handle;
5620 XSETINT (*x, win_y);
5621 XSETINT (*y, top_range);
5623 f->mouse_moved = 0;
5624 last_mouse_scroll_bar = Qnil;
5627 *time = last_mouse_movement_time;
5629 UNBLOCK_INPUT;
5633 /* The screen has been cleared so we may have changed foreground or
5634 background colors, and the scroll bars may need to be redrawn.
5635 Clear out the scroll bars, and ask for expose events, so we can
5636 redraw them. */
5638 static void
5639 x_scroll_bar_clear (FRAME_PTR f)
5641 #ifndef USE_TOOLKIT_SCROLL_BARS
5642 Lisp_Object bar;
5644 /* We can have scroll bars even if this is 0,
5645 if we just turned off scroll bar mode.
5646 But in that case we should not clear them. */
5647 if (FRAME_HAS_VERTICAL_SCROLL_BARS (f))
5648 for (bar = FRAME_SCROLL_BARS (f); VECTORP (bar);
5649 bar = XSCROLL_BAR (bar)->next)
5650 XClearArea (FRAME_X_DISPLAY (f),
5651 XSCROLL_BAR (bar)->x_window,
5652 0, 0, 0, 0, True);
5653 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5657 /* The main X event-reading loop - XTread_socket. */
5659 /* This holds the state XLookupString needs to implement dead keys
5660 and other tricks known as "compose processing". _X Window System_
5661 says that a portable program can't use this, but Stephen Gildea assures
5662 me that letting the compiler initialize it to zeros will work okay.
5664 This must be defined outside of XTread_socket, for the same reasons
5665 given for enter_timestamp, above. */
5667 static XComposeStatus compose_status;
5669 /* Record the last 100 characters stored
5670 to help debug the loss-of-chars-during-GC problem. */
5672 static int temp_index;
5673 static short temp_buffer[100];
5675 #define STORE_KEYSYM_FOR_DEBUG(keysym) \
5676 if (temp_index == sizeof temp_buffer / sizeof (short)) \
5677 temp_index = 0; \
5678 temp_buffer[temp_index++] = (keysym)
5680 /* Set this to nonzero to fake an "X I/O error"
5681 on a particular display. */
5683 struct x_display_info *XTread_socket_fake_io_error;
5685 /* When we find no input here, we occasionally do a no-op command
5686 to verify that the X server is still running and we can still talk with it.
5687 We try all the open displays, one by one.
5688 This variable is used for cycling thru the displays. */
5690 static struct x_display_info *next_noop_dpyinfo;
5692 #define SET_SAVED_BUTTON_EVENT \
5693 do \
5695 if (f->output_data.x->saved_menu_event == 0) \
5696 f->output_data.x->saved_menu_event \
5697 = (XEvent *) xmalloc (sizeof (XEvent)); \
5698 *f->output_data.x->saved_menu_event = event; \
5699 inev.ie.kind = MENU_BAR_ACTIVATE_EVENT; \
5700 XSETFRAME (inev.ie.frame_or_window, f); \
5702 while (0)
5704 enum
5706 X_EVENT_NORMAL,
5707 X_EVENT_GOTO_OUT,
5708 X_EVENT_DROP
5711 /* Filter events for the current X input method.
5712 DPYINFO is the display this event is for.
5713 EVENT is the X event to filter.
5715 Returns non-zero if the event was filtered, caller shall not process
5716 this event further.
5717 Returns zero if event is wasn't filtered. */
5719 #ifdef HAVE_X_I18N
5720 static int
5721 x_filter_event (struct x_display_info *dpyinfo, XEvent *event)
5723 /* XFilterEvent returns non-zero if the input method has
5724 consumed the event. We pass the frame's X window to
5725 XFilterEvent because that's the one for which the IC
5726 was created. */
5728 struct frame *f1 = x_any_window_to_frame (dpyinfo,
5729 event->xclient.window);
5731 return XFilterEvent (event, f1 ? FRAME_X_WINDOW (f1) : None);
5733 #endif
5735 #ifdef USE_GTK
5736 static int current_count;
5737 static int current_finish;
5738 static struct input_event *current_hold_quit;
5740 /* This is the filter function invoked by the GTK event loop.
5741 It is invoked before the XEvent is translated to a GdkEvent,
5742 so we have a chance to act on the event before GTK. */
5743 static GdkFilterReturn
5744 event_handler_gdk (GdkXEvent *gxev, GdkEvent *ev, gpointer data)
5746 XEvent *xev = (XEvent *) gxev;
5748 BLOCK_INPUT;
5749 if (current_count >= 0)
5751 struct x_display_info *dpyinfo;
5753 dpyinfo = x_display_info_for_display (xev->xany.display);
5755 #ifdef HAVE_X_I18N
5756 /* Filter events for the current X input method.
5757 GTK calls XFilterEvent but not for key press and release,
5758 so we do it here. */
5759 if ((xev->type == KeyPress || xev->type == KeyRelease)
5760 && dpyinfo
5761 && x_filter_event (dpyinfo, xev))
5763 UNBLOCK_INPUT;
5764 return GDK_FILTER_REMOVE;
5766 #endif
5768 if (! dpyinfo)
5769 current_finish = X_EVENT_NORMAL;
5770 else
5771 current_count +=
5772 handle_one_xevent (dpyinfo, xev, &current_finish,
5773 current_hold_quit);
5775 else
5776 current_finish = x_dispatch_event (xev, xev->xany.display);
5778 UNBLOCK_INPUT;
5780 if (current_finish == X_EVENT_GOTO_OUT || current_finish == X_EVENT_DROP)
5781 return GDK_FILTER_REMOVE;
5783 return GDK_FILTER_CONTINUE;
5785 #endif /* USE_GTK */
5788 static void xembed_send_message (struct frame *f, Time time,
5789 enum xembed_message message,
5790 long detail, long data1, long data2);
5792 /* Handles the XEvent EVENT on display DPYINFO.
5794 *FINISH is X_EVENT_GOTO_OUT if caller should stop reading events.
5795 *FINISH is zero if caller should continue reading events.
5796 *FINISH is X_EVENT_DROP if event should not be passed to the toolkit.
5798 We return the number of characters stored into the buffer. */
5800 static int
5801 handle_one_xevent (struct x_display_info *dpyinfo, XEvent *eventp, int *finish, struct input_event *hold_quit)
5803 union {
5804 struct input_event ie;
5805 struct selection_input_event sie;
5806 } inev;
5807 int count = 0;
5808 int do_help = 0;
5809 int nbytes = 0;
5810 struct frame *f = NULL;
5811 struct coding_system coding;
5812 XEvent event = *eventp;
5813 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
5815 *finish = X_EVENT_NORMAL;
5817 EVENT_INIT (inev.ie);
5818 inev.ie.kind = NO_EVENT;
5819 inev.ie.arg = Qnil;
5821 if (pending_event_wait.eventtype == event.type)
5822 pending_event_wait.eventtype = 0; /* Indicates we got it. */
5824 switch (event.type)
5826 case ClientMessage:
5828 if (event.xclient.message_type
5829 == dpyinfo->Xatom_wm_protocols
5830 && event.xclient.format == 32)
5832 if (event.xclient.data.l[0]
5833 == dpyinfo->Xatom_wm_take_focus)
5835 /* Use x_any_window_to_frame because this
5836 could be the shell widget window
5837 if the frame has no title bar. */
5838 f = x_any_window_to_frame (dpyinfo, event.xclient.window);
5839 #ifdef HAVE_X_I18N
5840 /* Not quite sure this is needed -pd */
5841 if (f && FRAME_XIC (f))
5842 XSetICFocus (FRAME_XIC (f));
5843 #endif
5844 #if 0 /* Emacs sets WM hints whose `input' field is `true'. This
5845 instructs the WM to set the input focus automatically for
5846 Emacs with a call to XSetInputFocus. Setting WM_TAKE_FOCUS
5847 tells the WM to send us a ClientMessage WM_TAKE_FOCUS after
5848 it has set the focus. So, XSetInputFocus below is not
5849 needed.
5851 The call to XSetInputFocus below has also caused trouble. In
5852 cases where the XSetInputFocus done by the WM and the one
5853 below are temporally close (on a fast machine), the call
5854 below can generate additional FocusIn events which confuse
5855 Emacs. */
5857 /* Since we set WM_TAKE_FOCUS, we must call
5858 XSetInputFocus explicitly. But not if f is null,
5859 since that might be an event for a deleted frame. */
5860 if (f)
5862 Display *d = event.xclient.display;
5863 /* Catch and ignore errors, in case window has been
5864 iconified by a window manager such as GWM. */
5865 x_catch_errors (d);
5866 XSetInputFocus (d, event.xclient.window,
5867 /* The ICCCM says this is
5868 the only valid choice. */
5869 RevertToParent,
5870 event.xclient.data.l[1]);
5871 /* This is needed to detect the error
5872 if there is an error. */
5873 XSync (d, False);
5874 x_uncatch_errors ();
5876 /* Not certain about handling scroll bars here */
5877 #endif /* 0 */
5878 goto done;
5881 if (event.xclient.data.l[0]
5882 == dpyinfo->Xatom_wm_save_yourself)
5884 /* Save state modify the WM_COMMAND property to
5885 something which can reinstate us. This notifies
5886 the session manager, who's looking for such a
5887 PropertyNotify. Can restart processing when
5888 a keyboard or mouse event arrives. */
5889 /* If we have a session manager, don't set this.
5890 KDE will then start two Emacsen, one for the
5891 session manager and one for this. */
5892 #ifdef HAVE_X_SM
5893 if (! x_session_have_connection ())
5894 #endif
5896 f = x_top_window_to_frame (dpyinfo,
5897 event.xclient.window);
5898 /* This is just so we only give real data once
5899 for a single Emacs process. */
5900 if (f == SELECTED_FRAME ())
5901 XSetCommand (FRAME_X_DISPLAY (f),
5902 event.xclient.window,
5903 initial_argv, initial_argc);
5904 else if (f)
5905 XSetCommand (FRAME_X_DISPLAY (f),
5906 event.xclient.window,
5907 0, 0);
5909 goto done;
5912 if (event.xclient.data.l[0]
5913 == dpyinfo->Xatom_wm_delete_window)
5915 f = x_any_window_to_frame (dpyinfo,
5916 event.xclient.window);
5917 if (!f)
5918 goto OTHER; /* May be a dialog that is to be removed */
5920 inev.ie.kind = DELETE_WINDOW_EVENT;
5921 XSETFRAME (inev.ie.frame_or_window, f);
5922 goto done;
5925 goto done;
5928 if (event.xclient.message_type
5929 == dpyinfo->Xatom_wm_configure_denied)
5931 goto done;
5934 if (event.xclient.message_type
5935 == dpyinfo->Xatom_wm_window_moved)
5937 int new_x, new_y;
5938 f = x_window_to_frame (dpyinfo, event.xclient.window);
5940 new_x = event.xclient.data.s[0];
5941 new_y = event.xclient.data.s[1];
5943 if (f)
5945 f->left_pos = new_x;
5946 f->top_pos = new_y;
5948 goto done;
5951 #ifdef HACK_EDITRES
5952 if (event.xclient.message_type
5953 == dpyinfo->Xatom_editres)
5955 f = x_any_window_to_frame (dpyinfo, event.xclient.window);
5956 if (f)
5957 _XEditResCheckMessages (f->output_data.x->widget, NULL,
5958 &event, NULL);
5959 goto done;
5961 #endif /* HACK_EDITRES */
5963 if ((event.xclient.message_type
5964 == dpyinfo->Xatom_DONE)
5965 || (event.xclient.message_type
5966 == dpyinfo->Xatom_PAGE))
5968 /* Ghostview job completed. Kill it. We could
5969 reply with "Next" if we received "Page", but we
5970 currently never do because we are interested in
5971 images, only, which should have 1 page. */
5972 Pixmap pixmap = (Pixmap) event.xclient.data.l[1];
5973 f = x_window_to_frame (dpyinfo, event.xclient.window);
5974 if (!f)
5975 goto OTHER;
5976 x_kill_gs_process (pixmap, f);
5977 expose_frame (f, 0, 0, 0, 0);
5978 goto done;
5981 #ifdef USE_TOOLKIT_SCROLL_BARS
5982 /* Scroll bar callbacks send a ClientMessage from which
5983 we construct an input_event. */
5984 if (event.xclient.message_type
5985 == dpyinfo->Xatom_Scrollbar)
5987 x_scroll_bar_to_input_event (&event, &inev.ie);
5988 *finish = X_EVENT_GOTO_OUT;
5989 goto done;
5991 #endif /* USE_TOOLKIT_SCROLL_BARS */
5993 /* XEmbed messages from the embedder (if any). */
5994 if (event.xclient.message_type
5995 == dpyinfo->Xatom_XEMBED)
5997 enum xembed_message msg = event.xclient.data.l[1];
5998 if (msg == XEMBED_FOCUS_IN || msg == XEMBED_FOCUS_OUT)
5999 x_detect_focus_change (dpyinfo, &event, &inev.ie);
6001 *finish = X_EVENT_GOTO_OUT;
6002 goto done;
6005 xft_settings_event (dpyinfo, &event);
6007 f = x_any_window_to_frame (dpyinfo, event.xclient.window);
6008 if (!f)
6009 goto OTHER;
6010 if (x_handle_dnd_message (f, &event.xclient, dpyinfo, &inev.ie))
6011 *finish = X_EVENT_DROP;
6013 break;
6015 case SelectionNotify:
6016 last_user_time = event.xselection.time;
6017 #ifdef USE_X_TOOLKIT
6018 if (! x_window_to_frame (dpyinfo, event.xselection.requestor))
6019 goto OTHER;
6020 #endif /* not USE_X_TOOLKIT */
6021 x_handle_selection_notify (&event.xselection);
6022 break;
6024 case SelectionClear: /* Someone has grabbed ownership. */
6025 last_user_time = event.xselectionclear.time;
6026 #ifdef USE_X_TOOLKIT
6027 if (! x_window_to_frame (dpyinfo, event.xselectionclear.window))
6028 goto OTHER;
6029 #endif /* USE_X_TOOLKIT */
6031 XSelectionClearEvent *eventp = (XSelectionClearEvent *) &event;
6033 inev.ie.kind = SELECTION_CLEAR_EVENT;
6034 SELECTION_EVENT_DISPLAY (&inev.sie) = eventp->display;
6035 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
6036 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
6037 inev.ie.frame_or_window = Qnil;
6039 break;
6041 case SelectionRequest: /* Someone wants our selection. */
6042 last_user_time = event.xselectionrequest.time;
6043 #ifdef USE_X_TOOLKIT
6044 if (!x_window_to_frame (dpyinfo, event.xselectionrequest.owner))
6045 goto OTHER;
6046 #endif /* USE_X_TOOLKIT */
6048 XSelectionRequestEvent *eventp
6049 = (XSelectionRequestEvent *) &event;
6051 inev.ie.kind = SELECTION_REQUEST_EVENT;
6052 SELECTION_EVENT_DISPLAY (&inev.sie) = eventp->display;
6053 SELECTION_EVENT_REQUESTOR (&inev.sie) = eventp->requestor;
6054 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
6055 SELECTION_EVENT_TARGET (&inev.sie) = eventp->target;
6056 SELECTION_EVENT_PROPERTY (&inev.sie) = eventp->property;
6057 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
6058 inev.ie.frame_or_window = Qnil;
6060 break;
6062 case PropertyNotify:
6063 last_user_time = event.xproperty.time;
6064 f = x_top_window_to_frame (dpyinfo, event.xproperty.window);
6065 if (f && event.xproperty.atom == dpyinfo->Xatom_net_wm_state)
6066 x_handle_net_wm_state (f, &event.xproperty);
6068 x_handle_property_notify (&event.xproperty);
6069 xft_settings_event (dpyinfo, &event);
6070 goto OTHER;
6072 case ReparentNotify:
6073 f = x_top_window_to_frame (dpyinfo, event.xreparent.window);
6074 if (f)
6076 int x, y;
6077 f->output_data.x->parent_desc = event.xreparent.parent;
6078 x_real_positions (f, &x, &y);
6079 f->left_pos = x;
6080 f->top_pos = y;
6082 /* Perhaps reparented due to a WM restart. Reset this. */
6083 FRAME_X_DISPLAY_INFO (f)->wm_type = X_WMTYPE_UNKNOWN;
6084 FRAME_X_DISPLAY_INFO (f)->net_supported_window = 0;
6086 goto OTHER;
6088 case Expose:
6089 f = x_window_to_frame (dpyinfo, event.xexpose.window);
6090 if (f)
6092 #ifdef USE_GTK
6093 /* This seems to be needed for GTK 2.6. */
6094 x_clear_area (event.xexpose.display,
6095 event.xexpose.window,
6096 event.xexpose.x, event.xexpose.y,
6097 event.xexpose.width, event.xexpose.height,
6098 FALSE);
6099 #endif
6100 if (f->async_visible == 0)
6102 f->async_visible = 1;
6103 f->async_iconified = 0;
6104 f->output_data.x->has_been_visible = 1;
6105 SET_FRAME_GARBAGED (f);
6107 else
6108 expose_frame (f,
6109 event.xexpose.x, event.xexpose.y,
6110 event.xexpose.width, event.xexpose.height);
6112 else
6114 #ifndef USE_TOOLKIT_SCROLL_BARS
6115 struct scroll_bar *bar;
6116 #endif
6117 #if defined USE_LUCID
6118 /* Submenus of the Lucid menu bar aren't widgets
6119 themselves, so there's no way to dispatch events
6120 to them. Recognize this case separately. */
6122 Widget widget
6123 = x_window_to_menu_bar (event.xexpose.window);
6124 if (widget)
6125 xlwmenu_redisplay (widget);
6127 #endif /* USE_LUCID */
6129 #ifdef USE_TOOLKIT_SCROLL_BARS
6130 /* Dispatch event to the widget. */
6131 goto OTHER;
6132 #else /* not USE_TOOLKIT_SCROLL_BARS */
6133 bar = x_window_to_scroll_bar (event.xexpose.display,
6134 event.xexpose.window);
6136 if (bar)
6137 x_scroll_bar_expose (bar, &event);
6138 #ifdef USE_X_TOOLKIT
6139 else
6140 goto OTHER;
6141 #endif /* USE_X_TOOLKIT */
6142 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6144 break;
6146 case GraphicsExpose: /* This occurs when an XCopyArea's
6147 source area was obscured or not
6148 available. */
6149 f = x_window_to_frame (dpyinfo, event.xgraphicsexpose.drawable);
6150 if (f)
6152 expose_frame (f,
6153 event.xgraphicsexpose.x, event.xgraphicsexpose.y,
6154 event.xgraphicsexpose.width,
6155 event.xgraphicsexpose.height);
6157 #ifdef USE_X_TOOLKIT
6158 else
6159 goto OTHER;
6160 #endif /* USE_X_TOOLKIT */
6161 break;
6163 case NoExpose: /* This occurs when an XCopyArea's
6164 source area was completely
6165 available. */
6166 break;
6168 case UnmapNotify:
6169 /* Redo the mouse-highlight after the tooltip has gone. */
6170 if (event.xmap.window == tip_window)
6172 tip_window = 0;
6173 redo_mouse_highlight ();
6176 f = x_top_window_to_frame (dpyinfo, event.xunmap.window);
6177 if (f) /* F may no longer exist if
6178 the frame was deleted. */
6180 /* While a frame is unmapped, display generation is
6181 disabled; you don't want to spend time updating a
6182 display that won't ever be seen. */
6183 f->async_visible = 0;
6184 /* We can't distinguish, from the event, whether the window
6185 has become iconified or invisible. So assume, if it
6186 was previously visible, than now it is iconified.
6187 But x_make_frame_invisible clears both
6188 the visible flag and the iconified flag;
6189 and that way, we know the window is not iconified now. */
6190 if (FRAME_VISIBLE_P (f) || FRAME_ICONIFIED_P (f))
6192 f->async_iconified = 1;
6194 inev.ie.kind = ICONIFY_EVENT;
6195 XSETFRAME (inev.ie.frame_or_window, f);
6198 goto OTHER;
6200 case MapNotify:
6201 if (event.xmap.window == tip_window)
6202 /* The tooltip has been drawn already. Avoid
6203 the SET_FRAME_GARBAGED below. */
6204 goto OTHER;
6206 /* We use x_top_window_to_frame because map events can
6207 come for sub-windows and they don't mean that the
6208 frame is visible. */
6209 f = x_top_window_to_frame (dpyinfo, event.xmap.window);
6210 if (f)
6212 /* wait_reading_process_output will notice this and update
6213 the frame's display structures.
6214 If we where iconified, we should not set garbaged,
6215 because that stops redrawing on Expose events. This looks
6216 bad if we are called from a recursive event loop
6217 (x_dispatch_event), for example when a dialog is up. */
6218 if (! f->async_iconified)
6219 SET_FRAME_GARBAGED (f);
6221 /* Check if fullscreen was specified before we where mapped the
6222 first time, i.e. from the command line. */
6223 if (!f->output_data.x->has_been_visible)
6224 x_check_fullscreen (f);
6226 f->async_visible = 1;
6227 f->async_iconified = 0;
6228 f->output_data.x->has_been_visible = 1;
6230 if (f->iconified)
6232 inev.ie.kind = DEICONIFY_EVENT;
6233 XSETFRAME (inev.ie.frame_or_window, f);
6235 else if (! NILP (Vframe_list)
6236 && ! NILP (XCDR (Vframe_list)))
6237 /* Force a redisplay sooner or later
6238 to update the frame titles
6239 in case this is the second frame. */
6240 record_asynch_buffer_change ();
6242 #ifdef USE_GTK
6243 xg_frame_resized (f, -1, -1);
6244 #endif
6246 goto OTHER;
6248 case KeyPress:
6250 last_user_time = event.xkey.time;
6251 ignore_next_mouse_click_timeout = 0;
6253 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
6254 /* Dispatch KeyPress events when in menu. */
6255 if (popup_activated ())
6256 goto OTHER;
6257 #endif
6259 f = x_any_window_to_frame (dpyinfo, event.xkey.window);
6261 /* If mouse-highlight is an integer, input clears out
6262 mouse highlighting. */
6263 if (!hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight)
6264 && (f == 0
6265 || !EQ (f->tool_bar_window, hlinfo->mouse_face_window)))
6267 clear_mouse_face (hlinfo);
6268 hlinfo->mouse_face_hidden = 1;
6271 #if defined USE_MOTIF && defined USE_TOOLKIT_SCROLL_BARS
6272 if (f == 0)
6274 /* Scroll bars consume key events, but we want
6275 the keys to go to the scroll bar's frame. */
6276 Widget widget = XtWindowToWidget (dpyinfo->display,
6277 event.xkey.window);
6278 if (widget && XmIsScrollBar (widget))
6280 widget = XtParent (widget);
6281 f = x_any_window_to_frame (dpyinfo, XtWindow (widget));
6284 #endif /* USE_MOTIF and USE_TOOLKIT_SCROLL_BARS */
6286 if (f != 0)
6288 KeySym keysym, orig_keysym;
6289 /* al%imercury@uunet.uu.net says that making this 81
6290 instead of 80 fixed a bug whereby meta chars made
6291 his Emacs hang.
6293 It seems that some version of XmbLookupString has
6294 a bug of not returning XBufferOverflow in
6295 status_return even if the input is too long to
6296 fit in 81 bytes. So, we must prepare sufficient
6297 bytes for copy_buffer. 513 bytes (256 chars for
6298 two-byte character set) seems to be a fairly good
6299 approximation. -- 2000.8.10 handa@etl.go.jp */
6300 unsigned char copy_buffer[513];
6301 unsigned char *copy_bufptr = copy_buffer;
6302 int copy_bufsiz = sizeof (copy_buffer);
6303 int modifiers;
6304 Lisp_Object coding_system = Qlatin_1;
6305 Lisp_Object c;
6307 #ifdef USE_GTK
6308 /* Don't pass keys to GTK. A Tab will shift focus to the
6309 tool bar in GTK 2.4. Keys will still go to menus and
6310 dialogs because in that case popup_activated is TRUE
6311 (see above). */
6312 *finish = X_EVENT_DROP;
6313 #endif
6315 event.xkey.state
6316 |= x_emacs_to_x_modifiers (FRAME_X_DISPLAY_INFO (f),
6317 extra_keyboard_modifiers);
6318 modifiers = event.xkey.state;
6320 /* This will have to go some day... */
6322 /* make_lispy_event turns chars into control chars.
6323 Don't do it here because XLookupString is too eager. */
6324 event.xkey.state &= ~ControlMask;
6325 event.xkey.state &= ~(dpyinfo->meta_mod_mask
6326 | dpyinfo->super_mod_mask
6327 | dpyinfo->hyper_mod_mask
6328 | dpyinfo->alt_mod_mask);
6330 /* In case Meta is ComposeCharacter,
6331 clear its status. According to Markus Ehrnsperger
6332 Markus.Ehrnsperger@lehrstuhl-bross.physik.uni-muenchen.de
6333 this enables ComposeCharacter to work whether or
6334 not it is combined with Meta. */
6335 if (modifiers & dpyinfo->meta_mod_mask)
6336 memset (&compose_status, 0, sizeof (compose_status));
6338 #ifdef HAVE_X_I18N
6339 if (FRAME_XIC (f))
6341 Status status_return;
6343 coding_system = Vlocale_coding_system;
6344 nbytes = XmbLookupString (FRAME_XIC (f),
6345 &event.xkey, copy_bufptr,
6346 copy_bufsiz, &keysym,
6347 &status_return);
6348 if (status_return == XBufferOverflow)
6350 copy_bufsiz = nbytes + 1;
6351 copy_bufptr = (unsigned char *) alloca (copy_bufsiz);
6352 nbytes = XmbLookupString (FRAME_XIC (f),
6353 &event.xkey, copy_bufptr,
6354 copy_bufsiz, &keysym,
6355 &status_return);
6357 /* Xutf8LookupString is a new but already deprecated interface. -stef */
6358 if (status_return == XLookupNone)
6359 break;
6360 else if (status_return == XLookupChars)
6362 keysym = NoSymbol;
6363 modifiers = 0;
6365 else if (status_return != XLookupKeySym
6366 && status_return != XLookupBoth)
6367 abort ();
6369 else
6370 nbytes = XLookupString (&event.xkey, copy_bufptr,
6371 copy_bufsiz, &keysym,
6372 &compose_status);
6373 #else
6374 nbytes = XLookupString (&event.xkey, copy_bufptr,
6375 copy_bufsiz, &keysym,
6376 &compose_status);
6377 #endif
6379 /* If not using XIM/XIC, and a compose sequence is in progress,
6380 we break here. Otherwise, chars_matched is always 0. */
6381 if (compose_status.chars_matched > 0 && nbytes == 0)
6382 break;
6384 memset (&compose_status, 0, sizeof (compose_status));
6385 orig_keysym = keysym;
6387 /* Common for all keysym input events. */
6388 XSETFRAME (inev.ie.frame_or_window, f);
6389 inev.ie.modifiers
6390 = x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO (f), modifiers);
6391 inev.ie.timestamp = event.xkey.time;
6393 /* First deal with keysyms which have defined
6394 translations to characters. */
6395 if (keysym >= 32 && keysym < 128)
6396 /* Avoid explicitly decoding each ASCII character. */
6398 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
6399 inev.ie.code = keysym;
6400 goto done_keysym;
6403 /* Keysyms directly mapped to Unicode characters. */
6404 if (keysym >= 0x01000000 && keysym <= 0x0110FFFF)
6406 if (keysym < 0x01000080)
6407 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
6408 else
6409 inev.ie.kind = MULTIBYTE_CHAR_KEYSTROKE_EVENT;
6410 inev.ie.code = keysym & 0xFFFFFF;
6411 goto done_keysym;
6414 /* Now non-ASCII. */
6415 if (HASH_TABLE_P (Vx_keysym_table)
6416 && (NATNUMP (c = Fgethash (make_number (keysym),
6417 Vx_keysym_table,
6418 Qnil))))
6420 inev.ie.kind = (SINGLE_BYTE_CHAR_P (XFASTINT (c))
6421 ? ASCII_KEYSTROKE_EVENT
6422 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
6423 inev.ie.code = XFASTINT (c);
6424 goto done_keysym;
6427 /* Random non-modifier sorts of keysyms. */
6428 if (((keysym >= XK_BackSpace && keysym <= XK_Escape)
6429 || keysym == XK_Delete
6430 #ifdef XK_ISO_Left_Tab
6431 || (keysym >= XK_ISO_Left_Tab
6432 && keysym <= XK_ISO_Enter)
6433 #endif
6434 || IsCursorKey (keysym) /* 0xff50 <= x < 0xff60 */
6435 || IsMiscFunctionKey (keysym) /* 0xff60 <= x < VARIES */
6436 #ifdef HPUX
6437 /* This recognizes the "extended function
6438 keys". It seems there's no cleaner way.
6439 Test IsModifierKey to avoid handling
6440 mode_switch incorrectly. */
6441 || ((unsigned) (keysym) >= XK_Select
6442 && (unsigned)(keysym) < XK_KP_Space)
6443 #endif
6444 #ifdef XK_dead_circumflex
6445 || orig_keysym == XK_dead_circumflex
6446 #endif
6447 #ifdef XK_dead_grave
6448 || orig_keysym == XK_dead_grave
6449 #endif
6450 #ifdef XK_dead_tilde
6451 || orig_keysym == XK_dead_tilde
6452 #endif
6453 #ifdef XK_dead_diaeresis
6454 || orig_keysym == XK_dead_diaeresis
6455 #endif
6456 #ifdef XK_dead_macron
6457 || orig_keysym == XK_dead_macron
6458 #endif
6459 #ifdef XK_dead_degree
6460 || orig_keysym == XK_dead_degree
6461 #endif
6462 #ifdef XK_dead_acute
6463 || orig_keysym == XK_dead_acute
6464 #endif
6465 #ifdef XK_dead_cedilla
6466 || orig_keysym == XK_dead_cedilla
6467 #endif
6468 #ifdef XK_dead_breve
6469 || orig_keysym == XK_dead_breve
6470 #endif
6471 #ifdef XK_dead_ogonek
6472 || orig_keysym == XK_dead_ogonek
6473 #endif
6474 #ifdef XK_dead_caron
6475 || orig_keysym == XK_dead_caron
6476 #endif
6477 #ifdef XK_dead_doubleacute
6478 || orig_keysym == XK_dead_doubleacute
6479 #endif
6480 #ifdef XK_dead_abovedot
6481 || orig_keysym == XK_dead_abovedot
6482 #endif
6483 || IsKeypadKey (keysym) /* 0xff80 <= x < 0xffbe */
6484 || IsFunctionKey (keysym) /* 0xffbe <= x < 0xffe1 */
6485 /* Any "vendor-specific" key is ok. */
6486 || (orig_keysym & (1 << 28))
6487 || (keysym != NoSymbol && nbytes == 0))
6488 && ! (IsModifierKey (orig_keysym)
6489 /* The symbols from XK_ISO_Lock
6490 to XK_ISO_Last_Group_Lock
6491 don't have real modifiers but
6492 should be treated similarly to
6493 Mode_switch by Emacs. */
6494 #if defined XK_ISO_Lock && defined XK_ISO_Last_Group_Lock
6495 || ((unsigned)(orig_keysym)
6496 >= XK_ISO_Lock
6497 && (unsigned)(orig_keysym)
6498 <= XK_ISO_Last_Group_Lock)
6499 #endif
6502 STORE_KEYSYM_FOR_DEBUG (keysym);
6503 /* make_lispy_event will convert this to a symbolic
6504 key. */
6505 inev.ie.kind = NON_ASCII_KEYSTROKE_EVENT;
6506 inev.ie.code = keysym;
6507 goto done_keysym;
6510 { /* Raw bytes, not keysym. */
6511 register int i;
6512 register int c;
6513 int nchars, len;
6515 for (i = 0, nchars = 0; i < nbytes; i++)
6517 if (ASCII_BYTE_P (copy_bufptr[i]))
6518 nchars++;
6519 STORE_KEYSYM_FOR_DEBUG (copy_bufptr[i]);
6522 if (nchars < nbytes)
6524 /* Decode the input data. */
6525 int require;
6527 /* The input should be decoded with `coding_system'
6528 which depends on which X*LookupString function
6529 we used just above and the locale. */
6530 setup_coding_system (coding_system, &coding);
6531 coding.src_multibyte = 0;
6532 coding.dst_multibyte = 1;
6533 /* The input is converted to events, thus we can't
6534 handle composition. Anyway, there's no XIM that
6535 gives us composition information. */
6536 coding.common_flags &= ~CODING_ANNOTATION_MASK;
6538 require = MAX_MULTIBYTE_LENGTH * nbytes;
6539 coding.destination = alloca (require);
6540 coding.dst_bytes = require;
6541 coding.mode |= CODING_MODE_LAST_BLOCK;
6542 decode_coding_c_string (&coding, copy_bufptr, nbytes, Qnil);
6543 nbytes = coding.produced;
6544 nchars = coding.produced_char;
6545 copy_bufptr = coding.destination;
6548 /* Convert the input data to a sequence of
6549 character events. */
6550 for (i = 0; i < nbytes; i += len)
6552 if (nchars == nbytes)
6553 c = copy_bufptr[i], len = 1;
6554 else
6555 c = STRING_CHAR_AND_LENGTH (copy_bufptr + i, len);
6556 inev.ie.kind = (SINGLE_BYTE_CHAR_P (c)
6557 ? ASCII_KEYSTROKE_EVENT
6558 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
6559 inev.ie.code = c;
6560 kbd_buffer_store_event_hold (&inev.ie, hold_quit);
6563 count += nchars;
6565 inev.ie.kind = NO_EVENT; /* Already stored above. */
6567 if (keysym == NoSymbol)
6568 break;
6571 done_keysym:
6572 #ifdef HAVE_X_I18N
6573 /* Don't dispatch this event since XtDispatchEvent calls
6574 XFilterEvent, and two calls in a row may freeze the
6575 client. */
6576 break;
6577 #else
6578 goto OTHER;
6579 #endif
6581 case KeyRelease:
6582 last_user_time = event.xkey.time;
6583 #ifdef HAVE_X_I18N
6584 /* Don't dispatch this event since XtDispatchEvent calls
6585 XFilterEvent, and two calls in a row may freeze the
6586 client. */
6587 break;
6588 #else
6589 goto OTHER;
6590 #endif
6592 case EnterNotify:
6593 last_user_time = event.xcrossing.time;
6594 x_detect_focus_change (dpyinfo, &event, &inev.ie);
6596 f = x_any_window_to_frame (dpyinfo, event.xcrossing.window);
6598 if (f && x_mouse_click_focus_ignore_position)
6599 ignore_next_mouse_click_timeout = event.xmotion.time + 200;
6601 /* EnterNotify counts as mouse movement,
6602 so update things that depend on mouse position. */
6603 if (f && !f->output_data.x->hourglass_p)
6604 note_mouse_movement (f, &event.xmotion);
6605 #ifdef USE_GTK
6606 /* We may get an EnterNotify on the buttons in the toolbar. In that
6607 case we moved out of any highlighted area and need to note this. */
6608 if (!f && last_mouse_glyph_frame)
6609 note_mouse_movement (last_mouse_glyph_frame, &event.xmotion);
6610 #endif
6611 goto OTHER;
6613 case FocusIn:
6614 x_detect_focus_change (dpyinfo, &event, &inev.ie);
6615 goto OTHER;
6617 case LeaveNotify:
6618 last_user_time = event.xcrossing.time;
6619 x_detect_focus_change (dpyinfo, &event, &inev.ie);
6621 f = x_top_window_to_frame (dpyinfo, event.xcrossing.window);
6622 if (f)
6624 if (f == hlinfo->mouse_face_mouse_frame)
6626 /* If we move outside the frame, then we're
6627 certainly no longer on any text in the frame. */
6628 clear_mouse_face (hlinfo);
6629 hlinfo->mouse_face_mouse_frame = 0;
6632 /* Generate a nil HELP_EVENT to cancel a help-echo.
6633 Do it only if there's something to cancel.
6634 Otherwise, the startup message is cleared when
6635 the mouse leaves the frame. */
6636 if (any_help_event_p)
6637 do_help = -1;
6639 #ifdef USE_GTK
6640 /* See comment in EnterNotify above */
6641 else if (last_mouse_glyph_frame)
6642 note_mouse_movement (last_mouse_glyph_frame, &event.xmotion);
6643 #endif
6644 goto OTHER;
6646 case FocusOut:
6647 x_detect_focus_change (dpyinfo, &event, &inev.ie);
6648 goto OTHER;
6650 case MotionNotify:
6652 last_user_time = event.xmotion.time;
6653 previous_help_echo_string = help_echo_string;
6654 help_echo_string = Qnil;
6656 if (dpyinfo->grabbed && last_mouse_frame
6657 && FRAME_LIVE_P (last_mouse_frame))
6658 f = last_mouse_frame;
6659 else
6660 f = x_window_to_frame (dpyinfo, event.xmotion.window);
6662 if (hlinfo->mouse_face_hidden)
6664 hlinfo->mouse_face_hidden = 0;
6665 clear_mouse_face (hlinfo);
6668 #ifdef USE_GTK
6669 if (f && xg_event_is_for_scrollbar (f, &event))
6670 f = 0;
6671 #endif
6672 if (f)
6675 /* Generate SELECT_WINDOW_EVENTs when needed.
6676 Don't let popup menus influence things (bug#1261). */
6677 if (!NILP (Vmouse_autoselect_window) && !popup_activated ())
6679 Lisp_Object window;
6681 window = window_from_coordinates (f,
6682 event.xmotion.x, event.xmotion.y,
6683 0, 0);
6685 /* Window will be selected only when it is not selected now and
6686 last mouse movement event was not in it. Minibuffer window
6687 will be selected only when it is active. */
6688 if (WINDOWP (window)
6689 && !EQ (window, last_window)
6690 && !EQ (window, selected_window)
6691 /* For click-to-focus window managers
6692 create event iff we don't leave the
6693 selected frame. */
6694 && (focus_follows_mouse
6695 || (EQ (XWINDOW (window)->frame,
6696 XWINDOW (selected_window)->frame))))
6698 inev.ie.kind = SELECT_WINDOW_EVENT;
6699 inev.ie.frame_or_window = window;
6702 last_window=window;
6704 if (!note_mouse_movement (f, &event.xmotion))
6705 help_echo_string = previous_help_echo_string;
6707 else
6709 #ifndef USE_TOOLKIT_SCROLL_BARS
6710 struct scroll_bar *bar
6711 = x_window_to_scroll_bar (event.xmotion.display,
6712 event.xmotion.window);
6714 if (bar)
6715 x_scroll_bar_note_movement (bar, &event);
6716 #endif /* USE_TOOLKIT_SCROLL_BARS */
6718 /* If we move outside the frame, then we're
6719 certainly no longer on any text in the frame. */
6720 clear_mouse_face (hlinfo);
6723 /* If the contents of the global variable help_echo_string
6724 has changed, generate a HELP_EVENT. */
6725 if (!NILP (help_echo_string)
6726 || !NILP (previous_help_echo_string))
6727 do_help = 1;
6728 goto OTHER;
6731 case ConfigureNotify:
6732 f = x_top_window_to_frame (dpyinfo, event.xconfigure.window);
6733 #ifdef USE_GTK
6734 if (!f
6735 && (f = x_any_window_to_frame (dpyinfo, event.xconfigure.window))
6736 && event.xconfigure.window == FRAME_X_WINDOW (f))
6738 xg_frame_resized (f, event.xconfigure.width,
6739 event.xconfigure.height);
6740 f = 0;
6742 #endif
6743 if (f)
6745 #ifndef USE_X_TOOLKIT
6746 #ifndef USE_GTK
6747 int rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, event.xconfigure.height);
6748 int columns = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, event.xconfigure.width);
6750 /* In the toolkit version, change_frame_size
6751 is called by the code that handles resizing
6752 of the EmacsFrame widget. */
6754 /* Even if the number of character rows and columns has
6755 not changed, the font size may have changed, so we need
6756 to check the pixel dimensions as well. */
6757 if (columns != FRAME_COLS (f)
6758 || rows != FRAME_LINES (f)
6759 || event.xconfigure.width != FRAME_PIXEL_WIDTH (f)
6760 || event.xconfigure.height != FRAME_PIXEL_HEIGHT (f))
6762 change_frame_size (f, rows, columns, 0, 1, 0);
6763 SET_FRAME_GARBAGED (f);
6764 cancel_mouse_face (f);
6767 FRAME_PIXEL_WIDTH (f) = event.xconfigure.width;
6768 FRAME_PIXEL_HEIGHT (f) = event.xconfigure.height;
6769 #endif /* not USE_GTK */
6770 #endif
6772 #ifdef USE_GTK
6773 /* GTK creates windows but doesn't map them.
6774 Only get real positions when mapped. */
6775 if (FRAME_GTK_OUTER_WIDGET (f)
6776 && gtk_widget_get_mapped (FRAME_GTK_OUTER_WIDGET (f)))
6777 #endif
6779 x_real_positions (f, &f->left_pos, &f->top_pos);
6782 #ifdef HAVE_X_I18N
6783 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMStatusArea))
6784 xic_set_statusarea (f);
6785 #endif
6788 goto OTHER;
6790 case ButtonRelease:
6791 case ButtonPress:
6793 /* If we decide we want to generate an event to be seen
6794 by the rest of Emacs, we put it here. */
6795 int tool_bar_p = 0;
6797 memset (&compose_status, 0, sizeof (compose_status));
6798 last_mouse_glyph_frame = 0;
6799 last_user_time = event.xbutton.time;
6801 if (dpyinfo->grabbed
6802 && last_mouse_frame
6803 && FRAME_LIVE_P (last_mouse_frame))
6804 f = last_mouse_frame;
6805 else
6806 f = x_window_to_frame (dpyinfo, event.xbutton.window);
6808 #ifdef USE_GTK
6809 if (f && xg_event_is_for_scrollbar (f, &event))
6810 f = 0;
6811 #endif
6812 if (f)
6814 /* Is this in the tool-bar? */
6815 if (WINDOWP (f->tool_bar_window)
6816 && WINDOW_TOTAL_LINES (XWINDOW (f->tool_bar_window)))
6818 Lisp_Object window;
6819 int x = event.xbutton.x;
6820 int y = event.xbutton.y;
6822 window = window_from_coordinates (f, x, y, 0, 1);
6823 tool_bar_p = EQ (window, f->tool_bar_window);
6825 if (tool_bar_p && event.xbutton.button < 4)
6827 handle_tool_bar_click (f, x, y,
6828 event.xbutton.type == ButtonPress,
6829 x_x_to_emacs_modifiers (dpyinfo,
6830 event.xbutton.state));
6834 if (!tool_bar_p)
6835 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
6836 if (! popup_activated ())
6837 #endif
6839 if (ignore_next_mouse_click_timeout)
6841 if (event.type == ButtonPress
6842 && (int)(event.xbutton.time - ignore_next_mouse_click_timeout) > 0)
6844 ignore_next_mouse_click_timeout = 0;
6845 construct_mouse_click (&inev.ie, &event.xbutton, f);
6847 if (event.type == ButtonRelease)
6848 ignore_next_mouse_click_timeout = 0;
6850 else
6851 construct_mouse_click (&inev.ie, &event.xbutton, f);
6853 if (FRAME_X_EMBEDDED_P (f))
6854 xembed_send_message (f, event.xbutton.time,
6855 XEMBED_REQUEST_FOCUS, 0, 0, 0);
6857 else
6859 struct scroll_bar *bar
6860 = x_window_to_scroll_bar (event.xbutton.display,
6861 event.xbutton.window);
6863 #ifdef USE_TOOLKIT_SCROLL_BARS
6864 /* Make the "Ctrl-Mouse-2 splits window" work for toolkit
6865 scroll bars. */
6866 if (bar && event.xbutton.state & ControlMask)
6868 x_scroll_bar_handle_click (bar, &event, &inev.ie);
6869 *finish = X_EVENT_DROP;
6871 #else /* not USE_TOOLKIT_SCROLL_BARS */
6872 if (bar)
6873 x_scroll_bar_handle_click (bar, &event, &inev.ie);
6874 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6877 if (event.type == ButtonPress)
6879 dpyinfo->grabbed |= (1 << event.xbutton.button);
6880 last_mouse_frame = f;
6882 if (!tool_bar_p)
6883 last_tool_bar_item = -1;
6885 else
6886 dpyinfo->grabbed &= ~(1 << event.xbutton.button);
6888 /* Ignore any mouse motion that happened before this event;
6889 any subsequent mouse-movement Emacs events should reflect
6890 only motion after the ButtonPress/Release. */
6891 if (f != 0)
6892 f->mouse_moved = 0;
6894 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
6895 f = x_menubar_window_to_frame (dpyinfo, &event);
6896 /* For a down-event in the menu bar,
6897 don't pass it to Xt right now.
6898 Instead, save it away
6899 and we will pass it to Xt from kbd_buffer_get_event.
6900 That way, we can run some Lisp code first. */
6901 if (! popup_activated ()
6902 #ifdef USE_GTK
6903 /* Gtk+ menus only react to the first three buttons. */
6904 && event.xbutton.button < 3
6905 #endif
6906 && f && event.type == ButtonPress
6907 /* Verify the event is really within the menu bar
6908 and not just sent to it due to grabbing. */
6909 && event.xbutton.x >= 0
6910 && event.xbutton.x < FRAME_PIXEL_WIDTH (f)
6911 && event.xbutton.y >= 0
6912 && event.xbutton.y < f->output_data.x->menubar_height
6913 && event.xbutton.same_screen)
6915 SET_SAVED_BUTTON_EVENT;
6916 XSETFRAME (last_mouse_press_frame, f);
6917 *finish = X_EVENT_DROP;
6919 else if (event.type == ButtonPress)
6921 last_mouse_press_frame = Qnil;
6922 goto OTHER;
6924 else
6925 goto OTHER;
6926 #endif /* USE_X_TOOLKIT || USE_GTK */
6928 break;
6930 case CirculateNotify:
6931 goto OTHER;
6933 case CirculateRequest:
6934 goto OTHER;
6936 case VisibilityNotify:
6937 goto OTHER;
6939 case MappingNotify:
6940 /* Someone has changed the keyboard mapping - update the
6941 local cache. */
6942 switch (event.xmapping.request)
6944 case MappingModifier:
6945 x_find_modifier_meanings (dpyinfo);
6946 /* This is meant to fall through. */
6947 case MappingKeyboard:
6948 XRefreshKeyboardMapping (&event.xmapping);
6950 goto OTHER;
6952 case DestroyNotify:
6953 xft_settings_event (dpyinfo, &event);
6954 break;
6956 default:
6957 OTHER:
6958 #ifdef USE_X_TOOLKIT
6959 BLOCK_INPUT;
6960 if (*finish != X_EVENT_DROP)
6961 XtDispatchEvent (&event);
6962 UNBLOCK_INPUT;
6963 #endif /* USE_X_TOOLKIT */
6964 break;
6967 done:
6968 if (inev.ie.kind != NO_EVENT)
6970 kbd_buffer_store_event_hold (&inev.ie, hold_quit);
6971 count++;
6974 if (do_help
6975 && !(hold_quit && hold_quit->kind != NO_EVENT))
6977 Lisp_Object frame;
6979 if (f)
6980 XSETFRAME (frame, f);
6981 else
6982 frame = Qnil;
6984 if (do_help > 0)
6986 any_help_event_p = 1;
6987 gen_help_event (help_echo_string, frame, help_echo_window,
6988 help_echo_object, help_echo_pos);
6990 else
6992 help_echo_string = Qnil;
6993 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
6995 count++;
6998 *eventp = event;
6999 return count;
7003 /* Handles the XEvent EVENT on display DISPLAY.
7004 This is used for event loops outside the normal event handling,
7005 i.e. looping while a popup menu or a dialog is posted.
7007 Returns the value handle_one_xevent sets in the finish argument. */
7009 x_dispatch_event (XEvent *event, Display *display)
7011 struct x_display_info *dpyinfo;
7012 int finish = X_EVENT_NORMAL;
7014 dpyinfo = x_display_info_for_display (display);
7016 if (dpyinfo)
7017 handle_one_xevent (dpyinfo, event, &finish, 0);
7019 return finish;
7023 /* Read events coming from the X server.
7024 This routine is called by the SIGIO handler.
7025 We return as soon as there are no more events to be read.
7027 We return the number of characters stored into the buffer,
7028 thus pretending to be `read' (except the characters we store
7029 in the keyboard buffer can be multibyte, so are not necessarily
7030 C chars).
7032 EXPECTED is nonzero if the caller knows input is available. */
7034 static int
7035 XTread_socket (struct terminal *terminal, int expected, struct input_event *hold_quit)
7037 int count = 0;
7038 XEvent event;
7039 int event_found = 0;
7041 if (interrupt_input_blocked)
7043 interrupt_input_pending = 1;
7044 #ifdef SYNC_INPUT
7045 pending_signals = 1;
7046 #endif
7047 return -1;
7050 interrupt_input_pending = 0;
7051 #ifdef SYNC_INPUT
7052 pending_signals = pending_atimers;
7053 #endif
7054 BLOCK_INPUT;
7056 /* So people can tell when we have read the available input. */
7057 input_signal_count++;
7059 ++handling_signal;
7061 #ifdef HAVE_X_SM
7062 /* Only check session manager input for the primary display. */
7063 if (terminal->id == 1 && x_session_have_connection ())
7065 struct input_event inev;
7066 BLOCK_INPUT;
7067 /* We don't need to EVENT_INIT (inev) here, as
7068 x_session_check_input copies an entire input_event. */
7069 if (x_session_check_input (&inev))
7071 kbd_buffer_store_event_hold (&inev, hold_quit);
7072 count++;
7074 UNBLOCK_INPUT;
7076 #endif
7078 /* For debugging, this gives a way to fake an I/O error. */
7079 if (terminal->display_info.x == XTread_socket_fake_io_error)
7081 XTread_socket_fake_io_error = 0;
7082 x_io_error_quitter (terminal->display_info.x->display);
7085 #ifndef USE_GTK
7086 while (XPending (terminal->display_info.x->display))
7088 int finish;
7090 XNextEvent (terminal->display_info.x->display, &event);
7092 #ifdef HAVE_X_I18N
7093 /* Filter events for the current X input method. */
7094 if (x_filter_event (terminal->display_info.x, &event))
7095 continue;
7096 #endif
7097 event_found = 1;
7099 count += handle_one_xevent (terminal->display_info.x,
7100 &event, &finish, hold_quit);
7102 if (finish == X_EVENT_GOTO_OUT)
7103 goto out;
7106 #else /* USE_GTK */
7108 /* For GTK we must use the GTK event loop. But XEvents gets passed
7109 to our filter function above, and then to the big event switch.
7110 We use a bunch of globals to communicate with our filter function,
7111 that is kind of ugly, but it works.
7113 There is no way to do one display at the time, GTK just does events
7114 from all displays. */
7116 while (gtk_events_pending ())
7118 current_count = count;
7119 current_hold_quit = hold_quit;
7121 gtk_main_iteration ();
7123 count = current_count;
7124 current_count = -1;
7125 current_hold_quit = 0;
7127 if (current_finish == X_EVENT_GOTO_OUT)
7128 break;
7130 #endif /* USE_GTK */
7132 out:;
7134 /* On some systems, an X bug causes Emacs to get no more events
7135 when the window is destroyed. Detect that. (1994.) */
7136 if (! event_found)
7138 /* Emacs and the X Server eats up CPU time if XNoOp is done every time.
7139 One XNOOP in 100 loops will make Emacs terminate.
7140 B. Bretthauer, 1994 */
7141 x_noop_count++;
7142 if (x_noop_count >= 100)
7144 x_noop_count=0;
7146 if (next_noop_dpyinfo == 0)
7147 next_noop_dpyinfo = x_display_list;
7149 XNoOp (next_noop_dpyinfo->display);
7151 /* Each time we get here, cycle through the displays now open. */
7152 next_noop_dpyinfo = next_noop_dpyinfo->next;
7156 /* If the focus was just given to an auto-raising frame,
7157 raise it now. */
7158 /* ??? This ought to be able to handle more than one such frame. */
7159 if (pending_autoraise_frame)
7161 x_raise_frame (pending_autoraise_frame);
7162 pending_autoraise_frame = 0;
7165 --handling_signal;
7166 UNBLOCK_INPUT;
7168 return count;
7174 /***********************************************************************
7175 Text Cursor
7176 ***********************************************************************/
7178 /* Set clipping for output in glyph row ROW. W is the window in which
7179 we operate. GC is the graphics context to set clipping in.
7181 ROW may be a text row or, e.g., a mode line. Text rows must be
7182 clipped to the interior of the window dedicated to text display,
7183 mode lines must be clipped to the whole window. */
7185 static void
7186 x_clip_to_row (struct window *w, struct glyph_row *row, int area, GC gc)
7188 struct frame *f = XFRAME (WINDOW_FRAME (w));
7189 XRectangle clip_rect;
7190 int window_x, window_y, window_width;
7192 window_box (w, area, &window_x, &window_y, &window_width, 0);
7194 clip_rect.x = window_x;
7195 clip_rect.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
7196 clip_rect.y = max (clip_rect.y, window_y);
7197 clip_rect.width = window_width;
7198 clip_rect.height = row->visible_height;
7200 XSetClipRectangles (FRAME_X_DISPLAY (f), gc, 0, 0, &clip_rect, 1, Unsorted);
7204 /* Draw a hollow box cursor on window W in glyph row ROW. */
7206 static void
7207 x_draw_hollow_cursor (struct window *w, struct glyph_row *row)
7209 struct frame *f = XFRAME (WINDOW_FRAME (w));
7210 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
7211 Display *dpy = FRAME_X_DISPLAY (f);
7212 int x, y, wd, h;
7213 XGCValues xgcv;
7214 struct glyph *cursor_glyph;
7215 GC gc;
7217 /* Get the glyph the cursor is on. If we can't tell because
7218 the current matrix is invalid or such, give up. */
7219 cursor_glyph = get_phys_cursor_glyph (w);
7220 if (cursor_glyph == NULL)
7221 return;
7223 /* Compute frame-relative coordinates for phys cursor. */
7224 get_phys_cursor_geometry (w, row, cursor_glyph, &x, &y, &h);
7225 wd = w->phys_cursor_width;
7227 /* The foreground of cursor_gc is typically the same as the normal
7228 background color, which can cause the cursor box to be invisible. */
7229 xgcv.foreground = f->output_data.x->cursor_pixel;
7230 if (dpyinfo->scratch_cursor_gc)
7231 XChangeGC (dpy, dpyinfo->scratch_cursor_gc, GCForeground, &xgcv);
7232 else
7233 dpyinfo->scratch_cursor_gc = XCreateGC (dpy, FRAME_X_WINDOW (f),
7234 GCForeground, &xgcv);
7235 gc = dpyinfo->scratch_cursor_gc;
7237 /* Set clipping, draw the rectangle, and reset clipping again. */
7238 x_clip_to_row (w, row, TEXT_AREA, gc);
7239 XDrawRectangle (dpy, FRAME_X_WINDOW (f), gc, x, y, wd, h - 1);
7240 XSetClipMask (dpy, gc, None);
7244 /* Draw a bar cursor on window W in glyph row ROW.
7246 Implementation note: One would like to draw a bar cursor with an
7247 angle equal to the one given by the font property XA_ITALIC_ANGLE.
7248 Unfortunately, I didn't find a font yet that has this property set.
7249 --gerd. */
7251 static void
7252 x_draw_bar_cursor (struct window *w, struct glyph_row *row, int width, enum text_cursor_kinds kind)
7254 struct frame *f = XFRAME (w->frame);
7255 struct glyph *cursor_glyph;
7257 /* If cursor is out of bounds, don't draw garbage. This can happen
7258 in mini-buffer windows when switching between echo area glyphs
7259 and mini-buffer. */
7260 cursor_glyph = get_phys_cursor_glyph (w);
7261 if (cursor_glyph == NULL)
7262 return;
7264 /* If on an image, draw like a normal cursor. That's usually better
7265 visible than drawing a bar, esp. if the image is large so that
7266 the bar might not be in the window. */
7267 if (cursor_glyph->type == IMAGE_GLYPH)
7269 struct glyph_row *row;
7270 row = MATRIX_ROW (w->current_matrix, w->phys_cursor.vpos);
7271 draw_phys_cursor_glyph (w, row, DRAW_CURSOR);
7273 else
7275 Display *dpy = FRAME_X_DISPLAY (f);
7276 Window window = FRAME_X_WINDOW (f);
7277 GC gc = FRAME_X_DISPLAY_INFO (f)->scratch_cursor_gc;
7278 unsigned long mask = GCForeground | GCBackground | GCGraphicsExposures;
7279 struct face *face = FACE_FROM_ID (f, cursor_glyph->face_id);
7280 XGCValues xgcv;
7282 /* If the glyph's background equals the color we normally draw
7283 the bars cursor in, the bar cursor in its normal color is
7284 invisible. Use the glyph's foreground color instead in this
7285 case, on the assumption that the glyph's colors are chosen so
7286 that the glyph is legible. */
7287 if (face->background == f->output_data.x->cursor_pixel)
7288 xgcv.background = xgcv.foreground = face->foreground;
7289 else
7290 xgcv.background = xgcv.foreground = f->output_data.x->cursor_pixel;
7291 xgcv.graphics_exposures = 0;
7293 if (gc)
7294 XChangeGC (dpy, gc, mask, &xgcv);
7295 else
7297 gc = XCreateGC (dpy, window, mask, &xgcv);
7298 FRAME_X_DISPLAY_INFO (f)->scratch_cursor_gc = gc;
7301 x_clip_to_row (w, row, TEXT_AREA, gc);
7303 if (kind == BAR_CURSOR)
7305 int x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
7307 if (width < 0)
7308 width = FRAME_CURSOR_WIDTH (f);
7309 width = min (cursor_glyph->pixel_width, width);
7311 w->phys_cursor_width = width;
7313 /* If the character under cursor is R2L, draw the bar cursor
7314 on the right of its glyph, rather than on the left. */
7315 if ((cursor_glyph->resolved_level & 1) != 0)
7316 x += cursor_glyph->pixel_width - width;
7318 XFillRectangle (dpy, window, gc, x,
7319 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y),
7320 width, row->height);
7322 else
7324 int dummy_x, dummy_y, dummy_h;
7326 if (width < 0)
7327 width = row->height;
7329 width = min (row->height, width);
7331 get_phys_cursor_geometry (w, row, cursor_glyph, &dummy_x,
7332 &dummy_y, &dummy_h);
7334 XFillRectangle (dpy, window, gc,
7335 WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x),
7336 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y +
7337 row->height - width),
7338 w->phys_cursor_width, width);
7341 XSetClipMask (dpy, gc, None);
7346 /* RIF: Define cursor CURSOR on frame F. */
7348 static void
7349 x_define_frame_cursor (struct frame *f, Cursor cursor)
7351 if (!f->pointer_invisible
7352 && f->output_data.x->current_cursor != cursor)
7353 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), cursor);
7354 f->output_data.x->current_cursor = cursor;
7358 /* RIF: Clear area on frame F. */
7360 static void
7361 x_clear_frame_area (struct frame *f, int x, int y, int width, int height)
7363 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
7364 x, y, width, height, False);
7365 #ifdef USE_GTK
7366 /* Must queue a redraw, because scroll bars might have been cleared. */
7367 if (FRAME_GTK_WIDGET (f))
7368 gtk_widget_queue_draw (FRAME_GTK_WIDGET (f));
7369 #endif
7373 /* RIF: Draw cursor on window W. */
7375 static void
7376 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)
7378 struct frame *f = XFRAME (WINDOW_FRAME (w));
7380 if (on_p)
7382 w->phys_cursor_type = cursor_type;
7383 w->phys_cursor_on_p = 1;
7385 if (glyph_row->exact_window_width_line_p
7386 && (glyph_row->reversed_p
7387 ? (w->phys_cursor.hpos < 0)
7388 : (w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])))
7390 glyph_row->cursor_in_fringe_p = 1;
7391 draw_fringe_bitmap (w, glyph_row, glyph_row->reversed_p);
7393 else
7395 switch (cursor_type)
7397 case HOLLOW_BOX_CURSOR:
7398 x_draw_hollow_cursor (w, glyph_row);
7399 break;
7401 case FILLED_BOX_CURSOR:
7402 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
7403 break;
7405 case BAR_CURSOR:
7406 x_draw_bar_cursor (w, glyph_row, cursor_width, BAR_CURSOR);
7407 break;
7409 case HBAR_CURSOR:
7410 x_draw_bar_cursor (w, glyph_row, cursor_width, HBAR_CURSOR);
7411 break;
7413 case NO_CURSOR:
7414 w->phys_cursor_width = 0;
7415 break;
7417 default:
7418 abort ();
7422 #ifdef HAVE_X_I18N
7423 if (w == XWINDOW (f->selected_window))
7424 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMPreeditPosition))
7425 xic_set_preeditarea (w, x, y);
7426 #endif
7429 #ifndef XFlush
7430 XFlush (FRAME_X_DISPLAY (f));
7431 #endif
7435 /* Icons. */
7437 /* Make the x-window of frame F use the gnu icon bitmap. */
7440 x_bitmap_icon (struct frame *f, Lisp_Object file)
7442 int bitmap_id;
7444 if (FRAME_X_WINDOW (f) == 0)
7445 return 1;
7447 /* Free up our existing icon bitmap and mask if any. */
7448 if (f->output_data.x->icon_bitmap > 0)
7449 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
7450 f->output_data.x->icon_bitmap = 0;
7452 if (STRINGP (file))
7454 #ifdef USE_GTK
7455 /* Use gtk_window_set_icon_from_file () if available,
7456 It's not restricted to bitmaps */
7457 if (xg_set_icon (f, file))
7458 return 0;
7459 #endif /* USE_GTK */
7460 bitmap_id = x_create_bitmap_from_file (f, file);
7461 x_create_bitmap_mask (f, bitmap_id);
7463 else
7465 /* Create the GNU bitmap and mask if necessary. */
7466 if (FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id < 0)
7468 int rc = -1;
7470 #ifdef USE_GTK
7472 if (xg_set_icon (f, xg_default_icon_file)
7473 || xg_set_icon_from_xpm_data (f, gnu_xpm_bits))
7474 return 0;
7476 #elif defined (HAVE_XPM) && defined (HAVE_X_WINDOWS)
7478 rc = x_create_bitmap_from_xpm_data (f, gnu_xpm_bits);
7479 if (rc != -1)
7480 FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id = rc;
7482 #endif
7484 /* If all else fails, use the (black and white) xbm image. */
7485 if (rc == -1)
7487 rc = x_create_bitmap_from_data (f, gnu_xbm_bits,
7488 gnu_xbm_width, gnu_xbm_height);
7489 if (rc == -1)
7490 return 1;
7492 FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id = rc;
7493 x_create_bitmap_mask (f, FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id);
7497 /* The first time we create the GNU bitmap and mask,
7498 this increments the ref-count one extra time.
7499 As a result, the GNU bitmap and mask are never freed.
7500 That way, we don't have to worry about allocating it again. */
7501 x_reference_bitmap (f, FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id);
7503 bitmap_id = FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id;
7506 x_wm_set_icon_pixmap (f, bitmap_id);
7507 f->output_data.x->icon_bitmap = bitmap_id;
7509 return 0;
7513 /* Make the x-window of frame F use a rectangle with text.
7514 Use ICON_NAME as the text. */
7517 x_text_icon (struct frame *f, const char *icon_name)
7519 if (FRAME_X_WINDOW (f) == 0)
7520 return 1;
7523 XTextProperty text;
7524 text.value = (unsigned char *) icon_name;
7525 text.encoding = XA_STRING;
7526 text.format = 8;
7527 text.nitems = strlen (icon_name);
7528 XSetWMIconName (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f), &text);
7531 if (f->output_data.x->icon_bitmap > 0)
7532 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
7533 f->output_data.x->icon_bitmap = 0;
7534 x_wm_set_icon_pixmap (f, 0);
7536 return 0;
7539 #define X_ERROR_MESSAGE_SIZE 200
7541 /* If non-nil, this should be a string.
7542 It means catch X errors and store the error message in this string.
7544 The reason we use a stack is that x_catch_error/x_uncatch_error can
7545 be called from a signal handler.
7548 struct x_error_message_stack {
7549 char string[X_ERROR_MESSAGE_SIZE];
7550 Display *dpy;
7551 struct x_error_message_stack *prev;
7553 static struct x_error_message_stack *x_error_message;
7555 /* An X error handler which stores the error message in
7556 *x_error_message. This is called from x_error_handler if
7557 x_catch_errors is in effect. */
7559 static void
7560 x_error_catcher (Display *display, XErrorEvent *error)
7562 XGetErrorText (display, error->error_code,
7563 x_error_message->string,
7564 X_ERROR_MESSAGE_SIZE);
7567 /* Begin trapping X errors for display DPY. Actually we trap X errors
7568 for all displays, but DPY should be the display you are actually
7569 operating on.
7571 After calling this function, X protocol errors no longer cause
7572 Emacs to exit; instead, they are recorded in the string
7573 stored in *x_error_message.
7575 Calling x_check_errors signals an Emacs error if an X error has
7576 occurred since the last call to x_catch_errors or x_check_errors.
7578 Calling x_uncatch_errors resumes the normal error handling. */
7580 void x_check_errors (Display *dpy, const char *format);
7582 void
7583 x_catch_errors (Display *dpy)
7585 struct x_error_message_stack *data = xmalloc (sizeof (*data));
7587 /* Make sure any errors from previous requests have been dealt with. */
7588 XSync (dpy, False);
7590 data->dpy = dpy;
7591 data->string[0] = 0;
7592 data->prev = x_error_message;
7593 x_error_message = data;
7596 /* Undo the last x_catch_errors call.
7597 DPY should be the display that was passed to x_catch_errors. */
7599 void
7600 x_uncatch_errors (void)
7602 struct x_error_message_stack *tmp;
7604 BLOCK_INPUT;
7606 /* The display may have been closed before this function is called.
7607 Check if it is still open before calling XSync. */
7608 if (x_display_info_for_display (x_error_message->dpy) != 0)
7609 XSync (x_error_message->dpy, False);
7611 tmp = x_error_message;
7612 x_error_message = x_error_message->prev;
7613 xfree (tmp);
7614 UNBLOCK_INPUT;
7617 /* If any X protocol errors have arrived since the last call to
7618 x_catch_errors or x_check_errors, signal an Emacs error using
7619 sprintf (a buffer, FORMAT, the x error message text) as the text. */
7621 void
7622 x_check_errors (Display *dpy, const char *format)
7624 /* Make sure to catch any errors incurred so far. */
7625 XSync (dpy, False);
7627 if (x_error_message->string[0])
7629 char string[X_ERROR_MESSAGE_SIZE];
7630 memcpy (string, x_error_message->string, X_ERROR_MESSAGE_SIZE);
7631 x_uncatch_errors ();
7632 error (format, string);
7636 /* Nonzero if we had any X protocol errors
7637 since we did x_catch_errors on DPY. */
7640 x_had_errors_p (Display *dpy)
7642 /* Make sure to catch any errors incurred so far. */
7643 XSync (dpy, False);
7645 return x_error_message->string[0] != 0;
7648 /* Forget about any errors we have had, since we did x_catch_errors on DPY. */
7650 void
7651 x_clear_errors (Display *dpy)
7653 x_error_message->string[0] = 0;
7656 #if 0 /* See comment in unwind_to_catch why calling this is a bad
7657 * idea. --lorentey */
7658 /* Close off all unclosed x_catch_errors calls. */
7660 void
7661 x_fully_uncatch_errors (void)
7663 while (x_error_message)
7664 x_uncatch_errors ();
7666 #endif
7668 /* Nonzero if x_catch_errors has been done and not yet canceled. */
7671 x_catching_errors (void)
7673 return x_error_message != 0;
7676 #if 0
7677 static unsigned int x_wire_count;
7678 x_trace_wire (void)
7680 fprintf (stderr, "Lib call: %d\n", ++x_wire_count);
7682 #endif /* ! 0 */
7685 /* Handle SIGPIPE, which can happen when the connection to a server
7686 simply goes away. SIGPIPE is handled by x_connection_signal.
7687 Don't need to do anything, because the write which caused the
7688 SIGPIPE will fail, causing Xlib to invoke the X IO error handler,
7689 which will do the appropriate cleanup for us. */
7691 static SIGTYPE
7692 x_connection_signal (int signalnum) /* If we don't have an argument, */
7693 /* some compilers complain in signal calls. */
7695 #ifdef USG
7696 /* USG systems forget handlers when they are used;
7697 must reestablish each time */
7698 signal (signalnum, x_connection_signal);
7699 #endif /* USG */
7703 /************************************************************************
7704 Handling X errors
7705 ************************************************************************/
7707 /* Error message passed to x_connection_closed. */
7709 static char *error_msg;
7711 /* Function installed as fatal_error_signal_hook in
7712 x_connection_closed. Print the X error message, and exit normally,
7713 instead of dumping core when XtCloseDisplay fails. */
7715 static void
7716 x_fatal_error_signal (void)
7718 fprintf (stderr, "%s\n", error_msg);
7719 exit (70);
7722 /* Handle the loss of connection to display DPY. ERROR_MESSAGE is
7723 the text of an error message that lead to the connection loss. */
7725 static SIGTYPE
7726 x_connection_closed (Display *dpy, const char *error_message)
7728 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
7729 Lisp_Object frame, tail;
7730 int index = SPECPDL_INDEX ();
7732 error_msg = (char *) alloca (strlen (error_message) + 1);
7733 strcpy (error_msg, error_message);
7734 handling_signal = 0;
7736 /* Prevent being called recursively because of an error condition
7737 below. Otherwise, we might end up with printing ``can't find per
7738 display information'' in the recursive call instead of printing
7739 the original message here. */
7740 x_catch_errors (dpy);
7742 /* Inhibit redisplay while frames are being deleted. */
7743 specbind (Qinhibit_redisplay, Qt);
7745 if (dpyinfo)
7747 /* Protect display from being closed when we delete the last
7748 frame on it. */
7749 dpyinfo->reference_count++;
7750 dpyinfo->terminal->reference_count++;
7753 /* First delete frames whose mini-buffers are on frames
7754 that are on the dead display. */
7755 FOR_EACH_FRAME (tail, frame)
7757 Lisp_Object minibuf_frame;
7758 minibuf_frame
7759 = WINDOW_FRAME (XWINDOW (FRAME_MINIBUF_WINDOW (XFRAME (frame))));
7760 if (FRAME_X_P (XFRAME (frame))
7761 && FRAME_X_P (XFRAME (minibuf_frame))
7762 && ! EQ (frame, minibuf_frame)
7763 && FRAME_X_DISPLAY_INFO (XFRAME (minibuf_frame)) == dpyinfo)
7764 delete_frame (frame, Qnoelisp);
7767 /* Now delete all remaining frames on the dead display.
7768 We are now sure none of these is used as the mini-buffer
7769 for another frame that we need to delete. */
7770 FOR_EACH_FRAME (tail, frame)
7771 if (FRAME_X_P (XFRAME (frame))
7772 && FRAME_X_DISPLAY_INFO (XFRAME (frame)) == dpyinfo)
7774 /* Set this to t so that delete_frame won't get confused
7775 trying to find a replacement. */
7776 FRAME_KBOARD (XFRAME (frame))->Vdefault_minibuffer_frame = Qt;
7777 delete_frame (frame, Qnoelisp);
7780 /* If DPYINFO is null, this means we didn't open the display in the
7781 first place, so don't try to close it. */
7782 if (dpyinfo)
7784 #ifdef USE_X_TOOLKIT
7785 /* We have to close the display to inform Xt that it doesn't
7786 exist anymore. If we don't, Xt will continue to wait for
7787 events from the display. As a consequence, a sequence of
7789 M-x make-frame-on-display RET :1 RET
7790 ...kill the new frame, so that we get an IO error...
7791 M-x make-frame-on-display RET :1 RET
7793 will indefinitely wait in Xt for events for display `:1',
7794 opened in the first call to make-frame-on-display.
7796 Closing the display is reported to lead to a bus error on
7797 OpenWindows in certain situations. I suspect that is a bug
7798 in OpenWindows. I don't know how to circumvent it here. */
7799 fatal_error_signal_hook = x_fatal_error_signal;
7800 XtCloseDisplay (dpy);
7801 fatal_error_signal_hook = NULL;
7802 #endif /* USE_X_TOOLKIT */
7804 #ifdef USE_GTK
7805 /* A long-standing GTK bug prevents proper disconnect handling
7806 (https://bugzilla.gnome.org/show_bug.cgi?id=85715). Once,
7807 the resulting Glib error message loop filled a user's disk.
7808 To avoid this, kill Emacs unconditionally on disconnect. */
7809 shut_down_emacs (0, 0, Qnil);
7810 fprintf (stderr, "%s\n\
7811 When compiled with GTK, Emacs cannot recover from X disconnects.\n\
7812 This is a GTK bug: https://bugzilla.gnome.org/show_bug.cgi?id=85715\n\
7813 For details, see etc/PROBLEMS.\n",
7814 error_msg);
7815 abort ();
7816 #endif /* USE_GTK */
7818 /* Indicate that this display is dead. */
7819 dpyinfo->display = 0;
7821 dpyinfo->reference_count--;
7822 dpyinfo->terminal->reference_count--;
7823 if (dpyinfo->reference_count != 0)
7824 /* We have just closed all frames on this display. */
7825 abort ();
7828 Lisp_Object tmp;
7829 XSETTERMINAL (tmp, dpyinfo->terminal);
7830 Fdelete_terminal (tmp, Qnoelisp);
7834 x_uncatch_errors ();
7836 if (terminal_list == 0)
7838 fprintf (stderr, "%s\n", error_msg);
7839 Fkill_emacs (make_number (70));
7840 /* NOTREACHED */
7843 /* Ordinary stack unwind doesn't deal with these. */
7844 #ifdef SIGIO
7845 sigunblock (sigmask (SIGIO));
7846 #endif
7847 sigunblock (sigmask (SIGALRM));
7848 TOTALLY_UNBLOCK_INPUT;
7850 unbind_to (index, Qnil);
7851 clear_waiting_for_input ();
7852 /* Here, we absolutely have to use a non-local exit (e.g. signal, throw,
7853 longjmp), because returning from this function would get us back into
7854 Xlib's code which will directly call `exit'. */
7855 error ("%s", error_msg);
7858 /* We specifically use it before defining it, so that gcc doesn't inline it,
7859 otherwise gdb doesn't know how to properly put a breakpoint on it. */
7860 static void x_error_quitter (Display *, XErrorEvent *);
7862 /* This is the first-level handler for X protocol errors.
7863 It calls x_error_quitter or x_error_catcher. */
7865 static int
7866 x_error_handler (Display *display, XErrorEvent *error)
7868 if (x_error_message)
7869 x_error_catcher (display, error);
7870 else
7871 x_error_quitter (display, error);
7872 return 0;
7875 /* This is the usual handler for X protocol errors.
7876 It kills all frames on the display that we got the error for.
7877 If that was the only one, it prints an error message and kills Emacs. */
7879 /* .gdbinit puts a breakpoint here, so make sure it is not inlined. */
7881 /* On older GCC versions, just putting x_error_quitter
7882 after x_error_handler prevents inlining into the former. */
7884 static void NO_INLINE
7885 x_error_quitter (Display *display, XErrorEvent *error)
7887 char buf[256], buf1[356];
7889 /* Ignore BadName errors. They can happen because of fonts
7890 or colors that are not defined. */
7892 if (error->error_code == BadName)
7893 return;
7895 /* Note that there is no real way portable across R3/R4 to get the
7896 original error handler. */
7898 XGetErrorText (display, error->error_code, buf, sizeof (buf));
7899 sprintf (buf1, "X protocol error: %s on protocol request %d",
7900 buf, error->request_code);
7901 x_connection_closed (display, buf1);
7905 /* This is the handler for X IO errors, always.
7906 It kills all frames on the display that we lost touch with.
7907 If that was the only one, it prints an error message and kills Emacs. */
7909 static int
7910 x_io_error_quitter (Display *display)
7912 char buf[256];
7914 sprintf (buf, "Connection lost to X server `%s'", DisplayString (display));
7915 x_connection_closed (display, buf);
7916 return 0;
7919 /* Changing the font of the frame. */
7921 /* Give frame F the font FONT-OBJECT as its default font. The return
7922 value is FONT-OBJECT. FONTSET is an ID of the fontset for the
7923 frame. If it is negative, generate a new fontset from
7924 FONT-OBJECT. */
7926 Lisp_Object
7927 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
7929 struct font *font = XFONT_OBJECT (font_object);
7931 if (fontset < 0)
7932 fontset = fontset_from_font (font_object);
7933 FRAME_FONTSET (f) = fontset;
7934 if (FRAME_FONT (f) == font)
7935 /* This font is already set in frame F. There's nothing more to
7936 do. */
7937 return font_object;
7939 FRAME_FONT (f) = font;
7940 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
7941 FRAME_COLUMN_WIDTH (f) = font->average_width;
7942 FRAME_SPACE_WIDTH (f) = font->space_width;
7943 FRAME_LINE_HEIGHT (f) = FONT_HEIGHT (font);
7945 compute_fringe_widths (f, 1);
7947 /* Compute the scroll bar width in character columns. */
7948 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
7950 int wid = FRAME_COLUMN_WIDTH (f);
7951 FRAME_CONFIG_SCROLL_BAR_COLS (f)
7952 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid-1) / wid;
7954 else
7956 int wid = FRAME_COLUMN_WIDTH (f);
7957 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
7960 if (FRAME_X_WINDOW (f) != 0)
7962 /* Don't change the size of a tip frame; there's no point in
7963 doing it because it's done in Fx_show_tip, and it leads to
7964 problems because the tip frame has no widget. */
7965 if (NILP (tip_frame) || XFRAME (tip_frame) != f)
7966 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
7969 #ifdef HAVE_X_I18N
7970 if (FRAME_XIC (f)
7971 && (FRAME_XIC_STYLE (f) & (XIMPreeditPosition | XIMStatusArea)))
7973 BLOCK_INPUT;
7974 xic_set_xfontset (f, SDATA (fontset_ascii (fontset)));
7975 UNBLOCK_INPUT;
7977 #endif
7979 return font_object;
7983 /***********************************************************************
7984 X Input Methods
7985 ***********************************************************************/
7987 #ifdef HAVE_X_I18N
7989 #ifdef HAVE_X11R6
7991 /* XIM destroy callback function, which is called whenever the
7992 connection to input method XIM dies. CLIENT_DATA contains a
7993 pointer to the x_display_info structure corresponding to XIM. */
7995 static void
7996 xim_destroy_callback (XIM xim, XPointer client_data, XPointer call_data)
7998 struct x_display_info *dpyinfo = (struct x_display_info *) client_data;
7999 Lisp_Object frame, tail;
8001 BLOCK_INPUT;
8003 /* No need to call XDestroyIC.. */
8004 FOR_EACH_FRAME (tail, frame)
8006 struct frame *f = XFRAME (frame);
8007 if (FRAME_X_P (f) && FRAME_X_DISPLAY_INFO (f) == dpyinfo)
8009 FRAME_XIC (f) = NULL;
8010 xic_free_xfontset (f);
8014 /* No need to call XCloseIM. */
8015 dpyinfo->xim = NULL;
8016 XFree (dpyinfo->xim_styles);
8017 UNBLOCK_INPUT;
8020 #endif /* HAVE_X11R6 */
8022 #ifdef HAVE_X11R6
8023 /* This isn't prototyped in OSF 5.0 or 5.1a. */
8024 extern char *XSetIMValues (XIM, ...);
8025 #endif
8027 /* Open the connection to the XIM server on display DPYINFO.
8028 RESOURCE_NAME is the resource name Emacs uses. */
8030 static void
8031 xim_open_dpy (struct x_display_info *dpyinfo, char *resource_name)
8033 XIM xim;
8035 #ifdef HAVE_XIM
8036 if (use_xim)
8038 if (dpyinfo->xim)
8039 XCloseIM (dpyinfo->xim);
8040 xim = XOpenIM (dpyinfo->display, dpyinfo->xrdb, resource_name,
8041 emacs_class);
8042 dpyinfo->xim = xim;
8044 if (xim)
8046 #ifdef HAVE_X11R6
8047 XIMCallback destroy;
8048 #endif
8050 /* Get supported styles and XIM values. */
8051 XGetIMValues (xim, XNQueryInputStyle, &dpyinfo->xim_styles, NULL);
8053 #ifdef HAVE_X11R6
8054 destroy.callback = xim_destroy_callback;
8055 destroy.client_data = (XPointer)dpyinfo;
8056 XSetIMValues (xim, XNDestroyCallback, &destroy, NULL);
8057 #endif
8061 else
8062 #endif /* HAVE_XIM */
8063 dpyinfo->xim = NULL;
8067 #ifdef HAVE_X11R6_XIM
8069 /* XIM instantiate callback function, which is called whenever an XIM
8070 server is available. DISPLAY is the display of the XIM.
8071 CLIENT_DATA contains a pointer to an xim_inst_t structure created
8072 when the callback was registered. */
8074 static void
8075 xim_instantiate_callback (Display *display, XPointer client_data, XPointer call_data)
8077 struct xim_inst_t *xim_inst = (struct xim_inst_t *) client_data;
8078 struct x_display_info *dpyinfo = xim_inst->dpyinfo;
8080 /* We don't support multiple XIM connections. */
8081 if (dpyinfo->xim)
8082 return;
8084 xim_open_dpy (dpyinfo, xim_inst->resource_name);
8086 /* Create XIC for the existing frames on the same display, as long
8087 as they have no XIC. */
8088 if (dpyinfo->xim && dpyinfo->reference_count > 0)
8090 Lisp_Object tail, frame;
8092 BLOCK_INPUT;
8093 FOR_EACH_FRAME (tail, frame)
8095 struct frame *f = XFRAME (frame);
8097 if (FRAME_X_P (f)
8098 && FRAME_X_DISPLAY_INFO (f) == xim_inst->dpyinfo)
8099 if (FRAME_XIC (f) == NULL)
8101 create_frame_xic (f);
8102 if (FRAME_XIC_STYLE (f) & XIMStatusArea)
8103 xic_set_statusarea (f);
8104 if (FRAME_XIC_STYLE (f) & XIMPreeditPosition)
8106 struct window *w = XWINDOW (f->selected_window);
8107 xic_set_preeditarea (w, w->cursor.x, w->cursor.y);
8112 UNBLOCK_INPUT;
8116 #endif /* HAVE_X11R6_XIM */
8119 /* Open a connection to the XIM server on display DPYINFO.
8120 RESOURCE_NAME is the resource name for Emacs. On X11R5, open the
8121 connection only at the first time. On X11R6, open the connection
8122 in the XIM instantiate callback function. */
8124 static void
8125 xim_initialize (struct x_display_info *dpyinfo, char *resource_name)
8127 dpyinfo->xim = NULL;
8128 #ifdef HAVE_XIM
8129 if (use_xim)
8131 #ifdef HAVE_X11R6_XIM
8132 struct xim_inst_t *xim_inst;
8133 int len;
8135 xim_inst = (struct xim_inst_t *) xmalloc (sizeof (struct xim_inst_t));
8136 dpyinfo->xim_callback_data = xim_inst;
8137 xim_inst->dpyinfo = dpyinfo;
8138 len = strlen (resource_name);
8139 xim_inst->resource_name = (char *) xmalloc (len + 1);
8140 memcpy (xim_inst->resource_name, resource_name, len + 1);
8141 XRegisterIMInstantiateCallback (dpyinfo->display, dpyinfo->xrdb,
8142 resource_name, emacs_class,
8143 xim_instantiate_callback,
8144 /* This is XPointer in XFree86
8145 but (XPointer *) on Tru64, at
8146 least, hence the configure test. */
8147 (XRegisterIMInstantiateCallback_arg6) xim_inst);
8148 #else /* not HAVE_X11R6_XIM */
8149 xim_open_dpy (dpyinfo, resource_name);
8150 #endif /* not HAVE_X11R6_XIM */
8152 #endif /* HAVE_XIM */
8156 /* Close the connection to the XIM server on display DPYINFO. */
8158 static void
8159 xim_close_dpy (struct x_display_info *dpyinfo)
8161 #ifdef HAVE_XIM
8162 if (use_xim)
8164 #ifdef HAVE_X11R6_XIM
8165 if (dpyinfo->display)
8166 XUnregisterIMInstantiateCallback (dpyinfo->display, dpyinfo->xrdb,
8167 NULL, emacs_class,
8168 xim_instantiate_callback, NULL);
8169 xfree (dpyinfo->xim_callback_data->resource_name);
8170 xfree (dpyinfo->xim_callback_data);
8171 #endif /* HAVE_X11R6_XIM */
8172 if (dpyinfo->display)
8173 XCloseIM (dpyinfo->xim);
8174 dpyinfo->xim = NULL;
8175 XFree (dpyinfo->xim_styles);
8177 #endif /* HAVE_XIM */
8180 #endif /* not HAVE_X11R6_XIM */
8184 /* Calculate the absolute position in frame F
8185 from its current recorded position values and gravity. */
8187 void
8188 x_calc_absolute_position (struct frame *f)
8190 int flags = f->size_hint_flags;
8192 /* We have nothing to do if the current position
8193 is already for the top-left corner. */
8194 if (! ((flags & XNegative) || (flags & YNegative)))
8195 return;
8197 /* Treat negative positions as relative to the leftmost bottommost
8198 position that fits on the screen. */
8199 if (flags & XNegative)
8200 f->left_pos = x_display_pixel_width (FRAME_X_DISPLAY_INFO (f))
8201 - FRAME_PIXEL_WIDTH (f) + f->left_pos;
8204 int height = FRAME_PIXEL_HEIGHT (f);
8206 #if defined USE_X_TOOLKIT && defined USE_MOTIF
8207 /* Something is fishy here. When using Motif, starting Emacs with
8208 `-g -0-0', the frame appears too low by a few pixels.
8210 This seems to be so because initially, while Emacs is starting,
8211 the column widget's height and the frame's pixel height are
8212 different. The column widget's height is the right one. In
8213 later invocations, when Emacs is up, the frame's pixel height
8214 is right, though.
8216 It's not obvious where the initial small difference comes from.
8217 2000-12-01, gerd. */
8219 XtVaGetValues (f->output_data.x->column_widget, XtNheight, &height, NULL);
8220 #endif
8222 if (flags & YNegative)
8223 f->top_pos = x_display_pixel_height (FRAME_X_DISPLAY_INFO (f))
8224 - height + f->top_pos;
8227 /* The left_pos and top_pos
8228 are now relative to the top and left screen edges,
8229 so the flags should correspond. */
8230 f->size_hint_flags &= ~ (XNegative | YNegative);
8233 /* CHANGE_GRAVITY is 1 when calling from Fset_frame_position,
8234 to really change the position, and 0 when calling from
8235 x_make_frame_visible (in that case, XOFF and YOFF are the current
8236 position values). It is -1 when calling from x_set_frame_parameters,
8237 which means, do adjust for borders but don't change the gravity. */
8239 void
8240 x_set_offset (struct frame *f, register int xoff, register int yoff, int change_gravity)
8242 int modified_top, modified_left;
8244 if (change_gravity > 0)
8246 FRAME_X_OUTPUT (f)->left_before_move = f->left_pos;
8247 FRAME_X_OUTPUT (f)->top_before_move = f->top_pos;
8249 f->top_pos = yoff;
8250 f->left_pos = xoff;
8251 f->size_hint_flags &= ~ (XNegative | YNegative);
8252 if (xoff < 0)
8253 f->size_hint_flags |= XNegative;
8254 if (yoff < 0)
8255 f->size_hint_flags |= YNegative;
8256 f->win_gravity = NorthWestGravity;
8258 x_calc_absolute_position (f);
8260 BLOCK_INPUT;
8261 x_wm_set_size_hint (f, (long) 0, 0);
8263 modified_left = f->left_pos;
8264 modified_top = f->top_pos;
8266 if (change_gravity != 0 && FRAME_X_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A)
8268 /* Some WMs (twm, wmaker at least) has an offset that is smaller
8269 than the WM decorations. So we use the calculated offset instead
8270 of the WM decoration sizes here (x/y_pixels_outer_diff). */
8271 modified_left += FRAME_X_OUTPUT (f)->move_offset_left;
8272 modified_top += FRAME_X_OUTPUT (f)->move_offset_top;
8275 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8276 modified_left, modified_top);
8278 x_sync_with_move (f, f->left_pos, f->top_pos,
8279 FRAME_X_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN
8280 ? 1 : 0);
8282 /* change_gravity is non-zero when this function is called from Lisp to
8283 programmatically move a frame. In that case, we call
8284 x_check_expected_move to discover if we have a "Type A" or "Type B"
8285 window manager, and, for a "Type A" window manager, adjust the position
8286 of the frame.
8288 We call x_check_expected_move if a programmatic move occurred, and
8289 either the window manager type (A/B) is unknown or it is Type A but we
8290 need to compute the top/left offset adjustment for this frame. */
8292 if (change_gravity != 0 &&
8293 (FRAME_X_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN
8294 || (FRAME_X_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A
8295 && (FRAME_X_OUTPUT (f)->move_offset_left == 0
8296 && FRAME_X_OUTPUT (f)->move_offset_top == 0))))
8297 x_check_expected_move (f, modified_left, modified_top);
8299 UNBLOCK_INPUT;
8302 /* Return non-zero if _NET_SUPPORTING_WM_CHECK window exists and _NET_SUPPORTED
8303 on the root window for frame F contains ATOMNAME.
8304 This is how a WM check shall be done according to the Window Manager
8305 Specification/Extended Window Manager Hints at
8306 http://freedesktop.org/wiki/Specifications/wm-spec. */
8308 static int
8309 wm_supports (struct frame *f, Atom want_atom)
8311 Atom actual_type;
8312 unsigned long actual_size, bytes_remaining;
8313 int i, rc, actual_format;
8314 Window wmcheck_window;
8315 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8316 Window target_window = dpyinfo->root_window;
8317 long max_len = 65536;
8318 Display *dpy = FRAME_X_DISPLAY (f);
8319 unsigned char *tmp_data = NULL;
8320 Atom target_type = XA_WINDOW;
8322 BLOCK_INPUT;
8324 x_catch_errors (dpy);
8325 rc = XGetWindowProperty (dpy, target_window,
8326 dpyinfo->Xatom_net_supporting_wm_check,
8327 0, max_len, False, target_type,
8328 &actual_type, &actual_format, &actual_size,
8329 &bytes_remaining, &tmp_data);
8331 if (rc != Success || actual_type != XA_WINDOW || x_had_errors_p (dpy))
8333 if (tmp_data) XFree (tmp_data);
8334 x_uncatch_errors ();
8335 UNBLOCK_INPUT;
8336 return 0;
8339 wmcheck_window = *(Window *) tmp_data;
8340 XFree (tmp_data);
8342 /* Check if window exists. */
8343 XSelectInput (dpy, wmcheck_window, StructureNotifyMask);
8344 x_sync (f);
8345 if (x_had_errors_p (dpy))
8347 x_uncatch_errors ();
8348 UNBLOCK_INPUT;
8349 return 0;
8352 if (dpyinfo->net_supported_window != wmcheck_window)
8354 /* Window changed, reload atoms */
8355 if (dpyinfo->net_supported_atoms != NULL)
8356 XFree (dpyinfo->net_supported_atoms);
8357 dpyinfo->net_supported_atoms = NULL;
8358 dpyinfo->nr_net_supported_atoms = 0;
8359 dpyinfo->net_supported_window = 0;
8361 target_type = XA_ATOM;
8362 tmp_data = NULL;
8363 rc = XGetWindowProperty (dpy, target_window,
8364 dpyinfo->Xatom_net_supported,
8365 0, max_len, False, target_type,
8366 &actual_type, &actual_format, &actual_size,
8367 &bytes_remaining, &tmp_data);
8369 if (rc != Success || actual_type != XA_ATOM || x_had_errors_p (dpy))
8371 if (tmp_data) XFree (tmp_data);
8372 x_uncatch_errors ();
8373 UNBLOCK_INPUT;
8374 return 0;
8377 dpyinfo->net_supported_atoms = (Atom *)tmp_data;
8378 dpyinfo->nr_net_supported_atoms = actual_size;
8379 dpyinfo->net_supported_window = wmcheck_window;
8382 rc = 0;
8384 for (i = 0; rc == 0 && i < dpyinfo->nr_net_supported_atoms; ++i)
8385 rc = dpyinfo->net_supported_atoms[i] == want_atom;
8387 x_uncatch_errors ();
8388 UNBLOCK_INPUT;
8390 return rc;
8393 static void
8394 set_wm_state (Lisp_Object frame, int add, Atom atom, Atom value)
8396 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (XFRAME (frame));
8398 x_send_client_event (frame, make_number (0), frame,
8399 dpyinfo->Xatom_net_wm_state,
8400 make_number (32),
8401 /* 1 = add, 0 = remove */
8402 Fcons
8403 (make_number (add ? 1 : 0),
8404 Fcons
8405 (make_fixnum_or_float (atom),
8406 value != 0
8407 ? Fcons (make_fixnum_or_float (value), Qnil)
8408 : Qnil)));
8411 void
8412 x_set_sticky (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
8414 Lisp_Object frame;
8415 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8417 XSETFRAME (frame, f);
8419 set_wm_state (frame, NILP (new_value) ? 0 : 1,
8420 dpyinfo->Xatom_net_wm_state_sticky, None);
8423 /* Return the current _NET_WM_STATE.
8424 SIZE_STATE is set to one of the FULLSCREEN_* values.
8425 STICKY is set to 1 if the sticky state is set, 0 if not. */
8427 static void
8428 get_current_wm_state (struct frame *f,
8429 Window window,
8430 int *size_state,
8431 int *sticky)
8433 Atom actual_type;
8434 unsigned long actual_size, bytes_remaining;
8435 int i, rc, actual_format;
8436 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8437 long max_len = 65536;
8438 Display *dpy = FRAME_X_DISPLAY (f);
8439 unsigned char *tmp_data = NULL;
8440 Atom target_type = XA_ATOM;
8442 *sticky = 0;
8443 *size_state = FULLSCREEN_NONE;
8445 BLOCK_INPUT;
8446 x_catch_errors (dpy);
8447 rc = XGetWindowProperty (dpy, window, dpyinfo->Xatom_net_wm_state,
8448 0, max_len, False, target_type,
8449 &actual_type, &actual_format, &actual_size,
8450 &bytes_remaining, &tmp_data);
8452 if (rc != Success || actual_type != target_type || x_had_errors_p (dpy))
8454 if (tmp_data) XFree (tmp_data);
8455 x_uncatch_errors ();
8456 UNBLOCK_INPUT;
8457 return;
8460 x_uncatch_errors ();
8462 for (i = 0; i < actual_size; ++i)
8464 Atom a = ((Atom*)tmp_data)[i];
8465 if (a == dpyinfo->Xatom_net_wm_state_maximized_horz)
8467 if (*size_state == FULLSCREEN_HEIGHT)
8468 *size_state = FULLSCREEN_MAXIMIZED;
8469 else
8470 *size_state = FULLSCREEN_WIDTH;
8472 else if (a == dpyinfo->Xatom_net_wm_state_maximized_vert)
8474 if (*size_state == FULLSCREEN_WIDTH)
8475 *size_state = FULLSCREEN_MAXIMIZED;
8476 else
8477 *size_state = FULLSCREEN_HEIGHT;
8479 else if (a == dpyinfo->Xatom_net_wm_state_fullscreen)
8480 *size_state = FULLSCREEN_BOTH;
8481 else if (a == dpyinfo->Xatom_net_wm_state_sticky)
8482 *sticky = 1;
8485 if (tmp_data) XFree (tmp_data);
8486 UNBLOCK_INPUT;
8489 /* Do fullscreen as specified in extended window manager hints */
8491 static int
8492 do_ewmh_fullscreen (struct frame *f)
8494 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8495 int have_net_atom = wm_supports (f, dpyinfo->Xatom_net_wm_state);
8496 int cur, dummy;
8498 get_current_wm_state (f, FRAME_OUTER_WINDOW (f), &cur, &dummy);
8500 /* Some window managers don't say they support _NET_WM_STATE, but they do say
8501 they support _NET_WM_STATE_FULLSCREEN. Try that also. */
8502 if (!have_net_atom)
8503 have_net_atom = wm_supports (f, dpyinfo->Xatom_net_wm_state_fullscreen);
8505 if (have_net_atom && cur != f->want_fullscreen)
8507 Lisp_Object frame;
8509 XSETFRAME (frame, f);
8511 /* Keep number of calls to set_wm_state as low as possible.
8512 Some window managers, or possible Gtk+, hangs when too many
8513 are sent at once. */
8514 switch (f->want_fullscreen)
8516 case FULLSCREEN_BOTH:
8517 if (cur == FULLSCREEN_WIDTH || cur == FULLSCREEN_MAXIMIZED
8518 || cur == FULLSCREEN_HEIGHT)
8519 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_maximized_horz,
8520 dpyinfo->Xatom_net_wm_state_maximized_vert);
8521 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_fullscreen, None);
8522 break;
8523 case FULLSCREEN_WIDTH:
8524 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_HEIGHT
8525 || cur == FULLSCREEN_MAXIMIZED)
8526 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen,
8527 dpyinfo->Xatom_net_wm_state_maximized_vert);
8528 if (cur != FULLSCREEN_MAXIMIZED)
8529 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_maximized_horz, None);
8530 break;
8531 case FULLSCREEN_HEIGHT:
8532 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_WIDTH
8533 || cur == FULLSCREEN_MAXIMIZED)
8534 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen,
8535 dpyinfo->Xatom_net_wm_state_maximized_horz);
8536 if (cur != FULLSCREEN_MAXIMIZED)
8537 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_maximized_vert, None);
8538 break;
8539 case FULLSCREEN_MAXIMIZED:
8540 if (cur == FULLSCREEN_BOTH)
8541 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen, None);
8542 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_maximized_horz,
8543 dpyinfo->Xatom_net_wm_state_maximized_vert);
8544 break;
8545 case FULLSCREEN_NONE:
8546 if (cur == FULLSCREEN_BOTH)
8547 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen, None);
8548 else
8549 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_maximized_horz,
8550 dpyinfo->Xatom_net_wm_state_maximized_vert);
8553 f->want_fullscreen = FULLSCREEN_NONE;
8557 return have_net_atom;
8560 static void
8561 XTfullscreen_hook (FRAME_PTR f)
8563 if (f->async_visible)
8565 BLOCK_INPUT;
8566 x_check_fullscreen (f);
8567 x_sync (f);
8568 UNBLOCK_INPUT;
8573 static void
8574 x_handle_net_wm_state (struct frame *f, XPropertyEvent *event)
8576 int value = FULLSCREEN_NONE;
8577 Lisp_Object lval;
8578 int sticky = 0;
8580 get_current_wm_state (f, event->window, &value, &sticky);
8581 lval = Qnil;
8582 switch (value)
8584 case FULLSCREEN_WIDTH:
8585 lval = Qfullwidth;
8586 break;
8587 case FULLSCREEN_HEIGHT:
8588 lval = Qfullheight;
8589 break;
8590 case FULLSCREEN_BOTH:
8591 lval = Qfullboth;
8592 break;
8593 case FULLSCREEN_MAXIMIZED:
8594 lval = Qmaximized;
8595 break;
8598 store_frame_param (f, Qfullscreen, lval);
8599 store_frame_param (f, Qsticky, sticky ? Qt : Qnil);
8602 /* Check if we need to resize the frame due to a fullscreen request.
8603 If so needed, resize the frame. */
8604 static void
8605 x_check_fullscreen (struct frame *f)
8607 if (do_ewmh_fullscreen (f))
8608 return;
8610 if (f->output_data.x->parent_desc != FRAME_X_DISPLAY_INFO (f)->root_window)
8611 return; /* Only fullscreen without WM or with EWM hints (above). */
8613 /* Setting fullscreen to nil doesn't do anything. We could save the
8614 last non-fullscreen size and restore it, but it seems like a
8615 lot of work for this unusual case (no window manager running). */
8617 if (f->want_fullscreen != FULLSCREEN_NONE)
8619 int width = FRAME_PIXEL_WIDTH (f), height = FRAME_PIXEL_HEIGHT (f);
8620 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8622 switch (f->want_fullscreen)
8624 /* No difference between these two when there is no WM */
8625 case FULLSCREEN_BOTH:
8626 case FULLSCREEN_MAXIMIZED:
8627 width = x_display_pixel_width (dpyinfo);
8628 height = x_display_pixel_height (dpyinfo);
8629 break;
8630 case FULLSCREEN_WIDTH:
8631 width = x_display_pixel_width (dpyinfo);
8632 break;
8633 case FULLSCREEN_HEIGHT:
8634 height = x_display_pixel_height (dpyinfo);
8637 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8638 width, height);
8642 /* This function is called by x_set_offset to determine whether the window
8643 manager interfered with the positioning of the frame. Type A window
8644 managers position the surrounding window manager decorations a small
8645 amount above and left of the user-supplied position. Type B window
8646 managers position the surrounding window manager decorations at the
8647 user-specified position. If we detect a Type A window manager, we
8648 compensate by moving the window right and down by the proper amount. */
8650 static void
8651 x_check_expected_move (struct frame *f, int expected_left, int expected_top)
8653 int current_left = 0, current_top = 0;
8655 /* x_real_positions returns the left and top offsets of the outermost
8656 window manager window around the frame. */
8658 x_real_positions (f, &current_left, &current_top);
8660 if (current_left != expected_left || current_top != expected_top)
8662 /* It's a "Type A" window manager. */
8664 int adjusted_left;
8665 int adjusted_top;
8667 FRAME_X_DISPLAY_INFO (f)->wm_type = X_WMTYPE_A;
8668 FRAME_X_OUTPUT (f)->move_offset_left = expected_left - current_left;
8669 FRAME_X_OUTPUT (f)->move_offset_top = expected_top - current_top;
8671 /* Now fix the mispositioned frame's location. */
8673 adjusted_left = expected_left + FRAME_X_OUTPUT (f)->move_offset_left;
8674 adjusted_top = expected_top + FRAME_X_OUTPUT (f)->move_offset_top;
8676 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8677 adjusted_left, adjusted_top);
8679 x_sync_with_move (f, expected_left, expected_top, 0);
8681 else
8682 /* It's a "Type B" window manager. We don't have to adjust the
8683 frame's position. */
8685 FRAME_X_DISPLAY_INFO (f)->wm_type = X_WMTYPE_B;
8689 /* Wait for XGetGeometry to return up-to-date position information for a
8690 recently-moved frame. Call this immediately after calling XMoveWindow.
8691 If FUZZY is non-zero, then LEFT and TOP are just estimates of where the
8692 frame has been moved to, so we use a fuzzy position comparison instead
8693 of an exact comparison. */
8695 static void
8696 x_sync_with_move (struct frame *f, int left, int top, int fuzzy)
8698 int count = 0;
8700 while (count++ < 50)
8702 int current_left = 0, current_top = 0;
8704 /* In theory, this call to XSync only needs to happen once, but in
8705 practice, it doesn't seem to work, hence the need for the surrounding
8706 loop. */
8708 XSync (FRAME_X_DISPLAY (f), False);
8709 x_real_positions (f, &current_left, &current_top);
8711 if (fuzzy)
8713 /* The left fuzz-factor is 10 pixels. The top fuzz-factor is 40
8714 pixels. */
8716 if (eabs (current_left - left) <= 10
8717 && eabs (current_top - top) <= 40)
8718 return;
8720 else if (current_left == left && current_top == top)
8721 return;
8724 /* As a last resort, just wait 0.5 seconds and hope that XGetGeometry
8725 will then return up-to-date position info. */
8727 wait_reading_process_output (0, 500000, 0, 0, Qnil, NULL, 0);
8731 /* Wait for an event on frame F matching EVENTTYPE. */
8732 void
8733 x_wait_for_event (struct frame *f, int eventtype)
8735 int level = interrupt_input_blocked;
8737 SELECT_TYPE fds;
8738 EMACS_TIME tmo, tmo_at, time_now;
8739 int fd = ConnectionNumber (FRAME_X_DISPLAY (f));
8741 pending_event_wait.f = f;
8742 pending_event_wait.eventtype = eventtype;
8744 /* Set timeout to 0.1 second. Hopefully not noticable.
8745 Maybe it should be configurable. */
8746 EMACS_SET_SECS_USECS (tmo, 0, 100000);
8747 EMACS_GET_TIME (tmo_at);
8748 EMACS_ADD_TIME (tmo_at, tmo_at, tmo);
8750 while (pending_event_wait.eventtype)
8752 interrupt_input_pending = 1;
8753 TOTALLY_UNBLOCK_INPUT;
8754 /* XTread_socket is called after unblock. */
8755 BLOCK_INPUT;
8756 interrupt_input_blocked = level;
8758 FD_ZERO (&fds);
8759 FD_SET (fd, &fds);
8761 EMACS_GET_TIME (time_now);
8762 EMACS_SUB_TIME (tmo, tmo_at, time_now);
8764 if (EMACS_TIME_NEG_P (tmo) || select (fd+1, &fds, NULL, NULL, &tmo) == 0)
8765 break; /* Timeout */
8767 pending_event_wait.f = 0;
8768 pending_event_wait.eventtype = 0;
8772 /* Change the size of frame F's X window to COLS/ROWS in the case F
8773 doesn't have a widget. If CHANGE_GRAVITY is 1, we change to
8774 top-left-corner window gravity for this size change and subsequent
8775 size changes. Otherwise we leave the window gravity unchanged. */
8777 static void
8778 x_set_window_size_1 (struct frame *f, int change_gravity, int cols, int rows)
8780 int pixelwidth, pixelheight;
8782 check_frame_size (f, &rows, &cols);
8783 f->scroll_bar_actual_width
8784 = (!FRAME_HAS_VERTICAL_SCROLL_BARS (f)
8786 : FRAME_CONFIG_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f));
8788 compute_fringe_widths (f, 0);
8790 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, cols)
8791 + FRAME_TOOLBAR_WIDTH (f);
8792 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows)
8793 + FRAME_MENUBAR_HEIGHT (f) + FRAME_TOOLBAR_HEIGHT (f);
8795 if (change_gravity) f->win_gravity = NorthWestGravity;
8796 x_wm_set_size_hint (f, (long) 0, 0);
8797 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8798 pixelwidth, pixelheight);
8801 /* We've set {FRAME,PIXEL}_{WIDTH,HEIGHT} to the values we hope to
8802 receive in the ConfigureNotify event; if we get what we asked
8803 for, then the event won't cause the screen to become garbaged, so
8804 we have to make sure to do it here. */
8805 SET_FRAME_GARBAGED (f);
8807 /* Now, strictly speaking, we can't be sure that this is accurate,
8808 but the window manager will get around to dealing with the size
8809 change request eventually, and we'll hear how it went when the
8810 ConfigureNotify event gets here.
8812 We could just not bother storing any of this information here,
8813 and let the ConfigureNotify event set everything up, but that
8814 might be kind of confusing to the Lisp code, since size changes
8815 wouldn't be reported in the frame parameters until some random
8816 point in the future when the ConfigureNotify event arrives.
8818 We pass 1 for DELAY since we can't run Lisp code inside of
8819 a BLOCK_INPUT. */
8821 /* But the ConfigureNotify may in fact never arrive, and then this is
8822 not right if the frame is visible. Instead wait (with timeout)
8823 for the ConfigureNotify. */
8824 if (f->async_visible)
8825 x_wait_for_event (f, ConfigureNotify);
8826 else
8828 change_frame_size (f, rows, cols, 0, 1, 0);
8829 FRAME_PIXEL_WIDTH (f) = pixelwidth;
8830 FRAME_PIXEL_HEIGHT (f) = pixelheight;
8831 x_sync (f);
8836 /* Call this to change the size of frame F's x-window.
8837 If CHANGE_GRAVITY is 1, we change to top-left-corner window gravity
8838 for this size change and subsequent size changes.
8839 Otherwise we leave the window gravity unchanged. */
8841 void
8842 x_set_window_size (struct frame *f, int change_gravity, int cols, int rows)
8844 BLOCK_INPUT;
8846 if (NILP (tip_frame) || XFRAME (tip_frame) != f)
8848 int r, c;
8850 /* When the frame is maximized/fullscreen or running under for
8851 example Xmonad, x_set_window_size_1 will be a no-op.
8852 In that case, the right thing to do is extend rows/cols to
8853 the current frame size. We do that first if x_set_window_size_1
8854 turns out to not be a no-op (there is no way to know).
8855 The size will be adjusted again if the frame gets a
8856 ConfigureNotify event as a result of x_set_window_size. */
8857 int pixelh = FRAME_PIXEL_HEIGHT (f);
8858 #ifdef USE_X_TOOLKIT
8859 /* The menu bar is not part of text lines. The tool bar
8860 is however. */
8861 pixelh -= FRAME_MENUBAR_HEIGHT (f);
8862 #endif
8863 r = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, pixelh);
8864 /* Update f->scroll_bar_actual_width because it is used in
8865 FRAME_PIXEL_WIDTH_TO_TEXT_COLS. */
8866 f->scroll_bar_actual_width
8867 = FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f);
8868 c = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, FRAME_PIXEL_WIDTH (f));
8869 change_frame_size (f, r, c, 0, 1, 0);
8872 #ifdef USE_GTK
8873 if (FRAME_GTK_WIDGET (f))
8874 xg_frame_set_char_size (f, cols, rows);
8875 else
8876 x_set_window_size_1 (f, change_gravity, cols, rows);
8877 #else /* not USE_GTK */
8879 x_set_window_size_1 (f, change_gravity, cols, rows);
8881 #endif /* not USE_GTK */
8883 /* If cursor was outside the new size, mark it as off. */
8884 mark_window_cursors_off (XWINDOW (f->root_window));
8886 /* Clear out any recollection of where the mouse highlighting was,
8887 since it might be in a place that's outside the new frame size.
8888 Actually checking whether it is outside is a pain in the neck,
8889 so don't try--just let the highlighting be done afresh with new size. */
8890 cancel_mouse_face (f);
8892 UNBLOCK_INPUT;
8895 /* Mouse warping. */
8897 void
8898 x_set_mouse_position (struct frame *f, int x, int y)
8900 int pix_x, pix_y;
8902 pix_x = FRAME_COL_TO_PIXEL_X (f, x) + FRAME_COLUMN_WIDTH (f) / 2;
8903 pix_y = FRAME_LINE_TO_PIXEL_Y (f, y) + FRAME_LINE_HEIGHT (f) / 2;
8905 if (pix_x < 0) pix_x = 0;
8906 if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
8908 if (pix_y < 0) pix_y = 0;
8909 if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
8911 BLOCK_INPUT;
8913 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
8914 0, 0, 0, 0, pix_x, pix_y);
8915 UNBLOCK_INPUT;
8918 /* Move the mouse to position pixel PIX_X, PIX_Y relative to frame F. */
8920 void
8921 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
8923 BLOCK_INPUT;
8925 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
8926 0, 0, 0, 0, pix_x, pix_y);
8927 UNBLOCK_INPUT;
8930 /* focus shifting, raising and lowering. */
8932 void
8933 x_focus_on_frame (struct frame *f)
8935 #if 0
8936 /* I don't think that the ICCCM allows programs to do things like this
8937 without the interaction of the window manager. Whatever you end up
8938 doing with this code, do it to x_unfocus_frame too. */
8939 XSetInputFocus (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
8940 RevertToPointerRoot, CurrentTime);
8941 #endif /* ! 0 */
8944 void
8945 x_unfocus_frame (struct frame *f)
8947 #if 0
8948 /* Look at the remarks in x_focus_on_frame. */
8949 if (FRAME_X_DISPLAY_INFO (f)->x_focus_frame == f)
8950 XSetInputFocus (FRAME_X_DISPLAY (f), PointerRoot,
8951 RevertToPointerRoot, CurrentTime);
8952 #endif /* ! 0 */
8955 /* Raise frame F. */
8957 void
8958 x_raise_frame (struct frame *f)
8960 BLOCK_INPUT;
8961 if (f->async_visible)
8962 XRaiseWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
8964 XFlush (FRAME_X_DISPLAY (f));
8965 UNBLOCK_INPUT;
8968 /* Lower frame F. */
8970 void
8971 x_lower_frame (struct frame *f)
8973 if (f->async_visible)
8975 BLOCK_INPUT;
8976 XLowerWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
8977 XFlush (FRAME_X_DISPLAY (f));
8978 UNBLOCK_INPUT;
8982 /* Activate frame with Extended Window Manager Hints */
8984 void
8985 x_ewmh_activate_frame (FRAME_PTR f)
8987 /* See Window Manager Specification/Extended Window Manager Hints at
8988 http://freedesktop.org/wiki/Specifications/wm-spec */
8990 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8991 if (f->async_visible && wm_supports (f, dpyinfo->Xatom_net_active_window))
8993 Lisp_Object frame;
8994 XSETFRAME (frame, f);
8995 x_send_client_event (frame, make_number (0), frame,
8996 dpyinfo->Xatom_net_active_window,
8997 make_number (32),
8998 Fcons (make_number (1),
8999 Fcons (make_number (last_user_time),
9000 Qnil)));
9004 static void
9005 XTframe_raise_lower (FRAME_PTR f, int raise_flag)
9007 if (raise_flag)
9008 x_raise_frame (f);
9009 else
9010 x_lower_frame (f);
9013 /* XEmbed implementation. */
9015 static void
9016 xembed_set_info (struct frame *f, enum xembed_info flags)
9018 unsigned long data[2];
9019 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
9021 data[0] = XEMBED_VERSION;
9022 data[1] = flags;
9024 XChangeProperty (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
9025 dpyinfo->Xatom_XEMBED_INFO, dpyinfo->Xatom_XEMBED_INFO,
9026 32, PropModeReplace, (unsigned char *) data, 2);
9029 static void
9030 xembed_send_message (struct frame *f, Time time, enum xembed_message message, long int detail, long int data1, long int data2)
9032 XEvent event;
9034 event.xclient.type = ClientMessage;
9035 event.xclient.window = FRAME_X_OUTPUT (f)->parent_desc;
9036 event.xclient.message_type = FRAME_X_DISPLAY_INFO (f)->Xatom_XEMBED;
9037 event.xclient.format = 32;
9038 event.xclient.data.l[0] = time;
9039 event.xclient.data.l[1] = message;
9040 event.xclient.data.l[2] = detail;
9041 event.xclient.data.l[3] = data1;
9042 event.xclient.data.l[4] = data2;
9044 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_OUTPUT (f)->parent_desc,
9045 False, NoEventMask, &event);
9046 XSync (FRAME_X_DISPLAY (f), False);
9049 /* Change of visibility. */
9051 /* This tries to wait until the frame is really visible.
9052 However, if the window manager asks the user where to position
9053 the frame, this will return before the user finishes doing that.
9054 The frame will not actually be visible at that time,
9055 but it will become visible later when the window manager
9056 finishes with it. */
9058 void
9059 x_make_frame_visible (struct frame *f)
9061 Lisp_Object type;
9062 int original_top, original_left;
9063 int retry_count = 2;
9065 retry:
9067 BLOCK_INPUT;
9069 type = x_icon_type (f);
9070 if (!NILP (type))
9071 x_bitmap_icon (f, type);
9073 if (! FRAME_VISIBLE_P (f))
9075 /* We test FRAME_GARBAGED_P here to make sure we don't
9076 call x_set_offset a second time
9077 if we get to x_make_frame_visible a second time
9078 before the window gets really visible. */
9079 if (! FRAME_ICONIFIED_P (f)
9080 && ! FRAME_X_EMBEDDED_P (f)
9081 && ! f->output_data.x->asked_for_visible)
9082 x_set_offset (f, f->left_pos, f->top_pos, 0);
9084 f->output_data.x->asked_for_visible = 1;
9086 if (! EQ (Vx_no_window_manager, Qt))
9087 x_wm_set_window_state (f, NormalState);
9088 #ifdef USE_X_TOOLKIT
9089 if (FRAME_X_EMBEDDED_P (f))
9090 xembed_set_info (f, XEMBED_MAPPED);
9091 else
9093 /* This was XtPopup, but that did nothing for an iconified frame. */
9094 XtMapWidget (f->output_data.x->widget);
9096 #else /* not USE_X_TOOLKIT */
9097 #ifdef USE_GTK
9098 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
9099 gtk_window_deiconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
9100 #else
9101 if (FRAME_X_EMBEDDED_P (f))
9102 xembed_set_info (f, XEMBED_MAPPED);
9103 else
9104 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9105 #endif /* not USE_GTK */
9106 #endif /* not USE_X_TOOLKIT */
9109 XFlush (FRAME_X_DISPLAY (f));
9111 /* Synchronize to ensure Emacs knows the frame is visible
9112 before we do anything else. We do this loop with input not blocked
9113 so that incoming events are handled. */
9115 Lisp_Object frame;
9116 int count;
9117 /* This must be before UNBLOCK_INPUT
9118 since events that arrive in response to the actions above
9119 will set it when they are handled. */
9120 int previously_visible = f->output_data.x->has_been_visible;
9122 original_left = f->left_pos;
9123 original_top = f->top_pos;
9125 /* This must come after we set COUNT. */
9126 UNBLOCK_INPUT;
9128 /* We unblock here so that arriving X events are processed. */
9130 /* Now move the window back to where it was "supposed to be".
9131 But don't do it if the gravity is negative.
9132 When the gravity is negative, this uses a position
9133 that is 3 pixels too low. Perhaps that's really the border width.
9135 Don't do this if the window has never been visible before,
9136 because the window manager may choose the position
9137 and we don't want to override it. */
9139 if (! FRAME_VISIBLE_P (f)
9140 && ! FRAME_ICONIFIED_P (f)
9141 && ! FRAME_X_EMBEDDED_P (f)
9142 && f->win_gravity == NorthWestGravity
9143 && previously_visible)
9145 Drawable rootw;
9146 int x, y;
9147 unsigned int width, height, border, depth;
9149 BLOCK_INPUT;
9151 /* On some window managers (such as FVWM) moving an existing
9152 window, even to the same place, causes the window manager
9153 to introduce an offset. This can cause the window to move
9154 to an unexpected location. Check the geometry (a little
9155 slow here) and then verify that the window is in the right
9156 place. If the window is not in the right place, move it
9157 there, and take the potential window manager hit. */
9158 XGetGeometry (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
9159 &rootw, &x, &y, &width, &height, &border, &depth);
9161 if (original_left != x || original_top != y)
9162 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
9163 original_left, original_top);
9165 UNBLOCK_INPUT;
9168 XSETFRAME (frame, f);
9170 /* Wait until the frame is visible. Process X events until a
9171 MapNotify event has been seen, or until we think we won't get a
9172 MapNotify at all.. */
9173 for (count = input_signal_count + 10;
9174 input_signal_count < count && !FRAME_VISIBLE_P (f);)
9176 /* Force processing of queued events. */
9177 x_sync (f);
9179 /* Machines that do polling rather than SIGIO have been
9180 observed to go into a busy-wait here. So we'll fake an
9181 alarm signal to let the handler know that there's something
9182 to be read. We used to raise a real alarm, but it seems
9183 that the handler isn't always enabled here. This is
9184 probably a bug. */
9185 if (input_polling_used ())
9187 /* It could be confusing if a real alarm arrives while
9188 processing the fake one. Turn it off and let the
9189 handler reset it. */
9190 int old_poll_suppress_count = poll_suppress_count;
9191 poll_suppress_count = 1;
9192 poll_for_input_1 ();
9193 poll_suppress_count = old_poll_suppress_count;
9196 /* See if a MapNotify event has been processed. */
9197 FRAME_SAMPLE_VISIBILITY (f);
9200 /* 2000-09-28: In
9202 (let ((f (selected-frame)))
9203 (iconify-frame f)
9204 (raise-frame f))
9206 the frame is not raised with various window managers on
9207 FreeBSD, GNU/Linux and Solaris. It turns out that, for some
9208 unknown reason, the call to XtMapWidget is completely ignored.
9209 Mapping the widget a second time works. */
9211 if (!FRAME_VISIBLE_P (f) && --retry_count > 0)
9212 goto retry;
9216 /* Change from mapped state to withdrawn state. */
9218 /* Make the frame visible (mapped and not iconified). */
9220 void
9221 x_make_frame_invisible (struct frame *f)
9223 Window window;
9225 /* Use the frame's outermost window, not the one we normally draw on. */
9226 window = FRAME_OUTER_WINDOW (f);
9228 /* Don't keep the highlight on an invisible frame. */
9229 if (FRAME_X_DISPLAY_INFO (f)->x_highlight_frame == f)
9230 FRAME_X_DISPLAY_INFO (f)->x_highlight_frame = 0;
9232 BLOCK_INPUT;
9234 /* Before unmapping the window, update the WM_SIZE_HINTS property to claim
9235 that the current position of the window is user-specified, rather than
9236 program-specified, so that when the window is mapped again, it will be
9237 placed at the same location, without forcing the user to position it
9238 by hand again (they have already done that once for this window.) */
9239 x_wm_set_size_hint (f, (long) 0, 1);
9241 #ifdef USE_GTK
9242 if (FRAME_GTK_OUTER_WIDGET (f))
9243 gtk_widget_hide (FRAME_GTK_OUTER_WIDGET (f));
9244 else
9245 #else
9246 if (FRAME_X_EMBEDDED_P (f))
9247 xembed_set_info (f, 0);
9248 else
9249 #endif
9252 if (! XWithdrawWindow (FRAME_X_DISPLAY (f), window,
9253 DefaultScreen (FRAME_X_DISPLAY (f))))
9255 UNBLOCK_INPUT_RESIGNAL;
9256 error ("Can't notify window manager of window withdrawal");
9260 /* We can't distinguish this from iconification
9261 just by the event that we get from the server.
9262 So we can't win using the usual strategy of letting
9263 FRAME_SAMPLE_VISIBILITY set this. So do it by hand,
9264 and synchronize with the server to make sure we agree. */
9265 f->visible = 0;
9266 FRAME_ICONIFIED_P (f) = 0;
9267 f->async_visible = 0;
9268 f->async_iconified = 0;
9270 x_sync (f);
9272 UNBLOCK_INPUT;
9275 /* Change window state from mapped to iconified. */
9277 void
9278 x_iconify_frame (struct frame *f)
9280 int result;
9281 Lisp_Object type;
9283 /* Don't keep the highlight on an invisible frame. */
9284 if (FRAME_X_DISPLAY_INFO (f)->x_highlight_frame == f)
9285 FRAME_X_DISPLAY_INFO (f)->x_highlight_frame = 0;
9287 if (f->async_iconified)
9288 return;
9290 BLOCK_INPUT;
9292 FRAME_SAMPLE_VISIBILITY (f);
9294 type = x_icon_type (f);
9295 if (!NILP (type))
9296 x_bitmap_icon (f, type);
9298 #ifdef USE_GTK
9299 if (FRAME_GTK_OUTER_WIDGET (f))
9301 if (! FRAME_VISIBLE_P (f))
9302 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
9304 gtk_window_iconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
9305 f->iconified = 1;
9306 f->visible = 1;
9307 f->async_iconified = 1;
9308 f->async_visible = 0;
9309 UNBLOCK_INPUT;
9310 return;
9312 #endif
9314 #ifdef USE_X_TOOLKIT
9316 if (! FRAME_VISIBLE_P (f))
9318 if (! EQ (Vx_no_window_manager, Qt))
9319 x_wm_set_window_state (f, IconicState);
9320 /* This was XtPopup, but that did nothing for an iconified frame. */
9321 XtMapWidget (f->output_data.x->widget);
9322 /* The server won't give us any event to indicate
9323 that an invisible frame was changed to an icon,
9324 so we have to record it here. */
9325 f->iconified = 1;
9326 f->visible = 1;
9327 f->async_iconified = 1;
9328 f->async_visible = 0;
9329 UNBLOCK_INPUT;
9330 return;
9333 result = XIconifyWindow (FRAME_X_DISPLAY (f),
9334 XtWindow (f->output_data.x->widget),
9335 DefaultScreen (FRAME_X_DISPLAY (f)));
9336 UNBLOCK_INPUT;
9338 if (!result)
9339 error ("Can't notify window manager of iconification");
9341 f->async_iconified = 1;
9342 f->async_visible = 0;
9345 BLOCK_INPUT;
9346 XFlush (FRAME_X_DISPLAY (f));
9347 UNBLOCK_INPUT;
9348 #else /* not USE_X_TOOLKIT */
9350 /* Make sure the X server knows where the window should be positioned,
9351 in case the user deiconifies with the window manager. */
9352 if (! FRAME_VISIBLE_P (f)
9353 && ! FRAME_ICONIFIED_P (f)
9354 && ! FRAME_X_EMBEDDED_P (f))
9355 x_set_offset (f, f->left_pos, f->top_pos, 0);
9357 /* Since we don't know which revision of X we're running, we'll use both
9358 the X11R3 and X11R4 techniques. I don't know if this is a good idea. */
9360 /* X11R4: send a ClientMessage to the window manager using the
9361 WM_CHANGE_STATE type. */
9363 XEvent message;
9365 message.xclient.window = FRAME_X_WINDOW (f);
9366 message.xclient.type = ClientMessage;
9367 message.xclient.message_type = FRAME_X_DISPLAY_INFO (f)->Xatom_wm_change_state;
9368 message.xclient.format = 32;
9369 message.xclient.data.l[0] = IconicState;
9371 if (! XSendEvent (FRAME_X_DISPLAY (f),
9372 DefaultRootWindow (FRAME_X_DISPLAY (f)),
9373 False,
9374 SubstructureRedirectMask | SubstructureNotifyMask,
9375 &message))
9377 UNBLOCK_INPUT_RESIGNAL;
9378 error ("Can't notify window manager of iconification");
9382 /* X11R3: set the initial_state field of the window manager hints to
9383 IconicState. */
9384 x_wm_set_window_state (f, IconicState);
9386 if (!FRAME_VISIBLE_P (f))
9388 /* If the frame was withdrawn, before, we must map it. */
9389 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9392 f->async_iconified = 1;
9393 f->async_visible = 0;
9395 XFlush (FRAME_X_DISPLAY (f));
9396 UNBLOCK_INPUT;
9397 #endif /* not USE_X_TOOLKIT */
9401 /* Free X resources of frame F. */
9403 void
9404 x_free_frame_resources (struct frame *f)
9406 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
9407 Lisp_Object bar;
9408 struct scroll_bar *b;
9409 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
9411 BLOCK_INPUT;
9413 /* If a display connection is dead, don't try sending more
9414 commands to the X server. */
9415 if (dpyinfo->display)
9417 /* We must free faces before destroying windows because some
9418 font-driver (e.g. xft) access a window while finishing a
9419 face. */
9420 if (FRAME_FACE_CACHE (f))
9421 free_frame_faces (f);
9423 if (f->output_data.x->icon_desc)
9424 XDestroyWindow (FRAME_X_DISPLAY (f), f->output_data.x->icon_desc);
9426 #ifdef USE_X_TOOLKIT
9427 /* Explicitly destroy the scroll bars of the frame. Without
9428 this, we get "BadDrawable" errors from the toolkit later on,
9429 presumably from expose events generated for the disappearing
9430 toolkit scroll bars. */
9431 for (bar = FRAME_SCROLL_BARS (f); !NILP (bar); bar = b->next)
9433 b = XSCROLL_BAR (bar);
9434 x_scroll_bar_remove (b);
9436 #endif
9438 #ifdef HAVE_X_I18N
9439 if (FRAME_XIC (f))
9440 free_frame_xic (f);
9441 #endif
9443 #ifdef USE_X_TOOLKIT
9444 if (f->output_data.x->widget)
9446 XtDestroyWidget (f->output_data.x->widget);
9447 f->output_data.x->widget = NULL;
9449 /* Tooltips don't have widgets, only a simple X window, even if
9450 we are using a toolkit. */
9451 else if (FRAME_X_WINDOW (f))
9452 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9454 free_frame_menubar (f);
9455 #else /* !USE_X_TOOLKIT */
9457 #ifdef USE_GTK
9458 xg_free_frame_widgets (f);
9459 #endif /* USE_GTK */
9461 if (FRAME_X_WINDOW (f))
9462 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9463 #endif /* !USE_X_TOOLKIT */
9465 unload_color (f, FRAME_FOREGROUND_PIXEL (f));
9466 unload_color (f, FRAME_BACKGROUND_PIXEL (f));
9467 unload_color (f, f->output_data.x->cursor_pixel);
9468 unload_color (f, f->output_data.x->cursor_foreground_pixel);
9469 unload_color (f, f->output_data.x->border_pixel);
9470 unload_color (f, f->output_data.x->mouse_pixel);
9472 if (f->output_data.x->scroll_bar_background_pixel != -1)
9473 unload_color (f, f->output_data.x->scroll_bar_background_pixel);
9474 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
9475 unload_color (f, f->output_data.x->scroll_bar_foreground_pixel);
9476 #ifdef USE_TOOLKIT_SCROLL_BARS
9477 /* Scrollbar shadow colors. */
9478 if (f->output_data.x->scroll_bar_top_shadow_pixel != -1)
9479 unload_color (f, f->output_data.x->scroll_bar_top_shadow_pixel);
9480 if (f->output_data.x->scroll_bar_bottom_shadow_pixel != -1)
9481 unload_color (f, f->output_data.x->scroll_bar_bottom_shadow_pixel);
9482 #endif /* USE_TOOLKIT_SCROLL_BARS */
9483 if (f->output_data.x->white_relief.allocated_p)
9484 unload_color (f, f->output_data.x->white_relief.pixel);
9485 if (f->output_data.x->black_relief.allocated_p)
9486 unload_color (f, f->output_data.x->black_relief.pixel);
9488 x_free_gcs (f);
9489 XFlush (FRAME_X_DISPLAY (f));
9492 xfree (f->output_data.x->saved_menu_event);
9493 xfree (f->output_data.x);
9494 f->output_data.x = NULL;
9496 if (f == dpyinfo->x_focus_frame)
9497 dpyinfo->x_focus_frame = 0;
9498 if (f == dpyinfo->x_focus_event_frame)
9499 dpyinfo->x_focus_event_frame = 0;
9500 if (f == dpyinfo->x_highlight_frame)
9501 dpyinfo->x_highlight_frame = 0;
9503 if (f == hlinfo->mouse_face_mouse_frame)
9505 hlinfo->mouse_face_beg_row
9506 = hlinfo->mouse_face_beg_col = -1;
9507 hlinfo->mouse_face_end_row
9508 = hlinfo->mouse_face_end_col = -1;
9509 hlinfo->mouse_face_window = Qnil;
9510 hlinfo->mouse_face_deferred_gc = 0;
9511 hlinfo->mouse_face_mouse_frame = 0;
9514 UNBLOCK_INPUT;
9518 /* Destroy the X window of frame F. */
9520 void
9521 x_destroy_window (struct frame *f)
9523 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
9525 /* If a display connection is dead, don't try sending more
9526 commands to the X server. */
9527 if (dpyinfo->display != 0)
9528 x_free_frame_resources (f);
9530 dpyinfo->reference_count--;
9534 /* Setting window manager hints. */
9536 /* Set the normal size hints for the window manager, for frame F.
9537 FLAGS is the flags word to use--or 0 meaning preserve the flags
9538 that the window now has.
9539 If USER_POSITION is nonzero, we set the USPosition
9540 flag (this is useful when FLAGS is 0).
9541 The GTK version is in gtkutils.c */
9543 #ifndef USE_GTK
9544 void
9545 x_wm_set_size_hint (struct frame *f, long flags, int user_position)
9547 XSizeHints size_hints;
9548 Window window = FRAME_OUTER_WINDOW (f);
9550 /* Setting PMaxSize caused various problems. */
9551 size_hints.flags = PResizeInc | PMinSize /* | PMaxSize */;
9553 size_hints.x = f->left_pos;
9554 size_hints.y = f->top_pos;
9556 size_hints.height = FRAME_PIXEL_HEIGHT (f);
9557 size_hints.width = FRAME_PIXEL_WIDTH (f);
9559 size_hints.width_inc = FRAME_COLUMN_WIDTH (f);
9560 size_hints.height_inc = FRAME_LINE_HEIGHT (f);
9561 size_hints.max_width = x_display_pixel_width (FRAME_X_DISPLAY_INFO (f))
9562 - FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
9563 size_hints.max_height = x_display_pixel_height (FRAME_X_DISPLAY_INFO (f))
9564 - FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
9566 /* Calculate the base and minimum sizes. */
9568 int base_width, base_height;
9569 int min_rows = 0, min_cols = 0;
9571 base_width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
9572 base_height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
9574 check_frame_size (f, &min_rows, &min_cols);
9576 /* The window manager uses the base width hints to calculate the
9577 current number of rows and columns in the frame while
9578 resizing; min_width and min_height aren't useful for this
9579 purpose, since they might not give the dimensions for a
9580 zero-row, zero-column frame.
9582 We use the base_width and base_height members if we have
9583 them; otherwise, we set the min_width and min_height members
9584 to the size for a zero x zero frame. */
9586 size_hints.flags |= PBaseSize;
9587 size_hints.base_width = base_width;
9588 size_hints.base_height = base_height + FRAME_MENUBAR_HEIGHT (f);
9589 size_hints.min_width = base_width + min_cols * size_hints.width_inc;
9590 size_hints.min_height = base_height + min_rows * size_hints.height_inc;
9593 /* If we don't need the old flags, we don't need the old hint at all. */
9594 if (flags)
9596 size_hints.flags |= flags;
9597 goto no_read;
9601 XSizeHints hints; /* Sometimes I hate X Windows... */
9602 long supplied_return;
9603 int value;
9605 value = XGetWMNormalHints (FRAME_X_DISPLAY (f), window, &hints,
9606 &supplied_return);
9608 if (flags)
9609 size_hints.flags |= flags;
9610 else
9612 if (value == 0)
9613 hints.flags = 0;
9614 if (hints.flags & PSize)
9615 size_hints.flags |= PSize;
9616 if (hints.flags & PPosition)
9617 size_hints.flags |= PPosition;
9618 if (hints.flags & USPosition)
9619 size_hints.flags |= USPosition;
9620 if (hints.flags & USSize)
9621 size_hints.flags |= USSize;
9625 no_read:
9627 #ifdef PWinGravity
9628 size_hints.win_gravity = f->win_gravity;
9629 size_hints.flags |= PWinGravity;
9631 if (user_position)
9633 size_hints.flags &= ~ PPosition;
9634 size_hints.flags |= USPosition;
9636 #endif /* PWinGravity */
9638 XSetWMNormalHints (FRAME_X_DISPLAY (f), window, &size_hints);
9640 #endif /* not USE_GTK */
9642 /* Used for IconicState or NormalState */
9644 void
9645 x_wm_set_window_state (struct frame *f, int state)
9647 #ifdef USE_X_TOOLKIT
9648 Arg al[1];
9650 XtSetArg (al[0], XtNinitialState, state);
9651 XtSetValues (f->output_data.x->widget, al, 1);
9652 #else /* not USE_X_TOOLKIT */
9653 Window window = FRAME_X_WINDOW (f);
9655 f->output_data.x->wm_hints.flags |= StateHint;
9656 f->output_data.x->wm_hints.initial_state = state;
9658 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
9659 #endif /* not USE_X_TOOLKIT */
9662 void
9663 x_wm_set_icon_pixmap (struct frame *f, int pixmap_id)
9665 Pixmap icon_pixmap, icon_mask;
9667 #if !defined USE_X_TOOLKIT && !defined USE_GTK
9668 Window window = FRAME_OUTER_WINDOW (f);
9669 #endif
9671 if (pixmap_id > 0)
9673 icon_pixmap = x_bitmap_pixmap (f, pixmap_id);
9674 f->output_data.x->wm_hints.icon_pixmap = icon_pixmap;
9675 icon_mask = x_bitmap_mask (f, pixmap_id);
9676 f->output_data.x->wm_hints.icon_mask = icon_mask;
9678 else
9680 /* It seems there is no way to turn off use of an icon
9681 pixmap. */
9682 return;
9686 #ifdef USE_GTK
9688 xg_set_frame_icon (f, icon_pixmap, icon_mask);
9689 return;
9692 #elif defined (USE_X_TOOLKIT) /* same as in x_wm_set_window_state. */
9695 Arg al[1];
9696 XtSetArg (al[0], XtNiconPixmap, icon_pixmap);
9697 XtSetValues (f->output_data.x->widget, al, 1);
9698 XtSetArg (al[0], XtNiconMask, icon_mask);
9699 XtSetValues (f->output_data.x->widget, al, 1);
9702 #else /* not USE_X_TOOLKIT && not USE_GTK */
9704 f->output_data.x->wm_hints.flags |= (IconPixmapHint | IconMaskHint);
9705 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
9707 #endif /* not USE_X_TOOLKIT && not USE_GTK */
9710 void
9711 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
9713 Window window = FRAME_OUTER_WINDOW (f);
9715 f->output_data.x->wm_hints.flags |= IconPositionHint;
9716 f->output_data.x->wm_hints.icon_x = icon_x;
9717 f->output_data.x->wm_hints.icon_y = icon_y;
9719 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
9723 /***********************************************************************
9724 Fonts
9725 ***********************************************************************/
9727 #if GLYPH_DEBUG
9729 /* Check that FONT is valid on frame F. It is if it can be found in F's
9730 font table. */
9732 static void
9733 x_check_font (struct frame *f, struct font *font)
9735 Lisp_Object frame;
9737 xassert (font != NULL && ! NILP (font->props[FONT_TYPE_INDEX]));
9738 if (font->driver->check)
9739 xassert (font->driver->check (f, font) == 0);
9742 #endif /* GLYPH_DEBUG != 0 */
9745 /***********************************************************************
9746 Initialization
9747 ***********************************************************************/
9749 #ifdef USE_X_TOOLKIT
9750 static XrmOptionDescRec emacs_options[] = {
9751 {"-geometry", ".geometry", XrmoptionSepArg, NULL},
9752 {"-iconic", ".iconic", XrmoptionNoArg, (XtPointer) "yes"},
9754 {"-internal-border-width", "*EmacsScreen.internalBorderWidth",
9755 XrmoptionSepArg, NULL},
9756 {"-ib", "*EmacsScreen.internalBorderWidth", XrmoptionSepArg, NULL},
9758 {"-T", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
9759 {"-wn", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
9760 {"-title", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
9761 {"-iconname", "*EmacsShell.iconName", XrmoptionSepArg, (XtPointer) NULL},
9762 {"-in", "*EmacsShell.iconName", XrmoptionSepArg, (XtPointer) NULL},
9763 {"-mc", "*pointerColor", XrmoptionSepArg, (XtPointer) NULL},
9764 {"-cr", "*cursorColor", XrmoptionSepArg, (XtPointer) NULL}
9767 /* Whether atimer for Xt timeouts is activated or not. */
9769 static int x_timeout_atimer_activated_flag;
9771 #endif /* USE_X_TOOLKIT */
9773 static int x_initialized;
9775 #ifdef HAVE_X_SM
9776 static int x_session_initialized;
9777 #endif
9779 /* Test whether two display-name strings agree up to the dot that separates
9780 the screen number from the server number. */
9781 static int
9782 same_x_server (const char *name1, const char *name2)
9784 int seen_colon = 0;
9785 const unsigned char *system_name = SDATA (Vsystem_name);
9786 int system_name_length = strlen (system_name);
9787 int length_until_period = 0;
9789 while (system_name[length_until_period] != 0
9790 && system_name[length_until_period] != '.')
9791 length_until_period++;
9793 /* Treat `unix' like an empty host name. */
9794 if (! strncmp (name1, "unix:", 5))
9795 name1 += 4;
9796 if (! strncmp (name2, "unix:", 5))
9797 name2 += 4;
9798 /* Treat this host's name like an empty host name. */
9799 if (! strncmp (name1, system_name, system_name_length)
9800 && name1[system_name_length] == ':')
9801 name1 += system_name_length;
9802 if (! strncmp (name2, system_name, system_name_length)
9803 && name2[system_name_length] == ':')
9804 name2 += system_name_length;
9805 /* Treat this host's domainless name like an empty host name. */
9806 if (! strncmp (name1, system_name, length_until_period)
9807 && name1[length_until_period] == ':')
9808 name1 += length_until_period;
9809 if (! strncmp (name2, system_name, length_until_period)
9810 && name2[length_until_period] == ':')
9811 name2 += length_until_period;
9813 for (; *name1 != '\0' && *name1 == *name2; name1++, name2++)
9815 if (*name1 == ':')
9816 seen_colon++;
9817 if (seen_colon && *name1 == '.')
9818 return 1;
9820 return (seen_colon
9821 && (*name1 == '.' || *name1 == '\0')
9822 && (*name2 == '.' || *name2 == '\0'));
9825 /* Count number of set bits in mask and number of bits to shift to
9826 get to the first bit. With MASK 0x7e0, *BITS is set to 6, and *OFFSET
9827 to 5. */
9828 static void
9829 get_bits_and_offset (long unsigned int mask, int *bits, int *offset)
9831 int nr = 0;
9832 int off = 0;
9834 while (!(mask & 1))
9836 off++;
9837 mask >>= 1;
9840 while (mask & 1)
9842 nr++;
9843 mask >>= 1;
9846 *offset = off;
9847 *bits = nr;
9850 /* Return 1 if display DISPLAY is available for use, 0 otherwise.
9851 But don't permanently open it, just test its availability. */
9854 x_display_ok (const char *display)
9856 int dpy_ok = 1;
9857 Display *dpy;
9859 dpy = XOpenDisplay (display);
9860 if (dpy)
9861 XCloseDisplay (dpy);
9862 else
9863 dpy_ok = 0;
9864 return dpy_ok;
9867 #ifdef USE_GTK
9868 static void
9869 my_log_handler (const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer user_data)
9871 if (!strstr (message, "g_set_prgname"))
9872 fprintf (stderr, "%s-WARNING **: %s\n", log_domain, message);
9874 #endif
9876 /* Open a connection to X display DISPLAY_NAME, and return
9877 the structure that describes the open display.
9878 If we cannot contact the display, return null. */
9880 struct x_display_info *
9881 x_term_init (Lisp_Object display_name, char *xrm_option, char *resource_name)
9883 int connection;
9884 Display *dpy;
9885 struct terminal *terminal;
9886 struct x_display_info *dpyinfo;
9887 XrmDatabase xrdb;
9888 Mouse_HLInfo *hlinfo;
9890 BLOCK_INPUT;
9892 if (!x_initialized)
9894 x_initialize ();
9895 ++x_initialized;
9898 if (! x_display_ok (SDATA (display_name)))
9899 error ("Display %s can't be opened", SDATA (display_name));
9901 #ifdef USE_GTK
9903 #define NUM_ARGV 10
9904 int argc;
9905 char *argv[NUM_ARGV];
9906 char **argv2 = argv;
9907 guint id;
9909 if (x_initialized++ > 1)
9911 xg_display_open (SDATA (display_name), &dpy);
9913 else
9915 static char display_opt[] = "--display";
9916 static char name_opt[] = "--name";
9918 for (argc = 0; argc < NUM_ARGV; ++argc)
9919 argv[argc] = 0;
9921 argc = 0;
9922 argv[argc++] = initial_argv[0];
9924 if (! NILP (display_name))
9926 argv[argc++] = display_opt;
9927 argv[argc++] = SDATA (display_name);
9930 argv[argc++] = name_opt;
9931 argv[argc++] = resource_name;
9933 XSetLocaleModifiers ("");
9935 /* Work around GLib bug that outputs a faulty warning. See
9936 https://bugzilla.gnome.org/show_bug.cgi?id=563627. */
9937 id = g_log_set_handler ("GLib", G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
9938 | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
9939 gtk_init (&argc, &argv2);
9940 g_log_remove_handler ("GLib", id);
9942 /* gtk_init does set_locale. We must fix locale after calling it. */
9943 fixup_locale ();
9944 xg_initialize ();
9946 dpy = GDK_DISPLAY ();
9948 /* NULL window -> events for all windows go to our function */
9949 gdk_window_add_filter (NULL, event_handler_gdk, NULL);
9951 /* Load our own gtkrc if it exists. */
9953 const char *file = "~/.emacs.d/gtkrc";
9954 Lisp_Object s, abs_file;
9956 s = make_string (file, strlen (file));
9957 abs_file = Fexpand_file_name (s, Qnil);
9959 if (! NILP (abs_file) && !NILP (Ffile_readable_p (abs_file)))
9960 gtk_rc_parse (SDATA (abs_file));
9963 XSetErrorHandler (x_error_handler);
9964 XSetIOErrorHandler (x_io_error_quitter);
9967 #else /* not USE_GTK */
9968 #ifdef USE_X_TOOLKIT
9969 /* weiner@footloose.sps.mot.com reports that this causes
9970 errors with X11R5:
9971 X protocol error: BadAtom (invalid Atom parameter)
9972 on protocol request 18skiloaf.
9973 So let's not use it until R6. */
9974 #ifdef HAVE_X11XTR6
9975 XtSetLanguageProc (NULL, NULL, NULL);
9976 #endif
9979 int argc = 0;
9980 char *argv[3];
9982 argv[0] = "";
9983 argc = 1;
9984 if (xrm_option)
9986 argv[argc++] = "-xrm";
9987 argv[argc++] = xrm_option;
9989 turn_on_atimers (0);
9990 dpy = XtOpenDisplay (Xt_app_con, SDATA (display_name),
9991 resource_name, EMACS_CLASS,
9992 emacs_options, XtNumber (emacs_options),
9993 &argc, argv);
9994 turn_on_atimers (1);
9996 #ifdef HAVE_X11XTR6
9997 /* I think this is to compensate for XtSetLanguageProc. */
9998 fixup_locale ();
9999 #endif
10002 #else /* not USE_X_TOOLKIT */
10003 XSetLocaleModifiers ("");
10004 dpy = XOpenDisplay (SDATA (display_name));
10005 #endif /* not USE_X_TOOLKIT */
10006 #endif /* not USE_GTK*/
10008 /* Detect failure. */
10009 if (dpy == 0)
10011 UNBLOCK_INPUT;
10012 return 0;
10015 /* We have definitely succeeded. Record the new connection. */
10017 dpyinfo = (struct x_display_info *) xmalloc (sizeof (struct x_display_info));
10018 memset (dpyinfo, 0, sizeof *dpyinfo);
10019 hlinfo = &dpyinfo->mouse_highlight;
10021 terminal = x_create_terminal (dpyinfo);
10024 struct x_display_info *share;
10025 Lisp_Object tail;
10027 for (share = x_display_list, tail = x_display_name_list; share;
10028 share = share->next, tail = XCDR (tail))
10029 if (same_x_server (SDATA (XCAR (XCAR (tail))),
10030 SDATA (display_name)))
10031 break;
10032 if (share)
10033 terminal->kboard = share->terminal->kboard;
10034 else
10036 terminal->kboard = (KBOARD *) xmalloc (sizeof (KBOARD));
10037 init_kboard (terminal->kboard);
10038 terminal->kboard->Vwindow_system = Qx;
10040 /* Add the keyboard to the list before running Lisp code (via
10041 Qvendor_specific_keysyms below), since these are not traced
10042 via terminals but only through all_kboards. */
10043 terminal->kboard->next_kboard = all_kboards;
10044 all_kboards = terminal->kboard;
10046 if (!EQ (XSYMBOL (Qvendor_specific_keysyms)->function, Qunbound))
10048 char *vendor = ServerVendor (dpy);
10050 /* Protect terminal from GC before removing it from the
10051 list of terminals. */
10052 struct gcpro gcpro1;
10053 Lisp_Object gcpro_term;
10054 XSETTERMINAL (gcpro_term, terminal);
10055 GCPRO1 (gcpro_term);
10057 /* Temporarily hide the partially initialized terminal. */
10058 terminal_list = terminal->next_terminal;
10059 UNBLOCK_INPUT;
10060 terminal->kboard->Vsystem_key_alist
10061 = call1 (Qvendor_specific_keysyms,
10062 vendor ? build_string (vendor) : empty_unibyte_string);
10063 BLOCK_INPUT;
10064 terminal->next_terminal = terminal_list;
10065 terminal_list = terminal;
10066 UNGCPRO;
10069 /* Don't let the initial kboard remain current longer than necessary.
10070 That would cause problems if a file loaded on startup tries to
10071 prompt in the mini-buffer. */
10072 if (current_kboard == initial_kboard)
10073 current_kboard = terminal->kboard;
10075 terminal->kboard->reference_count++;
10078 /* Put this display on the chain. */
10079 dpyinfo->next = x_display_list;
10080 x_display_list = dpyinfo;
10082 /* Put it on x_display_name_list as well, to keep them parallel. */
10083 x_display_name_list = Fcons (Fcons (display_name, Qnil),
10084 x_display_name_list);
10085 dpyinfo->name_list_element = XCAR (x_display_name_list);
10087 dpyinfo->display = dpy;
10089 /* Set the name of the terminal. */
10090 terminal->name = (char *) xmalloc (SBYTES (display_name) + 1);
10091 strncpy (terminal->name, SDATA (display_name), SBYTES (display_name));
10092 terminal->name[SBYTES (display_name)] = 0;
10094 #if 0
10095 XSetAfterFunction (x_current_display, x_trace_wire);
10096 #endif /* ! 0 */
10098 dpyinfo->x_id_name
10099 = (char *) xmalloc (SBYTES (Vinvocation_name)
10100 + SBYTES (Vsystem_name)
10101 + 2);
10102 sprintf (dpyinfo->x_id_name, "%s@%s",
10103 SDATA (Vinvocation_name), SDATA (Vsystem_name));
10105 /* Figure out which modifier bits mean what. */
10106 x_find_modifier_meanings (dpyinfo);
10108 /* Get the scroll bar cursor. */
10109 #ifdef USE_GTK
10110 /* We must create a GTK cursor, it is required for GTK widgets. */
10111 dpyinfo->xg_cursor = xg_create_default_cursor (dpyinfo->display);
10112 #endif /* USE_GTK */
10114 dpyinfo->vertical_scroll_bar_cursor
10115 = XCreateFontCursor (dpyinfo->display, XC_sb_v_double_arrow);
10117 xrdb = x_load_resources (dpyinfo->display, xrm_option,
10118 resource_name, EMACS_CLASS);
10119 #ifdef HAVE_XRMSETDATABASE
10120 XrmSetDatabase (dpyinfo->display, xrdb);
10121 #else
10122 dpyinfo->display->db = xrdb;
10123 #endif
10124 /* Put the rdb where we can find it in a way that works on
10125 all versions. */
10126 dpyinfo->xrdb = xrdb;
10128 dpyinfo->screen = ScreenOfDisplay (dpyinfo->display,
10129 DefaultScreen (dpyinfo->display));
10130 select_visual (dpyinfo);
10131 dpyinfo->cmap = DefaultColormapOfScreen (dpyinfo->screen);
10132 dpyinfo->root_window = RootWindowOfScreen (dpyinfo->screen);
10133 dpyinfo->client_leader_window = 0;
10134 dpyinfo->grabbed = 0;
10135 dpyinfo->reference_count = 0;
10136 dpyinfo->icon_bitmap_id = -1;
10137 dpyinfo->n_fonts = 0;
10138 dpyinfo->bitmaps = 0;
10139 dpyinfo->bitmaps_size = 0;
10140 dpyinfo->bitmaps_last = 0;
10141 dpyinfo->scratch_cursor_gc = 0;
10142 hlinfo->mouse_face_mouse_frame = 0;
10143 hlinfo->mouse_face_deferred_gc = 0;
10144 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
10145 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
10146 hlinfo->mouse_face_face_id = DEFAULT_FACE_ID;
10147 hlinfo->mouse_face_window = Qnil;
10148 hlinfo->mouse_face_overlay = Qnil;
10149 hlinfo->mouse_face_mouse_x = hlinfo->mouse_face_mouse_y = 0;
10150 hlinfo->mouse_face_defer = 0;
10151 hlinfo->mouse_face_hidden = 0;
10152 dpyinfo->x_focus_frame = 0;
10153 dpyinfo->x_focus_event_frame = 0;
10154 dpyinfo->x_highlight_frame = 0;
10155 dpyinfo->wm_type = X_WMTYPE_UNKNOWN;
10157 /* See if we can construct pixel values from RGB values. */
10158 dpyinfo->red_bits = dpyinfo->blue_bits = dpyinfo->green_bits = 0;
10159 dpyinfo->red_offset = dpyinfo->blue_offset = dpyinfo->green_offset = 0;
10161 if (dpyinfo->visual->class == TrueColor)
10163 get_bits_and_offset (dpyinfo->visual->red_mask,
10164 &dpyinfo->red_bits, &dpyinfo->red_offset);
10165 get_bits_and_offset (dpyinfo->visual->blue_mask,
10166 &dpyinfo->blue_bits, &dpyinfo->blue_offset);
10167 get_bits_and_offset (dpyinfo->visual->green_mask,
10168 &dpyinfo->green_bits, &dpyinfo->green_offset);
10171 /* See if a private colormap is requested. */
10172 if (dpyinfo->visual == DefaultVisualOfScreen (dpyinfo->screen))
10174 if (dpyinfo->visual->class == PseudoColor)
10176 Lisp_Object value;
10177 value = display_x_get_resource (dpyinfo,
10178 build_string ("privateColormap"),
10179 build_string ("PrivateColormap"),
10180 Qnil, Qnil);
10181 if (STRINGP (value)
10182 && (!strcmp (SDATA (value), "true")
10183 || !strcmp (SDATA (value), "on")))
10184 dpyinfo->cmap = XCopyColormapAndFree (dpyinfo->display, dpyinfo->cmap);
10187 else
10188 dpyinfo->cmap = XCreateColormap (dpyinfo->display, dpyinfo->root_window,
10189 dpyinfo->visual, AllocNone);
10191 #ifdef HAVE_XFT
10193 /* If we are using Xft, check dpi value in X resources.
10194 It is better we use it as well, since Xft will use it, as will all
10195 Gnome applications. If our real DPI is smaller or larger than the
10196 one Xft uses, our font will look smaller or larger than other
10197 for other applications, even if it is the same font name (monospace-10
10198 for example). */
10199 char *v = XGetDefault (dpyinfo->display, "Xft", "dpi");
10200 double d;
10201 if (v != NULL && sscanf (v, "%lf", &d) == 1)
10202 dpyinfo->resy = dpyinfo->resx = d;
10204 #endif
10206 if (dpyinfo->resy < 1)
10208 int screen_number = XScreenNumberOfScreen (dpyinfo->screen);
10209 double pixels = DisplayHeight (dpyinfo->display, screen_number);
10210 double mm = DisplayHeightMM (dpyinfo->display, screen_number);
10211 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
10212 dpyinfo->resy = (mm < 1) ? 100 : pixels * 25.4 / mm;
10213 pixels = DisplayWidth (dpyinfo->display, screen_number);
10214 mm = DisplayWidthMM (dpyinfo->display, screen_number);
10215 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
10216 dpyinfo->resx = (mm < 1) ? 100 : pixels * 25.4 / mm;
10220 const struct
10222 const char *name;
10223 Atom *atom;
10224 } atom_refs[] = {
10225 { "WM_PROTOCOLS", &dpyinfo->Xatom_wm_protocols },
10226 { "WM_TAKE_FOCUS", &dpyinfo->Xatom_wm_take_focus },
10227 { "WM_SAVE_YOURSELF", &dpyinfo->Xatom_wm_save_yourself },
10228 { "WM_DELETE_WINDOW", &dpyinfo->Xatom_wm_delete_window },
10229 { "WM_CHANGE_STATE", &dpyinfo->Xatom_wm_change_state },
10230 { "WM_CONFIGURE_DENIED", &dpyinfo->Xatom_wm_configure_denied },
10231 { "WM_MOVED", &dpyinfo->Xatom_wm_window_moved },
10232 { "WM_CLIENT_LEADER", &dpyinfo->Xatom_wm_client_leader },
10233 { "Editres", &dpyinfo->Xatom_editres },
10234 { "CLIPBOARD", &dpyinfo->Xatom_CLIPBOARD },
10235 { "TIMESTAMP", &dpyinfo->Xatom_TIMESTAMP },
10236 { "TEXT", &dpyinfo->Xatom_TEXT },
10237 { "COMPOUND_TEXT", &dpyinfo->Xatom_COMPOUND_TEXT },
10238 { "UTF8_STRING", &dpyinfo->Xatom_UTF8_STRING },
10239 { "DELETE", &dpyinfo->Xatom_DELETE },
10240 { "MULTIPLE", &dpyinfo->Xatom_MULTIPLE },
10241 { "INCR", &dpyinfo->Xatom_INCR },
10242 { "_EMACS_TMP_", &dpyinfo->Xatom_EMACS_TMP },
10243 { "TARGETS", &dpyinfo->Xatom_TARGETS },
10244 { "NULL", &dpyinfo->Xatom_NULL },
10245 { "ATOM_PAIR", &dpyinfo->Xatom_ATOM_PAIR },
10246 { "_XEMBED_INFO", &dpyinfo->Xatom_XEMBED_INFO },
10247 /* For properties of font. */
10248 { "PIXEL_SIZE", &dpyinfo->Xatom_PIXEL_SIZE },
10249 { "AVERAGE_WIDTH", &dpyinfo->Xatom_AVERAGE_WIDTH },
10250 { "_MULE_BASELINE_OFFSET", &dpyinfo->Xatom_MULE_BASELINE_OFFSET },
10251 { "_MULE_RELATIVE_COMPOSE", &dpyinfo->Xatom_MULE_RELATIVE_COMPOSE },
10252 { "_MULE_DEFAULT_ASCENT", &dpyinfo->Xatom_MULE_DEFAULT_ASCENT },
10253 /* Ghostscript support. */
10254 { "DONE", &dpyinfo->Xatom_DONE },
10255 { "PAGE", &dpyinfo->Xatom_PAGE },
10256 { "SCROLLBAR", &dpyinfo->Xatom_Scrollbar },
10257 { "_XEMBED", &dpyinfo->Xatom_XEMBED },
10258 /* EWMH */
10259 { "_NET_WM_STATE", &dpyinfo->Xatom_net_wm_state },
10260 { "_NET_WM_STATE_FULLSCREEN", &dpyinfo->Xatom_net_wm_state_fullscreen },
10261 { "_NET_WM_STATE_MAXIMIZED_HORZ",
10262 &dpyinfo->Xatom_net_wm_state_maximized_horz },
10263 { "_NET_WM_STATE_MAXIMIZED_VERT",
10264 &dpyinfo->Xatom_net_wm_state_maximized_vert },
10265 { "_NET_WM_STATE_STICKY", &dpyinfo->Xatom_net_wm_state_sticky },
10266 { "_NET_WM_WINDOW_TYPE", &dpyinfo->Xatom_net_window_type },
10267 { "_NET_WM_WINDOW_TYPE_TOOLTIP",
10268 &dpyinfo->Xatom_net_window_type_tooltip },
10269 { "_NET_WM_ICON_NAME", &dpyinfo->Xatom_net_wm_icon_name },
10270 { "_NET_WM_NAME", &dpyinfo->Xatom_net_wm_name },
10271 { "_NET_SUPPORTED", &dpyinfo->Xatom_net_supported },
10272 { "_NET_SUPPORTING_WM_CHECK", &dpyinfo->Xatom_net_supporting_wm_check },
10273 { "_NET_WM_WINDOW_OPACITY", &dpyinfo->Xatom_net_wm_window_opacity },
10274 { "_NET_ACTIVE_WINDOW", &dpyinfo->Xatom_net_active_window },
10275 { "_NET_FRAME_EXTENTS", &dpyinfo->Xatom_net_frame_extents },
10276 /* Session management */
10277 { "SM_CLIENT_ID", &dpyinfo->Xatom_SM_CLIENT_ID },
10278 { "_XSETTINGS_SETTINGS", &dpyinfo->Xatom_xsettings_prop },
10279 { "MANAGER", &dpyinfo->Xatom_xsettings_mgr },
10282 int i;
10283 const int atom_count = sizeof (atom_refs) / sizeof (atom_refs[0]);
10284 /* 1 for _XSETTINGS_SN */
10285 const int total_atom_count = 1 + atom_count;
10286 Atom *atoms_return = xmalloc (sizeof (Atom) * total_atom_count);
10287 char **atom_names = xmalloc (sizeof (char *) * total_atom_count);
10288 char xsettings_atom_name[64];
10290 for (i = 0; i < atom_count; i++)
10291 atom_names[i] = (char *) atom_refs[i].name;
10293 /* Build _XSETTINGS_SN atom name */
10294 snprintf (xsettings_atom_name, sizeof (xsettings_atom_name),
10295 "_XSETTINGS_S%d", XScreenNumberOfScreen (dpyinfo->screen));
10296 atom_names[i] = xsettings_atom_name;
10298 XInternAtoms (dpyinfo->display, atom_names, total_atom_count,
10299 False, atoms_return);
10301 for (i = 0; i < atom_count; i++)
10302 *atom_refs[i].atom = atoms_return[i];
10304 /* Manual copy of last atom */
10305 dpyinfo->Xatom_xsettings_sel = atoms_return[i];
10307 xfree (atom_names);
10308 xfree (atoms_return);
10311 dpyinfo->x_dnd_atoms_size = 8;
10312 dpyinfo->x_dnd_atoms_length = 0;
10313 dpyinfo->x_dnd_atoms = xmalloc (sizeof (*dpyinfo->x_dnd_atoms)
10314 * dpyinfo->x_dnd_atoms_size);
10316 dpyinfo->net_supported_atoms = NULL;
10317 dpyinfo->nr_net_supported_atoms = 0;
10318 dpyinfo->net_supported_window = 0;
10320 connection = ConnectionNumber (dpyinfo->display);
10321 dpyinfo->connection = connection;
10324 dpyinfo->gray
10325 = XCreatePixmapFromBitmapData (dpyinfo->display, dpyinfo->root_window,
10326 gray_bitmap_bits,
10327 gray_bitmap_width, gray_bitmap_height,
10328 (unsigned long) 1, (unsigned long) 0, 1);
10331 #ifdef HAVE_X_I18N
10332 xim_initialize (dpyinfo, resource_name);
10333 #endif
10335 xsettings_initialize (dpyinfo);
10337 /* This is only needed for distinguishing keyboard and process input. */
10338 if (connection != 0)
10339 add_keyboard_wait_descriptor (connection);
10341 #ifdef F_SETOWN
10342 fcntl (connection, F_SETOWN, getpid ());
10343 #endif /* ! defined (F_SETOWN) */
10345 #ifdef SIGIO
10346 if (interrupt_input)
10347 init_sigio (connection);
10348 #endif /* ! defined (SIGIO) */
10350 #ifdef USE_LUCID
10352 Display *dpy = dpyinfo->display;
10353 XrmValue d, fr, to;
10354 Font font;
10356 d.addr = (XPointer)&dpy;
10357 d.size = sizeof (Display *);
10358 fr.addr = XtDefaultFont;
10359 fr.size = sizeof (XtDefaultFont);
10360 to.size = sizeof (Font *);
10361 to.addr = (XPointer)&font;
10362 x_catch_errors (dpy);
10363 if (!XtCallConverter (dpy, XtCvtStringToFont, &d, 1, &fr, &to, NULL))
10364 abort ();
10365 if (x_had_errors_p (dpy) || !XQueryFont (dpy, font))
10366 XrmPutLineResource (&xrdb, "Emacs.dialog.*.font: 9x15");
10367 x_uncatch_errors ();
10369 #endif
10371 /* See if we should run in synchronous mode. This is useful
10372 for debugging X code. */
10374 Lisp_Object value;
10375 value = display_x_get_resource (dpyinfo,
10376 build_string ("synchronous"),
10377 build_string ("Synchronous"),
10378 Qnil, Qnil);
10379 if (STRINGP (value)
10380 && (!strcmp (SDATA (value), "true")
10381 || !strcmp (SDATA (value), "on")))
10382 XSynchronize (dpyinfo->display, True);
10386 Lisp_Object value;
10387 value = display_x_get_resource (dpyinfo,
10388 build_string ("useXIM"),
10389 build_string ("UseXIM"),
10390 Qnil, Qnil);
10391 #ifdef USE_XIM
10392 if (STRINGP (value)
10393 && (!strcmp (SDATA (value), "false")
10394 || !strcmp (SDATA (value), "off")))
10395 use_xim = 0;
10396 #else
10397 if (STRINGP (value)
10398 && (!strcmp (SDATA (value), "true")
10399 || !strcmp (SDATA (value), "on")))
10400 use_xim = 1;
10401 #endif
10404 #ifdef HAVE_X_SM
10405 /* Only do this for the very first display in the Emacs session.
10406 Ignore X session management when Emacs was first started on a
10407 tty. */
10408 if (terminal->id == 1)
10409 x_session_initialize (dpyinfo);
10410 #endif
10412 UNBLOCK_INPUT;
10414 return dpyinfo;
10417 /* Get rid of display DPYINFO, deleting all frames on it,
10418 and without sending any more commands to the X server. */
10420 void
10421 x_delete_display (struct x_display_info *dpyinfo)
10423 struct terminal *t;
10425 /* Close all frames and delete the generic struct terminal for this
10426 X display. */
10427 for (t = terminal_list; t; t = t->next_terminal)
10428 if (t->type == output_x_window && t->display_info.x == dpyinfo)
10430 #ifdef HAVE_X_SM
10431 /* Close X session management when we close its display. */
10432 if (t->id == 1 && x_session_have_connection ())
10433 x_session_close ();
10434 #endif
10435 delete_terminal (t);
10436 break;
10439 delete_keyboard_wait_descriptor (dpyinfo->connection);
10441 /* Discard this display from x_display_name_list and x_display_list.
10442 We can't use Fdelq because that can quit. */
10443 if (! NILP (x_display_name_list)
10444 && EQ (XCAR (x_display_name_list), dpyinfo->name_list_element))
10445 x_display_name_list = XCDR (x_display_name_list);
10446 else
10448 Lisp_Object tail;
10450 tail = x_display_name_list;
10451 while (CONSP (tail) && CONSP (XCDR (tail)))
10453 if (EQ (XCAR (XCDR (tail)), dpyinfo->name_list_element))
10455 XSETCDR (tail, XCDR (XCDR (tail)));
10456 break;
10458 tail = XCDR (tail);
10462 if (next_noop_dpyinfo == dpyinfo)
10463 next_noop_dpyinfo = dpyinfo->next;
10465 if (x_display_list == dpyinfo)
10466 x_display_list = dpyinfo->next;
10467 else
10469 struct x_display_info *tail;
10471 for (tail = x_display_list; tail; tail = tail->next)
10472 if (tail->next == dpyinfo)
10473 tail->next = tail->next->next;
10476 xfree (dpyinfo->x_id_name);
10477 xfree (dpyinfo->x_dnd_atoms);
10478 xfree (dpyinfo->color_cells);
10479 xfree (dpyinfo);
10482 #ifdef USE_X_TOOLKIT
10484 /* Atimer callback function for TIMER. Called every 0.1s to process
10485 Xt timeouts, if needed. We must avoid calling XtAppPending as
10486 much as possible because that function does an implicit XFlush
10487 that slows us down. */
10489 static void
10490 x_process_timeouts (struct atimer *timer)
10492 BLOCK_INPUT;
10493 x_timeout_atimer_activated_flag = 0;
10494 if (toolkit_scroll_bar_interaction || popup_activated ())
10496 while (XtAppPending (Xt_app_con) & XtIMTimer)
10497 XtAppProcessEvent (Xt_app_con, XtIMTimer);
10498 /* Reactivate the atimer for next time. */
10499 x_activate_timeout_atimer ();
10501 UNBLOCK_INPUT;
10504 /* Install an asynchronous timer that processes Xt timeout events
10505 every 0.1s as long as either `toolkit_scroll_bar_interaction' or
10506 `popup_activated_flag' (in xmenu.c) is set. Make sure to call this
10507 function whenever these variables are set. This is necessary
10508 because some widget sets use timeouts internally, for example the
10509 LessTif menu bar, or the Xaw3d scroll bar. When Xt timeouts aren't
10510 processed, these widgets don't behave normally. */
10512 void
10513 x_activate_timeout_atimer (void)
10515 BLOCK_INPUT;
10516 if (!x_timeout_atimer_activated_flag)
10518 EMACS_TIME interval;
10520 EMACS_SET_SECS_USECS (interval, 0, 100000);
10521 start_atimer (ATIMER_RELATIVE, interval, x_process_timeouts, 0);
10522 x_timeout_atimer_activated_flag = 1;
10524 UNBLOCK_INPUT;
10527 #endif /* USE_X_TOOLKIT */
10530 /* Set up use of X before we make the first connection. */
10532 extern frame_parm_handler x_frame_parm_handlers[];
10534 static struct redisplay_interface x_redisplay_interface =
10536 x_frame_parm_handlers,
10537 x_produce_glyphs,
10538 x_write_glyphs,
10539 x_insert_glyphs,
10540 x_clear_end_of_line,
10541 x_scroll_run,
10542 x_after_update_window_line,
10543 x_update_window_begin,
10544 x_update_window_end,
10545 x_cursor_to,
10546 x_flush,
10547 #ifdef XFlush
10548 x_flush,
10549 #else
10550 0, /* flush_display_optional */
10551 #endif
10552 x_clear_window_mouse_face,
10553 x_get_glyph_overhangs,
10554 x_fix_overlapping_area,
10555 x_draw_fringe_bitmap,
10556 0, /* define_fringe_bitmap */
10557 0, /* destroy_fringe_bitmap */
10558 x_compute_glyph_string_overhangs,
10559 x_draw_glyph_string,
10560 x_define_frame_cursor,
10561 x_clear_frame_area,
10562 x_draw_window_cursor,
10563 x_draw_vertical_window_border,
10564 x_shift_glyphs_for_insert
10568 /* This function is called when the last frame on a display is deleted. */
10569 void
10570 x_delete_terminal (struct terminal *terminal)
10572 struct x_display_info *dpyinfo = terminal->display_info.x;
10574 /* Protect against recursive calls. delete_frame in
10575 delete_terminal calls us back when it deletes our last frame. */
10576 if (!terminal->name)
10577 return;
10579 BLOCK_INPUT;
10580 #ifdef HAVE_X_I18N
10581 /* We must close our connection to the XIM server before closing the
10582 X display. */
10583 if (dpyinfo->xim)
10584 xim_close_dpy (dpyinfo);
10585 #endif
10587 /* If called from x_connection_closed, the display may already be closed
10588 and dpyinfo->display was set to 0 to indicate that. */
10589 if (dpyinfo->display)
10591 x_destroy_all_bitmaps (dpyinfo);
10592 XSetCloseDownMode (dpyinfo->display, DestroyAll);
10594 /* Whether or not XCloseDisplay destroys the associated resource
10595 database depends on the version of libX11. To avoid both
10596 crash and memory leak, we dissociate the database from the
10597 display and then destroy dpyinfo->xrdb ourselves.
10599 Unfortunately, the above strategy does not work in some
10600 situations due to a bug in newer versions of libX11: because
10601 XrmSetDatabase doesn't clear the flag XlibDisplayDfltRMDB if
10602 dpy->db is NULL, XCloseDisplay destroys the associated
10603 database whereas it has not been created by XGetDefault
10604 (Bug#21974 in freedesktop.org Bugzilla). As a workaround, we
10605 don't destroy the database here in order to avoid the crash
10606 in the above situations for now, though that may cause memory
10607 leaks in other situations. */
10608 #if 0
10609 #ifdef HAVE_XRMSETDATABASE
10610 XrmSetDatabase (dpyinfo->display, NULL);
10611 #else
10612 dpyinfo->display->db = NULL;
10613 #endif
10614 /* We used to call XrmDestroyDatabase from x_delete_display, but
10615 some older versions of libX11 crash if we call it after
10616 closing all the displays. */
10617 XrmDestroyDatabase (dpyinfo->xrdb);
10618 #endif
10620 #ifdef USE_GTK
10621 xg_display_close (dpyinfo->display);
10622 #else
10623 #ifdef USE_X_TOOLKIT
10624 XtCloseDisplay (dpyinfo->display);
10625 #else
10626 XCloseDisplay (dpyinfo->display);
10627 #endif
10628 #endif /* ! USE_GTK */
10631 /* Mark as dead. */
10632 dpyinfo->display = NULL;
10633 x_delete_display (dpyinfo);
10634 UNBLOCK_INPUT;
10637 /* Create a struct terminal, initialize it with the X11 specific
10638 functions and make DISPLAY->TERMINAL point to it. */
10640 static struct terminal *
10641 x_create_terminal (struct x_display_info *dpyinfo)
10643 struct terminal *terminal;
10645 terminal = create_terminal ();
10647 terminal->type = output_x_window;
10648 terminal->display_info.x = dpyinfo;
10649 dpyinfo->terminal = terminal;
10651 /* kboard is initialized in x_term_init. */
10653 terminal->clear_frame_hook = x_clear_frame;
10654 terminal->ins_del_lines_hook = x_ins_del_lines;
10655 terminal->delete_glyphs_hook = x_delete_glyphs;
10656 terminal->ring_bell_hook = XTring_bell;
10657 terminal->toggle_invisible_pointer_hook = XTtoggle_invisible_pointer;
10658 terminal->reset_terminal_modes_hook = XTreset_terminal_modes;
10659 terminal->set_terminal_modes_hook = XTset_terminal_modes;
10660 terminal->update_begin_hook = x_update_begin;
10661 terminal->update_end_hook = x_update_end;
10662 terminal->set_terminal_window_hook = XTset_terminal_window;
10663 terminal->read_socket_hook = XTread_socket;
10664 terminal->frame_up_to_date_hook = XTframe_up_to_date;
10665 terminal->mouse_position_hook = XTmouse_position;
10666 terminal->frame_rehighlight_hook = XTframe_rehighlight;
10667 terminal->frame_raise_lower_hook = XTframe_raise_lower;
10668 terminal->fullscreen_hook = XTfullscreen_hook;
10669 terminal->set_vertical_scroll_bar_hook = XTset_vertical_scroll_bar;
10670 terminal->condemn_scroll_bars_hook = XTcondemn_scroll_bars;
10671 terminal->redeem_scroll_bar_hook = XTredeem_scroll_bar;
10672 terminal->judge_scroll_bars_hook = XTjudge_scroll_bars;
10674 terminal->delete_frame_hook = x_destroy_window;
10675 terminal->delete_terminal_hook = x_delete_terminal;
10677 terminal->rif = &x_redisplay_interface;
10678 terminal->scroll_region_ok = 1; /* We'll scroll partial frames. */
10679 terminal->char_ins_del_ok = 1;
10680 terminal->line_ins_del_ok = 1; /* We'll just blt 'em. */
10681 terminal->fast_clear_end_of_line = 1; /* X does this well. */
10682 terminal->memory_below_frame = 0; /* We don't remember what scrolls
10683 off the bottom. */
10685 return terminal;
10688 void
10689 x_initialize (void)
10691 baud_rate = 19200;
10693 x_noop_count = 0;
10694 last_tool_bar_item = -1;
10695 any_help_event_p = 0;
10696 ignore_next_mouse_click_timeout = 0;
10697 #ifdef HAVE_X_SM
10698 x_session_initialized = 0;
10699 #endif
10701 #ifdef USE_GTK
10702 current_count = -1;
10703 #endif
10705 /* Try to use interrupt input; if we can't, then start polling. */
10706 Fset_input_interrupt_mode (Qt);
10708 #ifdef USE_X_TOOLKIT
10709 XtToolkitInitialize ();
10711 Xt_app_con = XtCreateApplicationContext ();
10713 /* Register a converter from strings to pixels, which uses
10714 Emacs' color allocation infrastructure. */
10715 XtAppSetTypeConverter (Xt_app_con,
10716 XtRString, XtRPixel, cvt_string_to_pixel,
10717 cvt_string_to_pixel_args,
10718 XtNumber (cvt_string_to_pixel_args),
10719 XtCacheByDisplay, cvt_pixel_dtor);
10721 XtAppSetFallbackResources (Xt_app_con, Xt_default_resources);
10722 #endif
10724 #ifdef USE_TOOLKIT_SCROLL_BARS
10725 #ifndef USE_GTK
10726 xaw3d_arrow_scroll = False;
10727 xaw3d_pick_top = True;
10728 #endif
10729 #endif
10731 pending_autoraise_frame = 0;
10732 pending_event_wait.f = 0;
10733 pending_event_wait.eventtype = 0;
10735 /* Note that there is no real way portable across R3/R4 to get the
10736 original error handler. */
10737 XSetErrorHandler (x_error_handler);
10738 XSetIOErrorHandler (x_io_error_quitter);
10740 signal (SIGPIPE, x_connection_signal);
10742 xgselect_initialize ();
10746 void
10747 syms_of_xterm (void)
10749 x_error_message = NULL;
10751 staticpro (&x_display_name_list);
10752 x_display_name_list = Qnil;
10754 staticpro (&last_mouse_scroll_bar);
10755 last_mouse_scroll_bar = Qnil;
10757 staticpro (&Qvendor_specific_keysyms);
10758 Qvendor_specific_keysyms = intern_c_string ("vendor-specific-keysyms");
10760 staticpro (&Qlatin_1);
10761 Qlatin_1 = intern_c_string ("latin-1");
10763 staticpro (&last_mouse_press_frame);
10764 last_mouse_press_frame = Qnil;
10766 #ifdef USE_GTK
10767 xg_default_icon_file = make_pure_c_string ("icons/hicolor/scalable/apps/emacs.svg");
10768 staticpro (&xg_default_icon_file);
10770 Qx_gtk_map_stock = intern_c_string ("x-gtk-map-stock");
10771 staticpro (&Qx_gtk_map_stock);
10772 #endif
10774 DEFVAR_BOOL ("x-use-underline-position-properties",
10775 &x_use_underline_position_properties,
10776 doc: /* *Non-nil means make use of UNDERLINE_POSITION font properties.
10777 A value of nil means ignore them. If you encounter fonts with bogus
10778 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
10779 to 4.1, set this to nil. You can also use `underline-minimum-offset'
10780 to override the font's UNDERLINE_POSITION for small font display
10781 sizes. */);
10782 x_use_underline_position_properties = 1;
10784 DEFVAR_BOOL ("x-underline-at-descent-line",
10785 &x_underline_at_descent_line,
10786 doc: /* *Non-nil means to draw the underline at the same place as the descent line.
10787 A value of nil means to draw the underline according to the value of the
10788 variable `x-use-underline-position-properties', which is usually at the
10789 baseline level. The default value is nil. */);
10790 x_underline_at_descent_line = 0;
10792 DEFVAR_BOOL ("x-mouse-click-focus-ignore-position",
10793 &x_mouse_click_focus_ignore_position,
10794 doc: /* Non-nil means that a mouse click to focus a frame does not move point.
10795 This variable is only used when the window manager requires that you
10796 click on a frame to select it (give it focus). In that case, a value
10797 of nil, means that the selected window and cursor position changes to
10798 reflect the mouse click position, while a non-nil value means that the
10799 selected window or cursor position is preserved. */);
10800 x_mouse_click_focus_ignore_position = 0;
10802 DEFVAR_LISP ("x-toolkit-scroll-bars", &Vx_toolkit_scroll_bars,
10803 doc: /* Which toolkit scroll bars Emacs uses, if any.
10804 A value of nil means Emacs doesn't use toolkit scroll bars.
10805 With the X Window system, the value is a symbol describing the
10806 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
10807 With MS Windows, the value is t. */);
10808 #ifdef USE_TOOLKIT_SCROLL_BARS
10809 #ifdef USE_MOTIF
10810 Vx_toolkit_scroll_bars = intern_c_string ("motif");
10811 #elif defined HAVE_XAW3D
10812 Vx_toolkit_scroll_bars = intern_c_string ("xaw3d");
10813 #elif USE_GTK
10814 Vx_toolkit_scroll_bars = intern_c_string ("gtk");
10815 #else
10816 Vx_toolkit_scroll_bars = intern_c_string ("xaw");
10817 #endif
10818 #else
10819 Vx_toolkit_scroll_bars = Qnil;
10820 #endif
10822 staticpro (&last_mouse_motion_frame);
10823 last_mouse_motion_frame = Qnil;
10825 Qmodifier_value = intern_c_string ("modifier-value");
10826 Qalt = intern_c_string ("alt");
10827 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
10828 Qhyper = intern_c_string ("hyper");
10829 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
10830 Qmeta = intern_c_string ("meta");
10831 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
10832 Qsuper = intern_c_string ("super");
10833 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
10835 DEFVAR_LISP ("x-alt-keysym", &Vx_alt_keysym,
10836 doc: /* Which keys Emacs uses for the alt modifier.
10837 This should be one of the symbols `alt', `hyper', `meta', `super'.
10838 For example, `alt' means use the Alt_L and Alt_R keysyms. The default
10839 is nil, which is the same as `alt'. */);
10840 Vx_alt_keysym = Qnil;
10842 DEFVAR_LISP ("x-hyper-keysym", &Vx_hyper_keysym,
10843 doc: /* Which keys Emacs uses for the hyper modifier.
10844 This should be one of the symbols `alt', `hyper', `meta', `super'.
10845 For example, `hyper' means use the Hyper_L and Hyper_R keysyms. The
10846 default is nil, which is the same as `hyper'. */);
10847 Vx_hyper_keysym = Qnil;
10849 DEFVAR_LISP ("x-meta-keysym", &Vx_meta_keysym,
10850 doc: /* Which keys Emacs uses for the meta modifier.
10851 This should be one of the symbols `alt', `hyper', `meta', `super'.
10852 For example, `meta' means use the Meta_L and Meta_R keysyms. The
10853 default is nil, which is the same as `meta'. */);
10854 Vx_meta_keysym = Qnil;
10856 DEFVAR_LISP ("x-super-keysym", &Vx_super_keysym,
10857 doc: /* Which keys Emacs uses for the super modifier.
10858 This should be one of the symbols `alt', `hyper', `meta', `super'.
10859 For example, `super' means use the Super_L and Super_R keysyms. The
10860 default is nil, which is the same as `super'. */);
10861 Vx_super_keysym = Qnil;
10863 DEFVAR_LISP ("x-keysym-table", &Vx_keysym_table,
10864 doc: /* Hash table of character codes indexed by X keysym codes. */);
10865 Vx_keysym_table = make_hash_table (Qeql, make_number (900),
10866 make_float (DEFAULT_REHASH_SIZE),
10867 make_float (DEFAULT_REHASH_THRESHOLD),
10868 Qnil, Qnil, Qnil);
10871 #endif /* HAVE_X_WINDOWS */