ifdef guarding of xwidget code. not complete
[emacs.git] / src / xterm.c
blob510016e3d456a357ce3ff2cfa31d0aacd37bda33
1 /* X Communication module for terminals which understand the X protocol.
3 Copyright (C) 1989, 1993-2011 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 /* New display code by Gerd Moellmann <gerd@gnu.org>. */
21 /* Xt features made by Fred Pierresteguy. */
23 #include <config.h>
24 #include <signal.h>
25 #include <stdio.h>
26 #include <setjmp.h>
28 #ifdef HAVE_X_WINDOWS
30 #include "lisp.h"
31 #include "blockinput.h"
33 /* Need syssignal.h for various externs and definitions that may be required
34 by some configurations for calls to signal later in this source file. */
35 #include "syssignal.h"
37 /* This may include sys/types.h, and that somehow loses
38 if this is not done before the other system files. */
39 #include "xterm.h"
40 #include <X11/cursorfont.h>
42 /* Load sys/types.h if not already loaded.
43 In some systems loading it twice is suicidal. */
44 #ifndef makedev
45 #include <sys/types.h>
46 #endif /* makedev */
48 #include <sys/ioctl.h>
50 #include "systime.h"
52 #include <fcntl.h>
53 #include <ctype.h>
54 #include <errno.h>
55 #include <setjmp.h>
56 #include <sys/stat.h>
57 /* Caused redefinition of DBL_DIG on Netbsd; seems not to be needed. */
58 /* #include <sys/param.h> */
60 #include "charset.h"
61 #include "character.h"
62 #include "coding.h"
63 #include "frame.h"
64 #include "dispextern.h"
65 #ifdef HAVE_XWIDGETS
66 #include "xwidget.h"
67 #endif
68 #include "fontset.h"
69 #include "termhooks.h"
70 #include "termopts.h"
71 #include "termchar.h"
72 #include "emacs-icon.h"
73 #include "disptab.h"
74 #include "buffer.h"
75 #include "window.h"
76 #include "keyboard.h"
77 #include "intervals.h"
78 #include "process.h"
79 #include "atimer.h"
80 #include "keymap.h"
81 #include "font.h"
82 #include "fontset.h"
83 #include "xsettings.h"
84 #include "xgselect.h"
85 #include "sysselect.h"
87 #ifdef USE_X_TOOLKIT
88 #include <X11/Shell.h>
89 #endif
91 #ifdef HAVE_SYS_TIME_H
92 #include <sys/time.h>
93 #endif
95 #include <unistd.h>
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 (Widget, XtPointer, XEvent *, Boolean *);
109 #endif /* not NO_EDITRES */
111 /* Include toolkit specific headers for the scroll bar widget. */
113 #ifdef USE_TOOLKIT_SCROLL_BARS
114 #if defined USE_MOTIF
115 #include <Xm/Xm.h> /* for LESSTIF_VERSION */
116 #include <Xm/ScrollBar.h>
117 #else /* !USE_MOTIF i.e. use Xaw */
119 #ifdef HAVE_XAW3D
120 #include <X11/Xaw3d/Simple.h>
121 #include <X11/Xaw3d/Scrollbar.h>
122 #include <X11/Xaw3d/ThreeD.h>
123 #else /* !HAVE_XAW3D */
124 #include <X11/Xaw/Simple.h>
125 #include <X11/Xaw/Scrollbar.h>
126 #endif /* !HAVE_XAW3D */
127 #ifndef XtNpickTop
128 #define XtNpickTop "pickTop"
129 #endif /* !XtNpickTop */
130 #endif /* !USE_MOTIF */
131 #endif /* USE_TOOLKIT_SCROLL_BARS */
133 #endif /* USE_X_TOOLKIT */
135 #ifdef USE_X_TOOLKIT
136 #include "widget.h"
137 #ifndef XtNinitialState
138 #define XtNinitialState "initialState"
139 #endif
140 #endif
142 /* Default to using XIM if available. */
143 #ifdef USE_XIM
144 int use_xim = 1;
145 #else
146 int use_xim = 0; /* configure --without-xim */
147 #endif
151 /* Non-zero means that a HELP_EVENT has been generated since Emacs
152 start. */
154 static int any_help_event_p;
156 /* Last window where we saw the mouse. Used by mouse-autoselect-window. */
157 static Lisp_Object last_window;
159 /* This is a chain of structures for all the X displays currently in
160 use. */
162 struct x_display_info *x_display_list;
164 /* This is a list of cons cells, each of the form (NAME
165 . FONT-LIST-CACHE), one for each element of x_display_list and in
166 the same order. NAME is the name of the frame. FONT-LIST-CACHE
167 records previous values returned by x-list-fonts. */
169 Lisp_Object x_display_name_list;
171 /* Frame being updated by update_frame. This is declared in term.c.
172 This is set by update_begin and looked at by all the XT functions.
173 It is zero while not inside an update. In that case, the XT
174 functions assume that `selected_frame' is the frame to apply to. */
176 extern struct frame *updating_frame;
178 /* This is a frame waiting to be auto-raised, within XTread_socket. */
180 static struct frame *pending_autoraise_frame;
182 /* This is a frame waiting for an event matching mask, within XTread_socket. */
184 static struct {
185 struct frame *f;
186 int eventtype;
187 } pending_event_wait;
189 #ifdef USE_X_TOOLKIT
190 /* The application context for Xt use. */
191 XtAppContext Xt_app_con;
192 static String Xt_default_resources[] = {0};
194 /* Non-zero means user is interacting with a toolkit scroll bar. */
196 static int toolkit_scroll_bar_interaction;
197 #endif /* USE_X_TOOLKIT */
199 /* Non-zero timeout value means ignore next mouse click if it arrives
200 before that timeout elapses (i.e. as part of the same sequence of
201 events resulting from clicking on a frame to select it). */
203 static unsigned long ignore_next_mouse_click_timeout;
205 /* Mouse movement.
207 Formerly, we used PointerMotionHintMask (in standard_event_mask)
208 so that we would have to call XQueryPointer after each MotionNotify
209 event to ask for another such event. However, this made mouse tracking
210 slow, and there was a bug that made it eventually stop.
212 Simply asking for MotionNotify all the time seems to work better.
214 In order to avoid asking for motion events and then throwing most
215 of them away or busy-polling the server for mouse positions, we ask
216 the server for pointer motion hints. This means that we get only
217 one event per group of mouse movements. "Groups" are delimited by
218 other kinds of events (focus changes and button clicks, for
219 example), or by XQueryPointer calls; when one of these happens, we
220 get another MotionNotify event the next time the mouse moves. This
221 is at least as efficient as getting motion events when mouse
222 tracking is on, and I suspect only negligibly worse when tracking
223 is off. */
225 /* Where the mouse was last time we reported a mouse event. */
227 static XRectangle last_mouse_glyph;
228 static FRAME_PTR last_mouse_glyph_frame;
229 static Lisp_Object last_mouse_press_frame;
231 /* The scroll bar in which the last X motion event occurred.
233 If the last X motion event occurred in a scroll bar, we set this so
234 XTmouse_position can know whether to report a scroll bar motion or
235 an ordinary motion.
237 If the last X motion event didn't occur in a scroll bar, we set
238 this to Qnil, to tell XTmouse_position to return an ordinary motion
239 event. */
241 static Lisp_Object last_mouse_scroll_bar;
243 /* This is a hack. We would really prefer that XTmouse_position would
244 return the time associated with the position it returns, but there
245 doesn't seem to be any way to wrest the time-stamp from the server
246 along with the position query. So, we just keep track of the time
247 of the last movement we received, and return that in hopes that
248 it's somewhat accurate. */
250 static Time last_mouse_movement_time;
252 /* Time for last user interaction as returned in X events. */
254 static Time last_user_time;
256 /* Incremented by XTread_socket whenever it really tries to read
257 events. */
259 #ifdef __STDC__
260 static int volatile input_signal_count;
261 #else
262 static int input_signal_count;
263 #endif
265 /* Used locally within XTread_socket. */
267 static int x_noop_count;
269 static Lisp_Object Qalt, Qhyper, Qmeta, Qsuper, Qmodifier_value;
271 static Lisp_Object Qvendor_specific_keysyms;
272 static Lisp_Object Qlatin_1;
274 #ifdef USE_GTK
275 /* The name of the Emacs icon file. */
276 static Lisp_Object xg_default_icon_file;
278 /* Used in gtkutil.c. */
279 Lisp_Object Qx_gtk_map_stock;
280 #endif
282 /* Some functions take this as char *, not const char *. */
283 static char emacs_class[] = EMACS_CLASS;
285 enum xembed_info
287 XEMBED_MAPPED = 1 << 0
290 enum xembed_message
292 XEMBED_EMBEDDED_NOTIFY = 0,
293 XEMBED_WINDOW_ACTIVATE = 1,
294 XEMBED_WINDOW_DEACTIVATE = 2,
295 XEMBED_REQUEST_FOCUS = 3,
296 XEMBED_FOCUS_IN = 4,
297 XEMBED_FOCUS_OUT = 5,
298 XEMBED_FOCUS_NEXT = 6,
299 XEMBED_FOCUS_PREV = 7,
301 XEMBED_MODALITY_ON = 10,
302 XEMBED_MODALITY_OFF = 11,
303 XEMBED_REGISTER_ACCELERATOR = 12,
304 XEMBED_UNREGISTER_ACCELERATOR = 13,
305 XEMBED_ACTIVATE_ACCELERATOR = 14
308 /* Used in x_flush. */
310 static int x_alloc_nearest_color_1 (Display *, Colormap, XColor *);
311 static void x_set_window_size_1 (struct frame *, int, int, int);
312 static void x_raise_frame (struct frame *);
313 static void x_lower_frame (struct frame *);
314 static const XColor *x_color_cells (Display *, int *);
315 static void x_update_window_end (struct window *, int, int);
317 static int x_io_error_quitter (Display *);
318 static struct terminal *x_create_terminal (struct x_display_info *);
319 void x_delete_terminal (struct terminal *);
320 static void x_update_end (struct frame *);
321 static void XTframe_up_to_date (struct frame *);
322 static void XTset_terminal_modes (struct terminal *);
323 static void XTreset_terminal_modes (struct terminal *);
324 static void x_clear_frame (struct frame *);
325 static void x_ins_del_lines (struct frame *, int, int) NO_RETURN;
326 static void frame_highlight (struct frame *);
327 static void frame_unhighlight (struct frame *);
328 static void x_new_focus_frame (struct x_display_info *, struct frame *);
329 static void x_focus_changed (int, int, struct x_display_info *,
330 struct frame *, struct input_event *);
331 static void x_detect_focus_change (struct x_display_info *,
332 XEvent *, struct input_event *);
333 static void XTframe_rehighlight (struct frame *);
334 static void x_frame_rehighlight (struct x_display_info *);
335 static void x_draw_hollow_cursor (struct window *, struct glyph_row *);
336 static void x_draw_bar_cursor (struct window *, struct glyph_row *, int,
337 enum text_cursor_kinds);
339 static void x_clip_to_row (struct window *, struct glyph_row *, int, GC);
340 static void x_flush (struct frame *f);
341 static void x_update_begin (struct frame *);
342 static void x_update_window_begin (struct window *);
343 static void x_after_update_window_line (struct glyph_row *);
344 static struct scroll_bar *x_window_to_scroll_bar (Display *, Window);
345 static void x_scroll_bar_report_motion (struct frame **, Lisp_Object *,
346 enum scroll_bar_part *,
347 Lisp_Object *, Lisp_Object *,
348 Time *);
349 static void x_handle_net_wm_state (struct frame *, XPropertyEvent *);
350 static void x_check_fullscreen (struct frame *);
351 static void x_check_expected_move (struct frame *, int, int);
352 static void x_sync_with_move (struct frame *, int, int, int);
353 static int handle_one_xevent (struct x_display_info *, XEvent *,
354 int *, struct input_event *);
355 #ifdef USE_GTK
356 static int x_dispatch_event (XEvent *, Display *);
357 #endif
358 /* Don't declare this NO_RETURN because we want no
359 interference with debugging failing X calls. */
360 static void x_connection_closed (Display *, const char *);
361 static void x_wm_set_window_state (struct frame *, int);
362 static void x_wm_set_icon_pixmap (struct frame *, ptrdiff_t);
363 static void x_initialize (void);
366 /* Flush display of frame F, or of all frames if F is null. */
368 static void
369 x_flush (struct frame *f)
371 /* Don't call XFlush when it is not safe to redisplay; the X
372 connection may be broken. */
373 if (!NILP (Vinhibit_redisplay))
374 return;
376 BLOCK_INPUT;
377 if (f == NULL)
379 Lisp_Object rest, frame;
380 FOR_EACH_FRAME (rest, frame)
381 if (FRAME_X_P (XFRAME (frame)))
382 x_flush (XFRAME (frame));
384 else if (FRAME_X_P (f))
385 XFlush (FRAME_X_DISPLAY (f));
386 UNBLOCK_INPUT;
390 /* Remove calls to XFlush by defining XFlush to an empty replacement.
391 Calls to XFlush should be unnecessary because the X output buffer
392 is flushed automatically as needed by calls to XPending,
393 XNextEvent, or XWindowEvent according to the XFlush man page.
394 XTread_socket calls XPending. Removing XFlush improves
395 performance. */
397 #define XFlush(DISPLAY) (void) 0
400 /***********************************************************************
401 Debugging
402 ***********************************************************************/
404 #if 0
406 /* This is a function useful for recording debugging information about
407 the sequence of occurrences in this file. */
409 struct record
411 char *locus;
412 int type;
415 struct record event_record[100];
417 int event_record_index;
419 void
420 record_event (char *locus, int type)
422 if (event_record_index == sizeof (event_record) / sizeof (struct record))
423 event_record_index = 0;
425 event_record[event_record_index].locus = locus;
426 event_record[event_record_index].type = type;
427 event_record_index++;
430 #endif /* 0 */
434 /* Return the struct x_display_info corresponding to DPY. */
436 struct x_display_info *
437 x_display_info_for_display (Display *dpy)
439 struct x_display_info *dpyinfo;
441 for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
442 if (dpyinfo->display == dpy)
443 return dpyinfo;
445 return 0;
448 #define OPAQUE 0xffffffff
450 void
451 x_set_frame_alpha (struct frame *f)
453 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
454 Display *dpy = FRAME_X_DISPLAY (f);
455 Window win = FRAME_OUTER_WINDOW (f);
456 double alpha = 1.0;
457 double alpha_min = 1.0;
458 unsigned long opac;
460 if (dpyinfo->x_highlight_frame == f)
461 alpha = f->alpha[0];
462 else
463 alpha = f->alpha[1];
465 if (FLOATP (Vframe_alpha_lower_limit))
466 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
467 else if (INTEGERP (Vframe_alpha_lower_limit))
468 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
470 if (alpha < 0.0)
471 return;
472 else if (alpha > 1.0)
473 alpha = 1.0;
474 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
475 alpha = alpha_min;
477 opac = alpha * OPAQUE;
479 /* return unless necessary */
481 unsigned char *data;
482 Atom actual;
483 int rc, format;
484 unsigned long n, left;
486 x_catch_errors (dpy);
487 rc = XGetWindowProperty (dpy, win, dpyinfo->Xatom_net_wm_window_opacity,
488 0L, 1L, False, XA_CARDINAL,
489 &actual, &format, &n, &left,
490 &data);
492 if (rc == Success && actual != None)
494 unsigned long value = *(unsigned long *)data;
495 XFree ((void *) data);
496 if (value == opac)
498 x_uncatch_errors ();
499 return;
504 XChangeProperty (dpy, win, dpyinfo->Xatom_net_wm_window_opacity,
505 XA_CARDINAL, 32, PropModeReplace,
506 (unsigned char *) &opac, 1L);
507 x_uncatch_errors ();
511 x_display_pixel_height (struct x_display_info *dpyinfo)
513 return HeightOfScreen (dpyinfo->screen);
517 x_display_pixel_width (struct x_display_info *dpyinfo)
519 return WidthOfScreen (dpyinfo->screen);
523 /***********************************************************************
524 Starting and ending an update
525 ***********************************************************************/
527 /* Start an update of frame F. This function is installed as a hook
528 for update_begin, i.e. it is called when update_begin is called.
529 This function is called prior to calls to x_update_window_begin for
530 each window being updated. Currently, there is nothing to do here
531 because all interesting stuff is done on a window basis. */
533 static void
534 x_update_begin (struct frame *f)
536 /* Nothing to do. */
540 /* Start update of window W. Set the global variable updated_window
541 to the window being updated and set output_cursor to the cursor
542 position of W. */
544 static void
545 x_update_window_begin (struct window *w)
547 struct frame *f = XFRAME (WINDOW_FRAME (w));
548 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
550 updated_window = w;
551 set_output_cursor (&w->cursor);
553 BLOCK_INPUT;
555 if (f == hlinfo->mouse_face_mouse_frame)
557 /* Don't do highlighting for mouse motion during the update. */
558 hlinfo->mouse_face_defer = 1;
560 /* If F needs to be redrawn, simply forget about any prior mouse
561 highlighting. */
562 if (FRAME_GARBAGED_P (f))
563 hlinfo->mouse_face_window = Qnil;
566 UNBLOCK_INPUT;
570 /* Draw a vertical window border from (x,y0) to (x,y1) */
572 static void
573 x_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
575 struct frame *f = XFRAME (WINDOW_FRAME (w));
576 struct face *face;
578 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
579 if (face)
580 XSetForeground (FRAME_X_DISPLAY (f), f->output_data.x->normal_gc,
581 face->foreground);
583 XDrawLine (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
584 f->output_data.x->normal_gc, x, y0, x, y1);
587 /* End update of window W (which is equal to updated_window).
589 Draw vertical borders between horizontally adjacent windows, and
590 display W's cursor if CURSOR_ON_P is non-zero.
592 MOUSE_FACE_OVERWRITTEN_P non-zero means that some row containing
593 glyphs in mouse-face were overwritten. In that case we have to
594 make sure that the mouse-highlight is properly redrawn.
596 W may be a menu bar pseudo-window in case we don't have X toolkit
597 support. Such windows don't have a cursor, so don't display it
598 here. */
600 static void
601 x_update_window_end (struct window *w, int cursor_on_p, int mouse_face_overwritten_p)
603 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (XFRAME (w->frame));
605 if (!w->pseudo_window_p)
607 BLOCK_INPUT;
609 if (cursor_on_p)
610 display_and_set_cursor (w, 1, output_cursor.hpos,
611 output_cursor.vpos,
612 output_cursor.x, output_cursor.y);
614 if (draw_window_fringes (w, 1))
615 x_draw_vertical_border (w);
617 UNBLOCK_INPUT;
620 /* If a row with mouse-face was overwritten, arrange for
621 XTframe_up_to_date to redisplay the mouse highlight. */
622 if (mouse_face_overwritten_p)
624 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
625 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
626 hlinfo->mouse_face_window = Qnil;
629 updated_window = NULL;
633 /* End update of frame F. This function is installed as a hook in
634 update_end. */
636 static void
637 x_update_end (struct frame *f)
639 /* Mouse highlight may be displayed again. */
640 MOUSE_HL_INFO (f)->mouse_face_defer = 0;
642 #ifndef XFlush
643 BLOCK_INPUT;
644 XFlush (FRAME_X_DISPLAY (f));
645 UNBLOCK_INPUT;
646 #endif
650 /* This function is called from various places in xdisp.c whenever a
651 complete update has been performed. The global variable
652 updated_window is not available here. */
654 static void
655 XTframe_up_to_date (struct frame *f)
657 if (FRAME_X_P (f))
659 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
661 if (hlinfo->mouse_face_deferred_gc
662 || f == hlinfo->mouse_face_mouse_frame)
664 BLOCK_INPUT;
665 if (hlinfo->mouse_face_mouse_frame)
666 note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
667 hlinfo->mouse_face_mouse_x,
668 hlinfo->mouse_face_mouse_y);
669 hlinfo->mouse_face_deferred_gc = 0;
670 UNBLOCK_INPUT;
676 /* Draw truncation mark bitmaps, continuation mark bitmaps, overlay
677 arrow bitmaps, or clear the fringes if no bitmaps are required
678 before DESIRED_ROW is made current. The window being updated is
679 found in updated_window. This function It is called from
680 update_window_line only if it is known that there are differences
681 between bitmaps to be drawn between current row and DESIRED_ROW. */
683 static void
684 x_after_update_window_line (struct glyph_row *desired_row)
686 struct window *w = updated_window;
687 struct frame *f;
688 int width, height;
690 xassert (w);
692 if (!desired_row->mode_line_p && !w->pseudo_window_p)
693 desired_row->redraw_fringe_bitmaps_p = 1;
695 /* When a window has disappeared, make sure that no rest of
696 full-width rows stays visible in the internal border. Could
697 check here if updated_window is the leftmost/rightmost window,
698 but I guess it's not worth doing since vertically split windows
699 are almost never used, internal border is rarely set, and the
700 overhead is very small. */
701 if (windows_or_buffers_changed
702 && desired_row->full_width_p
703 && (f = XFRAME (w->frame),
704 width = FRAME_INTERNAL_BORDER_WIDTH (f),
705 width != 0)
706 && (height = desired_row->visible_height,
707 height > 0))
709 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
711 BLOCK_INPUT;
712 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
713 0, y, width, height, False);
714 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
715 FRAME_PIXEL_WIDTH (f) - width,
716 y, width, height, False);
717 UNBLOCK_INPUT;
721 static void
722 x_draw_fringe_bitmap (struct window *w, struct glyph_row *row, struct draw_fringe_bitmap_params *p)
724 struct frame *f = XFRAME (WINDOW_FRAME (w));
725 Display *display = FRAME_X_DISPLAY (f);
726 Window window = FRAME_X_WINDOW (f);
727 GC gc = f->output_data.x->normal_gc;
728 struct face *face = p->face;
730 /* Must clip because of partially visible lines. */
731 x_clip_to_row (w, row, -1, gc);
733 if (!p->overlay_p)
735 int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
737 /* In case the same realized face is used for fringes and
738 for something displayed in the text (e.g. face `region' on
739 mono-displays, the fill style may have been changed to
740 FillSolid in x_draw_glyph_string_background. */
741 if (face->stipple)
742 XSetFillStyle (display, face->gc, FillOpaqueStippled);
743 else
744 XSetForeground (display, face->gc, face->background);
746 #ifdef USE_TOOLKIT_SCROLL_BARS
747 /* If the fringe is adjacent to the left (right) scroll bar of a
748 leftmost (rightmost, respectively) window, then extend its
749 background to the gap between the fringe and the bar. */
750 if ((WINDOW_LEFTMOST_P (w)
751 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
752 || (WINDOW_RIGHTMOST_P (w)
753 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w)))
755 int sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
757 if (sb_width > 0)
759 int bar_area_x = WINDOW_SCROLL_BAR_AREA_X (w);
760 int bar_area_width = (WINDOW_CONFIG_SCROLL_BAR_COLS (w)
761 * FRAME_COLUMN_WIDTH (f));
763 if (bx < 0)
765 /* Bitmap fills the fringe. */
766 if (bar_area_x + bar_area_width == p->x)
767 bx = bar_area_x + sb_width;
768 else if (p->x + p->wd == bar_area_x)
769 bx = bar_area_x;
770 if (bx >= 0)
772 int header_line_height = WINDOW_HEADER_LINE_HEIGHT (w);
774 nx = bar_area_width - sb_width;
775 by = WINDOW_TO_FRAME_PIXEL_Y (w, max (header_line_height,
776 row->y));
777 ny = row->visible_height;
780 else
782 if (bar_area_x + bar_area_width == bx)
784 bx = bar_area_x + sb_width;
785 nx += bar_area_width - sb_width;
787 else if (bx + nx == bar_area_x)
788 nx += bar_area_width - sb_width;
792 #endif
793 if (bx >= 0 && nx > 0)
794 XFillRectangle (display, window, face->gc, bx, by, nx, ny);
796 if (!face->stipple)
797 XSetForeground (display, face->gc, face->foreground);
800 if (p->which)
802 char *bits;
803 Pixmap pixmap, clipmask = (Pixmap) 0;
804 int depth = DefaultDepthOfScreen (FRAME_X_SCREEN (f));
805 XGCValues gcv;
807 if (p->wd > 8)
808 bits = (char *) (p->bits + p->dh);
809 else
810 bits = (char *) p->bits + p->dh;
812 /* Draw the bitmap. I believe these small pixmaps can be cached
813 by the server. */
814 pixmap = XCreatePixmapFromBitmapData (display, window, bits, p->wd, p->h,
815 (p->cursor_p
816 ? (p->overlay_p ? face->background
817 : f->output_data.x->cursor_pixel)
818 : face->foreground),
819 face->background, depth);
821 if (p->overlay_p)
823 clipmask = XCreatePixmapFromBitmapData (display,
824 FRAME_X_DISPLAY_INFO (f)->root_window,
825 bits, p->wd, p->h,
826 1, 0, 1);
827 gcv.clip_mask = clipmask;
828 gcv.clip_x_origin = p->x;
829 gcv.clip_y_origin = p->y;
830 XChangeGC (display, gc, GCClipMask | GCClipXOrigin | GCClipYOrigin, &gcv);
833 XCopyArea (display, pixmap, window, gc, 0, 0,
834 p->wd, p->h, p->x, p->y);
835 XFreePixmap (display, pixmap);
837 if (p->overlay_p)
839 gcv.clip_mask = (Pixmap) 0;
840 XChangeGC (display, gc, GCClipMask, &gcv);
841 XFreePixmap (display, clipmask);
845 XSetClipMask (display, gc, None);
850 /* This is called when starting Emacs and when restarting after
851 suspend. When starting Emacs, no X window is mapped. And nothing
852 must be done to Emacs's own window if it is suspended (though that
853 rarely happens). */
855 static void
856 XTset_terminal_modes (struct terminal *terminal)
860 /* This is called when exiting or suspending Emacs. Exiting will make
861 the X-windows go away, and suspending requires no action. */
863 static void
864 XTreset_terminal_modes (struct terminal *terminal)
869 /***********************************************************************
870 Glyph display
871 ***********************************************************************/
875 static void x_set_glyph_string_clipping (struct glyph_string *);
876 static void x_set_glyph_string_gc (struct glyph_string *);
877 static void x_draw_glyph_string_background (struct glyph_string *,
878 int);
879 static void x_draw_glyph_string_foreground (struct glyph_string *);
880 static void x_draw_composite_glyph_string_foreground (struct glyph_string *);
881 static void x_draw_glyph_string_box (struct glyph_string *);
882 static void x_draw_glyph_string (struct glyph_string *);
883 static void x_delete_glyphs (struct frame *, int) NO_RETURN;
884 static void x_compute_glyph_string_overhangs (struct glyph_string *);
885 static void x_set_cursor_gc (struct glyph_string *);
886 static void x_set_mode_line_face_gc (struct glyph_string *);
887 static void x_set_mouse_face_gc (struct glyph_string *);
888 static int x_alloc_lighter_color (struct frame *, Display *, Colormap,
889 unsigned long *, double, int);
890 static void x_setup_relief_color (struct frame *, struct relief *,
891 double, int, unsigned long);
892 static void x_setup_relief_colors (struct glyph_string *);
893 static void x_draw_image_glyph_string (struct glyph_string *);
894 static void x_draw_image_relief (struct glyph_string *);
895 static void x_draw_image_foreground (struct glyph_string *);
896 static void x_draw_image_foreground_1 (struct glyph_string *, Pixmap);
897 static void x_clear_glyph_string_rect (struct glyph_string *, int,
898 int, int, int);
899 static void x_draw_relief_rect (struct frame *, int, int, int, int,
900 int, int, int, int, int, int,
901 XRectangle *);
902 static void x_draw_box_rect (struct glyph_string *, int, int, int, int,
903 int, int, int, XRectangle *);
904 static void x_scroll_bar_clear (struct frame *);
906 #if GLYPH_DEBUG
907 static void x_check_font (struct frame *, struct font *);
908 #endif
911 /* Set S->gc to a suitable GC for drawing glyph string S in cursor
912 face. */
914 static void
915 x_set_cursor_gc (struct glyph_string *s)
917 if (s->font == FRAME_FONT (s->f)
918 && s->face->background == FRAME_BACKGROUND_PIXEL (s->f)
919 && s->face->foreground == FRAME_FOREGROUND_PIXEL (s->f)
920 && !s->cmp)
921 s->gc = s->f->output_data.x->cursor_gc;
922 else
924 /* Cursor on non-default face: must merge. */
925 XGCValues xgcv;
926 unsigned long mask;
928 xgcv.background = s->f->output_data.x->cursor_pixel;
929 xgcv.foreground = s->face->background;
931 /* If the glyph would be invisible, try a different foreground. */
932 if (xgcv.foreground == xgcv.background)
933 xgcv.foreground = s->face->foreground;
934 if (xgcv.foreground == xgcv.background)
935 xgcv.foreground = s->f->output_data.x->cursor_foreground_pixel;
936 if (xgcv.foreground == xgcv.background)
937 xgcv.foreground = s->face->foreground;
939 /* Make sure the cursor is distinct from text in this face. */
940 if (xgcv.background == s->face->background
941 && xgcv.foreground == s->face->foreground)
943 xgcv.background = s->face->foreground;
944 xgcv.foreground = s->face->background;
947 IF_DEBUG (x_check_font (s->f, s->font));
948 xgcv.graphics_exposures = False;
949 mask = GCForeground | GCBackground | GCGraphicsExposures;
951 if (FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc)
952 XChangeGC (s->display, FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc,
953 mask, &xgcv);
954 else
955 FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc
956 = XCreateGC (s->display, s->window, mask, &xgcv);
958 s->gc = FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc;
963 /* Set up S->gc of glyph string S for drawing text in mouse face. */
965 static void
966 x_set_mouse_face_gc (struct glyph_string *s)
968 int face_id;
969 struct face *face;
971 /* What face has to be used last for the mouse face? */
972 face_id = MOUSE_HL_INFO (s->f)->mouse_face_face_id;
973 face = FACE_FROM_ID (s->f, face_id);
974 if (face == NULL)
975 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
977 if (s->first_glyph->type == CHAR_GLYPH)
978 face_id = FACE_FOR_CHAR (s->f, face, s->first_glyph->u.ch, -1, Qnil);
979 else
980 face_id = FACE_FOR_CHAR (s->f, face, 0, -1, Qnil);
981 s->face = FACE_FROM_ID (s->f, face_id);
982 PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
984 if (s->font == s->face->font)
985 s->gc = s->face->gc;
986 else
988 /* Otherwise construct scratch_cursor_gc with values from FACE
989 except for FONT. */
990 XGCValues xgcv;
991 unsigned long mask;
993 xgcv.background = s->face->background;
994 xgcv.foreground = s->face->foreground;
995 xgcv.graphics_exposures = False;
996 mask = GCForeground | GCBackground | GCGraphicsExposures;
998 if (FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc)
999 XChangeGC (s->display, FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc,
1000 mask, &xgcv);
1001 else
1002 FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc
1003 = XCreateGC (s->display, s->window, mask, &xgcv);
1005 s->gc = FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc;
1008 xassert (s->gc != 0);
1012 /* Set S->gc of glyph string S to a GC suitable for drawing a mode line.
1013 Faces to use in the mode line have already been computed when the
1014 matrix was built, so there isn't much to do, here. */
1016 static inline void
1017 x_set_mode_line_face_gc (struct glyph_string *s)
1019 s->gc = s->face->gc;
1023 /* Set S->gc of glyph string S for drawing that glyph string. Set
1024 S->stippled_p to a non-zero value if the face of S has a stipple
1025 pattern. */
1027 static inline void
1028 x_set_glyph_string_gc (struct glyph_string *s)
1030 PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
1032 if (s->hl == DRAW_NORMAL_TEXT)
1034 s->gc = s->face->gc;
1035 s->stippled_p = s->face->stipple != 0;
1037 else if (s->hl == DRAW_INVERSE_VIDEO)
1039 x_set_mode_line_face_gc (s);
1040 s->stippled_p = s->face->stipple != 0;
1042 else if (s->hl == DRAW_CURSOR)
1044 x_set_cursor_gc (s);
1045 s->stippled_p = 0;
1047 else if (s->hl == DRAW_MOUSE_FACE)
1049 x_set_mouse_face_gc (s);
1050 s->stippled_p = s->face->stipple != 0;
1052 else if (s->hl == DRAW_IMAGE_RAISED
1053 || s->hl == DRAW_IMAGE_SUNKEN)
1055 s->gc = s->face->gc;
1056 s->stippled_p = s->face->stipple != 0;
1058 else
1060 s->gc = s->face->gc;
1061 s->stippled_p = s->face->stipple != 0;
1064 /* GC must have been set. */
1065 xassert (s->gc != 0);
1069 /* Set clipping for output of glyph string S. S may be part of a mode
1070 line or menu if we don't have X toolkit support. */
1072 static inline void
1073 x_set_glyph_string_clipping (struct glyph_string *s)
1075 XRectangle *r = s->clip;
1076 int n = get_glyph_string_clip_rects (s, r, 2);
1078 if (n > 0)
1079 XSetClipRectangles (s->display, s->gc, 0, 0, r, n, Unsorted);
1080 s->num_clips = n;
1084 /* Set SRC's clipping for output of glyph string DST. This is called
1085 when we are drawing DST's left_overhang or right_overhang only in
1086 the area of SRC. */
1088 static void
1089 x_set_glyph_string_clipping_exactly (struct glyph_string *src, struct glyph_string *dst)
1091 XRectangle r;
1093 r.x = src->x;
1094 r.width = src->width;
1095 r.y = src->y;
1096 r.height = src->height;
1097 dst->clip[0] = r;
1098 dst->num_clips = 1;
1099 XSetClipRectangles (dst->display, dst->gc, 0, 0, &r, 1, Unsorted);
1103 /* RIF:
1104 Compute left and right overhang of glyph string S. */
1106 static void
1107 x_compute_glyph_string_overhangs (struct glyph_string *s)
1109 if (s->cmp == NULL
1110 && (s->first_glyph->type == CHAR_GLYPH
1111 || s->first_glyph->type == COMPOSITE_GLYPH))
1113 struct font_metrics metrics;
1115 if (s->first_glyph->type == CHAR_GLYPH)
1117 unsigned *code = alloca (sizeof (unsigned) * s->nchars);
1118 struct font *font = s->font;
1119 int i;
1121 for (i = 0; i < s->nchars; i++)
1122 code[i] = (s->char2b[i].byte1 << 8) | s->char2b[i].byte2;
1123 font->driver->text_extents (font, code, s->nchars, &metrics);
1125 else
1127 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1129 composition_gstring_width (gstring, s->cmp_from, s->cmp_to, &metrics);
1131 s->right_overhang = (metrics.rbearing > metrics.width
1132 ? metrics.rbearing - metrics.width : 0);
1133 s->left_overhang = metrics.lbearing < 0 ? - metrics.lbearing : 0;
1135 else if (s->cmp)
1137 s->right_overhang = s->cmp->rbearing - s->cmp->pixel_width;
1138 s->left_overhang = - s->cmp->lbearing;
1143 /* Fill rectangle X, Y, W, H with background color of glyph string S. */
1145 static inline void
1146 x_clear_glyph_string_rect (struct glyph_string *s, int x, int y, int w, int h)
1148 XGCValues xgcv;
1149 XGetGCValues (s->display, s->gc, GCForeground | GCBackground, &xgcv);
1150 XSetForeground (s->display, s->gc, xgcv.background);
1151 XFillRectangle (s->display, s->window, s->gc, x, y, w, h);
1152 XSetForeground (s->display, s->gc, xgcv.foreground);
1156 /* Draw the background of glyph_string S. If S->background_filled_p
1157 is non-zero don't draw it. FORCE_P non-zero means draw the
1158 background even if it wouldn't be drawn normally. This is used
1159 when a string preceding S draws into the background of S, or S
1160 contains the first component of a composition. */
1162 static void
1163 x_draw_glyph_string_background (struct glyph_string *s, int force_p)
1165 /* Nothing to do if background has already been drawn or if it
1166 shouldn't be drawn in the first place. */
1167 if (!s->background_filled_p)
1169 int box_line_width = max (s->face->box_line_width, 0);
1171 if (s->stippled_p)
1173 /* Fill background with a stipple pattern. */
1174 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
1175 XFillRectangle (s->display, s->window, s->gc, s->x,
1176 s->y + box_line_width,
1177 s->background_width,
1178 s->height - 2 * box_line_width);
1179 XSetFillStyle (s->display, s->gc, FillSolid);
1180 s->background_filled_p = 1;
1182 else if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
1183 || s->font_not_found_p
1184 || s->extends_to_end_of_line_p
1185 || force_p)
1187 x_clear_glyph_string_rect (s, s->x, s->y + box_line_width,
1188 s->background_width,
1189 s->height - 2 * box_line_width);
1190 s->background_filled_p = 1;
1196 /* Draw the foreground of glyph string S. */
1198 static void
1199 x_draw_glyph_string_foreground (struct glyph_string *s)
1201 int i, x;
1203 /* If first glyph of S has a left box line, start drawing the text
1204 of S to the right of that box line. */
1205 if (s->face->box != FACE_NO_BOX
1206 && s->first_glyph->left_box_line_p)
1207 x = s->x + eabs (s->face->box_line_width);
1208 else
1209 x = s->x;
1211 /* Draw characters of S as rectangles if S's font could not be
1212 loaded. */
1213 if (s->font_not_found_p)
1215 for (i = 0; i < s->nchars; ++i)
1217 struct glyph *g = s->first_glyph + i;
1218 XDrawRectangle (s->display, s->window,
1219 s->gc, x, s->y, g->pixel_width - 1,
1220 s->height - 1);
1221 x += g->pixel_width;
1224 else
1226 struct font *font = s->font;
1227 int boff = font->baseline_offset;
1228 int y;
1230 if (font->vertical_centering)
1231 boff = VCENTER_BASELINE_OFFSET (font, s->f) - boff;
1233 y = s->ybase - boff;
1234 if (s->for_overlaps
1235 || (s->background_filled_p && s->hl != DRAW_CURSOR))
1236 font->driver->draw (s, 0, s->nchars, x, y, 0);
1237 else
1238 font->driver->draw (s, 0, s->nchars, x, y, 1);
1239 if (s->face->overstrike)
1240 font->driver->draw (s, 0, s->nchars, x + 1, y, 0);
1244 /* Draw the foreground of composite glyph string S. */
1246 static void
1247 x_draw_composite_glyph_string_foreground (struct glyph_string *s)
1249 int i, j, x;
1250 struct font *font = s->font;
1252 /* If first glyph of S has a left box line, start drawing the text
1253 of S to the right of that box line. */
1254 if (s->face && s->face->box != FACE_NO_BOX
1255 && s->first_glyph->left_box_line_p)
1256 x = s->x + eabs (s->face->box_line_width);
1257 else
1258 x = s->x;
1260 /* S is a glyph string for a composition. S->cmp_from is the index
1261 of the first character drawn for glyphs of this composition.
1262 S->cmp_from == 0 means we are drawing the very first character of
1263 this composition. */
1265 /* Draw a rectangle for the composition if the font for the very
1266 first character of the composition could not be loaded. */
1267 if (s->font_not_found_p)
1269 if (s->cmp_from == 0)
1270 XDrawRectangle (s->display, s->window, s->gc, x, s->y,
1271 s->width - 1, s->height - 1);
1273 else if (! s->first_glyph->u.cmp.automatic)
1275 int y = s->ybase;
1277 for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
1278 if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
1280 int xx = x + s->cmp->offsets[j * 2];
1281 int yy = y - s->cmp->offsets[j * 2 + 1];
1283 font->driver->draw (s, j, j + 1, xx, yy, 0);
1284 if (s->face->overstrike)
1285 font->driver->draw (s, j, j + 1, xx + 1, yy, 0);
1288 else
1290 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
1291 Lisp_Object glyph;
1292 int y = s->ybase;
1293 int width = 0;
1295 for (i = j = s->cmp_from; i < s->cmp_to; i++)
1297 glyph = LGSTRING_GLYPH (gstring, i);
1298 if (NILP (LGLYPH_ADJUSTMENT (glyph)))
1299 width += LGLYPH_WIDTH (glyph);
1300 else
1302 int xoff, yoff, wadjust;
1304 if (j < i)
1306 font->driver->draw (s, j, i, x, y, 0);
1307 if (s->face->overstrike)
1308 font->driver->draw (s, j, i, x + 1, y, 0);
1309 x += width;
1311 xoff = LGLYPH_XOFF (glyph);
1312 yoff = LGLYPH_YOFF (glyph);
1313 wadjust = LGLYPH_WADJUST (glyph);
1314 font->driver->draw (s, i, i + 1, x + xoff, y + yoff, 0);
1315 if (s->face->overstrike)
1316 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff, 0);
1317 x += wadjust;
1318 j = i + 1;
1319 width = 0;
1322 if (j < i)
1324 font->driver->draw (s, j, i, x, y, 0);
1325 if (s->face->overstrike)
1326 font->driver->draw (s, j, i, x + 1, y, 0);
1332 /* Draw the foreground of glyph string S for glyphless characters. */
1334 static void
1335 x_draw_glyphless_glyph_string_foreground (struct glyph_string *s)
1337 struct glyph *glyph = s->first_glyph;
1338 XChar2b char2b[8];
1339 int x, i, j;
1341 /* If first glyph of S has a left box line, start drawing the text
1342 of S to the right of that box line. */
1343 if (s->face && s->face->box != FACE_NO_BOX
1344 && s->first_glyph->left_box_line_p)
1345 x = s->x + eabs (s->face->box_line_width);
1346 else
1347 x = s->x;
1349 s->char2b = char2b;
1351 for (i = 0; i < s->nchars; i++, glyph++)
1353 char buf[7], *str = NULL;
1354 int len = glyph->u.glyphless.len;
1356 if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_ACRONYM)
1358 if (len > 0
1359 && CHAR_TABLE_P (Vglyphless_char_display)
1360 && (CHAR_TABLE_EXTRA_SLOTS (XCHAR_TABLE (Vglyphless_char_display))
1361 >= 1))
1363 Lisp_Object acronym
1364 = (! glyph->u.glyphless.for_no_font
1365 ? CHAR_TABLE_REF (Vglyphless_char_display,
1366 glyph->u.glyphless.ch)
1367 : XCHAR_TABLE (Vglyphless_char_display)->extras[0]);
1368 if (STRINGP (acronym))
1369 str = SSDATA (acronym);
1372 else if (glyph->u.glyphless.method == GLYPHLESS_DISPLAY_HEX_CODE)
1374 sprintf ((char *) buf, "%0*X",
1375 glyph->u.glyphless.ch < 0x10000 ? 4 : 6,
1376 glyph->u.glyphless.ch);
1377 str = buf;
1380 if (str)
1382 int upper_len = (len + 1) / 2;
1383 unsigned code;
1385 /* It is assured that all LEN characters in STR is ASCII. */
1386 for (j = 0; j < len; j++)
1388 code = s->font->driver->encode_char (s->font, str[j]);
1389 STORE_XCHAR2B (char2b + j, code >> 8, code & 0xFF);
1391 s->font->driver->draw (s, 0, upper_len,
1392 x + glyph->slice.glyphless.upper_xoff,
1393 s->ybase + glyph->slice.glyphless.upper_yoff,
1395 s->font->driver->draw (s, upper_len, len,
1396 x + glyph->slice.glyphless.lower_xoff,
1397 s->ybase + glyph->slice.glyphless.lower_yoff,
1400 if (glyph->u.glyphless.method != GLYPHLESS_DISPLAY_THIN_SPACE)
1401 XDrawRectangle (s->display, s->window, s->gc,
1402 x, s->ybase - glyph->ascent,
1403 glyph->pixel_width - 1,
1404 glyph->ascent + glyph->descent - 1);
1405 x += glyph->pixel_width;
1409 #ifdef USE_X_TOOLKIT
1411 static struct frame *x_frame_of_widget (Widget);
1412 static Boolean cvt_string_to_pixel (Display *, XrmValue *, Cardinal *,
1413 XrmValue *, XrmValue *, XtPointer *);
1414 static void cvt_pixel_dtor (XtAppContext, XrmValue *, XtPointer,
1415 XrmValue *, Cardinal *);
1418 /* Return the frame on which widget WIDGET is used.. Abort if frame
1419 cannot be determined. */
1421 static struct frame *
1422 x_frame_of_widget (Widget widget)
1424 struct x_display_info *dpyinfo;
1425 Lisp_Object tail;
1426 struct frame *f;
1428 dpyinfo = x_display_info_for_display (XtDisplay (widget));
1430 /* Find the top-level shell of the widget. Note that this function
1431 can be called when the widget is not yet realized, so XtWindow
1432 (widget) == 0. That's the reason we can't simply use
1433 x_any_window_to_frame. */
1434 while (!XtIsTopLevelShell (widget))
1435 widget = XtParent (widget);
1437 /* Look for a frame with that top-level widget. Allocate the color
1438 on that frame to get the right gamma correction value. */
1439 for (tail = Vframe_list; CONSP (tail); tail = XCDR (tail))
1440 if (FRAMEP (XCAR (tail))
1441 && (f = XFRAME (XCAR (tail)),
1442 (FRAME_X_P (f)
1443 && f->output_data.nothing != 1
1444 && FRAME_X_DISPLAY_INFO (f) == dpyinfo))
1445 && f->output_data.x->widget == widget)
1446 return f;
1448 abort ();
1452 #ifdef USE_LUCID
1454 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
1455 or DELTA. Try a color with RGB values multiplied by FACTOR first.
1456 If this produces the same color as PIXEL, try a color where all RGB
1457 values have DELTA added. Return the allocated color in *PIXEL.
1458 DISPLAY is the X display, CMAP is the colormap to operate on.
1459 Value is non-zero if successful. */
1462 x_alloc_lighter_color_for_widget (Widget widget, Display *display, Colormap cmap,
1463 unsigned long *pixel, double factor, int delta)
1465 struct frame *f = x_frame_of_widget (widget);
1466 return x_alloc_lighter_color (f, display, cmap, pixel, factor, delta);
1469 #endif
1472 /* Structure specifying which arguments should be passed by Xt to
1473 cvt_string_to_pixel. We want the widget's screen and colormap. */
1475 static XtConvertArgRec cvt_string_to_pixel_args[] =
1477 {XtWidgetBaseOffset, (XtPointer) XtOffset (Widget, core.screen),
1478 sizeof (Screen *)},
1479 {XtWidgetBaseOffset, (XtPointer) XtOffset (Widget, core.colormap),
1480 sizeof (Colormap)}
1484 /* The address of this variable is returned by
1485 cvt_string_to_pixel. */
1487 static Pixel cvt_string_to_pixel_value;
1490 /* Convert a color name to a pixel color.
1492 DPY is the display we are working on.
1494 ARGS is an array of *NARGS XrmValue structures holding additional
1495 information about the widget for which the conversion takes place.
1496 The contents of this array are determined by the specification
1497 in cvt_string_to_pixel_args.
1499 FROM is a pointer to an XrmValue which points to the color name to
1500 convert. TO is an XrmValue in which to return the pixel color.
1502 CLOSURE_RET is a pointer to user-data, in which we record if
1503 we allocated the color or not.
1505 Value is True if successful, False otherwise. */
1507 static Boolean
1508 cvt_string_to_pixel (Display *dpy, XrmValue *args, Cardinal *nargs,
1509 XrmValue *from, XrmValue *to,
1510 XtPointer *closure_ret)
1512 Screen *screen;
1513 Colormap cmap;
1514 Pixel pixel;
1515 String color_name;
1516 XColor color;
1518 if (*nargs != 2)
1520 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
1521 "wrongParameters", "cvt_string_to_pixel",
1522 "XtToolkitError",
1523 "Screen and colormap args required", NULL, NULL);
1524 return False;
1527 screen = *(Screen **) args[0].addr;
1528 cmap = *(Colormap *) args[1].addr;
1529 color_name = (String) from->addr;
1531 if (strcmp (color_name, XtDefaultBackground) == 0)
1533 *closure_ret = (XtPointer) False;
1534 pixel = WhitePixelOfScreen (screen);
1536 else if (strcmp (color_name, XtDefaultForeground) == 0)
1538 *closure_ret = (XtPointer) False;
1539 pixel = BlackPixelOfScreen (screen);
1541 else if (XParseColor (dpy, cmap, color_name, &color)
1542 && x_alloc_nearest_color_1 (dpy, cmap, &color))
1544 pixel = color.pixel;
1545 *closure_ret = (XtPointer) True;
1547 else
1549 String params[1];
1550 Cardinal nparams = 1;
1552 params[0] = color_name;
1553 XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
1554 "badValue", "cvt_string_to_pixel",
1555 "XtToolkitError", "Invalid color `%s'",
1556 params, &nparams);
1557 return False;
1560 if (to->addr != NULL)
1562 if (to->size < sizeof (Pixel))
1564 to->size = sizeof (Pixel);
1565 return False;
1568 *(Pixel *) to->addr = pixel;
1570 else
1572 cvt_string_to_pixel_value = pixel;
1573 to->addr = (XtPointer) &cvt_string_to_pixel_value;
1576 to->size = sizeof (Pixel);
1577 return True;
1581 /* Free a pixel color which was previously allocated via
1582 cvt_string_to_pixel. This is registered as the destructor
1583 for this type of resource via XtSetTypeConverter.
1585 APP is the application context in which we work.
1587 TO is a pointer to an XrmValue holding the color to free.
1588 CLOSURE is the value we stored in CLOSURE_RET for this color
1589 in cvt_string_to_pixel.
1591 ARGS and NARGS are like for cvt_string_to_pixel. */
1593 static void
1594 cvt_pixel_dtor (XtAppContext app, XrmValuePtr to, XtPointer closure, XrmValuePtr args,
1595 Cardinal *nargs)
1597 if (*nargs != 2)
1599 XtAppWarningMsg (app, "wrongParameters", "cvt_pixel_dtor",
1600 "XtToolkitError",
1601 "Screen and colormap arguments required",
1602 NULL, NULL);
1604 else if (closure != NULL)
1606 /* We did allocate the pixel, so free it. */
1607 Screen *screen = *(Screen **) args[0].addr;
1608 Colormap cmap = *(Colormap *) args[1].addr;
1609 x_free_dpy_colors (DisplayOfScreen (screen), screen, cmap,
1610 (Pixel *) to->addr, 1);
1615 #endif /* USE_X_TOOLKIT */
1618 /* Value is an array of XColor structures for the contents of the
1619 color map of display DPY. Set *NCELLS to the size of the array.
1620 Note that this probably shouldn't be called for large color maps,
1621 say a 24-bit TrueColor map. */
1623 static const XColor *
1624 x_color_cells (Display *dpy, int *ncells)
1626 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
1628 if (dpyinfo->color_cells == NULL)
1630 Screen *screen = dpyinfo->screen;
1631 int i;
1633 dpyinfo->ncolor_cells
1634 = XDisplayCells (dpy, XScreenNumberOfScreen (screen));
1635 dpyinfo->color_cells
1636 = (XColor *) xmalloc (dpyinfo->ncolor_cells
1637 * sizeof *dpyinfo->color_cells);
1639 for (i = 0; i < dpyinfo->ncolor_cells; ++i)
1640 dpyinfo->color_cells[i].pixel = i;
1642 XQueryColors (dpy, dpyinfo->cmap,
1643 dpyinfo->color_cells, dpyinfo->ncolor_cells);
1646 *ncells = dpyinfo->ncolor_cells;
1647 return dpyinfo->color_cells;
1651 /* On frame F, translate pixel colors to RGB values for the NCOLORS
1652 colors in COLORS. Use cached information, if available. */
1654 void
1655 x_query_colors (struct frame *f, XColor *colors, int ncolors)
1657 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
1659 if (dpyinfo->color_cells)
1661 int i;
1662 for (i = 0; i < ncolors; ++i)
1664 unsigned long pixel = colors[i].pixel;
1665 xassert (pixel < dpyinfo->ncolor_cells);
1666 xassert (dpyinfo->color_cells[pixel].pixel == pixel);
1667 colors[i] = dpyinfo->color_cells[pixel];
1670 else
1671 XQueryColors (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), colors, ncolors);
1675 /* On frame F, translate pixel color to RGB values for the color in
1676 COLOR. Use cached information, if available. */
1678 void
1679 x_query_color (struct frame *f, XColor *color)
1681 x_query_colors (f, color, 1);
1685 /* Allocate the color COLOR->pixel on DISPLAY, colormap CMAP. If an
1686 exact match can't be allocated, try the nearest color available.
1687 Value is non-zero if successful. Set *COLOR to the color
1688 allocated. */
1690 static int
1691 x_alloc_nearest_color_1 (Display *dpy, Colormap cmap, XColor *color)
1693 int rc;
1695 rc = XAllocColor (dpy, cmap, color);
1696 if (rc == 0)
1698 /* If we got to this point, the colormap is full, so we're going
1699 to try to get the next closest color. The algorithm used is
1700 a least-squares matching, which is what X uses for closest
1701 color matching with StaticColor visuals. */
1702 int nearest, i;
1703 int max_color_delta = 255;
1704 int max_delta = 3 * max_color_delta;
1705 int nearest_delta = max_delta + 1;
1706 int ncells;
1707 const XColor *cells = x_color_cells (dpy, &ncells);
1709 for (nearest = i = 0; i < ncells; ++i)
1711 int dred = (color->red >> 8) - (cells[i].red >> 8);
1712 int dgreen = (color->green >> 8) - (cells[i].green >> 8);
1713 int dblue = (color->blue >> 8) - (cells[i].blue >> 8);
1714 int delta = dred * dred + dgreen * dgreen + dblue * dblue;
1716 if (delta < nearest_delta)
1718 nearest = i;
1719 nearest_delta = delta;
1723 color->red = cells[nearest].red;
1724 color->green = cells[nearest].green;
1725 color->blue = cells[nearest].blue;
1726 rc = XAllocColor (dpy, cmap, color);
1728 else
1730 /* If allocation succeeded, and the allocated pixel color is not
1731 equal to a cached pixel color recorded earlier, there was a
1732 change in the colormap, so clear the color cache. */
1733 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
1734 XColor *cached_color;
1736 if (dpyinfo->color_cells
1737 && (cached_color = &dpyinfo->color_cells[color->pixel],
1738 (cached_color->red != color->red
1739 || cached_color->blue != color->blue
1740 || cached_color->green != color->green)))
1742 xfree (dpyinfo->color_cells);
1743 dpyinfo->color_cells = NULL;
1744 dpyinfo->ncolor_cells = 0;
1748 #ifdef DEBUG_X_COLORS
1749 if (rc)
1750 register_color (color->pixel);
1751 #endif /* DEBUG_X_COLORS */
1753 return rc;
1757 /* Allocate the color COLOR->pixel on frame F, colormap CMAP. If an
1758 exact match can't be allocated, try the nearest color available.
1759 Value is non-zero if successful. Set *COLOR to the color
1760 allocated. */
1763 x_alloc_nearest_color (struct frame *f, Colormap cmap, XColor *color)
1765 gamma_correct (f, color);
1766 return x_alloc_nearest_color_1 (FRAME_X_DISPLAY (f), cmap, color);
1770 /* Allocate color PIXEL on frame F. PIXEL must already be allocated.
1771 It's necessary to do this instead of just using PIXEL directly to
1772 get color reference counts right. */
1774 unsigned long
1775 x_copy_color (struct frame *f, long unsigned int pixel)
1777 XColor color;
1779 color.pixel = pixel;
1780 BLOCK_INPUT;
1781 x_query_color (f, &color);
1782 XAllocColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &color);
1783 UNBLOCK_INPUT;
1784 #ifdef DEBUG_X_COLORS
1785 register_color (pixel);
1786 #endif
1787 return color.pixel;
1791 /* Brightness beyond which a color won't have its highlight brightness
1792 boosted.
1794 Nominally, highlight colors for `3d' faces are calculated by
1795 brightening an object's color by a constant scale factor, but this
1796 doesn't yield good results for dark colors, so for colors who's
1797 brightness is less than this value (on a scale of 0-65535) have an
1798 use an additional additive factor.
1800 The value here is set so that the default menu-bar/mode-line color
1801 (grey75) will not have its highlights changed at all. */
1802 #define HIGHLIGHT_COLOR_DARK_BOOST_LIMIT 48000
1805 /* Allocate a color which is lighter or darker than *PIXEL by FACTOR
1806 or DELTA. Try a color with RGB values multiplied by FACTOR first.
1807 If this produces the same color as PIXEL, try a color where all RGB
1808 values have DELTA added. Return the allocated color in *PIXEL.
1809 DISPLAY is the X display, CMAP is the colormap to operate on.
1810 Value is non-zero if successful. */
1812 static int
1813 x_alloc_lighter_color (struct frame *f, Display *display, Colormap cmap, long unsigned int *pixel, double factor, int delta)
1815 XColor color, new;
1816 long bright;
1817 int success_p;
1819 /* Get RGB color values. */
1820 color.pixel = *pixel;
1821 x_query_color (f, &color);
1823 /* Change RGB values by specified FACTOR. Avoid overflow! */
1824 xassert (factor >= 0);
1825 new.red = min (0xffff, factor * color.red);
1826 new.green = min (0xffff, factor * color.green);
1827 new.blue = min (0xffff, factor * color.blue);
1829 /* Calculate brightness of COLOR. */
1830 bright = (2 * color.red + 3 * color.green + color.blue) / 6;
1832 /* We only boost colors that are darker than
1833 HIGHLIGHT_COLOR_DARK_BOOST_LIMIT. */
1834 if (bright < HIGHLIGHT_COLOR_DARK_BOOST_LIMIT)
1835 /* Make an additive adjustment to NEW, because it's dark enough so
1836 that scaling by FACTOR alone isn't enough. */
1838 /* How far below the limit this color is (0 - 1, 1 being darker). */
1839 double dimness = 1 - (double)bright / HIGHLIGHT_COLOR_DARK_BOOST_LIMIT;
1840 /* The additive adjustment. */
1841 int min_delta = delta * dimness * factor / 2;
1843 if (factor < 1)
1845 new.red = max (0, new.red - min_delta);
1846 new.green = max (0, new.green - min_delta);
1847 new.blue = max (0, new.blue - min_delta);
1849 else
1851 new.red = min (0xffff, min_delta + new.red);
1852 new.green = min (0xffff, min_delta + new.green);
1853 new.blue = min (0xffff, min_delta + new.blue);
1857 /* Try to allocate the color. */
1858 success_p = x_alloc_nearest_color (f, cmap, &new);
1859 if (success_p)
1861 if (new.pixel == *pixel)
1863 /* If we end up with the same color as before, try adding
1864 delta to the RGB values. */
1865 x_free_colors (f, &new.pixel, 1);
1867 new.red = min (0xffff, delta + color.red);
1868 new.green = min (0xffff, delta + color.green);
1869 new.blue = min (0xffff, delta + color.blue);
1870 success_p = x_alloc_nearest_color (f, cmap, &new);
1872 else
1873 success_p = 1;
1874 *pixel = new.pixel;
1877 return success_p;
1881 /* Set up the foreground color for drawing relief lines of glyph
1882 string S. RELIEF is a pointer to a struct relief containing the GC
1883 with which lines will be drawn. Use a color that is FACTOR or
1884 DELTA lighter or darker than the relief's background which is found
1885 in S->f->output_data.x->relief_background. If such a color cannot
1886 be allocated, use DEFAULT_PIXEL, instead. */
1888 static void
1889 x_setup_relief_color (struct frame *f, struct relief *relief, double factor, int delta, long unsigned int default_pixel)
1891 XGCValues xgcv;
1892 struct x_output *di = f->output_data.x;
1893 unsigned long mask = GCForeground | GCLineWidth | GCGraphicsExposures;
1894 unsigned long pixel;
1895 unsigned long background = di->relief_background;
1896 Colormap cmap = FRAME_X_COLORMAP (f);
1897 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
1898 Display *dpy = FRAME_X_DISPLAY (f);
1900 xgcv.graphics_exposures = False;
1901 xgcv.line_width = 1;
1903 /* Free previously allocated color. The color cell will be reused
1904 when it has been freed as many times as it was allocated, so this
1905 doesn't affect faces using the same colors. */
1906 if (relief->gc
1907 && relief->allocated_p)
1909 x_free_colors (f, &relief->pixel, 1);
1910 relief->allocated_p = 0;
1913 /* Allocate new color. */
1914 xgcv.foreground = default_pixel;
1915 pixel = background;
1916 if (dpyinfo->n_planes != 1
1917 && x_alloc_lighter_color (f, dpy, cmap, &pixel, factor, delta))
1919 relief->allocated_p = 1;
1920 xgcv.foreground = relief->pixel = pixel;
1923 if (relief->gc == 0)
1925 xgcv.stipple = dpyinfo->gray;
1926 mask |= GCStipple;
1927 relief->gc = XCreateGC (dpy, FRAME_X_WINDOW (f), mask, &xgcv);
1929 else
1930 XChangeGC (dpy, relief->gc, mask, &xgcv);
1934 /* Set up colors for the relief lines around glyph string S. */
1936 static void
1937 x_setup_relief_colors (struct glyph_string *s)
1939 struct x_output *di = s->f->output_data.x;
1940 unsigned long color;
1942 if (s->face->use_box_color_for_shadows_p)
1943 color = s->face->box_color;
1944 else if (s->first_glyph->type == IMAGE_GLYPH
1945 && s->img->pixmap
1946 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
1947 color = IMAGE_BACKGROUND (s->img, s->f, 0);
1948 else
1950 XGCValues xgcv;
1952 /* Get the background color of the face. */
1953 XGetGCValues (s->display, s->gc, GCBackground, &xgcv);
1954 color = xgcv.background;
1957 if (di->white_relief.gc == 0
1958 || color != di->relief_background)
1960 di->relief_background = color;
1961 x_setup_relief_color (s->f, &di->white_relief, 1.2, 0x8000,
1962 WHITE_PIX_DEFAULT (s->f));
1963 x_setup_relief_color (s->f, &di->black_relief, 0.6, 0x4000,
1964 BLACK_PIX_DEFAULT (s->f));
1969 /* Draw a relief on frame F inside the rectangle given by LEFT_X,
1970 TOP_Y, RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the relief
1971 to draw, it must be >= 0. RAISED_P non-zero means draw a raised
1972 relief. LEFT_P non-zero means draw a relief on the left side of
1973 the rectangle. RIGHT_P non-zero means draw a relief on the right
1974 side of the rectangle. CLIP_RECT is the clipping rectangle to use
1975 when drawing. */
1977 static void
1978 x_draw_relief_rect (struct frame *f,
1979 int left_x, int top_y, int right_x, int bottom_y, int width,
1980 int raised_p, int top_p, int bot_p, int left_p, int right_p,
1981 XRectangle *clip_rect)
1983 Display *dpy = FRAME_X_DISPLAY (f);
1984 Window window = FRAME_X_WINDOW (f);
1985 int i;
1986 GC gc;
1988 if (raised_p)
1989 gc = f->output_data.x->white_relief.gc;
1990 else
1991 gc = f->output_data.x->black_relief.gc;
1992 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
1994 /* This code is more complicated than it has to be, because of two
1995 minor hacks to make the boxes look nicer: (i) if width > 1, draw
1996 the outermost line using the black relief. (ii) Omit the four
1997 corner pixels. */
1999 /* Top. */
2000 if (top_p)
2002 if (width == 1)
2003 XDrawLine (dpy, window, gc,
2004 left_x + (left_p ? 1 : 0), top_y,
2005 right_x + (right_p ? 0 : 1), top_y);
2007 for (i = 1; i < width; ++i)
2008 XDrawLine (dpy, window, gc,
2009 left_x + i * left_p, top_y + i,
2010 right_x + 1 - i * right_p, top_y + i);
2013 /* Left. */
2014 if (left_p)
2016 if (width == 1)
2017 XDrawLine (dpy, window, gc, left_x, top_y + 1, left_x, bottom_y);
2019 XClearArea (dpy, window, left_x, top_y, 1, 1, False);
2020 XClearArea (dpy, window, left_x, bottom_y, 1, 1, False);
2022 for (i = (width > 1 ? 1 : 0); i < width; ++i)
2023 XDrawLine (dpy, window, gc,
2024 left_x + i, top_y + i, left_x + i, bottom_y - i + 1);
2027 XSetClipMask (dpy, gc, None);
2028 if (raised_p)
2029 gc = f->output_data.x->black_relief.gc;
2030 else
2031 gc = f->output_data.x->white_relief.gc;
2032 XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
2034 if (width > 1)
2036 /* Outermost top line. */
2037 if (top_p)
2038 XDrawLine (dpy, window, gc,
2039 left_x + (left_p ? 1 : 0), top_y,
2040 right_x + (right_p ? 0 : 1), top_y);
2042 /* Outermost left line. */
2043 if (left_p)
2044 XDrawLine (dpy, window, gc, left_x, top_y + 1, left_x, bottom_y);
2047 /* Bottom. */
2048 if (bot_p)
2050 XDrawLine (dpy, window, gc,
2051 left_x + (left_p ? 1 : 0), bottom_y,
2052 right_x + (right_p ? 0 : 1), bottom_y);
2053 for (i = 1; i < width; ++i)
2054 XDrawLine (dpy, window, gc,
2055 left_x + i * left_p, bottom_y - i,
2056 right_x + 1 - i * right_p, bottom_y - i);
2059 /* Right. */
2060 if (right_p)
2062 XClearArea (dpy, window, right_x, top_y, 1, 1, False);
2063 XClearArea (dpy, window, right_x, bottom_y, 1, 1, False);
2064 for (i = 0; i < width; ++i)
2065 XDrawLine (dpy, window, gc,
2066 right_x - i, top_y + i + 1, right_x - i, bottom_y - i);
2069 XSetClipMask (dpy, gc, None);
2073 /* Draw a box on frame F inside the rectangle given by LEFT_X, TOP_Y,
2074 RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the lines to
2075 draw, it must be >= 0. LEFT_P non-zero means draw a line on the
2076 left side of the rectangle. RIGHT_P non-zero means draw a line
2077 on the right side of the rectangle. CLIP_RECT is the clipping
2078 rectangle to use when drawing. */
2080 static void
2081 x_draw_box_rect (struct glyph_string *s,
2082 int left_x, int top_y, int right_x, int bottom_y, int width,
2083 int left_p, int right_p, XRectangle *clip_rect)
2085 XGCValues xgcv;
2087 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2088 XSetForeground (s->display, s->gc, s->face->box_color);
2089 XSetClipRectangles (s->display, s->gc, 0, 0, clip_rect, 1, Unsorted);
2091 /* Top. */
2092 XFillRectangle (s->display, s->window, s->gc,
2093 left_x, top_y, right_x - left_x + 1, width);
2095 /* Left. */
2096 if (left_p)
2097 XFillRectangle (s->display, s->window, s->gc,
2098 left_x, top_y, width, bottom_y - top_y + 1);
2100 /* Bottom. */
2101 XFillRectangle (s->display, s->window, s->gc,
2102 left_x, bottom_y - width + 1, right_x - left_x + 1, width);
2104 /* Right. */
2105 if (right_p)
2106 XFillRectangle (s->display, s->window, s->gc,
2107 right_x - width + 1, top_y, width, bottom_y - top_y + 1);
2109 XSetForeground (s->display, s->gc, xgcv.foreground);
2110 XSetClipMask (s->display, s->gc, None);
2114 /* Draw a box around glyph string S. */
2116 static void
2117 x_draw_glyph_string_box (struct glyph_string *s)
2119 int width, left_x, right_x, top_y, bottom_y, last_x, raised_p;
2120 int left_p, right_p;
2121 struct glyph *last_glyph;
2122 XRectangle clip_rect;
2124 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2125 ? WINDOW_RIGHT_EDGE_X (s->w)
2126 : window_box_right (s->w, s->area));
2128 /* The glyph that may have a right box line. */
2129 last_glyph = (s->cmp || s->img
2130 ? s->first_glyph
2131 : s->first_glyph + s->nchars - 1);
2133 width = eabs (s->face->box_line_width);
2134 raised_p = s->face->box == FACE_RAISED_BOX;
2135 left_x = s->x;
2136 right_x = (s->row->full_width_p && s->extends_to_end_of_line_p
2137 ? last_x - 1
2138 : min (last_x, s->x + s->background_width) - 1);
2139 top_y = s->y;
2140 bottom_y = top_y + s->height - 1;
2142 left_p = (s->first_glyph->left_box_line_p
2143 || (s->hl == DRAW_MOUSE_FACE
2144 && (s->prev == NULL
2145 || s->prev->hl != s->hl)));
2146 right_p = (last_glyph->right_box_line_p
2147 || (s->hl == DRAW_MOUSE_FACE
2148 && (s->next == NULL
2149 || s->next->hl != s->hl)));
2151 get_glyph_string_clip_rect (s, &clip_rect);
2153 if (s->face->box == FACE_SIMPLE_BOX)
2154 x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
2155 left_p, right_p, &clip_rect);
2156 else
2158 x_setup_relief_colors (s);
2159 x_draw_relief_rect (s->f, left_x, top_y, right_x, bottom_y,
2160 width, raised_p, 1, 1, left_p, right_p, &clip_rect);
2165 /* Draw foreground of image glyph string S. */
2167 static void
2168 x_draw_image_foreground (struct glyph_string *s)
2170 int x = s->x;
2171 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2173 /* If first glyph of S has a left box line, start drawing it to the
2174 right of that line. */
2175 if (s->face->box != FACE_NO_BOX
2176 && s->first_glyph->left_box_line_p
2177 && s->slice.x == 0)
2178 x += eabs (s->face->box_line_width);
2180 /* If there is a margin around the image, adjust x- and y-position
2181 by that margin. */
2182 if (s->slice.x == 0)
2183 x += s->img->hmargin;
2184 if (s->slice.y == 0)
2185 y += s->img->vmargin;
2187 if (s->img->pixmap)
2189 if (s->img->mask)
2191 /* We can't set both a clip mask and use XSetClipRectangles
2192 because the latter also sets a clip mask. We also can't
2193 trust on the shape extension to be available
2194 (XShapeCombineRegion). So, compute the rectangle to draw
2195 manually. */
2196 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
2197 | GCFunction);
2198 XGCValues xgcv;
2199 XRectangle clip_rect, image_rect, r;
2201 xgcv.clip_mask = s->img->mask;
2202 xgcv.clip_x_origin = x;
2203 xgcv.clip_y_origin = y;
2204 xgcv.function = GXcopy;
2205 XChangeGC (s->display, s->gc, mask, &xgcv);
2207 get_glyph_string_clip_rect (s, &clip_rect);
2208 image_rect.x = x;
2209 image_rect.y = y;
2210 image_rect.width = s->slice.width;
2211 image_rect.height = s->slice.height;
2212 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
2213 XCopyArea (s->display, s->img->pixmap, s->window, s->gc,
2214 s->slice.x + r.x - x, s->slice.y + r.y - y,
2215 r.width, r.height, r.x, r.y);
2217 else
2219 XRectangle clip_rect, image_rect, r;
2221 get_glyph_string_clip_rect (s, &clip_rect);
2222 image_rect.x = x;
2223 image_rect.y = y;
2224 image_rect.width = s->slice.width;
2225 image_rect.height = s->slice.height;
2226 if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
2227 XCopyArea (s->display, s->img->pixmap, s->window, s->gc,
2228 s->slice.x + r.x - x, s->slice.y + r.y - y,
2229 r.width, r.height, r.x, r.y);
2231 /* When the image has a mask, we can expect that at
2232 least part of a mouse highlight or a block cursor will
2233 be visible. If the image doesn't have a mask, make
2234 a block cursor visible by drawing a rectangle around
2235 the image. I believe it's looking better if we do
2236 nothing here for mouse-face. */
2237 if (s->hl == DRAW_CURSOR)
2239 int relief = s->img->relief;
2240 if (relief < 0) relief = -relief;
2241 XDrawRectangle (s->display, s->window, s->gc,
2242 x - relief, y - relief,
2243 s->slice.width + relief*2 - 1,
2244 s->slice.height + relief*2 - 1);
2248 else
2249 /* Draw a rectangle if image could not be loaded. */
2250 XDrawRectangle (s->display, s->window, s->gc, x, y,
2251 s->slice.width - 1, s->slice.height - 1);
2255 /* Draw a relief around the image glyph string S. */
2257 static void
2258 x_draw_image_relief (struct glyph_string *s)
2260 int x0, y0, x1, y1, thick, raised_p, extra;
2261 XRectangle r;
2262 int x = s->x;
2263 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2265 /* If first glyph of S has a left box line, start drawing it to the
2266 right of that line. */
2267 if (s->face->box != FACE_NO_BOX
2268 && s->first_glyph->left_box_line_p
2269 && s->slice.x == 0)
2270 x += eabs (s->face->box_line_width);
2272 /* If there is a margin around the image, adjust x- and y-position
2273 by that margin. */
2274 if (s->slice.x == 0)
2275 x += s->img->hmargin;
2276 if (s->slice.y == 0)
2277 y += s->img->vmargin;
2279 if (s->hl == DRAW_IMAGE_SUNKEN
2280 || s->hl == DRAW_IMAGE_RAISED)
2282 thick = tool_bar_button_relief >= 0 ? tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
2283 raised_p = s->hl == DRAW_IMAGE_RAISED;
2285 else
2287 thick = eabs (s->img->relief);
2288 raised_p = s->img->relief > 0;
2291 extra = s->face->id == TOOL_BAR_FACE_ID
2292 ? XINT (Vtool_bar_button_margin) : 0;
2294 x0 = x - thick - extra;
2295 y0 = y - thick - extra;
2296 x1 = x + s->slice.width + thick - 1 + extra;
2297 y1 = y + s->slice.height + thick - 1 + extra;
2299 x_setup_relief_colors (s);
2300 get_glyph_string_clip_rect (s, &r);
2301 x_draw_relief_rect (s->f, x0, y0, x1, y1, thick, raised_p,
2302 s->slice.y == 0,
2303 s->slice.y + s->slice.height == s->img->height,
2304 s->slice.x == 0,
2305 s->slice.x + s->slice.width == s->img->width,
2306 &r);
2310 /* Draw the foreground of image glyph string S to PIXMAP. */
2312 static void
2313 x_draw_image_foreground_1 (struct glyph_string *s, Pixmap pixmap)
2315 int x = 0;
2316 int y = s->ybase - s->y - image_ascent (s->img, s->face, &s->slice);
2318 /* If first glyph of S has a left box line, start drawing it to the
2319 right of that line. */
2320 if (s->face->box != FACE_NO_BOX
2321 && s->first_glyph->left_box_line_p
2322 && s->slice.x == 0)
2323 x += eabs (s->face->box_line_width);
2325 /* If there is a margin around the image, adjust x- and y-position
2326 by that margin. */
2327 if (s->slice.x == 0)
2328 x += s->img->hmargin;
2329 if (s->slice.y == 0)
2330 y += s->img->vmargin;
2332 if (s->img->pixmap)
2334 if (s->img->mask)
2336 /* We can't set both a clip mask and use XSetClipRectangles
2337 because the latter also sets a clip mask. We also can't
2338 trust on the shape extension to be available
2339 (XShapeCombineRegion). So, compute the rectangle to draw
2340 manually. */
2341 unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
2342 | GCFunction);
2343 XGCValues xgcv;
2345 xgcv.clip_mask = s->img->mask;
2346 xgcv.clip_x_origin = x - s->slice.x;
2347 xgcv.clip_y_origin = y - s->slice.y;
2348 xgcv.function = GXcopy;
2349 XChangeGC (s->display, s->gc, mask, &xgcv);
2351 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
2352 s->slice.x, s->slice.y,
2353 s->slice.width, s->slice.height, x, y);
2354 XSetClipMask (s->display, s->gc, None);
2356 else
2358 XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
2359 s->slice.x, s->slice.y,
2360 s->slice.width, s->slice.height, x, y);
2362 /* When the image has a mask, we can expect that at
2363 least part of a mouse highlight or a block cursor will
2364 be visible. If the image doesn't have a mask, make
2365 a block cursor visible by drawing a rectangle around
2366 the image. I believe it's looking better if we do
2367 nothing here for mouse-face. */
2368 if (s->hl == DRAW_CURSOR)
2370 int r = s->img->relief;
2371 if (r < 0) r = -r;
2372 XDrawRectangle (s->display, s->window, s->gc, x - r, y - r,
2373 s->slice.width + r*2 - 1,
2374 s->slice.height + r*2 - 1);
2378 else
2379 /* Draw a rectangle if image could not be loaded. */
2380 XDrawRectangle (s->display, pixmap, s->gc, x, y,
2381 s->slice.width - 1, s->slice.height - 1);
2385 /* Draw part of the background of glyph string S. X, Y, W, and H
2386 give the rectangle to draw. */
2388 static void
2389 x_draw_glyph_string_bg_rect (struct glyph_string *s, int x, int y, int w, int h)
2391 if (s->stippled_p)
2393 /* Fill background with a stipple pattern. */
2394 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
2395 XFillRectangle (s->display, s->window, s->gc, x, y, w, h);
2396 XSetFillStyle (s->display, s->gc, FillSolid);
2398 else
2399 x_clear_glyph_string_rect (s, x, y, w, h);
2403 /* Draw image glyph string S.
2405 s->y
2406 s->x +-------------------------
2407 | s->face->box
2409 | +-------------------------
2410 | | s->img->margin
2412 | | +-------------------
2413 | | | the image
2417 static void
2418 x_draw_image_glyph_string (struct glyph_string *s)
2420 int box_line_hwidth = eabs (s->face->box_line_width);
2421 int box_line_vwidth = max (s->face->box_line_width, 0);
2422 int height;
2423 Pixmap pixmap = None;
2425 height = s->height;
2426 if (s->slice.y == 0)
2427 height -= box_line_vwidth;
2428 if (s->slice.y + s->slice.height >= s->img->height)
2429 height -= box_line_vwidth;
2431 /* Fill background with face under the image. Do it only if row is
2432 taller than image or if image has a clip mask to reduce
2433 flickering. */
2434 s->stippled_p = s->face->stipple != 0;
2435 if (height > s->slice.height
2436 || s->img->hmargin
2437 || s->img->vmargin
2438 || s->img->mask
2439 || s->img->pixmap == 0
2440 || s->width != s->background_width)
2442 if (s->img->mask)
2444 /* Create a pixmap as large as the glyph string. Fill it
2445 with the background color. Copy the image to it, using
2446 its mask. Copy the temporary pixmap to the display. */
2447 Screen *screen = FRAME_X_SCREEN (s->f);
2448 int depth = DefaultDepthOfScreen (screen);
2450 /* Create a pixmap as large as the glyph string. */
2451 pixmap = XCreatePixmap (s->display, s->window,
2452 s->background_width,
2453 s->height, depth);
2455 /* Don't clip in the following because we're working on the
2456 pixmap. */
2457 XSetClipMask (s->display, s->gc, None);
2459 /* Fill the pixmap with the background color/stipple. */
2460 if (s->stippled_p)
2462 /* Fill background with a stipple pattern. */
2463 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
2464 XSetTSOrigin (s->display, s->gc, - s->x, - s->y);
2465 XFillRectangle (s->display, pixmap, s->gc,
2466 0, 0, s->background_width, s->height);
2467 XSetFillStyle (s->display, s->gc, FillSolid);
2468 XSetTSOrigin (s->display, s->gc, 0, 0);
2470 else
2472 XGCValues xgcv;
2473 XGetGCValues (s->display, s->gc, GCForeground | GCBackground,
2474 &xgcv);
2475 XSetForeground (s->display, s->gc, xgcv.background);
2476 XFillRectangle (s->display, pixmap, s->gc,
2477 0, 0, s->background_width, s->height);
2478 XSetForeground (s->display, s->gc, xgcv.foreground);
2481 else
2483 int x = s->x;
2484 int y = s->y;
2486 if (s->first_glyph->left_box_line_p
2487 && s->slice.x == 0)
2488 x += box_line_hwidth;
2490 if (s->slice.y == 0)
2491 y += box_line_vwidth;
2493 x_draw_glyph_string_bg_rect (s, x, y, s->background_width, height);
2496 s->background_filled_p = 1;
2499 /* Draw the foreground. */
2500 if (pixmap != None)
2502 x_draw_image_foreground_1 (s, pixmap);
2503 x_set_glyph_string_clipping (s);
2504 XCopyArea (s->display, pixmap, s->window, s->gc,
2505 0, 0, s->background_width, s->height, s->x, s->y);
2506 XFreePixmap (s->display, pixmap);
2508 else
2509 x_draw_image_foreground (s);
2511 /* If we must draw a relief around the image, do it. */
2512 if (s->img->relief
2513 || s->hl == DRAW_IMAGE_RAISED
2514 || s->hl == DRAW_IMAGE_SUNKEN)
2515 x_draw_image_relief (s);
2519 /* Draw stretch glyph string S. */
2521 static void
2522 x_draw_stretch_glyph_string (struct glyph_string *s)
2524 xassert (s->first_glyph->type == STRETCH_GLYPH);
2526 if (s->hl == DRAW_CURSOR
2527 && !x_stretch_cursor_p)
2529 /* If `x-stretch-cursor' is nil, don't draw a block cursor as
2530 wide as the stretch glyph. */
2531 int width, background_width = s->background_width;
2532 int x = s->x;
2534 if (!s->row->reversed_p)
2536 int left_x = window_box_left_offset (s->w, TEXT_AREA);
2538 if (x < left_x)
2540 background_width -= left_x - x;
2541 x = left_x;
2544 else
2546 /* In R2L rows, draw the cursor on the right edge of the
2547 stretch glyph. */
2548 int right_x = window_box_right_offset (s->w, TEXT_AREA);
2550 if (x + background_width > right_x)
2551 background_width -= x - right_x;
2552 x += background_width;
2554 width = min (FRAME_COLUMN_WIDTH (s->f), background_width);
2555 if (s->row->reversed_p)
2556 x -= width;
2558 /* Draw cursor. */
2559 x_draw_glyph_string_bg_rect (s, x, s->y, width, s->height);
2561 /* Clear rest using the GC of the original non-cursor face. */
2562 if (width < background_width)
2564 int y = s->y;
2565 int w = background_width - width, h = s->height;
2566 XRectangle r;
2567 GC gc;
2569 if (!s->row->reversed_p)
2570 x += width;
2571 else
2572 x = s->x;
2573 if (s->row->mouse_face_p
2574 && cursor_in_mouse_face_p (s->w))
2576 x_set_mouse_face_gc (s);
2577 gc = s->gc;
2579 else
2580 gc = s->face->gc;
2582 get_glyph_string_clip_rect (s, &r);
2583 XSetClipRectangles (s->display, gc, 0, 0, &r, 1, Unsorted);
2585 if (s->face->stipple)
2587 /* Fill background with a stipple pattern. */
2588 XSetFillStyle (s->display, gc, FillOpaqueStippled);
2589 XFillRectangle (s->display, s->window, gc, x, y, w, h);
2590 XSetFillStyle (s->display, gc, FillSolid);
2592 else
2594 XGCValues xgcv;
2595 XGetGCValues (s->display, gc, GCForeground | GCBackground, &xgcv);
2596 XSetForeground (s->display, gc, xgcv.background);
2597 XFillRectangle (s->display, s->window, gc, x, y, w, h);
2598 XSetForeground (s->display, gc, xgcv.foreground);
2602 else if (!s->background_filled_p)
2604 int background_width = s->background_width;
2605 int x = s->x, left_x = window_box_left_offset (s->w, TEXT_AREA);
2607 /* Don't draw into left margin, fringe or scrollbar area
2608 except for header line and mode line. */
2609 if (x < left_x && !s->row->mode_line_p)
2611 background_width -= left_x - x;
2612 x = left_x;
2614 if (background_width > 0)
2615 x_draw_glyph_string_bg_rect (s, x, s->y, background_width, s->height);
2618 s->background_filled_p = 1;
2622 /* Draw glyph string S. */
2624 static void
2625 x_draw_glyph_string (struct glyph_string *s)
2627 int relief_drawn_p = 0;
2629 /* If S draws into the background of its successors, draw the
2630 background of the successors first so that S can draw into it.
2631 This makes S->next use XDrawString instead of XDrawImageString. */
2632 if (s->next && s->right_overhang && !s->for_overlaps)
2634 int width;
2635 struct glyph_string *next;
2637 for (width = 0, next = s->next;
2638 next && width < s->right_overhang;
2639 width += next->width, next = next->next)
2640 if (next->first_glyph->type != IMAGE_GLYPH)
2642 x_set_glyph_string_gc (next);
2643 x_set_glyph_string_clipping (next);
2644 if (next->first_glyph->type == STRETCH_GLYPH)
2645 x_draw_stretch_glyph_string (next);
2646 else
2647 x_draw_glyph_string_background (next, 1);
2648 next->num_clips = 0;
2652 /* Set up S->gc, set clipping and draw S. */
2653 x_set_glyph_string_gc (s);
2655 /* Draw relief (if any) in advance for char/composition so that the
2656 glyph string can be drawn over it. */
2657 if (!s->for_overlaps
2658 && s->face->box != FACE_NO_BOX
2659 && (s->first_glyph->type == CHAR_GLYPH
2660 || s->first_glyph->type == COMPOSITE_GLYPH))
2663 x_set_glyph_string_clipping (s);
2664 x_draw_glyph_string_background (s, 1);
2665 x_draw_glyph_string_box (s);
2666 x_set_glyph_string_clipping (s);
2667 relief_drawn_p = 1;
2669 else if (!s->clip_head /* draw_glyphs didn't specify a clip mask. */
2670 && !s->clip_tail
2671 && ((s->prev && s->prev->hl != s->hl && s->left_overhang)
2672 || (s->next && s->next->hl != s->hl && s->right_overhang)))
2673 /* We must clip just this glyph. left_overhang part has already
2674 drawn when s->prev was drawn, and right_overhang part will be
2675 drawn later when s->next is drawn. */
2676 x_set_glyph_string_clipping_exactly (s, s);
2677 else
2678 x_set_glyph_string_clipping (s);
2680 switch (s->first_glyph->type)
2682 case IMAGE_GLYPH:
2683 x_draw_image_glyph_string (s);
2684 break;
2685 #ifdef HAVE_XWIDGETS
2686 case XWIDGET_GLYPH:
2687 //erase xwidget background
2688 x_draw_glyph_string_background (s, 0);
2689 x_draw_xwidget_glyph_string (s);
2690 break;
2691 #endif
2692 case STRETCH_GLYPH:
2693 x_draw_stretch_glyph_string (s);
2694 break;
2696 case CHAR_GLYPH:
2697 if (s->for_overlaps)
2698 s->background_filled_p = 1;
2699 else
2700 x_draw_glyph_string_background (s, 0);
2701 x_draw_glyph_string_foreground (s);
2702 break;
2704 case COMPOSITE_GLYPH:
2705 if (s->for_overlaps || (s->cmp_from > 0
2706 && ! s->first_glyph->u.cmp.automatic))
2707 s->background_filled_p = 1;
2708 else
2709 x_draw_glyph_string_background (s, 1);
2710 x_draw_composite_glyph_string_foreground (s);
2711 break;
2713 case GLYPHLESS_GLYPH:
2714 if (s->for_overlaps)
2715 s->background_filled_p = 1;
2716 else
2717 x_draw_glyph_string_background (s, 1);
2718 x_draw_glyphless_glyph_string_foreground (s);
2719 break;
2721 default:
2722 abort ();
2725 if (!s->for_overlaps)
2727 /* Draw underline. */
2728 if (s->face->underline_p)
2730 unsigned long thickness, position;
2731 int y;
2733 if (s->prev && s->prev->face->underline_p)
2735 /* We use the same underline style as the previous one. */
2736 thickness = s->prev->underline_thickness;
2737 position = s->prev->underline_position;
2739 else
2741 /* Get the underline thickness. Default is 1 pixel. */
2742 if (s->font && s->font->underline_thickness > 0)
2743 thickness = s->font->underline_thickness;
2744 else
2745 thickness = 1;
2746 if (x_underline_at_descent_line)
2747 position = (s->height - thickness) - (s->ybase - s->y);
2748 else
2750 /* Get the underline position. This is the recommended
2751 vertical offset in pixels from the baseline to the top of
2752 the underline. This is a signed value according to the
2753 specs, and its default is
2755 ROUND ((maximum descent) / 2), with
2756 ROUND(x) = floor (x + 0.5) */
2758 if (x_use_underline_position_properties
2759 && s->font && s->font->underline_position >= 0)
2760 position = s->font->underline_position;
2761 else if (s->font)
2762 position = (s->font->descent + 1) / 2;
2763 else
2764 position = underline_minimum_offset;
2766 position = max (position, underline_minimum_offset);
2768 /* Check the sanity of thickness and position. We should
2769 avoid drawing underline out of the current line area. */
2770 if (s->y + s->height <= s->ybase + position)
2771 position = (s->height - 1) - (s->ybase - s->y);
2772 if (s->y + s->height < s->ybase + position + thickness)
2773 thickness = (s->y + s->height) - (s->ybase + position);
2774 s->underline_thickness = thickness;
2775 s->underline_position = position;
2776 y = s->ybase + position;
2777 if (s->face->underline_defaulted_p)
2778 XFillRectangle (s->display, s->window, s->gc,
2779 s->x, y, s->width, thickness);
2780 else
2782 XGCValues xgcv;
2783 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2784 XSetForeground (s->display, s->gc, s->face->underline_color);
2785 XFillRectangle (s->display, s->window, s->gc,
2786 s->x, y, s->width, thickness);
2787 XSetForeground (s->display, s->gc, xgcv.foreground);
2791 /* Draw overline. */
2792 if (s->face->overline_p)
2794 unsigned long dy = 0, h = 1;
2796 if (s->face->overline_color_defaulted_p)
2797 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2798 s->width, h);
2799 else
2801 XGCValues xgcv;
2802 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2803 XSetForeground (s->display, s->gc, s->face->overline_color);
2804 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2805 s->width, h);
2806 XSetForeground (s->display, s->gc, xgcv.foreground);
2810 /* Draw strike-through. */
2811 if (s->face->strike_through_p)
2813 unsigned long h = 1;
2814 unsigned long dy = (s->height - h) / 2;
2816 if (s->face->strike_through_color_defaulted_p)
2817 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2818 s->width, h);
2819 else
2821 XGCValues xgcv;
2822 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2823 XSetForeground (s->display, s->gc, s->face->strike_through_color);
2824 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2825 s->width, h);
2826 XSetForeground (s->display, s->gc, xgcv.foreground);
2830 /* Draw relief if not yet drawn. */
2831 if (!relief_drawn_p && s->face->box != FACE_NO_BOX)
2832 x_draw_glyph_string_box (s);
2834 if (s->prev)
2836 struct glyph_string *prev;
2838 for (prev = s->prev; prev; prev = prev->prev)
2839 if (prev->hl != s->hl
2840 && prev->x + prev->width + prev->right_overhang > s->x)
2842 /* As prev was drawn while clipped to its own area, we
2843 must draw the right_overhang part using s->hl now. */
2844 enum draw_glyphs_face save = prev->hl;
2846 prev->hl = s->hl;
2847 x_set_glyph_string_gc (prev);
2848 x_set_glyph_string_clipping_exactly (s, prev);
2849 if (prev->first_glyph->type == CHAR_GLYPH)
2850 x_draw_glyph_string_foreground (prev);
2851 else
2852 x_draw_composite_glyph_string_foreground (prev);
2853 XSetClipMask (prev->display, prev->gc, None);
2854 prev->hl = save;
2855 prev->num_clips = 0;
2859 if (s->next)
2861 struct glyph_string *next;
2863 for (next = s->next; next; next = next->next)
2864 if (next->hl != s->hl
2865 && next->x - next->left_overhang < s->x + s->width)
2867 /* As next will be drawn while clipped to its own area,
2868 we must draw the left_overhang part using s->hl now. */
2869 enum draw_glyphs_face save = next->hl;
2871 next->hl = s->hl;
2872 x_set_glyph_string_gc (next);
2873 x_set_glyph_string_clipping_exactly (s, next);
2874 if (next->first_glyph->type == CHAR_GLYPH)
2875 x_draw_glyph_string_foreground (next);
2876 else
2877 x_draw_composite_glyph_string_foreground (next);
2878 XSetClipMask (next->display, next->gc, None);
2879 next->hl = save;
2880 next->num_clips = 0;
2885 /* Reset clipping. */
2886 XSetClipMask (s->display, s->gc, None);
2887 s->num_clips = 0;
2890 /* Shift display to make room for inserted glyphs. */
2892 static void
2893 x_shift_glyphs_for_insert (struct frame *f, int x, int y, int width, int height, int shift_by)
2895 XCopyArea (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), FRAME_X_WINDOW (f),
2896 f->output_data.x->normal_gc,
2897 x, y, width, height,
2898 x + shift_by, y);
2901 /* Delete N glyphs at the nominal cursor position. Not implemented
2902 for X frames. */
2904 static void
2905 x_delete_glyphs (struct frame *f, register int n)
2907 abort ();
2911 /* Like XClearArea, but check that WIDTH and HEIGHT are reasonable.
2912 If they are <= 0, this is probably an error. */
2914 void
2915 x_clear_area (Display *dpy, Window window, int x, int y, int width, int height, int exposures)
2917 xassert (width > 0 && height > 0);
2918 XClearArea (dpy, window, x, y, width, height, exposures);
2922 /* Clear an entire frame. */
2924 static void
2925 x_clear_frame (struct frame *f)
2927 /* Clearing the frame will erase any cursor, so mark them all as no
2928 longer visible. */
2929 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2930 output_cursor.hpos = output_cursor.vpos = 0;
2931 output_cursor.x = -1;
2933 /* We don't set the output cursor here because there will always
2934 follow an explicit cursor_to. */
2935 BLOCK_INPUT;
2937 /* The following call is commented out because it does not seem to accomplish
2938 anything, apart from causing flickering during window resize. */
2939 /* XClearWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f)); */
2941 /* We have to clear the scroll bars. If we have changed colors or
2942 something like that, then they should be notified. */
2943 x_scroll_bar_clear (f);
2945 #if defined (USE_GTK) && defined (USE_TOOLKIT_SCROLL_BARS)
2946 /* Make sure scroll bars are redrawn. As they aren't redrawn by
2947 redisplay, do it here. */
2948 if (FRAME_GTK_WIDGET (f))
2949 gtk_widget_queue_draw (FRAME_GTK_WIDGET (f));
2950 #endif
2952 XFlush (FRAME_X_DISPLAY (f));
2954 UNBLOCK_INPUT;
2959 /* Invert the middle quarter of the frame for .15 sec. */
2961 /* We use the select system call to do the waiting, so we have to make
2962 sure it's available. If it isn't, we just won't do visual bells. */
2964 #if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
2967 /* Subtract the `struct timeval' values X and Y, storing the result in
2968 *RESULT. Return 1 if the difference is negative, otherwise 0. */
2970 static int
2971 timeval_subtract (struct timeval *result, struct timeval x, struct timeval y)
2973 /* Perform the carry for the later subtraction by updating y. This
2974 is safer because on some systems the tv_sec member is unsigned. */
2975 if (x.tv_usec < y.tv_usec)
2977 int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
2978 y.tv_usec -= 1000000 * nsec;
2979 y.tv_sec += nsec;
2982 if (x.tv_usec - y.tv_usec > 1000000)
2984 int nsec = (y.tv_usec - x.tv_usec) / 1000000;
2985 y.tv_usec += 1000000 * nsec;
2986 y.tv_sec -= nsec;
2989 /* Compute the time remaining to wait. tv_usec is certainly
2990 positive. */
2991 result->tv_sec = x.tv_sec - y.tv_sec;
2992 result->tv_usec = x.tv_usec - y.tv_usec;
2994 /* Return indication of whether the result should be considered
2995 negative. */
2996 return x.tv_sec < y.tv_sec;
2999 static void
3000 XTflash (struct frame *f)
3002 BLOCK_INPUT;
3005 #ifdef USE_GTK
3006 /* Use Gdk routines to draw. This way, we won't draw over scroll bars
3007 when the scroll bars and the edit widget share the same X window. */
3008 GdkWindow *window = gtk_widget_get_window (FRAME_GTK_WIDGET (f));
3009 #ifdef HAVE_GTK3
3010 cairo_t *cr = gdk_cairo_create (window);
3011 cairo_set_source_rgb (cr, 1, 1, 1);
3012 cairo_set_operator (cr, CAIRO_OPERATOR_DIFFERENCE);
3013 #define XFillRectangle(d, win, gc, x, y, w, h) \
3014 do { \
3015 cairo_rectangle (cr, x, y, w, h); \
3016 cairo_fill (cr); \
3018 while (0)
3019 #else /* ! HAVE_GTK3 */
3020 GdkGCValues vals;
3021 GdkGC *gc;
3022 vals.foreground.pixel = (FRAME_FOREGROUND_PIXEL (f)
3023 ^ FRAME_BACKGROUND_PIXEL (f));
3024 vals.function = GDK_XOR;
3025 gc = gdk_gc_new_with_values (window,
3026 &vals, GDK_GC_FUNCTION | GDK_GC_FOREGROUND);
3027 #define XFillRectangle(d, win, gc, x, y, w, h) \
3028 gdk_draw_rectangle (window, gc, TRUE, x, y, w, h)
3029 #endif /* ! HAVE_GTK3 */
3030 #else /* ! USE_GTK */
3031 GC gc;
3033 /* Create a GC that will use the GXxor function to flip foreground
3034 pixels into background pixels. */
3036 XGCValues values;
3038 values.function = GXxor;
3039 values.foreground = (FRAME_FOREGROUND_PIXEL (f)
3040 ^ FRAME_BACKGROUND_PIXEL (f));
3042 gc = XCreateGC (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3043 GCFunction | GCForeground, &values);
3045 #endif
3047 /* Get the height not including a menu bar widget. */
3048 int height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, FRAME_LINES (f));
3049 /* Height of each line to flash. */
3050 int flash_height = FRAME_LINE_HEIGHT (f);
3051 /* These will be the left and right margins of the rectangles. */
3052 int flash_left = FRAME_INTERNAL_BORDER_WIDTH (f);
3053 int flash_right = FRAME_PIXEL_WIDTH (f) - FRAME_INTERNAL_BORDER_WIDTH (f);
3055 int width;
3057 /* Don't flash the area between a scroll bar and the frame
3058 edge it is next to. */
3059 switch (FRAME_VERTICAL_SCROLL_BAR_TYPE (f))
3061 case vertical_scroll_bar_left:
3062 flash_left += VERTICAL_SCROLL_BAR_WIDTH_TRIM;
3063 break;
3065 case vertical_scroll_bar_right:
3066 flash_right -= VERTICAL_SCROLL_BAR_WIDTH_TRIM;
3067 break;
3069 default:
3070 break;
3073 width = flash_right - flash_left;
3075 /* If window is tall, flash top and bottom line. */
3076 if (height > 3 * FRAME_LINE_HEIGHT (f))
3078 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3079 flash_left,
3080 (FRAME_INTERNAL_BORDER_WIDTH (f)
3081 + FRAME_TOP_MARGIN_HEIGHT (f)),
3082 width, flash_height);
3083 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3084 flash_left,
3085 (height - flash_height
3086 - FRAME_INTERNAL_BORDER_WIDTH (f)),
3087 width, flash_height);
3090 else
3091 /* If it is short, flash it all. */
3092 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3093 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
3094 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
3096 x_flush (f);
3099 struct timeval wakeup;
3101 EMACS_GET_TIME (wakeup);
3103 /* Compute time to wait until, propagating carry from usecs. */
3104 wakeup.tv_usec += 150000;
3105 wakeup.tv_sec += (wakeup.tv_usec / 1000000);
3106 wakeup.tv_usec %= 1000000;
3108 /* Keep waiting until past the time wakeup or any input gets
3109 available. */
3110 while (! detect_input_pending ())
3112 struct timeval current;
3113 struct timeval timeout;
3115 EMACS_GET_TIME (current);
3117 /* Break if result would be negative. */
3118 if (timeval_subtract (&current, wakeup, current))
3119 break;
3121 /* How long `select' should wait. */
3122 timeout.tv_sec = 0;
3123 timeout.tv_usec = 10000;
3125 /* Try to wait that long--but we might wake up sooner. */
3126 select (0, NULL, NULL, NULL, &timeout);
3130 /* If window is tall, flash top and bottom line. */
3131 if (height > 3 * FRAME_LINE_HEIGHT (f))
3133 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3134 flash_left,
3135 (FRAME_INTERNAL_BORDER_WIDTH (f)
3136 + FRAME_TOP_MARGIN_HEIGHT (f)),
3137 width, flash_height);
3138 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3139 flash_left,
3140 (height - flash_height
3141 - FRAME_INTERNAL_BORDER_WIDTH (f)),
3142 width, flash_height);
3144 else
3145 /* If it is short, flash it all. */
3146 XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3147 flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
3148 width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
3150 #ifdef USE_GTK
3151 #ifdef HAVE_GTK3
3152 cairo_destroy (cr);
3153 #else
3154 g_object_unref (G_OBJECT (gc));
3155 #endif
3156 #undef XFillRectangle
3157 #else
3158 XFreeGC (FRAME_X_DISPLAY (f), gc);
3159 #endif
3160 x_flush (f);
3164 UNBLOCK_INPUT;
3167 #endif /* defined (HAVE_TIMEVAL) && defined (HAVE_SELECT) */
3170 static void
3171 XTtoggle_invisible_pointer (FRAME_PTR f, int invisible)
3173 BLOCK_INPUT;
3174 if (invisible)
3176 if (FRAME_X_DISPLAY_INFO (f)->invisible_cursor != 0)
3177 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3178 FRAME_X_DISPLAY_INFO (f)->invisible_cursor);
3180 else
3181 XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3182 f->output_data.x->current_cursor);
3183 f->pointer_invisible = invisible;
3184 UNBLOCK_INPUT;
3188 /* Make audible bell. */
3190 static void
3191 XTring_bell (struct frame *f)
3193 if (FRAME_X_DISPLAY (f))
3195 #if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
3196 if (visible_bell)
3197 XTflash (f);
3198 else
3199 #endif
3201 BLOCK_INPUT;
3202 XBell (FRAME_X_DISPLAY (f), 0);
3203 XFlush (FRAME_X_DISPLAY (f));
3204 UNBLOCK_INPUT;
3210 /* Specify how many text lines, from the top of the window,
3211 should be affected by insert-lines and delete-lines operations.
3212 This, and those operations, are used only within an update
3213 that is bounded by calls to x_update_begin and x_update_end. */
3215 static void
3216 XTset_terminal_window (struct frame *f, int n)
3218 /* This function intentionally left blank. */
3223 /***********************************************************************
3224 Line Dance
3225 ***********************************************************************/
3227 /* Perform an insert-lines or delete-lines operation, inserting N
3228 lines or deleting -N lines at vertical position VPOS. */
3230 static void
3231 x_ins_del_lines (struct frame *f, int vpos, int n)
3233 abort ();
3237 /* Scroll part of the display as described by RUN. */
3239 static void
3240 x_scroll_run (struct window *w, struct run *run)
3242 struct frame *f = XFRAME (w->frame);
3243 int x, y, width, height, from_y, to_y, bottom_y;
3245 /* Get frame-relative bounding box of the text display area of W,
3246 without mode lines. Include in this box the left and right
3247 fringe of W. */
3248 window_box (w, -1, &x, &y, &width, &height);
3250 #ifdef USE_TOOLKIT_SCROLL_BARS
3251 /* If the fringe is adjacent to the left (right) scroll bar of a
3252 leftmost (rightmost, respectively) window, then extend its
3253 background to the gap between the fringe and the bar. */
3254 if ((WINDOW_LEFTMOST_P (w)
3255 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
3256 || (WINDOW_RIGHTMOST_P (w)
3257 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w)))
3259 int sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
3261 if (sb_width > 0)
3263 int bar_area_x = WINDOW_SCROLL_BAR_AREA_X (w);
3264 int bar_area_width = (WINDOW_CONFIG_SCROLL_BAR_COLS (w)
3265 * FRAME_COLUMN_WIDTH (f));
3267 if (bar_area_x + bar_area_width == x)
3269 x = bar_area_x + sb_width;
3270 width += bar_area_width - sb_width;
3272 else if (x + width == bar_area_x)
3273 width += bar_area_width - sb_width;
3276 #endif
3278 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
3279 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
3280 bottom_y = y + height;
3282 if (to_y < from_y)
3284 /* Scrolling up. Make sure we don't copy part of the mode
3285 line at the bottom. */
3286 if (from_y + run->height > bottom_y)
3287 height = bottom_y - from_y;
3288 else
3289 height = run->height;
3291 else
3293 /* Scolling down. Make sure we don't copy over the mode line.
3294 at the bottom. */
3295 if (to_y + run->height > bottom_y)
3296 height = bottom_y - to_y;
3297 else
3298 height = run->height;
3301 BLOCK_INPUT;
3303 /* Cursor off. Will be switched on again in x_update_window_end. */
3304 updated_window = w;
3305 x_clear_cursor (w);
3307 XCopyArea (FRAME_X_DISPLAY (f),
3308 FRAME_X_WINDOW (f), FRAME_X_WINDOW (f),
3309 f->output_data.x->normal_gc,
3310 x, from_y,
3311 width, height,
3312 x, to_y);
3314 UNBLOCK_INPUT;
3319 /***********************************************************************
3320 Exposure Events
3321 ***********************************************************************/
3324 static void
3325 frame_highlight (struct frame *f)
3327 /* We used to only do this if Vx_no_window_manager was non-nil, but
3328 the ICCCM (section 4.1.6) says that the window's border pixmap
3329 and border pixel are window attributes which are "private to the
3330 client", so we can always change it to whatever we want. */
3331 BLOCK_INPUT;
3332 XSetWindowBorder (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3333 f->output_data.x->border_pixel);
3334 UNBLOCK_INPUT;
3335 x_update_cursor (f, 1);
3336 x_set_frame_alpha (f);
3339 static void
3340 frame_unhighlight (struct frame *f)
3342 /* We used to only do this if Vx_no_window_manager was non-nil, but
3343 the ICCCM (section 4.1.6) says that the window's border pixmap
3344 and border pixel are window attributes which are "private to the
3345 client", so we can always change it to whatever we want. */
3346 BLOCK_INPUT;
3347 XSetWindowBorderPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3348 f->output_data.x->border_tile);
3349 UNBLOCK_INPUT;
3350 x_update_cursor (f, 1);
3351 x_set_frame_alpha (f);
3354 /* The focus has changed. Update the frames as necessary to reflect
3355 the new situation. Note that we can't change the selected frame
3356 here, because the Lisp code we are interrupting might become confused.
3357 Each event gets marked with the frame in which it occurred, so the
3358 Lisp code can tell when the switch took place by examining the events. */
3360 static void
3361 x_new_focus_frame (struct x_display_info *dpyinfo, struct frame *frame)
3363 struct frame *old_focus = dpyinfo->x_focus_frame;
3365 if (frame != dpyinfo->x_focus_frame)
3367 /* Set this before calling other routines, so that they see
3368 the correct value of x_focus_frame. */
3369 dpyinfo->x_focus_frame = frame;
3371 if (old_focus && old_focus->auto_lower)
3372 x_lower_frame (old_focus);
3374 if (dpyinfo->x_focus_frame && dpyinfo->x_focus_frame->auto_raise)
3375 pending_autoraise_frame = dpyinfo->x_focus_frame;
3376 else
3377 pending_autoraise_frame = 0;
3380 x_frame_rehighlight (dpyinfo);
3383 /* Handle FocusIn and FocusOut state changes for FRAME.
3384 If FRAME has focus and there exists more than one frame, puts
3385 a FOCUS_IN_EVENT into *BUFP. */
3387 static void
3388 x_focus_changed (int type, int state, struct x_display_info *dpyinfo, struct frame *frame, struct input_event *bufp)
3390 if (type == FocusIn)
3392 if (dpyinfo->x_focus_event_frame != frame)
3394 x_new_focus_frame (dpyinfo, frame);
3395 dpyinfo->x_focus_event_frame = frame;
3397 /* Don't stop displaying the initial startup message
3398 for a switch-frame event we don't need. */
3399 if (NILP (Vterminal_frame)
3400 && CONSP (Vframe_list)
3401 && !NILP (XCDR (Vframe_list)))
3403 bufp->kind = FOCUS_IN_EVENT;
3404 XSETFRAME (bufp->frame_or_window, frame);
3408 frame->output_data.x->focus_state |= state;
3410 #ifdef HAVE_X_I18N
3411 if (FRAME_XIC (frame))
3412 XSetICFocus (FRAME_XIC (frame));
3413 #endif
3415 else if (type == FocusOut)
3417 frame->output_data.x->focus_state &= ~state;
3419 if (dpyinfo->x_focus_event_frame == frame)
3421 dpyinfo->x_focus_event_frame = 0;
3422 x_new_focus_frame (dpyinfo, 0);
3425 #ifdef HAVE_X_I18N
3426 if (FRAME_XIC (frame))
3427 XUnsetICFocus (FRAME_XIC (frame));
3428 #endif
3429 if (frame->pointer_invisible)
3430 XTtoggle_invisible_pointer (frame, 0);
3434 /* The focus may have changed. Figure out if it is a real focus change,
3435 by checking both FocusIn/Out and Enter/LeaveNotify events.
3437 Returns FOCUS_IN_EVENT event in *BUFP. */
3439 static void
3440 x_detect_focus_change (struct x_display_info *dpyinfo, XEvent *event, struct input_event *bufp)
3442 struct frame *frame;
3444 frame = x_any_window_to_frame (dpyinfo, event->xany.window);
3445 if (! frame)
3446 return;
3448 switch (event->type)
3450 case EnterNotify:
3451 case LeaveNotify:
3453 struct frame *focus_frame = dpyinfo->x_focus_event_frame;
3454 int focus_state
3455 = focus_frame ? focus_frame->output_data.x->focus_state : 0;
3457 if (event->xcrossing.detail != NotifyInferior
3458 && event->xcrossing.focus
3459 && ! (focus_state & FOCUS_EXPLICIT))
3460 x_focus_changed ((event->type == EnterNotify ? FocusIn : FocusOut),
3461 FOCUS_IMPLICIT,
3462 dpyinfo, frame, bufp);
3464 break;
3466 case FocusIn:
3467 case FocusOut:
3468 x_focus_changed (event->type,
3469 (event->xfocus.detail == NotifyPointer ?
3470 FOCUS_IMPLICIT : FOCUS_EXPLICIT),
3471 dpyinfo, frame, bufp);
3472 break;
3474 case ClientMessage:
3475 if (event->xclient.message_type == dpyinfo->Xatom_XEMBED)
3477 enum xembed_message msg = event->xclient.data.l[1];
3478 x_focus_changed ((msg == XEMBED_FOCUS_IN ? FocusIn : FocusOut),
3479 FOCUS_EXPLICIT, dpyinfo, frame, bufp);
3481 break;
3486 #if defined HAVE_MENUS && !defined USE_X_TOOLKIT && !defined USE_GTK
3487 /* Handle an event saying the mouse has moved out of an Emacs frame. */
3489 void
3490 x_mouse_leave (struct x_display_info *dpyinfo)
3492 x_new_focus_frame (dpyinfo, dpyinfo->x_focus_event_frame);
3494 #endif
3496 /* The focus has changed, or we have redirected a frame's focus to
3497 another frame (this happens when a frame uses a surrogate
3498 mini-buffer frame). Shift the highlight as appropriate.
3500 The FRAME argument doesn't necessarily have anything to do with which
3501 frame is being highlighted or un-highlighted; we only use it to find
3502 the appropriate X display info. */
3504 static void
3505 XTframe_rehighlight (struct frame *frame)
3507 x_frame_rehighlight (FRAME_X_DISPLAY_INFO (frame));
3510 static void
3511 x_frame_rehighlight (struct x_display_info *dpyinfo)
3513 struct frame *old_highlight = dpyinfo->x_highlight_frame;
3515 if (dpyinfo->x_focus_frame)
3517 dpyinfo->x_highlight_frame
3518 = ((FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame)))
3519 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
3520 : dpyinfo->x_focus_frame);
3521 if (! FRAME_LIVE_P (dpyinfo->x_highlight_frame))
3523 FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
3524 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
3527 else
3528 dpyinfo->x_highlight_frame = 0;
3530 if (dpyinfo->x_highlight_frame != old_highlight)
3532 if (old_highlight)
3533 frame_unhighlight (old_highlight);
3534 if (dpyinfo->x_highlight_frame)
3535 frame_highlight (dpyinfo->x_highlight_frame);
3541 /* Keyboard processing - modifier keys, vendor-specific keysyms, etc. */
3543 /* Initialize mode_switch_bit and modifier_meaning. */
3544 static void
3545 x_find_modifier_meanings (struct x_display_info *dpyinfo)
3547 int min_code, max_code;
3548 KeySym *syms;
3549 int syms_per_code;
3550 XModifierKeymap *mods;
3552 dpyinfo->meta_mod_mask = 0;
3553 dpyinfo->shift_lock_mask = 0;
3554 dpyinfo->alt_mod_mask = 0;
3555 dpyinfo->super_mod_mask = 0;
3556 dpyinfo->hyper_mod_mask = 0;
3558 XDisplayKeycodes (dpyinfo->display, &min_code, &max_code);
3560 syms = XGetKeyboardMapping (dpyinfo->display,
3561 min_code, max_code - min_code + 1,
3562 &syms_per_code);
3563 mods = XGetModifierMapping (dpyinfo->display);
3565 /* Scan the modifier table to see which modifier bits the Meta and
3566 Alt keysyms are on. */
3568 int row, col; /* The row and column in the modifier table. */
3569 int found_alt_or_meta;
3571 for (row = 3; row < 8; row++)
3573 found_alt_or_meta = 0;
3574 for (col = 0; col < mods->max_keypermod; col++)
3576 KeyCode code = mods->modifiermap[(row * mods->max_keypermod) + col];
3578 /* Zeroes are used for filler. Skip them. */
3579 if (code == 0)
3580 continue;
3582 /* Are any of this keycode's keysyms a meta key? */
3584 int code_col;
3586 for (code_col = 0; code_col < syms_per_code; code_col++)
3588 int sym = syms[((code - min_code) * syms_per_code) + code_col];
3590 switch (sym)
3592 case XK_Meta_L:
3593 case XK_Meta_R:
3594 found_alt_or_meta = 1;
3595 dpyinfo->meta_mod_mask |= (1 << row);
3596 break;
3598 case XK_Alt_L:
3599 case XK_Alt_R:
3600 found_alt_or_meta = 1;
3601 dpyinfo->alt_mod_mask |= (1 << row);
3602 break;
3604 case XK_Hyper_L:
3605 case XK_Hyper_R:
3606 if (!found_alt_or_meta)
3607 dpyinfo->hyper_mod_mask |= (1 << row);
3608 code_col = syms_per_code;
3609 col = mods->max_keypermod;
3610 break;
3612 case XK_Super_L:
3613 case XK_Super_R:
3614 if (!found_alt_or_meta)
3615 dpyinfo->super_mod_mask |= (1 << row);
3616 code_col = syms_per_code;
3617 col = mods->max_keypermod;
3618 break;
3620 case XK_Shift_Lock:
3621 /* Ignore this if it's not on the lock modifier. */
3622 if (!found_alt_or_meta && ((1 << row) == LockMask))
3623 dpyinfo->shift_lock_mask = LockMask;
3624 code_col = syms_per_code;
3625 col = mods->max_keypermod;
3626 break;
3634 /* If we couldn't find any meta keys, accept any alt keys as meta keys. */
3635 if (! dpyinfo->meta_mod_mask)
3637 dpyinfo->meta_mod_mask = dpyinfo->alt_mod_mask;
3638 dpyinfo->alt_mod_mask = 0;
3641 /* If some keys are both alt and meta,
3642 make them just meta, not alt. */
3643 if (dpyinfo->alt_mod_mask & dpyinfo->meta_mod_mask)
3645 dpyinfo->alt_mod_mask &= ~dpyinfo->meta_mod_mask;
3648 XFree ((char *) syms);
3649 XFreeModifiermap (mods);
3652 /* Convert between the modifier bits X uses and the modifier bits
3653 Emacs uses. */
3655 EMACS_INT
3656 x_x_to_emacs_modifiers (struct x_display_info *dpyinfo, int state)
3658 EMACS_INT mod_meta = meta_modifier;
3659 EMACS_INT mod_alt = alt_modifier;
3660 EMACS_INT mod_hyper = hyper_modifier;
3661 EMACS_INT mod_super = super_modifier;
3662 Lisp_Object tem;
3664 tem = Fget (Vx_alt_keysym, Qmodifier_value);
3665 if (INTEGERP (tem)) mod_alt = XINT (tem);
3666 tem = Fget (Vx_meta_keysym, Qmodifier_value);
3667 if (INTEGERP (tem)) mod_meta = XINT (tem);
3668 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
3669 if (INTEGERP (tem)) mod_hyper = XINT (tem);
3670 tem = Fget (Vx_super_keysym, Qmodifier_value);
3671 if (INTEGERP (tem)) mod_super = XINT (tem);
3674 return ( ((state & (ShiftMask | dpyinfo->shift_lock_mask)) ? shift_modifier : 0)
3675 | ((state & ControlMask) ? ctrl_modifier : 0)
3676 | ((state & dpyinfo->meta_mod_mask) ? mod_meta : 0)
3677 | ((state & dpyinfo->alt_mod_mask) ? mod_alt : 0)
3678 | ((state & dpyinfo->super_mod_mask) ? mod_super : 0)
3679 | ((state & dpyinfo->hyper_mod_mask) ? mod_hyper : 0));
3682 static int
3683 x_emacs_to_x_modifiers (struct x_display_info *dpyinfo, EMACS_INT state)
3685 int mod_meta = meta_modifier;
3686 int mod_alt = alt_modifier;
3687 int mod_hyper = hyper_modifier;
3688 int mod_super = super_modifier;
3690 Lisp_Object tem;
3692 tem = Fget (Vx_alt_keysym, Qmodifier_value);
3693 if (INTEGERP (tem)) mod_alt = XINT (tem);
3694 tem = Fget (Vx_meta_keysym, Qmodifier_value);
3695 if (INTEGERP (tem)) mod_meta = XINT (tem);
3696 tem = Fget (Vx_hyper_keysym, Qmodifier_value);
3697 if (INTEGERP (tem)) mod_hyper = XINT (tem);
3698 tem = Fget (Vx_super_keysym, Qmodifier_value);
3699 if (INTEGERP (tem)) mod_super = XINT (tem);
3702 return ( ((state & mod_alt) ? dpyinfo->alt_mod_mask : 0)
3703 | ((state & mod_super) ? dpyinfo->super_mod_mask : 0)
3704 | ((state & mod_hyper) ? dpyinfo->hyper_mod_mask : 0)
3705 | ((state & shift_modifier) ? ShiftMask : 0)
3706 | ((state & ctrl_modifier) ? ControlMask : 0)
3707 | ((state & mod_meta) ? dpyinfo->meta_mod_mask : 0));
3710 /* Convert a keysym to its name. */
3712 char *
3713 x_get_keysym_name (int keysym)
3715 char *value;
3717 BLOCK_INPUT;
3718 value = XKeysymToString (keysym);
3719 UNBLOCK_INPUT;
3721 return value;
3726 /* Mouse clicks and mouse movement. Rah. */
3728 /* Prepare a mouse-event in *RESULT for placement in the input queue.
3730 If the event is a button press, then note that we have grabbed
3731 the mouse. */
3733 static Lisp_Object
3734 construct_mouse_click (struct input_event *result, XButtonEvent *event, struct frame *f)
3736 /* Make the event type NO_EVENT; we'll change that when we decide
3737 otherwise. */
3738 result->kind = MOUSE_CLICK_EVENT;
3739 result->code = event->button - Button1;
3740 result->timestamp = event->time;
3741 result->modifiers = (x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO (f),
3742 event->state)
3743 | (event->type == ButtonRelease
3744 ? up_modifier
3745 : down_modifier));
3747 XSETINT (result->x, event->x);
3748 XSETINT (result->y, event->y);
3749 XSETFRAME (result->frame_or_window, f);
3750 result->arg = Qnil;
3751 return Qnil;
3755 /* Function to report a mouse movement to the mainstream Emacs code.
3756 The input handler calls this.
3758 We have received a mouse movement event, which is given in *event.
3759 If the mouse is over a different glyph than it was last time, tell
3760 the mainstream emacs code by setting mouse_moved. If not, ask for
3761 another motion event, so we can check again the next time it moves. */
3763 static XMotionEvent last_mouse_motion_event;
3764 static Lisp_Object last_mouse_motion_frame;
3766 static int
3767 note_mouse_movement (FRAME_PTR frame, XMotionEvent *event)
3769 last_mouse_movement_time = event->time;
3770 last_mouse_motion_event = *event;
3771 XSETFRAME (last_mouse_motion_frame, frame);
3773 if (!FRAME_X_OUTPUT (frame))
3774 return 0;
3776 if (event->window != FRAME_X_WINDOW (frame))
3778 frame->mouse_moved = 1;
3779 last_mouse_scroll_bar = Qnil;
3780 note_mouse_highlight (frame, -1, -1);
3781 last_mouse_glyph_frame = 0;
3782 return 1;
3786 /* Has the mouse moved off the glyph it was on at the last sighting? */
3787 if (frame != last_mouse_glyph_frame
3788 || event->x < last_mouse_glyph.x
3789 || event->x >= last_mouse_glyph.x + last_mouse_glyph.width
3790 || event->y < last_mouse_glyph.y
3791 || event->y >= last_mouse_glyph.y + last_mouse_glyph.height)
3793 frame->mouse_moved = 1;
3794 last_mouse_scroll_bar = Qnil;
3795 note_mouse_highlight (frame, event->x, event->y);
3796 /* Remember which glyph we're now on. */
3797 remember_mouse_glyph (frame, event->x, event->y, &last_mouse_glyph);
3798 last_mouse_glyph_frame = frame;
3799 return 1;
3802 return 0;
3806 /************************************************************************
3807 Mouse Face
3808 ************************************************************************/
3810 static void
3811 redo_mouse_highlight (void)
3813 if (!NILP (last_mouse_motion_frame)
3814 && FRAME_LIVE_P (XFRAME (last_mouse_motion_frame)))
3815 note_mouse_highlight (XFRAME (last_mouse_motion_frame),
3816 last_mouse_motion_event.x,
3817 last_mouse_motion_event.y);
3822 /* Return the current position of the mouse.
3823 *FP should be a frame which indicates which display to ask about.
3825 If the mouse movement started in a scroll bar, set *FP, *BAR_WINDOW,
3826 and *PART to the frame, window, and scroll bar part that the mouse
3827 is over. Set *X and *Y to the portion and whole of the mouse's
3828 position on the scroll bar.
3830 If the mouse movement started elsewhere, set *FP to the frame the
3831 mouse is on, *BAR_WINDOW to nil, and *X and *Y to the character cell
3832 the mouse is over.
3834 Set *TIMESTAMP to the server time-stamp for the time at which the mouse
3835 was at this position.
3837 Don't store anything if we don't have a valid set of values to report.
3839 This clears the mouse_moved flag, so we can wait for the next mouse
3840 movement. */
3842 static void
3843 XTmouse_position (FRAME_PTR *fp, int insist, Lisp_Object *bar_window,
3844 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
3845 Time *timestamp)
3847 FRAME_PTR f1;
3849 BLOCK_INPUT;
3851 if (! NILP (last_mouse_scroll_bar) && insist == 0)
3852 x_scroll_bar_report_motion (fp, bar_window, part, x, y, timestamp);
3853 else
3855 Window root;
3856 int root_x, root_y;
3858 Window dummy_window;
3859 int dummy;
3861 Lisp_Object frame, tail;
3863 /* Clear the mouse-moved flag for every frame on this display. */
3864 FOR_EACH_FRAME (tail, frame)
3865 if (FRAME_X_P (XFRAME (frame))
3866 && FRAME_X_DISPLAY (XFRAME (frame)) == FRAME_X_DISPLAY (*fp))
3867 XFRAME (frame)->mouse_moved = 0;
3869 last_mouse_scroll_bar = Qnil;
3871 /* Figure out which root window we're on. */
3872 XQueryPointer (FRAME_X_DISPLAY (*fp),
3873 DefaultRootWindow (FRAME_X_DISPLAY (*fp)),
3875 /* The root window which contains the pointer. */
3876 &root,
3878 /* Trash which we can't trust if the pointer is on
3879 a different screen. */
3880 &dummy_window,
3882 /* The position on that root window. */
3883 &root_x, &root_y,
3885 /* More trash we can't trust. */
3886 &dummy, &dummy,
3888 /* Modifier keys and pointer buttons, about which
3889 we don't care. */
3890 (unsigned int *) &dummy);
3892 /* Now we have a position on the root; find the innermost window
3893 containing the pointer. */
3895 Window win, child;
3896 int win_x, win_y;
3897 int parent_x = 0, parent_y = 0;
3899 win = root;
3901 /* XTranslateCoordinates can get errors if the window
3902 structure is changing at the same time this function
3903 is running. So at least we must not crash from them. */
3905 x_catch_errors (FRAME_X_DISPLAY (*fp));
3907 if (FRAME_X_DISPLAY_INFO (*fp)->grabbed && last_mouse_frame
3908 && FRAME_LIVE_P (last_mouse_frame))
3910 /* If mouse was grabbed on a frame, give coords for that frame
3911 even if the mouse is now outside it. */
3912 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
3914 /* From-window, to-window. */
3915 root, FRAME_X_WINDOW (last_mouse_frame),
3917 /* From-position, to-position. */
3918 root_x, root_y, &win_x, &win_y,
3920 /* Child of win. */
3921 &child);
3922 f1 = last_mouse_frame;
3924 else
3926 while (1)
3928 XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
3930 /* From-window, to-window. */
3931 root, win,
3933 /* From-position, to-position. */
3934 root_x, root_y, &win_x, &win_y,
3936 /* Child of win. */
3937 &child);
3939 if (child == None || child == win)
3940 break;
3941 #ifdef USE_GTK
3942 /* We don't wan't to know the innermost window. We
3943 want the edit window. For non-Gtk+ the innermost
3944 window is the edit window. For Gtk+ it might not
3945 be. It might be the tool bar for example. */
3946 if (x_window_to_frame (FRAME_X_DISPLAY_INFO (*fp), win))
3947 break;
3948 #endif
3949 win = child;
3950 parent_x = win_x;
3951 parent_y = win_y;
3954 /* Now we know that:
3955 win is the innermost window containing the pointer
3956 (XTC says it has no child containing the pointer),
3957 win_x and win_y are the pointer's position in it
3958 (XTC did this the last time through), and
3959 parent_x and parent_y are the pointer's position in win's parent.
3960 (They are what win_x and win_y were when win was child.
3961 If win is the root window, it has no parent, and
3962 parent_{x,y} are invalid, but that's okay, because we'll
3963 never use them in that case.) */
3965 #ifdef USE_GTK
3966 /* We don't wan't to know the innermost window. We
3967 want the edit window. */
3968 f1 = x_window_to_frame (FRAME_X_DISPLAY_INFO (*fp), win);
3969 #else
3970 /* Is win one of our frames? */
3971 f1 = x_any_window_to_frame (FRAME_X_DISPLAY_INFO (*fp), win);
3972 #endif
3974 #ifdef USE_X_TOOLKIT
3975 /* If we end up with the menu bar window, say it's not
3976 on the frame. */
3977 if (f1 != NULL
3978 && f1->output_data.x->menubar_widget
3979 && win == XtWindow (f1->output_data.x->menubar_widget))
3980 f1 = NULL;
3981 #endif /* USE_X_TOOLKIT */
3984 if (x_had_errors_p (FRAME_X_DISPLAY (*fp)))
3985 f1 = 0;
3987 x_uncatch_errors ();
3989 /* If not, is it one of our scroll bars? */
3990 if (! f1)
3992 struct scroll_bar *bar;
3994 bar = x_window_to_scroll_bar (FRAME_X_DISPLAY (*fp), win);
3996 if (bar)
3998 f1 = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
3999 win_x = parent_x;
4000 win_y = parent_y;
4004 if (f1 == 0 && insist > 0)
4005 f1 = SELECTED_FRAME ();
4007 if (f1)
4009 /* Ok, we found a frame. Store all the values.
4010 last_mouse_glyph is a rectangle used to reduce the
4011 generation of mouse events. To not miss any motion
4012 events, we must divide the frame into rectangles of the
4013 size of the smallest character that could be displayed
4014 on it, i.e. into the same rectangles that matrices on
4015 the frame are divided into. */
4017 remember_mouse_glyph (f1, win_x, win_y, &last_mouse_glyph);
4018 last_mouse_glyph_frame = f1;
4020 *bar_window = Qnil;
4021 *part = 0;
4022 *fp = f1;
4023 XSETINT (*x, win_x);
4024 XSETINT (*y, win_y);
4025 *timestamp = last_mouse_movement_time;
4030 UNBLOCK_INPUT;
4035 /***********************************************************************
4036 Scroll bars
4037 ***********************************************************************/
4039 /* Scroll bar support. */
4041 /* Given an X window ID and a DISPLAY, find the struct scroll_bar which
4042 manages it.
4043 This can be called in GC, so we have to make sure to strip off mark
4044 bits. */
4046 static struct scroll_bar *
4047 x_window_to_scroll_bar (Display *display, Window window_id)
4049 Lisp_Object tail;
4051 #if defined (USE_GTK) && defined (USE_TOOLKIT_SCROLL_BARS)
4052 window_id = (Window) xg_get_scroll_id_for_window (display, window_id);
4053 #endif /* USE_GTK && USE_TOOLKIT_SCROLL_BARS */
4055 for (tail = Vframe_list; CONSP (tail); tail = XCDR (tail))
4057 Lisp_Object frame, bar, condemned;
4059 frame = XCAR (tail);
4060 /* All elements of Vframe_list should be frames. */
4061 if (! FRAMEP (frame))
4062 abort ();
4064 if (! FRAME_X_P (XFRAME (frame)))
4065 continue;
4067 /* Scan this frame's scroll bar list for a scroll bar with the
4068 right window ID. */
4069 condemned = FRAME_CONDEMNED_SCROLL_BARS (XFRAME (frame));
4070 for (bar = FRAME_SCROLL_BARS (XFRAME (frame));
4071 /* This trick allows us to search both the ordinary and
4072 condemned scroll bar lists with one loop. */
4073 ! NILP (bar) || (bar = condemned,
4074 condemned = Qnil,
4075 ! NILP (bar));
4076 bar = XSCROLL_BAR (bar)->next)
4077 if (XSCROLL_BAR (bar)->x_window == window_id &&
4078 FRAME_X_DISPLAY (XFRAME (frame)) == display)
4079 return XSCROLL_BAR (bar);
4082 return NULL;
4086 #if defined USE_LUCID
4088 /* Return the Lucid menu bar WINDOW is part of. Return null
4089 if WINDOW is not part of a menu bar. */
4091 static Widget
4092 x_window_to_menu_bar (Window window)
4094 Lisp_Object tail;
4096 for (tail = Vframe_list; CONSP (tail); tail = XCDR (tail))
4098 if (FRAME_X_P (XFRAME (XCAR (tail))))
4100 Lisp_Object frame = XCAR (tail);
4101 Widget menu_bar = XFRAME (frame)->output_data.x->menubar_widget;
4103 if (menu_bar && xlwmenu_window_p (menu_bar, window))
4104 return menu_bar;
4108 return NULL;
4111 #endif /* USE_LUCID */
4114 /************************************************************************
4115 Toolkit scroll bars
4116 ************************************************************************/
4118 #ifdef USE_TOOLKIT_SCROLL_BARS
4120 static void x_scroll_bar_to_input_event (XEvent *, struct input_event *);
4121 static void x_send_scroll_bar_event (Lisp_Object, int, int, int);
4122 static void x_create_toolkit_scroll_bar (struct frame *,
4123 struct scroll_bar *);
4124 static void x_set_toolkit_scroll_bar_thumb (struct scroll_bar *,
4125 int, int, int);
4128 /* Lisp window being scrolled. Set when starting to interact with
4129 a toolkit scroll bar, reset to nil when ending the interaction. */
4131 static Lisp_Object window_being_scrolled;
4133 /* Last scroll bar part sent in xm_scroll_callback. */
4135 static int last_scroll_bar_part;
4137 /* Whether this is an Xaw with arrow-scrollbars. This should imply
4138 that movements of 1/20 of the screen size are mapped to up/down. */
4140 #ifndef USE_GTK
4141 /* Id of action hook installed for scroll bars. */
4143 static XtActionHookId action_hook_id;
4145 static Boolean xaw3d_arrow_scroll;
4147 /* Whether the drag scrolling maintains the mouse at the top of the
4148 thumb. If not, resizing the thumb needs to be done more carefully
4149 to avoid jerkyness. */
4151 static Boolean xaw3d_pick_top;
4153 /* Action hook installed via XtAppAddActionHook when toolkit scroll
4154 bars are used.. The hook is responsible for detecting when
4155 the user ends an interaction with the scroll bar, and generates
4156 a `end-scroll' SCROLL_BAR_CLICK_EVENT' event if so. */
4158 static void
4159 xt_action_hook (Widget widget, XtPointer client_data, String action_name,
4160 XEvent *event, String *params, Cardinal *num_params)
4162 int scroll_bar_p;
4163 const char *end_action;
4165 #ifdef USE_MOTIF
4166 scroll_bar_p = XmIsScrollBar (widget);
4167 end_action = "Release";
4168 #else /* !USE_MOTIF i.e. use Xaw */
4169 scroll_bar_p = XtIsSubclass (widget, scrollbarWidgetClass);
4170 end_action = "EndScroll";
4171 #endif /* USE_MOTIF */
4173 if (scroll_bar_p
4174 && strcmp (action_name, end_action) == 0
4175 && WINDOWP (window_being_scrolled))
4177 struct window *w;
4179 x_send_scroll_bar_event (window_being_scrolled,
4180 scroll_bar_end_scroll, 0, 0);
4181 w = XWINDOW (window_being_scrolled);
4183 if (!NILP (XSCROLL_BAR (w->vertical_scroll_bar)->dragging))
4185 XSCROLL_BAR (w->vertical_scroll_bar)->dragging = Qnil;
4186 /* The thumb size is incorrect while dragging: fix it. */
4187 set_vertical_scroll_bar (w);
4189 window_being_scrolled = Qnil;
4190 last_scroll_bar_part = -1;
4192 /* Xt timeouts no longer needed. */
4193 toolkit_scroll_bar_interaction = 0;
4196 #endif /* not USE_GTK */
4198 /* A vector of windows used for communication between
4199 x_send_scroll_bar_event and x_scroll_bar_to_input_event. */
4201 static struct window **scroll_bar_windows;
4202 static size_t scroll_bar_windows_size;
4205 /* Send a client message with message type Xatom_Scrollbar for a
4206 scroll action to the frame of WINDOW. PART is a value identifying
4207 the part of the scroll bar that was clicked on. PORTION is the
4208 amount to scroll of a whole of WHOLE. */
4210 static void
4211 x_send_scroll_bar_event (Lisp_Object window, int part, int portion, int whole)
4213 XEvent event;
4214 XClientMessageEvent *ev = (XClientMessageEvent *) &event;
4215 struct window *w = XWINDOW (window);
4216 struct frame *f = XFRAME (w->frame);
4217 size_t i;
4219 BLOCK_INPUT;
4221 /* Construct a ClientMessage event to send to the frame. */
4222 ev->type = ClientMessage;
4223 ev->message_type = FRAME_X_DISPLAY_INFO (f)->Xatom_Scrollbar;
4224 ev->display = FRAME_X_DISPLAY (f);
4225 ev->window = FRAME_X_WINDOW (f);
4226 ev->format = 32;
4228 /* We can only transfer 32 bits in the XClientMessageEvent, which is
4229 not enough to store a pointer or Lisp_Object on a 64 bit system.
4230 So, store the window in scroll_bar_windows and pass the index
4231 into that array in the event. */
4232 for (i = 0; i < scroll_bar_windows_size; ++i)
4233 if (scroll_bar_windows[i] == NULL)
4234 break;
4236 if (i == scroll_bar_windows_size)
4238 size_t new_size = max (10, 2 * scroll_bar_windows_size);
4239 size_t nbytes = new_size * sizeof *scroll_bar_windows;
4240 size_t old_nbytes = scroll_bar_windows_size * sizeof *scroll_bar_windows;
4242 if ((size_t) -1 / sizeof *scroll_bar_windows < new_size)
4243 memory_full (SIZE_MAX);
4244 scroll_bar_windows = (struct window **) xrealloc (scroll_bar_windows,
4245 nbytes);
4246 memset (&scroll_bar_windows[i], 0, nbytes - old_nbytes);
4247 scroll_bar_windows_size = new_size;
4250 scroll_bar_windows[i] = w;
4251 ev->data.l[0] = (long) i;
4252 ev->data.l[1] = (long) part;
4253 ev->data.l[2] = (long) 0;
4254 ev->data.l[3] = (long) portion;
4255 ev->data.l[4] = (long) whole;
4257 /* Make Xt timeouts work while the scroll bar is active. */
4258 #ifdef USE_X_TOOLKIT
4259 toolkit_scroll_bar_interaction = 1;
4260 x_activate_timeout_atimer ();
4261 #endif
4263 /* Setting the event mask to zero means that the message will
4264 be sent to the client that created the window, and if that
4265 window no longer exists, no event will be sent. */
4266 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), False, 0, &event);
4267 UNBLOCK_INPUT;
4271 /* Transform a scroll bar ClientMessage EVENT to an Emacs input event
4272 in *IEVENT. */
4274 static void
4275 x_scroll_bar_to_input_event (XEvent *event, struct input_event *ievent)
4277 XClientMessageEvent *ev = (XClientMessageEvent *) event;
4278 Lisp_Object window;
4279 struct window *w;
4281 w = scroll_bar_windows[ev->data.l[0]];
4282 scroll_bar_windows[ev->data.l[0]] = NULL;
4284 XSETWINDOW (window, w);
4286 ievent->kind = SCROLL_BAR_CLICK_EVENT;
4287 ievent->frame_or_window = window;
4288 ievent->arg = Qnil;
4289 #ifdef USE_GTK
4290 ievent->timestamp = CurrentTime;
4291 #else
4292 ievent->timestamp =
4293 XtLastTimestampProcessed (FRAME_X_DISPLAY (XFRAME (w->frame)));
4294 #endif
4295 ievent->part = ev->data.l[1];
4296 ievent->code = ev->data.l[2];
4297 ievent->x = make_number ((int) ev->data.l[3]);
4298 ievent->y = make_number ((int) ev->data.l[4]);
4299 ievent->modifiers = 0;
4303 #ifdef USE_MOTIF
4305 /* Minimum and maximum values used for Motif scroll bars. */
4307 #define XM_SB_MAX 10000000
4310 /* Scroll bar callback for Motif scroll bars. WIDGET is the scroll
4311 bar widget. CLIENT_DATA is a pointer to the scroll_bar structure.
4312 CALL_DATA is a pointer to a XmScrollBarCallbackStruct. */
4314 static void
4315 xm_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
4317 struct scroll_bar *bar = (struct scroll_bar *) client_data;
4318 XmScrollBarCallbackStruct *cs = (XmScrollBarCallbackStruct *) call_data;
4319 int part = -1, whole = 0, portion = 0;
4321 switch (cs->reason)
4323 case XmCR_DECREMENT:
4324 bar->dragging = Qnil;
4325 part = scroll_bar_up_arrow;
4326 break;
4328 case XmCR_INCREMENT:
4329 bar->dragging = Qnil;
4330 part = scroll_bar_down_arrow;
4331 break;
4333 case XmCR_PAGE_DECREMENT:
4334 bar->dragging = Qnil;
4335 part = scroll_bar_above_handle;
4336 break;
4338 case XmCR_PAGE_INCREMENT:
4339 bar->dragging = Qnil;
4340 part = scroll_bar_below_handle;
4341 break;
4343 case XmCR_TO_TOP:
4344 bar->dragging = Qnil;
4345 part = scroll_bar_to_top;
4346 break;
4348 case XmCR_TO_BOTTOM:
4349 bar->dragging = Qnil;
4350 part = scroll_bar_to_bottom;
4351 break;
4353 case XmCR_DRAG:
4355 int slider_size;
4357 /* Get the slider size. */
4358 BLOCK_INPUT;
4359 XtVaGetValues (widget, XmNsliderSize, &slider_size, NULL);
4360 UNBLOCK_INPUT;
4362 whole = XM_SB_MAX - slider_size;
4363 portion = min (cs->value, whole);
4364 part = scroll_bar_handle;
4365 bar->dragging = make_number (cs->value);
4367 break;
4369 case XmCR_VALUE_CHANGED:
4370 break;
4373 if (part >= 0)
4375 window_being_scrolled = bar->window;
4376 last_scroll_bar_part = part;
4377 x_send_scroll_bar_event (bar->window, part, portion, whole);
4381 #elif defined USE_GTK
4383 /* Scroll bar callback for GTK scroll bars. WIDGET is the scroll
4384 bar widget. DATA is a pointer to the scroll_bar structure. */
4386 static gboolean
4387 xg_scroll_callback (GtkRange *range,
4388 GtkScrollType scroll,
4389 gdouble value,
4390 gpointer user_data)
4392 struct scroll_bar *bar = (struct scroll_bar *) user_data;
4393 gdouble position;
4394 int part = -1, whole = 0, portion = 0;
4395 GtkAdjustment *adj = GTK_ADJUSTMENT (gtk_range_get_adjustment (range));
4396 FRAME_PTR f = (FRAME_PTR) g_object_get_data (G_OBJECT (range), XG_FRAME_DATA);
4398 if (xg_ignore_gtk_scrollbar) return FALSE;
4399 position = gtk_adjustment_get_value (adj);
4402 switch (scroll)
4404 case GTK_SCROLL_JUMP:
4405 /* Buttons 1 2 or 3 must be grabbed. */
4406 if (FRAME_X_DISPLAY_INFO (f)->grabbed != 0
4407 && FRAME_X_DISPLAY_INFO (f)->grabbed < (1 << 4))
4409 part = scroll_bar_handle;
4410 whole = gtk_adjustment_get_upper (adj) -
4411 gtk_adjustment_get_page_size (adj);
4412 portion = min ((int)position, whole);
4413 bar->dragging = make_number ((int)portion);
4415 break;
4416 case GTK_SCROLL_STEP_BACKWARD:
4417 part = scroll_bar_up_arrow;
4418 bar->dragging = Qnil;
4419 break;
4420 case GTK_SCROLL_STEP_FORWARD:
4421 part = scroll_bar_down_arrow;
4422 bar->dragging = Qnil;
4423 break;
4424 case GTK_SCROLL_PAGE_BACKWARD:
4425 part = scroll_bar_above_handle;
4426 bar->dragging = Qnil;
4427 break;
4428 case GTK_SCROLL_PAGE_FORWARD:
4429 part = scroll_bar_below_handle;
4430 bar->dragging = Qnil;
4431 break;
4434 if (part >= 0)
4436 window_being_scrolled = bar->window;
4437 last_scroll_bar_part = part;
4438 x_send_scroll_bar_event (bar->window, part, portion, whole);
4441 return FALSE;
4444 /* Callback for button release. Sets dragging to Qnil when dragging is done. */
4446 static gboolean
4447 xg_end_scroll_callback (GtkWidget *widget,
4448 GdkEventButton *event,
4449 gpointer user_data)
4451 struct scroll_bar *bar = (struct scroll_bar *) user_data;
4452 bar->dragging = Qnil;
4453 if (WINDOWP (window_being_scrolled))
4455 x_send_scroll_bar_event (window_being_scrolled,
4456 scroll_bar_end_scroll, 0, 0);
4457 window_being_scrolled = Qnil;
4460 return FALSE;
4464 #else /* not USE_GTK and not USE_MOTIF */
4466 /* Xaw scroll bar callback. Invoked when the thumb is dragged.
4467 WIDGET is the scroll bar widget. CLIENT_DATA is a pointer to the
4468 scroll bar struct. CALL_DATA is a pointer to a float saying where
4469 the thumb is. */
4471 static void
4472 xaw_jump_callback (Widget widget, XtPointer client_data, XtPointer call_data)
4474 struct scroll_bar *bar = (struct scroll_bar *) client_data;
4475 float top = *(float *) call_data;
4476 float shown;
4477 int whole, portion, height;
4478 int part;
4480 /* Get the size of the thumb, a value between 0 and 1. */
4481 BLOCK_INPUT;
4482 XtVaGetValues (widget, XtNshown, &shown, XtNheight, &height, NULL);
4483 UNBLOCK_INPUT;
4485 whole = 10000000;
4486 portion = shown < 1 ? top * whole : 0;
4488 if (shown < 1 && (eabs (top + shown - 1) < 1.0/height))
4489 /* Some derivatives of Xaw refuse to shrink the thumb when you reach
4490 the bottom, so we force the scrolling whenever we see that we're
4491 too close to the bottom (in x_set_toolkit_scroll_bar_thumb
4492 we try to ensure that we always stay two pixels away from the
4493 bottom). */
4494 part = scroll_bar_down_arrow;
4495 else
4496 part = scroll_bar_handle;
4498 window_being_scrolled = bar->window;
4499 bar->dragging = make_number (portion);
4500 last_scroll_bar_part = part;
4501 x_send_scroll_bar_event (bar->window, part, portion, whole);
4505 /* Xaw scroll bar callback. Invoked for incremental scrolling.,
4506 i.e. line or page up or down. WIDGET is the Xaw scroll bar
4507 widget. CLIENT_DATA is a pointer to the scroll_bar structure for
4508 the scroll bar. CALL_DATA is an integer specifying the action that
4509 has taken place. Its magnitude is in the range 0..height of the
4510 scroll bar. Negative values mean scroll towards buffer start.
4511 Values < height of scroll bar mean line-wise movement. */
4513 static void
4514 xaw_scroll_callback (Widget widget, XtPointer client_data, XtPointer call_data)
4516 struct scroll_bar *bar = (struct scroll_bar *) client_data;
4517 /* The position really is stored cast to a pointer. */
4518 int position = (long) call_data;
4519 Dimension height;
4520 int part;
4522 /* Get the height of the scroll bar. */
4523 BLOCK_INPUT;
4524 XtVaGetValues (widget, XtNheight, &height, NULL);
4525 UNBLOCK_INPUT;
4527 if (eabs (position) >= height)
4528 part = (position < 0) ? scroll_bar_above_handle : scroll_bar_below_handle;
4530 /* If Xaw3d was compiled with ARROW_SCROLLBAR,
4531 it maps line-movement to call_data = max(5, height/20). */
4532 else if (xaw3d_arrow_scroll && eabs (position) <= max (5, height / 20))
4533 part = (position < 0) ? scroll_bar_up_arrow : scroll_bar_down_arrow;
4534 else
4535 part = scroll_bar_move_ratio;
4537 window_being_scrolled = bar->window;
4538 bar->dragging = Qnil;
4539 last_scroll_bar_part = part;
4540 x_send_scroll_bar_event (bar->window, part, position, height);
4543 #endif /* not USE_GTK and not USE_MOTIF */
4545 #define SCROLL_BAR_NAME "verticalScrollBar"
4547 /* Create the widget for scroll bar BAR on frame F. Record the widget
4548 and X window of the scroll bar in BAR. */
4550 #ifdef USE_GTK
4551 static void
4552 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
4554 const char *scroll_bar_name = SCROLL_BAR_NAME;
4556 BLOCK_INPUT;
4557 xg_create_scroll_bar (f, bar, G_CALLBACK (xg_scroll_callback),
4558 G_CALLBACK (xg_end_scroll_callback),
4559 scroll_bar_name);
4560 UNBLOCK_INPUT;
4563 #else /* not USE_GTK */
4565 static void
4566 x_create_toolkit_scroll_bar (struct frame *f, struct scroll_bar *bar)
4568 Window xwindow;
4569 Widget widget;
4570 Arg av[20];
4571 int ac = 0;
4572 char const *scroll_bar_name = SCROLL_BAR_NAME;
4573 unsigned long pixel;
4575 BLOCK_INPUT;
4577 #ifdef USE_MOTIF
4578 /* Set resources. Create the widget. */
4579 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
4580 XtSetArg (av[ac], XmNminimum, 0); ++ac;
4581 XtSetArg (av[ac], XmNmaximum, XM_SB_MAX); ++ac;
4582 XtSetArg (av[ac], XmNorientation, XmVERTICAL); ++ac;
4583 XtSetArg (av[ac], XmNprocessingDirection, XmMAX_ON_BOTTOM), ++ac;
4584 XtSetArg (av[ac], XmNincrement, 1); ++ac;
4585 XtSetArg (av[ac], XmNpageIncrement, 1); ++ac;
4587 pixel = f->output_data.x->scroll_bar_foreground_pixel;
4588 if (pixel != -1)
4590 XtSetArg (av[ac], XmNforeground, pixel);
4591 ++ac;
4594 pixel = f->output_data.x->scroll_bar_background_pixel;
4595 if (pixel != -1)
4597 XtSetArg (av[ac], XmNbackground, pixel);
4598 ++ac;
4601 widget = XmCreateScrollBar (f->output_data.x->edit_widget,
4602 scroll_bar_name, av, ac);
4604 /* Add one callback for everything that can happen. */
4605 XtAddCallback (widget, XmNdecrementCallback, xm_scroll_callback,
4606 (XtPointer) bar);
4607 XtAddCallback (widget, XmNdragCallback, xm_scroll_callback,
4608 (XtPointer) bar);
4609 XtAddCallback (widget, XmNincrementCallback, xm_scroll_callback,
4610 (XtPointer) bar);
4611 XtAddCallback (widget, XmNpageDecrementCallback, xm_scroll_callback,
4612 (XtPointer) bar);
4613 XtAddCallback (widget, XmNpageIncrementCallback, xm_scroll_callback,
4614 (XtPointer) bar);
4615 XtAddCallback (widget, XmNtoBottomCallback, xm_scroll_callback,
4616 (XtPointer) bar);
4617 XtAddCallback (widget, XmNtoTopCallback, xm_scroll_callback,
4618 (XtPointer) bar);
4620 /* Realize the widget. Only after that is the X window created. */
4621 XtRealizeWidget (widget);
4623 /* Set the cursor to an arrow. I didn't find a resource to do that.
4624 And I'm wondering why it hasn't an arrow cursor by default. */
4625 XDefineCursor (XtDisplay (widget), XtWindow (widget),
4626 f->output_data.x->nontext_cursor);
4628 #else /* !USE_MOTIF i.e. use Xaw */
4630 /* Set resources. Create the widget. The background of the
4631 Xaw3d scroll bar widget is a little bit light for my taste.
4632 We don't alter it here to let users change it according
4633 to their taste with `emacs*verticalScrollBar.background: xxx'. */
4634 XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
4635 XtSetArg (av[ac], XtNorientation, XtorientVertical); ++ac;
4636 /* For smoother scrolling with Xaw3d -sm */
4637 /* XtSetArg (av[ac], XtNpickTop, True); ++ac; */
4639 pixel = f->output_data.x->scroll_bar_foreground_pixel;
4640 if (pixel != -1)
4642 XtSetArg (av[ac], XtNforeground, pixel);
4643 ++ac;
4646 pixel = f->output_data.x->scroll_bar_background_pixel;
4647 if (pixel != -1)
4649 XtSetArg (av[ac], XtNbackground, pixel);
4650 ++ac;
4653 /* Top/bottom shadow colors. */
4655 /* Allocate them, if necessary. */
4656 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1)
4658 pixel = f->output_data.x->scroll_bar_background_pixel;
4659 if (pixel != -1)
4661 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
4662 FRAME_X_COLORMAP (f),
4663 &pixel, 1.2, 0x8000))
4664 pixel = -1;
4665 f->output_data.x->scroll_bar_top_shadow_pixel = pixel;
4668 if (f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
4670 pixel = f->output_data.x->scroll_bar_background_pixel;
4671 if (pixel != -1)
4673 if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f),
4674 FRAME_X_COLORMAP (f),
4675 &pixel, 0.6, 0x4000))
4676 pixel = -1;
4677 f->output_data.x->scroll_bar_bottom_shadow_pixel = pixel;
4681 #ifdef XtNbeNiceToColormap
4682 /* Tell the toolkit about them. */
4683 if (f->output_data.x->scroll_bar_top_shadow_pixel == -1
4684 || f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
4685 /* We tried to allocate a color for the top/bottom shadow, and
4686 failed, so tell Xaw3d to use dithering instead. */
4687 /* But only if we have a small colormap. Xaw3d can allocate nice
4688 colors itself. */
4690 XtSetArg (av[ac], XtNbeNiceToColormap,
4691 DefaultDepthOfScreen (FRAME_X_SCREEN (f)) < 16);
4692 ++ac;
4694 else
4695 /* Tell what colors Xaw3d should use for the top/bottom shadow, to
4696 be more consistent with other emacs 3d colors, and since Xaw3d is
4697 not good at dealing with allocation failure. */
4699 /* This tells Xaw3d to use real colors instead of dithering for
4700 the shadows. */
4701 XtSetArg (av[ac], XtNbeNiceToColormap, False);
4702 ++ac;
4704 /* Specify the colors. */
4705 pixel = f->output_data.x->scroll_bar_top_shadow_pixel;
4706 if (pixel != -1)
4708 XtSetArg (av[ac], XtNtopShadowPixel, pixel);
4709 ++ac;
4711 pixel = f->output_data.x->scroll_bar_bottom_shadow_pixel;
4712 if (pixel != -1)
4714 XtSetArg (av[ac], XtNbottomShadowPixel, pixel);
4715 ++ac;
4718 #endif
4720 widget = XtCreateWidget (scroll_bar_name, scrollbarWidgetClass,
4721 f->output_data.x->edit_widget, av, ac);
4724 char const *initial = "";
4725 char const *val = initial;
4726 XtVaGetValues (widget, XtNscrollVCursor, (XtPointer) &val,
4727 #ifdef XtNarrowScrollbars
4728 XtNarrowScrollbars, (XtPointer) &xaw3d_arrow_scroll,
4729 #endif
4730 XtNpickTop, (XtPointer) &xaw3d_pick_top, NULL);
4731 if (xaw3d_arrow_scroll || val == initial)
4732 { /* ARROW_SCROLL */
4733 xaw3d_arrow_scroll = True;
4734 /* Isn't that just a personal preference ? --Stef */
4735 XtVaSetValues (widget, XtNcursorName, "top_left_arrow", NULL);
4739 /* Define callbacks. */
4740 XtAddCallback (widget, XtNjumpProc, xaw_jump_callback, (XtPointer) bar);
4741 XtAddCallback (widget, XtNscrollProc, xaw_scroll_callback,
4742 (XtPointer) bar);
4744 /* Realize the widget. Only after that is the X window created. */
4745 XtRealizeWidget (widget);
4747 #endif /* !USE_MOTIF */
4749 /* Install an action hook that lets us detect when the user
4750 finishes interacting with a scroll bar. */
4751 if (action_hook_id == 0)
4752 action_hook_id = XtAppAddActionHook (Xt_app_con, xt_action_hook, 0);
4754 /* Remember X window and widget in the scroll bar vector. */
4755 SET_SCROLL_BAR_X_WIDGET (bar, widget);
4756 xwindow = XtWindow (widget);
4757 bar->x_window = xwindow;
4759 UNBLOCK_INPUT;
4761 #endif /* not USE_GTK */
4764 /* Set the thumb size and position of scroll bar BAR. We are currently
4765 displaying PORTION out of a whole WHOLE, and our position POSITION. */
4767 #ifdef USE_GTK
4768 static void
4769 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position, int whole)
4771 xg_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
4774 #else /* not USE_GTK */
4775 static void
4776 x_set_toolkit_scroll_bar_thumb (struct scroll_bar *bar, int portion, int position,
4777 int whole)
4779 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
4780 Widget widget = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
4781 float top, shown;
4783 BLOCK_INPUT;
4785 #ifdef USE_MOTIF
4787 /* We use an estimate of 30 chars per line rather than the real
4788 `portion' value. This has the disadvantage that the thumb size
4789 is not very representative, but it makes our life a lot easier.
4790 Otherwise, we have to constantly adjust the thumb size, which
4791 we can't always do quickly enough: while dragging, the size of
4792 the thumb might prevent the user from dragging the thumb all the
4793 way to the end. but Motif and some versions of Xaw3d don't allow
4794 updating the thumb size while dragging. Also, even if we can update
4795 its size, the update will often happen too late.
4796 If you don't believe it, check out revision 1.650 of xterm.c to see
4797 what hoops we were going through and the still poor behavior we got. */
4798 portion = WINDOW_TOTAL_LINES (XWINDOW (bar->window)) * 30;
4799 /* When the thumb is at the bottom, position == whole.
4800 So we need to increase `whole' to make space for the thumb. */
4801 whole += portion;
4803 if (whole <= 0)
4804 top = 0, shown = 1;
4805 else
4807 top = (float) position / whole;
4808 shown = (float) portion / whole;
4811 if (NILP (bar->dragging))
4813 int size, value;
4815 /* Slider size. Must be in the range [1 .. MAX - MIN] where MAX
4816 is the scroll bar's maximum and MIN is the scroll bar's minimum
4817 value. */
4818 size = shown * XM_SB_MAX;
4819 size = min (size, XM_SB_MAX);
4820 size = max (size, 1);
4822 /* Position. Must be in the range [MIN .. MAX - SLIDER_SIZE]. */
4823 value = top * XM_SB_MAX;
4824 value = min (value, XM_SB_MAX - size);
4826 XmScrollBarSetValues (widget, value, size, 0, 0, False);
4828 #else /* !USE_MOTIF i.e. use Xaw */
4830 if (whole == 0)
4831 top = 0, shown = 1;
4832 else
4834 top = (float) position / whole;
4835 shown = (float) portion / whole;
4839 float old_top, old_shown;
4840 Dimension height;
4841 XtVaGetValues (widget,
4842 XtNtopOfThumb, &old_top,
4843 XtNshown, &old_shown,
4844 XtNheight, &height,
4845 NULL);
4847 /* Massage the top+shown values. */
4848 if (NILP (bar->dragging) || last_scroll_bar_part == scroll_bar_down_arrow)
4849 top = max (0, min (1, top));
4850 else
4851 top = old_top;
4852 /* Keep two pixels available for moving the thumb down. */
4853 shown = max (0, min (1 - top - (2.0 / height), shown));
4855 /* If the call to XawScrollbarSetThumb below doesn't seem to work,
4856 check that your system's configuration file contains a define
4857 for `NARROWPROTO'. See s/freebsd.h for an example. */
4858 if (top != old_top || shown != old_shown)
4860 if (NILP (bar->dragging))
4861 XawScrollbarSetThumb (widget, top, shown);
4862 else
4864 /* Try to make the scrolling a tad smoother. */
4865 if (!xaw3d_pick_top)
4866 shown = min (shown, old_shown);
4868 XawScrollbarSetThumb (widget, top, shown);
4872 #endif /* !USE_MOTIF */
4874 UNBLOCK_INPUT;
4876 #endif /* not USE_GTK */
4878 #endif /* USE_TOOLKIT_SCROLL_BARS */
4882 /************************************************************************
4883 Scroll bars, general
4884 ************************************************************************/
4886 /* Create a scroll bar and return the scroll bar vector for it. W is
4887 the Emacs window on which to create the scroll bar. TOP, LEFT,
4888 WIDTH and HEIGHT are the pixel coordinates and dimensions of the
4889 scroll bar. */
4891 static struct scroll_bar *
4892 x_scroll_bar_create (struct window *w, int top, int left, int width, int height)
4894 struct frame *f = XFRAME (w->frame);
4895 struct scroll_bar *bar
4896 = ALLOCATE_PSEUDOVECTOR (struct scroll_bar, x_window, PVEC_OTHER);
4898 BLOCK_INPUT;
4900 #ifdef USE_TOOLKIT_SCROLL_BARS
4901 x_create_toolkit_scroll_bar (f, bar);
4902 #else /* not USE_TOOLKIT_SCROLL_BARS */
4904 XSetWindowAttributes a;
4905 unsigned long mask;
4906 Window window;
4908 a.background_pixel = f->output_data.x->scroll_bar_background_pixel;
4909 if (a.background_pixel == -1)
4910 a.background_pixel = FRAME_BACKGROUND_PIXEL (f);
4912 a.event_mask = (ButtonPressMask | ButtonReleaseMask
4913 | ButtonMotionMask | PointerMotionHintMask
4914 | ExposureMask);
4915 a.cursor = FRAME_X_DISPLAY_INFO (f)->vertical_scroll_bar_cursor;
4917 mask = (CWBackPixel | CWEventMask | CWCursor);
4919 /* Clear the area of W that will serve as a scroll bar. This is
4920 for the case that a window has been split horizontally. In
4921 this case, no clear_frame is generated to reduce flickering. */
4922 if (width > 0 && height > 0)
4923 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4924 left, top, width,
4925 window_box_height (w), False);
4927 window = XCreateWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4928 /* Position and size of scroll bar. */
4929 left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
4930 top,
4931 width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
4932 height,
4933 /* Border width, depth, class, and visual. */
4935 CopyFromParent,
4936 CopyFromParent,
4937 CopyFromParent,
4938 /* Attributes. */
4939 mask, &a);
4940 bar->x_window = window;
4942 #endif /* not USE_TOOLKIT_SCROLL_BARS */
4944 XSETWINDOW (bar->window, w);
4945 bar->top = top;
4946 bar->left = left;
4947 bar->width = width;
4948 bar->height = height;
4949 bar->start = 0;
4950 bar->end = 0;
4951 bar->dragging = Qnil;
4952 bar->fringe_extended_p = 0;
4954 /* Add bar to its frame's list of scroll bars. */
4955 bar->next = FRAME_SCROLL_BARS (f);
4956 bar->prev = Qnil;
4957 XSETVECTOR (FRAME_SCROLL_BARS (f), bar);
4958 if (!NILP (bar->next))
4959 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
4961 /* Map the window/widget. */
4962 #ifdef USE_TOOLKIT_SCROLL_BARS
4964 #ifdef USE_GTK
4965 xg_update_scrollbar_pos (f,
4966 bar->x_window,
4967 top,
4968 left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
4969 width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
4970 max (height, 1));
4971 #else /* not USE_GTK */
4972 Widget scroll_bar = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
4973 XtConfigureWidget (scroll_bar,
4974 left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
4975 top,
4976 width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
4977 max (height, 1), 0);
4978 XtMapWidget (scroll_bar);
4979 #endif /* not USE_GTK */
4981 #else /* not USE_TOOLKIT_SCROLL_BARS */
4982 XMapRaised (FRAME_X_DISPLAY (f), bar->x_window);
4983 #endif /* not USE_TOOLKIT_SCROLL_BARS */
4985 UNBLOCK_INPUT;
4986 return bar;
4990 #ifndef USE_TOOLKIT_SCROLL_BARS
4992 /* Draw BAR's handle in the proper position.
4994 If the handle is already drawn from START to END, don't bother
4995 redrawing it, unless REBUILD is non-zero; in that case, always
4996 redraw it. (REBUILD is handy for drawing the handle after expose
4997 events.)
4999 Normally, we want to constrain the start and end of the handle to
5000 fit inside its rectangle, but if the user is dragging the scroll
5001 bar handle, we want to let them drag it down all the way, so that
5002 the bar's top is as far down as it goes; otherwise, there's no way
5003 to move to the very end of the buffer. */
5005 static void
5006 x_scroll_bar_set_handle (struct scroll_bar *bar, int start, int end, int rebuild)
5008 int dragging = ! NILP (bar->dragging);
5009 Window w = bar->x_window;
5010 FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5011 GC gc = f->output_data.x->normal_gc;
5013 /* If the display is already accurate, do nothing. */
5014 if (! rebuild
5015 && start == bar->start
5016 && end == bar->end)
5017 return;
5019 BLOCK_INPUT;
5022 int inside_width = VERTICAL_SCROLL_BAR_INSIDE_WIDTH (f, bar->width);
5023 int inside_height = VERTICAL_SCROLL_BAR_INSIDE_HEIGHT (f, bar->height);
5024 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
5026 /* Make sure the values are reasonable, and try to preserve
5027 the distance between start and end. */
5029 int length = end - start;
5031 if (start < 0)
5032 start = 0;
5033 else if (start > top_range)
5034 start = top_range;
5035 end = start + length;
5037 if (end < start)
5038 end = start;
5039 else if (end > top_range && ! dragging)
5040 end = top_range;
5043 /* Store the adjusted setting in the scroll bar. */
5044 bar->start = start;
5045 bar->end = end;
5047 /* Clip the end position, just for display. */
5048 if (end > top_range)
5049 end = top_range;
5051 /* Draw bottom positions VERTICAL_SCROLL_BAR_MIN_HANDLE pixels
5052 below top positions, to make sure the handle is always at least
5053 that many pixels tall. */
5054 end += VERTICAL_SCROLL_BAR_MIN_HANDLE;
5056 /* Draw the empty space above the handle. Note that we can't clear
5057 zero-height areas; that means "clear to end of window." */
5058 if (0 < start)
5059 x_clear_area (FRAME_X_DISPLAY (f), w,
5060 /* x, y, width, height, and exposures. */
5061 VERTICAL_SCROLL_BAR_LEFT_BORDER,
5062 VERTICAL_SCROLL_BAR_TOP_BORDER,
5063 inside_width, start,
5064 False);
5066 /* Change to proper foreground color if one is specified. */
5067 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5068 XSetForeground (FRAME_X_DISPLAY (f), gc,
5069 f->output_data.x->scroll_bar_foreground_pixel);
5071 /* Draw the handle itself. */
5072 XFillRectangle (FRAME_X_DISPLAY (f), w, gc,
5073 /* x, y, width, height */
5074 VERTICAL_SCROLL_BAR_LEFT_BORDER,
5075 VERTICAL_SCROLL_BAR_TOP_BORDER + start,
5076 inside_width, end - start);
5078 /* Restore the foreground color of the GC if we changed it above. */
5079 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5080 XSetForeground (FRAME_X_DISPLAY (f), gc,
5081 FRAME_FOREGROUND_PIXEL (f));
5083 /* Draw the empty space below the handle. Note that we can't
5084 clear zero-height areas; that means "clear to end of window." */
5085 if (end < inside_height)
5086 x_clear_area (FRAME_X_DISPLAY (f), w,
5087 /* x, y, width, height, and exposures. */
5088 VERTICAL_SCROLL_BAR_LEFT_BORDER,
5089 VERTICAL_SCROLL_BAR_TOP_BORDER + end,
5090 inside_width, inside_height - end,
5091 False);
5095 UNBLOCK_INPUT;
5098 #endif /* !USE_TOOLKIT_SCROLL_BARS */
5100 /* Destroy scroll bar BAR, and set its Emacs window's scroll bar to
5101 nil. */
5103 static void
5104 x_scroll_bar_remove (struct scroll_bar *bar)
5106 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5107 BLOCK_INPUT;
5109 #ifdef USE_TOOLKIT_SCROLL_BARS
5110 #ifdef USE_GTK
5111 xg_remove_scroll_bar (f, bar->x_window);
5112 #else /* not USE_GTK */
5113 XtDestroyWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar));
5114 #endif /* not USE_GTK */
5115 #else
5116 XDestroyWindow (FRAME_X_DISPLAY (f), bar->x_window);
5117 #endif
5119 /* Disassociate this scroll bar from its window. */
5120 XWINDOW (bar->window)->vertical_scroll_bar = Qnil;
5122 UNBLOCK_INPUT;
5126 /* Set the handle of the vertical scroll bar for WINDOW to indicate
5127 that we are displaying PORTION characters out of a total of WHOLE
5128 characters, starting at POSITION. If WINDOW has no scroll bar,
5129 create one. */
5131 static void
5132 XTset_vertical_scroll_bar (struct window *w, int portion, int whole, int position)
5134 struct frame *f = XFRAME (w->frame);
5135 struct scroll_bar *bar;
5136 int top, height, left, sb_left, width, sb_width;
5137 int window_y, window_height;
5138 #ifdef USE_TOOLKIT_SCROLL_BARS
5139 int fringe_extended_p;
5140 #endif
5142 /* Get window dimensions. */
5143 window_box (w, -1, 0, &window_y, 0, &window_height);
5144 top = window_y;
5145 width = WINDOW_CONFIG_SCROLL_BAR_COLS (w) * FRAME_COLUMN_WIDTH (f);
5146 height = window_height;
5148 /* Compute the left edge of the scroll bar area. */
5149 left = WINDOW_SCROLL_BAR_AREA_X (w);
5151 /* Compute the width of the scroll bar which might be less than
5152 the width of the area reserved for the scroll bar. */
5153 if (WINDOW_CONFIG_SCROLL_BAR_WIDTH (w) > 0)
5154 sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
5155 else
5156 sb_width = width;
5158 /* Compute the left edge of the scroll bar. */
5159 #ifdef USE_TOOLKIT_SCROLL_BARS
5160 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w))
5161 sb_left = left + (WINDOW_RIGHTMOST_P (w) ? width - sb_width : 0);
5162 else
5163 sb_left = left + (WINDOW_LEFTMOST_P (w) ? 0 : width - sb_width);
5164 #else
5165 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w))
5166 sb_left = left + width - sb_width;
5167 else
5168 sb_left = left;
5169 #endif
5171 #ifdef USE_TOOLKIT_SCROLL_BARS
5172 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
5173 fringe_extended_p = (WINDOW_LEFTMOST_P (w)
5174 && WINDOW_LEFT_FRINGE_WIDTH (w)
5175 && (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (w)
5176 || WINDOW_LEFT_MARGIN_COLS (w) == 0));
5177 else
5178 fringe_extended_p = (WINDOW_RIGHTMOST_P (w)
5179 && WINDOW_RIGHT_FRINGE_WIDTH (w)
5180 && (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (w)
5181 || WINDOW_RIGHT_MARGIN_COLS (w) == 0));
5182 #endif
5184 /* Does the scroll bar exist yet? */
5185 if (NILP (w->vertical_scroll_bar))
5187 if (width > 0 && height > 0)
5189 BLOCK_INPUT;
5190 #ifdef USE_TOOLKIT_SCROLL_BARS
5191 if (fringe_extended_p)
5192 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5193 sb_left, top, sb_width, height, False);
5194 else
5195 #endif
5196 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5197 left, top, width, height, False);
5198 UNBLOCK_INPUT;
5201 bar = x_scroll_bar_create (w, top, sb_left, sb_width, height);
5203 else
5205 /* It may just need to be moved and resized. */
5206 unsigned int mask = 0;
5208 bar = XSCROLL_BAR (w->vertical_scroll_bar);
5210 BLOCK_INPUT;
5212 if (sb_left != bar->left)
5213 mask |= CWX;
5214 if (top != bar->top)
5215 mask |= CWY;
5216 if (sb_width != bar->width)
5217 mask |= CWWidth;
5218 if (height != bar->height)
5219 mask |= CWHeight;
5221 #ifdef USE_TOOLKIT_SCROLL_BARS
5223 /* Move/size the scroll bar widget. */
5224 if (mask || bar->fringe_extended_p != fringe_extended_p)
5226 /* Since toolkit scroll bars are smaller than the space reserved
5227 for them on the frame, we have to clear "under" them. */
5228 if (width > 0 && height > 0)
5230 if (fringe_extended_p)
5231 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5232 sb_left, top, sb_width, height, False);
5233 else
5234 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5235 left, top, width, height, False);
5237 #ifdef USE_GTK
5238 xg_update_scrollbar_pos (f,
5239 bar->x_window,
5240 top,
5241 sb_left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5242 sb_width - VERTICAL_SCROLL_BAR_WIDTH_TRIM *2,
5243 max (height, 1));
5244 #else /* not USE_GTK */
5245 XtConfigureWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar),
5246 sb_left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5247 top,
5248 sb_width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
5249 max (height, 1), 0);
5250 #endif /* not USE_GTK */
5252 #else /* not USE_TOOLKIT_SCROLL_BARS */
5254 /* Clear areas not covered by the scroll bar because of
5255 VERTICAL_SCROLL_BAR_WIDTH_TRIM. */
5256 if (VERTICAL_SCROLL_BAR_WIDTH_TRIM)
5258 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5259 left, top, VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5260 height, False);
5261 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5262 left + width - VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5263 top, VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5264 height, False);
5267 /* Clear areas not covered by the scroll bar because it's not as
5268 wide as the area reserved for it. This makes sure a
5269 previous mode line display is cleared after C-x 2 C-x 1, for
5270 example. */
5272 int area_width = WINDOW_CONFIG_SCROLL_BAR_COLS (w) * FRAME_COLUMN_WIDTH (f);
5273 int rest = area_width - sb_width;
5274 if (rest > 0 && height > 0)
5276 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
5277 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5278 left + area_width - rest, top,
5279 rest, height, False);
5280 else
5281 x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5282 left, top, rest, height, False);
5286 /* Move/size the scroll bar window. */
5287 if (mask)
5289 XWindowChanges wc;
5291 wc.x = sb_left + VERTICAL_SCROLL_BAR_WIDTH_TRIM;
5292 wc.y = top;
5293 wc.width = sb_width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2;
5294 wc.height = height;
5295 XConfigureWindow (FRAME_X_DISPLAY (f), bar->x_window,
5296 mask, &wc);
5299 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5301 /* Remember new settings. */
5302 bar->left = sb_left;
5303 bar->top = top;
5304 bar->width = sb_width;
5305 bar->height = height;
5307 UNBLOCK_INPUT;
5310 #ifdef USE_TOOLKIT_SCROLL_BARS
5311 bar->fringe_extended_p = fringe_extended_p;
5313 x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
5314 #else /* not USE_TOOLKIT_SCROLL_BARS */
5315 /* Set the scroll bar's current state, unless we're currently being
5316 dragged. */
5317 if (NILP (bar->dragging))
5319 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, height);
5321 if (whole == 0)
5322 x_scroll_bar_set_handle (bar, 0, top_range, 0);
5323 else
5325 int start = ((double) position * top_range) / whole;
5326 int end = ((double) (position + portion) * top_range) / whole;
5327 x_scroll_bar_set_handle (bar, start, end, 0);
5330 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5332 XSETVECTOR (w->vertical_scroll_bar, bar);
5336 /* The following three hooks are used when we're doing a thorough
5337 redisplay of the frame. We don't explicitly know which scroll bars
5338 are going to be deleted, because keeping track of when windows go
5339 away is a real pain - "Can you say set-window-configuration, boys
5340 and girls?" Instead, we just assert at the beginning of redisplay
5341 that *all* scroll bars are to be removed, and then save a scroll bar
5342 from the fiery pit when we actually redisplay its window. */
5344 /* Arrange for all scroll bars on FRAME to be removed at the next call
5345 to `*judge_scroll_bars_hook'. A scroll bar may be spared if
5346 `*redeem_scroll_bar_hook' is applied to its window before the judgment. */
5348 static void
5349 XTcondemn_scroll_bars (FRAME_PTR frame)
5351 /* Transfer all the scroll bars to FRAME_CONDEMNED_SCROLL_BARS. */
5352 while (! NILP (FRAME_SCROLL_BARS (frame)))
5354 Lisp_Object bar;
5355 bar = FRAME_SCROLL_BARS (frame);
5356 FRAME_SCROLL_BARS (frame) = XSCROLL_BAR (bar)->next;
5357 XSCROLL_BAR (bar)->next = FRAME_CONDEMNED_SCROLL_BARS (frame);
5358 XSCROLL_BAR (bar)->prev = Qnil;
5359 if (! NILP (FRAME_CONDEMNED_SCROLL_BARS (frame)))
5360 XSCROLL_BAR (FRAME_CONDEMNED_SCROLL_BARS (frame))->prev = bar;
5361 FRAME_CONDEMNED_SCROLL_BARS (frame) = bar;
5366 /* Un-mark WINDOW's scroll bar for deletion in this judgment cycle.
5367 Note that WINDOW isn't necessarily condemned at all. */
5369 static void
5370 XTredeem_scroll_bar (struct window *window)
5372 struct scroll_bar *bar;
5373 struct frame *f;
5375 /* We can't redeem this window's scroll bar if it doesn't have one. */
5376 if (NILP (window->vertical_scroll_bar))
5377 abort ();
5379 bar = XSCROLL_BAR (window->vertical_scroll_bar);
5381 /* Unlink it from the condemned list. */
5382 f = XFRAME (WINDOW_FRAME (window));
5383 if (NILP (bar->prev))
5385 /* If the prev pointer is nil, it must be the first in one of
5386 the lists. */
5387 if (EQ (FRAME_SCROLL_BARS (f), window->vertical_scroll_bar))
5388 /* It's not condemned. Everything's fine. */
5389 return;
5390 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
5391 window->vertical_scroll_bar))
5392 FRAME_CONDEMNED_SCROLL_BARS (f) = bar->next;
5393 else
5394 /* If its prev pointer is nil, it must be at the front of
5395 one or the other! */
5396 abort ();
5398 else
5399 XSCROLL_BAR (bar->prev)->next = bar->next;
5401 if (! NILP (bar->next))
5402 XSCROLL_BAR (bar->next)->prev = bar->prev;
5404 bar->next = FRAME_SCROLL_BARS (f);
5405 bar->prev = Qnil;
5406 XSETVECTOR (FRAME_SCROLL_BARS (f), bar);
5407 if (! NILP (bar->next))
5408 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
5411 /* Remove all scroll bars on FRAME that haven't been saved since the
5412 last call to `*condemn_scroll_bars_hook'. */
5414 static void
5415 XTjudge_scroll_bars (FRAME_PTR f)
5417 Lisp_Object bar, next;
5419 bar = FRAME_CONDEMNED_SCROLL_BARS (f);
5421 /* Clear out the condemned list now so we won't try to process any
5422 more events on the hapless scroll bars. */
5423 FRAME_CONDEMNED_SCROLL_BARS (f) = Qnil;
5425 for (; ! NILP (bar); bar = next)
5427 struct scroll_bar *b = XSCROLL_BAR (bar);
5429 x_scroll_bar_remove (b);
5431 next = b->next;
5432 b->next = b->prev = Qnil;
5435 /* Now there should be no references to the condemned scroll bars,
5436 and they should get garbage-collected. */
5440 #ifndef USE_TOOLKIT_SCROLL_BARS
5441 /* Handle an Expose or GraphicsExpose event on a scroll bar. This
5442 is a no-op when using toolkit scroll bars.
5444 This may be called from a signal handler, so we have to ignore GC
5445 mark bits. */
5447 static void
5448 x_scroll_bar_expose (struct scroll_bar *bar, XEvent *event)
5450 Window w = bar->x_window;
5451 FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5452 GC gc = f->output_data.x->normal_gc;
5453 int width_trim = VERTICAL_SCROLL_BAR_WIDTH_TRIM;
5455 BLOCK_INPUT;
5457 x_scroll_bar_set_handle (bar, bar->start, bar->end, 1);
5459 /* Switch to scroll bar foreground color. */
5460 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5461 XSetForeground (FRAME_X_DISPLAY (f), gc,
5462 f->output_data.x->scroll_bar_foreground_pixel);
5464 /* Draw a one-pixel border just inside the edges of the scroll bar. */
5465 XDrawRectangle (FRAME_X_DISPLAY (f), w, gc,
5467 /* x, y, width, height */
5468 0, 0,
5469 bar->width - 1 - width_trim - width_trim,
5470 bar->height - 1);
5472 /* Restore the foreground color of the GC if we changed it above. */
5473 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5474 XSetForeground (FRAME_X_DISPLAY (f), gc,
5475 FRAME_FOREGROUND_PIXEL (f));
5477 UNBLOCK_INPUT;
5480 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5482 /* Handle a mouse click on the scroll bar BAR. If *EMACS_EVENT's kind
5483 is set to something other than NO_EVENT, it is enqueued.
5485 This may be called from a signal handler, so we have to ignore GC
5486 mark bits. */
5489 static void
5490 x_scroll_bar_handle_click (struct scroll_bar *bar, XEvent *event, struct input_event *emacs_event)
5492 if (! WINDOWP (bar->window))
5493 abort ();
5495 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
5496 emacs_event->code = event->xbutton.button - Button1;
5497 emacs_event->modifiers
5498 = (x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO
5499 (XFRAME (WINDOW_FRAME (XWINDOW (bar->window)))),
5500 event->xbutton.state)
5501 | (event->type == ButtonRelease
5502 ? up_modifier
5503 : down_modifier));
5504 emacs_event->frame_or_window = bar->window;
5505 emacs_event->arg = Qnil;
5506 emacs_event->timestamp = event->xbutton.time;
5508 int top_range
5509 = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
5510 int y = event->xbutton.y - VERTICAL_SCROLL_BAR_TOP_BORDER;
5512 if (y < 0) y = 0;
5513 if (y > top_range) y = top_range;
5515 if (y < bar->start)
5516 emacs_event->part = scroll_bar_above_handle;
5517 else if (y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
5518 emacs_event->part = scroll_bar_handle;
5519 else
5520 emacs_event->part = scroll_bar_below_handle;
5522 #ifndef USE_TOOLKIT_SCROLL_BARS
5523 /* If the user has released the handle, set it to its final position. */
5524 if (event->type == ButtonRelease
5525 && ! NILP (bar->dragging))
5527 int new_start = y - XINT (bar->dragging);
5528 int new_end = new_start + bar->end - bar->start;
5530 x_scroll_bar_set_handle (bar, new_start, new_end, 0);
5531 bar->dragging = Qnil;
5533 #endif
5535 XSETINT (emacs_event->x, y);
5536 XSETINT (emacs_event->y, top_range);
5540 #ifndef USE_TOOLKIT_SCROLL_BARS
5542 /* Handle some mouse motion while someone is dragging the scroll bar.
5544 This may be called from a signal handler, so we have to ignore GC
5545 mark bits. */
5547 static void
5548 x_scroll_bar_note_movement (struct scroll_bar *bar, XEvent *event)
5550 FRAME_PTR f = XFRAME (XWINDOW (bar->window)->frame);
5552 last_mouse_movement_time = event->xmotion.time;
5554 f->mouse_moved = 1;
5555 XSETVECTOR (last_mouse_scroll_bar, bar);
5557 /* If we're dragging the bar, display it. */
5558 if (! NILP (bar->dragging))
5560 /* Where should the handle be now? */
5561 int new_start = event->xmotion.y - XINT (bar->dragging);
5563 if (new_start != bar->start)
5565 int new_end = new_start + bar->end - bar->start;
5567 x_scroll_bar_set_handle (bar, new_start, new_end, 0);
5572 #endif /* !USE_TOOLKIT_SCROLL_BARS */
5574 /* Return information to the user about the current position of the mouse
5575 on the scroll bar. */
5577 static void
5578 x_scroll_bar_report_motion (FRAME_PTR *fp, Lisp_Object *bar_window,
5579 enum scroll_bar_part *part, Lisp_Object *x,
5580 Lisp_Object *y, Time *timestamp)
5582 struct scroll_bar *bar = XSCROLL_BAR (last_mouse_scroll_bar);
5583 Window w = bar->x_window;
5584 FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5585 int win_x, win_y;
5586 Window dummy_window;
5587 int dummy_coord;
5588 unsigned int dummy_mask;
5590 BLOCK_INPUT;
5592 /* Get the mouse's position relative to the scroll bar window, and
5593 report that. */
5594 if (! XQueryPointer (FRAME_X_DISPLAY (f), w,
5596 /* Root, child, root x and root y. */
5597 &dummy_window, &dummy_window,
5598 &dummy_coord, &dummy_coord,
5600 /* Position relative to scroll bar. */
5601 &win_x, &win_y,
5603 /* Mouse buttons and modifier keys. */
5604 &dummy_mask))
5606 else
5608 int top_range
5609 = VERTICAL_SCROLL_BAR_TOP_RANGE (f, bar->height);
5611 win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
5613 if (! NILP (bar->dragging))
5614 win_y -= XINT (bar->dragging);
5616 if (win_y < 0)
5617 win_y = 0;
5618 if (win_y > top_range)
5619 win_y = top_range;
5621 *fp = f;
5622 *bar_window = bar->window;
5624 if (! NILP (bar->dragging))
5625 *part = scroll_bar_handle;
5626 else if (win_y < bar->start)
5627 *part = scroll_bar_above_handle;
5628 else if (win_y < bar->end + VERTICAL_SCROLL_BAR_MIN_HANDLE)
5629 *part = scroll_bar_handle;
5630 else
5631 *part = scroll_bar_below_handle;
5633 XSETINT (*x, win_y);
5634 XSETINT (*y, top_range);
5636 f->mouse_moved = 0;
5637 last_mouse_scroll_bar = Qnil;
5640 *timestamp = last_mouse_movement_time;
5642 UNBLOCK_INPUT;
5646 /* The screen has been cleared so we may have changed foreground or
5647 background colors, and the scroll bars may need to be redrawn.
5648 Clear out the scroll bars, and ask for expose events, so we can
5649 redraw them. */
5651 static void
5652 x_scroll_bar_clear (FRAME_PTR f)
5654 #ifndef USE_TOOLKIT_SCROLL_BARS
5655 Lisp_Object bar;
5657 /* We can have scroll bars even if this is 0,
5658 if we just turned off scroll bar mode.
5659 But in that case we should not clear them. */
5660 if (FRAME_HAS_VERTICAL_SCROLL_BARS (f))
5661 for (bar = FRAME_SCROLL_BARS (f); VECTORP (bar);
5662 bar = XSCROLL_BAR (bar)->next)
5663 XClearArea (FRAME_X_DISPLAY (f),
5664 XSCROLL_BAR (bar)->x_window,
5665 0, 0, 0, 0, True);
5666 #endif /* not USE_TOOLKIT_SCROLL_BARS */
5670 /* The main X event-reading loop - XTread_socket. */
5672 /* This holds the state XLookupString needs to implement dead keys
5673 and other tricks known as "compose processing". _X Window System_
5674 says that a portable program can't use this, but Stephen Gildea assures
5675 me that letting the compiler initialize it to zeros will work okay.
5677 This must be defined outside of XTread_socket, for the same reasons
5678 given for enter_timestamp, above. */
5680 static XComposeStatus compose_status;
5682 /* Record the last 100 characters stored
5683 to help debug the loss-of-chars-during-GC problem. */
5685 static int temp_index;
5686 static short temp_buffer[100];
5688 #define STORE_KEYSYM_FOR_DEBUG(keysym) \
5689 if (temp_index == sizeof temp_buffer / sizeof (short)) \
5690 temp_index = 0; \
5691 temp_buffer[temp_index++] = (keysym)
5693 /* Set this to nonzero to fake an "X I/O error"
5694 on a particular display. */
5696 static struct x_display_info *XTread_socket_fake_io_error;
5698 /* When we find no input here, we occasionally do a no-op command
5699 to verify that the X server is still running and we can still talk with it.
5700 We try all the open displays, one by one.
5701 This variable is used for cycling thru the displays. */
5703 static struct x_display_info *next_noop_dpyinfo;
5705 #if defined USE_X_TOOLKIT || defined USE_GTK
5706 #define SET_SAVED_BUTTON_EVENT \
5707 do \
5709 if (f->output_data.x->saved_menu_event == 0) \
5710 f->output_data.x->saved_menu_event \
5711 = (XEvent *) xmalloc (sizeof (XEvent)); \
5712 *f->output_data.x->saved_menu_event = event; \
5713 inev.ie.kind = MENU_BAR_ACTIVATE_EVENT; \
5714 XSETFRAME (inev.ie.frame_or_window, f); \
5716 while (0)
5717 #endif
5719 enum
5721 X_EVENT_NORMAL,
5722 X_EVENT_GOTO_OUT,
5723 X_EVENT_DROP
5726 /* Filter events for the current X input method.
5727 DPYINFO is the display this event is for.
5728 EVENT is the X event to filter.
5730 Returns non-zero if the event was filtered, caller shall not process
5731 this event further.
5732 Returns zero if event is wasn't filtered. */
5734 #ifdef HAVE_X_I18N
5735 static int
5736 x_filter_event (struct x_display_info *dpyinfo, XEvent *event)
5738 /* XFilterEvent returns non-zero if the input method has
5739 consumed the event. We pass the frame's X window to
5740 XFilterEvent because that's the one for which the IC
5741 was created. */
5743 struct frame *f1 = x_any_window_to_frame (dpyinfo,
5744 event->xclient.window);
5746 return XFilterEvent (event, f1 ? FRAME_X_WINDOW (f1) : None);
5748 #endif
5750 #ifdef USE_GTK
5751 static int current_count;
5752 static int current_finish;
5753 static struct input_event *current_hold_quit;
5755 /* This is the filter function invoked by the GTK event loop.
5756 It is invoked before the XEvent is translated to a GdkEvent,
5757 so we have a chance to act on the event before GTK. */
5758 static GdkFilterReturn
5759 event_handler_gdk (GdkXEvent *gxev, GdkEvent *ev, gpointer data)
5761 XEvent *xev = (XEvent *) gxev;
5763 BLOCK_INPUT;
5764 if (current_count >= 0)
5766 struct x_display_info *dpyinfo;
5768 dpyinfo = x_display_info_for_display (xev->xany.display);
5770 #ifdef HAVE_X_I18N
5771 /* Filter events for the current X input method.
5772 GTK calls XFilterEvent but not for key press and release,
5773 so we do it here. */
5774 if ((xev->type == KeyPress || xev->type == KeyRelease)
5775 && dpyinfo
5776 && x_filter_event (dpyinfo, xev))
5778 UNBLOCK_INPUT;
5779 return GDK_FILTER_REMOVE;
5781 #endif
5783 if (! dpyinfo)
5784 current_finish = X_EVENT_NORMAL;
5785 else
5786 current_count +=
5787 handle_one_xevent (dpyinfo, xev, &current_finish,
5788 current_hold_quit);
5790 else
5791 current_finish = x_dispatch_event (xev, xev->xany.display);
5793 UNBLOCK_INPUT;
5795 if (current_finish == X_EVENT_GOTO_OUT || current_finish == X_EVENT_DROP)
5796 return GDK_FILTER_REMOVE;
5798 return GDK_FILTER_CONTINUE;
5800 #endif /* USE_GTK */
5803 static void xembed_send_message (struct frame *f, Time,
5804 enum xembed_message,
5805 long detail, long data1, long data2);
5807 /* Handles the XEvent EVENT on display DPYINFO.
5809 *FINISH is X_EVENT_GOTO_OUT if caller should stop reading events.
5810 *FINISH is zero if caller should continue reading events.
5811 *FINISH is X_EVENT_DROP if event should not be passed to the toolkit.
5813 We return the number of characters stored into the buffer. */
5815 static int
5816 handle_one_xevent (struct x_display_info *dpyinfo, XEvent *eventptr,
5817 int *finish, struct input_event *hold_quit)
5819 union {
5820 struct input_event ie;
5821 struct selection_input_event sie;
5822 } inev;
5823 int count = 0;
5824 int do_help = 0;
5825 int nbytes = 0;
5826 struct frame *f = NULL;
5827 struct coding_system coding;
5828 XEvent event = *eventptr;
5829 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
5831 *finish = X_EVENT_NORMAL;
5833 EVENT_INIT (inev.ie);
5834 inev.ie.kind = NO_EVENT;
5835 inev.ie.arg = Qnil;
5837 if (pending_event_wait.eventtype == event.type)
5838 pending_event_wait.eventtype = 0; /* Indicates we got it. */
5840 switch (event.type)
5842 case ClientMessage:
5844 if (event.xclient.message_type
5845 == dpyinfo->Xatom_wm_protocols
5846 && event.xclient.format == 32)
5848 if (event.xclient.data.l[0]
5849 == dpyinfo->Xatom_wm_take_focus)
5851 /* Use x_any_window_to_frame because this
5852 could be the shell widget window
5853 if the frame has no title bar. */
5854 f = x_any_window_to_frame (dpyinfo, event.xclient.window);
5855 #ifdef HAVE_X_I18N
5856 /* Not quite sure this is needed -pd */
5857 if (f && FRAME_XIC (f))
5858 XSetICFocus (FRAME_XIC (f));
5859 #endif
5860 #if 0 /* Emacs sets WM hints whose `input' field is `true'. This
5861 instructs the WM to set the input focus automatically for
5862 Emacs with a call to XSetInputFocus. Setting WM_TAKE_FOCUS
5863 tells the WM to send us a ClientMessage WM_TAKE_FOCUS after
5864 it has set the focus. So, XSetInputFocus below is not
5865 needed.
5867 The call to XSetInputFocus below has also caused trouble. In
5868 cases where the XSetInputFocus done by the WM and the one
5869 below are temporally close (on a fast machine), the call
5870 below can generate additional FocusIn events which confuse
5871 Emacs. */
5873 /* Since we set WM_TAKE_FOCUS, we must call
5874 XSetInputFocus explicitly. But not if f is null,
5875 since that might be an event for a deleted frame. */
5876 if (f)
5878 Display *d = event.xclient.display;
5879 /* Catch and ignore errors, in case window has been
5880 iconified by a window manager such as GWM. */
5881 x_catch_errors (d);
5882 XSetInputFocus (d, event.xclient.window,
5883 /* The ICCCM says this is
5884 the only valid choice. */
5885 RevertToParent,
5886 event.xclient.data.l[1]);
5887 /* This is needed to detect the error
5888 if there is an error. */
5889 XSync (d, False);
5890 x_uncatch_errors ();
5892 /* Not certain about handling scroll bars here */
5893 #endif /* 0 */
5894 goto done;
5897 if (event.xclient.data.l[0]
5898 == dpyinfo->Xatom_wm_save_yourself)
5900 /* Save state modify the WM_COMMAND property to
5901 something which can reinstate us. This notifies
5902 the session manager, who's looking for such a
5903 PropertyNotify. Can restart processing when
5904 a keyboard or mouse event arrives. */
5905 /* If we have a session manager, don't set this.
5906 KDE will then start two Emacsen, one for the
5907 session manager and one for this. */
5908 #ifdef HAVE_X_SM
5909 if (! x_session_have_connection ())
5910 #endif
5912 f = x_top_window_to_frame (dpyinfo,
5913 event.xclient.window);
5914 /* This is just so we only give real data once
5915 for a single Emacs process. */
5916 if (f == SELECTED_FRAME ())
5917 XSetCommand (FRAME_X_DISPLAY (f),
5918 event.xclient.window,
5919 initial_argv, initial_argc);
5920 else if (f)
5921 XSetCommand (FRAME_X_DISPLAY (f),
5922 event.xclient.window,
5923 0, 0);
5925 goto done;
5928 if (event.xclient.data.l[0]
5929 == dpyinfo->Xatom_wm_delete_window)
5931 f = x_any_window_to_frame (dpyinfo,
5932 event.xclient.window);
5933 if (!f)
5934 goto OTHER; /* May be a dialog that is to be removed */
5936 inev.ie.kind = DELETE_WINDOW_EVENT;
5937 XSETFRAME (inev.ie.frame_or_window, f);
5938 goto done;
5941 goto done;
5944 if (event.xclient.message_type
5945 == dpyinfo->Xatom_wm_configure_denied)
5947 goto done;
5950 if (event.xclient.message_type
5951 == dpyinfo->Xatom_wm_window_moved)
5953 int new_x, new_y;
5954 f = x_window_to_frame (dpyinfo, event.xclient.window);
5956 new_x = event.xclient.data.s[0];
5957 new_y = event.xclient.data.s[1];
5959 if (f)
5961 f->left_pos = new_x;
5962 f->top_pos = new_y;
5964 goto done;
5967 #ifdef HACK_EDITRES
5968 if (event.xclient.message_type
5969 == dpyinfo->Xatom_editres)
5971 f = x_any_window_to_frame (dpyinfo, event.xclient.window);
5972 if (f)
5973 _XEditResCheckMessages (f->output_data.x->widget, NULL,
5974 &event, NULL);
5975 goto done;
5977 #endif /* HACK_EDITRES */
5979 if ((event.xclient.message_type
5980 == dpyinfo->Xatom_DONE)
5981 || (event.xclient.message_type
5982 == dpyinfo->Xatom_PAGE))
5984 /* Ghostview job completed. Kill it. We could
5985 reply with "Next" if we received "Page", but we
5986 currently never do because we are interested in
5987 images, only, which should have 1 page. */
5988 Pixmap pixmap = (Pixmap) event.xclient.data.l[1];
5989 f = x_window_to_frame (dpyinfo, event.xclient.window);
5990 if (!f)
5991 goto OTHER;
5992 x_kill_gs_process (pixmap, f);
5993 expose_frame (f, 0, 0, 0, 0);
5994 goto done;
5997 #ifdef USE_TOOLKIT_SCROLL_BARS
5998 /* Scroll bar callbacks send a ClientMessage from which
5999 we construct an input_event. */
6000 if (event.xclient.message_type
6001 == dpyinfo->Xatom_Scrollbar)
6003 x_scroll_bar_to_input_event (&event, &inev.ie);
6004 *finish = X_EVENT_GOTO_OUT;
6005 goto done;
6007 #endif /* USE_TOOLKIT_SCROLL_BARS */
6009 /* XEmbed messages from the embedder (if any). */
6010 if (event.xclient.message_type
6011 == dpyinfo->Xatom_XEMBED)
6013 enum xembed_message msg = event.xclient.data.l[1];
6014 if (msg == XEMBED_FOCUS_IN || msg == XEMBED_FOCUS_OUT)
6015 x_detect_focus_change (dpyinfo, &event, &inev.ie);
6017 *finish = X_EVENT_GOTO_OUT;
6018 goto done;
6021 xft_settings_event (dpyinfo, &event);
6023 f = x_any_window_to_frame (dpyinfo, event.xclient.window);
6024 if (!f)
6025 goto OTHER;
6026 if (x_handle_dnd_message (f, &event.xclient, dpyinfo, &inev.ie))
6027 *finish = X_EVENT_DROP;
6029 break;
6031 case SelectionNotify:
6032 last_user_time = event.xselection.time;
6033 #ifdef USE_X_TOOLKIT
6034 if (! x_window_to_frame (dpyinfo, event.xselection.requestor))
6035 goto OTHER;
6036 #endif /* not USE_X_TOOLKIT */
6037 x_handle_selection_notify (&event.xselection);
6038 break;
6040 case SelectionClear: /* Someone has grabbed ownership. */
6041 last_user_time = event.xselectionclear.time;
6042 #ifdef USE_X_TOOLKIT
6043 if (! x_window_to_frame (dpyinfo, event.xselectionclear.window))
6044 goto OTHER;
6045 #endif /* USE_X_TOOLKIT */
6047 XSelectionClearEvent *eventp = &(event.xselectionclear);
6049 inev.ie.kind = SELECTION_CLEAR_EVENT;
6050 SELECTION_EVENT_DISPLAY (&inev.sie) = eventp->display;
6051 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
6052 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
6053 inev.ie.frame_or_window = Qnil;
6055 break;
6057 case SelectionRequest: /* Someone wants our selection. */
6058 last_user_time = event.xselectionrequest.time;
6059 #ifdef USE_X_TOOLKIT
6060 if (!x_window_to_frame (dpyinfo, event.xselectionrequest.owner))
6061 goto OTHER;
6062 #endif /* USE_X_TOOLKIT */
6064 XSelectionRequestEvent *eventp = &(event.xselectionrequest);
6066 inev.ie.kind = SELECTION_REQUEST_EVENT;
6067 SELECTION_EVENT_DISPLAY (&inev.sie) = eventp->display;
6068 SELECTION_EVENT_REQUESTOR (&inev.sie) = eventp->requestor;
6069 SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
6070 SELECTION_EVENT_TARGET (&inev.sie) = eventp->target;
6071 SELECTION_EVENT_PROPERTY (&inev.sie) = eventp->property;
6072 SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
6073 inev.ie.frame_or_window = Qnil;
6075 break;
6077 case PropertyNotify:
6078 last_user_time = event.xproperty.time;
6079 f = x_top_window_to_frame (dpyinfo, event.xproperty.window);
6080 if (f && event.xproperty.atom == dpyinfo->Xatom_net_wm_state)
6081 x_handle_net_wm_state (f, &event.xproperty);
6083 x_handle_property_notify (&event.xproperty);
6084 xft_settings_event (dpyinfo, &event);
6085 goto OTHER;
6087 case ReparentNotify:
6088 f = x_top_window_to_frame (dpyinfo, event.xreparent.window);
6089 if (f)
6091 int x, y;
6092 f->output_data.x->parent_desc = event.xreparent.parent;
6093 x_real_positions (f, &x, &y);
6094 f->left_pos = x;
6095 f->top_pos = y;
6097 /* Perhaps reparented due to a WM restart. Reset this. */
6098 FRAME_X_DISPLAY_INFO (f)->wm_type = X_WMTYPE_UNKNOWN;
6099 FRAME_X_DISPLAY_INFO (f)->net_supported_window = 0;
6101 goto OTHER;
6103 case Expose:
6104 f = x_window_to_frame (dpyinfo, event.xexpose.window);
6105 if (f)
6107 #ifdef USE_GTK
6108 /* This seems to be needed for GTK 2.6. */
6109 x_clear_area (event.xexpose.display,
6110 event.xexpose.window,
6111 event.xexpose.x, event.xexpose.y,
6112 event.xexpose.width, event.xexpose.height,
6113 FALSE);
6114 #endif
6115 if (f->async_visible == 0)
6117 f->async_visible = 1;
6118 f->async_iconified = 0;
6119 f->output_data.x->has_been_visible = 1;
6120 SET_FRAME_GARBAGED (f);
6122 else
6123 expose_frame (f,
6124 event.xexpose.x, event.xexpose.y,
6125 event.xexpose.width, event.xexpose.height);
6127 else
6129 #ifndef USE_TOOLKIT_SCROLL_BARS
6130 struct scroll_bar *bar;
6131 #endif
6132 #if defined USE_LUCID
6133 /* Submenus of the Lucid menu bar aren't widgets
6134 themselves, so there's no way to dispatch events
6135 to them. Recognize this case separately. */
6137 Widget widget
6138 = x_window_to_menu_bar (event.xexpose.window);
6139 if (widget)
6140 xlwmenu_redisplay (widget);
6142 #endif /* USE_LUCID */
6144 #ifdef USE_TOOLKIT_SCROLL_BARS
6145 /* Dispatch event to the widget. */
6146 goto OTHER;
6147 #else /* not USE_TOOLKIT_SCROLL_BARS */
6148 bar = x_window_to_scroll_bar (event.xexpose.display,
6149 event.xexpose.window);
6151 if (bar)
6152 x_scroll_bar_expose (bar, &event);
6153 #ifdef USE_X_TOOLKIT
6154 else
6155 goto OTHER;
6156 #endif /* USE_X_TOOLKIT */
6157 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6159 break;
6161 case GraphicsExpose: /* This occurs when an XCopyArea's
6162 source area was obscured or not
6163 available. */
6164 f = x_window_to_frame (dpyinfo, event.xgraphicsexpose.drawable);
6165 if (f)
6167 expose_frame (f,
6168 event.xgraphicsexpose.x, event.xgraphicsexpose.y,
6169 event.xgraphicsexpose.width,
6170 event.xgraphicsexpose.height);
6172 #ifdef USE_X_TOOLKIT
6173 else
6174 goto OTHER;
6175 #endif /* USE_X_TOOLKIT */
6176 break;
6178 case NoExpose: /* This occurs when an XCopyArea's
6179 source area was completely
6180 available. */
6181 break;
6183 case UnmapNotify:
6184 /* Redo the mouse-highlight after the tooltip has gone. */
6185 if (event.xmap.window == tip_window)
6187 tip_window = 0;
6188 redo_mouse_highlight ();
6191 f = x_top_window_to_frame (dpyinfo, event.xunmap.window);
6192 if (f) /* F may no longer exist if
6193 the frame was deleted. */
6195 /* While a frame is unmapped, display generation is
6196 disabled; you don't want to spend time updating a
6197 display that won't ever be seen. */
6198 f->async_visible = 0;
6199 /* We can't distinguish, from the event, whether the window
6200 has become iconified or invisible. So assume, if it
6201 was previously visible, than now it is iconified.
6202 But x_make_frame_invisible clears both
6203 the visible flag and the iconified flag;
6204 and that way, we know the window is not iconified now. */
6205 if (FRAME_VISIBLE_P (f) || FRAME_ICONIFIED_P (f))
6207 f->async_iconified = 1;
6209 inev.ie.kind = ICONIFY_EVENT;
6210 XSETFRAME (inev.ie.frame_or_window, f);
6213 goto OTHER;
6215 case MapNotify:
6216 if (event.xmap.window == tip_window)
6217 /* The tooltip has been drawn already. Avoid
6218 the SET_FRAME_GARBAGED below. */
6219 goto OTHER;
6221 /* We use x_top_window_to_frame because map events can
6222 come for sub-windows and they don't mean that the
6223 frame is visible. */
6224 f = x_top_window_to_frame (dpyinfo, event.xmap.window);
6225 if (f)
6227 /* wait_reading_process_output will notice this and update
6228 the frame's display structures.
6229 If we where iconified, we should not set garbaged,
6230 because that stops redrawing on Expose events. This looks
6231 bad if we are called from a recursive event loop
6232 (x_dispatch_event), for example when a dialog is up. */
6233 if (! f->async_iconified)
6234 SET_FRAME_GARBAGED (f);
6236 /* Check if fullscreen was specified before we where mapped the
6237 first time, i.e. from the command line. */
6238 if (!f->output_data.x->has_been_visible)
6239 x_check_fullscreen (f);
6241 f->async_visible = 1;
6242 f->async_iconified = 0;
6243 f->output_data.x->has_been_visible = 1;
6245 if (f->iconified)
6247 inev.ie.kind = DEICONIFY_EVENT;
6248 XSETFRAME (inev.ie.frame_or_window, f);
6250 else if (! NILP (Vframe_list)
6251 && ! NILP (XCDR (Vframe_list)))
6252 /* Force a redisplay sooner or later
6253 to update the frame titles
6254 in case this is the second frame. */
6255 record_asynch_buffer_change ();
6257 #ifdef USE_GTK
6258 xg_frame_resized (f, -1, -1);
6259 #endif
6261 goto OTHER;
6263 case KeyPress:
6265 last_user_time = event.xkey.time;
6266 ignore_next_mouse_click_timeout = 0;
6268 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
6269 /* Dispatch KeyPress events when in menu. */
6270 if (popup_activated ())
6271 goto OTHER;
6272 #endif
6274 f = x_any_window_to_frame (dpyinfo, event.xkey.window);
6276 /* If mouse-highlight is an integer, input clears out
6277 mouse highlighting. */
6278 if (!hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight)
6279 && (f == 0
6280 || !EQ (f->tool_bar_window, hlinfo->mouse_face_window)))
6282 clear_mouse_face (hlinfo);
6283 hlinfo->mouse_face_hidden = 1;
6286 #if defined USE_MOTIF && defined USE_TOOLKIT_SCROLL_BARS
6287 if (f == 0)
6289 /* Scroll bars consume key events, but we want
6290 the keys to go to the scroll bar's frame. */
6291 Widget widget = XtWindowToWidget (dpyinfo->display,
6292 event.xkey.window);
6293 if (widget && XmIsScrollBar (widget))
6295 widget = XtParent (widget);
6296 f = x_any_window_to_frame (dpyinfo, XtWindow (widget));
6299 #endif /* USE_MOTIF and USE_TOOLKIT_SCROLL_BARS */
6301 if (f != 0)
6303 KeySym keysym, orig_keysym;
6304 /* al%imercury@uunet.uu.net says that making this 81
6305 instead of 80 fixed a bug whereby meta chars made
6306 his Emacs hang.
6308 It seems that some version of XmbLookupString has
6309 a bug of not returning XBufferOverflow in
6310 status_return even if the input is too long to
6311 fit in 81 bytes. So, we must prepare sufficient
6312 bytes for copy_buffer. 513 bytes (256 chars for
6313 two-byte character set) seems to be a fairly good
6314 approximation. -- 2000.8.10 handa@etl.go.jp */
6315 unsigned char copy_buffer[513];
6316 unsigned char *copy_bufptr = copy_buffer;
6317 int copy_bufsiz = sizeof (copy_buffer);
6318 int modifiers;
6319 Lisp_Object coding_system = Qlatin_1;
6320 Lisp_Object c;
6322 #ifdef USE_GTK
6323 /* Don't pass keys to GTK. A Tab will shift focus to the
6324 tool bar in GTK 2.4. Keys will still go to menus and
6325 dialogs because in that case popup_activated is TRUE
6326 (see above). */
6327 *finish = X_EVENT_DROP;
6328 #endif
6330 event.xkey.state
6331 |= x_emacs_to_x_modifiers (FRAME_X_DISPLAY_INFO (f),
6332 extra_keyboard_modifiers);
6333 modifiers = event.xkey.state;
6335 /* This will have to go some day... */
6337 /* make_lispy_event turns chars into control chars.
6338 Don't do it here because XLookupString is too eager. */
6339 event.xkey.state &= ~ControlMask;
6340 event.xkey.state &= ~(dpyinfo->meta_mod_mask
6341 | dpyinfo->super_mod_mask
6342 | dpyinfo->hyper_mod_mask
6343 | dpyinfo->alt_mod_mask);
6345 /* In case Meta is ComposeCharacter,
6346 clear its status. According to Markus Ehrnsperger
6347 Markus.Ehrnsperger@lehrstuhl-bross.physik.uni-muenchen.de
6348 this enables ComposeCharacter to work whether or
6349 not it is combined with Meta. */
6350 if (modifiers & dpyinfo->meta_mod_mask)
6351 memset (&compose_status, 0, sizeof (compose_status));
6353 #ifdef HAVE_X_I18N
6354 if (FRAME_XIC (f))
6356 Status status_return;
6358 coding_system = Vlocale_coding_system;
6359 nbytes = XmbLookupString (FRAME_XIC (f),
6360 &event.xkey, (char *) copy_bufptr,
6361 copy_bufsiz, &keysym,
6362 &status_return);
6363 if (status_return == XBufferOverflow)
6365 copy_bufsiz = nbytes + 1;
6366 copy_bufptr = (unsigned char *) alloca (copy_bufsiz);
6367 nbytes = XmbLookupString (FRAME_XIC (f),
6368 &event.xkey, (char *) copy_bufptr,
6369 copy_bufsiz, &keysym,
6370 &status_return);
6372 /* Xutf8LookupString is a new but already deprecated interface. -stef */
6373 if (status_return == XLookupNone)
6374 break;
6375 else if (status_return == XLookupChars)
6377 keysym = NoSymbol;
6378 modifiers = 0;
6380 else if (status_return != XLookupKeySym
6381 && status_return != XLookupBoth)
6382 abort ();
6384 else
6385 nbytes = XLookupString (&event.xkey, (char *) copy_bufptr,
6386 copy_bufsiz, &keysym,
6387 &compose_status);
6388 #else
6389 nbytes = XLookupString (&event.xkey, (char *) copy_bufptr,
6390 copy_bufsiz, &keysym,
6391 &compose_status);
6392 #endif
6394 /* If not using XIM/XIC, and a compose sequence is in progress,
6395 we break here. Otherwise, chars_matched is always 0. */
6396 if (compose_status.chars_matched > 0 && nbytes == 0)
6397 break;
6399 memset (&compose_status, 0, sizeof (compose_status));
6400 orig_keysym = keysym;
6402 /* Common for all keysym input events. */
6403 XSETFRAME (inev.ie.frame_or_window, f);
6404 inev.ie.modifiers
6405 = x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO (f), modifiers);
6406 inev.ie.timestamp = event.xkey.time;
6408 /* First deal with keysyms which have defined
6409 translations to characters. */
6410 if (keysym >= 32 && keysym < 128)
6411 /* Avoid explicitly decoding each ASCII character. */
6413 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
6414 inev.ie.code = keysym;
6415 goto done_keysym;
6418 /* Keysyms directly mapped to Unicode characters. */
6419 if (keysym >= 0x01000000 && keysym <= 0x0110FFFF)
6421 if (keysym < 0x01000080)
6422 inev.ie.kind = ASCII_KEYSTROKE_EVENT;
6423 else
6424 inev.ie.kind = MULTIBYTE_CHAR_KEYSTROKE_EVENT;
6425 inev.ie.code = keysym & 0xFFFFFF;
6426 goto done_keysym;
6429 /* Now non-ASCII. */
6430 if (HASH_TABLE_P (Vx_keysym_table)
6431 && (NATNUMP (c = Fgethash (make_number (keysym),
6432 Vx_keysym_table,
6433 Qnil))))
6435 inev.ie.kind = (SINGLE_BYTE_CHAR_P (XFASTINT (c))
6436 ? ASCII_KEYSTROKE_EVENT
6437 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
6438 inev.ie.code = XFASTINT (c);
6439 goto done_keysym;
6442 /* Random non-modifier sorts of keysyms. */
6443 if (((keysym >= XK_BackSpace && keysym <= XK_Escape)
6444 || keysym == XK_Delete
6445 #ifdef XK_ISO_Left_Tab
6446 || (keysym >= XK_ISO_Left_Tab
6447 && keysym <= XK_ISO_Enter)
6448 #endif
6449 || IsCursorKey (keysym) /* 0xff50 <= x < 0xff60 */
6450 || IsMiscFunctionKey (keysym) /* 0xff60 <= x < VARIES */
6451 #ifdef HPUX
6452 /* This recognizes the "extended function
6453 keys". It seems there's no cleaner way.
6454 Test IsModifierKey to avoid handling
6455 mode_switch incorrectly. */
6456 || (XK_Select <= keysym && keysym < XK_KP_Space)
6457 #endif
6458 #ifdef XK_dead_circumflex
6459 || orig_keysym == XK_dead_circumflex
6460 #endif
6461 #ifdef XK_dead_grave
6462 || orig_keysym == XK_dead_grave
6463 #endif
6464 #ifdef XK_dead_tilde
6465 || orig_keysym == XK_dead_tilde
6466 #endif
6467 #ifdef XK_dead_diaeresis
6468 || orig_keysym == XK_dead_diaeresis
6469 #endif
6470 #ifdef XK_dead_macron
6471 || orig_keysym == XK_dead_macron
6472 #endif
6473 #ifdef XK_dead_degree
6474 || orig_keysym == XK_dead_degree
6475 #endif
6476 #ifdef XK_dead_acute
6477 || orig_keysym == XK_dead_acute
6478 #endif
6479 #ifdef XK_dead_cedilla
6480 || orig_keysym == XK_dead_cedilla
6481 #endif
6482 #ifdef XK_dead_breve
6483 || orig_keysym == XK_dead_breve
6484 #endif
6485 #ifdef XK_dead_ogonek
6486 || orig_keysym == XK_dead_ogonek
6487 #endif
6488 #ifdef XK_dead_caron
6489 || orig_keysym == XK_dead_caron
6490 #endif
6491 #ifdef XK_dead_doubleacute
6492 || orig_keysym == XK_dead_doubleacute
6493 #endif
6494 #ifdef XK_dead_abovedot
6495 || orig_keysym == XK_dead_abovedot
6496 #endif
6497 || IsKeypadKey (keysym) /* 0xff80 <= x < 0xffbe */
6498 || IsFunctionKey (keysym) /* 0xffbe <= x < 0xffe1 */
6499 /* Any "vendor-specific" key is ok. */
6500 || (orig_keysym & (1 << 28))
6501 || (keysym != NoSymbol && nbytes == 0))
6502 && ! (IsModifierKey (orig_keysym)
6503 /* The symbols from XK_ISO_Lock
6504 to XK_ISO_Last_Group_Lock
6505 don't have real modifiers but
6506 should be treated similarly to
6507 Mode_switch by Emacs. */
6508 #if defined XK_ISO_Lock && defined XK_ISO_Last_Group_Lock
6509 || (XK_ISO_Lock <= orig_keysym
6510 && orig_keysym <= XK_ISO_Last_Group_Lock)
6511 #endif
6514 STORE_KEYSYM_FOR_DEBUG (keysym);
6515 /* make_lispy_event will convert this to a symbolic
6516 key. */
6517 inev.ie.kind = NON_ASCII_KEYSTROKE_EVENT;
6518 inev.ie.code = keysym;
6519 goto done_keysym;
6522 { /* Raw bytes, not keysym. */
6523 register int i;
6524 int nchars, len;
6526 for (i = 0, nchars = 0; i < nbytes; i++)
6528 if (ASCII_BYTE_P (copy_bufptr[i]))
6529 nchars++;
6530 STORE_KEYSYM_FOR_DEBUG (copy_bufptr[i]);
6533 if (nchars < nbytes)
6535 /* Decode the input data. */
6536 int require;
6538 /* The input should be decoded with `coding_system'
6539 which depends on which X*LookupString function
6540 we used just above and the locale. */
6541 setup_coding_system (coding_system, &coding);
6542 coding.src_multibyte = 0;
6543 coding.dst_multibyte = 1;
6544 /* The input is converted to events, thus we can't
6545 handle composition. Anyway, there's no XIM that
6546 gives us composition information. */
6547 coding.common_flags &= ~CODING_ANNOTATION_MASK;
6549 require = MAX_MULTIBYTE_LENGTH * nbytes;
6550 coding.destination = alloca (require);
6551 coding.dst_bytes = require;
6552 coding.mode |= CODING_MODE_LAST_BLOCK;
6553 decode_coding_c_string (&coding, copy_bufptr, nbytes, Qnil);
6554 nbytes = coding.produced;
6555 nchars = coding.produced_char;
6556 copy_bufptr = coding.destination;
6559 /* Convert the input data to a sequence of
6560 character events. */
6561 for (i = 0; i < nbytes; i += len)
6563 int ch;
6564 if (nchars == nbytes)
6565 ch = copy_bufptr[i], len = 1;
6566 else
6567 ch = STRING_CHAR_AND_LENGTH (copy_bufptr + i, len);
6568 inev.ie.kind = (SINGLE_BYTE_CHAR_P (ch)
6569 ? ASCII_KEYSTROKE_EVENT
6570 : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
6571 inev.ie.code = ch;
6572 kbd_buffer_store_event_hold (&inev.ie, hold_quit);
6575 count += nchars;
6577 inev.ie.kind = NO_EVENT; /* Already stored above. */
6579 if (keysym == NoSymbol)
6580 break;
6583 done_keysym:
6584 #ifdef HAVE_X_I18N
6585 /* Don't dispatch this event since XtDispatchEvent calls
6586 XFilterEvent, and two calls in a row may freeze the
6587 client. */
6588 break;
6589 #else
6590 goto OTHER;
6591 #endif
6593 case KeyRelease:
6594 last_user_time = event.xkey.time;
6595 #ifdef HAVE_X_I18N
6596 /* Don't dispatch this event since XtDispatchEvent calls
6597 XFilterEvent, and two calls in a row may freeze the
6598 client. */
6599 break;
6600 #else
6601 goto OTHER;
6602 #endif
6604 case EnterNotify:
6605 last_user_time = event.xcrossing.time;
6606 x_detect_focus_change (dpyinfo, &event, &inev.ie);
6608 f = x_any_window_to_frame (dpyinfo, event.xcrossing.window);
6610 if (f && x_mouse_click_focus_ignore_position)
6611 ignore_next_mouse_click_timeout = event.xmotion.time + 200;
6613 /* EnterNotify counts as mouse movement,
6614 so update things that depend on mouse position. */
6615 if (f && !f->output_data.x->hourglass_p)
6616 note_mouse_movement (f, &event.xmotion);
6617 #ifdef USE_GTK
6618 /* We may get an EnterNotify on the buttons in the toolbar. In that
6619 case we moved out of any highlighted area and need to note this. */
6620 if (!f && last_mouse_glyph_frame)
6621 note_mouse_movement (last_mouse_glyph_frame, &event.xmotion);
6622 #endif
6623 goto OTHER;
6625 case FocusIn:
6626 x_detect_focus_change (dpyinfo, &event, &inev.ie);
6627 goto OTHER;
6629 case LeaveNotify:
6630 last_user_time = event.xcrossing.time;
6631 x_detect_focus_change (dpyinfo, &event, &inev.ie);
6633 f = x_top_window_to_frame (dpyinfo, event.xcrossing.window);
6634 if (f)
6636 if (f == hlinfo->mouse_face_mouse_frame)
6638 /* If we move outside the frame, then we're
6639 certainly no longer on any text in the frame. */
6640 clear_mouse_face (hlinfo);
6641 hlinfo->mouse_face_mouse_frame = 0;
6644 /* Generate a nil HELP_EVENT to cancel a help-echo.
6645 Do it only if there's something to cancel.
6646 Otherwise, the startup message is cleared when
6647 the mouse leaves the frame. */
6648 if (any_help_event_p)
6649 do_help = -1;
6651 #ifdef USE_GTK
6652 /* See comment in EnterNotify above */
6653 else if (last_mouse_glyph_frame)
6654 note_mouse_movement (last_mouse_glyph_frame, &event.xmotion);
6655 #endif
6656 goto OTHER;
6658 case FocusOut:
6659 x_detect_focus_change (dpyinfo, &event, &inev.ie);
6660 goto OTHER;
6662 case MotionNotify:
6664 last_user_time = event.xmotion.time;
6665 previous_help_echo_string = help_echo_string;
6666 help_echo_string = Qnil;
6668 if (dpyinfo->grabbed && last_mouse_frame
6669 && FRAME_LIVE_P (last_mouse_frame))
6670 f = last_mouse_frame;
6671 else
6672 f = x_window_to_frame (dpyinfo, event.xmotion.window);
6674 if (hlinfo->mouse_face_hidden)
6676 hlinfo->mouse_face_hidden = 0;
6677 clear_mouse_face (hlinfo);
6680 #ifdef USE_GTK
6681 if (f && xg_event_is_for_scrollbar (f, &event))
6682 f = 0;
6683 #endif
6684 if (f)
6687 /* Generate SELECT_WINDOW_EVENTs when needed.
6688 Don't let popup menus influence things (bug#1261). */
6689 if (!NILP (Vmouse_autoselect_window) && !popup_activated ())
6691 Lisp_Object window;
6693 window = window_from_coordinates (f,
6694 event.xmotion.x, event.xmotion.y,
6695 0, 0);
6697 /* Window will be selected only when it is not selected now and
6698 last mouse movement event was not in it. Minibuffer window
6699 will be selected only when it is active. */
6700 if (WINDOWP (window)
6701 && !EQ (window, last_window)
6702 && !EQ (window, selected_window)
6703 /* For click-to-focus window managers
6704 create event iff we don't leave the
6705 selected frame. */
6706 && (focus_follows_mouse
6707 || (EQ (XWINDOW (window)->frame,
6708 XWINDOW (selected_window)->frame))))
6710 inev.ie.kind = SELECT_WINDOW_EVENT;
6711 inev.ie.frame_or_window = window;
6714 last_window=window;
6716 if (!note_mouse_movement (f, &event.xmotion))
6717 help_echo_string = previous_help_echo_string;
6719 else
6721 #ifndef USE_TOOLKIT_SCROLL_BARS
6722 struct scroll_bar *bar
6723 = x_window_to_scroll_bar (event.xmotion.display,
6724 event.xmotion.window);
6726 if (bar)
6727 x_scroll_bar_note_movement (bar, &event);
6728 #endif /* USE_TOOLKIT_SCROLL_BARS */
6730 /* If we move outside the frame, then we're
6731 certainly no longer on any text in the frame. */
6732 clear_mouse_face (hlinfo);
6735 /* If the contents of the global variable help_echo_string
6736 has changed, generate a HELP_EVENT. */
6737 if (!NILP (help_echo_string)
6738 || !NILP (previous_help_echo_string))
6739 do_help = 1;
6740 goto OTHER;
6743 case ConfigureNotify:
6744 f = x_top_window_to_frame (dpyinfo, event.xconfigure.window);
6745 #ifdef USE_GTK
6746 if (!f
6747 && (f = x_any_window_to_frame (dpyinfo, event.xconfigure.window))
6748 && event.xconfigure.window == FRAME_X_WINDOW (f))
6750 xg_frame_resized (f, event.xconfigure.width,
6751 event.xconfigure.height);
6752 f = 0;
6754 #endif
6755 if (f)
6757 #ifndef USE_X_TOOLKIT
6758 #ifndef USE_GTK
6759 int rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, event.xconfigure.height);
6760 int columns = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, event.xconfigure.width);
6762 /* In the toolkit version, change_frame_size
6763 is called by the code that handles resizing
6764 of the EmacsFrame widget. */
6766 /* Even if the number of character rows and columns has
6767 not changed, the font size may have changed, so we need
6768 to check the pixel dimensions as well. */
6769 if (columns != FRAME_COLS (f)
6770 || rows != FRAME_LINES (f)
6771 || event.xconfigure.width != FRAME_PIXEL_WIDTH (f)
6772 || event.xconfigure.height != FRAME_PIXEL_HEIGHT (f))
6774 change_frame_size (f, rows, columns, 0, 1, 0);
6775 SET_FRAME_GARBAGED (f);
6776 cancel_mouse_face (f);
6779 FRAME_PIXEL_WIDTH (f) = event.xconfigure.width;
6780 FRAME_PIXEL_HEIGHT (f) = event.xconfigure.height;
6781 #endif /* not USE_GTK */
6782 #endif
6784 #ifdef USE_GTK
6785 /* GTK creates windows but doesn't map them.
6786 Only get real positions when mapped. */
6787 if (FRAME_GTK_OUTER_WIDGET (f)
6788 && gtk_widget_get_mapped (FRAME_GTK_OUTER_WIDGET (f)))
6789 #endif
6791 x_real_positions (f, &f->left_pos, &f->top_pos);
6794 #ifdef HAVE_X_I18N
6795 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMStatusArea))
6796 xic_set_statusarea (f);
6797 #endif
6800 goto OTHER;
6802 case ButtonRelease:
6803 case ButtonPress:
6805 /* If we decide we want to generate an event to be seen
6806 by the rest of Emacs, we put it here. */
6807 int tool_bar_p = 0;
6809 memset (&compose_status, 0, sizeof (compose_status));
6810 last_mouse_glyph_frame = 0;
6811 last_user_time = event.xbutton.time;
6813 if (dpyinfo->grabbed
6814 && last_mouse_frame
6815 && FRAME_LIVE_P (last_mouse_frame))
6816 f = last_mouse_frame;
6817 else
6818 f = x_window_to_frame (dpyinfo, event.xbutton.window);
6820 #ifdef USE_GTK
6821 if (f && xg_event_is_for_scrollbar (f, &event))
6822 f = 0;
6823 #endif
6824 if (f)
6826 /* Is this in the tool-bar? */
6827 if (WINDOWP (f->tool_bar_window)
6828 && WINDOW_TOTAL_LINES (XWINDOW (f->tool_bar_window)))
6830 Lisp_Object window;
6831 int x = event.xbutton.x;
6832 int y = event.xbutton.y;
6834 window = window_from_coordinates (f, x, y, 0, 1);
6835 tool_bar_p = EQ (window, f->tool_bar_window);
6837 if (tool_bar_p && event.xbutton.button < 4)
6839 handle_tool_bar_click (f, x, y,
6840 event.xbutton.type == ButtonPress,
6841 x_x_to_emacs_modifiers (dpyinfo,
6842 event.xbutton.state));
6846 if (!tool_bar_p)
6847 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
6848 if (! popup_activated ())
6849 #endif
6851 if (ignore_next_mouse_click_timeout)
6853 if (event.type == ButtonPress
6854 && (int)(event.xbutton.time - ignore_next_mouse_click_timeout) > 0)
6856 ignore_next_mouse_click_timeout = 0;
6857 construct_mouse_click (&inev.ie, &event.xbutton, f);
6859 if (event.type == ButtonRelease)
6860 ignore_next_mouse_click_timeout = 0;
6862 else
6863 construct_mouse_click (&inev.ie, &event.xbutton, f);
6865 if (FRAME_X_EMBEDDED_P (f))
6866 xembed_send_message (f, event.xbutton.time,
6867 XEMBED_REQUEST_FOCUS, 0, 0, 0);
6869 else
6871 struct scroll_bar *bar
6872 = x_window_to_scroll_bar (event.xbutton.display,
6873 event.xbutton.window);
6875 #ifdef USE_TOOLKIT_SCROLL_BARS
6876 /* Make the "Ctrl-Mouse-2 splits window" work for toolkit
6877 scroll bars. */
6878 if (bar && event.xbutton.state & ControlMask)
6880 x_scroll_bar_handle_click (bar, &event, &inev.ie);
6881 *finish = X_EVENT_DROP;
6883 #else /* not USE_TOOLKIT_SCROLL_BARS */
6884 if (bar)
6885 x_scroll_bar_handle_click (bar, &event, &inev.ie);
6886 #endif /* not USE_TOOLKIT_SCROLL_BARS */
6889 if (event.type == ButtonPress)
6891 dpyinfo->grabbed |= (1 << event.xbutton.button);
6892 last_mouse_frame = f;
6894 if (!tool_bar_p)
6895 last_tool_bar_item = -1;
6897 else
6898 dpyinfo->grabbed &= ~(1 << event.xbutton.button);
6900 /* Ignore any mouse motion that happened before this event;
6901 any subsequent mouse-movement Emacs events should reflect
6902 only motion after the ButtonPress/Release. */
6903 if (f != 0)
6904 f->mouse_moved = 0;
6906 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
6907 f = x_menubar_window_to_frame (dpyinfo, &event);
6908 /* For a down-event in the menu bar,
6909 don't pass it to Xt right now.
6910 Instead, save it away
6911 and we will pass it to Xt from kbd_buffer_get_event.
6912 That way, we can run some Lisp code first. */
6913 if (! popup_activated ()
6914 #ifdef USE_GTK
6915 /* Gtk+ menus only react to the first three buttons. */
6916 && event.xbutton.button < 3
6917 #endif
6918 && f && event.type == ButtonPress
6919 /* Verify the event is really within the menu bar
6920 and not just sent to it due to grabbing. */
6921 && event.xbutton.x >= 0
6922 && event.xbutton.x < FRAME_PIXEL_WIDTH (f)
6923 && event.xbutton.y >= 0
6924 && event.xbutton.y < f->output_data.x->menubar_height
6925 && event.xbutton.same_screen)
6927 SET_SAVED_BUTTON_EVENT;
6928 XSETFRAME (last_mouse_press_frame, f);
6929 *finish = X_EVENT_DROP;
6931 else if (event.type == ButtonPress)
6933 last_mouse_press_frame = Qnil;
6934 goto OTHER;
6936 else
6937 goto OTHER;
6938 #endif /* USE_X_TOOLKIT || USE_GTK */
6940 break;
6942 case CirculateNotify:
6943 goto OTHER;
6945 case CirculateRequest:
6946 goto OTHER;
6948 case VisibilityNotify:
6949 goto OTHER;
6951 case MappingNotify:
6952 /* Someone has changed the keyboard mapping - update the
6953 local cache. */
6954 switch (event.xmapping.request)
6956 case MappingModifier:
6957 x_find_modifier_meanings (dpyinfo);
6958 /* This is meant to fall through. */
6959 case MappingKeyboard:
6960 XRefreshKeyboardMapping (&event.xmapping);
6962 goto OTHER;
6964 case DestroyNotify:
6965 xft_settings_event (dpyinfo, &event);
6966 break;
6968 default:
6969 OTHER:
6970 #ifdef USE_X_TOOLKIT
6971 BLOCK_INPUT;
6972 if (*finish != X_EVENT_DROP)
6973 XtDispatchEvent (&event);
6974 UNBLOCK_INPUT;
6975 #endif /* USE_X_TOOLKIT */
6976 break;
6979 done:
6980 if (inev.ie.kind != NO_EVENT)
6982 kbd_buffer_store_event_hold (&inev.ie, hold_quit);
6983 count++;
6986 if (do_help
6987 && !(hold_quit && hold_quit->kind != NO_EVENT))
6989 Lisp_Object frame;
6991 if (f)
6992 XSETFRAME (frame, f);
6993 else
6994 frame = Qnil;
6996 if (do_help > 0)
6998 any_help_event_p = 1;
6999 gen_help_event (help_echo_string, frame, help_echo_window,
7000 help_echo_object, help_echo_pos);
7002 else
7004 help_echo_string = Qnil;
7005 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
7007 count++;
7010 *eventptr = event;
7011 return count;
7014 #if defined USE_GTK || defined USE_X_TOOLKIT
7016 /* Handles the XEvent EVENT on display DISPLAY.
7017 This is used for event loops outside the normal event handling,
7018 i.e. looping while a popup menu or a dialog is posted.
7020 Returns the value handle_one_xevent sets in the finish argument. */
7022 x_dispatch_event (XEvent *event, Display *display)
7024 struct x_display_info *dpyinfo;
7025 int finish = X_EVENT_NORMAL;
7027 dpyinfo = x_display_info_for_display (display);
7029 if (dpyinfo)
7030 handle_one_xevent (dpyinfo, event, &finish, 0);
7032 return finish;
7034 #endif
7037 /* Read events coming from the X server.
7038 This routine is called by the SIGIO handler.
7039 We return as soon as there are no more events to be read.
7041 We return the number of characters stored into the buffer,
7042 thus pretending to be `read' (except the characters we store
7043 in the keyboard buffer can be multibyte, so are not necessarily
7044 C chars).
7046 EXPECTED is nonzero if the caller knows input is available. */
7048 static int
7049 XTread_socket (struct terminal *terminal, int expected, struct input_event *hold_quit)
7051 int count = 0;
7052 int event_found = 0;
7054 if (interrupt_input_blocked)
7056 interrupt_input_pending = 1;
7057 #ifdef SYNC_INPUT
7058 pending_signals = 1;
7059 #endif
7060 return -1;
7063 interrupt_input_pending = 0;
7064 #ifdef SYNC_INPUT
7065 pending_signals = pending_atimers;
7066 #endif
7067 BLOCK_INPUT;
7069 /* So people can tell when we have read the available input. */
7070 input_signal_count++;
7072 ++handling_signal;
7074 /* For debugging, this gives a way to fake an I/O error. */
7075 if (terminal->display_info.x == XTread_socket_fake_io_error)
7077 XTread_socket_fake_io_error = 0;
7078 x_io_error_quitter (terminal->display_info.x->display);
7081 #ifndef USE_GTK
7082 while (XPending (terminal->display_info.x->display))
7084 int finish;
7085 XEvent event;
7087 XNextEvent (terminal->display_info.x->display, &event);
7089 #ifdef HAVE_X_I18N
7090 /* Filter events for the current X input method. */
7091 if (x_filter_event (terminal->display_info.x, &event))
7092 continue;
7093 #endif
7094 event_found = 1;
7096 count += handle_one_xevent (terminal->display_info.x,
7097 &event, &finish, hold_quit);
7099 if (finish == X_EVENT_GOTO_OUT)
7100 goto out;
7103 out:;
7105 #else /* USE_GTK */
7107 /* For GTK we must use the GTK event loop. But XEvents gets passed
7108 to our filter function above, and then to the big event switch.
7109 We use a bunch of globals to communicate with our filter function,
7110 that is kind of ugly, but it works.
7112 There is no way to do one display at the time, GTK just does events
7113 from all displays. */
7115 while (gtk_events_pending ())
7117 current_count = count;
7118 current_hold_quit = hold_quit;
7120 gtk_main_iteration ();
7122 count = current_count;
7123 current_count = -1;
7124 current_hold_quit = 0;
7126 if (current_finish == X_EVENT_GOTO_OUT)
7127 break;
7129 #endif /* USE_GTK */
7131 /* On some systems, an X bug causes Emacs to get no more events
7132 when the window is destroyed. Detect that. (1994.) */
7133 if (! event_found)
7135 /* Emacs and the X Server eats up CPU time if XNoOp is done every time.
7136 One XNOOP in 100 loops will make Emacs terminate.
7137 B. Bretthauer, 1994 */
7138 x_noop_count++;
7139 if (x_noop_count >= 100)
7141 x_noop_count=0;
7143 if (next_noop_dpyinfo == 0)
7144 next_noop_dpyinfo = x_display_list;
7146 XNoOp (next_noop_dpyinfo->display);
7148 /* Each time we get here, cycle through the displays now open. */
7149 next_noop_dpyinfo = next_noop_dpyinfo->next;
7153 /* If the focus was just given to an auto-raising frame,
7154 raise it now. */
7155 /* ??? This ought to be able to handle more than one such frame. */
7156 if (pending_autoraise_frame)
7158 x_raise_frame (pending_autoraise_frame);
7159 pending_autoraise_frame = 0;
7162 --handling_signal;
7163 UNBLOCK_INPUT;
7165 return count;
7171 /***********************************************************************
7172 Text Cursor
7173 ***********************************************************************/
7175 /* Set clipping for output in glyph row ROW. W is the window in which
7176 we operate. GC is the graphics context to set clipping in.
7178 ROW may be a text row or, e.g., a mode line. Text rows must be
7179 clipped to the interior of the window dedicated to text display,
7180 mode lines must be clipped to the whole window. */
7182 static void
7183 x_clip_to_row (struct window *w, struct glyph_row *row, int area, GC gc)
7185 struct frame *f = XFRAME (WINDOW_FRAME (w));
7186 XRectangle clip_rect;
7187 int window_x, window_y, window_width;
7189 window_box (w, area, &window_x, &window_y, &window_width, 0);
7191 clip_rect.x = window_x;
7192 clip_rect.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
7193 clip_rect.y = max (clip_rect.y, window_y);
7194 clip_rect.width = window_width;
7195 clip_rect.height = row->visible_height;
7197 XSetClipRectangles (FRAME_X_DISPLAY (f), gc, 0, 0, &clip_rect, 1, Unsorted);
7201 /* Draw a hollow box cursor on window W in glyph row ROW. */
7203 static void
7204 x_draw_hollow_cursor (struct window *w, struct glyph_row *row)
7206 struct frame *f = XFRAME (WINDOW_FRAME (w));
7207 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
7208 Display *dpy = FRAME_X_DISPLAY (f);
7209 int x, y, wd, h;
7210 XGCValues xgcv;
7211 struct glyph *cursor_glyph;
7212 GC gc;
7214 /* Get the glyph the cursor is on. If we can't tell because
7215 the current matrix is invalid or such, give up. */
7216 cursor_glyph = get_phys_cursor_glyph (w);
7217 if (cursor_glyph == NULL)
7218 return;
7220 /* Compute frame-relative coordinates for phys cursor. */
7221 get_phys_cursor_geometry (w, row, cursor_glyph, &x, &y, &h);
7222 wd = w->phys_cursor_width;
7224 /* The foreground of cursor_gc is typically the same as the normal
7225 background color, which can cause the cursor box to be invisible. */
7226 xgcv.foreground = f->output_data.x->cursor_pixel;
7227 if (dpyinfo->scratch_cursor_gc)
7228 XChangeGC (dpy, dpyinfo->scratch_cursor_gc, GCForeground, &xgcv);
7229 else
7230 dpyinfo->scratch_cursor_gc = XCreateGC (dpy, FRAME_X_WINDOW (f),
7231 GCForeground, &xgcv);
7232 gc = dpyinfo->scratch_cursor_gc;
7234 /* Set clipping, draw the rectangle, and reset clipping again. */
7235 x_clip_to_row (w, row, TEXT_AREA, gc);
7236 XDrawRectangle (dpy, FRAME_X_WINDOW (f), gc, x, y, wd, h - 1);
7237 XSetClipMask (dpy, gc, None);
7241 /* Draw a bar cursor on window W in glyph row ROW.
7243 Implementation note: One would like to draw a bar cursor with an
7244 angle equal to the one given by the font property XA_ITALIC_ANGLE.
7245 Unfortunately, I didn't find a font yet that has this property set.
7246 --gerd. */
7248 static void
7249 x_draw_bar_cursor (struct window *w, struct glyph_row *row, int width, enum text_cursor_kinds kind)
7251 struct frame *f = XFRAME (w->frame);
7252 struct glyph *cursor_glyph;
7254 /* If cursor is out of bounds, don't draw garbage. This can happen
7255 in mini-buffer windows when switching between echo area glyphs
7256 and mini-buffer. */
7257 cursor_glyph = get_phys_cursor_glyph (w);
7258 if (cursor_glyph == NULL)
7259 return;
7260 #ifdef HAVE_XWIDGETS
7261 if (cursor_glyph->type == XWIDGET_GLYPH){
7262 printf("tried avoiding xwidget cursor\n");
7263 return; //experimental avoidance of cursor on xwidget
7265 #endif
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 *r;
7272 r = MATRIX_ROW (w->current_matrix, w->phys_cursor.vpos);
7273 draw_phys_cursor_glyph (w, r, 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 ptrdiff_t 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 ptrdiff_t 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, (char *) 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 *event)
7564 XGetErrorText (display, event->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
7583 x_catch_errors (Display *dpy)
7585 struct x_error_message_stack *data = xmalloc (sizeof (*data));
7587 /* Make sure any errors from previous requests have been dealt with. */
7588 XSync (dpy, False);
7590 data->dpy = dpy;
7591 data->string[0] = 0;
7592 data->prev = x_error_message;
7593 x_error_message = data;
7596 /* Undo the last x_catch_errors call.
7597 DPY should be the display that was passed to x_catch_errors. */
7599 void
7600 x_uncatch_errors (void)
7602 struct x_error_message_stack *tmp;
7604 BLOCK_INPUT;
7606 /* The display may have been closed before this function is called.
7607 Check if it is still open before calling XSync. */
7608 if (x_display_info_for_display (x_error_message->dpy) != 0)
7609 XSync (x_error_message->dpy, False);
7611 tmp = x_error_message;
7612 x_error_message = x_error_message->prev;
7613 xfree (tmp);
7614 UNBLOCK_INPUT;
7617 /* If any X protocol errors have arrived since the last call to
7618 x_catch_errors or x_check_errors, signal an Emacs error using
7619 sprintf (a buffer, FORMAT, the x error message text) as the text. */
7621 void
7622 x_check_errors (Display *dpy, const char *format)
7624 /* Make sure to catch any errors incurred so far. */
7625 XSync (dpy, False);
7627 if (x_error_message->string[0])
7629 char string[X_ERROR_MESSAGE_SIZE];
7630 memcpy (string, x_error_message->string, X_ERROR_MESSAGE_SIZE);
7631 x_uncatch_errors ();
7632 error (format, string);
7636 /* Nonzero if we had any X protocol errors
7637 since we did x_catch_errors on DPY. */
7640 x_had_errors_p (Display *dpy)
7642 /* Make sure to catch any errors incurred so far. */
7643 XSync (dpy, False);
7645 return x_error_message->string[0] != 0;
7648 /* Forget about any errors we have had, since we did x_catch_errors on DPY. */
7650 void
7651 x_clear_errors (Display *dpy)
7653 x_error_message->string[0] = 0;
7656 #if 0 /* See comment in unwind_to_catch why calling this is a bad
7657 * idea. --lorentey */
7658 /* Close off all unclosed x_catch_errors calls. */
7660 void
7661 x_fully_uncatch_errors (void)
7663 while (x_error_message)
7664 x_uncatch_errors ();
7666 #endif
7668 /* Nonzero if x_catch_errors has been done and not yet canceled. */
7671 x_catching_errors (void)
7673 return x_error_message != 0;
7676 #if 0
7677 static unsigned int x_wire_count;
7678 x_trace_wire (void)
7680 fprintf (stderr, "Lib call: %d\n", ++x_wire_count);
7682 #endif /* ! 0 */
7685 /* Handle SIGPIPE, which can happen when the connection to a server
7686 simply goes away. SIGPIPE is handled by x_connection_signal.
7687 Don't need to do anything, because the write which caused the
7688 SIGPIPE will fail, causing Xlib to invoke the X IO error handler,
7689 which will do the appropriate cleanup for us. */
7691 static void
7692 x_connection_signal (int signalnum) /* If we don't have an argument, */
7693 /* some compilers complain in signal calls. */
7695 #ifdef USG
7696 /* USG systems forget handlers when they are used;
7697 must reestablish each time */
7698 signal (signalnum, x_connection_signal);
7699 #endif /* USG */
7703 /************************************************************************
7704 Handling X errors
7705 ************************************************************************/
7707 /* Error message passed to x_connection_closed. */
7709 static char *error_msg;
7711 /* Handle the loss of connection to display DPY. ERROR_MESSAGE is
7712 the text of an error message that lead to the connection loss. */
7714 static void
7715 x_connection_closed (Display *dpy, const char *error_message)
7717 struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
7718 Lisp_Object frame, tail;
7719 int idx = SPECPDL_INDEX ();
7721 error_msg = (char *) alloca (strlen (error_message) + 1);
7722 strcpy (error_msg, error_message);
7723 handling_signal = 0;
7725 /* Inhibit redisplay while frames are being deleted. */
7726 specbind (Qinhibit_redisplay, Qt);
7728 if (dpyinfo)
7730 /* Protect display from being closed when we delete the last
7731 frame on it. */
7732 dpyinfo->reference_count++;
7733 dpyinfo->terminal->reference_count++;
7736 /* First delete frames whose mini-buffers are on frames
7737 that are on the dead display. */
7738 FOR_EACH_FRAME (tail, frame)
7740 Lisp_Object minibuf_frame;
7741 minibuf_frame
7742 = WINDOW_FRAME (XWINDOW (FRAME_MINIBUF_WINDOW (XFRAME (frame))));
7743 if (FRAME_X_P (XFRAME (frame))
7744 && FRAME_X_P (XFRAME (minibuf_frame))
7745 && ! EQ (frame, minibuf_frame)
7746 && FRAME_X_DISPLAY_INFO (XFRAME (minibuf_frame)) == dpyinfo)
7747 delete_frame (frame, Qnoelisp);
7750 /* Now delete all remaining frames on the dead display.
7751 We are now sure none of these is used as the mini-buffer
7752 for another frame that we need to delete. */
7753 FOR_EACH_FRAME (tail, frame)
7754 if (FRAME_X_P (XFRAME (frame))
7755 && FRAME_X_DISPLAY_INFO (XFRAME (frame)) == dpyinfo)
7757 /* Set this to t so that delete_frame won't get confused
7758 trying to find a replacement. */
7759 KVAR (FRAME_KBOARD (XFRAME (frame)), Vdefault_minibuffer_frame) = Qt;
7760 delete_frame (frame, Qnoelisp);
7763 /* If DPYINFO is null, this means we didn't open the display in the
7764 first place, so don't try to close it. */
7765 if (dpyinfo)
7767 /* We can not call XtCloseDisplay here because it calls XSync.
7768 XSync inside the error handler apparently hangs Emacs. On
7769 current Xt versions, this isn't needed either. */
7770 #ifdef USE_GTK
7771 /* A long-standing GTK bug prevents proper disconnect handling
7772 (https://bugzilla.gnome.org/show_bug.cgi?id=85715). Once,
7773 the resulting Glib error message loop filled a user's disk.
7774 To avoid this, kill Emacs unconditionally on disconnect. */
7775 shut_down_emacs (0, 0, Qnil);
7776 fprintf (stderr, "%s\n\
7777 When compiled with GTK, Emacs cannot recover from X disconnects.\n\
7778 This is a GTK bug: https://bugzilla.gnome.org/show_bug.cgi?id=85715\n\
7779 For details, see etc/PROBLEMS.\n",
7780 error_msg);
7781 abort ();
7782 #endif /* USE_GTK */
7784 /* Indicate that this display is dead. */
7785 dpyinfo->display = 0;
7787 dpyinfo->reference_count--;
7788 dpyinfo->terminal->reference_count--;
7789 if (dpyinfo->reference_count != 0)
7790 /* We have just closed all frames on this display. */
7791 abort ();
7794 Lisp_Object tmp;
7795 XSETTERMINAL (tmp, dpyinfo->terminal);
7796 Fdelete_terminal (tmp, Qnoelisp);
7800 if (terminal_list == 0)
7802 fprintf (stderr, "%s\n", error_msg);
7803 Fkill_emacs (make_number (70));
7804 /* NOTREACHED */
7807 /* Ordinary stack unwind doesn't deal with these. */
7808 #ifdef SIGIO
7809 sigunblock (sigmask (SIGIO));
7810 #endif
7811 sigunblock (sigmask (SIGALRM));
7812 TOTALLY_UNBLOCK_INPUT;
7814 unbind_to (idx, Qnil);
7815 clear_waiting_for_input ();
7817 /* Tell GCC not to suggest attribute 'noreturn' for this function. */
7818 IF_LINT (if (! terminal_list) return; )
7820 /* Here, we absolutely have to use a non-local exit (e.g. signal, throw,
7821 longjmp), because returning from this function would get us back into
7822 Xlib's code which will directly call `exit'. */
7823 error ("%s", error_msg);
7826 /* We specifically use it before defining it, so that gcc doesn't inline it,
7827 otherwise gdb doesn't know how to properly put a breakpoint on it. */
7828 static void x_error_quitter (Display *, XErrorEvent *);
7830 /* This is the first-level handler for X protocol errors.
7831 It calls x_error_quitter or x_error_catcher. */
7833 static int
7834 x_error_handler (Display *display, XErrorEvent *event)
7836 if (x_error_message)
7837 x_error_catcher (display, event);
7838 else
7839 x_error_quitter (display, event);
7840 return 0;
7843 /* This is the usual handler for X protocol errors.
7844 It kills all frames on the display that we got the error for.
7845 If that was the only one, it prints an error message and kills Emacs. */
7847 /* .gdbinit puts a breakpoint here, so make sure it is not inlined. */
7849 /* On older GCC versions, just putting x_error_quitter
7850 after x_error_handler prevents inlining into the former. */
7852 static void NO_INLINE
7853 x_error_quitter (Display *display, XErrorEvent *event)
7855 char buf[256], buf1[356];
7857 /* Ignore BadName errors. They can happen because of fonts
7858 or colors that are not defined. */
7860 if (event->error_code == BadName)
7861 return;
7863 /* Note that there is no real way portable across R3/R4 to get the
7864 original error handler. */
7866 XGetErrorText (display, event->error_code, buf, sizeof (buf));
7867 sprintf (buf1, "X protocol error: %s on protocol request %d",
7868 buf, event->request_code);
7869 x_connection_closed (display, buf1);
7873 /* This is the handler for X IO errors, always.
7874 It kills all frames on the display that we lost touch with.
7875 If that was the only one, it prints an error message and kills Emacs. */
7877 static int
7878 x_io_error_quitter (Display *display)
7880 char buf[256];
7882 sprintf (buf, "Connection lost to X server `%s'", DisplayString (display));
7883 x_connection_closed (display, buf);
7884 return 0;
7887 /* Changing the font of the frame. */
7889 /* Give frame F the font FONT-OBJECT as its default font. The return
7890 value is FONT-OBJECT. FONTSET is an ID of the fontset for the
7891 frame. If it is negative, generate a new fontset from
7892 FONT-OBJECT. */
7894 Lisp_Object
7895 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
7897 struct font *font = XFONT_OBJECT (font_object);
7899 if (fontset < 0)
7900 fontset = fontset_from_font (font_object);
7901 FRAME_FONTSET (f) = fontset;
7902 if (FRAME_FONT (f) == font)
7903 /* This font is already set in frame F. There's nothing more to
7904 do. */
7905 return font_object;
7907 FRAME_FONT (f) = font;
7908 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
7909 FRAME_COLUMN_WIDTH (f) = font->average_width;
7910 FRAME_SPACE_WIDTH (f) = font->space_width;
7911 FRAME_LINE_HEIGHT (f) = FONT_HEIGHT (font);
7913 compute_fringe_widths (f, 1);
7915 /* Compute the scroll bar width in character columns. */
7916 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
7918 int wid = FRAME_COLUMN_WIDTH (f);
7919 FRAME_CONFIG_SCROLL_BAR_COLS (f)
7920 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid-1) / wid;
7922 else
7924 int wid = FRAME_COLUMN_WIDTH (f);
7925 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
7928 if (FRAME_X_WINDOW (f) != 0)
7930 /* Don't change the size of a tip frame; there's no point in
7931 doing it because it's done in Fx_show_tip, and it leads to
7932 problems because the tip frame has no widget. */
7933 if (NILP (tip_frame) || XFRAME (tip_frame) != f)
7934 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
7937 #ifdef HAVE_X_I18N
7938 if (FRAME_XIC (f)
7939 && (FRAME_XIC_STYLE (f) & (XIMPreeditPosition | XIMStatusArea)))
7941 BLOCK_INPUT;
7942 xic_set_xfontset (f, SSDATA (fontset_ascii (fontset)));
7943 UNBLOCK_INPUT;
7945 #endif
7947 return font_object;
7951 /***********************************************************************
7952 X Input Methods
7953 ***********************************************************************/
7955 #ifdef HAVE_X_I18N
7957 #ifdef HAVE_X11R6
7959 /* XIM destroy callback function, which is called whenever the
7960 connection to input method XIM dies. CLIENT_DATA contains a
7961 pointer to the x_display_info structure corresponding to XIM. */
7963 static void
7964 xim_destroy_callback (XIM xim, XPointer client_data, XPointer call_data)
7966 struct x_display_info *dpyinfo = (struct x_display_info *) client_data;
7967 Lisp_Object frame, tail;
7969 BLOCK_INPUT;
7971 /* No need to call XDestroyIC.. */
7972 FOR_EACH_FRAME (tail, frame)
7974 struct frame *f = XFRAME (frame);
7975 if (FRAME_X_P (f) && FRAME_X_DISPLAY_INFO (f) == dpyinfo)
7977 FRAME_XIC (f) = NULL;
7978 xic_free_xfontset (f);
7982 /* No need to call XCloseIM. */
7983 dpyinfo->xim = NULL;
7984 XFree (dpyinfo->xim_styles);
7985 UNBLOCK_INPUT;
7988 #endif /* HAVE_X11R6 */
7990 #ifdef HAVE_X11R6
7991 /* This isn't prototyped in OSF 5.0 or 5.1a. */
7992 extern char *XSetIMValues (XIM, ...);
7993 #endif
7995 /* Open the connection to the XIM server on display DPYINFO.
7996 RESOURCE_NAME is the resource name Emacs uses. */
7998 static void
7999 xim_open_dpy (struct x_display_info *dpyinfo, char *resource_name)
8001 XIM xim;
8003 #ifdef HAVE_XIM
8004 if (use_xim)
8006 if (dpyinfo->xim)
8007 XCloseIM (dpyinfo->xim);
8008 xim = XOpenIM (dpyinfo->display, dpyinfo->xrdb, resource_name,
8009 emacs_class);
8010 dpyinfo->xim = xim;
8012 if (xim)
8014 #ifdef HAVE_X11R6
8015 XIMCallback destroy;
8016 #endif
8018 /* Get supported styles and XIM values. */
8019 XGetIMValues (xim, XNQueryInputStyle, &dpyinfo->xim_styles, NULL);
8021 #ifdef HAVE_X11R6
8022 destroy.callback = xim_destroy_callback;
8023 destroy.client_data = (XPointer)dpyinfo;
8024 XSetIMValues (xim, XNDestroyCallback, &destroy, NULL);
8025 #endif
8029 else
8030 #endif /* HAVE_XIM */
8031 dpyinfo->xim = NULL;
8035 #ifdef HAVE_X11R6_XIM
8037 /* XIM instantiate callback function, which is called whenever an XIM
8038 server is available. DISPLAY is the display of the XIM.
8039 CLIENT_DATA contains a pointer to an xim_inst_t structure created
8040 when the callback was registered. */
8042 static void
8043 xim_instantiate_callback (Display *display, XPointer client_data, XPointer call_data)
8045 struct xim_inst_t *xim_inst = (struct xim_inst_t *) client_data;
8046 struct x_display_info *dpyinfo = xim_inst->dpyinfo;
8048 /* We don't support multiple XIM connections. */
8049 if (dpyinfo->xim)
8050 return;
8052 xim_open_dpy (dpyinfo, xim_inst->resource_name);
8054 /* Create XIC for the existing frames on the same display, as long
8055 as they have no XIC. */
8056 if (dpyinfo->xim && dpyinfo->reference_count > 0)
8058 Lisp_Object tail, frame;
8060 BLOCK_INPUT;
8061 FOR_EACH_FRAME (tail, frame)
8063 struct frame *f = XFRAME (frame);
8065 if (FRAME_X_P (f)
8066 && FRAME_X_DISPLAY_INFO (f) == xim_inst->dpyinfo)
8067 if (FRAME_XIC (f) == NULL)
8069 create_frame_xic (f);
8070 if (FRAME_XIC_STYLE (f) & XIMStatusArea)
8071 xic_set_statusarea (f);
8072 if (FRAME_XIC_STYLE (f) & XIMPreeditPosition)
8074 struct window *w = XWINDOW (f->selected_window);
8075 xic_set_preeditarea (w, w->cursor.x, w->cursor.y);
8080 UNBLOCK_INPUT;
8084 #endif /* HAVE_X11R6_XIM */
8087 /* Open a connection to the XIM server on display DPYINFO.
8088 RESOURCE_NAME is the resource name for Emacs. On X11R5, open the
8089 connection only at the first time. On X11R6, open the connection
8090 in the XIM instantiate callback function. */
8092 static void
8093 xim_initialize (struct x_display_info *dpyinfo, char *resource_name)
8095 dpyinfo->xim = NULL;
8096 #ifdef HAVE_XIM
8097 if (use_xim)
8099 #ifdef HAVE_X11R6_XIM
8100 struct xim_inst_t *xim_inst;
8101 ptrdiff_t len;
8103 xim_inst = (struct xim_inst_t *) xmalloc (sizeof (struct xim_inst_t));
8104 dpyinfo->xim_callback_data = xim_inst;
8105 xim_inst->dpyinfo = dpyinfo;
8106 len = strlen (resource_name);
8107 xim_inst->resource_name = (char *) xmalloc (len + 1);
8108 memcpy (xim_inst->resource_name, resource_name, len + 1);
8109 XRegisterIMInstantiateCallback (dpyinfo->display, dpyinfo->xrdb,
8110 resource_name, emacs_class,
8111 xim_instantiate_callback,
8112 /* This is XPointer in XFree86
8113 but (XPointer *) on Tru64, at
8114 least, hence the configure test. */
8115 (XRegisterIMInstantiateCallback_arg6) xim_inst);
8116 #else /* not HAVE_X11R6_XIM */
8117 xim_open_dpy (dpyinfo, resource_name);
8118 #endif /* not HAVE_X11R6_XIM */
8120 #endif /* HAVE_XIM */
8124 /* Close the connection to the XIM server on display DPYINFO. */
8126 static void
8127 xim_close_dpy (struct x_display_info *dpyinfo)
8129 #ifdef HAVE_XIM
8130 if (use_xim)
8132 #ifdef HAVE_X11R6_XIM
8133 if (dpyinfo->display)
8134 XUnregisterIMInstantiateCallback (dpyinfo->display, dpyinfo->xrdb,
8135 NULL, emacs_class,
8136 xim_instantiate_callback, NULL);
8137 xfree (dpyinfo->xim_callback_data->resource_name);
8138 xfree (dpyinfo->xim_callback_data);
8139 #endif /* HAVE_X11R6_XIM */
8140 if (dpyinfo->display)
8141 XCloseIM (dpyinfo->xim);
8142 dpyinfo->xim = NULL;
8143 XFree (dpyinfo->xim_styles);
8145 #endif /* HAVE_XIM */
8148 #endif /* not HAVE_X11R6_XIM */
8152 /* Calculate the absolute position in frame F
8153 from its current recorded position values and gravity. */
8155 static void
8156 x_calc_absolute_position (struct frame *f)
8158 int flags = f->size_hint_flags;
8160 /* We have nothing to do if the current position
8161 is already for the top-left corner. */
8162 if (! ((flags & XNegative) || (flags & YNegative)))
8163 return;
8165 /* Treat negative positions as relative to the leftmost bottommost
8166 position that fits on the screen. */
8167 if (flags & XNegative)
8168 f->left_pos = x_display_pixel_width (FRAME_X_DISPLAY_INFO (f))
8169 - FRAME_PIXEL_WIDTH (f) + f->left_pos;
8172 int height = FRAME_PIXEL_HEIGHT (f);
8174 #if defined USE_X_TOOLKIT && defined USE_MOTIF
8175 /* Something is fishy here. When using Motif, starting Emacs with
8176 `-g -0-0', the frame appears too low by a few pixels.
8178 This seems to be so because initially, while Emacs is starting,
8179 the column widget's height and the frame's pixel height are
8180 different. The column widget's height is the right one. In
8181 later invocations, when Emacs is up, the frame's pixel height
8182 is right, though.
8184 It's not obvious where the initial small difference comes from.
8185 2000-12-01, gerd. */
8187 XtVaGetValues (f->output_data.x->column_widget, XtNheight, &height, NULL);
8188 #endif
8190 if (flags & YNegative)
8191 f->top_pos = x_display_pixel_height (FRAME_X_DISPLAY_INFO (f))
8192 - height + f->top_pos;
8195 /* The left_pos and top_pos
8196 are now relative to the top and left screen edges,
8197 so the flags should correspond. */
8198 f->size_hint_flags &= ~ (XNegative | YNegative);
8201 /* CHANGE_GRAVITY is 1 when calling from Fset_frame_position,
8202 to really change the position, and 0 when calling from
8203 x_make_frame_visible (in that case, XOFF and YOFF are the current
8204 position values). It is -1 when calling from x_set_frame_parameters,
8205 which means, do adjust for borders but don't change the gravity. */
8207 void
8208 x_set_offset (struct frame *f, register int xoff, register int yoff, int change_gravity)
8210 int modified_top, modified_left;
8212 if (change_gravity > 0)
8214 FRAME_X_OUTPUT (f)->left_before_move = f->left_pos;
8215 FRAME_X_OUTPUT (f)->top_before_move = f->top_pos;
8217 f->top_pos = yoff;
8218 f->left_pos = xoff;
8219 f->size_hint_flags &= ~ (XNegative | YNegative);
8220 if (xoff < 0)
8221 f->size_hint_flags |= XNegative;
8222 if (yoff < 0)
8223 f->size_hint_flags |= YNegative;
8224 f->win_gravity = NorthWestGravity;
8226 x_calc_absolute_position (f);
8228 BLOCK_INPUT;
8229 x_wm_set_size_hint (f, (long) 0, 0);
8231 modified_left = f->left_pos;
8232 modified_top = f->top_pos;
8234 if (change_gravity != 0 && FRAME_X_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A)
8236 /* Some WMs (twm, wmaker at least) has an offset that is smaller
8237 than the WM decorations. So we use the calculated offset instead
8238 of the WM decoration sizes here (x/y_pixels_outer_diff). */
8239 modified_left += FRAME_X_OUTPUT (f)->move_offset_left;
8240 modified_top += FRAME_X_OUTPUT (f)->move_offset_top;
8243 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8244 modified_left, modified_top);
8246 x_sync_with_move (f, f->left_pos, f->top_pos,
8247 FRAME_X_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN
8248 ? 1 : 0);
8250 /* change_gravity is non-zero when this function is called from Lisp to
8251 programmatically move a frame. In that case, we call
8252 x_check_expected_move to discover if we have a "Type A" or "Type B"
8253 window manager, and, for a "Type A" window manager, adjust the position
8254 of the frame.
8256 We call x_check_expected_move if a programmatic move occurred, and
8257 either the window manager type (A/B) is unknown or it is Type A but we
8258 need to compute the top/left offset adjustment for this frame. */
8260 if (change_gravity != 0 &&
8261 (FRAME_X_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN
8262 || (FRAME_X_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A
8263 && (FRAME_X_OUTPUT (f)->move_offset_left == 0
8264 && FRAME_X_OUTPUT (f)->move_offset_top == 0))))
8265 x_check_expected_move (f, modified_left, modified_top);
8267 UNBLOCK_INPUT;
8270 /* Return non-zero if _NET_SUPPORTING_WM_CHECK window exists and _NET_SUPPORTED
8271 on the root window for frame F contains ATOMNAME.
8272 This is how a WM check shall be done according to the Window Manager
8273 Specification/Extended Window Manager Hints at
8274 http://freedesktop.org/wiki/Specifications/wm-spec. */
8276 static int
8277 wm_supports (struct frame *f, Atom want_atom)
8279 Atom actual_type;
8280 unsigned long actual_size, bytes_remaining;
8281 int i, rc, actual_format;
8282 Window wmcheck_window;
8283 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8284 Window target_window = dpyinfo->root_window;
8285 long max_len = 65536;
8286 Display *dpy = FRAME_X_DISPLAY (f);
8287 unsigned char *tmp_data = NULL;
8288 Atom target_type = XA_WINDOW;
8290 BLOCK_INPUT;
8292 x_catch_errors (dpy);
8293 rc = XGetWindowProperty (dpy, target_window,
8294 dpyinfo->Xatom_net_supporting_wm_check,
8295 0, max_len, False, target_type,
8296 &actual_type, &actual_format, &actual_size,
8297 &bytes_remaining, &tmp_data);
8299 if (rc != Success || actual_type != XA_WINDOW || x_had_errors_p (dpy))
8301 if (tmp_data) XFree (tmp_data);
8302 x_uncatch_errors ();
8303 UNBLOCK_INPUT;
8304 return 0;
8307 wmcheck_window = *(Window *) tmp_data;
8308 XFree (tmp_data);
8310 /* Check if window exists. */
8311 XSelectInput (dpy, wmcheck_window, StructureNotifyMask);
8312 x_sync (f);
8313 if (x_had_errors_p (dpy))
8315 x_uncatch_errors ();
8316 UNBLOCK_INPUT;
8317 return 0;
8320 if (dpyinfo->net_supported_window != wmcheck_window)
8322 /* Window changed, reload atoms */
8323 if (dpyinfo->net_supported_atoms != NULL)
8324 XFree (dpyinfo->net_supported_atoms);
8325 dpyinfo->net_supported_atoms = NULL;
8326 dpyinfo->nr_net_supported_atoms = 0;
8327 dpyinfo->net_supported_window = 0;
8329 target_type = XA_ATOM;
8330 tmp_data = NULL;
8331 rc = XGetWindowProperty (dpy, target_window,
8332 dpyinfo->Xatom_net_supported,
8333 0, max_len, False, target_type,
8334 &actual_type, &actual_format, &actual_size,
8335 &bytes_remaining, &tmp_data);
8337 if (rc != Success || actual_type != XA_ATOM || x_had_errors_p (dpy))
8339 if (tmp_data) XFree (tmp_data);
8340 x_uncatch_errors ();
8341 UNBLOCK_INPUT;
8342 return 0;
8345 dpyinfo->net_supported_atoms = (Atom *)tmp_data;
8346 dpyinfo->nr_net_supported_atoms = actual_size;
8347 dpyinfo->net_supported_window = wmcheck_window;
8350 rc = 0;
8352 for (i = 0; rc == 0 && i < dpyinfo->nr_net_supported_atoms; ++i)
8353 rc = dpyinfo->net_supported_atoms[i] == want_atom;
8355 x_uncatch_errors ();
8356 UNBLOCK_INPUT;
8358 return rc;
8361 static void
8362 set_wm_state (Lisp_Object frame, int add, Atom atom, Atom value)
8364 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (XFRAME (frame));
8366 x_send_client_event (frame, make_number (0), frame,
8367 dpyinfo->Xatom_net_wm_state,
8368 make_number (32),
8369 /* 1 = add, 0 = remove */
8370 Fcons
8371 (make_number (add ? 1 : 0),
8372 Fcons
8373 (make_fixnum_or_float (atom),
8374 value != 0
8375 ? Fcons (make_fixnum_or_float (value), Qnil)
8376 : Qnil)));
8379 void
8380 x_set_sticky (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
8382 Lisp_Object frame;
8383 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8385 XSETFRAME (frame, f);
8387 set_wm_state (frame, NILP (new_value) ? 0 : 1,
8388 dpyinfo->Xatom_net_wm_state_sticky, None);
8391 /* Return the current _NET_WM_STATE.
8392 SIZE_STATE is set to one of the FULLSCREEN_* values.
8393 STICKY is set to 1 if the sticky state is set, 0 if not. */
8395 static void
8396 get_current_wm_state (struct frame *f,
8397 Window window,
8398 int *size_state,
8399 int *sticky)
8401 Atom actual_type;
8402 unsigned long actual_size, bytes_remaining;
8403 int i, rc, actual_format;
8404 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8405 long max_len = 65536;
8406 Display *dpy = FRAME_X_DISPLAY (f);
8407 unsigned char *tmp_data = NULL;
8408 Atom target_type = XA_ATOM;
8410 *sticky = 0;
8411 *size_state = FULLSCREEN_NONE;
8413 BLOCK_INPUT;
8414 x_catch_errors (dpy);
8415 rc = XGetWindowProperty (dpy, window, dpyinfo->Xatom_net_wm_state,
8416 0, max_len, False, target_type,
8417 &actual_type, &actual_format, &actual_size,
8418 &bytes_remaining, &tmp_data);
8420 if (rc != Success || actual_type != target_type || x_had_errors_p (dpy))
8422 if (tmp_data) XFree (tmp_data);
8423 x_uncatch_errors ();
8424 UNBLOCK_INPUT;
8425 return;
8428 x_uncatch_errors ();
8430 for (i = 0; i < actual_size; ++i)
8432 Atom a = ((Atom*)tmp_data)[i];
8433 if (a == dpyinfo->Xatom_net_wm_state_maximized_horz)
8435 if (*size_state == FULLSCREEN_HEIGHT)
8436 *size_state = FULLSCREEN_MAXIMIZED;
8437 else
8438 *size_state = FULLSCREEN_WIDTH;
8440 else if (a == dpyinfo->Xatom_net_wm_state_maximized_vert)
8442 if (*size_state == FULLSCREEN_WIDTH)
8443 *size_state = FULLSCREEN_MAXIMIZED;
8444 else
8445 *size_state = FULLSCREEN_HEIGHT;
8447 else if (a == dpyinfo->Xatom_net_wm_state_fullscreen)
8448 *size_state = FULLSCREEN_BOTH;
8449 else if (a == dpyinfo->Xatom_net_wm_state_sticky)
8450 *sticky = 1;
8453 if (tmp_data) XFree (tmp_data);
8454 UNBLOCK_INPUT;
8457 /* Do fullscreen as specified in extended window manager hints */
8459 static int
8460 do_ewmh_fullscreen (struct frame *f)
8462 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8463 int have_net_atom = wm_supports (f, dpyinfo->Xatom_net_wm_state);
8464 int cur, dummy;
8466 get_current_wm_state (f, FRAME_OUTER_WINDOW (f), &cur, &dummy);
8468 /* Some window managers don't say they support _NET_WM_STATE, but they do say
8469 they support _NET_WM_STATE_FULLSCREEN. Try that also. */
8470 if (!have_net_atom)
8471 have_net_atom = wm_supports (f, dpyinfo->Xatom_net_wm_state_fullscreen);
8473 if (have_net_atom && cur != f->want_fullscreen)
8475 Lisp_Object frame;
8477 XSETFRAME (frame, f);
8479 /* Keep number of calls to set_wm_state as low as possible.
8480 Some window managers, or possible Gtk+, hangs when too many
8481 are sent at once. */
8482 switch (f->want_fullscreen)
8484 case FULLSCREEN_BOTH:
8485 if (cur == FULLSCREEN_WIDTH || cur == FULLSCREEN_MAXIMIZED
8486 || cur == FULLSCREEN_HEIGHT)
8487 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_maximized_horz,
8488 dpyinfo->Xatom_net_wm_state_maximized_vert);
8489 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_fullscreen, None);
8490 break;
8491 case FULLSCREEN_WIDTH:
8492 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_HEIGHT
8493 || cur == FULLSCREEN_MAXIMIZED)
8494 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen,
8495 dpyinfo->Xatom_net_wm_state_maximized_vert);
8496 if (cur != FULLSCREEN_MAXIMIZED)
8497 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_maximized_horz, None);
8498 break;
8499 case FULLSCREEN_HEIGHT:
8500 if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_WIDTH
8501 || cur == FULLSCREEN_MAXIMIZED)
8502 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen,
8503 dpyinfo->Xatom_net_wm_state_maximized_horz);
8504 if (cur != FULLSCREEN_MAXIMIZED)
8505 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_maximized_vert, None);
8506 break;
8507 case FULLSCREEN_MAXIMIZED:
8508 if (cur == FULLSCREEN_BOTH)
8509 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen, None);
8510 set_wm_state (frame, 1, dpyinfo->Xatom_net_wm_state_maximized_horz,
8511 dpyinfo->Xatom_net_wm_state_maximized_vert);
8512 break;
8513 case FULLSCREEN_NONE:
8514 if (cur == FULLSCREEN_BOTH)
8515 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_fullscreen, None);
8516 else
8517 set_wm_state (frame, 0, dpyinfo->Xatom_net_wm_state_maximized_horz,
8518 dpyinfo->Xatom_net_wm_state_maximized_vert);
8521 f->want_fullscreen = FULLSCREEN_NONE;
8525 return have_net_atom;
8528 static void
8529 XTfullscreen_hook (FRAME_PTR f)
8531 if (f->async_visible)
8533 BLOCK_INPUT;
8534 x_check_fullscreen (f);
8535 x_sync (f);
8536 UNBLOCK_INPUT;
8541 static void
8542 x_handle_net_wm_state (struct frame *f, XPropertyEvent *event)
8544 int value = FULLSCREEN_NONE;
8545 Lisp_Object lval;
8546 int sticky = 0;
8548 get_current_wm_state (f, event->window, &value, &sticky);
8549 lval = Qnil;
8550 switch (value)
8552 case FULLSCREEN_WIDTH:
8553 lval = Qfullwidth;
8554 break;
8555 case FULLSCREEN_HEIGHT:
8556 lval = Qfullheight;
8557 break;
8558 case FULLSCREEN_BOTH:
8559 lval = Qfullboth;
8560 break;
8561 case FULLSCREEN_MAXIMIZED:
8562 lval = Qmaximized;
8563 break;
8566 store_frame_param (f, Qfullscreen, lval);
8567 store_frame_param (f, Qsticky, sticky ? Qt : Qnil);
8570 /* Check if we need to resize the frame due to a fullscreen request.
8571 If so needed, resize the frame. */
8572 static void
8573 x_check_fullscreen (struct frame *f)
8575 if (do_ewmh_fullscreen (f))
8576 return;
8578 if (f->output_data.x->parent_desc != FRAME_X_DISPLAY_INFO (f)->root_window)
8579 return; /* Only fullscreen without WM or with EWM hints (above). */
8581 /* Setting fullscreen to nil doesn't do anything. We could save the
8582 last non-fullscreen size and restore it, but it seems like a
8583 lot of work for this unusual case (no window manager running). */
8585 if (f->want_fullscreen != FULLSCREEN_NONE)
8587 int width = FRAME_PIXEL_WIDTH (f), height = FRAME_PIXEL_HEIGHT (f);
8588 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8590 switch (f->want_fullscreen)
8592 /* No difference between these two when there is no WM */
8593 case FULLSCREEN_BOTH:
8594 case FULLSCREEN_MAXIMIZED:
8595 width = x_display_pixel_width (dpyinfo);
8596 height = x_display_pixel_height (dpyinfo);
8597 break;
8598 case FULLSCREEN_WIDTH:
8599 width = x_display_pixel_width (dpyinfo);
8600 break;
8601 case FULLSCREEN_HEIGHT:
8602 height = x_display_pixel_height (dpyinfo);
8605 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8606 width, height);
8610 /* This function is called by x_set_offset to determine whether the window
8611 manager interfered with the positioning of the frame. Type A window
8612 managers position the surrounding window manager decorations a small
8613 amount above and left of the user-supplied position. Type B window
8614 managers position the surrounding window manager decorations at the
8615 user-specified position. If we detect a Type A window manager, we
8616 compensate by moving the window right and down by the proper amount. */
8618 static void
8619 x_check_expected_move (struct frame *f, int expected_left, int expected_top)
8621 int current_left = 0, current_top = 0;
8623 /* x_real_positions returns the left and top offsets of the outermost
8624 window manager window around the frame. */
8626 x_real_positions (f, &current_left, &current_top);
8628 if (current_left != expected_left || current_top != expected_top)
8630 /* It's a "Type A" window manager. */
8632 int adjusted_left;
8633 int adjusted_top;
8635 FRAME_X_DISPLAY_INFO (f)->wm_type = X_WMTYPE_A;
8636 FRAME_X_OUTPUT (f)->move_offset_left = expected_left - current_left;
8637 FRAME_X_OUTPUT (f)->move_offset_top = expected_top - current_top;
8639 /* Now fix the mispositioned frame's location. */
8641 adjusted_left = expected_left + FRAME_X_OUTPUT (f)->move_offset_left;
8642 adjusted_top = expected_top + FRAME_X_OUTPUT (f)->move_offset_top;
8644 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8645 adjusted_left, adjusted_top);
8647 x_sync_with_move (f, expected_left, expected_top, 0);
8649 else
8650 /* It's a "Type B" window manager. We don't have to adjust the
8651 frame's position. */
8653 FRAME_X_DISPLAY_INFO (f)->wm_type = X_WMTYPE_B;
8657 /* Wait for XGetGeometry to return up-to-date position information for a
8658 recently-moved frame. Call this immediately after calling XMoveWindow.
8659 If FUZZY is non-zero, then LEFT and TOP are just estimates of where the
8660 frame has been moved to, so we use a fuzzy position comparison instead
8661 of an exact comparison. */
8663 static void
8664 x_sync_with_move (struct frame *f, int left, int top, int fuzzy)
8666 int count = 0;
8668 while (count++ < 50)
8670 int current_left = 0, current_top = 0;
8672 /* In theory, this call to XSync only needs to happen once, but in
8673 practice, it doesn't seem to work, hence the need for the surrounding
8674 loop. */
8676 XSync (FRAME_X_DISPLAY (f), False);
8677 x_real_positions (f, &current_left, &current_top);
8679 if (fuzzy)
8681 /* The left fuzz-factor is 10 pixels. The top fuzz-factor is 40
8682 pixels. */
8684 if (eabs (current_left - left) <= 10
8685 && eabs (current_top - top) <= 40)
8686 return;
8688 else if (current_left == left && current_top == top)
8689 return;
8692 /* As a last resort, just wait 0.5 seconds and hope that XGetGeometry
8693 will then return up-to-date position info. */
8695 wait_reading_process_output (0, 500000, 0, 0, Qnil, NULL, 0);
8699 /* Wait for an event on frame F matching EVENTTYPE. */
8700 void
8701 x_wait_for_event (struct frame *f, int eventtype)
8703 int level = interrupt_input_blocked;
8705 SELECT_TYPE fds;
8706 EMACS_TIME tmo, tmo_at, time_now;
8707 int fd = ConnectionNumber (FRAME_X_DISPLAY (f));
8709 pending_event_wait.f = f;
8710 pending_event_wait.eventtype = eventtype;
8712 /* Set timeout to 0.1 second. Hopefully not noticable.
8713 Maybe it should be configurable. */
8714 EMACS_SET_SECS_USECS (tmo, 0, 100000);
8715 EMACS_GET_TIME (tmo_at);
8716 EMACS_ADD_TIME (tmo_at, tmo_at, tmo);
8718 while (pending_event_wait.eventtype)
8720 interrupt_input_pending = 1;
8721 TOTALLY_UNBLOCK_INPUT;
8722 /* XTread_socket is called after unblock. */
8723 BLOCK_INPUT;
8724 interrupt_input_blocked = level;
8726 FD_ZERO (&fds);
8727 FD_SET (fd, &fds);
8729 EMACS_GET_TIME (time_now);
8730 EMACS_SUB_TIME (tmo, tmo_at, time_now);
8732 if (EMACS_TIME_NEG_P (tmo) || select (fd+1, &fds, NULL, NULL, &tmo) == 0)
8733 break; /* Timeout */
8735 pending_event_wait.f = 0;
8736 pending_event_wait.eventtype = 0;
8740 /* Change the size of frame F's X window to COLS/ROWS in the case F
8741 doesn't have a widget. If CHANGE_GRAVITY is 1, we change to
8742 top-left-corner window gravity for this size change and subsequent
8743 size changes. Otherwise we leave the window gravity unchanged. */
8745 static void
8746 x_set_window_size_1 (struct frame *f, int change_gravity, int cols, int rows)
8748 int pixelwidth, pixelheight;
8750 check_frame_size (f, &rows, &cols);
8751 f->scroll_bar_actual_width
8752 = (!FRAME_HAS_VERTICAL_SCROLL_BARS (f)
8754 : FRAME_CONFIG_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f));
8756 compute_fringe_widths (f, 0);
8758 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, cols)
8759 + FRAME_TOOLBAR_WIDTH (f);
8760 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows)
8761 + FRAME_MENUBAR_HEIGHT (f) + FRAME_TOOLBAR_HEIGHT (f);
8763 if (change_gravity) f->win_gravity = NorthWestGravity;
8764 x_wm_set_size_hint (f, (long) 0, 0);
8765 XResizeWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8766 pixelwidth, pixelheight);
8769 /* We've set {FRAME,PIXEL}_{WIDTH,HEIGHT} to the values we hope to
8770 receive in the ConfigureNotify event; if we get what we asked
8771 for, then the event won't cause the screen to become garbaged, so
8772 we have to make sure to do it here. */
8773 SET_FRAME_GARBAGED (f);
8775 /* Now, strictly speaking, we can't be sure that this is accurate,
8776 but the window manager will get around to dealing with the size
8777 change request eventually, and we'll hear how it went when the
8778 ConfigureNotify event gets here.
8780 We could just not bother storing any of this information here,
8781 and let the ConfigureNotify event set everything up, but that
8782 might be kind of confusing to the Lisp code, since size changes
8783 wouldn't be reported in the frame parameters until some random
8784 point in the future when the ConfigureNotify event arrives.
8786 We pass 1 for DELAY since we can't run Lisp code inside of
8787 a BLOCK_INPUT. */
8789 /* But the ConfigureNotify may in fact never arrive, and then this is
8790 not right if the frame is visible. Instead wait (with timeout)
8791 for the ConfigureNotify. */
8792 if (f->async_visible)
8793 x_wait_for_event (f, ConfigureNotify);
8794 else
8796 change_frame_size (f, rows, cols, 0, 1, 0);
8797 FRAME_PIXEL_WIDTH (f) = pixelwidth;
8798 FRAME_PIXEL_HEIGHT (f) = pixelheight;
8799 x_sync (f);
8804 /* Call this to change the size of frame F's x-window.
8805 If CHANGE_GRAVITY is 1, we change to top-left-corner window gravity
8806 for this size change and subsequent size changes.
8807 Otherwise we leave the window gravity unchanged. */
8809 void
8810 x_set_window_size (struct frame *f, int change_gravity, int cols, int rows)
8812 BLOCK_INPUT;
8814 if (NILP (tip_frame) || XFRAME (tip_frame) != f)
8816 int r, c;
8818 /* When the frame is maximized/fullscreen or running under for
8819 example Xmonad, x_set_window_size_1 will be a no-op.
8820 In that case, the right thing to do is extend rows/cols to
8821 the current frame size. We do that first if x_set_window_size_1
8822 turns out to not be a no-op (there is no way to know).
8823 The size will be adjusted again if the frame gets a
8824 ConfigureNotify event as a result of x_set_window_size. */
8825 int pixelh = FRAME_PIXEL_HEIGHT (f);
8826 #ifdef USE_X_TOOLKIT
8827 /* The menu bar is not part of text lines. The tool bar
8828 is however. */
8829 pixelh -= FRAME_MENUBAR_HEIGHT (f);
8830 #endif
8831 r = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, pixelh);
8832 /* Update f->scroll_bar_actual_width because it is used in
8833 FRAME_PIXEL_WIDTH_TO_TEXT_COLS. */
8834 f->scroll_bar_actual_width
8835 = FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f);
8836 c = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, FRAME_PIXEL_WIDTH (f));
8837 change_frame_size (f, r, c, 0, 1, 0);
8840 #ifdef USE_GTK
8841 if (FRAME_GTK_WIDGET (f))
8842 xg_frame_set_char_size (f, cols, rows);
8843 else
8844 x_set_window_size_1 (f, change_gravity, cols, rows);
8845 #else /* not USE_GTK */
8847 x_set_window_size_1 (f, change_gravity, cols, rows);
8849 #endif /* not USE_GTK */
8851 /* If cursor was outside the new size, mark it as off. */
8852 mark_window_cursors_off (XWINDOW (f->root_window));
8854 /* Clear out any recollection of where the mouse highlighting was,
8855 since it might be in a place that's outside the new frame size.
8856 Actually checking whether it is outside is a pain in the neck,
8857 so don't try--just let the highlighting be done afresh with new size. */
8858 cancel_mouse_face (f);
8860 UNBLOCK_INPUT;
8863 /* Mouse warping. */
8865 void
8866 x_set_mouse_position (struct frame *f, int x, int y)
8868 int pix_x, pix_y;
8870 pix_x = FRAME_COL_TO_PIXEL_X (f, x) + FRAME_COLUMN_WIDTH (f) / 2;
8871 pix_y = FRAME_LINE_TO_PIXEL_Y (f, y) + FRAME_LINE_HEIGHT (f) / 2;
8873 if (pix_x < 0) pix_x = 0;
8874 if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
8876 if (pix_y < 0) pix_y = 0;
8877 if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
8879 BLOCK_INPUT;
8881 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
8882 0, 0, 0, 0, pix_x, pix_y);
8883 UNBLOCK_INPUT;
8886 /* Move the mouse to position pixel PIX_X, PIX_Y relative to frame F. */
8888 void
8889 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
8891 BLOCK_INPUT;
8893 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
8894 0, 0, 0, 0, pix_x, pix_y);
8895 UNBLOCK_INPUT;
8898 /* Raise frame F. */
8900 void
8901 x_raise_frame (struct frame *f)
8903 BLOCK_INPUT;
8904 if (f->async_visible)
8905 XRaiseWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
8907 XFlush (FRAME_X_DISPLAY (f));
8908 UNBLOCK_INPUT;
8911 /* Lower frame F. */
8913 static void
8914 x_lower_frame (struct frame *f)
8916 if (f->async_visible)
8918 BLOCK_INPUT;
8919 XLowerWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
8920 XFlush (FRAME_X_DISPLAY (f));
8921 UNBLOCK_INPUT;
8925 /* Activate frame with Extended Window Manager Hints */
8927 void
8928 x_ewmh_activate_frame (FRAME_PTR f)
8930 /* See Window Manager Specification/Extended Window Manager Hints at
8931 http://freedesktop.org/wiki/Specifications/wm-spec */
8933 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8934 if (f->async_visible && wm_supports (f, dpyinfo->Xatom_net_active_window))
8936 Lisp_Object frame;
8937 XSETFRAME (frame, f);
8938 x_send_client_event (frame, make_number (0), frame,
8939 dpyinfo->Xatom_net_active_window,
8940 make_number (32),
8941 Fcons (make_number (1),
8942 Fcons (make_number (last_user_time),
8943 Qnil)));
8947 static void
8948 XTframe_raise_lower (FRAME_PTR f, int raise_flag)
8950 if (raise_flag)
8951 x_raise_frame (f);
8952 else
8953 x_lower_frame (f);
8956 /* XEmbed implementation. */
8958 #if defined USE_X_TOOLKIT || ! defined USE_GTK
8960 /* XEmbed implementation. */
8962 #define XEMBED_VERSION 0
8964 static void
8965 xembed_set_info (struct frame *f, enum xembed_info flags)
8967 unsigned long data[2];
8968 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8970 data[0] = XEMBED_VERSION;
8971 data[1] = flags;
8973 XChangeProperty (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8974 dpyinfo->Xatom_XEMBED_INFO, dpyinfo->Xatom_XEMBED_INFO,
8975 32, PropModeReplace, (unsigned char *) data, 2);
8977 #endif /* defined USE_X_TOOLKIT || ! defined USE_GTK */
8979 static void
8980 xembed_send_message (struct frame *f, Time t, enum xembed_message msg,
8981 long int detail, long int data1, long int data2)
8983 XEvent event;
8985 event.xclient.type = ClientMessage;
8986 event.xclient.window = FRAME_X_OUTPUT (f)->parent_desc;
8987 event.xclient.message_type = FRAME_X_DISPLAY_INFO (f)->Xatom_XEMBED;
8988 event.xclient.format = 32;
8989 event.xclient.data.l[0] = t;
8990 event.xclient.data.l[1] = msg;
8991 event.xclient.data.l[2] = detail;
8992 event.xclient.data.l[3] = data1;
8993 event.xclient.data.l[4] = data2;
8995 XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_OUTPUT (f)->parent_desc,
8996 False, NoEventMask, &event);
8997 XSync (FRAME_X_DISPLAY (f), False);
9000 /* Change of visibility. */
9002 /* This tries to wait until the frame is really visible.
9003 However, if the window manager asks the user where to position
9004 the frame, this will return before the user finishes doing that.
9005 The frame will not actually be visible at that time,
9006 but it will become visible later when the window manager
9007 finishes with it. */
9009 void
9010 x_make_frame_visible (struct frame *f)
9012 Lisp_Object type;
9013 int original_top, original_left;
9014 int retry_count = 2;
9016 retry:
9018 BLOCK_INPUT;
9020 type = x_icon_type (f);
9021 if (!NILP (type))
9022 x_bitmap_icon (f, type);
9024 if (! FRAME_VISIBLE_P (f))
9026 /* We test FRAME_GARBAGED_P here to make sure we don't
9027 call x_set_offset a second time
9028 if we get to x_make_frame_visible a second time
9029 before the window gets really visible. */
9030 if (! FRAME_ICONIFIED_P (f)
9031 && ! FRAME_X_EMBEDDED_P (f)
9032 && ! f->output_data.x->asked_for_visible)
9033 x_set_offset (f, f->left_pos, f->top_pos, 0);
9035 f->output_data.x->asked_for_visible = 1;
9037 if (! EQ (Vx_no_window_manager, Qt))
9038 x_wm_set_window_state (f, NormalState);
9039 #ifdef USE_X_TOOLKIT
9040 if (FRAME_X_EMBEDDED_P (f))
9041 xembed_set_info (f, XEMBED_MAPPED);
9042 else
9044 /* This was XtPopup, but that did nothing for an iconified frame. */
9045 XtMapWidget (f->output_data.x->widget);
9047 #else /* not USE_X_TOOLKIT */
9048 #ifdef USE_GTK
9049 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
9050 gtk_window_deiconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
9051 #else
9052 if (FRAME_X_EMBEDDED_P (f))
9053 xembed_set_info (f, XEMBED_MAPPED);
9054 else
9055 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9056 #endif /* not USE_GTK */
9057 #endif /* not USE_X_TOOLKIT */
9060 XFlush (FRAME_X_DISPLAY (f));
9062 /* Synchronize to ensure Emacs knows the frame is visible
9063 before we do anything else. We do this loop with input not blocked
9064 so that incoming events are handled. */
9066 Lisp_Object frame;
9067 int count;
9068 /* This must be before UNBLOCK_INPUT
9069 since events that arrive in response to the actions above
9070 will set it when they are handled. */
9071 int previously_visible = f->output_data.x->has_been_visible;
9073 original_left = f->left_pos;
9074 original_top = f->top_pos;
9076 /* This must come after we set COUNT. */
9077 UNBLOCK_INPUT;
9079 /* We unblock here so that arriving X events are processed. */
9081 /* Now move the window back to where it was "supposed to be".
9082 But don't do it if the gravity is negative.
9083 When the gravity is negative, this uses a position
9084 that is 3 pixels too low. Perhaps that's really the border width.
9086 Don't do this if the window has never been visible before,
9087 because the window manager may choose the position
9088 and we don't want to override it. */
9090 if (! FRAME_VISIBLE_P (f)
9091 && ! FRAME_ICONIFIED_P (f)
9092 && ! FRAME_X_EMBEDDED_P (f)
9093 && f->win_gravity == NorthWestGravity
9094 && previously_visible)
9096 Drawable rootw;
9097 int x, y;
9098 unsigned int width, height, border, depth;
9100 BLOCK_INPUT;
9102 /* On some window managers (such as FVWM) moving an existing
9103 window, even to the same place, causes the window manager
9104 to introduce an offset. This can cause the window to move
9105 to an unexpected location. Check the geometry (a little
9106 slow here) and then verify that the window is in the right
9107 place. If the window is not in the right place, move it
9108 there, and take the potential window manager hit. */
9109 XGetGeometry (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
9110 &rootw, &x, &y, &width, &height, &border, &depth);
9112 if (original_left != x || original_top != y)
9113 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
9114 original_left, original_top);
9116 UNBLOCK_INPUT;
9119 XSETFRAME (frame, f);
9121 /* Wait until the frame is visible. Process X events until a
9122 MapNotify event has been seen, or until we think we won't get a
9123 MapNotify at all.. */
9124 for (count = input_signal_count + 10;
9125 input_signal_count < count && !FRAME_VISIBLE_P (f);)
9127 /* Force processing of queued events. */
9128 x_sync (f);
9130 /* Machines that do polling rather than SIGIO have been
9131 observed to go into a busy-wait here. So we'll fake an
9132 alarm signal to let the handler know that there's something
9133 to be read. We used to raise a real alarm, but it seems
9134 that the handler isn't always enabled here. This is
9135 probably a bug. */
9136 if (input_polling_used ())
9138 /* It could be confusing if a real alarm arrives while
9139 processing the fake one. Turn it off and let the
9140 handler reset it. */
9141 int old_poll_suppress_count = poll_suppress_count;
9142 poll_suppress_count = 1;
9143 poll_for_input_1 ();
9144 poll_suppress_count = old_poll_suppress_count;
9147 /* See if a MapNotify event has been processed. */
9148 FRAME_SAMPLE_VISIBILITY (f);
9151 /* 2000-09-28: In
9153 (let ((f (selected-frame)))
9154 (iconify-frame f)
9155 (raise-frame f))
9157 the frame is not raised with various window managers on
9158 FreeBSD, GNU/Linux and Solaris. It turns out that, for some
9159 unknown reason, the call to XtMapWidget is completely ignored.
9160 Mapping the widget a second time works. */
9162 if (!FRAME_VISIBLE_P (f) && --retry_count != 0)
9163 goto retry;
9167 /* Change from mapped state to withdrawn state. */
9169 /* Make the frame visible (mapped and not iconified). */
9171 void
9172 x_make_frame_invisible (struct frame *f)
9174 Window window;
9176 /* Use the frame's outermost window, not the one we normally draw on. */
9177 window = FRAME_OUTER_WINDOW (f);
9179 /* Don't keep the highlight on an invisible frame. */
9180 if (FRAME_X_DISPLAY_INFO (f)->x_highlight_frame == f)
9181 FRAME_X_DISPLAY_INFO (f)->x_highlight_frame = 0;
9183 BLOCK_INPUT;
9185 /* Before unmapping the window, update the WM_SIZE_HINTS property to claim
9186 that the current position of the window is user-specified, rather than
9187 program-specified, so that when the window is mapped again, it will be
9188 placed at the same location, without forcing the user to position it
9189 by hand again (they have already done that once for this window.) */
9190 x_wm_set_size_hint (f, (long) 0, 1);
9192 #ifdef USE_GTK
9193 if (FRAME_GTK_OUTER_WIDGET (f))
9194 gtk_widget_hide (FRAME_GTK_OUTER_WIDGET (f));
9195 else
9196 #else
9197 if (FRAME_X_EMBEDDED_P (f))
9198 xembed_set_info (f, 0);
9199 else
9200 #endif
9203 if (! XWithdrawWindow (FRAME_X_DISPLAY (f), window,
9204 DefaultScreen (FRAME_X_DISPLAY (f))))
9206 UNBLOCK_INPUT_RESIGNAL;
9207 error ("Can't notify window manager of window withdrawal");
9211 /* We can't distinguish this from iconification
9212 just by the event that we get from the server.
9213 So we can't win using the usual strategy of letting
9214 FRAME_SAMPLE_VISIBILITY set this. So do it by hand,
9215 and synchronize with the server to make sure we agree. */
9216 f->visible = 0;
9217 FRAME_ICONIFIED_P (f) = 0;
9218 f->async_visible = 0;
9219 f->async_iconified = 0;
9221 x_sync (f);
9223 UNBLOCK_INPUT;
9226 /* Change window state from mapped to iconified. */
9228 void
9229 x_iconify_frame (struct frame *f)
9231 #ifdef USE_X_TOOLKIT
9232 int result;
9233 #endif
9234 Lisp_Object type;
9236 /* Don't keep the highlight on an invisible frame. */
9237 if (FRAME_X_DISPLAY_INFO (f)->x_highlight_frame == f)
9238 FRAME_X_DISPLAY_INFO (f)->x_highlight_frame = 0;
9240 if (f->async_iconified)
9241 return;
9243 BLOCK_INPUT;
9245 FRAME_SAMPLE_VISIBILITY (f);
9247 type = x_icon_type (f);
9248 if (!NILP (type))
9249 x_bitmap_icon (f, type);
9251 #ifdef USE_GTK
9252 if (FRAME_GTK_OUTER_WIDGET (f))
9254 if (! FRAME_VISIBLE_P (f))
9255 gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
9257 gtk_window_iconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
9258 f->iconified = 1;
9259 f->visible = 1;
9260 f->async_iconified = 1;
9261 f->async_visible = 0;
9262 UNBLOCK_INPUT;
9263 return;
9265 #endif
9267 #ifdef USE_X_TOOLKIT
9269 if (! FRAME_VISIBLE_P (f))
9271 if (! EQ (Vx_no_window_manager, Qt))
9272 x_wm_set_window_state (f, IconicState);
9273 /* This was XtPopup, but that did nothing for an iconified frame. */
9274 XtMapWidget (f->output_data.x->widget);
9275 /* The server won't give us any event to indicate
9276 that an invisible frame was changed to an icon,
9277 so we have to record it here. */
9278 f->iconified = 1;
9279 f->visible = 1;
9280 f->async_iconified = 1;
9281 f->async_visible = 0;
9282 UNBLOCK_INPUT;
9283 return;
9286 result = XIconifyWindow (FRAME_X_DISPLAY (f),
9287 XtWindow (f->output_data.x->widget),
9288 DefaultScreen (FRAME_X_DISPLAY (f)));
9289 UNBLOCK_INPUT;
9291 if (!result)
9292 error ("Can't notify window manager of iconification");
9294 f->async_iconified = 1;
9295 f->async_visible = 0;
9298 BLOCK_INPUT;
9299 XFlush (FRAME_X_DISPLAY (f));
9300 UNBLOCK_INPUT;
9301 #else /* not USE_X_TOOLKIT */
9303 /* Make sure the X server knows where the window should be positioned,
9304 in case the user deiconifies with the window manager. */
9305 if (! FRAME_VISIBLE_P (f)
9306 && ! FRAME_ICONIFIED_P (f)
9307 && ! FRAME_X_EMBEDDED_P (f))
9308 x_set_offset (f, f->left_pos, f->top_pos, 0);
9310 /* Since we don't know which revision of X we're running, we'll use both
9311 the X11R3 and X11R4 techniques. I don't know if this is a good idea. */
9313 /* X11R4: send a ClientMessage to the window manager using the
9314 WM_CHANGE_STATE type. */
9316 XEvent msg;
9318 msg.xclient.window = FRAME_X_WINDOW (f);
9319 msg.xclient.type = ClientMessage;
9320 msg.xclient.message_type = FRAME_X_DISPLAY_INFO (f)->Xatom_wm_change_state;
9321 msg.xclient.format = 32;
9322 msg.xclient.data.l[0] = IconicState;
9324 if (! XSendEvent (FRAME_X_DISPLAY (f),
9325 DefaultRootWindow (FRAME_X_DISPLAY (f)),
9326 False,
9327 SubstructureRedirectMask | SubstructureNotifyMask,
9328 &msg))
9330 UNBLOCK_INPUT_RESIGNAL;
9331 error ("Can't notify window manager of iconification");
9335 /* X11R3: set the initial_state field of the window manager hints to
9336 IconicState. */
9337 x_wm_set_window_state (f, IconicState);
9339 if (!FRAME_VISIBLE_P (f))
9341 /* If the frame was withdrawn, before, we must map it. */
9342 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9345 f->async_iconified = 1;
9346 f->async_visible = 0;
9348 XFlush (FRAME_X_DISPLAY (f));
9349 UNBLOCK_INPUT;
9350 #endif /* not USE_X_TOOLKIT */
9354 /* Free X resources of frame F. */
9356 void
9357 x_free_frame_resources (struct frame *f)
9359 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
9360 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
9361 #ifdef USE_X_TOOLKIT
9362 Lisp_Object bar;
9363 struct scroll_bar *b;
9364 #endif
9366 BLOCK_INPUT;
9368 /* If a display connection is dead, don't try sending more
9369 commands to the X server. */
9370 if (dpyinfo->display)
9372 /* We must free faces before destroying windows because some
9373 font-driver (e.g. xft) access a window while finishing a
9374 face. */
9375 if (FRAME_FACE_CACHE (f))
9376 free_frame_faces (f);
9378 if (f->output_data.x->icon_desc)
9379 XDestroyWindow (FRAME_X_DISPLAY (f), f->output_data.x->icon_desc);
9381 #ifdef USE_X_TOOLKIT
9382 /* Explicitly destroy the scroll bars of the frame. Without
9383 this, we get "BadDrawable" errors from the toolkit later on,
9384 presumably from expose events generated for the disappearing
9385 toolkit scroll bars. */
9386 for (bar = FRAME_SCROLL_BARS (f); !NILP (bar); bar = b->next)
9388 b = XSCROLL_BAR (bar);
9389 x_scroll_bar_remove (b);
9391 #endif
9393 #ifdef HAVE_X_I18N
9394 if (FRAME_XIC (f))
9395 free_frame_xic (f);
9396 #endif
9398 #ifdef USE_X_TOOLKIT
9399 if (f->output_data.x->widget)
9401 XtDestroyWidget (f->output_data.x->widget);
9402 f->output_data.x->widget = NULL;
9404 /* Tooltips don't have widgets, only a simple X window, even if
9405 we are using a toolkit. */
9406 else if (FRAME_X_WINDOW (f))
9407 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9409 free_frame_menubar (f);
9410 #else /* !USE_X_TOOLKIT */
9412 #ifdef USE_GTK
9413 xg_free_frame_widgets (f);
9414 #endif /* USE_GTK */
9416 if (FRAME_X_WINDOW (f))
9417 XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9418 #endif /* !USE_X_TOOLKIT */
9420 unload_color (f, FRAME_FOREGROUND_PIXEL (f));
9421 unload_color (f, FRAME_BACKGROUND_PIXEL (f));
9422 unload_color (f, f->output_data.x->cursor_pixel);
9423 unload_color (f, f->output_data.x->cursor_foreground_pixel);
9424 unload_color (f, f->output_data.x->border_pixel);
9425 unload_color (f, f->output_data.x->mouse_pixel);
9427 if (f->output_data.x->scroll_bar_background_pixel != -1)
9428 unload_color (f, f->output_data.x->scroll_bar_background_pixel);
9429 if (f->output_data.x->scroll_bar_foreground_pixel != -1)
9430 unload_color (f, f->output_data.x->scroll_bar_foreground_pixel);
9431 #ifdef USE_TOOLKIT_SCROLL_BARS
9432 /* Scrollbar shadow colors. */
9433 if (f->output_data.x->scroll_bar_top_shadow_pixel != -1)
9434 unload_color (f, f->output_data.x->scroll_bar_top_shadow_pixel);
9435 if (f->output_data.x->scroll_bar_bottom_shadow_pixel != -1)
9436 unload_color (f, f->output_data.x->scroll_bar_bottom_shadow_pixel);
9437 #endif /* USE_TOOLKIT_SCROLL_BARS */
9438 if (f->output_data.x->white_relief.allocated_p)
9439 unload_color (f, f->output_data.x->white_relief.pixel);
9440 if (f->output_data.x->black_relief.allocated_p)
9441 unload_color (f, f->output_data.x->black_relief.pixel);
9443 x_free_gcs (f);
9444 XFlush (FRAME_X_DISPLAY (f));
9447 xfree (f->output_data.x->saved_menu_event);
9448 xfree (f->output_data.x);
9449 f->output_data.x = NULL;
9451 if (f == dpyinfo->x_focus_frame)
9452 dpyinfo->x_focus_frame = 0;
9453 if (f == dpyinfo->x_focus_event_frame)
9454 dpyinfo->x_focus_event_frame = 0;
9455 if (f == dpyinfo->x_highlight_frame)
9456 dpyinfo->x_highlight_frame = 0;
9458 if (f == hlinfo->mouse_face_mouse_frame)
9460 hlinfo->mouse_face_beg_row
9461 = hlinfo->mouse_face_beg_col = -1;
9462 hlinfo->mouse_face_end_row
9463 = hlinfo->mouse_face_end_col = -1;
9464 hlinfo->mouse_face_window = Qnil;
9465 hlinfo->mouse_face_deferred_gc = 0;
9466 hlinfo->mouse_face_mouse_frame = 0;
9469 UNBLOCK_INPUT;
9473 /* Destroy the X window of frame F. */
9475 static void
9476 x_destroy_window (struct frame *f)
9478 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
9480 /* If a display connection is dead, don't try sending more
9481 commands to the X server. */
9482 if (dpyinfo->display != 0)
9483 x_free_frame_resources (f);
9485 dpyinfo->reference_count--;
9489 /* Setting window manager hints. */
9491 /* Set the normal size hints for the window manager, for frame F.
9492 FLAGS is the flags word to use--or 0 meaning preserve the flags
9493 that the window now has.
9494 If USER_POSITION is nonzero, we set the USPosition
9495 flag (this is useful when FLAGS is 0).
9496 The GTK version is in gtkutils.c */
9498 #ifndef USE_GTK
9499 void
9500 x_wm_set_size_hint (struct frame *f, long flags, int user_position)
9502 XSizeHints size_hints;
9503 Window window = FRAME_OUTER_WINDOW (f);
9505 /* Setting PMaxSize caused various problems. */
9506 size_hints.flags = PResizeInc | PMinSize /* | PMaxSize */;
9508 size_hints.x = f->left_pos;
9509 size_hints.y = f->top_pos;
9511 size_hints.height = FRAME_PIXEL_HEIGHT (f);
9512 size_hints.width = FRAME_PIXEL_WIDTH (f);
9514 size_hints.width_inc = FRAME_COLUMN_WIDTH (f);
9515 size_hints.height_inc = FRAME_LINE_HEIGHT (f);
9516 size_hints.max_width = x_display_pixel_width (FRAME_X_DISPLAY_INFO (f))
9517 - FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
9518 size_hints.max_height = x_display_pixel_height (FRAME_X_DISPLAY_INFO (f))
9519 - FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
9521 /* Calculate the base and minimum sizes. */
9523 int base_width, base_height;
9524 int min_rows = 0, min_cols = 0;
9526 base_width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
9527 base_height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
9529 check_frame_size (f, &min_rows, &min_cols);
9531 /* The window manager uses the base width hints to calculate the
9532 current number of rows and columns in the frame while
9533 resizing; min_width and min_height aren't useful for this
9534 purpose, since they might not give the dimensions for a
9535 zero-row, zero-column frame.
9537 We use the base_width and base_height members if we have
9538 them; otherwise, we set the min_width and min_height members
9539 to the size for a zero x zero frame. */
9541 size_hints.flags |= PBaseSize;
9542 size_hints.base_width = base_width;
9543 size_hints.base_height = base_height + FRAME_MENUBAR_HEIGHT (f);
9544 size_hints.min_width = base_width + min_cols * size_hints.width_inc;
9545 size_hints.min_height = base_height + min_rows * size_hints.height_inc;
9548 /* If we don't need the old flags, we don't need the old hint at all. */
9549 if (flags)
9551 size_hints.flags |= flags;
9552 goto no_read;
9556 XSizeHints hints; /* Sometimes I hate X Windows... */
9557 long supplied_return;
9558 int value;
9560 value = XGetWMNormalHints (FRAME_X_DISPLAY (f), window, &hints,
9561 &supplied_return);
9563 if (flags)
9564 size_hints.flags |= flags;
9565 else
9567 if (value == 0)
9568 hints.flags = 0;
9569 if (hints.flags & PSize)
9570 size_hints.flags |= PSize;
9571 if (hints.flags & PPosition)
9572 size_hints.flags |= PPosition;
9573 if (hints.flags & USPosition)
9574 size_hints.flags |= USPosition;
9575 if (hints.flags & USSize)
9576 size_hints.flags |= USSize;
9580 no_read:
9582 #ifdef PWinGravity
9583 size_hints.win_gravity = f->win_gravity;
9584 size_hints.flags |= PWinGravity;
9586 if (user_position)
9588 size_hints.flags &= ~ PPosition;
9589 size_hints.flags |= USPosition;
9591 #endif /* PWinGravity */
9593 XSetWMNormalHints (FRAME_X_DISPLAY (f), window, &size_hints);
9595 #endif /* not USE_GTK */
9597 /* Used for IconicState or NormalState */
9599 static void
9600 x_wm_set_window_state (struct frame *f, int state)
9602 #ifdef USE_X_TOOLKIT
9603 Arg al[1];
9605 XtSetArg (al[0], XtNinitialState, state);
9606 XtSetValues (f->output_data.x->widget, al, 1);
9607 #else /* not USE_X_TOOLKIT */
9608 Window window = FRAME_X_WINDOW (f);
9610 f->output_data.x->wm_hints.flags |= StateHint;
9611 f->output_data.x->wm_hints.initial_state = state;
9613 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
9614 #endif /* not USE_X_TOOLKIT */
9617 static void
9618 x_wm_set_icon_pixmap (struct frame *f, ptrdiff_t pixmap_id)
9620 Pixmap icon_pixmap, icon_mask;
9622 #if !defined USE_X_TOOLKIT && !defined USE_GTK
9623 Window window = FRAME_OUTER_WINDOW (f);
9624 #endif
9626 if (pixmap_id > 0)
9628 icon_pixmap = x_bitmap_pixmap (f, pixmap_id);
9629 f->output_data.x->wm_hints.icon_pixmap = icon_pixmap;
9630 icon_mask = x_bitmap_mask (f, pixmap_id);
9631 f->output_data.x->wm_hints.icon_mask = icon_mask;
9633 else
9635 /* It seems there is no way to turn off use of an icon
9636 pixmap. */
9637 return;
9641 #ifdef USE_GTK
9643 xg_set_frame_icon (f, icon_pixmap, icon_mask);
9644 return;
9647 #elif defined (USE_X_TOOLKIT) /* same as in x_wm_set_window_state. */
9650 Arg al[1];
9651 XtSetArg (al[0], XtNiconPixmap, icon_pixmap);
9652 XtSetValues (f->output_data.x->widget, al, 1);
9653 XtSetArg (al[0], XtNiconMask, icon_mask);
9654 XtSetValues (f->output_data.x->widget, al, 1);
9657 #else /* not USE_X_TOOLKIT && not USE_GTK */
9659 f->output_data.x->wm_hints.flags |= (IconPixmapHint | IconMaskHint);
9660 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
9662 #endif /* not USE_X_TOOLKIT && not USE_GTK */
9665 void
9666 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
9668 Window window = FRAME_OUTER_WINDOW (f);
9670 f->output_data.x->wm_hints.flags |= IconPositionHint;
9671 f->output_data.x->wm_hints.icon_x = icon_x;
9672 f->output_data.x->wm_hints.icon_y = icon_y;
9674 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
9678 /***********************************************************************
9679 Fonts
9680 ***********************************************************************/
9682 #if GLYPH_DEBUG
9684 /* Check that FONT is valid on frame F. It is if it can be found in F's
9685 font table. */
9687 static void
9688 x_check_font (struct frame *f, struct font *font)
9690 xassert (font != NULL && ! NILP (font->props[FONT_TYPE_INDEX]));
9691 if (font->driver->check)
9692 xassert (font->driver->check (f, font) == 0);
9695 #endif /* GLYPH_DEBUG != 0 */
9698 /***********************************************************************
9699 Initialization
9700 ***********************************************************************/
9702 #ifdef USE_X_TOOLKIT
9703 static XrmOptionDescRec emacs_options[] = {
9704 {"-geometry", ".geometry", XrmoptionSepArg, NULL},
9705 {"-iconic", ".iconic", XrmoptionNoArg, (XtPointer) "yes"},
9707 {"-internal-border-width", "*EmacsScreen.internalBorderWidth",
9708 XrmoptionSepArg, NULL},
9709 {"-ib", "*EmacsScreen.internalBorderWidth", XrmoptionSepArg, NULL},
9711 {"-T", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
9712 {"-wn", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
9713 {"-title", "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
9714 {"-iconname", "*EmacsShell.iconName", XrmoptionSepArg, (XtPointer) NULL},
9715 {"-in", "*EmacsShell.iconName", XrmoptionSepArg, (XtPointer) NULL},
9716 {"-mc", "*pointerColor", XrmoptionSepArg, (XtPointer) NULL},
9717 {"-cr", "*cursorColor", XrmoptionSepArg, (XtPointer) NULL}
9720 /* Whether atimer for Xt timeouts is activated or not. */
9722 static int x_timeout_atimer_activated_flag;
9724 #endif /* USE_X_TOOLKIT */
9726 static int x_initialized;
9728 /* Test whether two display-name strings agree up to the dot that separates
9729 the screen number from the server number. */
9730 static int
9731 same_x_server (const char *name1, const char *name2)
9733 int seen_colon = 0;
9734 const char *system_name = SSDATA (Vsystem_name);
9735 ptrdiff_t system_name_length = SBYTES (Vsystem_name);
9736 ptrdiff_t length_until_period = 0;
9738 while (system_name[length_until_period] != 0
9739 && system_name[length_until_period] != '.')
9740 length_until_period++;
9742 /* Treat `unix' like an empty host name. */
9743 if (! strncmp (name1, "unix:", 5))
9744 name1 += 4;
9745 if (! strncmp (name2, "unix:", 5))
9746 name2 += 4;
9747 /* Treat this host's name like an empty host name. */
9748 if (! strncmp (name1, system_name, system_name_length)
9749 && name1[system_name_length] == ':')
9750 name1 += system_name_length;
9751 if (! strncmp (name2, system_name, system_name_length)
9752 && name2[system_name_length] == ':')
9753 name2 += system_name_length;
9754 /* Treat this host's domainless name like an empty host name. */
9755 if (! strncmp (name1, system_name, length_until_period)
9756 && name1[length_until_period] == ':')
9757 name1 += length_until_period;
9758 if (! strncmp (name2, system_name, length_until_period)
9759 && name2[length_until_period] == ':')
9760 name2 += length_until_period;
9762 for (; *name1 != '\0' && *name1 == *name2; name1++, name2++)
9764 if (*name1 == ':')
9765 seen_colon = 1;
9766 if (seen_colon && *name1 == '.')
9767 return 1;
9769 return (seen_colon
9770 && (*name1 == '.' || *name1 == '\0')
9771 && (*name2 == '.' || *name2 == '\0'));
9774 /* Count number of set bits in mask and number of bits to shift to
9775 get to the first bit. With MASK 0x7e0, *BITS is set to 6, and *OFFSET
9776 to 5. */
9777 static void
9778 get_bits_and_offset (long unsigned int mask, int *bits, int *offset)
9780 int nr = 0;
9781 int off = 0;
9783 while (!(mask & 1))
9785 off++;
9786 mask >>= 1;
9789 while (mask & 1)
9791 nr++;
9792 mask >>= 1;
9795 *offset = off;
9796 *bits = nr;
9799 /* Return 1 if display DISPLAY is available for use, 0 otherwise.
9800 But don't permanently open it, just test its availability. */
9803 x_display_ok (const char *display)
9805 int dpy_ok = 1;
9806 Display *dpy;
9808 dpy = XOpenDisplay (display);
9809 if (dpy)
9810 XCloseDisplay (dpy);
9811 else
9812 dpy_ok = 0;
9813 return dpy_ok;
9816 #ifdef USE_GTK
9817 static void
9818 my_log_handler (const gchar *log_domain, GLogLevelFlags log_level,
9819 const gchar *msg, gpointer user_data)
9821 if (!strstr (msg, "g_set_prgname"))
9822 fprintf (stderr, "%s-WARNING **: %s\n", log_domain, msg);
9824 #endif
9826 /* Open a connection to X display DISPLAY_NAME, and return
9827 the structure that describes the open display.
9828 If we cannot contact the display, return null. */
9830 struct x_display_info *
9831 x_term_init (Lisp_Object display_name, char *xrm_option, char *resource_name)
9833 int connection;
9834 Display *dpy;
9835 struct terminal *terminal;
9836 struct x_display_info *dpyinfo;
9837 XrmDatabase xrdb;
9838 Mouse_HLInfo *hlinfo;
9840 BLOCK_INPUT;
9842 if (!x_initialized)
9844 x_initialize ();
9845 ++x_initialized;
9848 if (! x_display_ok (SSDATA (display_name)))
9849 error ("Display %s can't be opened", SSDATA (display_name));
9851 #ifdef USE_GTK
9853 #define NUM_ARGV 10
9854 int argc;
9855 char *argv[NUM_ARGV];
9856 char **argv2 = argv;
9857 guint id;
9859 if (x_initialized++ > 1)
9861 xg_display_open (SSDATA (display_name), &dpy);
9863 else
9865 static char display_opt[] = "--display";
9866 static char name_opt[] = "--name";
9868 for (argc = 0; argc < NUM_ARGV; ++argc)
9869 argv[argc] = 0;
9871 argc = 0;
9872 argv[argc++] = initial_argv[0];
9874 if (! NILP (display_name))
9876 argv[argc++] = display_opt;
9877 argv[argc++] = SSDATA (display_name);
9880 argv[argc++] = name_opt;
9881 argv[argc++] = resource_name;
9883 XSetLocaleModifiers ("");
9885 /* Emacs can only handle core input events, so make sure
9886 Gtk doesn't use Xinput or Xinput2 extensions. */
9888 static char fix_events[] = "GDK_CORE_DEVICE_EVENTS=1";
9889 putenv (fix_events);
9892 /* Work around GLib bug that outputs a faulty warning. See
9893 https://bugzilla.gnome.org/show_bug.cgi?id=563627. */
9894 id = g_log_set_handler ("GLib", G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
9895 | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
9896 #ifdef HAVE_CLUTTER
9897 gtk_clutter_init (&argc, &argv2);
9898 #else
9899 gtk_init (&argc, &argv2);
9900 #endif
9901 g_log_remove_handler ("GLib", id);
9903 /* gtk_init does set_locale. We must fix locale after calling it. */
9904 fixup_locale ();
9905 xg_initialize ();
9907 dpy = DEFAULT_GDK_DISPLAY ();
9909 /* NULL window -> events for all windows go to our function */
9910 gdk_window_add_filter (NULL, event_handler_gdk, NULL);
9912 #if GTK_MAJOR_VERSION <= 2 && GTK_MINOR_VERSION <= 90
9913 /* Load our own gtkrc if it exists. */
9915 const char *file = "~/.emacs.d/gtkrc";
9916 Lisp_Object s, abs_file;
9918 s = make_string (file, strlen (file));
9919 abs_file = Fexpand_file_name (s, Qnil);
9921 if (! NILP (abs_file) && !NILP (Ffile_readable_p (abs_file)))
9922 gtk_rc_parse (SSDATA (abs_file));
9924 #endif
9926 XSetErrorHandler (x_error_handler);
9927 XSetIOErrorHandler (x_io_error_quitter);
9930 #else /* not USE_GTK */
9931 #ifdef USE_X_TOOLKIT
9932 /* weiner@footloose.sps.mot.com reports that this causes
9933 errors with X11R5:
9934 X protocol error: BadAtom (invalid Atom parameter)
9935 on protocol request 18skiloaf.
9936 So let's not use it until R6. */
9937 #ifdef HAVE_X11XTR6
9938 XtSetLanguageProc (NULL, NULL, NULL);
9939 #endif
9942 int argc = 0;
9943 char *argv[3];
9945 argv[0] = "";
9946 argc = 1;
9947 if (xrm_option)
9949 argv[argc++] = "-xrm";
9950 argv[argc++] = xrm_option;
9952 turn_on_atimers (0);
9953 dpy = XtOpenDisplay (Xt_app_con, SSDATA (display_name),
9954 resource_name, EMACS_CLASS,
9955 emacs_options, XtNumber (emacs_options),
9956 &argc, argv);
9957 turn_on_atimers (1);
9959 #ifdef HAVE_X11XTR6
9960 /* I think this is to compensate for XtSetLanguageProc. */
9961 fixup_locale ();
9962 #endif
9965 #else /* not USE_X_TOOLKIT */
9966 XSetLocaleModifiers ("");
9967 dpy = XOpenDisplay (SSDATA (display_name));
9968 #endif /* not USE_X_TOOLKIT */
9969 #endif /* not USE_GTK*/
9971 /* Detect failure. */
9972 if (dpy == 0)
9974 UNBLOCK_INPUT;
9975 return 0;
9978 /* We have definitely succeeded. Record the new connection. */
9980 dpyinfo = (struct x_display_info *) xmalloc (sizeof (struct x_display_info));
9981 memset (dpyinfo, 0, sizeof *dpyinfo);
9982 hlinfo = &dpyinfo->mouse_highlight;
9984 terminal = x_create_terminal (dpyinfo);
9987 struct x_display_info *share;
9988 Lisp_Object tail;
9990 for (share = x_display_list, tail = x_display_name_list; share;
9991 share = share->next, tail = XCDR (tail))
9992 if (same_x_server (SSDATA (XCAR (XCAR (tail))),
9993 SSDATA (display_name)))
9994 break;
9995 if (share)
9996 terminal->kboard = share->terminal->kboard;
9997 else
9999 terminal->kboard = (KBOARD *) xmalloc (sizeof (KBOARD));
10000 init_kboard (terminal->kboard);
10001 KVAR (terminal->kboard, Vwindow_system) = Qx;
10003 /* Add the keyboard to the list before running Lisp code (via
10004 Qvendor_specific_keysyms below), since these are not traced
10005 via terminals but only through all_kboards. */
10006 terminal->kboard->next_kboard = all_kboards;
10007 all_kboards = terminal->kboard;
10009 if (!EQ (XSYMBOL (Qvendor_specific_keysyms)->function, Qunbound))
10011 char *vendor = ServerVendor (dpy);
10013 /* Protect terminal from GC before removing it from the
10014 list of terminals. */
10015 struct gcpro gcpro1;
10016 Lisp_Object gcpro_term;
10017 XSETTERMINAL (gcpro_term, terminal);
10018 GCPRO1 (gcpro_term);
10020 /* Temporarily hide the partially initialized terminal. */
10021 terminal_list = terminal->next_terminal;
10022 UNBLOCK_INPUT;
10023 KVAR (terminal->kboard, Vsystem_key_alist)
10024 = call1 (Qvendor_specific_keysyms,
10025 vendor ? build_string (vendor) : empty_unibyte_string);
10026 BLOCK_INPUT;
10027 terminal->next_terminal = terminal_list;
10028 terminal_list = terminal;
10029 UNGCPRO;
10032 /* Don't let the initial kboard remain current longer than necessary.
10033 That would cause problems if a file loaded on startup tries to
10034 prompt in the mini-buffer. */
10035 if (current_kboard == initial_kboard)
10036 current_kboard = terminal->kboard;
10038 terminal->kboard->reference_count++;
10041 /* Put this display on the chain. */
10042 dpyinfo->next = x_display_list;
10043 x_display_list = dpyinfo;
10045 /* Put it on x_display_name_list as well, to keep them parallel. */
10046 x_display_name_list = Fcons (Fcons (display_name, Qnil),
10047 x_display_name_list);
10048 dpyinfo->name_list_element = XCAR (x_display_name_list);
10050 dpyinfo->display = dpy;
10052 /* Set the name of the terminal. */
10053 terminal->name = (char *) xmalloc (SBYTES (display_name) + 1);
10054 strncpy (terminal->name, SSDATA (display_name), SBYTES (display_name));
10055 terminal->name[SBYTES (display_name)] = 0;
10057 #if 0
10058 XSetAfterFunction (x_current_display, x_trace_wire);
10059 #endif /* ! 0 */
10061 dpyinfo->x_id_name
10062 = (char *) xmalloc (SBYTES (Vinvocation_name)
10063 + SBYTES (Vsystem_name)
10064 + 2);
10065 sprintf (dpyinfo->x_id_name, "%s@%s",
10066 SSDATA (Vinvocation_name), SSDATA (Vsystem_name));
10068 /* Figure out which modifier bits mean what. */
10069 x_find_modifier_meanings (dpyinfo);
10071 /* Get the scroll bar cursor. */
10072 #ifdef USE_GTK
10073 /* We must create a GTK cursor, it is required for GTK widgets. */
10074 dpyinfo->xg_cursor = xg_create_default_cursor (dpyinfo->display);
10075 #endif /* USE_GTK */
10077 dpyinfo->vertical_scroll_bar_cursor
10078 = XCreateFontCursor (dpyinfo->display, XC_sb_v_double_arrow);
10080 xrdb = x_load_resources (dpyinfo->display, xrm_option,
10081 resource_name, EMACS_CLASS);
10082 #ifdef HAVE_XRMSETDATABASE
10083 XrmSetDatabase (dpyinfo->display, xrdb);
10084 #else
10085 dpyinfo->display->db = xrdb;
10086 #endif
10087 /* Put the rdb where we can find it in a way that works on
10088 all versions. */
10089 dpyinfo->xrdb = xrdb;
10091 dpyinfo->screen = ScreenOfDisplay (dpyinfo->display,
10092 DefaultScreen (dpyinfo->display));
10093 select_visual (dpyinfo);
10094 dpyinfo->cmap = DefaultColormapOfScreen (dpyinfo->screen);
10095 dpyinfo->root_window = RootWindowOfScreen (dpyinfo->screen);
10096 dpyinfo->client_leader_window = 0;
10097 dpyinfo->grabbed = 0;
10098 dpyinfo->reference_count = 0;
10099 dpyinfo->icon_bitmap_id = -1;
10100 dpyinfo->n_fonts = 0;
10101 dpyinfo->bitmaps = 0;
10102 dpyinfo->bitmaps_size = 0;
10103 dpyinfo->bitmaps_last = 0;
10104 dpyinfo->scratch_cursor_gc = 0;
10105 hlinfo->mouse_face_mouse_frame = 0;
10106 hlinfo->mouse_face_deferred_gc = 0;
10107 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
10108 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
10109 hlinfo->mouse_face_face_id = DEFAULT_FACE_ID;
10110 hlinfo->mouse_face_window = Qnil;
10111 hlinfo->mouse_face_overlay = Qnil;
10112 hlinfo->mouse_face_mouse_x = hlinfo->mouse_face_mouse_y = 0;
10113 hlinfo->mouse_face_defer = 0;
10114 hlinfo->mouse_face_hidden = 0;
10115 dpyinfo->x_focus_frame = 0;
10116 dpyinfo->x_focus_event_frame = 0;
10117 dpyinfo->x_highlight_frame = 0;
10118 dpyinfo->wm_type = X_WMTYPE_UNKNOWN;
10120 /* See if we can construct pixel values from RGB values. */
10121 dpyinfo->red_bits = dpyinfo->blue_bits = dpyinfo->green_bits = 0;
10122 dpyinfo->red_offset = dpyinfo->blue_offset = dpyinfo->green_offset = 0;
10124 if (dpyinfo->visual->class == TrueColor)
10126 get_bits_and_offset (dpyinfo->visual->red_mask,
10127 &dpyinfo->red_bits, &dpyinfo->red_offset);
10128 get_bits_and_offset (dpyinfo->visual->blue_mask,
10129 &dpyinfo->blue_bits, &dpyinfo->blue_offset);
10130 get_bits_and_offset (dpyinfo->visual->green_mask,
10131 &dpyinfo->green_bits, &dpyinfo->green_offset);
10134 /* See if a private colormap is requested. */
10135 if (dpyinfo->visual == DefaultVisualOfScreen (dpyinfo->screen))
10137 if (dpyinfo->visual->class == PseudoColor)
10139 Lisp_Object value;
10140 value = display_x_get_resource (dpyinfo,
10141 build_string ("privateColormap"),
10142 build_string ("PrivateColormap"),
10143 Qnil, Qnil);
10144 if (STRINGP (value)
10145 && (!strcmp (SSDATA (value), "true")
10146 || !strcmp (SSDATA (value), "on")))
10147 dpyinfo->cmap = XCopyColormapAndFree (dpyinfo->display, dpyinfo->cmap);
10150 else
10151 dpyinfo->cmap = XCreateColormap (dpyinfo->display, dpyinfo->root_window,
10152 dpyinfo->visual, AllocNone);
10154 #ifdef HAVE_XFT
10156 /* If we are using Xft, check dpi value in X resources.
10157 It is better we use it as well, since Xft will use it, as will all
10158 Gnome applications. If our real DPI is smaller or larger than the
10159 one Xft uses, our font will look smaller or larger than other
10160 for other applications, even if it is the same font name (monospace-10
10161 for example). */
10162 char *v = XGetDefault (dpyinfo->display, "Xft", "dpi");
10163 double d;
10164 if (v != NULL && sscanf (v, "%lf", &d) == 1)
10165 dpyinfo->resy = dpyinfo->resx = d;
10167 #endif
10169 if (dpyinfo->resy < 1)
10171 int screen_number = XScreenNumberOfScreen (dpyinfo->screen);
10172 double pixels = DisplayHeight (dpyinfo->display, screen_number);
10173 double mm = DisplayHeightMM (dpyinfo->display, screen_number);
10174 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
10175 dpyinfo->resy = (mm < 1) ? 100 : pixels * 25.4 / mm;
10176 pixels = DisplayWidth (dpyinfo->display, screen_number);
10177 mm = DisplayWidthMM (dpyinfo->display, screen_number);
10178 /* Mac OS X 10.3's Xserver sometimes reports 0.0mm. */
10179 dpyinfo->resx = (mm < 1) ? 100 : pixels * 25.4 / mm;
10183 const struct
10185 const char *name;
10186 Atom *atom;
10187 } atom_refs[] = {
10188 { "WM_PROTOCOLS", &dpyinfo->Xatom_wm_protocols },
10189 { "WM_TAKE_FOCUS", &dpyinfo->Xatom_wm_take_focus },
10190 { "WM_SAVE_YOURSELF", &dpyinfo->Xatom_wm_save_yourself },
10191 { "WM_DELETE_WINDOW", &dpyinfo->Xatom_wm_delete_window },
10192 { "WM_CHANGE_STATE", &dpyinfo->Xatom_wm_change_state },
10193 { "WM_CONFIGURE_DENIED", &dpyinfo->Xatom_wm_configure_denied },
10194 { "WM_MOVED", &dpyinfo->Xatom_wm_window_moved },
10195 { "WM_CLIENT_LEADER", &dpyinfo->Xatom_wm_client_leader },
10196 { "Editres", &dpyinfo->Xatom_editres },
10197 { "CLIPBOARD", &dpyinfo->Xatom_CLIPBOARD },
10198 { "TIMESTAMP", &dpyinfo->Xatom_TIMESTAMP },
10199 { "TEXT", &dpyinfo->Xatom_TEXT },
10200 { "COMPOUND_TEXT", &dpyinfo->Xatom_COMPOUND_TEXT },
10201 { "UTF8_STRING", &dpyinfo->Xatom_UTF8_STRING },
10202 { "DELETE", &dpyinfo->Xatom_DELETE },
10203 { "MULTIPLE", &dpyinfo->Xatom_MULTIPLE },
10204 { "INCR", &dpyinfo->Xatom_INCR },
10205 { "_EMACS_TMP_", &dpyinfo->Xatom_EMACS_TMP },
10206 { "TARGETS", &dpyinfo->Xatom_TARGETS },
10207 { "NULL", &dpyinfo->Xatom_NULL },
10208 { "ATOM", &dpyinfo->Xatom_ATOM },
10209 { "ATOM_PAIR", &dpyinfo->Xatom_ATOM_PAIR },
10210 { "CLIPBOARD_MANAGER", &dpyinfo->Xatom_CLIPBOARD_MANAGER },
10211 { "_XEMBED_INFO", &dpyinfo->Xatom_XEMBED_INFO },
10212 /* For properties of font. */
10213 { "PIXEL_SIZE", &dpyinfo->Xatom_PIXEL_SIZE },
10214 { "AVERAGE_WIDTH", &dpyinfo->Xatom_AVERAGE_WIDTH },
10215 { "_MULE_BASELINE_OFFSET", &dpyinfo->Xatom_MULE_BASELINE_OFFSET },
10216 { "_MULE_RELATIVE_COMPOSE", &dpyinfo->Xatom_MULE_RELATIVE_COMPOSE },
10217 { "_MULE_DEFAULT_ASCENT", &dpyinfo->Xatom_MULE_DEFAULT_ASCENT },
10218 /* Ghostscript support. */
10219 { "DONE", &dpyinfo->Xatom_DONE },
10220 { "PAGE", &dpyinfo->Xatom_PAGE },
10221 { "SCROLLBAR", &dpyinfo->Xatom_Scrollbar },
10222 { "_XEMBED", &dpyinfo->Xatom_XEMBED },
10223 /* EWMH */
10224 { "_NET_WM_STATE", &dpyinfo->Xatom_net_wm_state },
10225 { "_NET_WM_STATE_FULLSCREEN", &dpyinfo->Xatom_net_wm_state_fullscreen },
10226 { "_NET_WM_STATE_MAXIMIZED_HORZ",
10227 &dpyinfo->Xatom_net_wm_state_maximized_horz },
10228 { "_NET_WM_STATE_MAXIMIZED_VERT",
10229 &dpyinfo->Xatom_net_wm_state_maximized_vert },
10230 { "_NET_WM_STATE_STICKY", &dpyinfo->Xatom_net_wm_state_sticky },
10231 { "_NET_WM_WINDOW_TYPE", &dpyinfo->Xatom_net_window_type },
10232 { "_NET_WM_WINDOW_TYPE_TOOLTIP",
10233 &dpyinfo->Xatom_net_window_type_tooltip },
10234 { "_NET_WM_ICON_NAME", &dpyinfo->Xatom_net_wm_icon_name },
10235 { "_NET_WM_NAME", &dpyinfo->Xatom_net_wm_name },
10236 { "_NET_SUPPORTED", &dpyinfo->Xatom_net_supported },
10237 { "_NET_SUPPORTING_WM_CHECK", &dpyinfo->Xatom_net_supporting_wm_check },
10238 { "_NET_WM_WINDOW_OPACITY", &dpyinfo->Xatom_net_wm_window_opacity },
10239 { "_NET_ACTIVE_WINDOW", &dpyinfo->Xatom_net_active_window },
10240 { "_NET_FRAME_EXTENTS", &dpyinfo->Xatom_net_frame_extents },
10241 /* Session management */
10242 { "SM_CLIENT_ID", &dpyinfo->Xatom_SM_CLIENT_ID },
10243 { "_XSETTINGS_SETTINGS", &dpyinfo->Xatom_xsettings_prop },
10244 { "MANAGER", &dpyinfo->Xatom_xsettings_mgr },
10247 int i;
10248 const int atom_count = sizeof (atom_refs) / sizeof (atom_refs[0]);
10249 /* 1 for _XSETTINGS_SN */
10250 const int total_atom_count = 1 + atom_count;
10251 Atom *atoms_return = xmalloc (sizeof (Atom) * total_atom_count);
10252 char **atom_names = xmalloc (sizeof (char *) * total_atom_count);
10253 char xsettings_atom_name[64];
10255 for (i = 0; i < atom_count; i++)
10256 atom_names[i] = (char *) atom_refs[i].name;
10258 /* Build _XSETTINGS_SN atom name */
10259 snprintf (xsettings_atom_name, sizeof (xsettings_atom_name),
10260 "_XSETTINGS_S%d", XScreenNumberOfScreen (dpyinfo->screen));
10261 atom_names[i] = xsettings_atom_name;
10263 XInternAtoms (dpyinfo->display, atom_names, total_atom_count,
10264 False, atoms_return);
10266 for (i = 0; i < atom_count; i++)
10267 *atom_refs[i].atom = atoms_return[i];
10269 /* Manual copy of last atom */
10270 dpyinfo->Xatom_xsettings_sel = atoms_return[i];
10272 xfree (atom_names);
10273 xfree (atoms_return);
10276 dpyinfo->x_dnd_atoms_size = 8;
10277 dpyinfo->x_dnd_atoms_length = 0;
10278 dpyinfo->x_dnd_atoms = xmalloc (sizeof (*dpyinfo->x_dnd_atoms)
10279 * dpyinfo->x_dnd_atoms_size);
10281 dpyinfo->net_supported_atoms = NULL;
10282 dpyinfo->nr_net_supported_atoms = 0;
10283 dpyinfo->net_supported_window = 0;
10285 connection = ConnectionNumber (dpyinfo->display);
10286 dpyinfo->connection = connection;
10289 dpyinfo->gray
10290 = XCreatePixmapFromBitmapData (dpyinfo->display, dpyinfo->root_window,
10291 gray_bitmap_bits,
10292 gray_bitmap_width, gray_bitmap_height,
10293 1, 0, 1);
10296 #ifdef HAVE_X_I18N
10297 xim_initialize (dpyinfo, resource_name);
10298 #endif
10300 xsettings_initialize (dpyinfo);
10302 /* This is only needed for distinguishing keyboard and process input. */
10303 if (connection != 0)
10304 add_keyboard_wait_descriptor (connection);
10306 #ifdef F_SETOWN
10307 fcntl (connection, F_SETOWN, getpid ());
10308 #endif /* ! defined (F_SETOWN) */
10310 #ifdef SIGIO
10311 if (interrupt_input)
10312 init_sigio (connection);
10313 #endif /* ! defined (SIGIO) */
10315 #ifdef USE_LUCID
10317 XrmValue d, fr, to;
10318 Font font;
10320 dpy = dpyinfo->display;
10321 d.addr = (XPointer)&dpy;
10322 d.size = sizeof (Display *);
10323 fr.addr = XtDefaultFont;
10324 fr.size = sizeof (XtDefaultFont);
10325 to.size = sizeof (Font *);
10326 to.addr = (XPointer)&font;
10327 x_catch_errors (dpy);
10328 if (!XtCallConverter (dpy, XtCvtStringToFont, &d, 1, &fr, &to, NULL))
10329 abort ();
10330 if (x_had_errors_p (dpy) || !XQueryFont (dpy, font))
10331 XrmPutLineResource (&xrdb, "Emacs.dialog.*.font: 9x15");
10332 x_uncatch_errors ();
10334 #endif
10336 /* See if we should run in synchronous mode. This is useful
10337 for debugging X code. */
10339 Lisp_Object value;
10340 value = display_x_get_resource (dpyinfo,
10341 build_string ("synchronous"),
10342 build_string ("Synchronous"),
10343 Qnil, Qnil);
10344 if (STRINGP (value)
10345 && (!strcmp (SSDATA (value), "true")
10346 || !strcmp (SSDATA (value), "on")))
10347 XSynchronize (dpyinfo->display, True);
10351 Lisp_Object value;
10352 value = display_x_get_resource (dpyinfo,
10353 build_string ("useXIM"),
10354 build_string ("UseXIM"),
10355 Qnil, Qnil);
10356 #ifdef USE_XIM
10357 if (STRINGP (value)
10358 && (!strcmp (SSDATA (value), "false")
10359 || !strcmp (SSDATA (value), "off")))
10360 use_xim = 0;
10361 #else
10362 if (STRINGP (value)
10363 && (!strcmp (SSDATA (value), "true")
10364 || !strcmp (SSDATA (value), "on")))
10365 use_xim = 1;
10366 #endif
10369 #ifdef HAVE_X_SM
10370 /* Only do this for the very first display in the Emacs session.
10371 Ignore X session management when Emacs was first started on a
10372 tty. */
10373 if (terminal->id == 1)
10374 x_session_initialize (dpyinfo);
10375 #endif
10377 UNBLOCK_INPUT;
10379 return dpyinfo;
10382 /* Get rid of display DPYINFO, deleting all frames on it,
10383 and without sending any more commands to the X server. */
10385 static void
10386 x_delete_display (struct x_display_info *dpyinfo)
10388 struct terminal *t;
10390 /* Close all frames and delete the generic struct terminal for this
10391 X display. */
10392 for (t = terminal_list; t; t = t->next_terminal)
10393 if (t->type == output_x_window && t->display_info.x == dpyinfo)
10395 #ifdef HAVE_X_SM
10396 /* Close X session management when we close its display. */
10397 if (t->id == 1 && x_session_have_connection ())
10398 x_session_close ();
10399 #endif
10400 delete_terminal (t);
10401 break;
10404 delete_keyboard_wait_descriptor (dpyinfo->connection);
10406 /* Discard this display from x_display_name_list and x_display_list.
10407 We can't use Fdelq because that can quit. */
10408 if (! NILP (x_display_name_list)
10409 && EQ (XCAR (x_display_name_list), dpyinfo->name_list_element))
10410 x_display_name_list = XCDR (x_display_name_list);
10411 else
10413 Lisp_Object tail;
10415 tail = x_display_name_list;
10416 while (CONSP (tail) && CONSP (XCDR (tail)))
10418 if (EQ (XCAR (XCDR (tail)), dpyinfo->name_list_element))
10420 XSETCDR (tail, XCDR (XCDR (tail)));
10421 break;
10423 tail = XCDR (tail);
10427 if (next_noop_dpyinfo == dpyinfo)
10428 next_noop_dpyinfo = dpyinfo->next;
10430 if (x_display_list == dpyinfo)
10431 x_display_list = dpyinfo->next;
10432 else
10434 struct x_display_info *tail;
10436 for (tail = x_display_list; tail; tail = tail->next)
10437 if (tail->next == dpyinfo)
10438 tail->next = tail->next->next;
10441 xfree (dpyinfo->x_id_name);
10442 xfree (dpyinfo->x_dnd_atoms);
10443 xfree (dpyinfo->color_cells);
10444 xfree (dpyinfo);
10447 #ifdef USE_X_TOOLKIT
10449 /* Atimer callback function for TIMER. Called every 0.1s to process
10450 Xt timeouts, if needed. We must avoid calling XtAppPending as
10451 much as possible because that function does an implicit XFlush
10452 that slows us down. */
10454 static void
10455 x_process_timeouts (struct atimer *timer)
10457 BLOCK_INPUT;
10458 x_timeout_atimer_activated_flag = 0;
10459 if (toolkit_scroll_bar_interaction || popup_activated ())
10461 while (XtAppPending (Xt_app_con) & XtIMTimer)
10462 XtAppProcessEvent (Xt_app_con, XtIMTimer);
10463 /* Reactivate the atimer for next time. */
10464 x_activate_timeout_atimer ();
10466 UNBLOCK_INPUT;
10469 /* Install an asynchronous timer that processes Xt timeout events
10470 every 0.1s as long as either `toolkit_scroll_bar_interaction' or
10471 `popup_activated_flag' (in xmenu.c) is set. Make sure to call this
10472 function whenever these variables are set. This is necessary
10473 because some widget sets use timeouts internally, for example the
10474 LessTif menu bar, or the Xaw3d scroll bar. When Xt timeouts aren't
10475 processed, these widgets don't behave normally. */
10477 void
10478 x_activate_timeout_atimer (void)
10480 BLOCK_INPUT;
10481 if (!x_timeout_atimer_activated_flag)
10483 EMACS_TIME interval;
10485 EMACS_SET_SECS_USECS (interval, 0, 100000);
10486 start_atimer (ATIMER_RELATIVE, interval, x_process_timeouts, 0);
10487 x_timeout_atimer_activated_flag = 1;
10489 UNBLOCK_INPUT;
10492 #endif /* USE_X_TOOLKIT */
10495 /* Set up use of X before we make the first connection. */
10497 extern frame_parm_handler x_frame_parm_handlers[];
10499 static struct redisplay_interface x_redisplay_interface =
10501 x_frame_parm_handlers,
10502 x_produce_glyphs,
10503 x_write_glyphs,
10504 x_insert_glyphs,
10505 x_clear_end_of_line,
10506 x_scroll_run,
10507 x_after_update_window_line,
10508 x_update_window_begin,
10509 x_update_window_end,
10510 x_cursor_to,
10511 x_flush,
10512 #ifdef XFlush
10513 x_flush,
10514 #else
10515 0, /* flush_display_optional */
10516 #endif
10517 x_clear_window_mouse_face,
10518 x_get_glyph_overhangs,
10519 x_fix_overlapping_area,
10520 x_draw_fringe_bitmap,
10521 0, /* define_fringe_bitmap */
10522 0, /* destroy_fringe_bitmap */
10523 x_compute_glyph_string_overhangs,
10524 x_draw_glyph_string,
10525 x_define_frame_cursor,
10526 x_clear_frame_area,
10527 x_draw_window_cursor,
10528 x_draw_vertical_window_border,
10529 x_shift_glyphs_for_insert
10533 /* This function is called when the last frame on a display is deleted. */
10534 void
10535 x_delete_terminal (struct terminal *terminal)
10537 struct x_display_info *dpyinfo = terminal->display_info.x;
10539 /* Protect against recursive calls. delete_frame in
10540 delete_terminal calls us back when it deletes our last frame. */
10541 if (!terminal->name)
10542 return;
10544 BLOCK_INPUT;
10545 #ifdef HAVE_X_I18N
10546 /* We must close our connection to the XIM server before closing the
10547 X display. */
10548 if (dpyinfo->xim)
10549 xim_close_dpy (dpyinfo);
10550 #endif
10552 /* If called from x_connection_closed, the display may already be closed
10553 and dpyinfo->display was set to 0 to indicate that. */
10554 if (dpyinfo->display)
10556 x_destroy_all_bitmaps (dpyinfo);
10557 XSetCloseDownMode (dpyinfo->display, DestroyAll);
10559 /* Whether or not XCloseDisplay destroys the associated resource
10560 database depends on the version of libX11. To avoid both
10561 crash and memory leak, we dissociate the database from the
10562 display and then destroy dpyinfo->xrdb ourselves.
10564 Unfortunately, the above strategy does not work in some
10565 situations due to a bug in newer versions of libX11: because
10566 XrmSetDatabase doesn't clear the flag XlibDisplayDfltRMDB if
10567 dpy->db is NULL, XCloseDisplay destroys the associated
10568 database whereas it has not been created by XGetDefault
10569 (Bug#21974 in freedesktop.org Bugzilla). As a workaround, we
10570 don't destroy the database here in order to avoid the crash
10571 in the above situations for now, though that may cause memory
10572 leaks in other situations. */
10573 #if 0
10574 #ifdef HAVE_XRMSETDATABASE
10575 XrmSetDatabase (dpyinfo->display, NULL);
10576 #else
10577 dpyinfo->display->db = NULL;
10578 #endif
10579 /* We used to call XrmDestroyDatabase from x_delete_display, but
10580 some older versions of libX11 crash if we call it after
10581 closing all the displays. */
10582 XrmDestroyDatabase (dpyinfo->xrdb);
10583 #endif
10585 #ifdef USE_GTK
10586 xg_display_close (dpyinfo->display);
10587 #else
10588 #ifdef USE_X_TOOLKIT
10589 XtCloseDisplay (dpyinfo->display);
10590 #else
10591 XCloseDisplay (dpyinfo->display);
10592 #endif
10593 #endif /* ! USE_GTK */
10596 /* Mark as dead. */
10597 dpyinfo->display = NULL;
10598 x_delete_display (dpyinfo);
10599 UNBLOCK_INPUT;
10602 /* Create a struct terminal, initialize it with the X11 specific
10603 functions and make DISPLAY->TERMINAL point to it. */
10605 static struct terminal *
10606 x_create_terminal (struct x_display_info *dpyinfo)
10608 struct terminal *terminal;
10610 terminal = create_terminal ();
10612 terminal->type = output_x_window;
10613 terminal->display_info.x = dpyinfo;
10614 dpyinfo->terminal = terminal;
10616 /* kboard is initialized in x_term_init. */
10618 terminal->clear_frame_hook = x_clear_frame;
10619 terminal->ins_del_lines_hook = x_ins_del_lines;
10620 terminal->delete_glyphs_hook = x_delete_glyphs;
10621 terminal->ring_bell_hook = XTring_bell;
10622 terminal->toggle_invisible_pointer_hook = XTtoggle_invisible_pointer;
10623 terminal->reset_terminal_modes_hook = XTreset_terminal_modes;
10624 terminal->set_terminal_modes_hook = XTset_terminal_modes;
10625 terminal->update_begin_hook = x_update_begin;
10626 terminal->update_end_hook = x_update_end;
10627 terminal->set_terminal_window_hook = XTset_terminal_window;
10628 terminal->read_socket_hook = XTread_socket;
10629 terminal->frame_up_to_date_hook = XTframe_up_to_date;
10630 terminal->mouse_position_hook = XTmouse_position;
10631 terminal->frame_rehighlight_hook = XTframe_rehighlight;
10632 terminal->frame_raise_lower_hook = XTframe_raise_lower;
10633 terminal->fullscreen_hook = XTfullscreen_hook;
10634 terminal->set_vertical_scroll_bar_hook = XTset_vertical_scroll_bar;
10635 terminal->condemn_scroll_bars_hook = XTcondemn_scroll_bars;
10636 terminal->redeem_scroll_bar_hook = XTredeem_scroll_bar;
10637 terminal->judge_scroll_bars_hook = XTjudge_scroll_bars;
10639 terminal->delete_frame_hook = x_destroy_window;
10640 terminal->delete_terminal_hook = x_delete_terminal;
10642 terminal->rif = &x_redisplay_interface;
10643 terminal->scroll_region_ok = 1; /* We'll scroll partial frames. */
10644 terminal->char_ins_del_ok = 1;
10645 terminal->line_ins_del_ok = 1; /* We'll just blt 'em. */
10646 terminal->fast_clear_end_of_line = 1; /* X does this well. */
10647 terminal->memory_below_frame = 0; /* We don't remember what scrolls
10648 off the bottom. */
10650 return terminal;
10653 void
10654 x_initialize (void)
10656 baud_rate = 19200;
10658 x_noop_count = 0;
10659 last_tool_bar_item = -1;
10660 any_help_event_p = 0;
10661 ignore_next_mouse_click_timeout = 0;
10663 #ifdef USE_GTK
10664 current_count = -1;
10665 #endif
10667 /* Try to use interrupt input; if we can't, then start polling. */
10668 Fset_input_interrupt_mode (Qt);
10670 #ifdef USE_X_TOOLKIT
10671 XtToolkitInitialize ();
10673 Xt_app_con = XtCreateApplicationContext ();
10675 /* Register a converter from strings to pixels, which uses
10676 Emacs' color allocation infrastructure. */
10677 XtAppSetTypeConverter (Xt_app_con,
10678 XtRString, XtRPixel, cvt_string_to_pixel,
10679 cvt_string_to_pixel_args,
10680 XtNumber (cvt_string_to_pixel_args),
10681 XtCacheByDisplay, cvt_pixel_dtor);
10683 XtAppSetFallbackResources (Xt_app_con, Xt_default_resources);
10684 #endif
10686 #ifdef USE_TOOLKIT_SCROLL_BARS
10687 #ifndef USE_GTK
10688 xaw3d_arrow_scroll = False;
10689 xaw3d_pick_top = True;
10690 #endif
10691 #endif
10693 pending_autoraise_frame = 0;
10694 pending_event_wait.f = 0;
10695 pending_event_wait.eventtype = 0;
10697 /* Note that there is no real way portable across R3/R4 to get the
10698 original error handler. */
10699 XSetErrorHandler (x_error_handler);
10700 XSetIOErrorHandler (x_io_error_quitter);
10702 signal (SIGPIPE, x_connection_signal);
10704 xgselect_initialize ();
10708 void
10709 syms_of_xterm (void)
10711 x_error_message = NULL;
10713 staticpro (&x_display_name_list);
10714 x_display_name_list = Qnil;
10716 staticpro (&last_mouse_scroll_bar);
10717 last_mouse_scroll_bar = Qnil;
10719 DEFSYM (Qvendor_specific_keysyms, "vendor-specific-keysyms");
10720 DEFSYM (Qlatin_1, "latin-1");
10722 staticpro (&last_mouse_press_frame);
10723 last_mouse_press_frame = Qnil;
10725 #ifdef USE_GTK
10726 xg_default_icon_file = make_pure_c_string ("icons/hicolor/scalable/apps/emacs.svg");
10727 staticpro (&xg_default_icon_file);
10729 DEFSYM (Qx_gtk_map_stock, "x-gtk-map-stock");
10730 #endif
10732 DEFVAR_BOOL ("x-use-underline-position-properties",
10733 x_use_underline_position_properties,
10734 doc: /* *Non-nil means make use of UNDERLINE_POSITION font properties.
10735 A value of nil means ignore them. If you encounter fonts with bogus
10736 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
10737 to 4.1, set this to nil. You can also use `underline-minimum-offset'
10738 to override the font's UNDERLINE_POSITION for small font display
10739 sizes. */);
10740 x_use_underline_position_properties = 1;
10742 DEFVAR_BOOL ("x-underline-at-descent-line",
10743 x_underline_at_descent_line,
10744 doc: /* *Non-nil means to draw the underline at the same place as the descent line.
10745 A value of nil means to draw the underline according to the value of the
10746 variable `x-use-underline-position-properties', which is usually at the
10747 baseline level. The default value is nil. */);
10748 x_underline_at_descent_line = 0;
10750 DEFVAR_BOOL ("x-mouse-click-focus-ignore-position",
10751 x_mouse_click_focus_ignore_position,
10752 doc: /* Non-nil means that a mouse click to focus a frame does not move point.
10753 This variable is only used when the window manager requires that you
10754 click on a frame to select it (give it focus). In that case, a value
10755 of nil, means that the selected window and cursor position changes to
10756 reflect the mouse click position, while a non-nil value means that the
10757 selected window or cursor position is preserved. */);
10758 x_mouse_click_focus_ignore_position = 0;
10760 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
10761 doc: /* Which toolkit scroll bars Emacs uses, if any.
10762 A value of nil means Emacs doesn't use toolkit scroll bars.
10763 With the X Window system, the value is a symbol describing the
10764 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
10765 With MS Windows, the value is t. */);
10766 #ifdef USE_TOOLKIT_SCROLL_BARS
10767 #ifdef USE_MOTIF
10768 Vx_toolkit_scroll_bars = intern_c_string ("motif");
10769 #elif defined HAVE_XAW3D
10770 Vx_toolkit_scroll_bars = intern_c_string ("xaw3d");
10771 #elif USE_GTK
10772 Vx_toolkit_scroll_bars = intern_c_string ("gtk");
10773 #else
10774 Vx_toolkit_scroll_bars = intern_c_string ("xaw");
10775 #endif
10776 #else
10777 Vx_toolkit_scroll_bars = Qnil;
10778 #endif
10780 staticpro (&last_mouse_motion_frame);
10781 last_mouse_motion_frame = Qnil;
10783 Qmodifier_value = intern_c_string ("modifier-value");
10784 Qalt = intern_c_string ("alt");
10785 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
10786 Qhyper = intern_c_string ("hyper");
10787 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
10788 Qmeta = intern_c_string ("meta");
10789 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
10790 Qsuper = intern_c_string ("super");
10791 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
10793 DEFVAR_LISP ("x-alt-keysym", Vx_alt_keysym,
10794 doc: /* Which keys Emacs uses for the alt modifier.
10795 This should be one of the symbols `alt', `hyper', `meta', `super'.
10796 For example, `alt' means use the Alt_L and Alt_R keysyms. The default
10797 is nil, which is the same as `alt'. */);
10798 Vx_alt_keysym = Qnil;
10800 DEFVAR_LISP ("x-hyper-keysym", Vx_hyper_keysym,
10801 doc: /* Which keys Emacs uses for the hyper modifier.
10802 This should be one of the symbols `alt', `hyper', `meta', `super'.
10803 For example, `hyper' means use the Hyper_L and Hyper_R keysyms. The
10804 default is nil, which is the same as `hyper'. */);
10805 Vx_hyper_keysym = Qnil;
10807 DEFVAR_LISP ("x-meta-keysym", Vx_meta_keysym,
10808 doc: /* Which keys Emacs uses for the meta modifier.
10809 This should be one of the symbols `alt', `hyper', `meta', `super'.
10810 For example, `meta' means use the Meta_L and Meta_R keysyms. The
10811 default is nil, which is the same as `meta'. */);
10812 Vx_meta_keysym = Qnil;
10814 DEFVAR_LISP ("x-super-keysym", Vx_super_keysym,
10815 doc: /* Which keys Emacs uses for the super modifier.
10816 This should be one of the symbols `alt', `hyper', `meta', `super'.
10817 For example, `super' means use the Super_L and Super_R keysyms. The
10818 default is nil, which is the same as `super'. */);
10819 Vx_super_keysym = Qnil;
10821 DEFVAR_LISP ("x-keysym-table", Vx_keysym_table,
10822 doc: /* Hash table of character codes indexed by X keysym codes. */);
10823 Vx_keysym_table = make_hash_table (Qeql, make_number (900),
10824 make_float (DEFAULT_REHASH_SIZE),
10825 make_float (DEFAULT_REHASH_THRESHOLD),
10826 Qnil, Qnil, Qnil);
10829 #endif /* HAVE_X_WINDOWS */