* lisp/emacs-lisp/unsafep.el (unsafep): Handle backquoted forms.
[emacs.git] / src / xterm.c
blobf0ef8746b017ec3ce27b613b7eb176175bc54307
1 /* X Communication module for terminals which understand the X protocol.
3 Copyright (C) 1989, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
4 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
5 Free Software Foundation, Inc.
7 This file is part of GNU Emacs.
9 GNU Emacs is free software: you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation, either version 3 of the License, or
12 (at your option) any later version.
14 GNU Emacs is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 /* New display code by Gerd Moellmann <gerd@gnu.org>. */
23 /* Xt features made by Fred Pierresteguy. */
25 #include <config.h>
26 #include <signal.h>
27 #include <stdio.h>
28 #include <setjmp.h>
30 #ifdef HAVE_X_WINDOWS
32 #include "lisp.h"
33 #include "blockinput.h"
35 /* Need syssignal.h for various externs and definitions that may be required
36 by some configurations for calls to signal later in this source file. */
37 #include "syssignal.h"
39 /* This may include sys/types.h, and that somehow loses
40 if this is not done before the other system files. */
41 #include "xterm.h"
42 #include <X11/cursorfont.h>
44 /* Load sys/types.h if not already loaded.
45 In some systems loading it twice is suicidal. */
46 #ifndef makedev
47 #include <sys/types.h>
48 #endif /* makedev */
50 #include <sys/ioctl.h>
52 #include "systime.h"
54 #include <fcntl.h>
55 #include <ctype.h>
56 #include <errno.h>
57 #include <setjmp.h>
58 #include <sys/stat.h>
59 /* Caused redefinition of DBL_DIG on Netbsd; seems not to be needed. */
60 /* #include <sys/param.h> */
62 #include "charset.h"
63 #include "character.h"
64 #include "coding.h"
65 #include "frame.h"
66 #include "dispextern.h"
67 #include "fontset.h"
68 #include "termhooks.h"
69 #include "termopts.h"
70 #include "termchar.h"
71 #include "emacs-icon.h"
72 #include "disptab.h"
73 #include "buffer.h"
74 #include "window.h"
75 #include "keyboard.h"
76 #include "intervals.h"
77 #include "process.h"
78 #include "atimer.h"
79 #include "keymap.h"
80 #include "font.h"
81 #include "fontset.h"
82 #include "xsettings.h"
83 #include "xgselect.h"
84 #include "sysselect.h"
86 #ifdef USE_X_TOOLKIT
87 #include <X11/Shell.h>
88 #endif
90 #ifdef HAVE_SYS_TIME_H
91 #include <sys/time.h>
92 #endif
93 #ifdef HAVE_UNISTD_H
94 #include <unistd.h>
95 #endif
97 #ifdef USE_GTK
98 #include "gtkutil.h"
99 #endif
101 #ifdef USE_LUCID
102 #include "../lwlib/xlwmenu.h"
103 #endif
105 #ifdef USE_X_TOOLKIT
106 #if !defined(NO_EDITRES)
107 #define HACK_EDITRES
108 extern void _XEditResCheckMessages ();
109 #endif /* not NO_EDITRES */
111 /* Include toolkit specific headers for the scroll bar widget. */
113 #ifdef USE_TOOLKIT_SCROLL_BARS
114 #if defined USE_MOTIF
115 #include <Xm/Xm.h> /* for LESSTIF_VERSION */
116 #include <Xm/ScrollBar.h>
117 #else /* !USE_MOTIF i.e. use Xaw */
119 #ifdef HAVE_XAW3D
120 #include <X11/Xaw3d/Simple.h>
121 #include <X11/Xaw3d/Scrollbar.h>
122 #include <X11/Xaw3d/ThreeD.h>
123 #else /* !HAVE_XAW3D */
124 #include <X11/Xaw/Simple.h>
125 #include <X11/Xaw/Scrollbar.h>
126 #endif /* !HAVE_XAW3D */
127 #ifndef XtNpickTop
128 #define XtNpickTop "pickTop"
129 #endif /* !XtNpickTop */
130 #endif /* !USE_MOTIF */
131 #endif /* USE_TOOLKIT_SCROLL_BARS */
133 #endif /* USE_X_TOOLKIT */
135 #ifdef USE_X_TOOLKIT
136 #include "widget.h"
137 #ifndef XtNinitialState
138 #define XtNinitialState "initialState"
139 #endif
140 #endif
142 /* Default to using XIM if available. */
143 #ifdef USE_XIM
144 int use_xim = 1;
145 #else
146 int use_xim = 0; /* configure --without-xim */
147 #endif
151 /* Non-nil means Emacs uses toolkit scroll bars. */
153 Lisp_Object Vx_toolkit_scroll_bars;
155 /* Non-zero means that a HELP_EVENT has been generated since Emacs
156 start. */
158 static int any_help_event_p;
160 /* Last window where we saw the mouse. Used by mouse-autoselect-window. */
161 static Lisp_Object last_window;
163 /* Non-zero means make use of UNDERLINE_POSITION font properties. */
165 int x_use_underline_position_properties;
167 /* Non-zero means to draw the underline at the same place as the descent line. */
169 int x_underline_at_descent_line;
171 /* This is a chain of structures for all the X displays currently in
172 use. */
174 struct x_display_info *x_display_list;
176 /* This is a list of cons cells, each of the form (NAME
177 . FONT-LIST-CACHE), one for each element of x_display_list and in
178 the same order. NAME is the name of the frame. FONT-LIST-CACHE
179 records previous values returned by x-list-fonts. */
181 Lisp_Object x_display_name_list;
183 /* Frame being updated by update_frame. This is declared in term.c.
184 This is set by update_begin and looked at by all the XT functions.
185 It is zero while not inside an update. In that case, the XT
186 functions assume that `selected_frame' is the frame to apply to. */
188 extern struct frame *updating_frame;
190 /* This is a frame waiting to be auto-raised, within XTread_socket. */
192 static struct frame *pending_autoraise_frame;
194 /* This is a frame waiting for an event matching mask, within XTread_socket. */
196 static struct {
197 struct frame *f;
198 int eventtype;
199 } pending_event_wait;
201 #ifdef USE_X_TOOLKIT
202 /* The application context for Xt use. */
203 XtAppContext Xt_app_con;
204 static String Xt_default_resources[] = {0};
205 #endif /* USE_X_TOOLKIT */
207 /* Non-zero means user is interacting with a toolkit scroll bar. */
209 static int toolkit_scroll_bar_interaction;
211 /* Non-zero means to not move point as a result of clicking on a
212 frame to focus it (when focus-follows-mouse is nil). */
214 int x_mouse_click_focus_ignore_position;
216 /* Non-zero timeout value means ignore next mouse click if it arrives
217 before that timeout elapses (i.e. as part of the same sequence of
218 events resulting from clicking on a frame to select it). */
220 static unsigned long ignore_next_mouse_click_timeout;
222 /* Mouse movement.
224 Formerly, we used PointerMotionHintMask (in standard_event_mask)
225 so that we would have to call XQueryPointer after each MotionNotify
226 event to ask for another such event. However, this made mouse tracking
227 slow, and there was a bug that made it eventually stop.
229 Simply asking for MotionNotify all the time seems to work better.
231 In order to avoid asking for motion events and then throwing most
232 of them away or busy-polling the server for mouse positions, we ask
233 the server for pointer motion hints. This means that we get only
234 one event per group of mouse movements. "Groups" are delimited by
235 other kinds of events (focus changes and button clicks, for
236 example), or by XQueryPointer calls; when one of these happens, we
237 get another MotionNotify event the next time the mouse moves. This
238 is at least as efficient as getting motion events when mouse
239 tracking is on, and I suspect only negligibly worse when tracking
240 is off. */
242 /* Where the mouse was last time we reported a mouse event. */
244 static XRectangle last_mouse_glyph;
245 static FRAME_PTR last_mouse_glyph_frame;
246 static Lisp_Object last_mouse_press_frame;
248 /* The scroll bar in which the last X motion event occurred.
250 If the last X motion event occurred in a scroll bar, we set this so
251 XTmouse_position can know whether to report a scroll bar motion or
252 an ordinary motion.
254 If the last X motion event didn't occur in a scroll bar, we set
255 this to Qnil, to tell XTmouse_position to return an ordinary motion
256 event. */
258 static Lisp_Object last_mouse_scroll_bar;
260 /* This is a hack. We would really prefer that XTmouse_position would
261 return the time associated with the position it returns, but there
262 doesn't seem to be any way to wrest the time-stamp from the server
263 along with the position query. So, we just keep track of the time
264 of the last movement we received, and return that in hopes that
265 it's somewhat accurate. */
267 static Time last_mouse_movement_time;
269 /* Time for last user interaction as returned in X events. */
271 static Time last_user_time;
273 /* Incremented by XTread_socket whenever it really tries to read
274 events. */
276 #ifdef __STDC__
277 static int volatile input_signal_count;
278 #else
279 static int input_signal_count;
280 #endif
282 /* Used locally within XTread_socket. */
284 static int x_noop_count;
286 /* The keysyms to use for the various modifiers. */
288 Lisp_Object Vx_alt_keysym, Vx_hyper_keysym, Vx_meta_keysym, Vx_super_keysym;
289 Lisp_Object Vx_keysym_table;
290 static Lisp_Object Qalt, Qhyper, Qmeta, Qsuper, Qmodifier_value;
292 static Lisp_Object Qvendor_specific_keysyms;
293 static Lisp_Object Qlatin_1;
295 #ifdef USE_GTK
296 /* The name of the Emacs icon file. */
297 static Lisp_Object xg_default_icon_file;
299 /* Used in gtkutil.c. */
300 Lisp_Object Qx_gtk_map_stock;
301 #endif
303 /* Some functions take this as char *, not const char *. */
304 static char emacs_class[] = EMACS_CLASS;
306 /* XEmbed implementation. */
308 #define XEMBED_VERSION 0
310 enum xembed_info
312 XEMBED_MAPPED = 1 << 0
315 enum xembed_message
317 XEMBED_EMBEDDED_NOTIFY = 0,
318 XEMBED_WINDOW_ACTIVATE = 1,
319 XEMBED_WINDOW_DEACTIVATE = 2,
320 XEMBED_REQUEST_FOCUS = 3,
321 XEMBED_FOCUS_IN = 4,
322 XEMBED_FOCUS_OUT = 5,
323 XEMBED_FOCUS_NEXT = 6,
324 XEMBED_FOCUS_PREV = 7,
326 XEMBED_MODALITY_ON = 10,
327 XEMBED_MODALITY_OFF = 11,
328 XEMBED_REGISTER_ACCELERATOR = 12,
329 XEMBED_UNREGISTER_ACCELERATOR = 13,
330 XEMBED_ACTIVATE_ACCELERATOR = 14
333 /* Used in x_flush. */
335 static int x_alloc_nearest_color_1 (Display *, Colormap, XColor *);
336 static void x_set_window_size_1 (struct frame *, int, int, int);
337 static const XColor *x_color_cells (Display *, int *);
338 static void x_update_window_end (struct window *, int, int);
340 static int x_io_error_quitter (Display *);
341 static struct terminal *x_create_terminal (struct x_display_info *);
342 void x_delete_terminal (struct terminal *);
343 static void x_update_end (struct frame *);
344 static void XTframe_up_to_date (struct frame *);
345 static void XTset_terminal_modes (struct terminal *);
346 static void XTreset_terminal_modes (struct terminal *);
347 static void x_clear_frame (struct frame *);
348 static void frame_highlight (struct frame *);
349 static void frame_unhighlight (struct frame *);
350 static void x_new_focus_frame (struct x_display_info *, struct frame *);
351 static void x_focus_changed (int, int, struct x_display_info *,
352 struct frame *, struct input_event *);
353 static void x_detect_focus_change (struct x_display_info *,
354 XEvent *, struct input_event *);
355 static void XTframe_rehighlight (struct frame *);
356 static void x_frame_rehighlight (struct x_display_info *);
357 static void x_draw_hollow_cursor (struct window *, struct glyph_row *);
358 static void x_draw_bar_cursor (struct window *, struct glyph_row *, int,
359 enum text_cursor_kinds);
361 static void x_clip_to_row (struct window *, struct glyph_row *, int, GC);
362 static void x_flush (struct frame *f);
363 static void x_update_begin (struct frame *);
364 static void x_update_window_begin (struct window *);
365 static void x_after_update_window_line (struct glyph_row *);
366 static struct scroll_bar *x_window_to_scroll_bar (Display *, Window);
367 static void x_scroll_bar_report_motion (struct frame **, Lisp_Object *,
368 enum scroll_bar_part *,
369 Lisp_Object *, Lisp_Object *,
370 unsigned long *);
371 static void x_handle_net_wm_state (struct frame *, XPropertyEvent *);
372 static void x_check_fullscreen (struct frame *);
373 static void x_check_expected_move (struct frame *, int, int);
374 static void x_sync_with_move (struct frame *, int, int, int);
375 static int handle_one_xevent (struct x_display_info *, XEvent *,
376 int *, struct input_event *);
377 /* Don't declare this NO_RETURN because we want no
378 interference with debugging failing X calls. */
379 static SIGTYPE x_connection_closed (Display *, const char *);
382 /* Flush display of frame F, or of all frames if F is null. */
384 static void
385 x_flush (struct frame *f)
387 /* Don't call XFlush when it is not safe to redisplay; the X
388 connection may be broken. */
389 if (!NILP (Vinhibit_redisplay))
390 return;
392 BLOCK_INPUT;
393 if (f == NULL)
395 Lisp_Object rest, frame;
396 FOR_EACH_FRAME (rest, frame)
397 if (FRAME_X_P (XFRAME (frame)))
398 x_flush (XFRAME (frame));
400 else if (FRAME_X_P (f))
401 XFlush (FRAME_X_DISPLAY (f));
402 UNBLOCK_INPUT;
406 /* Remove calls to XFlush by defining XFlush to an empty replacement.
407 Calls to XFlush should be unnecessary because the X output buffer
408 is flushed automatically as needed by calls to XPending,
409 XNextEvent, or XWindowEvent according to the XFlush man page.
410 XTread_socket calls XPending. Removing XFlush improves
411 performance. */
413 #define XFlush(DISPLAY) (void) 0
416 /***********************************************************************
417 Debugging
418 ***********************************************************************/
420 #if 0
422 /* This is a function useful for recording debugging information about
423 the sequence of occurrences in this file. */
425 struct record
427 char *locus;
428 int type;
431 struct record event_record[100];
433 int event_record_index;
435 void
436 record_event (char *locus, int type)
438 if (event_record_index == sizeof (event_record) / sizeof (struct record))
439 event_record_index = 0;
441 event_record[event_record_index].locus = locus;
442 event_record[event_record_index].type = type;
443 event_record_index++;
446 #endif /* 0 */
450 /* Return the struct x_display_info corresponding to DPY. */
452 struct x_display_info *
453 x_display_info_for_display (Display *dpy)
455 struct x_display_info *dpyinfo;
457 for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
458 if (dpyinfo->display == dpy)
459 return dpyinfo;
461 return 0;
464 #define OPAQUE 0xffffffff
466 void
467 x_set_frame_alpha (struct frame *f)
469 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
470 Display *dpy = FRAME_X_DISPLAY (f);
471 Window win = FRAME_OUTER_WINDOW (f);
472 double alpha = 1.0;
473 double alpha_min = 1.0;
474 unsigned long opac;
476 if (FRAME_X_DISPLAY_INFO (f)->root_window != FRAME_X_OUTPUT (f)->parent_desc)
477 /* Since the WM decoration lies under the FRAME_OUTER_WINDOW,
478 we must treat the former instead of the latter. */
479 win = FRAME_X_OUTPUT (f)->parent_desc;
481 if (dpyinfo->x_highlight_frame == f)
482 alpha = f->alpha[0];
483 else
484 alpha = f->alpha[1];
486 if (FLOATP (Vframe_alpha_lower_limit))
487 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
488 else if (INTEGERP (Vframe_alpha_lower_limit))
489 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
491 if (alpha < 0.0)
492 return;
493 else if (alpha > 1.0)
494 alpha = 1.0;
495 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
496 alpha = alpha_min;
498 opac = alpha * OPAQUE;
500 /* return unless necessary */
502 unsigned char *data;
503 Atom actual;
504 int rc, format;
505 unsigned long n, left;
507 x_catch_errors (dpy);
508 rc = XGetWindowProperty (dpy, win, dpyinfo->Xatom_net_wm_window_opacity,
509 0L, 1L, False, XA_CARDINAL,
510 &actual, &format, &n, &left,
511 &data);
513 if (rc == Success && actual != None)
515 XFree ((void *) data);
516 if (*(unsigned long *)data == opac)
518 x_uncatch_errors ();
519 return;
522 x_uncatch_errors ();
525 x_catch_errors (dpy);
526 XChangeProperty (dpy, win, dpyinfo->Xatom_net_wm_window_opacity,
527 XA_CARDINAL, 32, PropModeReplace,
528 (unsigned char *) &opac, 1L);
529 x_uncatch_errors ();
533 x_display_pixel_height (struct x_display_info *dpyinfo)
535 return HeightOfScreen (dpyinfo->screen);
539 x_display_pixel_width (struct x_display_info *dpyinfo)
541 return WidthOfScreen (dpyinfo->screen);
545 /***********************************************************************
546 Starting and ending an update
547 ***********************************************************************/
549 /* Start an update of frame F. This function is installed as a hook
550 for update_begin, i.e. it is called when update_begin is called.
551 This function is called prior to calls to x_update_window_begin for
552 each window being updated. Currently, there is nothing to do here
553 because all interesting stuff is done on a window basis. */
555 static void
556 x_update_begin (struct frame *f)
558 /* Nothing to do. */
562 /* Start update of window W. Set the global variable updated_window
563 to the window being updated and set output_cursor to the cursor
564 position of W. */
566 static void
567 x_update_window_begin (struct window *w)
569 struct frame *f = XFRAME (WINDOW_FRAME (w));
570 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
572 updated_window = w;
573 set_output_cursor (&w->cursor);
575 BLOCK_INPUT;
577 if (f == hlinfo->mouse_face_mouse_frame)
579 /* Don't do highlighting for mouse motion during the update. */
580 hlinfo->mouse_face_defer = 1;
582 /* If F needs to be redrawn, simply forget about any prior mouse
583 highlighting. */
584 if (FRAME_GARBAGED_P (f))
585 hlinfo->mouse_face_window = Qnil;
588 UNBLOCK_INPUT;
592 /* Draw a vertical window border from (x,y0) to (x,y1) */
594 static void
595 x_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
597 struct frame *f = XFRAME (WINDOW_FRAME (w));
598 struct face *face;
600 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
601 if (face)
602 XSetForeground (FRAME_X_DISPLAY (f), f->output_data.x->normal_gc,
603 face->foreground);
605 XDrawLine (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
606 f->output_data.x->normal_gc, x, y0, x, y1);
609 /* End update of window W (which is equal to updated_window).
611 Draw vertical borders between horizontally adjacent windows, and
612 display W's cursor if CURSOR_ON_P is non-zero.
614 MOUSE_FACE_OVERWRITTEN_P non-zero means that some row containing
615 glyphs in mouse-face were overwritten. In that case we have to
616 make sure that the mouse-highlight is properly redrawn.
618 W may be a menu bar pseudo-window in case we don't have X toolkit
619 support. Such windows don't have a cursor, so don't display it
620 here. */
622 static void
623 x_update_window_end (struct window *w, int cursor_on_p, int mouse_face_overwritten_p)
625 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (XFRAME (w->frame));
627 if (!w->pseudo_window_p)
629 BLOCK_INPUT;
631 if (cursor_on_p)
632 display_and_set_cursor (w, 1, output_cursor.hpos,
633 output_cursor.vpos,
634 output_cursor.x, output_cursor.y);
636 if (draw_window_fringes (w, 1))
637 x_draw_vertical_border (w);
639 UNBLOCK_INPUT;
642 /* If a row with mouse-face was overwritten, arrange for
643 XTframe_up_to_date to redisplay the mouse highlight. */
644 if (mouse_face_overwritten_p)
646 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
647 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
648 hlinfo->mouse_face_window = Qnil;
651 updated_window = NULL;
655 /* End update of frame F. This function is installed as a hook in
656 update_end. */
658 static void
659 x_update_end (struct frame *f)
661 /* Mouse highlight may be displayed again. */
662 MOUSE_HL_INFO (f)->mouse_face_defer = 0;
664 #ifndef XFlush
665 BLOCK_INPUT;
666 XFlush (FRAME_X_DISPLAY (f));
667 UNBLOCK_INPUT;
668 #endif
672 /* This function is called from various places in xdisp.c whenever a
673 complete update has been performed. The global variable
674 updated_window is not available here. */
676 static void
677 XTframe_up_to_date (struct frame *f)
679 if (FRAME_X_P (f))
681 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
683 if (hlinfo->mouse_face_deferred_gc
684 || f == hlinfo->mouse_face_mouse_frame)
686 BLOCK_INPUT;
687 if (hlinfo->mouse_face_mouse_frame)
688 note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
689 hlinfo->mouse_face_mouse_x,
690 hlinfo->mouse_face_mouse_y);
691 hlinfo->mouse_face_deferred_gc = 0;
692 UNBLOCK_INPUT;
698 /* Draw truncation mark bitmaps, continuation mark bitmaps, overlay
699 arrow bitmaps, or clear the fringes if no bitmaps are required
700 before DESIRED_ROW is made current. The window being updated is
701 found in updated_window. This function It is called from
702 update_window_line only if it is known that there are differences
703 between bitmaps to be drawn between current row and DESIRED_ROW. */
705 static void
706 x_after_update_window_line (struct glyph_row *desired_row)
708 struct window *w = updated_window;
709 struct frame *f;
710 int width, height;
712 xassert (w);
714 if (!desired_row->mode_line_p && !w->pseudo_window_p)
715 desired_row->redraw_fringe_bitmaps_p = 1;
717 /* When a window has disappeared, make sure that no rest of
718 full-width rows stays visible in the internal border. Could
719 check here if updated_window is the leftmost/rightmost window,
720 but I guess it's not worth doing since vertically split windows
721 are almost never used, internal border is rarely set, and the
722 overhead is very small. */
723 if (windows_or_buffers_changed
724 && desired_row->full_width_p
725 && (f = XFRAME (w->frame),
726 width = FRAME_INTERNAL_BORDER_WIDTH (f),
727 width != 0)
728 && (height = desired_row->visible_height,
729 height > 0))
731 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
733 BLOCK_INPUT;
734 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
735 0, y, width, height, False);
736 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
737 FRAME_PIXEL_WIDTH (f) - width,
738 y, width, height, False);
739 UNBLOCK_INPUT;
743 static void
744 x_draw_fringe_bitmap (struct window *w, struct glyph_row *row, struct draw_fringe_bitmap_params *p)
746 struct frame *f = XFRAME (WINDOW_FRAME (w));
747 Display *display = FRAME_X_DISPLAY (f);
748 Window window = FRAME_X_WINDOW (f);
749 GC gc = f->output_data.x->normal_gc;
750 struct face *face = p->face;
752 /* Must clip because of partially visible lines. */
753 x_clip_to_row (w, row, -1, gc);
755 if (!p->overlay_p)
757 int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
759 /* In case the same realized face is used for fringes and
760 for something displayed in the text (e.g. face `region' on
761 mono-displays, the fill style may have been changed to
762 FillSolid in x_draw_glyph_string_background. */
763 if (face->stipple)
764 XSetFillStyle (display, face->gc, FillOpaqueStippled);
765 else
766 XSetForeground (display, face->gc, face->background);
768 #ifdef USE_TOOLKIT_SCROLL_BARS
769 /* If the fringe is adjacent to the left (right) scroll bar of a
770 leftmost (rightmost, respectively) window, then extend its
771 background to the gap between the fringe and the bar. */
772 if ((WINDOW_LEFTMOST_P (w)
773 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
774 || (WINDOW_RIGHTMOST_P (w)
775 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w)))
777 int sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
779 if (sb_width > 0)
781 int left = WINDOW_SCROLL_BAR_AREA_X (w);
782 int width = (WINDOW_CONFIG_SCROLL_BAR_COLS (w)
783 * FRAME_COLUMN_WIDTH (f));
785 if (bx < 0)
787 /* Bitmap fills the fringe. */
788 if (left + width == p->x)
789 bx = left + sb_width;
790 else if (p->x + p->wd == left)
791 bx = left;
792 if (bx >= 0)
794 int header_line_height = WINDOW_HEADER_LINE_HEIGHT (w);
796 nx = width - sb_width;
797 by = WINDOW_TO_FRAME_PIXEL_Y (w, max (header_line_height,
798 row->y));
799 ny = row->visible_height;
802 else
804 if (left + width == bx)
806 bx = left + sb_width;
807 nx += width - sb_width;
809 else if (bx + nx == left)
810 nx += width - sb_width;
814 #endif
815 if (bx >= 0 && nx > 0)
816 XFillRectangle (display, window, face->gc, bx, by, nx, ny);
818 if (!face->stipple)
819 XSetForeground (display, face->gc, face->foreground);
822 if (p->which)
824 unsigned char *bits;
825 Pixmap pixmap, clipmask = (Pixmap) 0;
826 int depth = DefaultDepthOfScreen (FRAME_X_SCREEN (f));
827 XGCValues gcv;
829 if (p->wd > 8)
830 bits = (unsigned char *)(p->bits + p->dh);
831 else
832 bits = (unsigned char *)p->bits + p->dh;
834 /* Draw the bitmap. I believe these small pixmaps can be cached
835 by the server. */
836 pixmap = XCreatePixmapFromBitmapData (display, window, bits, p->wd, p->h,
837 (p->cursor_p
838 ? (p->overlay_p ? face->background
839 : f->output_data.x->cursor_pixel)
840 : face->foreground),
841 face->background, depth);
843 if (p->overlay_p)
845 clipmask = XCreatePixmapFromBitmapData (display,
846 FRAME_X_DISPLAY_INFO (f)->root_window,
847 bits, p->wd, p->h,
848 1, 0, 1);
849 gcv.clip_mask = clipmask;
850 gcv.clip_x_origin = p->x;
851 gcv.clip_y_origin = p->y;
852 XChangeGC (display, gc, GCClipMask | GCClipXOrigin | GCClipYOrigin, &gcv);
855 XCopyArea (display, pixmap, window, gc, 0, 0,
856 p->wd, p->h, p->x, p->y);
857 XFreePixmap (display, pixmap);
859 if (p->overlay_p)
861 gcv.clip_mask = (Pixmap) 0;
862 XChangeGC (display, gc, GCClipMask, &gcv);
863 XFreePixmap (display, clipmask);
867 XSetClipMask (display, gc, None);
872 /* This is called when starting Emacs and when restarting after
873 suspend. When starting Emacs, no X window is mapped. And nothing
874 must be done to Emacs's own window if it is suspended (though that
875 rarely happens). */
877 static void
878 XTset_terminal_modes (struct terminal *terminal)
882 /* This is called when exiting or suspending Emacs. Exiting will make
883 the X-windows go away, and suspending requires no action. */
885 static void
886 XTreset_terminal_modes (struct terminal *terminal)
891 /***********************************************************************
892 Glyph display
893 ***********************************************************************/
897 static void x_set_glyph_string_clipping (struct glyph_string *);
898 static void x_set_glyph_string_gc (struct glyph_string *);
899 static void x_draw_glyph_string_background (struct glyph_string *,
900 int);
901 static void x_draw_glyph_string_foreground (struct glyph_string *);
902 static void x_draw_composite_glyph_string_foreground (struct glyph_string *);
903 static void x_draw_glyph_string_box (struct glyph_string *);
904 static void x_draw_glyph_string (struct glyph_string *);
905 static void x_compute_glyph_string_overhangs (struct glyph_string *);
906 static void x_set_cursor_gc (struct glyph_string *);
907 static void x_set_mode_line_face_gc (struct glyph_string *);
908 static void x_set_mouse_face_gc (struct glyph_string *);
909 static int x_alloc_lighter_color (struct frame *, Display *, Colormap,
910 unsigned long *, double, int);
911 static void x_setup_relief_color (struct frame *, struct relief *,
912 double, int, unsigned long);
913 static void x_setup_relief_colors (struct glyph_string *);
914 static void x_draw_image_glyph_string (struct glyph_string *);
915 static void x_draw_image_relief (struct glyph_string *);
916 static void x_draw_image_foreground (struct glyph_string *);
917 static void x_draw_image_foreground_1 (struct glyph_string *, Pixmap);
918 static void x_clear_glyph_string_rect (struct glyph_string *, int,
919 int, int, int);
920 static void x_draw_relief_rect (struct frame *, int, int, int, int,
921 int, int, int, int, int, int,
922 XRectangle *);
923 static void x_draw_box_rect (struct glyph_string *, int, int, int, int,
924 int, int, int, XRectangle *);
925 static void x_scroll_bar_clear (struct frame *);
927 #if GLYPH_DEBUG
928 static void x_check_font (struct frame *, struct font *);
929 #endif
932 /* Set S->gc to a suitable GC for drawing glyph string S in cursor
933 face. */
935 static void
936 x_set_cursor_gc (struct glyph_string *s)
938 if (s->font == FRAME_FONT (s->f)
939 && s->face->background == FRAME_BACKGROUND_PIXEL (s->f)
940 && s->face->foreground == FRAME_FOREGROUND_PIXEL (s->f)
941 && !s->cmp)
942 s->gc = s->f->output_data.x->cursor_gc;
943 else
945 /* Cursor on non-default face: must merge. */
946 XGCValues xgcv;
947 unsigned long mask;
949 xgcv.background = s->f->output_data.x->cursor_pixel;
950 xgcv.foreground = s->face->background;
952 /* If the glyph would be invisible, try a different foreground. */
953 if (xgcv.foreground == xgcv.background)
954 xgcv.foreground = s->face->foreground;
955 if (xgcv.foreground == xgcv.background)
956 xgcv.foreground = s->f->output_data.x->cursor_foreground_pixel;
957 if (xgcv.foreground == xgcv.background)
958 xgcv.foreground = s->face->foreground;
960 /* Make sure the cursor is distinct from text in this face. */
961 if (xgcv.background == s->face->background
962 && xgcv.foreground == s->face->foreground)
964 xgcv.background = s->face->foreground;
965 xgcv.foreground = s->face->background;
968 IF_DEBUG (x_check_font (s->f, s->font));
969 xgcv.graphics_exposures = False;
970 mask = GCForeground | GCBackground | GCGraphicsExposures;
972 if (FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc)
973 XChangeGC (s->display, FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc,
974 mask, &xgcv);
975 else
976 FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc
977 = XCreateGC (s->display, s->window, mask, &xgcv);
979 s->gc = FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc;
984 /* Set up S->gc of glyph string S for drawing text in mouse face. */
986 static void
987 x_set_mouse_face_gc (struct glyph_string *s)
989 int face_id;
990 struct face *face;
992 /* What face has to be used last for the mouse face? */
993 face_id = MOUSE_HL_INFO (s->f)->mouse_face_face_id;
994 face = FACE_FROM_ID (s->f, face_id);
995 if (face == NULL)
996 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
998 if (s->first_glyph->type == CHAR_GLYPH)
999 face_id = FACE_FOR_CHAR (s->f, face, s->first_glyph->u.ch, -1, Qnil);
1000 else
1001 face_id = FACE_FOR_CHAR (s->f, face, 0, -1, Qnil);
1002 s->face = FACE_FROM_ID (s->f, face_id);
1003 PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
1005 if (s->font == s->face->font)
1006 s->gc = s->face->gc;
1007 else
1009 /* Otherwise construct scratch_cursor_gc with values from FACE
1010 except for FONT. */
1011 XGCValues xgcv;
1012 unsigned long mask;
1014 xgcv.background = s->face->background;
1015 xgcv.foreground = s->face->foreground;
1016 xgcv.graphics_exposures = False;
1017 mask = GCForeground | GCBackground | GCGraphicsExposures;
1019 if (FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc)
1020 XChangeGC (s->display, FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc,
1021 mask, &xgcv);
1022 else
1023 FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc
1024 = XCreateGC (s->display, s->window, mask, &xgcv);
1026 s->gc = FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc;
1029 xassert (s->gc != 0);
1033 /* Set S->gc of glyph string S to a GC suitable for drawing a mode line.
1034 Faces to use in the mode line have already been computed when the
1035 matrix was built, so there isn't much to do, here. */
1037 static INLINE void
1038 x_set_mode_line_face_gc (struct glyph_string *s)
1040 s->gc = s->face->gc;
1044 /* Set S->gc of glyph string S for drawing that glyph string. Set
1045 S->stippled_p to a non-zero value if the face of S has a stipple
1046 pattern. */
1048 static INLINE void
1049 x_set_glyph_string_gc (struct glyph_string *s)
1051 PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
1053 if (s->hl == DRAW_NORMAL_TEXT)
1055 s->gc = s->face->gc;
1056 s->stippled_p = s->face->stipple != 0;
1058 else if (s->hl == DRAW_INVERSE_VIDEO)
1060 x_set_mode_line_face_gc (s);
1061 s->stippled_p = s->face->stipple != 0;
1063 else if (s->hl == DRAW_CURSOR)
1065 x_set_cursor_gc (s);
1066 s->stippled_p = 0;
1068 else if (s->hl == DRAW_MOUSE_FACE)
1070 x_set_mouse_face_gc (s);
1071 s->stippled_p = s->face->stipple != 0;
1073 else if (s->hl == DRAW_IMAGE_RAISED
1074 || s->hl == DRAW_IMAGE_SUNKEN)
1076 s->gc = s->face->gc;
1077 s->stippled_p = s->face->stipple != 0;
1079 else
1081 s->gc = s->face->gc;
1082 s->stippled_p = s->face->stipple != 0;
1085 /* GC must have been set. */
1086 xassert (s->gc != 0);
1090 /* Set clipping for output of glyph string S. S may be part of a mode
1091 line or menu if we don't have X toolkit support. */
1093 static INLINE void
1094 x_set_glyph_string_clipping (struct glyph_string *s)
1096 XRectangle *r = s->clip;
1097 int n = get_glyph_string_clip_rects (s, r, 2);
1099 if (n > 0)
1100 XSetClipRectangles (s->display, s->gc, 0, 0, r, n, Unsorted);
1101 s->num_clips = n;
1105 /* Set SRC's clipping for output of glyph string DST. This is called
1106 when we are drawing DST's left_overhang or right_overhang only in
1107 the area of SRC. */
1109 static void
1110 x_set_glyph_string_clipping_exactly (struct glyph_string *src, struct glyph_string *dst)
1112 XRectangle r;
1114 r.x = src->x;
1115 r.width = src->width;
1116 r.y = src->y;
1117 r.height = src->height;
1118 dst->clip[0] = r;
1119 dst->num_clips = 1;
1120 XSetClipRectangles (dst->display, dst->gc, 0, 0, &r, 1, Unsorted);
1124 /* RIF:
1125 Compute left and right overhang of glyph string S. */
1127 static void
1128 x_compute_glyph_string_overhangs (struct glyph_string *s)
1130 if (s->cmp == NULL
1131 && (s->first_glyph->type == CHAR_GLYPH
1132 || s->first_glyph->type == COMPOSITE_GLYPH))
1134 struct font_metrics metrics;
1136 if (s->first_glyph->type == CHAR_GLYPH)
1138 unsigned *code = alloca (sizeof (unsigned) * s->nchars);
1139 struct font *font = s->font;
1140 int i;
1142 for (i = 0; i < s->nchars; i++)
1143 code[i] = (s->char2b[i].byte1 << 8) | s->char2b[i].byte2;
1144 font->driver->text_extents (font, code, s->nchars, &metrics);
1146 else
1148 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1150 composition_gstring_width (gstring, s->cmp_from, s->cmp_to, &metrics);
1152 s->right_overhang = (metrics.rbearing > metrics.width
1153 ? metrics.rbearing - metrics.width : 0);
1154 s->left_overhang = metrics.lbearing < 0 ? - metrics.lbearing : 0;
1156 else if (s->cmp)
1158 s->right_overhang = s->cmp->rbearing - s->cmp->pixel_width;
1159 s->left_overhang = - s->cmp->lbearing;
1164 /* Fill rectangle X, Y, W, H with background color of glyph string S. */
1166 static INLINE void
1167 x_clear_glyph_string_rect (struct glyph_string *s, int x, int y, int w, int h)
1169 XGCValues xgcv;
1170 XGetGCValues (s->display, s->gc, GCForeground | GCBackground, &xgcv);
1171 XSetForeground (s->display, s->gc, xgcv.background);
1172 XFillRectangle (s->display, s->window, s->gc, x, y, w, h);
1173 XSetForeground (s->display, s->gc, xgcv.foreground);
1177 /* Draw the background of glyph_string S. If S->background_filled_p
1178 is non-zero don't draw it. FORCE_P non-zero means draw the
1179 background even if it wouldn't be drawn normally. This is used
1180 when a string preceding S draws into the background of S, or S
1181 contains the first component of a composition. */
1183 static void
1184 x_draw_glyph_string_background (struct glyph_string *s, int force_p)
1186 /* Nothing to do if background has already been drawn or if it
1187 shouldn't be drawn in the first place. */
1188 if (!s->background_filled_p)
1190 int box_line_width = max (s->face->box_line_width, 0);
1192 if (s->stippled_p)
1194 /* Fill background with a stipple pattern. */
1195 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
1196 XFillRectangle (s->display, s->window, s->gc, s->x,
1197 s->y + box_line_width,
1198 s->background_width,
1199 s->height - 2 * box_line_width);
1200 XSetFillStyle (s->display, s->gc, FillSolid);
1201 s->background_filled_p = 1;
1203 else if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
1204 || s->font_not_found_p
1205 || s->extends_to_end_of_line_p
1206 || force_p)
1208 x_clear_glyph_string_rect (s, s->x, s->y + box_line_width,
1209 s->background_width,
1210 s->height - 2 * box_line_width);
1211 s->background_filled_p = 1;
1217 /* Draw the foreground of glyph string S. */
1219 static void
1220 x_draw_glyph_string_foreground (struct glyph_string *s)
1222 int i, x;
1224 /* If first glyph of S has a left box line, start drawing the text
1225 of S to the right of that box line. */
1226 if (s->face->box != FACE_NO_BOX
1227 && s->first_glyph->left_box_line_p)
1228 x = s->x + eabs (s->face->box_line_width);
1229 else
1230 x = s->x;
1232 /* Draw characters of S as rectangles if S's font could not be
1233 loaded. */
1234 if (s->font_not_found_p)
1236 for (i = 0; i < s->nchars; ++i)
1238 struct glyph *g = s->first_glyph + i;
1239 XDrawRectangle (s->display, s->window,
1240 s->gc, x, s->y, g->pixel_width - 1,
1241 s->height - 1);
1242 x += g->pixel_width;
1245 else
1247 struct font *font = s->font;
1248 int boff = font->baseline_offset;
1249 int y;
1251 if (font->vertical_centering)
1252 boff = VCENTER_BASELINE_OFFSET (font, s->f) - boff;
1254 y = s->ybase - boff;
1255 if (s->for_overlaps
1256 || (s->background_filled_p && s->hl != DRAW_CURSOR))
1257 font->driver->draw (s, 0, s->nchars, x, y, 0);
1258 else
1259 font->driver->draw (s, 0, s->nchars, x, y, 1);
1260 if (s->face->overstrike)
1261 font->driver->draw (s, 0, s->nchars, x + 1, y, 0);
1265 /* Draw the foreground of composite glyph string S. */
1267 static void
1268 x_draw_composite_glyph_string_foreground (struct glyph_string *s)
1270 int i, j, x;
1271 struct font *font = s->font;
1273 /* If first glyph of S has a left box line, start drawing the text
1274 of S to the right of that box line. */
1275 if (s->face && s->face->box != FACE_NO_BOX
1276 && s->first_glyph->left_box_line_p)
1277 x = s->x + eabs (s->face->box_line_width);
1278 else
1279 x = s->x;
1281 /* S is a glyph string for a composition. S->cmp_from is the index
1282 of the first character drawn for glyphs of this composition.
1283 S->cmp_from == 0 means we are drawing the very first character of
1284 this composition. */
1286 /* Draw a rectangle for the composition if the font for the very
1287 first character of the composition could not be loaded. */
1288 if (s->font_not_found_p)
1290 if (s->cmp_from == 0)
1291 XDrawRectangle (s->display, s->window, s->gc, x, s->y,
1292 s->width - 1, s->height - 1);
1294 else if (! s->first_glyph->u.cmp.automatic)
1296 int y = s->ybase;
1298 for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
1299 if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
1301 int xx = x + s->cmp->offsets[j * 2];
1302 int yy = y - s->cmp->offsets[j * 2 + 1];
1304 font->driver->draw (s, j, j + 1, xx, yy, 0);
1305 if (s->face->overstrike)
1306 font->driver->draw (s, j, j + 1, xx + 1, yy, 0);
1309 else
1311 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1312 Lisp_Object glyph;
1313 int y = s->ybase;
1314 int width = 0;
1316 for (i = j = s->cmp_from; i < s->cmp_to; i++)
1318 glyph = LGSTRING_GLYPH (gstring, i);
1319 if (NILP (LGLYPH_ADJUSTMENT (glyph)))
1320 width += LGLYPH_WIDTH (glyph);
1321 else
1323 int xoff, yoff, wadjust;
1325 if (j < i)
1327 font->driver->draw (s, j, i, x, y, 0);
1328 if (s->face->overstrike)
1329 font->driver->draw (s, j, i, x + 1, y, 0);
1330 x += width;
1332 xoff = LGLYPH_XOFF (glyph);
1333 yoff = LGLYPH_YOFF (glyph);
1334 wadjust = LGLYPH_WADJUST (glyph);
1335 font->driver->draw (s, i, i + 1, x + xoff, y + yoff, 0);
1336 if (s->face->overstrike)
1337 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff, 0);
1338 x += wadjust;
1339 j = i + 1;
1340 width = 0;
1343 if (j < i)
1345 font->driver->draw (s, j, i, x, y, 0);
1346 if (s->face->overstrike)
1347 font->driver->draw (s, j, i, x + 1, y, 0);
1353 /* Draw the foreground of glyph string S for glyphless characters. */
1355 static void
1356 x_draw_glyphless_glyph_string_foreground (struct glyph_string *s)
1358 struct glyph *glyph = s->first_glyph;
1359 XChar2b char2b[8];
1360 int x, i, j;
1362 /* If first glyph of S has a left box line, start drawing the text
1363 of S to the right of that box line. */
1364 if (s->face && s->face->box != FACE_NO_BOX
1365 && s->first_glyph->left_box_line_p)
1366 x = s->x + eabs (s->face->box_line_width);
1367 else
1368 x = s->x;
1370 s->char2b = char2b;
1372 for (i = 0; i < s->nchars; i++, glyph++)
1374 char buf[7], *str = NULL;
1375 int len = glyph->u.glyphless.len;
1377 if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_ACRONYM)
1379 if (len > 0
1380 && CHAR_TABLE_P (Vglyphless_char_display)
1381 && (CHAR_TABLE_EXTRA_SLOTS (XCHAR_TABLE (Vglyphless_char_display))
1382 >= 1))
1384 Lisp_Object acronym
1385 = (! glyph->u.glyphless.for_no_font
1386 ? CHAR_TABLE_REF (Vglyphless_char_display,
1387 glyph->u.glyphless.ch)
1388 : XCHAR_TABLE (Vglyphless_char_display)->extras[0]);
1389 if (STRINGP (acronym))
1390 str = (char *) SDATA (acronym);
1393 else if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_HEX_CODE)
1395 sprintf ((char *) buf, "%0*X",
1396 glyph->u.glyphless.ch < 0x10000 ? 4 : 6,
1397 glyph->u.glyphless.ch);
1398 str = buf;
1401 if (str)
1403 int upper_len = (len + 1) / 2;
1404 unsigned code;
1406 /* It is assured that all LEN characters in STR is ASCII. */
1407 for (j = 0; j < len; j++)
1409 code = s->font->driver->encode_char (s->font, str[j]);
1410 STORE_XCHAR2B (char2b + j, code >> 8, code & 0xFF);
1412 s->font->driver->draw (s, 0, upper_len,
1413 x + glyph->slice.glyphless.upper_xoff,
1414 s->ybase + glyph->slice.glyphless.upper_yoff,
1416 s->font->driver->draw (s, upper_len, len,
1417 x + glyph->slice.glyphless.lower_xoff,
1418 s->ybase + glyph->slice.glyphless.lower_yoff,
1421 if (glyph->u.glyphless.method != GLYPHLESS_DISPLAY_THIN_SPACE)
1422 XDrawRectangle (s->display, s->window, s->gc,
1423 x, s->ybase - glyph->ascent,
1424 glyph->pixel_width - 1,
1425 glyph->ascent + glyph->descent - 1);
1426 x += glyph->pixel_width;
1430 #ifdef USE_X_TOOLKIT
1432 static struct frame *x_frame_of_widget (Widget);
1433 static Boolean cvt_string_to_pixel (Display *, XrmValue *, Cardinal *,
1434 XrmValue *, XrmValue *, XtPointer *);
1435 static void cvt_pixel_dtor (XtAppContext, XrmValue *, XtPointer,
1436 XrmValue *, Cardinal *);
1439 /* Return the frame on which widget WIDGET is used.. Abort if frame
1440 cannot be determined. */
1442 static struct frame *
1443 x_frame_of_widget (Widget widget)
1445 struct x_display_info *dpyinfo;
1446 Lisp_Object tail;
1447 struct frame *f;
1449 dpyinfo = x_display_info_for_display (XtDisplay (widget));
1451 /* Find the top-level shell of the widget. Note that this function
1452 can be called when the widget is not yet realized, so XtWindow
1453 (widget) == 0. That's the reason we can't simply use
1454 x_any_window_to_frame. */
1455 while (!XtIsTopLevelShell (widget))
1456 widget = XtParent (widget);
1458 /* Look for a frame with that top-level widget. Allocate the color
1459 on that frame to get the right gamma correction value. */
1460 for (tail = Vframe_list; CONSP (tail); tail = XCDR (tail))
1461 if (FRAMEP (XCAR (tail))
1462 && (f = XFRAME (XCAR (tail)),
1463 (FRAME_X_P (f)
1464 && f->output_data.nothing != 1
1465 && FRAME_X_DISPLAY_INFO (f) == dpyinfo))
1466 && f->output_data.x->widget == widget)
1467 return f;
1469 abort ();
1473 /* Allocate the color COLOR->pixel on the screen and display of
1474 widget WIDGET in colormap CMAP. If an exact match cannot be
1475 allocated, try the nearest color available. Value is non-zero
1476 if successful. This is called from lwlib. */
1479 x_alloc_nearest_color_for_widget (Widget widget, Colormap cmap, XColor *color)
1481 struct frame *f = x_frame_of_widget (widget);
1482 return x_alloc_nearest_color (f, cmap, color);
1486 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
1487 or DELTA. Try a color with RGB values multiplied by FACTOR first.
1488 If this produces the same color as PIXEL, try a color where all RGB
1489 values have DELTA added. Return the allocated color in *PIXEL.
1490 DISPLAY is the X display, CMAP is the colormap to operate on.
1491 Value is non-zero if successful. */
1494 x_alloc_lighter_color_for_widget (Widget widget, Display *display, Colormap cmap,
1495 unsigned long *pixel, double factor, int delta)
1497 struct frame *f = x_frame_of_widget (widget);
1498 return x_alloc_lighter_color (f, display, cmap, pixel, factor, delta);
1502 /* Structure specifying which arguments should be passed by Xt to
1503 cvt_string_to_pixel. We want the widget's screen and colormap. */
1505 static XtConvertArgRec cvt_string_to_pixel_args[] =
1507 {XtWidgetBaseOffset, (XtPointer) XtOffset (Widget, core.screen),
1508 sizeof (Screen *)},
1509 {XtWidgetBaseOffset, (XtPointer) XtOffset (Widget, core.colormap),
1510 sizeof (Colormap)}
1514 /* The address of this variable is returned by
1515 cvt_string_to_pixel. */
1517 static Pixel cvt_string_to_pixel_value;
1520 /* Convert a color name to a pixel color.
1522 DPY is the display we are working on.
1524 ARGS is an array of *NARGS XrmValue structures holding additional
1525 information about the widget for which the conversion takes place.
1526 The contents of this array are determined by the specification
1527 in cvt_string_to_pixel_args.
1529 FROM is a pointer to an XrmValue which points to the color name to
1530 convert. TO is an XrmValue in which to return the pixel color.
1532 CLOSURE_RET is a pointer to user-data, in which we record if
1533 we allocated the color or not.
1535 Value is True if successful, False otherwise. */
1537 static Boolean
1538 cvt_string_to_pixel (Display *dpy, XrmValue *args, Cardinal *nargs,
1539 XrmValue *from, XrmValue *to,
1540 XtPointer *closure_ret)
1542 Screen *screen;
1543 Colormap cmap;
1544 Pixel pixel;
1545 String color_name;
1546 XColor color;
1548 if (*nargs != 2)
1550 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
1551 "wrongParameters", "cvt_string_to_pixel",
1552 "XtToolkitError",
1553 "Screen and colormap args required", NULL, NULL);
1554 return False;
1557 screen = *(Screen **) args[0].addr;
1558 cmap = *(Colormap *) args[1].addr;
1559 color_name = (String) from->addr;
1561 if (strcmp (color_name, XtDefaultBackground) == 0)
1563 *closure_ret = (XtPointer) False;
1564 pixel = WhitePixelOfScreen (screen);
1566 else if (strcmp (color_name, XtDefaultForeground) == 0)
1568 *closure_ret = (XtPointer) False;
1569 pixel = BlackPixelOfScreen (screen);
1571 else if (XParseColor (dpy, cmap, color_name, &color)
1572 && x_alloc_nearest_color_1 (dpy, cmap, &color))
1574 pixel = color.pixel;
1575 *closure_ret = (XtPointer) True;
1577 else
1579 String params[1];
1580 Cardinal nparams = 1;
1582 params[0] = color_name;
1583 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
1584 "badValue", "cvt_string_to_pixel",
1585 "XtToolkitError", "Invalid color `%s'",
1586 params, &nparams);
1587 return False;
1590 if (to->addr != NULL)
1592 if (to->size < sizeof (Pixel))
1594 to->size = sizeof (Pixel);
1595 return False;
1598 *(Pixel *) to->addr = pixel;
1600 else
1602 cvt_string_to_pixel_value = pixel;
1603 to->addr = (XtPointer) &cvt_string_to_pixel_value;
1606 to->size = sizeof (Pixel);
1607 return True;
1611 /* Free a pixel color which was previously allocated via
1612 cvt_string_to_pixel. This is registered as the destructor
1613 for this type of resource via XtSetTypeConverter.
1615 APP is the application context in which we work.
1617 TO is a pointer to an XrmValue holding the color to free.
1618 CLOSURE is the value we stored in CLOSURE_RET for this color
1619 in cvt_string_to_pixel.
1621 ARGS and NARGS are like for cvt_string_to_pixel. */
1623 static void
1624 cvt_pixel_dtor (XtAppContext app, XrmValuePtr to, XtPointer closure, XrmValuePtr args,
1625 Cardinal *nargs)
1627 if (*nargs != 2)
1629 XtAppWarningMsg (app, "wrongParameters", "cvt_pixel_dtor",
1630 "XtToolkitError",
1631 "Screen and colormap arguments required",
1632 NULL, NULL);
1634 else if (closure != NULL)
1636 /* We did allocate the pixel, so free it. */
1637 Screen *screen = *(Screen **) args[0].addr;
1638 Colormap cmap = *(Colormap *) args[1].addr;
1639 x_free_dpy_colors (DisplayOfScreen (screen), screen, cmap,
1640 (Pixel *) to->addr, 1);
1645 #endif /* USE_X_TOOLKIT */
1648 /* Value is an array of XColor structures for the contents of the
1649 color map of display DPY. Set *NCELLS to the size of the array.
1650 Note that this probably shouldn't be called for large color maps,
1651 say a 24-bit TrueColor map. */
1653 static const XColor *
1654 x_color_cells (Display *dpy, int *ncells)
1656 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
1658 if (dpyinfo->color_cells == NULL)
1660 Screen *screen = dpyinfo->screen;
1661 int i;
1663 dpyinfo->ncolor_cells
1664 = XDisplayCells (dpy, XScreenNumberOfScreen (screen));
1665 dpyinfo->color_cells
1666 = (XColor *) xmalloc (dpyinfo->ncolor_cells
1667 * sizeof *dpyinfo->color_cells);
1669 for (i = 0; i < dpyinfo->ncolor_cells; ++i)
1670 dpyinfo->color_cells[i].pixel = i;
1672 XQueryColors (dpy, dpyinfo->cmap,
1673 dpyinfo->color_cells, dpyinfo->ncolor_cells);
1676 *ncells = dpyinfo->ncolor_cells;
1677 return dpyinfo->color_cells;
1681 /* On frame F, translate pixel colors to RGB values for the NCOLORS
1682 colors in COLORS. Use cached information, if available. */
1684 void
1685 x_query_colors (struct frame *f, XColor *colors, int ncolors)
1687 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
1689 if (dpyinfo->color_cells)
1691 int i;
1692 for (i = 0; i < ncolors; ++i)
1694 unsigned long pixel = colors[i].pixel;
1695 xassert (pixel < dpyinfo->ncolor_cells);
1696 xassert (dpyinfo->color_cells[pixel].pixel == pixel);
1697 colors[i] = dpyinfo->color_cells[pixel];
1700 else
1701 XQueryColors (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), colors, ncolors);
1705 /* On frame F, translate pixel color to RGB values for the color in
1706 COLOR. Use cached information, if available. */
1708 void
1709 x_query_color (struct frame *f, XColor *color)
1711 x_query_colors (f, color, 1);
1715 /* Allocate the color COLOR->pixel on DISPLAY, colormap CMAP. If an
1716 exact match can't be allocated, try the nearest color available.
1717 Value is non-zero if successful. Set *COLOR to the color
1718 allocated. */
1720 static int
1721 x_alloc_nearest_color_1 (Display *dpy, Colormap cmap, XColor *color)
1723 int rc;
1725 rc = XAllocColor (dpy, cmap, color);
1726 if (rc == 0)
1728 /* If we got to this point, the colormap is full, so we're going
1729 to try to get the next closest color. The algorithm used is
1730 a least-squares matching, which is what X uses for closest
1731 color matching with StaticColor visuals. */
1732 int nearest, i;
1733 unsigned long nearest_delta = ~0;
1734 int ncells;
1735 const XColor *cells = x_color_cells (dpy, &ncells);
1737 for (nearest = i = 0; i < ncells; ++i)
1739 long dred = (color->red >> 8) - (cells[i].red >> 8);
1740 long dgreen = (color->green >> 8) - (cells[i].green >> 8);
1741 long dblue = (color->blue >> 8) - (cells[i].blue >> 8);
1742 unsigned long delta = dred * dred + dgreen * dgreen + dblue * dblue;
1744 if (delta < nearest_delta)
1746 nearest = i;
1747 nearest_delta = delta;
1751 color->red = cells[nearest].red;
1752 color->green = cells[nearest].green;
1753 color->blue = cells[nearest].blue;
1754 rc = XAllocColor (dpy, cmap, color);
1756 else
1758 /* If allocation succeeded, and the allocated pixel color is not
1759 equal to a cached pixel color recorded earlier, there was a
1760 change in the colormap, so clear the color cache. */
1761 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
1762 XColor *cached_color;
1764 if (dpyinfo->color_cells
1765 && (cached_color = &dpyinfo->color_cells[color->pixel],
1766 (cached_color->red != color->red
1767 || cached_color->blue != color->blue
1768 || cached_color->green != color->green)))
1770 xfree (dpyinfo->color_cells);
1771 dpyinfo->color_cells = NULL;
1772 dpyinfo->ncolor_cells = 0;
1776 #ifdef DEBUG_X_COLORS
1777 if (rc)
1778 register_color (color->pixel);
1779 #endif /* DEBUG_X_COLORS */
1781 return rc;
1785 /* Allocate the color COLOR->pixel on frame F, colormap CMAP. If an
1786 exact match can't be allocated, try the nearest color available.
1787 Value is non-zero if successful. Set *COLOR to the color
1788 allocated. */
1791 x_alloc_nearest_color (struct frame *f, Colormap cmap, XColor *color)
1793 gamma_correct (f, color);
1794 return x_alloc_nearest_color_1 (FRAME_X_DISPLAY (f), cmap, color);
1798 /* Allocate color PIXEL on frame F. PIXEL must already be allocated.
1799 It's necessary to do this instead of just using PIXEL directly to
1800 get color reference counts right. */
1802 unsigned long
1803 x_copy_color (struct frame *f, long unsigned int pixel)
1805 XColor color;
1807 color.pixel = pixel;
1808 BLOCK_INPUT;
1809 x_query_color (f, &color);
1810 XAllocColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &color);
1811 UNBLOCK_INPUT;
1812 #ifdef DEBUG_X_COLORS
1813 register_color (pixel);
1814 #endif
1815 return color.pixel;
1819 /* Allocate color PIXEL on display DPY. PIXEL must already be allocated.
1820 It's necessary to do this instead of just using PIXEL directly to
1821 get color reference counts right. */
1823 unsigned long
1824 x_copy_dpy_color (Display *dpy, Colormap cmap, long unsigned int pixel)
1826 XColor color;
1828 color.pixel = pixel;
1829 BLOCK_INPUT;
1830 XQueryColor (dpy, cmap, &color);
1831 XAllocColor (dpy, cmap, &color);
1832 UNBLOCK_INPUT;
1833 #ifdef DEBUG_X_COLORS
1834 register_color (pixel);
1835 #endif
1836 return color.pixel;
1840 /* Brightness beyond which a color won't have its highlight brightness
1841 boosted.
1843 Nominally, highlight colors for `3d' faces are calculated by
1844 brightening an object's color by a constant scale factor, but this
1845 doesn't yield good results for dark colors, so for colors who's
1846 brightness is less than this value (on a scale of 0-65535) have an
1847 use an additional additive factor.
1849 The value here is set so that the default menu-bar/mode-line color
1850 (grey75) will not have its highlights changed at all. */
1851 #define HIGHLIGHT_COLOR_DARK_BOOST_LIMIT 48000
1854 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
1855 or DELTA. Try a color with RGB values multiplied by FACTOR first.
1856 If this produces the same color as PIXEL, try a color where all RGB
1857 values have DELTA added. Return the allocated color in *PIXEL.
1858 DISPLAY is the X display, CMAP is the colormap to operate on.
1859 Value is non-zero if successful. */
1861 static int
1862 x_alloc_lighter_color (struct frame *f, Display *display, Colormap cmap, long unsigned int *pixel, double factor, int delta)
1864 XColor color, new;
1865 long bright;
1866 int success_p;
1868 /* Get RGB color values. */
1869 color.pixel = *pixel;
1870 x_query_color (f, &color);
1872 /* Change RGB values by specified FACTOR. Avoid overflow! */
1873 xassert (factor >= 0);
1874 new.red = min (0xffff, factor * color.red);
1875 new.green = min (0xffff, factor * color.green);
1876 new.blue = min (0xffff, factor * color.blue);
1878 /* Calculate brightness of COLOR. */
1879 bright = (2 * color.red + 3 * color.green + color.blue) / 6;
1881 /* We only boost colors that are darker than
1882 HIGHLIGHT_COLOR_DARK_BOOST_LIMIT. */
1883 if (bright < HIGHLIGHT_COLOR_DARK_BOOST_LIMIT)
1884 /* Make an additive adjustment to NEW, because it's dark enough so
1885 that scaling by FACTOR alone isn't enough. */
1887 /* How far below the limit this color is (0 - 1, 1 being darker). */
1888 double dimness = 1 - (double)bright / HIGHLIGHT_COLOR_DARK_BOOST_LIMIT;
1889 /* The additive adjustment. */
1890 int min_delta = delta * dimness * factor / 2;
1892 if (factor < 1)
1894 new.red = max (0, new.red - min_delta);
1895 new.green = max (0, new.green - min_delta);
1896 new.blue = max (0, new.blue - min_delta);
1898 else
1900 new.red = min (0xffff, min_delta + new.red);
1901 new.green = min (0xffff, min_delta + new.green);
1902 new.blue = min (0xffff, min_delta + new.blue);
1906 /* Try to allocate the color. */
1907 success_p = x_alloc_nearest_color (f, cmap, &new);
1908 if (success_p)
1910 if (new.pixel == *pixel)
1912 /* If we end up with the same color as before, try adding
1913 delta to the RGB values. */
1914 x_free_colors (f, &new.pixel, 1);
1916 new.red = min (0xffff, delta + color.red);
1917 new.green = min (0xffff, delta + color.green);
1918 new.blue = min (0xffff, delta + color.blue);
1919 success_p = x_alloc_nearest_color (f, cmap, &new);
1921 else
1922 success_p = 1;
1923 *pixel = new.pixel;
1926 return success_p;
1930 /* Set up the foreground color for drawing relief lines of glyph
1931 string S. RELIEF is a pointer to a struct relief containing the GC
1932 with which lines will be drawn. Use a color that is FACTOR or
1933 DELTA lighter or darker than the relief's background which is found
1934 in S->f->output_data.x->relief_background. If such a color cannot
1935 be allocated, use DEFAULT_PIXEL, instead. */
1937 static void
1938 x_setup_relief_color (struct frame *f, struct relief *relief, double factor, int delta, long unsigned int default_pixel)
1940 XGCValues xgcv;
1941 struct x_output *di = f->output_data.x;
1942 unsigned long mask = GCForeground | GCLineWidth | GCGraphicsExposures;
1943 unsigned long pixel;
1944 unsigned long background = di->relief_background;
1945 Colormap cmap = FRAME_X_COLORMAP (f);
1946 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
1947 Display *dpy = FRAME_X_DISPLAY (f);
1949 xgcv.graphics_exposures = False;
1950 xgcv.line_width = 1;
1952 /* Free previously allocated color. The color cell will be reused
1953 when it has been freed as many times as it was allocated, so this
1954 doesn't affect faces using the same colors. */
1955 if (relief->gc
1956 && relief->allocated_p)
1958 x_free_colors (f, &relief->pixel, 1);
1959 relief->allocated_p = 0;
1962 /* Allocate new color. */
1963 xgcv.foreground = default_pixel;
1964 pixel = background;
1965 if (dpyinfo->n_planes != 1
1966 && x_alloc_lighter_color (f, dpy, cmap, &pixel, factor, delta))
1968 relief->allocated_p = 1;
1969 xgcv.foreground = relief->pixel = pixel;
1972 if (relief->gc == 0)
1974 xgcv.stipple = dpyinfo->gray;
1975 mask |= GCStipple;
1976 relief->gc = XCreateGC (dpy, FRAME_X_WINDOW (f), mask, &xgcv);
1978 else
1979 XChangeGC (dpy, relief->gc, mask, &xgcv);
1983 /* Set up colors for the relief lines around glyph string S. */
1985 static void
1986 x_setup_relief_colors (struct glyph_string *s)
1988 struct x_output *di = s->f->output_data.x;
1989 unsigned long color;
1991 if (s->face->use_box_color_for_shadows_p)
1992 color = s->face->box_color;
1993 else if (s->first_glyph->type == IMAGE_GLYPH
1994 && s->img->pixmap
1995 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
1996 color = IMAGE_BACKGROUND (s->img, s->f, 0);
1997 else
1999 XGCValues xgcv;
2001 /* Get the background color of the face. */
2002 XGetGCValues (s->display, s->gc, GCBackground, &xgcv);
2003 color = xgcv.background;
2006 if (di->white_relief.gc == 0
2007 || color != di->relief_background)
2009 di->relief_background = color;
2010 x_setup_relief_color (s->f, &di->white_relief, 1.2, 0x8000,
2011 WHITE_PIX_DEFAULT (s->f));
2012 x_setup_relief_color (s->f, &di->black_relief, 0.6, 0x4000,
2013 BLACK_PIX_DEFAULT (s->f));
2018 /* Draw a relief on frame F inside the rectangle given by LEFT_X,
2019 TOP_Y, RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the relief
2020 to draw, it must be >= 0. RAISED_P non-zero means draw a raised
2021 relief. LEFT_P non-zero means draw a relief on the left side of
2022 the rectangle. RIGHT_P non-zero means draw a relief on the right
2023 side of the rectangle. CLIP_RECT is the clipping rectangle to use
2024 when drawing. */
2026 static void
2027 x_draw_relief_rect (struct frame *f,
2028 int left_x, int top_y, int right_x, int bottom_y, int width,
2029 int raised_p, int top_p, int bot_p, int left_p, int right_p,
2030 XRectangle *clip_rect)
2032 Display *dpy = FRAME_X_DISPLAY (f);
2033 Window window = FRAME_X_WINDOW (f);
2034 int i;
2035 GC gc;
2037 if (raised_p)
2038 gc = f->output_data.x->white_relief.gc;
2039 else
2040 gc = f->output_data.x->black_relief.gc;
2041 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
2043 /* This code is more complicated than it has to be, because of two
2044 minor hacks to make the boxes look nicer: (i) if width > 1, draw
2045 the outermost line using the black relief. (ii) Omit the four
2046 corner pixels. */
2048 /* Top. */
2049 if (top_p)
2051 if (width == 1)
2052 XDrawLine (dpy, window, gc,
2053 left_x + (left_p ? 1 : 0), top_y,
2054 right_x + (right_p ? 0 : 1), top_y);
2056 for (i = 1; i < width; ++i)
2057 XDrawLine (dpy, window, gc,
2058 left_x + i * left_p, top_y + i,
2059 right_x + 1 - i * right_p, top_y + i);
2062 /* Left. */
2063 if (left_p)
2065 if (width == 1)
2066 XDrawLine (dpy, window, gc, left_x, top_y + 1, left_x, bottom_y);
2068 XClearArea (dpy, window, left_x, top_y, 1, 1, False);
2069 XClearArea (dpy, window, left_x, bottom_y, 1, 1, False);
2071 for (i = (width > 1 ? 1 : 0); i < width; ++i)
2072 XDrawLine (dpy, window, gc,
2073 left_x + i, top_y + i, left_x + i, bottom_y - i + 1);
2076 XSetClipMask (dpy, gc, None);
2077 if (raised_p)
2078 gc = f->output_data.x->black_relief.gc;
2079 else
2080 gc = f->output_data.x->white_relief.gc;
2081 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
2083 if (width > 1)
2085 /* Outermost top line. */
2086 if (top_p)
2087 XDrawLine (dpy, window, gc,
2088 left_x + (left_p ? 1 : 0), top_y,
2089 right_x + (right_p ? 0 : 1), top_y);
2091 /* Outermost left line. */
2092 if (left_p)
2093 XDrawLine (dpy, window, gc, left_x, top_y + 1, left_x, bottom_y);
2096 /* Bottom. */
2097 if (bot_p)
2099 XDrawLine (dpy, window, gc,
2100 left_x + (left_p ? 1 : 0), bottom_y,
2101 right_x + (right_p ? 0 : 1), bottom_y);
2102 for (i = 1; i < width; ++i)
2103 XDrawLine (dpy, window, gc,
2104 left_x + i * left_p, bottom_y - i,
2105 right_x + 1 - i * right_p, bottom_y - i);
2108 /* Right. */
2109 if (right_p)
2111 XClearArea (dpy, window, right_x, top_y, 1, 1, False);
2112 XClearArea (dpy, window, right_x, bottom_y, 1, 1, False);
2113 for (i = 0; i < width; ++i)
2114 XDrawLine (dpy, window, gc,
2115 right_x - i, top_y + i + 1, right_x - i, bottom_y - i);
2118 XSetClipMask (dpy, gc, None);
2122 /* Draw a box on frame F inside the rectangle given by LEFT_X, TOP_Y,
2123 RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the lines to
2124 draw, it must be >= 0. LEFT_P non-zero means draw a line on the
2125 left side of the rectangle. RIGHT_P non-zero means draw a line
2126 on the right side of the rectangle. CLIP_RECT is the clipping
2127 rectangle to use when drawing. */
2129 static void
2130 x_draw_box_rect (struct glyph_string *s,
2131 int left_x, int top_y, int right_x, int bottom_y, int width,
2132 int left_p, int right_p, XRectangle *clip_rect)
2134 XGCValues xgcv;
2136 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2137 XSetForeground (s->display, s->gc, s->face->box_color);
2138 XSetClipRectangles (s->display, s->gc, 0, 0, clip_rect, 1, Unsorted);
2140 /* Top. */
2141 XFillRectangle (s->display, s->window, s->gc,
2142 left_x, top_y, right_x - left_x + 1, width);
2144 /* Left. */
2145 if (left_p)
2146 XFillRectangle (s->display, s->window, s->gc,
2147 left_x, top_y, width, bottom_y - top_y + 1);
2149 /* Bottom. */
2150 XFillRectangle (s->display, s->window, s->gc,
2151 left_x, bottom_y - width + 1, right_x - left_x + 1, width);
2153 /* Right. */
2154 if (right_p)
2155 XFillRectangle (s->display, s->window, s->gc,
2156 right_x - width + 1, top_y, width, bottom_y - top_y + 1);
2158 XSetForeground (s->display, s->gc, xgcv.foreground);
2159 XSetClipMask (s->display, s->gc, None);
2163 /* Draw a box around glyph string S. */
2165 static void
2166 x_draw_glyph_string_box (struct glyph_string *s)
2168 int width, left_x, right_x, top_y, bottom_y, last_x, raised_p;
2169 int left_p, right_p;
2170 struct glyph *last_glyph;
2171 XRectangle clip_rect;
2173 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2174 ? WINDOW_RIGHT_EDGE_X (s->w)
2175 : window_box_right (s->w, s->area));
2177 /* The glyph that may have a right box line. */
2178 last_glyph = (s->cmp || s->img
2179 ? s->first_glyph
2180 : s->first_glyph + s->nchars - 1);
2182 width = eabs (s->face->box_line_width);
2183 raised_p = s->face->box == FACE_RAISED_BOX;
2184 left_x = s->x;
2185 right_x = (s->row->full_width_p && s->extends_to_end_of_line_p
2186 ? last_x - 1
2187 : min (last_x, s->x + s->background_width) - 1);
2188 top_y = s->y;
2189 bottom_y = top_y + s->height - 1;
2191 left_p = (s->first_glyph->left_box_line_p
2192 || (s->hl == DRAW_MOUSE_FACE
2193 && (s->prev == NULL
2194 || s->prev->hl != s->hl)));
2195 right_p = (last_glyph->right_box_line_p
2196 || (s->hl == DRAW_MOUSE_FACE
2197 && (s->next == NULL
2198 || s->next->hl != s->hl)));
2200 get_glyph_string_clip_rect (s, &clip_rect);
2202 if (s->face->box == FACE_SIMPLE_BOX)
2203 x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
2204 left_p, right_p, &clip_rect);
2205 else
2207 x_setup_relief_colors (s);
2208 x_draw_relief_rect (s->f, left_x, top_y, right_x, bottom_y,
2209 width, raised_p, 1, 1, left_p, right_p, &clip_rect);
2214 /* Draw foreground of image glyph string S. */
2216 static void
2217 x_draw_image_foreground (struct glyph_string *s)
2219 int x = s->x;
2220 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2222 /* If first glyph of S has a left box line, start drawing it to the
2223 right of that line. */
2224 if (s->face->box != FACE_NO_BOX
2225 && s->first_glyph->left_box_line_p
2226 && s->slice.x == 0)
2227 x += eabs (s->face->box_line_width);
2229 /* If there is a margin around the image, adjust x- and y-position
2230 by that margin. */
2231 if (s->slice.x == 0)
2232 x += s->img->hmargin;
2233 if (s->slice.y == 0)
2234 y += s->img->vmargin;
2236 if (s->img->pixmap)
2238 if (s->img->mask)
2240 /* We can't set both a clip mask and use XSetClipRectangles
2241 because the latter also sets a clip mask. We also can't
2242 trust on the shape extension to be available
2243 (XShapeCombineRegion). So, compute the rectangle to draw
2244 manually. */
2245 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
2246 | GCFunction);
2247 XGCValues xgcv;
2248 XRectangle clip_rect, image_rect, r;
2250 xgcv.clip_mask = s->img->mask;
2251 xgcv.clip_x_origin = x;
2252 xgcv.clip_y_origin = y;
2253 xgcv.function = GXcopy;
2254 XChangeGC (s->display, s->gc, mask, &xgcv);
2256 get_glyph_string_clip_rect (s, &clip_rect);
2257 image_rect.x = x;
2258 image_rect.y = y;
2259 image_rect.width = s->slice.width;
2260 image_rect.height = s->slice.height;
2261 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
2262 XCopyArea (s->display, s->img->pixmap, s->window, s->gc,
2263 s->slice.x + r.x - x, s->slice.y + r.y - y,
2264 r.width, r.height, r.x, r.y);
2266 else
2268 XRectangle clip_rect, image_rect, r;
2270 get_glyph_string_clip_rect (s, &clip_rect);
2271 image_rect.x = x;
2272 image_rect.y = y;
2273 image_rect.width = s->slice.width;
2274 image_rect.height = s->slice.height;
2275 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
2276 XCopyArea (s->display, s->img->pixmap, s->window, s->gc,
2277 s->slice.x + r.x - x, s->slice.y + r.y - y,
2278 r.width, r.height, r.x, r.y);
2280 /* When the image has a mask, we can expect that at
2281 least part of a mouse highlight or a block cursor will
2282 be visible. If the image doesn't have a mask, make
2283 a block cursor visible by drawing a rectangle around
2284 the image. I believe it's looking better if we do
2285 nothing here for mouse-face. */
2286 if (s->hl == DRAW_CURSOR)
2288 int r = s->img->relief;
2289 if (r < 0) r = -r;
2290 XDrawRectangle (s->display, s->window, s->gc,
2291 x - r, y - r,
2292 s->slice.width + r*2 - 1,
2293 s->slice.height + r*2 - 1);
2297 else
2298 /* Draw a rectangle if image could not be loaded. */
2299 XDrawRectangle (s->display, s->window, s->gc, x, y,
2300 s->slice.width - 1, s->slice.height - 1);
2304 /* Draw a relief around the image glyph string S. */
2306 static void
2307 x_draw_image_relief (struct glyph_string *s)
2309 int x0, y0, x1, y1, thick, raised_p, extra;
2310 XRectangle r;
2311 int x = s->x;
2312 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2314 /* If first glyph of S has a left box line, start drawing it to the
2315 right of that line. */
2316 if (s->face->box != FACE_NO_BOX
2317 && s->first_glyph->left_box_line_p
2318 && s->slice.x == 0)
2319 x += eabs (s->face->box_line_width);
2321 /* If there is a margin around the image, adjust x- and y-position
2322 by that margin. */
2323 if (s->slice.x == 0)
2324 x += s->img->hmargin;
2325 if (s->slice.y == 0)
2326 y += s->img->vmargin;
2328 if (s->hl == DRAW_IMAGE_SUNKEN
2329 || s->hl == DRAW_IMAGE_RAISED)
2331 thick = tool_bar_button_relief >= 0 ? tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
2332 raised_p = s->hl == DRAW_IMAGE_RAISED;
2334 else
2336 thick = eabs (s->img->relief);
2337 raised_p = s->img->relief > 0;
2340 extra = s->face->id == TOOL_BAR_FACE_ID
2341 ? XINT (Vtool_bar_button_margin) : 0;
2343 x0 = x - thick - extra;
2344 y0 = y - thick - extra;
2345 x1 = x + s->slice.width + thick - 1 + extra;
2346 y1 = y + s->slice.height + thick - 1 + extra;
2348 x_setup_relief_colors (s);
2349 get_glyph_string_clip_rect (s, &r);
2350 x_draw_relief_rect (s->f, x0, y0, x1, y1, thick, raised_p,
2351 s->slice.y == 0,
2352 s->slice.y + s->slice.height == s->img->height,
2353 s->slice.x == 0,
2354 s->slice.x + s->slice.width == s->img->width,
2355 &r);
2359 /* Draw the foreground of image glyph string S to PIXMAP. */
2361 static void
2362 x_draw_image_foreground_1 (struct glyph_string *s, Pixmap pixmap)
2364 int x = 0;
2365 int y = s->ybase - s->y - image_ascent (s->img, s->face, &s->slice);
2367 /* If first glyph of S has a left box line, start drawing it to the
2368 right of that line. */
2369 if (s->face->box != FACE_NO_BOX
2370 && s->first_glyph->left_box_line_p
2371 && s->slice.x == 0)
2372 x += eabs (s->face->box_line_width);
2374 /* If there is a margin around the image, adjust x- and y-position
2375 by that margin. */
2376 if (s->slice.x == 0)
2377 x += s->img->hmargin;
2378 if (s->slice.y == 0)
2379 y += s->img->vmargin;
2381 if (s->img->pixmap)
2383 if (s->img->mask)
2385 /* We can't set both a clip mask and use XSetClipRectangles
2386 because the latter also sets a clip mask. We also can't
2387 trust on the shape extension to be available
2388 (XShapeCombineRegion). So, compute the rectangle to draw
2389 manually. */
2390 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
2391 | GCFunction);
2392 XGCValues xgcv;
2394 xgcv.clip_mask = s->img->mask;
2395 xgcv.clip_x_origin = x - s->slice.x;
2396 xgcv.clip_y_origin = y - s->slice.y;
2397 xgcv.function = GXcopy;
2398 XChangeGC (s->display, s->gc, mask, &xgcv);
2400 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
2401 s->slice.x, s->slice.y,
2402 s->slice.width, s->slice.height, x, y);
2403 XSetClipMask (s->display, s->gc, None);
2405 else
2407 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
2408 s->slice.x, s->slice.y,
2409 s->slice.width, s->slice.height, x, y);
2411 /* When the image has a mask, we can expect that at
2412 least part of a mouse highlight or a block cursor will
2413 be visible. If the image doesn't have a mask, make
2414 a block cursor visible by drawing a rectangle around
2415 the image. I believe it's looking better if we do
2416 nothing here for mouse-face. */
2417 if (s->hl == DRAW_CURSOR)
2419 int r = s->img->relief;
2420 if (r < 0) r = -r;
2421 XDrawRectangle (s->display, s->window, s->gc, x - r, y - r,
2422 s->slice.width + r*2 - 1,
2423 s->slice.height + r*2 - 1);
2427 else
2428 /* Draw a rectangle if image could not be loaded. */
2429 XDrawRectangle (s->display, pixmap, s->gc, x, y,
2430 s->slice.width - 1, s->slice.height - 1);
2434 /* Draw part of the background of glyph string S. X, Y, W, and H
2435 give the rectangle to draw. */
2437 static void
2438 x_draw_glyph_string_bg_rect (struct glyph_string *s, int x, int y, int w, int h)
2440 if (s->stippled_p)
2442 /* Fill background with a stipple pattern. */
2443 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
2444 XFillRectangle (s->display, s->window, s->gc, x, y, w, h);
2445 XSetFillStyle (s->display, s->gc, FillSolid);
2447 else
2448 x_clear_glyph_string_rect (s, x, y, w, h);
2452 /* Draw image glyph string S.
2454 s->y
2455 s->x +-------------------------
2456 | s->face->box
2458 | +-------------------------
2459 | | s->img->margin
2461 | | +-------------------
2462 | | | the image
2466 static void
2467 x_draw_image_glyph_string (struct glyph_string *s)
2469 int box_line_hwidth = eabs (s->face->box_line_width);
2470 int box_line_vwidth = max (s->face->box_line_width, 0);
2471 int height;
2472 Pixmap pixmap = None;
2474 height = s->height;
2475 if (s->slice.y == 0)
2476 height -= box_line_vwidth;
2477 if (s->slice.y + s->slice.height >= s->img->height)
2478 height -= box_line_vwidth;
2480 /* Fill background with face under the image. Do it only if row is
2481 taller than image or if image has a clip mask to reduce
2482 flickering. */
2483 s->stippled_p = s->face->stipple != 0;
2484 if (height > s->slice.height
2485 || s->img->hmargin
2486 || s->img->vmargin
2487 || s->img->mask
2488 || s->img->pixmap == 0
2489 || s->width != s->background_width)
2491 if (s->img->mask)
2493 /* Create a pixmap as large as the glyph string. Fill it
2494 with the background color. Copy the image to it, using
2495 its mask. Copy the temporary pixmap to the display. */
2496 Screen *screen = FRAME_X_SCREEN (s->f);
2497 int depth = DefaultDepthOfScreen (screen);
2499 /* Create a pixmap as large as the glyph string. */
2500 pixmap = XCreatePixmap (s->display, s->window,
2501 s->background_width,
2502 s->height, depth);
2504 /* Don't clip in the following because we're working on the
2505 pixmap. */
2506 XSetClipMask (s->display, s->gc, None);
2508 /* Fill the pixmap with the background color/stipple. */
2509 if (s->stippled_p)
2511 /* Fill background with a stipple pattern. */
2512 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
2513 XSetTSOrigin (s->display, s->gc, - s->x, - s->y);
2514 XFillRectangle (s->display, pixmap, s->gc,
2515 0, 0, s->background_width, s->height);
2516 XSetFillStyle (s->display, s->gc, FillSolid);
2517 XSetTSOrigin (s->display, s->gc, 0, 0);
2519 else
2521 XGCValues xgcv;
2522 XGetGCValues (s->display, s->gc, GCForeground | GCBackground,
2523 &xgcv);
2524 XSetForeground (s->display, s->gc, xgcv.background);
2525 XFillRectangle (s->display, pixmap, s->gc,
2526 0, 0, s->background_width, s->height);
2527 XSetForeground (s->display, s->gc, xgcv.foreground);
2530 else
2532 int x = s->x;
2533 int y = s->y;
2535 if (s->first_glyph->left_box_line_p
2536 && s->slice.x == 0)
2537 x += box_line_hwidth;
2539 if (s->slice.y == 0)
2540 y += box_line_vwidth;
2542 x_draw_glyph_string_bg_rect (s, x, y, s->background_width, height);
2545 s->background_filled_p = 1;
2548 /* Draw the foreground. */
2549 if (pixmap != None)
2551 x_draw_image_foreground_1 (s, pixmap);
2552 x_set_glyph_string_clipping (s);
2553 XCopyArea (s->display, pixmap, s->window, s->gc,
2554 0, 0, s->background_width, s->height, s->x, s->y);
2555 XFreePixmap (s->display, pixmap);
2557 else
2558 x_draw_image_foreground (s);
2560 /* If we must draw a relief around the image, do it. */
2561 if (s->img->relief
2562 || s->hl == DRAW_IMAGE_RAISED
2563 || s->hl == DRAW_IMAGE_SUNKEN)
2564 x_draw_image_relief (s);
2568 /* Draw stretch glyph string S. */
2570 static void
2571 x_draw_stretch_glyph_string (struct glyph_string *s)
2573 xassert (s->first_glyph->type == STRETCH_GLYPH);
2575 if (s->hl == DRAW_CURSOR
2576 && !x_stretch_cursor_p)
2578 /* If `x-stretch-cursor' is nil, don't draw a block cursor as
2579 wide as the stretch glyph. */
2580 int width, background_width = s->background_width;
2581 int x = s->x;
2583 if (!s->row->reversed_p)
2585 int left_x = window_box_left_offset (s->w, TEXT_AREA);
2587 if (x < left_x)
2589 background_width -= left_x - x;
2590 x = left_x;
2593 else
2595 /* In R2L rows, draw the cursor on the right edge of the
2596 stretch glyph. */
2597 int right_x = window_box_right_offset (s->w, TEXT_AREA);
2599 if (x + background_width > right_x)
2600 background_width -= x - right_x;
2601 x += background_width;
2603 width = min (FRAME_COLUMN_WIDTH (s->f), background_width);
2604 if (s->row->reversed_p)
2605 x -= width;
2607 /* Draw cursor. */
2608 x_draw_glyph_string_bg_rect (s, x, s->y, width, s->height);
2610 /* Clear rest using the GC of the original non-cursor face. */
2611 if (width < background_width)
2613 int y = s->y;
2614 int w = background_width - width, h = s->height;
2615 XRectangle r;
2616 GC gc;
2618 if (!s->row->reversed_p)
2619 x += width;
2620 else
2621 x = s->x;
2622 if (s->row->mouse_face_p
2623 && cursor_in_mouse_face_p (s->w))
2625 x_set_mouse_face_gc (s);
2626 gc = s->gc;
2628 else
2629 gc = s->face->gc;
2631 get_glyph_string_clip_rect (s, &r);
2632 XSetClipRectangles (s->display, gc, 0, 0, &r, 1, Unsorted);
2634 if (s->face->stipple)
2636 /* Fill background with a stipple pattern. */
2637 XSetFillStyle (s->display, gc, FillOpaqueStippled);
2638 XFillRectangle (s->display, s->window, gc, x, y, w, h);
2639 XSetFillStyle (s->display, gc, FillSolid);
2641 else
2643 XGCValues xgcv;
2644 XGetGCValues (s->display, gc, GCForeground | GCBackground, &xgcv);
2645 XSetForeground (s->display, gc, xgcv.background);
2646 XFillRectangle (s->display, s->window, gc, x, y, w, h);
2647 XSetForeground (s->display, gc, xgcv.foreground);
2651 else if (!s->background_filled_p)
2653 int background_width = s->background_width;
2654 int x = s->x, left_x = window_box_left_offset (s->w, TEXT_AREA);
2656 /* Don't draw into left margin, fringe or scrollbar area
2657 except for header line and mode line. */
2658 if (x < left_x && !s->row->mode_line_p)
2660 background_width -= left_x - x;
2661 x = left_x;
2663 if (background_width > 0)
2664 x_draw_glyph_string_bg_rect (s, x, s->y, background_width, s->height);
2667 s->background_filled_p = 1;
2671 /* Draw glyph string S. */
2673 static void
2674 x_draw_glyph_string (struct glyph_string *s)
2676 int relief_drawn_p = 0;
2678 /* If S draws into the background of its successors, draw the
2679 background of the successors first so that S can draw into it.
2680 This makes S->next use XDrawString instead of XDrawImageString. */
2681 if (s->next && s->right_overhang && !s->for_overlaps)
2683 int width;
2684 struct glyph_string *next;
2686 for (width = 0, next = s->next;
2687 next && width < s->right_overhang;
2688 width += next->width, next = next->next)
2689 if (next->first_glyph->type != IMAGE_GLYPH)
2691 x_set_glyph_string_gc (next);
2692 x_set_glyph_string_clipping (next);
2693 if (next->first_glyph->type == STRETCH_GLYPH)
2694 x_draw_stretch_glyph_string (next);
2695 else
2696 x_draw_glyph_string_background (next, 1);
2697 next->num_clips = 0;
2701 /* Set up S->gc, set clipping and draw S. */
2702 x_set_glyph_string_gc (s);
2704 /* Draw relief (if any) in advance for char/composition so that the
2705 glyph string can be drawn over it. */
2706 if (!s->for_overlaps
2707 && s->face->box != FACE_NO_BOX
2708 && (s->first_glyph->type == CHAR_GLYPH
2709 || s->first_glyph->type == COMPOSITE_GLYPH))
2712 x_set_glyph_string_clipping (s);
2713 x_draw_glyph_string_background (s, 1);
2714 x_draw_glyph_string_box (s);
2715 x_set_glyph_string_clipping (s);
2716 relief_drawn_p = 1;
2718 else if (!s->clip_head /* draw_glyphs didn't specify a clip mask. */
2719 && !s->clip_tail
2720 && ((s->prev && s->prev->hl != s->hl && s->left_overhang)
2721 || (s->next && s->next->hl != s->hl && s->right_overhang)))
2722 /* We must clip just this glyph. left_overhang part has already
2723 drawn when s->prev was drawn, and right_overhang part will be
2724 drawn later when s->next is drawn. */
2725 x_set_glyph_string_clipping_exactly (s, s);
2726 else
2727 x_set_glyph_string_clipping (s);
2729 switch (s->first_glyph->type)
2731 case IMAGE_GLYPH:
2732 x_draw_image_glyph_string (s);
2733 break;
2735 case STRETCH_GLYPH:
2736 x_draw_stretch_glyph_string (s);
2737 break;
2739 case CHAR_GLYPH:
2740 if (s->for_overlaps)
2741 s->background_filled_p = 1;
2742 else
2743 x_draw_glyph_string_background (s, 0);
2744 x_draw_glyph_string_foreground (s);
2745 break;
2747 case COMPOSITE_GLYPH:
2748 if (s->for_overlaps || (s->cmp_from > 0
2749 && ! s->first_glyph->u.cmp.automatic))
2750 s->background_filled_p = 1;
2751 else
2752 x_draw_glyph_string_background (s, 1);
2753 x_draw_composite_glyph_string_foreground (s);
2754 break;
2756 case GLYPHLESS_GLYPH:
2757 if (s->for_overlaps)
2758 s->background_filled_p = 1;
2759 else
2760 x_draw_glyph_string_background (s, 1);
2761 x_draw_glyphless_glyph_string_foreground (s);
2762 break;
2764 default:
2765 abort ();
2768 if (!s->for_overlaps)
2770 /* Draw underline. */
2771 if (s->face->underline_p)
2773 unsigned long thickness, position;
2774 int y;
2776 if (s->prev && s->prev->face->underline_p)
2778 /* We use the same underline style as the previous one. */
2779 thickness = s->prev->underline_thickness;
2780 position = s->prev->underline_position;
2782 else
2784 /* Get the underline thickness. Default is 1 pixel. */
2785 if (s->font && s->font->underline_thickness > 0)
2786 thickness = s->font->underline_thickness;
2787 else
2788 thickness = 1;
2789 if (x_underline_at_descent_line)
2790 position = (s->height - thickness) - (s->ybase - s->y);
2791 else
2793 /* Get the underline position. This is the recommended
2794 vertical offset in pixels from the baseline to the top of
2795 the underline. This is a signed value according to the
2796 specs, and its default is
2798 ROUND ((maximum descent) / 2), with
2799 ROUND(x) = floor (x + 0.5) */
2801 if (x_use_underline_position_properties
2802 && s->font && s->font->underline_position >= 0)
2803 position = s->font->underline_position;
2804 else if (s->font)
2805 position = (s->font->descent + 1) / 2;
2806 else
2807 position = underline_minimum_offset;
2809 position = max (position, underline_minimum_offset);
2811 /* Check the sanity of thickness and position. We should
2812 avoid drawing underline out of the current line area. */
2813 if (s->y + s->height <= s->ybase + position)
2814 position = (s->height - 1) - (s->ybase - s->y);
2815 if (s->y + s->height < s->ybase + position + thickness)
2816 thickness = (s->y + s->height) - (s->ybase + position);
2817 s->underline_thickness = thickness;
2818 s->underline_position = position;
2819 y = s->ybase + position;
2820 if (s->face->underline_defaulted_p)
2821 XFillRectangle (s->display, s->window, s->gc,
2822 s->x, y, s->width, thickness);
2823 else
2825 XGCValues xgcv;
2826 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2827 XSetForeground (s->display, s->gc, s->face->underline_color);
2828 XFillRectangle (s->display, s->window, s->gc,
2829 s->x, y, s->width, thickness);
2830 XSetForeground (s->display, s->gc, xgcv.foreground);
2834 /* Draw overline. */
2835 if (s->face->overline_p)
2837 unsigned long dy = 0, h = 1;
2839 if (s->face->overline_color_defaulted_p)
2840 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2841 s->width, h);
2842 else
2844 XGCValues xgcv;
2845 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2846 XSetForeground (s->display, s->gc, s->face->overline_color);
2847 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2848 s->width, h);
2849 XSetForeground (s->display, s->gc, xgcv.foreground);
2853 /* Draw strike-through. */
2854 if (s->face->strike_through_p)
2856 unsigned long h = 1;
2857 unsigned long dy = (s->height - h) / 2;
2859 if (s->face->strike_through_color_defaulted_p)
2860 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2861 s->width, h);
2862 else
2864 XGCValues xgcv;
2865 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2866 XSetForeground (s->display, s->gc, s->face->strike_through_color);
2867 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2868 s->width, h);
2869 XSetForeground (s->display, s->gc, xgcv.foreground);
2873 /* Draw relief if not yet drawn. */
2874 if (!relief_drawn_p && s->face->box != FACE_NO_BOX)
2875 x_draw_glyph_string_box (s);
2877 if (s->prev)
2879 struct glyph_string *prev;
2881 for (prev = s->prev; prev; prev = prev->prev)
2882 if (prev->hl != s->hl
2883 && prev->x + prev->width + prev->right_overhang > s->x)
2885 /* As prev was drawn while clipped to its own area, we
2886 must draw the right_overhang part using s->hl now. */
2887 enum draw_glyphs_face save = prev->hl;
2889 prev->hl = s->hl;
2890 x_set_glyph_string_gc (prev);
2891 x_set_glyph_string_clipping_exactly (s, prev);
2892 if (prev->first_glyph->type == CHAR_GLYPH)
2893 x_draw_glyph_string_foreground (prev);
2894 else
2895 x_draw_composite_glyph_string_foreground (prev);
2896 XSetClipMask (prev->display, prev->gc, None);
2897 prev->hl = save;
2898 prev->num_clips = 0;
2902 if (s->next)
2904 struct glyph_string *next;
2906 for (next = s->next; next; next = next->next)
2907 if (next->hl != s->hl
2908 && next->x - next->left_overhang < s->x + s->width)
2910 /* As next will be drawn while clipped to its own area,
2911 we must draw the left_overhang part using s->hl now. */
2912 enum draw_glyphs_face save = next->hl;
2914 next->hl = s->hl;
2915 x_set_glyph_string_gc (next);
2916 x_set_glyph_string_clipping_exactly (s, next);
2917 if (next->first_glyph->type == CHAR_GLYPH)
2918 x_draw_glyph_string_foreground (next);
2919 else
2920 x_draw_composite_glyph_string_foreground (next);
2921 XSetClipMask (next->display, next->gc, None);
2922 next->hl = save;
2923 next->num_clips = 0;
2928 /* Reset clipping. */
2929 XSetClipMask (s->display, s->gc, None);
2930 s->num_clips = 0;
2933 /* Shift display to make room for inserted glyphs. */
2935 void
2936 x_shift_glyphs_for_insert (struct frame *f, int x, int y, int width, int height, int shift_by)
2938 XCopyArea (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), FRAME_X_WINDOW (f),
2939 f->output_data.x->normal_gc,
2940 x, y, width, height,
2941 x + shift_by, y);
2944 /* Delete N glyphs at the nominal cursor position. Not implemented
2945 for X frames. */
2947 static void
2948 x_delete_glyphs (struct frame *f, register int n)
2950 abort ();
2954 /* Like XClearArea, but check that WIDTH and HEIGHT are reasonable.
2955 If they are <= 0, this is probably an error. */
2957 void
2958 x_clear_area (Display *dpy, Window window, int x, int y, int width, int height, int exposures)
2960 xassert (width > 0 && height > 0);
2961 XClearArea (dpy, window, x, y, width, height, exposures);
2965 /* Clear an entire frame. */
2967 static void
2968 x_clear_frame (struct frame *f)
2970 /* Clearing the frame will erase any cursor, so mark them all as no
2971 longer visible. */
2972 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2973 output_cursor.hpos = output_cursor.vpos = 0;
2974 output_cursor.x = -1;
2976 /* We don't set the output cursor here because there will always
2977 follow an explicit cursor_to. */
2978 BLOCK_INPUT;
2979 XClearWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
2981 /* We have to clear the scroll bars, too. If we have changed
2982 colors or something like that, then they should be notified. */
2983 x_scroll_bar_clear (f);
2985 #if defined (USE_GTK) && defined (USE_TOOLKIT_SCROLL_BARS)
2986 /* Make sure scroll bars are redrawn. As they aren't redrawn by
2987 redisplay, do it here. */
2988 if (FRAME_GTK_WIDGET (f))
2989 gtk_widget_queue_draw (FRAME_GTK_WIDGET (f));
2990 #endif
2992 XFlush (FRAME_X_DISPLAY (f));
2994 UNBLOCK_INPUT;
2999 /* Invert the middle quarter of the frame for .15 sec. */
3001 /* We use the select system call to do the waiting, so we have to make
3002 sure it's available. If it isn't, we just won't do visual bells. */
3004 #if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
3007 /* Subtract the `struct timeval' values X and Y, storing the result in
3008 *RESULT. Return 1 if the difference is negative, otherwise 0. */
3010 static int
3011 timeval_subtract (struct timeval *result, struct timeval x, struct timeval y)
3013 /* Perform the carry for the later subtraction by updating y. This
3014 is safer because on some systems the tv_sec member is unsigned. */
3015 if (x.tv_usec < y.tv_usec)
3017 int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
3018 y.tv_usec -= 1000000 * nsec;
3019 y.tv_sec += nsec;
3022 if (x.tv_usec - y.tv_usec > 1000000)
3024 int nsec = (y.tv_usec - x.tv_usec) / 1000000;
3025 y.tv_usec += 1000000 * nsec;
3026 y.tv_sec -= nsec;
3029 /* Compute the time remaining to wait. tv_usec is certainly
3030 positive. */
3031 result->tv_sec = x.tv_sec - y.tv_sec;
3032 result->tv_usec = x.tv_usec - y.tv_usec;
3034 /* Return indication of whether the result should be considered
3035 negative. */
3036 return x.tv_sec < y.tv_sec;
3039 void
3040 XTflash (struct frame *f)
3042 BLOCK_INPUT;
3045 #ifdef USE_GTK
3046 /* Use Gdk routines to draw. This way, we won't draw over scroll bars
3047 when the scroll bars and the edit widget share the same X window. */
3048 GdkWindow *window = gtk_widget_get_window (FRAME_GTK_WIDGET (f));
3049 GdkGCValues vals;
3050 GdkGC *gc;
3051 vals.foreground.pixel = (FRAME_FOREGROUND_PIXEL (f)
3052 ^ FRAME_BACKGROUND_PIXEL (f));
3053 vals.function = GDK_XOR;
3054 gc = gdk_gc_new_with_values (window,
3055 &vals, GDK_GC_FUNCTION | GDK_GC_FOREGROUND);
3056 #define XFillRectangle(d, win, gc, x, y, w, h) \
3057 gdk_draw_rectangle (window, gc, TRUE, x, y, w, h)
3058 #else
3059 GC gc;
3061 /* Create a GC that will use the GXxor function to flip foreground
3062 pixels into background pixels. */
3064 XGCValues values;
3066 values.function = GXxor;
3067 values.foreground = (FRAME_FOREGROUND_PIXEL (f)
3068 ^ FRAME_BACKGROUND_PIXEL (f));
3070 gc = XCreateGC (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3071 GCFunction | GCForeground, &values);
3073 #endif
3075 /* Get the height not including a menu bar widget. */
3076 int height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, FRAME_LINES (f));
3077 /* Height of each line to flash. */
3078 int flash_height = FRAME_LINE_HEIGHT (f);
3079 /* These will be the left and right margins of the rectangles. */
3080 int flash_left = FRAME_INTERNAL_BORDER_WIDTH (f);
3081 int flash_right = FRAME_PIXEL_WIDTH (f) - FRAME_INTERNAL_BORDER_WIDTH (f);
3083 int width;
3085 /* Don't flash the area between a scroll bar and the frame
3086 edge it is next to. */
3087 switch (FRAME_VERTICAL_SCROLL_BAR_TYPE (f))
3089 case vertical_scroll_bar_left:
3090 flash_left += VERTICAL_SCROLL_BAR_WIDTH_TRIM;
3091 break;
3093 case vertical_scroll_bar_right:
3094 flash_right -= VERTICAL_SCROLL_BAR_WIDTH_TRIM;
3095 break;
3097 default:
3098 break;
3101 width = flash_right - flash_left;
3103 /* If window is tall, flash top and bottom line. */
3104 if (height > 3 * FRAME_LINE_HEIGHT (f))
3106 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3107 flash_left,
3108 (FRAME_INTERNAL_BORDER_WIDTH (f)
3109 + FRAME_TOP_MARGIN_HEIGHT (f)),
3110 width, flash_height);
3111 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3112 flash_left,
3113 (height - flash_height
3114 - FRAME_INTERNAL_BORDER_WIDTH (f)),
3115 width, flash_height);
3118 else
3119 /* If it is short, flash it all. */
3120 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3121 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
3122 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
3124 x_flush (f);
3127 struct timeval wakeup;
3129 EMACS_GET_TIME (wakeup);
3131 /* Compute time to wait until, propagating carry from usecs. */
3132 wakeup.tv_usec += 150000;
3133 wakeup.tv_sec += (wakeup.tv_usec / 1000000);
3134 wakeup.tv_usec %= 1000000;
3136 /* Keep waiting until past the time wakeup or any input gets
3137 available. */
3138 while (! detect_input_pending ())
3140 struct timeval current;
3141 struct timeval timeout;
3143 EMACS_GET_TIME (current);
3145 /* Break if result would be negative. */
3146 if (timeval_subtract (&current, wakeup, current))
3147 break;
3149 /* How long `select' should wait. */
3150 timeout.tv_sec = 0;
3151 timeout.tv_usec = 10000;
3153 /* Try to wait that long--but we might wake up sooner. */
3154 select (0, NULL, NULL, NULL, &timeout);
3158 /* If window is tall, flash top and bottom line. */
3159 if (height > 3 * FRAME_LINE_HEIGHT (f))
3161 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3162 flash_left,
3163 (FRAME_INTERNAL_BORDER_WIDTH (f)
3164 + FRAME_TOP_MARGIN_HEIGHT (f)),
3165 width, flash_height);
3166 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3167 flash_left,
3168 (height - flash_height
3169 - FRAME_INTERNAL_BORDER_WIDTH (f)),
3170 width, flash_height);
3172 else
3173 /* If it is short, flash it all. */
3174 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3175 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
3176 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
3178 #ifdef USE_GTK
3179 g_object_unref (G_OBJECT (gc));
3180 #undef XFillRectangle
3181 #else
3182 XFreeGC (FRAME_X_DISPLAY (f), gc);
3183 #endif
3184 x_flush (f);
3188 UNBLOCK_INPUT;
3191 #endif /* defined (HAVE_TIMEVAL) && defined (HAVE_SELECT) */
3194 static void
3195 XTtoggle_invisible_pointer (FRAME_PTR f, int invisible)
3197 BLOCK_INPUT;
3198 if (invisible)
3200 if (FRAME_X_DISPLAY_INFO (f)->invisible_cursor != 0)
3201 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3202 FRAME_X_DISPLAY_INFO (f)->invisible_cursor);
3204 else
3205 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3206 f->output_data.x->current_cursor);
3207 f->pointer_invisible = invisible;
3208 UNBLOCK_INPUT;
3212 /* Make audible bell. */
3214 void
3215 XTring_bell (struct frame *f)
3217 if (FRAME_X_DISPLAY (f))
3219 #if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
3220 if (visible_bell)
3221 XTflash (f);
3222 else
3223 #endif
3225 BLOCK_INPUT;
3226 XBell (FRAME_X_DISPLAY (f), 0);
3227 XFlush (FRAME_X_DISPLAY (f));
3228 UNBLOCK_INPUT;
3234 /* Specify how many text lines, from the top of the window,
3235 should be affected by insert-lines and delete-lines operations.
3236 This, and those operations, are used only within an update
3237 that is bounded by calls to x_update_begin and x_update_end. */
3239 static void
3240 XTset_terminal_window (struct frame *f, int n)
3242 /* This function intentionally left blank. */
3247 /***********************************************************************
3248 Line Dance
3249 ***********************************************************************/
3251 /* Perform an insert-lines or delete-lines operation, inserting N
3252 lines or deleting -N lines at vertical position VPOS. */
3254 static void
3255 x_ins_del_lines (struct frame *f, int vpos, int n)
3257 abort ();
3261 /* Scroll part of the display as described by RUN. */
3263 static void
3264 x_scroll_run (struct window *w, struct run *run)
3266 struct frame *f = XFRAME (w->frame);
3267 int x, y, width, height, from_y, to_y, bottom_y;
3269 /* Get frame-relative bounding box of the text display area of W,
3270 without mode lines. Include in this box the left and right
3271 fringe of W. */
3272 window_box (w, -1, &x, &y, &width, &height);
3274 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
3275 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
3276 bottom_y = y + height;
3278 if (to_y < from_y)
3280 /* Scrolling up. Make sure we don't copy part of the mode
3281 line at the bottom. */
3282 if (from_y + run->height > bottom_y)
3283 height = bottom_y - from_y;
3284 else
3285 height = run->height;
3287 else
3289 /* Scolling down. Make sure we don't copy over the mode line.
3290 at the bottom. */
3291 if (to_y + run->height > bottom_y)
3292 height = bottom_y - to_y;
3293 else
3294 height = run->height;
3297 BLOCK_INPUT;
3299 /* Cursor off. Will be switched on again in x_update_window_end. */
3300 updated_window = w;
3301 x_clear_cursor (w);
3303 XCopyArea (FRAME_X_DISPLAY (f),
3304 FRAME_X_WINDOW (f), FRAME_X_WINDOW (f),
3305 f->output_data.x->normal_gc,
3306 x, from_y,
3307 width, height,
3308 x, to_y);
3310 UNBLOCK_INPUT;
3315 /***********************************************************************
3316 Exposure Events
3317 ***********************************************************************/
3320 static void
3321 frame_highlight (struct frame *f)
3323 /* We used to only do this if Vx_no_window_manager was non-nil, but
3324 the ICCCM (section 4.1.6) says that the window's border pixmap
3325 and border pixel are window attributes which are "private to the
3326 client", so we can always change it to whatever we want. */
3327 BLOCK_INPUT;
3328 XSetWindowBorder (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3329 f->output_data.x->border_pixel);
3330 UNBLOCK_INPUT;
3331 x_update_cursor (f, 1);
3332 x_set_frame_alpha (f);
3335 static void
3336 frame_unhighlight (struct frame *f)
3338 /* We used to only do this if Vx_no_window_manager was non-nil, but
3339 the ICCCM (section 4.1.6) says that the window's border pixmap
3340 and border pixel are window attributes which are "private to the
3341 client", so we can always change it to whatever we want. */
3342 BLOCK_INPUT;
3343 XSetWindowBorderPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3344 f->output_data.x->border_tile);
3345 UNBLOCK_INPUT;
3346 x_update_cursor (f, 1);
3347 x_set_frame_alpha (f);
3350 /* The focus has changed. Update the frames as necessary to reflect
3351 the new situation. Note that we can't change the selected frame
3352 here, because the Lisp code we are interrupting might become confused.
3353 Each event gets marked with the frame in which it occurred, so the
3354 Lisp code can tell when the switch took place by examining the events. */
3356 static void
3357 x_new_focus_frame (struct x_display_info *dpyinfo, struct frame *frame)
3359 struct frame *old_focus = dpyinfo->x_focus_frame;
3361 if (frame != dpyinfo->x_focus_frame)
3363 /* Set this before calling other routines, so that they see
3364 the correct value of x_focus_frame. */
3365 dpyinfo->x_focus_frame = frame;
3367 if (old_focus && old_focus->auto_lower)
3368 x_lower_frame (old_focus);
3370 if (dpyinfo->x_focus_frame && dpyinfo->x_focus_frame->auto_raise)
3371 pending_autoraise_frame = dpyinfo->x_focus_frame;
3372 else
3373 pending_autoraise_frame = 0;
3376 x_frame_rehighlight (dpyinfo);
3379 /* Handle FocusIn and FocusOut state changes for FRAME.
3380 If FRAME has focus and there exists more than one frame, puts
3381 a FOCUS_IN_EVENT into *BUFP. */
3383 static void
3384 x_focus_changed (int type, int state, struct x_display_info *dpyinfo, struct frame *frame, struct input_event *bufp)
3386 if (type == FocusIn)
3388 if (dpyinfo->x_focus_event_frame != frame)
3390 x_new_focus_frame (dpyinfo, frame);
3391 dpyinfo->x_focus_event_frame = frame;
3393 /* Don't stop displaying the initial startup message
3394 for a switch-frame event we don't need. */
3395 if (NILP (Vterminal_frame)
3396 && CONSP (Vframe_list)
3397 && !NILP (XCDR (Vframe_list)))
3399 bufp->kind = FOCUS_IN_EVENT;
3400 XSETFRAME (bufp->frame_or_window, frame);
3404 frame->output_data.x->focus_state |= state;
3406 #ifdef HAVE_X_I18N
3407 if (FRAME_XIC (frame))
3408 XSetICFocus (FRAME_XIC (frame));
3409 #endif
3411 else if (type == FocusOut)
3413 frame->output_data.x->focus_state &= ~state;
3415 if (dpyinfo->x_focus_event_frame == frame)
3417 dpyinfo->x_focus_event_frame = 0;
3418 x_new_focus_frame (dpyinfo, 0);
3421 #ifdef HAVE_X_I18N
3422 if (FRAME_XIC (frame))
3423 XUnsetICFocus (FRAME_XIC (frame));
3424 #endif
3425 if (frame->pointer_invisible)
3426 XTtoggle_invisible_pointer (frame, 0);
3430 /* The focus may have changed. Figure out if it is a real focus change,
3431 by checking both FocusIn/Out and Enter/LeaveNotify events.
3433 Returns FOCUS_IN_EVENT event in *BUFP. */
3435 static void
3436 x_detect_focus_change (struct x_display_info *dpyinfo, XEvent *event, struct input_event *bufp)
3438 struct frame *frame;
3440 frame = x_any_window_to_frame (dpyinfo, event->xany.window);
3441 if (! frame)
3442 return;
3444 switch (event->type)
3446 case EnterNotify:
3447 case LeaveNotify:
3449 struct frame *focus_frame = dpyinfo->x_focus_event_frame;
3450 int focus_state
3451 = focus_frame ? focus_frame->output_data.x->focus_state : 0;
3453 if (event->xcrossing.detail != NotifyInferior
3454 && event->xcrossing.focus
3455 && ! (focus_state & FOCUS_EXPLICIT))
3456 x_focus_changed ((event->type == EnterNotify ? FocusIn : FocusOut),
3457 FOCUS_IMPLICIT,
3458 dpyinfo, frame, bufp);
3460 break;
3462 case FocusIn:
3463 case FocusOut:
3464 x_focus_changed (event->type,
3465 (event->xfocus.detail == NotifyPointer ?
3466 FOCUS_IMPLICIT : FOCUS_EXPLICIT),
3467 dpyinfo, frame, bufp);
3468 break;
3470 case ClientMessage:
3471 if (event->xclient.message_type == dpyinfo->Xatom_XEMBED)
3473 enum xembed_message msg = event->xclient.data.l[1];
3474 x_focus_changed ((msg == XEMBED_FOCUS_IN ? FocusIn : FocusOut),
3475 FOCUS_EXPLICIT, dpyinfo, frame, bufp);
3477 break;
3482 /* Handle an event saying the mouse has moved out of an Emacs frame. */
3484 void
3485 x_mouse_leave (struct x_display_info *dpyinfo)
3487 x_new_focus_frame (dpyinfo, dpyinfo->x_focus_event_frame);
3490 /* The focus has changed, or we have redirected a frame's focus to
3491 another frame (this happens when a frame uses a surrogate
3492 mini-buffer frame). Shift the highlight as appropriate.
3494 The FRAME argument doesn't necessarily have anything to do with which
3495 frame is being highlighted or un-highlighted; we only use it to find
3496 the appropriate X display info. */
3498 static void
3499 XTframe_rehighlight (struct frame *frame)
3501 x_frame_rehighlight (FRAME_X_DISPLAY_INFO (frame));
3504 static void
3505 x_frame_rehighlight (struct x_display_info *dpyinfo)
3507 struct frame *old_highlight = dpyinfo->x_highlight_frame;
3509 if (dpyinfo->x_focus_frame)
3511 dpyinfo->x_highlight_frame
3512 = ((FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame)))
3513 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
3514 : dpyinfo->x_focus_frame);
3515 if (! FRAME_LIVE_P (dpyinfo->x_highlight_frame))
3517 FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
3518 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
3521 else
3522 dpyinfo->x_highlight_frame = 0;
3524 if (dpyinfo->x_highlight_frame != old_highlight)
3526 if (old_highlight)
3527 frame_unhighlight (old_highlight);
3528 if (dpyinfo->x_highlight_frame)
3529 frame_highlight (dpyinfo->x_highlight_frame);
3535 /* Keyboard processing - modifier keys, vendor-specific keysyms, etc. */
3537 /* Initialize mode_switch_bit and modifier_meaning. */
3538 static void
3539 x_find_modifier_meanings (struct x_display_info *dpyinfo)
3541 int min_code, max_code;
3542 KeySym *syms;
3543 int syms_per_code;
3544 XModifierKeymap *mods;
3546 dpyinfo->meta_mod_mask = 0;
3547 dpyinfo->shift_lock_mask = 0;
3548 dpyinfo->alt_mod_mask = 0;
3549 dpyinfo->super_mod_mask = 0;
3550 dpyinfo->hyper_mod_mask = 0;
3552 XDisplayKeycodes (dpyinfo->display, &min_code, &max_code);
3554 syms = XGetKeyboardMapping (dpyinfo->display,
3555 min_code, max_code - min_code + 1,
3556 &syms_per_code);
3557 mods = XGetModifierMapping (dpyinfo->display);
3559 /* Scan the modifier table to see which modifier bits the Meta and
3560 Alt keysyms are on. */
3562 int row, col; /* The row and column in the modifier table. */
3563 int found_alt_or_meta;
3565 for (row = 3; row < 8; row++)
3567 found_alt_or_meta = 0;
3568 for (col = 0; col < mods->max_keypermod; col++)
3570 KeyCode code = mods->modifiermap[(row * mods->max_keypermod) + col];
3572 /* Zeroes are used for filler. Skip them. */
3573 if (code == 0)
3574 continue;
3576 /* Are any of this keycode's keysyms a meta key? */
3578 int code_col;
3580 for (code_col = 0; code_col < syms_per_code; code_col++)
3582 int sym = syms[((code - min_code) * syms_per_code) + code_col];
3584 switch (sym)
3586 case XK_Meta_L:
3587 case XK_Meta_R:
3588 found_alt_or_meta = 1;
3589 dpyinfo->meta_mod_mask |= (1 << row);
3590 break;
3592 case XK_Alt_L:
3593 case XK_Alt_R:
3594 found_alt_or_meta = 1;
3595 dpyinfo->alt_mod_mask |= (1 << row);
3596 break;
3598 case XK_Hyper_L:
3599 case XK_Hyper_R:
3600 if (!found_alt_or_meta)
3601 dpyinfo->hyper_mod_mask |= (1 << row);
3602 code_col = syms_per_code;
3603 col = mods->max_keypermod;
3604 break;
3606 case XK_Super_L:
3607 case XK_Super_R:
3608 if (!found_alt_or_meta)
3609 dpyinfo->super_mod_mask |= (1 << row);
3610 code_col = syms_per_code;
3611 col = mods->max_keypermod;
3612 break;
3614 case XK_Shift_Lock:
3615 /* Ignore this if it's not on the lock modifier. */
3616 if (!found_alt_or_meta && ((1 << row) == LockMask))
3617 dpyinfo->shift_lock_mask = LockMask;
3618 code_col = syms_per_code;
3619 col = mods->max_keypermod;
3620 break;
3628 /* If we couldn't find any meta keys, accept any alt keys as meta keys. */
3629 if (! dpyinfo->meta_mod_mask)
3631 dpyinfo->meta_mod_mask = dpyinfo->alt_mod_mask;
3632 dpyinfo->alt_mod_mask = 0;
3635 /* If some keys are both alt and meta,
3636 make them just meta, not alt. */
3637 if (dpyinfo->alt_mod_mask & dpyinfo->meta_mod_mask)
3639 dpyinfo->alt_mod_mask &= ~dpyinfo->meta_mod_mask;
3642 XFree ((char *) syms);
3643 XFreeModifiermap (mods);
3646 /* Convert between the modifier bits X uses and the modifier bits
3647 Emacs uses. */
3649 unsigned int
3650 x_x_to_emacs_modifiers (struct x_display_info *dpyinfo, unsigned int state)
3652 EMACS_UINT mod_meta = meta_modifier;
3653 EMACS_UINT mod_alt = alt_modifier;
3654 EMACS_UINT mod_hyper = hyper_modifier;
3655 EMACS_UINT mod_super = super_modifier;
3656 Lisp_Object tem;
3658 tem = Fget (Vx_alt_keysym, Qmodifier_value);
3659 if (! EQ (tem, Qnil)) mod_alt = XUINT (tem);
3660 tem = Fget (Vx_meta_keysym, Qmodifier_value);
3661 if (! EQ (tem, Qnil)) mod_meta = XUINT (tem);
3662 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
3663 if (! EQ (tem, Qnil)) mod_hyper = XUINT (tem);
3664 tem = Fget (Vx_super_keysym, Qmodifier_value);
3665 if (! EQ (tem, Qnil)) mod_super = XUINT (tem);
3668 return ( ((state & (ShiftMask | dpyinfo->shift_lock_mask)) ? shift_modifier : 0)
3669 | ((state & ControlMask) ? ctrl_modifier : 0)
3670 | ((state & dpyinfo->meta_mod_mask) ? mod_meta : 0)
3671 | ((state & dpyinfo->alt_mod_mask) ? mod_alt : 0)
3672 | ((state & dpyinfo->super_mod_mask) ? mod_super : 0)
3673 | ((state & dpyinfo->hyper_mod_mask) ? mod_hyper : 0));
3676 static unsigned int
3677 x_emacs_to_x_modifiers (struct x_display_info *dpyinfo, unsigned int state)
3679 EMACS_UINT mod_meta = meta_modifier;
3680 EMACS_UINT mod_alt = alt_modifier;
3681 EMACS_UINT mod_hyper = hyper_modifier;
3682 EMACS_UINT mod_super = super_modifier;
3684 Lisp_Object tem;
3686 tem = Fget (Vx_alt_keysym, Qmodifier_value);
3687 if (! EQ (tem, Qnil)) mod_alt = XUINT (tem);
3688 tem = Fget (Vx_meta_keysym, Qmodifier_value);
3689 if (! EQ (tem, Qnil)) mod_meta = XUINT (tem);
3690 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
3691 if (! EQ (tem, Qnil)) mod_hyper = XUINT (tem);
3692 tem = Fget (Vx_super_keysym, Qmodifier_value);
3693 if (! EQ (tem, Qnil)) mod_super = XUINT (tem);
3696 return ( ((state & mod_alt) ? dpyinfo->alt_mod_mask : 0)
3697 | ((state & mod_super) ? dpyinfo->super_mod_mask : 0)
3698 | ((state & mod_hyper) ? dpyinfo->hyper_mod_mask : 0)
3699 | ((state & shift_modifier) ? ShiftMask : 0)
3700 | ((state & ctrl_modifier) ? ControlMask : 0)
3701 | ((state & mod_meta) ? dpyinfo->meta_mod_mask : 0));
3704 /* Convert a keysym to its name. */
3706 char *
3707 x_get_keysym_name (int keysym)
3709 char *value;
3711 BLOCK_INPUT;
3712 value = XKeysymToString (keysym);
3713 UNBLOCK_INPUT;
3715 return value;
3720 /* Mouse clicks and mouse movement. Rah. */
3722 /* Prepare a mouse-event in *RESULT for placement in the input queue.
3724 If the event is a button press, then note that we have grabbed
3725 the mouse. */
3727 static Lisp_Object
3728 construct_mouse_click (struct input_event *result, XButtonEvent *event, struct frame *f)
3730 /* Make the event type NO_EVENT; we'll change that when we decide
3731 otherwise. */
3732 result->kind = MOUSE_CLICK_EVENT;
3733 result->code = event->button - Button1;
3734 result->timestamp = event->time;
3735 result->modifiers = (x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO (f),
3736 event->state)
3737 | (event->type == ButtonRelease
3738 ? up_modifier
3739 : down_modifier));
3741 XSETINT (result->x, event->x);
3742 XSETINT (result->y, event->y);
3743 XSETFRAME (result->frame_or_window, f);
3744 result->arg = Qnil;
3745 return Qnil;
3749 /* Function to report a mouse movement to the mainstream Emacs code.
3750 The input handler calls this.
3752 We have received a mouse movement event, which is given in *event.
3753 If the mouse is over a different glyph than it was last time, tell
3754 the mainstream emacs code by setting mouse_moved. If not, ask for
3755 another motion event, so we can check again the next time it moves. */
3757 static XMotionEvent last_mouse_motion_event;
3758 static Lisp_Object last_mouse_motion_frame;
3760 static int
3761 note_mouse_movement (FRAME_PTR frame, XMotionEvent *event)
3763 last_mouse_movement_time = event->time;
3764 last_mouse_motion_event = *event;
3765 XSETFRAME (last_mouse_motion_frame, frame);
3767 if (!FRAME_X_OUTPUT (frame))
3768 return 0;
3770 if (event->window != FRAME_X_WINDOW (frame))
3772 frame->mouse_moved = 1;
3773 last_mouse_scroll_bar = Qnil;
3774 note_mouse_highlight (frame, -1, -1);
3775 last_mouse_glyph_frame = 0;
3776 return 1;
3780 /* Has the mouse moved off the glyph it was on at the last sighting? */
3781 if (frame != last_mouse_glyph_frame
3782 || event->x < last_mouse_glyph.x
3783 || event->x >= last_mouse_glyph.x + last_mouse_glyph.width
3784 || event->y < last_mouse_glyph.y
3785 || event->y >= last_mouse_glyph.y + last_mouse_glyph.height)
3787 frame->mouse_moved = 1;
3788 last_mouse_scroll_bar = Qnil;
3789 note_mouse_highlight (frame, event->x, event->y);
3790 /* Remember which glyph we're now on. */
3791 remember_mouse_glyph (frame, event->x, event->y, &last_mouse_glyph);
3792 last_mouse_glyph_frame = frame;
3793 return 1;
3796 return 0;
3800 /************************************************************************
3801 Mouse Face
3802 ************************************************************************/
3804 static void
3805 redo_mouse_highlight (void)
3807 if (!NILP (last_mouse_motion_frame)
3808 && FRAME_LIVE_P (XFRAME (last_mouse_motion_frame)))
3809 note_mouse_highlight (XFRAME (last_mouse_motion_frame),
3810 last_mouse_motion_event.x,
3811 last_mouse_motion_event.y);
3816 /* Return the current position of the mouse.
3817 *FP should be a frame which indicates which display to ask about.
3819 If the mouse movement started in a scroll bar, set *FP, *BAR_WINDOW,
3820 and *PART to the frame, window, and scroll bar part that the mouse
3821 is over. Set *X and *Y to the portion and whole of the mouse's
3822 position on the scroll bar.
3824 If the mouse movement started elsewhere, set *FP to the frame the
3825 mouse is on, *BAR_WINDOW to nil, and *X and *Y to the character cell
3826 the mouse is over.
3828 Set *TIME to the server time-stamp for the time at which the mouse
3829 was at this position.
3831 Don't store anything if we don't have a valid set of values to report.
3833 This clears the mouse_moved flag, so we can wait for the next mouse
3834 movement. */
3836 static void
3837 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)
3839 FRAME_PTR f1;
3841 BLOCK_INPUT;
3843 if (! NILP (last_mouse_scroll_bar) && insist == 0)
3844 x_scroll_bar_report_motion (fp, bar_window, part, x, y, time);
3845 else
3847 Window root;
3848 int root_x, root_y;
3850 Window dummy_window;
3851 int dummy;
3853 Lisp_Object frame, tail;
3855 /* Clear the mouse-moved flag for every frame on this display. */
3856 FOR_EACH_FRAME (tail, frame)
3857 if (FRAME_X_P (XFRAME (frame))
3858 && FRAME_X_DISPLAY (XFRAME (frame)) == FRAME_X_DISPLAY (*fp))
3859 XFRAME (frame)->mouse_moved = 0;
3861 last_mouse_scroll_bar = Qnil;
3863 /* Figure out which root window we're on. */
3864 XQueryPointer (FRAME_X_DISPLAY (*fp),
3865 DefaultRootWindow (FRAME_X_DISPLAY (*fp)),
3867 /* The root window which contains the pointer. */
3868 &root,
3870 /* Trash which we can't trust if the pointer is on
3871 a different screen. */
3872 &dummy_window,
3874 /* The position on that root window. */
3875 &root_x, &root_y,
3877 /* More trash we can't trust. */
3878 &dummy, &dummy,
3880 /* Modifier keys and pointer buttons, about which
3881 we don't care. */
3882 (unsigned int *) &dummy);
3884 /* Now we have a position on the root; find the innermost window
3885 containing the pointer. */
3887 Window win, child;
3888 int win_x, win_y;
3889 int parent_x = 0, parent_y = 0;
3891 win = root;
3893 /* XTranslateCoordinates can get errors if the window
3894 structure is changing at the same time this function
3895 is running. So at least we must not crash from them. */
3897 x_catch_errors (FRAME_X_DISPLAY (*fp));
3899 if (FRAME_X_DISPLAY_INFO (*fp)->grabbed && last_mouse_frame
3900 && FRAME_LIVE_P (last_mouse_frame))
3902 /* If mouse was grabbed on a frame, give coords for that frame
3903 even if the mouse is now outside it. */
3904 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
3906 /* From-window, to-window. */
3907 root, FRAME_X_WINDOW (last_mouse_frame),
3909 /* From-position, to-position. */
3910 root_x, root_y, &win_x, &win_y,
3912 /* Child of win. */
3913 &child);
3914 f1 = last_mouse_frame;
3916 else
3918 while (1)
3920 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
3922 /* From-window, to-window. */
3923 root, win,
3925 /* From-position, to-position. */
3926 root_x, root_y, &win_x, &win_y,
3928 /* Child of win. */
3929 &child);
3931 if (child == None || child == win)
3932 break;
3933 #ifdef USE_GTK
3934 /* We don't wan't to know the innermost window. We
3935 want the edit window. For non-Gtk+ the innermost
3936 window is the edit window. For Gtk+ it might not
3937 be. It might be the tool bar for example. */
3938 if (x_window_to_frame (FRAME_X_DISPLAY_INFO (*fp), win))
3939 break;
3940 #endif
3941 win = child;
3942 parent_x = win_x;
3943 parent_y = win_y;
3946 /* Now we know that:
3947 win is the innermost window containing the pointer
3948 (XTC says it has no child containing the pointer),
3949 win_x and win_y are the pointer's position in it
3950 (XTC did this the last time through), and
3951 parent_x and parent_y are the pointer's position in win's parent.
3952 (They are what win_x and win_y were when win was child.
3953 If win is the root window, it has no parent, and
3954 parent_{x,y} are invalid, but that's okay, because we'll
3955 never use them in that case.) */
3957 #ifdef USE_GTK
3958 /* We don't wan't to know the innermost window. We
3959 want the edit window. */
3960 f1 = x_window_to_frame (FRAME_X_DISPLAY_INFO (*fp), win);
3961 #else
3962 /* Is win one of our frames? */
3963 f1 = x_any_window_to_frame (FRAME_X_DISPLAY_INFO (*fp), win);
3964 #endif
3966 #ifdef USE_X_TOOLKIT
3967 /* If we end up with the menu bar window, say it's not
3968 on the frame. */
3969 if (f1 != NULL
3970 && f1->output_data.x->menubar_widget
3971 && win == XtWindow (f1->output_data.x->menubar_widget))
3972 f1 = NULL;
3973 #endif /* USE_X_TOOLKIT */
3976 if (x_had_errors_p (FRAME_X_DISPLAY (*fp)))
3977 f1 = 0;
3979 x_uncatch_errors ();
3981 /* If not, is it one of our scroll bars? */
3982 if (! f1)
3984 struct scroll_bar *bar;
3986 bar = x_window_to_scroll_bar (FRAME_X_DISPLAY (*fp), win);
3988 if (bar)
3990 f1 = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
3991 win_x = parent_x;
3992 win_y = parent_y;
3996 if (f1 == 0 && insist > 0)
3997 f1 = SELECTED_FRAME ();
3999 if (f1)
4001 /* Ok, we found a frame. Store all the values.
4002 last_mouse_glyph is a rectangle used to reduce the
4003 generation of mouse events. To not miss any motion
4004 events, we must divide the frame into rectangles of the
4005 size of the smallest character that could be displayed
4006 on it, i.e. into the same rectangles that matrices on
4007 the frame are divided into. */
4009 remember_mouse_glyph (f1, win_x, win_y, &last_mouse_glyph);
4010 last_mouse_glyph_frame = f1;
4012 *bar_window = Qnil;
4013 *part = 0;
4014 *fp = f1;
4015 XSETINT (*x, win_x);
4016 XSETINT (*y, win_y);
4017 *time = last_mouse_movement_time;
4022 UNBLOCK_INPUT;
4027 /***********************************************************************
4028 Scroll bars
4029 ***********************************************************************/
4031 /* Scroll bar support. */
4033 /* Given an X window ID and a DISPLAY, find the struct scroll_bar which
4034 manages it.
4035 This can be called in GC, so we have to make sure to strip off mark
4036 bits. */
4038 static struct scroll_bar *
4039 x_window_to_scroll_bar (Display *display, Window window_id)
4041 Lisp_Object tail;
4043 #if defined (USE_GTK) && defined (USE_TOOLKIT_SCROLL_BARS)
4044 window_id = (Window) xg_get_scroll_id_for_window (display, window_id);
4045 #endif /* USE_GTK && USE_TOOLKIT_SCROLL_BARS */
4047 for (tail = Vframe_list; CONSP (tail); tail = XCDR (tail))
4049 Lisp_Object frame, bar, condemned;
4051 frame = XCAR (tail);
4052 /* All elements of Vframe_list should be frames. */
4053 if (! FRAMEP (frame))
4054 abort ();
4056 if (! FRAME_X_P (XFRAME (frame)))
4057 continue;
4059 /* Scan this frame's scroll bar list for a scroll bar with the
4060 right window ID. */
4061 condemned = FRAME_CONDEMNED_SCROLL_BARS (XFRAME (frame));
4062 for (bar = FRAME_SCROLL_BARS (XFRAME (frame));
4063 /* This trick allows us to search both the ordinary and
4064 condemned scroll bar lists with one loop. */
4065 ! NILP (bar) || (bar = condemned,
4066 condemned = Qnil,
4067 ! NILP (bar));
4068 bar = XSCROLL_BAR (bar)->next)
4069 if (XSCROLL_BAR (bar)->x_window == window_id &&
4070 FRAME_X_DISPLAY (XFRAME (frame)) == display)
4071 return XSCROLL_BAR (bar);
4074 return 0;
4078 #if defined USE_LUCID
4080 /* Return the Lucid menu bar WINDOW is part of. Return null
4081 if WINDOW is not part of a menu bar. */
4083 static Widget
4084 x_window_to_menu_bar (Window window)
4086 Lisp_Object tail;
4088 for (tail = Vframe_list; CONSP (tail); tail = XCDR (tail))
4090 if (FRAME_X_P (XFRAME (XCAR (tail))))
4092 Lisp_Object frame = XCAR (tail);
4093 Widget menu_bar = XFRAME (frame)->output_data.x->menubar_widget;
4095 if (menu_bar && xlwmenu_window_p (menu_bar, window))
4096 return menu_bar;
4100 return NULL;
4103 #endif /* USE_LUCID */
4106 /************************************************************************
4107 Toolkit scroll bars
4108 ************************************************************************/
4110 #ifdef USE_TOOLKIT_SCROLL_BARS
4112 static void x_scroll_bar_to_input_event (XEvent *, struct input_event *);
4113 static void x_send_scroll_bar_event (Lisp_Object, int, int, int);
4114 static void x_create_toolkit_scroll_bar (struct frame *,
4115 struct scroll_bar *);
4116 static void x_set_toolkit_scroll_bar_thumb (struct scroll_bar *,
4117 int, int, int);
4120 /* Lisp window being scrolled. Set when starting to interact with
4121 a toolkit scroll bar, reset to nil when ending the interaction. */
4123 static Lisp_Object window_being_scrolled;
4125 /* Last scroll bar part sent in xm_scroll_callback. */
4127 static int last_scroll_bar_part;
4129 /* Whether this is an Xaw with arrow-scrollbars. This should imply
4130 that movements of 1/20 of the screen size are mapped to up/down. */
4132 #ifndef USE_GTK
4133 /* Id of action hook installed for scroll bars. */
4135 static XtActionHookId action_hook_id;
4137 static Boolean xaw3d_arrow_scroll;
4139 /* Whether the drag scrolling maintains the mouse at the top of the
4140 thumb. If not, resizing the thumb needs to be done more carefully
4141 to avoid jerkyness. */
4143 static Boolean xaw3d_pick_top;
4145 /* Action hook installed via XtAppAddActionHook when toolkit scroll
4146 bars are used.. The hook is responsible for detecting when
4147 the user ends an interaction with the scroll bar, and generates
4148 a `end-scroll' SCROLL_BAR_CLICK_EVENT' event if so. */
4150 static void
4151 xt_action_hook (Widget widget, XtPointer client_data, String action_name,
4152 XEvent *event, String *params, Cardinal *num_params)
4154 int scroll_bar_p;
4155 const char *end_action;
4157 #ifdef USE_MOTIF
4158 scroll_bar_p = XmIsScrollBar (widget);
4159 end_action = "Release";
4160 #else /* !USE_MOTIF i.e. use Xaw */
4161 scroll_bar_p = XtIsSubclass (widget, scrollbarWidgetClass);
4162 end_action = "EndScroll";
4163 #endif /* USE_MOTIF */
4165 if (scroll_bar_p
4166 && strcmp (action_name, end_action) == 0
4167 && WINDOWP (window_being_scrolled))
4169 struct window *w;
4171 x_send_scroll_bar_event (window_being_scrolled,
4172 scroll_bar_end_scroll, 0, 0);
4173 w = XWINDOW (window_being_scrolled);
4175 if (!NILP (XSCROLL_BAR (w->vertical_scroll_bar)->dragging))
4177 XSCROLL_BAR (w->vertical_scroll_bar)->dragging = Qnil;
4178 /* The thumb size is incorrect while dragging: fix it. */
4179 set_vertical_scroll_bar (w);
4181 window_being_scrolled = Qnil;
4182 last_scroll_bar_part = -1;
4184 /* Xt timeouts no longer needed. */
4185 toolkit_scroll_bar_interaction = 0;
4188 #endif /* not USE_GTK */
4190 /* A vector of windows used for communication between
4191 x_send_scroll_bar_event and x_scroll_bar_to_input_event. */
4193 static struct window **scroll_bar_windows;
4194 static int scroll_bar_windows_size;
4197 /* Send a client message with message type Xatom_Scrollbar for a
4198 scroll action to the frame of WINDOW. PART is a value identifying
4199 the part of the scroll bar that was clicked on. PORTION is the
4200 amount to scroll of a whole of WHOLE. */
4202 static void
4203 x_send_scroll_bar_event (Lisp_Object window, int part, int portion, int whole)
4205 XEvent event;
4206 XClientMessageEvent *ev = (XClientMessageEvent *) &event;
4207 struct window *w = XWINDOW (window);
4208 struct frame *f = XFRAME (w->frame);
4209 int i;
4211 BLOCK_INPUT;
4213 /* Construct a ClientMessage event to send to the frame. */
4214 ev->type = ClientMessage;
4215 ev->message_type = FRAME_X_DISPLAY_INFO (f)->Xatom_Scrollbar;
4216 ev->display = FRAME_X_DISPLAY (f);
4217 ev->window = FRAME_X_WINDOW (f);
4218 ev->format = 32;
4220 /* We can only transfer 32 bits in the XClientMessageEvent, which is
4221 not enough to store a pointer or Lisp_Object on a 64 bit system.
4222 So, store the window in scroll_bar_windows and pass the index
4223 into that array in the event. */
4224 for (i = 0; i < scroll_bar_windows_size; ++i)
4225 if (scroll_bar_windows[i] == NULL)
4226 break;
4228 if (i == scroll_bar_windows_size)
4230 int new_size = max (10, 2 * scroll_bar_windows_size);
4231 size_t nbytes = new_size * sizeof *scroll_bar_windows;
4232 size_t old_nbytes = scroll_bar_windows_size * sizeof *scroll_bar_windows;
4234 scroll_bar_windows = (struct window **) xrealloc (scroll_bar_windows,
4235 nbytes);
4236 memset (&scroll_bar_windows[i], 0, nbytes - old_nbytes);
4237 scroll_bar_windows_size = new_size;
4240 scroll_bar_windows[i] = w;
4241 ev->data.l[0] = (long) i;
4242 ev->data.l[1] = (long) part;
4243 ev->data.l[2] = (long) 0;
4244 ev->data.l[3] = (long) portion;
4245 ev->data.l[4] = (long) whole;
4247 /* Make Xt timeouts work while the scroll bar is active. */
4248 toolkit_scroll_bar_interaction = 1;
4249 #ifdef USE_X_TOOLKIT
4250 x_activate_timeout_atimer ();
4251 #endif
4253 /* Setting the event mask to zero means that the message will
4254 be sent to the client that created the window, and if that
4255 window no longer exists, no event will be sent. */
4256 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), False, 0, &event);
4257 UNBLOCK_INPUT;
4261 /* Transform a scroll bar ClientMessage EVENT to an Emacs input event
4262 in *IEVENT. */
4264 static void
4265 x_scroll_bar_to_input_event (XEvent *event, struct input_event *ievent)
4267 XClientMessageEvent *ev = (XClientMessageEvent *) event;
4268 Lisp_Object window;
4269 struct frame *f;
4270 struct window *w;
4272 w = scroll_bar_windows[ev->data.l[0]];
4273 scroll_bar_windows[ev->data.l[0]] = NULL;
4275 XSETWINDOW (window, w);
4276 f = XFRAME (w->frame);
4278 ievent->kind = SCROLL_BAR_CLICK_EVENT;
4279 ievent->frame_or_window = window;
4280 ievent->arg = Qnil;
4281 #ifdef USE_GTK
4282 ievent->timestamp = CurrentTime;
4283 #else
4284 ievent->timestamp = XtLastTimestampProcessed (FRAME_X_DISPLAY (f));
4285 #endif
4286 ievent->part = ev->data.l[1];
4287 ievent->code = ev->data.l[2];
4288 ievent->x = make_number ((int) ev->data.l[3]);
4289 ievent->y = make_number ((int) ev->data.l[4]);
4290 ievent->modifiers = 0;
4294 #ifdef USE_MOTIF
4296 /* Minimum and maximum values used for Motif scroll bars. */
4298 #define XM_SB_MAX 10000000
4301 /* Scroll bar callback for Motif scroll bars. WIDGET is the scroll
4302 bar widget. CLIENT_DATA is a pointer to the scroll_bar structure.
4303 CALL_DATA is a pointer to a XmScrollBarCallbackStruct. */
4305 static void
4306 xm_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
4308 struct scroll_bar *bar = (struct scroll_bar *) client_data;
4309 XmScrollBarCallbackStruct *cs = (XmScrollBarCallbackStruct *) call_data;
4310 int part = -1, whole = 0, portion = 0;
4312 switch (cs->reason)
4314 case XmCR_DECREMENT:
4315 bar->dragging = Qnil;
4316 part = scroll_bar_up_arrow;
4317 break;
4319 case XmCR_INCREMENT:
4320 bar->dragging = Qnil;
4321 part = scroll_bar_down_arrow;
4322 break;
4324 case XmCR_PAGE_DECREMENT:
4325 bar->dragging = Qnil;
4326 part = scroll_bar_above_handle;
4327 break;
4329 case XmCR_PAGE_INCREMENT:
4330 bar->dragging = Qnil;
4331 part = scroll_bar_below_handle;
4332 break;
4334 case XmCR_TO_TOP:
4335 bar->dragging = Qnil;
4336 part = scroll_bar_to_top;
4337 break;
4339 case XmCR_TO_BOTTOM:
4340 bar->dragging = Qnil;
4341 part = scroll_bar_to_bottom;
4342 break;
4344 case XmCR_DRAG:
4346 int slider_size;
4348 /* Get the slider size. */
4349 BLOCK_INPUT;
4350 XtVaGetValues (widget, XmNsliderSize, &slider_size, NULL);
4351 UNBLOCK_INPUT;
4353 whole = XM_SB_MAX - slider_size;
4354 portion = min (cs->value, whole);
4355 part = scroll_bar_handle;
4356 bar->dragging = make_number (cs->value);
4358 break;
4360 case XmCR_VALUE_CHANGED:
4361 break;
4364 if (part >= 0)
4366 window_being_scrolled = bar->window;
4367 last_scroll_bar_part = part;
4368 x_send_scroll_bar_event (bar->window, part, portion, whole);
4372 #elif defined USE_GTK
4374 /* Scroll bar callback for GTK scroll bars. WIDGET is the scroll
4375 bar widget. DATA is a pointer to the scroll_bar structure. */
4377 static gboolean
4378 xg_scroll_callback (GtkRange *range,
4379 GtkScrollType scroll,
4380 gdouble value,
4381 gpointer user_data)
4383 struct scroll_bar *bar = (struct scroll_bar *) user_data;
4384 gdouble position;
4385 int part = -1, whole = 0, portion = 0;
4386 GtkAdjustment *adj = GTK_ADJUSTMENT (gtk_range_get_adjustment (range));
4387 FRAME_PTR f = (FRAME_PTR) g_object_get_data (G_OBJECT (range), XG_FRAME_DATA);
4389 if (xg_ignore_gtk_scrollbar) return FALSE;
4390 position = gtk_adjustment_get_value (adj);
4393 switch (scroll)
4395 case GTK_SCROLL_JUMP:
4396 /* Buttons 1 2 or 3 must be grabbed. */
4397 if (FRAME_X_DISPLAY_INFO (f)->grabbed != 0
4398 && FRAME_X_DISPLAY_INFO (f)->grabbed < (1 << 4))
4400 part = scroll_bar_handle;
4401 whole = gtk_adjustment_get_upper (adj) -
4402 gtk_adjustment_get_page_size (adj);
4403 portion = min ((int)position, whole);
4404 bar->dragging = make_number ((int)portion);
4406 break;
4407 case GTK_SCROLL_STEP_BACKWARD:
4408 part = scroll_bar_up_arrow;
4409 bar->dragging = Qnil;
4410 break;
4411 case GTK_SCROLL_STEP_FORWARD:
4412 part = scroll_bar_down_arrow;
4413 bar->dragging = Qnil;
4414 break;
4415 case GTK_SCROLL_PAGE_BACKWARD:
4416 part = scroll_bar_above_handle;
4417 bar->dragging = Qnil;
4418 break;
4419 case GTK_SCROLL_PAGE_FORWARD:
4420 part = scroll_bar_below_handle;
4421 bar->dragging = Qnil;
4422 break;
4425 if (part >= 0)
4427 window_being_scrolled = bar->window;
4428 last_scroll_bar_part = part;
4429 x_send_scroll_bar_event (bar->window, part, portion, whole);
4432 return FALSE;
4435 /* Callback for button release. Sets dragging to Qnil when dragging is done. */
4437 static gboolean
4438 xg_end_scroll_callback (GtkWidget *widget,
4439 GdkEventButton *event,
4440 gpointer user_data)
4442 struct scroll_bar *bar = (struct scroll_bar *) user_data;
4443 bar->dragging = Qnil;
4444 if (WINDOWP (window_being_scrolled))
4446 x_send_scroll_bar_event (window_being_scrolled,
4447 scroll_bar_end_scroll, 0, 0);
4448 window_being_scrolled = Qnil;
4451 return FALSE;
4455 #else /* not USE_GTK and not USE_MOTIF */
4457 /* Xaw scroll bar callback. Invoked when the thumb is dragged.
4458 WIDGET is the scroll bar widget. CLIENT_DATA is a pointer to the
4459 scroll bar struct. CALL_DATA is a pointer to a float saying where
4460 the thumb is. */
4462 static void
4463 xaw_jump_callback (Widget widget, XtPointer client_data, XtPointer call_data)
4465 struct scroll_bar *bar = (struct scroll_bar *) client_data;
4466 float top = *(float *) call_data;
4467 float shown;
4468 int whole, portion, height;
4469 int part;
4471 /* Get the size of the thumb, a value between 0 and 1. */
4472 BLOCK_INPUT;
4473 XtVaGetValues (widget, XtNshown, &shown, XtNheight, &height, NULL);
4474 UNBLOCK_INPUT;
4476 whole = 10000000;
4477 portion = shown < 1 ? top * whole : 0;
4479 if (shown < 1 && (eabs (top + shown - 1) < 1.0/height))
4480 /* Some derivatives of Xaw refuse to shrink the thumb when you reach
4481 the bottom, so we force the scrolling whenever we see that we're
4482 too close to the bottom (in x_set_toolkit_scroll_bar_thumb
4483 we try to ensure that we always stay two pixels away from the
4484 bottom). */
4485 part = scroll_bar_down_arrow;
4486 else
4487 part = scroll_bar_handle;
4489 window_being_scrolled = bar->window;
4490 bar->dragging = make_number (portion);
4491 last_scroll_bar_part = part;
4492 x_send_scroll_bar_event (bar->window, part, portion, whole);
4496 /* Xaw scroll bar callback. Invoked for incremental scrolling.,
4497 i.e. line or page up or down. WIDGET is the Xaw scroll bar
4498 widget. CLIENT_DATA is a pointer to the scroll_bar structure for
4499 the scroll bar. CALL_DATA is an integer specifying the action that
4500 has taken place. Its magnitude is in the range 0..height of the
4501 scroll bar. Negative values mean scroll towards buffer start.
4502 Values < height of scroll bar mean line-wise movement. */
4504 static void
4505 xaw_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
4507 struct scroll_bar *bar = (struct scroll_bar *) client_data;
4508 /* The position really is stored cast to a pointer. */
4509 int position = (long) call_data;
4510 Dimension height;
4511 int part;
4513 /* Get the height of the scroll bar. */
4514 BLOCK_INPUT;
4515 XtVaGetValues (widget, XtNheight, &height, NULL);
4516 UNBLOCK_INPUT;
4518 if (eabs (position) >= height)
4519 part = (position < 0) ? scroll_bar_above_handle : scroll_bar_below_handle;
4521 /* If Xaw3d was compiled with ARROW_SCROLLBAR,
4522 it maps line-movement to call_data = max(5, height/20). */
4523 else if (xaw3d_arrow_scroll && eabs (position) <= max (5, height / 20))
4524 part = (position < 0) ? scroll_bar_up_arrow : scroll_bar_down_arrow;
4525 else
4526 part = scroll_bar_move_ratio;
4528 window_being_scrolled = bar->window;
4529 bar->dragging = Qnil;
4530 last_scroll_bar_part = part;
4531 x_send_scroll_bar_event (bar->window, part, position, height);
4534 #endif /* not USE_GTK and not USE_MOTIF */
4536 #define SCROLL_BAR_NAME "verticalScrollBar"
4538 /* Create the widget for scroll bar BAR on frame F. Record the widget
4539 and X window of the scroll bar in BAR. */
4541 #ifdef USE_GTK
4542 static void
4543 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
4545 const char *scroll_bar_name = SCROLL_BAR_NAME;
4547 BLOCK_INPUT;
4548 xg_create_scroll_bar (f, bar, G_CALLBACK (xg_scroll_callback),
4549 G_CALLBACK (xg_end_scroll_callback),
4550 scroll_bar_name);
4551 UNBLOCK_INPUT;
4554 #else /* not USE_GTK */
4556 static void
4557 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
4559 Window xwindow;
4560 Widget widget;
4561 Arg av[20];
4562 int ac = 0;
4563 char *scroll_bar_name = SCROLL_BAR_NAME;
4564 unsigned long pixel;
4566 BLOCK_INPUT;
4568 #ifdef USE_MOTIF
4569 /* Set resources. Create the widget. */
4570 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
4571 XtSetArg (av[ac], XmNminimum, 0); ++ac;
4572 XtSetArg (av[ac], XmNmaximum, XM_SB_MAX); ++ac;
4573 XtSetArg (av[ac], XmNorientation, XmVERTICAL); ++ac;
4574 XtSetArg (av[ac], XmNprocessingDirection, XmMAX_ON_BOTTOM), ++ac;
4575 XtSetArg (av[ac], XmNincrement, 1); ++ac;
4576 XtSetArg (av[ac], XmNpageIncrement, 1); ++ac;
4578 pixel = f->output_data.x->scroll_bar_foreground_pixel;
4579 if (pixel != -1)
4581 XtSetArg (av[ac], XmNforeground, pixel);
4582 ++ac;
4585 pixel = f->output_data.x->scroll_bar_background_pixel;
4586 if (pixel != -1)
4588 XtSetArg (av[ac], XmNbackground, pixel);
4589 ++ac;
4592 widget = XmCreateScrollBar (f->output_data.x->edit_widget,
4593 scroll_bar_name, av, ac);
4595 /* Add one callback for everything that can happen. */
4596 XtAddCallback (widget, XmNdecrementCallback, xm_scroll_callback,
4597 (XtPointer) bar);
4598 XtAddCallback (widget, XmNdragCallback, xm_scroll_callback,
4599 (XtPointer) bar);
4600 XtAddCallback (widget, XmNincrementCallback, xm_scroll_callback,
4601 (XtPointer) bar);
4602 XtAddCallback (widget, XmNpageDecrementCallback, xm_scroll_callback,
4603 (XtPointer) bar);
4604 XtAddCallback (widget, XmNpageIncrementCallback, xm_scroll_callback,
4605 (XtPointer) bar);
4606 XtAddCallback (widget, XmNtoBottomCallback, xm_scroll_callback,
4607 (XtPointer) bar);
4608 XtAddCallback (widget, XmNtoTopCallback, xm_scroll_callback,
4609 (XtPointer) bar);
4611 /* Realize the widget. Only after that is the X window created. */
4612 XtRealizeWidget (widget);
4614 /* Set the cursor to an arrow. I didn't find a resource to do that.
4615 And I'm wondering why it hasn't an arrow cursor by default. */
4616 XDefineCursor (XtDisplay (widget), XtWindow (widget),
4617 f->output_data.x->nontext_cursor);
4619 #else /* !USE_MOTIF i.e. use Xaw */
4621 /* Set resources. Create the widget. The background of the
4622 Xaw3d scroll bar widget is a little bit light for my taste.
4623 We don't alter it here to let users change it according
4624 to their taste with `emacs*verticalScrollBar.background: xxx'. */
4625 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
4626 XtSetArg (av[ac], XtNorientation, XtorientVertical); ++ac;
4627 /* For smoother scrolling with Xaw3d -sm */
4628 /* XtSetArg (av[ac], XtNpickTop, True); ++ac; */
4630 pixel = f->output_data.x->scroll_bar_foreground_pixel;
4631 if (pixel != -1)
4633 XtSetArg (av[ac], XtNforeground, pixel);
4634 ++ac;
4637 pixel = f->output_data.x->scroll_bar_background_pixel;
4638 if (pixel != -1)
4640 XtSetArg (av[ac], XtNbackground, pixel);
4641 ++ac;
4644 /* Top/bottom shadow colors. */
4646 /* Allocate them, if necessary. */
4647 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1)
4649 pixel = f->output_data.x->scroll_bar_background_pixel;
4650 if (pixel != -1)
4652 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
4653 FRAME_X_COLORMAP (f),
4654 &pixel, 1.2, 0x8000))
4655 pixel = -1;
4656 f->output_data.x->scroll_bar_top_shadow_pixel = pixel;
4659 if (f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
4661 pixel = f->output_data.x->scroll_bar_background_pixel;
4662 if (pixel != -1)
4664 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
4665 FRAME_X_COLORMAP (f),
4666 &pixel, 0.6, 0x4000))
4667 pixel = -1;
4668 f->output_data.x->scroll_bar_bottom_shadow_pixel = pixel;
4672 #ifdef XtNbeNiceToColormap
4673 /* Tell the toolkit about them. */
4674 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1
4675 || f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
4676 /* We tried to allocate a color for the top/bottom shadow, and
4677 failed, so tell Xaw3d to use dithering instead. */
4678 /* But only if we have a small colormap. Xaw3d can allocate nice
4679 colors itself. */
4681 XtSetArg (av[ac], XtNbeNiceToColormap,
4682 DefaultDepthOfScreen (FRAME_X_SCREEN (f)) < 16);
4683 ++ac;
4685 else
4686 /* Tell what colors Xaw3d should use for the top/bottom shadow, to
4687 be more consistent with other emacs 3d colors, and since Xaw3d is
4688 not good at dealing with allocation failure. */
4690 /* This tells Xaw3d to use real colors instead of dithering for
4691 the shadows. */
4692 XtSetArg (av[ac], XtNbeNiceToColormap, False);
4693 ++ac;
4695 /* Specify the colors. */
4696 pixel = f->output_data.x->scroll_bar_top_shadow_pixel;
4697 if (pixel != -1)
4699 XtSetArg (av[ac], XtNtopShadowPixel, pixel);
4700 ++ac;
4702 pixel = f->output_data.x->scroll_bar_bottom_shadow_pixel;
4703 if (pixel != -1)
4705 XtSetArg (av[ac], XtNbottomShadowPixel, pixel);
4706 ++ac;
4709 #endif
4711 widget = XtCreateWidget (scroll_bar_name, scrollbarWidgetClass,
4712 f->output_data.x->edit_widget, av, ac);
4715 char *initial = "";
4716 char *val = initial;
4717 XtVaGetValues (widget, XtNscrollVCursor, (XtPointer) &val,
4718 #ifdef XtNarrowScrollbars
4719 XtNarrowScrollbars, (XtPointer) &xaw3d_arrow_scroll,
4720 #endif
4721 XtNpickTop, (XtPointer) &xaw3d_pick_top, NULL);
4722 if (xaw3d_arrow_scroll || val == initial)
4723 { /* ARROW_SCROLL */
4724 xaw3d_arrow_scroll = True;
4725 /* Isn't that just a personal preference ? --Stef */
4726 XtVaSetValues (widget, XtNcursorName, "top_left_arrow", NULL);
4730 /* Define callbacks. */
4731 XtAddCallback (widget, XtNjumpProc, xaw_jump_callback, (XtPointer) bar);
4732 XtAddCallback (widget, XtNscrollProc, xaw_scroll_callback,
4733 (XtPointer) bar);
4735 /* Realize the widget. Only after that is the X window created. */
4736 XtRealizeWidget (widget);
4738 #endif /* !USE_MOTIF */
4740 /* Install an action hook that lets us detect when the user
4741 finishes interacting with a scroll bar. */
4742 if (action_hook_id == 0)
4743 action_hook_id = XtAppAddActionHook (Xt_app_con, xt_action_hook, 0);
4745 /* Remember X window and widget in the scroll bar vector. */
4746 SET_SCROLL_BAR_X_WIDGET (bar, widget);
4747 xwindow = XtWindow (widget);
4748 bar->x_window = xwindow;
4750 UNBLOCK_INPUT;
4752 #endif /* not USE_GTK */
4755 /* Set the thumb size and position of scroll bar BAR. We are currently
4756 displaying PORTION out of a whole WHOLE, and our position POSITION. */
4758 #ifdef USE_GTK
4759 static void
4760 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position, int whole)
4762 xg_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
4765 #else /* not USE_GTK */
4766 static void
4767 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position,
4768 int whole)
4770 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
4771 Widget widget = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
4772 float top, shown;
4774 BLOCK_INPUT;
4776 #ifdef USE_MOTIF
4778 /* We use an estimate of 30 chars per line rather than the real
4779 `portion' value. This has the disadvantage that the thumb size
4780 is not very representative, but it makes our life a lot easier.
4781 Otherwise, we have to constantly adjust the thumb size, which
4782 we can't always do quickly enough: while dragging, the size of
4783 the thumb might prevent the user from dragging the thumb all the
4784 way to the end. but Motif and some versions of Xaw3d don't allow
4785 updating the thumb size while dragging. Also, even if we can update
4786 its size, the update will often happen too late.
4787 If you don't believe it, check out revision 1.650 of xterm.c to see
4788 what hoops we were going through and the still poor behavior we got. */
4789 portion = WINDOW_TOTAL_LINES (XWINDOW (bar->window)) * 30;
4790 /* When the thumb is at the bottom, position == whole.
4791 So we need to increase `whole' to make space for the thumb. */
4792 whole += portion;
4794 if (whole <= 0)
4795 top = 0, shown = 1;
4796 else
4798 top = (float) position / whole;
4799 shown = (float) portion / whole;
4802 if (NILP (bar->dragging))
4804 int size, value;
4806 /* Slider size. Must be in the range [1 .. MAX - MIN] where MAX
4807 is the scroll bar's maximum and MIN is the scroll bar's minimum
4808 value. */
4809 size = shown * XM_SB_MAX;
4810 size = min (size, XM_SB_MAX);
4811 size = max (size, 1);
4813 /* Position. Must be in the range [MIN .. MAX - SLIDER_SIZE]. */
4814 value = top * XM_SB_MAX;
4815 value = min (value, XM_SB_MAX - size);
4817 XmScrollBarSetValues (widget, value, size, 0, 0, False);
4819 #else /* !USE_MOTIF i.e. use Xaw */
4821 if (whole == 0)
4822 top = 0, shown = 1;
4823 else
4825 top = (float) position / whole;
4826 shown = (float) portion / whole;
4830 float old_top, old_shown;
4831 Dimension height;
4832 XtVaGetValues (widget,
4833 XtNtopOfThumb, &old_top,
4834 XtNshown, &old_shown,
4835 XtNheight, &height,
4836 NULL);
4838 /* Massage the top+shown values. */
4839 if (NILP (bar->dragging) || last_scroll_bar_part == scroll_bar_down_arrow)
4840 top = max (0, min (1, top));
4841 else
4842 top = old_top;
4843 /* Keep two pixels available for moving the thumb down. */
4844 shown = max (0, min (1 - top - (2.0 / height), shown));
4846 /* If the call to XawScrollbarSetThumb below doesn't seem to work,
4847 check that your system's configuration file contains a define
4848 for `NARROWPROTO'. See s/freebsd.h for an example. */
4849 if (top != old_top || shown != old_shown)
4851 if (NILP (bar->dragging))
4852 XawScrollbarSetThumb (widget, top, shown);
4853 else
4855 /* Try to make the scrolling a tad smoother. */
4856 if (!xaw3d_pick_top)
4857 shown = min (shown, old_shown);
4859 XawScrollbarSetThumb (widget, top, shown);
4863 #endif /* !USE_MOTIF */
4865 UNBLOCK_INPUT;
4867 #endif /* not USE_GTK */
4869 #endif /* USE_TOOLKIT_SCROLL_BARS */
4873 /************************************************************************
4874 Scroll bars, general
4875 ************************************************************************/
4877 /* Create a scroll bar and return the scroll bar vector for it. W is
4878 the Emacs window on which to create the scroll bar. TOP, LEFT,
4879 WIDTH and HEIGHT are the pixel coordinates and dimensions of the
4880 scroll bar. */
4882 static struct scroll_bar *
4883 x_scroll_bar_create (struct window *w, int top, int left, int width, int height)
4885 struct frame *f = XFRAME (w->frame);
4886 struct scroll_bar *bar
4887 = ALLOCATE_PSEUDOVECTOR (struct scroll_bar, x_window, PVEC_OTHER);
4889 BLOCK_INPUT;
4891 #ifdef USE_TOOLKIT_SCROLL_BARS
4892 x_create_toolkit_scroll_bar (f, bar);
4893 #else /* not USE_TOOLKIT_SCROLL_BARS */
4895 XSetWindowAttributes a;
4896 unsigned long mask;
4897 Window window;
4899 a.background_pixel = f->output_data.x->scroll_bar_background_pixel;
4900 if (a.background_pixel == -1)
4901 a.background_pixel = FRAME_BACKGROUND_PIXEL (f);
4903 a.event_mask = (ButtonPressMask | ButtonReleaseMask
4904 | ButtonMotionMask | PointerMotionHintMask
4905 | ExposureMask);
4906 a.cursor = FRAME_X_DISPLAY_INFO (f)->vertical_scroll_bar_cursor;
4908 mask = (CWBackPixel | CWEventMask | CWCursor);
4910 /* Clear the area of W that will serve as a scroll bar. This is
4911 for the case that a window has been split horizontally. In
4912 this case, no clear_frame is generated to reduce flickering. */
4913 if (width > 0 && height > 0)
4914 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4915 left, top, width,
4916 window_box_height (w), False);
4918 window = XCreateWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4919 /* Position and size of scroll bar. */
4920 left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
4921 top,
4922 width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
4923 height,
4924 /* Border width, depth, class, and visual. */
4926 CopyFromParent,
4927 CopyFromParent,
4928 CopyFromParent,
4929 /* Attributes. */
4930 mask, &a);
4931 bar->x_window = window;
4933 #endif /* not USE_TOOLKIT_SCROLL_BARS */
4935 XSETWINDOW (bar->window, w);
4936 bar->top = top;
4937 bar->left = left;
4938 bar->width = width;
4939 bar->height = height;
4940 bar->start = 0;
4941 bar->end = 0;
4942 bar->dragging = Qnil;
4943 bar->fringe_extended_p = 0;
4945 /* Add bar to its frame's list of scroll bars. */
4946 bar->next = FRAME_SCROLL_BARS (f);
4947 bar->prev = Qnil;
4948 XSETVECTOR (FRAME_SCROLL_BARS (f), bar);
4949 if (!NILP (bar->next))
4950 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
4952 /* Map the window/widget. */
4953 #ifdef USE_TOOLKIT_SCROLL_BARS
4955 #ifdef USE_GTK
4956 xg_update_scrollbar_pos (f,
4957 bar->x_window,
4958 top,
4959 left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
4960 width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
4961 max (height, 1));
4962 #else /* not USE_GTK */
4963 Widget scroll_bar = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
4964 XtConfigureWidget (scroll_bar,
4965 left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
4966 top,
4967 width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
4968 max (height, 1), 0);
4969 XtMapWidget (scroll_bar);
4970 #endif /* not USE_GTK */
4972 #else /* not USE_TOOLKIT_SCROLL_BARS */
4973 XMapRaised (FRAME_X_DISPLAY (f), bar->x_window);
4974 #endif /* not USE_TOOLKIT_SCROLL_BARS */
4976 UNBLOCK_INPUT;
4977 return bar;
4981 #ifndef USE_TOOLKIT_SCROLL_BARS
4983 /* Draw BAR's handle in the proper position.
4985 If the handle is already drawn from START to END, don't bother
4986 redrawing it, unless REBUILD is non-zero; in that case, always
4987 redraw it. (REBUILD is handy for drawing the handle after expose
4988 events.)
4990 Normally, we want to constrain the start and end of the handle to
4991 fit inside its rectangle, but if the user is dragging the scroll
4992 bar handle, we want to let them drag it down all the way, so that
4993 the bar's top is as far down as it goes; otherwise, there's no way
4994 to move to the very end of the buffer. */
4996 static void
4997 x_scroll_bar_set_handle (struct scroll_bar *bar, int start, int end, int rebuild)
4999 int dragging = ! NILP (bar->dragging);
5000 Window w = bar->x_window;
5001 FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5002 GC gc = f->output_data.x->normal_gc;
5004 /* If the display is already accurate, do nothing. */
5005 if (! rebuild
5006 && start == bar->start
5007 && end == bar->end)
5008 return;
5010 BLOCK_INPUT;
5013 int inside_width = VERTICAL_SCROLL_BAR_INSIDE_WIDTH (f, bar->width);
5014 int inside_height = VERTICAL_SCROLL_BAR_INSIDE_HEIGHT (f, bar->height);
5015 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
5017 /* Make sure the values are reasonable, and try to preserve
5018 the distance between start and end. */
5020 int length = end - start;
5022 if (start < 0)
5023 start = 0;
5024 else if (start > top_range)
5025 start = top_range;
5026 end = start + length;
5028 if (end < start)
5029 end = start;
5030 else if (end > top_range && ! dragging)
5031 end = top_range;
5034 /* Store the adjusted setting in the scroll bar. */
5035 bar->start = start;
5036 bar->end = end;
5038 /* Clip the end position, just for display. */
5039 if (end > top_range)
5040 end = top_range;
5042 /* Draw bottom positions VERTICAL_SCROLL_BAR_MIN_HANDLE pixels
5043 below top positions, to make sure the handle is always at least
5044 that many pixels tall. */
5045 end += VERTICAL_SCROLL_BAR_MIN_HANDLE;
5047 /* Draw the empty space above the handle. Note that we can't clear
5048 zero-height areas; that means "clear to end of window." */
5049 if (0 < start)
5050 x_clear_area (FRAME_X_DISPLAY (f), w,
5051 /* x, y, width, height, and exposures. */
5052 VERTICAL_SCROLL_BAR_LEFT_BORDER,
5053 VERTICAL_SCROLL_BAR_TOP_BORDER,
5054 inside_width, start,
5055 False);
5057 /* Change to proper foreground color if one is specified. */
5058 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5059 XSetForeground (FRAME_X_DISPLAY (f), gc,
5060 f->output_data.x->scroll_bar_foreground_pixel);
5062 /* Draw the handle itself. */
5063 XFillRectangle (FRAME_X_DISPLAY (f), w, gc,
5064 /* x, y, width, height */
5065 VERTICAL_SCROLL_BAR_LEFT_BORDER,
5066 VERTICAL_SCROLL_BAR_TOP_BORDER + start,
5067 inside_width, end - start);
5069 /* Restore the foreground color of the GC if we changed it above. */
5070 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5071 XSetForeground (FRAME_X_DISPLAY (f), gc,
5072 FRAME_FOREGROUND_PIXEL (f));
5074 /* Draw the empty space below the handle. Note that we can't
5075 clear zero-height areas; that means "clear to end of window." */
5076 if (end < inside_height)
5077 x_clear_area (FRAME_X_DISPLAY (f), w,
5078 /* x, y, width, height, and exposures. */
5079 VERTICAL_SCROLL_BAR_LEFT_BORDER,
5080 VERTICAL_SCROLL_BAR_TOP_BORDER + end,
5081 inside_width, inside_height - end,
5082 False);
5086 UNBLOCK_INPUT;
5089 #endif /* !USE_TOOLKIT_SCROLL_BARS */
5091 /* Destroy scroll bar BAR, and set its Emacs window's scroll bar to
5092 nil. */
5094 static void
5095 x_scroll_bar_remove (struct scroll_bar *bar)
5097 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5098 BLOCK_INPUT;
5100 #ifdef USE_TOOLKIT_SCROLL_BARS
5101 #ifdef USE_GTK
5102 xg_remove_scroll_bar (f, bar->x_window);
5103 #else /* not USE_GTK */
5104 XtDestroyWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar));
5105 #endif /* not USE_GTK */
5106 #else
5107 XDestroyWindow (FRAME_X_DISPLAY (f), bar->x_window);
5108 #endif
5110 /* Disassociate this scroll bar from its window. */
5111 XWINDOW (bar->window)->vertical_scroll_bar = Qnil;
5113 UNBLOCK_INPUT;
5117 /* Set the handle of the vertical scroll bar for WINDOW to indicate
5118 that we are displaying PORTION characters out of a total of WHOLE
5119 characters, starting at POSITION. If WINDOW has no scroll bar,
5120 create one. */
5122 static void
5123 XTset_vertical_scroll_bar (struct window *w, int portion, int whole, int position)
5125 struct frame *f = XFRAME (w->frame);
5126 struct scroll_bar *bar;
5127 int top, height, left, sb_left, width, sb_width;
5128 int window_y, window_height;
5129 #ifdef USE_TOOLKIT_SCROLL_BARS
5130 int fringe_extended_p;
5131 #endif
5133 /* Get window dimensions. */
5134 window_box (w, -1, 0, &window_y, 0, &window_height);
5135 top = window_y;
5136 width = WINDOW_CONFIG_SCROLL_BAR_COLS (w) * FRAME_COLUMN_WIDTH (f);
5137 height = window_height;
5139 /* Compute the left edge of the scroll bar area. */
5140 left = WINDOW_SCROLL_BAR_AREA_X (w);
5142 /* Compute the width of the scroll bar which might be less than
5143 the width of the area reserved for the scroll bar. */
5144 if (WINDOW_CONFIG_SCROLL_BAR_WIDTH (w) > 0)
5145 sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
5146 else
5147 sb_width = width;
5149 /* Compute the left edge of the scroll bar. */
5150 #ifdef USE_TOOLKIT_SCROLL_BARS
5151 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w))
5152 sb_left = left + (WINDOW_RIGHTMOST_P (w) ? width - sb_width : 0);
5153 else
5154 sb_left = left + (WINDOW_LEFTMOST_P (w) ? 0 : width - sb_width);
5155 #else
5156 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w))
5157 sb_left = left + width - sb_width;
5158 else
5159 sb_left = left;
5160 #endif
5162 #ifdef USE_TOOLKIT_SCROLL_BARS
5163 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
5164 fringe_extended_p = (WINDOW_LEFTMOST_P (w)
5165 && WINDOW_LEFT_FRINGE_WIDTH (w)
5166 && (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (w)
5167 || WINDOW_LEFT_MARGIN_COLS (w) == 0));
5168 else
5169 fringe_extended_p = (WINDOW_RIGHTMOST_P (w)
5170 && WINDOW_RIGHT_FRINGE_WIDTH (w)
5171 && (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (w)
5172 || WINDOW_RIGHT_MARGIN_COLS (w) == 0));
5173 #endif
5175 /* Does the scroll bar exist yet? */
5176 if (NILP (w->vertical_scroll_bar))
5178 if (width > 0 && height > 0)
5180 BLOCK_INPUT;
5181 #ifdef USE_TOOLKIT_SCROLL_BARS
5182 if (fringe_extended_p)
5183 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5184 sb_left, top, sb_width, height, False);
5185 else
5186 #endif
5187 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5188 left, top, width, height, False);
5189 UNBLOCK_INPUT;
5192 bar = x_scroll_bar_create (w, top, sb_left, sb_width, height);
5194 else
5196 /* It may just need to be moved and resized. */
5197 unsigned int mask = 0;
5199 bar = XSCROLL_BAR (w->vertical_scroll_bar);
5201 BLOCK_INPUT;
5203 if (sb_left != bar->left)
5204 mask |= CWX;
5205 if (top != bar->top)
5206 mask |= CWY;
5207 if (sb_width != bar->width)
5208 mask |= CWWidth;
5209 if (height != bar->height)
5210 mask |= CWHeight;
5212 #ifdef USE_TOOLKIT_SCROLL_BARS
5214 /* Move/size the scroll bar widget. */
5215 if (mask || bar->fringe_extended_p != fringe_extended_p)
5217 /* Since toolkit scroll bars are smaller than the space reserved
5218 for them on the frame, we have to clear "under" them. */
5219 if (width > 0 && height > 0)
5221 if (fringe_extended_p)
5222 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5223 sb_left, top, sb_width, height, False);
5224 else
5225 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5226 left, top, width, height, False);
5228 #ifdef USE_GTK
5229 xg_update_scrollbar_pos (f,
5230 bar->x_window,
5231 top,
5232 sb_left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5233 sb_width - VERTICAL_SCROLL_BAR_WIDTH_TRIM *2,
5234 max (height, 1));
5235 #else /* not USE_GTK */
5236 XtConfigureWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar),
5237 sb_left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5238 top,
5239 sb_width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
5240 max (height, 1), 0);
5241 #endif /* not USE_GTK */
5243 #else /* not USE_TOOLKIT_SCROLL_BARS */
5245 /* Clear areas not covered by the scroll bar because of
5246 VERTICAL_SCROLL_BAR_WIDTH_TRIM. */
5247 if (VERTICAL_SCROLL_BAR_WIDTH_TRIM)
5249 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5250 left, top, VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5251 height, False);
5252 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5253 left + width - VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5254 top, VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5255 height, False);
5258 /* Clear areas not covered by the scroll bar because it's not as
5259 wide as the area reserved for it. This makes sure a
5260 previous mode line display is cleared after C-x 2 C-x 1, for
5261 example. */
5263 int area_width = WINDOW_CONFIG_SCROLL_BAR_COLS (w) * FRAME_COLUMN_WIDTH (f);
5264 int rest = area_width - sb_width;
5265 if (rest > 0 && height > 0)
5267 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
5268 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5269 left + area_width - rest, top,
5270 rest, height, False);
5271 else
5272 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5273 left, top, rest, height, False);
5277 /* Move/size the scroll bar window. */
5278 if (mask)
5280 XWindowChanges wc;
5282 wc.x = sb_left + VERTICAL_SCROLL_BAR_WIDTH_TRIM;
5283 wc.y = top;
5284 wc.width = sb_width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2;
5285 wc.height = height;
5286 XConfigureWindow (FRAME_X_DISPLAY (f), bar->x_window,
5287 mask, &wc);
5290 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5292 /* Remember new settings. */
5293 bar->left = sb_left;
5294 bar->top = top;
5295 bar->width = sb_width;
5296 bar->height = height;
5298 UNBLOCK_INPUT;
5301 #ifdef USE_TOOLKIT_SCROLL_BARS
5302 bar->fringe_extended_p = fringe_extended_p;
5304 x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
5305 #else /* not USE_TOOLKIT_SCROLL_BARS */
5306 /* Set the scroll bar's current state, unless we're currently being
5307 dragged. */
5308 if (NILP (bar->dragging))
5310 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, height);
5312 if (whole == 0)
5313 x_scroll_bar_set_handle (bar, 0, top_range, 0);
5314 else
5316 int start = ((double) position * top_range) / whole;
5317 int end = ((double) (position + portion) * top_range) / whole;
5318 x_scroll_bar_set_handle (bar, start, end, 0);
5321 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5323 XSETVECTOR (w->vertical_scroll_bar, bar);
5327 /* The following three hooks are used when we're doing a thorough
5328 redisplay of the frame. We don't explicitly know which scroll bars
5329 are going to be deleted, because keeping track of when windows go
5330 away is a real pain - "Can you say set-window-configuration, boys
5331 and girls?" Instead, we just assert at the beginning of redisplay
5332 that *all* scroll bars are to be removed, and then save a scroll bar
5333 from the fiery pit when we actually redisplay its window. */
5335 /* Arrange for all scroll bars on FRAME to be removed at the next call
5336 to `*judge_scroll_bars_hook'. A scroll bar may be spared if
5337 `*redeem_scroll_bar_hook' is applied to its window before the judgment. */
5339 static void
5340 XTcondemn_scroll_bars (FRAME_PTR frame)
5342 /* Transfer all the scroll bars to FRAME_CONDEMNED_SCROLL_BARS. */
5343 while (! NILP (FRAME_SCROLL_BARS (frame)))
5345 Lisp_Object bar;
5346 bar = FRAME_SCROLL_BARS (frame);
5347 FRAME_SCROLL_BARS (frame) = XSCROLL_BAR (bar)->next;
5348 XSCROLL_BAR (bar)->next = FRAME_CONDEMNED_SCROLL_BARS (frame);
5349 XSCROLL_BAR (bar)->prev = Qnil;
5350 if (! NILP (FRAME_CONDEMNED_SCROLL_BARS (frame)))
5351 XSCROLL_BAR (FRAME_CONDEMNED_SCROLL_BARS (frame))->prev = bar;
5352 FRAME_CONDEMNED_SCROLL_BARS (frame) = bar;
5357 /* Un-mark WINDOW's scroll bar for deletion in this judgment cycle.
5358 Note that WINDOW isn't necessarily condemned at all. */
5360 static void
5361 XTredeem_scroll_bar (struct window *window)
5363 struct scroll_bar *bar;
5364 struct frame *f;
5366 /* We can't redeem this window's scroll bar if it doesn't have one. */
5367 if (NILP (window->vertical_scroll_bar))
5368 abort ();
5370 bar = XSCROLL_BAR (window->vertical_scroll_bar);
5372 /* Unlink it from the condemned list. */
5373 f = XFRAME (WINDOW_FRAME (window));
5374 if (NILP (bar->prev))
5376 /* If the prev pointer is nil, it must be the first in one of
5377 the lists. */
5378 if (EQ (FRAME_SCROLL_BARS (f), window->vertical_scroll_bar))
5379 /* It's not condemned. Everything's fine. */
5380 return;
5381 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
5382 window->vertical_scroll_bar))
5383 FRAME_CONDEMNED_SCROLL_BARS (f) = bar->next;
5384 else
5385 /* If its prev pointer is nil, it must be at the front of
5386 one or the other! */
5387 abort ();
5389 else
5390 XSCROLL_BAR (bar->prev)->next = bar->next;
5392 if (! NILP (bar->next))
5393 XSCROLL_BAR (bar->next)->prev = bar->prev;
5395 bar->next = FRAME_SCROLL_BARS (f);
5396 bar->prev = Qnil;
5397 XSETVECTOR (FRAME_SCROLL_BARS (f), bar);
5398 if (! NILP (bar->next))
5399 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
5402 /* Remove all scroll bars on FRAME that haven't been saved since the
5403 last call to `*condemn_scroll_bars_hook'. */
5405 static void
5406 XTjudge_scroll_bars (FRAME_PTR f)
5408 Lisp_Object bar, next;
5410 bar = FRAME_CONDEMNED_SCROLL_BARS (f);
5412 /* Clear out the condemned list now so we won't try to process any
5413 more events on the hapless scroll bars. */
5414 FRAME_CONDEMNED_SCROLL_BARS (f) = Qnil;
5416 for (; ! NILP (bar); bar = next)
5418 struct scroll_bar *b = XSCROLL_BAR (bar);
5420 x_scroll_bar_remove (b);
5422 next = b->next;
5423 b->next = b->prev = Qnil;
5426 /* Now there should be no references to the condemned scroll bars,
5427 and they should get garbage-collected. */
5431 #ifndef USE_TOOLKIT_SCROLL_BARS
5432 /* Handle an Expose or GraphicsExpose event on a scroll bar. This
5433 is a no-op when using toolkit scroll bars.
5435 This may be called from a signal handler, so we have to ignore GC
5436 mark bits. */
5438 static void
5439 x_scroll_bar_expose (struct scroll_bar *bar, XEvent *event)
5441 Window w = bar->x_window;
5442 FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5443 GC gc = f->output_data.x->normal_gc;
5444 int width_trim = VERTICAL_SCROLL_BAR_WIDTH_TRIM;
5446 BLOCK_INPUT;
5448 x_scroll_bar_set_handle (bar, bar->start, bar->end, 1);
5450 /* Switch to scroll bar foreground color. */
5451 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5452 XSetForeground (FRAME_X_DISPLAY (f), gc,
5453 f->output_data.x->scroll_bar_foreground_pixel);
5455 /* Draw a one-pixel border just inside the edges of the scroll bar. */
5456 XDrawRectangle (FRAME_X_DISPLAY (f), w, gc,
5458 /* x, y, width, height */
5459 0, 0,
5460 bar->width - 1 - width_trim - width_trim,
5461 bar->height - 1);
5463 /* Restore the foreground color of the GC if we changed it above. */
5464 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5465 XSetForeground (FRAME_X_DISPLAY (f), gc,
5466 FRAME_FOREGROUND_PIXEL (f));
5468 UNBLOCK_INPUT;
5471 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5473 /* Handle a mouse click on the scroll bar BAR. If *EMACS_EVENT's kind
5474 is set to something other than NO_EVENT, it is enqueued.
5476 This may be called from a signal handler, so we have to ignore GC
5477 mark bits. */
5480 static void
5481 x_scroll_bar_handle_click (struct scroll_bar *bar, XEvent *event, struct input_event *emacs_event)
5483 if (! WINDOWP (bar->window))
5484 abort ();
5486 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
5487 emacs_event->code = event->xbutton.button - Button1;
5488 emacs_event->modifiers
5489 = (x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO
5490 (XFRAME (WINDOW_FRAME (XWINDOW (bar->window)))),
5491 event->xbutton.state)
5492 | (event->type == ButtonRelease
5493 ? up_modifier
5494 : down_modifier));
5495 emacs_event->frame_or_window = bar->window;
5496 emacs_event->arg = Qnil;
5497 emacs_event->timestamp = event->xbutton.time;
5499 int top_range
5500 = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
5501 int y = event->xbutton.y - VERTICAL_SCROLL_BAR_TOP_BORDER;
5503 if (y < 0) y = 0;
5504 if (y > top_range) y = top_range;
5506 if (y < bar->start)
5507 emacs_event->part = scroll_bar_above_handle;
5508 else if (y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
5509 emacs_event->part = scroll_bar_handle;
5510 else
5511 emacs_event->part = scroll_bar_below_handle;
5513 #ifndef USE_TOOLKIT_SCROLL_BARS
5514 /* If the user has released the handle, set it to its final position. */
5515 if (event->type == ButtonRelease
5516 && ! NILP (bar->dragging))
5518 int new_start = y - XINT (bar->dragging);
5519 int new_end = new_start + bar->end - bar->start;
5521 x_scroll_bar_set_handle (bar, new_start, new_end, 0);
5522 bar->dragging = Qnil;
5524 #endif
5526 XSETINT (emacs_event->x, y);
5527 XSETINT (emacs_event->y, top_range);
5531 #ifndef USE_TOOLKIT_SCROLL_BARS
5533 /* Handle some mouse motion while someone is dragging the scroll bar.
5535 This may be called from a signal handler, so we have to ignore GC
5536 mark bits. */
5538 static void
5539 x_scroll_bar_note_movement (struct scroll_bar *bar, XEvent *event)
5541 FRAME_PTR f = XFRAME (XWINDOW (bar->window)->frame);
5543 last_mouse_movement_time = event->xmotion.time;
5545 f->mouse_moved = 1;
5546 XSETVECTOR (last_mouse_scroll_bar, bar);
5548 /* If we're dragging the bar, display it. */
5549 if (! NILP (bar->dragging))
5551 /* Where should the handle be now? */
5552 int new_start = event->xmotion.y - XINT (bar->dragging);
5554 if (new_start != bar->start)
5556 int new_end = new_start + bar->end - bar->start;
5558 x_scroll_bar_set_handle (bar, new_start, new_end, 0);
5563 #endif /* !USE_TOOLKIT_SCROLL_BARS */
5565 /* Return information to the user about the current position of the mouse
5566 on the scroll bar. */
5568 static void
5569 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)
5571 struct scroll_bar *bar = XSCROLL_BAR (last_mouse_scroll_bar);
5572 Window w = bar->x_window;
5573 FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5574 int win_x, win_y;
5575 Window dummy_window;
5576 int dummy_coord;
5577 unsigned int dummy_mask;
5579 BLOCK_INPUT;
5581 /* Get the mouse's position relative to the scroll bar window, and
5582 report that. */
5583 if (! XQueryPointer (FRAME_X_DISPLAY (f), w,
5585 /* Root, child, root x and root y. */
5586 &dummy_window, &dummy_window,
5587 &dummy_coord, &dummy_coord,
5589 /* Position relative to scroll bar. */
5590 &win_x, &win_y,
5592 /* Mouse buttons and modifier keys. */
5593 &dummy_mask))
5595 else
5597 int top_range
5598 = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
5600 win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
5602 if (! NILP (bar->dragging))
5603 win_y -= XINT (bar->dragging);
5605 if (win_y < 0)
5606 win_y = 0;
5607 if (win_y > top_range)
5608 win_y = top_range;
5610 *fp = f;
5611 *bar_window = bar->window;
5613 if (! NILP (bar->dragging))
5614 *part = scroll_bar_handle;
5615 else if (win_y < bar->start)
5616 *part = scroll_bar_above_handle;
5617 else if (win_y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
5618 *part = scroll_bar_handle;
5619 else
5620 *part = scroll_bar_below_handle;
5622 XSETINT (*x, win_y);
5623 XSETINT (*y, top_range);
5625 f->mouse_moved = 0;
5626 last_mouse_scroll_bar = Qnil;
5629 *time = last_mouse_movement_time;
5631 UNBLOCK_INPUT;
5635 /* The screen has been cleared so we may have changed foreground or
5636 background colors, and the scroll bars may need to be redrawn.
5637 Clear out the scroll bars, and ask for expose events, so we can
5638 redraw them. */
5640 static void
5641 x_scroll_bar_clear (FRAME_PTR f)
5643 #ifndef USE_TOOLKIT_SCROLL_BARS
5644 Lisp_Object bar;
5646 /* We can have scroll bars even if this is 0,
5647 if we just turned off scroll bar mode.
5648 But in that case we should not clear them. */
5649 if (FRAME_HAS_VERTICAL_SCROLL_BARS (f))
5650 for (bar = FRAME_SCROLL_BARS (f); VECTORP (bar);
5651 bar = XSCROLL_BAR (bar)->next)
5652 XClearArea (FRAME_X_DISPLAY (f),
5653 XSCROLL_BAR (bar)->x_window,
5654 0, 0, 0, 0, True);
5655 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5659 /* The main X event-reading loop - XTread_socket. */
5661 /* This holds the state XLookupString needs to implement dead keys
5662 and other tricks known as "compose processing". _X Window System_
5663 says that a portable program can't use this, but Stephen Gildea assures
5664 me that letting the compiler initialize it to zeros will work okay.
5666 This must be defined outside of XTread_socket, for the same reasons
5667 given for enter_timestamp, above. */
5669 static XComposeStatus compose_status;
5671 /* Record the last 100 characters stored
5672 to help debug the loss-of-chars-during-GC problem. */
5674 static int temp_index;
5675 static short temp_buffer[100];
5677 #define STORE_KEYSYM_FOR_DEBUG(keysym) \
5678 if (temp_index == sizeof temp_buffer / sizeof (short)) \
5679 temp_index = 0; \
5680 temp_buffer[temp_index++] = (keysym)
5682 /* Set this to nonzero to fake an "X I/O error"
5683 on a particular display. */
5685 struct x_display_info *XTread_socket_fake_io_error;
5687 /* When we find no input here, we occasionally do a no-op command
5688 to verify that the X server is still running and we can still talk with it.
5689 We try all the open displays, one by one.
5690 This variable is used for cycling thru the displays. */
5692 static struct x_display_info *next_noop_dpyinfo;
5694 #define SET_SAVED_BUTTON_EVENT \
5695 do \
5697 if (f->output_data.x->saved_menu_event == 0) \
5698 f->output_data.x->saved_menu_event \
5699 = (XEvent *) xmalloc (sizeof (XEvent)); \
5700 *f->output_data.x->saved_menu_event = event; \
5701 inev.ie.kind = MENU_BAR_ACTIVATE_EVENT; \
5702 XSETFRAME (inev.ie.frame_or_window, f); \
5704 while (0)
5706 enum
5708 X_EVENT_NORMAL,
5709 X_EVENT_GOTO_OUT,
5710 X_EVENT_DROP
5713 /* Filter events for the current X input method.
5714 DPYINFO is the display this event is for.
5715 EVENT is the X event to filter.
5717 Returns non-zero if the event was filtered, caller shall not process
5718 this event further.
5719 Returns zero if event is wasn't filtered. */
5721 #ifdef HAVE_X_I18N
5722 static int
5723 x_filter_event (struct x_display_info *dpyinfo, XEvent *event)
5725 /* XFilterEvent returns non-zero if the input method has
5726 consumed the event. We pass the frame's X window to
5727 XFilterEvent because that's the one for which the IC
5728 was created. */
5730 struct frame *f1 = x_any_window_to_frame (dpyinfo,
5731 event->xclient.window);
5733 return XFilterEvent (event, f1 ? FRAME_X_WINDOW (f1) : None);
5735 #endif
5737 #ifdef USE_GTK
5738 static int current_count;
5739 static int current_finish;
5740 static struct input_event *current_hold_quit;
5742 /* This is the filter function invoked by the GTK event loop.
5743 It is invoked before the XEvent is translated to a GdkEvent,
5744 so we have a chance to act on the event before GTK. */
5745 static GdkFilterReturn
5746 event_handler_gdk (GdkXEvent *gxev, GdkEvent *ev, gpointer data)
5748 XEvent *xev = (XEvent *) gxev;
5750 BLOCK_INPUT;
5751 if (current_count >= 0)
5753 struct x_display_info *dpyinfo;
5755 dpyinfo = x_display_info_for_display (xev->xany.display);
5757 #ifdef HAVE_X_I18N
5758 /* Filter events for the current X input method.
5759 GTK calls XFilterEvent but not for key press and release,
5760 so we do it here. */
5761 if ((xev->type == KeyPress || xev->type == KeyRelease)
5762 && dpyinfo
5763 && x_filter_event (dpyinfo, xev))
5765 UNBLOCK_INPUT;
5766 return GDK_FILTER_REMOVE;
5768 #endif
5770 if (! dpyinfo)
5771 current_finish = X_EVENT_NORMAL;
5772 else
5773 current_count +=
5774 handle_one_xevent (dpyinfo, xev, &current_finish,
5775 current_hold_quit);
5777 else
5778 current_finish = x_dispatch_event (xev, xev->xany.display);
5780 UNBLOCK_INPUT;
5782 if (current_finish == X_EVENT_GOTO_OUT || current_finish == X_EVENT_DROP)
5783 return GDK_FILTER_REMOVE;
5785 return GDK_FILTER_CONTINUE;
5787 #endif /* USE_GTK */
5790 static void xembed_send_message (struct frame *f, Time time,
5791 enum xembed_message message,
5792 long detail, long data1, long data2);
5794 /* Handles the XEvent EVENT on display DPYINFO.
5796 *FINISH is X_EVENT_GOTO_OUT if caller should stop reading events.
5797 *FINISH is zero if caller should continue reading events.
5798 *FINISH is X_EVENT_DROP if event should not be passed to the toolkit.
5800 We return the number of characters stored into the buffer. */
5802 static int
5803 handle_one_xevent (struct x_display_info *dpyinfo, XEvent *eventp, int *finish, struct input_event *hold_quit)
5805 union {
5806 struct input_event ie;
5807 struct selection_input_event sie;
5808 } inev;
5809 int count = 0;
5810 int do_help = 0;
5811 int nbytes = 0;
5812 struct frame *f = NULL;
5813 struct coding_system coding;
5814 XEvent event = *eventp;
5815 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
5817 *finish = X_EVENT_NORMAL;
5819 EVENT_INIT (inev.ie);
5820 inev.ie.kind = NO_EVENT;
5821 inev.ie.arg = Qnil;
5823 if (pending_event_wait.eventtype == event.type)
5824 pending_event_wait.eventtype = 0; /* Indicates we got it. */
5826 switch (event.type)
5828 case ClientMessage:
5830 if (event.xclient.message_type
5831 == dpyinfo->Xatom_wm_protocols
5832 && event.xclient.format == 32)
5834 if (event.xclient.data.l[0]
5835 == dpyinfo->Xatom_wm_take_focus)
5837 /* Use x_any_window_to_frame because this
5838 could be the shell widget window
5839 if the frame has no title bar. */
5840 f = x_any_window_to_frame (dpyinfo, event.xclient.window);
5841 #ifdef HAVE_X_I18N
5842 /* Not quite sure this is needed -pd */
5843 if (f && FRAME_XIC (f))
5844 XSetICFocus (FRAME_XIC (f));
5845 #endif
5846 #if 0 /* Emacs sets WM hints whose `input' field is `true'. This
5847 instructs the WM to set the input focus automatically for
5848 Emacs with a call to XSetInputFocus. Setting WM_TAKE_FOCUS
5849 tells the WM to send us a ClientMessage WM_TAKE_FOCUS after
5850 it has set the focus. So, XSetInputFocus below is not
5851 needed.
5853 The call to XSetInputFocus below has also caused trouble. In
5854 cases where the XSetInputFocus done by the WM and the one
5855 below are temporally close (on a fast machine), the call
5856 below can generate additional FocusIn events which confuse
5857 Emacs. */
5859 /* Since we set WM_TAKE_FOCUS, we must call
5860 XSetInputFocus explicitly. But not if f is null,
5861 since that might be an event for a deleted frame. */
5862 if (f)
5864 Display *d = event.xclient.display;
5865 /* Catch and ignore errors, in case window has been
5866 iconified by a window manager such as GWM. */
5867 x_catch_errors (d);
5868 XSetInputFocus (d, event.xclient.window,
5869 /* The ICCCM says this is
5870 the only valid choice. */
5871 RevertToParent,
5872 event.xclient.data.l[1]);
5873 /* This is needed to detect the error
5874 if there is an error. */
5875 XSync (d, False);
5876 x_uncatch_errors ();
5878 /* Not certain about handling scroll bars here */
5879 #endif /* 0 */
5880 goto done;
5883 if (event.xclient.data.l[0]
5884 == dpyinfo->Xatom_wm_save_yourself)
5886 /* Save state modify the WM_COMMAND property to
5887 something which can reinstate us. This notifies
5888 the session manager, who's looking for such a
5889 PropertyNotify. Can restart processing when
5890 a keyboard or mouse event arrives. */
5891 /* If we have a session manager, don't set this.
5892 KDE will then start two Emacsen, one for the
5893 session manager and one for this. */
5894 #ifdef HAVE_X_SM
5895 if (! x_session_have_connection ())
5896 #endif
5898 f = x_top_window_to_frame (dpyinfo,
5899 event.xclient.window);
5900 /* This is just so we only give real data once
5901 for a single Emacs process. */
5902 if (f == SELECTED_FRAME ())
5903 XSetCommand (FRAME_X_DISPLAY (f),
5904 event.xclient.window,
5905 initial_argv, initial_argc);
5906 else if (f)
5907 XSetCommand (FRAME_X_DISPLAY (f),
5908 event.xclient.window,
5909 0, 0);
5911 goto done;
5914 if (event.xclient.data.l[0]
5915 == dpyinfo->Xatom_wm_delete_window)
5917 f = x_any_window_to_frame (dpyinfo,
5918 event.xclient.window);
5919 if (!f)
5920 goto OTHER; /* May be a dialog that is to be removed */
5922 inev.ie.kind = DELETE_WINDOW_EVENT;
5923 XSETFRAME (inev.ie.frame_or_window, f);
5924 goto done;
5927 goto done;
5930 if (event.xclient.message_type
5931 == dpyinfo->Xatom_wm_configure_denied)
5933 goto done;
5936 if (event.xclient.message_type
5937 == dpyinfo->Xatom_wm_window_moved)
5939 int new_x, new_y;
5940 f = x_window_to_frame (dpyinfo, event.xclient.window);
5942 new_x = event.xclient.data.s[0];
5943 new_y = event.xclient.data.s[1];
5945 if (f)
5947 f->left_pos = new_x;
5948 f->top_pos = new_y;
5950 goto done;
5953 #ifdef HACK_EDITRES
5954 if (event.xclient.message_type
5955 == dpyinfo->Xatom_editres)
5957 f = x_any_window_to_frame (dpyinfo, event.xclient.window);
5958 if (f)
5959 _XEditResCheckMessages (f->output_data.x->widget, NULL,
5960 &event, NULL);
5961 goto done;
5963 #endif /* HACK_EDITRES */
5965 if ((event.xclient.message_type
5966 == dpyinfo->Xatom_DONE)
5967 || (event.xclient.message_type
5968 == dpyinfo->Xatom_PAGE))
5970 /* Ghostview job completed. Kill it. We could
5971 reply with "Next" if we received "Page", but we
5972 currently never do because we are interested in
5973 images, only, which should have 1 page. */
5974 Pixmap pixmap = (Pixmap) event.xclient.data.l[1];
5975 f = x_window_to_frame (dpyinfo, event.xclient.window);
5976 if (!f)
5977 goto OTHER;
5978 x_kill_gs_process (pixmap, f);
5979 expose_frame (f, 0, 0, 0, 0);
5980 goto done;
5983 #ifdef USE_TOOLKIT_SCROLL_BARS
5984 /* Scroll bar callbacks send a ClientMessage from which
5985 we construct an input_event. */
5986 if (event.xclient.message_type
5987 == dpyinfo->Xatom_Scrollbar)
5989 x_scroll_bar_to_input_event (&event, &inev.ie);
5990 *finish = X_EVENT_GOTO_OUT;
5991 goto done;
5993 #endif /* USE_TOOLKIT_SCROLL_BARS */
5995 /* XEmbed messages from the embedder (if any). */
5996 if (event.xclient.message_type
5997 == dpyinfo->Xatom_XEMBED)
5999 enum xembed_message msg = event.xclient.data.l[1];
6000 if (msg == XEMBED_FOCUS_IN || msg == XEMBED_FOCUS_OUT)
6001 x_detect_focus_change (dpyinfo, &event, &inev.ie);
6003 *finish = X_EVENT_GOTO_OUT;
6004 goto done;
6007 xft_settings_event (dpyinfo, &event);
6009 f = x_any_window_to_frame (dpyinfo, event.xclient.window);
6010 if (!f)
6011 goto OTHER;
6012 if (x_handle_dnd_message (f, &event.xclient, dpyinfo, &inev.ie))
6013 *finish = X_EVENT_DROP;
6015 break;
6017 case SelectionNotify:
6018 last_user_time = event.xselection.time;
6019 #ifdef USE_X_TOOLKIT
6020 if (! x_window_to_frame (dpyinfo, event.xselection.requestor))
6021 goto OTHER;
6022 #endif /* not USE_X_TOOLKIT */
6023 x_handle_selection_notify (&event.xselection);
6024 break;
6026 case SelectionClear: /* Someone has grabbed ownership. */
6027 last_user_time = event.xselectionclear.time;
6028 #ifdef USE_X_TOOLKIT
6029 if (! x_window_to_frame (dpyinfo, event.xselectionclear.window))
6030 goto OTHER;
6031 #endif /* USE_X_TOOLKIT */
6033 XSelectionClearEvent *eventp = (XSelectionClearEvent *) &event;
6035 inev.ie.kind = SELECTION_CLEAR_EVENT;
6036 SELECTION_EVENT_DISPLAY (&inev.sie) = eventp->display;
6037 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
6038 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
6039 inev.ie.frame_or_window = Qnil;
6041 break;
6043 case SelectionRequest: /* Someone wants our selection. */
6044 last_user_time = event.xselectionrequest.time;
6045 #ifdef USE_X_TOOLKIT
6046 if (!x_window_to_frame (dpyinfo, event.xselectionrequest.owner))
6047 goto OTHER;
6048 #endif /* USE_X_TOOLKIT */
6050 XSelectionRequestEvent *eventp
6051 = (XSelectionRequestEvent *) &event;
6053 inev.ie.kind = SELECTION_REQUEST_EVENT;
6054 SELECTION_EVENT_DISPLAY (&inev.sie) = eventp->display;
6055 SELECTION_EVENT_REQUESTOR (&inev.sie) = eventp->requestor;
6056 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
6057 SELECTION_EVENT_TARGET (&inev.sie) = eventp->target;
6058 SELECTION_EVENT_PROPERTY (&inev.sie) = eventp->property;
6059 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
6060 inev.ie.frame_or_window = Qnil;
6062 break;
6064 case PropertyNotify:
6065 last_user_time = event.xproperty.time;
6066 f = x_top_window_to_frame (dpyinfo, event.xproperty.window);
6067 if (f && event.xproperty.atom == dpyinfo->Xatom_net_wm_state)
6068 x_handle_net_wm_state (f, &event.xproperty);
6070 x_handle_property_notify (&event.xproperty);
6071 xft_settings_event (dpyinfo, &event);
6072 goto OTHER;
6074 case ReparentNotify:
6075 f = x_top_window_to_frame (dpyinfo, event.xreparent.window);
6076 if (f)
6078 int x, y;
6079 f->output_data.x->parent_desc = event.xreparent.parent;
6080 x_real_positions (f, &x, &y);
6081 f->left_pos = x;
6082 f->top_pos = y;
6084 /* Perhaps reparented due to a WM restart. Reset this. */
6085 FRAME_X_DISPLAY_INFO (f)->wm_type = X_WMTYPE_UNKNOWN;
6086 FRAME_X_DISPLAY_INFO (f)->net_supported_window = 0;
6088 goto OTHER;
6090 case Expose:
6091 f = x_window_to_frame (dpyinfo, event.xexpose.window);
6092 if (f)
6094 #ifdef USE_GTK
6095 /* This seems to be needed for GTK 2.6. */
6096 x_clear_area (event.xexpose.display,
6097 event.xexpose.window,
6098 event.xexpose.x, event.xexpose.y,
6099 event.xexpose.width, event.xexpose.height,
6100 FALSE);
6101 #endif
6102 if (f->async_visible == 0)
6104 f->async_visible = 1;
6105 f->async_iconified = 0;
6106 f->output_data.x->has_been_visible = 1;
6107 SET_FRAME_GARBAGED (f);
6109 else
6110 expose_frame (f,
6111 event.xexpose.x, event.xexpose.y,
6112 event.xexpose.width, event.xexpose.height);
6114 else
6116 #ifndef USE_TOOLKIT_SCROLL_BARS
6117 struct scroll_bar *bar;
6118 #endif
6119 #if defined USE_LUCID
6120 /* Submenus of the Lucid menu bar aren't widgets
6121 themselves, so there's no way to dispatch events
6122 to them. Recognize this case separately. */
6124 Widget widget
6125 = x_window_to_menu_bar (event.xexpose.window);
6126 if (widget)
6127 xlwmenu_redisplay (widget);
6129 #endif /* USE_LUCID */
6131 #ifdef USE_TOOLKIT_SCROLL_BARS
6132 /* Dispatch event to the widget. */
6133 goto OTHER;
6134 #else /* not USE_TOOLKIT_SCROLL_BARS */
6135 bar = x_window_to_scroll_bar (event.xexpose.display,
6136 event.xexpose.window);
6138 if (bar)
6139 x_scroll_bar_expose (bar, &event);
6140 #ifdef USE_X_TOOLKIT
6141 else
6142 goto OTHER;
6143 #endif /* USE_X_TOOLKIT */
6144 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6146 break;
6148 case GraphicsExpose: /* This occurs when an XCopyArea's
6149 source area was obscured or not
6150 available. */
6151 f = x_window_to_frame (dpyinfo, event.xgraphicsexpose.drawable);
6152 if (f)
6154 expose_frame (f,
6155 event.xgraphicsexpose.x, event.xgraphicsexpose.y,
6156 event.xgraphicsexpose.width,
6157 event.xgraphicsexpose.height);
6159 #ifdef USE_X_TOOLKIT
6160 else
6161 goto OTHER;
6162 #endif /* USE_X_TOOLKIT */
6163 break;
6165 case NoExpose: /* This occurs when an XCopyArea's
6166 source area was completely
6167 available. */
6168 break;
6170 case UnmapNotify:
6171 /* Redo the mouse-highlight after the tooltip has gone. */
6172 if (event.xmap.window == tip_window)
6174 tip_window = 0;
6175 redo_mouse_highlight ();
6178 f = x_top_window_to_frame (dpyinfo, event.xunmap.window);
6179 if (f) /* F may no longer exist if
6180 the frame was deleted. */
6182 /* While a frame is unmapped, display generation is
6183 disabled; you don't want to spend time updating a
6184 display that won't ever be seen. */
6185 f->async_visible = 0;
6186 /* We can't distinguish, from the event, whether the window
6187 has become iconified or invisible. So assume, if it
6188 was previously visible, than now it is iconified.
6189 But x_make_frame_invisible clears both
6190 the visible flag and the iconified flag;
6191 and that way, we know the window is not iconified now. */
6192 if (FRAME_VISIBLE_P (f) || FRAME_ICONIFIED_P (f))
6194 f->async_iconified = 1;
6196 inev.ie.kind = ICONIFY_EVENT;
6197 XSETFRAME (inev.ie.frame_or_window, f);
6200 goto OTHER;
6202 case MapNotify:
6203 if (event.xmap.window == tip_window)
6204 /* The tooltip has been drawn already. Avoid
6205 the SET_FRAME_GARBAGED below. */
6206 goto OTHER;
6208 /* We use x_top_window_to_frame because map events can
6209 come for sub-windows and they don't mean that the
6210 frame is visible. */
6211 f = x_top_window_to_frame (dpyinfo, event.xmap.window);
6212 if (f)
6214 /* wait_reading_process_output will notice this and update
6215 the frame's display structures.
6216 If we where iconified, we should not set garbaged,
6217 because that stops redrawing on Expose events. This looks
6218 bad if we are called from a recursive event loop
6219 (x_dispatch_event), for example when a dialog is up. */
6220 if (! f->async_iconified)
6221 SET_FRAME_GARBAGED (f);
6223 /* Check if fullscreen was specified before we where mapped the
6224 first time, i.e. from the command line. */
6225 if (!f->output_data.x->has_been_visible)
6226 x_check_fullscreen (f);
6228 f->async_visible = 1;
6229 f->async_iconified = 0;
6230 f->output_data.x->has_been_visible = 1;
6232 if (f->iconified)
6234 inev.ie.kind = DEICONIFY_EVENT;
6235 XSETFRAME (inev.ie.frame_or_window, f);
6237 else if (! NILP (Vframe_list)
6238 && ! NILP (XCDR (Vframe_list)))
6239 /* Force a redisplay sooner or later
6240 to update the frame titles
6241 in case this is the second frame. */
6242 record_asynch_buffer_change ();
6244 #ifdef USE_GTK
6245 xg_frame_resized (f, -1, -1);
6246 #endif
6248 goto OTHER;
6250 case KeyPress:
6252 last_user_time = event.xkey.time;
6253 ignore_next_mouse_click_timeout = 0;
6255 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
6256 /* Dispatch KeyPress events when in menu. */
6257 if (popup_activated ())
6258 goto OTHER;
6259 #endif
6261 f = x_any_window_to_frame (dpyinfo, event.xkey.window);
6263 /* If mouse-highlight is an integer, input clears out
6264 mouse highlighting. */
6265 if (!hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight)
6266 && (f == 0
6267 || !EQ (f->tool_bar_window, hlinfo->mouse_face_window)))
6269 clear_mouse_face (hlinfo);
6270 hlinfo->mouse_face_hidden = 1;
6273 #if defined USE_MOTIF && defined USE_TOOLKIT_SCROLL_BARS
6274 if (f == 0)
6276 /* Scroll bars consume key events, but we want
6277 the keys to go to the scroll bar's frame. */
6278 Widget widget = XtWindowToWidget (dpyinfo->display,
6279 event.xkey.window);
6280 if (widget && XmIsScrollBar (widget))
6282 widget = XtParent (widget);
6283 f = x_any_window_to_frame (dpyinfo, XtWindow (widget));
6286 #endif /* USE_MOTIF and USE_TOOLKIT_SCROLL_BARS */
6288 if (f != 0)
6290 KeySym keysym, orig_keysym;
6291 /* al%imercury@uunet.uu.net says that making this 81
6292 instead of 80 fixed a bug whereby meta chars made
6293 his Emacs hang.
6295 It seems that some version of XmbLookupString has
6296 a bug of not returning XBufferOverflow in
6297 status_return even if the input is too long to
6298 fit in 81 bytes. So, we must prepare sufficient
6299 bytes for copy_buffer. 513 bytes (256 chars for
6300 two-byte character set) seems to be a fairly good
6301 approximation. -- 2000.8.10 handa@etl.go.jp */
6302 unsigned char copy_buffer[513];
6303 unsigned char *copy_bufptr = copy_buffer;
6304 int copy_bufsiz = sizeof (copy_buffer);
6305 int modifiers;
6306 Lisp_Object coding_system = Qlatin_1;
6307 Lisp_Object c;
6309 #ifdef USE_GTK
6310 /* Don't pass keys to GTK. A Tab will shift focus to the
6311 tool bar in GTK 2.4. Keys will still go to menus and
6312 dialogs because in that case popup_activated is TRUE
6313 (see above). */
6314 *finish = X_EVENT_DROP;
6315 #endif
6317 event.xkey.state
6318 |= x_emacs_to_x_modifiers (FRAME_X_DISPLAY_INFO (f),
6319 extra_keyboard_modifiers);
6320 modifiers = event.xkey.state;
6322 /* This will have to go some day... */
6324 /* make_lispy_event turns chars into control chars.
6325 Don't do it here because XLookupString is too eager. */
6326 event.xkey.state &= ~ControlMask;
6327 event.xkey.state &= ~(dpyinfo->meta_mod_mask
6328 | dpyinfo->super_mod_mask
6329 | dpyinfo->hyper_mod_mask
6330 | dpyinfo->alt_mod_mask);
6332 /* In case Meta is ComposeCharacter,
6333 clear its status. According to Markus Ehrnsperger
6334 Markus.Ehrnsperger@lehrstuhl-bross.physik.uni-muenchen.de
6335 this enables ComposeCharacter to work whether or
6336 not it is combined with Meta. */
6337 if (modifiers & dpyinfo->meta_mod_mask)
6338 memset (&compose_status, 0, sizeof (compose_status));
6340 #ifdef HAVE_X_I18N
6341 if (FRAME_XIC (f))
6343 Status status_return;
6345 coding_system = Vlocale_coding_system;
6346 nbytes = XmbLookupString (FRAME_XIC (f),
6347 &event.xkey, copy_bufptr,
6348 copy_bufsiz, &keysym,
6349 &status_return);
6350 if (status_return == XBufferOverflow)
6352 copy_bufsiz = nbytes + 1;
6353 copy_bufptr = (unsigned char *) alloca (copy_bufsiz);
6354 nbytes = XmbLookupString (FRAME_XIC (f),
6355 &event.xkey, copy_bufptr,
6356 copy_bufsiz, &keysym,
6357 &status_return);
6359 /* Xutf8LookupString is a new but already deprecated interface. -stef */
6360 if (status_return == XLookupNone)
6361 break;
6362 else if (status_return == XLookupChars)
6364 keysym = NoSymbol;
6365 modifiers = 0;
6367 else if (status_return != XLookupKeySym
6368 && status_return != XLookupBoth)
6369 abort ();
6371 else
6372 nbytes = XLookupString (&event.xkey, copy_bufptr,
6373 copy_bufsiz, &keysym,
6374 &compose_status);
6375 #else
6376 nbytes = XLookupString (&event.xkey, copy_bufptr,
6377 copy_bufsiz, &keysym,
6378 &compose_status);
6379 #endif
6381 /* If not using XIM/XIC, and a compose sequence is in progress,
6382 we break here. Otherwise, chars_matched is always 0. */
6383 if (compose_status.chars_matched > 0 && nbytes == 0)
6384 break;
6386 memset (&compose_status, 0, sizeof (compose_status));
6387 orig_keysym = keysym;
6389 /* Common for all keysym input events. */
6390 XSETFRAME (inev.ie.frame_or_window, f);
6391 inev.ie.modifiers
6392 = x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO (f), modifiers);
6393 inev.ie.timestamp = event.xkey.time;
6395 /* First deal with keysyms which have defined
6396 translations to characters. */
6397 if (keysym >= 32 && keysym < 128)
6398 /* Avoid explicitly decoding each ASCII character. */
6400 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
6401 inev.ie.code = keysym;
6402 goto done_keysym;
6405 /* Keysyms directly mapped to Unicode characters. */
6406 if (keysym >= 0x01000000 && keysym <= 0x0110FFFF)
6408 if (keysym < 0x01000080)
6409 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
6410 else
6411 inev.ie.kind = MULTIBYTE_CHAR_KEYSTROKE_EVENT;
6412 inev.ie.code = keysym & 0xFFFFFF;
6413 goto done_keysym;
6416 /* Now non-ASCII. */
6417 if (HASH_TABLE_P (Vx_keysym_table)
6418 && (NATNUMP (c = Fgethash (make_number (keysym),
6419 Vx_keysym_table,
6420 Qnil))))
6422 inev.ie.kind = (SINGLE_BYTE_CHAR_P (XFASTINT (c))
6423 ? ASCII_KEYSTROKE_EVENT
6424 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
6425 inev.ie.code = XFASTINT (c);
6426 goto done_keysym;
6429 /* Random non-modifier sorts of keysyms. */
6430 if (((keysym >= XK_BackSpace && keysym <= XK_Escape)
6431 || keysym == XK_Delete
6432 #ifdef XK_ISO_Left_Tab
6433 || (keysym >= XK_ISO_Left_Tab
6434 && keysym <= XK_ISO_Enter)
6435 #endif
6436 || IsCursorKey (keysym) /* 0xff50 <= x < 0xff60 */
6437 || IsMiscFunctionKey (keysym) /* 0xff60 <= x < VARIES */
6438 #ifdef HPUX
6439 /* This recognizes the "extended function
6440 keys". It seems there's no cleaner way.
6441 Test IsModifierKey to avoid handling
6442 mode_switch incorrectly. */
6443 || ((unsigned) (keysym) >= XK_Select
6444 && (unsigned)(keysym) < XK_KP_Space)
6445 #endif
6446 #ifdef XK_dead_circumflex
6447 || orig_keysym == XK_dead_circumflex
6448 #endif
6449 #ifdef XK_dead_grave
6450 || orig_keysym == XK_dead_grave
6451 #endif
6452 #ifdef XK_dead_tilde
6453 || orig_keysym == XK_dead_tilde
6454 #endif
6455 #ifdef XK_dead_diaeresis
6456 || orig_keysym == XK_dead_diaeresis
6457 #endif
6458 #ifdef XK_dead_macron
6459 || orig_keysym == XK_dead_macron
6460 #endif
6461 #ifdef XK_dead_degree
6462 || orig_keysym == XK_dead_degree
6463 #endif
6464 #ifdef XK_dead_acute
6465 || orig_keysym == XK_dead_acute
6466 #endif
6467 #ifdef XK_dead_cedilla
6468 || orig_keysym == XK_dead_cedilla
6469 #endif
6470 #ifdef XK_dead_breve
6471 || orig_keysym == XK_dead_breve
6472 #endif
6473 #ifdef XK_dead_ogonek
6474 || orig_keysym == XK_dead_ogonek
6475 #endif
6476 #ifdef XK_dead_caron
6477 || orig_keysym == XK_dead_caron
6478 #endif
6479 #ifdef XK_dead_doubleacute
6480 || orig_keysym == XK_dead_doubleacute
6481 #endif
6482 #ifdef XK_dead_abovedot
6483 || orig_keysym == XK_dead_abovedot
6484 #endif
6485 || IsKeypadKey (keysym) /* 0xff80 <= x < 0xffbe */
6486 || IsFunctionKey (keysym) /* 0xffbe <= x < 0xffe1 */
6487 /* Any "vendor-specific" key is ok. */
6488 || (orig_keysym & (1 << 28))
6489 || (keysym != NoSymbol && nbytes == 0))
6490 && ! (IsModifierKey (orig_keysym)
6491 /* The symbols from XK_ISO_Lock
6492 to XK_ISO_Last_Group_Lock
6493 don't have real modifiers but
6494 should be treated similarly to
6495 Mode_switch by Emacs. */
6496 #if defined XK_ISO_Lock && defined XK_ISO_Last_Group_Lock
6497 || ((unsigned)(orig_keysym)
6498 >= XK_ISO_Lock
6499 && (unsigned)(orig_keysym)
6500 <= XK_ISO_Last_Group_Lock)
6501 #endif
6504 STORE_KEYSYM_FOR_DEBUG (keysym);
6505 /* make_lispy_event will convert this to a symbolic
6506 key. */
6507 inev.ie.kind = NON_ASCII_KEYSTROKE_EVENT;
6508 inev.ie.code = keysym;
6509 goto done_keysym;
6512 { /* Raw bytes, not keysym. */
6513 register int i;
6514 register int c;
6515 int nchars, len;
6517 for (i = 0, nchars = 0; i < nbytes; i++)
6519 if (ASCII_BYTE_P (copy_bufptr[i]))
6520 nchars++;
6521 STORE_KEYSYM_FOR_DEBUG (copy_bufptr[i]);
6524 if (nchars < nbytes)
6526 /* Decode the input data. */
6527 int require;
6529 /* The input should be decoded with `coding_system'
6530 which depends on which X*LookupString function
6531 we used just above and the locale. */
6532 setup_coding_system (coding_system, &coding);
6533 coding.src_multibyte = 0;
6534 coding.dst_multibyte = 1;
6535 /* The input is converted to events, thus we can't
6536 handle composition. Anyway, there's no XIM that
6537 gives us composition information. */
6538 coding.common_flags &= ~CODING_ANNOTATION_MASK;
6540 require = MAX_MULTIBYTE_LENGTH * nbytes;
6541 coding.destination = alloca (require);
6542 coding.dst_bytes = require;
6543 coding.mode |= CODING_MODE_LAST_BLOCK;
6544 decode_coding_c_string (&coding, copy_bufptr, nbytes, Qnil);
6545 nbytes = coding.produced;
6546 nchars = coding.produced_char;
6547 copy_bufptr = coding.destination;
6550 /* Convert the input data to a sequence of
6551 character events. */
6552 for (i = 0; i < nbytes; i += len)
6554 if (nchars == nbytes)
6555 c = copy_bufptr[i], len = 1;
6556 else
6557 c = STRING_CHAR_AND_LENGTH (copy_bufptr + i, len);
6558 inev.ie.kind = (SINGLE_BYTE_CHAR_P (c)
6559 ? ASCII_KEYSTROKE_EVENT
6560 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
6561 inev.ie.code = c;
6562 kbd_buffer_store_event_hold (&inev.ie, hold_quit);
6565 count += nchars;
6567 inev.ie.kind = NO_EVENT; /* Already stored above. */
6569 if (keysym == NoSymbol)
6570 break;
6573 done_keysym:
6574 #ifdef HAVE_X_I18N
6575 /* Don't dispatch this event since XtDispatchEvent calls
6576 XFilterEvent, and two calls in a row may freeze the
6577 client. */
6578 break;
6579 #else
6580 goto OTHER;
6581 #endif
6583 case KeyRelease:
6584 last_user_time = event.xkey.time;
6585 #ifdef HAVE_X_I18N
6586 /* Don't dispatch this event since XtDispatchEvent calls
6587 XFilterEvent, and two calls in a row may freeze the
6588 client. */
6589 break;
6590 #else
6591 goto OTHER;
6592 #endif
6594 case EnterNotify:
6595 last_user_time = event.xcrossing.time;
6596 x_detect_focus_change (dpyinfo, &event, &inev.ie);
6598 f = x_any_window_to_frame (dpyinfo, event.xcrossing.window);
6600 if (f && x_mouse_click_focus_ignore_position)
6601 ignore_next_mouse_click_timeout = event.xmotion.time + 200;
6603 /* EnterNotify counts as mouse movement,
6604 so update things that depend on mouse position. */
6605 if (f && !f->output_data.x->hourglass_p)
6606 note_mouse_movement (f, &event.xmotion);
6607 #ifdef USE_GTK
6608 /* We may get an EnterNotify on the buttons in the toolbar. In that
6609 case we moved out of any highlighted area and need to note this. */
6610 if (!f && last_mouse_glyph_frame)
6611 note_mouse_movement (last_mouse_glyph_frame, &event.xmotion);
6612 #endif
6613 goto OTHER;
6615 case FocusIn:
6616 x_detect_focus_change (dpyinfo, &event, &inev.ie);
6617 goto OTHER;
6619 case LeaveNotify:
6620 last_user_time = event.xcrossing.time;
6621 x_detect_focus_change (dpyinfo, &event, &inev.ie);
6623 f = x_top_window_to_frame (dpyinfo, event.xcrossing.window);
6624 if (f)
6626 if (f == hlinfo->mouse_face_mouse_frame)
6628 /* If we move outside the frame, then we're
6629 certainly no longer on any text in the frame. */
6630 clear_mouse_face (hlinfo);
6631 hlinfo->mouse_face_mouse_frame = 0;
6634 /* Generate a nil HELP_EVENT to cancel a help-echo.
6635 Do it only if there's something to cancel.
6636 Otherwise, the startup message is cleared when
6637 the mouse leaves the frame. */
6638 if (any_help_event_p)
6639 do_help = -1;
6641 #ifdef USE_GTK
6642 /* See comment in EnterNotify above */
6643 else if (last_mouse_glyph_frame)
6644 note_mouse_movement (last_mouse_glyph_frame, &event.xmotion);
6645 #endif
6646 goto OTHER;
6648 case FocusOut:
6649 x_detect_focus_change (dpyinfo, &event, &inev.ie);
6650 goto OTHER;
6652 case MotionNotify:
6654 last_user_time = event.xmotion.time;
6655 previous_help_echo_string = help_echo_string;
6656 help_echo_string = Qnil;
6658 if (dpyinfo->grabbed && last_mouse_frame
6659 && FRAME_LIVE_P (last_mouse_frame))
6660 f = last_mouse_frame;
6661 else
6662 f = x_window_to_frame (dpyinfo, event.xmotion.window);
6664 if (hlinfo->mouse_face_hidden)
6666 hlinfo->mouse_face_hidden = 0;
6667 clear_mouse_face (hlinfo);
6670 #ifdef USE_GTK
6671 if (f && xg_event_is_for_scrollbar (f, &event))
6672 f = 0;
6673 #endif
6674 if (f)
6677 /* Generate SELECT_WINDOW_EVENTs when needed.
6678 Don't let popup menus influence things (bug#1261). */
6679 if (!NILP (Vmouse_autoselect_window) && !popup_activated ())
6681 Lisp_Object window;
6683 window = window_from_coordinates (f,
6684 event.xmotion.x, event.xmotion.y,
6685 0, 0);
6687 /* Window will be selected only when it is not selected now and
6688 last mouse movement event was not in it. Minibuffer window
6689 will be selected only when it is active. */
6690 if (WINDOWP (window)
6691 && !EQ (window, last_window)
6692 && !EQ (window, selected_window)
6693 /* For click-to-focus window managers
6694 create event iff we don't leave the
6695 selected frame. */
6696 && (focus_follows_mouse
6697 || (EQ (XWINDOW (window)->frame,
6698 XWINDOW (selected_window)->frame))))
6700 inev.ie.kind = SELECT_WINDOW_EVENT;
6701 inev.ie.frame_or_window = window;
6704 last_window=window;
6706 if (!note_mouse_movement (f, &event.xmotion))
6707 help_echo_string = previous_help_echo_string;
6709 else
6711 #ifndef USE_TOOLKIT_SCROLL_BARS
6712 struct scroll_bar *bar
6713 = x_window_to_scroll_bar (event.xmotion.display,
6714 event.xmotion.window);
6716 if (bar)
6717 x_scroll_bar_note_movement (bar, &event);
6718 #endif /* USE_TOOLKIT_SCROLL_BARS */
6720 /* If we move outside the frame, then we're
6721 certainly no longer on any text in the frame. */
6722 clear_mouse_face (hlinfo);
6725 /* If the contents of the global variable help_echo_string
6726 has changed, generate a HELP_EVENT. */
6727 if (!NILP (help_echo_string)
6728 || !NILP (previous_help_echo_string))
6729 do_help = 1;
6730 goto OTHER;
6733 case ConfigureNotify:
6734 f = x_top_window_to_frame (dpyinfo, event.xconfigure.window);
6735 #ifdef USE_GTK
6736 if (!f
6737 && (f = x_any_window_to_frame (dpyinfo, event.xconfigure.window))
6738 && event.xconfigure.window == FRAME_X_WINDOW (f))
6740 xg_frame_resized (f, event.xconfigure.width,
6741 event.xconfigure.height);
6742 f = 0;
6744 #endif
6745 if (f)
6747 #ifndef USE_X_TOOLKIT
6748 #ifndef USE_GTK
6749 int rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, event.xconfigure.height);
6750 int columns = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, event.xconfigure.width);
6752 /* In the toolkit version, change_frame_size
6753 is called by the code that handles resizing
6754 of the EmacsFrame widget. */
6756 /* Even if the number of character rows and columns has
6757 not changed, the font size may have changed, so we need
6758 to check the pixel dimensions as well. */
6759 if (columns != FRAME_COLS (f)
6760 || rows != FRAME_LINES (f)
6761 || event.xconfigure.width != FRAME_PIXEL_WIDTH (f)
6762 || event.xconfigure.height != FRAME_PIXEL_HEIGHT (f))
6764 change_frame_size (f, rows, columns, 0, 1, 0);
6765 SET_FRAME_GARBAGED (f);
6766 cancel_mouse_face (f);
6769 FRAME_PIXEL_WIDTH (f) = event.xconfigure.width;
6770 FRAME_PIXEL_HEIGHT (f) = event.xconfigure.height;
6771 #endif /* not USE_GTK */
6772 #endif
6774 #ifdef USE_GTK
6775 /* GTK creates windows but doesn't map them.
6776 Only get real positions when mapped. */
6777 if (FRAME_GTK_OUTER_WIDGET (f)
6778 && gtk_widget_get_mapped (FRAME_GTK_OUTER_WIDGET (f)))
6779 #endif
6781 x_real_positions (f, &f->left_pos, &f->top_pos);
6784 #ifdef HAVE_X_I18N
6785 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMStatusArea))
6786 xic_set_statusarea (f);
6787 #endif
6790 goto OTHER;
6792 case ButtonRelease:
6793 case ButtonPress:
6795 /* If we decide we want to generate an event to be seen
6796 by the rest of Emacs, we put it here. */
6797 int tool_bar_p = 0;
6799 memset (&compose_status, 0, sizeof (compose_status));
6800 last_mouse_glyph_frame = 0;
6801 last_user_time = event.xbutton.time;
6803 if (dpyinfo->grabbed
6804 && last_mouse_frame
6805 && FRAME_LIVE_P (last_mouse_frame))
6806 f = last_mouse_frame;
6807 else
6808 f = x_window_to_frame (dpyinfo, event.xbutton.window);
6810 #ifdef USE_GTK
6811 if (f && xg_event_is_for_scrollbar (f, &event))
6812 f = 0;
6813 #endif
6814 if (f)
6816 /* Is this in the tool-bar? */
6817 if (WINDOWP (f->tool_bar_window)
6818 && WINDOW_TOTAL_LINES (XWINDOW (f->tool_bar_window)))
6820 Lisp_Object window;
6821 int x = event.xbutton.x;
6822 int y = event.xbutton.y;
6824 window = window_from_coordinates (f, x, y, 0, 1);
6825 tool_bar_p = EQ (window, f->tool_bar_window);
6827 if (tool_bar_p && event.xbutton.button < 4)
6829 handle_tool_bar_click (f, x, y,
6830 event.xbutton.type == ButtonPress,
6831 x_x_to_emacs_modifiers (dpyinfo,
6832 event.xbutton.state));
6836 if (!tool_bar_p)
6837 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
6838 if (! popup_activated ())
6839 #endif
6841 if (ignore_next_mouse_click_timeout)
6843 if (event.type == ButtonPress
6844 && (int)(event.xbutton.time - ignore_next_mouse_click_timeout) > 0)
6846 ignore_next_mouse_click_timeout = 0;
6847 construct_mouse_click (&inev.ie, &event.xbutton, f);
6849 if (event.type == ButtonRelease)
6850 ignore_next_mouse_click_timeout = 0;
6852 else
6853 construct_mouse_click (&inev.ie, &event.xbutton, f);
6855 if (FRAME_X_EMBEDDED_P (f))
6856 xembed_send_message (f, event.xbutton.time,
6857 XEMBED_REQUEST_FOCUS, 0, 0, 0);
6859 else
6861 struct scroll_bar *bar
6862 = x_window_to_scroll_bar (event.xbutton.display,
6863 event.xbutton.window);
6865 #ifdef USE_TOOLKIT_SCROLL_BARS
6866 /* Make the "Ctrl-Mouse-2 splits window" work for toolkit
6867 scroll bars. */
6868 if (bar && event.xbutton.state & ControlMask)
6870 x_scroll_bar_handle_click (bar, &event, &inev.ie);
6871 *finish = X_EVENT_DROP;
6873 #else /* not USE_TOOLKIT_SCROLL_BARS */
6874 if (bar)
6875 x_scroll_bar_handle_click (bar, &event, &inev.ie);
6876 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6879 if (event.type == ButtonPress)
6881 dpyinfo->grabbed |= (1 << event.xbutton.button);
6882 last_mouse_frame = f;
6884 if (!tool_bar_p)
6885 last_tool_bar_item = -1;
6887 else
6888 dpyinfo->grabbed &= ~(1 << event.xbutton.button);
6890 /* Ignore any mouse motion that happened before this event;
6891 any subsequent mouse-movement Emacs events should reflect
6892 only motion after the ButtonPress/Release. */
6893 if (f != 0)
6894 f->mouse_moved = 0;
6896 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
6897 f = x_menubar_window_to_frame (dpyinfo, &event);
6898 /* For a down-event in the menu bar,
6899 don't pass it to Xt right now.
6900 Instead, save it away
6901 and we will pass it to Xt from kbd_buffer_get_event.
6902 That way, we can run some Lisp code first. */
6903 if (! popup_activated ()
6904 #ifdef USE_GTK
6905 /* Gtk+ menus only react to the first three buttons. */
6906 && event.xbutton.button < 3
6907 #endif
6908 && f && event.type == ButtonPress
6909 /* Verify the event is really within the menu bar
6910 and not just sent to it due to grabbing. */
6911 && event.xbutton.x >= 0
6912 && event.xbutton.x < FRAME_PIXEL_WIDTH (f)
6913 && event.xbutton.y >= 0
6914 && event.xbutton.y < f->output_data.x->menubar_height
6915 && event.xbutton.same_screen)
6917 SET_SAVED_BUTTON_EVENT;
6918 XSETFRAME (last_mouse_press_frame, f);
6919 *finish = X_EVENT_DROP;
6921 else if (event.type == ButtonPress)
6923 last_mouse_press_frame = Qnil;
6924 goto OTHER;
6926 else
6927 goto OTHER;
6928 #endif /* USE_X_TOOLKIT || USE_GTK */
6930 break;
6932 case CirculateNotify:
6933 goto OTHER;
6935 case CirculateRequest:
6936 goto OTHER;
6938 case VisibilityNotify:
6939 goto OTHER;
6941 case MappingNotify:
6942 /* Someone has changed the keyboard mapping - update the
6943 local cache. */
6944 switch (event.xmapping.request)
6946 case MappingModifier:
6947 x_find_modifier_meanings (dpyinfo);
6948 /* This is meant to fall through. */
6949 case MappingKeyboard:
6950 XRefreshKeyboardMapping (&event.xmapping);
6952 goto OTHER;
6954 case DestroyNotify:
6955 xft_settings_event (dpyinfo, &event);
6956 break;
6958 default:
6959 OTHER:
6960 #ifdef USE_X_TOOLKIT
6961 BLOCK_INPUT;
6962 if (*finish != X_EVENT_DROP)
6963 XtDispatchEvent (&event);
6964 UNBLOCK_INPUT;
6965 #endif /* USE_X_TOOLKIT */
6966 break;
6969 done:
6970 if (inev.ie.kind != NO_EVENT)
6972 kbd_buffer_store_event_hold (&inev.ie, hold_quit);
6973 count++;
6976 if (do_help
6977 && !(hold_quit && hold_quit->kind != NO_EVENT))
6979 Lisp_Object frame;
6981 if (f)
6982 XSETFRAME (frame, f);
6983 else
6984 frame = Qnil;
6986 if (do_help > 0)
6988 any_help_event_p = 1;
6989 gen_help_event (help_echo_string, frame, help_echo_window,
6990 help_echo_object, help_echo_pos);
6992 else
6994 help_echo_string = Qnil;
6995 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
6997 count++;
7000 *eventp = event;
7001 return count;
7005 /* Handles the XEvent EVENT on display DISPLAY.
7006 This is used for event loops outside the normal event handling,
7007 i.e. looping while a popup menu or a dialog is posted.
7009 Returns the value handle_one_xevent sets in the finish argument. */
7011 x_dispatch_event (XEvent *event, Display *display)
7013 struct x_display_info *dpyinfo;
7014 int finish = X_EVENT_NORMAL;
7016 dpyinfo = x_display_info_for_display (display);
7018 if (dpyinfo)
7019 handle_one_xevent (dpyinfo, event, &finish, 0);
7021 return finish;
7025 /* Read events coming from the X server.
7026 This routine is called by the SIGIO handler.
7027 We return as soon as there are no more events to be read.
7029 We return the number of characters stored into the buffer,
7030 thus pretending to be `read' (except the characters we store
7031 in the keyboard buffer can be multibyte, so are not necessarily
7032 C chars).
7034 EXPECTED is nonzero if the caller knows input is available. */
7036 static int
7037 XTread_socket (struct terminal *terminal, int expected, struct input_event *hold_quit)
7039 int count = 0;
7040 XEvent event;
7041 int event_found = 0;
7043 if (interrupt_input_blocked)
7045 interrupt_input_pending = 1;
7046 #ifdef SYNC_INPUT
7047 pending_signals = 1;
7048 #endif
7049 return -1;
7052 interrupt_input_pending = 0;
7053 #ifdef SYNC_INPUT
7054 pending_signals = pending_atimers;
7055 #endif
7056 BLOCK_INPUT;
7058 /* So people can tell when we have read the available input. */
7059 input_signal_count++;
7061 ++handling_signal;
7063 #ifdef HAVE_X_SM
7064 /* Only check session manager input for the primary display. */
7065 if (terminal->id == 1 && x_session_have_connection ())
7067 struct input_event inev;
7068 BLOCK_INPUT;
7069 /* We don't need to EVENT_INIT (inev) here, as
7070 x_session_check_input copies an entire input_event. */
7071 if (x_session_check_input (&inev))
7073 kbd_buffer_store_event_hold (&inev, hold_quit);
7074 count++;
7076 UNBLOCK_INPUT;
7078 #endif
7080 /* For debugging, this gives a way to fake an I/O error. */
7081 if (terminal->display_info.x == XTread_socket_fake_io_error)
7083 XTread_socket_fake_io_error = 0;
7084 x_io_error_quitter (terminal->display_info.x->display);
7087 #ifndef USE_GTK
7088 while (XPending (terminal->display_info.x->display))
7090 int finish;
7092 XNextEvent (terminal->display_info.x->display, &event);
7094 #ifdef HAVE_X_I18N
7095 /* Filter events for the current X input method. */
7096 if (x_filter_event (terminal->display_info.x, &event))
7097 continue;
7098 #endif
7099 event_found = 1;
7101 count += handle_one_xevent (terminal->display_info.x,
7102 &event, &finish, hold_quit);
7104 if (finish == X_EVENT_GOTO_OUT)
7105 goto out;
7108 #else /* USE_GTK */
7110 /* For GTK we must use the GTK event loop. But XEvents gets passed
7111 to our filter function above, and then to the big event switch.
7112 We use a bunch of globals to communicate with our filter function,
7113 that is kind of ugly, but it works.
7115 There is no way to do one display at the time, GTK just does events
7116 from all displays. */
7118 while (gtk_events_pending ())
7120 current_count = count;
7121 current_hold_quit = hold_quit;
7123 gtk_main_iteration ();
7125 count = current_count;
7126 current_count = -1;
7127 current_hold_quit = 0;
7129 if (current_finish == X_EVENT_GOTO_OUT)
7130 break;
7132 #endif /* USE_GTK */
7134 out:;
7136 /* On some systems, an X bug causes Emacs to get no more events
7137 when the window is destroyed. Detect that. (1994.) */
7138 if (! event_found)
7140 /* Emacs and the X Server eats up CPU time if XNoOp is done every time.
7141 One XNOOP in 100 loops will make Emacs terminate.
7142 B. Bretthauer, 1994 */
7143 x_noop_count++;
7144 if (x_noop_count >= 100)
7146 x_noop_count=0;
7148 if (next_noop_dpyinfo == 0)
7149 next_noop_dpyinfo = x_display_list;
7151 XNoOp (next_noop_dpyinfo->display);
7153 /* Each time we get here, cycle through the displays now open. */
7154 next_noop_dpyinfo = next_noop_dpyinfo->next;
7158 /* If the focus was just given to an auto-raising frame,
7159 raise it now. */
7160 /* ??? This ought to be able to handle more than one such frame. */
7161 if (pending_autoraise_frame)
7163 x_raise_frame (pending_autoraise_frame);
7164 pending_autoraise_frame = 0;
7167 --handling_signal;
7168 UNBLOCK_INPUT;
7170 return count;
7176 /***********************************************************************
7177 Text Cursor
7178 ***********************************************************************/
7180 /* Set clipping for output in glyph row ROW. W is the window in which
7181 we operate. GC is the graphics context to set clipping in.
7183 ROW may be a text row or, e.g., a mode line. Text rows must be
7184 clipped to the interior of the window dedicated to text display,
7185 mode lines must be clipped to the whole window. */
7187 static void
7188 x_clip_to_row (struct window *w, struct glyph_row *row, int area, GC gc)
7190 struct frame *f = XFRAME (WINDOW_FRAME (w));
7191 XRectangle clip_rect;
7192 int window_x, window_y, window_width;
7194 window_box (w, area, &window_x, &window_y, &window_width, 0);
7196 clip_rect.x = window_x;
7197 clip_rect.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
7198 clip_rect.y = max (clip_rect.y, window_y);
7199 clip_rect.width = window_width;
7200 clip_rect.height = row->visible_height;
7202 XSetClipRectangles (FRAME_X_DISPLAY (f), gc, 0, 0, &clip_rect, 1, Unsorted);
7206 /* Draw a hollow box cursor on window W in glyph row ROW. */
7208 static void
7209 x_draw_hollow_cursor (struct window *w, struct glyph_row *row)
7211 struct frame *f = XFRAME (WINDOW_FRAME (w));
7212 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
7213 Display *dpy = FRAME_X_DISPLAY (f);
7214 int x, y, wd, h;
7215 XGCValues xgcv;
7216 struct glyph *cursor_glyph;
7217 GC gc;
7219 /* Get the glyph the cursor is on. If we can't tell because
7220 the current matrix is invalid or such, give up. */
7221 cursor_glyph = get_phys_cursor_glyph (w);
7222 if (cursor_glyph == NULL)
7223 return;
7225 /* Compute frame-relative coordinates for phys cursor. */
7226 get_phys_cursor_geometry (w, row, cursor_glyph, &x, &y, &h);
7227 wd = w->phys_cursor_width;
7229 /* The foreground of cursor_gc is typically the same as the normal
7230 background color, which can cause the cursor box to be invisible. */
7231 xgcv.foreground = f->output_data.x->cursor_pixel;
7232 if (dpyinfo->scratch_cursor_gc)
7233 XChangeGC (dpy, dpyinfo->scratch_cursor_gc, GCForeground, &xgcv);
7234 else
7235 dpyinfo->scratch_cursor_gc = XCreateGC (dpy, FRAME_X_WINDOW (f),
7236 GCForeground, &xgcv);
7237 gc = dpyinfo->scratch_cursor_gc;
7239 /* Set clipping, draw the rectangle, and reset clipping again. */
7240 x_clip_to_row (w, row, TEXT_AREA, gc);
7241 XDrawRectangle (dpy, FRAME_X_WINDOW (f), gc, x, y, wd, h - 1);
7242 XSetClipMask (dpy, gc, None);
7246 /* Draw a bar cursor on window W in glyph row ROW.
7248 Implementation note: One would like to draw a bar cursor with an
7249 angle equal to the one given by the font property XA_ITALIC_ANGLE.
7250 Unfortunately, I didn't find a font yet that has this property set.
7251 --gerd. */
7253 static void
7254 x_draw_bar_cursor (struct window *w, struct glyph_row *row, int width, enum text_cursor_kinds kind)
7256 struct frame *f = XFRAME (w->frame);
7257 struct glyph *cursor_glyph;
7259 /* If cursor is out of bounds, don't draw garbage. This can happen
7260 in mini-buffer windows when switching between echo area glyphs
7261 and mini-buffer. */
7262 cursor_glyph = get_phys_cursor_glyph (w);
7263 if (cursor_glyph == NULL)
7264 return;
7266 /* If on an image, draw like a normal cursor. That's usually better
7267 visible than drawing a bar, esp. if the image is large so that
7268 the bar might not be in the window. */
7269 if (cursor_glyph->type == IMAGE_GLYPH)
7271 struct glyph_row *row;
7272 row = MATRIX_ROW (w->current_matrix, w->phys_cursor.vpos);
7273 draw_phys_cursor_glyph (w, row, DRAW_CURSOR);
7275 else
7277 Display *dpy = FRAME_X_DISPLAY (f);
7278 Window window = FRAME_X_WINDOW (f);
7279 GC gc = FRAME_X_DISPLAY_INFO (f)->scratch_cursor_gc;
7280 unsigned long mask = GCForeground | GCBackground | GCGraphicsExposures;
7281 struct face *face = FACE_FROM_ID (f, cursor_glyph->face_id);
7282 XGCValues xgcv;
7284 /* If the glyph's background equals the color we normally draw
7285 the bars cursor in, the bar cursor in its normal color is
7286 invisible. Use the glyph's foreground color instead in this
7287 case, on the assumption that the glyph's colors are chosen so
7288 that the glyph is legible. */
7289 if (face->background == f->output_data.x->cursor_pixel)
7290 xgcv.background = xgcv.foreground = face->foreground;
7291 else
7292 xgcv.background = xgcv.foreground = f->output_data.x->cursor_pixel;
7293 xgcv.graphics_exposures = 0;
7295 if (gc)
7296 XChangeGC (dpy, gc, mask, &xgcv);
7297 else
7299 gc = XCreateGC (dpy, window, mask, &xgcv);
7300 FRAME_X_DISPLAY_INFO (f)->scratch_cursor_gc = gc;
7303 x_clip_to_row (w, row, TEXT_AREA, gc);
7305 if (kind == BAR_CURSOR)
7307 int x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
7309 if (width < 0)
7310 width = FRAME_CURSOR_WIDTH (f);
7311 width = min (cursor_glyph->pixel_width, width);
7313 w->phys_cursor_width = width;
7315 /* If the character under cursor is R2L, draw the bar cursor
7316 on the right of its glyph, rather than on the left. */
7317 if ((cursor_glyph->resolved_level & 1) != 0)
7318 x += cursor_glyph->pixel_width - width;
7320 XFillRectangle (dpy, window, gc, x,
7321 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y),
7322 width, row->height);
7324 else
7326 int dummy_x, dummy_y, dummy_h;
7328 if (width < 0)
7329 width = row->height;
7331 width = min (row->height, width);
7333 get_phys_cursor_geometry (w, row, cursor_glyph, &dummy_x,
7334 &dummy_y, &dummy_h);
7336 XFillRectangle (dpy, window, gc,
7337 WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x),
7338 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y +
7339 row->height - width),
7340 w->phys_cursor_width, width);
7343 XSetClipMask (dpy, gc, None);
7348 /* RIF: Define cursor CURSOR on frame F. */
7350 static void
7351 x_define_frame_cursor (struct frame *f, Cursor cursor)
7353 if (!f->pointer_invisible
7354 && f->output_data.x->current_cursor != cursor)
7355 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), cursor);
7356 f->output_data.x->current_cursor = cursor;
7360 /* RIF: Clear area on frame F. */
7362 static void
7363 x_clear_frame_area (struct frame *f, int x, int y, int width, int height)
7365 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
7366 x, y, width, height, False);
7367 #ifdef USE_GTK
7368 /* Must queue a redraw, because scroll bars might have been cleared. */
7369 if (FRAME_GTK_WIDGET (f))
7370 gtk_widget_queue_draw (FRAME_GTK_WIDGET (f));
7371 #endif
7375 /* RIF: Draw cursor on window W. */
7377 static void
7378 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)
7380 struct frame *f = XFRAME (WINDOW_FRAME (w));
7382 if (on_p)
7384 w->phys_cursor_type = cursor_type;
7385 w->phys_cursor_on_p = 1;
7387 if (glyph_row->exact_window_width_line_p
7388 && (glyph_row->reversed_p
7389 ? (w->phys_cursor.hpos < 0)
7390 : (w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])))
7392 glyph_row->cursor_in_fringe_p = 1;
7393 draw_fringe_bitmap (w, glyph_row, glyph_row->reversed_p);
7395 else
7397 switch (cursor_type)
7399 case HOLLOW_BOX_CURSOR:
7400 x_draw_hollow_cursor (w, glyph_row);
7401 break;
7403 case FILLED_BOX_CURSOR:
7404 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
7405 break;
7407 case BAR_CURSOR:
7408 x_draw_bar_cursor (w, glyph_row, cursor_width, BAR_CURSOR);
7409 break;
7411 case HBAR_CURSOR:
7412 x_draw_bar_cursor (w, glyph_row, cursor_width, HBAR_CURSOR);
7413 break;
7415 case NO_CURSOR:
7416 w->phys_cursor_width = 0;
7417 break;
7419 default:
7420 abort ();
7424 #ifdef HAVE_X_I18N
7425 if (w == XWINDOW (f->selected_window))
7426 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMPreeditPosition))
7427 xic_set_preeditarea (w, x, y);
7428 #endif
7431 #ifndef XFlush
7432 XFlush (FRAME_X_DISPLAY (f));
7433 #endif
7437 /* Icons. */
7439 /* Make the x-window of frame F use the gnu icon bitmap. */
7442 x_bitmap_icon (struct frame *f, Lisp_Object file)
7444 int bitmap_id;
7446 if (FRAME_X_WINDOW (f) == 0)
7447 return 1;
7449 /* Free up our existing icon bitmap and mask if any. */
7450 if (f->output_data.x->icon_bitmap > 0)
7451 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
7452 f->output_data.x->icon_bitmap = 0;
7454 if (STRINGP (file))
7456 #ifdef USE_GTK
7457 /* Use gtk_window_set_icon_from_file () if available,
7458 It's not restricted to bitmaps */
7459 if (xg_set_icon (f, file))
7460 return 0;
7461 #endif /* USE_GTK */
7462 bitmap_id = x_create_bitmap_from_file (f, file);
7463 x_create_bitmap_mask (f, bitmap_id);
7465 else
7467 /* Create the GNU bitmap and mask if necessary. */
7468 if (FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id < 0)
7470 int rc = -1;
7472 #ifdef USE_GTK
7474 if (xg_set_icon (f, xg_default_icon_file)
7475 || xg_set_icon_from_xpm_data (f, gnu_xpm_bits))
7476 return 0;
7478 #elif defined (HAVE_XPM) && defined (HAVE_X_WINDOWS)
7480 rc = x_create_bitmap_from_xpm_data (f, gnu_xpm_bits);
7481 if (rc != -1)
7482 FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id = rc;
7484 #endif
7486 /* If all else fails, use the (black and white) xbm image. */
7487 if (rc == -1)
7489 rc = x_create_bitmap_from_data (f, gnu_xbm_bits,
7490 gnu_xbm_width, gnu_xbm_height);
7491 if (rc == -1)
7492 return 1;
7494 FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id = rc;
7495 x_create_bitmap_mask (f, FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id);
7499 /* The first time we create the GNU bitmap and mask,
7500 this increments the ref-count one extra time.
7501 As a result, the GNU bitmap and mask are never freed.
7502 That way, we don't have to worry about allocating it again. */
7503 x_reference_bitmap (f, FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id);
7505 bitmap_id = FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id;
7508 x_wm_set_icon_pixmap (f, bitmap_id);
7509 f->output_data.x->icon_bitmap = bitmap_id;
7511 return 0;
7515 /* Make the x-window of frame F use a rectangle with text.
7516 Use ICON_NAME as the text. */
7519 x_text_icon (struct frame *f, const char *icon_name)
7521 if (FRAME_X_WINDOW (f) == 0)
7522 return 1;
7525 XTextProperty text;
7526 text.value = (unsigned char *) icon_name;
7527 text.encoding = XA_STRING;
7528 text.format = 8;
7529 text.nitems = strlen (icon_name);
7530 XSetWMIconName (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f), &text);
7533 if (f->output_data.x->icon_bitmap > 0)
7534 x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
7535 f->output_data.x->icon_bitmap = 0;
7536 x_wm_set_icon_pixmap (f, 0);
7538 return 0;
7541 #define X_ERROR_MESSAGE_SIZE 200
7543 /* If non-nil, this should be a string.
7544 It means catch X errors and store the error message in this string.
7546 The reason we use a stack is that x_catch_error/x_uncatch_error can
7547 be called from a signal handler.
7550 struct x_error_message_stack {
7551 char string[X_ERROR_MESSAGE_SIZE];
7552 Display *dpy;
7553 struct x_error_message_stack *prev;
7555 static struct x_error_message_stack *x_error_message;
7557 /* An X error handler which stores the error message in
7558 *x_error_message. This is called from x_error_handler if
7559 x_catch_errors is in effect. */
7561 static void
7562 x_error_catcher (Display *display, XErrorEvent *error)
7564 XGetErrorText (display, error->error_code,
7565 x_error_message->string,
7566 X_ERROR_MESSAGE_SIZE);
7569 /* Begin trapping X errors for display DPY. Actually we trap X errors
7570 for all displays, but DPY should be the display you are actually
7571 operating on.
7573 After calling this function, X protocol errors no longer cause
7574 Emacs to exit; instead, they are recorded in the string
7575 stored in *x_error_message.
7577 Calling x_check_errors signals an Emacs error if an X error has
7578 occurred since the last call to x_catch_errors or x_check_errors.
7580 Calling x_uncatch_errors resumes the normal error handling. */
7582 void x_check_errors (Display *dpy, const char *format);
7584 void
7585 x_catch_errors (Display *dpy)
7587 struct x_error_message_stack *data = xmalloc (sizeof (*data));
7589 /* Make sure any errors from previous requests have been dealt with. */
7590 XSync (dpy, False);
7592 data->dpy = dpy;
7593 data->string[0] = 0;
7594 data->prev = x_error_message;
7595 x_error_message = data;
7598 /* Undo the last x_catch_errors call.
7599 DPY should be the display that was passed to x_catch_errors. */
7601 void
7602 x_uncatch_errors (void)
7604 struct x_error_message_stack *tmp;
7606 BLOCK_INPUT;
7608 /* The display may have been closed before this function is called.
7609 Check if it is still open before calling XSync. */
7610 if (x_display_info_for_display (x_error_message->dpy) != 0)
7611 XSync (x_error_message->dpy, False);
7613 tmp = x_error_message;
7614 x_error_message = x_error_message->prev;
7615 xfree (tmp);
7616 UNBLOCK_INPUT;
7619 /* If any X protocol errors have arrived since the last call to
7620 x_catch_errors or x_check_errors, signal an Emacs error using
7621 sprintf (a buffer, FORMAT, the x error message text) as the text. */
7623 void
7624 x_check_errors (Display *dpy, const char *format)
7626 /* Make sure to catch any errors incurred so far. */
7627 XSync (dpy, False);
7629 if (x_error_message->string[0])
7631 char string[X_ERROR_MESSAGE_SIZE];
7632 memcpy (string, x_error_message->string, X_ERROR_MESSAGE_SIZE);
7633 x_uncatch_errors ();
7634 error (format, string);
7638 /* Nonzero if we had any X protocol errors
7639 since we did x_catch_errors on DPY. */
7642 x_had_errors_p (Display *dpy)
7644 /* Make sure to catch any errors incurred so far. */
7645 XSync (dpy, False);
7647 return x_error_message->string[0] != 0;
7650 /* Forget about any errors we have had, since we did x_catch_errors on DPY. */
7652 void
7653 x_clear_errors (Display *dpy)
7655 x_error_message->string[0] = 0;
7658 #if 0 /* See comment in unwind_to_catch why calling this is a bad
7659 * idea. --lorentey */
7660 /* Close off all unclosed x_catch_errors calls. */
7662 void
7663 x_fully_uncatch_errors (void)
7665 while (x_error_message)
7666 x_uncatch_errors ();
7668 #endif
7670 /* Nonzero if x_catch_errors has been done and not yet canceled. */
7673 x_catching_errors (void)
7675 return x_error_message != 0;
7678 #if 0
7679 static unsigned int x_wire_count;
7680 x_trace_wire (void)
7682 fprintf (stderr, "Lib call: %d\n", ++x_wire_count);
7684 #endif /* ! 0 */
7687 /* Handle SIGPIPE, which can happen when the connection to a server
7688 simply goes away. SIGPIPE is handled by x_connection_signal.
7689 Don't need to do anything, because the write which caused the
7690 SIGPIPE will fail, causing Xlib to invoke the X IO error handler,
7691 which will do the appropriate cleanup for us. */
7693 static SIGTYPE
7694 x_connection_signal (int signalnum) /* If we don't have an argument, */
7695 /* some compilers complain in signal calls. */
7697 #ifdef USG
7698 /* USG systems forget handlers when they are used;
7699 must reestablish each time */
7700 signal (signalnum, x_connection_signal);
7701 #endif /* USG */
7705 /************************************************************************
7706 Handling X errors
7707 ************************************************************************/
7709 /* Error message passed to x_connection_closed. */
7711 static char *error_msg;
7713 /* Function installed as fatal_error_signal_hook in
7714 x_connection_closed. Print the X error message, and exit normally,
7715 instead of dumping core when XtCloseDisplay fails. */
7717 static void
7718 x_fatal_error_signal (void)
7720 fprintf (stderr, "%s\n", error_msg);
7721 exit (70);
7724 /* Handle the loss of connection to display DPY. ERROR_MESSAGE is
7725 the text of an error message that lead to the connection loss. */
7727 static SIGTYPE
7728 x_connection_closed (Display *dpy, const char *error_message)
7730 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
7731 Lisp_Object frame, tail;
7732 int index = SPECPDL_INDEX ();
7734 error_msg = (char *) alloca (strlen (error_message) + 1);
7735 strcpy (error_msg, error_message);
7736 handling_signal = 0;
7738 /* Prevent being called recursively because of an error condition
7739 below. Otherwise, we might end up with printing ``can't find per
7740 display information'' in the recursive call instead of printing
7741 the original message here. */
7742 x_catch_errors (dpy);
7744 /* Inhibit redisplay while frames are being deleted. */
7745 specbind (Qinhibit_redisplay, Qt);
7747 if (dpyinfo)
7749 /* Protect display from being closed when we delete the last
7750 frame on it. */
7751 dpyinfo->reference_count++;
7752 dpyinfo->terminal->reference_count++;
7755 /* First delete frames whose mini-buffers are on frames
7756 that are on the dead display. */
7757 FOR_EACH_FRAME (tail, frame)
7759 Lisp_Object minibuf_frame;
7760 minibuf_frame
7761 = WINDOW_FRAME (XWINDOW (FRAME_MINIBUF_WINDOW (XFRAME (frame))));
7762 if (FRAME_X_P (XFRAME (frame))
7763 && FRAME_X_P (XFRAME (minibuf_frame))
7764 && ! EQ (frame, minibuf_frame)
7765 && FRAME_X_DISPLAY_INFO (XFRAME (minibuf_frame)) == dpyinfo)
7766 delete_frame (frame, Qnoelisp);
7769 /* Now delete all remaining frames on the dead display.
7770 We are now sure none of these is used as the mini-buffer
7771 for another frame that we need to delete. */
7772 FOR_EACH_FRAME (tail, frame)
7773 if (FRAME_X_P (XFRAME (frame))
7774 && FRAME_X_DISPLAY_INFO (XFRAME (frame)) == dpyinfo)
7776 /* Set this to t so that delete_frame won't get confused
7777 trying to find a replacement. */
7778 FRAME_KBOARD (XFRAME (frame))->Vdefault_minibuffer_frame = Qt;
7779 delete_frame (frame, Qnoelisp);
7782 /* If DPYINFO is null, this means we didn't open the display in the
7783 first place, so don't try to close it. */
7784 if (dpyinfo)
7786 #ifdef USE_X_TOOLKIT
7787 /* We have to close the display to inform Xt that it doesn't
7788 exist anymore. If we don't, Xt will continue to wait for
7789 events from the display. As a consequence, a sequence of
7791 M-x make-frame-on-display RET :1 RET
7792 ...kill the new frame, so that we get an IO error...
7793 M-x make-frame-on-display RET :1 RET
7795 will indefinitely wait in Xt for events for display `:1',
7796 opened in the first call to make-frame-on-display.
7798 Closing the display is reported to lead to a bus error on
7799 OpenWindows in certain situations. I suspect that is a bug
7800 in OpenWindows. I don't know how to circumvent it here. */
7801 fatal_error_signal_hook = x_fatal_error_signal;
7802 XtCloseDisplay (dpy);
7803 fatal_error_signal_hook = NULL;
7804 #endif /* USE_X_TOOLKIT */
7806 #ifdef USE_GTK
7807 /* A long-standing GTK bug prevents proper disconnect handling
7808 (https://bugzilla.gnome.org/show_bug.cgi?id=85715). Once,
7809 the resulting Glib error message loop filled a user's disk.
7810 To avoid this, kill Emacs unconditionally on disconnect. */
7811 shut_down_emacs (0, 0, Qnil);
7812 fprintf (stderr, "%s\n\
7813 When compiled with GTK, Emacs cannot recover from X disconnects.\n\
7814 This is a GTK bug: https://bugzilla.gnome.org/show_bug.cgi?id=85715\n\
7815 For details, see etc/PROBLEMS.\n",
7816 error_msg);
7817 abort ();
7818 #endif /* USE_GTK */
7820 /* Indicate that this display is dead. */
7821 dpyinfo->display = 0;
7823 dpyinfo->reference_count--;
7824 dpyinfo->terminal->reference_count--;
7825 if (dpyinfo->reference_count != 0)
7826 /* We have just closed all frames on this display. */
7827 abort ();
7830 Lisp_Object tmp;
7831 XSETTERMINAL (tmp, dpyinfo->terminal);
7832 Fdelete_terminal (tmp, Qnoelisp);
7836 x_uncatch_errors ();
7838 if (terminal_list == 0)
7840 fprintf (stderr, "%s\n", error_msg);
7841 Fkill_emacs (make_number (70));
7842 /* NOTREACHED */
7845 /* Ordinary stack unwind doesn't deal with these. */
7846 #ifdef SIGIO
7847 sigunblock (sigmask (SIGIO));
7848 #endif
7849 sigunblock (sigmask (SIGALRM));
7850 TOTALLY_UNBLOCK_INPUT;
7852 unbind_to (index, Qnil);
7853 clear_waiting_for_input ();
7854 /* Here, we absolutely have to use a non-local exit (e.g. signal, throw,
7855 longjmp), because returning from this function would get us back into
7856 Xlib's code which will directly call `exit'. */
7857 error ("%s", error_msg);
7860 /* We specifically use it before defining it, so that gcc doesn't inline it,
7861 otherwise gdb doesn't know how to properly put a breakpoint on it. */
7862 static void x_error_quitter (Display *, XErrorEvent *);
7864 /* This is the first-level handler for X protocol errors.
7865 It calls x_error_quitter or x_error_catcher. */
7867 static int
7868 x_error_handler (Display *display, XErrorEvent *error)
7870 if (x_error_message)
7871 x_error_catcher (display, error);
7872 else
7873 x_error_quitter (display, error);
7874 return 0;
7877 /* This is the usual handler for X protocol errors.
7878 It kills all frames on the display that we got the error for.
7879 If that was the only one, it prints an error message and kills Emacs. */
7881 /* .gdbinit puts a breakpoint here, so make sure it is not inlined. */
7883 /* On older GCC versions, just putting x_error_quitter
7884 after x_error_handler prevents inlining into the former. */
7886 static void NO_INLINE
7887 x_error_quitter (Display *display, XErrorEvent *error)
7889 char buf[256], buf1[356];
7891 /* Ignore BadName errors. They can happen because of fonts
7892 or colors that are not defined. */
7894 if (error->error_code == BadName)
7895 return;
7897 /* Note that there is no real way portable across R3/R4 to get the
7898 original error handler. */
7900 XGetErrorText (display, error->error_code, buf, sizeof (buf));
7901 sprintf (buf1, "X protocol error: %s on protocol request %d",
7902 buf, error->request_code);
7903 x_connection_closed (display, buf1);
7907 /* This is the handler for X IO errors, always.
7908 It kills all frames on the display that we lost touch with.
7909 If that was the only one, it prints an error message and kills Emacs. */
7911 static int
7912 x_io_error_quitter (Display *display)
7914 char buf[256];
7916 sprintf (buf, "Connection lost to X server `%s'", DisplayString (display));
7917 x_connection_closed (display, buf);
7918 return 0;
7921 /* Changing the font of the frame. */
7923 /* Give frame F the font FONT-OBJECT as its default font. The return
7924 value is FONT-OBJECT. FONTSET is an ID of the fontset for the
7925 frame. If it is negative, generate a new fontset from
7926 FONT-OBJECT. */
7928 Lisp_Object
7929 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
7931 struct font *font = XFONT_OBJECT (font_object);
7933 if (fontset < 0)
7934 fontset = fontset_from_font (font_object);
7935 FRAME_FONTSET (f) = fontset;
7936 if (FRAME_FONT (f) == font)
7937 /* This font is already set in frame F. There's nothing more to
7938 do. */
7939 return font_object;
7941 FRAME_FONT (f) = font;
7942 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
7943 FRAME_COLUMN_WIDTH (f) = font->average_width;
7944 FRAME_SPACE_WIDTH (f) = font->space_width;
7945 FRAME_LINE_HEIGHT (f) = FONT_HEIGHT (font);
7947 compute_fringe_widths (f, 1);
7949 /* Compute the scroll bar width in character columns. */
7950 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
7952 int wid = FRAME_COLUMN_WIDTH (f);
7953 FRAME_CONFIG_SCROLL_BAR_COLS (f)
7954 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid-1) / wid;
7956 else
7958 int wid = FRAME_COLUMN_WIDTH (f);
7959 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
7962 if (FRAME_X_WINDOW (f) != 0)
7964 /* Don't change the size of a tip frame; there's no point in
7965 doing it because it's done in Fx_show_tip, and it leads to
7966 problems because the tip frame has no widget. */
7967 if (NILP (tip_frame) || XFRAME (tip_frame) != f)
7968 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
7971 #ifdef HAVE_X_I18N
7972 if (FRAME_XIC (f)
7973 && (FRAME_XIC_STYLE (f) & (XIMPreeditPosition | XIMStatusArea)))
7975 BLOCK_INPUT;
7976 xic_set_xfontset (f, SDATA (fontset_ascii (fontset)));
7977 UNBLOCK_INPUT;
7979 #endif
7981 return font_object;
7985 /***********************************************************************
7986 X Input Methods
7987 ***********************************************************************/
7989 #ifdef HAVE_X_I18N
7991 #ifdef HAVE_X11R6
7993 /* XIM destroy callback function, which is called whenever the
7994 connection to input method XIM dies. CLIENT_DATA contains a
7995 pointer to the x_display_info structure corresponding to XIM. */
7997 static void
7998 xim_destroy_callback (XIM xim, XPointer client_data, XPointer call_data)
8000 struct x_display_info *dpyinfo = (struct x_display_info *) client_data;
8001 Lisp_Object frame, tail;
8003 BLOCK_INPUT;
8005 /* No need to call XDestroyIC.. */
8006 FOR_EACH_FRAME (tail, frame)
8008 struct frame *f = XFRAME (frame);
8009 if (FRAME_X_P (f) && FRAME_X_DISPLAY_INFO (f) == dpyinfo)
8011 FRAME_XIC (f) = NULL;
8012 xic_free_xfontset (f);
8016 /* No need to call XCloseIM. */
8017 dpyinfo->xim = NULL;
8018 XFree (dpyinfo->xim_styles);
8019 UNBLOCK_INPUT;
8022 #endif /* HAVE_X11R6 */
8024 #ifdef HAVE_X11R6
8025 /* This isn't prototyped in OSF 5.0 or 5.1a. */
8026 extern char *XSetIMValues (XIM, ...);
8027 #endif
8029 /* Open the connection to the XIM server on display DPYINFO.
8030 RESOURCE_NAME is the resource name Emacs uses. */
8032 static void
8033 xim_open_dpy (struct x_display_info *dpyinfo, char *resource_name)
8035 XIM xim;
8037 #ifdef HAVE_XIM
8038 if (use_xim)
8040 if (dpyinfo->xim)
8041 XCloseIM (dpyinfo->xim);
8042 xim = XOpenIM (dpyinfo->display, dpyinfo->xrdb, resource_name,
8043 emacs_class);
8044 dpyinfo->xim = xim;
8046 if (xim)
8048 #ifdef HAVE_X11R6
8049 XIMCallback destroy;
8050 #endif
8052 /* Get supported styles and XIM values. */
8053 XGetIMValues (xim, XNQueryInputStyle, &dpyinfo->xim_styles, NULL);
8055 #ifdef HAVE_X11R6
8056 destroy.callback = xim_destroy_callback;
8057 destroy.client_data = (XPointer)dpyinfo;
8058 XSetIMValues (xim, XNDestroyCallback, &destroy, NULL);
8059 #endif
8063 else
8064 #endif /* HAVE_XIM */
8065 dpyinfo->xim = NULL;
8069 #ifdef HAVE_X11R6_XIM
8071 /* XIM instantiate callback function, which is called whenever an XIM
8072 server is available. DISPLAY is the display of the XIM.
8073 CLIENT_DATA contains a pointer to an xim_inst_t structure created
8074 when the callback was registered. */
8076 static void
8077 xim_instantiate_callback (Display *display, XPointer client_data, XPointer call_data)
8079 struct xim_inst_t *xim_inst = (struct xim_inst_t *) client_data;
8080 struct x_display_info *dpyinfo = xim_inst->dpyinfo;
8082 /* We don't support multiple XIM connections. */
8083 if (dpyinfo->xim)
8084 return;
8086 xim_open_dpy (dpyinfo, xim_inst->resource_name);
8088 /* Create XIC for the existing frames on the same display, as long
8089 as they have no XIC. */
8090 if (dpyinfo->xim && dpyinfo->reference_count > 0)
8092 Lisp_Object tail, frame;
8094 BLOCK_INPUT;
8095 FOR_EACH_FRAME (tail, frame)
8097 struct frame *f = XFRAME (frame);
8099 if (FRAME_X_P (f)
8100 && FRAME_X_DISPLAY_INFO (f) == xim_inst->dpyinfo)
8101 if (FRAME_XIC (f) == NULL)
8103 create_frame_xic (f);
8104 if (FRAME_XIC_STYLE (f) & XIMStatusArea)
8105 xic_set_statusarea (f);
8106 if (FRAME_XIC_STYLE (f) & XIMPreeditPosition)
8108 struct window *w = XWINDOW (f->selected_window);
8109 xic_set_preeditarea (w, w->cursor.x, w->cursor.y);
8114 UNBLOCK_INPUT;
8118 #endif /* HAVE_X11R6_XIM */
8121 /* Open a connection to the XIM server on display DPYINFO.
8122 RESOURCE_NAME is the resource name for Emacs. On X11R5, open the
8123 connection only at the first time. On X11R6, open the connection
8124 in the XIM instantiate callback function. */
8126 static void
8127 xim_initialize (struct x_display_info *dpyinfo, char *resource_name)
8129 dpyinfo->xim = NULL;
8130 #ifdef HAVE_XIM
8131 if (use_xim)
8133 #ifdef HAVE_X11R6_XIM
8134 struct xim_inst_t *xim_inst;
8135 int len;
8137 xim_inst = (struct xim_inst_t *) xmalloc (sizeof (struct xim_inst_t));
8138 dpyinfo->xim_callback_data = xim_inst;
8139 xim_inst->dpyinfo = dpyinfo;
8140 len = strlen (resource_name);
8141 xim_inst->resource_name = (char *) xmalloc (len + 1);
8142 memcpy (xim_inst->resource_name, resource_name, len + 1);
8143 XRegisterIMInstantiateCallback (dpyinfo->display, dpyinfo->xrdb,
8144 resource_name, emacs_class,
8145 xim_instantiate_callback,
8146 /* This is XPointer in XFree86
8147 but (XPointer *) on Tru64, at
8148 least, hence the configure test. */
8149 (XRegisterIMInstantiateCallback_arg6) xim_inst);
8150 #else /* not HAVE_X11R6_XIM */
8151 xim_open_dpy (dpyinfo, resource_name);
8152 #endif /* not HAVE_X11R6_XIM */
8154 #endif /* HAVE_XIM */
8158 /* Close the connection to the XIM server on display DPYINFO. */
8160 static void
8161 xim_close_dpy (struct x_display_info *dpyinfo)
8163 #ifdef HAVE_XIM
8164 if (use_xim)
8166 #ifdef HAVE_X11R6_XIM
8167 if (dpyinfo->display)
8168 XUnregisterIMInstantiateCallback (dpyinfo->display, dpyinfo->xrdb,
8169 NULL, emacs_class,
8170 xim_instantiate_callback, NULL);
8171 xfree (dpyinfo->xim_callback_data->resource_name);
8172 xfree (dpyinfo->xim_callback_data);
8173 #endif /* HAVE_X11R6_XIM */
8174 if (dpyinfo->display)
8175 XCloseIM (dpyinfo->xim);
8176 dpyinfo->xim = NULL;
8177 XFree (dpyinfo->xim_styles);
8179 #endif /* HAVE_XIM */
8182 #endif /* not HAVE_X11R6_XIM */
8186 /* Calculate the absolute position in frame F
8187 from its current recorded position values and gravity. */
8189 void
8190 x_calc_absolute_position (struct frame *f)
8192 int flags = f->size_hint_flags;
8194 /* We have nothing to do if the current position
8195 is already for the top-left corner. */
8196 if (! ((flags & XNegative) || (flags & YNegative)))
8197 return;
8199 /* Treat negative positions as relative to the leftmost bottommost
8200 position that fits on the screen. */
8201 if (flags & XNegative)
8202 f->left_pos = x_display_pixel_width (FRAME_X_DISPLAY_INFO (f))
8203 - FRAME_PIXEL_WIDTH (f) + f->left_pos;
8206 int height = FRAME_PIXEL_HEIGHT (f);
8208 #if defined USE_X_TOOLKIT && defined USE_MOTIF
8209 /* Something is fishy here. When using Motif, starting Emacs with
8210 `-g -0-0', the frame appears too low by a few pixels.
8212 This seems to be so because initially, while Emacs is starting,
8213 the column widget's height and the frame's pixel height are
8214 different. The column widget's height is the right one. In
8215 later invocations, when Emacs is up, the frame's pixel height
8216 is right, though.
8218 It's not obvious where the initial small difference comes from.
8219 2000-12-01, gerd. */
8221 XtVaGetValues (f->output_data.x->column_widget, XtNheight, &height, NULL);
8222 #endif
8224 if (flags & YNegative)
8225 f->top_pos = x_display_pixel_height (FRAME_X_DISPLAY_INFO (f))
8226 - height + f->top_pos;
8229 /* The left_pos and top_pos
8230 are now relative to the top and left screen edges,
8231 so the flags should correspond. */
8232 f->size_hint_flags &= ~ (XNegative | YNegative);
8235 /* CHANGE_GRAVITY is 1 when calling from Fset_frame_position,
8236 to really change the position, and 0 when calling from
8237 x_make_frame_visible (in that case, XOFF and YOFF are the current
8238 position values). It is -1 when calling from x_set_frame_parameters,
8239 which means, do adjust for borders but don't change the gravity. */
8241 void
8242 x_set_offset (struct frame *f, register int xoff, register int yoff, int change_gravity)
8244 int modified_top, modified_left;
8246 if (change_gravity > 0)
8248 FRAME_X_OUTPUT (f)->left_before_move = f->left_pos;
8249 FRAME_X_OUTPUT (f)->top_before_move = f->top_pos;
8251 f->top_pos = yoff;
8252 f->left_pos = xoff;
8253 f->size_hint_flags &= ~ (XNegative | YNegative);
8254 if (xoff < 0)
8255 f->size_hint_flags |= XNegative;
8256 if (yoff < 0)
8257 f->size_hint_flags |= YNegative;
8258 f->win_gravity = NorthWestGravity;
8260 x_calc_absolute_position (f);
8262 BLOCK_INPUT;
8263 x_wm_set_size_hint (f, (long) 0, 0);
8265 modified_left = f->left_pos;
8266 modified_top = f->top_pos;
8268 if (change_gravity != 0 && FRAME_X_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A)
8270 /* Some WMs (twm, wmaker at least) has an offset that is smaller
8271 than the WM decorations. So we use the calculated offset instead
8272 of the WM decoration sizes here (x/y_pixels_outer_diff). */
8273 modified_left += FRAME_X_OUTPUT (f)->move_offset_left;
8274 modified_top += FRAME_X_OUTPUT (f)->move_offset_top;
8277 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8278 modified_left, modified_top);
8280 x_sync_with_move (f, f->left_pos, f->top_pos,
8281 FRAME_X_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN
8282 ? 1 : 0);
8284 /* change_gravity is non-zero when this function is called from Lisp to
8285 programmatically move a frame. In that case, we call
8286 x_check_expected_move to discover if we have a "Type A" or "Type B"
8287 window manager, and, for a "Type A" window manager, adjust the position
8288 of the frame.
8290 We call x_check_expected_move if a programmatic move occurred, and
8291 either the window manager type (A/B) is unknown or it is Type A but we
8292 need to compute the top/left offset adjustment for this frame. */
8294 if (change_gravity != 0 &&
8295 (FRAME_X_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN
8296 || (FRAME_X_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A
8297 && (FRAME_X_OUTPUT (f)->move_offset_left == 0
8298 && FRAME_X_OUTPUT (f)->move_offset_top == 0))))
8299 x_check_expected_move (f, modified_left, modified_top);
8301 UNBLOCK_INPUT;
8304 /* Return non-zero if _NET_SUPPORTING_WM_CHECK window exists and _NET_SUPPORTED
8305 on the root window for frame F contains ATOMNAME.
8306 This is how a WM check shall be done according to the Window Manager
8307 Specification/Extended Window Manager Hints at
8308 http://freedesktop.org/wiki/Specifications/wm-spec. */
8310 static int
8311 wm_supports (struct frame *f, Atom want_atom)
8313 Atom actual_type;
8314 unsigned long actual_size, bytes_remaining;
8315 int i, rc, actual_format;
8316 Window wmcheck_window;
8317 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8318 Window target_window = dpyinfo->root_window;
8319 long max_len = 65536;
8320 Display *dpy = FRAME_X_DISPLAY (f);
8321 unsigned char *tmp_data = NULL;
8322 Atom target_type = XA_WINDOW;
8324 BLOCK_INPUT;
8326 x_catch_errors (dpy);
8327 rc = XGetWindowProperty (dpy, target_window,
8328 dpyinfo->Xatom_net_supporting_wm_check,
8329 0, max_len, False, target_type,
8330 &actual_type, &actual_format, &actual_size,
8331 &bytes_remaining, &tmp_data);
8333 if (rc != Success || actual_type != XA_WINDOW || x_had_errors_p (dpy))
8335 if (tmp_data) XFree (tmp_data);
8336 x_uncatch_errors ();
8337 UNBLOCK_INPUT;
8338 return 0;
8341 wmcheck_window = *(Window *) tmp_data;
8342 XFree (tmp_data);
8344 /* Check if window exists. */
8345 XSelectInput (dpy, wmcheck_window, StructureNotifyMask);
8346 x_sync (f);
8347 if (x_had_errors_p (dpy))
8349 x_uncatch_errors ();
8350 UNBLOCK_INPUT;
8351 return 0;
8354 if (dpyinfo->net_supported_window != wmcheck_window)
8356 /* Window changed, reload atoms */
8357 if (dpyinfo->net_supported_atoms != NULL)
8358 XFree (dpyinfo->net_supported_atoms);
8359 dpyinfo->net_supported_atoms = NULL;
8360 dpyinfo->nr_net_supported_atoms = 0;
8361 dpyinfo->net_supported_window = 0;
8363 target_type = XA_ATOM;
8364 tmp_data = NULL;
8365 rc = XGetWindowProperty (dpy, target_window,
8366 dpyinfo->Xatom_net_supported,
8367 0, max_len, False, target_type,
8368 &actual_type, &actual_format, &actual_size,
8369 &bytes_remaining, &tmp_data);
8371 if (rc != Success || actual_type != XA_ATOM || x_had_errors_p (dpy))
8373 if (tmp_data) XFree (tmp_data);
8374 x_uncatch_errors ();
8375 UNBLOCK_INPUT;
8376 return 0;
8379 dpyinfo->net_supported_atoms = (Atom *)tmp_data;
8380 dpyinfo->nr_net_supported_atoms = actual_size;
8381 dpyinfo->net_supported_window = wmcheck_window;
8384 rc = 0;
8386 for (i = 0; rc == 0 && i < dpyinfo->nr_net_supported_atoms; ++i)
8387 rc = dpyinfo->net_supported_atoms[i] == want_atom;
8389 x_uncatch_errors ();
8390 UNBLOCK_INPUT;
8392 return rc;
8395 static void
8396 set_wm_state (Lisp_Object frame, int add, Atom atom, Atom value)
8398 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (XFRAME (frame));
8400 x_send_client_event (frame, make_number (0), frame,
8401 dpyinfo->Xatom_net_wm_state,
8402 make_number (32),
8403 /* 1 = add, 0 = remove */
8404 Fcons
8405 (make_number (add ? 1 : 0),
8406 Fcons
8407 (make_fixnum_or_float (atom),
8408 value != 0
8409 ? Fcons (make_fixnum_or_float (value), Qnil)
8410 : Qnil)));
8413 void
8414 x_set_sticky (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
8416 Lisp_Object frame;
8417 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8419 XSETFRAME (frame, f);
8421 set_wm_state (frame, NILP (new_value) ? 0 : 1,
8422 dpyinfo->Xatom_net_wm_state_sticky, None);
8425 /* Return the current _NET_WM_STATE.
8426 SIZE_STATE is set to one of the FULLSCREEN_* values.
8427 STICKY is set to 1 if the sticky state is set, 0 if not. */
8429 static void
8430 get_current_wm_state (struct frame *f,
8431 Window window,
8432 int *size_state,
8433 int *sticky)
8435 Atom actual_type;
8436 unsigned long actual_size, bytes_remaining;
8437 int i, rc, actual_format;
8438 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8439 long max_len = 65536;
8440 Display *dpy = FRAME_X_DISPLAY (f);
8441 unsigned char *tmp_data = NULL;
8442 Atom target_type = XA_ATOM;
8444 *sticky = 0;
8445 *size_state = FULLSCREEN_NONE;
8447 BLOCK_INPUT;
8448 x_catch_errors (dpy);
8449 rc = XGetWindowProperty (dpy, window, dpyinfo->Xatom_net_wm_state,
8450 0, max_len, False, target_type,
8451 &actual_type, &actual_format, &actual_size,
8452 &bytes_remaining, &tmp_data);
8454 if (rc != Success || actual_type != target_type || x_had_errors_p (dpy))
8456 if (tmp_data) XFree (tmp_data);
8457 x_uncatch_errors ();
8458 UNBLOCK_INPUT;
8459 return;
8462 x_uncatch_errors ();
8464 for (i = 0; i < actual_size; ++i)
8466 Atom a = ((Atom*)tmp_data)[i];
8467 if (a == dpyinfo->Xatom_net_wm_state_maximized_horz)
8469 if (*size_state == FULLSCREEN_HEIGHT)
8470 *size_state = FULLSCREEN_MAXIMIZED;
8471 else
8472 *size_state = FULLSCREEN_WIDTH;
8474 else if (a == dpyinfo->Xatom_net_wm_state_maximized_vert)
8476 if (*size_state == FULLSCREEN_WIDTH)
8477 *size_state = FULLSCREEN_MAXIMIZED;
8478 else
8479 *size_state = FULLSCREEN_HEIGHT;
8481 else if (a == dpyinfo->Xatom_net_wm_state_fullscreen)
8482 *size_state = FULLSCREEN_BOTH;
8483 else if (a == dpyinfo->Xatom_net_wm_state_sticky)
8484 *sticky = 1;
8487 if (tmp_data) XFree (tmp_data);
8488 UNBLOCK_INPUT;
8491 /* Do fullscreen as specified in extended window manager hints */
8493 static int
8494 do_ewmh_fullscreen (struct frame *f)
8496 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8497 int have_net_atom = wm_supports (f, dpyinfo->Xatom_net_wm_state);
8498 int cur, dummy;
8500 get_current_wm_state (f, FRAME_OUTER_WINDOW (f), &cur, &dummy);
8502 /* Some window managers don't say they support _NET_WM_STATE, but they do say
8503 they support _NET_WM_STATE_FULLSCREEN. Try that also. */
8504 if (!have_net_atom)
8505 have_net_atom = wm_supports (f, dpyinfo->Xatom_net_wm_state_fullscreen);
8507 if (have_net_atom && cur != f->want_fullscreen)
8509 Lisp_Object frame;
8511 XSETFRAME (frame, f);
8513 /* Keep number of calls to set_wm_state as low as possible.
8514 Some window managers, or possible Gtk+, hangs when too many
8515 are sent at once. */
8516 switch (f->want_fullscreen)
8518 case FULLSCREEN_BOTH:
8519 if (cur == FULLSCREEN_WIDTH || cur == FULLSCREEN_MAXIMIZED
8520 || cur == FULLSCREEN_HEIGHT)
8521 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_maximized_horz,
8522 dpyinfo->Xatom_net_wm_state_maximized_vert);
8523 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_fullscreen, None);
8524 break;
8525 case FULLSCREEN_WIDTH:
8526 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_HEIGHT
8527 || cur == FULLSCREEN_MAXIMIZED)
8528 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen,
8529 dpyinfo->Xatom_net_wm_state_maximized_vert);
8530 if (cur != FULLSCREEN_MAXIMIZED)
8531 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_maximized_horz, None);
8532 break;
8533 case FULLSCREEN_HEIGHT:
8534 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_WIDTH
8535 || cur == FULLSCREEN_MAXIMIZED)
8536 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen,
8537 dpyinfo->Xatom_net_wm_state_maximized_horz);
8538 if (cur != FULLSCREEN_MAXIMIZED)
8539 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_maximized_vert, None);
8540 break;
8541 case FULLSCREEN_MAXIMIZED:
8542 if (cur == FULLSCREEN_BOTH)
8543 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen, None);
8544 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_maximized_horz,
8545 dpyinfo->Xatom_net_wm_state_maximized_vert);
8546 break;
8547 case FULLSCREEN_NONE:
8548 if (cur == FULLSCREEN_BOTH)
8549 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen, None);
8550 else
8551 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_maximized_horz,
8552 dpyinfo->Xatom_net_wm_state_maximized_vert);
8555 f->want_fullscreen = FULLSCREEN_NONE;
8559 return have_net_atom;
8562 static void
8563 XTfullscreen_hook (FRAME_PTR f)
8565 if (f->async_visible)
8567 BLOCK_INPUT;
8568 x_check_fullscreen (f);
8569 x_sync (f);
8570 UNBLOCK_INPUT;
8575 static void
8576 x_handle_net_wm_state (struct frame *f, XPropertyEvent *event)
8578 int value = FULLSCREEN_NONE;
8579 Lisp_Object lval;
8580 int sticky = 0;
8582 get_current_wm_state (f, event->window, &value, &sticky);
8583 lval = Qnil;
8584 switch (value)
8586 case FULLSCREEN_WIDTH:
8587 lval = Qfullwidth;
8588 break;
8589 case FULLSCREEN_HEIGHT:
8590 lval = Qfullheight;
8591 break;
8592 case FULLSCREEN_BOTH:
8593 lval = Qfullboth;
8594 break;
8595 case FULLSCREEN_MAXIMIZED:
8596 lval = Qmaximized;
8597 break;
8600 store_frame_param (f, Qfullscreen, lval);
8601 store_frame_param (f, Qsticky, sticky ? Qt : Qnil);
8604 /* Check if we need to resize the frame due to a fullscreen request.
8605 If so needed, resize the frame. */
8606 static void
8607 x_check_fullscreen (struct frame *f)
8609 if (do_ewmh_fullscreen (f))
8610 return;
8612 if (f->output_data.x->parent_desc != FRAME_X_DISPLAY_INFO (f)->root_window)
8613 return; /* Only fullscreen without WM or with EWM hints (above). */
8615 /* Setting fullscreen to nil doesn't do anything. We could save the
8616 last non-fullscreen size and restore it, but it seems like a
8617 lot of work for this unusual case (no window manager running). */
8619 if (f->want_fullscreen != FULLSCREEN_NONE)
8621 int width = FRAME_PIXEL_WIDTH (f), height = FRAME_PIXEL_HEIGHT (f);
8622 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8624 switch (f->want_fullscreen)
8626 /* No difference between these two when there is no WM */
8627 case FULLSCREEN_BOTH:
8628 case FULLSCREEN_MAXIMIZED:
8629 width = x_display_pixel_width (dpyinfo);
8630 height = x_display_pixel_height (dpyinfo);
8631 break;
8632 case FULLSCREEN_WIDTH:
8633 width = x_display_pixel_width (dpyinfo);
8634 break;
8635 case FULLSCREEN_HEIGHT:
8636 height = x_display_pixel_height (dpyinfo);
8639 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8640 width, height);
8644 /* This function is called by x_set_offset to determine whether the window
8645 manager interfered with the positioning of the frame. Type A window
8646 managers position the surrounding window manager decorations a small
8647 amount above and left of the user-supplied position. Type B window
8648 managers position the surrounding window manager decorations at the
8649 user-specified position. If we detect a Type A window manager, we
8650 compensate by moving the window right and down by the proper amount. */
8652 static void
8653 x_check_expected_move (struct frame *f, int expected_left, int expected_top)
8655 int current_left = 0, current_top = 0;
8657 /* x_real_positions returns the left and top offsets of the outermost
8658 window manager window around the frame. */
8660 x_real_positions (f, &current_left, &current_top);
8662 if (current_left != expected_left || current_top != expected_top)
8664 /* It's a "Type A" window manager. */
8666 int adjusted_left;
8667 int adjusted_top;
8669 FRAME_X_DISPLAY_INFO (f)->wm_type = X_WMTYPE_A;
8670 FRAME_X_OUTPUT (f)->move_offset_left = expected_left - current_left;
8671 FRAME_X_OUTPUT (f)->move_offset_top = expected_top - current_top;
8673 /* Now fix the mispositioned frame's location. */
8675 adjusted_left = expected_left + FRAME_X_OUTPUT (f)->move_offset_left;
8676 adjusted_top = expected_top + FRAME_X_OUTPUT (f)->move_offset_top;
8678 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8679 adjusted_left, adjusted_top);
8681 x_sync_with_move (f, expected_left, expected_top, 0);
8683 else
8684 /* It's a "Type B" window manager. We don't have to adjust the
8685 frame's position. */
8687 FRAME_X_DISPLAY_INFO (f)->wm_type = X_WMTYPE_B;
8691 /* Wait for XGetGeometry to return up-to-date position information for a
8692 recently-moved frame. Call this immediately after calling XMoveWindow.
8693 If FUZZY is non-zero, then LEFT and TOP are just estimates of where the
8694 frame has been moved to, so we use a fuzzy position comparison instead
8695 of an exact comparison. */
8697 static void
8698 x_sync_with_move (struct frame *f, int left, int top, int fuzzy)
8700 int count = 0;
8702 while (count++ < 50)
8704 int current_left = 0, current_top = 0;
8706 /* In theory, this call to XSync only needs to happen once, but in
8707 practice, it doesn't seem to work, hence the need for the surrounding
8708 loop. */
8710 XSync (FRAME_X_DISPLAY (f), False);
8711 x_real_positions (f, &current_left, &current_top);
8713 if (fuzzy)
8715 /* The left fuzz-factor is 10 pixels. The top fuzz-factor is 40
8716 pixels. */
8718 if (eabs (current_left - left) <= 10
8719 && eabs (current_top - top) <= 40)
8720 return;
8722 else if (current_left == left && current_top == top)
8723 return;
8726 /* As a last resort, just wait 0.5 seconds and hope that XGetGeometry
8727 will then return up-to-date position info. */
8729 wait_reading_process_output (0, 500000, 0, 0, Qnil, NULL, 0);
8733 /* Wait for an event on frame F matching EVENTTYPE. */
8734 void
8735 x_wait_for_event (struct frame *f, int eventtype)
8737 int level = interrupt_input_blocked;
8739 SELECT_TYPE fds;
8740 EMACS_TIME tmo, tmo_at, time_now;
8741 int fd = ConnectionNumber (FRAME_X_DISPLAY (f));
8743 pending_event_wait.f = f;
8744 pending_event_wait.eventtype = eventtype;
8746 /* Set timeout to 0.1 second. Hopefully not noticable.
8747 Maybe it should be configurable. */
8748 EMACS_SET_SECS_USECS (tmo, 0, 100000);
8749 EMACS_GET_TIME (tmo_at);
8750 EMACS_ADD_TIME (tmo_at, tmo_at, tmo);
8752 while (pending_event_wait.eventtype)
8754 interrupt_input_pending = 1;
8755 TOTALLY_UNBLOCK_INPUT;
8756 /* XTread_socket is called after unblock. */
8757 BLOCK_INPUT;
8758 interrupt_input_blocked = level;
8760 FD_ZERO (&fds);
8761 FD_SET (fd, &fds);
8763 EMACS_GET_TIME (time_now);
8764 EMACS_SUB_TIME (tmo, tmo_at, time_now);
8766 if (EMACS_TIME_NEG_P (tmo) || select (fd+1, &fds, NULL, NULL, &tmo) == 0)
8767 break; /* Timeout */
8769 pending_event_wait.f = 0;
8770 pending_event_wait.eventtype = 0;
8774 /* Change the size of frame F's X window to COLS/ROWS in the case F
8775 doesn't have a widget. If CHANGE_GRAVITY is 1, we change to
8776 top-left-corner window gravity for this size change and subsequent
8777 size changes. Otherwise we leave the window gravity unchanged. */
8779 static void
8780 x_set_window_size_1 (struct frame *f, int change_gravity, int cols, int rows)
8782 int pixelwidth, pixelheight;
8784 check_frame_size (f, &rows, &cols);
8785 f->scroll_bar_actual_width
8786 = (!FRAME_HAS_VERTICAL_SCROLL_BARS (f)
8788 : FRAME_CONFIG_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f));
8790 compute_fringe_widths (f, 0);
8792 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, cols)
8793 + FRAME_TOOLBAR_WIDTH (f);
8794 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows)
8795 + FRAME_MENUBAR_HEIGHT (f) + FRAME_TOOLBAR_HEIGHT (f);
8797 if (change_gravity) f->win_gravity = NorthWestGravity;
8798 x_wm_set_size_hint (f, (long) 0, 0);
8799 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8800 pixelwidth, pixelheight);
8803 /* We've set {FRAME,PIXEL}_{WIDTH,HEIGHT} to the values we hope to
8804 receive in the ConfigureNotify event; if we get what we asked
8805 for, then the event won't cause the screen to become garbaged, so
8806 we have to make sure to do it here. */
8807 SET_FRAME_GARBAGED (f);
8809 /* Now, strictly speaking, we can't be sure that this is accurate,
8810 but the window manager will get around to dealing with the size
8811 change request eventually, and we'll hear how it went when the
8812 ConfigureNotify event gets here.
8814 We could just not bother storing any of this information here,
8815 and let the ConfigureNotify event set everything up, but that
8816 might be kind of confusing to the Lisp code, since size changes
8817 wouldn't be reported in the frame parameters until some random
8818 point in the future when the ConfigureNotify event arrives.
8820 We pass 1 for DELAY since we can't run Lisp code inside of
8821 a BLOCK_INPUT. */
8823 /* But the ConfigureNotify may in fact never arrive, and then this is
8824 not right if the frame is visible. Instead wait (with timeout)
8825 for the ConfigureNotify. */
8826 if (f->async_visible)
8827 x_wait_for_event (f, ConfigureNotify);
8828 else
8830 change_frame_size (f, rows, cols, 0, 1, 0);
8831 FRAME_PIXEL_WIDTH (f) = pixelwidth;
8832 FRAME_PIXEL_HEIGHT (f) = pixelheight;
8833 x_sync (f);
8838 /* Call this to change the size of frame F's x-window.
8839 If CHANGE_GRAVITY is 1, we change to top-left-corner window gravity
8840 for this size change and subsequent size changes.
8841 Otherwise we leave the window gravity unchanged. */
8843 void
8844 x_set_window_size (struct frame *f, int change_gravity, int cols, int rows)
8846 BLOCK_INPUT;
8848 if (NILP (tip_frame) || XFRAME (tip_frame) != f)
8850 int r, c;
8852 /* When the frame is maximized/fullscreen or running under for
8853 example Xmonad, x_set_window_size_1 will be a no-op.
8854 In that case, the right thing to do is extend rows/cols to
8855 the current frame size. We do that first if x_set_window_size_1
8856 turns out to not be a no-op (there is no way to know).
8857 The size will be adjusted again if the frame gets a
8858 ConfigureNotify event as a result of x_set_window_size. */
8859 int pixelh = FRAME_PIXEL_HEIGHT (f);
8860 #ifdef USE_X_TOOLKIT
8861 /* The menu bar is not part of text lines. The tool bar
8862 is however. */
8863 pixelh -= FRAME_MENUBAR_HEIGHT (f);
8864 #endif
8865 r = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, pixelh);
8866 /* Update f->scroll_bar_actual_width because it is used in
8867 FRAME_PIXEL_WIDTH_TO_TEXT_COLS. */
8868 f->scroll_bar_actual_width
8869 = FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f);
8870 c = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, FRAME_PIXEL_WIDTH (f));
8871 change_frame_size (f, r, c, 0, 1, 0);
8874 #ifdef USE_GTK
8875 if (FRAME_GTK_WIDGET (f))
8876 xg_frame_set_char_size (f, cols, rows);
8877 else
8878 x_set_window_size_1 (f, change_gravity, cols, rows);
8879 #else /* not USE_GTK */
8881 x_set_window_size_1 (f, change_gravity, cols, rows);
8883 #endif /* not USE_GTK */
8885 /* If cursor was outside the new size, mark it as off. */
8886 mark_window_cursors_off (XWINDOW (f->root_window));
8888 /* Clear out any recollection of where the mouse highlighting was,
8889 since it might be in a place that's outside the new frame size.
8890 Actually checking whether it is outside is a pain in the neck,
8891 so don't try--just let the highlighting be done afresh with new size. */
8892 cancel_mouse_face (f);
8894 UNBLOCK_INPUT;
8897 /* Mouse warping. */
8899 void
8900 x_set_mouse_position (struct frame *f, int x, int y)
8902 int pix_x, pix_y;
8904 pix_x = FRAME_COL_TO_PIXEL_X (f, x) + FRAME_COLUMN_WIDTH (f) / 2;
8905 pix_y = FRAME_LINE_TO_PIXEL_Y (f, y) + FRAME_LINE_HEIGHT (f) / 2;
8907 if (pix_x < 0) pix_x = 0;
8908 if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
8910 if (pix_y < 0) pix_y = 0;
8911 if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
8913 BLOCK_INPUT;
8915 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
8916 0, 0, 0, 0, pix_x, pix_y);
8917 UNBLOCK_INPUT;
8920 /* Move the mouse to position pixel PIX_X, PIX_Y relative to frame F. */
8922 void
8923 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
8925 BLOCK_INPUT;
8927 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
8928 0, 0, 0, 0, pix_x, pix_y);
8929 UNBLOCK_INPUT;
8932 /* focus shifting, raising and lowering. */
8934 void
8935 x_focus_on_frame (struct frame *f)
8937 #if 0
8938 /* I don't think that the ICCCM allows programs to do things like this
8939 without the interaction of the window manager. Whatever you end up
8940 doing with this code, do it to x_unfocus_frame too. */
8941 XSetInputFocus (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
8942 RevertToPointerRoot, CurrentTime);
8943 #endif /* ! 0 */
8946 void
8947 x_unfocus_frame (struct frame *f)
8949 #if 0
8950 /* Look at the remarks in x_focus_on_frame. */
8951 if (FRAME_X_DISPLAY_INFO (f)->x_focus_frame == f)
8952 XSetInputFocus (FRAME_X_DISPLAY (f), PointerRoot,
8953 RevertToPointerRoot, CurrentTime);
8954 #endif /* ! 0 */
8957 /* Raise frame F. */
8959 void
8960 x_raise_frame (struct frame *f)
8962 BLOCK_INPUT;
8963 if (f->async_visible)
8964 XRaiseWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
8966 XFlush (FRAME_X_DISPLAY (f));
8967 UNBLOCK_INPUT;
8970 /* Lower frame F. */
8972 void
8973 x_lower_frame (struct frame *f)
8975 if (f->async_visible)
8977 BLOCK_INPUT;
8978 XLowerWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
8979 XFlush (FRAME_X_DISPLAY (f));
8980 UNBLOCK_INPUT;
8984 /* Activate frame with Extended Window Manager Hints */
8986 void
8987 x_ewmh_activate_frame (FRAME_PTR f)
8989 /* See Window Manager Specification/Extended Window Manager Hints at
8990 http://freedesktop.org/wiki/Specifications/wm-spec */
8992 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8993 if (f->async_visible && wm_supports (f, dpyinfo->Xatom_net_active_window))
8995 Lisp_Object frame;
8996 XSETFRAME (frame, f);
8997 x_send_client_event (frame, make_number (0), frame,
8998 dpyinfo->Xatom_net_active_window,
8999 make_number (32),
9000 Fcons (make_number (1),
9001 Fcons (make_number (last_user_time),
9002 Qnil)));
9006 static void
9007 XTframe_raise_lower (FRAME_PTR f, int raise_flag)
9009 if (raise_flag)
9010 x_raise_frame (f);
9011 else
9012 x_lower_frame (f);
9015 /* XEmbed implementation. */
9017 static void
9018 xembed_set_info (struct frame *f, enum xembed_info flags)
9020 unsigned long data[2];
9021 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
9023 data[0] = XEMBED_VERSION;
9024 data[1] = flags;
9026 XChangeProperty (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
9027 dpyinfo->Xatom_XEMBED_INFO, dpyinfo->Xatom_XEMBED_INFO,
9028 32, PropModeReplace, (unsigned char *) data, 2);
9031 static void
9032 xembed_send_message (struct frame *f, Time time, enum xembed_message message, long int detail, long int data1, long int data2)
9034 XEvent event;
9036 event.xclient.type = ClientMessage;
9037 event.xclient.window = FRAME_X_OUTPUT (f)->parent_desc;
9038 event.xclient.message_type = FRAME_X_DISPLAY_INFO (f)->Xatom_XEMBED;
9039 event.xclient.format = 32;
9040 event.xclient.data.l[0] = time;
9041 event.xclient.data.l[1] = message;
9042 event.xclient.data.l[2] = detail;
9043 event.xclient.data.l[3] = data1;
9044 event.xclient.data.l[4] = data2;
9046 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_OUTPUT (f)->parent_desc,
9047 False, NoEventMask, &event);
9048 XSync (FRAME_X_DISPLAY (f), False);
9051 /* Change of visibility. */
9053 /* This tries to wait until the frame is really visible.
9054 However, if the window manager asks the user where to position
9055 the frame, this will return before the user finishes doing that.
9056 The frame will not actually be visible at that time,
9057 but it will become visible later when the window manager
9058 finishes with it. */
9060 void
9061 x_make_frame_visible (struct frame *f)
9063 Lisp_Object type;
9064 int original_top, original_left;
9065 int retry_count = 2;
9067 retry:
9069 BLOCK_INPUT;
9071 type = x_icon_type (f);
9072 if (!NILP (type))
9073 x_bitmap_icon (f, type);
9075 if (! FRAME_VISIBLE_P (f))
9077 /* We test FRAME_GARBAGED_P here to make sure we don't
9078 call x_set_offset a second time
9079 if we get to x_make_frame_visible a second time
9080 before the window gets really visible. */
9081 if (! FRAME_ICONIFIED_P (f)
9082 && ! FRAME_X_EMBEDDED_P (f)
9083 && ! f->output_data.x->asked_for_visible)
9084 x_set_offset (f, f->left_pos, f->top_pos, 0);
9086 f->output_data.x->asked_for_visible = 1;
9088 if (! EQ (Vx_no_window_manager, Qt))
9089 x_wm_set_window_state (f, NormalState);
9090 #ifdef USE_X_TOOLKIT
9091 if (FRAME_X_EMBEDDED_P (f))
9092 xembed_set_info (f, XEMBED_MAPPED);
9093 else
9095 /* This was XtPopup, but that did nothing for an iconified frame. */
9096 XtMapWidget (f->output_data.x->widget);
9098 #else /* not USE_X_TOOLKIT */
9099 #ifdef USE_GTK
9100 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
9101 gtk_window_deiconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
9102 #else
9103 if (FRAME_X_EMBEDDED_P (f))
9104 xembed_set_info (f, XEMBED_MAPPED);
9105 else
9106 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9107 #endif /* not USE_GTK */
9108 #endif /* not USE_X_TOOLKIT */
9111 XFlush (FRAME_X_DISPLAY (f));
9113 /* Synchronize to ensure Emacs knows the frame is visible
9114 before we do anything else. We do this loop with input not blocked
9115 so that incoming events are handled. */
9117 Lisp_Object frame;
9118 int count;
9119 /* This must be before UNBLOCK_INPUT
9120 since events that arrive in response to the actions above
9121 will set it when they are handled. */
9122 int previously_visible = f->output_data.x->has_been_visible;
9124 original_left = f->left_pos;
9125 original_top = f->top_pos;
9127 /* This must come after we set COUNT. */
9128 UNBLOCK_INPUT;
9130 /* We unblock here so that arriving X events are processed. */
9132 /* Now move the window back to where it was "supposed to be".
9133 But don't do it if the gravity is negative.
9134 When the gravity is negative, this uses a position
9135 that is 3 pixels too low. Perhaps that's really the border width.
9137 Don't do this if the window has never been visible before,
9138 because the window manager may choose the position
9139 and we don't want to override it. */
9141 if (! FRAME_VISIBLE_P (f)
9142 && ! FRAME_ICONIFIED_P (f)
9143 && ! FRAME_X_EMBEDDED_P (f)
9144 && f->win_gravity == NorthWestGravity
9145 && previously_visible)
9147 Drawable rootw;
9148 int x, y;
9149 unsigned int width, height, border, depth;
9151 BLOCK_INPUT;
9153 /* On some window managers (such as FVWM) moving an existing
9154 window, even to the same place, causes the window manager
9155 to introduce an offset. This can cause the window to move
9156 to an unexpected location. Check the geometry (a little
9157 slow here) and then verify that the window is in the right
9158 place. If the window is not in the right place, move it
9159 there, and take the potential window manager hit. */
9160 XGetGeometry (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
9161 &rootw, &x, &y, &width, &height, &border, &depth);
9163 if (original_left != x || original_top != y)
9164 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
9165 original_left, original_top);
9167 UNBLOCK_INPUT;
9170 XSETFRAME (frame, f);
9172 /* Wait until the frame is visible. Process X events until a
9173 MapNotify event has been seen, or until we think we won't get a
9174 MapNotify at all.. */
9175 for (count = input_signal_count + 10;
9176 input_signal_count < count && !FRAME_VISIBLE_P (f);)
9178 /* Force processing of queued events. */
9179 x_sync (f);
9181 /* Machines that do polling rather than SIGIO have been
9182 observed to go into a busy-wait here. So we'll fake an
9183 alarm signal to let the handler know that there's something
9184 to be read. We used to raise a real alarm, but it seems
9185 that the handler isn't always enabled here. This is
9186 probably a bug. */
9187 if (input_polling_used ())
9189 /* It could be confusing if a real alarm arrives while
9190 processing the fake one. Turn it off and let the
9191 handler reset it. */
9192 int old_poll_suppress_count = poll_suppress_count;
9193 poll_suppress_count = 1;
9194 poll_for_input_1 ();
9195 poll_suppress_count = old_poll_suppress_count;
9198 /* See if a MapNotify event has been processed. */
9199 FRAME_SAMPLE_VISIBILITY (f);
9202 /* 2000-09-28: In
9204 (let ((f (selected-frame)))
9205 (iconify-frame f)
9206 (raise-frame f))
9208 the frame is not raised with various window managers on
9209 FreeBSD, GNU/Linux and Solaris. It turns out that, for some
9210 unknown reason, the call to XtMapWidget is completely ignored.
9211 Mapping the widget a second time works. */
9213 if (!FRAME_VISIBLE_P (f) && --retry_count > 0)
9214 goto retry;
9218 /* Change from mapped state to withdrawn state. */
9220 /* Make the frame visible (mapped and not iconified). */
9222 void
9223 x_make_frame_invisible (struct frame *f)
9225 Window window;
9227 /* Use the frame's outermost window, not the one we normally draw on. */
9228 window = FRAME_OUTER_WINDOW (f);
9230 /* Don't keep the highlight on an invisible frame. */
9231 if (FRAME_X_DISPLAY_INFO (f)->x_highlight_frame == f)
9232 FRAME_X_DISPLAY_INFO (f)->x_highlight_frame = 0;
9234 BLOCK_INPUT;
9236 /* Before unmapping the window, update the WM_SIZE_HINTS property to claim
9237 that the current position of the window is user-specified, rather than
9238 program-specified, so that when the window is mapped again, it will be
9239 placed at the same location, without forcing the user to position it
9240 by hand again (they have already done that once for this window.) */
9241 x_wm_set_size_hint (f, (long) 0, 1);
9243 #ifdef USE_GTK
9244 if (FRAME_GTK_OUTER_WIDGET (f))
9245 gtk_widget_hide (FRAME_GTK_OUTER_WIDGET (f));
9246 else
9247 #else
9248 if (FRAME_X_EMBEDDED_P (f))
9249 xembed_set_info (f, 0);
9250 else
9251 #endif
9254 if (! XWithdrawWindow (FRAME_X_DISPLAY (f), window,
9255 DefaultScreen (FRAME_X_DISPLAY (f))))
9257 UNBLOCK_INPUT_RESIGNAL;
9258 error ("Can't notify window manager of window withdrawal");
9262 /* We can't distinguish this from iconification
9263 just by the event that we get from the server.
9264 So we can't win using the usual strategy of letting
9265 FRAME_SAMPLE_VISIBILITY set this. So do it by hand,
9266 and synchronize with the server to make sure we agree. */
9267 f->visible = 0;
9268 FRAME_ICONIFIED_P (f) = 0;
9269 f->async_visible = 0;
9270 f->async_iconified = 0;
9272 x_sync (f);
9274 UNBLOCK_INPUT;
9277 /* Change window state from mapped to iconified. */
9279 void
9280 x_iconify_frame (struct frame *f)
9282 int result;
9283 Lisp_Object type;
9285 /* Don't keep the highlight on an invisible frame. */
9286 if (FRAME_X_DISPLAY_INFO (f)->x_highlight_frame == f)
9287 FRAME_X_DISPLAY_INFO (f)->x_highlight_frame = 0;
9289 if (f->async_iconified)
9290 return;
9292 BLOCK_INPUT;
9294 FRAME_SAMPLE_VISIBILITY (f);
9296 type = x_icon_type (f);
9297 if (!NILP (type))
9298 x_bitmap_icon (f, type);
9300 #ifdef USE_GTK
9301 if (FRAME_GTK_OUTER_WIDGET (f))
9303 if (! FRAME_VISIBLE_P (f))
9304 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
9306 gtk_window_iconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
9307 f->iconified = 1;
9308 f->visible = 1;
9309 f->async_iconified = 1;
9310 f->async_visible = 0;
9311 UNBLOCK_INPUT;
9312 return;
9314 #endif
9316 #ifdef USE_X_TOOLKIT
9318 if (! FRAME_VISIBLE_P (f))
9320 if (! EQ (Vx_no_window_manager, Qt))
9321 x_wm_set_window_state (f, IconicState);
9322 /* This was XtPopup, but that did nothing for an iconified frame. */
9323 XtMapWidget (f->output_data.x->widget);
9324 /* The server won't give us any event to indicate
9325 that an invisible frame was changed to an icon,
9326 so we have to record it here. */
9327 f->iconified = 1;
9328 f->visible = 1;
9329 f->async_iconified = 1;
9330 f->async_visible = 0;
9331 UNBLOCK_INPUT;
9332 return;
9335 result = XIconifyWindow (FRAME_X_DISPLAY (f),
9336 XtWindow (f->output_data.x->widget),
9337 DefaultScreen (FRAME_X_DISPLAY (f)));
9338 UNBLOCK_INPUT;
9340 if (!result)
9341 error ("Can't notify window manager of iconification");
9343 f->async_iconified = 1;
9344 f->async_visible = 0;
9347 BLOCK_INPUT;
9348 XFlush (FRAME_X_DISPLAY (f));
9349 UNBLOCK_INPUT;
9350 #else /* not USE_X_TOOLKIT */
9352 /* Make sure the X server knows where the window should be positioned,
9353 in case the user deiconifies with the window manager. */
9354 if (! FRAME_VISIBLE_P (f)
9355 && ! FRAME_ICONIFIED_P (f)
9356 && ! FRAME_X_EMBEDDED_P (f))
9357 x_set_offset (f, f->left_pos, f->top_pos, 0);
9359 /* Since we don't know which revision of X we're running, we'll use both
9360 the X11R3 and X11R4 techniques. I don't know if this is a good idea. */
9362 /* X11R4: send a ClientMessage to the window manager using the
9363 WM_CHANGE_STATE type. */
9365 XEvent message;
9367 message.xclient.window = FRAME_X_WINDOW (f);
9368 message.xclient.type = ClientMessage;
9369 message.xclient.message_type = FRAME_X_DISPLAY_INFO (f)->Xatom_wm_change_state;
9370 message.xclient.format = 32;
9371 message.xclient.data.l[0] = IconicState;
9373 if (! XSendEvent (FRAME_X_DISPLAY (f),
9374 DefaultRootWindow (FRAME_X_DISPLAY (f)),
9375 False,
9376 SubstructureRedirectMask | SubstructureNotifyMask,
9377 &message))
9379 UNBLOCK_INPUT_RESIGNAL;
9380 error ("Can't notify window manager of iconification");
9384 /* X11R3: set the initial_state field of the window manager hints to
9385 IconicState. */
9386 x_wm_set_window_state (f, IconicState);
9388 if (!FRAME_VISIBLE_P (f))
9390 /* If the frame was withdrawn, before, we must map it. */
9391 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9394 f->async_iconified = 1;
9395 f->async_visible = 0;
9397 XFlush (FRAME_X_DISPLAY (f));
9398 UNBLOCK_INPUT;
9399 #endif /* not USE_X_TOOLKIT */
9403 /* Free X resources of frame F. */
9405 void
9406 x_free_frame_resources (struct frame *f)
9408 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
9409 Lisp_Object bar;
9410 struct scroll_bar *b;
9411 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
9413 BLOCK_INPUT;
9415 /* If a display connection is dead, don't try sending more
9416 commands to the X server. */
9417 if (dpyinfo->display)
9419 /* We must free faces before destroying windows because some
9420 font-driver (e.g. xft) access a window while finishing a
9421 face. */
9422 if (FRAME_FACE_CACHE (f))
9423 free_frame_faces (f);
9425 if (f->output_data.x->icon_desc)
9426 XDestroyWindow (FRAME_X_DISPLAY (f), f->output_data.x->icon_desc);
9428 #ifdef USE_X_TOOLKIT
9429 /* Explicitly destroy the scroll bars of the frame. Without
9430 this, we get "BadDrawable" errors from the toolkit later on,
9431 presumably from expose events generated for the disappearing
9432 toolkit scroll bars. */
9433 for (bar = FRAME_SCROLL_BARS (f); !NILP (bar); bar = b->next)
9435 b = XSCROLL_BAR (bar);
9436 x_scroll_bar_remove (b);
9438 #endif
9440 #ifdef HAVE_X_I18N
9441 if (FRAME_XIC (f))
9442 free_frame_xic (f);
9443 #endif
9445 #ifdef USE_X_TOOLKIT
9446 if (f->output_data.x->widget)
9448 XtDestroyWidget (f->output_data.x->widget);
9449 f->output_data.x->widget = NULL;
9451 /* Tooltips don't have widgets, only a simple X window, even if
9452 we are using a toolkit. */
9453 else if (FRAME_X_WINDOW (f))
9454 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9456 free_frame_menubar (f);
9457 #else /* !USE_X_TOOLKIT */
9459 #ifdef USE_GTK
9460 xg_free_frame_widgets (f);
9461 #endif /* USE_GTK */
9463 if (FRAME_X_WINDOW (f))
9464 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9465 #endif /* !USE_X_TOOLKIT */
9467 unload_color (f, FRAME_FOREGROUND_PIXEL (f));
9468 unload_color (f, FRAME_BACKGROUND_PIXEL (f));
9469 unload_color (f, f->output_data.x->cursor_pixel);
9470 unload_color (f, f->output_data.x->cursor_foreground_pixel);
9471 unload_color (f, f->output_data.x->border_pixel);
9472 unload_color (f, f->output_data.x->mouse_pixel);
9474 if (f->output_data.x->scroll_bar_background_pixel != -1)
9475 unload_color (f, f->output_data.x->scroll_bar_background_pixel);
9476 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
9477 unload_color (f, f->output_data.x->scroll_bar_foreground_pixel);
9478 #ifdef USE_TOOLKIT_SCROLL_BARS
9479 /* Scrollbar shadow colors. */
9480 if (f->output_data.x->scroll_bar_top_shadow_pixel != -1)
9481 unload_color (f, f->output_data.x->scroll_bar_top_shadow_pixel);
9482 if (f->output_data.x->scroll_bar_bottom_shadow_pixel != -1)
9483 unload_color (f, f->output_data.x->scroll_bar_bottom_shadow_pixel);
9484 #endif /* USE_TOOLKIT_SCROLL_BARS */
9485 if (f->output_data.x->white_relief.allocated_p)
9486 unload_color (f, f->output_data.x->white_relief.pixel);
9487 if (f->output_data.x->black_relief.allocated_p)
9488 unload_color (f, f->output_data.x->black_relief.pixel);
9490 x_free_gcs (f);
9491 XFlush (FRAME_X_DISPLAY (f));
9494 xfree (f->output_data.x->saved_menu_event);
9495 xfree (f->output_data.x);
9496 f->output_data.x = NULL;
9498 if (f == dpyinfo->x_focus_frame)
9499 dpyinfo->x_focus_frame = 0;
9500 if (f == dpyinfo->x_focus_event_frame)
9501 dpyinfo->x_focus_event_frame = 0;
9502 if (f == dpyinfo->x_highlight_frame)
9503 dpyinfo->x_highlight_frame = 0;
9505 if (f == hlinfo->mouse_face_mouse_frame)
9507 hlinfo->mouse_face_beg_row
9508 = hlinfo->mouse_face_beg_col = -1;
9509 hlinfo->mouse_face_end_row
9510 = hlinfo->mouse_face_end_col = -1;
9511 hlinfo->mouse_face_window = Qnil;
9512 hlinfo->mouse_face_deferred_gc = 0;
9513 hlinfo->mouse_face_mouse_frame = 0;
9516 UNBLOCK_INPUT;
9520 /* Destroy the X window of frame F. */
9522 void
9523 x_destroy_window (struct frame *f)
9525 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
9527 /* If a display connection is dead, don't try sending more
9528 commands to the X server. */
9529 if (dpyinfo->display != 0)
9530 x_free_frame_resources (f);
9532 dpyinfo->reference_count--;
9536 /* Setting window manager hints. */
9538 /* Set the normal size hints for the window manager, for frame F.
9539 FLAGS is the flags word to use--or 0 meaning preserve the flags
9540 that the window now has.
9541 If USER_POSITION is nonzero, we set the USPosition
9542 flag (this is useful when FLAGS is 0).
9543 The GTK version is in gtkutils.c */
9545 #ifndef USE_GTK
9546 void
9547 x_wm_set_size_hint (struct frame *f, long flags, int user_position)
9549 XSizeHints size_hints;
9550 Window window = FRAME_OUTER_WINDOW (f);
9552 /* Setting PMaxSize caused various problems. */
9553 size_hints.flags = PResizeInc | PMinSize /* | PMaxSize */;
9555 size_hints.x = f->left_pos;
9556 size_hints.y = f->top_pos;
9558 size_hints.height = FRAME_PIXEL_HEIGHT (f);
9559 size_hints.width = FRAME_PIXEL_WIDTH (f);
9561 size_hints.width_inc = FRAME_COLUMN_WIDTH (f);
9562 size_hints.height_inc = FRAME_LINE_HEIGHT (f);
9563 size_hints.max_width = x_display_pixel_width (FRAME_X_DISPLAY_INFO (f))
9564 - FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
9565 size_hints.max_height = x_display_pixel_height (FRAME_X_DISPLAY_INFO (f))
9566 - FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
9568 /* Calculate the base and minimum sizes. */
9570 int base_width, base_height;
9571 int min_rows = 0, min_cols = 0;
9573 base_width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
9574 base_height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
9576 check_frame_size (f, &min_rows, &min_cols);
9578 /* The window manager uses the base width hints to calculate the
9579 current number of rows and columns in the frame while
9580 resizing; min_width and min_height aren't useful for this
9581 purpose, since they might not give the dimensions for a
9582 zero-row, zero-column frame.
9584 We use the base_width and base_height members if we have
9585 them; otherwise, we set the min_width and min_height members
9586 to the size for a zero x zero frame. */
9588 size_hints.flags |= PBaseSize;
9589 size_hints.base_width = base_width;
9590 size_hints.base_height = base_height + FRAME_MENUBAR_HEIGHT (f);
9591 size_hints.min_width = base_width + min_cols * size_hints.width_inc;
9592 size_hints.min_height = base_height + min_rows * size_hints.height_inc;
9595 /* If we don't need the old flags, we don't need the old hint at all. */
9596 if (flags)
9598 size_hints.flags |= flags;
9599 goto no_read;
9603 XSizeHints hints; /* Sometimes I hate X Windows... */
9604 long supplied_return;
9605 int value;
9607 value = XGetWMNormalHints (FRAME_X_DISPLAY (f), window, &hints,
9608 &supplied_return);
9610 if (flags)
9611 size_hints.flags |= flags;
9612 else
9614 if (value == 0)
9615 hints.flags = 0;
9616 if (hints.flags & PSize)
9617 size_hints.flags |= PSize;
9618 if (hints.flags & PPosition)
9619 size_hints.flags |= PPosition;
9620 if (hints.flags & USPosition)
9621 size_hints.flags |= USPosition;
9622 if (hints.flags & USSize)
9623 size_hints.flags |= USSize;
9627 no_read:
9629 #ifdef PWinGravity
9630 size_hints.win_gravity = f->win_gravity;
9631 size_hints.flags |= PWinGravity;
9633 if (user_position)
9635 size_hints.flags &= ~ PPosition;
9636 size_hints.flags |= USPosition;
9638 #endif /* PWinGravity */
9640 XSetWMNormalHints (FRAME_X_DISPLAY (f), window, &size_hints);
9642 #endif /* not USE_GTK */
9644 /* Used for IconicState or NormalState */
9646 void
9647 x_wm_set_window_state (struct frame *f, int state)
9649 #ifdef USE_X_TOOLKIT
9650 Arg al[1];
9652 XtSetArg (al[0], XtNinitialState, state);
9653 XtSetValues (f->output_data.x->widget, al, 1);
9654 #else /* not USE_X_TOOLKIT */
9655 Window window = FRAME_X_WINDOW (f);
9657 f->output_data.x->wm_hints.flags |= StateHint;
9658 f->output_data.x->wm_hints.initial_state = state;
9660 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
9661 #endif /* not USE_X_TOOLKIT */
9664 void
9665 x_wm_set_icon_pixmap (struct frame *f, int pixmap_id)
9667 Pixmap icon_pixmap, icon_mask;
9669 #if !defined USE_X_TOOLKIT && !defined USE_GTK
9670 Window window = FRAME_OUTER_WINDOW (f);
9671 #endif
9673 if (pixmap_id > 0)
9675 icon_pixmap = x_bitmap_pixmap (f, pixmap_id);
9676 f->output_data.x->wm_hints.icon_pixmap = icon_pixmap;
9677 icon_mask = x_bitmap_mask (f, pixmap_id);
9678 f->output_data.x->wm_hints.icon_mask = icon_mask;
9680 else
9682 /* It seems there is no way to turn off use of an icon
9683 pixmap. */
9684 return;
9688 #ifdef USE_GTK
9690 xg_set_frame_icon (f, icon_pixmap, icon_mask);
9691 return;
9694 #elif defined (USE_X_TOOLKIT) /* same as in x_wm_set_window_state. */
9697 Arg al[1];
9698 XtSetArg (al[0], XtNiconPixmap, icon_pixmap);
9699 XtSetValues (f->output_data.x->widget, al, 1);
9700 XtSetArg (al[0], XtNiconMask, icon_mask);
9701 XtSetValues (f->output_data.x->widget, al, 1);
9704 #else /* not USE_X_TOOLKIT && not USE_GTK */
9706 f->output_data.x->wm_hints.flags |= (IconPixmapHint | IconMaskHint);
9707 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
9709 #endif /* not USE_X_TOOLKIT && not USE_GTK */
9712 void
9713 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
9715 Window window = FRAME_OUTER_WINDOW (f);
9717 f->output_data.x->wm_hints.flags |= IconPositionHint;
9718 f->output_data.x->wm_hints.icon_x = icon_x;
9719 f->output_data.x->wm_hints.icon_y = icon_y;
9721 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
9725 /***********************************************************************
9726 Fonts
9727 ***********************************************************************/
9729 #if GLYPH_DEBUG
9731 /* Check that FONT is valid on frame F. It is if it can be found in F's
9732 font table. */
9734 static void
9735 x_check_font (struct frame *f, struct font *font)
9737 Lisp_Object frame;
9739 xassert (font != NULL && ! NILP (font->props[FONT_TYPE_INDEX]));
9740 if (font->driver->check)
9741 xassert (font->driver->check (f, font) == 0);
9744 #endif /* GLYPH_DEBUG != 0 */
9747 /***********************************************************************
9748 Initialization
9749 ***********************************************************************/
9751 #ifdef USE_X_TOOLKIT
9752 static XrmOptionDescRec emacs_options[] = {
9753 {"-geometry", ".geometry", XrmoptionSepArg, NULL},
9754 {"-iconic", ".iconic", XrmoptionNoArg, (XtPointer) "yes"},
9756 {"-internal-border-width", "*EmacsScreen.internalBorderWidth",
9757 XrmoptionSepArg, NULL},
9758 {"-ib", "*EmacsScreen.internalBorderWidth", XrmoptionSepArg, NULL},
9760 {"-T", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
9761 {"-wn", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
9762 {"-title", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
9763 {"-iconname", "*EmacsShell.iconName", XrmoptionSepArg, (XtPointer) NULL},
9764 {"-in", "*EmacsShell.iconName", XrmoptionSepArg, (XtPointer) NULL},
9765 {"-mc", "*pointerColor", XrmoptionSepArg, (XtPointer) NULL},
9766 {"-cr", "*cursorColor", XrmoptionSepArg, (XtPointer) NULL}
9769 /* Whether atimer for Xt timeouts is activated or not. */
9771 static int x_timeout_atimer_activated_flag;
9773 #endif /* USE_X_TOOLKIT */
9775 static int x_initialized;
9777 #ifdef HAVE_X_SM
9778 static int x_session_initialized;
9779 #endif
9781 /* Test whether two display-name strings agree up to the dot that separates
9782 the screen number from the server number. */
9783 static int
9784 same_x_server (const char *name1, const char *name2)
9786 int seen_colon = 0;
9787 const unsigned char *system_name = SDATA (Vsystem_name);
9788 int system_name_length = strlen (system_name);
9789 int length_until_period = 0;
9791 while (system_name[length_until_period] != 0
9792 && system_name[length_until_period] != '.')
9793 length_until_period++;
9795 /* Treat `unix' like an empty host name. */
9796 if (! strncmp (name1, "unix:", 5))
9797 name1 += 4;
9798 if (! strncmp (name2, "unix:", 5))
9799 name2 += 4;
9800 /* Treat this host's name like an empty host name. */
9801 if (! strncmp (name1, system_name, system_name_length)
9802 && name1[system_name_length] == ':')
9803 name1 += system_name_length;
9804 if (! strncmp (name2, system_name, system_name_length)
9805 && name2[system_name_length] == ':')
9806 name2 += system_name_length;
9807 /* Treat this host's domainless name like an empty host name. */
9808 if (! strncmp (name1, system_name, length_until_period)
9809 && name1[length_until_period] == ':')
9810 name1 += length_until_period;
9811 if (! strncmp (name2, system_name, length_until_period)
9812 && name2[length_until_period] == ':')
9813 name2 += length_until_period;
9815 for (; *name1 != '\0' && *name1 == *name2; name1++, name2++)
9817 if (*name1 == ':')
9818 seen_colon++;
9819 if (seen_colon && *name1 == '.')
9820 return 1;
9822 return (seen_colon
9823 && (*name1 == '.' || *name1 == '\0')
9824 && (*name2 == '.' || *name2 == '\0'));
9827 /* Count number of set bits in mask and number of bits to shift to
9828 get to the first bit. With MASK 0x7e0, *BITS is set to 6, and *OFFSET
9829 to 5. */
9830 static void
9831 get_bits_and_offset (long unsigned int mask, int *bits, int *offset)
9833 int nr = 0;
9834 int off = 0;
9836 while (!(mask & 1))
9838 off++;
9839 mask >>= 1;
9842 while (mask & 1)
9844 nr++;
9845 mask >>= 1;
9848 *offset = off;
9849 *bits = nr;
9852 /* Return 1 if display DISPLAY is available for use, 0 otherwise.
9853 But don't permanently open it, just test its availability. */
9856 x_display_ok (const char *display)
9858 int dpy_ok = 1;
9859 Display *dpy;
9861 dpy = XOpenDisplay (display);
9862 if (dpy)
9863 XCloseDisplay (dpy);
9864 else
9865 dpy_ok = 0;
9866 return dpy_ok;
9869 #ifdef USE_GTK
9870 static void
9871 my_log_handler (const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer user_data)
9873 if (!strstr (message, "g_set_prgname"))
9874 fprintf (stderr, "%s-WARNING **: %s\n", log_domain, message);
9876 #endif
9878 /* Open a connection to X display DISPLAY_NAME, and return
9879 the structure that describes the open display.
9880 If we cannot contact the display, return null. */
9882 struct x_display_info *
9883 x_term_init (Lisp_Object display_name, char *xrm_option, char *resource_name)
9885 int connection;
9886 Display *dpy;
9887 struct terminal *terminal;
9888 struct x_display_info *dpyinfo;
9889 XrmDatabase xrdb;
9890 Mouse_HLInfo *hlinfo;
9892 BLOCK_INPUT;
9894 if (!x_initialized)
9896 x_initialize ();
9897 ++x_initialized;
9900 if (! x_display_ok (SDATA (display_name)))
9901 error ("Display %s can't be opened", SDATA (display_name));
9903 #ifdef USE_GTK
9905 #define NUM_ARGV 10
9906 int argc;
9907 char *argv[NUM_ARGV];
9908 char **argv2 = argv;
9909 guint id;
9911 if (x_initialized++ > 1)
9913 xg_display_open (SDATA (display_name), &dpy);
9915 else
9917 static char display_opt[] = "--display";
9918 static char name_opt[] = "--name";
9920 for (argc = 0; argc < NUM_ARGV; ++argc)
9921 argv[argc] = 0;
9923 argc = 0;
9924 argv[argc++] = initial_argv[0];
9926 if (! NILP (display_name))
9928 argv[argc++] = display_opt;
9929 argv[argc++] = SDATA (display_name);
9932 argv[argc++] = name_opt;
9933 argv[argc++] = resource_name;
9935 XSetLocaleModifiers ("");
9937 /* Work around GLib bug that outputs a faulty warning. See
9938 https://bugzilla.gnome.org/show_bug.cgi?id=563627. */
9939 id = g_log_set_handler ("GLib", G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
9940 | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
9941 gtk_init (&argc, &argv2);
9942 g_log_remove_handler ("GLib", id);
9944 /* gtk_init does set_locale. We must fix locale after calling it. */
9945 fixup_locale ();
9946 xg_initialize ();
9948 dpy = GDK_DISPLAY ();
9950 /* NULL window -> events for all windows go to our function */
9951 gdk_window_add_filter (NULL, event_handler_gdk, NULL);
9953 /* Load our own gtkrc if it exists. */
9955 const char *file = "~/.emacs.d/gtkrc";
9956 Lisp_Object s, abs_file;
9958 s = make_string (file, strlen (file));
9959 abs_file = Fexpand_file_name (s, Qnil);
9961 if (! NILP (abs_file) && !NILP (Ffile_readable_p (abs_file)))
9962 gtk_rc_parse (SDATA (abs_file));
9965 XSetErrorHandler (x_error_handler);
9966 XSetIOErrorHandler (x_io_error_quitter);
9969 #else /* not USE_GTK */
9970 #ifdef USE_X_TOOLKIT
9971 /* weiner@footloose.sps.mot.com reports that this causes
9972 errors with X11R5:
9973 X protocol error: BadAtom (invalid Atom parameter)
9974 on protocol request 18skiloaf.
9975 So let's not use it until R6. */
9976 #ifdef HAVE_X11XTR6
9977 XtSetLanguageProc (NULL, NULL, NULL);
9978 #endif
9981 int argc = 0;
9982 char *argv[3];
9984 argv[0] = "";
9985 argc = 1;
9986 if (xrm_option)
9988 argv[argc++] = "-xrm";
9989 argv[argc++] = xrm_option;
9991 turn_on_atimers (0);
9992 dpy = XtOpenDisplay (Xt_app_con, SDATA (display_name),
9993 resource_name, EMACS_CLASS,
9994 emacs_options, XtNumber (emacs_options),
9995 &argc, argv);
9996 turn_on_atimers (1);
9998 #ifdef HAVE_X11XTR6
9999 /* I think this is to compensate for XtSetLanguageProc. */
10000 fixup_locale ();
10001 #endif
10004 #else /* not USE_X_TOOLKIT */
10005 XSetLocaleModifiers ("");
10006 dpy = XOpenDisplay (SDATA (display_name));
10007 #endif /* not USE_X_TOOLKIT */
10008 #endif /* not USE_GTK*/
10010 /* Detect failure. */
10011 if (dpy == 0)
10013 UNBLOCK_INPUT;
10014 return 0;
10017 /* We have definitely succeeded. Record the new connection. */
10019 dpyinfo = (struct x_display_info *) xmalloc (sizeof (struct x_display_info));
10020 memset (dpyinfo, 0, sizeof *dpyinfo);
10021 hlinfo = &dpyinfo->mouse_highlight;
10023 terminal = x_create_terminal (dpyinfo);
10026 struct x_display_info *share;
10027 Lisp_Object tail;
10029 for (share = x_display_list, tail = x_display_name_list; share;
10030 share = share->next, tail = XCDR (tail))
10031 if (same_x_server (SDATA (XCAR (XCAR (tail))),
10032 SDATA (display_name)))
10033 break;
10034 if (share)
10035 terminal->kboard = share->terminal->kboard;
10036 else
10038 terminal->kboard = (KBOARD *) xmalloc (sizeof (KBOARD));
10039 init_kboard (terminal->kboard);
10040 terminal->kboard->Vwindow_system = Qx;
10042 /* Add the keyboard to the list before running Lisp code (via
10043 Qvendor_specific_keysyms below), since these are not traced
10044 via terminals but only through all_kboards. */
10045 terminal->kboard->next_kboard = all_kboards;
10046 all_kboards = terminal->kboard;
10048 if (!EQ (XSYMBOL (Qvendor_specific_keysyms)->function, Qunbound))
10050 char *vendor = ServerVendor (dpy);
10052 /* Protect terminal from GC before removing it from the
10053 list of terminals. */
10054 struct gcpro gcpro1;
10055 Lisp_Object gcpro_term;
10056 XSETTERMINAL (gcpro_term, terminal);
10057 GCPRO1 (gcpro_term);
10059 /* Temporarily hide the partially initialized terminal. */
10060 terminal_list = terminal->next_terminal;
10061 UNBLOCK_INPUT;
10062 terminal->kboard->Vsystem_key_alist
10063 = call1 (Qvendor_specific_keysyms,
10064 vendor ? build_string (vendor) : empty_unibyte_string);
10065 BLOCK_INPUT;
10066 terminal->next_terminal = terminal_list;
10067 terminal_list = terminal;
10068 UNGCPRO;
10071 /* Don't let the initial kboard remain current longer than necessary.
10072 That would cause problems if a file loaded on startup tries to
10073 prompt in the mini-buffer. */
10074 if (current_kboard == initial_kboard)
10075 current_kboard = terminal->kboard;
10077 terminal->kboard->reference_count++;
10080 /* Put this display on the chain. */
10081 dpyinfo->next = x_display_list;
10082 x_display_list = dpyinfo;
10084 /* Put it on x_display_name_list as well, to keep them parallel. */
10085 x_display_name_list = Fcons (Fcons (display_name, Qnil),
10086 x_display_name_list);
10087 dpyinfo->name_list_element = XCAR (x_display_name_list);
10089 dpyinfo->display = dpy;
10091 /* Set the name of the terminal. */
10092 terminal->name = (char *) xmalloc (SBYTES (display_name) + 1);
10093 strncpy (terminal->name, SDATA (display_name), SBYTES (display_name));
10094 terminal->name[SBYTES (display_name)] = 0;
10096 #if 0
10097 XSetAfterFunction (x_current_display, x_trace_wire);
10098 #endif /* ! 0 */
10100 dpyinfo->x_id_name
10101 = (char *) xmalloc (SBYTES (Vinvocation_name)
10102 + SBYTES (Vsystem_name)
10103 + 2);
10104 sprintf (dpyinfo->x_id_name, "%s@%s",
10105 SDATA (Vinvocation_name), SDATA (Vsystem_name));
10107 /* Figure out which modifier bits mean what. */
10108 x_find_modifier_meanings (dpyinfo);
10110 /* Get the scroll bar cursor. */
10111 #ifdef USE_GTK
10112 /* We must create a GTK cursor, it is required for GTK widgets. */
10113 dpyinfo->xg_cursor = xg_create_default_cursor (dpyinfo->display);
10114 #endif /* USE_GTK */
10116 dpyinfo->vertical_scroll_bar_cursor
10117 = XCreateFontCursor (dpyinfo->display, XC_sb_v_double_arrow);
10119 xrdb = x_load_resources (dpyinfo->display, xrm_option,
10120 resource_name, EMACS_CLASS);
10121 #ifdef HAVE_XRMSETDATABASE
10122 XrmSetDatabase (dpyinfo->display, xrdb);
10123 #else
10124 dpyinfo->display->db = xrdb;
10125 #endif
10126 /* Put the rdb where we can find it in a way that works on
10127 all versions. */
10128 dpyinfo->xrdb = xrdb;
10130 dpyinfo->screen = ScreenOfDisplay (dpyinfo->display,
10131 DefaultScreen (dpyinfo->display));
10132 select_visual (dpyinfo);
10133 dpyinfo->cmap = DefaultColormapOfScreen (dpyinfo->screen);
10134 dpyinfo->root_window = RootWindowOfScreen (dpyinfo->screen);
10135 dpyinfo->client_leader_window = 0;
10136 dpyinfo->grabbed = 0;
10137 dpyinfo->reference_count = 0;
10138 dpyinfo->icon_bitmap_id = -1;
10139 dpyinfo->n_fonts = 0;
10140 dpyinfo->bitmaps = 0;
10141 dpyinfo->bitmaps_size = 0;
10142 dpyinfo->bitmaps_last = 0;
10143 dpyinfo->scratch_cursor_gc = 0;
10144 hlinfo->mouse_face_mouse_frame = 0;
10145 hlinfo->mouse_face_deferred_gc = 0;
10146 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
10147 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
10148 hlinfo->mouse_face_face_id = DEFAULT_FACE_ID;
10149 hlinfo->mouse_face_window = Qnil;
10150 hlinfo->mouse_face_overlay = Qnil;
10151 hlinfo->mouse_face_mouse_x = hlinfo->mouse_face_mouse_y = 0;
10152 hlinfo->mouse_face_defer = 0;
10153 hlinfo->mouse_face_hidden = 0;
10154 dpyinfo->x_focus_frame = 0;
10155 dpyinfo->x_focus_event_frame = 0;
10156 dpyinfo->x_highlight_frame = 0;
10157 dpyinfo->wm_type = X_WMTYPE_UNKNOWN;
10159 /* See if we can construct pixel values from RGB values. */
10160 dpyinfo->red_bits = dpyinfo->blue_bits = dpyinfo->green_bits = 0;
10161 dpyinfo->red_offset = dpyinfo->blue_offset = dpyinfo->green_offset = 0;
10163 if (dpyinfo->visual->class == TrueColor)
10165 get_bits_and_offset (dpyinfo->visual->red_mask,
10166 &dpyinfo->red_bits, &dpyinfo->red_offset);
10167 get_bits_and_offset (dpyinfo->visual->blue_mask,
10168 &dpyinfo->blue_bits, &dpyinfo->blue_offset);
10169 get_bits_and_offset (dpyinfo->visual->green_mask,
10170 &dpyinfo->green_bits, &dpyinfo->green_offset);
10173 /* See if a private colormap is requested. */
10174 if (dpyinfo->visual == DefaultVisualOfScreen (dpyinfo->screen))
10176 if (dpyinfo->visual->class == PseudoColor)
10178 Lisp_Object value;
10179 value = display_x_get_resource (dpyinfo,
10180 build_string ("privateColormap"),
10181 build_string ("PrivateColormap"),
10182 Qnil, Qnil);
10183 if (STRINGP (value)
10184 && (!strcmp (SDATA (value), "true")
10185 || !strcmp (SDATA (value), "on")))
10186 dpyinfo->cmap = XCopyColormapAndFree (dpyinfo->display, dpyinfo->cmap);
10189 else
10190 dpyinfo->cmap = XCreateColormap (dpyinfo->display, dpyinfo->root_window,
10191 dpyinfo->visual, AllocNone);
10193 #ifdef HAVE_XFT
10195 /* If we are using Xft, check dpi value in X resources.
10196 It is better we use it as well, since Xft will use it, as will all
10197 Gnome applications. If our real DPI is smaller or larger than the
10198 one Xft uses, our font will look smaller or larger than other
10199 for other applications, even if it is the same font name (monospace-10
10200 for example). */
10201 char *v = XGetDefault (dpyinfo->display, "Xft", "dpi");
10202 double d;
10203 if (v != NULL && sscanf (v, "%lf", &d) == 1)
10204 dpyinfo->resy = dpyinfo->resx = d;
10206 #endif
10208 if (dpyinfo->resy < 1)
10210 int screen_number = XScreenNumberOfScreen (dpyinfo->screen);
10211 double pixels = DisplayHeight (dpyinfo->display, screen_number);
10212 double mm = DisplayHeightMM (dpyinfo->display, screen_number);
10213 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
10214 dpyinfo->resy = (mm < 1) ? 100 : pixels * 25.4 / mm;
10215 pixels = DisplayWidth (dpyinfo->display, screen_number);
10216 mm = DisplayWidthMM (dpyinfo->display, screen_number);
10217 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
10218 dpyinfo->resx = (mm < 1) ? 100 : pixels * 25.4 / mm;
10222 const struct
10224 const char *name;
10225 Atom *atom;
10226 } atom_refs[] = {
10227 { "WM_PROTOCOLS", &dpyinfo->Xatom_wm_protocols },
10228 { "WM_TAKE_FOCUS", &dpyinfo->Xatom_wm_take_focus },
10229 { "WM_SAVE_YOURSELF", &dpyinfo->Xatom_wm_save_yourself },
10230 { "WM_DELETE_WINDOW", &dpyinfo->Xatom_wm_delete_window },
10231 { "WM_CHANGE_STATE", &dpyinfo->Xatom_wm_change_state },
10232 { "WM_CONFIGURE_DENIED", &dpyinfo->Xatom_wm_configure_denied },
10233 { "WM_MOVED", &dpyinfo->Xatom_wm_window_moved },
10234 { "WM_CLIENT_LEADER", &dpyinfo->Xatom_wm_client_leader },
10235 { "Editres", &dpyinfo->Xatom_editres },
10236 { "CLIPBOARD", &dpyinfo->Xatom_CLIPBOARD },
10237 { "TIMESTAMP", &dpyinfo->Xatom_TIMESTAMP },
10238 { "TEXT", &dpyinfo->Xatom_TEXT },
10239 { "COMPOUND_TEXT", &dpyinfo->Xatom_COMPOUND_TEXT },
10240 { "UTF8_STRING", &dpyinfo->Xatom_UTF8_STRING },
10241 { "DELETE", &dpyinfo->Xatom_DELETE },
10242 { "MULTIPLE", &dpyinfo->Xatom_MULTIPLE },
10243 { "INCR", &dpyinfo->Xatom_INCR },
10244 { "_EMACS_TMP_", &dpyinfo->Xatom_EMACS_TMP },
10245 { "TARGETS", &dpyinfo->Xatom_TARGETS },
10246 { "NULL", &dpyinfo->Xatom_NULL },
10247 { "ATOM_PAIR", &dpyinfo->Xatom_ATOM_PAIR },
10248 { "_XEMBED_INFO", &dpyinfo->Xatom_XEMBED_INFO },
10249 /* For properties of font. */
10250 { "PIXEL_SIZE", &dpyinfo->Xatom_PIXEL_SIZE },
10251 { "AVERAGE_WIDTH", &dpyinfo->Xatom_AVERAGE_WIDTH },
10252 { "_MULE_BASELINE_OFFSET", &dpyinfo->Xatom_MULE_BASELINE_OFFSET },
10253 { "_MULE_RELATIVE_COMPOSE", &dpyinfo->Xatom_MULE_RELATIVE_COMPOSE },
10254 { "_MULE_DEFAULT_ASCENT", &dpyinfo->Xatom_MULE_DEFAULT_ASCENT },
10255 /* Ghostscript support. */
10256 { "DONE", &dpyinfo->Xatom_DONE },
10257 { "PAGE", &dpyinfo->Xatom_PAGE },
10258 { "SCROLLBAR", &dpyinfo->Xatom_Scrollbar },
10259 { "_XEMBED", &dpyinfo->Xatom_XEMBED },
10260 /* EWMH */
10261 { "_NET_WM_STATE", &dpyinfo->Xatom_net_wm_state },
10262 { "_NET_WM_STATE_FULLSCREEN", &dpyinfo->Xatom_net_wm_state_fullscreen },
10263 { "_NET_WM_STATE_MAXIMIZED_HORZ",
10264 &dpyinfo->Xatom_net_wm_state_maximized_horz },
10265 { "_NET_WM_STATE_MAXIMIZED_VERT",
10266 &dpyinfo->Xatom_net_wm_state_maximized_vert },
10267 { "_NET_WM_STATE_STICKY", &dpyinfo->Xatom_net_wm_state_sticky },
10268 { "_NET_WM_WINDOW_TYPE", &dpyinfo->Xatom_net_window_type },
10269 { "_NET_WM_WINDOW_TYPE_TOOLTIP",
10270 &dpyinfo->Xatom_net_window_type_tooltip },
10271 { "_NET_WM_ICON_NAME", &dpyinfo->Xatom_net_wm_icon_name },
10272 { "_NET_WM_NAME", &dpyinfo->Xatom_net_wm_name },
10273 { "_NET_SUPPORTED", &dpyinfo->Xatom_net_supported },
10274 { "_NET_SUPPORTING_WM_CHECK", &dpyinfo->Xatom_net_supporting_wm_check },
10275 { "_NET_WM_WINDOW_OPACITY", &dpyinfo->Xatom_net_wm_window_opacity },
10276 { "_NET_ACTIVE_WINDOW", &dpyinfo->Xatom_net_active_window },
10277 { "_NET_FRAME_EXTENTS", &dpyinfo->Xatom_net_frame_extents },
10278 /* Session management */
10279 { "SM_CLIENT_ID", &dpyinfo->Xatom_SM_CLIENT_ID },
10280 { "_XSETTINGS_SETTINGS", &dpyinfo->Xatom_xsettings_prop },
10281 { "MANAGER", &dpyinfo->Xatom_xsettings_mgr },
10284 int i;
10285 const int atom_count = sizeof (atom_refs) / sizeof (atom_refs[0]);
10286 /* 1 for _XSETTINGS_SN */
10287 const int total_atom_count = 1 + atom_count;
10288 Atom *atoms_return = xmalloc (sizeof (Atom) * total_atom_count);
10289 char **atom_names = xmalloc (sizeof (char *) * total_atom_count);
10290 char xsettings_atom_name[64];
10292 for (i = 0; i < atom_count; i++)
10293 atom_names[i] = (char *) atom_refs[i].name;
10295 /* Build _XSETTINGS_SN atom name */
10296 snprintf (xsettings_atom_name, sizeof (xsettings_atom_name),
10297 "_XSETTINGS_S%d", XScreenNumberOfScreen (dpyinfo->screen));
10298 atom_names[i] = xsettings_atom_name;
10300 XInternAtoms (dpyinfo->display, atom_names, total_atom_count,
10301 False, atoms_return);
10303 for (i = 0; i < atom_count; i++)
10304 *atom_refs[i].atom = atoms_return[i];
10306 /* Manual copy of last atom */
10307 dpyinfo->Xatom_xsettings_sel = atoms_return[i];
10309 xfree (atom_names);
10310 xfree (atoms_return);
10313 dpyinfo->x_dnd_atoms_size = 8;
10314 dpyinfo->x_dnd_atoms_length = 0;
10315 dpyinfo->x_dnd_atoms = xmalloc (sizeof (*dpyinfo->x_dnd_atoms)
10316 * dpyinfo->x_dnd_atoms_size);
10318 dpyinfo->net_supported_atoms = NULL;
10319 dpyinfo->nr_net_supported_atoms = 0;
10320 dpyinfo->net_supported_window = 0;
10322 connection = ConnectionNumber (dpyinfo->display);
10323 dpyinfo->connection = connection;
10326 dpyinfo->gray
10327 = XCreatePixmapFromBitmapData (dpyinfo->display, dpyinfo->root_window,
10328 gray_bitmap_bits,
10329 gray_bitmap_width, gray_bitmap_height,
10330 (unsigned long) 1, (unsigned long) 0, 1);
10333 #ifdef HAVE_X_I18N
10334 xim_initialize (dpyinfo, resource_name);
10335 #endif
10337 xsettings_initialize (dpyinfo);
10339 /* This is only needed for distinguishing keyboard and process input. */
10340 if (connection != 0)
10341 add_keyboard_wait_descriptor (connection);
10343 #ifdef F_SETOWN
10344 fcntl (connection, F_SETOWN, getpid ());
10345 #endif /* ! defined (F_SETOWN) */
10347 #ifdef SIGIO
10348 if (interrupt_input)
10349 init_sigio (connection);
10350 #endif /* ! defined (SIGIO) */
10352 #ifdef USE_LUCID
10354 Display *dpy = dpyinfo->display;
10355 XrmValue d, fr, to;
10356 Font font;
10358 d.addr = (XPointer)&dpy;
10359 d.size = sizeof (Display *);
10360 fr.addr = XtDefaultFont;
10361 fr.size = sizeof (XtDefaultFont);
10362 to.size = sizeof (Font *);
10363 to.addr = (XPointer)&font;
10364 x_catch_errors (dpy);
10365 if (!XtCallConverter (dpy, XtCvtStringToFont, &d, 1, &fr, &to, NULL))
10366 abort ();
10367 if (x_had_errors_p (dpy) || !XQueryFont (dpy, font))
10368 XrmPutLineResource (&xrdb, "Emacs.dialog.*.font: 9x15");
10369 x_uncatch_errors ();
10371 #endif
10373 /* See if we should run in synchronous mode. This is useful
10374 for debugging X code. */
10376 Lisp_Object value;
10377 value = display_x_get_resource (dpyinfo,
10378 build_string ("synchronous"),
10379 build_string ("Synchronous"),
10380 Qnil, Qnil);
10381 if (STRINGP (value)
10382 && (!strcmp (SDATA (value), "true")
10383 || !strcmp (SDATA (value), "on")))
10384 XSynchronize (dpyinfo->display, True);
10388 Lisp_Object value;
10389 value = display_x_get_resource (dpyinfo,
10390 build_string ("useXIM"),
10391 build_string ("UseXIM"),
10392 Qnil, Qnil);
10393 #ifdef USE_XIM
10394 if (STRINGP (value)
10395 && (!strcmp (SDATA (value), "false")
10396 || !strcmp (SDATA (value), "off")))
10397 use_xim = 0;
10398 #else
10399 if (STRINGP (value)
10400 && (!strcmp (SDATA (value), "true")
10401 || !strcmp (SDATA (value), "on")))
10402 use_xim = 1;
10403 #endif
10406 #ifdef HAVE_X_SM
10407 /* Only do this for the very first display in the Emacs session.
10408 Ignore X session management when Emacs was first started on a
10409 tty. */
10410 if (terminal->id == 1)
10411 x_session_initialize (dpyinfo);
10412 #endif
10414 UNBLOCK_INPUT;
10416 return dpyinfo;
10419 /* Get rid of display DPYINFO, deleting all frames on it,
10420 and without sending any more commands to the X server. */
10422 void
10423 x_delete_display (struct x_display_info *dpyinfo)
10425 struct terminal *t;
10427 /* Close all frames and delete the generic struct terminal for this
10428 X display. */
10429 for (t = terminal_list; t; t = t->next_terminal)
10430 if (t->type == output_x_window && t->display_info.x == dpyinfo)
10432 #ifdef HAVE_X_SM
10433 /* Close X session management when we close its display. */
10434 if (t->id == 1 && x_session_have_connection ())
10435 x_session_close ();
10436 #endif
10437 delete_terminal (t);
10438 break;
10441 delete_keyboard_wait_descriptor (dpyinfo->connection);
10443 /* Discard this display from x_display_name_list and x_display_list.
10444 We can't use Fdelq because that can quit. */
10445 if (! NILP (x_display_name_list)
10446 && EQ (XCAR (x_display_name_list), dpyinfo->name_list_element))
10447 x_display_name_list = XCDR (x_display_name_list);
10448 else
10450 Lisp_Object tail;
10452 tail = x_display_name_list;
10453 while (CONSP (tail) && CONSP (XCDR (tail)))
10455 if (EQ (XCAR (XCDR (tail)), dpyinfo->name_list_element))
10457 XSETCDR (tail, XCDR (XCDR (tail)));
10458 break;
10460 tail = XCDR (tail);
10464 if (next_noop_dpyinfo == dpyinfo)
10465 next_noop_dpyinfo = dpyinfo->next;
10467 if (x_display_list == dpyinfo)
10468 x_display_list = dpyinfo->next;
10469 else
10471 struct x_display_info *tail;
10473 for (tail = x_display_list; tail; tail = tail->next)
10474 if (tail->next == dpyinfo)
10475 tail->next = tail->next->next;
10478 xfree (dpyinfo->x_id_name);
10479 xfree (dpyinfo->x_dnd_atoms);
10480 xfree (dpyinfo->color_cells);
10481 xfree (dpyinfo);
10484 #ifdef USE_X_TOOLKIT
10486 /* Atimer callback function for TIMER. Called every 0.1s to process
10487 Xt timeouts, if needed. We must avoid calling XtAppPending as
10488 much as possible because that function does an implicit XFlush
10489 that slows us down. */
10491 static void
10492 x_process_timeouts (struct atimer *timer)
10494 BLOCK_INPUT;
10495 x_timeout_atimer_activated_flag = 0;
10496 if (toolkit_scroll_bar_interaction || popup_activated ())
10498 while (XtAppPending (Xt_app_con) & XtIMTimer)
10499 XtAppProcessEvent (Xt_app_con, XtIMTimer);
10500 /* Reactivate the atimer for next time. */
10501 x_activate_timeout_atimer ();
10503 UNBLOCK_INPUT;
10506 /* Install an asynchronous timer that processes Xt timeout events
10507 every 0.1s as long as either `toolkit_scroll_bar_interaction' or
10508 `popup_activated_flag' (in xmenu.c) is set. Make sure to call this
10509 function whenever these variables are set. This is necessary
10510 because some widget sets use timeouts internally, for example the
10511 LessTif menu bar, or the Xaw3d scroll bar. When Xt timeouts aren't
10512 processed, these widgets don't behave normally. */
10514 void
10515 x_activate_timeout_atimer (void)
10517 BLOCK_INPUT;
10518 if (!x_timeout_atimer_activated_flag)
10520 EMACS_TIME interval;
10522 EMACS_SET_SECS_USECS (interval, 0, 100000);
10523 start_atimer (ATIMER_RELATIVE, interval, x_process_timeouts, 0);
10524 x_timeout_atimer_activated_flag = 1;
10526 UNBLOCK_INPUT;
10529 #endif /* USE_X_TOOLKIT */
10532 /* Set up use of X before we make the first connection. */
10534 extern frame_parm_handler x_frame_parm_handlers[];
10536 static struct redisplay_interface x_redisplay_interface =
10538 x_frame_parm_handlers,
10539 x_produce_glyphs,
10540 x_write_glyphs,
10541 x_insert_glyphs,
10542 x_clear_end_of_line,
10543 x_scroll_run,
10544 x_after_update_window_line,
10545 x_update_window_begin,
10546 x_update_window_end,
10547 x_cursor_to,
10548 x_flush,
10549 #ifdef XFlush
10550 x_flush,
10551 #else
10552 0, /* flush_display_optional */
10553 #endif
10554 x_clear_window_mouse_face,
10555 x_get_glyph_overhangs,
10556 x_fix_overlapping_area,
10557 x_draw_fringe_bitmap,
10558 0, /* define_fringe_bitmap */
10559 0, /* destroy_fringe_bitmap */
10560 x_compute_glyph_string_overhangs,
10561 x_draw_glyph_string,
10562 x_define_frame_cursor,
10563 x_clear_frame_area,
10564 x_draw_window_cursor,
10565 x_draw_vertical_window_border,
10566 x_shift_glyphs_for_insert
10570 /* This function is called when the last frame on a display is deleted. */
10571 void
10572 x_delete_terminal (struct terminal *terminal)
10574 struct x_display_info *dpyinfo = terminal->display_info.x;
10576 /* Protect against recursive calls. delete_frame in
10577 delete_terminal calls us back when it deletes our last frame. */
10578 if (!terminal->name)
10579 return;
10581 BLOCK_INPUT;
10582 #ifdef HAVE_X_I18N
10583 /* We must close our connection to the XIM server before closing the
10584 X display. */
10585 if (dpyinfo->xim)
10586 xim_close_dpy (dpyinfo);
10587 #endif
10589 /* If called from x_connection_closed, the display may already be closed
10590 and dpyinfo->display was set to 0 to indicate that. */
10591 if (dpyinfo->display)
10593 x_destroy_all_bitmaps (dpyinfo);
10594 XSetCloseDownMode (dpyinfo->display, DestroyAll);
10596 /* Whether or not XCloseDisplay destroys the associated resource
10597 database depends on the version of libX11. To avoid both
10598 crash and memory leak, we dissociate the database from the
10599 display and then destroy dpyinfo->xrdb ourselves.
10601 Unfortunately, the above strategy does not work in some
10602 situations due to a bug in newer versions of libX11: because
10603 XrmSetDatabase doesn't clear the flag XlibDisplayDfltRMDB if
10604 dpy->db is NULL, XCloseDisplay destroys the associated
10605 database whereas it has not been created by XGetDefault
10606 (Bug#21974 in freedesktop.org Bugzilla). As a workaround, we
10607 don't destroy the database here in order to avoid the crash
10608 in the above situations for now, though that may cause memory
10609 leaks in other situations. */
10610 #if 0
10611 #ifdef HAVE_XRMSETDATABASE
10612 XrmSetDatabase (dpyinfo->display, NULL);
10613 #else
10614 dpyinfo->display->db = NULL;
10615 #endif
10616 /* We used to call XrmDestroyDatabase from x_delete_display, but
10617 some older versions of libX11 crash if we call it after
10618 closing all the displays. */
10619 XrmDestroyDatabase (dpyinfo->xrdb);
10620 #endif
10622 #ifdef USE_GTK
10623 xg_display_close (dpyinfo->display);
10624 #else
10625 #ifdef USE_X_TOOLKIT
10626 XtCloseDisplay (dpyinfo->display);
10627 #else
10628 XCloseDisplay (dpyinfo->display);
10629 #endif
10630 #endif /* ! USE_GTK */
10633 /* Mark as dead. */
10634 dpyinfo->display = NULL;
10635 x_delete_display (dpyinfo);
10636 UNBLOCK_INPUT;
10639 /* Create a struct terminal, initialize it with the X11 specific
10640 functions and make DISPLAY->TERMINAL point to it. */
10642 static struct terminal *
10643 x_create_terminal (struct x_display_info *dpyinfo)
10645 struct terminal *terminal;
10647 terminal = create_terminal ();
10649 terminal->type = output_x_window;
10650 terminal->display_info.x = dpyinfo;
10651 dpyinfo->terminal = terminal;
10653 /* kboard is initialized in x_term_init. */
10655 terminal->clear_frame_hook = x_clear_frame;
10656 terminal->ins_del_lines_hook = x_ins_del_lines;
10657 terminal->delete_glyphs_hook = x_delete_glyphs;
10658 terminal->ring_bell_hook = XTring_bell;
10659 terminal->toggle_invisible_pointer_hook = XTtoggle_invisible_pointer;
10660 terminal->reset_terminal_modes_hook = XTreset_terminal_modes;
10661 terminal->set_terminal_modes_hook = XTset_terminal_modes;
10662 terminal->update_begin_hook = x_update_begin;
10663 terminal->update_end_hook = x_update_end;
10664 terminal->set_terminal_window_hook = XTset_terminal_window;
10665 terminal->read_socket_hook = XTread_socket;
10666 terminal->frame_up_to_date_hook = XTframe_up_to_date;
10667 terminal->mouse_position_hook = XTmouse_position;
10668 terminal->frame_rehighlight_hook = XTframe_rehighlight;
10669 terminal->frame_raise_lower_hook = XTframe_raise_lower;
10670 terminal->fullscreen_hook = XTfullscreen_hook;
10671 terminal->set_vertical_scroll_bar_hook = XTset_vertical_scroll_bar;
10672 terminal->condemn_scroll_bars_hook = XTcondemn_scroll_bars;
10673 terminal->redeem_scroll_bar_hook = XTredeem_scroll_bar;
10674 terminal->judge_scroll_bars_hook = XTjudge_scroll_bars;
10676 terminal->delete_frame_hook = x_destroy_window;
10677 terminal->delete_terminal_hook = x_delete_terminal;
10679 terminal->rif = &x_redisplay_interface;
10680 terminal->scroll_region_ok = 1; /* We'll scroll partial frames. */
10681 terminal->char_ins_del_ok = 1;
10682 terminal->line_ins_del_ok = 1; /* We'll just blt 'em. */
10683 terminal->fast_clear_end_of_line = 1; /* X does this well. */
10684 terminal->memory_below_frame = 0; /* We don't remember what scrolls
10685 off the bottom. */
10687 return terminal;
10690 void
10691 x_initialize (void)
10693 baud_rate = 19200;
10695 x_noop_count = 0;
10696 last_tool_bar_item = -1;
10697 any_help_event_p = 0;
10698 ignore_next_mouse_click_timeout = 0;
10699 #ifdef HAVE_X_SM
10700 x_session_initialized = 0;
10701 #endif
10703 #ifdef USE_GTK
10704 current_count = -1;
10705 #endif
10707 /* Try to use interrupt input; if we can't, then start polling. */
10708 Fset_input_interrupt_mode (Qt);
10710 #ifdef USE_X_TOOLKIT
10711 XtToolkitInitialize ();
10713 Xt_app_con = XtCreateApplicationContext ();
10715 /* Register a converter from strings to pixels, which uses
10716 Emacs' color allocation infrastructure. */
10717 XtAppSetTypeConverter (Xt_app_con,
10718 XtRString, XtRPixel, cvt_string_to_pixel,
10719 cvt_string_to_pixel_args,
10720 XtNumber (cvt_string_to_pixel_args),
10721 XtCacheByDisplay, cvt_pixel_dtor);
10723 XtAppSetFallbackResources (Xt_app_con, Xt_default_resources);
10724 #endif
10726 #ifdef USE_TOOLKIT_SCROLL_BARS
10727 #ifndef USE_GTK
10728 xaw3d_arrow_scroll = False;
10729 xaw3d_pick_top = True;
10730 #endif
10731 #endif
10733 pending_autoraise_frame = 0;
10734 pending_event_wait.f = 0;
10735 pending_event_wait.eventtype = 0;
10737 /* Note that there is no real way portable across R3/R4 to get the
10738 original error handler. */
10739 XSetErrorHandler (x_error_handler);
10740 XSetIOErrorHandler (x_io_error_quitter);
10742 signal (SIGPIPE, x_connection_signal);
10744 xgselect_initialize ();
10748 void
10749 syms_of_xterm (void)
10751 x_error_message = NULL;
10753 staticpro (&x_display_name_list);
10754 x_display_name_list = Qnil;
10756 staticpro (&last_mouse_scroll_bar);
10757 last_mouse_scroll_bar = Qnil;
10759 staticpro (&Qvendor_specific_keysyms);
10760 Qvendor_specific_keysyms = intern_c_string ("vendor-specific-keysyms");
10762 staticpro (&Qlatin_1);
10763 Qlatin_1 = intern_c_string ("latin-1");
10765 staticpro (&last_mouse_press_frame);
10766 last_mouse_press_frame = Qnil;
10768 #ifdef USE_GTK
10769 xg_default_icon_file = make_pure_c_string ("icons/hicolor/scalable/apps/emacs.svg");
10770 staticpro (&xg_default_icon_file);
10772 Qx_gtk_map_stock = intern_c_string ("x-gtk-map-stock");
10773 staticpro (&Qx_gtk_map_stock);
10774 #endif
10776 DEFVAR_BOOL ("x-use-underline-position-properties",
10777 &x_use_underline_position_properties,
10778 doc: /* *Non-nil means make use of UNDERLINE_POSITION font properties.
10779 A value of nil means ignore them. If you encounter fonts with bogus
10780 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
10781 to 4.1, set this to nil. You can also use `underline-minimum-offset'
10782 to override the font's UNDERLINE_POSITION for small font display
10783 sizes. */);
10784 x_use_underline_position_properties = 1;
10786 DEFVAR_BOOL ("x-underline-at-descent-line",
10787 &x_underline_at_descent_line,
10788 doc: /* *Non-nil means to draw the underline at the same place as the descent line.
10789 A value of nil means to draw the underline according to the value of the
10790 variable `x-use-underline-position-properties', which is usually at the
10791 baseline level. The default value is nil. */);
10792 x_underline_at_descent_line = 0;
10794 DEFVAR_BOOL ("x-mouse-click-focus-ignore-position",
10795 &x_mouse_click_focus_ignore_position,
10796 doc: /* Non-nil means that a mouse click to focus a frame does not move point.
10797 This variable is only used when the window manager requires that you
10798 click on a frame to select it (give it focus). In that case, a value
10799 of nil, means that the selected window and cursor position changes to
10800 reflect the mouse click position, while a non-nil value means that the
10801 selected window or cursor position is preserved. */);
10802 x_mouse_click_focus_ignore_position = 0;
10804 DEFVAR_LISP ("x-toolkit-scroll-bars", &Vx_toolkit_scroll_bars,
10805 doc: /* Which toolkit scroll bars Emacs uses, if any.
10806 A value of nil means Emacs doesn't use toolkit scroll bars.
10807 With the X Window system, the value is a symbol describing the
10808 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
10809 With MS Windows, the value is t. */);
10810 #ifdef USE_TOOLKIT_SCROLL_BARS
10811 #ifdef USE_MOTIF
10812 Vx_toolkit_scroll_bars = intern_c_string ("motif");
10813 #elif defined HAVE_XAW3D
10814 Vx_toolkit_scroll_bars = intern_c_string ("xaw3d");
10815 #elif USE_GTK
10816 Vx_toolkit_scroll_bars = intern_c_string ("gtk");
10817 #else
10818 Vx_toolkit_scroll_bars = intern_c_string ("xaw");
10819 #endif
10820 #else
10821 Vx_toolkit_scroll_bars = Qnil;
10822 #endif
10824 staticpro (&last_mouse_motion_frame);
10825 last_mouse_motion_frame = Qnil;
10827 Qmodifier_value = intern_c_string ("modifier-value");
10828 Qalt = intern_c_string ("alt");
10829 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
10830 Qhyper = intern_c_string ("hyper");
10831 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
10832 Qmeta = intern_c_string ("meta");
10833 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
10834 Qsuper = intern_c_string ("super");
10835 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
10837 DEFVAR_LISP ("x-alt-keysym", &Vx_alt_keysym,
10838 doc: /* Which keys Emacs uses for the alt modifier.
10839 This should be one of the symbols `alt', `hyper', `meta', `super'.
10840 For example, `alt' means use the Alt_L and Alt_R keysyms. The default
10841 is nil, which is the same as `alt'. */);
10842 Vx_alt_keysym = Qnil;
10844 DEFVAR_LISP ("x-hyper-keysym", &Vx_hyper_keysym,
10845 doc: /* Which keys Emacs uses for the hyper modifier.
10846 This should be one of the symbols `alt', `hyper', `meta', `super'.
10847 For example, `hyper' means use the Hyper_L and Hyper_R keysyms. The
10848 default is nil, which is the same as `hyper'. */);
10849 Vx_hyper_keysym = Qnil;
10851 DEFVAR_LISP ("x-meta-keysym", &Vx_meta_keysym,
10852 doc: /* Which keys Emacs uses for the meta modifier.
10853 This should be one of the symbols `alt', `hyper', `meta', `super'.
10854 For example, `meta' means use the Meta_L and Meta_R keysyms. The
10855 default is nil, which is the same as `meta'. */);
10856 Vx_meta_keysym = Qnil;
10858 DEFVAR_LISP ("x-super-keysym", &Vx_super_keysym,
10859 doc: /* Which keys Emacs uses for the super modifier.
10860 This should be one of the symbols `alt', `hyper', `meta', `super'.
10861 For example, `super' means use the Super_L and Super_R keysyms. The
10862 default is nil, which is the same as `super'. */);
10863 Vx_super_keysym = Qnil;
10865 DEFVAR_LISP ("x-keysym-table", &Vx_keysym_table,
10866 doc: /* Hash table of character codes indexed by X keysym codes. */);
10867 Vx_keysym_table = make_hash_table (Qeql, make_number (900),
10868 make_float (DEFAULT_REHASH_SIZE),
10869 make_float (DEFAULT_REHASH_THRESHOLD),
10870 Qnil, Qnil, Qnil);
10873 #endif /* HAVE_X_WINDOWS */