Use add/delete_read_fd in xsmfns to simplify. Also restart with initial_argv.
[emacs.git] / src / xterm.c
blob936a5f6b24ebe1939898a840adce2b5ff4a8ba98
1 /* X Communication module for terminals which understand the X protocol.
3 Copyright (C) 1989, 1993-2011 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 /* New display code by Gerd Moellmann <gerd@gnu.org>. */
21 /* Xt features made by Fred Pierresteguy. */
23 #include <config.h>
24 #include <signal.h>
25 #include <stdio.h>
26 #include <setjmp.h>
28 #ifdef HAVE_X_WINDOWS
30 #include "lisp.h"
31 #include "blockinput.h"
33 /* Need syssignal.h for various externs and definitions that may be required
34 by some configurations for calls to signal later in this source file. */
35 #include "syssignal.h"
37 /* This may include sys/types.h, and that somehow loses
38 if this is not done before the other system files. */
39 #include "xterm.h"
40 #include <X11/cursorfont.h>
42 /* Load sys/types.h if not already loaded.
43 In some systems loading it twice is suicidal. */
44 #ifndef makedev
45 #include <sys/types.h>
46 #endif /* makedev */
48 #include <sys/ioctl.h>
50 #include "systime.h"
52 #include <fcntl.h>
53 #include <ctype.h>
54 #include <errno.h>
55 #include <setjmp.h>
56 #include <sys/stat.h>
57 /* Caused redefinition of DBL_DIG on Netbsd; seems not to be needed. */
58 /* #include <sys/param.h> */
60 #include "charset.h"
61 #include "character.h"
62 #include "coding.h"
63 #include "frame.h"
64 #include "dispextern.h"
65 #include "fontset.h"
66 #include "termhooks.h"
67 #include "termopts.h"
68 #include "termchar.h"
69 #include "emacs-icon.h"
70 #include "disptab.h"
71 #include "buffer.h"
72 #include "window.h"
73 #include "keyboard.h"
74 #include "intervals.h"
75 #include "process.h"
76 #include "atimer.h"
77 #include "keymap.h"
78 #include "font.h"
79 #include "fontset.h"
80 #include "xsettings.h"
81 #include "xgselect.h"
82 #include "sysselect.h"
84 #ifdef USE_X_TOOLKIT
85 #include <X11/Shell.h>
86 #endif
88 #ifdef HAVE_SYS_TIME_H
89 #include <sys/time.h>
90 #endif
92 #include <unistd.h>
94 #ifdef USE_GTK
95 #include "gtkutil.h"
96 #endif
98 #ifdef USE_LUCID
99 #include "../lwlib/xlwmenu.h"
100 #endif
102 #ifdef USE_X_TOOLKIT
103 #if !defined(NO_EDITRES)
104 #define HACK_EDITRES
105 extern void _XEditResCheckMessages ();
106 #endif /* not NO_EDITRES */
108 /* Include toolkit specific headers for the scroll bar widget. */
110 #ifdef USE_TOOLKIT_SCROLL_BARS
111 #if defined USE_MOTIF
112 #include <Xm/Xm.h> /* for LESSTIF_VERSION */
113 #include <Xm/ScrollBar.h>
114 #else /* !USE_MOTIF i.e. use Xaw */
116 #ifdef HAVE_XAW3D
117 #include <X11/Xaw3d/Simple.h>
118 #include <X11/Xaw3d/Scrollbar.h>
119 #include <X11/Xaw3d/ThreeD.h>
120 #else /* !HAVE_XAW3D */
121 #include <X11/Xaw/Simple.h>
122 #include <X11/Xaw/Scrollbar.h>
123 #endif /* !HAVE_XAW3D */
124 #ifndef XtNpickTop
125 #define XtNpickTop "pickTop"
126 #endif /* !XtNpickTop */
127 #endif /* !USE_MOTIF */
128 #endif /* USE_TOOLKIT_SCROLL_BARS */
130 #endif /* USE_X_TOOLKIT */
132 #ifdef USE_X_TOOLKIT
133 #include "widget.h"
134 #ifndef XtNinitialState
135 #define XtNinitialState "initialState"
136 #endif
137 #endif
139 /* Default to using XIM if available. */
140 #ifdef USE_XIM
141 int use_xim = 1;
142 #else
143 int use_xim = 0; /* configure --without-xim */
144 #endif
148 /* Non-zero means that a HELP_EVENT has been generated since Emacs
149 start. */
151 static int any_help_event_p;
153 /* Last window where we saw the mouse. Used by mouse-autoselect-window. */
154 static Lisp_Object last_window;
156 /* This is a chain of structures for all the X displays currently in
157 use. */
159 struct x_display_info *x_display_list;
161 /* This is a list of cons cells, each of the form (NAME
162 . FONT-LIST-CACHE), one for each element of x_display_list and in
163 the same order. NAME is the name of the frame. FONT-LIST-CACHE
164 records previous values returned by x-list-fonts. */
166 Lisp_Object x_display_name_list;
168 /* Frame being updated by update_frame. This is declared in term.c.
169 This is set by update_begin and looked at by all the XT functions.
170 It is zero while not inside an update. In that case, the XT
171 functions assume that `selected_frame' is the frame to apply to. */
173 extern struct frame *updating_frame;
175 /* This is a frame waiting to be auto-raised, within XTread_socket. */
177 static struct frame *pending_autoraise_frame;
179 /* This is a frame waiting for an event matching mask, within XTread_socket. */
181 static struct {
182 struct frame *f;
183 int eventtype;
184 } pending_event_wait;
186 #ifdef USE_X_TOOLKIT
187 /* The application context for Xt use. */
188 XtAppContext Xt_app_con;
189 static String Xt_default_resources[] = {0};
190 #endif /* USE_X_TOOLKIT */
192 /* Non-zero means user is interacting with a toolkit scroll bar. */
194 static int toolkit_scroll_bar_interaction;
196 /* Non-zero timeout value means ignore next mouse click if it arrives
197 before that timeout elapses (i.e. as part of the same sequence of
198 events resulting from clicking on a frame to select it). */
200 static unsigned long ignore_next_mouse_click_timeout;
202 /* Mouse movement.
204 Formerly, we used PointerMotionHintMask (in standard_event_mask)
205 so that we would have to call XQueryPointer after each MotionNotify
206 event to ask for another such event. However, this made mouse tracking
207 slow, and there was a bug that made it eventually stop.
209 Simply asking for MotionNotify all the time seems to work better.
211 In order to avoid asking for motion events and then throwing most
212 of them away or busy-polling the server for mouse positions, we ask
213 the server for pointer motion hints. This means that we get only
214 one event per group of mouse movements. "Groups" are delimited by
215 other kinds of events (focus changes and button clicks, for
216 example), or by XQueryPointer calls; when one of these happens, we
217 get another MotionNotify event the next time the mouse moves. This
218 is at least as efficient as getting motion events when mouse
219 tracking is on, and I suspect only negligibly worse when tracking
220 is off. */
222 /* Where the mouse was last time we reported a mouse event. */
224 static XRectangle last_mouse_glyph;
225 static FRAME_PTR last_mouse_glyph_frame;
226 static Lisp_Object last_mouse_press_frame;
228 /* The scroll bar in which the last X motion event occurred.
230 If the last X motion event occurred in a scroll bar, we set this so
231 XTmouse_position can know whether to report a scroll bar motion or
232 an ordinary motion.
234 If the last X motion event didn't occur in a scroll bar, we set
235 this to Qnil, to tell XTmouse_position to return an ordinary motion
236 event. */
238 static Lisp_Object last_mouse_scroll_bar;
240 /* This is a hack. We would really prefer that XTmouse_position would
241 return the time associated with the position it returns, but there
242 doesn't seem to be any way to wrest the time-stamp from the server
243 along with the position query. So, we just keep track of the time
244 of the last movement we received, and return that in hopes that
245 it's somewhat accurate. */
247 static Time last_mouse_movement_time;
249 /* Time for last user interaction as returned in X events. */
251 static Time last_user_time;
253 /* Incremented by XTread_socket whenever it really tries to read
254 events. */
256 #ifdef __STDC__
257 static int volatile input_signal_count;
258 #else
259 static int input_signal_count;
260 #endif
262 /* Used locally within XTread_socket. */
264 static int x_noop_count;
266 static Lisp_Object Qalt, Qhyper, Qmeta, Qsuper, Qmodifier_value;
268 static Lisp_Object Qvendor_specific_keysyms;
269 static Lisp_Object Qlatin_1;
271 #ifdef USE_GTK
272 /* The name of the Emacs icon file. */
273 static Lisp_Object xg_default_icon_file;
275 /* Used in gtkutil.c. */
276 Lisp_Object Qx_gtk_map_stock;
277 #endif
279 /* Some functions take this as char *, not const char *. */
280 static char emacs_class[] = EMACS_CLASS;
282 /* XEmbed implementation. */
284 #define XEMBED_VERSION 0
286 enum xembed_info
288 XEMBED_MAPPED = 1 << 0
291 enum xembed_message
293 XEMBED_EMBEDDED_NOTIFY = 0,
294 XEMBED_WINDOW_ACTIVATE = 1,
295 XEMBED_WINDOW_DEACTIVATE = 2,
296 XEMBED_REQUEST_FOCUS = 3,
297 XEMBED_FOCUS_IN = 4,
298 XEMBED_FOCUS_OUT = 5,
299 XEMBED_FOCUS_NEXT = 6,
300 XEMBED_FOCUS_PREV = 7,
302 XEMBED_MODALITY_ON = 10,
303 XEMBED_MODALITY_OFF = 11,
304 XEMBED_REGISTER_ACCELERATOR = 12,
305 XEMBED_UNREGISTER_ACCELERATOR = 13,
306 XEMBED_ACTIVATE_ACCELERATOR = 14
309 /* Used in x_flush. */
311 static int x_alloc_nearest_color_1 (Display *, Colormap, XColor *);
312 static void x_set_window_size_1 (struct frame *, int, int, int);
313 static const XColor *x_color_cells (Display *, int *);
314 static void x_update_window_end (struct window *, int, int);
316 static int x_io_error_quitter (Display *);
317 static struct terminal *x_create_terminal (struct x_display_info *);
318 void x_delete_terminal (struct terminal *);
319 static void x_update_end (struct frame *);
320 static void XTframe_up_to_date (struct frame *);
321 static void XTset_terminal_modes (struct terminal *);
322 static void XTreset_terminal_modes (struct terminal *);
323 static void x_clear_frame (struct frame *);
324 static void frame_highlight (struct frame *);
325 static void frame_unhighlight (struct frame *);
326 static void x_new_focus_frame (struct x_display_info *, struct frame *);
327 static void x_focus_changed (int, int, struct x_display_info *,
328 struct frame *, struct input_event *);
329 static void x_detect_focus_change (struct x_display_info *,
330 XEvent *, struct input_event *);
331 static void XTframe_rehighlight (struct frame *);
332 static void x_frame_rehighlight (struct x_display_info *);
333 static void x_draw_hollow_cursor (struct window *, struct glyph_row *);
334 static void x_draw_bar_cursor (struct window *, struct glyph_row *, int,
335 enum text_cursor_kinds);
337 static void x_clip_to_row (struct window *, struct glyph_row *, int, GC);
338 static void x_flush (struct frame *f);
339 static void x_update_begin (struct frame *);
340 static void x_update_window_begin (struct window *);
341 static void x_after_update_window_line (struct glyph_row *);
342 static struct scroll_bar *x_window_to_scroll_bar (Display *, Window);
343 static void x_scroll_bar_report_motion (struct frame **, Lisp_Object *,
344 enum scroll_bar_part *,
345 Lisp_Object *, Lisp_Object *,
346 unsigned long *);
347 static void x_handle_net_wm_state (struct frame *, XPropertyEvent *);
348 static void x_check_fullscreen (struct frame *);
349 static void x_check_expected_move (struct frame *, int, int);
350 static void x_sync_with_move (struct frame *, int, int, int);
351 static int handle_one_xevent (struct x_display_info *, XEvent *,
352 int *, struct input_event *);
353 /* Don't declare this NO_RETURN because we want no
354 interference with debugging failing X calls. */
355 static SIGTYPE x_connection_closed (Display *, const char *);
358 /* Flush display of frame F, or of all frames if F is null. */
360 static void
361 x_flush (struct frame *f)
363 /* Don't call XFlush when it is not safe to redisplay; the X
364 connection may be broken. */
365 if (!NILP (Vinhibit_redisplay))
366 return;
368 BLOCK_INPUT;
369 if (f == NULL)
371 Lisp_Object rest, frame;
372 FOR_EACH_FRAME (rest, frame)
373 if (FRAME_X_P (XFRAME (frame)))
374 x_flush (XFRAME (frame));
376 else if (FRAME_X_P (f))
377 XFlush (FRAME_X_DISPLAY (f));
378 UNBLOCK_INPUT;
382 /* Remove calls to XFlush by defining XFlush to an empty replacement.
383 Calls to XFlush should be unnecessary because the X output buffer
384 is flushed automatically as needed by calls to XPending,
385 XNextEvent, or XWindowEvent according to the XFlush man page.
386 XTread_socket calls XPending. Removing XFlush improves
387 performance. */
389 #define XFlush(DISPLAY) (void) 0
392 /***********************************************************************
393 Debugging
394 ***********************************************************************/
396 #if 0
398 /* This is a function useful for recording debugging information about
399 the sequence of occurrences in this file. */
401 struct record
403 char *locus;
404 int type;
407 struct record event_record[100];
409 int event_record_index;
411 void
412 record_event (char *locus, int type)
414 if (event_record_index == sizeof (event_record) / sizeof (struct record))
415 event_record_index = 0;
417 event_record[event_record_index].locus = locus;
418 event_record[event_record_index].type = type;
419 event_record_index++;
422 #endif /* 0 */
426 /* Return the struct x_display_info corresponding to DPY. */
428 struct x_display_info *
429 x_display_info_for_display (Display *dpy)
431 struct x_display_info *dpyinfo;
433 for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
434 if (dpyinfo->display == dpy)
435 return dpyinfo;
437 return 0;
440 #define OPAQUE 0xffffffff
442 void
443 x_set_frame_alpha (struct frame *f)
445 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
446 Display *dpy = FRAME_X_DISPLAY (f);
447 Window win = FRAME_OUTER_WINDOW (f);
448 double alpha = 1.0;
449 double alpha_min = 1.0;
450 unsigned long opac;
452 if (FRAME_X_DISPLAY_INFO (f)->root_window != FRAME_X_OUTPUT (f)->parent_desc)
453 /* Since the WM decoration lies under the FRAME_OUTER_WINDOW,
454 we must treat the former instead of the latter. */
455 win = FRAME_X_OUTPUT (f)->parent_desc;
457 if (dpyinfo->x_highlight_frame == f)
458 alpha = f->alpha[0];
459 else
460 alpha = f->alpha[1];
462 if (FLOATP (Vframe_alpha_lower_limit))
463 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
464 else if (INTEGERP (Vframe_alpha_lower_limit))
465 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
467 if (alpha < 0.0)
468 return;
469 else if (alpha > 1.0)
470 alpha = 1.0;
471 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
472 alpha = alpha_min;
474 opac = alpha * OPAQUE;
476 /* return unless necessary */
478 unsigned char *data;
479 Atom actual;
480 int rc, format;
481 unsigned long n, left;
483 x_catch_errors (dpy);
484 rc = XGetWindowProperty (dpy, win, dpyinfo->Xatom_net_wm_window_opacity,
485 0L, 1L, False, XA_CARDINAL,
486 &actual, &format, &n, &left,
487 &data);
489 if (rc == Success && actual != None)
491 XFree ((void *) data);
492 if (*(unsigned long *)data == opac)
494 x_uncatch_errors ();
495 return;
498 x_uncatch_errors ();
501 x_catch_errors (dpy);
502 XChangeProperty (dpy, win, dpyinfo->Xatom_net_wm_window_opacity,
503 XA_CARDINAL, 32, PropModeReplace,
504 (unsigned char *) &opac, 1L);
505 x_uncatch_errors ();
509 x_display_pixel_height (struct x_display_info *dpyinfo)
511 return HeightOfScreen (dpyinfo->screen);
515 x_display_pixel_width (struct x_display_info *dpyinfo)
517 return WidthOfScreen (dpyinfo->screen);
521 /***********************************************************************
522 Starting and ending an update
523 ***********************************************************************/
525 /* Start an update of frame F. This function is installed as a hook
526 for update_begin, i.e. it is called when update_begin is called.
527 This function is called prior to calls to x_update_window_begin for
528 each window being updated. Currently, there is nothing to do here
529 because all interesting stuff is done on a window basis. */
531 static void
532 x_update_begin (struct frame *f)
534 /* Nothing to do. */
538 /* Start update of window W. Set the global variable updated_window
539 to the window being updated and set output_cursor to the cursor
540 position of W. */
542 static void
543 x_update_window_begin (struct window *w)
545 struct frame *f = XFRAME (WINDOW_FRAME (w));
546 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
548 updated_window = w;
549 set_output_cursor (&w->cursor);
551 BLOCK_INPUT;
553 if (f == hlinfo->mouse_face_mouse_frame)
555 /* Don't do highlighting for mouse motion during the update. */
556 hlinfo->mouse_face_defer = 1;
558 /* If F needs to be redrawn, simply forget about any prior mouse
559 highlighting. */
560 if (FRAME_GARBAGED_P (f))
561 hlinfo->mouse_face_window = Qnil;
564 UNBLOCK_INPUT;
568 /* Draw a vertical window border from (x,y0) to (x,y1) */
570 static void
571 x_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
573 struct frame *f = XFRAME (WINDOW_FRAME (w));
574 struct face *face;
576 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
577 if (face)
578 XSetForeground (FRAME_X_DISPLAY (f), f->output_data.x->normal_gc,
579 face->foreground);
581 XDrawLine (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
582 f->output_data.x->normal_gc, x, y0, x, y1);
585 /* End update of window W (which is equal to updated_window).
587 Draw vertical borders between horizontally adjacent windows, and
588 display W's cursor if CURSOR_ON_P is non-zero.
590 MOUSE_FACE_OVERWRITTEN_P non-zero means that some row containing
591 glyphs in mouse-face were overwritten. In that case we have to
592 make sure that the mouse-highlight is properly redrawn.
594 W may be a menu bar pseudo-window in case we don't have X toolkit
595 support. Such windows don't have a cursor, so don't display it
596 here. */
598 static void
599 x_update_window_end (struct window *w, int cursor_on_p, int mouse_face_overwritten_p)
601 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (XFRAME (w->frame));
603 if (!w->pseudo_window_p)
605 BLOCK_INPUT;
607 if (cursor_on_p)
608 display_and_set_cursor (w, 1, output_cursor.hpos,
609 output_cursor.vpos,
610 output_cursor.x, output_cursor.y);
612 if (draw_window_fringes (w, 1))
613 x_draw_vertical_border (w);
615 UNBLOCK_INPUT;
618 /* If a row with mouse-face was overwritten, arrange for
619 XTframe_up_to_date to redisplay the mouse highlight. */
620 if (mouse_face_overwritten_p)
622 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
623 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
624 hlinfo->mouse_face_window = Qnil;
627 updated_window = NULL;
631 /* End update of frame F. This function is installed as a hook in
632 update_end. */
634 static void
635 x_update_end (struct frame *f)
637 /* Mouse highlight may be displayed again. */
638 MOUSE_HL_INFO (f)->mouse_face_defer = 0;
640 #ifndef XFlush
641 BLOCK_INPUT;
642 XFlush (FRAME_X_DISPLAY (f));
643 UNBLOCK_INPUT;
644 #endif
648 /* This function is called from various places in xdisp.c whenever a
649 complete update has been performed. The global variable
650 updated_window is not available here. */
652 static void
653 XTframe_up_to_date (struct frame *f)
655 if (FRAME_X_P (f))
657 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
659 if (hlinfo->mouse_face_deferred_gc
660 || f == hlinfo->mouse_face_mouse_frame)
662 BLOCK_INPUT;
663 if (hlinfo->mouse_face_mouse_frame)
664 note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
665 hlinfo->mouse_face_mouse_x,
666 hlinfo->mouse_face_mouse_y);
667 hlinfo->mouse_face_deferred_gc = 0;
668 UNBLOCK_INPUT;
674 /* Draw truncation mark bitmaps, continuation mark bitmaps, overlay
675 arrow bitmaps, or clear the fringes if no bitmaps are required
676 before DESIRED_ROW is made current. The window being updated is
677 found in updated_window. This function It is called from
678 update_window_line only if it is known that there are differences
679 between bitmaps to be drawn between current row and DESIRED_ROW. */
681 static void
682 x_after_update_window_line (struct glyph_row *desired_row)
684 struct window *w = updated_window;
685 struct frame *f;
686 int width, height;
688 xassert (w);
690 if (!desired_row->mode_line_p && !w->pseudo_window_p)
691 desired_row->redraw_fringe_bitmaps_p = 1;
693 /* When a window has disappeared, make sure that no rest of
694 full-width rows stays visible in the internal border. Could
695 check here if updated_window is the leftmost/rightmost window,
696 but I guess it's not worth doing since vertically split windows
697 are almost never used, internal border is rarely set, and the
698 overhead is very small. */
699 if (windows_or_buffers_changed
700 && desired_row->full_width_p
701 && (f = XFRAME (w->frame),
702 width = FRAME_INTERNAL_BORDER_WIDTH (f),
703 width != 0)
704 && (height = desired_row->visible_height,
705 height > 0))
707 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
709 BLOCK_INPUT;
710 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
711 0, y, width, height, False);
712 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
713 FRAME_PIXEL_WIDTH (f) - width,
714 y, width, height, False);
715 UNBLOCK_INPUT;
719 static void
720 x_draw_fringe_bitmap (struct window *w, struct glyph_row *row, struct draw_fringe_bitmap_params *p)
722 struct frame *f = XFRAME (WINDOW_FRAME (w));
723 Display *display = FRAME_X_DISPLAY (f);
724 Window window = FRAME_X_WINDOW (f);
725 GC gc = f->output_data.x->normal_gc;
726 struct face *face = p->face;
728 /* Must clip because of partially visible lines. */
729 x_clip_to_row (w, row, -1, gc);
731 if (!p->overlay_p)
733 int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
735 /* In case the same realized face is used for fringes and
736 for something displayed in the text (e.g. face `region' on
737 mono-displays, the fill style may have been changed to
738 FillSolid in x_draw_glyph_string_background. */
739 if (face->stipple)
740 XSetFillStyle (display, face->gc, FillOpaqueStippled);
741 else
742 XSetForeground (display, face->gc, face->background);
744 #ifdef USE_TOOLKIT_SCROLL_BARS
745 /* If the fringe is adjacent to the left (right) scroll bar of a
746 leftmost (rightmost, respectively) window, then extend its
747 background to the gap between the fringe and the bar. */
748 if ((WINDOW_LEFTMOST_P (w)
749 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
750 || (WINDOW_RIGHTMOST_P (w)
751 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w)))
753 int sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
755 if (sb_width > 0)
757 int left = WINDOW_SCROLL_BAR_AREA_X (w);
758 int width = (WINDOW_CONFIG_SCROLL_BAR_COLS (w)
759 * FRAME_COLUMN_WIDTH (f));
761 if (bx < 0)
763 /* Bitmap fills the fringe. */
764 if (left + width == p->x)
765 bx = left + sb_width;
766 else if (p->x + p->wd == left)
767 bx = left;
768 if (bx >= 0)
770 int header_line_height = WINDOW_HEADER_LINE_HEIGHT (w);
772 nx = width - sb_width;
773 by = WINDOW_TO_FRAME_PIXEL_Y (w, max (header_line_height,
774 row->y));
775 ny = row->visible_height;
778 else
780 if (left + width == bx)
782 bx = left + sb_width;
783 nx += width - sb_width;
785 else if (bx + nx == left)
786 nx += width - sb_width;
790 #endif
791 if (bx >= 0 && nx > 0)
792 XFillRectangle (display, window, face->gc, bx, by, nx, ny);
794 if (!face->stipple)
795 XSetForeground (display, face->gc, face->foreground);
798 if (p->which)
800 unsigned char *bits;
801 Pixmap pixmap, clipmask = (Pixmap) 0;
802 int depth = DefaultDepthOfScreen (FRAME_X_SCREEN (f));
803 XGCValues gcv;
805 if (p->wd > 8)
806 bits = (unsigned char *)(p->bits + p->dh);
807 else
808 bits = (unsigned char *)p->bits + p->dh;
810 /* Draw the bitmap. I believe these small pixmaps can be cached
811 by the server. */
812 pixmap = XCreatePixmapFromBitmapData (display, window, bits, p->wd, p->h,
813 (p->cursor_p
814 ? (p->overlay_p ? face->background
815 : f->output_data.x->cursor_pixel)
816 : face->foreground),
817 face->background, depth);
819 if (p->overlay_p)
821 clipmask = XCreatePixmapFromBitmapData (display,
822 FRAME_X_DISPLAY_INFO (f)->root_window,
823 bits, p->wd, p->h,
824 1, 0, 1);
825 gcv.clip_mask = clipmask;
826 gcv.clip_x_origin = p->x;
827 gcv.clip_y_origin = p->y;
828 XChangeGC (display, gc, GCClipMask | GCClipXOrigin | GCClipYOrigin, &gcv);
831 XCopyArea (display, pixmap, window, gc, 0, 0,
832 p->wd, p->h, p->x, p->y);
833 XFreePixmap (display, pixmap);
835 if (p->overlay_p)
837 gcv.clip_mask = (Pixmap) 0;
838 XChangeGC (display, gc, GCClipMask, &gcv);
839 XFreePixmap (display, clipmask);
843 XSetClipMask (display, gc, None);
848 /* This is called when starting Emacs and when restarting after
849 suspend. When starting Emacs, no X window is mapped. And nothing
850 must be done to Emacs's own window if it is suspended (though that
851 rarely happens). */
853 static void
854 XTset_terminal_modes (struct terminal *terminal)
858 /* This is called when exiting or suspending Emacs. Exiting will make
859 the X-windows go away, and suspending requires no action. */
861 static void
862 XTreset_terminal_modes (struct terminal *terminal)
867 /***********************************************************************
868 Glyph display
869 ***********************************************************************/
873 static void x_set_glyph_string_clipping (struct glyph_string *);
874 static void x_set_glyph_string_gc (struct glyph_string *);
875 static void x_draw_glyph_string_background (struct glyph_string *,
876 int);
877 static void x_draw_glyph_string_foreground (struct glyph_string *);
878 static void x_draw_composite_glyph_string_foreground (struct glyph_string *);
879 static void x_draw_glyph_string_box (struct glyph_string *);
880 static void x_draw_glyph_string (struct glyph_string *);
881 static void x_compute_glyph_string_overhangs (struct glyph_string *);
882 static void x_set_cursor_gc (struct glyph_string *);
883 static void x_set_mode_line_face_gc (struct glyph_string *);
884 static void x_set_mouse_face_gc (struct glyph_string *);
885 static int x_alloc_lighter_color (struct frame *, Display *, Colormap,
886 unsigned long *, double, int);
887 static void x_setup_relief_color (struct frame *, struct relief *,
888 double, int, unsigned long);
889 static void x_setup_relief_colors (struct glyph_string *);
890 static void x_draw_image_glyph_string (struct glyph_string *);
891 static void x_draw_image_relief (struct glyph_string *);
892 static void x_draw_image_foreground (struct glyph_string *);
893 static void x_draw_image_foreground_1 (struct glyph_string *, Pixmap);
894 static void x_clear_glyph_string_rect (struct glyph_string *, int,
895 int, int, int);
896 static void x_draw_relief_rect (struct frame *, int, int, int, int,
897 int, int, int, int, int, int,
898 XRectangle *);
899 static void x_draw_box_rect (struct glyph_string *, int, int, int, int,
900 int, int, int, XRectangle *);
901 static void x_scroll_bar_clear (struct frame *);
903 #if GLYPH_DEBUG
904 static void x_check_font (struct frame *, struct font *);
905 #endif
908 /* Set S->gc to a suitable GC for drawing glyph string S in cursor
909 face. */
911 static void
912 x_set_cursor_gc (struct glyph_string *s)
914 if (s->font == FRAME_FONT (s->f)
915 && s->face->background == FRAME_BACKGROUND_PIXEL (s->f)
916 && s->face->foreground == FRAME_FOREGROUND_PIXEL (s->f)
917 && !s->cmp)
918 s->gc = s->f->output_data.x->cursor_gc;
919 else
921 /* Cursor on non-default face: must merge. */
922 XGCValues xgcv;
923 unsigned long mask;
925 xgcv.background = s->f->output_data.x->cursor_pixel;
926 xgcv.foreground = s->face->background;
928 /* If the glyph would be invisible, try a different foreground. */
929 if (xgcv.foreground == xgcv.background)
930 xgcv.foreground = s->face->foreground;
931 if (xgcv.foreground == xgcv.background)
932 xgcv.foreground = s->f->output_data.x->cursor_foreground_pixel;
933 if (xgcv.foreground == xgcv.background)
934 xgcv.foreground = s->face->foreground;
936 /* Make sure the cursor is distinct from text in this face. */
937 if (xgcv.background == s->face->background
938 && xgcv.foreground == s->face->foreground)
940 xgcv.background = s->face->foreground;
941 xgcv.foreground = s->face->background;
944 IF_DEBUG (x_check_font (s->f, s->font));
945 xgcv.graphics_exposures = False;
946 mask = GCForeground | GCBackground | GCGraphicsExposures;
948 if (FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc)
949 XChangeGC (s->display, FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc,
950 mask, &xgcv);
951 else
952 FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc
953 = XCreateGC (s->display, s->window, mask, &xgcv);
955 s->gc = FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc;
960 /* Set up S->gc of glyph string S for drawing text in mouse face. */
962 static void
963 x_set_mouse_face_gc (struct glyph_string *s)
965 int face_id;
966 struct face *face;
968 /* What face has to be used last for the mouse face? */
969 face_id = MOUSE_HL_INFO (s->f)->mouse_face_face_id;
970 face = FACE_FROM_ID (s->f, face_id);
971 if (face == NULL)
972 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
974 if (s->first_glyph->type == CHAR_GLYPH)
975 face_id = FACE_FOR_CHAR (s->f, face, s->first_glyph->u.ch, -1, Qnil);
976 else
977 face_id = FACE_FOR_CHAR (s->f, face, 0, -1, Qnil);
978 s->face = FACE_FROM_ID (s->f, face_id);
979 PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
981 if (s->font == s->face->font)
982 s->gc = s->face->gc;
983 else
985 /* Otherwise construct scratch_cursor_gc with values from FACE
986 except for FONT. */
987 XGCValues xgcv;
988 unsigned long mask;
990 xgcv.background = s->face->background;
991 xgcv.foreground = s->face->foreground;
992 xgcv.graphics_exposures = False;
993 mask = GCForeground | GCBackground | GCGraphicsExposures;
995 if (FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc)
996 XChangeGC (s->display, FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc,
997 mask, &xgcv);
998 else
999 FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc
1000 = XCreateGC (s->display, s->window, mask, &xgcv);
1002 s->gc = FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc;
1005 xassert (s->gc != 0);
1009 /* Set S->gc of glyph string S to a GC suitable for drawing a mode line.
1010 Faces to use in the mode line have already been computed when the
1011 matrix was built, so there isn't much to do, here. */
1013 static INLINE void
1014 x_set_mode_line_face_gc (struct glyph_string *s)
1016 s->gc = s->face->gc;
1020 /* Set S->gc of glyph string S for drawing that glyph string. Set
1021 S->stippled_p to a non-zero value if the face of S has a stipple
1022 pattern. */
1024 static INLINE void
1025 x_set_glyph_string_gc (struct glyph_string *s)
1027 PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
1029 if (s->hl == DRAW_NORMAL_TEXT)
1031 s->gc = s->face->gc;
1032 s->stippled_p = s->face->stipple != 0;
1034 else if (s->hl == DRAW_INVERSE_VIDEO)
1036 x_set_mode_line_face_gc (s);
1037 s->stippled_p = s->face->stipple != 0;
1039 else if (s->hl == DRAW_CURSOR)
1041 x_set_cursor_gc (s);
1042 s->stippled_p = 0;
1044 else if (s->hl == DRAW_MOUSE_FACE)
1046 x_set_mouse_face_gc (s);
1047 s->stippled_p = s->face->stipple != 0;
1049 else if (s->hl == DRAW_IMAGE_RAISED
1050 || s->hl == DRAW_IMAGE_SUNKEN)
1052 s->gc = s->face->gc;
1053 s->stippled_p = s->face->stipple != 0;
1055 else
1057 s->gc = s->face->gc;
1058 s->stippled_p = s->face->stipple != 0;
1061 /* GC must have been set. */
1062 xassert (s->gc != 0);
1066 /* Set clipping for output of glyph string S. S may be part of a mode
1067 line or menu if we don't have X toolkit support. */
1069 static INLINE void
1070 x_set_glyph_string_clipping (struct glyph_string *s)
1072 XRectangle *r = s->clip;
1073 int n = get_glyph_string_clip_rects (s, r, 2);
1075 if (n > 0)
1076 XSetClipRectangles (s->display, s->gc, 0, 0, r, n, Unsorted);
1077 s->num_clips = n;
1081 /* Set SRC's clipping for output of glyph string DST. This is called
1082 when we are drawing DST's left_overhang or right_overhang only in
1083 the area of SRC. */
1085 static void
1086 x_set_glyph_string_clipping_exactly (struct glyph_string *src, struct glyph_string *dst)
1088 XRectangle r;
1090 r.x = src->x;
1091 r.width = src->width;
1092 r.y = src->y;
1093 r.height = src->height;
1094 dst->clip[0] = r;
1095 dst->num_clips = 1;
1096 XSetClipRectangles (dst->display, dst->gc, 0, 0, &r, 1, Unsorted);
1100 /* RIF:
1101 Compute left and right overhang of glyph string S. */
1103 static void
1104 x_compute_glyph_string_overhangs (struct glyph_string *s)
1106 if (s->cmp == NULL
1107 && (s->first_glyph->type == CHAR_GLYPH
1108 || s->first_glyph->type == COMPOSITE_GLYPH))
1110 struct font_metrics metrics;
1112 if (s->first_glyph->type == CHAR_GLYPH)
1114 unsigned *code = alloca (sizeof (unsigned) * s->nchars);
1115 struct font *font = s->font;
1116 int i;
1118 for (i = 0; i < s->nchars; i++)
1119 code[i] = (s->char2b[i].byte1 << 8) | s->char2b[i].byte2;
1120 font->driver->text_extents (font, code, s->nchars, &metrics);
1122 else
1124 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1126 composition_gstring_width (gstring, s->cmp_from, s->cmp_to, &metrics);
1128 s->right_overhang = (metrics.rbearing > metrics.width
1129 ? metrics.rbearing - metrics.width : 0);
1130 s->left_overhang = metrics.lbearing < 0 ? - metrics.lbearing : 0;
1132 else if (s->cmp)
1134 s->right_overhang = s->cmp->rbearing - s->cmp->pixel_width;
1135 s->left_overhang = - s->cmp->lbearing;
1140 /* Fill rectangle X, Y, W, H with background color of glyph string S. */
1142 static INLINE void
1143 x_clear_glyph_string_rect (struct glyph_string *s, int x, int y, int w, int h)
1145 XGCValues xgcv;
1146 XGetGCValues (s->display, s->gc, GCForeground | GCBackground, &xgcv);
1147 XSetForeground (s->display, s->gc, xgcv.background);
1148 XFillRectangle (s->display, s->window, s->gc, x, y, w, h);
1149 XSetForeground (s->display, s->gc, xgcv.foreground);
1153 /* Draw the background of glyph_string S. If S->background_filled_p
1154 is non-zero don't draw it. FORCE_P non-zero means draw the
1155 background even if it wouldn't be drawn normally. This is used
1156 when a string preceding S draws into the background of S, or S
1157 contains the first component of a composition. */
1159 static void
1160 x_draw_glyph_string_background (struct glyph_string *s, int force_p)
1162 /* Nothing to do if background has already been drawn or if it
1163 shouldn't be drawn in the first place. */
1164 if (!s->background_filled_p)
1166 int box_line_width = max (s->face->box_line_width, 0);
1168 if (s->stippled_p)
1170 /* Fill background with a stipple pattern. */
1171 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
1172 XFillRectangle (s->display, s->window, s->gc, s->x,
1173 s->y + box_line_width,
1174 s->background_width,
1175 s->height - 2 * box_line_width);
1176 XSetFillStyle (s->display, s->gc, FillSolid);
1177 s->background_filled_p = 1;
1179 else if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
1180 || s->font_not_found_p
1181 || s->extends_to_end_of_line_p
1182 || force_p)
1184 x_clear_glyph_string_rect (s, s->x, s->y + box_line_width,
1185 s->background_width,
1186 s->height - 2 * box_line_width);
1187 s->background_filled_p = 1;
1193 /* Draw the foreground of glyph string S. */
1195 static void
1196 x_draw_glyph_string_foreground (struct glyph_string *s)
1198 int i, x;
1200 /* If first glyph of S has a left box line, start drawing the text
1201 of S to the right of that box line. */
1202 if (s->face->box != FACE_NO_BOX
1203 && s->first_glyph->left_box_line_p)
1204 x = s->x + eabs (s->face->box_line_width);
1205 else
1206 x = s->x;
1208 /* Draw characters of S as rectangles if S's font could not be
1209 loaded. */
1210 if (s->font_not_found_p)
1212 for (i = 0; i < s->nchars; ++i)
1214 struct glyph *g = s->first_glyph + i;
1215 XDrawRectangle (s->display, s->window,
1216 s->gc, x, s->y, g->pixel_width - 1,
1217 s->height - 1);
1218 x += g->pixel_width;
1221 else
1223 struct font *font = s->font;
1224 int boff = font->baseline_offset;
1225 int y;
1227 if (font->vertical_centering)
1228 boff = VCENTER_BASELINE_OFFSET (font, s->f) - boff;
1230 y = s->ybase - boff;
1231 if (s->for_overlaps
1232 || (s->background_filled_p && s->hl != DRAW_CURSOR))
1233 font->driver->draw (s, 0, s->nchars, x, y, 0);
1234 else
1235 font->driver->draw (s, 0, s->nchars, x, y, 1);
1236 if (s->face->overstrike)
1237 font->driver->draw (s, 0, s->nchars, x + 1, y, 0);
1241 /* Draw the foreground of composite glyph string S. */
1243 static void
1244 x_draw_composite_glyph_string_foreground (struct glyph_string *s)
1246 int i, j, x;
1247 struct font *font = s->font;
1249 /* If first glyph of S has a left box line, start drawing the text
1250 of S to the right of that box line. */
1251 if (s->face && s->face->box != FACE_NO_BOX
1252 && s->first_glyph->left_box_line_p)
1253 x = s->x + eabs (s->face->box_line_width);
1254 else
1255 x = s->x;
1257 /* S is a glyph string for a composition. S->cmp_from is the index
1258 of the first character drawn for glyphs of this composition.
1259 S->cmp_from == 0 means we are drawing the very first character of
1260 this composition. */
1262 /* Draw a rectangle for the composition if the font for the very
1263 first character of the composition could not be loaded. */
1264 if (s->font_not_found_p)
1266 if (s->cmp_from == 0)
1267 XDrawRectangle (s->display, s->window, s->gc, x, s->y,
1268 s->width - 1, s->height - 1);
1270 else if (! s->first_glyph->u.cmp.automatic)
1272 int y = s->ybase;
1274 for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
1275 if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
1277 int xx = x + s->cmp->offsets[j * 2];
1278 int yy = y - s->cmp->offsets[j * 2 + 1];
1280 font->driver->draw (s, j, j + 1, xx, yy, 0);
1281 if (s->face->overstrike)
1282 font->driver->draw (s, j, j + 1, xx + 1, yy, 0);
1285 else
1287 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1288 Lisp_Object glyph;
1289 int y = s->ybase;
1290 int width = 0;
1292 for (i = j = s->cmp_from; i < s->cmp_to; i++)
1294 glyph = LGSTRING_GLYPH (gstring, i);
1295 if (NILP (LGLYPH_ADJUSTMENT (glyph)))
1296 width += LGLYPH_WIDTH (glyph);
1297 else
1299 int xoff, yoff, wadjust;
1301 if (j < i)
1303 font->driver->draw (s, j, i, x, y, 0);
1304 if (s->face->overstrike)
1305 font->driver->draw (s, j, i, x + 1, y, 0);
1306 x += width;
1308 xoff = LGLYPH_XOFF (glyph);
1309 yoff = LGLYPH_YOFF (glyph);
1310 wadjust = LGLYPH_WADJUST (glyph);
1311 font->driver->draw (s, i, i + 1, x + xoff, y + yoff, 0);
1312 if (s->face->overstrike)
1313 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff, 0);
1314 x += wadjust;
1315 j = i + 1;
1316 width = 0;
1319 if (j < i)
1321 font->driver->draw (s, j, i, x, y, 0);
1322 if (s->face->overstrike)
1323 font->driver->draw (s, j, i, x + 1, y, 0);
1329 /* Draw the foreground of glyph string S for glyphless characters. */
1331 static void
1332 x_draw_glyphless_glyph_string_foreground (struct glyph_string *s)
1334 struct glyph *glyph = s->first_glyph;
1335 XChar2b char2b[8];
1336 int x, i, j;
1338 /* If first glyph of S has a left box line, start drawing the text
1339 of S to the right of that box line. */
1340 if (s->face && s->face->box != FACE_NO_BOX
1341 && s->first_glyph->left_box_line_p)
1342 x = s->x + eabs (s->face->box_line_width);
1343 else
1344 x = s->x;
1346 s->char2b = char2b;
1348 for (i = 0; i < s->nchars; i++, glyph++)
1350 char buf[7], *str = NULL;
1351 int len = glyph->u.glyphless.len;
1353 if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_ACRONYM)
1355 if (len > 0
1356 && CHAR_TABLE_P (Vglyphless_char_display)
1357 && (CHAR_TABLE_EXTRA_SLOTS (XCHAR_TABLE (Vglyphless_char_display))
1358 >= 1))
1360 Lisp_Object acronym
1361 = (! glyph->u.glyphless.for_no_font
1362 ? CHAR_TABLE_REF (Vglyphless_char_display,
1363 glyph->u.glyphless.ch)
1364 : XCHAR_TABLE (Vglyphless_char_display)->extras[0]);
1365 if (STRINGP (acronym))
1366 str = SSDATA (acronym);
1369 else if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_HEX_CODE)
1371 sprintf ((char *) buf, "%0*X",
1372 glyph->u.glyphless.ch < 0x10000 ? 4 : 6,
1373 glyph->u.glyphless.ch);
1374 str = buf;
1377 if (str)
1379 int upper_len = (len + 1) / 2;
1380 unsigned code;
1382 /* It is assured that all LEN characters in STR is ASCII. */
1383 for (j = 0; j < len; j++)
1385 code = s->font->driver->encode_char (s->font, str[j]);
1386 STORE_XCHAR2B (char2b + j, code >> 8, code & 0xFF);
1388 s->font->driver->draw (s, 0, upper_len,
1389 x + glyph->slice.glyphless.upper_xoff,
1390 s->ybase + glyph->slice.glyphless.upper_yoff,
1392 s->font->driver->draw (s, upper_len, len,
1393 x + glyph->slice.glyphless.lower_xoff,
1394 s->ybase + glyph->slice.glyphless.lower_yoff,
1397 if (glyph->u.glyphless.method != GLYPHLESS_DISPLAY_THIN_SPACE)
1398 XDrawRectangle (s->display, s->window, s->gc,
1399 x, s->ybase - glyph->ascent,
1400 glyph->pixel_width - 1,
1401 glyph->ascent + glyph->descent - 1);
1402 x += glyph->pixel_width;
1406 #ifdef USE_X_TOOLKIT
1408 static struct frame *x_frame_of_widget (Widget);
1409 static Boolean cvt_string_to_pixel (Display *, XrmValue *, Cardinal *,
1410 XrmValue *, XrmValue *, XtPointer *);
1411 static void cvt_pixel_dtor (XtAppContext, XrmValue *, XtPointer,
1412 XrmValue *, Cardinal *);
1415 /* Return the frame on which widget WIDGET is used.. Abort if frame
1416 cannot be determined. */
1418 static struct frame *
1419 x_frame_of_widget (Widget widget)
1421 struct x_display_info *dpyinfo;
1422 Lisp_Object tail;
1423 struct frame *f;
1425 dpyinfo = x_display_info_for_display (XtDisplay (widget));
1427 /* Find the top-level shell of the widget. Note that this function
1428 can be called when the widget is not yet realized, so XtWindow
1429 (widget) == 0. That's the reason we can't simply use
1430 x_any_window_to_frame. */
1431 while (!XtIsTopLevelShell (widget))
1432 widget = XtParent (widget);
1434 /* Look for a frame with that top-level widget. Allocate the color
1435 on that frame to get the right gamma correction value. */
1436 for (tail = Vframe_list; CONSP (tail); tail = XCDR (tail))
1437 if (FRAMEP (XCAR (tail))
1438 && (f = XFRAME (XCAR (tail)),
1439 (FRAME_X_P (f)
1440 && f->output_data.nothing != 1
1441 && FRAME_X_DISPLAY_INFO (f) == dpyinfo))
1442 && f->output_data.x->widget == widget)
1443 return f;
1445 abort ();
1449 /* Allocate the color COLOR->pixel on the screen and display of
1450 widget WIDGET in colormap CMAP. If an exact match cannot be
1451 allocated, try the nearest color available. Value is non-zero
1452 if successful. This is called from lwlib. */
1455 x_alloc_nearest_color_for_widget (Widget widget, Colormap cmap, XColor *color)
1457 struct frame *f = x_frame_of_widget (widget);
1458 return x_alloc_nearest_color (f, cmap, color);
1462 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
1463 or DELTA. Try a color with RGB values multiplied by FACTOR first.
1464 If this produces the same color as PIXEL, try a color where all RGB
1465 values have DELTA added. Return the allocated color in *PIXEL.
1466 DISPLAY is the X display, CMAP is the colormap to operate on.
1467 Value is non-zero if successful. */
1470 x_alloc_lighter_color_for_widget (Widget widget, Display *display, Colormap cmap,
1471 unsigned long *pixel, double factor, int delta)
1473 struct frame *f = x_frame_of_widget (widget);
1474 return x_alloc_lighter_color (f, display, cmap, pixel, factor, delta);
1478 /* Structure specifying which arguments should be passed by Xt to
1479 cvt_string_to_pixel. We want the widget's screen and colormap. */
1481 static XtConvertArgRec cvt_string_to_pixel_args[] =
1483 {XtWidgetBaseOffset, (XtPointer) XtOffset (Widget, core.screen),
1484 sizeof (Screen *)},
1485 {XtWidgetBaseOffset, (XtPointer) XtOffset (Widget, core.colormap),
1486 sizeof (Colormap)}
1490 /* The address of this variable is returned by
1491 cvt_string_to_pixel. */
1493 static Pixel cvt_string_to_pixel_value;
1496 /* Convert a color name to a pixel color.
1498 DPY is the display we are working on.
1500 ARGS is an array of *NARGS XrmValue structures holding additional
1501 information about the widget for which the conversion takes place.
1502 The contents of this array are determined by the specification
1503 in cvt_string_to_pixel_args.
1505 FROM is a pointer to an XrmValue which points to the color name to
1506 convert. TO is an XrmValue in which to return the pixel color.
1508 CLOSURE_RET is a pointer to user-data, in which we record if
1509 we allocated the color or not.
1511 Value is True if successful, False otherwise. */
1513 static Boolean
1514 cvt_string_to_pixel (Display *dpy, XrmValue *args, Cardinal *nargs,
1515 XrmValue *from, XrmValue *to,
1516 XtPointer *closure_ret)
1518 Screen *screen;
1519 Colormap cmap;
1520 Pixel pixel;
1521 String color_name;
1522 XColor color;
1524 if (*nargs != 2)
1526 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
1527 "wrongParameters", "cvt_string_to_pixel",
1528 "XtToolkitError",
1529 "Screen and colormap args required", NULL, NULL);
1530 return False;
1533 screen = *(Screen **) args[0].addr;
1534 cmap = *(Colormap *) args[1].addr;
1535 color_name = (String) from->addr;
1537 if (strcmp (color_name, XtDefaultBackground) == 0)
1539 *closure_ret = (XtPointer) False;
1540 pixel = WhitePixelOfScreen (screen);
1542 else if (strcmp (color_name, XtDefaultForeground) == 0)
1544 *closure_ret = (XtPointer) False;
1545 pixel = BlackPixelOfScreen (screen);
1547 else if (XParseColor (dpy, cmap, color_name, &color)
1548 && x_alloc_nearest_color_1 (dpy, cmap, &color))
1550 pixel = color.pixel;
1551 *closure_ret = (XtPointer) True;
1553 else
1555 String params[1];
1556 Cardinal nparams = 1;
1558 params[0] = color_name;
1559 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
1560 "badValue", "cvt_string_to_pixel",
1561 "XtToolkitError", "Invalid color `%s'",
1562 params, &nparams);
1563 return False;
1566 if (to->addr != NULL)
1568 if (to->size < sizeof (Pixel))
1570 to->size = sizeof (Pixel);
1571 return False;
1574 *(Pixel *) to->addr = pixel;
1576 else
1578 cvt_string_to_pixel_value = pixel;
1579 to->addr = (XtPointer) &cvt_string_to_pixel_value;
1582 to->size = sizeof (Pixel);
1583 return True;
1587 /* Free a pixel color which was previously allocated via
1588 cvt_string_to_pixel. This is registered as the destructor
1589 for this type of resource via XtSetTypeConverter.
1591 APP is the application context in which we work.
1593 TO is a pointer to an XrmValue holding the color to free.
1594 CLOSURE is the value we stored in CLOSURE_RET for this color
1595 in cvt_string_to_pixel.
1597 ARGS and NARGS are like for cvt_string_to_pixel. */
1599 static void
1600 cvt_pixel_dtor (XtAppContext app, XrmValuePtr to, XtPointer closure, XrmValuePtr args,
1601 Cardinal *nargs)
1603 if (*nargs != 2)
1605 XtAppWarningMsg (app, "wrongParameters", "cvt_pixel_dtor",
1606 "XtToolkitError",
1607 "Screen and colormap arguments required",
1608 NULL, NULL);
1610 else if (closure != NULL)
1612 /* We did allocate the pixel, so free it. */
1613 Screen *screen = *(Screen **) args[0].addr;
1614 Colormap cmap = *(Colormap *) args[1].addr;
1615 x_free_dpy_colors (DisplayOfScreen (screen), screen, cmap,
1616 (Pixel *) to->addr, 1);
1621 #endif /* USE_X_TOOLKIT */
1624 /* Value is an array of XColor structures for the contents of the
1625 color map of display DPY. Set *NCELLS to the size of the array.
1626 Note that this probably shouldn't be called for large color maps,
1627 say a 24-bit TrueColor map. */
1629 static const XColor *
1630 x_color_cells (Display *dpy, int *ncells)
1632 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
1634 if (dpyinfo->color_cells == NULL)
1636 Screen *screen = dpyinfo->screen;
1637 int i;
1639 dpyinfo->ncolor_cells
1640 = XDisplayCells (dpy, XScreenNumberOfScreen (screen));
1641 dpyinfo->color_cells
1642 = (XColor *) xmalloc (dpyinfo->ncolor_cells
1643 * sizeof *dpyinfo->color_cells);
1645 for (i = 0; i < dpyinfo->ncolor_cells; ++i)
1646 dpyinfo->color_cells[i].pixel = i;
1648 XQueryColors (dpy, dpyinfo->cmap,
1649 dpyinfo->color_cells, dpyinfo->ncolor_cells);
1652 *ncells = dpyinfo->ncolor_cells;
1653 return dpyinfo->color_cells;
1657 /* On frame F, translate pixel colors to RGB values for the NCOLORS
1658 colors in COLORS. Use cached information, if available. */
1660 void
1661 x_query_colors (struct frame *f, XColor *colors, int ncolors)
1663 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
1665 if (dpyinfo->color_cells)
1667 int i;
1668 for (i = 0; i < ncolors; ++i)
1670 unsigned long pixel = colors[i].pixel;
1671 xassert (pixel < dpyinfo->ncolor_cells);
1672 xassert (dpyinfo->color_cells[pixel].pixel == pixel);
1673 colors[i] = dpyinfo->color_cells[pixel];
1676 else
1677 XQueryColors (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), colors, ncolors);
1681 /* On frame F, translate pixel color to RGB values for the color in
1682 COLOR. Use cached information, if available. */
1684 void
1685 x_query_color (struct frame *f, XColor *color)
1687 x_query_colors (f, color, 1);
1691 /* Allocate the color COLOR->pixel on DISPLAY, colormap CMAP. If an
1692 exact match can't be allocated, try the nearest color available.
1693 Value is non-zero if successful. Set *COLOR to the color
1694 allocated. */
1696 static int
1697 x_alloc_nearest_color_1 (Display *dpy, Colormap cmap, XColor *color)
1699 int rc;
1701 rc = XAllocColor (dpy, cmap, color);
1702 if (rc == 0)
1704 /* If we got to this point, the colormap is full, so we're going
1705 to try to get the next closest color. The algorithm used is
1706 a least-squares matching, which is what X uses for closest
1707 color matching with StaticColor visuals. */
1708 int nearest, i;
1709 unsigned long nearest_delta = ~0;
1710 int ncells;
1711 const XColor *cells = x_color_cells (dpy, &ncells);
1713 for (nearest = i = 0; i < ncells; ++i)
1715 long dred = (color->red >> 8) - (cells[i].red >> 8);
1716 long dgreen = (color->green >> 8) - (cells[i].green >> 8);
1717 long dblue = (color->blue >> 8) - (cells[i].blue >> 8);
1718 unsigned long delta = dred * dred + dgreen * dgreen + dblue * dblue;
1720 if (delta < nearest_delta)
1722 nearest = i;
1723 nearest_delta = delta;
1727 color->red = cells[nearest].red;
1728 color->green = cells[nearest].green;
1729 color->blue = cells[nearest].blue;
1730 rc = XAllocColor (dpy, cmap, color);
1732 else
1734 /* If allocation succeeded, and the allocated pixel color is not
1735 equal to a cached pixel color recorded earlier, there was a
1736 change in the colormap, so clear the color cache. */
1737 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
1738 XColor *cached_color;
1740 if (dpyinfo->color_cells
1741 && (cached_color = &dpyinfo->color_cells[color->pixel],
1742 (cached_color->red != color->red
1743 || cached_color->blue != color->blue
1744 || cached_color->green != color->green)))
1746 xfree (dpyinfo->color_cells);
1747 dpyinfo->color_cells = NULL;
1748 dpyinfo->ncolor_cells = 0;
1752 #ifdef DEBUG_X_COLORS
1753 if (rc)
1754 register_color (color->pixel);
1755 #endif /* DEBUG_X_COLORS */
1757 return rc;
1761 /* Allocate the color COLOR->pixel on frame F, colormap CMAP. If an
1762 exact match can't be allocated, try the nearest color available.
1763 Value is non-zero if successful. Set *COLOR to the color
1764 allocated. */
1767 x_alloc_nearest_color (struct frame *f, Colormap cmap, XColor *color)
1769 gamma_correct (f, color);
1770 return x_alloc_nearest_color_1 (FRAME_X_DISPLAY (f), cmap, color);
1774 /* Allocate color PIXEL on frame F. PIXEL must already be allocated.
1775 It's necessary to do this instead of just using PIXEL directly to
1776 get color reference counts right. */
1778 unsigned long
1779 x_copy_color (struct frame *f, long unsigned int pixel)
1781 XColor color;
1783 color.pixel = pixel;
1784 BLOCK_INPUT;
1785 x_query_color (f, &color);
1786 XAllocColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &color);
1787 UNBLOCK_INPUT;
1788 #ifdef DEBUG_X_COLORS
1789 register_color (pixel);
1790 #endif
1791 return color.pixel;
1795 /* Allocate color PIXEL on display DPY. PIXEL must already be allocated.
1796 It's necessary to do this instead of just using PIXEL directly to
1797 get color reference counts right. */
1799 unsigned long
1800 x_copy_dpy_color (Display *dpy, Colormap cmap, long unsigned int pixel)
1802 XColor color;
1804 color.pixel = pixel;
1805 BLOCK_INPUT;
1806 XQueryColor (dpy, cmap, &color);
1807 XAllocColor (dpy, cmap, &color);
1808 UNBLOCK_INPUT;
1809 #ifdef DEBUG_X_COLORS
1810 register_color (pixel);
1811 #endif
1812 return color.pixel;
1816 /* Brightness beyond which a color won't have its highlight brightness
1817 boosted.
1819 Nominally, highlight colors for `3d' faces are calculated by
1820 brightening an object's color by a constant scale factor, but this
1821 doesn't yield good results for dark colors, so for colors who's
1822 brightness is less than this value (on a scale of 0-65535) have an
1823 use an additional additive factor.
1825 The value here is set so that the default menu-bar/mode-line color
1826 (grey75) will not have its highlights changed at all. */
1827 #define HIGHLIGHT_COLOR_DARK_BOOST_LIMIT 48000
1830 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
1831 or DELTA. Try a color with RGB values multiplied by FACTOR first.
1832 If this produces the same color as PIXEL, try a color where all RGB
1833 values have DELTA added. Return the allocated color in *PIXEL.
1834 DISPLAY is the X display, CMAP is the colormap to operate on.
1835 Value is non-zero if successful. */
1837 static int
1838 x_alloc_lighter_color (struct frame *f, Display *display, Colormap cmap, long unsigned int *pixel, double factor, int delta)
1840 XColor color, new;
1841 long bright;
1842 int success_p;
1844 /* Get RGB color values. */
1845 color.pixel = *pixel;
1846 x_query_color (f, &color);
1848 /* Change RGB values by specified FACTOR. Avoid overflow! */
1849 xassert (factor >= 0);
1850 new.red = min (0xffff, factor * color.red);
1851 new.green = min (0xffff, factor * color.green);
1852 new.blue = min (0xffff, factor * color.blue);
1854 /* Calculate brightness of COLOR. */
1855 bright = (2 * color.red + 3 * color.green + color.blue) / 6;
1857 /* We only boost colors that are darker than
1858 HIGHLIGHT_COLOR_DARK_BOOST_LIMIT. */
1859 if (bright < HIGHLIGHT_COLOR_DARK_BOOST_LIMIT)
1860 /* Make an additive adjustment to NEW, because it's dark enough so
1861 that scaling by FACTOR alone isn't enough. */
1863 /* How far below the limit this color is (0 - 1, 1 being darker). */
1864 double dimness = 1 - (double)bright / HIGHLIGHT_COLOR_DARK_BOOST_LIMIT;
1865 /* The additive adjustment. */
1866 int min_delta = delta * dimness * factor / 2;
1868 if (factor < 1)
1870 new.red = max (0, new.red - min_delta);
1871 new.green = max (0, new.green - min_delta);
1872 new.blue = max (0, new.blue - min_delta);
1874 else
1876 new.red = min (0xffff, min_delta + new.red);
1877 new.green = min (0xffff, min_delta + new.green);
1878 new.blue = min (0xffff, min_delta + new.blue);
1882 /* Try to allocate the color. */
1883 success_p = x_alloc_nearest_color (f, cmap, &new);
1884 if (success_p)
1886 if (new.pixel == *pixel)
1888 /* If we end up with the same color as before, try adding
1889 delta to the RGB values. */
1890 x_free_colors (f, &new.pixel, 1);
1892 new.red = min (0xffff, delta + color.red);
1893 new.green = min (0xffff, delta + color.green);
1894 new.blue = min (0xffff, delta + color.blue);
1895 success_p = x_alloc_nearest_color (f, cmap, &new);
1897 else
1898 success_p = 1;
1899 *pixel = new.pixel;
1902 return success_p;
1906 /* Set up the foreground color for drawing relief lines of glyph
1907 string S. RELIEF is a pointer to a struct relief containing the GC
1908 with which lines will be drawn. Use a color that is FACTOR or
1909 DELTA lighter or darker than the relief's background which is found
1910 in S->f->output_data.x->relief_background. If such a color cannot
1911 be allocated, use DEFAULT_PIXEL, instead. */
1913 static void
1914 x_setup_relief_color (struct frame *f, struct relief *relief, double factor, int delta, long unsigned int default_pixel)
1916 XGCValues xgcv;
1917 struct x_output *di = f->output_data.x;
1918 unsigned long mask = GCForeground | GCLineWidth | GCGraphicsExposures;
1919 unsigned long pixel;
1920 unsigned long background = di->relief_background;
1921 Colormap cmap = FRAME_X_COLORMAP (f);
1922 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
1923 Display *dpy = FRAME_X_DISPLAY (f);
1925 xgcv.graphics_exposures = False;
1926 xgcv.line_width = 1;
1928 /* Free previously allocated color. The color cell will be reused
1929 when it has been freed as many times as it was allocated, so this
1930 doesn't affect faces using the same colors. */
1931 if (relief->gc
1932 && relief->allocated_p)
1934 x_free_colors (f, &relief->pixel, 1);
1935 relief->allocated_p = 0;
1938 /* Allocate new color. */
1939 xgcv.foreground = default_pixel;
1940 pixel = background;
1941 if (dpyinfo->n_planes != 1
1942 && x_alloc_lighter_color (f, dpy, cmap, &pixel, factor, delta))
1944 relief->allocated_p = 1;
1945 xgcv.foreground = relief->pixel = pixel;
1948 if (relief->gc == 0)
1950 xgcv.stipple = dpyinfo->gray;
1951 mask |= GCStipple;
1952 relief->gc = XCreateGC (dpy, FRAME_X_WINDOW (f), mask, &xgcv);
1954 else
1955 XChangeGC (dpy, relief->gc, mask, &xgcv);
1959 /* Set up colors for the relief lines around glyph string S. */
1961 static void
1962 x_setup_relief_colors (struct glyph_string *s)
1964 struct x_output *di = s->f->output_data.x;
1965 unsigned long color;
1967 if (s->face->use_box_color_for_shadows_p)
1968 color = s->face->box_color;
1969 else if (s->first_glyph->type == IMAGE_GLYPH
1970 && s->img->pixmap
1971 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
1972 color = IMAGE_BACKGROUND (s->img, s->f, 0);
1973 else
1975 XGCValues xgcv;
1977 /* Get the background color of the face. */
1978 XGetGCValues (s->display, s->gc, GCBackground, &xgcv);
1979 color = xgcv.background;
1982 if (di->white_relief.gc == 0
1983 || color != di->relief_background)
1985 di->relief_background = color;
1986 x_setup_relief_color (s->f, &di->white_relief, 1.2, 0x8000,
1987 WHITE_PIX_DEFAULT (s->f));
1988 x_setup_relief_color (s->f, &di->black_relief, 0.6, 0x4000,
1989 BLACK_PIX_DEFAULT (s->f));
1994 /* Draw a relief on frame F inside the rectangle given by LEFT_X,
1995 TOP_Y, RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the relief
1996 to draw, it must be >= 0. RAISED_P non-zero means draw a raised
1997 relief. LEFT_P non-zero means draw a relief on the left side of
1998 the rectangle. RIGHT_P non-zero means draw a relief on the right
1999 side of the rectangle. CLIP_RECT is the clipping rectangle to use
2000 when drawing. */
2002 static void
2003 x_draw_relief_rect (struct frame *f,
2004 int left_x, int top_y, int right_x, int bottom_y, int width,
2005 int raised_p, int top_p, int bot_p, int left_p, int right_p,
2006 XRectangle *clip_rect)
2008 Display *dpy = FRAME_X_DISPLAY (f);
2009 Window window = FRAME_X_WINDOW (f);
2010 int i;
2011 GC gc;
2013 if (raised_p)
2014 gc = f->output_data.x->white_relief.gc;
2015 else
2016 gc = f->output_data.x->black_relief.gc;
2017 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
2019 /* This code is more complicated than it has to be, because of two
2020 minor hacks to make the boxes look nicer: (i) if width > 1, draw
2021 the outermost line using the black relief. (ii) Omit the four
2022 corner pixels. */
2024 /* Top. */
2025 if (top_p)
2027 if (width == 1)
2028 XDrawLine (dpy, window, gc,
2029 left_x + (left_p ? 1 : 0), top_y,
2030 right_x + (right_p ? 0 : 1), top_y);
2032 for (i = 1; i < width; ++i)
2033 XDrawLine (dpy, window, gc,
2034 left_x + i * left_p, top_y + i,
2035 right_x + 1 - i * right_p, top_y + i);
2038 /* Left. */
2039 if (left_p)
2041 if (width == 1)
2042 XDrawLine (dpy, window, gc, left_x, top_y + 1, left_x, bottom_y);
2044 XClearArea (dpy, window, left_x, top_y, 1, 1, False);
2045 XClearArea (dpy, window, left_x, bottom_y, 1, 1, False);
2047 for (i = (width > 1 ? 1 : 0); i < width; ++i)
2048 XDrawLine (dpy, window, gc,
2049 left_x + i, top_y + i, left_x + i, bottom_y - i + 1);
2052 XSetClipMask (dpy, gc, None);
2053 if (raised_p)
2054 gc = f->output_data.x->black_relief.gc;
2055 else
2056 gc = f->output_data.x->white_relief.gc;
2057 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
2059 if (width > 1)
2061 /* Outermost top line. */
2062 if (top_p)
2063 XDrawLine (dpy, window, gc,
2064 left_x + (left_p ? 1 : 0), top_y,
2065 right_x + (right_p ? 0 : 1), top_y);
2067 /* Outermost left line. */
2068 if (left_p)
2069 XDrawLine (dpy, window, gc, left_x, top_y + 1, left_x, bottom_y);
2072 /* Bottom. */
2073 if (bot_p)
2075 XDrawLine (dpy, window, gc,
2076 left_x + (left_p ? 1 : 0), bottom_y,
2077 right_x + (right_p ? 0 : 1), bottom_y);
2078 for (i = 1; i < width; ++i)
2079 XDrawLine (dpy, window, gc,
2080 left_x + i * left_p, bottom_y - i,
2081 right_x + 1 - i * right_p, bottom_y - i);
2084 /* Right. */
2085 if (right_p)
2087 XClearArea (dpy, window, right_x, top_y, 1, 1, False);
2088 XClearArea (dpy, window, right_x, bottom_y, 1, 1, False);
2089 for (i = 0; i < width; ++i)
2090 XDrawLine (dpy, window, gc,
2091 right_x - i, top_y + i + 1, right_x - i, bottom_y - i);
2094 XSetClipMask (dpy, gc, None);
2098 /* Draw a box on frame F inside the rectangle given by LEFT_X, TOP_Y,
2099 RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the lines to
2100 draw, it must be >= 0. LEFT_P non-zero means draw a line on the
2101 left side of the rectangle. RIGHT_P non-zero means draw a line
2102 on the right side of the rectangle. CLIP_RECT is the clipping
2103 rectangle to use when drawing. */
2105 static void
2106 x_draw_box_rect (struct glyph_string *s,
2107 int left_x, int top_y, int right_x, int bottom_y, int width,
2108 int left_p, int right_p, XRectangle *clip_rect)
2110 XGCValues xgcv;
2112 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2113 XSetForeground (s->display, s->gc, s->face->box_color);
2114 XSetClipRectangles (s->display, s->gc, 0, 0, clip_rect, 1, Unsorted);
2116 /* Top. */
2117 XFillRectangle (s->display, s->window, s->gc,
2118 left_x, top_y, right_x - left_x + 1, width);
2120 /* Left. */
2121 if (left_p)
2122 XFillRectangle (s->display, s->window, s->gc,
2123 left_x, top_y, width, bottom_y - top_y + 1);
2125 /* Bottom. */
2126 XFillRectangle (s->display, s->window, s->gc,
2127 left_x, bottom_y - width + 1, right_x - left_x + 1, width);
2129 /* Right. */
2130 if (right_p)
2131 XFillRectangle (s->display, s->window, s->gc,
2132 right_x - width + 1, top_y, width, bottom_y - top_y + 1);
2134 XSetForeground (s->display, s->gc, xgcv.foreground);
2135 XSetClipMask (s->display, s->gc, None);
2139 /* Draw a box around glyph string S. */
2141 static void
2142 x_draw_glyph_string_box (struct glyph_string *s)
2144 int width, left_x, right_x, top_y, bottom_y, last_x, raised_p;
2145 int left_p, right_p;
2146 struct glyph *last_glyph;
2147 XRectangle clip_rect;
2149 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2150 ? WINDOW_RIGHT_EDGE_X (s->w)
2151 : window_box_right (s->w, s->area));
2153 /* The glyph that may have a right box line. */
2154 last_glyph = (s->cmp || s->img
2155 ? s->first_glyph
2156 : s->first_glyph + s->nchars - 1);
2158 width = eabs (s->face->box_line_width);
2159 raised_p = s->face->box == FACE_RAISED_BOX;
2160 left_x = s->x;
2161 right_x = (s->row->full_width_p && s->extends_to_end_of_line_p
2162 ? last_x - 1
2163 : min (last_x, s->x + s->background_width) - 1);
2164 top_y = s->y;
2165 bottom_y = top_y + s->height - 1;
2167 left_p = (s->first_glyph->left_box_line_p
2168 || (s->hl == DRAW_MOUSE_FACE
2169 && (s->prev == NULL
2170 || s->prev->hl != s->hl)));
2171 right_p = (last_glyph->right_box_line_p
2172 || (s->hl == DRAW_MOUSE_FACE
2173 && (s->next == NULL
2174 || s->next->hl != s->hl)));
2176 get_glyph_string_clip_rect (s, &clip_rect);
2178 if (s->face->box == FACE_SIMPLE_BOX)
2179 x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
2180 left_p, right_p, &clip_rect);
2181 else
2183 x_setup_relief_colors (s);
2184 x_draw_relief_rect (s->f, left_x, top_y, right_x, bottom_y,
2185 width, raised_p, 1, 1, left_p, right_p, &clip_rect);
2190 /* Draw foreground of image glyph string S. */
2192 static void
2193 x_draw_image_foreground (struct glyph_string *s)
2195 int x = s->x;
2196 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2198 /* If first glyph of S has a left box line, start drawing it to the
2199 right of that line. */
2200 if (s->face->box != FACE_NO_BOX
2201 && s->first_glyph->left_box_line_p
2202 && s->slice.x == 0)
2203 x += eabs (s->face->box_line_width);
2205 /* If there is a margin around the image, adjust x- and y-position
2206 by that margin. */
2207 if (s->slice.x == 0)
2208 x += s->img->hmargin;
2209 if (s->slice.y == 0)
2210 y += s->img->vmargin;
2212 if (s->img->pixmap)
2214 if (s->img->mask)
2216 /* We can't set both a clip mask and use XSetClipRectangles
2217 because the latter also sets a clip mask. We also can't
2218 trust on the shape extension to be available
2219 (XShapeCombineRegion). So, compute the rectangle to draw
2220 manually. */
2221 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
2222 | GCFunction);
2223 XGCValues xgcv;
2224 XRectangle clip_rect, image_rect, r;
2226 xgcv.clip_mask = s->img->mask;
2227 xgcv.clip_x_origin = x;
2228 xgcv.clip_y_origin = y;
2229 xgcv.function = GXcopy;
2230 XChangeGC (s->display, s->gc, mask, &xgcv);
2232 get_glyph_string_clip_rect (s, &clip_rect);
2233 image_rect.x = x;
2234 image_rect.y = y;
2235 image_rect.width = s->slice.width;
2236 image_rect.height = s->slice.height;
2237 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
2238 XCopyArea (s->display, s->img->pixmap, s->window, s->gc,
2239 s->slice.x + r.x - x, s->slice.y + r.y - y,
2240 r.width, r.height, r.x, r.y);
2242 else
2244 XRectangle clip_rect, image_rect, r;
2246 get_glyph_string_clip_rect (s, &clip_rect);
2247 image_rect.x = x;
2248 image_rect.y = y;
2249 image_rect.width = s->slice.width;
2250 image_rect.height = s->slice.height;
2251 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
2252 XCopyArea (s->display, s->img->pixmap, s->window, s->gc,
2253 s->slice.x + r.x - x, s->slice.y + r.y - y,
2254 r.width, r.height, r.x, r.y);
2256 /* When the image has a mask, we can expect that at
2257 least part of a mouse highlight or a block cursor will
2258 be visible. If the image doesn't have a mask, make
2259 a block cursor visible by drawing a rectangle around
2260 the image. I believe it's looking better if we do
2261 nothing here for mouse-face. */
2262 if (s->hl == DRAW_CURSOR)
2264 int r = s->img->relief;
2265 if (r < 0) r = -r;
2266 XDrawRectangle (s->display, s->window, s->gc,
2267 x - r, y - r,
2268 s->slice.width + r*2 - 1,
2269 s->slice.height + r*2 - 1);
2273 else
2274 /* Draw a rectangle if image could not be loaded. */
2275 XDrawRectangle (s->display, s->window, s->gc, x, y,
2276 s->slice.width - 1, s->slice.height - 1);
2280 /* Draw a relief around the image glyph string S. */
2282 static void
2283 x_draw_image_relief (struct glyph_string *s)
2285 int x0, y0, x1, y1, thick, raised_p, extra;
2286 XRectangle r;
2287 int x = s->x;
2288 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2290 /* If first glyph of S has a left box line, start drawing it to the
2291 right of that line. */
2292 if (s->face->box != FACE_NO_BOX
2293 && s->first_glyph->left_box_line_p
2294 && s->slice.x == 0)
2295 x += eabs (s->face->box_line_width);
2297 /* If there is a margin around the image, adjust x- and y-position
2298 by that margin. */
2299 if (s->slice.x == 0)
2300 x += s->img->hmargin;
2301 if (s->slice.y == 0)
2302 y += s->img->vmargin;
2304 if (s->hl == DRAW_IMAGE_SUNKEN
2305 || s->hl == DRAW_IMAGE_RAISED)
2307 thick = tool_bar_button_relief >= 0 ? tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
2308 raised_p = s->hl == DRAW_IMAGE_RAISED;
2310 else
2312 thick = eabs (s->img->relief);
2313 raised_p = s->img->relief > 0;
2316 extra = s->face->id == TOOL_BAR_FACE_ID
2317 ? XINT (Vtool_bar_button_margin) : 0;
2319 x0 = x - thick - extra;
2320 y0 = y - thick - extra;
2321 x1 = x + s->slice.width + thick - 1 + extra;
2322 y1 = y + s->slice.height + thick - 1 + extra;
2324 x_setup_relief_colors (s);
2325 get_glyph_string_clip_rect (s, &r);
2326 x_draw_relief_rect (s->f, x0, y0, x1, y1, thick, raised_p,
2327 s->slice.y == 0,
2328 s->slice.y + s->slice.height == s->img->height,
2329 s->slice.x == 0,
2330 s->slice.x + s->slice.width == s->img->width,
2331 &r);
2335 /* Draw the foreground of image glyph string S to PIXMAP. */
2337 static void
2338 x_draw_image_foreground_1 (struct glyph_string *s, Pixmap pixmap)
2340 int x = 0;
2341 int y = s->ybase - s->y - image_ascent (s->img, s->face, &s->slice);
2343 /* If first glyph of S has a left box line, start drawing it to the
2344 right of that line. */
2345 if (s->face->box != FACE_NO_BOX
2346 && s->first_glyph->left_box_line_p
2347 && s->slice.x == 0)
2348 x += eabs (s->face->box_line_width);
2350 /* If there is a margin around the image, adjust x- and y-position
2351 by that margin. */
2352 if (s->slice.x == 0)
2353 x += s->img->hmargin;
2354 if (s->slice.y == 0)
2355 y += s->img->vmargin;
2357 if (s->img->pixmap)
2359 if (s->img->mask)
2361 /* We can't set both a clip mask and use XSetClipRectangles
2362 because the latter also sets a clip mask. We also can't
2363 trust on the shape extension to be available
2364 (XShapeCombineRegion). So, compute the rectangle to draw
2365 manually. */
2366 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
2367 | GCFunction);
2368 XGCValues xgcv;
2370 xgcv.clip_mask = s->img->mask;
2371 xgcv.clip_x_origin = x - s->slice.x;
2372 xgcv.clip_y_origin = y - s->slice.y;
2373 xgcv.function = GXcopy;
2374 XChangeGC (s->display, s->gc, mask, &xgcv);
2376 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
2377 s->slice.x, s->slice.y,
2378 s->slice.width, s->slice.height, x, y);
2379 XSetClipMask (s->display, s->gc, None);
2381 else
2383 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
2384 s->slice.x, s->slice.y,
2385 s->slice.width, s->slice.height, x, y);
2387 /* When the image has a mask, we can expect that at
2388 least part of a mouse highlight or a block cursor will
2389 be visible. If the image doesn't have a mask, make
2390 a block cursor visible by drawing a rectangle around
2391 the image. I believe it's looking better if we do
2392 nothing here for mouse-face. */
2393 if (s->hl == DRAW_CURSOR)
2395 int r = s->img->relief;
2396 if (r < 0) r = -r;
2397 XDrawRectangle (s->display, s->window, s->gc, x - r, y - r,
2398 s->slice.width + r*2 - 1,
2399 s->slice.height + r*2 - 1);
2403 else
2404 /* Draw a rectangle if image could not be loaded. */
2405 XDrawRectangle (s->display, pixmap, s->gc, x, y,
2406 s->slice.width - 1, s->slice.height - 1);
2410 /* Draw part of the background of glyph string S. X, Y, W, and H
2411 give the rectangle to draw. */
2413 static void
2414 x_draw_glyph_string_bg_rect (struct glyph_string *s, int x, int y, int w, int h)
2416 if (s->stippled_p)
2418 /* Fill background with a stipple pattern. */
2419 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
2420 XFillRectangle (s->display, s->window, s->gc, x, y, w, h);
2421 XSetFillStyle (s->display, s->gc, FillSolid);
2423 else
2424 x_clear_glyph_string_rect (s, x, y, w, h);
2428 /* Draw image glyph string S.
2430 s->y
2431 s->x +-------------------------
2432 | s->face->box
2434 | +-------------------------
2435 | | s->img->margin
2437 | | +-------------------
2438 | | | the image
2442 static void
2443 x_draw_image_glyph_string (struct glyph_string *s)
2445 int box_line_hwidth = eabs (s->face->box_line_width);
2446 int box_line_vwidth = max (s->face->box_line_width, 0);
2447 int height;
2448 Pixmap pixmap = None;
2450 height = s->height;
2451 if (s->slice.y == 0)
2452 height -= box_line_vwidth;
2453 if (s->slice.y + s->slice.height >= s->img->height)
2454 height -= box_line_vwidth;
2456 /* Fill background with face under the image. Do it only if row is
2457 taller than image or if image has a clip mask to reduce
2458 flickering. */
2459 s->stippled_p = s->face->stipple != 0;
2460 if (height > s->slice.height
2461 || s->img->hmargin
2462 || s->img->vmargin
2463 || s->img->mask
2464 || s->img->pixmap == 0
2465 || s->width != s->background_width)
2467 if (s->img->mask)
2469 /* Create a pixmap as large as the glyph string. Fill it
2470 with the background color. Copy the image to it, using
2471 its mask. Copy the temporary pixmap to the display. */
2472 Screen *screen = FRAME_X_SCREEN (s->f);
2473 int depth = DefaultDepthOfScreen (screen);
2475 /* Create a pixmap as large as the glyph string. */
2476 pixmap = XCreatePixmap (s->display, s->window,
2477 s->background_width,
2478 s->height, depth);
2480 /* Don't clip in the following because we're working on the
2481 pixmap. */
2482 XSetClipMask (s->display, s->gc, None);
2484 /* Fill the pixmap with the background color/stipple. */
2485 if (s->stippled_p)
2487 /* Fill background with a stipple pattern. */
2488 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
2489 XSetTSOrigin (s->display, s->gc, - s->x, - s->y);
2490 XFillRectangle (s->display, pixmap, s->gc,
2491 0, 0, s->background_width, s->height);
2492 XSetFillStyle (s->display, s->gc, FillSolid);
2493 XSetTSOrigin (s->display, s->gc, 0, 0);
2495 else
2497 XGCValues xgcv;
2498 XGetGCValues (s->display, s->gc, GCForeground | GCBackground,
2499 &xgcv);
2500 XSetForeground (s->display, s->gc, xgcv.background);
2501 XFillRectangle (s->display, pixmap, s->gc,
2502 0, 0, s->background_width, s->height);
2503 XSetForeground (s->display, s->gc, xgcv.foreground);
2506 else
2508 int x = s->x;
2509 int y = s->y;
2511 if (s->first_glyph->left_box_line_p
2512 && s->slice.x == 0)
2513 x += box_line_hwidth;
2515 if (s->slice.y == 0)
2516 y += box_line_vwidth;
2518 x_draw_glyph_string_bg_rect (s, x, y, s->background_width, height);
2521 s->background_filled_p = 1;
2524 /* Draw the foreground. */
2525 if (pixmap != None)
2527 x_draw_image_foreground_1 (s, pixmap);
2528 x_set_glyph_string_clipping (s);
2529 XCopyArea (s->display, pixmap, s->window, s->gc,
2530 0, 0, s->background_width, s->height, s->x, s->y);
2531 XFreePixmap (s->display, pixmap);
2533 else
2534 x_draw_image_foreground (s);
2536 /* If we must draw a relief around the image, do it. */
2537 if (s->img->relief
2538 || s->hl == DRAW_IMAGE_RAISED
2539 || s->hl == DRAW_IMAGE_SUNKEN)
2540 x_draw_image_relief (s);
2544 /* Draw stretch glyph string S. */
2546 static void
2547 x_draw_stretch_glyph_string (struct glyph_string *s)
2549 xassert (s->first_glyph->type == STRETCH_GLYPH);
2551 if (s->hl == DRAW_CURSOR
2552 && !x_stretch_cursor_p)
2554 /* If `x-stretch-cursor' is nil, don't draw a block cursor as
2555 wide as the stretch glyph. */
2556 int width, background_width = s->background_width;
2557 int x = s->x;
2559 if (!s->row->reversed_p)
2561 int left_x = window_box_left_offset (s->w, TEXT_AREA);
2563 if (x < left_x)
2565 background_width -= left_x - x;
2566 x = left_x;
2569 else
2571 /* In R2L rows, draw the cursor on the right edge of the
2572 stretch glyph. */
2573 int right_x = window_box_right_offset (s->w, TEXT_AREA);
2575 if (x + background_width > right_x)
2576 background_width -= x - right_x;
2577 x += background_width;
2579 width = min (FRAME_COLUMN_WIDTH (s->f), background_width);
2580 if (s->row->reversed_p)
2581 x -= width;
2583 /* Draw cursor. */
2584 x_draw_glyph_string_bg_rect (s, x, s->y, width, s->height);
2586 /* Clear rest using the GC of the original non-cursor face. */
2587 if (width < background_width)
2589 int y = s->y;
2590 int w = background_width - width, h = s->height;
2591 XRectangle r;
2592 GC gc;
2594 if (!s->row->reversed_p)
2595 x += width;
2596 else
2597 x = s->x;
2598 if (s->row->mouse_face_p
2599 && cursor_in_mouse_face_p (s->w))
2601 x_set_mouse_face_gc (s);
2602 gc = s->gc;
2604 else
2605 gc = s->face->gc;
2607 get_glyph_string_clip_rect (s, &r);
2608 XSetClipRectangles (s->display, gc, 0, 0, &r, 1, Unsorted);
2610 if (s->face->stipple)
2612 /* Fill background with a stipple pattern. */
2613 XSetFillStyle (s->display, gc, FillOpaqueStippled);
2614 XFillRectangle (s->display, s->window, gc, x, y, w, h);
2615 XSetFillStyle (s->display, gc, FillSolid);
2617 else
2619 XGCValues xgcv;
2620 XGetGCValues (s->display, gc, GCForeground | GCBackground, &xgcv);
2621 XSetForeground (s->display, gc, xgcv.background);
2622 XFillRectangle (s->display, s->window, gc, x, y, w, h);
2623 XSetForeground (s->display, gc, xgcv.foreground);
2627 else if (!s->background_filled_p)
2629 int background_width = s->background_width;
2630 int x = s->x, left_x = window_box_left_offset (s->w, TEXT_AREA);
2632 /* Don't draw into left margin, fringe or scrollbar area
2633 except for header line and mode line. */
2634 if (x < left_x && !s->row->mode_line_p)
2636 background_width -= left_x - x;
2637 x = left_x;
2639 if (background_width > 0)
2640 x_draw_glyph_string_bg_rect (s, x, s->y, background_width, s->height);
2643 s->background_filled_p = 1;
2647 /* Draw glyph string S. */
2649 static void
2650 x_draw_glyph_string (struct glyph_string *s)
2652 int relief_drawn_p = 0;
2654 /* If S draws into the background of its successors, draw the
2655 background of the successors first so that S can draw into it.
2656 This makes S->next use XDrawString instead of XDrawImageString. */
2657 if (s->next && s->right_overhang && !s->for_overlaps)
2659 int width;
2660 struct glyph_string *next;
2662 for (width = 0, next = s->next;
2663 next && width < s->right_overhang;
2664 width += next->width, next = next->next)
2665 if (next->first_glyph->type != IMAGE_GLYPH)
2667 x_set_glyph_string_gc (next);
2668 x_set_glyph_string_clipping (next);
2669 if (next->first_glyph->type == STRETCH_GLYPH)
2670 x_draw_stretch_glyph_string (next);
2671 else
2672 x_draw_glyph_string_background (next, 1);
2673 next->num_clips = 0;
2677 /* Set up S->gc, set clipping and draw S. */
2678 x_set_glyph_string_gc (s);
2680 /* Draw relief (if any) in advance for char/composition so that the
2681 glyph string can be drawn over it. */
2682 if (!s->for_overlaps
2683 && s->face->box != FACE_NO_BOX
2684 && (s->first_glyph->type == CHAR_GLYPH
2685 || s->first_glyph->type == COMPOSITE_GLYPH))
2688 x_set_glyph_string_clipping (s);
2689 x_draw_glyph_string_background (s, 1);
2690 x_draw_glyph_string_box (s);
2691 x_set_glyph_string_clipping (s);
2692 relief_drawn_p = 1;
2694 else if (!s->clip_head /* draw_glyphs didn't specify a clip mask. */
2695 && !s->clip_tail
2696 && ((s->prev && s->prev->hl != s->hl && s->left_overhang)
2697 || (s->next && s->next->hl != s->hl && s->right_overhang)))
2698 /* We must clip just this glyph. left_overhang part has already
2699 drawn when s->prev was drawn, and right_overhang part will be
2700 drawn later when s->next is drawn. */
2701 x_set_glyph_string_clipping_exactly (s, s);
2702 else
2703 x_set_glyph_string_clipping (s);
2705 switch (s->first_glyph->type)
2707 case IMAGE_GLYPH:
2708 x_draw_image_glyph_string (s);
2709 break;
2711 case STRETCH_GLYPH:
2712 x_draw_stretch_glyph_string (s);
2713 break;
2715 case CHAR_GLYPH:
2716 if (s->for_overlaps)
2717 s->background_filled_p = 1;
2718 else
2719 x_draw_glyph_string_background (s, 0);
2720 x_draw_glyph_string_foreground (s);
2721 break;
2723 case COMPOSITE_GLYPH:
2724 if (s->for_overlaps || (s->cmp_from > 0
2725 && ! s->first_glyph->u.cmp.automatic))
2726 s->background_filled_p = 1;
2727 else
2728 x_draw_glyph_string_background (s, 1);
2729 x_draw_composite_glyph_string_foreground (s);
2730 break;
2732 case GLYPHLESS_GLYPH:
2733 if (s->for_overlaps)
2734 s->background_filled_p = 1;
2735 else
2736 x_draw_glyph_string_background (s, 1);
2737 x_draw_glyphless_glyph_string_foreground (s);
2738 break;
2740 default:
2741 abort ();
2744 if (!s->for_overlaps)
2746 /* Draw underline. */
2747 if (s->face->underline_p)
2749 unsigned long thickness, position;
2750 int y;
2752 if (s->prev && s->prev->face->underline_p)
2754 /* We use the same underline style as the previous one. */
2755 thickness = s->prev->underline_thickness;
2756 position = s->prev->underline_position;
2758 else
2760 /* Get the underline thickness. Default is 1 pixel. */
2761 if (s->font && s->font->underline_thickness > 0)
2762 thickness = s->font->underline_thickness;
2763 else
2764 thickness = 1;
2765 if (x_underline_at_descent_line)
2766 position = (s->height - thickness) - (s->ybase - s->y);
2767 else
2769 /* Get the underline position. This is the recommended
2770 vertical offset in pixels from the baseline to the top of
2771 the underline. This is a signed value according to the
2772 specs, and its default is
2774 ROUND ((maximum descent) / 2), with
2775 ROUND(x) = floor (x + 0.5) */
2777 if (x_use_underline_position_properties
2778 && s->font && s->font->underline_position >= 0)
2779 position = s->font->underline_position;
2780 else if (s->font)
2781 position = (s->font->descent + 1) / 2;
2782 else
2783 position = underline_minimum_offset;
2785 position = max (position, underline_minimum_offset);
2787 /* Check the sanity of thickness and position. We should
2788 avoid drawing underline out of the current line area. */
2789 if (s->y + s->height <= s->ybase + position)
2790 position = (s->height - 1) - (s->ybase - s->y);
2791 if (s->y + s->height < s->ybase + position + thickness)
2792 thickness = (s->y + s->height) - (s->ybase + position);
2793 s->underline_thickness = thickness;
2794 s->underline_position = position;
2795 y = s->ybase + position;
2796 if (s->face->underline_defaulted_p)
2797 XFillRectangle (s->display, s->window, s->gc,
2798 s->x, y, s->width, thickness);
2799 else
2801 XGCValues xgcv;
2802 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2803 XSetForeground (s->display, s->gc, s->face->underline_color);
2804 XFillRectangle (s->display, s->window, s->gc,
2805 s->x, y, s->width, thickness);
2806 XSetForeground (s->display, s->gc, xgcv.foreground);
2810 /* Draw overline. */
2811 if (s->face->overline_p)
2813 unsigned long dy = 0, h = 1;
2815 if (s->face->overline_color_defaulted_p)
2816 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2817 s->width, h);
2818 else
2820 XGCValues xgcv;
2821 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2822 XSetForeground (s->display, s->gc, s->face->overline_color);
2823 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2824 s->width, h);
2825 XSetForeground (s->display, s->gc, xgcv.foreground);
2829 /* Draw strike-through. */
2830 if (s->face->strike_through_p)
2832 unsigned long h = 1;
2833 unsigned long dy = (s->height - h) / 2;
2835 if (s->face->strike_through_color_defaulted_p)
2836 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2837 s->width, h);
2838 else
2840 XGCValues xgcv;
2841 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2842 XSetForeground (s->display, s->gc, s->face->strike_through_color);
2843 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2844 s->width, h);
2845 XSetForeground (s->display, s->gc, xgcv.foreground);
2849 /* Draw relief if not yet drawn. */
2850 if (!relief_drawn_p && s->face->box != FACE_NO_BOX)
2851 x_draw_glyph_string_box (s);
2853 if (s->prev)
2855 struct glyph_string *prev;
2857 for (prev = s->prev; prev; prev = prev->prev)
2858 if (prev->hl != s->hl
2859 && prev->x + prev->width + prev->right_overhang > s->x)
2861 /* As prev was drawn while clipped to its own area, we
2862 must draw the right_overhang part using s->hl now. */
2863 enum draw_glyphs_face save = prev->hl;
2865 prev->hl = s->hl;
2866 x_set_glyph_string_gc (prev);
2867 x_set_glyph_string_clipping_exactly (s, prev);
2868 if (prev->first_glyph->type == CHAR_GLYPH)
2869 x_draw_glyph_string_foreground (prev);
2870 else
2871 x_draw_composite_glyph_string_foreground (prev);
2872 XSetClipMask (prev->display, prev->gc, None);
2873 prev->hl = save;
2874 prev->num_clips = 0;
2878 if (s->next)
2880 struct glyph_string *next;
2882 for (next = s->next; next; next = next->next)
2883 if (next->hl != s->hl
2884 && next->x - next->left_overhang < s->x + s->width)
2886 /* As next will be drawn while clipped to its own area,
2887 we must draw the left_overhang part using s->hl now. */
2888 enum draw_glyphs_face save = next->hl;
2890 next->hl = s->hl;
2891 x_set_glyph_string_gc (next);
2892 x_set_glyph_string_clipping_exactly (s, next);
2893 if (next->first_glyph->type == CHAR_GLYPH)
2894 x_draw_glyph_string_foreground (next);
2895 else
2896 x_draw_composite_glyph_string_foreground (next);
2897 XSetClipMask (next->display, next->gc, None);
2898 next->hl = save;
2899 next->num_clips = 0;
2904 /* Reset clipping. */
2905 XSetClipMask (s->display, s->gc, None);
2906 s->num_clips = 0;
2909 /* Shift display to make room for inserted glyphs. */
2911 void
2912 x_shift_glyphs_for_insert (struct frame *f, int x, int y, int width, int height, int shift_by)
2914 XCopyArea (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), FRAME_X_WINDOW (f),
2915 f->output_data.x->normal_gc,
2916 x, y, width, height,
2917 x + shift_by, y);
2920 /* Delete N glyphs at the nominal cursor position. Not implemented
2921 for X frames. */
2923 static void
2924 x_delete_glyphs (struct frame *f, register int n)
2926 abort ();
2930 /* Like XClearArea, but check that WIDTH and HEIGHT are reasonable.
2931 If they are <= 0, this is probably an error. */
2933 void
2934 x_clear_area (Display *dpy, Window window, int x, int y, int width, int height, int exposures)
2936 xassert (width > 0 && height > 0);
2937 XClearArea (dpy, window, x, y, width, height, exposures);
2941 /* Clear an entire frame. */
2943 static void
2944 x_clear_frame (struct frame *f)
2946 /* Clearing the frame will erase any cursor, so mark them all as no
2947 longer visible. */
2948 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2949 output_cursor.hpos = output_cursor.vpos = 0;
2950 output_cursor.x = -1;
2952 /* We don't set the output cursor here because there will always
2953 follow an explicit cursor_to. */
2954 BLOCK_INPUT;
2955 XClearWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
2957 /* We have to clear the scroll bars, too. If we have changed
2958 colors or something like that, then they should be notified. */
2959 x_scroll_bar_clear (f);
2961 #if defined (USE_GTK) && defined (USE_TOOLKIT_SCROLL_BARS)
2962 /* Make sure scroll bars are redrawn. As they aren't redrawn by
2963 redisplay, do it here. */
2964 if (FRAME_GTK_WIDGET (f))
2965 gtk_widget_queue_draw (FRAME_GTK_WIDGET (f));
2966 #endif
2968 XFlush (FRAME_X_DISPLAY (f));
2970 UNBLOCK_INPUT;
2975 /* Invert the middle quarter of the frame for .15 sec. */
2977 /* We use the select system call to do the waiting, so we have to make
2978 sure it's available. If it isn't, we just won't do visual bells. */
2980 #if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
2983 /* Subtract the `struct timeval' values X and Y, storing the result in
2984 *RESULT. Return 1 if the difference is negative, otherwise 0. */
2986 static int
2987 timeval_subtract (struct timeval *result, struct timeval x, struct timeval y)
2989 /* Perform the carry for the later subtraction by updating y. This
2990 is safer because on some systems the tv_sec member is unsigned. */
2991 if (x.tv_usec < y.tv_usec)
2993 int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
2994 y.tv_usec -= 1000000 * nsec;
2995 y.tv_sec += nsec;
2998 if (x.tv_usec - y.tv_usec > 1000000)
3000 int nsec = (y.tv_usec - x.tv_usec) / 1000000;
3001 y.tv_usec += 1000000 * nsec;
3002 y.tv_sec -= nsec;
3005 /* Compute the time remaining to wait. tv_usec is certainly
3006 positive. */
3007 result->tv_sec = x.tv_sec - y.tv_sec;
3008 result->tv_usec = x.tv_usec - y.tv_usec;
3010 /* Return indication of whether the result should be considered
3011 negative. */
3012 return x.tv_sec < y.tv_sec;
3015 void
3016 XTflash (struct frame *f)
3018 BLOCK_INPUT;
3021 #ifdef USE_GTK
3022 /* Use Gdk routines to draw. This way, we won't draw over scroll bars
3023 when the scroll bars and the edit widget share the same X window. */
3024 GdkWindow *window = gtk_widget_get_window (FRAME_GTK_WIDGET (f));
3025 GdkGCValues vals;
3026 GdkGC *gc;
3027 vals.foreground.pixel = (FRAME_FOREGROUND_PIXEL (f)
3028 ^ FRAME_BACKGROUND_PIXEL (f));
3029 vals.function = GDK_XOR;
3030 gc = gdk_gc_new_with_values (window,
3031 &vals, GDK_GC_FUNCTION | GDK_GC_FOREGROUND);
3032 #define XFillRectangle(d, win, gc, x, y, w, h) \
3033 gdk_draw_rectangle (window, gc, TRUE, x, y, w, h)
3034 #else
3035 GC gc;
3037 /* Create a GC that will use the GXxor function to flip foreground
3038 pixels into background pixels. */
3040 XGCValues values;
3042 values.function = GXxor;
3043 values.foreground = (FRAME_FOREGROUND_PIXEL (f)
3044 ^ FRAME_BACKGROUND_PIXEL (f));
3046 gc = XCreateGC (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3047 GCFunction | GCForeground, &values);
3049 #endif
3051 /* Get the height not including a menu bar widget. */
3052 int height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, FRAME_LINES (f));
3053 /* Height of each line to flash. */
3054 int flash_height = FRAME_LINE_HEIGHT (f);
3055 /* These will be the left and right margins of the rectangles. */
3056 int flash_left = FRAME_INTERNAL_BORDER_WIDTH (f);
3057 int flash_right = FRAME_PIXEL_WIDTH (f) - FRAME_INTERNAL_BORDER_WIDTH (f);
3059 int width;
3061 /* Don't flash the area between a scroll bar and the frame
3062 edge it is next to. */
3063 switch (FRAME_VERTICAL_SCROLL_BAR_TYPE (f))
3065 case vertical_scroll_bar_left:
3066 flash_left += VERTICAL_SCROLL_BAR_WIDTH_TRIM;
3067 break;
3069 case vertical_scroll_bar_right:
3070 flash_right -= VERTICAL_SCROLL_BAR_WIDTH_TRIM;
3071 break;
3073 default:
3074 break;
3077 width = flash_right - flash_left;
3079 /* If window is tall, flash top and bottom line. */
3080 if (height > 3 * FRAME_LINE_HEIGHT (f))
3082 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3083 flash_left,
3084 (FRAME_INTERNAL_BORDER_WIDTH (f)
3085 + FRAME_TOP_MARGIN_HEIGHT (f)),
3086 width, flash_height);
3087 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3088 flash_left,
3089 (height - flash_height
3090 - FRAME_INTERNAL_BORDER_WIDTH (f)),
3091 width, flash_height);
3094 else
3095 /* If it is short, flash it all. */
3096 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3097 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
3098 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
3100 x_flush (f);
3103 struct timeval wakeup;
3105 EMACS_GET_TIME (wakeup);
3107 /* Compute time to wait until, propagating carry from usecs. */
3108 wakeup.tv_usec += 150000;
3109 wakeup.tv_sec += (wakeup.tv_usec / 1000000);
3110 wakeup.tv_usec %= 1000000;
3112 /* Keep waiting until past the time wakeup or any input gets
3113 available. */
3114 while (! detect_input_pending ())
3116 struct timeval current;
3117 struct timeval timeout;
3119 EMACS_GET_TIME (current);
3121 /* Break if result would be negative. */
3122 if (timeval_subtract (&current, wakeup, current))
3123 break;
3125 /* How long `select' should wait. */
3126 timeout.tv_sec = 0;
3127 timeout.tv_usec = 10000;
3129 /* Try to wait that long--but we might wake up sooner. */
3130 select (0, NULL, NULL, NULL, &timeout);
3134 /* If window is tall, flash top and bottom line. */
3135 if (height > 3 * FRAME_LINE_HEIGHT (f))
3137 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3138 flash_left,
3139 (FRAME_INTERNAL_BORDER_WIDTH (f)
3140 + FRAME_TOP_MARGIN_HEIGHT (f)),
3141 width, flash_height);
3142 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3143 flash_left,
3144 (height - flash_height
3145 - FRAME_INTERNAL_BORDER_WIDTH (f)),
3146 width, flash_height);
3148 else
3149 /* If it is short, flash it all. */
3150 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3151 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
3152 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
3154 #ifdef USE_GTK
3155 g_object_unref (G_OBJECT (gc));
3156 #undef XFillRectangle
3157 #else
3158 XFreeGC (FRAME_X_DISPLAY (f), gc);
3159 #endif
3160 x_flush (f);
3164 UNBLOCK_INPUT;
3167 #endif /* defined (HAVE_TIMEVAL) && defined (HAVE_SELECT) */
3170 static void
3171 XTtoggle_invisible_pointer (FRAME_PTR f, int invisible)
3173 BLOCK_INPUT;
3174 if (invisible)
3176 if (FRAME_X_DISPLAY_INFO (f)->invisible_cursor != 0)
3177 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3178 FRAME_X_DISPLAY_INFO (f)->invisible_cursor);
3180 else
3181 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3182 f->output_data.x->current_cursor);
3183 f->pointer_invisible = invisible;
3184 UNBLOCK_INPUT;
3188 /* Make audible bell. */
3190 void
3191 XTring_bell (struct frame *f)
3193 if (FRAME_X_DISPLAY (f))
3195 #if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
3196 if (visible_bell)
3197 XTflash (f);
3198 else
3199 #endif
3201 BLOCK_INPUT;
3202 XBell (FRAME_X_DISPLAY (f), 0);
3203 XFlush (FRAME_X_DISPLAY (f));
3204 UNBLOCK_INPUT;
3210 /* Specify how many text lines, from the top of the window,
3211 should be affected by insert-lines and delete-lines operations.
3212 This, and those operations, are used only within an update
3213 that is bounded by calls to x_update_begin and x_update_end. */
3215 static void
3216 XTset_terminal_window (struct frame *f, int n)
3218 /* This function intentionally left blank. */
3223 /***********************************************************************
3224 Line Dance
3225 ***********************************************************************/
3227 /* Perform an insert-lines or delete-lines operation, inserting N
3228 lines or deleting -N lines at vertical position VPOS. */
3230 static void
3231 x_ins_del_lines (struct frame *f, int vpos, int n)
3233 abort ();
3237 /* Scroll part of the display as described by RUN. */
3239 static void
3240 x_scroll_run (struct window *w, struct run *run)
3242 struct frame *f = XFRAME (w->frame);
3243 int x, y, width, height, from_y, to_y, bottom_y;
3245 /* Get frame-relative bounding box of the text display area of W,
3246 without mode lines. Include in this box the left and right
3247 fringe of W. */
3248 window_box (w, -1, &x, &y, &width, &height);
3250 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
3251 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
3252 bottom_y = y + height;
3254 if (to_y < from_y)
3256 /* Scrolling up. Make sure we don't copy part of the mode
3257 line at the bottom. */
3258 if (from_y + run->height > bottom_y)
3259 height = bottom_y - from_y;
3260 else
3261 height = run->height;
3263 else
3265 /* Scolling down. Make sure we don't copy over the mode line.
3266 at the bottom. */
3267 if (to_y + run->height > bottom_y)
3268 height = bottom_y - to_y;
3269 else
3270 height = run->height;
3273 BLOCK_INPUT;
3275 /* Cursor off. Will be switched on again in x_update_window_end. */
3276 updated_window = w;
3277 x_clear_cursor (w);
3279 XCopyArea (FRAME_X_DISPLAY (f),
3280 FRAME_X_WINDOW (f), FRAME_X_WINDOW (f),
3281 f->output_data.x->normal_gc,
3282 x, from_y,
3283 width, height,
3284 x, to_y);
3286 UNBLOCK_INPUT;
3291 /***********************************************************************
3292 Exposure Events
3293 ***********************************************************************/
3296 static void
3297 frame_highlight (struct frame *f)
3299 /* We used to only do this if Vx_no_window_manager was non-nil, but
3300 the ICCCM (section 4.1.6) says that the window's border pixmap
3301 and border pixel are window attributes which are "private to the
3302 client", so we can always change it to whatever we want. */
3303 BLOCK_INPUT;
3304 XSetWindowBorder (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3305 f->output_data.x->border_pixel);
3306 UNBLOCK_INPUT;
3307 x_update_cursor (f, 1);
3308 x_set_frame_alpha (f);
3311 static void
3312 frame_unhighlight (struct frame *f)
3314 /* We used to only do this if Vx_no_window_manager was non-nil, but
3315 the ICCCM (section 4.1.6) says that the window's border pixmap
3316 and border pixel are window attributes which are "private to the
3317 client", so we can always change it to whatever we want. */
3318 BLOCK_INPUT;
3319 XSetWindowBorderPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3320 f->output_data.x->border_tile);
3321 UNBLOCK_INPUT;
3322 x_update_cursor (f, 1);
3323 x_set_frame_alpha (f);
3326 /* The focus has changed. Update the frames as necessary to reflect
3327 the new situation. Note that we can't change the selected frame
3328 here, because the Lisp code we are interrupting might become confused.
3329 Each event gets marked with the frame in which it occurred, so the
3330 Lisp code can tell when the switch took place by examining the events. */
3332 static void
3333 x_new_focus_frame (struct x_display_info *dpyinfo, struct frame *frame)
3335 struct frame *old_focus = dpyinfo->x_focus_frame;
3337 if (frame != dpyinfo->x_focus_frame)
3339 /* Set this before calling other routines, so that they see
3340 the correct value of x_focus_frame. */
3341 dpyinfo->x_focus_frame = frame;
3343 if (old_focus && old_focus->auto_lower)
3344 x_lower_frame (old_focus);
3346 if (dpyinfo->x_focus_frame && dpyinfo->x_focus_frame->auto_raise)
3347 pending_autoraise_frame = dpyinfo->x_focus_frame;
3348 else
3349 pending_autoraise_frame = 0;
3352 x_frame_rehighlight (dpyinfo);
3355 /* Handle FocusIn and FocusOut state changes for FRAME.
3356 If FRAME has focus and there exists more than one frame, puts
3357 a FOCUS_IN_EVENT into *BUFP. */
3359 static void
3360 x_focus_changed (int type, int state, struct x_display_info *dpyinfo, struct frame *frame, struct input_event *bufp)
3362 if (type == FocusIn)
3364 if (dpyinfo->x_focus_event_frame != frame)
3366 x_new_focus_frame (dpyinfo, frame);
3367 dpyinfo->x_focus_event_frame = frame;
3369 /* Don't stop displaying the initial startup message
3370 for a switch-frame event we don't need. */
3371 if (NILP (Vterminal_frame)
3372 && CONSP (Vframe_list)
3373 && !NILP (XCDR (Vframe_list)))
3375 bufp->kind = FOCUS_IN_EVENT;
3376 XSETFRAME (bufp->frame_or_window, frame);
3380 frame->output_data.x->focus_state |= state;
3382 #ifdef HAVE_X_I18N
3383 if (FRAME_XIC (frame))
3384 XSetICFocus (FRAME_XIC (frame));
3385 #endif
3387 else if (type == FocusOut)
3389 frame->output_data.x->focus_state &= ~state;
3391 if (dpyinfo->x_focus_event_frame == frame)
3393 dpyinfo->x_focus_event_frame = 0;
3394 x_new_focus_frame (dpyinfo, 0);
3397 #ifdef HAVE_X_I18N
3398 if (FRAME_XIC (frame))
3399 XUnsetICFocus (FRAME_XIC (frame));
3400 #endif
3401 if (frame->pointer_invisible)
3402 XTtoggle_invisible_pointer (frame, 0);
3406 /* The focus may have changed. Figure out if it is a real focus change,
3407 by checking both FocusIn/Out and Enter/LeaveNotify events.
3409 Returns FOCUS_IN_EVENT event in *BUFP. */
3411 static void
3412 x_detect_focus_change (struct x_display_info *dpyinfo, XEvent *event, struct input_event *bufp)
3414 struct frame *frame;
3416 frame = x_any_window_to_frame (dpyinfo, event->xany.window);
3417 if (! frame)
3418 return;
3420 switch (event->type)
3422 case EnterNotify:
3423 case LeaveNotify:
3425 struct frame *focus_frame = dpyinfo->x_focus_event_frame;
3426 int focus_state
3427 = focus_frame ? focus_frame->output_data.x->focus_state : 0;
3429 if (event->xcrossing.detail != NotifyInferior
3430 && event->xcrossing.focus
3431 && ! (focus_state & FOCUS_EXPLICIT))
3432 x_focus_changed ((event->type == EnterNotify ? FocusIn : FocusOut),
3433 FOCUS_IMPLICIT,
3434 dpyinfo, frame, bufp);
3436 break;
3438 case FocusIn:
3439 case FocusOut:
3440 x_focus_changed (event->type,
3441 (event->xfocus.detail == NotifyPointer ?
3442 FOCUS_IMPLICIT : FOCUS_EXPLICIT),
3443 dpyinfo, frame, bufp);
3444 break;
3446 case ClientMessage:
3447 if (event->xclient.message_type == dpyinfo->Xatom_XEMBED)
3449 enum xembed_message msg = event->xclient.data.l[1];
3450 x_focus_changed ((msg == XEMBED_FOCUS_IN ? FocusIn : FocusOut),
3451 FOCUS_EXPLICIT, dpyinfo, frame, bufp);
3453 break;
3458 /* Handle an event saying the mouse has moved out of an Emacs frame. */
3460 void
3461 x_mouse_leave (struct x_display_info *dpyinfo)
3463 x_new_focus_frame (dpyinfo, dpyinfo->x_focus_event_frame);
3466 /* The focus has changed, or we have redirected a frame's focus to
3467 another frame (this happens when a frame uses a surrogate
3468 mini-buffer frame). Shift the highlight as appropriate.
3470 The FRAME argument doesn't necessarily have anything to do with which
3471 frame is being highlighted or un-highlighted; we only use it to find
3472 the appropriate X display info. */
3474 static void
3475 XTframe_rehighlight (struct frame *frame)
3477 x_frame_rehighlight (FRAME_X_DISPLAY_INFO (frame));
3480 static void
3481 x_frame_rehighlight (struct x_display_info *dpyinfo)
3483 struct frame *old_highlight = dpyinfo->x_highlight_frame;
3485 if (dpyinfo->x_focus_frame)
3487 dpyinfo->x_highlight_frame
3488 = ((FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame)))
3489 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
3490 : dpyinfo->x_focus_frame);
3491 if (! FRAME_LIVE_P (dpyinfo->x_highlight_frame))
3493 FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
3494 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
3497 else
3498 dpyinfo->x_highlight_frame = 0;
3500 if (dpyinfo->x_highlight_frame != old_highlight)
3502 if (old_highlight)
3503 frame_unhighlight (old_highlight);
3504 if (dpyinfo->x_highlight_frame)
3505 frame_highlight (dpyinfo->x_highlight_frame);
3511 /* Keyboard processing - modifier keys, vendor-specific keysyms, etc. */
3513 /* Initialize mode_switch_bit and modifier_meaning. */
3514 static void
3515 x_find_modifier_meanings (struct x_display_info *dpyinfo)
3517 int min_code, max_code;
3518 KeySym *syms;
3519 int syms_per_code;
3520 XModifierKeymap *mods;
3522 dpyinfo->meta_mod_mask = 0;
3523 dpyinfo->shift_lock_mask = 0;
3524 dpyinfo->alt_mod_mask = 0;
3525 dpyinfo->super_mod_mask = 0;
3526 dpyinfo->hyper_mod_mask = 0;
3528 XDisplayKeycodes (dpyinfo->display, &min_code, &max_code);
3530 syms = XGetKeyboardMapping (dpyinfo->display,
3531 min_code, max_code - min_code + 1,
3532 &syms_per_code);
3533 mods = XGetModifierMapping (dpyinfo->display);
3535 /* Scan the modifier table to see which modifier bits the Meta and
3536 Alt keysyms are on. */
3538 int row, col; /* The row and column in the modifier table. */
3539 int found_alt_or_meta;
3541 for (row = 3; row < 8; row++)
3543 found_alt_or_meta = 0;
3544 for (col = 0; col < mods->max_keypermod; col++)
3546 KeyCode code = mods->modifiermap[(row * mods->max_keypermod) + col];
3548 /* Zeroes are used for filler. Skip them. */
3549 if (code == 0)
3550 continue;
3552 /* Are any of this keycode's keysyms a meta key? */
3554 int code_col;
3556 for (code_col = 0; code_col < syms_per_code; code_col++)
3558 int sym = syms[((code - min_code) * syms_per_code) + code_col];
3560 switch (sym)
3562 case XK_Meta_L:
3563 case XK_Meta_R:
3564 found_alt_or_meta = 1;
3565 dpyinfo->meta_mod_mask |= (1 << row);
3566 break;
3568 case XK_Alt_L:
3569 case XK_Alt_R:
3570 found_alt_or_meta = 1;
3571 dpyinfo->alt_mod_mask |= (1 << row);
3572 break;
3574 case XK_Hyper_L:
3575 case XK_Hyper_R:
3576 if (!found_alt_or_meta)
3577 dpyinfo->hyper_mod_mask |= (1 << row);
3578 code_col = syms_per_code;
3579 col = mods->max_keypermod;
3580 break;
3582 case XK_Super_L:
3583 case XK_Super_R:
3584 if (!found_alt_or_meta)
3585 dpyinfo->super_mod_mask |= (1 << row);
3586 code_col = syms_per_code;
3587 col = mods->max_keypermod;
3588 break;
3590 case XK_Shift_Lock:
3591 /* Ignore this if it's not on the lock modifier. */
3592 if (!found_alt_or_meta && ((1 << row) == LockMask))
3593 dpyinfo->shift_lock_mask = LockMask;
3594 code_col = syms_per_code;
3595 col = mods->max_keypermod;
3596 break;
3604 /* If we couldn't find any meta keys, accept any alt keys as meta keys. */
3605 if (! dpyinfo->meta_mod_mask)
3607 dpyinfo->meta_mod_mask = dpyinfo->alt_mod_mask;
3608 dpyinfo->alt_mod_mask = 0;
3611 /* If some keys are both alt and meta,
3612 make them just meta, not alt. */
3613 if (dpyinfo->alt_mod_mask & dpyinfo->meta_mod_mask)
3615 dpyinfo->alt_mod_mask &= ~dpyinfo->meta_mod_mask;
3618 XFree ((char *) syms);
3619 XFreeModifiermap (mods);
3622 /* Convert between the modifier bits X uses and the modifier bits
3623 Emacs uses. */
3625 unsigned int
3626 x_x_to_emacs_modifiers (struct x_display_info *dpyinfo, unsigned int state)
3628 EMACS_UINT mod_meta = meta_modifier;
3629 EMACS_UINT mod_alt = alt_modifier;
3630 EMACS_UINT mod_hyper = hyper_modifier;
3631 EMACS_UINT mod_super = super_modifier;
3632 Lisp_Object tem;
3634 tem = Fget (Vx_alt_keysym, Qmodifier_value);
3635 if (! EQ (tem, Qnil)) mod_alt = XUINT (tem);
3636 tem = Fget (Vx_meta_keysym, Qmodifier_value);
3637 if (! EQ (tem, Qnil)) mod_meta = XUINT (tem);
3638 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
3639 if (! EQ (tem, Qnil)) mod_hyper = XUINT (tem);
3640 tem = Fget (Vx_super_keysym, Qmodifier_value);
3641 if (! EQ (tem, Qnil)) mod_super = XUINT (tem);
3644 return ( ((state & (ShiftMask | dpyinfo->shift_lock_mask)) ? shift_modifier : 0)
3645 | ((state & ControlMask) ? ctrl_modifier : 0)
3646 | ((state & dpyinfo->meta_mod_mask) ? mod_meta : 0)
3647 | ((state & dpyinfo->alt_mod_mask) ? mod_alt : 0)
3648 | ((state & dpyinfo->super_mod_mask) ? mod_super : 0)
3649 | ((state & dpyinfo->hyper_mod_mask) ? mod_hyper : 0));
3652 static unsigned int
3653 x_emacs_to_x_modifiers (struct x_display_info *dpyinfo, unsigned int state)
3655 EMACS_UINT mod_meta = meta_modifier;
3656 EMACS_UINT mod_alt = alt_modifier;
3657 EMACS_UINT mod_hyper = hyper_modifier;
3658 EMACS_UINT mod_super = super_modifier;
3660 Lisp_Object tem;
3662 tem = Fget (Vx_alt_keysym, Qmodifier_value);
3663 if (! EQ (tem, Qnil)) mod_alt = XUINT (tem);
3664 tem = Fget (Vx_meta_keysym, Qmodifier_value);
3665 if (! EQ (tem, Qnil)) mod_meta = XUINT (tem);
3666 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
3667 if (! EQ (tem, Qnil)) mod_hyper = XUINT (tem);
3668 tem = Fget (Vx_super_keysym, Qmodifier_value);
3669 if (! EQ (tem, Qnil)) mod_super = XUINT (tem);
3672 return ( ((state & mod_alt) ? dpyinfo->alt_mod_mask : 0)
3673 | ((state & mod_super) ? dpyinfo->super_mod_mask : 0)
3674 | ((state & mod_hyper) ? dpyinfo->hyper_mod_mask : 0)
3675 | ((state & shift_modifier) ? ShiftMask : 0)
3676 | ((state & ctrl_modifier) ? ControlMask : 0)
3677 | ((state & mod_meta) ? dpyinfo->meta_mod_mask : 0));
3680 /* Convert a keysym to its name. */
3682 char *
3683 x_get_keysym_name (int keysym)
3685 char *value;
3687 BLOCK_INPUT;
3688 value = XKeysymToString (keysym);
3689 UNBLOCK_INPUT;
3691 return value;
3696 /* Mouse clicks and mouse movement. Rah. */
3698 /* Prepare a mouse-event in *RESULT for placement in the input queue.
3700 If the event is a button press, then note that we have grabbed
3701 the mouse. */
3703 static Lisp_Object
3704 construct_mouse_click (struct input_event *result, XButtonEvent *event, struct frame *f)
3706 /* Make the event type NO_EVENT; we'll change that when we decide
3707 otherwise. */
3708 result->kind = MOUSE_CLICK_EVENT;
3709 result->code = event->button - Button1;
3710 result->timestamp = event->time;
3711 result->modifiers = (x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO (f),
3712 event->state)
3713 | (event->type == ButtonRelease
3714 ? up_modifier
3715 : down_modifier));
3717 XSETINT (result->x, event->x);
3718 XSETINT (result->y, event->y);
3719 XSETFRAME (result->frame_or_window, f);
3720 result->arg = Qnil;
3721 return Qnil;
3725 /* Function to report a mouse movement to the mainstream Emacs code.
3726 The input handler calls this.
3728 We have received a mouse movement event, which is given in *event.
3729 If the mouse is over a different glyph than it was last time, tell
3730 the mainstream emacs code by setting mouse_moved. If not, ask for
3731 another motion event, so we can check again the next time it moves. */
3733 static XMotionEvent last_mouse_motion_event;
3734 static Lisp_Object last_mouse_motion_frame;
3736 static int
3737 note_mouse_movement (FRAME_PTR frame, XMotionEvent *event)
3739 last_mouse_movement_time = event->time;
3740 last_mouse_motion_event = *event;
3741 XSETFRAME (last_mouse_motion_frame, frame);
3743 if (!FRAME_X_OUTPUT (frame))
3744 return 0;
3746 if (event->window != FRAME_X_WINDOW (frame))
3748 frame->mouse_moved = 1;
3749 last_mouse_scroll_bar = Qnil;
3750 note_mouse_highlight (frame, -1, -1);
3751 last_mouse_glyph_frame = 0;
3752 return 1;
3756 /* Has the mouse moved off the glyph it was on at the last sighting? */
3757 if (frame != last_mouse_glyph_frame
3758 || event->x < last_mouse_glyph.x
3759 || event->x >= last_mouse_glyph.x + last_mouse_glyph.width
3760 || event->y < last_mouse_glyph.y
3761 || event->y >= last_mouse_glyph.y + last_mouse_glyph.height)
3763 frame->mouse_moved = 1;
3764 last_mouse_scroll_bar = Qnil;
3765 note_mouse_highlight (frame, event->x, event->y);
3766 /* Remember which glyph we're now on. */
3767 remember_mouse_glyph (frame, event->x, event->y, &last_mouse_glyph);
3768 last_mouse_glyph_frame = frame;
3769 return 1;
3772 return 0;
3776 /************************************************************************
3777 Mouse Face
3778 ************************************************************************/
3780 static void
3781 redo_mouse_highlight (void)
3783 if (!NILP (last_mouse_motion_frame)
3784 && FRAME_LIVE_P (XFRAME (last_mouse_motion_frame)))
3785 note_mouse_highlight (XFRAME (last_mouse_motion_frame),
3786 last_mouse_motion_event.x,
3787 last_mouse_motion_event.y);
3792 /* Return the current position of the mouse.
3793 *FP should be a frame which indicates which display to ask about.
3795 If the mouse movement started in a scroll bar, set *FP, *BAR_WINDOW,
3796 and *PART to the frame, window, and scroll bar part that the mouse
3797 is over. Set *X and *Y to the portion and whole of the mouse's
3798 position on the scroll bar.
3800 If the mouse movement started elsewhere, set *FP to the frame the
3801 mouse is on, *BAR_WINDOW to nil, and *X and *Y to the character cell
3802 the mouse is over.
3804 Set *TIME to the server time-stamp for the time at which the mouse
3805 was at this position.
3807 Don't store anything if we don't have a valid set of values to report.
3809 This clears the mouse_moved flag, so we can wait for the next mouse
3810 movement. */
3812 static void
3813 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)
3815 FRAME_PTR f1;
3817 BLOCK_INPUT;
3819 if (! NILP (last_mouse_scroll_bar) && insist == 0)
3820 x_scroll_bar_report_motion (fp, bar_window, part, x, y, time);
3821 else
3823 Window root;
3824 int root_x, root_y;
3826 Window dummy_window;
3827 int dummy;
3829 Lisp_Object frame, tail;
3831 /* Clear the mouse-moved flag for every frame on this display. */
3832 FOR_EACH_FRAME (tail, frame)
3833 if (FRAME_X_P (XFRAME (frame))
3834 && FRAME_X_DISPLAY (XFRAME (frame)) == FRAME_X_DISPLAY (*fp))
3835 XFRAME (frame)->mouse_moved = 0;
3837 last_mouse_scroll_bar = Qnil;
3839 /* Figure out which root window we're on. */
3840 XQueryPointer (FRAME_X_DISPLAY (*fp),
3841 DefaultRootWindow (FRAME_X_DISPLAY (*fp)),
3843 /* The root window which contains the pointer. */
3844 &root,
3846 /* Trash which we can't trust if the pointer is on
3847 a different screen. */
3848 &dummy_window,
3850 /* The position on that root window. */
3851 &root_x, &root_y,
3853 /* More trash we can't trust. */
3854 &dummy, &dummy,
3856 /* Modifier keys and pointer buttons, about which
3857 we don't care. */
3858 (unsigned int *) &dummy);
3860 /* Now we have a position on the root; find the innermost window
3861 containing the pointer. */
3863 Window win, child;
3864 int win_x, win_y;
3865 int parent_x = 0, parent_y = 0;
3867 win = root;
3869 /* XTranslateCoordinates can get errors if the window
3870 structure is changing at the same time this function
3871 is running. So at least we must not crash from them. */
3873 x_catch_errors (FRAME_X_DISPLAY (*fp));
3875 if (FRAME_X_DISPLAY_INFO (*fp)->grabbed && last_mouse_frame
3876 && FRAME_LIVE_P (last_mouse_frame))
3878 /* If mouse was grabbed on a frame, give coords for that frame
3879 even if the mouse is now outside it. */
3880 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
3882 /* From-window, to-window. */
3883 root, FRAME_X_WINDOW (last_mouse_frame),
3885 /* From-position, to-position. */
3886 root_x, root_y, &win_x, &win_y,
3888 /* Child of win. */
3889 &child);
3890 f1 = last_mouse_frame;
3892 else
3894 while (1)
3896 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
3898 /* From-window, to-window. */
3899 root, win,
3901 /* From-position, to-position. */
3902 root_x, root_y, &win_x, &win_y,
3904 /* Child of win. */
3905 &child);
3907 if (child == None || child == win)
3908 break;
3909 #ifdef USE_GTK
3910 /* We don't wan't to know the innermost window. We
3911 want the edit window. For non-Gtk+ the innermost
3912 window is the edit window. For Gtk+ it might not
3913 be. It might be the tool bar for example. */
3914 if (x_window_to_frame (FRAME_X_DISPLAY_INFO (*fp), win))
3915 break;
3916 #endif
3917 win = child;
3918 parent_x = win_x;
3919 parent_y = win_y;
3922 /* Now we know that:
3923 win is the innermost window containing the pointer
3924 (XTC says it has no child containing the pointer),
3925 win_x and win_y are the pointer's position in it
3926 (XTC did this the last time through), and
3927 parent_x and parent_y are the pointer's position in win's parent.
3928 (They are what win_x and win_y were when win was child.
3929 If win is the root window, it has no parent, and
3930 parent_{x,y} are invalid, but that's okay, because we'll
3931 never use them in that case.) */
3933 #ifdef USE_GTK
3934 /* We don't wan't to know the innermost window. We
3935 want the edit window. */
3936 f1 = x_window_to_frame (FRAME_X_DISPLAY_INFO (*fp), win);
3937 #else
3938 /* Is win one of our frames? */
3939 f1 = x_any_window_to_frame (FRAME_X_DISPLAY_INFO (*fp), win);
3940 #endif
3942 #ifdef USE_X_TOOLKIT
3943 /* If we end up with the menu bar window, say it's not
3944 on the frame. */
3945 if (f1 != NULL
3946 && f1->output_data.x->menubar_widget
3947 && win == XtWindow (f1->output_data.x->menubar_widget))
3948 f1 = NULL;
3949 #endif /* USE_X_TOOLKIT */
3952 if (x_had_errors_p (FRAME_X_DISPLAY (*fp)))
3953 f1 = 0;
3955 x_uncatch_errors ();
3957 /* If not, is it one of our scroll bars? */
3958 if (! f1)
3960 struct scroll_bar *bar;
3962 bar = x_window_to_scroll_bar (FRAME_X_DISPLAY (*fp), win);
3964 if (bar)
3966 f1 = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
3967 win_x = parent_x;
3968 win_y = parent_y;
3972 if (f1 == 0 && insist > 0)
3973 f1 = SELECTED_FRAME ();
3975 if (f1)
3977 /* Ok, we found a frame. Store all the values.
3978 last_mouse_glyph is a rectangle used to reduce the
3979 generation of mouse events. To not miss any motion
3980 events, we must divide the frame into rectangles of the
3981 size of the smallest character that could be displayed
3982 on it, i.e. into the same rectangles that matrices on
3983 the frame are divided into. */
3985 remember_mouse_glyph (f1, win_x, win_y, &last_mouse_glyph);
3986 last_mouse_glyph_frame = f1;
3988 *bar_window = Qnil;
3989 *part = 0;
3990 *fp = f1;
3991 XSETINT (*x, win_x);
3992 XSETINT (*y, win_y);
3993 *time = last_mouse_movement_time;
3998 UNBLOCK_INPUT;
4003 /***********************************************************************
4004 Scroll bars
4005 ***********************************************************************/
4007 /* Scroll bar support. */
4009 /* Given an X window ID and a DISPLAY, find the struct scroll_bar which
4010 manages it.
4011 This can be called in GC, so we have to make sure to strip off mark
4012 bits. */
4014 static struct scroll_bar *
4015 x_window_to_scroll_bar (Display *display, Window window_id)
4017 Lisp_Object tail;
4019 #if defined (USE_GTK) && defined (USE_TOOLKIT_SCROLL_BARS)
4020 window_id = (Window) xg_get_scroll_id_for_window (display, window_id);
4021 #endif /* USE_GTK && USE_TOOLKIT_SCROLL_BARS */
4023 for (tail = Vframe_list; CONSP (tail); tail = XCDR (tail))
4025 Lisp_Object frame, bar, condemned;
4027 frame = XCAR (tail);
4028 /* All elements of Vframe_list should be frames. */
4029 if (! FRAMEP (frame))
4030 abort ();
4032 if (! FRAME_X_P (XFRAME (frame)))
4033 continue;
4035 /* Scan this frame's scroll bar list for a scroll bar with the
4036 right window ID. */
4037 condemned = FRAME_CONDEMNED_SCROLL_BARS (XFRAME (frame));
4038 for (bar = FRAME_SCROLL_BARS (XFRAME (frame));
4039 /* This trick allows us to search both the ordinary and
4040 condemned scroll bar lists with one loop. */
4041 ! NILP (bar) || (bar = condemned,
4042 condemned = Qnil,
4043 ! NILP (bar));
4044 bar = XSCROLL_BAR (bar)->next)
4045 if (XSCROLL_BAR (bar)->x_window == window_id &&
4046 FRAME_X_DISPLAY (XFRAME (frame)) == display)
4047 return XSCROLL_BAR (bar);
4050 return 0;
4054 #if defined USE_LUCID
4056 /* Return the Lucid menu bar WINDOW is part of. Return null
4057 if WINDOW is not part of a menu bar. */
4059 static Widget
4060 x_window_to_menu_bar (Window window)
4062 Lisp_Object tail;
4064 for (tail = Vframe_list; CONSP (tail); tail = XCDR (tail))
4066 if (FRAME_X_P (XFRAME (XCAR (tail))))
4068 Lisp_Object frame = XCAR (tail);
4069 Widget menu_bar = XFRAME (frame)->output_data.x->menubar_widget;
4071 if (menu_bar && xlwmenu_window_p (menu_bar, window))
4072 return menu_bar;
4076 return NULL;
4079 #endif /* USE_LUCID */
4082 /************************************************************************
4083 Toolkit scroll bars
4084 ************************************************************************/
4086 #ifdef USE_TOOLKIT_SCROLL_BARS
4088 static void x_scroll_bar_to_input_event (XEvent *, struct input_event *);
4089 static void x_send_scroll_bar_event (Lisp_Object, int, int, int);
4090 static void x_create_toolkit_scroll_bar (struct frame *,
4091 struct scroll_bar *);
4092 static void x_set_toolkit_scroll_bar_thumb (struct scroll_bar *,
4093 int, int, int);
4096 /* Lisp window being scrolled. Set when starting to interact with
4097 a toolkit scroll bar, reset to nil when ending the interaction. */
4099 static Lisp_Object window_being_scrolled;
4101 /* Last scroll bar part sent in xm_scroll_callback. */
4103 static int last_scroll_bar_part;
4105 /* Whether this is an Xaw with arrow-scrollbars. This should imply
4106 that movements of 1/20 of the screen size are mapped to up/down. */
4108 #ifndef USE_GTK
4109 /* Id of action hook installed for scroll bars. */
4111 static XtActionHookId action_hook_id;
4113 static Boolean xaw3d_arrow_scroll;
4115 /* Whether the drag scrolling maintains the mouse at the top of the
4116 thumb. If not, resizing the thumb needs to be done more carefully
4117 to avoid jerkyness. */
4119 static Boolean xaw3d_pick_top;
4121 /* Action hook installed via XtAppAddActionHook when toolkit scroll
4122 bars are used.. The hook is responsible for detecting when
4123 the user ends an interaction with the scroll bar, and generates
4124 a `end-scroll' SCROLL_BAR_CLICK_EVENT' event if so. */
4126 static void
4127 xt_action_hook (Widget widget, XtPointer client_data, String action_name,
4128 XEvent *event, String *params, Cardinal *num_params)
4130 int scroll_bar_p;
4131 const char *end_action;
4133 #ifdef USE_MOTIF
4134 scroll_bar_p = XmIsScrollBar (widget);
4135 end_action = "Release";
4136 #else /* !USE_MOTIF i.e. use Xaw */
4137 scroll_bar_p = XtIsSubclass (widget, scrollbarWidgetClass);
4138 end_action = "EndScroll";
4139 #endif /* USE_MOTIF */
4141 if (scroll_bar_p
4142 && strcmp (action_name, end_action) == 0
4143 && WINDOWP (window_being_scrolled))
4145 struct window *w;
4147 x_send_scroll_bar_event (window_being_scrolled,
4148 scroll_bar_end_scroll, 0, 0);
4149 w = XWINDOW (window_being_scrolled);
4151 if (!NILP (XSCROLL_BAR (w->vertical_scroll_bar)->dragging))
4153 XSCROLL_BAR (w->vertical_scroll_bar)->dragging = Qnil;
4154 /* The thumb size is incorrect while dragging: fix it. */
4155 set_vertical_scroll_bar (w);
4157 window_being_scrolled = Qnil;
4158 last_scroll_bar_part = -1;
4160 /* Xt timeouts no longer needed. */
4161 toolkit_scroll_bar_interaction = 0;
4164 #endif /* not USE_GTK */
4166 /* A vector of windows used for communication between
4167 x_send_scroll_bar_event and x_scroll_bar_to_input_event. */
4169 static struct window **scroll_bar_windows;
4170 static int scroll_bar_windows_size;
4173 /* Send a client message with message type Xatom_Scrollbar for a
4174 scroll action to the frame of WINDOW. PART is a value identifying
4175 the part of the scroll bar that was clicked on. PORTION is the
4176 amount to scroll of a whole of WHOLE. */
4178 static void
4179 x_send_scroll_bar_event (Lisp_Object window, int part, int portion, int whole)
4181 XEvent event;
4182 XClientMessageEvent *ev = (XClientMessageEvent *) &event;
4183 struct window *w = XWINDOW (window);
4184 struct frame *f = XFRAME (w->frame);
4185 int i;
4187 BLOCK_INPUT;
4189 /* Construct a ClientMessage event to send to the frame. */
4190 ev->type = ClientMessage;
4191 ev->message_type = FRAME_X_DISPLAY_INFO (f)->Xatom_Scrollbar;
4192 ev->display = FRAME_X_DISPLAY (f);
4193 ev->window = FRAME_X_WINDOW (f);
4194 ev->format = 32;
4196 /* We can only transfer 32 bits in the XClientMessageEvent, which is
4197 not enough to store a pointer or Lisp_Object on a 64 bit system.
4198 So, store the window in scroll_bar_windows and pass the index
4199 into that array in the event. */
4200 for (i = 0; i < scroll_bar_windows_size; ++i)
4201 if (scroll_bar_windows[i] == NULL)
4202 break;
4204 if (i == scroll_bar_windows_size)
4206 int new_size = max (10, 2 * scroll_bar_windows_size);
4207 size_t nbytes = new_size * sizeof *scroll_bar_windows;
4208 size_t old_nbytes = scroll_bar_windows_size * sizeof *scroll_bar_windows;
4210 scroll_bar_windows = (struct window **) xrealloc (scroll_bar_windows,
4211 nbytes);
4212 memset (&scroll_bar_windows[i], 0, nbytes - old_nbytes);
4213 scroll_bar_windows_size = new_size;
4216 scroll_bar_windows[i] = w;
4217 ev->data.l[0] = (long) i;
4218 ev->data.l[1] = (long) part;
4219 ev->data.l[2] = (long) 0;
4220 ev->data.l[3] = (long) portion;
4221 ev->data.l[4] = (long) whole;
4223 /* Make Xt timeouts work while the scroll bar is active. */
4224 toolkit_scroll_bar_interaction = 1;
4225 #ifdef USE_X_TOOLKIT
4226 x_activate_timeout_atimer ();
4227 #endif
4229 /* Setting the event mask to zero means that the message will
4230 be sent to the client that created the window, and if that
4231 window no longer exists, no event will be sent. */
4232 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), False, 0, &event);
4233 UNBLOCK_INPUT;
4237 /* Transform a scroll bar ClientMessage EVENT to an Emacs input event
4238 in *IEVENT. */
4240 static void
4241 x_scroll_bar_to_input_event (XEvent *event, struct input_event *ievent)
4243 XClientMessageEvent *ev = (XClientMessageEvent *) event;
4244 Lisp_Object window;
4245 struct frame *f;
4246 struct window *w;
4248 w = scroll_bar_windows[ev->data.l[0]];
4249 scroll_bar_windows[ev->data.l[0]] = NULL;
4251 XSETWINDOW (window, w);
4252 f = XFRAME (w->frame);
4254 ievent->kind = SCROLL_BAR_CLICK_EVENT;
4255 ievent->frame_or_window = window;
4256 ievent->arg = Qnil;
4257 #ifdef USE_GTK
4258 ievent->timestamp = CurrentTime;
4259 #else
4260 ievent->timestamp = XtLastTimestampProcessed (FRAME_X_DISPLAY (f));
4261 #endif
4262 ievent->part = ev->data.l[1];
4263 ievent->code = ev->data.l[2];
4264 ievent->x = make_number ((int) ev->data.l[3]);
4265 ievent->y = make_number ((int) ev->data.l[4]);
4266 ievent->modifiers = 0;
4270 #ifdef USE_MOTIF
4272 /* Minimum and maximum values used for Motif scroll bars. */
4274 #define XM_SB_MAX 10000000
4277 /* Scroll bar callback for Motif scroll bars. WIDGET is the scroll
4278 bar widget. CLIENT_DATA is a pointer to the scroll_bar structure.
4279 CALL_DATA is a pointer to a XmScrollBarCallbackStruct. */
4281 static void
4282 xm_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
4284 struct scroll_bar *bar = (struct scroll_bar *) client_data;
4285 XmScrollBarCallbackStruct *cs = (XmScrollBarCallbackStruct *) call_data;
4286 int part = -1, whole = 0, portion = 0;
4288 switch (cs->reason)
4290 case XmCR_DECREMENT:
4291 bar->dragging = Qnil;
4292 part = scroll_bar_up_arrow;
4293 break;
4295 case XmCR_INCREMENT:
4296 bar->dragging = Qnil;
4297 part = scroll_bar_down_arrow;
4298 break;
4300 case XmCR_PAGE_DECREMENT:
4301 bar->dragging = Qnil;
4302 part = scroll_bar_above_handle;
4303 break;
4305 case XmCR_PAGE_INCREMENT:
4306 bar->dragging = Qnil;
4307 part = scroll_bar_below_handle;
4308 break;
4310 case XmCR_TO_TOP:
4311 bar->dragging = Qnil;
4312 part = scroll_bar_to_top;
4313 break;
4315 case XmCR_TO_BOTTOM:
4316 bar->dragging = Qnil;
4317 part = scroll_bar_to_bottom;
4318 break;
4320 case XmCR_DRAG:
4322 int slider_size;
4324 /* Get the slider size. */
4325 BLOCK_INPUT;
4326 XtVaGetValues (widget, XmNsliderSize, &slider_size, NULL);
4327 UNBLOCK_INPUT;
4329 whole = XM_SB_MAX - slider_size;
4330 portion = min (cs->value, whole);
4331 part = scroll_bar_handle;
4332 bar->dragging = make_number (cs->value);
4334 break;
4336 case XmCR_VALUE_CHANGED:
4337 break;
4340 if (part >= 0)
4342 window_being_scrolled = bar->window;
4343 last_scroll_bar_part = part;
4344 x_send_scroll_bar_event (bar->window, part, portion, whole);
4348 #elif defined USE_GTK
4350 /* Scroll bar callback for GTK scroll bars. WIDGET is the scroll
4351 bar widget. DATA is a pointer to the scroll_bar structure. */
4353 static gboolean
4354 xg_scroll_callback (GtkRange *range,
4355 GtkScrollType scroll,
4356 gdouble value,
4357 gpointer user_data)
4359 struct scroll_bar *bar = (struct scroll_bar *) user_data;
4360 gdouble position;
4361 int part = -1, whole = 0, portion = 0;
4362 GtkAdjustment *adj = GTK_ADJUSTMENT (gtk_range_get_adjustment (range));
4363 FRAME_PTR f = (FRAME_PTR) g_object_get_data (G_OBJECT (range), XG_FRAME_DATA);
4365 if (xg_ignore_gtk_scrollbar) return FALSE;
4366 position = gtk_adjustment_get_value (adj);
4369 switch (scroll)
4371 case GTK_SCROLL_JUMP:
4372 /* Buttons 1 2 or 3 must be grabbed. */
4373 if (FRAME_X_DISPLAY_INFO (f)->grabbed != 0
4374 && FRAME_X_DISPLAY_INFO (f)->grabbed < (1 << 4))
4376 part = scroll_bar_handle;
4377 whole = gtk_adjustment_get_upper (adj) -
4378 gtk_adjustment_get_page_size (adj);
4379 portion = min ((int)position, whole);
4380 bar->dragging = make_number ((int)portion);
4382 break;
4383 case GTK_SCROLL_STEP_BACKWARD:
4384 part = scroll_bar_up_arrow;
4385 bar->dragging = Qnil;
4386 break;
4387 case GTK_SCROLL_STEP_FORWARD:
4388 part = scroll_bar_down_arrow;
4389 bar->dragging = Qnil;
4390 break;
4391 case GTK_SCROLL_PAGE_BACKWARD:
4392 part = scroll_bar_above_handle;
4393 bar->dragging = Qnil;
4394 break;
4395 case GTK_SCROLL_PAGE_FORWARD:
4396 part = scroll_bar_below_handle;
4397 bar->dragging = Qnil;
4398 break;
4401 if (part >= 0)
4403 window_being_scrolled = bar->window;
4404 last_scroll_bar_part = part;
4405 x_send_scroll_bar_event (bar->window, part, portion, whole);
4408 return FALSE;
4411 /* Callback for button release. Sets dragging to Qnil when dragging is done. */
4413 static gboolean
4414 xg_end_scroll_callback (GtkWidget *widget,
4415 GdkEventButton *event,
4416 gpointer user_data)
4418 struct scroll_bar *bar = (struct scroll_bar *) user_data;
4419 bar->dragging = Qnil;
4420 if (WINDOWP (window_being_scrolled))
4422 x_send_scroll_bar_event (window_being_scrolled,
4423 scroll_bar_end_scroll, 0, 0);
4424 window_being_scrolled = Qnil;
4427 return FALSE;
4431 #else /* not USE_GTK and not USE_MOTIF */
4433 /* Xaw scroll bar callback. Invoked when the thumb is dragged.
4434 WIDGET is the scroll bar widget. CLIENT_DATA is a pointer to the
4435 scroll bar struct. CALL_DATA is a pointer to a float saying where
4436 the thumb is. */
4438 static void
4439 xaw_jump_callback (Widget widget, XtPointer client_data, XtPointer call_data)
4441 struct scroll_bar *bar = (struct scroll_bar *) client_data;
4442 float top = *(float *) call_data;
4443 float shown;
4444 int whole, portion, height;
4445 int part;
4447 /* Get the size of the thumb, a value between 0 and 1. */
4448 BLOCK_INPUT;
4449 XtVaGetValues (widget, XtNshown, &shown, XtNheight, &height, NULL);
4450 UNBLOCK_INPUT;
4452 whole = 10000000;
4453 portion = shown < 1 ? top * whole : 0;
4455 if (shown < 1 && (eabs (top + shown - 1) < 1.0/height))
4456 /* Some derivatives of Xaw refuse to shrink the thumb when you reach
4457 the bottom, so we force the scrolling whenever we see that we're
4458 too close to the bottom (in x_set_toolkit_scroll_bar_thumb
4459 we try to ensure that we always stay two pixels away from the
4460 bottom). */
4461 part = scroll_bar_down_arrow;
4462 else
4463 part = scroll_bar_handle;
4465 window_being_scrolled = bar->window;
4466 bar->dragging = make_number (portion);
4467 last_scroll_bar_part = part;
4468 x_send_scroll_bar_event (bar->window, part, portion, whole);
4472 /* Xaw scroll bar callback. Invoked for incremental scrolling.,
4473 i.e. line or page up or down. WIDGET is the Xaw scroll bar
4474 widget. CLIENT_DATA is a pointer to the scroll_bar structure for
4475 the scroll bar. CALL_DATA is an integer specifying the action that
4476 has taken place. Its magnitude is in the range 0..height of the
4477 scroll bar. Negative values mean scroll towards buffer start.
4478 Values < height of scroll bar mean line-wise movement. */
4480 static void
4481 xaw_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
4483 struct scroll_bar *bar = (struct scroll_bar *) client_data;
4484 /* The position really is stored cast to a pointer. */
4485 int position = (long) call_data;
4486 Dimension height;
4487 int part;
4489 /* Get the height of the scroll bar. */
4490 BLOCK_INPUT;
4491 XtVaGetValues (widget, XtNheight, &height, NULL);
4492 UNBLOCK_INPUT;
4494 if (eabs (position) >= height)
4495 part = (position < 0) ? scroll_bar_above_handle : scroll_bar_below_handle;
4497 /* If Xaw3d was compiled with ARROW_SCROLLBAR,
4498 it maps line-movement to call_data = max(5, height/20). */
4499 else if (xaw3d_arrow_scroll && eabs (position) <= max (5, height / 20))
4500 part = (position < 0) ? scroll_bar_up_arrow : scroll_bar_down_arrow;
4501 else
4502 part = scroll_bar_move_ratio;
4504 window_being_scrolled = bar->window;
4505 bar->dragging = Qnil;
4506 last_scroll_bar_part = part;
4507 x_send_scroll_bar_event (bar->window, part, position, height);
4510 #endif /* not USE_GTK and not USE_MOTIF */
4512 #define SCROLL_BAR_NAME "verticalScrollBar"
4514 /* Create the widget for scroll bar BAR on frame F. Record the widget
4515 and X window of the scroll bar in BAR. */
4517 #ifdef USE_GTK
4518 static void
4519 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
4521 const char *scroll_bar_name = SCROLL_BAR_NAME;
4523 BLOCK_INPUT;
4524 xg_create_scroll_bar (f, bar, G_CALLBACK (xg_scroll_callback),
4525 G_CALLBACK (xg_end_scroll_callback),
4526 scroll_bar_name);
4527 UNBLOCK_INPUT;
4530 #else /* not USE_GTK */
4532 static void
4533 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
4535 Window xwindow;
4536 Widget widget;
4537 Arg av[20];
4538 int ac = 0;
4539 char *scroll_bar_name = SCROLL_BAR_NAME;
4540 unsigned long pixel;
4542 BLOCK_INPUT;
4544 #ifdef USE_MOTIF
4545 /* Set resources. Create the widget. */
4546 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
4547 XtSetArg (av[ac], XmNminimum, 0); ++ac;
4548 XtSetArg (av[ac], XmNmaximum, XM_SB_MAX); ++ac;
4549 XtSetArg (av[ac], XmNorientation, XmVERTICAL); ++ac;
4550 XtSetArg (av[ac], XmNprocessingDirection, XmMAX_ON_BOTTOM), ++ac;
4551 XtSetArg (av[ac], XmNincrement, 1); ++ac;
4552 XtSetArg (av[ac], XmNpageIncrement, 1); ++ac;
4554 pixel = f->output_data.x->scroll_bar_foreground_pixel;
4555 if (pixel != -1)
4557 XtSetArg (av[ac], XmNforeground, pixel);
4558 ++ac;
4561 pixel = f->output_data.x->scroll_bar_background_pixel;
4562 if (pixel != -1)
4564 XtSetArg (av[ac], XmNbackground, pixel);
4565 ++ac;
4568 widget = XmCreateScrollBar (f->output_data.x->edit_widget,
4569 scroll_bar_name, av, ac);
4571 /* Add one callback for everything that can happen. */
4572 XtAddCallback (widget, XmNdecrementCallback, xm_scroll_callback,
4573 (XtPointer) bar);
4574 XtAddCallback (widget, XmNdragCallback, xm_scroll_callback,
4575 (XtPointer) bar);
4576 XtAddCallback (widget, XmNincrementCallback, xm_scroll_callback,
4577 (XtPointer) bar);
4578 XtAddCallback (widget, XmNpageDecrementCallback, xm_scroll_callback,
4579 (XtPointer) bar);
4580 XtAddCallback (widget, XmNpageIncrementCallback, xm_scroll_callback,
4581 (XtPointer) bar);
4582 XtAddCallback (widget, XmNtoBottomCallback, xm_scroll_callback,
4583 (XtPointer) bar);
4584 XtAddCallback (widget, XmNtoTopCallback, xm_scroll_callback,
4585 (XtPointer) bar);
4587 /* Realize the widget. Only after that is the X window created. */
4588 XtRealizeWidget (widget);
4590 /* Set the cursor to an arrow. I didn't find a resource to do that.
4591 And I'm wondering why it hasn't an arrow cursor by default. */
4592 XDefineCursor (XtDisplay (widget), XtWindow (widget),
4593 f->output_data.x->nontext_cursor);
4595 #else /* !USE_MOTIF i.e. use Xaw */
4597 /* Set resources. Create the widget. The background of the
4598 Xaw3d scroll bar widget is a little bit light for my taste.
4599 We don't alter it here to let users change it according
4600 to their taste with `emacs*verticalScrollBar.background: xxx'. */
4601 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
4602 XtSetArg (av[ac], XtNorientation, XtorientVertical); ++ac;
4603 /* For smoother scrolling with Xaw3d -sm */
4604 /* XtSetArg (av[ac], XtNpickTop, True); ++ac; */
4606 pixel = f->output_data.x->scroll_bar_foreground_pixel;
4607 if (pixel != -1)
4609 XtSetArg (av[ac], XtNforeground, pixel);
4610 ++ac;
4613 pixel = f->output_data.x->scroll_bar_background_pixel;
4614 if (pixel != -1)
4616 XtSetArg (av[ac], XtNbackground, pixel);
4617 ++ac;
4620 /* Top/bottom shadow colors. */
4622 /* Allocate them, if necessary. */
4623 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1)
4625 pixel = f->output_data.x->scroll_bar_background_pixel;
4626 if (pixel != -1)
4628 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
4629 FRAME_X_COLORMAP (f),
4630 &pixel, 1.2, 0x8000))
4631 pixel = -1;
4632 f->output_data.x->scroll_bar_top_shadow_pixel = pixel;
4635 if (f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
4637 pixel = f->output_data.x->scroll_bar_background_pixel;
4638 if (pixel != -1)
4640 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
4641 FRAME_X_COLORMAP (f),
4642 &pixel, 0.6, 0x4000))
4643 pixel = -1;
4644 f->output_data.x->scroll_bar_bottom_shadow_pixel = pixel;
4648 #ifdef XtNbeNiceToColormap
4649 /* Tell the toolkit about them. */
4650 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1
4651 || f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
4652 /* We tried to allocate a color for the top/bottom shadow, and
4653 failed, so tell Xaw3d to use dithering instead. */
4654 /* But only if we have a small colormap. Xaw3d can allocate nice
4655 colors itself. */
4657 XtSetArg (av[ac], XtNbeNiceToColormap,
4658 DefaultDepthOfScreen (FRAME_X_SCREEN (f)) < 16);
4659 ++ac;
4661 else
4662 /* Tell what colors Xaw3d should use for the top/bottom shadow, to
4663 be more consistent with other emacs 3d colors, and since Xaw3d is
4664 not good at dealing with allocation failure. */
4666 /* This tells Xaw3d to use real colors instead of dithering for
4667 the shadows. */
4668 XtSetArg (av[ac], XtNbeNiceToColormap, False);
4669 ++ac;
4671 /* Specify the colors. */
4672 pixel = f->output_data.x->scroll_bar_top_shadow_pixel;
4673 if (pixel != -1)
4675 XtSetArg (av[ac], XtNtopShadowPixel, pixel);
4676 ++ac;
4678 pixel = f->output_data.x->scroll_bar_bottom_shadow_pixel;
4679 if (pixel != -1)
4681 XtSetArg (av[ac], XtNbottomShadowPixel, pixel);
4682 ++ac;
4685 #endif
4687 widget = XtCreateWidget (scroll_bar_name, scrollbarWidgetClass,
4688 f->output_data.x->edit_widget, av, ac);
4691 char *initial = "";
4692 char *val = initial;
4693 XtVaGetValues (widget, XtNscrollVCursor, (XtPointer) &val,
4694 #ifdef XtNarrowScrollbars
4695 XtNarrowScrollbars, (XtPointer) &xaw3d_arrow_scroll,
4696 #endif
4697 XtNpickTop, (XtPointer) &xaw3d_pick_top, NULL);
4698 if (xaw3d_arrow_scroll || val == initial)
4699 { /* ARROW_SCROLL */
4700 xaw3d_arrow_scroll = True;
4701 /* Isn't that just a personal preference ? --Stef */
4702 XtVaSetValues (widget, XtNcursorName, "top_left_arrow", NULL);
4706 /* Define callbacks. */
4707 XtAddCallback (widget, XtNjumpProc, xaw_jump_callback, (XtPointer) bar);
4708 XtAddCallback (widget, XtNscrollProc, xaw_scroll_callback,
4709 (XtPointer) bar);
4711 /* Realize the widget. Only after that is the X window created. */
4712 XtRealizeWidget (widget);
4714 #endif /* !USE_MOTIF */
4716 /* Install an action hook that lets us detect when the user
4717 finishes interacting with a scroll bar. */
4718 if (action_hook_id == 0)
4719 action_hook_id = XtAppAddActionHook (Xt_app_con, xt_action_hook, 0);
4721 /* Remember X window and widget in the scroll bar vector. */
4722 SET_SCROLL_BAR_X_WIDGET (bar, widget);
4723 xwindow = XtWindow (widget);
4724 bar->x_window = xwindow;
4726 UNBLOCK_INPUT;
4728 #endif /* not USE_GTK */
4731 /* Set the thumb size and position of scroll bar BAR. We are currently
4732 displaying PORTION out of a whole WHOLE, and our position POSITION. */
4734 #ifdef USE_GTK
4735 static void
4736 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position, int whole)
4738 xg_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
4741 #else /* not USE_GTK */
4742 static void
4743 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position,
4744 int whole)
4746 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
4747 Widget widget = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
4748 float top, shown;
4750 BLOCK_INPUT;
4752 #ifdef USE_MOTIF
4754 /* We use an estimate of 30 chars per line rather than the real
4755 `portion' value. This has the disadvantage that the thumb size
4756 is not very representative, but it makes our life a lot easier.
4757 Otherwise, we have to constantly adjust the thumb size, which
4758 we can't always do quickly enough: while dragging, the size of
4759 the thumb might prevent the user from dragging the thumb all the
4760 way to the end. but Motif and some versions of Xaw3d don't allow
4761 updating the thumb size while dragging. Also, even if we can update
4762 its size, the update will often happen too late.
4763 If you don't believe it, check out revision 1.650 of xterm.c to see
4764 what hoops we were going through and the still poor behavior we got. */
4765 portion = WINDOW_TOTAL_LINES (XWINDOW (bar->window)) * 30;
4766 /* When the thumb is at the bottom, position == whole.
4767 So we need to increase `whole' to make space for the thumb. */
4768 whole += portion;
4770 if (whole <= 0)
4771 top = 0, shown = 1;
4772 else
4774 top = (float) position / whole;
4775 shown = (float) portion / whole;
4778 if (NILP (bar->dragging))
4780 int size, value;
4782 /* Slider size. Must be in the range [1 .. MAX - MIN] where MAX
4783 is the scroll bar's maximum and MIN is the scroll bar's minimum
4784 value. */
4785 size = shown * XM_SB_MAX;
4786 size = min (size, XM_SB_MAX);
4787 size = max (size, 1);
4789 /* Position. Must be in the range [MIN .. MAX - SLIDER_SIZE]. */
4790 value = top * XM_SB_MAX;
4791 value = min (value, XM_SB_MAX - size);
4793 XmScrollBarSetValues (widget, value, size, 0, 0, False);
4795 #else /* !USE_MOTIF i.e. use Xaw */
4797 if (whole == 0)
4798 top = 0, shown = 1;
4799 else
4801 top = (float) position / whole;
4802 shown = (float) portion / whole;
4806 float old_top, old_shown;
4807 Dimension height;
4808 XtVaGetValues (widget,
4809 XtNtopOfThumb, &old_top,
4810 XtNshown, &old_shown,
4811 XtNheight, &height,
4812 NULL);
4814 /* Massage the top+shown values. */
4815 if (NILP (bar->dragging) || last_scroll_bar_part == scroll_bar_down_arrow)
4816 top = max (0, min (1, top));
4817 else
4818 top = old_top;
4819 /* Keep two pixels available for moving the thumb down. */
4820 shown = max (0, min (1 - top - (2.0 / height), shown));
4822 /* If the call to XawScrollbarSetThumb below doesn't seem to work,
4823 check that your system's configuration file contains a define
4824 for `NARROWPROTO'. See s/freebsd.h for an example. */
4825 if (top != old_top || shown != old_shown)
4827 if (NILP (bar->dragging))
4828 XawScrollbarSetThumb (widget, top, shown);
4829 else
4831 /* Try to make the scrolling a tad smoother. */
4832 if (!xaw3d_pick_top)
4833 shown = min (shown, old_shown);
4835 XawScrollbarSetThumb (widget, top, shown);
4839 #endif /* !USE_MOTIF */
4841 UNBLOCK_INPUT;
4843 #endif /* not USE_GTK */
4845 #endif /* USE_TOOLKIT_SCROLL_BARS */
4849 /************************************************************************
4850 Scroll bars, general
4851 ************************************************************************/
4853 /* Create a scroll bar and return the scroll bar vector for it. W is
4854 the Emacs window on which to create the scroll bar. TOP, LEFT,
4855 WIDTH and HEIGHT are the pixel coordinates and dimensions of the
4856 scroll bar. */
4858 static struct scroll_bar *
4859 x_scroll_bar_create (struct window *w, int top, int left, int width, int height)
4861 struct frame *f = XFRAME (w->frame);
4862 struct scroll_bar *bar
4863 = ALLOCATE_PSEUDOVECTOR (struct scroll_bar, x_window, PVEC_OTHER);
4865 BLOCK_INPUT;
4867 #ifdef USE_TOOLKIT_SCROLL_BARS
4868 x_create_toolkit_scroll_bar (f, bar);
4869 #else /* not USE_TOOLKIT_SCROLL_BARS */
4871 XSetWindowAttributes a;
4872 unsigned long mask;
4873 Window window;
4875 a.background_pixel = f->output_data.x->scroll_bar_background_pixel;
4876 if (a.background_pixel == -1)
4877 a.background_pixel = FRAME_BACKGROUND_PIXEL (f);
4879 a.event_mask = (ButtonPressMask | ButtonReleaseMask
4880 | ButtonMotionMask | PointerMotionHintMask
4881 | ExposureMask);
4882 a.cursor = FRAME_X_DISPLAY_INFO (f)->vertical_scroll_bar_cursor;
4884 mask = (CWBackPixel | CWEventMask | CWCursor);
4886 /* Clear the area of W that will serve as a scroll bar. This is
4887 for the case that a window has been split horizontally. In
4888 this case, no clear_frame is generated to reduce flickering. */
4889 if (width > 0 && height > 0)
4890 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4891 left, top, width,
4892 window_box_height (w), False);
4894 window = XCreateWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4895 /* Position and size of scroll bar. */
4896 left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
4897 top,
4898 width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
4899 height,
4900 /* Border width, depth, class, and visual. */
4902 CopyFromParent,
4903 CopyFromParent,
4904 CopyFromParent,
4905 /* Attributes. */
4906 mask, &a);
4907 bar->x_window = window;
4909 #endif /* not USE_TOOLKIT_SCROLL_BARS */
4911 XSETWINDOW (bar->window, w);
4912 bar->top = top;
4913 bar->left = left;
4914 bar->width = width;
4915 bar->height = height;
4916 bar->start = 0;
4917 bar->end = 0;
4918 bar->dragging = Qnil;
4919 bar->fringe_extended_p = 0;
4921 /* Add bar to its frame's list of scroll bars. */
4922 bar->next = FRAME_SCROLL_BARS (f);
4923 bar->prev = Qnil;
4924 XSETVECTOR (FRAME_SCROLL_BARS (f), bar);
4925 if (!NILP (bar->next))
4926 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
4928 /* Map the window/widget. */
4929 #ifdef USE_TOOLKIT_SCROLL_BARS
4931 #ifdef USE_GTK
4932 xg_update_scrollbar_pos (f,
4933 bar->x_window,
4934 top,
4935 left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
4936 width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
4937 max (height, 1));
4938 #else /* not USE_GTK */
4939 Widget scroll_bar = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
4940 XtConfigureWidget (scroll_bar,
4941 left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
4942 top,
4943 width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
4944 max (height, 1), 0);
4945 XtMapWidget (scroll_bar);
4946 #endif /* not USE_GTK */
4948 #else /* not USE_TOOLKIT_SCROLL_BARS */
4949 XMapRaised (FRAME_X_DISPLAY (f), bar->x_window);
4950 #endif /* not USE_TOOLKIT_SCROLL_BARS */
4952 UNBLOCK_INPUT;
4953 return bar;
4957 #ifndef USE_TOOLKIT_SCROLL_BARS
4959 /* Draw BAR's handle in the proper position.
4961 If the handle is already drawn from START to END, don't bother
4962 redrawing it, unless REBUILD is non-zero; in that case, always
4963 redraw it. (REBUILD is handy for drawing the handle after expose
4964 events.)
4966 Normally, we want to constrain the start and end of the handle to
4967 fit inside its rectangle, but if the user is dragging the scroll
4968 bar handle, we want to let them drag it down all the way, so that
4969 the bar's top is as far down as it goes; otherwise, there's no way
4970 to move to the very end of the buffer. */
4972 static void
4973 x_scroll_bar_set_handle (struct scroll_bar *bar, int start, int end, int rebuild)
4975 int dragging = ! NILP (bar->dragging);
4976 Window w = bar->x_window;
4977 FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
4978 GC gc = f->output_data.x->normal_gc;
4980 /* If the display is already accurate, do nothing. */
4981 if (! rebuild
4982 && start == bar->start
4983 && end == bar->end)
4984 return;
4986 BLOCK_INPUT;
4989 int inside_width = VERTICAL_SCROLL_BAR_INSIDE_WIDTH (f, bar->width);
4990 int inside_height = VERTICAL_SCROLL_BAR_INSIDE_HEIGHT (f, bar->height);
4991 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
4993 /* Make sure the values are reasonable, and try to preserve
4994 the distance between start and end. */
4996 int length = end - start;
4998 if (start < 0)
4999 start = 0;
5000 else if (start > top_range)
5001 start = top_range;
5002 end = start + length;
5004 if (end < start)
5005 end = start;
5006 else if (end > top_range && ! dragging)
5007 end = top_range;
5010 /* Store the adjusted setting in the scroll bar. */
5011 bar->start = start;
5012 bar->end = end;
5014 /* Clip the end position, just for display. */
5015 if (end > top_range)
5016 end = top_range;
5018 /* Draw bottom positions VERTICAL_SCROLL_BAR_MIN_HANDLE pixels
5019 below top positions, to make sure the handle is always at least
5020 that many pixels tall. */
5021 end += VERTICAL_SCROLL_BAR_MIN_HANDLE;
5023 /* Draw the empty space above the handle. Note that we can't clear
5024 zero-height areas; that means "clear to end of window." */
5025 if (0 < start)
5026 x_clear_area (FRAME_X_DISPLAY (f), w,
5027 /* x, y, width, height, and exposures. */
5028 VERTICAL_SCROLL_BAR_LEFT_BORDER,
5029 VERTICAL_SCROLL_BAR_TOP_BORDER,
5030 inside_width, start,
5031 False);
5033 /* Change to proper foreground color if one is specified. */
5034 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5035 XSetForeground (FRAME_X_DISPLAY (f), gc,
5036 f->output_data.x->scroll_bar_foreground_pixel);
5038 /* Draw the handle itself. */
5039 XFillRectangle (FRAME_X_DISPLAY (f), w, gc,
5040 /* x, y, width, height */
5041 VERTICAL_SCROLL_BAR_LEFT_BORDER,
5042 VERTICAL_SCROLL_BAR_TOP_BORDER + start,
5043 inside_width, end - start);
5045 /* Restore the foreground color of the GC if we changed it above. */
5046 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5047 XSetForeground (FRAME_X_DISPLAY (f), gc,
5048 FRAME_FOREGROUND_PIXEL (f));
5050 /* Draw the empty space below the handle. Note that we can't
5051 clear zero-height areas; that means "clear to end of window." */
5052 if (end < inside_height)
5053 x_clear_area (FRAME_X_DISPLAY (f), w,
5054 /* x, y, width, height, and exposures. */
5055 VERTICAL_SCROLL_BAR_LEFT_BORDER,
5056 VERTICAL_SCROLL_BAR_TOP_BORDER + end,
5057 inside_width, inside_height - end,
5058 False);
5062 UNBLOCK_INPUT;
5065 #endif /* !USE_TOOLKIT_SCROLL_BARS */
5067 /* Destroy scroll bar BAR, and set its Emacs window's scroll bar to
5068 nil. */
5070 static void
5071 x_scroll_bar_remove (struct scroll_bar *bar)
5073 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5074 BLOCK_INPUT;
5076 #ifdef USE_TOOLKIT_SCROLL_BARS
5077 #ifdef USE_GTK
5078 xg_remove_scroll_bar (f, bar->x_window);
5079 #else /* not USE_GTK */
5080 XtDestroyWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar));
5081 #endif /* not USE_GTK */
5082 #else
5083 XDestroyWindow (FRAME_X_DISPLAY (f), bar->x_window);
5084 #endif
5086 /* Disassociate this scroll bar from its window. */
5087 XWINDOW (bar->window)->vertical_scroll_bar = Qnil;
5089 UNBLOCK_INPUT;
5093 /* Set the handle of the vertical scroll bar for WINDOW to indicate
5094 that we are displaying PORTION characters out of a total of WHOLE
5095 characters, starting at POSITION. If WINDOW has no scroll bar,
5096 create one. */
5098 static void
5099 XTset_vertical_scroll_bar (struct window *w, int portion, int whole, int position)
5101 struct frame *f = XFRAME (w->frame);
5102 struct scroll_bar *bar;
5103 int top, height, left, sb_left, width, sb_width;
5104 int window_y, window_height;
5105 #ifdef USE_TOOLKIT_SCROLL_BARS
5106 int fringe_extended_p;
5107 #endif
5109 /* Get window dimensions. */
5110 window_box (w, -1, 0, &window_y, 0, &window_height);
5111 top = window_y;
5112 width = WINDOW_CONFIG_SCROLL_BAR_COLS (w) * FRAME_COLUMN_WIDTH (f);
5113 height = window_height;
5115 /* Compute the left edge of the scroll bar area. */
5116 left = WINDOW_SCROLL_BAR_AREA_X (w);
5118 /* Compute the width of the scroll bar which might be less than
5119 the width of the area reserved for the scroll bar. */
5120 if (WINDOW_CONFIG_SCROLL_BAR_WIDTH (w) > 0)
5121 sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
5122 else
5123 sb_width = width;
5125 /* Compute the left edge of the scroll bar. */
5126 #ifdef USE_TOOLKIT_SCROLL_BARS
5127 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w))
5128 sb_left = left + (WINDOW_RIGHTMOST_P (w) ? width - sb_width : 0);
5129 else
5130 sb_left = left + (WINDOW_LEFTMOST_P (w) ? 0 : width - sb_width);
5131 #else
5132 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w))
5133 sb_left = left + width - sb_width;
5134 else
5135 sb_left = left;
5136 #endif
5138 #ifdef USE_TOOLKIT_SCROLL_BARS
5139 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
5140 fringe_extended_p = (WINDOW_LEFTMOST_P (w)
5141 && WINDOW_LEFT_FRINGE_WIDTH (w)
5142 && (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (w)
5143 || WINDOW_LEFT_MARGIN_COLS (w) == 0));
5144 else
5145 fringe_extended_p = (WINDOW_RIGHTMOST_P (w)
5146 && WINDOW_RIGHT_FRINGE_WIDTH (w)
5147 && (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (w)
5148 || WINDOW_RIGHT_MARGIN_COLS (w) == 0));
5149 #endif
5151 /* Does the scroll bar exist yet? */
5152 if (NILP (w->vertical_scroll_bar))
5154 if (width > 0 && height > 0)
5156 BLOCK_INPUT;
5157 #ifdef USE_TOOLKIT_SCROLL_BARS
5158 if (fringe_extended_p)
5159 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5160 sb_left, top, sb_width, height, False);
5161 else
5162 #endif
5163 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5164 left, top, width, height, False);
5165 UNBLOCK_INPUT;
5168 bar = x_scroll_bar_create (w, top, sb_left, sb_width, height);
5170 else
5172 /* It may just need to be moved and resized. */
5173 unsigned int mask = 0;
5175 bar = XSCROLL_BAR (w->vertical_scroll_bar);
5177 BLOCK_INPUT;
5179 if (sb_left != bar->left)
5180 mask |= CWX;
5181 if (top != bar->top)
5182 mask |= CWY;
5183 if (sb_width != bar->width)
5184 mask |= CWWidth;
5185 if (height != bar->height)
5186 mask |= CWHeight;
5188 #ifdef USE_TOOLKIT_SCROLL_BARS
5190 /* Move/size the scroll bar widget. */
5191 if (mask || bar->fringe_extended_p != fringe_extended_p)
5193 /* Since toolkit scroll bars are smaller than the space reserved
5194 for them on the frame, we have to clear "under" them. */
5195 if (width > 0 && height > 0)
5197 if (fringe_extended_p)
5198 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5199 sb_left, top, sb_width, height, False);
5200 else
5201 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5202 left, top, width, height, False);
5204 #ifdef USE_GTK
5205 xg_update_scrollbar_pos (f,
5206 bar->x_window,
5207 top,
5208 sb_left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5209 sb_width - VERTICAL_SCROLL_BAR_WIDTH_TRIM *2,
5210 max (height, 1));
5211 #else /* not USE_GTK */
5212 XtConfigureWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar),
5213 sb_left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5214 top,
5215 sb_width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
5216 max (height, 1), 0);
5217 #endif /* not USE_GTK */
5219 #else /* not USE_TOOLKIT_SCROLL_BARS */
5221 /* Clear areas not covered by the scroll bar because of
5222 VERTICAL_SCROLL_BAR_WIDTH_TRIM. */
5223 if (VERTICAL_SCROLL_BAR_WIDTH_TRIM)
5225 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5226 left, top, VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5227 height, False);
5228 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5229 left + width - VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5230 top, VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5231 height, False);
5234 /* Clear areas not covered by the scroll bar because it's not as
5235 wide as the area reserved for it. This makes sure a
5236 previous mode line display is cleared after C-x 2 C-x 1, for
5237 example. */
5239 int area_width = WINDOW_CONFIG_SCROLL_BAR_COLS (w) * FRAME_COLUMN_WIDTH (f);
5240 int rest = area_width - sb_width;
5241 if (rest > 0 && height > 0)
5243 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
5244 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5245 left + area_width - rest, top,
5246 rest, height, False);
5247 else
5248 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5249 left, top, rest, height, False);
5253 /* Move/size the scroll bar window. */
5254 if (mask)
5256 XWindowChanges wc;
5258 wc.x = sb_left + VERTICAL_SCROLL_BAR_WIDTH_TRIM;
5259 wc.y = top;
5260 wc.width = sb_width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2;
5261 wc.height = height;
5262 XConfigureWindow (FRAME_X_DISPLAY (f), bar->x_window,
5263 mask, &wc);
5266 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5268 /* Remember new settings. */
5269 bar->left = sb_left;
5270 bar->top = top;
5271 bar->width = sb_width;
5272 bar->height = height;
5274 UNBLOCK_INPUT;
5277 #ifdef USE_TOOLKIT_SCROLL_BARS
5278 bar->fringe_extended_p = fringe_extended_p;
5280 x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
5281 #else /* not USE_TOOLKIT_SCROLL_BARS */
5282 /* Set the scroll bar's current state, unless we're currently being
5283 dragged. */
5284 if (NILP (bar->dragging))
5286 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, height);
5288 if (whole == 0)
5289 x_scroll_bar_set_handle (bar, 0, top_range, 0);
5290 else
5292 int start = ((double) position * top_range) / whole;
5293 int end = ((double) (position + portion) * top_range) / whole;
5294 x_scroll_bar_set_handle (bar, start, end, 0);
5297 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5299 XSETVECTOR (w->vertical_scroll_bar, bar);
5303 /* The following three hooks are used when we're doing a thorough
5304 redisplay of the frame. We don't explicitly know which scroll bars
5305 are going to be deleted, because keeping track of when windows go
5306 away is a real pain - "Can you say set-window-configuration, boys
5307 and girls?" Instead, we just assert at the beginning of redisplay
5308 that *all* scroll bars are to be removed, and then save a scroll bar
5309 from the fiery pit when we actually redisplay its window. */
5311 /* Arrange for all scroll bars on FRAME to be removed at the next call
5312 to `*judge_scroll_bars_hook'. A scroll bar may be spared if
5313 `*redeem_scroll_bar_hook' is applied to its window before the judgment. */
5315 static void
5316 XTcondemn_scroll_bars (FRAME_PTR frame)
5318 /* Transfer all the scroll bars to FRAME_CONDEMNED_SCROLL_BARS. */
5319 while (! NILP (FRAME_SCROLL_BARS (frame)))
5321 Lisp_Object bar;
5322 bar = FRAME_SCROLL_BARS (frame);
5323 FRAME_SCROLL_BARS (frame) = XSCROLL_BAR (bar)->next;
5324 XSCROLL_BAR (bar)->next = FRAME_CONDEMNED_SCROLL_BARS (frame);
5325 XSCROLL_BAR (bar)->prev = Qnil;
5326 if (! NILP (FRAME_CONDEMNED_SCROLL_BARS (frame)))
5327 XSCROLL_BAR (FRAME_CONDEMNED_SCROLL_BARS (frame))->prev = bar;
5328 FRAME_CONDEMNED_SCROLL_BARS (frame) = bar;
5333 /* Un-mark WINDOW's scroll bar for deletion in this judgment cycle.
5334 Note that WINDOW isn't necessarily condemned at all. */
5336 static void
5337 XTredeem_scroll_bar (struct window *window)
5339 struct scroll_bar *bar;
5340 struct frame *f;
5342 /* We can't redeem this window's scroll bar if it doesn't have one. */
5343 if (NILP (window->vertical_scroll_bar))
5344 abort ();
5346 bar = XSCROLL_BAR (window->vertical_scroll_bar);
5348 /* Unlink it from the condemned list. */
5349 f = XFRAME (WINDOW_FRAME (window));
5350 if (NILP (bar->prev))
5352 /* If the prev pointer is nil, it must be the first in one of
5353 the lists. */
5354 if (EQ (FRAME_SCROLL_BARS (f), window->vertical_scroll_bar))
5355 /* It's not condemned. Everything's fine. */
5356 return;
5357 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
5358 window->vertical_scroll_bar))
5359 FRAME_CONDEMNED_SCROLL_BARS (f) = bar->next;
5360 else
5361 /* If its prev pointer is nil, it must be at the front of
5362 one or the other! */
5363 abort ();
5365 else
5366 XSCROLL_BAR (bar->prev)->next = bar->next;
5368 if (! NILP (bar->next))
5369 XSCROLL_BAR (bar->next)->prev = bar->prev;
5371 bar->next = FRAME_SCROLL_BARS (f);
5372 bar->prev = Qnil;
5373 XSETVECTOR (FRAME_SCROLL_BARS (f), bar);
5374 if (! NILP (bar->next))
5375 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
5378 /* Remove all scroll bars on FRAME that haven't been saved since the
5379 last call to `*condemn_scroll_bars_hook'. */
5381 static void
5382 XTjudge_scroll_bars (FRAME_PTR f)
5384 Lisp_Object bar, next;
5386 bar = FRAME_CONDEMNED_SCROLL_BARS (f);
5388 /* Clear out the condemned list now so we won't try to process any
5389 more events on the hapless scroll bars. */
5390 FRAME_CONDEMNED_SCROLL_BARS (f) = Qnil;
5392 for (; ! NILP (bar); bar = next)
5394 struct scroll_bar *b = XSCROLL_BAR (bar);
5396 x_scroll_bar_remove (b);
5398 next = b->next;
5399 b->next = b->prev = Qnil;
5402 /* Now there should be no references to the condemned scroll bars,
5403 and they should get garbage-collected. */
5407 #ifndef USE_TOOLKIT_SCROLL_BARS
5408 /* Handle an Expose or GraphicsExpose event on a scroll bar. This
5409 is a no-op when using toolkit scroll bars.
5411 This may be called from a signal handler, so we have to ignore GC
5412 mark bits. */
5414 static void
5415 x_scroll_bar_expose (struct scroll_bar *bar, XEvent *event)
5417 Window w = bar->x_window;
5418 FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5419 GC gc = f->output_data.x->normal_gc;
5420 int width_trim = VERTICAL_SCROLL_BAR_WIDTH_TRIM;
5422 BLOCK_INPUT;
5424 x_scroll_bar_set_handle (bar, bar->start, bar->end, 1);
5426 /* Switch to scroll bar foreground color. */
5427 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5428 XSetForeground (FRAME_X_DISPLAY (f), gc,
5429 f->output_data.x->scroll_bar_foreground_pixel);
5431 /* Draw a one-pixel border just inside the edges of the scroll bar. */
5432 XDrawRectangle (FRAME_X_DISPLAY (f), w, gc,
5434 /* x, y, width, height */
5435 0, 0,
5436 bar->width - 1 - width_trim - width_trim,
5437 bar->height - 1);
5439 /* Restore the foreground color of the GC if we changed it above. */
5440 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5441 XSetForeground (FRAME_X_DISPLAY (f), gc,
5442 FRAME_FOREGROUND_PIXEL (f));
5444 UNBLOCK_INPUT;
5447 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5449 /* Handle a mouse click on the scroll bar BAR. If *EMACS_EVENT's kind
5450 is set to something other than NO_EVENT, it is enqueued.
5452 This may be called from a signal handler, so we have to ignore GC
5453 mark bits. */
5456 static void
5457 x_scroll_bar_handle_click (struct scroll_bar *bar, XEvent *event, struct input_event *emacs_event)
5459 if (! WINDOWP (bar->window))
5460 abort ();
5462 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
5463 emacs_event->code = event->xbutton.button - Button1;
5464 emacs_event->modifiers
5465 = (x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO
5466 (XFRAME (WINDOW_FRAME (XWINDOW (bar->window)))),
5467 event->xbutton.state)
5468 | (event->type == ButtonRelease
5469 ? up_modifier
5470 : down_modifier));
5471 emacs_event->frame_or_window = bar->window;
5472 emacs_event->arg = Qnil;
5473 emacs_event->timestamp = event->xbutton.time;
5475 int top_range
5476 = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
5477 int y = event->xbutton.y - VERTICAL_SCROLL_BAR_TOP_BORDER;
5479 if (y < 0) y = 0;
5480 if (y > top_range) y = top_range;
5482 if (y < bar->start)
5483 emacs_event->part = scroll_bar_above_handle;
5484 else if (y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
5485 emacs_event->part = scroll_bar_handle;
5486 else
5487 emacs_event->part = scroll_bar_below_handle;
5489 #ifndef USE_TOOLKIT_SCROLL_BARS
5490 /* If the user has released the handle, set it to its final position. */
5491 if (event->type == ButtonRelease
5492 && ! NILP (bar->dragging))
5494 int new_start = y - XINT (bar->dragging);
5495 int new_end = new_start + bar->end - bar->start;
5497 x_scroll_bar_set_handle (bar, new_start, new_end, 0);
5498 bar->dragging = Qnil;
5500 #endif
5502 XSETINT (emacs_event->x, y);
5503 XSETINT (emacs_event->y, top_range);
5507 #ifndef USE_TOOLKIT_SCROLL_BARS
5509 /* Handle some mouse motion while someone is dragging the scroll bar.
5511 This may be called from a signal handler, so we have to ignore GC
5512 mark bits. */
5514 static void
5515 x_scroll_bar_note_movement (struct scroll_bar *bar, XEvent *event)
5517 FRAME_PTR f = XFRAME (XWINDOW (bar->window)->frame);
5519 last_mouse_movement_time = event->xmotion.time;
5521 f->mouse_moved = 1;
5522 XSETVECTOR (last_mouse_scroll_bar, bar);
5524 /* If we're dragging the bar, display it. */
5525 if (! NILP (bar->dragging))
5527 /* Where should the handle be now? */
5528 int new_start = event->xmotion.y - XINT (bar->dragging);
5530 if (new_start != bar->start)
5532 int new_end = new_start + bar->end - bar->start;
5534 x_scroll_bar_set_handle (bar, new_start, new_end, 0);
5539 #endif /* !USE_TOOLKIT_SCROLL_BARS */
5541 /* Return information to the user about the current position of the mouse
5542 on the scroll bar. */
5544 static void
5545 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)
5547 struct scroll_bar *bar = XSCROLL_BAR (last_mouse_scroll_bar);
5548 Window w = bar->x_window;
5549 FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5550 int win_x, win_y;
5551 Window dummy_window;
5552 int dummy_coord;
5553 unsigned int dummy_mask;
5555 BLOCK_INPUT;
5557 /* Get the mouse's position relative to the scroll bar window, and
5558 report that. */
5559 if (! XQueryPointer (FRAME_X_DISPLAY (f), w,
5561 /* Root, child, root x and root y. */
5562 &dummy_window, &dummy_window,
5563 &dummy_coord, &dummy_coord,
5565 /* Position relative to scroll bar. */
5566 &win_x, &win_y,
5568 /* Mouse buttons and modifier keys. */
5569 &dummy_mask))
5571 else
5573 int top_range
5574 = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
5576 win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
5578 if (! NILP (bar->dragging))
5579 win_y -= XINT (bar->dragging);
5581 if (win_y < 0)
5582 win_y = 0;
5583 if (win_y > top_range)
5584 win_y = top_range;
5586 *fp = f;
5587 *bar_window = bar->window;
5589 if (! NILP (bar->dragging))
5590 *part = scroll_bar_handle;
5591 else if (win_y < bar->start)
5592 *part = scroll_bar_above_handle;
5593 else if (win_y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
5594 *part = scroll_bar_handle;
5595 else
5596 *part = scroll_bar_below_handle;
5598 XSETINT (*x, win_y);
5599 XSETINT (*y, top_range);
5601 f->mouse_moved = 0;
5602 last_mouse_scroll_bar = Qnil;
5605 *time = last_mouse_movement_time;
5607 UNBLOCK_INPUT;
5611 /* The screen has been cleared so we may have changed foreground or
5612 background colors, and the scroll bars may need to be redrawn.
5613 Clear out the scroll bars, and ask for expose events, so we can
5614 redraw them. */
5616 static void
5617 x_scroll_bar_clear (FRAME_PTR f)
5619 #ifndef USE_TOOLKIT_SCROLL_BARS
5620 Lisp_Object bar;
5622 /* We can have scroll bars even if this is 0,
5623 if we just turned off scroll bar mode.
5624 But in that case we should not clear them. */
5625 if (FRAME_HAS_VERTICAL_SCROLL_BARS (f))
5626 for (bar = FRAME_SCROLL_BARS (f); VECTORP (bar);
5627 bar = XSCROLL_BAR (bar)->next)
5628 XClearArea (FRAME_X_DISPLAY (f),
5629 XSCROLL_BAR (bar)->x_window,
5630 0, 0, 0, 0, True);
5631 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5635 /* The main X event-reading loop - XTread_socket. */
5637 /* This holds the state XLookupString needs to implement dead keys
5638 and other tricks known as "compose processing". _X Window System_
5639 says that a portable program can't use this, but Stephen Gildea assures
5640 me that letting the compiler initialize it to zeros will work okay.
5642 This must be defined outside of XTread_socket, for the same reasons
5643 given for enter_timestamp, above. */
5645 static XComposeStatus compose_status;
5647 /* Record the last 100 characters stored
5648 to help debug the loss-of-chars-during-GC problem. */
5650 static int temp_index;
5651 static short temp_buffer[100];
5653 #define STORE_KEYSYM_FOR_DEBUG(keysym) \
5654 if (temp_index == sizeof temp_buffer / sizeof (short)) \
5655 temp_index = 0; \
5656 temp_buffer[temp_index++] = (keysym)
5658 /* Set this to nonzero to fake an "X I/O error"
5659 on a particular display. */
5661 struct x_display_info *XTread_socket_fake_io_error;
5663 /* When we find no input here, we occasionally do a no-op command
5664 to verify that the X server is still running and we can still talk with it.
5665 We try all the open displays, one by one.
5666 This variable is used for cycling thru the displays. */
5668 static struct x_display_info *next_noop_dpyinfo;
5670 #define SET_SAVED_BUTTON_EVENT \
5671 do \
5673 if (f->output_data.x->saved_menu_event == 0) \
5674 f->output_data.x->saved_menu_event \
5675 = (XEvent *) xmalloc (sizeof (XEvent)); \
5676 *f->output_data.x->saved_menu_event = event; \
5677 inev.ie.kind = MENU_BAR_ACTIVATE_EVENT; \
5678 XSETFRAME (inev.ie.frame_or_window, f); \
5680 while (0)
5682 enum
5684 X_EVENT_NORMAL,
5685 X_EVENT_GOTO_OUT,
5686 X_EVENT_DROP
5689 /* Filter events for the current X input method.
5690 DPYINFO is the display this event is for.
5691 EVENT is the X event to filter.
5693 Returns non-zero if the event was filtered, caller shall not process
5694 this event further.
5695 Returns zero if event is wasn't filtered. */
5697 #ifdef HAVE_X_I18N
5698 static int
5699 x_filter_event (struct x_display_info *dpyinfo, XEvent *event)
5701 /* XFilterEvent returns non-zero if the input method has
5702 consumed the event. We pass the frame's X window to
5703 XFilterEvent because that's the one for which the IC
5704 was created. */
5706 struct frame *f1 = x_any_window_to_frame (dpyinfo,
5707 event->xclient.window);
5709 return XFilterEvent (event, f1 ? FRAME_X_WINDOW (f1) : None);
5711 #endif
5713 #ifdef USE_GTK
5714 static int current_count;
5715 static int current_finish;
5716 static struct input_event *current_hold_quit;
5718 /* This is the filter function invoked by the GTK event loop.
5719 It is invoked before the XEvent is translated to a GdkEvent,
5720 so we have a chance to act on the event before GTK. */
5721 static GdkFilterReturn
5722 event_handler_gdk (GdkXEvent *gxev, GdkEvent *ev, gpointer data)
5724 XEvent *xev = (XEvent *) gxev;
5726 BLOCK_INPUT;
5727 if (current_count >= 0)
5729 struct x_display_info *dpyinfo;
5731 dpyinfo = x_display_info_for_display (xev->xany.display);
5733 #ifdef HAVE_X_I18N
5734 /* Filter events for the current X input method.
5735 GTK calls XFilterEvent but not for key press and release,
5736 so we do it here. */
5737 if ((xev->type == KeyPress || xev->type == KeyRelease)
5738 && dpyinfo
5739 && x_filter_event (dpyinfo, xev))
5741 UNBLOCK_INPUT;
5742 return GDK_FILTER_REMOVE;
5744 #endif
5746 if (! dpyinfo)
5747 current_finish = X_EVENT_NORMAL;
5748 else
5749 current_count +=
5750 handle_one_xevent (dpyinfo, xev, &current_finish,
5751 current_hold_quit);
5753 else
5754 current_finish = x_dispatch_event (xev, xev->xany.display);
5756 UNBLOCK_INPUT;
5758 if (current_finish == X_EVENT_GOTO_OUT || current_finish == X_EVENT_DROP)
5759 return GDK_FILTER_REMOVE;
5761 return GDK_FILTER_CONTINUE;
5763 #endif /* USE_GTK */
5766 static void xembed_send_message (struct frame *f, Time time,
5767 enum xembed_message message,
5768 long detail, long data1, long data2);
5770 /* Handles the XEvent EVENT on display DPYINFO.
5772 *FINISH is X_EVENT_GOTO_OUT if caller should stop reading events.
5773 *FINISH is zero if caller should continue reading events.
5774 *FINISH is X_EVENT_DROP if event should not be passed to the toolkit.
5776 We return the number of characters stored into the buffer. */
5778 static int
5779 handle_one_xevent (struct x_display_info *dpyinfo, XEvent *eventp, int *finish, struct input_event *hold_quit)
5781 union {
5782 struct input_event ie;
5783 struct selection_input_event sie;
5784 } inev;
5785 int count = 0;
5786 int do_help = 0;
5787 int nbytes = 0;
5788 struct frame *f = NULL;
5789 struct coding_system coding;
5790 XEvent event = *eventp;
5791 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
5793 *finish = X_EVENT_NORMAL;
5795 EVENT_INIT (inev.ie);
5796 inev.ie.kind = NO_EVENT;
5797 inev.ie.arg = Qnil;
5799 if (pending_event_wait.eventtype == event.type)
5800 pending_event_wait.eventtype = 0; /* Indicates we got it. */
5802 switch (event.type)
5804 case ClientMessage:
5806 if (event.xclient.message_type
5807 == dpyinfo->Xatom_wm_protocols
5808 && event.xclient.format == 32)
5810 if (event.xclient.data.l[0]
5811 == dpyinfo->Xatom_wm_take_focus)
5813 /* Use x_any_window_to_frame because this
5814 could be the shell widget window
5815 if the frame has no title bar. */
5816 f = x_any_window_to_frame (dpyinfo, event.xclient.window);
5817 #ifdef HAVE_X_I18N
5818 /* Not quite sure this is needed -pd */
5819 if (f && FRAME_XIC (f))
5820 XSetICFocus (FRAME_XIC (f));
5821 #endif
5822 #if 0 /* Emacs sets WM hints whose `input' field is `true'. This
5823 instructs the WM to set the input focus automatically for
5824 Emacs with a call to XSetInputFocus. Setting WM_TAKE_FOCUS
5825 tells the WM to send us a ClientMessage WM_TAKE_FOCUS after
5826 it has set the focus. So, XSetInputFocus below is not
5827 needed.
5829 The call to XSetInputFocus below has also caused trouble. In
5830 cases where the XSetInputFocus done by the WM and the one
5831 below are temporally close (on a fast machine), the call
5832 below can generate additional FocusIn events which confuse
5833 Emacs. */
5835 /* Since we set WM_TAKE_FOCUS, we must call
5836 XSetInputFocus explicitly. But not if f is null,
5837 since that might be an event for a deleted frame. */
5838 if (f)
5840 Display *d = event.xclient.display;
5841 /* Catch and ignore errors, in case window has been
5842 iconified by a window manager such as GWM. */
5843 x_catch_errors (d);
5844 XSetInputFocus (d, event.xclient.window,
5845 /* The ICCCM says this is
5846 the only valid choice. */
5847 RevertToParent,
5848 event.xclient.data.l[1]);
5849 /* This is needed to detect the error
5850 if there is an error. */
5851 XSync (d, False);
5852 x_uncatch_errors ();
5854 /* Not certain about handling scroll bars here */
5855 #endif /* 0 */
5856 goto done;
5859 if (event.xclient.data.l[0]
5860 == dpyinfo->Xatom_wm_save_yourself)
5862 /* Save state modify the WM_COMMAND property to
5863 something which can reinstate us. This notifies
5864 the session manager, who's looking for such a
5865 PropertyNotify. Can restart processing when
5866 a keyboard or mouse event arrives. */
5867 /* If we have a session manager, don't set this.
5868 KDE will then start two Emacsen, one for the
5869 session manager and one for this. */
5870 #ifdef HAVE_X_SM
5871 if (! x_session_have_connection ())
5872 #endif
5874 f = x_top_window_to_frame (dpyinfo,
5875 event.xclient.window);
5876 /* This is just so we only give real data once
5877 for a single Emacs process. */
5878 if (f == SELECTED_FRAME ())
5879 XSetCommand (FRAME_X_DISPLAY (f),
5880 event.xclient.window,
5881 initial_argv, initial_argc);
5882 else if (f)
5883 XSetCommand (FRAME_X_DISPLAY (f),
5884 event.xclient.window,
5885 0, 0);
5887 goto done;
5890 if (event.xclient.data.l[0]
5891 == dpyinfo->Xatom_wm_delete_window)
5893 f = x_any_window_to_frame (dpyinfo,
5894 event.xclient.window);
5895 if (!f)
5896 goto OTHER; /* May be a dialog that is to be removed */
5898 inev.ie.kind = DELETE_WINDOW_EVENT;
5899 XSETFRAME (inev.ie.frame_or_window, f);
5900 goto done;
5903 goto done;
5906 if (event.xclient.message_type
5907 == dpyinfo->Xatom_wm_configure_denied)
5909 goto done;
5912 if (event.xclient.message_type
5913 == dpyinfo->Xatom_wm_window_moved)
5915 int new_x, new_y;
5916 f = x_window_to_frame (dpyinfo, event.xclient.window);
5918 new_x = event.xclient.data.s[0];
5919 new_y = event.xclient.data.s[1];
5921 if (f)
5923 f->left_pos = new_x;
5924 f->top_pos = new_y;
5926 goto done;
5929 #ifdef HACK_EDITRES
5930 if (event.xclient.message_type
5931 == dpyinfo->Xatom_editres)
5933 f = x_any_window_to_frame (dpyinfo, event.xclient.window);
5934 if (f)
5935 _XEditResCheckMessages (f->output_data.x->widget, NULL,
5936 &event, NULL);
5937 goto done;
5939 #endif /* HACK_EDITRES */
5941 if ((event.xclient.message_type
5942 == dpyinfo->Xatom_DONE)
5943 || (event.xclient.message_type
5944 == dpyinfo->Xatom_PAGE))
5946 /* Ghostview job completed. Kill it. We could
5947 reply with "Next" if we received "Page", but we
5948 currently never do because we are interested in
5949 images, only, which should have 1 page. */
5950 Pixmap pixmap = (Pixmap) event.xclient.data.l[1];
5951 f = x_window_to_frame (dpyinfo, event.xclient.window);
5952 if (!f)
5953 goto OTHER;
5954 x_kill_gs_process (pixmap, f);
5955 expose_frame (f, 0, 0, 0, 0);
5956 goto done;
5959 #ifdef USE_TOOLKIT_SCROLL_BARS
5960 /* Scroll bar callbacks send a ClientMessage from which
5961 we construct an input_event. */
5962 if (event.xclient.message_type
5963 == dpyinfo->Xatom_Scrollbar)
5965 x_scroll_bar_to_input_event (&event, &inev.ie);
5966 *finish = X_EVENT_GOTO_OUT;
5967 goto done;
5969 #endif /* USE_TOOLKIT_SCROLL_BARS */
5971 /* XEmbed messages from the embedder (if any). */
5972 if (event.xclient.message_type
5973 == dpyinfo->Xatom_XEMBED)
5975 enum xembed_message msg = event.xclient.data.l[1];
5976 if (msg == XEMBED_FOCUS_IN || msg == XEMBED_FOCUS_OUT)
5977 x_detect_focus_change (dpyinfo, &event, &inev.ie);
5979 *finish = X_EVENT_GOTO_OUT;
5980 goto done;
5983 xft_settings_event (dpyinfo, &event);
5985 f = x_any_window_to_frame (dpyinfo, event.xclient.window);
5986 if (!f)
5987 goto OTHER;
5988 if (x_handle_dnd_message (f, &event.xclient, dpyinfo, &inev.ie))
5989 *finish = X_EVENT_DROP;
5991 break;
5993 case SelectionNotify:
5994 last_user_time = event.xselection.time;
5995 #ifdef USE_X_TOOLKIT
5996 if (! x_window_to_frame (dpyinfo, event.xselection.requestor))
5997 goto OTHER;
5998 #endif /* not USE_X_TOOLKIT */
5999 x_handle_selection_notify (&event.xselection);
6000 break;
6002 case SelectionClear: /* Someone has grabbed ownership. */
6003 last_user_time = event.xselectionclear.time;
6004 #ifdef USE_X_TOOLKIT
6005 if (! x_window_to_frame (dpyinfo, event.xselectionclear.window))
6006 goto OTHER;
6007 #endif /* USE_X_TOOLKIT */
6009 XSelectionClearEvent *eventp = (XSelectionClearEvent *) &event;
6011 inev.ie.kind = SELECTION_CLEAR_EVENT;
6012 SELECTION_EVENT_DISPLAY (&inev.sie) = eventp->display;
6013 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
6014 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
6015 inev.ie.frame_or_window = Qnil;
6017 break;
6019 case SelectionRequest: /* Someone wants our selection. */
6020 last_user_time = event.xselectionrequest.time;
6021 #ifdef USE_X_TOOLKIT
6022 if (!x_window_to_frame (dpyinfo, event.xselectionrequest.owner))
6023 goto OTHER;
6024 #endif /* USE_X_TOOLKIT */
6026 XSelectionRequestEvent *eventp
6027 = (XSelectionRequestEvent *) &event;
6029 inev.ie.kind = SELECTION_REQUEST_EVENT;
6030 SELECTION_EVENT_DISPLAY (&inev.sie) = eventp->display;
6031 SELECTION_EVENT_REQUESTOR (&inev.sie) = eventp->requestor;
6032 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
6033 SELECTION_EVENT_TARGET (&inev.sie) = eventp->target;
6034 SELECTION_EVENT_PROPERTY (&inev.sie) = eventp->property;
6035 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
6036 inev.ie.frame_or_window = Qnil;
6038 break;
6040 case PropertyNotify:
6041 last_user_time = event.xproperty.time;
6042 f = x_top_window_to_frame (dpyinfo, event.xproperty.window);
6043 if (f && event.xproperty.atom == dpyinfo->Xatom_net_wm_state)
6044 x_handle_net_wm_state (f, &event.xproperty);
6046 x_handle_property_notify (&event.xproperty);
6047 xft_settings_event (dpyinfo, &event);
6048 goto OTHER;
6050 case ReparentNotify:
6051 f = x_top_window_to_frame (dpyinfo, event.xreparent.window);
6052 if (f)
6054 int x, y;
6055 f->output_data.x->parent_desc = event.xreparent.parent;
6056 x_real_positions (f, &x, &y);
6057 f->left_pos = x;
6058 f->top_pos = y;
6060 /* Perhaps reparented due to a WM restart. Reset this. */
6061 FRAME_X_DISPLAY_INFO (f)->wm_type = X_WMTYPE_UNKNOWN;
6062 FRAME_X_DISPLAY_INFO (f)->net_supported_window = 0;
6064 goto OTHER;
6066 case Expose:
6067 f = x_window_to_frame (dpyinfo, event.xexpose.window);
6068 if (f)
6070 #ifdef USE_GTK
6071 /* This seems to be needed for GTK 2.6. */
6072 x_clear_area (event.xexpose.display,
6073 event.xexpose.window,
6074 event.xexpose.x, event.xexpose.y,
6075 event.xexpose.width, event.xexpose.height,
6076 FALSE);
6077 #endif
6078 if (f->async_visible == 0)
6080 f->async_visible = 1;
6081 f->async_iconified = 0;
6082 f->output_data.x->has_been_visible = 1;
6083 SET_FRAME_GARBAGED (f);
6085 else
6086 expose_frame (f,
6087 event.xexpose.x, event.xexpose.y,
6088 event.xexpose.width, event.xexpose.height);
6090 else
6092 #ifndef USE_TOOLKIT_SCROLL_BARS
6093 struct scroll_bar *bar;
6094 #endif
6095 #if defined USE_LUCID
6096 /* Submenus of the Lucid menu bar aren't widgets
6097 themselves, so there's no way to dispatch events
6098 to them. Recognize this case separately. */
6100 Widget widget
6101 = x_window_to_menu_bar (event.xexpose.window);
6102 if (widget)
6103 xlwmenu_redisplay (widget);
6105 #endif /* USE_LUCID */
6107 #ifdef USE_TOOLKIT_SCROLL_BARS
6108 /* Dispatch event to the widget. */
6109 goto OTHER;
6110 #else /* not USE_TOOLKIT_SCROLL_BARS */
6111 bar = x_window_to_scroll_bar (event.xexpose.display,
6112 event.xexpose.window);
6114 if (bar)
6115 x_scroll_bar_expose (bar, &event);
6116 #ifdef USE_X_TOOLKIT
6117 else
6118 goto OTHER;
6119 #endif /* USE_X_TOOLKIT */
6120 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6122 break;
6124 case GraphicsExpose: /* This occurs when an XCopyArea's
6125 source area was obscured or not
6126 available. */
6127 f = x_window_to_frame (dpyinfo, event.xgraphicsexpose.drawable);
6128 if (f)
6130 expose_frame (f,
6131 event.xgraphicsexpose.x, event.xgraphicsexpose.y,
6132 event.xgraphicsexpose.width,
6133 event.xgraphicsexpose.height);
6135 #ifdef USE_X_TOOLKIT
6136 else
6137 goto OTHER;
6138 #endif /* USE_X_TOOLKIT */
6139 break;
6141 case NoExpose: /* This occurs when an XCopyArea's
6142 source area was completely
6143 available. */
6144 break;
6146 case UnmapNotify:
6147 /* Redo the mouse-highlight after the tooltip has gone. */
6148 if (event.xmap.window == tip_window)
6150 tip_window = 0;
6151 redo_mouse_highlight ();
6154 f = x_top_window_to_frame (dpyinfo, event.xunmap.window);
6155 if (f) /* F may no longer exist if
6156 the frame was deleted. */
6158 /* While a frame is unmapped, display generation is
6159 disabled; you don't want to spend time updating a
6160 display that won't ever be seen. */
6161 f->async_visible = 0;
6162 /* We can't distinguish, from the event, whether the window
6163 has become iconified or invisible. So assume, if it
6164 was previously visible, than now it is iconified.
6165 But x_make_frame_invisible clears both
6166 the visible flag and the iconified flag;
6167 and that way, we know the window is not iconified now. */
6168 if (FRAME_VISIBLE_P (f) || FRAME_ICONIFIED_P (f))
6170 f->async_iconified = 1;
6172 inev.ie.kind = ICONIFY_EVENT;
6173 XSETFRAME (inev.ie.frame_or_window, f);
6176 goto OTHER;
6178 case MapNotify:
6179 if (event.xmap.window == tip_window)
6180 /* The tooltip has been drawn already. Avoid
6181 the SET_FRAME_GARBAGED below. */
6182 goto OTHER;
6184 /* We use x_top_window_to_frame because map events can
6185 come for sub-windows and they don't mean that the
6186 frame is visible. */
6187 f = x_top_window_to_frame (dpyinfo, event.xmap.window);
6188 if (f)
6190 /* wait_reading_process_output will notice this and update
6191 the frame's display structures.
6192 If we where iconified, we should not set garbaged,
6193 because that stops redrawing on Expose events. This looks
6194 bad if we are called from a recursive event loop
6195 (x_dispatch_event), for example when a dialog is up. */
6196 if (! f->async_iconified)
6197 SET_FRAME_GARBAGED (f);
6199 /* Check if fullscreen was specified before we where mapped the
6200 first time, i.e. from the command line. */
6201 if (!f->output_data.x->has_been_visible)
6202 x_check_fullscreen (f);
6204 f->async_visible = 1;
6205 f->async_iconified = 0;
6206 f->output_data.x->has_been_visible = 1;
6208 if (f->iconified)
6210 inev.ie.kind = DEICONIFY_EVENT;
6211 XSETFRAME (inev.ie.frame_or_window, f);
6213 else if (! NILP (Vframe_list)
6214 && ! NILP (XCDR (Vframe_list)))
6215 /* Force a redisplay sooner or later
6216 to update the frame titles
6217 in case this is the second frame. */
6218 record_asynch_buffer_change ();
6220 #ifdef USE_GTK
6221 xg_frame_resized (f, -1, -1);
6222 #endif
6224 goto OTHER;
6226 case KeyPress:
6228 last_user_time = event.xkey.time;
6229 ignore_next_mouse_click_timeout = 0;
6231 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
6232 /* Dispatch KeyPress events when in menu. */
6233 if (popup_activated ())
6234 goto OTHER;
6235 #endif
6237 f = x_any_window_to_frame (dpyinfo, event.xkey.window);
6239 /* If mouse-highlight is an integer, input clears out
6240 mouse highlighting. */
6241 if (!hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight)
6242 && (f == 0
6243 || !EQ (f->tool_bar_window, hlinfo->mouse_face_window)))
6245 clear_mouse_face (hlinfo);
6246 hlinfo->mouse_face_hidden = 1;
6249 #if defined USE_MOTIF && defined USE_TOOLKIT_SCROLL_BARS
6250 if (f == 0)
6252 /* Scroll bars consume key events, but we want
6253 the keys to go to the scroll bar's frame. */
6254 Widget widget = XtWindowToWidget (dpyinfo->display,
6255 event.xkey.window);
6256 if (widget && XmIsScrollBar (widget))
6258 widget = XtParent (widget);
6259 f = x_any_window_to_frame (dpyinfo, XtWindow (widget));
6262 #endif /* USE_MOTIF and USE_TOOLKIT_SCROLL_BARS */
6264 if (f != 0)
6266 KeySym keysym, orig_keysym;
6267 /* al%imercury@uunet.uu.net says that making this 81
6268 instead of 80 fixed a bug whereby meta chars made
6269 his Emacs hang.
6271 It seems that some version of XmbLookupString has
6272 a bug of not returning XBufferOverflow in
6273 status_return even if the input is too long to
6274 fit in 81 bytes. So, we must prepare sufficient
6275 bytes for copy_buffer. 513 bytes (256 chars for
6276 two-byte character set) seems to be a fairly good
6277 approximation. -- 2000.8.10 handa@etl.go.jp */
6278 unsigned char copy_buffer[513];
6279 unsigned char *copy_bufptr = copy_buffer;
6280 int copy_bufsiz = sizeof (copy_buffer);
6281 int modifiers;
6282 Lisp_Object coding_system = Qlatin_1;
6283 Lisp_Object c;
6285 #ifdef USE_GTK
6286 /* Don't pass keys to GTK. A Tab will shift focus to the
6287 tool bar in GTK 2.4. Keys will still go to menus and
6288 dialogs because in that case popup_activated is TRUE
6289 (see above). */
6290 *finish = X_EVENT_DROP;
6291 #endif
6293 event.xkey.state
6294 |= x_emacs_to_x_modifiers (FRAME_X_DISPLAY_INFO (f),
6295 extra_keyboard_modifiers);
6296 modifiers = event.xkey.state;
6298 /* This will have to go some day... */
6300 /* make_lispy_event turns chars into control chars.
6301 Don't do it here because XLookupString is too eager. */
6302 event.xkey.state &= ~ControlMask;
6303 event.xkey.state &= ~(dpyinfo->meta_mod_mask
6304 | dpyinfo->super_mod_mask
6305 | dpyinfo->hyper_mod_mask
6306 | dpyinfo->alt_mod_mask);
6308 /* In case Meta is ComposeCharacter,
6309 clear its status. According to Markus Ehrnsperger
6310 Markus.Ehrnsperger@lehrstuhl-bross.physik.uni-muenchen.de
6311 this enables ComposeCharacter to work whether or
6312 not it is combined with Meta. */
6313 if (modifiers & dpyinfo->meta_mod_mask)
6314 memset (&compose_status, 0, sizeof (compose_status));
6316 #ifdef HAVE_X_I18N
6317 if (FRAME_XIC (f))
6319 Status status_return;
6321 coding_system = Vlocale_coding_system;
6322 nbytes = XmbLookupString (FRAME_XIC (f),
6323 &event.xkey, copy_bufptr,
6324 copy_bufsiz, &keysym,
6325 &status_return);
6326 if (status_return == XBufferOverflow)
6328 copy_bufsiz = nbytes + 1;
6329 copy_bufptr = (unsigned char *) alloca (copy_bufsiz);
6330 nbytes = XmbLookupString (FRAME_XIC (f),
6331 &event.xkey, copy_bufptr,
6332 copy_bufsiz, &keysym,
6333 &status_return);
6335 /* Xutf8LookupString is a new but already deprecated interface. -stef */
6336 if (status_return == XLookupNone)
6337 break;
6338 else if (status_return == XLookupChars)
6340 keysym = NoSymbol;
6341 modifiers = 0;
6343 else if (status_return != XLookupKeySym
6344 && status_return != XLookupBoth)
6345 abort ();
6347 else
6348 nbytes = XLookupString (&event.xkey, copy_bufptr,
6349 copy_bufsiz, &keysym,
6350 &compose_status);
6351 #else
6352 nbytes = XLookupString (&event.xkey, copy_bufptr,
6353 copy_bufsiz, &keysym,
6354 &compose_status);
6355 #endif
6357 /* If not using XIM/XIC, and a compose sequence is in progress,
6358 we break here. Otherwise, chars_matched is always 0. */
6359 if (compose_status.chars_matched > 0 && nbytes == 0)
6360 break;
6362 memset (&compose_status, 0, sizeof (compose_status));
6363 orig_keysym = keysym;
6365 /* Common for all keysym input events. */
6366 XSETFRAME (inev.ie.frame_or_window, f);
6367 inev.ie.modifiers
6368 = x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO (f), modifiers);
6369 inev.ie.timestamp = event.xkey.time;
6371 /* First deal with keysyms which have defined
6372 translations to characters. */
6373 if (keysym >= 32 && keysym < 128)
6374 /* Avoid explicitly decoding each ASCII character. */
6376 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
6377 inev.ie.code = keysym;
6378 goto done_keysym;
6381 /* Keysyms directly mapped to Unicode characters. */
6382 if (keysym >= 0x01000000 && keysym <= 0x0110FFFF)
6384 if (keysym < 0x01000080)
6385 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
6386 else
6387 inev.ie.kind = MULTIBYTE_CHAR_KEYSTROKE_EVENT;
6388 inev.ie.code = keysym & 0xFFFFFF;
6389 goto done_keysym;
6392 /* Now non-ASCII. */
6393 if (HASH_TABLE_P (Vx_keysym_table)
6394 && (NATNUMP (c = Fgethash (make_number (keysym),
6395 Vx_keysym_table,
6396 Qnil))))
6398 inev.ie.kind = (SINGLE_BYTE_CHAR_P (XFASTINT (c))
6399 ? ASCII_KEYSTROKE_EVENT
6400 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
6401 inev.ie.code = XFASTINT (c);
6402 goto done_keysym;
6405 /* Random non-modifier sorts of keysyms. */
6406 if (((keysym >= XK_BackSpace && keysym <= XK_Escape)
6407 || keysym == XK_Delete
6408 #ifdef XK_ISO_Left_Tab
6409 || (keysym >= XK_ISO_Left_Tab
6410 && keysym <= XK_ISO_Enter)
6411 #endif
6412 || IsCursorKey (keysym) /* 0xff50 <= x < 0xff60 */
6413 || IsMiscFunctionKey (keysym) /* 0xff60 <= x < VARIES */
6414 #ifdef HPUX
6415 /* This recognizes the "extended function
6416 keys". It seems there's no cleaner way.
6417 Test IsModifierKey to avoid handling
6418 mode_switch incorrectly. */
6419 || ((unsigned) (keysym) >= XK_Select
6420 && (unsigned)(keysym) < XK_KP_Space)
6421 #endif
6422 #ifdef XK_dead_circumflex
6423 || orig_keysym == XK_dead_circumflex
6424 #endif
6425 #ifdef XK_dead_grave
6426 || orig_keysym == XK_dead_grave
6427 #endif
6428 #ifdef XK_dead_tilde
6429 || orig_keysym == XK_dead_tilde
6430 #endif
6431 #ifdef XK_dead_diaeresis
6432 || orig_keysym == XK_dead_diaeresis
6433 #endif
6434 #ifdef XK_dead_macron
6435 || orig_keysym == XK_dead_macron
6436 #endif
6437 #ifdef XK_dead_degree
6438 || orig_keysym == XK_dead_degree
6439 #endif
6440 #ifdef XK_dead_acute
6441 || orig_keysym == XK_dead_acute
6442 #endif
6443 #ifdef XK_dead_cedilla
6444 || orig_keysym == XK_dead_cedilla
6445 #endif
6446 #ifdef XK_dead_breve
6447 || orig_keysym == XK_dead_breve
6448 #endif
6449 #ifdef XK_dead_ogonek
6450 || orig_keysym == XK_dead_ogonek
6451 #endif
6452 #ifdef XK_dead_caron
6453 || orig_keysym == XK_dead_caron
6454 #endif
6455 #ifdef XK_dead_doubleacute
6456 || orig_keysym == XK_dead_doubleacute
6457 #endif
6458 #ifdef XK_dead_abovedot
6459 || orig_keysym == XK_dead_abovedot
6460 #endif
6461 || IsKeypadKey (keysym) /* 0xff80 <= x < 0xffbe */
6462 || IsFunctionKey (keysym) /* 0xffbe <= x < 0xffe1 */
6463 /* Any "vendor-specific" key is ok. */
6464 || (orig_keysym & (1 << 28))
6465 || (keysym != NoSymbol && nbytes == 0))
6466 && ! (IsModifierKey (orig_keysym)
6467 /* The symbols from XK_ISO_Lock
6468 to XK_ISO_Last_Group_Lock
6469 don't have real modifiers but
6470 should be treated similarly to
6471 Mode_switch by Emacs. */
6472 #if defined XK_ISO_Lock && defined XK_ISO_Last_Group_Lock
6473 || ((unsigned)(orig_keysym)
6474 >= XK_ISO_Lock
6475 && (unsigned)(orig_keysym)
6476 <= XK_ISO_Last_Group_Lock)
6477 #endif
6480 STORE_KEYSYM_FOR_DEBUG (keysym);
6481 /* make_lispy_event will convert this to a symbolic
6482 key. */
6483 inev.ie.kind = NON_ASCII_KEYSTROKE_EVENT;
6484 inev.ie.code = keysym;
6485 goto done_keysym;
6488 { /* Raw bytes, not keysym. */
6489 register int i;
6490 register int c;
6491 int nchars, len;
6493 for (i = 0, nchars = 0; i < nbytes; i++)
6495 if (ASCII_BYTE_P (copy_bufptr[i]))
6496 nchars++;
6497 STORE_KEYSYM_FOR_DEBUG (copy_bufptr[i]);
6500 if (nchars < nbytes)
6502 /* Decode the input data. */
6503 int require;
6505 /* The input should be decoded with `coding_system'
6506 which depends on which X*LookupString function
6507 we used just above and the locale. */
6508 setup_coding_system (coding_system, &coding);
6509 coding.src_multibyte = 0;
6510 coding.dst_multibyte = 1;
6511 /* The input is converted to events, thus we can't
6512 handle composition. Anyway, there's no XIM that
6513 gives us composition information. */
6514 coding.common_flags &= ~CODING_ANNOTATION_MASK;
6516 require = MAX_MULTIBYTE_LENGTH * nbytes;
6517 coding.destination = alloca (require);
6518 coding.dst_bytes = require;
6519 coding.mode |= CODING_MODE_LAST_BLOCK;
6520 decode_coding_c_string (&coding, copy_bufptr, nbytes, Qnil);
6521 nbytes = coding.produced;
6522 nchars = coding.produced_char;
6523 copy_bufptr = coding.destination;
6526 /* Convert the input data to a sequence of
6527 character events. */
6528 for (i = 0; i < nbytes; i += len)
6530 if (nchars == nbytes)
6531 c = copy_bufptr[i], len = 1;
6532 else
6533 c = STRING_CHAR_AND_LENGTH (copy_bufptr + i, len);
6534 inev.ie.kind = (SINGLE_BYTE_CHAR_P (c)
6535 ? ASCII_KEYSTROKE_EVENT
6536 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
6537 inev.ie.code = c;
6538 kbd_buffer_store_event_hold (&inev.ie, hold_quit);
6541 count += nchars;
6543 inev.ie.kind = NO_EVENT; /* Already stored above. */
6545 if (keysym == NoSymbol)
6546 break;
6549 done_keysym:
6550 #ifdef HAVE_X_I18N
6551 /* Don't dispatch this event since XtDispatchEvent calls
6552 XFilterEvent, and two calls in a row may freeze the
6553 client. */
6554 break;
6555 #else
6556 goto OTHER;
6557 #endif
6559 case KeyRelease:
6560 last_user_time = event.xkey.time;
6561 #ifdef HAVE_X_I18N
6562 /* Don't dispatch this event since XtDispatchEvent calls
6563 XFilterEvent, and two calls in a row may freeze the
6564 client. */
6565 break;
6566 #else
6567 goto OTHER;
6568 #endif
6570 case EnterNotify:
6571 last_user_time = event.xcrossing.time;
6572 x_detect_focus_change (dpyinfo, &event, &inev.ie);
6574 f = x_any_window_to_frame (dpyinfo, event.xcrossing.window);
6576 if (f && x_mouse_click_focus_ignore_position)
6577 ignore_next_mouse_click_timeout = event.xmotion.time + 200;
6579 /* EnterNotify counts as mouse movement,
6580 so update things that depend on mouse position. */
6581 if (f && !f->output_data.x->hourglass_p)
6582 note_mouse_movement (f, &event.xmotion);
6583 #ifdef USE_GTK
6584 /* We may get an EnterNotify on the buttons in the toolbar. In that
6585 case we moved out of any highlighted area and need to note this. */
6586 if (!f && last_mouse_glyph_frame)
6587 note_mouse_movement (last_mouse_glyph_frame, &event.xmotion);
6588 #endif
6589 goto OTHER;
6591 case FocusIn:
6592 x_detect_focus_change (dpyinfo, &event, &inev.ie);
6593 goto OTHER;
6595 case LeaveNotify:
6596 last_user_time = event.xcrossing.time;
6597 x_detect_focus_change (dpyinfo, &event, &inev.ie);
6599 f = x_top_window_to_frame (dpyinfo, event.xcrossing.window);
6600 if (f)
6602 if (f == hlinfo->mouse_face_mouse_frame)
6604 /* If we move outside the frame, then we're
6605 certainly no longer on any text in the frame. */
6606 clear_mouse_face (hlinfo);
6607 hlinfo->mouse_face_mouse_frame = 0;
6610 /* Generate a nil HELP_EVENT to cancel a help-echo.
6611 Do it only if there's something to cancel.
6612 Otherwise, the startup message is cleared when
6613 the mouse leaves the frame. */
6614 if (any_help_event_p)
6615 do_help = -1;
6617 #ifdef USE_GTK
6618 /* See comment in EnterNotify above */
6619 else if (last_mouse_glyph_frame)
6620 note_mouse_movement (last_mouse_glyph_frame, &event.xmotion);
6621 #endif
6622 goto OTHER;
6624 case FocusOut:
6625 x_detect_focus_change (dpyinfo, &event, &inev.ie);
6626 goto OTHER;
6628 case MotionNotify:
6630 last_user_time = event.xmotion.time;
6631 previous_help_echo_string = help_echo_string;
6632 help_echo_string = Qnil;
6634 if (dpyinfo->grabbed && last_mouse_frame
6635 && FRAME_LIVE_P (last_mouse_frame))
6636 f = last_mouse_frame;
6637 else
6638 f = x_window_to_frame (dpyinfo, event.xmotion.window);
6640 if (hlinfo->mouse_face_hidden)
6642 hlinfo->mouse_face_hidden = 0;
6643 clear_mouse_face (hlinfo);
6646 #ifdef USE_GTK
6647 if (f && xg_event_is_for_scrollbar (f, &event))
6648 f = 0;
6649 #endif
6650 if (f)
6653 /* Generate SELECT_WINDOW_EVENTs when needed.
6654 Don't let popup menus influence things (bug#1261). */
6655 if (!NILP (Vmouse_autoselect_window) && !popup_activated ())
6657 Lisp_Object window;
6659 window = window_from_coordinates (f,
6660 event.xmotion.x, event.xmotion.y,
6661 0, 0);
6663 /* Window will be selected only when it is not selected now and
6664 last mouse movement event was not in it. Minibuffer window
6665 will be selected only when it is active. */
6666 if (WINDOWP (window)
6667 && !EQ (window, last_window)
6668 && !EQ (window, selected_window)
6669 /* For click-to-focus window managers
6670 create event iff we don't leave the
6671 selected frame. */
6672 && (focus_follows_mouse
6673 || (EQ (XWINDOW (window)->frame,
6674 XWINDOW (selected_window)->frame))))
6676 inev.ie.kind = SELECT_WINDOW_EVENT;
6677 inev.ie.frame_or_window = window;
6680 last_window=window;
6682 if (!note_mouse_movement (f, &event.xmotion))
6683 help_echo_string = previous_help_echo_string;
6685 else
6687 #ifndef USE_TOOLKIT_SCROLL_BARS
6688 struct scroll_bar *bar
6689 = x_window_to_scroll_bar (event.xmotion.display,
6690 event.xmotion.window);
6692 if (bar)
6693 x_scroll_bar_note_movement (bar, &event);
6694 #endif /* USE_TOOLKIT_SCROLL_BARS */
6696 /* If we move outside the frame, then we're
6697 certainly no longer on any text in the frame. */
6698 clear_mouse_face (hlinfo);
6701 /* If the contents of the global variable help_echo_string
6702 has changed, generate a HELP_EVENT. */
6703 if (!NILP (help_echo_string)
6704 || !NILP (previous_help_echo_string))
6705 do_help = 1;
6706 goto OTHER;
6709 case ConfigureNotify:
6710 f = x_top_window_to_frame (dpyinfo, event.xconfigure.window);
6711 #ifdef USE_GTK
6712 if (!f
6713 && (f = x_any_window_to_frame (dpyinfo, event.xconfigure.window))
6714 && event.xconfigure.window == FRAME_X_WINDOW (f))
6716 xg_frame_resized (f, event.xconfigure.width,
6717 event.xconfigure.height);
6718 f = 0;
6720 #endif
6721 if (f)
6723 #ifndef USE_X_TOOLKIT
6724 #ifndef USE_GTK
6725 int rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, event.xconfigure.height);
6726 int columns = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, event.xconfigure.width);
6728 /* In the toolkit version, change_frame_size
6729 is called by the code that handles resizing
6730 of the EmacsFrame widget. */
6732 /* Even if the number of character rows and columns has
6733 not changed, the font size may have changed, so we need
6734 to check the pixel dimensions as well. */
6735 if (columns != FRAME_COLS (f)
6736 || rows != FRAME_LINES (f)
6737 || event.xconfigure.width != FRAME_PIXEL_WIDTH (f)
6738 || event.xconfigure.height != FRAME_PIXEL_HEIGHT (f))
6740 change_frame_size (f, rows, columns, 0, 1, 0);
6741 SET_FRAME_GARBAGED (f);
6742 cancel_mouse_face (f);
6745 FRAME_PIXEL_WIDTH (f) = event.xconfigure.width;
6746 FRAME_PIXEL_HEIGHT (f) = event.xconfigure.height;
6747 #endif /* not USE_GTK */
6748 #endif
6750 #ifdef USE_GTK
6751 /* GTK creates windows but doesn't map them.
6752 Only get real positions when mapped. */
6753 if (FRAME_GTK_OUTER_WIDGET (f)
6754 && gtk_widget_get_mapped (FRAME_GTK_OUTER_WIDGET (f)))
6755 #endif
6757 x_real_positions (f, &f->left_pos, &f->top_pos);
6760 #ifdef HAVE_X_I18N
6761 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMStatusArea))
6762 xic_set_statusarea (f);
6763 #endif
6766 goto OTHER;
6768 case ButtonRelease:
6769 case ButtonPress:
6771 /* If we decide we want to generate an event to be seen
6772 by the rest of Emacs, we put it here. */
6773 int tool_bar_p = 0;
6775 memset (&compose_status, 0, sizeof (compose_status));
6776 last_mouse_glyph_frame = 0;
6777 last_user_time = event.xbutton.time;
6779 if (dpyinfo->grabbed
6780 && last_mouse_frame
6781 && FRAME_LIVE_P (last_mouse_frame))
6782 f = last_mouse_frame;
6783 else
6784 f = x_window_to_frame (dpyinfo, event.xbutton.window);
6786 #ifdef USE_GTK
6787 if (f && xg_event_is_for_scrollbar (f, &event))
6788 f = 0;
6789 #endif
6790 if (f)
6792 /* Is this in the tool-bar? */
6793 if (WINDOWP (f->tool_bar_window)
6794 && WINDOW_TOTAL_LINES (XWINDOW (f->tool_bar_window)))
6796 Lisp_Object window;
6797 int x = event.xbutton.x;
6798 int y = event.xbutton.y;
6800 window = window_from_coordinates (f, x, y, 0, 1);
6801 tool_bar_p = EQ (window, f->tool_bar_window);
6803 if (tool_bar_p && event.xbutton.button < 4)
6805 handle_tool_bar_click (f, x, y,
6806 event.xbutton.type == ButtonPress,
6807 x_x_to_emacs_modifiers (dpyinfo,
6808 event.xbutton.state));
6812 if (!tool_bar_p)
6813 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
6814 if (! popup_activated ())
6815 #endif
6817 if (ignore_next_mouse_click_timeout)
6819 if (event.type == ButtonPress
6820 && (int)(event.xbutton.time - ignore_next_mouse_click_timeout) > 0)
6822 ignore_next_mouse_click_timeout = 0;
6823 construct_mouse_click (&inev.ie, &event.xbutton, f);
6825 if (event.type == ButtonRelease)
6826 ignore_next_mouse_click_timeout = 0;
6828 else
6829 construct_mouse_click (&inev.ie, &event.xbutton, f);
6831 if (FRAME_X_EMBEDDED_P (f))
6832 xembed_send_message (f, event.xbutton.time,
6833 XEMBED_REQUEST_FOCUS, 0, 0, 0);
6835 else
6837 struct scroll_bar *bar
6838 = x_window_to_scroll_bar (event.xbutton.display,
6839 event.xbutton.window);
6841 #ifdef USE_TOOLKIT_SCROLL_BARS
6842 /* Make the "Ctrl-Mouse-2 splits window" work for toolkit
6843 scroll bars. */
6844 if (bar && event.xbutton.state & ControlMask)
6846 x_scroll_bar_handle_click (bar, &event, &inev.ie);
6847 *finish = X_EVENT_DROP;
6849 #else /* not USE_TOOLKIT_SCROLL_BARS */
6850 if (bar)
6851 x_scroll_bar_handle_click (bar, &event, &inev.ie);
6852 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6855 if (event.type == ButtonPress)
6857 dpyinfo->grabbed |= (1 << event.xbutton.button);
6858 last_mouse_frame = f;
6860 if (!tool_bar_p)
6861 last_tool_bar_item = -1;
6863 else
6864 dpyinfo->grabbed &= ~(1 << event.xbutton.button);
6866 /* Ignore any mouse motion that happened before this event;
6867 any subsequent mouse-movement Emacs events should reflect
6868 only motion after the ButtonPress/Release. */
6869 if (f != 0)
6870 f->mouse_moved = 0;
6872 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
6873 f = x_menubar_window_to_frame (dpyinfo, &event);
6874 /* For a down-event in the menu bar,
6875 don't pass it to Xt right now.
6876 Instead, save it away
6877 and we will pass it to Xt from kbd_buffer_get_event.
6878 That way, we can run some Lisp code first. */
6879 if (! popup_activated ()
6880 #ifdef USE_GTK
6881 /* Gtk+ menus only react to the first three buttons. */
6882 && event.xbutton.button < 3
6883 #endif
6884 && f && event.type == ButtonPress
6885 /* Verify the event is really within the menu bar
6886 and not just sent to it due to grabbing. */
6887 && event.xbutton.x >= 0
6888 && event.xbutton.x < FRAME_PIXEL_WIDTH (f)
6889 && event.xbutton.y >= 0
6890 && event.xbutton.y < f->output_data.x->menubar_height
6891 && event.xbutton.same_screen)
6893 SET_SAVED_BUTTON_EVENT;
6894 XSETFRAME (last_mouse_press_frame, f);
6895 *finish = X_EVENT_DROP;
6897 else if (event.type == ButtonPress)
6899 last_mouse_press_frame = Qnil;
6900 goto OTHER;
6902 else
6903 goto OTHER;
6904 #endif /* USE_X_TOOLKIT || USE_GTK */
6906 break;
6908 case CirculateNotify:
6909 goto OTHER;
6911 case CirculateRequest:
6912 goto OTHER;
6914 case VisibilityNotify:
6915 goto OTHER;
6917 case MappingNotify:
6918 /* Someone has changed the keyboard mapping - update the
6919 local cache. */
6920 switch (event.xmapping.request)
6922 case MappingModifier:
6923 x_find_modifier_meanings (dpyinfo);
6924 /* This is meant to fall through. */
6925 case MappingKeyboard:
6926 XRefreshKeyboardMapping (&event.xmapping);
6928 goto OTHER;
6930 case DestroyNotify:
6931 xft_settings_event (dpyinfo, &event);
6932 break;
6934 default:
6935 OTHER:
6936 #ifdef USE_X_TOOLKIT
6937 BLOCK_INPUT;
6938 if (*finish != X_EVENT_DROP)
6939 XtDispatchEvent (&event);
6940 UNBLOCK_INPUT;
6941 #endif /* USE_X_TOOLKIT */
6942 break;
6945 done:
6946 if (inev.ie.kind != NO_EVENT)
6948 kbd_buffer_store_event_hold (&inev.ie, hold_quit);
6949 count++;
6952 if (do_help
6953 && !(hold_quit && hold_quit->kind != NO_EVENT))
6955 Lisp_Object frame;
6957 if (f)
6958 XSETFRAME (frame, f);
6959 else
6960 frame = Qnil;
6962 if (do_help > 0)
6964 any_help_event_p = 1;
6965 gen_help_event (help_echo_string, frame, help_echo_window,
6966 help_echo_object, help_echo_pos);
6968 else
6970 help_echo_string = Qnil;
6971 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
6973 count++;
6976 *eventp = event;
6977 return count;
6981 /* Handles the XEvent EVENT on display DISPLAY.
6982 This is used for event loops outside the normal event handling,
6983 i.e. looping while a popup menu or a dialog is posted.
6985 Returns the value handle_one_xevent sets in the finish argument. */
6987 x_dispatch_event (XEvent *event, Display *display)
6989 struct x_display_info *dpyinfo;
6990 int finish = X_EVENT_NORMAL;
6992 dpyinfo = x_display_info_for_display (display);
6994 if (dpyinfo)
6995 handle_one_xevent (dpyinfo, event, &finish, 0);
6997 return finish;
7001 /* Read events coming from the X server.
7002 This routine is called by the SIGIO handler.
7003 We return as soon as there are no more events to be read.
7005 We return the number of characters stored into the buffer,
7006 thus pretending to be `read' (except the characters we store
7007 in the keyboard buffer can be multibyte, so are not necessarily
7008 C chars).
7010 EXPECTED is nonzero if the caller knows input is available. */
7012 static int
7013 XTread_socket (struct terminal *terminal, int expected, struct input_event *hold_quit)
7015 int count = 0;
7016 XEvent event;
7017 int event_found = 0;
7019 if (interrupt_input_blocked)
7021 interrupt_input_pending = 1;
7022 #ifdef SYNC_INPUT
7023 pending_signals = 1;
7024 #endif
7025 return -1;
7028 interrupt_input_pending = 0;
7029 #ifdef SYNC_INPUT
7030 pending_signals = pending_atimers;
7031 #endif
7032 BLOCK_INPUT;
7034 /* So people can tell when we have read the available input. */
7035 input_signal_count++;
7037 ++handling_signal;
7039 /* For debugging, this gives a way to fake an I/O error. */
7040 if (terminal->display_info.x == XTread_socket_fake_io_error)
7042 XTread_socket_fake_io_error = 0;
7043 x_io_error_quitter (terminal->display_info.x->display);
7046 #ifndef USE_GTK
7047 while (XPending (terminal->display_info.x->display))
7049 int finish;
7051 XNextEvent (terminal->display_info.x->display, &event);
7053 #ifdef HAVE_X_I18N
7054 /* Filter events for the current X input method. */
7055 if (x_filter_event (terminal->display_info.x, &event))
7056 continue;
7057 #endif
7058 event_found = 1;
7060 count += handle_one_xevent (terminal->display_info.x,
7061 &event, &finish, hold_quit);
7063 if (finish == X_EVENT_GOTO_OUT)
7064 goto out;
7067 #else /* USE_GTK */
7069 /* For GTK we must use the GTK event loop. But XEvents gets passed
7070 to our filter function above, and then to the big event switch.
7071 We use a bunch of globals to communicate with our filter function,
7072 that is kind of ugly, but it works.
7074 There is no way to do one display at the time, GTK just does events
7075 from all displays. */
7077 while (gtk_events_pending ())
7079 current_count = count;
7080 current_hold_quit = hold_quit;
7082 gtk_main_iteration ();
7084 count = current_count;
7085 current_count = -1;
7086 current_hold_quit = 0;
7088 if (current_finish == X_EVENT_GOTO_OUT)
7089 break;
7091 #endif /* USE_GTK */
7093 out:;
7095 /* On some systems, an X bug causes Emacs to get no more events
7096 when the window is destroyed. Detect that. (1994.) */
7097 if (! event_found)
7099 /* Emacs and the X Server eats up CPU time if XNoOp is done every time.
7100 One XNOOP in 100 loops will make Emacs terminate.
7101 B. Bretthauer, 1994 */
7102 x_noop_count++;
7103 if (x_noop_count >= 100)
7105 x_noop_count=0;
7107 if (next_noop_dpyinfo == 0)
7108 next_noop_dpyinfo = x_display_list;
7110 XNoOp (next_noop_dpyinfo->display);
7112 /* Each time we get here, cycle through the displays now open. */
7113 next_noop_dpyinfo = next_noop_dpyinfo->next;
7117 /* If the focus was just given to an auto-raising frame,
7118 raise it now. */
7119 /* ??? This ought to be able to handle more than one such frame. */
7120 if (pending_autoraise_frame)
7122 x_raise_frame (pending_autoraise_frame);
7123 pending_autoraise_frame = 0;
7126 --handling_signal;
7127 UNBLOCK_INPUT;
7129 return count;
7135 /***********************************************************************
7136 Text Cursor
7137 ***********************************************************************/
7139 /* Set clipping for output in glyph row ROW. W is the window in which
7140 we operate. GC is the graphics context to set clipping in.
7142 ROW may be a text row or, e.g., a mode line. Text rows must be
7143 clipped to the interior of the window dedicated to text display,
7144 mode lines must be clipped to the whole window. */
7146 static void
7147 x_clip_to_row (struct window *w, struct glyph_row *row, int area, GC gc)
7149 struct frame *f = XFRAME (WINDOW_FRAME (w));
7150 XRectangle clip_rect;
7151 int window_x, window_y, window_width;
7153 window_box (w, area, &window_x, &window_y, &window_width, 0);
7155 clip_rect.x = window_x;
7156 clip_rect.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
7157 clip_rect.y = max (clip_rect.y, window_y);
7158 clip_rect.width = window_width;
7159 clip_rect.height = row->visible_height;
7161 XSetClipRectangles (FRAME_X_DISPLAY (f), gc, 0, 0, &clip_rect, 1, Unsorted);
7165 /* Draw a hollow box cursor on window W in glyph row ROW. */
7167 static void
7168 x_draw_hollow_cursor (struct window *w, struct glyph_row *row)
7170 struct frame *f = XFRAME (WINDOW_FRAME (w));
7171 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
7172 Display *dpy = FRAME_X_DISPLAY (f);
7173 int x, y, wd, h;
7174 XGCValues xgcv;
7175 struct glyph *cursor_glyph;
7176 GC gc;
7178 /* Get the glyph the cursor is on. If we can't tell because
7179 the current matrix is invalid or such, give up. */
7180 cursor_glyph = get_phys_cursor_glyph (w);
7181 if (cursor_glyph == NULL)
7182 return;
7184 /* Compute frame-relative coordinates for phys cursor. */
7185 get_phys_cursor_geometry (w, row, cursor_glyph, &x, &y, &h);
7186 wd = w->phys_cursor_width;
7188 /* The foreground of cursor_gc is typically the same as the normal
7189 background color, which can cause the cursor box to be invisible. */
7190 xgcv.foreground = f->output_data.x->cursor_pixel;
7191 if (dpyinfo->scratch_cursor_gc)
7192 XChangeGC (dpy, dpyinfo->scratch_cursor_gc, GCForeground, &xgcv);
7193 else
7194 dpyinfo->scratch_cursor_gc = XCreateGC (dpy, FRAME_X_WINDOW (f),
7195 GCForeground, &xgcv);
7196 gc = dpyinfo->scratch_cursor_gc;
7198 /* Set clipping, draw the rectangle, and reset clipping again. */
7199 x_clip_to_row (w, row, TEXT_AREA, gc);
7200 XDrawRectangle (dpy, FRAME_X_WINDOW (f), gc, x, y, wd, h - 1);
7201 XSetClipMask (dpy, gc, None);
7205 /* Draw a bar cursor on window W in glyph row ROW.
7207 Implementation note: One would like to draw a bar cursor with an
7208 angle equal to the one given by the font property XA_ITALIC_ANGLE.
7209 Unfortunately, I didn't find a font yet that has this property set.
7210 --gerd. */
7212 static void
7213 x_draw_bar_cursor (struct window *w, struct glyph_row *row, int width, enum text_cursor_kinds kind)
7215 struct frame *f = XFRAME (w->frame);
7216 struct glyph *cursor_glyph;
7218 /* If cursor is out of bounds, don't draw garbage. This can happen
7219 in mini-buffer windows when switching between echo area glyphs
7220 and mini-buffer. */
7221 cursor_glyph = get_phys_cursor_glyph (w);
7222 if (cursor_glyph == NULL)
7223 return;
7225 /* If on an image, draw like a normal cursor. That's usually better
7226 visible than drawing a bar, esp. if the image is large so that
7227 the bar might not be in the window. */
7228 if (cursor_glyph->type == IMAGE_GLYPH)
7230 struct glyph_row *row;
7231 row = MATRIX_ROW (w->current_matrix, w->phys_cursor.vpos);
7232 draw_phys_cursor_glyph (w, row, DRAW_CURSOR);
7234 else
7236 Display *dpy = FRAME_X_DISPLAY (f);
7237 Window window = FRAME_X_WINDOW (f);
7238 GC gc = FRAME_X_DISPLAY_INFO (f)->scratch_cursor_gc;
7239 unsigned long mask = GCForeground | GCBackground | GCGraphicsExposures;
7240 struct face *face = FACE_FROM_ID (f, cursor_glyph->face_id);
7241 XGCValues xgcv;
7243 /* If the glyph's background equals the color we normally draw
7244 the bars cursor in, the bar cursor in its normal color is
7245 invisible. Use the glyph's foreground color instead in this
7246 case, on the assumption that the glyph's colors are chosen so
7247 that the glyph is legible. */
7248 if (face->background == f->output_data.x->cursor_pixel)
7249 xgcv.background = xgcv.foreground = face->foreground;
7250 else
7251 xgcv.background = xgcv.foreground = f->output_data.x->cursor_pixel;
7252 xgcv.graphics_exposures = 0;
7254 if (gc)
7255 XChangeGC (dpy, gc, mask, &xgcv);
7256 else
7258 gc = XCreateGC (dpy, window, mask, &xgcv);
7259 FRAME_X_DISPLAY_INFO (f)->scratch_cursor_gc = gc;
7262 x_clip_to_row (w, row, TEXT_AREA, gc);
7264 if (kind == BAR_CURSOR)
7266 int x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
7268 if (width < 0)
7269 width = FRAME_CURSOR_WIDTH (f);
7270 width = min (cursor_glyph->pixel_width, width);
7272 w->phys_cursor_width = width;
7274 /* If the character under cursor is R2L, draw the bar cursor
7275 on the right of its glyph, rather than on the left. */
7276 if ((cursor_glyph->resolved_level & 1) != 0)
7277 x += cursor_glyph->pixel_width - width;
7279 XFillRectangle (dpy, window, gc, x,
7280 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y),
7281 width, row->height);
7283 else
7285 int dummy_x, dummy_y, dummy_h;
7287 if (width < 0)
7288 width = row->height;
7290 width = min (row->height, width);
7292 get_phys_cursor_geometry (w, row, cursor_glyph, &dummy_x,
7293 &dummy_y, &dummy_h);
7295 XFillRectangle (dpy, window, gc,
7296 WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x),
7297 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y +
7298 row->height - width),
7299 w->phys_cursor_width, width);
7302 XSetClipMask (dpy, gc, None);
7307 /* RIF: Define cursor CURSOR on frame F. */
7309 static void
7310 x_define_frame_cursor (struct frame *f, Cursor cursor)
7312 if (!f->pointer_invisible
7313 && f->output_data.x->current_cursor != cursor)
7314 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), cursor);
7315 f->output_data.x->current_cursor = cursor;
7319 /* RIF: Clear area on frame F. */
7321 static void
7322 x_clear_frame_area (struct frame *f, int x, int y, int width, int height)
7324 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
7325 x, y, width, height, False);
7326 #ifdef USE_GTK
7327 /* Must queue a redraw, because scroll bars might have been cleared. */
7328 if (FRAME_GTK_WIDGET (f))
7329 gtk_widget_queue_draw (FRAME_GTK_WIDGET (f));
7330 #endif
7334 /* RIF: Draw cursor on window W. */
7336 static void
7337 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)
7339 struct frame *f = XFRAME (WINDOW_FRAME (w));
7341 if (on_p)
7343 w->phys_cursor_type = cursor_type;
7344 w->phys_cursor_on_p = 1;
7346 if (glyph_row->exact_window_width_line_p
7347 && (glyph_row->reversed_p
7348 ? (w->phys_cursor.hpos < 0)
7349 : (w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])))
7351 glyph_row->cursor_in_fringe_p = 1;
7352 draw_fringe_bitmap (w, glyph_row, glyph_row->reversed_p);
7354 else
7356 switch (cursor_type)
7358 case HOLLOW_BOX_CURSOR:
7359 x_draw_hollow_cursor (w, glyph_row);
7360 break;
7362 case FILLED_BOX_CURSOR:
7363 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
7364 break;
7366 case BAR_CURSOR:
7367 x_draw_bar_cursor (w, glyph_row, cursor_width, BAR_CURSOR);
7368 break;
7370 case HBAR_CURSOR:
7371 x_draw_bar_cursor (w, glyph_row, cursor_width, HBAR_CURSOR);
7372 break;
7374 case NO_CURSOR:
7375 w->phys_cursor_width = 0;
7376 break;
7378 default:
7379 abort ();
7383 #ifdef HAVE_X_I18N
7384 if (w == XWINDOW (f->selected_window))
7385 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMPreeditPosition))
7386 xic_set_preeditarea (w, x, y);
7387 #endif
7390 #ifndef XFlush
7391 XFlush (FRAME_X_DISPLAY (f));
7392 #endif
7396 /* Icons. */
7398 /* Make the x-window of frame F use the gnu icon bitmap. */
7401 x_bitmap_icon (struct frame *f, Lisp_Object file)
7403 int bitmap_id;
7405 if (FRAME_X_WINDOW (f) == 0)
7406 return 1;
7408 /* Free up our existing icon bitmap and mask if any. */
7409 if (f->output_data.x->icon_bitmap > 0)
7410 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
7411 f->output_data.x->icon_bitmap = 0;
7413 if (STRINGP (file))
7415 #ifdef USE_GTK
7416 /* Use gtk_window_set_icon_from_file () if available,
7417 It's not restricted to bitmaps */
7418 if (xg_set_icon (f, file))
7419 return 0;
7420 #endif /* USE_GTK */
7421 bitmap_id = x_create_bitmap_from_file (f, file);
7422 x_create_bitmap_mask (f, bitmap_id);
7424 else
7426 /* Create the GNU bitmap and mask if necessary. */
7427 if (FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id < 0)
7429 int rc = -1;
7431 #ifdef USE_GTK
7433 if (xg_set_icon (f, xg_default_icon_file)
7434 || xg_set_icon_from_xpm_data (f, gnu_xpm_bits))
7435 return 0;
7437 #elif defined (HAVE_XPM) && defined (HAVE_X_WINDOWS)
7439 rc = x_create_bitmap_from_xpm_data (f, gnu_xpm_bits);
7440 if (rc != -1)
7441 FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id = rc;
7443 #endif
7445 /* If all else fails, use the (black and white) xbm image. */
7446 if (rc == -1)
7448 rc = x_create_bitmap_from_data (f, gnu_xbm_bits,
7449 gnu_xbm_width, gnu_xbm_height);
7450 if (rc == -1)
7451 return 1;
7453 FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id = rc;
7454 x_create_bitmap_mask (f, FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id);
7458 /* The first time we create the GNU bitmap and mask,
7459 this increments the ref-count one extra time.
7460 As a result, the GNU bitmap and mask are never freed.
7461 That way, we don't have to worry about allocating it again. */
7462 x_reference_bitmap (f, FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id);
7464 bitmap_id = FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id;
7467 x_wm_set_icon_pixmap (f, bitmap_id);
7468 f->output_data.x->icon_bitmap = bitmap_id;
7470 return 0;
7474 /* Make the x-window of frame F use a rectangle with text.
7475 Use ICON_NAME as the text. */
7478 x_text_icon (struct frame *f, const char *icon_name)
7480 if (FRAME_X_WINDOW (f) == 0)
7481 return 1;
7484 XTextProperty text;
7485 text.value = (unsigned char *) icon_name;
7486 text.encoding = XA_STRING;
7487 text.format = 8;
7488 text.nitems = strlen (icon_name);
7489 XSetWMIconName (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f), &text);
7492 if (f->output_data.x->icon_bitmap > 0)
7493 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
7494 f->output_data.x->icon_bitmap = 0;
7495 x_wm_set_icon_pixmap (f, 0);
7497 return 0;
7500 #define X_ERROR_MESSAGE_SIZE 200
7502 /* If non-nil, this should be a string.
7503 It means catch X errors and store the error message in this string.
7505 The reason we use a stack is that x_catch_error/x_uncatch_error can
7506 be called from a signal handler.
7509 struct x_error_message_stack {
7510 char string[X_ERROR_MESSAGE_SIZE];
7511 Display *dpy;
7512 struct x_error_message_stack *prev;
7514 static struct x_error_message_stack *x_error_message;
7516 /* An X error handler which stores the error message in
7517 *x_error_message. This is called from x_error_handler if
7518 x_catch_errors is in effect. */
7520 static void
7521 x_error_catcher (Display *display, XErrorEvent *error)
7523 XGetErrorText (display, error->error_code,
7524 x_error_message->string,
7525 X_ERROR_MESSAGE_SIZE);
7528 /* Begin trapping X errors for display DPY. Actually we trap X errors
7529 for all displays, but DPY should be the display you are actually
7530 operating on.
7532 After calling this function, X protocol errors no longer cause
7533 Emacs to exit; instead, they are recorded in the string
7534 stored in *x_error_message.
7536 Calling x_check_errors signals an Emacs error if an X error has
7537 occurred since the last call to x_catch_errors or x_check_errors.
7539 Calling x_uncatch_errors resumes the normal error handling. */
7541 void x_check_errors (Display *dpy, const char *format);
7543 void
7544 x_catch_errors (Display *dpy)
7546 struct x_error_message_stack *data = xmalloc (sizeof (*data));
7548 /* Make sure any errors from previous requests have been dealt with. */
7549 XSync (dpy, False);
7551 data->dpy = dpy;
7552 data->string[0] = 0;
7553 data->prev = x_error_message;
7554 x_error_message = data;
7557 /* Undo the last x_catch_errors call.
7558 DPY should be the display that was passed to x_catch_errors. */
7560 void
7561 x_uncatch_errors (void)
7563 struct x_error_message_stack *tmp;
7565 BLOCK_INPUT;
7567 /* The display may have been closed before this function is called.
7568 Check if it is still open before calling XSync. */
7569 if (x_display_info_for_display (x_error_message->dpy) != 0)
7570 XSync (x_error_message->dpy, False);
7572 tmp = x_error_message;
7573 x_error_message = x_error_message->prev;
7574 xfree (tmp);
7575 UNBLOCK_INPUT;
7578 /* If any X protocol errors have arrived since the last call to
7579 x_catch_errors or x_check_errors, signal an Emacs error using
7580 sprintf (a buffer, FORMAT, the x error message text) as the text. */
7582 void
7583 x_check_errors (Display *dpy, const char *format)
7585 /* Make sure to catch any errors incurred so far. */
7586 XSync (dpy, False);
7588 if (x_error_message->string[0])
7590 char string[X_ERROR_MESSAGE_SIZE];
7591 memcpy (string, x_error_message->string, X_ERROR_MESSAGE_SIZE);
7592 x_uncatch_errors ();
7593 error (format, string);
7597 /* Nonzero if we had any X protocol errors
7598 since we did x_catch_errors on DPY. */
7601 x_had_errors_p (Display *dpy)
7603 /* Make sure to catch any errors incurred so far. */
7604 XSync (dpy, False);
7606 return x_error_message->string[0] != 0;
7609 /* Forget about any errors we have had, since we did x_catch_errors on DPY. */
7611 void
7612 x_clear_errors (Display *dpy)
7614 x_error_message->string[0] = 0;
7617 #if 0 /* See comment in unwind_to_catch why calling this is a bad
7618 * idea. --lorentey */
7619 /* Close off all unclosed x_catch_errors calls. */
7621 void
7622 x_fully_uncatch_errors (void)
7624 while (x_error_message)
7625 x_uncatch_errors ();
7627 #endif
7629 /* Nonzero if x_catch_errors has been done and not yet canceled. */
7632 x_catching_errors (void)
7634 return x_error_message != 0;
7637 #if 0
7638 static unsigned int x_wire_count;
7639 x_trace_wire (void)
7641 fprintf (stderr, "Lib call: %d\n", ++x_wire_count);
7643 #endif /* ! 0 */
7646 /* Handle SIGPIPE, which can happen when the connection to a server
7647 simply goes away. SIGPIPE is handled by x_connection_signal.
7648 Don't need to do anything, because the write which caused the
7649 SIGPIPE will fail, causing Xlib to invoke the X IO error handler,
7650 which will do the appropriate cleanup for us. */
7652 static SIGTYPE
7653 x_connection_signal (int signalnum) /* If we don't have an argument, */
7654 /* some compilers complain in signal calls. */
7656 #ifdef USG
7657 /* USG systems forget handlers when they are used;
7658 must reestablish each time */
7659 signal (signalnum, x_connection_signal);
7660 #endif /* USG */
7664 /************************************************************************
7665 Handling X errors
7666 ************************************************************************/
7668 /* Error message passed to x_connection_closed. */
7670 static char *error_msg;
7672 /* Function installed as fatal_error_signal_hook in
7673 x_connection_closed. Print the X error message, and exit normally,
7674 instead of dumping core when XtCloseDisplay fails. */
7676 static void
7677 x_fatal_error_signal (void)
7679 fprintf (stderr, "%s\n", error_msg);
7680 exit (70);
7683 /* Handle the loss of connection to display DPY. ERROR_MESSAGE is
7684 the text of an error message that lead to the connection loss. */
7686 static SIGTYPE
7687 x_connection_closed (Display *dpy, const char *error_message)
7689 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
7690 Lisp_Object frame, tail;
7691 int index = SPECPDL_INDEX ();
7693 error_msg = (char *) alloca (strlen (error_message) + 1);
7694 strcpy (error_msg, error_message);
7695 handling_signal = 0;
7697 /* Prevent being called recursively because of an error condition
7698 below. Otherwise, we might end up with printing ``can't find per
7699 display information'' in the recursive call instead of printing
7700 the original message here. */
7701 x_catch_errors (dpy);
7703 /* Inhibit redisplay while frames are being deleted. */
7704 specbind (Qinhibit_redisplay, Qt);
7706 if (dpyinfo)
7708 /* Protect display from being closed when we delete the last
7709 frame on it. */
7710 dpyinfo->reference_count++;
7711 dpyinfo->terminal->reference_count++;
7714 /* First delete frames whose mini-buffers are on frames
7715 that are on the dead display. */
7716 FOR_EACH_FRAME (tail, frame)
7718 Lisp_Object minibuf_frame;
7719 minibuf_frame
7720 = WINDOW_FRAME (XWINDOW (FRAME_MINIBUF_WINDOW (XFRAME (frame))));
7721 if (FRAME_X_P (XFRAME (frame))
7722 && FRAME_X_P (XFRAME (minibuf_frame))
7723 && ! EQ (frame, minibuf_frame)
7724 && FRAME_X_DISPLAY_INFO (XFRAME (minibuf_frame)) == dpyinfo)
7725 delete_frame (frame, Qnoelisp);
7728 /* Now delete all remaining frames on the dead display.
7729 We are now sure none of these is used as the mini-buffer
7730 for another frame that we need to delete. */
7731 FOR_EACH_FRAME (tail, frame)
7732 if (FRAME_X_P (XFRAME (frame))
7733 && FRAME_X_DISPLAY_INFO (XFRAME (frame)) == dpyinfo)
7735 /* Set this to t so that delete_frame won't get confused
7736 trying to find a replacement. */
7737 FRAME_KBOARD (XFRAME (frame))->Vdefault_minibuffer_frame = Qt;
7738 delete_frame (frame, Qnoelisp);
7741 /* If DPYINFO is null, this means we didn't open the display in the
7742 first place, so don't try to close it. */
7743 if (dpyinfo)
7745 #ifdef USE_X_TOOLKIT
7746 /* We have to close the display to inform Xt that it doesn't
7747 exist anymore. If we don't, Xt will continue to wait for
7748 events from the display. As a consequence, a sequence of
7750 M-x make-frame-on-display RET :1 RET
7751 ...kill the new frame, so that we get an IO error...
7752 M-x make-frame-on-display RET :1 RET
7754 will indefinitely wait in Xt for events for display `:1',
7755 opened in the first call to make-frame-on-display.
7757 Closing the display is reported to lead to a bus error on
7758 OpenWindows in certain situations. I suspect that is a bug
7759 in OpenWindows. I don't know how to circumvent it here. */
7760 fatal_error_signal_hook = x_fatal_error_signal;
7761 XtCloseDisplay (dpy);
7762 fatal_error_signal_hook = NULL;
7763 #endif /* USE_X_TOOLKIT */
7765 #ifdef USE_GTK
7766 /* A long-standing GTK bug prevents proper disconnect handling
7767 (https://bugzilla.gnome.org/show_bug.cgi?id=85715). Once,
7768 the resulting Glib error message loop filled a user's disk.
7769 To avoid this, kill Emacs unconditionally on disconnect. */
7770 shut_down_emacs (0, 0, Qnil);
7771 fprintf (stderr, "%s\n\
7772 When compiled with GTK, Emacs cannot recover from X disconnects.\n\
7773 This is a GTK bug: https://bugzilla.gnome.org/show_bug.cgi?id=85715\n\
7774 For details, see etc/PROBLEMS.\n",
7775 error_msg);
7776 abort ();
7777 #endif /* USE_GTK */
7779 /* Indicate that this display is dead. */
7780 dpyinfo->display = 0;
7782 dpyinfo->reference_count--;
7783 dpyinfo->terminal->reference_count--;
7784 if (dpyinfo->reference_count != 0)
7785 /* We have just closed all frames on this display. */
7786 abort ();
7789 Lisp_Object tmp;
7790 XSETTERMINAL (tmp, dpyinfo->terminal);
7791 Fdelete_terminal (tmp, Qnoelisp);
7795 x_uncatch_errors ();
7797 if (terminal_list == 0)
7799 fprintf (stderr, "%s\n", error_msg);
7800 Fkill_emacs (make_number (70));
7801 /* NOTREACHED */
7804 /* Ordinary stack unwind doesn't deal with these. */
7805 #ifdef SIGIO
7806 sigunblock (sigmask (SIGIO));
7807 #endif
7808 sigunblock (sigmask (SIGALRM));
7809 TOTALLY_UNBLOCK_INPUT;
7811 unbind_to (index, Qnil);
7812 clear_waiting_for_input ();
7813 /* Here, we absolutely have to use a non-local exit (e.g. signal, throw,
7814 longjmp), because returning from this function would get us back into
7815 Xlib's code which will directly call `exit'. */
7816 error ("%s", error_msg);
7819 /* We specifically use it before defining it, so that gcc doesn't inline it,
7820 otherwise gdb doesn't know how to properly put a breakpoint on it. */
7821 static void x_error_quitter (Display *, XErrorEvent *);
7823 /* This is the first-level handler for X protocol errors.
7824 It calls x_error_quitter or x_error_catcher. */
7826 static int
7827 x_error_handler (Display *display, XErrorEvent *error)
7829 if (x_error_message)
7830 x_error_catcher (display, error);
7831 else
7832 x_error_quitter (display, error);
7833 return 0;
7836 /* This is the usual handler for X protocol errors.
7837 It kills all frames on the display that we got the error for.
7838 If that was the only one, it prints an error message and kills Emacs. */
7840 /* .gdbinit puts a breakpoint here, so make sure it is not inlined. */
7842 /* On older GCC versions, just putting x_error_quitter
7843 after x_error_handler prevents inlining into the former. */
7845 static void NO_INLINE
7846 x_error_quitter (Display *display, XErrorEvent *error)
7848 char buf[256], buf1[356];
7850 /* Ignore BadName errors. They can happen because of fonts
7851 or colors that are not defined. */
7853 if (error->error_code == BadName)
7854 return;
7856 /* Note that there is no real way portable across R3/R4 to get the
7857 original error handler. */
7859 XGetErrorText (display, error->error_code, buf, sizeof (buf));
7860 sprintf (buf1, "X protocol error: %s on protocol request %d",
7861 buf, error->request_code);
7862 x_connection_closed (display, buf1);
7866 /* This is the handler for X IO errors, always.
7867 It kills all frames on the display that we lost touch with.
7868 If that was the only one, it prints an error message and kills Emacs. */
7870 static int
7871 x_io_error_quitter (Display *display)
7873 char buf[256];
7875 sprintf (buf, "Connection lost to X server `%s'", DisplayString (display));
7876 x_connection_closed (display, buf);
7877 return 0;
7880 /* Changing the font of the frame. */
7882 /* Give frame F the font FONT-OBJECT as its default font. The return
7883 value is FONT-OBJECT. FONTSET is an ID of the fontset for the
7884 frame. If it is negative, generate a new fontset from
7885 FONT-OBJECT. */
7887 Lisp_Object
7888 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
7890 struct font *font = XFONT_OBJECT (font_object);
7892 if (fontset < 0)
7893 fontset = fontset_from_font (font_object);
7894 FRAME_FONTSET (f) = fontset;
7895 if (FRAME_FONT (f) == font)
7896 /* This font is already set in frame F. There's nothing more to
7897 do. */
7898 return font_object;
7900 FRAME_FONT (f) = font;
7901 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
7902 FRAME_COLUMN_WIDTH (f) = font->average_width;
7903 FRAME_SPACE_WIDTH (f) = font->space_width;
7904 FRAME_LINE_HEIGHT (f) = FONT_HEIGHT (font);
7906 compute_fringe_widths (f, 1);
7908 /* Compute the scroll bar width in character columns. */
7909 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
7911 int wid = FRAME_COLUMN_WIDTH (f);
7912 FRAME_CONFIG_SCROLL_BAR_COLS (f)
7913 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid-1) / wid;
7915 else
7917 int wid = FRAME_COLUMN_WIDTH (f);
7918 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
7921 if (FRAME_X_WINDOW (f) != 0)
7923 /* Don't change the size of a tip frame; there's no point in
7924 doing it because it's done in Fx_show_tip, and it leads to
7925 problems because the tip frame has no widget. */
7926 if (NILP (tip_frame) || XFRAME (tip_frame) != f)
7927 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
7930 #ifdef HAVE_X_I18N
7931 if (FRAME_XIC (f)
7932 && (FRAME_XIC_STYLE (f) & (XIMPreeditPosition | XIMStatusArea)))
7934 BLOCK_INPUT;
7935 xic_set_xfontset (f, SSDATA (fontset_ascii (fontset)));
7936 UNBLOCK_INPUT;
7938 #endif
7940 return font_object;
7944 /***********************************************************************
7945 X Input Methods
7946 ***********************************************************************/
7948 #ifdef HAVE_X_I18N
7950 #ifdef HAVE_X11R6
7952 /* XIM destroy callback function, which is called whenever the
7953 connection to input method XIM dies. CLIENT_DATA contains a
7954 pointer to the x_display_info structure corresponding to XIM. */
7956 static void
7957 xim_destroy_callback (XIM xim, XPointer client_data, XPointer call_data)
7959 struct x_display_info *dpyinfo = (struct x_display_info *) client_data;
7960 Lisp_Object frame, tail;
7962 BLOCK_INPUT;
7964 /* No need to call XDestroyIC.. */
7965 FOR_EACH_FRAME (tail, frame)
7967 struct frame *f = XFRAME (frame);
7968 if (FRAME_X_P (f) && FRAME_X_DISPLAY_INFO (f) == dpyinfo)
7970 FRAME_XIC (f) = NULL;
7971 xic_free_xfontset (f);
7975 /* No need to call XCloseIM. */
7976 dpyinfo->xim = NULL;
7977 XFree (dpyinfo->xim_styles);
7978 UNBLOCK_INPUT;
7981 #endif /* HAVE_X11R6 */
7983 #ifdef HAVE_X11R6
7984 /* This isn't prototyped in OSF 5.0 or 5.1a. */
7985 extern char *XSetIMValues (XIM, ...);
7986 #endif
7988 /* Open the connection to the XIM server on display DPYINFO.
7989 RESOURCE_NAME is the resource name Emacs uses. */
7991 static void
7992 xim_open_dpy (struct x_display_info *dpyinfo, char *resource_name)
7994 XIM xim;
7996 #ifdef HAVE_XIM
7997 if (use_xim)
7999 if (dpyinfo->xim)
8000 XCloseIM (dpyinfo->xim);
8001 xim = XOpenIM (dpyinfo->display, dpyinfo->xrdb, resource_name,
8002 emacs_class);
8003 dpyinfo->xim = xim;
8005 if (xim)
8007 #ifdef HAVE_X11R6
8008 XIMCallback destroy;
8009 #endif
8011 /* Get supported styles and XIM values. */
8012 XGetIMValues (xim, XNQueryInputStyle, &dpyinfo->xim_styles, NULL);
8014 #ifdef HAVE_X11R6
8015 destroy.callback = xim_destroy_callback;
8016 destroy.client_data = (XPointer)dpyinfo;
8017 XSetIMValues (xim, XNDestroyCallback, &destroy, NULL);
8018 #endif
8022 else
8023 #endif /* HAVE_XIM */
8024 dpyinfo->xim = NULL;
8028 #ifdef HAVE_X11R6_XIM
8030 /* XIM instantiate callback function, which is called whenever an XIM
8031 server is available. DISPLAY is the display of the XIM.
8032 CLIENT_DATA contains a pointer to an xim_inst_t structure created
8033 when the callback was registered. */
8035 static void
8036 xim_instantiate_callback (Display *display, XPointer client_data, XPointer call_data)
8038 struct xim_inst_t *xim_inst = (struct xim_inst_t *) client_data;
8039 struct x_display_info *dpyinfo = xim_inst->dpyinfo;
8041 /* We don't support multiple XIM connections. */
8042 if (dpyinfo->xim)
8043 return;
8045 xim_open_dpy (dpyinfo, xim_inst->resource_name);
8047 /* Create XIC for the existing frames on the same display, as long
8048 as they have no XIC. */
8049 if (dpyinfo->xim && dpyinfo->reference_count > 0)
8051 Lisp_Object tail, frame;
8053 BLOCK_INPUT;
8054 FOR_EACH_FRAME (tail, frame)
8056 struct frame *f = XFRAME (frame);
8058 if (FRAME_X_P (f)
8059 && FRAME_X_DISPLAY_INFO (f) == xim_inst->dpyinfo)
8060 if (FRAME_XIC (f) == NULL)
8062 create_frame_xic (f);
8063 if (FRAME_XIC_STYLE (f) & XIMStatusArea)
8064 xic_set_statusarea (f);
8065 if (FRAME_XIC_STYLE (f) & XIMPreeditPosition)
8067 struct window *w = XWINDOW (f->selected_window);
8068 xic_set_preeditarea (w, w->cursor.x, w->cursor.y);
8073 UNBLOCK_INPUT;
8077 #endif /* HAVE_X11R6_XIM */
8080 /* Open a connection to the XIM server on display DPYINFO.
8081 RESOURCE_NAME is the resource name for Emacs. On X11R5, open the
8082 connection only at the first time. On X11R6, open the connection
8083 in the XIM instantiate callback function. */
8085 static void
8086 xim_initialize (struct x_display_info *dpyinfo, char *resource_name)
8088 dpyinfo->xim = NULL;
8089 #ifdef HAVE_XIM
8090 if (use_xim)
8092 #ifdef HAVE_X11R6_XIM
8093 struct xim_inst_t *xim_inst;
8094 int len;
8096 xim_inst = (struct xim_inst_t *) xmalloc (sizeof (struct xim_inst_t));
8097 dpyinfo->xim_callback_data = xim_inst;
8098 xim_inst->dpyinfo = dpyinfo;
8099 len = strlen (resource_name);
8100 xim_inst->resource_name = (char *) xmalloc (len + 1);
8101 memcpy (xim_inst->resource_name, resource_name, len + 1);
8102 XRegisterIMInstantiateCallback (dpyinfo->display, dpyinfo->xrdb,
8103 resource_name, emacs_class,
8104 xim_instantiate_callback,
8105 /* This is XPointer in XFree86
8106 but (XPointer *) on Tru64, at
8107 least, hence the configure test. */
8108 (XRegisterIMInstantiateCallback_arg6) xim_inst);
8109 #else /* not HAVE_X11R6_XIM */
8110 xim_open_dpy (dpyinfo, resource_name);
8111 #endif /* not HAVE_X11R6_XIM */
8113 #endif /* HAVE_XIM */
8117 /* Close the connection to the XIM server on display DPYINFO. */
8119 static void
8120 xim_close_dpy (struct x_display_info *dpyinfo)
8122 #ifdef HAVE_XIM
8123 if (use_xim)
8125 #ifdef HAVE_X11R6_XIM
8126 if (dpyinfo->display)
8127 XUnregisterIMInstantiateCallback (dpyinfo->display, dpyinfo->xrdb,
8128 NULL, emacs_class,
8129 xim_instantiate_callback, NULL);
8130 xfree (dpyinfo->xim_callback_data->resource_name);
8131 xfree (dpyinfo->xim_callback_data);
8132 #endif /* HAVE_X11R6_XIM */
8133 if (dpyinfo->display)
8134 XCloseIM (dpyinfo->xim);
8135 dpyinfo->xim = NULL;
8136 XFree (dpyinfo->xim_styles);
8138 #endif /* HAVE_XIM */
8141 #endif /* not HAVE_X11R6_XIM */
8145 /* Calculate the absolute position in frame F
8146 from its current recorded position values and gravity. */
8148 void
8149 x_calc_absolute_position (struct frame *f)
8151 int flags = f->size_hint_flags;
8153 /* We have nothing to do if the current position
8154 is already for the top-left corner. */
8155 if (! ((flags & XNegative) || (flags & YNegative)))
8156 return;
8158 /* Treat negative positions as relative to the leftmost bottommost
8159 position that fits on the screen. */
8160 if (flags & XNegative)
8161 f->left_pos = x_display_pixel_width (FRAME_X_DISPLAY_INFO (f))
8162 - FRAME_PIXEL_WIDTH (f) + f->left_pos;
8165 int height = FRAME_PIXEL_HEIGHT (f);
8167 #if defined USE_X_TOOLKIT && defined USE_MOTIF
8168 /* Something is fishy here. When using Motif, starting Emacs with
8169 `-g -0-0', the frame appears too low by a few pixels.
8171 This seems to be so because initially, while Emacs is starting,
8172 the column widget's height and the frame's pixel height are
8173 different. The column widget's height is the right one. In
8174 later invocations, when Emacs is up, the frame's pixel height
8175 is right, though.
8177 It's not obvious where the initial small difference comes from.
8178 2000-12-01, gerd. */
8180 XtVaGetValues (f->output_data.x->column_widget, XtNheight, &height, NULL);
8181 #endif
8183 if (flags & YNegative)
8184 f->top_pos = x_display_pixel_height (FRAME_X_DISPLAY_INFO (f))
8185 - height + f->top_pos;
8188 /* The left_pos and top_pos
8189 are now relative to the top and left screen edges,
8190 so the flags should correspond. */
8191 f->size_hint_flags &= ~ (XNegative | YNegative);
8194 /* CHANGE_GRAVITY is 1 when calling from Fset_frame_position,
8195 to really change the position, and 0 when calling from
8196 x_make_frame_visible (in that case, XOFF and YOFF are the current
8197 position values). It is -1 when calling from x_set_frame_parameters,
8198 which means, do adjust for borders but don't change the gravity. */
8200 void
8201 x_set_offset (struct frame *f, register int xoff, register int yoff, int change_gravity)
8203 int modified_top, modified_left;
8205 if (change_gravity > 0)
8207 FRAME_X_OUTPUT (f)->left_before_move = f->left_pos;
8208 FRAME_X_OUTPUT (f)->top_before_move = f->top_pos;
8210 f->top_pos = yoff;
8211 f->left_pos = xoff;
8212 f->size_hint_flags &= ~ (XNegative | YNegative);
8213 if (xoff < 0)
8214 f->size_hint_flags |= XNegative;
8215 if (yoff < 0)
8216 f->size_hint_flags |= YNegative;
8217 f->win_gravity = NorthWestGravity;
8219 x_calc_absolute_position (f);
8221 BLOCK_INPUT;
8222 x_wm_set_size_hint (f, (long) 0, 0);
8224 modified_left = f->left_pos;
8225 modified_top = f->top_pos;
8227 if (change_gravity != 0 && FRAME_X_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A)
8229 /* Some WMs (twm, wmaker at least) has an offset that is smaller
8230 than the WM decorations. So we use the calculated offset instead
8231 of the WM decoration sizes here (x/y_pixels_outer_diff). */
8232 modified_left += FRAME_X_OUTPUT (f)->move_offset_left;
8233 modified_top += FRAME_X_OUTPUT (f)->move_offset_top;
8236 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8237 modified_left, modified_top);
8239 x_sync_with_move (f, f->left_pos, f->top_pos,
8240 FRAME_X_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN
8241 ? 1 : 0);
8243 /* change_gravity is non-zero when this function is called from Lisp to
8244 programmatically move a frame. In that case, we call
8245 x_check_expected_move to discover if we have a "Type A" or "Type B"
8246 window manager, and, for a "Type A" window manager, adjust the position
8247 of the frame.
8249 We call x_check_expected_move if a programmatic move occurred, and
8250 either the window manager type (A/B) is unknown or it is Type A but we
8251 need to compute the top/left offset adjustment for this frame. */
8253 if (change_gravity != 0 &&
8254 (FRAME_X_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN
8255 || (FRAME_X_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A
8256 && (FRAME_X_OUTPUT (f)->move_offset_left == 0
8257 && FRAME_X_OUTPUT (f)->move_offset_top == 0))))
8258 x_check_expected_move (f, modified_left, modified_top);
8260 UNBLOCK_INPUT;
8263 /* Return non-zero if _NET_SUPPORTING_WM_CHECK window exists and _NET_SUPPORTED
8264 on the root window for frame F contains ATOMNAME.
8265 This is how a WM check shall be done according to the Window Manager
8266 Specification/Extended Window Manager Hints at
8267 http://freedesktop.org/wiki/Specifications/wm-spec. */
8269 static int
8270 wm_supports (struct frame *f, Atom want_atom)
8272 Atom actual_type;
8273 unsigned long actual_size, bytes_remaining;
8274 int i, rc, actual_format;
8275 Window wmcheck_window;
8276 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8277 Window target_window = dpyinfo->root_window;
8278 long max_len = 65536;
8279 Display *dpy = FRAME_X_DISPLAY (f);
8280 unsigned char *tmp_data = NULL;
8281 Atom target_type = XA_WINDOW;
8283 BLOCK_INPUT;
8285 x_catch_errors (dpy);
8286 rc = XGetWindowProperty (dpy, target_window,
8287 dpyinfo->Xatom_net_supporting_wm_check,
8288 0, max_len, False, target_type,
8289 &actual_type, &actual_format, &actual_size,
8290 &bytes_remaining, &tmp_data);
8292 if (rc != Success || actual_type != XA_WINDOW || x_had_errors_p (dpy))
8294 if (tmp_data) XFree (tmp_data);
8295 x_uncatch_errors ();
8296 UNBLOCK_INPUT;
8297 return 0;
8300 wmcheck_window = *(Window *) tmp_data;
8301 XFree (tmp_data);
8303 /* Check if window exists. */
8304 XSelectInput (dpy, wmcheck_window, StructureNotifyMask);
8305 x_sync (f);
8306 if (x_had_errors_p (dpy))
8308 x_uncatch_errors ();
8309 UNBLOCK_INPUT;
8310 return 0;
8313 if (dpyinfo->net_supported_window != wmcheck_window)
8315 /* Window changed, reload atoms */
8316 if (dpyinfo->net_supported_atoms != NULL)
8317 XFree (dpyinfo->net_supported_atoms);
8318 dpyinfo->net_supported_atoms = NULL;
8319 dpyinfo->nr_net_supported_atoms = 0;
8320 dpyinfo->net_supported_window = 0;
8322 target_type = XA_ATOM;
8323 tmp_data = NULL;
8324 rc = XGetWindowProperty (dpy, target_window,
8325 dpyinfo->Xatom_net_supported,
8326 0, max_len, False, target_type,
8327 &actual_type, &actual_format, &actual_size,
8328 &bytes_remaining, &tmp_data);
8330 if (rc != Success || actual_type != XA_ATOM || x_had_errors_p (dpy))
8332 if (tmp_data) XFree (tmp_data);
8333 x_uncatch_errors ();
8334 UNBLOCK_INPUT;
8335 return 0;
8338 dpyinfo->net_supported_atoms = (Atom *)tmp_data;
8339 dpyinfo->nr_net_supported_atoms = actual_size;
8340 dpyinfo->net_supported_window = wmcheck_window;
8343 rc = 0;
8345 for (i = 0; rc == 0 && i < dpyinfo->nr_net_supported_atoms; ++i)
8346 rc = dpyinfo->net_supported_atoms[i] == want_atom;
8348 x_uncatch_errors ();
8349 UNBLOCK_INPUT;
8351 return rc;
8354 static void
8355 set_wm_state (Lisp_Object frame, int add, Atom atom, Atom value)
8357 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (XFRAME (frame));
8359 x_send_client_event (frame, make_number (0), frame,
8360 dpyinfo->Xatom_net_wm_state,
8361 make_number (32),
8362 /* 1 = add, 0 = remove */
8363 Fcons
8364 (make_number (add ? 1 : 0),
8365 Fcons
8366 (make_fixnum_or_float (atom),
8367 value != 0
8368 ? Fcons (make_fixnum_or_float (value), Qnil)
8369 : Qnil)));
8372 void
8373 x_set_sticky (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
8375 Lisp_Object frame;
8376 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8378 XSETFRAME (frame, f);
8380 set_wm_state (frame, NILP (new_value) ? 0 : 1,
8381 dpyinfo->Xatom_net_wm_state_sticky, None);
8384 /* Return the current _NET_WM_STATE.
8385 SIZE_STATE is set to one of the FULLSCREEN_* values.
8386 STICKY is set to 1 if the sticky state is set, 0 if not. */
8388 static void
8389 get_current_wm_state (struct frame *f,
8390 Window window,
8391 int *size_state,
8392 int *sticky)
8394 Atom actual_type;
8395 unsigned long actual_size, bytes_remaining;
8396 int i, rc, actual_format;
8397 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8398 long max_len = 65536;
8399 Display *dpy = FRAME_X_DISPLAY (f);
8400 unsigned char *tmp_data = NULL;
8401 Atom target_type = XA_ATOM;
8403 *sticky = 0;
8404 *size_state = FULLSCREEN_NONE;
8406 BLOCK_INPUT;
8407 x_catch_errors (dpy);
8408 rc = XGetWindowProperty (dpy, window, dpyinfo->Xatom_net_wm_state,
8409 0, max_len, False, target_type,
8410 &actual_type, &actual_format, &actual_size,
8411 &bytes_remaining, &tmp_data);
8413 if (rc != Success || actual_type != target_type || x_had_errors_p (dpy))
8415 if (tmp_data) XFree (tmp_data);
8416 x_uncatch_errors ();
8417 UNBLOCK_INPUT;
8418 return;
8421 x_uncatch_errors ();
8423 for (i = 0; i < actual_size; ++i)
8425 Atom a = ((Atom*)tmp_data)[i];
8426 if (a == dpyinfo->Xatom_net_wm_state_maximized_horz)
8428 if (*size_state == FULLSCREEN_HEIGHT)
8429 *size_state = FULLSCREEN_MAXIMIZED;
8430 else
8431 *size_state = FULLSCREEN_WIDTH;
8433 else if (a == dpyinfo->Xatom_net_wm_state_maximized_vert)
8435 if (*size_state == FULLSCREEN_WIDTH)
8436 *size_state = FULLSCREEN_MAXIMIZED;
8437 else
8438 *size_state = FULLSCREEN_HEIGHT;
8440 else if (a == dpyinfo->Xatom_net_wm_state_fullscreen)
8441 *size_state = FULLSCREEN_BOTH;
8442 else if (a == dpyinfo->Xatom_net_wm_state_sticky)
8443 *sticky = 1;
8446 if (tmp_data) XFree (tmp_data);
8447 UNBLOCK_INPUT;
8450 /* Do fullscreen as specified in extended window manager hints */
8452 static int
8453 do_ewmh_fullscreen (struct frame *f)
8455 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8456 int have_net_atom = wm_supports (f, dpyinfo->Xatom_net_wm_state);
8457 int cur, dummy;
8459 get_current_wm_state (f, FRAME_OUTER_WINDOW (f), &cur, &dummy);
8461 /* Some window managers don't say they support _NET_WM_STATE, but they do say
8462 they support _NET_WM_STATE_FULLSCREEN. Try that also. */
8463 if (!have_net_atom)
8464 have_net_atom = wm_supports (f, dpyinfo->Xatom_net_wm_state_fullscreen);
8466 if (have_net_atom && cur != f->want_fullscreen)
8468 Lisp_Object frame;
8470 XSETFRAME (frame, f);
8472 /* Keep number of calls to set_wm_state as low as possible.
8473 Some window managers, or possible Gtk+, hangs when too many
8474 are sent at once. */
8475 switch (f->want_fullscreen)
8477 case FULLSCREEN_BOTH:
8478 if (cur == FULLSCREEN_WIDTH || cur == FULLSCREEN_MAXIMIZED
8479 || cur == FULLSCREEN_HEIGHT)
8480 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_maximized_horz,
8481 dpyinfo->Xatom_net_wm_state_maximized_vert);
8482 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_fullscreen, None);
8483 break;
8484 case FULLSCREEN_WIDTH:
8485 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_HEIGHT
8486 || cur == FULLSCREEN_MAXIMIZED)
8487 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen,
8488 dpyinfo->Xatom_net_wm_state_maximized_vert);
8489 if (cur != FULLSCREEN_MAXIMIZED)
8490 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_maximized_horz, None);
8491 break;
8492 case FULLSCREEN_HEIGHT:
8493 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_WIDTH
8494 || cur == FULLSCREEN_MAXIMIZED)
8495 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen,
8496 dpyinfo->Xatom_net_wm_state_maximized_horz);
8497 if (cur != FULLSCREEN_MAXIMIZED)
8498 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_maximized_vert, None);
8499 break;
8500 case FULLSCREEN_MAXIMIZED:
8501 if (cur == FULLSCREEN_BOTH)
8502 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen, None);
8503 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_maximized_horz,
8504 dpyinfo->Xatom_net_wm_state_maximized_vert);
8505 break;
8506 case FULLSCREEN_NONE:
8507 if (cur == FULLSCREEN_BOTH)
8508 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen, None);
8509 else
8510 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_maximized_horz,
8511 dpyinfo->Xatom_net_wm_state_maximized_vert);
8514 f->want_fullscreen = FULLSCREEN_NONE;
8518 return have_net_atom;
8521 static void
8522 XTfullscreen_hook (FRAME_PTR f)
8524 if (f->async_visible)
8526 BLOCK_INPUT;
8527 x_check_fullscreen (f);
8528 x_sync (f);
8529 UNBLOCK_INPUT;
8534 static void
8535 x_handle_net_wm_state (struct frame *f, XPropertyEvent *event)
8537 int value = FULLSCREEN_NONE;
8538 Lisp_Object lval;
8539 int sticky = 0;
8541 get_current_wm_state (f, event->window, &value, &sticky);
8542 lval = Qnil;
8543 switch (value)
8545 case FULLSCREEN_WIDTH:
8546 lval = Qfullwidth;
8547 break;
8548 case FULLSCREEN_HEIGHT:
8549 lval = Qfullheight;
8550 break;
8551 case FULLSCREEN_BOTH:
8552 lval = Qfullboth;
8553 break;
8554 case FULLSCREEN_MAXIMIZED:
8555 lval = Qmaximized;
8556 break;
8559 store_frame_param (f, Qfullscreen, lval);
8560 store_frame_param (f, Qsticky, sticky ? Qt : Qnil);
8563 /* Check if we need to resize the frame due to a fullscreen request.
8564 If so needed, resize the frame. */
8565 static void
8566 x_check_fullscreen (struct frame *f)
8568 if (do_ewmh_fullscreen (f))
8569 return;
8571 if (f->output_data.x->parent_desc != FRAME_X_DISPLAY_INFO (f)->root_window)
8572 return; /* Only fullscreen without WM or with EWM hints (above). */
8574 /* Setting fullscreen to nil doesn't do anything. We could save the
8575 last non-fullscreen size and restore it, but it seems like a
8576 lot of work for this unusual case (no window manager running). */
8578 if (f->want_fullscreen != FULLSCREEN_NONE)
8580 int width = FRAME_PIXEL_WIDTH (f), height = FRAME_PIXEL_HEIGHT (f);
8581 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8583 switch (f->want_fullscreen)
8585 /* No difference between these two when there is no WM */
8586 case FULLSCREEN_BOTH:
8587 case FULLSCREEN_MAXIMIZED:
8588 width = x_display_pixel_width (dpyinfo);
8589 height = x_display_pixel_height (dpyinfo);
8590 break;
8591 case FULLSCREEN_WIDTH:
8592 width = x_display_pixel_width (dpyinfo);
8593 break;
8594 case FULLSCREEN_HEIGHT:
8595 height = x_display_pixel_height (dpyinfo);
8598 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8599 width, height);
8603 /* This function is called by x_set_offset to determine whether the window
8604 manager interfered with the positioning of the frame. Type A window
8605 managers position the surrounding window manager decorations a small
8606 amount above and left of the user-supplied position. Type B window
8607 managers position the surrounding window manager decorations at the
8608 user-specified position. If we detect a Type A window manager, we
8609 compensate by moving the window right and down by the proper amount. */
8611 static void
8612 x_check_expected_move (struct frame *f, int expected_left, int expected_top)
8614 int current_left = 0, current_top = 0;
8616 /* x_real_positions returns the left and top offsets of the outermost
8617 window manager window around the frame. */
8619 x_real_positions (f, &current_left, &current_top);
8621 if (current_left != expected_left || current_top != expected_top)
8623 /* It's a "Type A" window manager. */
8625 int adjusted_left;
8626 int adjusted_top;
8628 FRAME_X_DISPLAY_INFO (f)->wm_type = X_WMTYPE_A;
8629 FRAME_X_OUTPUT (f)->move_offset_left = expected_left - current_left;
8630 FRAME_X_OUTPUT (f)->move_offset_top = expected_top - current_top;
8632 /* Now fix the mispositioned frame's location. */
8634 adjusted_left = expected_left + FRAME_X_OUTPUT (f)->move_offset_left;
8635 adjusted_top = expected_top + FRAME_X_OUTPUT (f)->move_offset_top;
8637 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8638 adjusted_left, adjusted_top);
8640 x_sync_with_move (f, expected_left, expected_top, 0);
8642 else
8643 /* It's a "Type B" window manager. We don't have to adjust the
8644 frame's position. */
8646 FRAME_X_DISPLAY_INFO (f)->wm_type = X_WMTYPE_B;
8650 /* Wait for XGetGeometry to return up-to-date position information for a
8651 recently-moved frame. Call this immediately after calling XMoveWindow.
8652 If FUZZY is non-zero, then LEFT and TOP are just estimates of where the
8653 frame has been moved to, so we use a fuzzy position comparison instead
8654 of an exact comparison. */
8656 static void
8657 x_sync_with_move (struct frame *f, int left, int top, int fuzzy)
8659 int count = 0;
8661 while (count++ < 50)
8663 int current_left = 0, current_top = 0;
8665 /* In theory, this call to XSync only needs to happen once, but in
8666 practice, it doesn't seem to work, hence the need for the surrounding
8667 loop. */
8669 XSync (FRAME_X_DISPLAY (f), False);
8670 x_real_positions (f, &current_left, &current_top);
8672 if (fuzzy)
8674 /* The left fuzz-factor is 10 pixels. The top fuzz-factor is 40
8675 pixels. */
8677 if (eabs (current_left - left) <= 10
8678 && eabs (current_top - top) <= 40)
8679 return;
8681 else if (current_left == left && current_top == top)
8682 return;
8685 /* As a last resort, just wait 0.5 seconds and hope that XGetGeometry
8686 will then return up-to-date position info. */
8688 wait_reading_process_output (0, 500000, 0, 0, Qnil, NULL, 0);
8692 /* Wait for an event on frame F matching EVENTTYPE. */
8693 void
8694 x_wait_for_event (struct frame *f, int eventtype)
8696 int level = interrupt_input_blocked;
8698 SELECT_TYPE fds;
8699 EMACS_TIME tmo, tmo_at, time_now;
8700 int fd = ConnectionNumber (FRAME_X_DISPLAY (f));
8702 pending_event_wait.f = f;
8703 pending_event_wait.eventtype = eventtype;
8705 /* Set timeout to 0.1 second. Hopefully not noticable.
8706 Maybe it should be configurable. */
8707 EMACS_SET_SECS_USECS (tmo, 0, 100000);
8708 EMACS_GET_TIME (tmo_at);
8709 EMACS_ADD_TIME (tmo_at, tmo_at, tmo);
8711 while (pending_event_wait.eventtype)
8713 interrupt_input_pending = 1;
8714 TOTALLY_UNBLOCK_INPUT;
8715 /* XTread_socket is called after unblock. */
8716 BLOCK_INPUT;
8717 interrupt_input_blocked = level;
8719 FD_ZERO (&fds);
8720 FD_SET (fd, &fds);
8722 EMACS_GET_TIME (time_now);
8723 EMACS_SUB_TIME (tmo, tmo_at, time_now);
8725 if (EMACS_TIME_NEG_P (tmo) || select (fd+1, &fds, NULL, NULL, &tmo) == 0)
8726 break; /* Timeout */
8728 pending_event_wait.f = 0;
8729 pending_event_wait.eventtype = 0;
8733 /* Change the size of frame F's X window to COLS/ROWS in the case F
8734 doesn't have a widget. If CHANGE_GRAVITY is 1, we change to
8735 top-left-corner window gravity for this size change and subsequent
8736 size changes. Otherwise we leave the window gravity unchanged. */
8738 static void
8739 x_set_window_size_1 (struct frame *f, int change_gravity, int cols, int rows)
8741 int pixelwidth, pixelheight;
8743 check_frame_size (f, &rows, &cols);
8744 f->scroll_bar_actual_width
8745 = (!FRAME_HAS_VERTICAL_SCROLL_BARS (f)
8747 : FRAME_CONFIG_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f));
8749 compute_fringe_widths (f, 0);
8751 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, cols)
8752 + FRAME_TOOLBAR_WIDTH (f);
8753 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows)
8754 + FRAME_MENUBAR_HEIGHT (f) + FRAME_TOOLBAR_HEIGHT (f);
8756 if (change_gravity) f->win_gravity = NorthWestGravity;
8757 x_wm_set_size_hint (f, (long) 0, 0);
8758 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8759 pixelwidth, pixelheight);
8762 /* We've set {FRAME,PIXEL}_{WIDTH,HEIGHT} to the values we hope to
8763 receive in the ConfigureNotify event; if we get what we asked
8764 for, then the event won't cause the screen to become garbaged, so
8765 we have to make sure to do it here. */
8766 SET_FRAME_GARBAGED (f);
8768 /* Now, strictly speaking, we can't be sure that this is accurate,
8769 but the window manager will get around to dealing with the size
8770 change request eventually, and we'll hear how it went when the
8771 ConfigureNotify event gets here.
8773 We could just not bother storing any of this information here,
8774 and let the ConfigureNotify event set everything up, but that
8775 might be kind of confusing to the Lisp code, since size changes
8776 wouldn't be reported in the frame parameters until some random
8777 point in the future when the ConfigureNotify event arrives.
8779 We pass 1 for DELAY since we can't run Lisp code inside of
8780 a BLOCK_INPUT. */
8782 /* But the ConfigureNotify may in fact never arrive, and then this is
8783 not right if the frame is visible. Instead wait (with timeout)
8784 for the ConfigureNotify. */
8785 if (f->async_visible)
8786 x_wait_for_event (f, ConfigureNotify);
8787 else
8789 change_frame_size (f, rows, cols, 0, 1, 0);
8790 FRAME_PIXEL_WIDTH (f) = pixelwidth;
8791 FRAME_PIXEL_HEIGHT (f) = pixelheight;
8792 x_sync (f);
8797 /* Call this to change the size of frame F's x-window.
8798 If CHANGE_GRAVITY is 1, we change to top-left-corner window gravity
8799 for this size change and subsequent size changes.
8800 Otherwise we leave the window gravity unchanged. */
8802 void
8803 x_set_window_size (struct frame *f, int change_gravity, int cols, int rows)
8805 BLOCK_INPUT;
8807 if (NILP (tip_frame) || XFRAME (tip_frame) != f)
8809 int r, c;
8811 /* When the frame is maximized/fullscreen or running under for
8812 example Xmonad, x_set_window_size_1 will be a no-op.
8813 In that case, the right thing to do is extend rows/cols to
8814 the current frame size. We do that first if x_set_window_size_1
8815 turns out to not be a no-op (there is no way to know).
8816 The size will be adjusted again if the frame gets a
8817 ConfigureNotify event as a result of x_set_window_size. */
8818 int pixelh = FRAME_PIXEL_HEIGHT (f);
8819 #ifdef USE_X_TOOLKIT
8820 /* The menu bar is not part of text lines. The tool bar
8821 is however. */
8822 pixelh -= FRAME_MENUBAR_HEIGHT (f);
8823 #endif
8824 r = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, pixelh);
8825 /* Update f->scroll_bar_actual_width because it is used in
8826 FRAME_PIXEL_WIDTH_TO_TEXT_COLS. */
8827 f->scroll_bar_actual_width
8828 = FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f);
8829 c = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, FRAME_PIXEL_WIDTH (f));
8830 change_frame_size (f, r, c, 0, 1, 0);
8833 #ifdef USE_GTK
8834 if (FRAME_GTK_WIDGET (f))
8835 xg_frame_set_char_size (f, cols, rows);
8836 else
8837 x_set_window_size_1 (f, change_gravity, cols, rows);
8838 #else /* not USE_GTK */
8840 x_set_window_size_1 (f, change_gravity, cols, rows);
8842 #endif /* not USE_GTK */
8844 /* If cursor was outside the new size, mark it as off. */
8845 mark_window_cursors_off (XWINDOW (f->root_window));
8847 /* Clear out any recollection of where the mouse highlighting was,
8848 since it might be in a place that's outside the new frame size.
8849 Actually checking whether it is outside is a pain in the neck,
8850 so don't try--just let the highlighting be done afresh with new size. */
8851 cancel_mouse_face (f);
8853 UNBLOCK_INPUT;
8856 /* Mouse warping. */
8858 void
8859 x_set_mouse_position (struct frame *f, int x, int y)
8861 int pix_x, pix_y;
8863 pix_x = FRAME_COL_TO_PIXEL_X (f, x) + FRAME_COLUMN_WIDTH (f) / 2;
8864 pix_y = FRAME_LINE_TO_PIXEL_Y (f, y) + FRAME_LINE_HEIGHT (f) / 2;
8866 if (pix_x < 0) pix_x = 0;
8867 if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
8869 if (pix_y < 0) pix_y = 0;
8870 if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
8872 BLOCK_INPUT;
8874 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
8875 0, 0, 0, 0, pix_x, pix_y);
8876 UNBLOCK_INPUT;
8879 /* Move the mouse to position pixel PIX_X, PIX_Y relative to frame F. */
8881 void
8882 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
8884 BLOCK_INPUT;
8886 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
8887 0, 0, 0, 0, pix_x, pix_y);
8888 UNBLOCK_INPUT;
8891 /* focus shifting, raising and lowering. */
8893 void
8894 x_focus_on_frame (struct frame *f)
8896 #if 0
8897 /* I don't think that the ICCCM allows programs to do things like this
8898 without the interaction of the window manager. Whatever you end up
8899 doing with this code, do it to x_unfocus_frame too. */
8900 XSetInputFocus (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
8901 RevertToPointerRoot, CurrentTime);
8902 #endif /* ! 0 */
8905 void
8906 x_unfocus_frame (struct frame *f)
8908 #if 0
8909 /* Look at the remarks in x_focus_on_frame. */
8910 if (FRAME_X_DISPLAY_INFO (f)->x_focus_frame == f)
8911 XSetInputFocus (FRAME_X_DISPLAY (f), PointerRoot,
8912 RevertToPointerRoot, CurrentTime);
8913 #endif /* ! 0 */
8916 /* Raise frame F. */
8918 void
8919 x_raise_frame (struct frame *f)
8921 BLOCK_INPUT;
8922 if (f->async_visible)
8923 XRaiseWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
8925 XFlush (FRAME_X_DISPLAY (f));
8926 UNBLOCK_INPUT;
8929 /* Lower frame F. */
8931 void
8932 x_lower_frame (struct frame *f)
8934 if (f->async_visible)
8936 BLOCK_INPUT;
8937 XLowerWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
8938 XFlush (FRAME_X_DISPLAY (f));
8939 UNBLOCK_INPUT;
8943 /* Activate frame with Extended Window Manager Hints */
8945 void
8946 x_ewmh_activate_frame (FRAME_PTR f)
8948 /* See Window Manager Specification/Extended Window Manager Hints at
8949 http://freedesktop.org/wiki/Specifications/wm-spec */
8951 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8952 if (f->async_visible && wm_supports (f, dpyinfo->Xatom_net_active_window))
8954 Lisp_Object frame;
8955 XSETFRAME (frame, f);
8956 x_send_client_event (frame, make_number (0), frame,
8957 dpyinfo->Xatom_net_active_window,
8958 make_number (32),
8959 Fcons (make_number (1),
8960 Fcons (make_number (last_user_time),
8961 Qnil)));
8965 static void
8966 XTframe_raise_lower (FRAME_PTR f, int raise_flag)
8968 if (raise_flag)
8969 x_raise_frame (f);
8970 else
8971 x_lower_frame (f);
8974 /* XEmbed implementation. */
8976 static void
8977 xembed_set_info (struct frame *f, enum xembed_info flags)
8979 unsigned long data[2];
8980 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8982 data[0] = XEMBED_VERSION;
8983 data[1] = flags;
8985 XChangeProperty (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8986 dpyinfo->Xatom_XEMBED_INFO, dpyinfo->Xatom_XEMBED_INFO,
8987 32, PropModeReplace, (unsigned char *) data, 2);
8990 static void
8991 xembed_send_message (struct frame *f, Time time, enum xembed_message message, long int detail, long int data1, long int data2)
8993 XEvent event;
8995 event.xclient.type = ClientMessage;
8996 event.xclient.window = FRAME_X_OUTPUT (f)->parent_desc;
8997 event.xclient.message_type = FRAME_X_DISPLAY_INFO (f)->Xatom_XEMBED;
8998 event.xclient.format = 32;
8999 event.xclient.data.l[0] = time;
9000 event.xclient.data.l[1] = message;
9001 event.xclient.data.l[2] = detail;
9002 event.xclient.data.l[3] = data1;
9003 event.xclient.data.l[4] = data2;
9005 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_OUTPUT (f)->parent_desc,
9006 False, NoEventMask, &event);
9007 XSync (FRAME_X_DISPLAY (f), False);
9010 /* Change of visibility. */
9012 /* This tries to wait until the frame is really visible.
9013 However, if the window manager asks the user where to position
9014 the frame, this will return before the user finishes doing that.
9015 The frame will not actually be visible at that time,
9016 but it will become visible later when the window manager
9017 finishes with it. */
9019 void
9020 x_make_frame_visible (struct frame *f)
9022 Lisp_Object type;
9023 int original_top, original_left;
9024 int retry_count = 2;
9026 retry:
9028 BLOCK_INPUT;
9030 type = x_icon_type (f);
9031 if (!NILP (type))
9032 x_bitmap_icon (f, type);
9034 if (! FRAME_VISIBLE_P (f))
9036 /* We test FRAME_GARBAGED_P here to make sure we don't
9037 call x_set_offset a second time
9038 if we get to x_make_frame_visible a second time
9039 before the window gets really visible. */
9040 if (! FRAME_ICONIFIED_P (f)
9041 && ! FRAME_X_EMBEDDED_P (f)
9042 && ! f->output_data.x->asked_for_visible)
9043 x_set_offset (f, f->left_pos, f->top_pos, 0);
9045 f->output_data.x->asked_for_visible = 1;
9047 if (! EQ (Vx_no_window_manager, Qt))
9048 x_wm_set_window_state (f, NormalState);
9049 #ifdef USE_X_TOOLKIT
9050 if (FRAME_X_EMBEDDED_P (f))
9051 xembed_set_info (f, XEMBED_MAPPED);
9052 else
9054 /* This was XtPopup, but that did nothing for an iconified frame. */
9055 XtMapWidget (f->output_data.x->widget);
9057 #else /* not USE_X_TOOLKIT */
9058 #ifdef USE_GTK
9059 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
9060 gtk_window_deiconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
9061 #else
9062 if (FRAME_X_EMBEDDED_P (f))
9063 xembed_set_info (f, XEMBED_MAPPED);
9064 else
9065 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9066 #endif /* not USE_GTK */
9067 #endif /* not USE_X_TOOLKIT */
9070 XFlush (FRAME_X_DISPLAY (f));
9072 /* Synchronize to ensure Emacs knows the frame is visible
9073 before we do anything else. We do this loop with input not blocked
9074 so that incoming events are handled. */
9076 Lisp_Object frame;
9077 int count;
9078 /* This must be before UNBLOCK_INPUT
9079 since events that arrive in response to the actions above
9080 will set it when they are handled. */
9081 int previously_visible = f->output_data.x->has_been_visible;
9083 original_left = f->left_pos;
9084 original_top = f->top_pos;
9086 /* This must come after we set COUNT. */
9087 UNBLOCK_INPUT;
9089 /* We unblock here so that arriving X events are processed. */
9091 /* Now move the window back to where it was "supposed to be".
9092 But don't do it if the gravity is negative.
9093 When the gravity is negative, this uses a position
9094 that is 3 pixels too low. Perhaps that's really the border width.
9096 Don't do this if the window has never been visible before,
9097 because the window manager may choose the position
9098 and we don't want to override it. */
9100 if (! FRAME_VISIBLE_P (f)
9101 && ! FRAME_ICONIFIED_P (f)
9102 && ! FRAME_X_EMBEDDED_P (f)
9103 && f->win_gravity == NorthWestGravity
9104 && previously_visible)
9106 Drawable rootw;
9107 int x, y;
9108 unsigned int width, height, border, depth;
9110 BLOCK_INPUT;
9112 /* On some window managers (such as FVWM) moving an existing
9113 window, even to the same place, causes the window manager
9114 to introduce an offset. This can cause the window to move
9115 to an unexpected location. Check the geometry (a little
9116 slow here) and then verify that the window is in the right
9117 place. If the window is not in the right place, move it
9118 there, and take the potential window manager hit. */
9119 XGetGeometry (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
9120 &rootw, &x, &y, &width, &height, &border, &depth);
9122 if (original_left != x || original_top != y)
9123 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
9124 original_left, original_top);
9126 UNBLOCK_INPUT;
9129 XSETFRAME (frame, f);
9131 /* Wait until the frame is visible. Process X events until a
9132 MapNotify event has been seen, or until we think we won't get a
9133 MapNotify at all.. */
9134 for (count = input_signal_count + 10;
9135 input_signal_count < count && !FRAME_VISIBLE_P (f);)
9137 /* Force processing of queued events. */
9138 x_sync (f);
9140 /* Machines that do polling rather than SIGIO have been
9141 observed to go into a busy-wait here. So we'll fake an
9142 alarm signal to let the handler know that there's something
9143 to be read. We used to raise a real alarm, but it seems
9144 that the handler isn't always enabled here. This is
9145 probably a bug. */
9146 if (input_polling_used ())
9148 /* It could be confusing if a real alarm arrives while
9149 processing the fake one. Turn it off and let the
9150 handler reset it. */
9151 int old_poll_suppress_count = poll_suppress_count;
9152 poll_suppress_count = 1;
9153 poll_for_input_1 ();
9154 poll_suppress_count = old_poll_suppress_count;
9157 /* See if a MapNotify event has been processed. */
9158 FRAME_SAMPLE_VISIBILITY (f);
9161 /* 2000-09-28: In
9163 (let ((f (selected-frame)))
9164 (iconify-frame f)
9165 (raise-frame f))
9167 the frame is not raised with various window managers on
9168 FreeBSD, GNU/Linux and Solaris. It turns out that, for some
9169 unknown reason, the call to XtMapWidget is completely ignored.
9170 Mapping the widget a second time works. */
9172 if (!FRAME_VISIBLE_P (f) && --retry_count > 0)
9173 goto retry;
9177 /* Change from mapped state to withdrawn state. */
9179 /* Make the frame visible (mapped and not iconified). */
9181 void
9182 x_make_frame_invisible (struct frame *f)
9184 Window window;
9186 /* Use the frame's outermost window, not the one we normally draw on. */
9187 window = FRAME_OUTER_WINDOW (f);
9189 /* Don't keep the highlight on an invisible frame. */
9190 if (FRAME_X_DISPLAY_INFO (f)->x_highlight_frame == f)
9191 FRAME_X_DISPLAY_INFO (f)->x_highlight_frame = 0;
9193 BLOCK_INPUT;
9195 /* Before unmapping the window, update the WM_SIZE_HINTS property to claim
9196 that the current position of the window is user-specified, rather than
9197 program-specified, so that when the window is mapped again, it will be
9198 placed at the same location, without forcing the user to position it
9199 by hand again (they have already done that once for this window.) */
9200 x_wm_set_size_hint (f, (long) 0, 1);
9202 #ifdef USE_GTK
9203 if (FRAME_GTK_OUTER_WIDGET (f))
9204 gtk_widget_hide (FRAME_GTK_OUTER_WIDGET (f));
9205 else
9206 #else
9207 if (FRAME_X_EMBEDDED_P (f))
9208 xembed_set_info (f, 0);
9209 else
9210 #endif
9213 if (! XWithdrawWindow (FRAME_X_DISPLAY (f), window,
9214 DefaultScreen (FRAME_X_DISPLAY (f))))
9216 UNBLOCK_INPUT_RESIGNAL;
9217 error ("Can't notify window manager of window withdrawal");
9221 /* We can't distinguish this from iconification
9222 just by the event that we get from the server.
9223 So we can't win using the usual strategy of letting
9224 FRAME_SAMPLE_VISIBILITY set this. So do it by hand,
9225 and synchronize with the server to make sure we agree. */
9226 f->visible = 0;
9227 FRAME_ICONIFIED_P (f) = 0;
9228 f->async_visible = 0;
9229 f->async_iconified = 0;
9231 x_sync (f);
9233 UNBLOCK_INPUT;
9236 /* Change window state from mapped to iconified. */
9238 void
9239 x_iconify_frame (struct frame *f)
9241 int result;
9242 Lisp_Object type;
9244 /* Don't keep the highlight on an invisible frame. */
9245 if (FRAME_X_DISPLAY_INFO (f)->x_highlight_frame == f)
9246 FRAME_X_DISPLAY_INFO (f)->x_highlight_frame = 0;
9248 if (f->async_iconified)
9249 return;
9251 BLOCK_INPUT;
9253 FRAME_SAMPLE_VISIBILITY (f);
9255 type = x_icon_type (f);
9256 if (!NILP (type))
9257 x_bitmap_icon (f, type);
9259 #ifdef USE_GTK
9260 if (FRAME_GTK_OUTER_WIDGET (f))
9262 if (! FRAME_VISIBLE_P (f))
9263 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
9265 gtk_window_iconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
9266 f->iconified = 1;
9267 f->visible = 1;
9268 f->async_iconified = 1;
9269 f->async_visible = 0;
9270 UNBLOCK_INPUT;
9271 return;
9273 #endif
9275 #ifdef USE_X_TOOLKIT
9277 if (! FRAME_VISIBLE_P (f))
9279 if (! EQ (Vx_no_window_manager, Qt))
9280 x_wm_set_window_state (f, IconicState);
9281 /* This was XtPopup, but that did nothing for an iconified frame. */
9282 XtMapWidget (f->output_data.x->widget);
9283 /* The server won't give us any event to indicate
9284 that an invisible frame was changed to an icon,
9285 so we have to record it here. */
9286 f->iconified = 1;
9287 f->visible = 1;
9288 f->async_iconified = 1;
9289 f->async_visible = 0;
9290 UNBLOCK_INPUT;
9291 return;
9294 result = XIconifyWindow (FRAME_X_DISPLAY (f),
9295 XtWindow (f->output_data.x->widget),
9296 DefaultScreen (FRAME_X_DISPLAY (f)));
9297 UNBLOCK_INPUT;
9299 if (!result)
9300 error ("Can't notify window manager of iconification");
9302 f->async_iconified = 1;
9303 f->async_visible = 0;
9306 BLOCK_INPUT;
9307 XFlush (FRAME_X_DISPLAY (f));
9308 UNBLOCK_INPUT;
9309 #else /* not USE_X_TOOLKIT */
9311 /* Make sure the X server knows where the window should be positioned,
9312 in case the user deiconifies with the window manager. */
9313 if (! FRAME_VISIBLE_P (f)
9314 && ! FRAME_ICONIFIED_P (f)
9315 && ! FRAME_X_EMBEDDED_P (f))
9316 x_set_offset (f, f->left_pos, f->top_pos, 0);
9318 /* Since we don't know which revision of X we're running, we'll use both
9319 the X11R3 and X11R4 techniques. I don't know if this is a good idea. */
9321 /* X11R4: send a ClientMessage to the window manager using the
9322 WM_CHANGE_STATE type. */
9324 XEvent message;
9326 message.xclient.window = FRAME_X_WINDOW (f);
9327 message.xclient.type = ClientMessage;
9328 message.xclient.message_type = FRAME_X_DISPLAY_INFO (f)->Xatom_wm_change_state;
9329 message.xclient.format = 32;
9330 message.xclient.data.l[0] = IconicState;
9332 if (! XSendEvent (FRAME_X_DISPLAY (f),
9333 DefaultRootWindow (FRAME_X_DISPLAY (f)),
9334 False,
9335 SubstructureRedirectMask | SubstructureNotifyMask,
9336 &message))
9338 UNBLOCK_INPUT_RESIGNAL;
9339 error ("Can't notify window manager of iconification");
9343 /* X11R3: set the initial_state field of the window manager hints to
9344 IconicState. */
9345 x_wm_set_window_state (f, IconicState);
9347 if (!FRAME_VISIBLE_P (f))
9349 /* If the frame was withdrawn, before, we must map it. */
9350 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9353 f->async_iconified = 1;
9354 f->async_visible = 0;
9356 XFlush (FRAME_X_DISPLAY (f));
9357 UNBLOCK_INPUT;
9358 #endif /* not USE_X_TOOLKIT */
9362 /* Free X resources of frame F. */
9364 void
9365 x_free_frame_resources (struct frame *f)
9367 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
9368 Lisp_Object bar;
9369 struct scroll_bar *b;
9370 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
9372 BLOCK_INPUT;
9374 /* If a display connection is dead, don't try sending more
9375 commands to the X server. */
9376 if (dpyinfo->display)
9378 /* We must free faces before destroying windows because some
9379 font-driver (e.g. xft) access a window while finishing a
9380 face. */
9381 if (FRAME_FACE_CACHE (f))
9382 free_frame_faces (f);
9384 if (f->output_data.x->icon_desc)
9385 XDestroyWindow (FRAME_X_DISPLAY (f), f->output_data.x->icon_desc);
9387 #ifdef USE_X_TOOLKIT
9388 /* Explicitly destroy the scroll bars of the frame. Without
9389 this, we get "BadDrawable" errors from the toolkit later on,
9390 presumably from expose events generated for the disappearing
9391 toolkit scroll bars. */
9392 for (bar = FRAME_SCROLL_BARS (f); !NILP (bar); bar = b->next)
9394 b = XSCROLL_BAR (bar);
9395 x_scroll_bar_remove (b);
9397 #endif
9399 #ifdef HAVE_X_I18N
9400 if (FRAME_XIC (f))
9401 free_frame_xic (f);
9402 #endif
9404 #ifdef USE_X_TOOLKIT
9405 if (f->output_data.x->widget)
9407 XtDestroyWidget (f->output_data.x->widget);
9408 f->output_data.x->widget = NULL;
9410 /* Tooltips don't have widgets, only a simple X window, even if
9411 we are using a toolkit. */
9412 else if (FRAME_X_WINDOW (f))
9413 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9415 free_frame_menubar (f);
9416 #else /* !USE_X_TOOLKIT */
9418 #ifdef USE_GTK
9419 xg_free_frame_widgets (f);
9420 #endif /* USE_GTK */
9422 if (FRAME_X_WINDOW (f))
9423 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9424 #endif /* !USE_X_TOOLKIT */
9426 unload_color (f, FRAME_FOREGROUND_PIXEL (f));
9427 unload_color (f, FRAME_BACKGROUND_PIXEL (f));
9428 unload_color (f, f->output_data.x->cursor_pixel);
9429 unload_color (f, f->output_data.x->cursor_foreground_pixel);
9430 unload_color (f, f->output_data.x->border_pixel);
9431 unload_color (f, f->output_data.x->mouse_pixel);
9433 if (f->output_data.x->scroll_bar_background_pixel != -1)
9434 unload_color (f, f->output_data.x->scroll_bar_background_pixel);
9435 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
9436 unload_color (f, f->output_data.x->scroll_bar_foreground_pixel);
9437 #ifdef USE_TOOLKIT_SCROLL_BARS
9438 /* Scrollbar shadow colors. */
9439 if (f->output_data.x->scroll_bar_top_shadow_pixel != -1)
9440 unload_color (f, f->output_data.x->scroll_bar_top_shadow_pixel);
9441 if (f->output_data.x->scroll_bar_bottom_shadow_pixel != -1)
9442 unload_color (f, f->output_data.x->scroll_bar_bottom_shadow_pixel);
9443 #endif /* USE_TOOLKIT_SCROLL_BARS */
9444 if (f->output_data.x->white_relief.allocated_p)
9445 unload_color (f, f->output_data.x->white_relief.pixel);
9446 if (f->output_data.x->black_relief.allocated_p)
9447 unload_color (f, f->output_data.x->black_relief.pixel);
9449 x_free_gcs (f);
9450 XFlush (FRAME_X_DISPLAY (f));
9453 xfree (f->output_data.x->saved_menu_event);
9454 xfree (f->output_data.x);
9455 f->output_data.x = NULL;
9457 if (f == dpyinfo->x_focus_frame)
9458 dpyinfo->x_focus_frame = 0;
9459 if (f == dpyinfo->x_focus_event_frame)
9460 dpyinfo->x_focus_event_frame = 0;
9461 if (f == dpyinfo->x_highlight_frame)
9462 dpyinfo->x_highlight_frame = 0;
9464 if (f == hlinfo->mouse_face_mouse_frame)
9466 hlinfo->mouse_face_beg_row
9467 = hlinfo->mouse_face_beg_col = -1;
9468 hlinfo->mouse_face_end_row
9469 = hlinfo->mouse_face_end_col = -1;
9470 hlinfo->mouse_face_window = Qnil;
9471 hlinfo->mouse_face_deferred_gc = 0;
9472 hlinfo->mouse_face_mouse_frame = 0;
9475 UNBLOCK_INPUT;
9479 /* Destroy the X window of frame F. */
9481 void
9482 x_destroy_window (struct frame *f)
9484 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
9486 /* If a display connection is dead, don't try sending more
9487 commands to the X server. */
9488 if (dpyinfo->display != 0)
9489 x_free_frame_resources (f);
9491 dpyinfo->reference_count--;
9495 /* Setting window manager hints. */
9497 /* Set the normal size hints for the window manager, for frame F.
9498 FLAGS is the flags word to use--or 0 meaning preserve the flags
9499 that the window now has.
9500 If USER_POSITION is nonzero, we set the USPosition
9501 flag (this is useful when FLAGS is 0).
9502 The GTK version is in gtkutils.c */
9504 #ifndef USE_GTK
9505 void
9506 x_wm_set_size_hint (struct frame *f, long flags, int user_position)
9508 XSizeHints size_hints;
9509 Window window = FRAME_OUTER_WINDOW (f);
9511 /* Setting PMaxSize caused various problems. */
9512 size_hints.flags = PResizeInc | PMinSize /* | PMaxSize */;
9514 size_hints.x = f->left_pos;
9515 size_hints.y = f->top_pos;
9517 size_hints.height = FRAME_PIXEL_HEIGHT (f);
9518 size_hints.width = FRAME_PIXEL_WIDTH (f);
9520 size_hints.width_inc = FRAME_COLUMN_WIDTH (f);
9521 size_hints.height_inc = FRAME_LINE_HEIGHT (f);
9522 size_hints.max_width = x_display_pixel_width (FRAME_X_DISPLAY_INFO (f))
9523 - FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
9524 size_hints.max_height = x_display_pixel_height (FRAME_X_DISPLAY_INFO (f))
9525 - FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
9527 /* Calculate the base and minimum sizes. */
9529 int base_width, base_height;
9530 int min_rows = 0, min_cols = 0;
9532 base_width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
9533 base_height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
9535 check_frame_size (f, &min_rows, &min_cols);
9537 /* The window manager uses the base width hints to calculate the
9538 current number of rows and columns in the frame while
9539 resizing; min_width and min_height aren't useful for this
9540 purpose, since they might not give the dimensions for a
9541 zero-row, zero-column frame.
9543 We use the base_width and base_height members if we have
9544 them; otherwise, we set the min_width and min_height members
9545 to the size for a zero x zero frame. */
9547 size_hints.flags |= PBaseSize;
9548 size_hints.base_width = base_width;
9549 size_hints.base_height = base_height + FRAME_MENUBAR_HEIGHT (f);
9550 size_hints.min_width = base_width + min_cols * size_hints.width_inc;
9551 size_hints.min_height = base_height + min_rows * size_hints.height_inc;
9554 /* If we don't need the old flags, we don't need the old hint at all. */
9555 if (flags)
9557 size_hints.flags |= flags;
9558 goto no_read;
9562 XSizeHints hints; /* Sometimes I hate X Windows... */
9563 long supplied_return;
9564 int value;
9566 value = XGetWMNormalHints (FRAME_X_DISPLAY (f), window, &hints,
9567 &supplied_return);
9569 if (flags)
9570 size_hints.flags |= flags;
9571 else
9573 if (value == 0)
9574 hints.flags = 0;
9575 if (hints.flags & PSize)
9576 size_hints.flags |= PSize;
9577 if (hints.flags & PPosition)
9578 size_hints.flags |= PPosition;
9579 if (hints.flags & USPosition)
9580 size_hints.flags |= USPosition;
9581 if (hints.flags & USSize)
9582 size_hints.flags |= USSize;
9586 no_read:
9588 #ifdef PWinGravity
9589 size_hints.win_gravity = f->win_gravity;
9590 size_hints.flags |= PWinGravity;
9592 if (user_position)
9594 size_hints.flags &= ~ PPosition;
9595 size_hints.flags |= USPosition;
9597 #endif /* PWinGravity */
9599 XSetWMNormalHints (FRAME_X_DISPLAY (f), window, &size_hints);
9601 #endif /* not USE_GTK */
9603 /* Used for IconicState or NormalState */
9605 void
9606 x_wm_set_window_state (struct frame *f, int state)
9608 #ifdef USE_X_TOOLKIT
9609 Arg al[1];
9611 XtSetArg (al[0], XtNinitialState, state);
9612 XtSetValues (f->output_data.x->widget, al, 1);
9613 #else /* not USE_X_TOOLKIT */
9614 Window window = FRAME_X_WINDOW (f);
9616 f->output_data.x->wm_hints.flags |= StateHint;
9617 f->output_data.x->wm_hints.initial_state = state;
9619 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
9620 #endif /* not USE_X_TOOLKIT */
9623 void
9624 x_wm_set_icon_pixmap (struct frame *f, int pixmap_id)
9626 Pixmap icon_pixmap, icon_mask;
9628 #if !defined USE_X_TOOLKIT && !defined USE_GTK
9629 Window window = FRAME_OUTER_WINDOW (f);
9630 #endif
9632 if (pixmap_id > 0)
9634 icon_pixmap = x_bitmap_pixmap (f, pixmap_id);
9635 f->output_data.x->wm_hints.icon_pixmap = icon_pixmap;
9636 icon_mask = x_bitmap_mask (f, pixmap_id);
9637 f->output_data.x->wm_hints.icon_mask = icon_mask;
9639 else
9641 /* It seems there is no way to turn off use of an icon
9642 pixmap. */
9643 return;
9647 #ifdef USE_GTK
9649 xg_set_frame_icon (f, icon_pixmap, icon_mask);
9650 return;
9653 #elif defined (USE_X_TOOLKIT) /* same as in x_wm_set_window_state. */
9656 Arg al[1];
9657 XtSetArg (al[0], XtNiconPixmap, icon_pixmap);
9658 XtSetValues (f->output_data.x->widget, al, 1);
9659 XtSetArg (al[0], XtNiconMask, icon_mask);
9660 XtSetValues (f->output_data.x->widget, al, 1);
9663 #else /* not USE_X_TOOLKIT && not USE_GTK */
9665 f->output_data.x->wm_hints.flags |= (IconPixmapHint | IconMaskHint);
9666 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
9668 #endif /* not USE_X_TOOLKIT && not USE_GTK */
9671 void
9672 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
9674 Window window = FRAME_OUTER_WINDOW (f);
9676 f->output_data.x->wm_hints.flags |= IconPositionHint;
9677 f->output_data.x->wm_hints.icon_x = icon_x;
9678 f->output_data.x->wm_hints.icon_y = icon_y;
9680 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
9684 /***********************************************************************
9685 Fonts
9686 ***********************************************************************/
9688 #if GLYPH_DEBUG
9690 /* Check that FONT is valid on frame F. It is if it can be found in F's
9691 font table. */
9693 static void
9694 x_check_font (struct frame *f, struct font *font)
9696 Lisp_Object frame;
9698 xassert (font != NULL && ! NILP (font->props[FONT_TYPE_INDEX]));
9699 if (font->driver->check)
9700 xassert (font->driver->check (f, font) == 0);
9703 #endif /* GLYPH_DEBUG != 0 */
9706 /***********************************************************************
9707 Initialization
9708 ***********************************************************************/
9710 #ifdef USE_X_TOOLKIT
9711 static XrmOptionDescRec emacs_options[] = {
9712 {"-geometry", ".geometry", XrmoptionSepArg, NULL},
9713 {"-iconic", ".iconic", XrmoptionNoArg, (XtPointer) "yes"},
9715 {"-internal-border-width", "*EmacsScreen.internalBorderWidth",
9716 XrmoptionSepArg, NULL},
9717 {"-ib", "*EmacsScreen.internalBorderWidth", XrmoptionSepArg, NULL},
9719 {"-T", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
9720 {"-wn", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
9721 {"-title", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
9722 {"-iconname", "*EmacsShell.iconName", XrmoptionSepArg, (XtPointer) NULL},
9723 {"-in", "*EmacsShell.iconName", XrmoptionSepArg, (XtPointer) NULL},
9724 {"-mc", "*pointerColor", XrmoptionSepArg, (XtPointer) NULL},
9725 {"-cr", "*cursorColor", XrmoptionSepArg, (XtPointer) NULL}
9728 /* Whether atimer for Xt timeouts is activated or not. */
9730 static int x_timeout_atimer_activated_flag;
9732 #endif /* USE_X_TOOLKIT */
9734 static int x_initialized;
9736 /* Test whether two display-name strings agree up to the dot that separates
9737 the screen number from the server number. */
9738 static int
9739 same_x_server (const char *name1, const char *name2)
9741 int seen_colon = 0;
9742 const unsigned char *system_name = SDATA (Vsystem_name);
9743 int system_name_length = strlen (system_name);
9744 int length_until_period = 0;
9746 while (system_name[length_until_period] != 0
9747 && system_name[length_until_period] != '.')
9748 length_until_period++;
9750 /* Treat `unix' like an empty host name. */
9751 if (! strncmp (name1, "unix:", 5))
9752 name1 += 4;
9753 if (! strncmp (name2, "unix:", 5))
9754 name2 += 4;
9755 /* Treat this host's name like an empty host name. */
9756 if (! strncmp (name1, system_name, system_name_length)
9757 && name1[system_name_length] == ':')
9758 name1 += system_name_length;
9759 if (! strncmp (name2, system_name, system_name_length)
9760 && name2[system_name_length] == ':')
9761 name2 += system_name_length;
9762 /* Treat this host's domainless name like an empty host name. */
9763 if (! strncmp (name1, system_name, length_until_period)
9764 && name1[length_until_period] == ':')
9765 name1 += length_until_period;
9766 if (! strncmp (name2, system_name, length_until_period)
9767 && name2[length_until_period] == ':')
9768 name2 += length_until_period;
9770 for (; *name1 != '\0' && *name1 == *name2; name1++, name2++)
9772 if (*name1 == ':')
9773 seen_colon++;
9774 if (seen_colon && *name1 == '.')
9775 return 1;
9777 return (seen_colon
9778 && (*name1 == '.' || *name1 == '\0')
9779 && (*name2 == '.' || *name2 == '\0'));
9782 /* Count number of set bits in mask and number of bits to shift to
9783 get to the first bit. With MASK 0x7e0, *BITS is set to 6, and *OFFSET
9784 to 5. */
9785 static void
9786 get_bits_and_offset (long unsigned int mask, int *bits, int *offset)
9788 int nr = 0;
9789 int off = 0;
9791 while (!(mask & 1))
9793 off++;
9794 mask >>= 1;
9797 while (mask & 1)
9799 nr++;
9800 mask >>= 1;
9803 *offset = off;
9804 *bits = nr;
9807 /* Return 1 if display DISPLAY is available for use, 0 otherwise.
9808 But don't permanently open it, just test its availability. */
9811 x_display_ok (const char *display)
9813 int dpy_ok = 1;
9814 Display *dpy;
9816 dpy = XOpenDisplay (display);
9817 if (dpy)
9818 XCloseDisplay (dpy);
9819 else
9820 dpy_ok = 0;
9821 return dpy_ok;
9824 #ifdef USE_GTK
9825 static void
9826 my_log_handler (const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer user_data)
9828 if (!strstr (message, "g_set_prgname"))
9829 fprintf (stderr, "%s-WARNING **: %s\n", log_domain, message);
9831 #endif
9833 /* Open a connection to X display DISPLAY_NAME, and return
9834 the structure that describes the open display.
9835 If we cannot contact the display, return null. */
9837 struct x_display_info *
9838 x_term_init (Lisp_Object display_name, char *xrm_option, char *resource_name)
9840 int connection;
9841 Display *dpy;
9842 struct terminal *terminal;
9843 struct x_display_info *dpyinfo;
9844 XrmDatabase xrdb;
9845 Mouse_HLInfo *hlinfo;
9847 BLOCK_INPUT;
9849 if (!x_initialized)
9851 x_initialize ();
9852 ++x_initialized;
9855 if (! x_display_ok (SSDATA (display_name)))
9856 error ("Display %s can't be opened", SDATA (display_name));
9858 #ifdef USE_GTK
9860 #define NUM_ARGV 10
9861 int argc;
9862 char *argv[NUM_ARGV];
9863 char **argv2 = argv;
9864 guint id;
9866 if (x_initialized++ > 1)
9868 xg_display_open (SDATA (display_name), &dpy);
9870 else
9872 static char display_opt[] = "--display";
9873 static char name_opt[] = "--name";
9875 for (argc = 0; argc < NUM_ARGV; ++argc)
9876 argv[argc] = 0;
9878 argc = 0;
9879 argv[argc++] = initial_argv[0];
9881 if (! NILP (display_name))
9883 argv[argc++] = display_opt;
9884 argv[argc++] = SDATA (display_name);
9887 argv[argc++] = name_opt;
9888 argv[argc++] = resource_name;
9890 XSetLocaleModifiers ("");
9892 /* Work around GLib bug that outputs a faulty warning. See
9893 https://bugzilla.gnome.org/show_bug.cgi?id=563627. */
9894 id = g_log_set_handler ("GLib", G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
9895 | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
9896 gtk_init (&argc, &argv2);
9897 g_log_remove_handler ("GLib", id);
9899 /* gtk_init does set_locale. We must fix locale after calling it. */
9900 fixup_locale ();
9901 xg_initialize ();
9903 dpy = GDK_DISPLAY ();
9905 /* NULL window -> events for all windows go to our function */
9906 gdk_window_add_filter (NULL, event_handler_gdk, NULL);
9908 /* Load our own gtkrc if it exists. */
9910 const char *file = "~/.emacs.d/gtkrc";
9911 Lisp_Object s, abs_file;
9913 s = make_string (file, strlen (file));
9914 abs_file = Fexpand_file_name (s, Qnil);
9916 if (! NILP (abs_file) && !NILP (Ffile_readable_p (abs_file)))
9917 gtk_rc_parse (SDATA (abs_file));
9920 XSetErrorHandler (x_error_handler);
9921 XSetIOErrorHandler (x_io_error_quitter);
9924 #else /* not USE_GTK */
9925 #ifdef USE_X_TOOLKIT
9926 /* weiner@footloose.sps.mot.com reports that this causes
9927 errors with X11R5:
9928 X protocol error: BadAtom (invalid Atom parameter)
9929 on protocol request 18skiloaf.
9930 So let's not use it until R6. */
9931 #ifdef HAVE_X11XTR6
9932 XtSetLanguageProc (NULL, NULL, NULL);
9933 #endif
9936 int argc = 0;
9937 char *argv[3];
9939 argv[0] = "";
9940 argc = 1;
9941 if (xrm_option)
9943 argv[argc++] = "-xrm";
9944 argv[argc++] = xrm_option;
9946 turn_on_atimers (0);
9947 dpy = XtOpenDisplay (Xt_app_con, SSDATA (display_name),
9948 resource_name, EMACS_CLASS,
9949 emacs_options, XtNumber (emacs_options),
9950 &argc, argv);
9951 turn_on_atimers (1);
9953 #ifdef HAVE_X11XTR6
9954 /* I think this is to compensate for XtSetLanguageProc. */
9955 fixup_locale ();
9956 #endif
9959 #else /* not USE_X_TOOLKIT */
9960 XSetLocaleModifiers ("");
9961 dpy = XOpenDisplay (SDATA (display_name));
9962 #endif /* not USE_X_TOOLKIT */
9963 #endif /* not USE_GTK*/
9965 /* Detect failure. */
9966 if (dpy == 0)
9968 UNBLOCK_INPUT;
9969 return 0;
9972 /* We have definitely succeeded. Record the new connection. */
9974 dpyinfo = (struct x_display_info *) xmalloc (sizeof (struct x_display_info));
9975 memset (dpyinfo, 0, sizeof *dpyinfo);
9976 hlinfo = &dpyinfo->mouse_highlight;
9978 terminal = x_create_terminal (dpyinfo);
9981 struct x_display_info *share;
9982 Lisp_Object tail;
9984 for (share = x_display_list, tail = x_display_name_list; share;
9985 share = share->next, tail = XCDR (tail))
9986 if (same_x_server (SSDATA (XCAR (XCAR (tail))),
9987 SSDATA (display_name)))
9988 break;
9989 if (share)
9990 terminal->kboard = share->terminal->kboard;
9991 else
9993 terminal->kboard = (KBOARD *) xmalloc (sizeof (KBOARD));
9994 init_kboard (terminal->kboard);
9995 terminal->kboard->Vwindow_system = Qx;
9997 /* Add the keyboard to the list before running Lisp code (via
9998 Qvendor_specific_keysyms below), since these are not traced
9999 via terminals but only through all_kboards. */
10000 terminal->kboard->next_kboard = all_kboards;
10001 all_kboards = terminal->kboard;
10003 if (!EQ (XSYMBOL (Qvendor_specific_keysyms)->function, Qunbound))
10005 char *vendor = ServerVendor (dpy);
10007 /* Protect terminal from GC before removing it from the
10008 list of terminals. */
10009 struct gcpro gcpro1;
10010 Lisp_Object gcpro_term;
10011 XSETTERMINAL (gcpro_term, terminal);
10012 GCPRO1 (gcpro_term);
10014 /* Temporarily hide the partially initialized terminal. */
10015 terminal_list = terminal->next_terminal;
10016 UNBLOCK_INPUT;
10017 terminal->kboard->Vsystem_key_alist
10018 = call1 (Qvendor_specific_keysyms,
10019 vendor ? build_string (vendor) : empty_unibyte_string);
10020 BLOCK_INPUT;
10021 terminal->next_terminal = terminal_list;
10022 terminal_list = terminal;
10023 UNGCPRO;
10026 /* Don't let the initial kboard remain current longer than necessary.
10027 That would cause problems if a file loaded on startup tries to
10028 prompt in the mini-buffer. */
10029 if (current_kboard == initial_kboard)
10030 current_kboard = terminal->kboard;
10032 terminal->kboard->reference_count++;
10035 /* Put this display on the chain. */
10036 dpyinfo->next = x_display_list;
10037 x_display_list = dpyinfo;
10039 /* Put it on x_display_name_list as well, to keep them parallel. */
10040 x_display_name_list = Fcons (Fcons (display_name, Qnil),
10041 x_display_name_list);
10042 dpyinfo->name_list_element = XCAR (x_display_name_list);
10044 dpyinfo->display = dpy;
10046 /* Set the name of the terminal. */
10047 terminal->name = (char *) xmalloc (SBYTES (display_name) + 1);
10048 strncpy (terminal->name, SSDATA (display_name), SBYTES (display_name));
10049 terminal->name[SBYTES (display_name)] = 0;
10051 #if 0
10052 XSetAfterFunction (x_current_display, x_trace_wire);
10053 #endif /* ! 0 */
10055 dpyinfo->x_id_name
10056 = (char *) xmalloc (SBYTES (Vinvocation_name)
10057 + SBYTES (Vsystem_name)
10058 + 2);
10059 sprintf (dpyinfo->x_id_name, "%s@%s",
10060 SDATA (Vinvocation_name), SDATA (Vsystem_name));
10062 /* Figure out which modifier bits mean what. */
10063 x_find_modifier_meanings (dpyinfo);
10065 /* Get the scroll bar cursor. */
10066 #ifdef USE_GTK
10067 /* We must create a GTK cursor, it is required for GTK widgets. */
10068 dpyinfo->xg_cursor = xg_create_default_cursor (dpyinfo->display);
10069 #endif /* USE_GTK */
10071 dpyinfo->vertical_scroll_bar_cursor
10072 = XCreateFontCursor (dpyinfo->display, XC_sb_v_double_arrow);
10074 xrdb = x_load_resources (dpyinfo->display, xrm_option,
10075 resource_name, EMACS_CLASS);
10076 #ifdef HAVE_XRMSETDATABASE
10077 XrmSetDatabase (dpyinfo->display, xrdb);
10078 #else
10079 dpyinfo->display->db = xrdb;
10080 #endif
10081 /* Put the rdb where we can find it in a way that works on
10082 all versions. */
10083 dpyinfo->xrdb = xrdb;
10085 dpyinfo->screen = ScreenOfDisplay (dpyinfo->display,
10086 DefaultScreen (dpyinfo->display));
10087 select_visual (dpyinfo);
10088 dpyinfo->cmap = DefaultColormapOfScreen (dpyinfo->screen);
10089 dpyinfo->root_window = RootWindowOfScreen (dpyinfo->screen);
10090 dpyinfo->client_leader_window = 0;
10091 dpyinfo->grabbed = 0;
10092 dpyinfo->reference_count = 0;
10093 dpyinfo->icon_bitmap_id = -1;
10094 dpyinfo->n_fonts = 0;
10095 dpyinfo->bitmaps = 0;
10096 dpyinfo->bitmaps_size = 0;
10097 dpyinfo->bitmaps_last = 0;
10098 dpyinfo->scratch_cursor_gc = 0;
10099 hlinfo->mouse_face_mouse_frame = 0;
10100 hlinfo->mouse_face_deferred_gc = 0;
10101 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
10102 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
10103 hlinfo->mouse_face_face_id = DEFAULT_FACE_ID;
10104 hlinfo->mouse_face_window = Qnil;
10105 hlinfo->mouse_face_overlay = Qnil;
10106 hlinfo->mouse_face_mouse_x = hlinfo->mouse_face_mouse_y = 0;
10107 hlinfo->mouse_face_defer = 0;
10108 hlinfo->mouse_face_hidden = 0;
10109 dpyinfo->x_focus_frame = 0;
10110 dpyinfo->x_focus_event_frame = 0;
10111 dpyinfo->x_highlight_frame = 0;
10112 dpyinfo->wm_type = X_WMTYPE_UNKNOWN;
10114 /* See if we can construct pixel values from RGB values. */
10115 dpyinfo->red_bits = dpyinfo->blue_bits = dpyinfo->green_bits = 0;
10116 dpyinfo->red_offset = dpyinfo->blue_offset = dpyinfo->green_offset = 0;
10118 if (dpyinfo->visual->class == TrueColor)
10120 get_bits_and_offset (dpyinfo->visual->red_mask,
10121 &dpyinfo->red_bits, &dpyinfo->red_offset);
10122 get_bits_and_offset (dpyinfo->visual->blue_mask,
10123 &dpyinfo->blue_bits, &dpyinfo->blue_offset);
10124 get_bits_and_offset (dpyinfo->visual->green_mask,
10125 &dpyinfo->green_bits, &dpyinfo->green_offset);
10128 /* See if a private colormap is requested. */
10129 if (dpyinfo->visual == DefaultVisualOfScreen (dpyinfo->screen))
10131 if (dpyinfo->visual->class == PseudoColor)
10133 Lisp_Object value;
10134 value = display_x_get_resource (dpyinfo,
10135 build_string ("privateColormap"),
10136 build_string ("PrivateColormap"),
10137 Qnil, Qnil);
10138 if (STRINGP (value)
10139 && (!strcmp (SSDATA (value), "true")
10140 || !strcmp (SSDATA (value), "on")))
10141 dpyinfo->cmap = XCopyColormapAndFree (dpyinfo->display, dpyinfo->cmap);
10144 else
10145 dpyinfo->cmap = XCreateColormap (dpyinfo->display, dpyinfo->root_window,
10146 dpyinfo->visual, AllocNone);
10148 #ifdef HAVE_XFT
10150 /* If we are using Xft, check dpi value in X resources.
10151 It is better we use it as well, since Xft will use it, as will all
10152 Gnome applications. If our real DPI is smaller or larger than the
10153 one Xft uses, our font will look smaller or larger than other
10154 for other applications, even if it is the same font name (monospace-10
10155 for example). */
10156 char *v = XGetDefault (dpyinfo->display, "Xft", "dpi");
10157 double d;
10158 if (v != NULL && sscanf (v, "%lf", &d) == 1)
10159 dpyinfo->resy = dpyinfo->resx = d;
10161 #endif
10163 if (dpyinfo->resy < 1)
10165 int screen_number = XScreenNumberOfScreen (dpyinfo->screen);
10166 double pixels = DisplayHeight (dpyinfo->display, screen_number);
10167 double mm = DisplayHeightMM (dpyinfo->display, screen_number);
10168 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
10169 dpyinfo->resy = (mm < 1) ? 100 : pixels * 25.4 / mm;
10170 pixels = DisplayWidth (dpyinfo->display, screen_number);
10171 mm = DisplayWidthMM (dpyinfo->display, screen_number);
10172 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
10173 dpyinfo->resx = (mm < 1) ? 100 : pixels * 25.4 / mm;
10177 const struct
10179 const char *name;
10180 Atom *atom;
10181 } atom_refs[] = {
10182 { "WM_PROTOCOLS", &dpyinfo->Xatom_wm_protocols },
10183 { "WM_TAKE_FOCUS", &dpyinfo->Xatom_wm_take_focus },
10184 { "WM_SAVE_YOURSELF", &dpyinfo->Xatom_wm_save_yourself },
10185 { "WM_DELETE_WINDOW", &dpyinfo->Xatom_wm_delete_window },
10186 { "WM_CHANGE_STATE", &dpyinfo->Xatom_wm_change_state },
10187 { "WM_CONFIGURE_DENIED", &dpyinfo->Xatom_wm_configure_denied },
10188 { "WM_MOVED", &dpyinfo->Xatom_wm_window_moved },
10189 { "WM_CLIENT_LEADER", &dpyinfo->Xatom_wm_client_leader },
10190 { "Editres", &dpyinfo->Xatom_editres },
10191 { "CLIPBOARD", &dpyinfo->Xatom_CLIPBOARD },
10192 { "TIMESTAMP", &dpyinfo->Xatom_TIMESTAMP },
10193 { "TEXT", &dpyinfo->Xatom_TEXT },
10194 { "COMPOUND_TEXT", &dpyinfo->Xatom_COMPOUND_TEXT },
10195 { "UTF8_STRING", &dpyinfo->Xatom_UTF8_STRING },
10196 { "DELETE", &dpyinfo->Xatom_DELETE },
10197 { "MULTIPLE", &dpyinfo->Xatom_MULTIPLE },
10198 { "INCR", &dpyinfo->Xatom_INCR },
10199 { "_EMACS_TMP_", &dpyinfo->Xatom_EMACS_TMP },
10200 { "TARGETS", &dpyinfo->Xatom_TARGETS },
10201 { "NULL", &dpyinfo->Xatom_NULL },
10202 { "ATOM_PAIR", &dpyinfo->Xatom_ATOM_PAIR },
10203 { "_XEMBED_INFO", &dpyinfo->Xatom_XEMBED_INFO },
10204 /* For properties of font. */
10205 { "PIXEL_SIZE", &dpyinfo->Xatom_PIXEL_SIZE },
10206 { "AVERAGE_WIDTH", &dpyinfo->Xatom_AVERAGE_WIDTH },
10207 { "_MULE_BASELINE_OFFSET", &dpyinfo->Xatom_MULE_BASELINE_OFFSET },
10208 { "_MULE_RELATIVE_COMPOSE", &dpyinfo->Xatom_MULE_RELATIVE_COMPOSE },
10209 { "_MULE_DEFAULT_ASCENT", &dpyinfo->Xatom_MULE_DEFAULT_ASCENT },
10210 /* Ghostscript support. */
10211 { "DONE", &dpyinfo->Xatom_DONE },
10212 { "PAGE", &dpyinfo->Xatom_PAGE },
10213 { "SCROLLBAR", &dpyinfo->Xatom_Scrollbar },
10214 { "_XEMBED", &dpyinfo->Xatom_XEMBED },
10215 /* EWMH */
10216 { "_NET_WM_STATE", &dpyinfo->Xatom_net_wm_state },
10217 { "_NET_WM_STATE_FULLSCREEN", &dpyinfo->Xatom_net_wm_state_fullscreen },
10218 { "_NET_WM_STATE_MAXIMIZED_HORZ",
10219 &dpyinfo->Xatom_net_wm_state_maximized_horz },
10220 { "_NET_WM_STATE_MAXIMIZED_VERT",
10221 &dpyinfo->Xatom_net_wm_state_maximized_vert },
10222 { "_NET_WM_STATE_STICKY", &dpyinfo->Xatom_net_wm_state_sticky },
10223 { "_NET_WM_WINDOW_TYPE", &dpyinfo->Xatom_net_window_type },
10224 { "_NET_WM_WINDOW_TYPE_TOOLTIP",
10225 &dpyinfo->Xatom_net_window_type_tooltip },
10226 { "_NET_WM_ICON_NAME", &dpyinfo->Xatom_net_wm_icon_name },
10227 { "_NET_WM_NAME", &dpyinfo->Xatom_net_wm_name },
10228 { "_NET_SUPPORTED", &dpyinfo->Xatom_net_supported },
10229 { "_NET_SUPPORTING_WM_CHECK", &dpyinfo->Xatom_net_supporting_wm_check },
10230 { "_NET_WM_WINDOW_OPACITY", &dpyinfo->Xatom_net_wm_window_opacity },
10231 { "_NET_ACTIVE_WINDOW", &dpyinfo->Xatom_net_active_window },
10232 { "_NET_FRAME_EXTENTS", &dpyinfo->Xatom_net_frame_extents },
10233 /* Session management */
10234 { "SM_CLIENT_ID", &dpyinfo->Xatom_SM_CLIENT_ID },
10235 { "_XSETTINGS_SETTINGS", &dpyinfo->Xatom_xsettings_prop },
10236 { "MANAGER", &dpyinfo->Xatom_xsettings_mgr },
10239 int i;
10240 const int atom_count = sizeof (atom_refs) / sizeof (atom_refs[0]);
10241 /* 1 for _XSETTINGS_SN */
10242 const int total_atom_count = 1 + atom_count;
10243 Atom *atoms_return = xmalloc (sizeof (Atom) * total_atom_count);
10244 char **atom_names = xmalloc (sizeof (char *) * total_atom_count);
10245 char xsettings_atom_name[64];
10247 for (i = 0; i < atom_count; i++)
10248 atom_names[i] = (char *) atom_refs[i].name;
10250 /* Build _XSETTINGS_SN atom name */
10251 snprintf (xsettings_atom_name, sizeof (xsettings_atom_name),
10252 "_XSETTINGS_S%d", XScreenNumberOfScreen (dpyinfo->screen));
10253 atom_names[i] = xsettings_atom_name;
10255 XInternAtoms (dpyinfo->display, atom_names, total_atom_count,
10256 False, atoms_return);
10258 for (i = 0; i < atom_count; i++)
10259 *atom_refs[i].atom = atoms_return[i];
10261 /* Manual copy of last atom */
10262 dpyinfo->Xatom_xsettings_sel = atoms_return[i];
10264 xfree (atom_names);
10265 xfree (atoms_return);
10268 dpyinfo->x_dnd_atoms_size = 8;
10269 dpyinfo->x_dnd_atoms_length = 0;
10270 dpyinfo->x_dnd_atoms = xmalloc (sizeof (*dpyinfo->x_dnd_atoms)
10271 * dpyinfo->x_dnd_atoms_size);
10273 dpyinfo->net_supported_atoms = NULL;
10274 dpyinfo->nr_net_supported_atoms = 0;
10275 dpyinfo->net_supported_window = 0;
10277 connection = ConnectionNumber (dpyinfo->display);
10278 dpyinfo->connection = connection;
10281 dpyinfo->gray
10282 = XCreatePixmapFromBitmapData (dpyinfo->display, dpyinfo->root_window,
10283 gray_bitmap_bits,
10284 gray_bitmap_width, gray_bitmap_height,
10285 (unsigned long) 1, (unsigned long) 0, 1);
10288 #ifdef HAVE_X_I18N
10289 xim_initialize (dpyinfo, resource_name);
10290 #endif
10292 xsettings_initialize (dpyinfo);
10294 /* This is only needed for distinguishing keyboard and process input. */
10295 if (connection != 0)
10296 add_keyboard_wait_descriptor (connection);
10298 #ifdef F_SETOWN
10299 fcntl (connection, F_SETOWN, getpid ());
10300 #endif /* ! defined (F_SETOWN) */
10302 #ifdef SIGIO
10303 if (interrupt_input)
10304 init_sigio (connection);
10305 #endif /* ! defined (SIGIO) */
10307 #ifdef USE_LUCID
10309 Display *dpy = dpyinfo->display;
10310 XrmValue d, fr, to;
10311 Font font;
10313 d.addr = (XPointer)&dpy;
10314 d.size = sizeof (Display *);
10315 fr.addr = XtDefaultFont;
10316 fr.size = sizeof (XtDefaultFont);
10317 to.size = sizeof (Font *);
10318 to.addr = (XPointer)&font;
10319 x_catch_errors (dpy);
10320 if (!XtCallConverter (dpy, XtCvtStringToFont, &d, 1, &fr, &to, NULL))
10321 abort ();
10322 if (x_had_errors_p (dpy) || !XQueryFont (dpy, font))
10323 XrmPutLineResource (&xrdb, "Emacs.dialog.*.font: 9x15");
10324 x_uncatch_errors ();
10326 #endif
10328 /* See if we should run in synchronous mode. This is useful
10329 for debugging X code. */
10331 Lisp_Object value;
10332 value = display_x_get_resource (dpyinfo,
10333 build_string ("synchronous"),
10334 build_string ("Synchronous"),
10335 Qnil, Qnil);
10336 if (STRINGP (value)
10337 && (!strcmp (SSDATA (value), "true")
10338 || !strcmp (SSDATA (value), "on")))
10339 XSynchronize (dpyinfo->display, True);
10343 Lisp_Object value;
10344 value = display_x_get_resource (dpyinfo,
10345 build_string ("useXIM"),
10346 build_string ("UseXIM"),
10347 Qnil, Qnil);
10348 #ifdef USE_XIM
10349 if (STRINGP (value)
10350 && (!strcmp (SSDATA (value), "false")
10351 || !strcmp (SSDATA (value), "off")))
10352 use_xim = 0;
10353 #else
10354 if (STRINGP (value)
10355 && (!strcmp (SSDATA (value), "true")
10356 || !strcmp (SSDATA (value), "on")))
10357 use_xim = 1;
10358 #endif
10361 #ifdef HAVE_X_SM
10362 /* Only do this for the very first display in the Emacs session.
10363 Ignore X session management when Emacs was first started on a
10364 tty. */
10365 if (terminal->id == 1)
10366 x_session_initialize (dpyinfo);
10367 #endif
10369 UNBLOCK_INPUT;
10371 return dpyinfo;
10374 /* Get rid of display DPYINFO, deleting all frames on it,
10375 and without sending any more commands to the X server. */
10377 void
10378 x_delete_display (struct x_display_info *dpyinfo)
10380 struct terminal *t;
10382 /* Close all frames and delete the generic struct terminal for this
10383 X display. */
10384 for (t = terminal_list; t; t = t->next_terminal)
10385 if (t->type == output_x_window && t->display_info.x == dpyinfo)
10387 #ifdef HAVE_X_SM
10388 /* Close X session management when we close its display. */
10389 if (t->id == 1 && x_session_have_connection ())
10390 x_session_close ();
10391 #endif
10392 delete_terminal (t);
10393 break;
10396 delete_keyboard_wait_descriptor (dpyinfo->connection);
10398 /* Discard this display from x_display_name_list and x_display_list.
10399 We can't use Fdelq because that can quit. */
10400 if (! NILP (x_display_name_list)
10401 && EQ (XCAR (x_display_name_list), dpyinfo->name_list_element))
10402 x_display_name_list = XCDR (x_display_name_list);
10403 else
10405 Lisp_Object tail;
10407 tail = x_display_name_list;
10408 while (CONSP (tail) && CONSP (XCDR (tail)))
10410 if (EQ (XCAR (XCDR (tail)), dpyinfo->name_list_element))
10412 XSETCDR (tail, XCDR (XCDR (tail)));
10413 break;
10415 tail = XCDR (tail);
10419 if (next_noop_dpyinfo == dpyinfo)
10420 next_noop_dpyinfo = dpyinfo->next;
10422 if (x_display_list == dpyinfo)
10423 x_display_list = dpyinfo->next;
10424 else
10426 struct x_display_info *tail;
10428 for (tail = x_display_list; tail; tail = tail->next)
10429 if (tail->next == dpyinfo)
10430 tail->next = tail->next->next;
10433 xfree (dpyinfo->x_id_name);
10434 xfree (dpyinfo->x_dnd_atoms);
10435 xfree (dpyinfo->color_cells);
10436 xfree (dpyinfo);
10439 #ifdef USE_X_TOOLKIT
10441 /* Atimer callback function for TIMER. Called every 0.1s to process
10442 Xt timeouts, if needed. We must avoid calling XtAppPending as
10443 much as possible because that function does an implicit XFlush
10444 that slows us down. */
10446 static void
10447 x_process_timeouts (struct atimer *timer)
10449 BLOCK_INPUT;
10450 x_timeout_atimer_activated_flag = 0;
10451 if (toolkit_scroll_bar_interaction || popup_activated ())
10453 while (XtAppPending (Xt_app_con) & XtIMTimer)
10454 XtAppProcessEvent (Xt_app_con, XtIMTimer);
10455 /* Reactivate the atimer for next time. */
10456 x_activate_timeout_atimer ();
10458 UNBLOCK_INPUT;
10461 /* Install an asynchronous timer that processes Xt timeout events
10462 every 0.1s as long as either `toolkit_scroll_bar_interaction' or
10463 `popup_activated_flag' (in xmenu.c) is set. Make sure to call this
10464 function whenever these variables are set. This is necessary
10465 because some widget sets use timeouts internally, for example the
10466 LessTif menu bar, or the Xaw3d scroll bar. When Xt timeouts aren't
10467 processed, these widgets don't behave normally. */
10469 void
10470 x_activate_timeout_atimer (void)
10472 BLOCK_INPUT;
10473 if (!x_timeout_atimer_activated_flag)
10475 EMACS_TIME interval;
10477 EMACS_SET_SECS_USECS (interval, 0, 100000);
10478 start_atimer (ATIMER_RELATIVE, interval, x_process_timeouts, 0);
10479 x_timeout_atimer_activated_flag = 1;
10481 UNBLOCK_INPUT;
10484 #endif /* USE_X_TOOLKIT */
10487 /* Set up use of X before we make the first connection. */
10489 extern frame_parm_handler x_frame_parm_handlers[];
10491 static struct redisplay_interface x_redisplay_interface =
10493 x_frame_parm_handlers,
10494 x_produce_glyphs,
10495 x_write_glyphs,
10496 x_insert_glyphs,
10497 x_clear_end_of_line,
10498 x_scroll_run,
10499 x_after_update_window_line,
10500 x_update_window_begin,
10501 x_update_window_end,
10502 x_cursor_to,
10503 x_flush,
10504 #ifdef XFlush
10505 x_flush,
10506 #else
10507 0, /* flush_display_optional */
10508 #endif
10509 x_clear_window_mouse_face,
10510 x_get_glyph_overhangs,
10511 x_fix_overlapping_area,
10512 x_draw_fringe_bitmap,
10513 0, /* define_fringe_bitmap */
10514 0, /* destroy_fringe_bitmap */
10515 x_compute_glyph_string_overhangs,
10516 x_draw_glyph_string,
10517 x_define_frame_cursor,
10518 x_clear_frame_area,
10519 x_draw_window_cursor,
10520 x_draw_vertical_window_border,
10521 x_shift_glyphs_for_insert
10525 /* This function is called when the last frame on a display is deleted. */
10526 void
10527 x_delete_terminal (struct terminal *terminal)
10529 struct x_display_info *dpyinfo = terminal->display_info.x;
10531 /* Protect against recursive calls. delete_frame in
10532 delete_terminal calls us back when it deletes our last frame. */
10533 if (!terminal->name)
10534 return;
10536 BLOCK_INPUT;
10537 #ifdef HAVE_X_I18N
10538 /* We must close our connection to the XIM server before closing the
10539 X display. */
10540 if (dpyinfo->xim)
10541 xim_close_dpy (dpyinfo);
10542 #endif
10544 /* If called from x_connection_closed, the display may already be closed
10545 and dpyinfo->display was set to 0 to indicate that. */
10546 if (dpyinfo->display)
10548 x_destroy_all_bitmaps (dpyinfo);
10549 XSetCloseDownMode (dpyinfo->display, DestroyAll);
10551 /* Whether or not XCloseDisplay destroys the associated resource
10552 database depends on the version of libX11. To avoid both
10553 crash and memory leak, we dissociate the database from the
10554 display and then destroy dpyinfo->xrdb ourselves.
10556 Unfortunately, the above strategy does not work in some
10557 situations due to a bug in newer versions of libX11: because
10558 XrmSetDatabase doesn't clear the flag XlibDisplayDfltRMDB if
10559 dpy->db is NULL, XCloseDisplay destroys the associated
10560 database whereas it has not been created by XGetDefault
10561 (Bug#21974 in freedesktop.org Bugzilla). As a workaround, we
10562 don't destroy the database here in order to avoid the crash
10563 in the above situations for now, though that may cause memory
10564 leaks in other situations. */
10565 #if 0
10566 #ifdef HAVE_XRMSETDATABASE
10567 XrmSetDatabase (dpyinfo->display, NULL);
10568 #else
10569 dpyinfo->display->db = NULL;
10570 #endif
10571 /* We used to call XrmDestroyDatabase from x_delete_display, but
10572 some older versions of libX11 crash if we call it after
10573 closing all the displays. */
10574 XrmDestroyDatabase (dpyinfo->xrdb);
10575 #endif
10577 #ifdef USE_GTK
10578 xg_display_close (dpyinfo->display);
10579 #else
10580 #ifdef USE_X_TOOLKIT
10581 XtCloseDisplay (dpyinfo->display);
10582 #else
10583 XCloseDisplay (dpyinfo->display);
10584 #endif
10585 #endif /* ! USE_GTK */
10588 /* Mark as dead. */
10589 dpyinfo->display = NULL;
10590 x_delete_display (dpyinfo);
10591 UNBLOCK_INPUT;
10594 /* Create a struct terminal, initialize it with the X11 specific
10595 functions and make DISPLAY->TERMINAL point to it. */
10597 static struct terminal *
10598 x_create_terminal (struct x_display_info *dpyinfo)
10600 struct terminal *terminal;
10602 terminal = create_terminal ();
10604 terminal->type = output_x_window;
10605 terminal->display_info.x = dpyinfo;
10606 dpyinfo->terminal = terminal;
10608 /* kboard is initialized in x_term_init. */
10610 terminal->clear_frame_hook = x_clear_frame;
10611 terminal->ins_del_lines_hook = x_ins_del_lines;
10612 terminal->delete_glyphs_hook = x_delete_glyphs;
10613 terminal->ring_bell_hook = XTring_bell;
10614 terminal->toggle_invisible_pointer_hook = XTtoggle_invisible_pointer;
10615 terminal->reset_terminal_modes_hook = XTreset_terminal_modes;
10616 terminal->set_terminal_modes_hook = XTset_terminal_modes;
10617 terminal->update_begin_hook = x_update_begin;
10618 terminal->update_end_hook = x_update_end;
10619 terminal->set_terminal_window_hook = XTset_terminal_window;
10620 terminal->read_socket_hook = XTread_socket;
10621 terminal->frame_up_to_date_hook = XTframe_up_to_date;
10622 terminal->mouse_position_hook = XTmouse_position;
10623 terminal->frame_rehighlight_hook = XTframe_rehighlight;
10624 terminal->frame_raise_lower_hook = XTframe_raise_lower;
10625 terminal->fullscreen_hook = XTfullscreen_hook;
10626 terminal->set_vertical_scroll_bar_hook = XTset_vertical_scroll_bar;
10627 terminal->condemn_scroll_bars_hook = XTcondemn_scroll_bars;
10628 terminal->redeem_scroll_bar_hook = XTredeem_scroll_bar;
10629 terminal->judge_scroll_bars_hook = XTjudge_scroll_bars;
10631 terminal->delete_frame_hook = x_destroy_window;
10632 terminal->delete_terminal_hook = x_delete_terminal;
10634 terminal->rif = &x_redisplay_interface;
10635 terminal->scroll_region_ok = 1; /* We'll scroll partial frames. */
10636 terminal->char_ins_del_ok = 1;
10637 terminal->line_ins_del_ok = 1; /* We'll just blt 'em. */
10638 terminal->fast_clear_end_of_line = 1; /* X does this well. */
10639 terminal->memory_below_frame = 0; /* We don't remember what scrolls
10640 off the bottom. */
10642 return terminal;
10645 void
10646 x_initialize (void)
10648 baud_rate = 19200;
10650 x_noop_count = 0;
10651 last_tool_bar_item = -1;
10652 any_help_event_p = 0;
10653 ignore_next_mouse_click_timeout = 0;
10655 #ifdef USE_GTK
10656 current_count = -1;
10657 #endif
10659 /* Try to use interrupt input; if we can't, then start polling. */
10660 Fset_input_interrupt_mode (Qt);
10662 #ifdef USE_X_TOOLKIT
10663 XtToolkitInitialize ();
10665 Xt_app_con = XtCreateApplicationContext ();
10667 /* Register a converter from strings to pixels, which uses
10668 Emacs' color allocation infrastructure. */
10669 XtAppSetTypeConverter (Xt_app_con,
10670 XtRString, XtRPixel, cvt_string_to_pixel,
10671 cvt_string_to_pixel_args,
10672 XtNumber (cvt_string_to_pixel_args),
10673 XtCacheByDisplay, cvt_pixel_dtor);
10675 XtAppSetFallbackResources (Xt_app_con, Xt_default_resources);
10676 #endif
10678 #ifdef USE_TOOLKIT_SCROLL_BARS
10679 #ifndef USE_GTK
10680 xaw3d_arrow_scroll = False;
10681 xaw3d_pick_top = True;
10682 #endif
10683 #endif
10685 pending_autoraise_frame = 0;
10686 pending_event_wait.f = 0;
10687 pending_event_wait.eventtype = 0;
10689 /* Note that there is no real way portable across R3/R4 to get the
10690 original error handler. */
10691 XSetErrorHandler (x_error_handler);
10692 XSetIOErrorHandler (x_io_error_quitter);
10694 signal (SIGPIPE, x_connection_signal);
10696 xgselect_initialize ();
10700 void
10701 syms_of_xterm (void)
10703 x_error_message = NULL;
10705 staticpro (&x_display_name_list);
10706 x_display_name_list = Qnil;
10708 staticpro (&last_mouse_scroll_bar);
10709 last_mouse_scroll_bar = Qnil;
10711 staticpro (&Qvendor_specific_keysyms);
10712 Qvendor_specific_keysyms = intern_c_string ("vendor-specific-keysyms");
10714 staticpro (&Qlatin_1);
10715 Qlatin_1 = intern_c_string ("latin-1");
10717 staticpro (&last_mouse_press_frame);
10718 last_mouse_press_frame = Qnil;
10720 #ifdef USE_GTK
10721 xg_default_icon_file = make_pure_c_string ("icons/hicolor/scalable/apps/emacs.svg");
10722 staticpro (&xg_default_icon_file);
10724 Qx_gtk_map_stock = intern_c_string ("x-gtk-map-stock");
10725 staticpro (&Qx_gtk_map_stock);
10726 #endif
10728 DEFVAR_BOOL ("x-use-underline-position-properties",
10729 x_use_underline_position_properties,
10730 doc: /* *Non-nil means make use of UNDERLINE_POSITION font properties.
10731 A value of nil means ignore them. If you encounter fonts with bogus
10732 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
10733 to 4.1, set this to nil. You can also use `underline-minimum-offset'
10734 to override the font's UNDERLINE_POSITION for small font display
10735 sizes. */);
10736 x_use_underline_position_properties = 1;
10738 DEFVAR_BOOL ("x-underline-at-descent-line",
10739 x_underline_at_descent_line,
10740 doc: /* *Non-nil means to draw the underline at the same place as the descent line.
10741 A value of nil means to draw the underline according to the value of the
10742 variable `x-use-underline-position-properties', which is usually at the
10743 baseline level. The default value is nil. */);
10744 x_underline_at_descent_line = 0;
10746 DEFVAR_BOOL ("x-mouse-click-focus-ignore-position",
10747 x_mouse_click_focus_ignore_position,
10748 doc: /* Non-nil means that a mouse click to focus a frame does not move point.
10749 This variable is only used when the window manager requires that you
10750 click on a frame to select it (give it focus). In that case, a value
10751 of nil, means that the selected window and cursor position changes to
10752 reflect the mouse click position, while a non-nil value means that the
10753 selected window or cursor position is preserved. */);
10754 x_mouse_click_focus_ignore_position = 0;
10756 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
10757 doc: /* Which toolkit scroll bars Emacs uses, if any.
10758 A value of nil means Emacs doesn't use toolkit scroll bars.
10759 With the X Window system, the value is a symbol describing the
10760 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
10761 With MS Windows, the value is t. */);
10762 #ifdef USE_TOOLKIT_SCROLL_BARS
10763 #ifdef USE_MOTIF
10764 Vx_toolkit_scroll_bars = intern_c_string ("motif");
10765 #elif defined HAVE_XAW3D
10766 Vx_toolkit_scroll_bars = intern_c_string ("xaw3d");
10767 #elif USE_GTK
10768 Vx_toolkit_scroll_bars = intern_c_string ("gtk");
10769 #else
10770 Vx_toolkit_scroll_bars = intern_c_string ("xaw");
10771 #endif
10772 #else
10773 Vx_toolkit_scroll_bars = Qnil;
10774 #endif
10776 staticpro (&last_mouse_motion_frame);
10777 last_mouse_motion_frame = Qnil;
10779 Qmodifier_value = intern_c_string ("modifier-value");
10780 Qalt = intern_c_string ("alt");
10781 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
10782 Qhyper = intern_c_string ("hyper");
10783 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
10784 Qmeta = intern_c_string ("meta");
10785 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
10786 Qsuper = intern_c_string ("super");
10787 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
10789 DEFVAR_LISP ("x-alt-keysym", Vx_alt_keysym,
10790 doc: /* Which keys Emacs uses for the alt modifier.
10791 This should be one of the symbols `alt', `hyper', `meta', `super'.
10792 For example, `alt' means use the Alt_L and Alt_R keysyms. The default
10793 is nil, which is the same as `alt'. */);
10794 Vx_alt_keysym = Qnil;
10796 DEFVAR_LISP ("x-hyper-keysym", Vx_hyper_keysym,
10797 doc: /* Which keys Emacs uses for the hyper modifier.
10798 This should be one of the symbols `alt', `hyper', `meta', `super'.
10799 For example, `hyper' means use the Hyper_L and Hyper_R keysyms. The
10800 default is nil, which is the same as `hyper'. */);
10801 Vx_hyper_keysym = Qnil;
10803 DEFVAR_LISP ("x-meta-keysym", Vx_meta_keysym,
10804 doc: /* Which keys Emacs uses for the meta modifier.
10805 This should be one of the symbols `alt', `hyper', `meta', `super'.
10806 For example, `meta' means use the Meta_L and Meta_R keysyms. The
10807 default is nil, which is the same as `meta'. */);
10808 Vx_meta_keysym = Qnil;
10810 DEFVAR_LISP ("x-super-keysym", Vx_super_keysym,
10811 doc: /* Which keys Emacs uses for the super modifier.
10812 This should be one of the symbols `alt', `hyper', `meta', `super'.
10813 For example, `super' means use the Super_L and Super_R keysyms. The
10814 default is nil, which is the same as `super'. */);
10815 Vx_super_keysym = Qnil;
10817 DEFVAR_LISP ("x-keysym-table", Vx_keysym_table,
10818 doc: /* Hash table of character codes indexed by X keysym codes. */);
10819 Vx_keysym_table = make_hash_table (Qeql, make_number (900),
10820 make_float (DEFAULT_REHASH_SIZE),
10821 make_float (DEFAULT_REHASH_THRESHOLD),
10822 Qnil, Qnil, Qnil);
10825 #endif /* HAVE_X_WINDOWS */